返回 CodeWhale
codemode.rs
根目录 / crates / engine / src / tools / codemode.rs
1 //! `execute_tools` — code mode: run a model-provided JavaScript program that
2 //! composes tool calls through `tools.call(name, args)`.
3 //!
4 //! The program handles loops, branching, filtering, and data movement;
5 //! intermediate results stay in the VM and only the bounded return value plus
6 //! a host-owned receipt reach the model. The engine-side precedent is the
7 //! synthetic interpreter dispatch (`code_execution`): this
8 //! tool is engine-injected, never registered, and dispatched in
9 //! `core::engine::tool_execution`.
10 //!
11 //! Authority stays entirely in Rust, and there is one gate. In a session turn,
12 //! a sub-agent's included, the engine hands the program a [`NestedCallGate`];
13 //! every nested call — native, plugin, or MCP — is sent back to the turn loop
14 //! and planned by the same `plan_tool_calls` a direct call goes through
15 //! (deny/allow lists, preparation, hooks, ask-rules, Auto-Review, repo law, the
16 //! worker authority envelope, a sub-agent's grant, the K1 Computer Use
17 //! refusal), with the source tagged as code mode so only `tools.load`
18 //! activates a deferred schema. A nested call that needs approval suspends the
19 //! program: the engine raises the normal approval request
20 //! (`request_tool_approval`, same receipt log, same card) and the program
21 //! resumes on allow; on deny only that nested call fails, as an exception the
22 //! program can catch. Approving the program itself therefore grants nothing,
23 //! and `execute_tools` is prepared as auto-approved. A sub-agent's nested call
24 //! is then admitted at execution like its direct call
25 //! (`ToolRegistry::admit_child_call`: write-scope claim and live peers).
26 //!
27 //! Without a gate (a direct unit call, or a dispatch with no per-call context)
28 //! the program runs read-only, auto-approved native calls only, no MCP.
29 //!
30 //! Receipts (#6509): the host records every nested call when it starts, so a
31 //! program that hits its deadline still reports what finished, what was
32 //! refused, and what was in flight. Oversized nested results keep the
33 //! `{content, metadata, truncated}` keys, and the cut is never silent:
34 //! `truncated` names the original size, the spillover file holding the
35 //! full output and the `ref` that `retrieve_tool_result` pages it by. A JSON
36 //! `content` stays valid JSON of the same shape with trailing array
37 //! elements, object members and string tails cut; text `content` becomes its
38 //! leading text, so a script checks `truncated` before trusting counts. A
39 //! failed call's text is bounded and spilled the same way.
40 //!
41 //! KV-cache effect: `[features] code_mode` (on by default) makes
42 //! `execute_tools` eager from the first request of a session; with the flag
43 //! off it is deferred like the interpreter tools. The flag is session config,
44 //! so the prefix is stable within a session either way. The definition text
45 //! is static. Program text, nested results, and nested discovery live in
46 //! append-only turn history, never in the prefix; `tools.load` is the one
47 //! nested call that adds schemas to the next request, under a declared
48 //! `tool_surface` change.
49 //!
50 //! Known limitations:
51 //! - Nested calls do not take per-tool locks against sibling top-level calls;
52 //! the program runs under its own exclusive lock instead. Inside the
53 //! program, calls the gate marks non-parallel run one at a time.
54 //! - No nested `agent`, `workflow`, `rlm`, `request_user_input`, `show_data`,
55 //! `present`, `request_plugin_install`, interpreter, interactive shell,
56 //! sandbox escalation, Computer Use consent/script, MCP sign-in, or
57 //! recursive `execute_tools`. Those stay direct calls; `tools.load` adds a
58 //! deferred one to the next step.
59 //! - Rich content blocks (images) from nested results are dropped; text and
60 //! JSON payloads pass through bounded.
61 //! - Available in Plan mode too (every nested call still passes Plan's
62 //! read-only gates and requires the session tool gate). Hidden under a
63 //! worker authority envelope and from a sub-agent whose grant refuses it
64 //! (the evidence surface, or an explicit tool list that leaves it out).
65 //! Those surfaces offer `tool_search` instead.
66
67 use std::sync::{Arc, Mutex};
68 use std::time::{Duration, Instant};
69
70 use async_trait::async_trait;
71 use serde_json::{Value, json};
72 use tokio::sync::{Mutex as AsyncMutex, RwLock, Semaphore, mpsc, oneshot};
73 use tokio_util::sync::CancellationToken;
74
75 use codewhale_models::Tool;
76 use codewhale_workflow_js::{
77 DriverError, ProgressEvent, SpawnedTask, TaskRequest, ToolCallRequest, ToolCallResponse,
78 ToolInvoker, WorkflowDriver, WorkflowRunCancel, WorkflowVm,
79 };
80
81 use crate::core::events::Event;
82 use crate::mcp::McpPool;
83 use crate::tools::registry::{ToolRegistry, enforce_tool_authority};
84 use crate::tools::spec::{
85 ApprovalRequirement, RichToolResult, ToolContext, ToolError, ToolResult, ToolSpec, required_str,
86 };
87
88 /// Tool name surfaced to the model. Dispatched alongside the synthetic
89 /// interpreter tools; see `core::engine::tool_execution`.
90 pub const EXECUTE_TOOLS_TOOL_NAME: &str = "execute_tools";
91
92 const EXECUTE_TOOLS_TOOL_TYPE: &str = "execute_tools_20260918";
93
94 /// Maximum program source accepted, in bytes.
95 const MAX_CODE_BYTES: usize = 64 * 1024;
96 /// Run deadline when no engine turn serves the program (a direct unit call,
97 /// or a dispatch with no per-call context). This is an hour-long backstop
98 /// rather than an invented short cap. A gated run takes the remaining turn
99 /// wall clock instead, which is unbounded unless `[tui].turn_wall_clock_secs`
100 /// is set. A sub-agent's program also stops at the sub-agent's tool timeout
101 /// or work deadline, and still returns its receipt.
102 const FALLBACK_RUN_DEADLINE: Duration = Duration::from_secs(3_600);
103 /// How often the run watchdog re-checks while the program is paused on the
104 /// gate (approval card, hook, review). Bounds the overrun after a pause.
105 const PAUSED_WATCHDOG_POLL: Duration = Duration::from_millis(200);
106 /// Maximum nested tool calls in flight at once, enforced host-side.
107 const MAX_CONCURRENT_CALLS: usize = 4;
108 /// Per nested-call result cap, in serialized bytes. The same threshold the
109 /// engine spills a direct tool result at, so a nested result is never cut
110 /// sooner than the same call made directly.
111 const PER_CALL_RESULT_CAP_BYTES: usize = crate::tools::truncate::SPILLOVER_THRESHOLD_BYTES;
112 /// Model-visible return cap, in serialized bytes.
113 const RETURN_CAP_BYTES: usize = 16 * 1024;
114 const MAX_LOG_LINES: usize = 200;
115 const MAX_LOG_LINE_BYTES: usize = 1024;
116 const MAX_LOG_TOTAL_BYTES: usize = 8 * 1024;
117
118 /// Names refused before the gate, with a message that names the supported
119 /// alternative. These either need the turn loop itself (a prompt, a
120 /// sub-agent, a card drawn from the direct call) or would nest an execution
121 /// surface.
122 const PROHIBITED_NESTED: &[&str] = &[
123 EXECUTE_TOOLS_TOOL_NAME,
124 "code_execution",
125 "agent",
126 "workflow",
127 // Recursive RLM rounds are admitted by the turn loop serving the direct
128 // `rlm` call; a program has no such server for a nested one.
129 "rlm",
130 codewhale_tools::names::REQUEST_USER_INPUT_NAME,
131 "multi_tool_use.parallel",
132 "show_data",
133 "present",
134 "request_plugin_install",
135 ];
136
137 /// Model-facing definition. `defer_loading` is decided by the catalog
138 /// (eager under code mode, deferred otherwise); `allowed_callers` mirrors
139 /// `code_execution`. The text is static so it never moves the prefix.
140 pub fn execute_tools_tool_definition() -> Tool {
141 Tool {
142 tool_type: Some(EXECUTE_TOOLS_TOOL_TYPE.to_string()),
143 name: EXECUTE_TOOLS_TOOL_NAME.to_string(),
144 description: "Run a JavaScript program over tools; only its return value comes back. \
145 Use it for MCP tools, tools not in your list, and dependent or batched calls. \
146 `tools.search(query)`, `tools.list(namespace?)` and `tools.describe(names)` return \
147 names, TypeScript signatures and summaries; `tools.call(name, args)` or \
148 `tools.<server>.<op>(args)` runs one. Entries marked direct_only cannot run in a \
149 program: `tools.load(names)` adds their schemas to your next step. Every nested call \
150 passes the same permission checks as a direct call; an approval pauses the program \
151 and a denial throws. Results are {content, metadata, truncated}; when truncated is \
152 set, content is partial: page the rest with retrieve_tool_result {ref: \
153 truncated.ref, mode: 'json'}. 4 calls run at once; the return value is capped at \
154 16 KiB."
155 .to_string(),
156 input_schema: json!({
157 "type": "object",
158 "properties": {
159 "code": {
160 "type": "string",
161 "description": "JavaScript program. The return value (or thrown error) becomes the result; use tools.list/tools.search/tools.describe for discovery and tools.call(name, argsObject) or tools.<namespace>.<op>(argsObject) for tool calls."
162 }
163 },
164 "required": ["code"]
165 }),
166 allowed_callers: Some(vec!["direct".to_string()]),
167 defer_loading: Some(false),
168 input_examples: None,
169 strict: None,
170 cache_control: None,
171 }
172 }
173
174 // ---------------------------------------------------------------------------
175 // The engine-served gate
176 // ---------------------------------------------------------------------------
177
178 /// How the gate decided one nested call. Named in the receipt.
179 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
180 #[serde(rename_all = "snake_case")]
181 pub enum NestedDecision {
182 /// Admitted without a prompt: an auto-approved tier, a remembered grant,
183 /// or a posture that already covers it.
184 Auto,
185 /// A person approved this exact nested call.
186 Approved,
187 /// A person denied it.
188 Denied,
189 /// The approval card expired with no answer. The call did not run, and
190 /// the user did not deny it.
191 TimedOut,
192 /// A gate refused it before any prompt (policy, hook, authority, or a
193 /// name that stays a direct call).
194 Refused,
195 }
196
197 /// The gate's answer for one nested call.
198 pub enum NestedCallVerdict {
199 /// Run the call with the final (possibly hook-rewritten) name and input.
200 Run {
201 name: String,
202 input: Value,
203 supports_parallel: bool,
204 decision: NestedDecision,
205 /// `additionalContext` from tool_call_before hooks (#3026), recorded
206 /// on the call's receipt so it reaches the model.
207 hook_context: Option<String>,
208 },
209 /// The engine answered in place (describe-only `tool_search`, a guard).
210 Answered {
211 result: ToolResult,
212 hook_context: Option<String>,
213 },
214 /// Do not run it; the error is what the program sees.
215 Refused {
216 error: ToolError,
217 decision: NestedDecision,
218 },
219 }
220
221 /// One nested call waiting on the turn loop's gate.
222 pub enum NestedCallRequest {
223 Tool(NestedToolCallRequest),
224 Checkpoint {
225 caller: crate::core::events::SessionCheckpointCaller,
226 withdraw: CancellationToken,
227 reply: oneshot::Sender<Result<bool, ToolError>>,
228 },
229 UserQuestion {
230 caller: crate::core::events::SessionCheckpointCaller,
231 request: crate::tools::user_input::UserInputRequest,
232 withdraw: CancellationToken,
233 clock: Arc<Mutex<PauseClock>>,
234 reply: oneshot::Sender<Result<crate::tools::user_input::UserInputResponse, ToolError>>,
235 },
236 }
237
238 pub struct NestedToolCallRequest {
239 pub name: String,
240 pub input: Value,
241 pub reply: oneshot::Sender<NestedCallVerdict>,
242 /// Fires when the caller no longer wants an answer (an extension's host
243 /// cancelled the request, its owner was revoked, the host exited, the
244 /// invocation ended). The server must not start work for a request whose
245 /// token has fired ([`Self::is_stale`]) and must stop waiting on a person
246 /// when it fires: an approval is withdrawn, never silently decided.
247 pub withdraw: Option<CancellationToken>,
248 pub child_activation: bool,
249 }
250
251 impl NestedToolCallRequest {
252 /// Nobody is waiting for the answer any more.
253 pub fn is_stale(&self) -> bool {
254 self.reply.is_closed()
255 || self
256 .withdraw
257 .as_ref()
258 .is_some_and(CancellationToken::is_cancelled)
259 }
260 }
261
262 /// Who an extension's `core/call` is made for, as the core knows it: composed
263 /// by Rust from the extension tool's registration, never from anything the host
264 /// says.
265 #[derive(Debug, Clone, PartialEq, Eq)]
266 pub struct ExtensionCaller {
267 /// `extension:<plugin>`: named on the approval card and in audit records.
268 pub origin: String,
269 /// The extension tool the calls are made inside.
270 pub tool: String,
271 /// The approval-grant scope of that plugin build (`ext:<id>@<hash>`); the
272 /// approval keys of its calls are scoped by it, so a grant given to the
273 /// model never covers an extension's call and the reverse.
274 pub scope: String,
275 }
276
277 impl ExtensionCaller {
278 #[must_use]
279 pub fn plugin_id(&self) -> Option<&str> {
280 self.scope
281 .strip_prefix("ext:")
282 .and_then(|rest| rest.split_once('@'))
283 .map(|(plugin_id, _)| plugin_id)
284 .filter(|plugin_id| !plugin_id.is_empty())
285 }
286 }
287
288 /// What an extension tool's gate carries beyond the channel: who it is for,
289 /// and the tool snapshot its calls run against.
290 struct ExtensionGate {
291 caller: ExtensionCaller,
292 specs: Vec<Arc<dyn ToolSpec>>,
293 }
294
295 /// Handle a running program uses to reach the engine turn that launched it.
296 /// Built per `execute_tools` call by the turn loop and carried on that call's
297 /// [`ToolContext`]; dropped with the call.
298 #[derive(Clone)]
299 pub struct NestedCallGate {
300 requests: mpsc::Sender<NestedCallRequest>,
301 mcp_pool: Option<Arc<AsyncMutex<McpPool>>>,
302 tx_event: mpsc::Sender<Event>,
303 deadline: Duration,
304 /// Set only on the gate of an extension tool's call
305 /// ([`Self::for_extension`]).
306 extension: Option<Arc<ExtensionGate>>,
307 }
308
309 impl NestedCallGate {
310 /// A gate plus the receiver the turn loop serves. `deadline` bounds the
311 /// program's own run time; time spent waiting on the gate (approval
312 /// cards, hooks, reviews) does not count against it.
313 pub fn new(
314 mcp_pool: Option<Arc<AsyncMutex<McpPool>>>,
315 tx_event: mpsc::Sender<Event>,
316 deadline: Duration,
317 ) -> (Self, mpsc::Receiver<NestedCallRequest>) {
318 let (requests, receiver) = mpsc::channel(MAX_CONCURRENT_CALLS);
319 (
320 Self {
321 requests,
322 mcp_pool,
323 tx_event,
324 deadline,
325 extension: None,
326 },
327 receiver,
328 )
329 }
330
331 /// This gate serves one extension tool's call: `caller` is who it is for
332 /// and `specs` the tool snapshot its core calls run against.
333 pub fn for_extension(mut self, caller: ExtensionCaller, specs: Vec<Arc<dyn ToolSpec>>) -> Self {
334 self.extension = Some(Arc::new(ExtensionGate { caller, specs }));
335 self
336 }
337
338 /// The caller and tool snapshot of an extension tool's gate; `None` for
339 /// the gate of an `execute_tools` program or an `rlm` call.
340 pub fn extension(&self) -> Option<(&ExtensionCaller, &[Arc<dyn ToolSpec>])> {
341 self.extension
342 .as_deref()
343 .map(|gate| (&gate.caller, gate.specs.as_slice()))
344 }
345
346 pub fn mcp_pool(&self) -> Option<Arc<AsyncMutex<McpPool>>> {
347 self.mcp_pool.clone()
348 }
349
350 pub async fn checkpoint(
351 &self,
352 caller: crate::core::events::SessionCheckpointCaller,
353 withdraw: CancellationToken,
354 ) -> Result<bool, ToolError> {
355 if self.extension.is_none() {
356 return Err(ToolError::not_available(
357 "session checkpoint requires a directly served plugin invocation",
358 ));
359 }
360 let (reply, answer) = oneshot::channel();
361 let request = NestedCallRequest::Checkpoint {
362 caller,
363 withdraw: withdraw.clone(),
364 reply,
365 };
366 tokio::select! {
367 biased;
368 () = withdraw.cancelled() => Err(ToolError::cancelled("session checkpoint was withdrawn")),
369 result = async {
370 self.requests.send(request).await.map_err(|_| ToolError::not_available("the turn no longer serves session checkpoints"))?;
371 answer.await.map_err(|_| ToolError::not_available("owning host did not acknowledge the session checkpoint"))?
372 } => result,
373 }
374 }
375
376 pub async fn user_question(
377 &self,
378 caller: crate::core::events::SessionCheckpointCaller,
379 request: crate::tools::user_input::UserInputRequest,
380 withdraw: CancellationToken,
381 clock: Arc<Mutex<PauseClock>>,
382 ) -> Result<crate::tools::user_input::UserInputResponse, ToolError> {
383 if self.extension.is_none() {
384 return Err(ToolError::not_available(
385 "user questions require a directly served plugin invocation",
386 ));
387 }
388 let (reply, answer) = oneshot::channel();
389 let request = NestedCallRequest::UserQuestion {
390 caller,
391 request,
392 withdraw: withdraw.clone(),
393 clock,
394 reply,
395 };
396 tokio::select! {
397 biased;
398 () = withdraw.cancelled() => Err(ToolError::cancelled("user question was withdrawn")),
399 result = async {
400 self.requests.send(request).await.map_err(|_| ToolError::not_available("the turn no longer serves user questions"))?;
401 answer.await.map_err(|_| ToolError::not_available("owning host did not answer the user question"))?
402 } => result,
403 }
404 }
405
406 /// Ask the serving turn loop to decide one nested call. A gate nobody
407 /// serves any more refuses.
408 pub async fn ask(&self, name: String, input: Value) -> NestedCallVerdict {
409 self.ask_withdrawable(name, input, None).await
410 }
411
412 /// [`Self::ask`], withdrawn when `withdraw` fires: the request is dropped
413 /// if the server has not started it, and the server stops waiting on a
414 /// person if it has (the approval is recorded cancelled).
415 pub async fn ask_withdrawable(
416 &self,
417 name: String,
418 input: Value,
419 withdraw: Option<CancellationToken>,
420 ) -> NestedCallVerdict {
421 self.ask_request(name, input, withdraw, false).await
422 }
423
424 async fn ask_request(
425 &self,
426 name: String,
427 input: Value,
428 withdraw: Option<CancellationToken>,
429 child_activation: bool,
430 ) -> NestedCallVerdict {
431 let unavailable = || NestedCallVerdict::Refused {
432 error: ToolError::not_available(
433 "the turn that launched this program is no longer serving its permission gate",
434 ),
435 decision: NestedDecision::Refused,
436 };
437 let cancelled = || NestedCallVerdict::Refused {
438 error: ToolError::cancelled("the call was withdrawn before the gate answered"),
439 decision: NestedDecision::Refused,
440 };
441 let (reply, answer) = oneshot::channel();
442 let request = NestedCallRequest::Tool(NestedToolCallRequest {
443 name,
444 input,
445 reply,
446 withdraw: withdraw.clone(),
447 child_activation,
448 });
449 let wait = async {
450 if self.requests.send(request).await.is_err() {
451 return unavailable();
452 }
453 answer.await.unwrap_or_else(|_| unavailable())
454 };
455 match withdraw {
456 None => wait.await,
457 Some(withdraw) => tokio::select! {
458 biased;
459 () = withdraw.cancelled() => cancelled(),
460 verdict = wait => verdict,
461 },
462 }
463 }
464 }
465
466 #[cfg(any(test, feature = "test-support"))]
467 impl NestedCallGate {
468 /// A gate whose server admits every call exactly as asked, for tests of
469 /// consumers that are not about admission. Needs a Tokio runtime.
470 pub fn admitting_for_test() -> Self {
471 Self::answering_for_test(|name, input| NestedCallVerdict::Run {
472 name: name.to_string(),
473 input: input.clone(),
474 supports_parallel: false,
475 decision: NestedDecision::Auto,
476 hook_context: None,
477 })
478 }
479
480 /// A gate whose server answers every call with `answer`.
481 pub fn answering_for_test(
482 answer: impl Fn(&str, &Value) -> NestedCallVerdict + Send + 'static,
483 ) -> Self {
484 let (tx_event, mut rx_event) = mpsc::channel(64);
485 tokio::spawn(async move { while rx_event.recv().await.is_some() {} });
486 let (gate, mut requests) = Self::new(None, tx_event, Duration::from_secs(60));
487 tokio::spawn(async move {
488 while let Some(request) = requests.recv().await {
489 let request = match request {
490 NestedCallRequest::Tool(request) => request,
491 NestedCallRequest::UserQuestion { reply, .. } => {
492 let _ = reply.send(Err(ToolError::not_available(
493 "fixture has no user question backend",
494 )));
495 continue;
496 }
497 NestedCallRequest::Checkpoint { reply, .. } => {
498 let _ = reply.send(Err(ToolError::not_available(
499 "fixture has no session checkpoint backend",
500 )));
501 continue;
502 }
503 };
504 let _ = request.reply.send(answer(&request.name, &request.input));
505 }
506 });
507 gate
508 }
509 }
510
511 /// Refusals decided from the request alone: calls that need the turn loop
512 /// itself or their own approval card stay direct. Checked on the name the
513 /// program sent, and again by the turn loop on the name planning resolved it
514 /// to (`Agent` resolves to `agent`) and the final, hook-rewritten input.
515 ///
516 /// Names compare ASCII case-insensitively: dispatch resolves `Agent` to
517 /// `agent`, so a case-sensitive list would be a bypass, not a policy.
518 pub fn refusal_before_gate(name: &str, input: &Value) -> Option<String> {
519 let lower = name.to_ascii_lowercase();
520 if PROHIBITED_NESTED.contains(&lower.as_str()) {
521 return Some(format!(
522 "`{name}` is not available inside execute_tools programs; call it directly. If it is not in your tool list, tools.load([\"{lower}\"]) adds it to your next step"
523 ));
524 }
525 if matches!(lower.as_str(), "bash" | "exec_shell")
526 && input.get("interactive").and_then(Value::as_bool) == Some(true)
527 {
528 return Some(format!(
529 "`{name}` with interactive:true needs the terminal; call it directly"
530 ));
531 }
532 if input.get("sandbox_permissions").is_some() {
533 return Some(format!(
534 "`{name}` requests a sandbox escalation, which needs its own exact-call approval; call it directly"
535 ));
536 }
537 if crate::tools::approval_cache::computer_use_user_gate(name, input).is_some()
538 || crate::tools::approval_cache::computer_use_batch_hidden_gate(name, input).is_some()
539 {
540 return Some(format!(
541 "Computer Use call `{name}` grants consent or runs a script; it needs its own approval card, so call it directly and let the user decide"
542 ));
543 }
544 if crate::extension_host::creator_policy::is_creator_plugin_manager_name(&lower)
545 && !crate::extension_host::creator_policy::is_list_action(input)
546 {
547 return Some(format!(
548 "`{name}` changes plugins and is not available inside execute_tools programs; call it directly"
549 ));
550 }
551 if McpPool::is_mcp_tool(name)
552 && name.ends_with(&format!("_{}", crate::mcp::AUTHENTICATE_TOOL_NAME))
553 {
554 return Some(format!(
555 "`{name}` starts an MCP sign-in; call it directly. If it is not in your tool list, tools.load([\"{name}\"]) adds it to your next step"
556 ));
557 }
558 None
559 }
560
561 // ---------------------------------------------------------------------------
562 // Receipts
563 // ---------------------------------------------------------------------------
564
565 /// What was cut from an oversized value, and where the whole value went.
566 #[derive(Debug, Clone, PartialEq, serde::Serialize)]
567 struct Truncation {
568 original_bytes: usize,
569 kept_bytes: usize,
570 spill_path: Option<String>,
571 #[serde(rename = "ref", skip_serializing_if = "Option::is_none")]
572 retrieve_ref: Option<String>,
573 }
574
575 #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
576 #[serde(rename_all = "snake_case")]
577 enum CallStatus {
578 /// Started and not yet finished. Left in place when the run ends early,
579 /// so the receipt says the call may have partially run.
580 InFlight,
581 Ok,
582 Failed,
583 Refused,
584 }
585
586 /// One nested call, as recorded by the host — not the script. The receipt is
587 /// what makes "no failures found" distinguishable from "nothing ran".
588 #[derive(Debug, Clone, serde::Serialize)]
589 struct CallReceipt {
590 #[serde(skip_serializing)]
591 seq: usize,
592 tool: String,
593 #[serde(skip_serializing_if = "Option::is_none")]
594 decision: Option<NestedDecision>,
595 status: CallStatus,
596 ok: bool,
597 elapsed_ms: u64,
598 bytes: usize,
599 #[serde(skip_serializing_if = "Option::is_none")]
600 truncated: Option<Truncation>,
601 #[serde(skip_serializing_if = "Option::is_none")]
602 note: Option<String>,
603 /// `additionalContext` a tool_call_before hook attached to this call,
604 /// the same text a direct call appends to its result (#3026).
605 #[serde(skip_serializing_if = "Option::is_none")]
606 hook_context: Option<String>,
607 }
608
609 /// Run clock that stops while the program waits on the gate, so a person
610 /// taking a minute on an approval card does not spend the program's budget.
611 /// An extension tool's `tool/call` deadline runs on the same clock
612 /// (`extension_host::supervisor::HostProcess::call_with_clock`), paused while
613 /// one of its `core/call`s waits on the gate.
614 pub struct PauseClock {
615 started: Instant,
616 paused: Duration,
617 depth: usize,
618 since: Option<Instant>,
619 }
620
621 impl PauseClock {
622 pub(crate) fn new() -> Self {
623 Self {
624 started: Instant::now(),
625 paused: Duration::ZERO,
626 depth: 0,
627 since: None,
628 }
629 }
630
631 fn pause(&mut self) {
632 if self.depth == 0 {
633 self.since = Some(Instant::now());
634 }
635 self.depth += 1;
636 }
637
638 fn resume(&mut self) {
639 self.depth = self.depth.saturating_sub(1);
640 if self.depth == 0
641 && let Some(since) = self.since.take()
642 {
643 self.paused += since.elapsed();
644 }
645 }
646
647 fn active(&self) -> Duration {
648 let paused = self.paused + self.since.map_or(Duration::ZERO, |since| since.elapsed());
649 self.started.elapsed().saturating_sub(paused)
650 }
651
652 /// Time left before `deadline`, or `None` once it has passed. While the
653 /// clock is paused its budget is frozen, so the caller looks again shortly
654 /// ([`PAUSED_WATCHDOG_POLL`]): sleeping out the whole deadline would let it
655 /// overrun by that much once the pause ends.
656 pub fn remaining(&self, deadline: Duration) -> Option<Duration> {
657 if self.depth > 0 {
658 return Some(PAUSED_WATCHDOG_POLL.min(deadline));
659 }
660 deadline
661 .checked_sub(self.active())
662 .filter(|left| !left.is_zero())
663 }
664 }
665
666 pub struct PauseGuard<'a>(&'a Mutex<PauseClock>);
667
668 impl<'a> PauseGuard<'a> {
669 pub fn new(clock: &'a Mutex<PauseClock>) -> Self {
670 if let Ok(mut clock) = clock.lock() {
671 clock.pause();
672 }
673 Self(clock)
674 }
675 }
676
677 impl Drop for PauseGuard<'_> {
678 fn drop(&mut self) {
679 if let Ok(mut clock) = self.0.lock() {
680 clock.resume();
681 }
682 }
683 }
684
685 /// Abort a spawned nested call when the program stops waiting for it.
686 struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
687
688 impl<T> Drop for AbortOnDrop<T> {
689 fn drop(&mut self) {
690 self.0.abort();
691 }
692 }
693
694 // ---------------------------------------------------------------------------
695 // Invoker
696 // ---------------------------------------------------------------------------
697
698 #[derive(Default)]
699 struct NestedEffects {
700 usage_batch: crate::cost_status::RuntimeUsageBatch,
701 mcp_catalog_changed: bool,
702 backgrounded: bool,
703 evidence_available: bool,
704 goal_tool_ran: bool,
705 goal_created: bool,
706 edited_calls: Vec<(String, Value)>,
707 }
708
709 const MAX_NESTED_EDITED_CALLS: usize = 64;
710
711 /// [`ToolInvoker`] over a snapshot of the parent turn's registry.
712 ///
713 /// The snapshot (a registry of the spec Arcs under a cloned [`ToolContext`])
714 /// is taken at dispatch so the invoker is `'static` for the VM thread. Nested
715 /// calls run on the engine's runtime (captured at dispatch), not the VM
716 /// thread's.
717 pub struct CodemodeInvoker {
718 registry: Arc<ToolRegistry>,
719 context: ToolContext,
720 gate: Option<NestedCallGate>,
721 runtime: Option<tokio::runtime::Handle>,
722 semaphore: Arc<Semaphore>,
723 /// Non-parallel nested calls take this exclusively; parallel-safe ones
724 /// share it, mirroring how the engine schedules direct calls.
725 order: RwLock<()>,
726 receipts: Mutex<Vec<CallReceipt>>,
727 effects: Mutex<NestedEffects>,
728 clock: Arc<Mutex<PauseClock>>,
729 spill_prefix: String,
730 /// Refusals beyond code mode's own, decided from the request alone before
731 /// the gate is asked (an extension's list: `extension_host::core_call`).
732 extra_refusal: Option<ExtraRefusal>,
733 }
734
735 /// A refusal decided from the specs, the tool name and its input.
736 pub type ExtraRefusal = fn(&[Arc<dyn ToolSpec>], &str, &Value) -> Option<String>;
737
738 /// Why a gated call did not produce a result. The decision is what the gate
739 /// recorded; a caller that is not code mode maps it to its own error codes.
740 #[derive(Debug)]
741 pub enum NestedFailure {
742 /// Refused or denied: nothing ran.
743 Rejected {
744 decision: NestedDecision,
745 message: String,
746 },
747 /// The seam broke, the call timed out or was cancelled.
748 Unavailable(String),
749 }
750
751 impl From<NestedFailure> for DriverError {
752 fn from(failure: NestedFailure) -> Self {
753 match failure {
754 NestedFailure::Rejected { message, .. } => DriverError::Rejected(message),
755 NestedFailure::Unavailable(message) => DriverError::Unavailable(message),
756 }
757 }
758 }
759
760 impl CodemodeInvoker {
761 fn new(specs: Vec<Arc<dyn ToolSpec>>, context: ToolContext) -> Self {
762 let mut context = context;
763 let gate = context.execution.nested_call_gate.take();
764 let spill_prefix = context
765 .origin_tool_call_id
766 .clone()
767 .unwrap_or_else(|| EXECUTE_TOOLS_TOOL_NAME.to_string());
768 Self::with_gate(specs, context, gate, spill_prefix, None)
769 }
770
771 /// The machinery for an extension tool's `core/call`s: the same gate,
772 /// executor, receipts, concurrency cap and pausable clock as a program's
773 /// nested calls, with `extra_refusal` added to what is refused outright.
774 /// `context` is the extension tool's own; its gate is the one given here,
775 /// which the tool's calls then never see again.
776 pub fn for_extension(
777 specs: Vec<Arc<dyn ToolSpec>>,
778 mut context: ToolContext,
779 gate: NestedCallGate,
780 spill_prefix: String,
781 extra_refusal: ExtraRefusal,
782 ) -> Self {
783 context.execution.nested_call_gate = None;
784 context.execution.strict_workspace_confinement = true;
785 context.execution.trust_mode = false;
786 context.execution.follow_symlinks = false;
787 context.execution.trusted_external_paths.clear();
788 context.read_only_roots.clear();
789 Self::with_gate(
790 specs,
791 context,
792 Some(gate),
793 spill_prefix,
794 Some(extra_refusal),
795 )
796 }
797
798 fn with_gate(
799 specs: Vec<Arc<dyn ToolSpec>>,
800 context: ToolContext,
801 gate: Option<NestedCallGate>,
802 spill_prefix: String,
803 extra_refusal: Option<ExtraRefusal>,
804 ) -> Self {
805 let mut registry = ToolRegistry::new(context.clone());
806 registry.register_all(specs);
807 Self {
808 registry: Arc::new(registry),
809 context,
810 gate,
811 runtime: tokio::runtime::Handle::try_current().ok(),
812 semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_CALLS)),
813 order: RwLock::new(()),
814 receipts: Mutex::new(Vec::new()),
815 effects: Mutex::new(NestedEffects::default()),
816 clock: Arc::new(Mutex::new(PauseClock::new())),
817 spill_prefix,
818 extra_refusal,
819 }
820 }
821
822 fn deadline(&self) -> Duration {
823 self.gate
824 .as_ref()
825 .map_or(FALLBACK_RUN_DEADLINE, |gate| gate.deadline)
826 }
827
828 fn pause(&self) -> PauseGuard<'_> {
829 PauseGuard::new(&self.clock)
830 }
831
832 /// Time left before the deadline ([`PauseClock::remaining`]).
833 fn remaining(&self, deadline: Duration) -> Option<Duration> {
834 self.clock.lock().ok()?.remaining(deadline)
835 }
836
837 /// The clock the run's deadline is measured on, for a caller whose own
838 /// deadline must stop while this run waits on the gate.
839 pub fn clock(&self) -> Arc<Mutex<PauseClock>> {
840 Arc::clone(&self.clock)
841 }
842
843 fn begin(&self, tool: &str) -> usize {
844 let Ok(mut receipts) = self.receipts.lock() else {
845 return 0;
846 };
847 let seq = receipts.len() + 1;
848 receipts.push(CallReceipt {
849 seq,
850 tool: tool.to_string(),
851 decision: None,
852 status: CallStatus::InFlight,
853 ok: false,
854 elapsed_ms: 0,
855 bytes: 0,
856 truncated: None,
857 note: None,
858 hook_context: None,
859 });
860 seq
861 }
862
863 fn finish(&self, seq: usize, update: impl FnOnce(&mut CallReceipt)) {
864 if let Ok(mut receipts) = self.receipts.lock()
865 && let Some(receipt) = receipts.iter_mut().find(|receipt| receipt.seq == seq)
866 {
867 update(receipt);
868 }
869 }
870
871 fn drain(&self) -> Vec<CallReceipt> {
872 self.receipts
873 .lock()
874 .map(|receipts| receipts.clone())
875 .unwrap_or_default()
876 }
877
878 fn refused(
879 &self,
880 seq: usize,
881 started: Instant,
882 decision: NestedDecision,
883 note: String,
884 ) -> NestedFailure {
885 self.finish(seq, |receipt| {
886 receipt.decision = Some(decision);
887 receipt.status = CallStatus::Refused;
888 receipt.elapsed_ms = started.elapsed().as_millis() as u64;
889 receipt.note = Some(note.clone());
890 });
891 NestedFailure::Rejected {
892 decision,
893 message: note,
894 }
895 }
896
897 fn ungated_catalog(&self) -> Vec<Tool> {
898 let mut tools = self.registry.to_api_tools();
899 tools.retain(|tool| {
900 !McpPool::is_mcp_tool(&tool.name)
901 && self.registry.get(&tool.name).is_some_and(|spec| {
902 spec.is_read_only() && spec.approval_requirement() == ApprovalRequirement::Auto
903 })
904 });
905 tools
906 }
907
908 /// Admission when no engine gate serves the program.
909 fn ungated_admission(&self, name: &str, input: &Value) -> Result<(), String> {
910 if McpPool::is_mcp_tool(name) {
911 return Err(format!(
912 "`{name}` is an MCP tool; no engine turn serves this program's session permission gate, so call it directly"
913 ));
914 }
915 let Some(spec) = self.registry.get(name) else {
916 return Err(
917 crate::core::engine::tool_catalog::unknown_program_tool_message(
918 &self.ungated_catalog(),
919 name,
920 ),
921 );
922 };
923 if !spec.is_read_only_for(input) {
924 return Err(format!(
925 "`{name}` can mutate; without a session permission gate code mode executes read-only calls only"
926 ));
927 }
928 if spec.approval_requirement_for(input) != ApprovalRequirement::Auto {
929 return Err(format!(
930 "`{name}` needs approval; without a session permission gate code mode executes only auto-approved calls"
931 ));
932 }
933 if !self.context.auto_approve
934 && self.context.approval_mode == codewhale_execpolicy::ApprovalMode::Suggest
935 && crate::core::engine::tool_catalog::is_shell_tool_name(name)
936 {
937 return Err(format!(
938 "`{name}` runs a command, and Ask asks before every command; without a session permission gate code mode cannot ask, so call it directly"
939 ));
940 }
941 enforce_tool_authority(name, input, spec.as_ref(), &self.context)
942 .map_err(|err| err.to_string())
943 }
944
945 /// Execute an admitted call on the engine runtime: MCP through the
946 /// session pool (same dispatcher as a direct call), everything else
947 /// through the registry under the turn's authority envelope. Either way a
948 /// sub-agent's call is first admitted against its grant, as its direct
949 /// call is.
950 async fn execute(&self, name: &str, input: Value) -> Result<RichToolResult, ToolError> {
951 self.execute_in(name, input, self.context.clone()).await
952 }
953
954 async fn execute_in(
955 &self,
956 name: &str,
957 input: Value,
958 context: ToolContext,
959 ) -> Result<RichToolResult, ToolError> {
960 use crate::core::engine::tool_execution::OperationSpanGuard;
961 let action_id = super::activity::action_id(name, &input);
962 let mcp = if McpPool::is_mcp_tool(name) {
963 let Some(gate) = self.gate.as_ref() else {
964 return Err(ToolError::not_available(format!(
965 "MCP tool `{name}` needs the session MCP pool"
966 )));
967 };
968 let Some(pool) = gate.mcp_pool.clone() else {
969 return Err(ToolError::not_available(format!(
970 "MCP is not connected for this turn, so `{name}` cannot run"
971 )));
972 };
973 Some((pool, gate.tx_event.clone()))
974 } else {
975 None
976 };
977 let activity_kind = match mcp.as_ref() {
978 Some((pool, _)) => pool
979 .lock()
980 .await
981 .resolved_tool_servers()
982 .get(name)
983 .map(|server| super::activity::mcp_activity_kind(server)),
984 None => super::activity::registry_activity_kind(name, &input),
985 };
986 let registry = Arc::clone(&self.registry);
987 let name = name.to_string();
988 let tx = self.gate.as_ref().map(|gate| gate.tx_event.clone());
989 let cancel = self.context.cancel_token.clone();
990 let call_id = self
991 .context
992 .origin_tool_call_id
993 .clone()
994 .unwrap_or_else(|| self.spill_prefix.clone());
995 let future = async move {
996 if cancel.as_ref().is_some_and(CancellationToken::is_cancelled) {
997 return Err(ToolError::cancelled("Nested dispatch admission cancelled."));
998 }
999 let span = match (tx.as_ref(), activity_kind) {
1000 (Some(tx), Some(kind)) => Some(
1001 OperationSpanGuard::reserve(
1002 tx,
1003 &call_id,
1004 kind,
1005 Some(action_id),
1006 cancel.clone(),
1007 )
1008 .await,
1009 ),
1010 _ => None,
1011 };
1012 if cancel.as_ref().is_some_and(CancellationToken::is_cancelled) {
1013 return Err(ToolError::cancelled("Nested dispatch admission cancelled."));
1014 }
1015 let Some((pool, tx_event)) = mcp else {
1016 return registry
1017 .execute_rich_full_with_context(&name, input, Some(&context), || {
1018 Ok(span.map(OperationSpanGuard::activate))
1019 })
1020 .await;
1021 };
1022 let child = registry.admit_child_call(&name, &input, &context).await?;
1023 let span = span.map(OperationSpanGuard::activate);
1024 let outcome = crate::core::engine::Engine::execute_mcp_tool_with_pool(
1025 pool,
1026 &tx_event,
1027 &name,
1028 input,
1029 &context.disallowed_tools,
1030 // Calls a program makes never carry a person's decision.
1031 None,
1032 context.account_fence.as_deref(),
1033 None,
1034 child
1035 .as_ref()
1036 .and_then(|_| registry.delegated_mcp_read(&name)),
1037 )
1038 .await;
1039 if let Some(span) = span {
1040 span.complete(super::activity::operation_outcome(
1041 &outcome,
1042 cancel.as_ref().is_some_and(CancellationToken::is_cancelled),
1043 ))
1044 .await;
1045 }
1046 if outcome.as_ref().is_ok_and(|result| result.result.success)
1047 && let Some((authority, writes)) = child
1048 {
1049 authority.record_settled_writes(writes).await;
1050 }
1051 outcome
1052 };
1053 match self.runtime.as_ref() {
1054 Some(runtime) => {
1055 let mut task = AbortOnDrop(runtime.spawn(future));
1056 match (&mut task.0).await {
1057 Ok(result) => result,
1058 Err(err) => Err(ToolError::execution_failed(format!(
1059 "nested call did not complete: {err}"
1060 ))),
1061 }
1062 }
1063 None => future.await,
1064 }
1065 }
1066
1067 fn record_effects(
1068 &self,
1069 name: &str,
1070 input: Option<&Value>,
1071 success: bool,
1072 metadata: Option<&Value>,
1073 truncated: Option<&Truncation>,
1074 ) {
1075 let Ok(mut effects) = self.effects.lock() else {
1076 return;
1077 };
1078 if let Some(meta) = metadata {
1079 if let Some(batch) = crate::cost_status::child_usage_records_from_metadata(meta) {
1080 effects.usage_batch.decisions.extend(batch.decisions);
1081 effects.usage_batch.records.extend(batch.records);
1082 effects.usage_batch.drop_records.extend(batch.drop_records);
1083 effects.usage_batch.dropped_records = effects
1084 .usage_batch
1085 .dropped_records
1086 .saturating_add(batch.dropped_records);
1087 }
1088 if meta.get("mcp_catalog_changed").and_then(Value::as_bool) == Some(true) {
1089 effects.mcp_catalog_changed = true;
1090 }
1091 if crate::core::engine::tool_catalog::result_started_background_shell_job(Some(meta)) {
1092 effects.backgrounded = true;
1093 }
1094 if meta.get("evidence_available").and_then(Value::as_bool) == Some(true)
1095 || crate::core::engine::offers_retrieval(Some(meta))
1096 {
1097 effects.evidence_available = true;
1098 }
1099 }
1100 if truncated.is_some_and(|trunc| trunc.retrieve_ref.is_some()) {
1101 effects.evidence_available = true;
1102 }
1103 if matches!(name, "create_goal" | "update_goal") {
1104 effects.goal_tool_ran = true;
1105 if name == "create_goal" && success {
1106 effects.goal_created = true;
1107 }
1108 }
1109 if success
1110 && let Some(call_input) = input
1111 && effects.edited_calls.len() < MAX_NESTED_EDITED_CALLS
1112 {
1113 effects
1114 .edited_calls
1115 .push((name.to_string(), call_input.clone()));
1116 }
1117 }
1118
1119 fn mark_evidence_available(&self) {
1120 if let Ok(mut effects) = self.effects.lock() {
1121 effects.evidence_available = true;
1122 }
1123 }
1124
1125 fn take_effects(&self) -> NestedEffects {
1126 self.effects
1127 .lock()
1128 .map(|mut effects| std::mem::take(&mut *effects))
1129 .unwrap_or_default()
1130 }
1131
1132 /// Shape one finished call for the program and complete its receipt.
1133 fn deliver(
1134 &self,
1135 seq: usize,
1136 started: Instant,
1137 name: &str,
1138 input: Option<&Value>,
1139 decision: NestedDecision,
1140 outcome: Result<RichToolResult, ToolError>,
1141 ) -> Result<ToolCallResponse, NestedFailure> {
1142 let elapsed_ms = started.elapsed().as_millis() as u64;
1143 match outcome {
1144 Ok(rich) => {
1145 let result = rich.into_result();
1146 let success = result.success;
1147 let (payload, raw_len, truncated) = self.bounded_envelope(seq, name, &result);
1148 self.record_effects(
1149 name,
1150 input,
1151 success,
1152 result.metadata.as_ref(),
1153 truncated.as_ref(),
1154 );
1155 self.finish(seq, |receipt| {
1156 receipt.decision = Some(decision);
1157 receipt.status = if success {
1158 CallStatus::Ok
1159 } else {
1160 CallStatus::Failed
1161 };
1162 receipt.ok = success;
1163 receipt.elapsed_ms = elapsed_ms;
1164 receipt.bytes = raw_len;
1165 receipt.truncated = truncated;
1166 });
1167 Ok(ToolCallResponse {
1168 ok: success,
1169 result: payload,
1170 })
1171 }
1172 Err(err) => {
1173 let message = err.to_string();
1174 // Validation-shaped failures mean nothing ran (admission);
1175 // execution failures ran and failed (agent kind via ok:false);
1176 // seam breaks are unavailable.
1177 match err {
1178 ToolError::InvalidInput { .. } | ToolError::MissingField { .. } => {
1179 let signature = self
1180 .registry
1181 .to_api_tools()
1182 .into_iter()
1183 .find(|tool| tool.name == name)
1184 .map(|tool| {
1185 crate::core::engine::tool_catalog::render_ts_signature(&tool)
1186 });
1187 let enriched = match signature {
1188 Some(sig) => format!("{message} (expected signature: {sig})"),
1189 None => message,
1190 };
1191 Err(self.refused(seq, started, decision, enriched))
1192 }
1193 ToolError::PathEscape { .. } | ToolError::PermissionDenied { .. } => {
1194 Err(self.refused(seq, started, decision, message))
1195 }
1196 ToolError::Timeout { .. }
1197 | ToolError::Cancelled { .. }
1198 | ToolError::NotAvailable { .. } => {
1199 self.finish(seq, |receipt| {
1200 receipt.decision = Some(decision);
1201 receipt.status = CallStatus::Failed;
1202 receipt.elapsed_ms = elapsed_ms;
1203 receipt.note = Some(message.clone());
1204 });
1205 Err(NestedFailure::Unavailable(message))
1206 }
1207 ToolError::ExecutionFailed { .. } => {
1208 let bytes = message.len();
1209 let (text, truncated) = bound_text(
1210 message,
1211 PER_CALL_RESULT_CAP_BYTES,
1212 &self.spill_id(seq, name),
1213 &self.context.state_namespace,
1214 );
1215 self.finish(seq, |receipt| {
1216 receipt.decision = Some(decision);
1217 receipt.status = CallStatus::Failed;
1218 receipt.elapsed_ms = elapsed_ms;
1219 receipt.bytes = bytes;
1220 receipt.truncated = truncated;
1221 });
1222 Ok(ToolCallResponse {
1223 ok: false,
1224 result: text,
1225 })
1226 }
1227 }
1228 }
1229 }
1230 }
1231
1232 /// Spillover id for one nested call's full output.
1233 fn spill_id(&self, seq: usize, name: &str) -> String {
1234 format!("{}-nested-{seq}-{name}", self.spill_prefix)
1235 }
1236
1237 /// Stable envelope: the tool's text content (parsed as JSON when it is
1238 /// JSON), its structured metadata, and `truncated` (null unless cut).
1239 /// An oversized result keeps the same keys: JSON `content` keeps its
1240 /// shape with trailing elements and string tails cut, text `content`
1241 /// becomes its head, and `truncated` says how much there was, where the
1242 /// whole output was saved, and the `ref` that pages it.
1243 fn bounded_envelope(
1244 &self,
1245 seq: usize,
1246 name: &str,
1247 result: &ToolResult,
1248 ) -> (Value, usize, Option<Truncation>) {
1249 let metadata = result.metadata.clone().unwrap_or(Value::Null);
1250 let mut content = serde_json::from_str(&result.content)
1251 .unwrap_or_else(|_| Value::String(result.content.clone()));
1252 if McpPool::is_mcp_tool(name)
1253 && let Some(envelope) = content.as_object()
1254 && envelope
1255 .keys()
1256 .all(|key| key == "content" || key == "isError")
1257 && envelope
1258 .get("isError")
1259 .is_none_or(|value| value == &Value::Bool(false))
1260 && let Some(blocks) = envelope.get("content").and_then(Value::as_array)
1261 && let [block] = blocks.as_slice()
1262 && let Some(fields) = block.as_object()
1263 && fields.keys().all(|key| key == "type" || key == "text")
1264 && block.get("type").and_then(Value::as_str) == Some("text")
1265 && let Some(text) = block.get("text").and_then(Value::as_str)
1266 && let Ok(parsed) = serde_json::from_str::<Value>(text)
1267 {
1268 content = parsed;
1269 }
1270 let mut payload =
1271 json!({ "content": content, "metadata": metadata, "truncated": Value::Null });
1272 let raw = payload.to_string();
1273 if raw.len() <= PER_CALL_RESULT_CAP_BYTES {
1274 return (payload, raw.len(), None);
1275 }
1276 let (spill_path, retrieve_ref) = spill(
1277 &self.spill_id(seq, name),
1278 &raw,
1279 &self.context.state_namespace,
1280 );
1281 let metadata_len = metadata.to_string().len();
1282 let metadata = if metadata_len <= PER_CALL_RESULT_CAP_BYTES / 4 {
1283 metadata
1284 } else {
1285 Value::Null
1286 };
1287 let content = match payload["content"].take() {
1288 Value::String(text) => Value::String(char_prefix(&text, PER_CALL_RESULT_CAP_BYTES / 2)),
1289 value => crate::tools::truncate::shrink_json(value, PER_CALL_RESULT_CAP_BYTES / 2).0,
1290 };
1291 let kept_bytes = match &content {
1292 Value::String(text) => text.len(),
1293 value => crate::tools::truncate::json_len(value),
1294 };
1295 let truncation = Truncation {
1296 original_bytes: raw.len(),
1297 kept_bytes,
1298 spill_path,
1299 retrieve_ref,
1300 };
1301 (
1302 json!({
1303 "content": content,
1304 "metadata": metadata,
1305 "truncated": truncation,
1306 }),
1307 raw.len(),
1308 Some(truncation),
1309 )
1310 }
1311 }
1312
1313 /// The receipts' bounds when they are attached to another tool's result.
1314 const RECEIPT_NOTE_BYTES: usize = 256;
1315
1316 impl CodemodeInvoker {
1317 /// The receipts of the calls so far as JSON, at most `max` of them with
1318 /// each note cut short: what an extension tool's result records about the
1319 /// core calls it made. The count says how many there were in all.
1320 pub fn receipts_json(&self, max: usize) -> Value {
1321 let receipts = self.drain();
1322 let total = receipts.len();
1323 let shown: Vec<CallReceipt> = receipts
1324 .into_iter()
1325 .take(max)
1326 .map(|mut receipt| {
1327 receipt.note = receipt
1328 .note
1329 .map(|note| char_prefix(&note, RECEIPT_NOTE_BYTES));
1330 receipt.hook_context = None;
1331 receipt
1332 })
1333 .collect();
1334 json!({ "total": total, "calls": shown })
1335 }
1336
1337 /// One gated call: refuse it outright if it is on a refusal list, ask the
1338 /// engine's gate (the program is paused meanwhile), then run it and shape
1339 /// the answer, recording a receipt throughout. `withdraw` stops the wait
1340 /// for a slot, the gate's wait on a person, and the execution.
1341 pub async fn call(
1342 &self,
1343 tool: String,
1344 input: Value,
1345 withdraw: Option<&CancellationToken>,
1346 ) -> Result<ToolCallResponse, NestedFailure> {
1347 let permit = self.semaphore.clone().acquire_owned();
1348 let _permit = match withdraw {
1349 None => permit.await,
1350 Some(withdraw) => tokio::select! {
1351 biased;
1352 () = withdraw.cancelled() => {
1353 return Err(NestedFailure::Unavailable("the call was withdrawn".to_string()));
1354 }
1355 permit = permit => permit,
1356 },
1357 }
1358 .map_err(|_| NestedFailure::Unavailable("code-mode run shut down".to_string()))?;
1359 let started = Instant::now();
1360 let seq = self.begin(&tool);
1361
1362 if let Some(note) = refusal_before_gate(&tool, &input).or_else(|| {
1363 self.extra_refusal
1364 .and_then(|refuse| refuse(&self.registry.all(), &tool, &input))
1365 }) {
1366 return Err(self.refused(seq, started, NestedDecision::Refused, note));
1367 }
1368
1369 let (name, input, supports_parallel, decision, hook_context) = match self.gate.as_ref() {
1370 Some(gate) => {
1371 let verdict = {
1372 let _paused = self.pause();
1373 gate.ask_withdrawable(tool.clone(), input, withdraw.cloned())
1374 .await
1375 };
1376 match verdict {
1377 NestedCallVerdict::Run {
1378 name,
1379 input,
1380 supports_parallel,
1381 decision,
1382 hook_context,
1383 } => (name, input, supports_parallel, decision, hook_context),
1384 NestedCallVerdict::Answered {
1385 result,
1386 hook_context,
1387 } => {
1388 self.finish(seq, |receipt| receipt.hook_context = hook_context);
1389 return self.deliver(
1390 seq,
1391 started,
1392 &tool,
1393 None,
1394 NestedDecision::Auto,
1395 Ok(RichToolResult::plain(result)),
1396 );
1397 }
1398 NestedCallVerdict::Refused { error, decision } => {
1399 return Err(self.refused(seq, started, decision, error.to_string()));
1400 }
1401 }
1402 }
1403 None if tool == codewhale_tools::names::TOOL_SEARCH_NAME => {
1404 let found = crate::core::engine::tool_catalog::describe_tools_for_program(
1405 &input,
1406 &self.ungated_catalog(),
1407 );
1408 return self.deliver(
1409 seq,
1410 started,
1411 &tool,
1412 None,
1413 NestedDecision::Auto,
1414 found.map(RichToolResult::plain),
1415 );
1416 }
1417 None => {
1418 if let Err(note) = self.ungated_admission(&tool, &input) {
1419 return Err(self.refused(seq, started, NestedDecision::Refused, note));
1420 }
1421 (tool.clone(), input, true, NestedDecision::Auto, None)
1422 }
1423 };
1424 self.finish(seq, |receipt| {
1425 if name != tool {
1426 receipt.tool = name.clone();
1427 }
1428 receipt.hook_context = hook_context;
1429 });
1430
1431 let edit_input = matches!(
1432 codewhale_execpolicy::canonical_action::canonical_action_alias(&name, &input),
1433 "edit_file" | "write_file" | "apply_patch"
1434 )
1435 .then(|| input.clone());
1436 let run = async {
1437 if supports_parallel {
1438 let _shared = self.order.read().await;
1439 self.execute(&name, input).await
1440 } else {
1441 let _exclusive = self.order.write().await;
1442 self.execute(&name, input).await
1443 }
1444 };
1445 let outcome = match withdraw {
1446 None => run.await,
1447 Some(withdraw) => tokio::select! {
1448 biased;
1449 () = withdraw.cancelled() => {
1450 Err(ToolError::cancelled("the call was withdrawn while it ran"))
1451 }
1452 outcome = run => outcome,
1453 },
1454 };
1455 self.deliver(seq, started, &name, edit_input.as_ref(), decision, outcome)
1456 }
1457 }
1458
1459 impl CodemodeInvoker {
1460 pub async fn start_child_activation(
1461 &self,
1462 input: Value,
1463 withdraw: &CancellationToken,
1464 request: Arc<crate::tools::subagent::ChildActivationRequest>,
1465 ) -> Result<ToolCallResponse, NestedFailure> {
1466 let Some(gate) = self.gate.as_ref() else {
1467 return Err(NestedFailure::Unavailable(
1468 "child activation requires the turn's permission gate".to_string(),
1469 ));
1470 };
1471 let _permit = tokio::select! {
1472 biased;
1473 () = withdraw.cancelled() => {
1474 return Err(NestedFailure::Unavailable("the call was withdrawn".to_string()));
1475 }
1476 permit = self.semaphore.clone().acquire_owned() => permit,
1477 }
1478 .map_err(|_| NestedFailure::Unavailable("code-mode run shut down".to_string()))?;
1479 let started = Instant::now();
1480 let seq = self.begin("agent");
1481 let verdict = {
1482 let _paused = self.pause();
1483 gate.ask_request("agent".to_string(), input, Some(withdraw.clone()), true)
1484 .await
1485 };
1486 let (input, decision, hook_context) = match verdict {
1487 NestedCallVerdict::Run {
1488 name,
1489 input,
1490 decision,
1491 hook_context,
1492 ..
1493 } if name == "agent" && child_activation_input(&input) => {
1494 (input, decision, hook_context)
1495 }
1496 NestedCallVerdict::Run { .. } | NestedCallVerdict::Answered { .. } => {
1497 return Err(self.refused(
1498 seq,
1499 started,
1500 NestedDecision::Refused,
1501 "the admitted call is no longer a child activation start".to_string(),
1502 ));
1503 }
1504 NestedCallVerdict::Refused { error, decision } => {
1505 return Err(self.refused(seq, started, decision, error.to_string()));
1506 }
1507 };
1508 self.finish(seq, |receipt| receipt.hook_context = hook_context);
1509 let mut context = self.context.clone();
1510 context.execution.child_activation = Some(request);
1511 let outcome = {
1512 let _exclusive = self.order.write().await;
1513 tokio::select! {
1514 biased;
1515 () = withdraw.cancelled() => Err(ToolError::cancelled("the call was withdrawn while it ran")),
1516 outcome = self.execute_in("agent", input, context) => outcome,
1517 }
1518 };
1519 self.deliver(seq, started, "agent", None, decision, outcome)
1520 }
1521 }
1522
1523 pub fn child_activation_input(input: &Value) -> bool {
1524 input.as_object().is_some_and(|object| {
1525 object.get("action").and_then(Value::as_str) == Some("start")
1526 && object.get("fork_context").and_then(Value::as_bool) == Some(false)
1527 && object.get("prompt").and_then(Value::as_str).is_some()
1528 && object
1529 .keys()
1530 .all(|key| matches!(key.as_str(), "action" | "prompt" | "model" | "fork_context"))
1531 })
1532 }
1533
1534 #[async_trait]
1535 impl ToolInvoker for CodemodeInvoker {
1536 async fn invoke(&self, request: ToolCallRequest) -> Result<ToolCallResponse, DriverError> {
1537 let ToolCallRequest { tool, input } = request;
1538 self.call(tool, input, None)
1539 .await
1540 .map_err(DriverError::from)
1541 }
1542 }
1543
1544 #[derive(Default)]
1545 struct CodemodeLogBuffer {
1546 lines: Vec<String>,
1547 total_bytes: usize,
1548 dropped: usize,
1549 }
1550
1551 #[derive(Default)]
1552 pub struct CodemodeDriver {
1553 logs: Mutex<CodemodeLogBuffer>,
1554 }
1555
1556 impl CodemodeDriver {
1557 fn log_lines(&self) -> Vec<String> {
1558 self.logs
1559 .lock()
1560 .map(|logs| {
1561 let mut lines = logs.lines.clone();
1562 if logs.dropped > 0 {
1563 lines.push(format!("... ({} log entries omitted)", logs.dropped));
1564 }
1565 lines
1566 })
1567 .unwrap_or_default()
1568 }
1569 }
1570
1571 #[async_trait]
1572 impl WorkflowDriver for CodemodeDriver {
1573 async fn spawn_task(&self, _request: TaskRequest) -> Result<SpawnedTask, DriverError> {
1574 Err(DriverError::Rejected(
1575 "task() is unavailable in execute_tools programs; tools.call() composes direct tool calls"
1576 .to_string(),
1577 ))
1578 }
1579
1580 fn progress(&self, event: ProgressEvent) {
1581 let ProgressEvent::Log { message } = event else {
1582 return;
1583 };
1584 let Ok(mut logs) = self.logs.lock() else {
1585 return;
1586 };
1587 if logs.dropped > 0
1588 || logs.lines.len() >= MAX_LOG_LINES
1589 || logs.total_bytes >= MAX_LOG_TOTAL_BYTES
1590 {
1591 logs.dropped = logs.dropped.saturating_add(1);
1592 return;
1593 }
1594 let line = if message.len() > MAX_LOG_LINE_BYTES {
1595 format!("{}...", char_prefix(&message, MAX_LOG_LINE_BYTES - 3))
1596 } else {
1597 message
1598 };
1599 let remaining = MAX_LOG_TOTAL_BYTES.saturating_sub(logs.total_bytes);
1600 if line.len() > remaining {
1601 logs.dropped = logs.dropped.saturating_add(1);
1602 return;
1603 }
1604 logs.total_bytes = logs.total_bytes.saturating_add(line.len());
1605 logs.lines.push(line);
1606 }
1607
1608 fn cancel_all(&self) {}
1609 }
1610
1611 /// Longest prefix of `text` within `max_bytes` that ends on a char boundary.
1612 fn char_prefix(text: &str, max_bytes: usize) -> String {
1613 let cut = max_bytes.min(text.len());
1614 let cut = (0..=cut)
1615 .rev()
1616 .find(|&index| text.is_char_boundary(index))
1617 .unwrap_or(0);
1618 text[..cut].to_string()
1619 }
1620
1621 /// Save a full value through the session spillover store and record which
1622 /// session owns it, so `retrieve_tool_result` can page it by `ref`. The path
1623 /// is `None` when the store is unavailable (the truncation is still
1624 /// reported); the ref is `None` when ownership could not be recorded.
1625 fn spill(id: &str, content: &str, session: &str) -> (Option<String>, Option<String>) {
1626 let path = match crate::tools::truncate::write_spillover(id, content) {
1627 Ok(path) => path,
1628 Err(error) => {
1629 tracing::warn!(target: "codemode", %error, "nested result spillover failed");
1630 return (None, None);
1631 }
1632 };
1633 let retrieve_ref = crate::tools::truncate::publish_legacy_spillover_ownership(
1634 &path,
1635 session,
1636 content.as_bytes(),
1637 )
1638 .ok()
1639 .and_then(|_| path.file_stem())
1640 .map(|stem| stem.to_string_lossy().into_owned());
1641 (Some(path.display().to_string()), retrieve_ref)
1642 }
1643
1644 /// Bound the program's return value to `cap` serialized bytes. An oversized
1645 /// value keeps its JSON shape with trailing elements and string tails cut,
1646 /// and the truncation record says so.
1647 fn bound_json(
1648 value: Value,
1649 cap: usize,
1650 spill_id: &str,
1651 session: &str,
1652 ) -> (Value, Option<Truncation>) {
1653 let raw = value.to_string();
1654 if raw.len() <= cap {
1655 return (value, None);
1656 }
1657 if let Value::String(text) = value {
1658 return bound_text(text, cap, spill_id, session);
1659 }
1660 let (spill_path, retrieve_ref) = spill(spill_id, &raw, session);
1661 let (kept, _) = crate::tools::truncate::shrink_json(value, cap / 2);
1662 let truncation = Truncation {
1663 original_bytes: raw.len(),
1664 kept_bytes: crate::tools::truncate::json_len(&kept),
1665 spill_path,
1666 retrieve_ref,
1667 };
1668 (kept, Some(truncation))
1669 }
1670
1671 /// Bound `text` to `cap` bytes: an oversized text becomes its head, the
1672 /// whole text is saved, and the truncation record says so.
1673 fn bound_text(
1674 text: String,
1675 cap: usize,
1676 spill_id: &str,
1677 session: &str,
1678 ) -> (Value, Option<Truncation>) {
1679 let encoded_len = serde_json::to_string(&text).map_or(text.len(), |encoded| encoded.len());
1680 if encoded_len <= cap {
1681 return (Value::String(text), None);
1682 }
1683 let head = char_prefix(&text, cap / 2);
1684 let (spill_path, retrieve_ref) = spill(spill_id, &text, session);
1685 let truncation = Truncation {
1686 original_bytes: text.len(),
1687 kept_bytes: head.len(),
1688 spill_path,
1689 retrieve_ref,
1690 };
1691 (Value::String(head), Some(truncation))
1692 }
1693
1694 fn receipt_payload(
1695 success: bool,
1696 mut body: Value,
1697 invoker: &CodemodeInvoker,
1698 driver: &CodemodeDriver,
1699 ) -> ToolResult {
1700 let calls = invoker.drain();
1701 let effects = invoker.take_effects();
1702 let ran = calls.iter().any(|call| call.status != CallStatus::Refused);
1703 if !success
1704 && body.get("timed_out") != Some(&Value::Bool(true))
1705 && calls.iter().any(|call| call.status == CallStatus::InFlight)
1706 && let Some(obj) = body.as_object_mut()
1707 {
1708 obj.insert(
1709 "hint".into(),
1710 Value::String(
1711 "Sibling calls remained in_flight when the program threw. Use Promise.allSettled for independent batches so one failure or denial does not abort siblings."
1712 .into(),
1713 ),
1714 );
1715 }
1716 let content = json!({
1717 "success": success,
1718 "body": body,
1719 "calls": calls,
1720 "log": driver.log_lines(),
1721 })
1722 .to_string();
1723 let mut meta = serde_json::Map::new();
1724 if !ran {
1725 meta.insert("executed".into(), Value::Bool(false));
1726 }
1727 if effects.mcp_catalog_changed {
1728 meta.insert("mcp_catalog_changed".into(), Value::Bool(true));
1729 }
1730 if effects.backgrounded {
1731 meta.insert("backgrounded".into(), Value::Bool(true));
1732 }
1733 if effects.evidence_available {
1734 meta.insert("evidence_available".into(), Value::Bool(true));
1735 }
1736 if effects.goal_tool_ran {
1737 meta.insert("nested_goal_tool_ran".into(), Value::Bool(true));
1738 }
1739 if effects.goal_created {
1740 meta.insert("nested_goal_created".into(), Value::Bool(true));
1741 }
1742 if !effects.edited_calls.is_empty() {
1743 meta.insert(
1744 "nested_edited_calls".into(),
1745 Value::Array(
1746 effects
1747 .edited_calls
1748 .into_iter()
1749 .map(|(name, input)| json!({ "name": name, "input": input }))
1750 .collect(),
1751 ),
1752 );
1753 }
1754 let has_usage = !effects.usage_batch.records.is_empty()
1755 || !effects.usage_batch.drop_records.is_empty()
1756 || !effects.usage_batch.decisions.is_empty()
1757 || effects.usage_batch.dropped_records > 0;
1758 let mut metadata_value = Value::Object(meta);
1759 if has_usage {
1760 crate::cost_status::attach_child_usage_batch_metadata(
1761 &mut metadata_value,
1762 &effects.usage_batch,
1763 );
1764 }
1765 let metadata = metadata_value
1766 .as_object()
1767 .is_some_and(|obj| !obj.is_empty())
1768 .then_some(metadata_value);
1769 ToolResult {
1770 content,
1771 success,
1772 metadata,
1773 }
1774 }
1775
1776 /// Execute one `execute_tools` call: validate, run the program under its
1777 /// deadline, and return the bounded program value plus the host-owned
1778 /// receipt. A script failure or a deadline is a `success: false` payload
1779 /// that still lists every nested call — only VM setup failures are `Err`.
1780 pub async fn execute_tools_tool(
1781 input: &Value,
1782 registry: &ToolRegistry,
1783 context: &ToolContext,
1784 ) -> Result<ToolResult, ToolError> {
1785 if context.execution.nested_call_gate.is_none()
1786 && context
1787 .execution
1788 .live_posture
1789 .as_ref()
1790 .is_some_and(|posture| posture.read().mode() == codewhale_config::AppMode::Plan)
1791 {
1792 return Err(ToolError::permission_denied(
1793 "execute_tools in Plan mode requires the session tool gate.",
1794 ));
1795 }
1796 let (code, args) = match input.get("batch").filter(|value| !value.is_null()) {
1797 Some(batch) => {
1798 if input.get("code").is_some_and(|v| !v.is_null())
1799 || !batch.get("tool").is_some_and(Value::is_string)
1800 || !batch.get("arguments").is_some_and(Value::is_object)
1801 || batch.to_string().len() > MAX_CODE_BYTES
1802 {
1803 return Err(ToolError::invalid_input(
1804 "Supply either code or a bounded batch with tool and arguments.",
1805 ));
1806 }
1807 if context.execution.nested_call_gate.is_none() {
1808 return Err(ToolError::permission_denied(
1809 "A named batch requires the session tool gate.",
1810 ));
1811 }
1812 (
1813 "return await tools.call(args.tool, args.arguments);",
1814 batch.clone(),
1815 )
1816 }
1817 None => (required_str(input, "code")?, Value::Null),
1818 };
1819 if code.trim().is_empty() {
1820 return Err(ToolError::missing_field("code"));
1821 }
1822 if code.len() > MAX_CODE_BYTES {
1823 return Err(ToolError::invalid_input(format!(
1824 "code exceeds {MAX_CODE_BYTES} bytes"
1825 )));
1826 }
1827 let invoker = Arc::new(CodemodeInvoker::new(registry.all(), context.clone()));
1828 let driver = Arc::new(CodemodeDriver::default());
1829 let deadline = invoker.deadline();
1830 let cancel = WorkflowRunCancel::new();
1831 let vm = WorkflowVm::new();
1832 let mut run =
1833 Box::pin(vm.run_tools_script(code, args, driver.clone(), invoker.clone(), cancel.clone()));
1834 let watchdog = async {
1835 loop {
1836 let Some(remaining) = invoker.remaining(deadline) else {
1837 return Err(format!(
1838 "its {}s run deadline (time waiting on approvals is not counted)",
1839 deadline.as_secs()
1840 ));
1841 };
1842 tokio::select! {
1843 result = &mut run => return Ok(result),
1844 () = tokio::time::sleep(remaining) => {}
1845 }
1846 }
1847 };
1848 let outcome = match context.child_host.as_ref() {
1849 Some(child) => child
1850 .run_tool_bounded(async { Ok::<_, ToolError>(watchdog.await) })
1851 .await
1852 .unwrap_or_else(|_| {
1853 Err("the sub-agent's tool timeout (time waiting on approvals is not counted) or work deadline".to_string())
1854 }),
1855 None => watchdog.await,
1856 };
1857 let program_result = match outcome {
1858 Err(stopped_at) => {
1859 // Stop the VM (and with it every in-flight nested call) before
1860 // reading the receipt, so the listed state is final.
1861 cancel.cancel();
1862 drop(run);
1863 return Ok(receipt_payload(
1864 false,
1865 json!({
1866 "error": format!(
1867 "execute_tools stopped at {stopped_at}. Calls with status ok/failed/refused finished; calls still in_flight were cancelled and may have partially run."
1868 ),
1869 "timed_out": true,
1870 }),
1871 &invoker,
1872 &driver,
1873 ));
1874 }
1875 Ok(Err(err)) => {
1876 let spill_id = format!("{}-error", invoker.spill_prefix);
1877 let (bounded, truncated) = bound_text(
1878 err.to_string(),
1879 RETURN_CAP_BYTES,
1880 &spill_id,
1881 &invoker.context.state_namespace,
1882 );
1883 if truncated
1884 .as_ref()
1885 .is_some_and(|trunc| trunc.retrieve_ref.is_some())
1886 {
1887 invoker.mark_evidence_available();
1888 }
1889 let mut body = json!({ "error": bounded });
1890 if let Some(truncated) = truncated {
1891 body["error_truncated"] = json!(truncated);
1892 }
1893 return Ok(receipt_payload(false, body, &invoker, &driver));
1894 }
1895 Ok(Ok(value)) => value,
1896 };
1897 let spill_id = format!("{}-return", invoker.spill_prefix);
1898 let (bounded, truncated) = bound_json(
1899 program_result,
1900 RETURN_CAP_BYTES,
1901 &spill_id,
1902 &invoker.context.state_namespace,
1903 );
1904 if truncated
1905 .as_ref()
1906 .is_some_and(|trunc| trunc.retrieve_ref.is_some())
1907 {
1908 invoker.mark_evidence_available();
1909 }
1910 Ok(receipt_payload(
1911 true,
1912 json!({ "return": bounded, "return_truncated": truncated }),
1913 &invoker,
1914 &driver,
1915 ))
1916 }
1917
1918 #[cfg(test)]
1919 mod tests {
1920 use super::*;
1921
1922 #[test]
1923 fn catalog_advertises_execute_tools_deferred_in_direct_mode() {
1924 use codewhale_config::AppMode;
1925 use std::collections::HashSet;
1926 let empty = HashSet::new();
1927 let mut catalog = Vec::new();
1928 crate::core::engine::tool_catalog::ensure_advanced_tooling(
1929 &mut catalog,
1930 AppMode::Agent,
1931 &empty,
1932 ToolMode::Direct,
1933 );
1934 let tool = catalog
1935 .iter()
1936 .find(|tool| tool.name == EXECUTE_TOOLS_TOOL_NAME)
1937 .unwrap_or_else(|| panic!("{:?} catalog must advertise execute_tools", AppMode::Agent));
1938 assert_eq!(
1939 tool.defer_loading,
1940 Some(true),
1941 "{:?} must defer it",
1942 AppMode::Agent
1943 );
1944 let mut catalog = Vec::new();
1945 crate::core::engine::tool_catalog::ensure_advanced_tooling(
1946 &mut catalog,
1947 AppMode::Plan,
1948 &empty,
1949 ToolMode::Direct,
1950 );
1951 let plan_tool = catalog
1952 .iter()
1953 .find(|tool| tool.name == EXECUTE_TOOLS_TOOL_NAME)
1954 .expect("Plan catalog must advertise execute_tools");
1955 assert_eq!(plan_tool.defer_loading, Some(true));
1956 }
1957
1958 #[test]
1959 fn definition_is_deferred_direct_only() {
1960 let tool = execute_tools_tool_definition();
1961 assert_eq!(tool.name, EXECUTE_TOOLS_TOOL_NAME);
1962 assert_eq!(tool.tool_type.as_deref(), Some(EXECUTE_TOOLS_TOOL_TYPE));
1963 assert!(tool.description.contains("tools.call"));
1964 assert!(tool.description.contains("tools.list"));
1965 assert!(tool.description.contains("tools.search"));
1966 assert!(tool.description.contains("tools.describe"));
1967 // Catalog decides deferral; the name is absent from the eager set,
1968 // so injection marks it deferred like the interpreter tools.
1969 assert!(
1970 !crate::core::engine::tool_catalog::DEFAULT_ACTIVE_NATIVE_TOOLS
1971 .contains(&tool.name.as_str())
1972 );
1973 assert_eq!(tool.allowed_callers, Some(vec!["direct".to_string()]));
1974 }
1975
1976 #[test]
1977 fn bound_json_keeps_small_values_verbatim() {
1978 let (value, truncated) = bound_json(json!({"a": 1}), 1024, "bound-small", "");
1979 assert!(truncated.is_none());
1980 assert_eq!(value, json!({"a": 1}));
1981 }
1982
1983 #[test]
1984 fn bound_json_cuts_escape_heavy_strings_by_encoded_size() {
1985 let _guard = crate::tools::truncate::TEST_SPILLOVER_GUARD
1986 .lock()
1987 .unwrap_or_else(|err| err.into_inner());
1988 let spill_root = tempfile::tempdir().unwrap();
1989 let previous =
1990 crate::tools::truncate::set_test_spillover_root(Some(spill_root.path().to_path_buf()));
1991 let (value, truncated) = bound_json(
1992 json!("line\n".repeat(3000)),
1993 16 * 1024,
1994 "bound-escaped",
1995 "session-bound",
1996 );
1997 crate::tools::truncate::set_test_spillover_root(previous);
1998 assert!(truncated.is_some(), "escape-heavy string is reported cut");
1999 assert!(value.to_string().len() <= 16 * 1024);
2000 }
2001
2002 #[test]
2003 fn bound_json_names_what_it_cut() {
2004 let _guard = crate::tools::truncate::TEST_SPILLOVER_GUARD
2005 .lock()
2006 .unwrap_or_else(|err| err.into_inner());
2007 let spill_root = tempfile::tempdir().unwrap();
2008 let previous =
2009 crate::tools::truncate::set_test_spillover_root(Some(spill_root.path().to_path_buf()));
2010 let big = "x".repeat(100);
2011 let (value, truncated) = bound_json(
2012 json!({ "id": 7, "blob": big }),
2013 64,
2014 "bound-big",
2015 "session-bound",
2016 );
2017 crate::tools::truncate::set_test_spillover_root(previous);
2018 let truncated = truncated.expect("oversized value is reported");
2019 assert_eq!(truncated.original_bytes, 118);
2020 assert_eq!(value["id"], 7, "a cut JSON value stays parsed: {value}");
2021 assert!(
2022 value["blob"]
2023 .as_str()
2024 .is_some_and(|blob| blob.starts_with("xx"))
2025 );
2026 assert_eq!(truncated.kept_bytes, value.to_string().len());
2027 assert!(truncated.kept_bytes <= 32);
2028 assert_eq!(truncated.retrieve_ref.as_deref(), Some("bound-big"));
2029 let saved = truncated.spill_path.expect("full value saved");
2030 assert_eq!(std::fs::read_to_string(saved).unwrap().len(), 118);
2031
2032 let (kept_after_big_key, omitted) =
2033 crate::tools::truncate::shrink_json(json!({"k".repeat(9_000): 1, "z": 2}), 64);
2034 assert_eq!(kept_after_big_key, json!({"z": 2}));
2035 assert_eq!(omitted, 1);
2036 }
2037
2038 use crate::core::engine::tool_catalog::ToolMode;
2039 use crate::tools::file_tool::{ReadTool, WriteTool};
2040 use crate::tools::registry::ToolRegistryBuilder;
2041
2042 fn workspace_with_note() -> (tempfile::TempDir, std::path::PathBuf) {
2043 let dir = tempfile::tempdir().unwrap();
2044 let note = dir.path().join("note.txt");
2045 std::fs::write(&note, "alpha\nbeta\n").unwrap();
2046 (dir, note)
2047 }
2048
2049 #[tokio::test]
2050 async fn nested_read_passes_gates_and_records_receipt() {
2051 let (_dir, note) = workspace_with_note();
2052 let context = ToolContext::new(note.parent().unwrap());
2053 let invoker = CodemodeInvoker::new(vec![Arc::new(ReadTool)], context);
2054 let response = invoker
2055 .invoke(ToolCallRequest {
2056 tool: "read".to_string(),
2057 input: json!({ "path": note.to_string_lossy() }),
2058 })
2059 .await
2060 .unwrap();
2061 assert!(response.ok);
2062 assert!(response.result.to_string().contains("alpha"));
2063 let receipts = invoker.drain();
2064 assert_eq!(receipts.len(), 1);
2065 assert_eq!(receipts[0].tool, "read");
2066 assert!(receipts[0].ok);
2067 }
2068
2069 #[tokio::test]
2070 async fn nested_write_is_refused_and_writes_nothing() {
2071 let (_dir, note) = workspace_with_note();
2072 let target = note.parent().unwrap().join("evil.txt");
2073 let context = ToolContext::new(note.parent().unwrap());
2074 let invoker = CodemodeInvoker::new(vec![Arc::new(WriteTool)], context);
2075 let err = invoker
2076 .invoke(ToolCallRequest {
2077 tool: "write".to_string(),
2078 input: json!({ "path": target.to_string_lossy(), "content": "x" }),
2079 })
2080 .await
2081 .unwrap_err();
2082 assert!(
2083 matches!(&err, DriverError::Rejected(message) if message.contains("read-only")),
2084 "unexpected: {err:?}"
2085 );
2086 assert!(!target.exists());
2087 assert_eq!(invoker.drain().len(), 1);
2088 }
2089
2090 #[tokio::test]
2091 async fn prohibited_nested_names_are_refused() {
2092 let dir = tempfile::tempdir().unwrap();
2093 let context = ToolContext::new(dir.path());
2094 let invoker = CodemodeInvoker::new(vec![], context);
2095 for name in ["agent", "workflow", "rlm", "execute_tools", "nope"] {
2096 let err = invoker
2097 .invoke(ToolCallRequest {
2098 tool: name.to_string(),
2099 input: json!({}),
2100 })
2101 .await
2102 .unwrap_err();
2103 assert!(matches!(err, DriverError::Rejected(_)), "{name}: {err:?}");
2104 }
2105 }
2106
2107 #[tokio::test]
2108 async fn ungated_program_discovers_and_resolves_read_only_tools() {
2109 let (_dir, note) = workspace_with_note();
2110 let context = ToolContext::new(note.parent().unwrap());
2111 let registry = ToolRegistryBuilder::new()
2112 .with_tool(Arc::new(ReadTool))
2113 .with_tool(Arc::new(WriteTool))
2114 .with_tool(Arc::new(crate::tools::search::GrepFilesTool))
2115 .build(context.clone());
2116 let code = "const listed = (await tools.list()).map((tool) => tool.name); \
2117 const found = await tools.grep.files({ pattern: 'alpha' }); \
2118 let missing = ''; \
2119 try { await tools.grep.filez({}); } catch (err) { missing = err.message; } \
2120 return { listed, ran: JSON.stringify(found).includes('alpha'), missing };";
2121 let result = execute_tools_tool(&json!({ "code": code }), &registry, &context)
2122 .await
2123 .unwrap();
2124 let body: Value = serde_json::from_str(&result.content).unwrap();
2125 let returned = &body["body"]["return"];
2126 assert_eq!(returned["listed"], json!(["grep_files", "read"]), "{body}");
2127 assert_eq!(returned["ran"], true, "{body}");
2128 assert!(
2129 returned["missing"]
2130 .as_str()
2131 .is_some_and(|message| message.contains("grep_files(")),
2132 "{body}"
2133 );
2134 let dispatched = body["calls"]
2135 .as_array()
2136 .unwrap()
2137 .iter()
2138 .map(|call| call["tool"].as_str().unwrap())
2139 .collect::<Vec<_>>();
2140 assert_eq!(
2141 dispatched,
2142 ["tool_search", "tool_search", "grep_files", "tool_search"]
2143 );
2144 }
2145
2146 #[tokio::test]
2147 async fn program_composes_nested_read_and_returns_receipt() {
2148 let (_dir, note) = workspace_with_note();
2149 let workspace = note.parent().unwrap().to_path_buf();
2150 let context = ToolContext::new(workspace.clone());
2151 let registry = ToolRegistryBuilder::new()
2152 .with_tool(Arc::new(ReadTool))
2153 .build(context.clone());
2154 let path = note.to_string_lossy().replace('\\', "\\\\");
2155 let code = format!(
2156 "const r = await tools.call('read', {{ path: '{path}' }}); return {{ hasAlpha: JSON.stringify(r).includes('alpha') }};"
2157 );
2158 let result = execute_tools_tool(&json!({ "code": code }), &registry, &context)
2159 .await
2160 .unwrap();
2161 assert!(result.success, "{}", result.content);
2162 let body: Value = serde_json::from_str(&result.content).unwrap();
2163 assert_eq!(body["calls"].as_array().unwrap().len(), 1);
2164 assert_eq!(body["body"]["return"]["hasAlpha"], true);
2165 }
2166
2167 #[tokio::test]
2168 async fn program_loads_skills_at_runtime_through_load_skill() {
2169 // Skills-as-tools composes with code mode: `load_skill` is
2170 // read-only and auto-approved, so a program can list and load
2171 // skills at runtime without widening its authority.
2172 // A configured skills dir, not a project root: project skills load
2173 // only in a trusted workspace, which this composition test is not
2174 // about.
2175 let dir = tempfile::tempdir().unwrap();
2176 let workspace = dir.path().join("workspace");
2177 std::fs::create_dir_all(&workspace).unwrap();
2178 let skills_root = dir.path().join("configured-skills");
2179 let skill_dir = skills_root.join("greet");
2180 std::fs::create_dir_all(&skill_dir).unwrap();
2181 std::fs::write(
2182 skill_dir.join("SKILL.md"),
2183 "---\nname: greet\ndescription: Say hello\n---\n# Greet\nSay hello warmly.\n",
2184 )
2185 .unwrap();
2186 let context =
2187 ToolContext::new(&workspace).with_skills_config(&skills_root, Default::default());
2188 let registry = ToolRegistryBuilder::new()
2189 .with_tool(Arc::new(crate::tools::skill::LoadSkillTool))
2190 .build(context.clone());
2191 let code = "const list = await tools.call('load_skill', { name: 'list' }); \
2192 const body = await tools.call('load_skill', { name: 'greet' }); \
2193 return { listed: JSON.stringify(list).includes('greet'), \
2194 loaded: JSON.stringify(body).includes('warmly') };";
2195 let result = execute_tools_tool(&json!({ "code": code }), &registry, &context)
2196 .await
2197 .unwrap();
2198 assert!(result.success, "{}", result.content);
2199 let body: Value = serde_json::from_str(&result.content).unwrap();
2200 assert_eq!(body["calls"].as_array().unwrap().len(), 2);
2201 assert_eq!(body["body"]["return"]["listed"], true);
2202 assert_eq!(body["body"]["return"]["loaded"], true);
2203 }
2204
2205 // --- Gated (engine-served) programs -----------------------------------
2206
2207 use std::sync::atomic::{AtomicUsize, Ordering};
2208
2209 /// A stand-in for the turn loop's gate: answers every nested call with
2210 /// `answer` after `delay`, counting how often it was asked.
2211 fn gated_context(
2212 workspace: &std::path::Path,
2213 deadline: Duration,
2214 delay: Duration,
2215 mcp_pool: Option<Arc<AsyncMutex<McpPool>>>,
2216 answer: impl Fn(&str, &Value) -> NestedCallVerdict + Send + Sync + 'static,
2217 ) -> (ToolContext, Arc<AtomicUsize>) {
2218 let (tx_event, mut rx_event) = mpsc::channel(64);
2219 tokio::spawn(async move { while rx_event.recv().await.is_some() {} });
2220 let (gate, mut requests) = NestedCallGate::new(mcp_pool, tx_event, deadline);
2221 let asked = Arc::new(AtomicUsize::new(0));
2222 let counter = asked.clone();
2223 tokio::spawn(async move {
2224 while let Some(request) = requests.recv().await {
2225 let request = match request {
2226 NestedCallRequest::Tool(request) => request,
2227 NestedCallRequest::UserQuestion { reply, .. } => {
2228 let _ = reply.send(Err(ToolError::not_available(
2229 "fixture has no user question backend",
2230 )));
2231 continue;
2232 }
2233 NestedCallRequest::Checkpoint { reply, .. } => {
2234 let _ = reply.send(Err(ToolError::not_available(
2235 "fixture has no session checkpoint backend",
2236 )));
2237 continue;
2238 }
2239 };
2240 counter.fetch_add(1, Ordering::SeqCst);
2241 tokio::time::sleep(delay).await;
2242 let verdict = answer(&request.name, &request.input);
2243 let _ = request.reply.send(verdict);
2244 }
2245 });
2246 let mut context = ToolContext::new(workspace);
2247 context.execution.nested_call_gate = Some(gate);
2248 (context, asked)
2249 }
2250
2251 fn run_as_asked(name: &str, input: &Value) -> NestedCallVerdict {
2252 NestedCallVerdict::Run {
2253 name: name.to_string(),
2254 input: input.clone(),
2255 supports_parallel: true,
2256 decision: NestedDecision::Auto,
2257 hook_context: None,
2258 }
2259 }
2260
2261 fn body(result: &ToolResult) -> Value {
2262 serde_json::from_str(&result.content).expect("receipt is JSON")
2263 }
2264
2265 /// A tool that takes longer than any test deadline.
2266 struct SlowTool;
2267
2268 #[async_trait]
2269 impl ToolSpec for SlowTool {
2270 fn name(&self) -> &str {
2271 "slow"
2272 }
2273 fn description(&self) -> &str {
2274 "sleeps"
2275 }
2276 fn input_schema(&self) -> Value {
2277 json!({"type": "object"})
2278 }
2279 fn capabilities(&self) -> Vec<crate::tools::spec::ToolCapability> {
2280 vec![crate::tools::spec::ToolCapability::ReadOnly]
2281 }
2282 async fn execute(
2283 &self,
2284 _input: Value,
2285 _context: &ToolContext,
2286 ) -> Result<ToolResult, ToolError> {
2287 tokio::time::sleep(Duration::from_secs(30)).await;
2288 Ok(ToolResult::success("late"))
2289 }
2290 }
2291
2292 /// A tool whose output is larger than the nested result cap.
2293 struct HugeTool;
2294
2295 #[async_trait]
2296 impl ToolSpec for HugeTool {
2297 fn name(&self) -> &str {
2298 "huge"
2299 }
2300 fn description(&self) -> &str {
2301 "big output"
2302 }
2303 fn input_schema(&self) -> Value {
2304 json!({"type": "object"})
2305 }
2306 fn capabilities(&self) -> Vec<crate::tools::spec::ToolCapability> {
2307 vec![crate::tools::spec::ToolCapability::ReadOnly]
2308 }
2309 async fn execute(
2310 &self,
2311 input: Value,
2312 _context: &ToolContext,
2313 ) -> Result<ToolResult, ToolError> {
2314 let text = "y".repeat(PER_CALL_RESULT_CAP_BYTES * 2);
2315 if input.get("fail").and_then(Value::as_bool) == Some(true) {
2316 return Ok(ToolResult::error(text));
2317 }
2318 Ok(ToolResult::success(text))
2319 }
2320 }
2321
2322 #[tokio::test]
2323 async fn gated_nested_mcp_call_runs_through_the_session_pool() {
2324 let dir = tempfile::tempdir().unwrap();
2325 let pool = Arc::new(AsyncMutex::new(McpPool::new(
2326 codewhale_mcp::config::McpConfig::default(),
2327 )));
2328 let (context, asked) = gated_context(
2329 dir.path(),
2330 Duration::from_secs(30),
2331 Duration::ZERO,
2332 Some(pool),
2333 run_as_asked,
2334 );
2335 let registry = ToolRegistryBuilder::new().build(context.clone());
2336 let code = "const r = await tools.call('list_mcp_resources', {}); \
2337 return { hasContent: r.content !== undefined, truncated: r.truncated };";
2338 let result = execute_tools_tool(&json!({ "code": code }), &registry, &context)
2339 .await
2340 .unwrap();
2341 assert!(result.success, "{}", result.content);
2342 let body = body(&result);
2343 assert_eq!(body["body"]["return"]["hasContent"], true);
2344 assert_eq!(body["body"]["return"]["truncated"], Value::Null);
2345 assert_eq!(body["calls"][0]["tool"], "list_mcp_resources");
2346 assert_eq!(body["calls"][0]["decision"], "auto");
2347 assert_eq!(body["calls"][0]["status"], "ok");
2348 assert_eq!(
2349 asked.load(Ordering::SeqCst),
2350 1,
2351 "the MCP call went through the gate"
2352 );
2353 }
2354
2355 #[tokio::test]
2356 async fn gated_denial_fails_only_that_nested_call() {
2357 let (_dir, note) = workspace_with_note();
2358 let workspace = note.parent().unwrap().to_path_buf();
2359 let target = workspace.join("denied.txt");
2360 let (context, _asked) = gated_context(
2361 &workspace,
2362 Duration::from_secs(30),
2363 Duration::ZERO,
2364 None,
2365 |name, input| {
2366 if name == "write" {
2367 NestedCallVerdict::Refused {
2368 error: ToolError::permission_denied("Tool 'write' denied by user"),
2369 decision: NestedDecision::Denied,
2370 }
2371 } else {
2372 run_as_asked(name, input)
2373 }
2374 },
2375 );
2376 let registry = ToolRegistryBuilder::new()
2377 .with_tool(Arc::new(ReadTool))
2378 .with_tool(Arc::new(WriteTool))
2379 .build(context.clone());
2380 let note_path = note.to_string_lossy().replace('\\', "\\\\");
2381 let target_path = target.to_string_lossy().replace('\\', "\\\\");
2382 let code = format!(
2383 "let denied = null; \
2384 try {{ await tools.call('write', {{ path: '{target_path}', content: 'x' }}); }} \
2385 catch (e) {{ denied = String(e.message || e); }} \
2386 const r = await tools.call('read', {{ path: '{note_path}' }}); \
2387 return {{ denied, read: JSON.stringify(r).includes('alpha') }};"
2388 );
2389 let result = execute_tools_tool(&json!({ "code": code }), &registry, &context)
2390 .await
2391 .unwrap();
2392 assert!(result.success, "{}", result.content);
2393 let body = body(&result);
2394 assert!(
2395 body["body"]["return"]["denied"]
2396 .as_str()
2397 .is_some_and(|message| message.contains("denied by user")),
2398 "{body}"
2399 );
2400 assert_eq!(body["body"]["return"]["read"], true);
2401 assert_eq!(body["calls"][0]["decision"], "denied");
2402 assert_eq!(body["calls"][0]["status"], "refused");
2403 assert_eq!(body["calls"][1]["status"], "ok");
2404 assert!(!target.exists(), "a denied write never runs");
2405 }
2406
2407 #[tokio::test]
2408 async fn computer_use_consent_is_refused_inside_a_program_before_the_gate() {
2409 let dir = tempfile::tempdir().unwrap();
2410 let (context, asked) = gated_context(
2411 dir.path(),
2412 Duration::from_secs(30),
2413 Duration::ZERO,
2414 None,
2415 run_as_asked,
2416 );
2417 let invoker = CodemodeInvoker::new(Vec::new(), context);
2418 for (name, input) in [
2419 (
2420 "mcp_plugin-12-computer-use-computer_consent",
2421 json!({"action": "allow", "app": "Safari", "bundle_id": "com.apple.Safari"}),
2422 ),
2423 (
2424 "mcp_plugin-12-computer-use-computer_app_script",
2425 json!({"script": "do shell script \"id\""}),
2426 ),
2427 ("mcp_github_authenticate", json!({})),
2428 ("exec_shell", json!({"command": "ls", "interactive": true})),
2429 ("request_user_input", json!({})),
2430 // Dispatch resolves names case-insensitively, so the refusals do.
2431 ("Agent", json!({})),
2432 ("WORKFLOW", json!({})),
2433 ("Execute_Tools", json!({"code": "return 1;"})),
2434 ("BASH", json!({"command": "ls", "interactive": true})),
2435 ("Exec_Shell", json!({"command": "ls", "interactive": true})),
2436 ] {
2437 let err = invoker
2438 .invoke(ToolCallRequest {
2439 tool: name.to_string(),
2440 input,
2441 })
2442 .await
2443 .unwrap_err();
2444 assert!(matches!(err, DriverError::Rejected(_)), "{name}: {err:?}");
2445 }
2446 assert_eq!(asked.load(Ordering::SeqCst), 0, "nothing reached the gate");
2447 assert!(
2448 invoker
2449 .drain()
2450 .iter()
2451 .all(|receipt| receipt.status == CallStatus::Refused)
2452 );
2453 }
2454
2455 #[tokio::test]
2456 async fn deadline_keeps_finished_receipts_and_names_in_flight_calls() {
2457 let (_dir, note) = workspace_with_note();
2458 let workspace = note.parent().unwrap().to_path_buf();
2459 let (context, _asked) = gated_context(
2460 &workspace,
2461 Duration::from_millis(2000),
2462 Duration::ZERO,
2463 None,
2464 run_as_asked,
2465 );
2466 let registry = ToolRegistryBuilder::new()
2467 .with_tool(Arc::new(ReadTool))
2468 .with_tool(Arc::new(SlowTool))
2469 .build(context.clone());
2470 let note_path = note.to_string_lossy().replace('\\', "\\\\");
2471 let code = format!(
2472 "await tools.call('read', {{ path: '{note_path}' }}); \
2473 await tools.call('slow', {{}}); return 'unreachable';"
2474 );
2475 let result = tokio::time::timeout(
2476 Duration::from_secs(10),
2477 execute_tools_tool(&json!({ "code": code }), &registry, &context),
2478 )
2479 .await
2480 .expect("the run deadline ends the program")
2481 .expect("a deadline is a receipt, not a host error");
2482 assert!(!result.success);
2483 let body = body(&result);
2484 assert_eq!(body["body"]["timed_out"], true, "{body}");
2485 assert_eq!(body["calls"].as_array().unwrap().len(), 2);
2486 assert_eq!(body["calls"][0]["tool"], "read");
2487 assert_eq!(body["calls"][0]["status"], "ok");
2488 assert_eq!(body["calls"][1]["tool"], "slow");
2489 assert_eq!(body["calls"][1]["status"], "in_flight");
2490 }
2491
2492 #[tokio::test]
2493 async fn time_waiting_on_the_gate_does_not_spend_the_deadline() {
2494 let (_dir, note) = workspace_with_note();
2495 let workspace = note.parent().unwrap().to_path_buf();
2496 // Each gate answer takes longer than the whole run deadline, as a
2497 // person deciding an approval would.
2498 let (context, _asked) = gated_context(
2499 &workspace,
2500 Duration::from_secs(6),
2501 Duration::from_secs(7),
2502 None,
2503 run_as_asked,
2504 );
2505 let registry = ToolRegistryBuilder::new()
2506 .with_tool(Arc::new(ReadTool))
2507 .build(context.clone());
2508 let note_path = note.to_string_lossy().replace('\\', "\\\\");
2509 let code = format!(
2510 "const a = await tools.call('read', {{ path: '{note_path}' }}); \
2511 const b = await tools.call('read', {{ path: '{note_path}' }}); \
2512 return JSON.stringify([a, b]).includes('alpha');"
2513 );
2514 let result = execute_tools_tool(&json!({ "code": code }), &registry, &context)
2515 .await
2516 .unwrap();
2517 assert!(result.success, "{}", result.content);
2518 assert_eq!(body(&result)["body"]["return"], true);
2519 }
2520
2521 #[test]
2522 fn watchdog_rechecks_promptly_while_paused_on_the_gate() {
2523 let dir = tempfile::tempdir().unwrap();
2524 let invoker = CodemodeInvoker::new(Vec::new(), ToolContext::new(dir.path()));
2525 let deadline = Duration::from_secs(600);
2526 let paused = invoker.pause();
2527 // A paused program never times out, but the watchdog must not sleep
2528 // out the whole deadline or the run would overrun by that much once
2529 // the gate answers.
2530 assert_eq!(invoker.remaining(deadline), Some(PAUSED_WATCHDOG_POLL));
2531 drop(paused);
2532 assert!(
2533 invoker
2534 .remaining(deadline)
2535 .is_some_and(|left| left > PAUSED_WATCHDOG_POLL)
2536 );
2537 }
2538
2539 // This test deliberately serializes access to process-global spillover
2540 // state while awaiting the program.
2541 #[allow(clippy::await_holding_lock)]
2542 #[tokio::test]
2543 async fn oversized_nested_result_keeps_its_envelope_and_says_what_was_cut() {
2544 let _guard = crate::tools::truncate::TEST_SPILLOVER_GUARD
2545 .lock()
2546 .unwrap_or_else(|err| err.into_inner());
2547 let spill_root = tempfile::tempdir().unwrap();
2548 let previous =
2549 crate::tools::truncate::set_test_spillover_root(Some(spill_root.path().to_path_buf()));
2550 let dir = tempfile::tempdir().unwrap();
2551 let (context, _asked) = gated_context(
2552 dir.path(),
2553 Duration::from_secs(30),
2554 Duration::ZERO,
2555 None,
2556 run_as_asked,
2557 );
2558 let registry = ToolRegistryBuilder::new()
2559 .with_tool(Arc::new(HugeTool))
2560 .build(context.clone());
2561 let code = "const r = await tools.call('huge', {}); \
2562 let failed = null; \
2563 try { await tools.call('huge', { fail: true }); } \
2564 catch (e) { failed = String(e.message || e).length; } \
2565 return { keys: Object.keys(r).sort(), cut: r.truncated, \
2566 head: r.content.length, kind: typeof r.content, failed };";
2567 let result = execute_tools_tool(&json!({ "code": code }), &registry, &context)
2568 .await
2569 .unwrap();
2570 crate::tools::truncate::set_test_spillover_root(previous);
2571 assert!(result.success, "{}", result.content);
2572 let body = body(&result);
2573 let returned = &body["body"]["return"];
2574 assert_eq!(
2575 returned["keys"],
2576 json!(["content", "metadata", "truncated"])
2577 );
2578 assert!(
2579 returned["cut"]["original_bytes"].as_u64().unwrap() > PER_CALL_RESULT_CAP_BYTES as u64
2580 );
2581 assert_eq!(returned["head"], json!(PER_CALL_RESULT_CAP_BYTES / 2));
2582 assert_eq!(returned["kind"], "string", "a cut result is its raw head");
2583 assert!(returned["cut"]["spill_path"].as_str().is_some(), "{body}");
2584 assert!(body["calls"][0]["truncated"]["original_bytes"].is_u64());
2585 // A failed call's text is bounded and spilled the same way.
2586 assert_eq!(returned["failed"], json!(PER_CALL_RESULT_CAP_BYTES / 2));
2587 assert_eq!(body["calls"][1]["status"], "failed");
2588 assert!(
2589 body["calls"][1]["truncated"]["original_bytes"]
2590 .as_u64()
2591 .unwrap()
2592 >= (PER_CALL_RESULT_CAP_BYTES * 2) as u64
2593 );
2594 assert!(
2595 body["calls"][1]["truncated"]["spill_path"]
2596 .as_str()
2597 .is_some(),
2598 "{body}"
2599 );
2600 }
2601
2602 #[tokio::test]
2603 async fn console_methods_populate_receipt_log_and_respect_caps() {
2604 let dir = tempfile::tempdir().unwrap();
2605 let context = ToolContext::new(dir.path());
2606 let registry = ToolRegistryBuilder::new().build(context.clone());
2607
2608 let code = r#"
2609 console.log("hello", { n: 1 });
2610 console.info("step");
2611 console.warn("careful");
2612 console.error("problem");
2613 console.debug("detail");
2614 return "ok";
2615 "#;
2616 let result = execute_tools_tool(&json!({ "code": code }), &registry, &context)
2617 .await
2618 .unwrap();
2619 assert!(result.success, "{}", result.content);
2620 let parsed = body(&result);
2621 assert_eq!(parsed["body"]["return"], "ok");
2622 assert_eq!(
2623 parsed["log"],
2624 json!([
2625 r#"hello {"n":1}"#,
2626 "[info] step",
2627 "[warn] careful",
2628 "[error] problem",
2629 "[debug] detail",
2630 ])
2631 );
2632
2633 let spam_code = format!(
2634 "for (let i = 0; i < {}; i++) console.log('line-' + i); return true;",
2635 MAX_LOG_LINES + 25
2636 );
2637 let spam_result = execute_tools_tool(&json!({ "code": spam_code }), &registry, &context)
2638 .await
2639 .unwrap();
2640 assert!(spam_result.success, "{}", spam_result.content);
2641 let spam_logs = body(&spam_result)["log"].as_array().unwrap().clone();
2642 assert_eq!(spam_logs.len(), MAX_LOG_LINES + 1);
2643 assert_eq!(spam_logs[0], "line-0");
2644 assert_eq!(spam_logs[MAX_LOG_LINES], "... (25 log entries omitted)");
2645
2646 let huge_line_code = format!(
2647 "for (let i = 0; i < 20; i++) console.log('x'.repeat({})); return true;",
2648 MAX_LOG_LINE_BYTES + 500
2649 );
2650 let huge_result =
2651 execute_tools_tool(&json!({ "code": huge_line_code }), &registry, &context)
2652 .await
2653 .unwrap();
2654 assert!(huge_result.success, "{}", huge_result.content);
2655 let huge_logs = body(&huge_result)["log"].as_array().unwrap().clone();
2656 assert_eq!(
2657 huge_logs.len(),
2658 (MAX_LOG_TOTAL_BYTES / MAX_LOG_LINE_BYTES) + 1
2659 );
2660 assert_eq!(huge_logs[0].as_str().unwrap().len(), MAX_LOG_LINE_BYTES);
2661 assert!(huge_logs[0].as_str().unwrap().ends_with("..."));
2662 assert!(
2663 huge_logs
2664 .last()
2665 .and_then(Value::as_str)
2666 .is_some_and(|line| line.contains("log entries omitted")),
2667 "{huge_logs:?}"
2668 );
2669 }
2670
2671 #[tokio::test]
2672 async fn url_and_search_params_work_inside_execute_tools() {
2673 let dir = tempfile::tempdir().unwrap();
2674 let context = ToolContext::new(dir.path());
2675 let registry = ToolRegistryBuilder::new().build(context.clone());
2676
2677 let code = r#"
2678 const u = new URL("https://example.com:8443/a/b?b=1&k=v1#frag");
2679 u.searchParams.set("b", "2");
2680 u.searchParams.append("k", "v2");
2681 const p = new URLSearchParams("x=1&y=two+words");
2682 p.delete("x");
2683 return {
2684 protocol: u.protocol,
2685 hostname: u.hostname,
2686 host: u.host,
2687 port: u.port,
2688 pathname: u.pathname,
2689 search: u.search,
2690 hash: u.hash,
2691 origin: u.origin,
2692 href: u.href,
2693 kAll: u.searchParams.getAll("k"),
2694 pStr: p.toString(),
2695 pY: p.get("y"),
2696 };
2697 "#;
2698 let result = execute_tools_tool(&json!({ "code": code }), &registry, &context)
2699 .await
2700 .unwrap();
2701 assert!(result.success, "{}", result.content);
2702 assert_eq!(
2703 body(&result)["body"]["return"],
2704 json!({
2705 "protocol": "https:",
2706 "hostname": "example.com",
2707 "host": "example.com:8443",
2708 "port": "8443",
2709 "pathname": "/a/b",
2710 "search": "?b=2&k=v1&k=v2",
2711 "hash": "#frag",
2712 "origin": "https://example.com:8443",
2713 "href": "https://example.com:8443/a/b?b=2&k=v1&k=v2#frag",
2714 "kAll": ["v1", "v2"],
2715 "pStr": "y=two+words",
2716 "pY": "two words",
2717 })
2718 );
2719 }
2720
2721 #[tokio::test]
2722 async fn determinism_errors_in_execute_tools_avoid_workflow_wording() {
2723 let dir = tempfile::tempdir().unwrap();
2724 let context = ToolContext::new(dir.path());
2725 let registry = ToolRegistryBuilder::new().build(context.clone());
2726
2727 for (code, needle) in [
2728 ("return Date.now();", "Date.now()"),
2729 ("return new Date();", "new Date()/Date()"),
2730 ("return Math.random();", "Math.random()"),
2731 ] {
2732 let result = execute_tools_tool(&json!({ "code": code }), &registry, &context)
2733 .await
2734 .unwrap();
2735 assert!(!result.success, "{}", result.content);
2736 let error = body(&result)["body"]["error"]
2737 .as_str()
2738 .unwrap_or_default()
2739 .to_string();
2740 assert!(error.contains(needle), "{error}");
2741 assert!(error.contains("execute_tools"), "{error}");
2742 assert!(
2743 !error.contains("Workflow") && !error.contains("record/replay"),
2744 "{error}"
2745 );
2746 }
2747 }
2748
2749 #[tokio::test]
2750 async fn rejected_promise_all_hints_all_settled_when_siblings_remain_in_flight() {
2751 struct SignaledSlowTool(Arc<tokio::sync::Notify>);
2752 #[async_trait]
2753 impl ToolSpec for SignaledSlowTool {
2754 fn name(&self) -> &str {
2755 "slow"
2756 }
2757 fn description(&self) -> &str {
2758 "signals start then sleeps"
2759 }
2760 fn input_schema(&self) -> Value {
2761 json!({"type": "object"})
2762 }
2763 fn capabilities(&self) -> Vec<crate::tools::spec::ToolCapability> {
2764 vec![crate::tools::spec::ToolCapability::ReadOnly]
2765 }
2766 async fn execute(
2767 &self,
2768 _input: Value,
2769 _context: &ToolContext,
2770 ) -> Result<ToolResult, ToolError> {
2771 self.0.notify_one();
2772 tokio::time::sleep(Duration::from_secs(30)).await;
2773 Ok(ToolResult::success("late"))
2774 }
2775 }
2776
2777 struct FailAfterStartTool(Arc<tokio::sync::Notify>);
2778 #[async_trait]
2779 impl ToolSpec for FailAfterStartTool {
2780 fn name(&self) -> &str {
2781 "fail_after_start"
2782 }
2783 fn description(&self) -> &str {
2784 "fails once slow is in flight"
2785 }
2786 fn input_schema(&self) -> Value {
2787 json!({"type": "object"})
2788 }
2789 fn capabilities(&self) -> Vec<crate::tools::spec::ToolCapability> {
2790 vec![crate::tools::spec::ToolCapability::ReadOnly]
2791 }
2792 async fn execute(
2793 &self,
2794 _input: Value,
2795 _context: &ToolContext,
2796 ) -> Result<ToolResult, ToolError> {
2797 self.0.notified().await;
2798 Ok(ToolResult::error("boom"))
2799 }
2800 }
2801
2802 let dir = tempfile::tempdir().unwrap();
2803 let started = Arc::new(tokio::sync::Notify::new());
2804 let context = ToolContext::new(dir.path());
2805 let registry = ToolRegistryBuilder::new()
2806 .with_tool(Arc::new(SignaledSlowTool(Arc::clone(&started))))
2807 .with_tool(Arc::new(FailAfterStartTool(started)))
2808 .build(context.clone());
2809
2810 let code = r#"
2811 return await Promise.all([
2812 tools.call("slow", {}),
2813 tools.call("fail_after_start", {}),
2814 ]);
2815 "#;
2816 let result = tokio::time::timeout(
2817 Duration::from_secs(5),
2818 execute_tools_tool(&json!({ "code": code }), &registry, &context),
2819 )
2820 .await
2821 .expect("Promise.all rejection must settle promptly")
2822 .expect("program rejection returns a receipt");
2823 assert!(!result.success, "{}", result.content);
2824 let parsed = body(&result);
2825 assert!(
2826 parsed["calls"]
2827 .as_array()
2828 .unwrap()
2829 .iter()
2830 .any(|call| call["tool"] == "slow" && call["status"] == "in_flight"),
2831 "{parsed}"
2832 );
2833 let hint = parsed["body"]["hint"].as_str().unwrap_or_default();
2834 assert!(hint.contains("Promise.allSettled"), "{parsed}");
2835 }
2836 }
2837
2837 lines RUST