codewhale_workflow_js/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//! Budget ownership: token accounting and the §5.3 reservation semantics live
14//! entirely on the driver side (the manager's budget scopes). The VM only
15//! reads [`BudgetSnapshot`]s — it performs a fast-fail `spent >= total` check
16//! before spawning and exposes the numbers to JS as `budget.*`, but it never
17//! reserves or debits tokens itself. A driver that admits a spawn is the
18//! authority; its rejection surfaces as a JS throw on that `task()` call.
19
20use async_trait::async_trait;
21use serde::{Deserialize, Serialize};
22use tokio::sync::oneshot;
23
24use crate::error::DriverError;
25
26/// One `task()` invocation, fully resolved and validated on the VM side.
27///
28/// Field semantics mirror the `agent` tool's spawn options.
29///
30/// Step identity is fleet `role` (preferred) and/or `profile` (#4177). Both
31/// tokens are normalized (trimmed + lowercased) with the same rule as
32/// `crates/workflow` leaf profiles. Roster membership is resolved by the
33/// driver (tui) at spawn time — this crate never sees the saved Fleet roster.
34/// Provider/model remain optional overrides, not required identity fields.
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36pub struct TaskRequest {
37 /// The child prompt (JS `prompt`, falling back to `description`; required).
38 pub description: String,
39 /// Subagent type (JS `subagentType` or `type`); `None` lets the driver
40 /// apply its default (`general`).
41 pub subagent_type: Option<String>,
42 /// Fleet role name (JS `role`), e.g. `scout` / `implementer` (#4177).
43 pub role: Option<String>,
44 /// Fleet profile token, normalized (trimmed, lowercased) and validated.
45 /// Explicit profile wins over role mapping at spawn time.
46 pub profile: Option<String>,
47 /// Explicit model override; always wins over `model_strength`.
48 pub model: Option<String>,
49 /// Relative model strength (`same`/`faster`, plus driver-side aliases).
50 pub model_strength: Option<String>,
51 /// Reasoning effort (`inherit`/`off`/`low`/`medium`/`high`/`max`).
52 pub thinking: Option<String>,
53 /// Run the child in a fresh git worktree for parallel edits.
54 pub worktree: bool,
55 /// Explicit child mutation authority. A write-capable value remains
56 /// fail-closed unless at least one bounded scope below is declared.
57 #[serde(default)]
58 pub write_authority: Option<String>,
59 /// Repo-relative directory trees the child expects to mutate.
60 #[serde(default)]
61 pub write_roots: Vec<String>,
62 /// Repo-relative exact files the child expects to mutate.
63 #[serde(default)]
64 pub exact_files: Vec<String>,
65 /// Named shared contracts owned by this child while active.
66 #[serde(default)]
67 pub coordination_contracts: Vec<String>,
68 /// Bounded prerequisite facts relevant to this child.
69 #[serde(default)]
70 pub dependencies: Vec<String>,
71 /// Bounded observable checks for child completion.
72 #[serde(default)]
73 pub acceptance: Vec<String>,
74 /// Explicit tool allowlist; required by the driver for `custom` roles.
75 pub allowed_tools: Option<Vec<String>>,
76 /// Per-call spawn-depth override (driver clamps to its ceiling).
77 pub max_depth: Option<u32>,
78 /// Explicit token budget: forks an isolated pool on the driver side.
79 /// Omit it so the child inherits (and debits) the shared run pool.
80 pub token_budget: Option<u64>,
81 /// Maximum model turns for this child (driver clamps to its ceiling).
82 pub max_steps: Option<u32>,
83 /// Hard wall-clock limit for this child in seconds.
84 pub wall_time_secs: Option<u64>,
85 /// JSON schema the reply must satisfy; validated in the VM after the
86 /// driver returns the raw text (see [`crate`] docs for decode rules).
87 pub response_schema: Option<serde_json::Value>,
88 /// Short human label for progress surfaces.
89 pub label: Option<String>,
90 /// Phase name this task belongs to, for progress grouping.
91 pub phase: Option<String>,
92}
93
94/// Terminal outcome of one spawned task, delivered over the completion
95/// oneshot. Everything except `Completed` becomes a JS throw on the awaiting
96/// `task()` call.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum TaskCompletion {
99 /// The child finished; `text` is the full, untruncated result.
100 Completed { text: String },
101 /// The child failed (error result, timeout, ...).
102 Failed { message: String },
103 /// The child was cancelled (cascade or explicit).
104 Cancelled,
105 /// The child's budget scope drained mid-flight.
106 BudgetExhausted { message: String },
107}
108
109/// A successfully admitted spawn: the driver-assigned task id (the engine's
110/// `agent_id`) plus the oneshot the driver resolves on completion.
111///
112/// Dropping the receiver must not wedge the driver; drivers should treat a
113/// closed completion channel as "nobody is listening" and move on.
114#[derive(Debug)]
115pub struct SpawnedTask {
116 /// Driver-assigned id, unique within the run (engine `agent_id`).
117 pub task_id: String,
118 /// Resolved exactly once with the terminal [`TaskCompletion`].
119 pub completion: oneshot::Receiver<TaskCompletion>,
120}
121
122/// Live view of the run's shared token pool, owned by the driver.
123///
124/// `total == None` means no ceiling is configured; JS then sees
125/// `budget.total === null` and `budget.remaining() === Infinity`.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
127pub struct BudgetSnapshot {
128 /// Pool ceiling in tokens, if one is configured.
129 pub total: Option<u64>,
130 /// Tokens spent (plus driver-side reservations) against the pool.
131 pub spent: u64,
132}
133
134impl BudgetSnapshot {
135 /// Tokens left before the ceiling; `None` when the pool is unbounded.
136 pub fn remaining(&self) -> Option<u64> {
137 self.total.map(|total| total.saturating_sub(self.spent))
138 }
139
140 /// True once the pool has a ceiling and it is fully consumed.
141 pub fn exhausted(&self) -> bool {
142 matches!(self.total, Some(total) if self.spent >= total)
143 }
144}
145
146/// Progress events emitted by the script (`log(..)` / `phase(..)`), delivered
147/// to the driver synchronously and in script order.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub enum ProgressEvent {
150 /// `log(msg)` — a narrator line for the UI.
151 Log {
152 /// The stringified message.
153 message: String,
154 },
155 /// `phase(title)` — the script entered a named phase.
156 Phase {
157 /// The phase title.
158 title: String,
159 },
160 /// A completed child returned text that failed the caller's
161 /// `responseSchema`. The VM emits this before throwing the validation
162 /// error back into the script so host-side receipts can mark the leaf as
163 /// failed instead of reporting a successful child beside a `null` result.
164 TaskSchemaValidationFailed {
165 /// Driver-assigned task id (engine `agent_id`).
166 task_id: String,
167 /// The validation error already surfaced to JS.
168 message: String,
169 },
170}
171
172/// Host-side executor for a Workflow run.
173///
174/// Implementations must be cheap to call from the VM thread: `spawn_task`
175/// admits the task and returns immediately (fire-and-forget spawn — never
176/// await the child inline), while `budget`, `progress`, and `cancel_all` are
177/// synchronous. `cancel_all` must be idempotent; it is invoked when the
178/// script errors, when the run future is dropped, and once more never hurts.
179#[async_trait]
180pub trait WorkflowDriver: Send + Sync {
181 /// Admit and start one task. Errors surface as a JS throw on the
182 /// corresponding `task()` call.
183 async fn spawn_task(&self, request: TaskRequest) -> Result<SpawnedTask, DriverError>;
184
185 /// Cancel every in-flight task belonging to this run. Idempotent.
186 fn cancel_all(&self);
187
188 /// Current snapshot of the run's shared token pool.
189 fn budget(&self) -> BudgetSnapshot;
190
191 /// Receive a script progress event (ordered, synchronous).
192 fn progress(&self, event: ProgressEvent);
193}
194
195/// Normalize and validate a Fleet profile token: trim, lowercase, then apply
196/// the same token rule as `crates/workflow`'s `validate_leaf_profile` —
197/// non-empty, no whitespace, and none of `"`, `'`, `` ` ``, `=`.
198pub fn normalize_profile(raw: &str) -> Result<String, String> {
199 let normalized = raw.trim().to_lowercase();
200 let invalid = normalized.is_empty()
201 || normalized
202 .chars()
203 .any(|ch| ch.is_whitespace() || matches!(ch, '"' | '\'' | '`' | '='));
204 if invalid {
205 return Err(format!(
206 "invalid profile token {raw:?}: profiles must be non-empty and contain no whitespace, quotes, backticks, or '='"
207 ));
208 }
209 Ok(normalized)
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 #[test]
217 fn normalize_profile_trims_and_lowercases() {
218 assert_eq!(normalize_profile(" ALpha-1 ").unwrap(), "alpha-1");
219 }
220
221 #[test]
222 fn normalize_profile_rejects_bad_tokens() {
223 for bad in ["", " ", "two words", "a=b", "a\"b", "a'b", "a`b"] {
224 assert!(
225 normalize_profile(bad).is_err(),
226 "expected rejection: {bad:?}"
227 );
228 }
229 }
230
231 #[test]
232 fn budget_snapshot_math() {
233 let unbounded = BudgetSnapshot {
234 total: None,
235 spent: 10,
236 };
237 assert_eq!(unbounded.remaining(), None);
238 assert!(!unbounded.exhausted());
239
240 let pool = BudgetSnapshot {
241 total: Some(100),
242 spent: 40,
243 };
244 assert_eq!(pool.remaining(), Some(60));
245 assert!(!pool.exhausted());
246
247 let drained = BudgetSnapshot {
248 total: Some(100),
249 spent: 120,
250 };
251 assert_eq!(drained.remaining(), Some(0));
252 assert!(drained.exhausted());
253 }
254
255 #[test]
256 fn legacy_task_request_defaults_new_coordination_fields() {
257 let legacy = serde_json::json!({
258 "description": "inspect the candidate",
259 "subagent_type": null,
260 "role": "reviewer",
261 "profile": null,
262 "model": null,
263 "model_strength": null,
264 "thinking": null,
265 "worktree": false,
266 "allowed_tools": null,
267 "max_depth": null,
268 "token_budget": null,
269 "max_steps": null,
270 "wall_time_secs": null,
271 "response_schema": null,
272 "label": null,
273 "phase": null
274 });
275
276 let request: TaskRequest = serde_json::from_value(legacy).unwrap();
277 assert_eq!(request.write_authority, None);
278 assert!(request.write_roots.is_empty());
279 assert!(request.exact_files.is_empty());
280 assert!(request.coordination_contracts.is_empty());
281 assert!(request.dependencies.is_empty());
282 assert!(request.acceptance.is_empty());
283 }
284}