返回 CodeWhale
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
16 use std::collections::HashMap;
17 use std::env;
18 use std::future::Future;
19 use std::sync::atomic::{AtomicBool, Ordering};
20 use std::sync::{Arc, Mutex, OnceLock};
21
22 use rquickjs::function::{Async, Func};
23 use rquickjs::{AsyncContext, AsyncRuntime, CatchResultExt, CaughtError, Ctx, Promise, Value};
24 use serde::Deserialize;
25 use tokio::runtime::Handle;
26 use tokio::sync::{OwnedSemaphorePermit, Semaphore, oneshot, watch};
27 use tokio::task::JoinSet;
28
29 use crate::driver::{ProgressEvent, TaskCompletion, TaskRequest, WorkflowDriver};
30 use crate::error::{TaskError, TaskErrorKind, WorkflowJsError};
31 use crate::schema::{
32 ReplyDecodeError, SCHEMA_REPAIR_MAX_ATTEMPTS, carried_raw, compile_schema, decode_reply,
33 repair_prompt,
34 };
35 use crate::{PARALLEL_MAX_ITEMS, ToolCallRequest, ToolInvoker, normalize_profile};
36
37 const DEFAULT_VM_MEMORY_LIMIT_BYTES: usize = 32 * 1024 * 1024;
38 const MIN_VM_MEMORY_LIMIT_BYTES: usize = 4 * 1024 * 1024;
39 const MAX_VM_MEMORY_LIMIT_BYTES: usize = 512 * 1024 * 1024;
40 const DEFAULT_VM_STACK_BYTES: usize = 1024 * 1024;
41 const MIN_VM_STACK_BYTES: usize = 128 * 1024;
42 const MAX_VM_STACK_BYTES: usize = 8 * 1024 * 1024;
43 const DEFAULT_VM_THREAD_STACK_BYTES: usize = 2 * 1024 * 1024;
44 const MIN_VM_THREAD_STACK_BYTES: usize = 512 * 1024;
45 const MAX_VM_THREAD_STACK_BYTES: usize = 16 * 1024 * 1024;
46 const DEFAULT_MAX_CONCURRENT_VMS: usize = 4;
47 const MAX_CONCURRENT_VMS: usize = 256;
48 const MAX_VM_SOURCE_BYTES: usize = 1024 * 1024;
49 const MAX_VM_ARGS_BYTES: usize = 8 * 1024 * 1024;
50
51 const VM_MEMORY_LIMIT_MB_ENV: &str = "CODEWHALE_WORKFLOW_JS_MEMORY_LIMIT_MB";
52 const VM_STACK_KB_ENV: &str = "CODEWHALE_WORKFLOW_JS_STACK_KB";
53 const VM_THREAD_STACK_KB_ENV: &str = "CODEWHALE_WORKFLOW_JS_THREAD_STACK_KB";
54 const VM_MAX_CONCURRENT_ENV: &str = "CODEWHALE_WORKFLOW_JS_MAX_CONCURRENT";
55
56 /// Resource limits applied to the QuickJS runtime before any script runs.
57 ///
58 /// There is deliberately no wall-clock timeout here: cancellation (dropping
59 /// the run future, or the driver's cancel cascade) is the deadline mechanism.
60 #[derive(Debug, Clone, Copy)]
61 pub struct VmLimits {
62 /// QuickJS heap ceiling in bytes (default 32 MiB).
63 pub memory_limit_bytes: usize,
64 /// Maximum interpreter stack in bytes (default 1 MiB).
65 pub max_stack_bytes: usize,
66 }
67
68 impl Default for VmLimits {
69 fn default() -> Self {
70 Self::from_env()
71 }
72 }
73
74 impl VmLimits {
75 pub fn from_env() -> Self {
76 Self {
77 memory_limit_bytes: env_usize_bytes(
78 VM_MEMORY_LIMIT_MB_ENV,
79 1024 * 1024,
80 MIN_VM_MEMORY_LIMIT_BYTES,
81 MAX_VM_MEMORY_LIMIT_BYTES,
82 DEFAULT_VM_MEMORY_LIMIT_BYTES,
83 ),
84 max_stack_bytes: env_usize_bytes(
85 VM_STACK_KB_ENV,
86 1024,
87 MIN_VM_STACK_BYTES,
88 MAX_VM_STACK_BYTES,
89 DEFAULT_VM_STACK_BYTES,
90 ),
91 }
92 }
93 }
94
95 fn env_usize_bytes(name: &str, unit: usize, min: usize, max: usize, default: usize) -> usize {
96 env::var(name)
97 .ok()
98 .and_then(|raw| raw.parse::<usize>().ok())
99 .and_then(|value| value.checked_mul(unit))
100 .map(|bytes| bytes.clamp(min, max))
101 .unwrap_or(default)
102 }
103
104 fn max_concurrent_vms() -> usize {
105 env::var(VM_MAX_CONCURRENT_ENV)
106 .ok()
107 .and_then(|raw| raw.parse::<usize>().ok())
108 .map(|value| value.clamp(1, MAX_CONCURRENT_VMS))
109 .unwrap_or(DEFAULT_MAX_CONCURRENT_VMS)
110 }
111
112 fn vm_thread_stack_bytes() -> usize {
113 env_usize_bytes(
114 VM_THREAD_STACK_KB_ENV,
115 1024,
116 MIN_VM_THREAD_STACK_BYTES,
117 MAX_VM_THREAD_STACK_BYTES,
118 DEFAULT_VM_THREAD_STACK_BYTES,
119 )
120 }
121
122 fn vm_admission() -> &'static Arc<Semaphore> {
123 static ADMISSION: OnceLock<Arc<Semaphore>> = OnceLock::new();
124 ADMISSION.get_or_init(|| Arc::new(Semaphore::new(max_concurrent_vms())))
125 }
126
127 struct BoundedJson {
128 bytes: Vec<u8>,
129 }
130
131 impl std::io::Write for BoundedJson {
132 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
133 if self.bytes.len().saturating_add(buf.len()) > MAX_VM_ARGS_BYTES {
134 return Err(std::io::Error::other(format!(
135 "{MAX_VM_ARGS_BYTES}-byte limit exceeded"
136 )));
137 }
138 self.bytes.extend_from_slice(buf);
139 Ok(buf.len())
140 }
141
142 fn flush(&mut self) -> std::io::Result<()> {
143 Ok(())
144 }
145 }
146
147 fn encode_args_json(args: &serde_json::Value) -> Result<String, WorkflowJsError> {
148 let mut writer = BoundedJson { bytes: Vec::new() };
149 serde_json::to_writer(&mut writer, args)
150 .map_err(|err| WorkflowJsError::InvalidArgs(err.to_string()))?;
151 String::from_utf8(writer.bytes).map_err(|err| WorkflowJsError::InvalidArgs(err.to_string()))
152 }
153
154 /// Executes Workflow scripts, one isolated QuickJS runtime per run.
155 ///
156 /// Every [`WorkflowVm::run_script`] call spins up a fresh interpreter on a
157 /// dedicated thread, so runs share nothing (globals, heap, interned atoms)
158 /// and a wedged script can never stall a sibling run.
159 #[derive(Debug, Clone, Default)]
160 pub struct WorkflowVm {
161 limits: VmLimits,
162 }
163
164 impl WorkflowVm {
165 /// A VM with the default [`VmLimits`].
166 pub fn new() -> Self {
167 Self::default()
168 }
169
170 /// A VM with explicit resource limits.
171 pub fn with_limits(limits: VmLimits) -> Self {
172 Self { limits }
173 }
174
175 /// Run one Workflow script to completion.
176 ///
177 /// * `source` is the script body; it is wrapped in an async function, so
178 /// top-level `await` and `return` both work. The returned value is the
179 /// script's `return` value, JSON-encoded (`undefined` becomes `null`).
180 /// * `args` is exposed verbatim to the script as the `args` global.
181 /// * `driver` executes `task()` spawns and receives progress events. A
182 /// driver instance is scoped to exactly one run: `cancel_all` is always
183 /// invoked at run teardown (success, script error, or cancellation), so
184 /// stray children never outlive the script that spawned them.
185 ///
186 /// Cancellation cascade (design §9): dropping the returned future cancels
187 /// the run — the interrupt handler aborts executing JS, pending `task()`
188 /// awaits resolve to errors, and `driver.cancel_all()` is invoked
189 /// immediately from the dropping thread.
190 pub async fn run_script(
191 &self,
192 source: &str,
193 args: serde_json::Value,
194 driver: Arc<dyn WorkflowDriver>,
195 ) -> Result<serde_json::Value, WorkflowJsError> {
196 self.run_script_with_cancel(source, args, driver, WorkflowRunCancel::new())
197 .await
198 }
199
200 /// Like [`Self::run_script`], but accepts an external cancel handle so the
201 /// host can interrupt the VM without dropping the run future.
202 pub async fn run_script_with_cancel(
203 &self,
204 source: &str,
205 args: serde_json::Value,
206 driver: Arc<dyn WorkflowDriver>,
207 cancel: WorkflowRunCancel,
208 ) -> Result<serde_json::Value, WorkflowJsError> {
209 self.run_inner(source, args, driver, None, cancel).await
210 }
211
212 /// Run a code-mode script: the same VM, plus the `tools.call()` host
213 /// binding backed by `invoker`. Workflow runs (no invoker) never see the
214 /// binding, so the Workflow sandbox keeps its documented host surface.
215 pub async fn run_tools_script(
216 &self,
217 source: &str,
218 args: serde_json::Value,
219 driver: Arc<dyn WorkflowDriver>,
220 invoker: Arc<dyn ToolInvoker>,
221 cancel: WorkflowRunCancel,
222 ) -> Result<serde_json::Value, WorkflowJsError> {
223 self.run_inner(source, args, driver, Some(invoker), cancel)
224 .await
225 }
226
227 async fn run_inner(
228 &self,
229 source: &str,
230 args: serde_json::Value,
231 driver: Arc<dyn WorkflowDriver>,
232 invoker: Option<Arc<dyn ToolInvoker>>,
233 cancel: WorkflowRunCancel,
234 ) -> Result<serde_json::Value, WorkflowJsError> {
235 if source.len() > MAX_VM_SOURCE_BYTES {
236 return Err(WorkflowJsError::VmInit(format!(
237 "workflow source exceeds {MAX_VM_SOURCE_BYTES} bytes"
238 )));
239 }
240 let args_json = encode_args_json(&args)?;
241 let cancel = cancel.0;
242 let (result_tx, result_rx) = oneshot::channel();
243 let mut guard = RunGuard {
244 cancel: cancel.clone(),
245 driver: driver.clone(),
246 armed: true,
247 };
248
249 let permit = vm_admission()
250 .clone()
251 .acquire_owned()
252 .await
253 .map_err(|_| WorkflowJsError::VmInit("VM admission gate closed".to_string()))?;
254 let limits = self.limits;
255 let source = source.to_string();
256 let thread_driver = driver.clone();
257 let thread_cancel = cancel.clone();
258 let thread_invoker = invoker.clone();
259 // Native admission belongs to the originating host executor. The VM
260 // thread carries only Send requests/replies, never the Child Engine's
261 // Rust future on its bounded interpreter stack.
262 let host_runtime = Handle::try_current().map_err(|_| {
263 WorkflowJsError::VmInit("workflow host Tokio runtime is unavailable".to_string())
264 })?;
265 let spawned = std::thread::Builder::new()
266 .name("workflow-js-vm".to_string())
267 .stack_size(vm_thread_stack_bytes())
268 .spawn(move || {
269 let _permit: OwnedSemaphorePermit = permit;
270 let outcome = vm_thread_main(
271 source,
272 args_json,
273 thread_driver.clone(),
274 thread_cancel,
275 thread_invoker,
276 limits,
277 host_runtime,
278 );
279 // Run teardown: this driver is scoped to one run, so any task
280 // still in flight is unreachable now — cancel the cascade.
281 thread_driver.cancel_all();
282 let _ = result_tx.send(outcome);
283 });
284 if let Err(err) = spawned {
285 guard.armed = false;
286 return Err(WorkflowJsError::VmInit(format!(
287 "failed to spawn VM thread: {err}"
288 )));
289 }
290
291 match result_rx.await {
292 Ok(outcome) => {
293 // The VM thread has already torn down and cancelled children.
294 guard.armed = false;
295 outcome
296 }
297 // VM thread panicked before reporting; leave the guard armed so
298 // its drop (right now, at return) cancels outstanding tasks.
299 Err(_) => Err(WorkflowJsError::VmTerminated(
300 "VM thread exited without reporting a result".to_string(),
301 )),
302 }
303 }
304 }
305
306 /// Cooperative cancel signal shared by the run future (guard side) and the VM
307 /// thread. The atomic flag feeds the QuickJS interrupt handler (sync, called
308 /// mid-bytecode); the watch channel wakes host futures parked on driver
309 /// completions.
310 #[derive(Clone)]
311 pub struct WorkflowRunCancel(CancelHandle);
312
313 impl WorkflowRunCancel {
314 #[must_use]
315 pub fn new() -> Self {
316 Self(CancelHandle::new())
317 }
318
319 pub fn cancel(&self) {
320 self.0.cancel();
321 }
322 }
323
324 impl Default for WorkflowRunCancel {
325 fn default() -> Self {
326 Self::new()
327 }
328 }
329
330 #[derive(Clone)]
331 struct CancelHandle {
332 flag: Arc<AtomicBool>,
333 tx: Arc<watch::Sender<bool>>,
334 }
335
336 impl CancelHandle {
337 fn new() -> Self {
338 let (tx, _rx) = watch::channel(false);
339 Self {
340 flag: Arc::new(AtomicBool::new(false)),
341 tx: Arc::new(tx),
342 }
343 }
344
345 fn cancel(&self) {
346 self.flag.store(true, Ordering::SeqCst);
347 self.tx.send_replace(true);
348 }
349
350 fn is_cancelled(&self) -> bool {
351 self.flag.load(Ordering::SeqCst)
352 }
353
354 async fn cancelled(&self) {
355 let mut rx = self.tx.subscribe();
356 let _ = rx.wait_for(|cancelled| *cancelled).await;
357 }
358
359 fn flag_arc(&self) -> Arc<AtomicBool> {
360 self.flag.clone()
361 }
362 }
363
364 /// Fires the cancel cascade if the caller drops the run future before the VM
365 /// reports a result.
366 struct RunGuard {
367 cancel: CancelHandle,
368 driver: Arc<dyn WorkflowDriver>,
369 armed: bool,
370 }
371
372 impl Drop for RunGuard {
373 fn drop(&mut self) {
374 if self.armed {
375 self.cancel.cancel();
376 self.driver.cancel_all();
377 }
378 }
379 }
380
381 fn vm_thread_main(
382 source: String,
383 args_json: String,
384 driver: Arc<dyn WorkflowDriver>,
385 cancel: CancelHandle,
386 invoker: Option<Arc<dyn ToolInvoker>>,
387 limits: VmLimits,
388 host_runtime: Handle,
389 ) -> Result<serde_json::Value, WorkflowJsError> {
390 let reactor = tokio::runtime::Builder::new_current_thread()
391 .enable_all()
392 .build()
393 .map_err(|err| WorkflowJsError::VmInit(format!("failed to build VM reactor: {err}")))?;
394 reactor.block_on(run_in_vm(
395 source,
396 args_json,
397 driver,
398 cancel,
399 invoker,
400 limits,
401 host_runtime,
402 ))
403 }
404
405 async fn run_in_vm(
406 source: String,
407 args_json: String,
408 driver: Arc<dyn WorkflowDriver>,
409 cancel: CancelHandle,
410 invoker: Option<Arc<dyn ToolInvoker>>,
411 limits: VmLimits,
412 host_runtime: Handle,
413 ) -> Result<serde_json::Value, WorkflowJsError> {
414 let runtime = AsyncRuntime::new().map_err(|err| WorkflowJsError::VmInit(err.to_string()))?;
415 runtime.set_memory_limit(limits.memory_limit_bytes).await;
416 runtime.set_max_stack_size(limits.max_stack_bytes).await;
417 let interrupt_flag = cancel.flag_arc();
418 runtime
419 .set_interrupt_handler(Some(Box::new(move || {
420 interrupt_flag.load(Ordering::Acquire)
421 })))
422 .await;
423 let context = AsyncContext::full(&runtime)
424 .await
425 .map_err(|err| WorkflowJsError::VmInit(err.to_string()))?;
426
427 let result = context
428 .async_with(async |ctx| {
429 run_in_ctx(
430 ctx,
431 source,
432 args_json,
433 driver,
434 invoker,
435 cancel,
436 host_runtime,
437 )
438 .await
439 })
440 .await;
441 drop(context);
442 runtime.run_gc().await;
443 result
444 }
445
446 async fn run_in_ctx(
447 ctx: Ctx<'_>,
448 source: String,
449 args_json: String,
450 driver: Arc<dyn WorkflowDriver>,
451 invoker: Option<Arc<dyn ToolInvoker>>,
452 cancel: CancelHandle,
453 host_runtime: Handle,
454 ) -> Result<serde_json::Value, WorkflowJsError> {
455 install_host(
456 &ctx,
457 driver,
458 invoker.clone(),
459 cancel.clone(),
460 &args_json,
461 host_runtime,
462 )?;
463 ctx.eval::<(), _>(URL_PRELUDE)
464 .catch(&ctx)
465 .map_err(|err| WorkflowJsError::VmInit(format!("url prelude failed: {err}")))?;
466 ctx.eval::<(), _>(prelude(invoker.is_some()))
467 .catch(&ctx)
468 .map_err(|err| WorkflowJsError::VmInit(format!("prelude failed: {err}")))?;
469 if invoker.is_some() {
470 ctx.eval::<(), _>(CODEMODE_PRELUDE)
471 .catch(&ctx)
472 .map_err(|err| WorkflowJsError::VmInit(format!("codemode prelude failed: {err}")))?;
473 }
474
475 let desugared = desugar_export_default(&source);
476 let wrapped = format!("(async () => {{\n{desugared}\n}})()");
477 let promise = ctx
478 .eval::<Promise, _>(wrapped)
479 .catch(&ctx)
480 .map_err(|err| script_error(&cancel, err))?;
481 let value = promise
482 .into_future::<Value>()
483 .await
484 .catch(&ctx)
485 .map_err(|err| script_error(&cancel, err))?;
486 js_value_to_json(&ctx, value)
487 }
488
489 /// Rewrite the documented module-style authoring shape
490 /// (`export default async function (args) { ... }`) into the script form the
491 /// VM actually evals. Sources are wrapped in an async IIFE, where the
492 /// module-only `export` keyword is a syntax error, so without this every
493 /// imperative `export default` workflow (including the #4131 dogfood
494 /// fixtures) failed to parse. The default export is captured, invoked with
495 /// the `args` global when it is a function, and its result becomes the run
496 /// result; a non-function default export is returned as-is.
497 fn desugar_export_default(source: &str) -> String {
498 const EXPORT_DEFAULT: &str = "export default";
499 let Some(offset) = line_leading_export_default(source) else {
500 return source.to_string();
501 };
502 let mut out = source.to_string();
503 out.replace_range(
504 offset..offset + EXPORT_DEFAULT.len(),
505 "globalThis.__workflow_default =",
506 );
507 out.push('\n');
508 out.push_str(
509 ";{\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",
510 );
511 out
512 }
513
514 /// Return the byte offset of a line-leading `export default` token that is
515 /// actual JavaScript syntax, not text inside a string, template literal, or
516 /// comment. This intentionally recognizes only the documented authoring shape
517 /// instead of attempting to implement a general JavaScript module parser.
518 fn line_leading_export_default(source: &str) -> Option<usize> {
519 const EXPORT_DEFAULT: &[u8] = b"export default";
520 let bytes = source.as_bytes();
521 let mut idx = 0usize;
522 let mut quote = None;
523 let mut escaped = false;
524 let mut line_comment = false;
525 let mut block_comment = false;
526 let mut line_has_only_whitespace = true;
527
528 while idx < bytes.len() {
529 let byte = bytes[idx];
530
531 if line_comment {
532 if byte == b'\n' {
533 line_comment = false;
534 line_has_only_whitespace = true;
535 }
536 idx += 1;
537 continue;
538 }
539
540 if block_comment {
541 if byte == b'*' && bytes.get(idx + 1) == Some(&b'/') {
542 block_comment = false;
543 line_has_only_whitespace = false;
544 idx += 2;
545 continue;
546 }
547 if byte == b'\n' {
548 line_has_only_whitespace = true;
549 } else if !byte.is_ascii_whitespace() {
550 line_has_only_whitespace = false;
551 }
552 idx += 1;
553 continue;
554 }
555
556 if let Some(active_quote) = quote {
557 if byte == b'\n' {
558 line_has_only_whitespace = true;
559 escaped = false;
560 } else {
561 if !byte.is_ascii_whitespace() {
562 line_has_only_whitespace = false;
563 }
564 if escaped {
565 escaped = false;
566 } else if byte == b'\\' {
567 escaped = true;
568 } else if byte == active_quote {
569 quote = None;
570 }
571 }
572 idx += 1;
573 continue;
574 }
575
576 if byte == b'\n' {
577 line_has_only_whitespace = true;
578 idx += 1;
579 continue;
580 }
581 if line_has_only_whitespace && byte.is_ascii_whitespace() {
582 idx += 1;
583 continue;
584 }
585 if line_has_only_whitespace && bytes[idx..].starts_with(EXPORT_DEFAULT) {
586 return Some(idx);
587 }
588
589 line_has_only_whitespace = false;
590 if byte == b'/' && bytes.get(idx + 1) == Some(&b'/') {
591 line_comment = true;
592 idx += 2;
593 } else if byte == b'/' && bytes.get(idx + 1) == Some(&b'*') {
594 block_comment = true;
595 idx += 2;
596 } else {
597 if matches!(byte, b'\'' | b'"' | b'`') {
598 quote = Some(byte);
599 }
600 idx += 1;
601 }
602 }
603
604 None
605 }
606
607 fn script_error(cancel: &CancelHandle, err: CaughtError<'_>) -> WorkflowJsError {
608 if cancel.is_cancelled() {
609 WorkflowJsError::Cancelled
610 } else {
611 WorkflowJsError::Script(err.to_string())
612 }
613 }
614
615 fn js_value_to_json<'js>(
616 ctx: &Ctx<'js>,
617 value: Value<'js>,
618 ) -> Result<serde_json::Value, WorkflowJsError> {
619 if value.is_undefined() {
620 return Ok(serde_json::Value::Null);
621 }
622 let text = ctx
623 .json_stringify(value)
624 .map_err(|err| WorkflowJsError::ResultEncoding(err.to_string()))?;
625 match text {
626 None => Ok(serde_json::Value::Null),
627 Some(text) => {
628 let text = text
629 .to_string()
630 .map_err(|err| WorkflowJsError::ResultEncoding(err.to_string()))?;
631 serde_json::from_str(&text)
632 .map_err(|err| WorkflowJsError::ResultEncoding(err.to_string()))
633 }
634 }
635 }
636
637 /// Prelude fragment for code-mode runs only: captures `__codemode_call` into
638 /// the frozen `globalThis.tools` surface, then deletes the raw binding.
639 /// Workflow runs never eval this, so their documented host surface is
640 /// unchanged — `tools` simply does not exist there.
641 const CODEMODE_PRELUDE: &str = r#"
642 (() => {
643 const hostCall = __codemode_call;
644 const hostLog = globalThis.log;
645 const invoke = async (tool, input) => {
646 const envelope = JSON.parse(
647 await hostCall(JSON.stringify({ tool, input: input === undefined ? {} : input }))
648 );
649 if (envelope.error !== undefined) {
650 const err = new Error(envelope.error);
651 err.kind = envelope.error_kind;
652 if (envelope.metadata !== undefined) {
653 err.metadata = envelope.metadata;
654 }
655 throw err;
656 }
657 return envelope.result;
658 };
659 const isRecord = (value) => value !== null && typeof value === "object";
660 const text = (value) => (value === undefined || value === null ? "" : String(value).trim());
661 const discover = async (input) => {
662 const envelope = await invoke("tool_search", input);
663 const answer = envelope.content;
664 if (!isRecord(answer)) {
665 throw new Error("tool discovery did not answer: " + String(answer));
666 }
667 return { answer, cut: Boolean(envelope.truncated) };
668 };
669 const discoverTools = async (helper, narrow, input) => {
670 const { answer, cut } = await discover(input);
671 const found = Array.isArray(answer.tools) ? answer.tools : [];
672 if (cut || answer.truncated) {
673 Object.defineProperty(found, "total", { value: answer.total });
674 Object.defineProperty(found, "truncated", { value: true });
675 hostLog(
676 `tools.${helper}: showing ${found.length} of ${answer.total} tools` +
677 `${cut ? " (cut to the result size cap; the last entry may be partial)" : ""}; ${narrow}`
678 );
679 }
680 return found;
681 };
682 const baseTools = Object.freeze({
683 call: invoke,
684 list: async (namespace, opts) => {
685 const options = isRecord(namespace) ? namespace : isRecord(opts) ? opts : {};
686 const ns = text(isRecord(namespace) ? namespace.namespace : namespace);
687 const input = { mode: "list", query: ns || "*" };
688 if (ns !== "") {
689 input.namespace = ns;
690 }
691 if (options.limit !== undefined && options.limit !== null) {
692 input.max_results = options.limit;
693 }
694 return discoverTools(
695 "list",
696 "narrow with tools.list(namespace) or tools.search(query), or raise {limit} (max 500)",
697 input
698 );
699 },
700 search: async (query, opts) => {
701 const options = isRecord(opts) ? opts : {};
702 const input = { mode: "search", query: text(query) };
703 if (text(options.namespace) !== "") {
704 input.namespace = text(options.namespace);
705 }
706 const limit = options.limit === undefined ? options.max_results : options.limit;
707 if (limit !== undefined && limit !== null) {
708 input.max_results = limit;
709 }
710 if (text(options.match) !== "") {
711 input.match = text(options.match);
712 }
713 if (options.include_schema === true) {
714 input.include_schema = true;
715 }
716 return discoverTools("search", "lower {limit} or add {namespace}", input);
717 },
718 describe: async (names, opts) => {
719 const list = (Array.isArray(names) ? names : text(names) === "" ? [] : [names]).map(text);
720 const input = { mode: "describe", query: list.join(" "), names: list };
721 if (isRecord(opts) && opts.include_schema === true) {
722 input.include_schema = true;
723 }
724 return discoverTools("describe", "describe fewer names per call", input);
725 },
726 load: async (names) => {
727 const list = (Array.isArray(names) ? names : text(names) === "" ? [] : [names]).map(text);
728 return (await discover({ mode: "load", query: list.join(" "), names: list })).answer;
729 },
730 });
731 const resolved = new Map();
732 const resolve = (namespace, op) => {
733 const key = JSON.stringify([namespace, op]);
734 if (!resolved.has(key)) {
735 const server = namespace.startsWith("mcp_") ? namespace.slice(4) : namespace;
736 resolved.set(
737 key,
738 discover({ mode: "resolve", query: server, namespace, op }).then(
739 ({ answer }) => answer.name,
740 (err) => {
741 err.message = `tools.${namespace}.${op}: ${err.message}; tools.call(name, args) takes an exact name without a lookup`;
742 throw err;
743 }
744 )
745 );
746 }
747 return resolved.get(key);
748 };
749 const refuseChanges = {
750 set: () => false,
751 defineProperty: () => false,
752 deleteProperty: () => false,
753 preventExtensions: () => false,
754 };
755 const passesThrough = (prop) =>
756 typeof prop !== "string" || prop === "then" || prop === "toJSON" || prop in Object.prototype;
757 const namespaceProxy = (namespace) => {
758 const target = async (input) => invoke(namespace, input);
759 return new Proxy(target, {
760 ...refuseChanges,
761 get: (_target, prop, receiver) =>
762 passesThrough(prop)
763 ? Reflect.get(Object.prototype, prop, receiver)
764 : async (input) => invoke(await resolve(namespace, prop), input),
765 });
766 };
767 globalThis.tools = new Proxy(baseTools, {
768 ...refuseChanges,
769 get: (target, prop, receiver) =>
770 passesThrough(prop) || Object.prototype.hasOwnProperty.call(target, prop)
771 ? Reflect.get(target, prop, receiver)
772 : namespaceProxy(prop),
773 });
774 try { delete globalThis.__codemode_call; } catch (_) { /* frozen shape */ }
775 })();
776 "#;
777
778 // Construct and poll native host futures on the captured host executor.
779 // JoinSet aborts on drop; explicit cancellation also joins that abort before
780 // the VM receives its existing typed cancellation error.
781 async fn call_on_host<T, F>(
782 runtime: &Handle,
783 cancel: &CancelHandle,
784 cancel_error: TaskError,
785 call: impl FnOnce() -> F + Send + 'static,
786 ) -> Result<T, TaskError>
787 where
788 T: Send + 'static,
789 F: Future<Output = T> + Send + 'static,
790 {
791 let mut pending = JoinSet::new();
792 let host_cancel = cancel.clone();
793 let host_error = cancel_error.clone();
794 pending.spawn_on(
795 async move {
796 if host_cancel.is_cancelled() {
797 Err(host_error)
798 } else {
799 Ok(call().await)
800 }
801 },
802 runtime,
803 );
804 tokio::select! {
805 biased;
806 _ = cancel.cancelled() => {
807 pending.shutdown().await;
808 Err(cancel_error)
809 }
810 outcome = pending.join_next() => match outcome {
811 Some(Ok(value)) => value,
812 Some(Err(error)) if error.is_panic() => {
813 std::panic::resume_unwind(error.into_panic())
814 }
815 _ => Err(TaskError::new(
816 TaskErrorKind::Driver,
817 "workflow host callback ended without a reply",
818 )),
819 },
820 }
821 }
822
823 /// The `tools.call()` host call. Infallible at the binding level, like
824 /// `task_host`: outcomes return through the `{result}` /
825 /// `{error, error_kind}` envelope so the prelude rethrows typed errors.
826 /// Gate refusals arrive as admission errors (nothing ran); a nested tool
827 /// that ran and failed arrives as an agent error (work failed).
828 async fn tools_call_host(
829 call_json: String,
830 invoker: Arc<dyn ToolInvoker>,
831 cancel: CancelHandle,
832 host_runtime: Handle,
833 ) -> String {
834 let outcome = tools_call_host_inner(call_json, invoker, cancel, host_runtime).await;
835 let envelope = match outcome {
836 Ok(result) => serde_json::json!({ "result": result }),
837 Err((TaskError { kind, message }, Some(metadata))) => serde_json::json!({
838 "error": message,
839 "error_kind": kind.as_str(),
840 "metadata": metadata,
841 }),
842 Err((TaskError { kind, message }, None)) => {
843 serde_json::json!({ "error": message, "error_kind": kind.as_str() })
844 }
845 };
846 envelope.to_string()
847 }
848
849 async fn verify_candidate_host(
850 call_json: String,
851 driver: Arc<dyn WorkflowDriver>,
852 cancel: CancelHandle,
853 host_runtime: Handle,
854 ) -> String {
855 let outcome = async {
856 let request: serde_json::Value = serde_json::from_str(&call_json)
857 .map_err(|error| TaskError::new(TaskErrorKind::Admission, error.to_string()))?;
858 if !request.is_object() {
859 return Err(TaskError::new(
860 TaskErrorKind::Admission,
861 "verifyCandidate(): expected an object",
862 ));
863 }
864 call_on_host(
865 &host_runtime,
866 &cancel,
867 TaskError::new(TaskErrorKind::Cancelled, "verifyCandidate(): run cancelled"),
868 move || async move { driver.verify_candidate(request).await },
869 )
870 .await?
871 .map_err(|error| TaskError::new(TaskErrorKind::from(&error), error.to_string()))
872 }
873 .await;
874 match outcome {
875 Ok(result) => serde_json::json!({"result": result}).to_string(),
876 Err(TaskError { kind, message }) => {
877 serde_json::json!({"error": message, "error_kind": kind.as_str()}).to_string()
878 }
879 }
880 }
881
882 async fn tools_call_host_inner(
883 call_json: String,
884 invoker: Arc<dyn ToolInvoker>,
885 cancel: CancelHandle,
886 host_runtime: Handle,
887 ) -> Result<serde_json::Value, (TaskError, Option<serde_json::Value>)> {
888 let admission = |message: String| (TaskError::new(TaskErrorKind::Admission, message), None);
889 let request: ToolCallRequest = serde_json::from_str(&call_json).map_err(|err| {
890 admission(format!(
891 "tools.call(): expected {{\"tool\", \"input\"}} JSON: {err}"
892 ))
893 })?;
894 if request.tool.trim().is_empty() {
895 return Err(admission(
896 "tools.call(): `tool` must be a non-empty string".to_string(),
897 ));
898 }
899 if !request.input.is_object() {
900 return Err(admission(
901 "tools.call(): `input` must be a JSON object".to_string(),
902 ));
903 }
904 if cancel.is_cancelled() {
905 return Err((
906 TaskError::new(
907 TaskErrorKind::Cancelled,
908 "tools.call(): run cancelled".to_string(),
909 ),
910 None,
911 ));
912 }
913 let response = call_on_host(
914 &host_runtime,
915 &cancel,
916 TaskError::new(TaskErrorKind::Cancelled, "tools.call(): run cancelled"),
917 move || async move { invoker.invoke(request).await },
918 )
919 .await
920 .map_err(|err| (err, None))?
921 .map_err(|err| {
922 (
923 TaskError::new(TaskErrorKind::from(&err), format!("tools.call(): {err}")),
924 None,
925 )
926 })?;
927 if response.ok {
928 Ok(response.result)
929 } else {
930 let (message, metadata) = match &response.result {
931 serde_json::Value::String(text) => (text.clone(), None),
932 serde_json::Value::Object(map) => {
933 let message = match map.get("content") {
934 Some(serde_json::Value::String(text)) => text.clone(),
935 Some(other) if !other.is_null() => other.to_string(),
936 _ => "tools.call(): tool failed without a message".to_string(),
937 };
938 let metadata = map
939 .get("metadata")
940 .filter(|value| !value.is_null())
941 .cloned();
942 (message, metadata)
943 }
944 _ => (
945 "tools.call(): tool failed without a message".to_string(),
946 None,
947 ),
948 };
949 Err((TaskError::new(TaskErrorKind::Agent, message), metadata))
950 }
951 }
952
953 fn install_host(
954 ctx: &Ctx<'_>,
955 driver: Arc<dyn WorkflowDriver>,
956 invoker: Option<Arc<dyn ToolInvoker>>,
957 cancel: CancelHandle,
958 args_json: &str,
959 host_runtime: Handle,
960 ) -> Result<(), WorkflowJsError> {
961 let globals = ctx.globals();
962
963 let args_value: Value = ctx
964 .json_parse(args_json)
965 .map_err(|err| WorkflowJsError::InvalidArgs(err.to_string()))?;
966 globals.set("args", args_value).map_err(init_err)?;
967
968 let tickets = TaskTickets::default();
969 let task_driver = driver.clone();
970 let task_cancel = cancel.clone();
971 let task_runtime = host_runtime.clone();
972 let task_tickets = tickets.clone();
973 globals
974 .set(
975 "__workflow_task",
976 Func::from(Async(move |opts_json: String, ticket: u32| {
977 let driver = task_driver.clone();
978 let cancel = task_cancel.clone();
979 let host_runtime = task_runtime.clone();
980 let tickets = task_tickets.clone();
981 async move {
982 task_host(opts_json, ticket, tickets, driver, cancel, host_runtime).await
983 }
984 })),
985 )
986 .map_err(init_err)?;
987
988 let verifier_driver = driver.clone();
989 let verifier_cancel = cancel.clone();
990 let verifier_runtime = host_runtime.clone();
991 globals
992 .set(
993 "__workflow_verify_candidate",
994 Func::from(Async(move |call_json: String| {
995 let driver = verifier_driver.clone();
996 let cancel = verifier_cancel.clone();
997 let runtime = verifier_runtime.clone();
998 async move { verify_candidate_host(call_json, driver, cancel, runtime).await }
999 })),
1000 )
1001 .map_err(init_err)?;
1002
1003 let cancel_driver = driver.clone();
1004 globals
1005 .set(
1006 "__workflow_cancel_tasks",
1007 Func::from(move |group: Vec<u32>| {
1008 for task_id in tickets.cancel(&group) {
1009 cancel_driver.cancel_task(&task_id);
1010 }
1011 }),
1012 )
1013 .map_err(init_err)?;
1014
1015 if let Some(invoker) = invoker {
1016 let call_invoker = invoker.clone();
1017 let call_cancel = cancel.clone();
1018 globals
1019 .set(
1020 "__codemode_call",
1021 Func::from(Async(move |call_json: String| {
1022 let invoker = call_invoker.clone();
1023 let cancel = call_cancel.clone();
1024 let host_runtime = host_runtime.clone();
1025 async move { tools_call_host(call_json, invoker, cancel, host_runtime).await }
1026 })),
1027 )
1028 .map_err(init_err)?;
1029 }
1030
1031 let log_driver = driver.clone();
1032 globals
1033 .set(
1034 "__workflow_log",
1035 Func::from(move |message: String| {
1036 log_driver.progress(ProgressEvent::Log { message });
1037 }),
1038 )
1039 .map_err(init_err)?;
1040
1041 // Structured twin of the prelude's "every slot failed" breadcrumb (R9):
1042 // a dead fan-out of script-thrown thunks leaves no task record behind,
1043 // so the host needs a typed event — not a log line — to keep the run's
1044 // terminal status honest.
1045 let fanout_driver = driver.clone();
1046 globals
1047 .set(
1048 "__workflow_every_slot_failed",
1049 Func::from(move |construct: String, failed: u32, total: u32| {
1050 fanout_driver.progress(ProgressEvent::FanoutAllSlotsFailed {
1051 construct,
1052 failed,
1053 total,
1054 });
1055 }),
1056 )
1057 .map_err(init_err)?;
1058
1059 // Structured twin of the per-slot "dropped a failed slot as null"
1060 // breadcrumb (R9): a PARTIALLY failed fan-out still resolves and leaves
1061 // no task record for the dropped slot, so without this event the ledger
1062 // cannot see the loss and records a clean Completed.
1063 let fanout_driver = driver.clone();
1064 globals
1065 .set(
1066 "__workflow_slot_dropped",
1067 Func::from(move |construct: String, kind: String, slot: u32| {
1068 fanout_driver.progress(ProgressEvent::FanoutSlotDropped {
1069 construct,
1070 kind,
1071 slot,
1072 });
1073 }),
1074 )
1075 .map_err(init_err)?;
1076
1077 globals
1078 .set(
1079 "__workflow_phase",
1080 Func::from(move |title: String| {
1081 driver.progress(ProgressEvent::Phase { title });
1082 }),
1083 )
1084 .map_err(init_err)?;
1085
1086 Ok(())
1087 }
1088
1089 fn init_err(err: rquickjs::Error) -> WorkflowJsError {
1090 WorkflowJsError::VmInit(err.to_string())
1091 }
1092
1093 /// The `task()` host call. Everything that can go wrong is reported through
1094 /// the JSON envelope (`{"error": ..., "error_kind": ...}`) so the prelude
1095 /// re-throws it as a real JS `Error` with a script-side stack and a typed
1096 /// [`TaskErrorKind`] on `.kind` (R9). The kind is assigned here, where the
1097 /// failure actually happened — never re-derived from the message text.
1098 async fn task_host(
1099 opts_json: String,
1100 ticket: u32,
1101 tickets: TaskTickets,
1102 driver: Arc<dyn WorkflowDriver>,
1103 cancel: CancelHandle,
1104 host_runtime: Handle,
1105 ) -> String {
1106 tickets.open(ticket);
1107 let outcome = task_host_inner(opts_json, ticket, &tickets, driver, cancel, host_runtime).await;
1108 tickets.close(ticket);
1109 let envelope = match outcome {
1110 Ok(value) => serde_json::json!({ "value": value }),
1111 Err(TaskError { kind, message }) => {
1112 serde_json::json!({ "error": message, "error_kind": kind.as_str() })
1113 }
1114 };
1115 envelope.to_string()
1116 }
1117
1118 /// Best-effort `label`/`phase` from raw `task()` options, for rejection
1119 /// receipts when the options never survived parsing.
1120 fn task_identity_hint(opts_json: &str) -> (Option<String>, Option<String>) {
1121 let value: serde_json::Value =
1122 serde_json::from_str(opts_json).unwrap_or(serde_json::Value::Null);
1123 let pluck = |key: &str| {
1124 value
1125 .get(key)
1126 .and_then(serde_json::Value::as_str)
1127 .map(str::trim)
1128 .filter(|text| !text.is_empty())
1129 .map(str::to_string)
1130 };
1131 (pluck("label"), pluck("phase"))
1132 }
1133
1134 /// Record a pre-spawn `task()` rejection on the host ledger, then hand the
1135 /// message back for the JS throw. Rejections that never reach `spawn_task`
1136 /// would otherwise be invisible to the run record (#5035's surviving gap).
1137 fn reject_task(driver: &Arc<dyn WorkflowDriver>, opts_json: &str, message: String) -> String {
1138 let (label, phase) = task_identity_hint(opts_json);
1139 driver.progress(ProgressEvent::TaskRejected {
1140 label,
1141 phase,
1142 message: message.clone(),
1143 });
1144 message
1145 }
1146
1147 /// Emit the terminal schema-failure receipt for a `task()` whose reply failed
1148 /// `responseSchema` with no repair left to try, and hand the message back for
1149 /// the JS throw. `note` (when present) names why a repair was skipped, so the
1150 /// operator can tell "repair refused to run" from "repair also failed".
1151 fn fail_schema(
1152 driver: &Arc<dyn WorkflowDriver>,
1153 task_id: String,
1154 attempt: u32,
1155 error: &ReplyDecodeError,
1156 raw: String,
1157 raw_truncated: bool,
1158 ) -> String {
1159 let message = error.message().to_string();
1160 driver.progress(ProgressEvent::TaskSchemaValidationFailed {
1161 task_id,
1162 kind: error.kind().to_string(),
1163 attempt,
1164 message: message.clone(),
1165 raw,
1166 raw_truncated,
1167 });
1168 message
1169 }
1170
1171 /// Build the repair request for `next_attempt` (#5583): the same child
1172 /// identity, budget fields, and schema as the original, with a repair prompt
1173 /// carrying the original task, the schema, the failed reply, and why it failed.
1174 fn repair_request(
1175 original: &TaskRequest,
1176 next_attempt: u32,
1177 error: &ReplyDecodeError,
1178 failed_raw: &str,
1179 ) -> TaskRequest {
1180 let mut request = original.clone();
1181 let schema = original
1182 .response_schema
1183 .as_ref()
1184 .expect("repair only runs when responseSchema is set");
1185 // The bracket prefix identifies the repair at a glance on progress
1186 // surfaces and lets tests script the repair reply by rule order.
1187 request.description = format!(
1188 "[schema repair {next_attempt}] {}",
1189 repair_prompt(&original.description, schema, failed_raw, error)
1190 );
1191 // Label and phase stay inherited so progress surfaces group the repair
1192 // with its task.
1193 request
1194 }
1195
1196 /// The one cancellation error: the run's deadline fired. Fatal in every
1197 /// `parallel()` / `pipeline()` mode — a cancelled run must never resolve into
1198 /// a slot value.
1199 fn cancelled_task() -> TaskError {
1200 TaskError::new(TaskErrorKind::Cancelled, "task(): run cancelled")
1201 }
1202
1203 #[derive(Clone, Default)]
1204 struct TaskTickets(Arc<Mutex<HashMap<u32, TicketState>>>);
1205
1206 #[derive(Default)]
1207 struct TicketState {
1208 task_id: Option<String>,
1209 cancelled: bool,
1210 }
1211
1212 impl TaskTickets {
1213 fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<u32, TicketState>> {
1214 self.0.lock().unwrap_or_else(|poison| poison.into_inner())
1215 }
1216
1217 fn open(&self, ticket: u32) {
1218 self.lock().insert(ticket, TicketState::default());
1219 }
1220
1221 fn close(&self, ticket: u32) {
1222 self.lock().remove(&ticket);
1223 }
1224
1225 fn started(&self, ticket: u32, task_id: &str) -> bool {
1226 let mut tickets = self.lock();
1227 let Some(state) = tickets.get_mut(&ticket) else {
1228 return false;
1229 };
1230 state.task_id = Some(task_id.to_string());
1231 state.cancelled
1232 }
1233
1234 fn is_cancelled(&self, ticket: u32) -> bool {
1235 self.lock()
1236 .get(&ticket)
1237 .is_some_and(|state| state.cancelled)
1238 }
1239
1240 fn cancel(&self, group: &[u32]) -> Vec<String> {
1241 let mut tickets = self.lock();
1242 group
1243 .iter()
1244 .filter_map(|ticket| {
1245 let state = tickets.get_mut(ticket)?;
1246 if state.cancelled {
1247 return None;
1248 }
1249 state.cancelled = true;
1250 state.task_id.clone()
1251 })
1252 .collect()
1253 }
1254 }
1255
1256 /// A terminal `responseSchema` failure, already receipted by [`fail_schema`].
1257 fn schema_task(message: String) -> TaskError {
1258 TaskError::new(TaskErrorKind::Schema, message)
1259 }
1260
1261 async fn task_host_inner(
1262 opts_json: String,
1263 ticket: u32,
1264 tickets: &TaskTickets,
1265 driver: Arc<dyn WorkflowDriver>,
1266 cancel: CancelHandle,
1267 host_runtime: Handle,
1268 ) -> Result<serde_json::Value, TaskError> {
1269 let admission = |message: String| TaskError::new(TaskErrorKind::Admission, message);
1270 let workspace = driver.workspace_root();
1271 let request = parse_task_options(&opts_json, workspace.as_deref())
1272 .map_err(|message| admission(reject_task(&driver, &opts_json, message)))?;
1273 // Compile the schema before spawning so a malformed one fails fast
1274 // instead of burning a subagent.
1275 let validator = request
1276 .response_schema
1277 .as_ref()
1278 .map(|schema| compile_schema("task(): responseSchema", schema))
1279 .transpose()
1280 .map_err(|message| admission(reject_task(&driver, &opts_json, message)))?;
1281
1282 if cancel.is_cancelled() {
1283 return Err(cancelled_task());
1284 }
1285
1286 // Bounded schema repair (#5583): after a failed `responseSchema` decode,
1287 // re-ask the same route before throwing. `None` is the default single
1288 // repair; `Some(0)` disables it. The first attempt is attempt 1, so the
1289 // task is schema-terminal once `attempt` reaches this ceiling.
1290 let last_attempt = 1 + request.schema_repair_attempts.unwrap_or(1);
1291 let mut current = request.clone();
1292 let mut attempt: u32 = 0;
1293 loop {
1294 attempt += 1;
1295 // Admission can wait (a saturated concurrency gate, a routing call),
1296 // so it races the run's cancel exactly as the completion does below
1297 // and as `tools.call()` does: a cancel that only closed the driver's
1298 // gate used to be the one thing that could wake it.
1299 let task_driver = driver.clone();
1300 let task_request = current.clone();
1301 let spawned_task = call_on_host(
1302 &host_runtime,
1303 &cancel,
1304 cancelled_task(),
1305 move || async move { task_driver.spawn_task(task_request).await },
1306 )
1307 .await?
1308 .map_err(|err| TaskError::new(TaskErrorKind::from(&err), err.to_string()))?;
1309 let task_id = spawned_task.task_id;
1310 if tickets.started(ticket, &task_id) {
1311 driver.cancel_task(&task_id);
1312 }
1313 let completion_rx = spawned_task.completion;
1314 let completion = tokio::select! {
1315 _ = cancel.cancelled() => return Err(cancelled_task()),
1316 completion = completion_rx => completion.map_err(|_| {
1317 TaskError::new(
1318 TaskErrorKind::Driver,
1319 "task(): driver dropped the completion channel",
1320 )
1321 })?,
1322 };
1323
1324 let text = match completion {
1325 TaskCompletion::Completed { text } => text,
1326 TaskCompletion::Failed { message } => {
1327 return Err(TaskError::new(
1328 TaskErrorKind::Agent,
1329 format!("task(): subagent failed: {message}"),
1330 ));
1331 }
1332 TaskCompletion::Cancelled => {
1333 return Err(TaskError::new(
1334 TaskErrorKind::Cancelled,
1335 "task(): subagent cancelled",
1336 ));
1337 }
1338 TaskCompletion::BudgetExhausted { message } => {
1339 return Err(TaskError::new(
1340 TaskErrorKind::Budget,
1341 format!("task(): budget exhausted: {message}"),
1342 ));
1343 }
1344 };
1345 // Without a schema the raw text is the contract; with one, the decode
1346 // decides — and a failure may still be repaired.
1347 let Some(validator) = validator.as_ref() else {
1348 return Ok(serde_json::Value::String(text));
1349 };
1350 let error = match decode_reply("task(): responseSchema", &text, validator) {
1351 Ok(value) => return Ok(value),
1352 Err(error) => error,
1353 };
1354 let (raw, raw_truncated) = carried_raw(&text);
1355 if attempt >= last_attempt {
1356 return Err(schema_task(fail_schema(
1357 &driver,
1358 task_id,
1359 attempt,
1360 &error,
1361 raw,
1362 raw_truncated,
1363 )));
1364 }
1365 // The attempt failed but a repair remains: record it as a receipt
1366 // (visible even when the repair succeeds), then re-run the admission
1367 // gates — a repair is a real child, not a free retry.
1368 driver.progress(ProgressEvent::TaskSchemaRepairAttempted {
1369 task_id: task_id.clone(),
1370 kind: error.kind().to_string(),
1371 attempt,
1372 message: error.message().to_string(),
1373 raw: raw.clone(),
1374 raw_truncated,
1375 });
1376 if cancel.is_cancelled() || tickets.is_cancelled(ticket) {
1377 return Err(cancelled_task());
1378 }
1379 current = repair_request(&request, attempt + 1, &error, &raw);
1380 }
1381 }
1382
1383 /// JS-facing option names for `task()` (design §3.3). Unknown fields are
1384 /// rejected so a typo (`responseschema`) fails loudly instead of being
1385 /// silently dropped. Every multi-word field also accepts its snake_case
1386 /// spelling, and the `agent` tool's `workspace_policy` name is accepted as an
1387 /// alias for worktree isolation — the two spawn surfaces are written by the
1388 /// same authors (often models), so a schema that runs on one must not be an
1389 /// unknown-field error on the other.
1390 #[derive(Debug, Deserialize)]
1391 #[serde(rename_all = "camelCase", deny_unknown_fields)]
1392 struct TaskOptions {
1393 #[serde(alias = "title")]
1394 description: Option<String>,
1395 prompt: Option<String>,
1396 #[serde(alias = "type", alias = "subagent_type")]
1397 subagent_type: Option<String>,
1398 /// Fleet role name (#4177). Preferred step identity field.
1399 role: Option<String>,
1400 profile: Option<String>,
1401 model: Option<String>,
1402 #[serde(alias = "model_strength")]
1403 model_strength: Option<String>,
1404 thinking: Option<String>,
1405 cwd: Option<String>,
1406 #[serde(default)]
1407 worktree: bool,
1408 /// `agent`-tool alias for worktree isolation: "shared" | "worktree".
1409 #[serde(default, alias = "workspace_policy")]
1410 workspace_policy: Option<String>,
1411 #[serde(alias = "write_authority")]
1412 write_authority: Option<String>,
1413 #[serde(default, alias = "write_roots")]
1414 write_roots: Vec<String>,
1415 #[serde(default, alias = "exact_files")]
1416 exact_files: Vec<String>,
1417 #[serde(default, alias = "coordination_contracts")]
1418 coordination_contracts: Vec<String>,
1419 #[serde(default)]
1420 dependencies: Vec<String>,
1421 #[serde(default)]
1422 acceptance: Vec<String>,
1423 #[serde(alias = "allowed_tools")]
1424 allowed_tools: Option<Vec<String>>,
1425 #[serde(alias = "max_depth")]
1426 max_depth: Option<u32>,
1427 #[serde(alias = "token_budget")]
1428 token_budget: Option<u64>,
1429 #[serde(alias = "max_steps")]
1430 max_steps: Option<u32>,
1431 #[serde(alias = "wall_time_secs")]
1432 wall_time_secs: Option<u64>,
1433 #[serde(alias = "response_schema")]
1434 response_schema: Option<serde_json::Value>,
1435 /// Bounded `responseSchema` repair attempts after a failed decode
1436 /// (#5583): re-ask the same route with the schema and the failed reply.
1437 /// Defaults to one; `0` disables; capped at
1438 /// [`SCHEMA_REPAIR_MAX_ATTEMPTS`] so repair stays a bounded recovery.
1439 #[serde(default, alias = "schema_repair_attempts")]
1440 schema_repair_attempts: Option<u32>,
1441 label: Option<String>,
1442 phase: Option<String>,
1443 }
1444
1445 fn parse_task_options(
1446 opts_json: &str,
1447 workspace: Option<&std::path::Path>,
1448 ) -> Result<TaskRequest, String> {
1449 let mut options: TaskOptions =
1450 serde_json::from_str(opts_json).map_err(|err| format!("task(): invalid options: {err}"))?;
1451 if let Some(policy) = options.workspace_policy.take() {
1452 match policy.trim().to_ascii_lowercase().as_str() {
1453 "worktree" => options.worktree = true,
1454 "shared" => {
1455 if options.worktree {
1456 return Err(
1457 "task(): workspacePolicy 'shared' conflicts with worktree: true"
1458 .to_string(),
1459 );
1460 }
1461 }
1462 other => {
1463 return Err(format!(
1464 "task(): workspacePolicy must be shared or worktree; got {other:?}"
1465 ));
1466 }
1467 }
1468 }
1469 let description = options
1470 .prompt
1471 .or(options.description)
1472 .filter(|description| !description.trim().is_empty())
1473 .ok_or_else(|| "task(): 'description' (or 'prompt') is required".to_string())?;
1474 let role = options
1475 .role
1476 .as_deref()
1477 .map(normalize_profile)
1478 .transpose()
1479 .map_err(|err| format!("task(): role: {err}"))?;
1480 let profile = options
1481 .profile
1482 .as_deref()
1483 .map(normalize_profile)
1484 .transpose()
1485 .map_err(|err| format!("task(): {err}"))?;
1486 options.write_roots = normalize_task_paths("writeRoots", options.write_roots, 32)?;
1487 options.exact_files = normalize_task_paths("exactFiles", options.exact_files, 32)?;
1488 let cwd = options
1489 .cwd
1490 .as_deref()
1491 .map(|cwd| normalize_task_cwd_in(cwd, workspace))
1492 .transpose()?;
1493 options.coordination_contracts =
1494 normalize_task_string_list("coordinationContracts", options.coordination_contracts, 16)?;
1495 options.dependencies = normalize_task_string_list("dependencies", options.dependencies, 8)?;
1496 options.acceptance = normalize_task_string_list("acceptance", options.acceptance, 8)?;
1497 let write_authority = options
1498 .write_authority
1499 .as_deref()
1500 .map(|value| value.trim().to_ascii_lowercase())
1501 .map(|value| match value.as_str() {
1502 "read_only" | "workspace_write" | "worktree_write" => Ok(value),
1503 _ => Err(format!(
1504 "task(): writeAuthority must be read_only, workspace_write, or worktree_write; got {value:?}"
1505 )),
1506 })
1507 .transpose()?;
1508 if write_authority.as_deref() == Some("worktree_write") && !options.worktree {
1509 return Err("task(): writeAuthority worktree_write requires worktree: true".to_string());
1510 }
1511 let role_kind = role.as_deref().and_then(task_role_kind);
1512 let type_kind = options.subagent_type.as_deref().and_then(task_role_kind);
1513 if let (Some(role_kind), Some(type_kind)) = (role_kind, type_kind)
1514 && role_kind != type_kind
1515 {
1516 return Err("task(): role and subagentType declare contradictory authorities".to_string());
1517 }
1518 let declared_kind = role_kind.or(type_kind);
1519 if matches!(declared_kind, Some(TaskRoleKind::ReadOnly))
1520 && write_authority
1521 .as_deref()
1522 .is_some_and(|authority| authority != "read_only")
1523 {
1524 return Err("task(): read-only roles cannot declare write-capable authority".to_string());
1525 }
1526 // A write-capable task with no declared scope is not refused here: the
1527 // spawn boundary (`validate_spawn_write_contract`) claims the workspace
1528 // root, or the task's deliverables, exactly as it does for a plain Agent
1529 // spawn, and the coordination ledger arbitrates contention with live peers.
1530 if let Some(attempts) = options.schema_repair_attempts
1531 && attempts > SCHEMA_REPAIR_MAX_ATTEMPTS
1532 {
1533 return Err(format!(
1534 "task(): schemaRepairAttempts is bounded to {SCHEMA_REPAIR_MAX_ATTEMPTS}; \
1535 repair is a bounded recovery, not a retry loop"
1536 ));
1537 }
1538 Ok(TaskRequest {
1539 description,
1540 subagent_type: options.subagent_type,
1541 role,
1542 profile,
1543 model: options.model,
1544 model_strength: options.model_strength,
1545 thinking: options.thinking,
1546 cwd,
1547 worktree: options.worktree,
1548 write_authority,
1549 write_roots: options.write_roots,
1550 exact_files: options.exact_files,
1551 coordination_contracts: options.coordination_contracts,
1552 dependencies: options.dependencies,
1553 acceptance: options.acceptance,
1554 allowed_tools: options.allowed_tools,
1555 // Host-imposed only: a script cannot set (or clear) a deny list.
1556 disallowed_tools: Vec::new(),
1557 max_depth: options.max_depth,
1558 token_budget: options.token_budget,
1559 max_steps: options.max_steps,
1560 wall_time_secs: options.wall_time_secs,
1561 response_schema: options.response_schema,
1562 schema_repair_attempts: options.schema_repair_attempts,
1563 label: options.label,
1564 phase: options.phase,
1565 })
1566 }
1567
1568 fn normalize_task_string_list(
1569 field: &str,
1570 values: Vec<String>,
1571 limit: usize,
1572 ) -> Result<Vec<String>, String> {
1573 if values.len() > limit {
1574 return Err(format!("task(): {field} accepts at most {limit} entries"));
1575 }
1576 let mut normalized = Vec::new();
1577 for value in values {
1578 let value = value.trim();
1579 if value.is_empty() || value.chars().count() > 512 {
1580 return Err(format!(
1581 "task(): {field} entries must be 1..=512 characters"
1582 ));
1583 }
1584 if !normalized.iter().any(|existing| existing == value) {
1585 normalized.push(value.to_string());
1586 }
1587 }
1588 Ok(normalized)
1589 }
1590
1591 /// Normalize a task working directory at both plan preflight and VM dispatch.
1592 /// The same bounded repo-relative policy applies to both entry points.
1593 pub fn normalize_task_cwd(value: &str) -> Result<String, String> {
1594 normalize_task_paths("cwd", vec![value.to_owned()], 1).map(|mut paths| paths.remove(0))
1595 }
1596
1597 /// [`normalize_task_cwd`] for a run that knows its workspace root. An
1598 /// absolute path that lies inside `workspace` is rewritten to the same
1599 /// bounded repo-relative form; an absolute path outside it, or one that
1600 /// escapes through `..`, is still rejected. Without a workspace every
1601 /// absolute path is rejected, exactly as before.
1602 ///
1603 /// The comparison is lexical and component-wise (no filesystem access), so
1604 /// `/ws-other` is never inside `/ws`. On Windows a drive letter or UNC share
1605 /// matches with or without the verbatim `\\?\` prefix, `/` and `\` are both
1606 /// separators, and components compare case-insensitively.
1607 pub fn normalize_task_cwd_in(
1608 value: &str,
1609 workspace: Option<&std::path::Path>,
1610 ) -> Result<String, String> {
1611 let raw = value.trim();
1612 let path = std::path::Path::new(raw);
1613 let Some(workspace) = workspace.filter(|_| path.is_absolute()) else {
1614 return normalize_task_cwd(value);
1615 };
1616 let outside = || {
1617 format!(
1618 "task(): cwd {raw:?} is outside the workspace {}; cwd entries must be bounded repo-relative paths or absolute paths inside the workspace",
1619 workspace.display()
1620 )
1621 };
1622 let mut remainder = path_keys(path).ok_or_else(outside)?.into_iter();
1623 for expected in path_keys(workspace).ok_or_else(outside)? {
1624 match remainder.next() {
1625 Some(actual) if actual.matches(&expected) => {}
1626 // `..` right after the workspace prefix is an escape, not a
1627 // different root: name it as traversal.
1628 Some(PathKey::Parent) => {
1629 return Err("task(): cwd paths cannot contain parent traversal".to_string());
1630 }
1631 _ => return Err(outside()),
1632 }
1633 }
1634 let mut segments = Vec::new();
1635 for key in remainder {
1636 match key {
1637 PathKey::Name { original, .. } => segments.push(original),
1638 PathKey::Parent => {
1639 return Err("task(): cwd paths cannot contain parent traversal".to_string());
1640 }
1641 PathKey::Root => return Err(outside()),
1642 }
1643 }
1644 if segments.is_empty() {
1645 return Ok(".".to_string());
1646 }
1647 normalize_task_cwd(&segments.join("/"))
1648 }
1649
1650 /// One lexical path component, keyed for comparison: a drive or UNC prefix
1651 /// with its verbatim marker dropped, and names case-folded on Windows.
1652 #[derive(Debug)]
1653 enum PathKey {
1654 Root,
1655 Parent,
1656 Name { key: String, original: String },
1657 }
1658
1659 impl PathKey {
1660 fn matches(&self, other: &Self) -> bool {
1661 match (self, other) {
1662 (Self::Root, Self::Root) | (Self::Parent, Self::Parent) => true,
1663 (Self::Name { key: left, .. }, Self::Name { key: right, .. }) => left == right,
1664 _ => false,
1665 }
1666 }
1667 }
1668
1669 fn path_keys(path: &std::path::Path) -> Option<Vec<PathKey>> {
1670 use std::path::{Component, Prefix};
1671 let fold = |value: &str| {
1672 if cfg!(windows) {
1673 value.to_lowercase()
1674 } else {
1675 value.to_string()
1676 }
1677 };
1678 let mut keys = Vec::new();
1679 for component in path.components() {
1680 match component {
1681 Component::Prefix(prefix) => {
1682 let key = match prefix.kind() {
1683 Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => {
1684 format!("{}:", drive.to_ascii_lowercase() as char)
1685 }
1686 Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => format!(
1687 "//{}/{}",
1688 server.to_str()?.to_lowercase(),
1689 share.to_str()?.to_lowercase()
1690 ),
1691 _ => prefix.as_os_str().to_str()?.to_lowercase(),
1692 };
1693 keys.push(PathKey::Name {
1694 original: key.clone(),
1695 key,
1696 });
1697 }
1698 Component::RootDir => keys.push(PathKey::Root),
1699 Component::CurDir => {}
1700 Component::ParentDir => keys.push(PathKey::Parent),
1701 Component::Normal(name) => {
1702 let original = name.to_str()?.to_string();
1703 keys.push(PathKey::Name {
1704 key: fold(&original),
1705 original,
1706 });
1707 }
1708 }
1709 }
1710 Some(keys)
1711 }
1712
1713 fn normalize_task_paths(
1714 field: &str,
1715 values: Vec<String>,
1716 limit: usize,
1717 ) -> Result<Vec<String>, String> {
1718 if values.len() > limit {
1719 return Err(format!("task(): {field} accepts at most {limit} entries"));
1720 }
1721 let mut normalized = Vec::new();
1722 for raw in values {
1723 let raw = raw.trim().replace('\\', "/");
1724 let windows_drive = raw.as_bytes().get(1) == Some(&b':')
1725 && raw.as_bytes().first().is_some_and(u8::is_ascii_alphabetic);
1726 if raw.is_empty()
1727 || raw.chars().count() > 512
1728 || raw.starts_with('/')
1729 || raw.starts_with("//")
1730 || windows_drive
1731 || raw.chars().any(|ch| matches!(ch, '\0' | '\r' | '\n'))
1732 {
1733 return Err(format!(
1734 "task(): {field} entries must be bounded repo-relative paths"
1735 ));
1736 }
1737 let mut segments = Vec::new();
1738 for segment in raw.split('/') {
1739 match segment {
1740 "" | "." => {}
1741 ".." => {
1742 return Err(format!(
1743 "task(): {field} paths cannot contain parent traversal"
1744 ));
1745 }
1746 value => segments.push(value),
1747 }
1748 }
1749 let path = if segments.is_empty() {
1750 ".".to_string()
1751 } else {
1752 segments.join("/")
1753 };
1754 if !normalized.contains(&path) {
1755 normalized.push(path);
1756 }
1757 }
1758 Ok(normalized)
1759 }
1760
1761 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1762 enum TaskRoleKind {
1763 ReadOnly,
1764 General,
1765 Implementer,
1766 }
1767
1768 fn task_role_kind(value: &str) -> Option<TaskRoleKind> {
1769 match value.trim().to_ascii_lowercase().as_str() {
1770 "explore" | "explorer" | "scout" | "plan" | "planner" | "review" | "reviewer"
1771 | "verify" | "verifier" => Some(TaskRoleKind::ReadOnly),
1772 "general" | "worker" => Some(TaskRoleKind::General),
1773 "implement" | "implementer" | "builder" => Some(TaskRoleKind::Implementer),
1774 _ => None,
1775 }
1776 }
1777
1778 const URL_PRELUDE: &str = include_str!("url_prelude.js");
1779
1780 fn prelude(is_codemode: bool) -> String {
1781 let determinism_reason = if is_codemode {
1782 "in execute_tools programs: scripts run in a deterministic sandbox without wall-clock or random state"
1783 } else {
1784 "in Workflow scripts: runs must be deterministic for record/replay"
1785 };
1786 PRELUDE_TEMPLATE
1787 .replace("__MAX_ITEMS__", &PARALLEL_MAX_ITEMS.to_string())
1788 .replace("__DETERMINISM_REASON__", determinism_reason)
1789 }
1790
1791 const PRELUDE_TEMPLATE: &str = r#""use strict";
1792 (() => {
1793 const banned = (name) => () => {
1794 throw new Error(name + " is unavailable __DETERMINISM_REASON__");
1795 };
1796 const BannedDate = function Date() {
1797 throw new Error("new Date()/Date() is unavailable __DETERMINISM_REASON__");
1798 };
1799 BannedDate.now = banned("Date.now()");
1800 BannedDate.parse = banned("Date.parse()");
1801 BannedDate.UTC = banned("Date.UTC()");
1802 globalThis.Date = BannedDate;
1803 Math.random = banned("Math.random()");
1804
1805 // Capture temporary host bindings into this closure, then strip them from
1806 // globalThis so scripts only see the documented Workflow surface (#4129).
1807 const hostTask = __workflow_task;
1808 const hostVerifyCandidate = __workflow_verify_candidate;
1809 const hostCancelTasks = __workflow_cancel_tasks;
1810 const hostLog = __workflow_log;
1811 const hostEverySlotFailed = __workflow_every_slot_failed;
1812 const hostSlotDropped = __workflow_slot_dropped;
1813 const hostPhase = __workflow_phase;
1814
1815 const MAX_ITEMS = __MAX_ITEMS__;
1816 const taskErrorText = (err) => String(err && err.message !== undefined ? err.message : err);
1817
1818 // Typed slot errors (R9). Every error thrown by task() carries a
1819 // host-assigned `kind` copied off the task envelope; anything else that
1820 // reaches a slot was thrown by the script itself and reports as "script".
1821 //
1822 // The kind is read from the error object and never guessed from message
1823 // text. A substring classifier let a child's own words ("...budget
1824 // exhausted...", "...responseSchema...") forge a fatal classification and
1825 // abort a healthy run, and it could not tell a genuine subagent failure
1826 // apart from a plain `throw new Error(...)` in a stage.
1827 const HOST_KINDS = ["admission", "budget", "cancelled", "agent", "schema", "driver"];
1828 const SCRIPT_KIND = "script";
1829 const taskErrorKind = (err) =>
1830 err !== null && typeof err === "object" && HOST_KINDS.indexOf(err.kind) !== -1
1831 ? err.kind
1832 : SCRIPT_KIND;
1833 // Fatal kinds are never absorbed into a slot value: cancellation is the
1834 // run's own deadline, and a schema breach means the contract the caller
1835 // explicitly asked for was not met. `mode: "partial"` opts out for schema
1836 // (and only schema) by keeping it as a structured slot value instead.
1837 const isFatalTaskError = (err) => {
1838 const kind = taskErrorKind(err);
1839 return kind === "cancelled" || kind === "schema";
1840 };
1841
1842 // Stamp the resolved kind onto an error that is about to be rethrown, so a
1843 // script's own `catch (err) { err.kind }` reads the same vocabulary the
1844 // slot classifier used. Host errors already carry theirs; this only names
1845 // the script throws, which would otherwise surface as `undefined`.
1846 const stampKind = (err, kind) => {
1847 if (err !== null && typeof err === "object" && err.kind === undefined) {
1848 try {
1849 err.kind = kind;
1850 } catch (_) {
1851 // A frozen error keeps whatever it has; the log line still names it.
1852 }
1853 }
1854 return err;
1855 };
1856
1857 const SLOT_MODES = ["settled", "fail-fast", "partial"];
1858 // `settled` is the default and is exactly today's behavior: a non-fatal
1859 // slot failure resolves to `null` so an author need not handle every error.
1860 // An unrecognized mode throws rather than silently falling back — a typo
1861 // like `mode: "failfast"` used to read as `settled` and quietly keep
1862 // dropping slots the author believed were now fatal.
1863 const slotMode = (fn, opts) => {
1864 if (opts === null || typeof opts !== "object" || opts.mode === undefined) {
1865 return "settled";
1866 }
1867 if (SLOT_MODES.indexOf(opts.mode) === -1) {
1868 throw new Error(
1869 fn + "(): unknown mode " + JSON.stringify(opts.mode) +
1870 "; expected one of " + SLOT_MODES.join(", ")
1871 );
1872 }
1873 return opts.mode;
1874 };
1875
1876 // The failure ledger for one fan-out, attached to the resolved array as a
1877 // non-enumerable `errors` property. Non-enumerable and non-index, so the
1878 // array's contents, length, and JSON encoding are byte-identical to before:
1879 // `results.filter(Boolean)` still works, and a script that wants to know
1880 // WHY a slot is null can now ask instead of guessing.
1881 const attachSlotErrors = (results, errors) => {
1882 errors.sort((a, b) => a.index - b.index);
1883 Object.defineProperty(results, "errors", {
1884 value: Object.freeze(errors.map((entry) => Object.freeze(entry))),
1885 enumerable: false,
1886 configurable: false,
1887 writable: false,
1888 });
1889 return results;
1890 };
1891
1892 let taskTickets = 0;
1893 const failFastGroups = [];
1894
1895 globalThis.task = async (opts) => {
1896 if (opts === null || typeof opts !== "object") {
1897 throw new TypeError("task(): expected an options object");
1898 }
1899 const ticket = ++taskTickets;
1900 for (const group of failFastGroups) group.push(ticket);
1901 const envelope = JSON.parse(await hostTask(JSON.stringify(opts), ticket));
1902 if (envelope.error !== undefined) {
1903 const err = new Error(envelope.error);
1904 // The host always names the kind; a missing one means an envelope this
1905 // prelude did not produce, which is not a typed task failure.
1906 err.kind = HOST_KINDS.indexOf(envelope.error_kind) !== -1
1907 ? envelope.error_kind
1908 : SCRIPT_KIND;
1909 throw err;
1910 }
1911 return envelope.value;
1912 };
1913
1914 globalThis.task.verifyCandidate = async (request) => {
1915 if (request === null || typeof request !== "object") {
1916 throw new TypeError("verifyCandidate(): expected an object");
1917 }
1918 const envelope = JSON.parse(await hostVerifyCandidate(JSON.stringify(request)));
1919 if (envelope.error !== undefined) {
1920 const err = new Error(envelope.error);
1921 err.kind = envelope.error_kind;
1922 if (envelope.metadata !== undefined) {
1923 err.metadata = envelope.metadata;
1924 }
1925 throw err;
1926 }
1927 return envelope.result;
1928 };
1929
1930 globalThis.parallel = (thunks, opts) => {
1931 if (!Array.isArray(thunks)) {
1932 throw new TypeError("parallel(): expected an array of thunks");
1933 }
1934 if (thunks.length > MAX_ITEMS) {
1935 throw new Error("parallel(): max " + MAX_ITEMS + " items per call");
1936 }
1937 const mode = slotMode("parallel", opts);
1938 const failFast = mode === "fail-fast";
1939 const partial = mode === "partial";
1940 const errors = [];
1941 const group = failFast ? [] : null;
1942 let groupFailed = false;
1943 const cancelGroup = () => {
1944 groupFailed = true;
1945 hostCancelTasks(group);
1946 };
1947 // Returns the slot value, or throws to reject the whole fan-out.
1948 const slotError = (index, err) => {
1949 const kind = taskErrorKind(err);
1950 const message = taskErrorText(err);
1951 stampKind(err, kind);
1952 // Cancellation is the run's deadline in every mode, partial included.
1953 if (kind === "cancelled") throw err;
1954 if (partial) {
1955 // Opt-in partial mode: every non-cancellation slot failure becomes a
1956 // structured value the script can branch on. It never masquerades as
1957 // a success -- `__taskError` is the whole point of the shape.
1958 errors.push({ index: index, kind: kind, message: message });
1959 hostLog(
1960 "parallel(): partial mode kept a failed slot as __taskError (kind=" +
1961 kind + ", slot " + index + "): " + message
1962 );
1963 return { __taskError: { index: index, kind: kind, message: message } };
1964 }
1965 if (isFatalTaskError(err)) throw err;
1966 if (failFast) {
1967 hostLog(
1968 "parallel(): fail-fast slot error (kind=" + kind + ", slot " + index + "): " + message
1969 );
1970 throw err;
1971 }
1972 errors.push({ index: index, kind: kind, message: message });
1973 hostLog(
1974 "parallel(): dropped a failed slot as null (kind=" + kind + ", slot " + index + "): " +
1975 message
1976 );
1977 hostSlotDropped("parallel", kind, index);
1978 return null;
1979 };
1980 const onSlotError = (index, err) => {
1981 try {
1982 return slotError(index, err);
1983 } catch (rethrown) {
1984 if (group !== null) cancelGroup();
1985 throw rethrown;
1986 }
1987 };
1988 if (group !== null) failFastGroups.push(group);
1989 let slots;
1990 try {
1991 slots = thunks.map((thunk, index) => {
1992 try {
1993 return Promise.resolve(typeof thunk === "function" ? thunk() : thunk)
1994 .catch((err) => onSlotError(index, err));
1995 } catch (err) {
1996 try {
1997 return onSlotError(index, err);
1998 } catch (rethrown) {
1999 return Promise.reject(rethrown);
2000 }
2001 }
2002 });
2003 } finally {
2004 if (group !== null) {
2005 failFastGroups.splice(failFastGroups.indexOf(group), 1);
2006 if (groupFailed) hostCancelTasks(group);
2007 }
2008 }
2009 return Promise.all(slots).then((results) => {
2010 // A fan-out where nothing survived is a dead fan-out, not resilience.
2011 // The default stays ergonomic (the array still resolves) but the run
2012 // log says so in one line an operator can grep for, and the structured
2013 // event below lets the host status classifier refuse to call such a
2014 // run a plain success.
2015 if (results.length > 0 && errors.length === results.length) {
2016 hostLog(
2017 "parallel(): every slot failed (" + errors.length + " of " + results.length +
2018 "); no work survived this fan-out"
2019 );
2020 hostEverySlotFailed("parallel", errors.length, results.length);
2021 }
2022 return attachSlotErrors(results, errors);
2023 });
2024 };
2025
2026 globalThis.pipeline = (items, ...stages) => {
2027 if (!Array.isArray(items)) {
2028 throw new TypeError("pipeline(): expected an array of items");
2029 }
2030 if (items.length > MAX_ITEMS) {
2031 throw new Error("pipeline(): max " + MAX_ITEMS + " items per call");
2032 }
2033 // Options overload: pipeline(items, { stages: [...], mode: "fail-fast" }).
2034 let mode = "settled";
2035 if (
2036 stages.length === 1 &&
2037 stages[0] !== null &&
2038 typeof stages[0] === "object" &&
2039 Array.isArray(stages[0].stages)
2040 ) {
2041 mode = slotMode("pipeline", stages[0]);
2042 stages = stages[0].stages;
2043 }
2044 const failFast = mode === "fail-fast";
2045 const partial = mode === "partial";
2046 const errors = [];
2047 return Promise.all(items.map(async (item, index) => {
2048 let value = item;
2049 for (const stage of stages) {
2050 try {
2051 value = await stage(value, item, index);
2052 } catch (err) {
2053 const kind = taskErrorKind(err);
2054 const message = taskErrorText(err);
2055 stampKind(err, kind);
2056 if (kind === "cancelled") throw err;
2057 if (partial) {
2058 errors.push({ index: index, kind: kind, message: message });
2059 hostLog(
2060 "pipeline(): partial mode kept item " + index +
2061 " as __taskError (kind=" + kind + "): " + message
2062 );
2063 return { __taskError: { index: index, kind: kind, message: message } };
2064 }
2065 if (isFatalTaskError(err)) throw err;
2066 if (failFast) {
2067 hostLog(
2068 "pipeline(): fail-fast stage error on item " + index +
2069 " (kind=" + kind + "): " + message
2070 );
2071 throw err;
2072 }
2073 errors.push({ index: index, kind: kind, message: message });
2074 hostLog(
2075 "pipeline(): dropped item " + index + " as null (kind=" + kind + "): " + message
2076 );
2077 hostSlotDropped("pipeline", kind, index);
2078 return null;
2079 }
2080 }
2081 return value;
2082 })).then((results) => {
2083 if (results.length > 0 && errors.length === results.length) {
2084 hostLog(
2085 "pipeline(): every item failed (" + errors.length + " of " + results.length +
2086 "); no work survived this pipeline"
2087 );
2088 hostEverySlotFailed("pipeline", errors.length, results.length);
2089 }
2090 return attachSlotErrors(results, errors);
2091 });
2092 };
2093
2094 const UrlCtor = globalThis.URL;
2095 const UrlSearchParamsCtor = globalThis.URLSearchParams;
2096 const safeString = (value) => {
2097 try {
2098 return String(value);
2099 } catch (_) {
2100 return "[object Object]";
2101 }
2102 };
2103 const formatLogValue = (value) => {
2104 if (typeof value === "string") return value;
2105 if (value === null) return "null";
2106 if (value === undefined) return "undefined";
2107 if (
2108 typeof value === "number" ||
2109 typeof value === "boolean" ||
2110 typeof value === "bigint" ||
2111 typeof value === "symbol" ||
2112 typeof value === "function"
2113 ) {
2114 return String(value);
2115 }
2116 if (
2117 value instanceof Error ||
2118 (UrlCtor && value instanceof UrlCtor) ||
2119 (UrlSearchParamsCtor && value instanceof UrlSearchParamsCtor)
2120 ) {
2121 return safeString(value);
2122 }
2123 try {
2124 const encoded = JSON.stringify(value);
2125 return encoded === undefined ? safeString(value) : encoded;
2126 } catch (_) {
2127 return safeString(value);
2128 }
2129 };
2130 const formatConsoleArgs = (items) => {
2131 if (items.length === 0) return "";
2132 const parts = new Array(items.length);
2133 for (let i = 0; i < items.length; i++) {
2134 parts[i] = formatLogValue(items[i]);
2135 }
2136 return parts.join(" ");
2137 };
2138 const emitConsole = (prefix, items) => {
2139 const text = formatConsoleArgs(items);
2140 if (prefix === "") {
2141 hostLog(text);
2142 } else if (text === "") {
2143 hostLog(prefix);
2144 } else {
2145 hostLog(prefix + " " + text);
2146 }
2147 };
2148
2149 globalThis.log = (message) => {
2150 hostLog(formatLogValue(message));
2151 };
2152 globalThis.console = Object.freeze({
2153 log: (...items) => emitConsole("", items),
2154 info: (...items) => emitConsole("[info]", items),
2155 warn: (...items) => emitConsole("[warn]", items),
2156 error: (...items) => emitConsole("[error]", items),
2157 debug: (...items) => emitConsole("[debug]", items),
2158 });
2159 globalThis.phase = (title) => {
2160 hostPhase(String(title));
2161 };
2162
2163 globalThis.budget = Object.freeze({
2164 total: null,
2165 metered: false,
2166 spent: () => null,
2167 remaining: () => null,
2168 });
2169
2170 for (const name of [
2171 "__workflow_task",
2172 "__workflow_verify_candidate",
2173 "__workflow_cancel_tasks",
2174 "__workflow_log",
2175 "__workflow_every_slot_failed",
2176 "__workflow_slot_dropped",
2177 "__workflow_phase",
2178 ]) {
2179 try {
2180 delete globalThis[name];
2181 } catch (_) {
2182 // Non-configurable bindings stay; the inventory test will fail closed.
2183 }
2184 }
2185 })();
2186 "#;
2187
2187 lines RUST