//! Answer application: the one path every performed effect's answer takes //! back into the scheduler. //! //! The caller hands back a raw [`EffectAnswer`] - a completion, a tool's own //! output, a store outcome, a timer's firing - and knows nothing of what //! the parked chain asked for. `apply_answer` pairs the answer with the //! effect's [`Continuation`] and turns it into the chain's protocol //! [`Answer`] on the caller's thread, emitting the round's events there: //! the model turn's boundaries and content, the tool call's //! succeeded/failed event and `ToolResult` under the trust rule, the store //! operation's outcome. A timer's firing completes its //! entry and wakes the waiter instead of resuming a chain, and a render's //! answer freezes the section entry's sets and dispatches the round that //! issued it. A `Dropped` answer resumes the chain with the canceled //! error, whatever it was parked on; for a render, that is the round's //! canceled answer. A tool call's answer, of either kind, also ends the //! call's identity: what the tool did is joined back into the chain, and //! the call's access refuses every later operation. The answer to a file //! operation that a tool call asked for, a receipt, a failure, or a drop, //! resumes no chain and reports nothing: the tool has the outcome, and //! the chain still awaits the tool call. use runvil_types::error::{ErrorCode, place}; use runvil_types::event_lifecycle::{self as lifecycle, Lifecycle}; use runvil_types::ids::{RoundId, TaskId}; use runvil_types::tools::ToolOutput; use runvil_vfs::{ExecId, VfsError, VfsOp, VfsOutcome}; use crate::execute::infer::accept_infer; use crate::lua::{Answer, ModelCall, ToolCallOutcome, prepare_dispatch, prepare_model_dispatch}; use crate::model::Completion; use crate::{Error, Result, error}; use super::tasks::Stop; use super::{ CallSite, ChainIndex, ChainOps, Continuation, EffectAnswer, Pending, Scheduler, ToolCallContinuation, }; /// The succeeded/failed observation pair one store operation reports; /// nothing for an operation that no `store` function asks for. fn vfs_observations(op: &VfsOp) -> Option<(Lifecycle, Lifecycle)> { let pair = match op { VfsOp::Write { .. } => (lifecycle::VFS_WRITE_SUCCEEDED, lifecycle::VFS_WRITE_FAILED), VfsOp::Append { .. } => ( lifecycle::VFS_APPEND_SUCCEEDED, lifecycle::VFS_APPEND_FAILED, ), VfsOp::Read { .. } => (lifecycle::VFS_READ_SUCCEEDED, lifecycle::VFS_READ_FAILED), VfsOp::ReadNumbered { .. } => ( lifecycle::VFS_READ_NUMBERED_SUCCEEDED, lifecycle::VFS_READ_NUMBERED_FAILED, ), VfsOp::StrReplace { .. } => ( lifecycle::VFS_REPLACE_SUCCEEDED, lifecycle::VFS_REPLACE_FAILED, ), VfsOp::Delete { .. } => ( lifecycle::VFS_DELETE_SUCCEEDED, lifecycle::VFS_DELETE_FAILED, ), VfsOp::Glob { .. } => (lifecycle::VFS_GLOB_SUCCEEDED, lifecycle::VFS_GLOB_FAILED), VfsOp::Exists { .. } => ( lifecycle::VFS_EXISTS_SUCCEEDED, lifecycle::VFS_EXISTS_FAILED, ), VfsOp::Stat { .. } | VfsOp::List { .. } | VfsOp::ReadRange { .. } | VfsOp::Mkdir { .. } | VfsOp::Remove { .. } | VfsOp::Rename { .. } | VfsOp::Copy { .. } => return None, }; Some(pair) } /// Classifies one store operation's failure for the answer channel. A /// claims-model conflict becomes the fatal make_determinism_error violation: the /// driver intercepts it at the answer boundary and ends the run on the /// spot rather than resuming it into Lua, so no author `pcall` can catch /// it. Every other failure returns as the call's answer as a store /// failure with the model-facing message rendered for the operation and /// the store's code and facts, which ends the run with that code if it /// aborts the chunk uncaught. fn classify_vfs_failure(op: &VfsOp, cause: &VfsError) -> Error { match cause { VfsError::Conflict { detail, .. } => error::make_determinism_error(detail), // `VfsError` is `#[non_exhaustive]` across the crate seam; every // other failure is the call's answer. cause => error::make_store_op_error(op, cause), } } impl Scheduler { /// Applies one performed effect's answer to `parked`, the entry /// `resume` took out of the effect table: turns the raw answer into the /// parked chain's protocol answer under the effect's continuation /// (emitting the round's events), and re-queues the chain. A batched /// tool call's answer fills its slot instead, and the chain re-queues /// once the whole batch has landed. A timer's firing completes its entry /// and wakes its waiter instead, and a render's answer is merged by /// [`ChainOps::merge_render`] before the round that issued it is /// dispatched again through the inbox check, or answers that round /// with the merge's error. A `Dropped` answer is the caller /// giving the effect up: the chain resumes with the canceled error. /// Every answer to a tool call, `Dropped` included, first ends the /// call's identity through [`Scheduler::end_tool_call`], so whatever /// the tool did happens before the chain's next step and nothing it /// tries after is admitted. The answer to a file operation that a /// tool call asked for changes nothing, a failure and a drop /// included. /// /// # Errors /// Returns an `Internal` failure when the answer's kind does not match /// the effect's, a `Vfs` answer for an operation that a tool call /// asked for and a `VfsReceipt` answer for one that Lua asked for /// included, when a batched call's answer finds no open slot to /// fill, or when the chain it resumes has no suspended block. /// Returns a `Determinism` failure when a store answer reports a /// claims-model conflict: the run ends on the spot rather than /// resuming the conflict into Lua, where an author `pcall` could catch /// it. pub(super) fn apply_answer(&mut self, parked: Pending, answer: EffectAnswer) -> Result<()> { let Pending { chain, resume } = parked; let slot = match &resume { Continuation::ToolCall(call) => { self.end_tool_call(chain, call.exec()); match call.site { CallSite::Batch { slot, .. } => Some(slot), CallSite::Script | CallSite::Model { .. } => None, } } Continuation::Infer(_) | Continuation::Chat(_) | Continuation::Render(_) | Continuation::Vfs(_) | Continuation::ToolVfs | Continuation::Timer(_) => None, }; let answer = match (resume, answer) { (Continuation::Timer(task), EffectAnswer::Dropped) => return self.drop_timer(&task), // The outcome went to the tool, and so did a failure, so // neither it nor a drop moves a chain: the chain waits on the // tool call. (Continuation::ToolVfs, EffectAnswer::VfsReceipt(_) | EffectAnswer::Dropped) => { return Ok(()); } (_, EffectAnswer::Dropped) => Err(Error::canceled()), (Continuation::Infer(round), EffectAnswer::Chat(result)) => self .with_chain(chain, |ops| ops.accept_infer(round, result)) .map(Answer::Infer), (Continuation::Chat(round), EffectAnswer::Chat(result)) => { self.with_chain(chain, |ops| ops.accept_chat(round, result))? } (Continuation::Render(binding), EffectAnswer::Render(rendered)) => { return match self.with_chain(chain, |ops| ops.merge_render(rendered)) { Ok(list) => self.dispatch_round(chain, &list, Some(binding)), Err(error) => self.answer_inline(chain, Err(error)), }; } (Continuation::ToolCall(call), EffectAnswer::ToolCall(result)) => self .with_chain(chain, |ops| ops.accept_tool_call(&call, result)) .map(Answer::ToolCallResult), (Continuation::Vfs(op), EffectAnswer::Vfs(result)) => { match self.with_chain(chain, |ops| ops.accept_vfs(&op, result)) { // A claims-model conflict is fatal: the suspended // chains drop unarmed in the run's teardown, exactly // as on the cancellation path. Err(error) if error.code == ErrorCode::Determinism => return Err(error), result => result.map(Answer::Store), } } (Continuation::Timer(task), EffectAnswer::Timer) => return self.fire_timer(&task), // Every pair the arms above left: an answer of another kind // than its effect's, the whole outcome for an operation a tool // asked for and a receipt for one Lua asked for among them. // Both lists name every variant, so a new one fails the build // here. ( Continuation::Infer(_) | Continuation::Chat(_) | Continuation::Render(_) | Continuation::ToolCall(_) | Continuation::Vfs(_) | Continuation::ToolVfs | Continuation::Timer(_), EffectAnswer::Chat(_) | EffectAnswer::Render(_) | EffectAnswer::ToolCall(_) | EffectAnswer::Vfs(_) | EffectAnswer::VfsReceipt(_) | EffectAnswer::Timer, ) => { return Err(error::make_internal_error( "an effect's answer must be of the effect's own kind", )); } }; if let Some(slot) = slot { return self.with_chain(chain, |ops| ops.fill_batch_slot(slot, answer)); } self.answer_inline(chain, answer) } /// Ends `exec`, the identity of the tool call `chain` was parked on, /// whether the call was answered or aborted: merges it into the /// chain's access when the chain still holds one, and refuses every /// later operation, spawn, or store view through the call's access. /// A run whose scope has closed has already refused every access, so /// there is nothing to end. pub(super) fn end_tool_call(&self, chain: ChainIndex, exec: ExecId) { let Some(scope) = &self.scope else { return; }; let owner = self.chains[chain].access().ok().map(|access| access.id()); scope.end_access(owner, exec); } /// Applies a dropped timer: `task`'s entry moves to `Canceled`. While /// the run's cancel flag is clear, the caller gave up the timeout and /// the run goes on, so the chain parked on the timer leaves its wait /// with the canceled error, as a dropped `Chat` or `ToolCall` does: a /// timed `tasks.join` or `tasks.join_any` raises it. A timer whose /// entry isn't live, or that nothing waits on, is dropped silently. /// Under a run cancel the drop wakes no one, since the cancel tears /// the waiter down with every other chain. fn drop_timer(&mut self, task: &TaskId) -> Result<()> { let Some(owner) = self.tasks.owner_of(task) else { return Ok(()); }; if self.tasks.stop(task, Stop::Canceled).is_none() { return Ok(()); } if self.ctx.cancel().is_canceled() || !self.chains[owner].end_wait_for(task) { return Ok(()); } self.wake_from_wait(owner, Err(Error::canceled())) } } impl ChainOps<'_> { /// Applies a nested infer round's completion: the single-prose-round /// reporting through the chain's own emitter, stamped with `round`, /// then the round's text. fn accept_infer( &self, round: RoundId, result: std::result::Result, runvil_types::error::Error>, ) -> Result { let chain = &*self.chain; accept_infer(result, round, chain.ctx.reporting(), chain.section_name()) } /// Applies a bound tool call's own answer through the shared dispatch /// body: the succeeded/failed event, the trust rule, and the /// `ToolResult` report - under the model's call id when the model /// issued the call (a tool's own failure then resumes as untrusted /// failure text), else as a script call classified by the binding's /// declared output kind. A script call that receives a listing marks /// the chain's frame's innermost open adhoc call. fn accept_tool_call( &mut self, call: &ToolCallContinuation, result: std::result::Result, ) -> Result { let chain = &mut *self.chain; // The shared dispatch body reports through this chain's emitter, so // its reports land in the buffer under this chain's task. let emitter = chain.ctx.emitter(); let section = chain.section_name(); let nonce = chain.ctx.nonce(); let vendor = chain.ctx.tool_set().vendor_for(call.binding.id()); match &call.site { // Model-issued, alone or batched: the content always resumes, // plain - it is the tool record's text for the next round, // never classified by output kind. CallSite::Model { call_id, .. } | CallSite::Batch { call_id, .. } => { let report = ModelCall { call_id: call_id.clone(), turn: call.report.turn, }; prepare_model_dispatch( &call.binding, vendor, result, nonce, emitter, section, &report, ) .map(|outcome| ToolCallOutcome::Plain(outcome.into_content())) } CallSite::Script => match prepare_dispatch( &call.binding, vendor, result, nonce, emitter, section, call.report, ) { Ok(outcome) => { if outcome.listing() { chain.frame_mut()?.mark_listing(); } ToolCallOutcome::from_dispatch( call.binding.output_kind(), call.binding.alias(), outcome.into_content(), ) } Err(failure) => Err(failure), }, } } /// Applies a store operation's answer: the operation's succeeded or /// failed observation (pushed before the chain resumes, so the op's /// outcome precedes the chunk's closing boundary), then the outcome, /// with a failure classified for the answer channel under the /// operation's own wording and placed on the call line of the block /// parked on it, so a claims-model conflict, which never reaches Lua, /// is located too. fn accept_vfs( &self, op: &VfsOp, result: std::result::Result, ) -> Result { let chain = &*self.chain; if let Some((succeeded, failed)) = vfs_observations(op) { chain.ctx.emitter().report( chain.section_name(), if result.is_ok() { succeeded } else { failed }, ); } result.map_err(|cause| { let line = chain.frame().ok().and_then(|frame| frame.vm().call_line()); place( classify_vfs_failure(op, &cause), chain.ctx.prompt().file(), line, ) }) } }