Skip to main content

codewhale_workflow_js/
vm.rs

1//! The sandboxed QuickJS VM that executes Workflow scripts.
2//!
3//! Threading model (design §2.2): `rquickjs` contexts and every `'js` value
4//! are `!Send`, so each run gets a dedicated OS thread with its own
5//! current-thread tokio reactor. Host functions do no heavy work inline —
6//! only `Send` data (JSON strings, [`TaskRequest`]s, oneshot replies) crosses
7//! to the driver; conversion back into JS values happens on the VM thread
8//! after the await resolves.
9//!
10//! Sandbox: the context registers only standard ECMAScript intrinsics plus
11//! the Workflow globals (`task`, `parallel`, `pipeline`, `log`, `phase`,
12//! `budget`, `args`). There is no module loader, no fs/net/process access,
13//! and `Date`/`Math.random` are overridden to throw so recorded runs stay
14//! deterministic for replay.
15
16use std::cell::Cell;
17use std::env;
18use std::rc::Rc;
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::{Arc, OnceLock};
21
22use rquickjs::function::{Async, Func};
23use rquickjs::{AsyncContext, AsyncRuntime, CatchResultExt, CaughtError, Ctx, Promise, Value};
24use serde::Deserialize;
25use tokio::sync::{OwnedSemaphorePermit, Semaphore, oneshot, watch};
26
27use crate::driver::{ProgressEvent, TaskCompletion, TaskRequest, WorkflowDriver};
28use crate::error::WorkflowJsError;
29use crate::schema::{compile_schema, decode_reply};
30use crate::{PARALLEL_MAX_ITEMS, WORKFLOW_LIFETIME_CAP, normalize_profile};
31
32const DEFAULT_VM_MEMORY_LIMIT_BYTES: usize = 32 * 1024 * 1024;
33const MIN_VM_MEMORY_LIMIT_BYTES: usize = 4 * 1024 * 1024;
34const MAX_VM_MEMORY_LIMIT_BYTES: usize = 512 * 1024 * 1024;
35const DEFAULT_VM_STACK_BYTES: usize = 1024 * 1024;
36const MIN_VM_STACK_BYTES: usize = 128 * 1024;
37const MAX_VM_STACK_BYTES: usize = 8 * 1024 * 1024;
38const DEFAULT_VM_THREAD_STACK_BYTES: usize = 2 * 1024 * 1024;
39const MIN_VM_THREAD_STACK_BYTES: usize = 512 * 1024;
40const MAX_VM_THREAD_STACK_BYTES: usize = 16 * 1024 * 1024;
41const DEFAULT_MAX_CONCURRENT_VMS: usize = 4;
42const MAX_CONCURRENT_VMS: usize = 256;
43
44const VM_MEMORY_LIMIT_MB_ENV: &str = "CODEWHALE_WORKFLOW_JS_MEMORY_LIMIT_MB";
45const VM_STACK_KB_ENV: &str = "CODEWHALE_WORKFLOW_JS_STACK_KB";
46const VM_THREAD_STACK_KB_ENV: &str = "CODEWHALE_WORKFLOW_JS_THREAD_STACK_KB";
47const VM_MAX_CONCURRENT_ENV: &str = "CODEWHALE_WORKFLOW_JS_MAX_CONCURRENT";
48
49/// Resource limits applied to the QuickJS runtime before any script runs.
50///
51/// There is deliberately no wall-clock timeout here: cancellation (dropping
52/// the run future, or the driver's cancel cascade) is the deadline mechanism.
53#[derive(Debug, Clone, Copy)]
54pub struct VmLimits {
55    /// QuickJS heap ceiling in bytes (default 32 MiB).
56    pub memory_limit_bytes: usize,
57    /// Maximum interpreter stack in bytes (default 1 MiB).
58    pub max_stack_bytes: usize,
59}
60
61impl Default for VmLimits {
62    fn default() -> Self {
63        Self::from_env()
64    }
65}
66
67impl VmLimits {
68    pub fn from_env() -> Self {
69        Self {
70            memory_limit_bytes: env_usize_bytes(
71                VM_MEMORY_LIMIT_MB_ENV,
72                1024 * 1024,
73                MIN_VM_MEMORY_LIMIT_BYTES,
74                MAX_VM_MEMORY_LIMIT_BYTES,
75                DEFAULT_VM_MEMORY_LIMIT_BYTES,
76            ),
77            max_stack_bytes: env_usize_bytes(
78                VM_STACK_KB_ENV,
79                1024,
80                MIN_VM_STACK_BYTES,
81                MAX_VM_STACK_BYTES,
82                DEFAULT_VM_STACK_BYTES,
83            ),
84        }
85    }
86}
87
88fn env_usize_bytes(name: &str, unit: usize, min: usize, max: usize, default: usize) -> usize {
89    env::var(name)
90        .ok()
91        .and_then(|raw| raw.parse::<usize>().ok())
92        .and_then(|value| value.checked_mul(unit))
93        .map(|bytes| bytes.clamp(min, max))
94        .unwrap_or(default)
95}
96
97fn max_concurrent_vms() -> usize {
98    env::var(VM_MAX_CONCURRENT_ENV)
99        .ok()
100        .and_then(|raw| raw.parse::<usize>().ok())
101        .map(|value| value.clamp(1, MAX_CONCURRENT_VMS))
102        .unwrap_or(DEFAULT_MAX_CONCURRENT_VMS)
103}
104
105fn vm_thread_stack_bytes() -> usize {
106    env_usize_bytes(
107        VM_THREAD_STACK_KB_ENV,
108        1024,
109        MIN_VM_THREAD_STACK_BYTES,
110        MAX_VM_THREAD_STACK_BYTES,
111        DEFAULT_VM_THREAD_STACK_BYTES,
112    )
113}
114
115fn vm_admission() -> &'static Arc<Semaphore> {
116    static ADMISSION: OnceLock<Arc<Semaphore>> = OnceLock::new();
117    ADMISSION.get_or_init(|| Arc::new(Semaphore::new(max_concurrent_vms())))
118}
119
120/// Executes Workflow scripts, one isolated QuickJS runtime per run.
121///
122/// Every [`WorkflowVm::run_script`] call spins up a fresh interpreter on a
123/// dedicated thread, so runs share nothing (globals, heap, interned atoms)
124/// and a wedged script can never stall a sibling run.
125#[derive(Debug, Clone, Default)]
126pub struct WorkflowVm {
127    limits: VmLimits,
128}
129
130impl WorkflowVm {
131    /// A VM with the default [`VmLimits`].
132    pub fn new() -> Self {
133        Self::default()
134    }
135
136    /// A VM with explicit resource limits.
137    pub fn with_limits(limits: VmLimits) -> Self {
138        Self { limits }
139    }
140
141    /// Run one Workflow script to completion.
142    ///
143    /// * `source` is the script body; it is wrapped in an async function, so
144    ///   top-level `await` and `return` both work. The returned value is the
145    ///   script's `return` value, JSON-encoded (`undefined` becomes `null`).
146    /// * `args` is exposed verbatim to the script as the `args` global.
147    /// * `driver` executes `task()` spawns and receives progress events. A
148    ///   driver instance is scoped to exactly one run: `cancel_all` is always
149    ///   invoked at run teardown (success, script error, or cancellation), so
150    ///   stray children never outlive the script that spawned them.
151    ///
152    /// Cancellation cascade (design §9): dropping the returned future cancels
153    /// the run — the interrupt handler aborts executing JS, pending `task()`
154    /// awaits resolve to errors, and `driver.cancel_all()` is invoked
155    /// immediately from the dropping thread.
156    pub async fn run_script(
157        &self,
158        source: &str,
159        args: serde_json::Value,
160        driver: Arc<dyn WorkflowDriver>,
161    ) -> Result<serde_json::Value, WorkflowJsError> {
162        self.run_script_with_cancel(source, args, driver, WorkflowRunCancel::new())
163            .await
164    }
165
166    /// Like [`Self::run_script`], but accepts an external cancel handle so the
167    /// host can interrupt the VM without dropping the run future.
168    pub async fn run_script_with_cancel(
169        &self,
170        source: &str,
171        args: serde_json::Value,
172        driver: Arc<dyn WorkflowDriver>,
173        cancel: WorkflowRunCancel,
174    ) -> Result<serde_json::Value, WorkflowJsError> {
175        let args_json = serde_json::to_string(&args)
176            .map_err(|err| WorkflowJsError::InvalidArgs(err.to_string()))?;
177        let cancel = cancel.0;
178        let (result_tx, result_rx) = oneshot::channel();
179        let mut guard = RunGuard {
180            cancel: cancel.clone(),
181            driver: driver.clone(),
182            armed: true,
183        };
184
185        let permit = vm_admission()
186            .clone()
187            .acquire_owned()
188            .await
189            .map_err(|_| WorkflowJsError::VmInit("VM admission gate closed".to_string()))?;
190        let limits = self.limits;
191        let source = source.to_string();
192        let thread_driver = driver.clone();
193        let thread_cancel = cancel.clone();
194        let spawned = std::thread::Builder::new()
195            .name("workflow-js-vm".to_string())
196            .stack_size(vm_thread_stack_bytes())
197            .spawn(move || {
198                let _permit: OwnedSemaphorePermit = permit;
199                let outcome = vm_thread_main(
200                    source,
201                    args_json,
202                    thread_driver.clone(),
203                    thread_cancel,
204                    limits,
205                );
206                // Run teardown: this driver is scoped to one run, so any task
207                // still in flight is unreachable now — cancel the cascade.
208                thread_driver.cancel_all();
209                let _ = result_tx.send(outcome);
210            });
211        if let Err(err) = spawned {
212            guard.armed = false;
213            return Err(WorkflowJsError::VmInit(format!(
214                "failed to spawn VM thread: {err}"
215            )));
216        }
217
218        match result_rx.await {
219            Ok(outcome) => {
220                // The VM thread has already torn down and cancelled children.
221                guard.armed = false;
222                outcome
223            }
224            // VM thread panicked before reporting; leave the guard armed so
225            // its drop (right now, at return) cancels outstanding tasks.
226            Err(_) => Err(WorkflowJsError::VmTerminated(
227                "VM thread exited without reporting a result".to_string(),
228            )),
229        }
230    }
231}
232
233/// Cooperative cancel signal shared by the run future (guard side) and the VM
234/// thread. The atomic flag feeds the QuickJS interrupt handler (sync, called
235/// mid-bytecode); the watch channel wakes host futures parked on driver
236/// completions.
237#[derive(Clone)]
238pub struct WorkflowRunCancel(CancelHandle);
239
240impl WorkflowRunCancel {
241    #[must_use]
242    pub fn new() -> Self {
243        Self(CancelHandle::new())
244    }
245
246    pub fn cancel(&self) {
247        self.0.cancel();
248    }
249}
250
251impl Default for WorkflowRunCancel {
252    fn default() -> Self {
253        Self::new()
254    }
255}
256
257#[derive(Clone)]
258struct CancelHandle {
259    flag: Arc<AtomicBool>,
260    tx: Arc<watch::Sender<bool>>,
261}
262
263impl CancelHandle {
264    fn new() -> Self {
265        let (tx, _rx) = watch::channel(false);
266        Self {
267            flag: Arc::new(AtomicBool::new(false)),
268            tx: Arc::new(tx),
269        }
270    }
271
272    fn cancel(&self) {
273        self.flag.store(true, Ordering::SeqCst);
274        self.tx.send_replace(true);
275    }
276
277    fn is_cancelled(&self) -> bool {
278        self.flag.load(Ordering::SeqCst)
279    }
280
281    async fn cancelled(&self) {
282        let mut rx = self.tx.subscribe();
283        let _ = rx.wait_for(|cancelled| *cancelled).await;
284    }
285
286    fn flag_arc(&self) -> Arc<AtomicBool> {
287        self.flag.clone()
288    }
289}
290
291/// Fires the cancel cascade if the caller drops the run future before the VM
292/// reports a result.
293struct RunGuard {
294    cancel: CancelHandle,
295    driver: Arc<dyn WorkflowDriver>,
296    armed: bool,
297}
298
299impl Drop for RunGuard {
300    fn drop(&mut self) {
301        if self.armed {
302            self.cancel.cancel();
303            self.driver.cancel_all();
304        }
305    }
306}
307
308fn vm_thread_main(
309    source: String,
310    args_json: String,
311    driver: Arc<dyn WorkflowDriver>,
312    cancel: CancelHandle,
313    limits: VmLimits,
314) -> Result<serde_json::Value, WorkflowJsError> {
315    let reactor = tokio::runtime::Builder::new_current_thread()
316        .enable_all()
317        .build()
318        .map_err(|err| WorkflowJsError::VmInit(format!("failed to build VM reactor: {err}")))?;
319    reactor.block_on(run_in_vm(source, args_json, driver, cancel, limits))
320}
321
322async fn run_in_vm(
323    source: String,
324    args_json: String,
325    driver: Arc<dyn WorkflowDriver>,
326    cancel: CancelHandle,
327    limits: VmLimits,
328) -> Result<serde_json::Value, WorkflowJsError> {
329    let runtime = AsyncRuntime::new().map_err(|err| WorkflowJsError::VmInit(err.to_string()))?;
330    runtime.set_memory_limit(limits.memory_limit_bytes).await;
331    runtime.set_max_stack_size(limits.max_stack_bytes).await;
332    let interrupt_flag = cancel.flag_arc();
333    runtime
334        .set_interrupt_handler(Some(Box::new(move || {
335            interrupt_flag.load(Ordering::Acquire)
336        })))
337        .await;
338    let context = AsyncContext::full(&runtime)
339        .await
340        .map_err(|err| WorkflowJsError::VmInit(err.to_string()))?;
341
342    let result = context
343        .async_with(async |ctx| run_in_ctx(ctx, source, args_json, driver, cancel).await)
344        .await;
345    drop(context);
346    runtime.run_gc().await;
347    result
348}
349
350async fn run_in_ctx(
351    ctx: Ctx<'_>,
352    source: String,
353    args_json: String,
354    driver: Arc<dyn WorkflowDriver>,
355    cancel: CancelHandle,
356) -> Result<serde_json::Value, WorkflowJsError> {
357    install_host(&ctx, driver, cancel.clone(), &args_json)?;
358    ctx.eval::<(), _>(prelude())
359        .catch(&ctx)
360        .map_err(|err| WorkflowJsError::VmInit(format!("prelude failed: {err}")))?;
361
362    let desugared = desugar_export_default(&source);
363    let wrapped = format!("(async () => {{\n{desugared}\n}})()");
364    let promise = ctx
365        .eval::<Promise, _>(wrapped)
366        .catch(&ctx)
367        .map_err(|err| script_error(&cancel, err))?;
368    let value = promise
369        .into_future::<Value>()
370        .await
371        .catch(&ctx)
372        .map_err(|err| script_error(&cancel, err))?;
373    js_value_to_json(&ctx, value)
374}
375
376/// Rewrite the documented module-style authoring shape
377/// (`export default async function (args) { ... }`) into the script form the
378/// VM actually evals. Sources are wrapped in an async IIFE, where the
379/// module-only `export` keyword is a syntax error, so without this every
380/// imperative `export default` workflow (including the #4131 dogfood
381/// fixtures) failed to parse. The default export is captured, invoked with
382/// the `args` global when it is a function, and its result becomes the run
383/// result; a non-function default export is returned as-is.
384fn desugar_export_default(source: &str) -> String {
385    const EXPORT_DEFAULT: &str = "export default";
386    let Some(offset) = line_leading_export_default(source) else {
387        return source.to_string();
388    };
389    let mut out = source.to_string();
390    out.replace_range(
391        offset..offset + EXPORT_DEFAULT.len(),
392        "globalThis.__workflow_default =",
393    );
394    out.push('\n');
395    out.push_str(
396        ";{\n  const __wf_default = globalThis.__workflow_default;\n  delete globalThis.__workflow_default;\n  if (typeof __wf_default === \"function\") {\n    return await __wf_default(args);\n  }\n  if (__wf_default !== undefined) {\n    return __wf_default;\n  }\n}\n",
397    );
398    out
399}
400
401/// Return the byte offset of a line-leading `export default` token that is
402/// actual JavaScript syntax, not text inside a string, template literal, or
403/// comment. This intentionally recognizes only the documented authoring shape
404/// instead of attempting to implement a general JavaScript module parser.
405fn line_leading_export_default(source: &str) -> Option<usize> {
406    const EXPORT_DEFAULT: &[u8] = b"export default";
407    let bytes = source.as_bytes();
408    let mut idx = 0usize;
409    let mut quote = None;
410    let mut escaped = false;
411    let mut line_comment = false;
412    let mut block_comment = false;
413    let mut line_has_only_whitespace = true;
414
415    while idx < bytes.len() {
416        let byte = bytes[idx];
417
418        if line_comment {
419            if byte == b'\n' {
420                line_comment = false;
421                line_has_only_whitespace = true;
422            }
423            idx += 1;
424            continue;
425        }
426
427        if block_comment {
428            if byte == b'*' && bytes.get(idx + 1) == Some(&b'/') {
429                block_comment = false;
430                line_has_only_whitespace = false;
431                idx += 2;
432                continue;
433            }
434            if byte == b'\n' {
435                line_has_only_whitespace = true;
436            } else if !byte.is_ascii_whitespace() {
437                line_has_only_whitespace = false;
438            }
439            idx += 1;
440            continue;
441        }
442
443        if let Some(active_quote) = quote {
444            if byte == b'\n' {
445                line_has_only_whitespace = true;
446                escaped = false;
447            } else {
448                if !byte.is_ascii_whitespace() {
449                    line_has_only_whitespace = false;
450                }
451                if escaped {
452                    escaped = false;
453                } else if byte == b'\\' {
454                    escaped = true;
455                } else if byte == active_quote {
456                    quote = None;
457                }
458            }
459            idx += 1;
460            continue;
461        }
462
463        if byte == b'\n' {
464            line_has_only_whitespace = true;
465            idx += 1;
466            continue;
467        }
468        if line_has_only_whitespace && byte.is_ascii_whitespace() {
469            idx += 1;
470            continue;
471        }
472        if line_has_only_whitespace && bytes[idx..].starts_with(EXPORT_DEFAULT) {
473            return Some(idx);
474        }
475
476        line_has_only_whitespace = false;
477        if byte == b'/' && bytes.get(idx + 1) == Some(&b'/') {
478            line_comment = true;
479            idx += 2;
480        } else if byte == b'/' && bytes.get(idx + 1) == Some(&b'*') {
481            block_comment = true;
482            idx += 2;
483        } else {
484            if matches!(byte, b'\'' | b'"' | b'`') {
485                quote = Some(byte);
486            }
487            idx += 1;
488        }
489    }
490
491    None
492}
493
494fn script_error(cancel: &CancelHandle, err: CaughtError<'_>) -> WorkflowJsError {
495    if cancel.is_cancelled() {
496        WorkflowJsError::Cancelled
497    } else {
498        WorkflowJsError::Script(err.to_string())
499    }
500}
501
502fn js_value_to_json<'js>(
503    ctx: &Ctx<'js>,
504    value: Value<'js>,
505) -> Result<serde_json::Value, WorkflowJsError> {
506    if value.is_undefined() {
507        return Ok(serde_json::Value::Null);
508    }
509    let text = ctx
510        .json_stringify(value)
511        .map_err(|err| WorkflowJsError::ResultEncoding(err.to_string()))?;
512    match text {
513        None => Ok(serde_json::Value::Null),
514        Some(text) => {
515            let text = text
516                .to_string()
517                .map_err(|err| WorkflowJsError::ResultEncoding(err.to_string()))?;
518            serde_json::from_str(&text)
519                .map_err(|err| WorkflowJsError::ResultEncoding(err.to_string()))
520        }
521    }
522}
523
524fn install_host(
525    ctx: &Ctx<'_>,
526    driver: Arc<dyn WorkflowDriver>,
527    cancel: CancelHandle,
528    args_json: &str,
529) -> Result<(), WorkflowJsError> {
530    let globals = ctx.globals();
531
532    let args_value: Value = ctx
533        .json_parse(args_json)
534        .map_err(|err| WorkflowJsError::InvalidArgs(err.to_string()))?;
535    globals.set("args", args_value).map_err(init_err)?;
536
537    // Per-run lifetime counter (design §4.3): counts spawn *attempts*, and the
538    // check + increment happen with no await in between so a parallel burst
539    // cannot slip past the cap on the single-threaded VM.
540    let spawned = Rc::new(Cell::new(0u64));
541
542    let task_driver = driver.clone();
543    let task_cancel = cancel.clone();
544    globals
545        .set(
546            "__workflow_task",
547            Func::from(Async(move |opts_json: String| {
548                let driver = task_driver.clone();
549                let cancel = task_cancel.clone();
550                let spawned = spawned.clone();
551                async move { task_host(opts_json, driver, cancel, spawned).await }
552            })),
553        )
554        .map_err(init_err)?;
555
556    let log_driver = driver.clone();
557    globals
558        .set(
559            "__workflow_log",
560            Func::from(move |message: String| {
561                log_driver.progress(ProgressEvent::Log { message });
562            }),
563        )
564        .map_err(init_err)?;
565
566    let phase_driver = driver.clone();
567    globals
568        .set(
569            "__workflow_phase",
570            Func::from(move |title: String| {
571                phase_driver.progress(ProgressEvent::Phase { title });
572            }),
573        )
574        .map_err(init_err)?;
575
576    // Budget reads are live driver snapshots (design §5.2). NaN encodes
577    // "no ceiling" for `total`; the prelude maps it to `null`.
578    let total_driver = driver.clone();
579    globals
580        .set(
581            "__workflow_budget_total",
582            Func::from(move || -> f64 {
583                match total_driver.budget().total {
584                    Some(total) => total as f64,
585                    None => f64::NAN,
586                }
587            }),
588        )
589        .map_err(init_err)?;
590
591    let spent_driver = driver.clone();
592    globals
593        .set(
594            "__workflow_budget_spent",
595            Func::from(move || -> f64 { spent_driver.budget().spent as f64 }),
596        )
597        .map_err(init_err)?;
598
599    globals
600        .set(
601            "__workflow_budget_remaining",
602            Func::from(move || -> f64 {
603                match driver.budget().remaining() {
604                    Some(remaining) => remaining as f64,
605                    None => f64::INFINITY,
606                }
607            }),
608        )
609        .map_err(init_err)?;
610
611    Ok(())
612}
613
614fn init_err(err: rquickjs::Error) -> WorkflowJsError {
615    WorkflowJsError::VmInit(err.to_string())
616}
617
618/// The `task()` host call. Everything that can go wrong is reported through
619/// the JSON envelope (`{"error": ...}`) so the prelude re-throws it as a real
620/// JS `Error` with a script-side stack.
621async fn task_host(
622    opts_json: String,
623    driver: Arc<dyn WorkflowDriver>,
624    cancel: CancelHandle,
625    spawned: Rc<Cell<u64>>,
626) -> String {
627    let outcome = task_host_inner(opts_json, driver, cancel, spawned).await;
628    let envelope = match outcome {
629        Ok(value) => serde_json::json!({ "value": value }),
630        Err(message) => serde_json::json!({ "error": message }),
631    };
632    envelope.to_string()
633}
634
635async fn task_host_inner(
636    opts_json: String,
637    driver: Arc<dyn WorkflowDriver>,
638    cancel: CancelHandle,
639    spawned: Rc<Cell<u64>>,
640) -> Result<serde_json::Value, String> {
641    let request = parse_task_options(&opts_json)?;
642    // Compile the schema before spawning so a malformed one fails fast
643    // instead of burning a subagent.
644    let validator = request
645        .response_schema
646        .as_ref()
647        .map(compile_schema)
648        .transpose()?;
649
650    // Lifetime backstop (design §4.3) — checked and bumped before any await.
651    if spawned.get() >= WORKFLOW_LIFETIME_CAP {
652        return Err(format!(
653            "task(): Workflow lifetime agent cap ({WORKFLOW_LIFETIME_CAP}) reached for this run"
654        ));
655    }
656    // Fast-fail budget gate. The authoritative reservation lives in the
657    // driver (design §5.3); this only stops obviously-doomed spawns early.
658    let snapshot = driver.budget();
659    if snapshot.exhausted() {
660        return Err(format!(
661            "task(): budget exhausted ({} of {} tokens spent)",
662            snapshot.spent,
663            snapshot.total.unwrap_or(0)
664        ));
665    }
666    if cancel.is_cancelled() {
667        return Err("task(): run cancelled".to_string());
668    }
669    spawned.set(spawned.get() + 1);
670
671    let spawned_task = driver
672        .spawn_task(request)
673        .await
674        .map_err(|err| err.to_string())?;
675    let task_id = spawned_task.task_id;
676    let completion_rx = spawned_task.completion;
677    let completion = tokio::select! {
678        _ = cancel.cancelled() => return Err("task(): run cancelled".to_string()),
679        completion = completion_rx => completion
680            .map_err(|_| "task(): driver dropped the completion channel".to_string())?,
681    };
682
683    match completion {
684        TaskCompletion::Completed { text } => match &validator {
685            None => Ok(serde_json::Value::String(text)),
686            Some(validator) => match decode_reply(&text, validator) {
687                Ok(value) => Ok(value),
688                Err(message) => {
689                    driver.progress(ProgressEvent::TaskSchemaValidationFailed {
690                        task_id,
691                        message: message.clone(),
692                    });
693                    Err(message)
694                }
695            },
696        },
697        TaskCompletion::Failed { message } => Err(format!("task(): subagent failed: {message}")),
698        TaskCompletion::Cancelled => Err("task(): subagent cancelled".to_string()),
699        TaskCompletion::BudgetExhausted { message } => {
700            Err(format!("task(): budget exhausted: {message}"))
701        }
702    }
703}
704
705/// JS-facing option names for `task()` (design §3.3). Unknown fields are
706/// rejected so a typo (`responseschema`) fails loudly instead of being
707/// silently dropped.
708#[derive(Debug, Deserialize)]
709#[serde(rename_all = "camelCase", deny_unknown_fields)]
710struct TaskOptions {
711    description: Option<String>,
712    prompt: Option<String>,
713    #[serde(alias = "type")]
714    subagent_type: Option<String>,
715    /// Fleet role name (#4177). Preferred step identity field.
716    role: Option<String>,
717    profile: Option<String>,
718    model: Option<String>,
719    model_strength: Option<String>,
720    thinking: Option<String>,
721    cwd: Option<String>,
722    #[serde(default)]
723    worktree: bool,
724    write_authority: Option<String>,
725    #[serde(default)]
726    write_roots: Vec<String>,
727    #[serde(default)]
728    exact_files: Vec<String>,
729    #[serde(default)]
730    coordination_contracts: Vec<String>,
731    #[serde(default)]
732    dependencies: Vec<String>,
733    #[serde(default)]
734    acceptance: Vec<String>,
735    allowed_tools: Option<Vec<String>>,
736    max_depth: Option<u32>,
737    token_budget: Option<u64>,
738    max_steps: Option<u32>,
739    wall_time_secs: Option<u64>,
740    response_schema: Option<serde_json::Value>,
741    label: Option<String>,
742    phase: Option<String>,
743}
744
745fn parse_task_options(opts_json: &str) -> Result<TaskRequest, String> {
746    let mut options: TaskOptions =
747        serde_json::from_str(opts_json).map_err(|err| format!("task(): invalid options: {err}"))?;
748    let description = options
749        .prompt
750        .or(options.description)
751        .filter(|description| !description.trim().is_empty())
752        .ok_or_else(|| "task(): 'description' (or 'prompt') is required".to_string())?;
753    let role = options
754        .role
755        .as_deref()
756        .map(normalize_profile)
757        .transpose()
758        .map_err(|err| format!("task(): role: {err}"))?;
759    let profile = options
760        .profile
761        .as_deref()
762        .map(normalize_profile)
763        .transpose()
764        .map_err(|err| format!("task(): {err}"))?;
765    options.write_roots = normalize_task_paths("writeRoots", options.write_roots, 32)?;
766    options.exact_files = normalize_task_paths("exactFiles", options.exact_files, 32)?;
767    let cwd = options
768        .cwd
769        .take()
770        .map(|value| normalize_task_paths("cwd", vec![value], 1))
771        .transpose()?
772        .and_then(|mut paths| paths.pop());
773    options.coordination_contracts =
774        normalize_task_string_list("coordinationContracts", options.coordination_contracts, 16)?;
775    options.dependencies = normalize_task_string_list("dependencies", options.dependencies, 8)?;
776    options.acceptance = normalize_task_string_list("acceptance", options.acceptance, 8)?;
777    let write_authority = options
778        .write_authority
779        .as_deref()
780        .map(|value| value.trim().to_ascii_lowercase())
781        .map(|value| match value.as_str() {
782            "read_only" | "workspace_write" | "worktree_write" => Ok(value),
783            _ => Err(format!(
784                "task(): writeAuthority must be read_only, workspace_write, or worktree_write; got {value:?}"
785            )),
786        })
787        .transpose()?;
788    if write_authority.as_deref() == Some("worktree_write") && !options.worktree {
789        return Err("task(): writeAuthority worktree_write requires worktree: true".to_string());
790    }
791    let role_kind = role.as_deref().and_then(task_role_kind);
792    let type_kind = options.subagent_type.as_deref().and_then(task_role_kind);
793    if let (Some(role_kind), Some(type_kind)) = (role_kind, type_kind)
794        && role_kind != type_kind
795    {
796        return Err("task(): role and subagentType declare contradictory authorities".to_string());
797    }
798    let declared_kind = role_kind.or(type_kind);
799    if matches!(declared_kind, Some(TaskRoleKind::ReadOnly))
800        && write_authority
801            .as_deref()
802            .is_some_and(|authority| authority != "read_only")
803    {
804        return Err("task(): read-only roles cannot declare write-capable authority".to_string());
805    }
806    if write_authority
807        .as_deref()
808        .is_some_and(|authority| authority != "read_only")
809        && options.write_roots.is_empty()
810        && options.exact_files.is_empty()
811        && options.coordination_contracts.is_empty()
812    {
813        return Err(
814            "task(): write-capable authority requires writeRoots, exactFiles, or coordinationContracts"
815                .to_string(),
816        );
817    }
818    let explicit_write_identity = declared_kind == Some(TaskRoleKind::Implementer)
819        || (declared_kind == Some(TaskRoleKind::General)
820            && (role.is_some() || options.subagent_type.is_some()))
821        || (profile.is_some() && declared_kind.is_none());
822    if explicit_write_identity
823        && write_authority.as_deref() != Some("read_only")
824        && options.write_roots.is_empty()
825        && options.exact_files.is_empty()
826        && options.coordination_contracts.is_empty()
827    {
828        return Err(
829            "task(): explicit write-capable identities require writeRoots, exactFiles, or coordinationContracts"
830                .to_string(),
831        );
832    }
833    Ok(TaskRequest {
834        description,
835        subagent_type: options.subagent_type,
836        role,
837        profile,
838        model: options.model,
839        model_strength: options.model_strength,
840        thinking: options.thinking,
841        cwd,
842        worktree: options.worktree,
843        write_authority,
844        write_roots: options.write_roots,
845        exact_files: options.exact_files,
846        coordination_contracts: options.coordination_contracts,
847        dependencies: options.dependencies,
848        acceptance: options.acceptance,
849        allowed_tools: options.allowed_tools,
850        // Host-imposed only: a script cannot set (or clear) a deny list.
851        disallowed_tools: Vec::new(),
852        max_depth: options.max_depth,
853        token_budget: options.token_budget,
854        max_steps: options.max_steps,
855        wall_time_secs: options.wall_time_secs,
856        response_schema: options.response_schema,
857        label: options.label,
858        phase: options.phase,
859    })
860}
861
862fn normalize_task_string_list(
863    field: &str,
864    values: Vec<String>,
865    limit: usize,
866) -> Result<Vec<String>, String> {
867    if values.len() > limit {
868        return Err(format!("task(): {field} accepts at most {limit} entries"));
869    }
870    let mut normalized = Vec::new();
871    for value in values {
872        let value = value.trim();
873        if value.is_empty() || value.chars().count() > 512 {
874            return Err(format!(
875                "task(): {field} entries must be 1..=512 characters"
876            ));
877        }
878        if !normalized.iter().any(|existing| existing == value) {
879            normalized.push(value.to_string());
880        }
881    }
882    Ok(normalized)
883}
884
885fn normalize_task_paths(
886    field: &str,
887    values: Vec<String>,
888    limit: usize,
889) -> Result<Vec<String>, String> {
890    if values.len() > limit {
891        return Err(format!("task(): {field} accepts at most {limit} entries"));
892    }
893    let mut normalized = Vec::new();
894    for raw in values {
895        let raw = raw.trim().replace('\\', "/");
896        let windows_drive = raw.as_bytes().get(1) == Some(&b':')
897            && raw.as_bytes().first().is_some_and(u8::is_ascii_alphabetic);
898        if raw.is_empty()
899            || raw.chars().count() > 512
900            || raw.starts_with('/')
901            || raw.starts_with("//")
902            || windows_drive
903            || raw.chars().any(|ch| matches!(ch, '\0' | '\r' | '\n'))
904        {
905            return Err(format!(
906                "task(): {field} entries must be bounded repo-relative paths"
907            ));
908        }
909        let mut segments = Vec::new();
910        for segment in raw.split('/') {
911            match segment {
912                "" | "." => {}
913                ".." => {
914                    return Err(format!(
915                        "task(): {field} paths cannot contain parent traversal"
916                    ));
917                }
918                value => segments.push(value),
919            }
920        }
921        let path = if segments.is_empty() {
922            ".".to_string()
923        } else {
924            segments.join("/")
925        };
926        if !normalized.contains(&path) {
927            normalized.push(path);
928        }
929    }
930    Ok(normalized)
931}
932
933#[derive(Debug, Clone, Copy, PartialEq, Eq)]
934enum TaskRoleKind {
935    ReadOnly,
936    General,
937    Implementer,
938}
939
940fn task_role_kind(value: &str) -> Option<TaskRoleKind> {
941    match value.trim().to_ascii_lowercase().as_str() {
942        "explore" | "explorer" | "scout" | "plan" | "planner" | "review" | "reviewer"
943        | "verify" | "verifier" => Some(TaskRoleKind::ReadOnly),
944        "general" | "worker" => Some(TaskRoleKind::General),
945        "implement" | "implementer" | "builder" => Some(TaskRoleKind::Implementer),
946        _ => None,
947    }
948}
949
950/// The JS prelude injected before every script: determinism bans, the
951/// `task`/`parallel`/`pipeline`/`log`/`phase` stdlib (design §7), and the
952/// `budget` global.
953fn prelude() -> String {
954    PRELUDE_TEMPLATE.replace("__MAX_ITEMS__", &PARALLEL_MAX_ITEMS.to_string())
955}
956
957const PRELUDE_TEMPLATE: &str = r#""use strict";
958(() => {
959  const banned = (name) => () => {
960    throw new Error(name + " is unavailable in Workflow scripts: runs must be deterministic for record/replay");
961  };
962  const BannedDate = function Date() {
963    throw new Error("new Date()/Date() is unavailable in Workflow scripts: runs must be deterministic for record/replay");
964  };
965  BannedDate.now = banned("Date.now()");
966  BannedDate.parse = banned("Date.parse()");
967  BannedDate.UTC = banned("Date.UTC()");
968  globalThis.Date = BannedDate;
969  Math.random = banned("Math.random()");
970
971  // Capture temporary host bindings into this closure, then strip them from
972  // globalThis so scripts only see the documented Workflow surface (#4129).
973  const hostTask = __workflow_task;
974  const hostLog = __workflow_log;
975  const hostPhase = __workflow_phase;
976  const hostBudgetTotal = __workflow_budget_total;
977  const hostBudgetSpent = __workflow_budget_spent;
978  const hostBudgetRemaining = __workflow_budget_remaining;
979
980  const MAX_ITEMS = __MAX_ITEMS__;
981  const taskErrorText = (err) => String(err && err.message !== undefined ? err.message : err);
982  const isFatalTaskError = (err) => {
983    const text = taskErrorText(err);
984    return text.includes("responseSchema") || text.includes("run cancelled");
985  };
986
987  globalThis.task = async (opts) => {
988    if (opts === null || typeof opts !== "object") {
989      throw new TypeError("task(): expected an options object");
990    }
991    const envelope = JSON.parse(await hostTask(JSON.stringify(opts)));
992    if (envelope.error !== undefined) {
993      throw new Error(envelope.error);
994    }
995    return envelope.value;
996  };
997
998  globalThis.parallel = (thunks) => {
999    if (!Array.isArray(thunks)) {
1000      throw new TypeError("parallel(): expected an array of thunks");
1001    }
1002    if (thunks.length > MAX_ITEMS) {
1003      throw new Error("parallel(): max " + MAX_ITEMS + " items per call");
1004    }
1005    return Promise.all(thunks.map((thunk) => {
1006      try {
1007        return Promise.resolve(typeof thunk === "function" ? thunk() : thunk).catch((err) => {
1008          if (isFatalTaskError(err)) throw err;
1009          hostLog("parallel(): dropped a failed slot as null: " + String((err && err.message) || err));
1010          return null;
1011        });
1012      } catch (err) {
1013        if (isFatalTaskError(err)) return Promise.reject(err);
1014        hostLog("parallel(): dropped a failed slot as null: " + String((err && err.message) || err));
1015        return null;
1016      }
1017    }));
1018  };
1019
1020  globalThis.pipeline = (items, ...stages) => {
1021    if (!Array.isArray(items)) {
1022      throw new TypeError("pipeline(): expected an array of items");
1023    }
1024    if (items.length > MAX_ITEMS) {
1025      throw new Error("pipeline(): max " + MAX_ITEMS + " items per call");
1026    }
1027    return Promise.all(items.map(async (item, index) => {
1028      let value = item;
1029      for (const stage of stages) {
1030        try {
1031          value = await stage(value, item, index);
1032        } catch (err) {
1033          if (isFatalTaskError(err)) throw err;
1034          hostLog("pipeline(): dropped item " + index + " as null: " + String((err && err.message) || err));
1035          return null;
1036        }
1037      }
1038      return value;
1039    }));
1040  };
1041
1042  globalThis.log = (message) => {
1043    hostLog(typeof message === "string" ? message : (JSON.stringify(message) ?? String(message)));
1044  };
1045  globalThis.phase = (title) => {
1046    hostPhase(String(title));
1047  };
1048
1049  const total = hostBudgetTotal();
1050  globalThis.budget = Object.freeze({
1051    total: Number.isNaN(total) ? null : total,
1052    spent: () => hostBudgetSpent(),
1053    remaining: () => hostBudgetRemaining(),
1054  });
1055
1056  for (const name of [
1057    "__workflow_task",
1058    "__workflow_log",
1059    "__workflow_phase",
1060    "__workflow_budget_total",
1061    "__workflow_budget_spent",
1062    "__workflow_budget_remaining",
1063  ]) {
1064    try {
1065      delete globalThis[name];
1066    } catch (_) {
1067      // Non-configurable bindings stay; the inventory test will fail closed.
1068    }
1069  }
1070})();
1071"#;