返回 CodeWhale
driver.rs
根目录 / crates / workflow-js / src / driver.rs
1 //! The driver seam between the sandboxed VM and the subagent engine.
2 //!
3 //! The QuickJS VM lives on a dedicated thread and its `'js` values can never
4 //! cross an `.await` onto another thread, so everything that leaves the VM is
5 //! plain `Send` data: a [`TaskRequest`] goes out, a [`TaskCompletion`] comes
6 //! back over a oneshot. The [`WorkflowDriver`] trait is the host-side contract
7 //! the tui wiring implements over `SubAgentManager` (spawn is fire-and-forget
8 //! there; the driver's completion pump resolves the oneshot from the mailbox
9 //! `Completed` signal keyed by `agent_id`, then reads the full untruncated
10 //! text via `get_result`). Tests implement it with
11 //! [`crate::testing::FakeDriver`].
12
13 use async_trait::async_trait;
14 use serde::{Deserialize, Serialize};
15 use tokio::sync::oneshot;
16
17 use crate::error::DriverError;
18
19 /// One `task()` invocation, fully resolved and validated on the VM side.
20 ///
21 /// Field semantics mirror the `agent` tool's spawn options.
22 ///
23 /// Step identity is fleet `role` (preferred) and/or `profile` (#4177). Both
24 /// tokens are normalized (trimmed + lowercased) with the same rule as
25 /// `crates/workflow` leaf profiles. Roster membership is resolved by the
26 /// driver (tui) at spawn time — this crate never sees the saved Fleet roster.
27 /// Provider/model remain optional overrides, not required identity fields.
28 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29 pub struct TaskRequest {
30 /// The child prompt (JS `prompt`, falling back to `description`; required).
31 pub description: String,
32 /// Subagent type (JS `subagentType` or `type`); `None` lets the driver
33 /// apply its default (`general`).
34 pub subagent_type: Option<String>,
35 /// Fleet role name (JS `role`), e.g. `scout` / `implementer` (#4177).
36 pub role: Option<String>,
37 /// Fleet profile token, normalized (trimmed, lowercased) and validated.
38 /// Explicit profile wins over role mapping at spawn time.
39 pub profile: Option<String>,
40 /// Explicit model override; always wins over `model_strength`.
41 pub model: Option<String>,
42 /// Relative model strength (`same`/`faster`, plus driver-side aliases).
43 pub model_strength: Option<String>,
44 /// Reasoning effort (`inherit`/`off`/`low`/`medium`/`high`/`max`).
45 pub thinking: Option<String>,
46 /// Optional existing working directory, relative to the parent workspace.
47 /// The host validates that it exists and remains inside the workspace.
48 pub cwd: Option<String>,
49 /// Run the child in a fresh git worktree for parallel edits.
50 pub worktree: bool,
51 /// Explicit child mutation authority. A write-capable value remains
52 /// fail-closed unless at least one bounded scope below is declared.
53 #[serde(default)]
54 pub write_authority: Option<String>,
55 /// Repo-relative directory trees the child expects to mutate.
56 #[serde(default)]
57 pub write_roots: Vec<String>,
58 /// Repo-relative exact files the child expects to mutate.
59 #[serde(default)]
60 pub exact_files: Vec<String>,
61 /// Named shared contracts owned by this child while active.
62 #[serde(default)]
63 pub coordination_contracts: Vec<String>,
64 /// Bounded prerequisite facts relevant to this child.
65 #[serde(default)]
66 pub dependencies: Vec<String>,
67 /// Bounded observable checks for child completion.
68 #[serde(default)]
69 pub acceptance: Vec<String>,
70 /// Explicit tool allowlist; required by the driver for `custom` roles.
71 pub allowed_tools: Option<Vec<String>>,
72 /// Host-imposed tool deny list. Deny always wins over allow, including over
73 /// `allowed_tools` and over the role posture.
74 ///
75 /// Deliberately **not** settable from a workflow script: it is how a host
76 /// enforces a ceiling it derived (an exact Fleet member's
77 /// `network_tool = false`, for instance) on the child that actually runs.
78 /// A script that could write it could also clear it.
79 #[serde(default)]
80 pub disallowed_tools: Vec<String>,
81 /// Legacy model input; the runtime replaces it with trusted Fleet/parent depth.
82 pub max_depth: Option<u32>,
83 /// Legacy token hint; the production driver does not enforce a token pool.
84 pub token_budget: Option<u64>,
85 /// Legacy model input, ignored by the shared production spawn seam.
86 pub max_steps: Option<u32>,
87 /// Legacy model input, ignored by the shared production spawn seam.
88 pub wall_time_secs: Option<u64>,
89 /// JSON schema the reply must satisfy; validated in the VM after the
90 /// driver returns the raw text (see [`crate`] docs for decode rules).
91 pub response_schema: Option<serde_json::Value>,
92 /// Bounded repair attempts after a failed `responseSchema` decode
93 /// (#5583): re-ask the same route with the schema and the failed reply.
94 /// `None` uses the default of one attempt; `Some(0)` disables repair.
95 /// Clamped at parse time to [`crate::SCHEMA_REPAIR_MAX_ATTEMPTS`]. The driver
96 /// treats a repair spawn like any other task — same admission, budget,
97 /// and usage accounting.
98 pub schema_repair_attempts: Option<u32>,
99 /// Short human label for progress surfaces.
100 pub label: Option<String>,
101 /// Phase name this task belongs to, for progress grouping.
102 pub phase: Option<String>,
103 }
104
105 /// Terminal outcome of one spawned task, delivered over the completion
106 /// oneshot. Everything except `Completed` becomes a JS throw on the awaiting
107 /// `task()` call.
108 #[derive(Debug, Clone, PartialEq, Eq)]
109 pub enum TaskCompletion {
110 /// The child finished; `text` is the full, untruncated result.
111 Completed { text: String },
112 /// The child failed (error result, timeout, ...).
113 Failed { message: String },
114 /// The child was cancelled (cascade or explicit).
115 Cancelled,
116 /// The child's budget scope drained mid-flight.
117 BudgetExhausted { message: String },
118 }
119
120 /// A successfully admitted spawn: the driver-assigned task id (the engine's
121 /// `agent_id`) plus the oneshot the driver resolves on completion.
122 ///
123 /// Dropping the receiver must not wedge the driver; drivers should treat a
124 /// closed completion channel as "nobody is listening" and move on.
125 #[derive(Debug)]
126 pub struct SpawnedTask {
127 /// Driver-assigned id, unique within the run (engine `agent_id`).
128 pub task_id: String,
129 /// Resolved exactly once with the terminal [`TaskCompletion`].
130 pub completion: oneshot::Receiver<TaskCompletion>,
131 }
132
133 /// Progress events emitted by the script (`log(..)` / `phase(..)`), delivered
134 /// to the driver synchronously and in script order.
135 #[derive(Debug, Clone, PartialEq, Eq)]
136 pub enum ProgressEvent {
137 /// `log(msg)` — a narrator line for the UI.
138 Log {
139 /// The stringified message.
140 message: String,
141 },
142 /// `phase(title)` — the script entered a named phase.
143 Phase {
144 /// The phase title.
145 title: String,
146 },
147 /// A completed child returned text that failed the caller's
148 /// `responseSchema` and no repair remains (none configured, or every
149 /// repair attempt also failed — #5583). The VM emits this before
150 /// throwing the validation error back into the script so host-side
151 /// receipts can mark the leaf as failed instead of reporting a
152 /// successful child beside a `null` result. This event is terminal:
153 /// it fires exactly once per failed `task()`, for the attempt that
154 /// failed last, carrying every earlier attempt through
155 /// [`ProgressEvent::TaskSchemaRepairAttempted`].
156 TaskSchemaValidationFailed {
157 /// Driver-assigned task id (engine `agent_id`) of the failed attempt.
158 task_id: String,
159 /// Which decode stage failed: `json_parse` or `schema_validation`.
160 kind: String,
161 /// 1-based attempt number that failed terminally (1 = no repair
162 /// was tried; 2+ = repairs were tried and also failed).
163 attempt: u32,
164 /// The validation error already surfaced to JS.
165 message: String,
166 /// Raw reply text of the failed attempt, bounded by
167 /// [`crate::SCHEMA_RAW_CARRY_CHARS`]; the host writes the durable artifact.
168 raw: String,
169 /// True when `raw` was capped at the carry limit.
170 raw_truncated: bool,
171 },
172 /// A completed child failed its `responseSchema` and a bounded repair
173 /// will follow (#5583). Emitted before the repair spawn so the failed
174 /// attempt is visible even when the repair succeeds and the `task()`
175 /// call returns normally.
176 TaskSchemaRepairAttempted {
177 /// Driver-assigned task id (engine `agent_id`) of the failed attempt
178 /// that triggered this repair.
179 task_id: String,
180 /// Which decode stage failed: `json_parse` or `schema_validation`.
181 kind: String,
182 /// 1-based number of the attempt that failed.
183 attempt: u32,
184 /// The decode error of that attempt.
185 message: String,
186 /// Raw reply text of that attempt, bounded by
187 /// [`crate::SCHEMA_RAW_CARRY_CHARS`].
188 raw: String,
189 /// True when `raw` was capped at the carry limit.
190 raw_truncated: bool,
191 },
192 /// A `task()` call was rejected before any child agent existed —
193 /// malformed options, a bad `responseSchema`, the lifetime cap, or an
194 /// exhausted budget. Inside `parallel()` the JS throw collapses to a
195 /// `null` slot, so without this event the host would have no record that
196 /// a slot was ever requested; drivers fold it into the same ledger as
197 /// `spawn_task` rejections so run status can stay honest.
198 TaskRejected {
199 /// Best-effort `label` from the raw options, when parseable.
200 label: Option<String>,
201 /// Best-effort `phase` from the raw options, when parseable.
202 phase: Option<String>,
203 /// The rejection already surfaced to JS.
204 message: String,
205 },
206 /// A `parallel()` / `pipeline()` fan-out resolved with every slot failed
207 /// and nothing surviving (R9). Emitted by the prelude beside its run-log
208 /// breadcrumb. A fan-out of thunks that throw without calling `task()`
209 /// leaves no task record and no dispatch failure behind, so a log line
210 /// was the only trace — and a log line cannot feed the status
211 /// classifier. This event is the structured twin of that breadcrumb:
212 /// drivers count it so the terminal-status ledger can refuse to record
213 /// such a run as a plain success.
214 FanoutAllSlotsFailed {
215 /// Which fan-out construct died: `parallel` or `pipeline`.
216 construct: String,
217 /// Slots that failed (always equal to `total`).
218 failed: u32,
219 /// Total slots the fan-out declared.
220 total: u32,
221 },
222 /// ONE slot of a settled fan-out dropped to null while other slots
223 /// survived. The structured twin of the per-slot breadcrumb: the ledger
224 /// counts these so a PARTIALLY failed fan-out records Degraded instead
225 /// of a clean Completed with silently lost work.
226 FanoutSlotDropped {
227 /// Which fan-out construct dropped it: `parallel` or `pipeline`.
228 construct: String,
229 /// Typed failure kind (`script`, `task`, `schema`, ...).
230 kind: String,
231 /// Zero-based slot index.
232 slot: u32,
233 },
234 }
235
236 /// Host-side executor for a Workflow run.
237 ///
238 /// Implementations must be cheap to call from the VM thread: `spawn_task`
239 /// admits the task and returns immediately (fire-and-forget spawn — never
240 /// await the child inline), while `progress` and `cancel_all` are
241 /// synchronous. `cancel_all` must be idempotent; it is invoked when the
242 /// script errors, when the run future is dropped, and once more never hurts.
243 #[async_trait]
244 pub trait WorkflowDriver: Send + Sync {
245 /// Admit and start one task. Errors surface as a JS throw on the
246 /// corresponding `task()` call.
247 async fn spawn_task(&self, request: TaskRequest) -> Result<SpawnedTask, DriverError>;
248
249 async fn verify_candidate(
250 &self,
251 _request: serde_json::Value,
252 ) -> Result<serde_json::Value, DriverError> {
253 Err(DriverError::Rejected(
254 "verified candidate evaluator was not frozen for this run".to_string(),
255 ))
256 }
257
258 /// Cancel every in-flight task belonging to this run. Idempotent.
259 fn cancel_all(&self);
260
261 fn cancel_task(&self, _task_id: &str) {}
262
263 /// Receive a script progress event (ordered, synchronous).
264 fn progress(&self, event: ProgressEvent);
265
266 /// The run's workspace root. When known, `task()` accepts an absolute
267 /// `cwd` inside it and normalizes it to the repo-relative form.
268 fn workspace_root(&self) -> Option<std::path::PathBuf> {
269 None
270 }
271 }
272
273 /// One `tools.call()` invocation: a tool name plus its JSON arguments.
274 ///
275 /// Unlike [`TaskRequest`], this carries no identity, route, or authority
276 /// fields. Authority comes from the host side alone: the invoker resolves the
277 /// name against its own registry snapshot, enforces the parent turn's
278 /// deny-lists and authority envelope, and applies the run profile's gates
279 /// (read-only, auto-approve). A script can neither widen nor name its own
280 /// ceiling.
281 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
282 pub struct ToolCallRequest {
283 /// Tool name as the turn's catalog spells it (e.g. `read`).
284 pub tool: String,
285 /// Arguments for the tool. Must be a JSON object.
286 pub input: serde_json::Value,
287 }
288
289 /// Terminal outcome of one `tools.call()`, as JSON the VM passes to JS.
290 ///
291 /// A resolved call either ran clean (`ok: true`, `result` is the tool
292 /// payload) or ran and failed (`ok: false`, `result` is the failure
293 /// message). Gate refusals and seam breaks never arrive here — those are
294 /// `Err`, so the VM can tell "nothing ran" (admission) from "work failed".
295 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
296 pub struct ToolCallResponse {
297 /// True when the tool ran clean. False carries the failure message.
298 pub ok: bool,
299 /// Tool payload on success; failure message string on failure.
300 pub result: serde_json::Value,
301 }
302
303 /// Host-side executor for direct tool calls from a script.
304 ///
305 /// This is the tool analogue of [`WorkflowDriver`]: where the driver launches
306 /// another agent/model task, the invoker executes one ordinary tool and
307 /// returns its result. The two must not be confused — in particular, an
308 /// invoker must never implement a call by spawning a subagent.
309 ///
310 /// Gate refusals (unknown tool, read-only violation, approval requirement,
311 /// recursion) surface as [`DriverError::Rejected`]; a broken seam surfaces
312 /// as [`DriverError::Unavailable`].
313 #[async_trait]
314 pub trait ToolInvoker: Send + Sync {
315 /// Execute one tool call and return its outcome.
316 async fn invoke(&self, request: ToolCallRequest) -> Result<ToolCallResponse, DriverError>;
317 }
318
319 /// Normalize and validate a Fleet profile token: trim, lowercase, then apply
320 /// the same token rule as `crates/workflow`'s `validate_leaf_profile` —
321 /// non-empty, no whitespace, and none of `"`, `'`, `` ` ``, `=`.
322 pub fn normalize_profile(raw: &str) -> Result<String, String> {
323 let normalized = raw.trim().to_lowercase();
324 let invalid = normalized.is_empty()
325 || normalized
326 .chars()
327 .any(|ch| ch.is_whitespace() || matches!(ch, '"' | '\'' | '`' | '='));
328 if invalid {
329 return Err(format!(
330 "invalid profile token {raw:?}: profiles must be non-empty and contain no whitespace, quotes, backticks, or '='"
331 ));
332 }
333 Ok(normalized)
334 }
335
336 #[cfg(test)]
337 mod tests {
338 use super::*;
339
340 #[test]
341 fn normalize_profile_trims_and_lowercases() {
342 assert_eq!(normalize_profile(" ALpha-1 ").unwrap(), "alpha-1");
343 }
344
345 #[test]
346 fn normalize_profile_rejects_bad_tokens() {
347 for bad in ["", " ", "two words", "a=b", "a\"b", "a'b", "a`b"] {
348 assert!(
349 normalize_profile(bad).is_err(),
350 "expected rejection: {bad:?}"
351 );
352 }
353 }
354
355 #[test]
356 fn legacy_task_request_defaults_new_coordination_fields() {
357 let legacy = serde_json::json!({
358 "description": "inspect the candidate",
359 "subagent_type": null,
360 "role": "reviewer",
361 "profile": null,
362 "model": null,
363 "model_strength": null,
364 "thinking": null,
365 "cwd": null,
366 "worktree": false,
367 "allowed_tools": null,
368 "max_depth": null,
369 "token_budget": null,
370 "max_steps": null,
371 "wall_time_secs": null,
372 "response_schema": null,
373 "label": null,
374 "phase": null
375 });
376
377 let request: TaskRequest = serde_json::from_value(legacy).unwrap();
378 assert_eq!(request.write_authority, None);
379 assert!(request.write_roots.is_empty());
380 assert!(request.exact_files.is_empty());
381 assert!(request.coordination_contracts.is_empty());
382 assert!(request.dependencies.is_empty());
383 assert!(request.acceptance.is_empty());
384 }
385 }
386
386 lines RUST