Multiplayer agent harness for work.
Make execute the sole command launcher (#2205)
Regan Bella40bc8912f2b
diff --git a/docs/sandbox-resources.md b/docs/sandbox-resources.mdindex e3107d32b..b8ea63602 100644--- a/docs/sandbox-resources.md+++ b/docs/sandbox-resources.md@@ -2,33 +2,40 @@A sandbox is an independently recorded resource with an owning scope, provider, backing identity, and lifecycle state. Creating a sandbox provisions a blank machine without copying files or changing a default. Setting a default changes routing only. Background jobs retain the target on which they started.-Sandbox resources are always on. A single `sandbox` tool provides management, command execution, and process control. `list` returns the available providers and supported actions. Unsupported provider operations fail explicitly. Files publication is separate from sandbox management.+Sandbox resources are always on. The `sandbox` tool provides lifecycle management; `execute` is the sole command launcher and `background` controls existing processes. `list` returns the available providers and supported actions. Unsupported provider operations fail explicitly. Files publication is separate from sandbox management.-`sandbox` actions `exec` and `start_process` accept `sandbox_id`. Without a target, execution requires the scope's stored default. `set_default` accepts an ID or null; null clears the default. A new scope has no default. Retiring a sandbox requires clearing its default and stopping its jobs first. Retirement is available only for providers with direct scope deletion. It never provisions or restores a machine. Once retirement begins, execution stays blocked; interrupted or failed cleanup remains visible and can be retried. Retirement deletes its working state, so durable outputs should be published to Files or git beforehand.+`execute` accepts `sandbox_id` for both foreground and background commands. Without a target, execution requires the scope's stored default. `set_default` accepts an ID or null; null clears the default. A new scope has no default. Retiring a sandbox requires clearing its default and stopping its jobs first. Retirement is available only for providers with direct scope deletion. It never provisions or restores a machine. Once retirement begins, execution stays blocked; interrupted or failed cleanup remains visible and can be retried. Retirement deletes its working state, so durable outputs should be published to Files or git beforehand.In Isolated posture, agent inventory and operations stay in the current owning scope. In Open posture, authenticated human turns and owner-authorized scheduled turns can also target the acting person's personal sandboxes and Open shared sandboxes where they are a current member. Access is rechecked for each operation; changing conversations does not transfer ownership or grant other participants personal access. Cross-context execution uses the target's existing workspace without copying the calling conversation's credentials, files, or capability tokens onto it. Defaults remain local to their owning scope. Cross-context commands must satisfy both the calling conversation's and target sandbox's command policies. Network access is narrowed to satisfy both egress policies. Provider-native recovery status includes its own expiry; a sandbox record is not an indefinite backup guarantee.## Agent actions-| Action | Parameters |-| ------------------- | ----------------------------------------------------------------------------------------------------------- |-| `list` | `purpose`; returns providers, capabilities, resources and default |-| `create` | `backend`, optional `name`, `purpose`; creates a blank resource |-| `set_default` | `sandbox_id` or null, `purpose`; changes routing |-| `status`, `restart` | optional `sandbox_id`, `purpose` |-| `retire` | `sandbox_id`, `purpose` |-| `exec` | `command`, `purpose`, optional `sandbox_id`, `timeout_seconds`, and supported routing/credential parameters |-| `start_process` | `command`, `purpose`, optional `sandbox_id`, `timeout_seconds`; returns a process ID |-| `read_process` | `process_id`, optional `since_cursor`, `wait_seconds`, `max_bytes` |-| `write_stdin` | `process_id`, `data`; newline is not appended |-| `signal_process` | `process_id`, optional `signal` (`TERM`, `KILL`, `INT`, `HUP`, `QUIT`) |-| `list_processes` | lists jobs belonging to this scope |-| `watch_process` | `process_id`, optional `since_cursor`, `pattern`, `instructions`; returns a monitor ID |-| `unwatch_process` | `monitor_id` |--`start_process` requires a short `purpose` (about five words) describing the job. It is saved with the process and displayed instead of the command; the raw command remains available in expanded job output. Other process actions accept optional `purpose` for approval context. Unrelated fields are rejected rather than silently ignored. `exec` retains the enabled scoped, scratch, owner-auth and reached-room routing options and command credential handles. Process starts use the default or a named authorized resource; subsequent operations use the process ID's durable saved target, even after the scope default changes. Watches retain their durable monitor registration and wake this conversation with output or exit. Provider loss or expiry can still interrupt a process.--Execution and process handlers retain their existing approval and output-screening paths. Strict sandbox approvals are scoped to each action (`tool:sandbox:exec`, for example); an older broad `tool:sandbox` grant does not authorize newly exposed command or process actions. Transcript entries identify the actual `sandbox` action. Files publication, application deployment, and file read/write remain separate capabilities; unsupported resize and clone actions are not advertised.+| Action | Parameters |+| ------------------- | ----------------------------------------------------------------- |+| `list` | `purpose`; returns providers, capabilities, resources and default |+| `create` | `backend`, optional `name`, `purpose`; creates a blank resource |+| `set_default` | `sandbox_id` or null, `purpose`; changes routing |+| `status`, `restart` | optional `sandbox_id`, `purpose` |+| `retire` | `sandbox_id`, `purpose` |++Commands use `execute(command, sandbox_id?, credentials?, background?)`. Set+`background:true` for a detached job and a process ID. The short `purpose` is saved+with the job and displayed instead of the command; the raw command remains available+in expanded output. `timeout_seconds` is the foreground wall-clock timeout or the+background job lifetime. Background jobs require scoped, durable execution; disposable+scratch, owner-auth and reached-room routing remain foreground-only.++The `background` tool controls existing jobs with `poll`, `send_input`, `stop`, `list`,+`watch`, and `unwatch`. Process IDs retain their durable saved target even after the+scope default changes. Watches retain their durable monitor registration and wake this+conversation with output or exit. Provider loss or expiry can still interrupt a process.++Execution and process handlers retain existing command-policy, credential authorization,+and output-screening checks. Strict approvals use the called tool identity (`execute`,+a process action such as `background:poll`, or a lifecycle action such as `sandbox:retire`); a sandbox grant cannot+authorize commands. Transcript entries identify the called tool. Removed sandbox command+and process actions and `background start` are not aliases. No database migration or+backfill is needed; existing jobs remain controllable by process ID. Interrupted old tool calls may return an unsupported-action error and require agent recovery with the new tools.## Upgrade and rollbackdiff --git a/plugins/web-ui/src/timeline.ts b/plugins/web-ui/src/timeline.tsindex 076012906..8e47aac6b 100644--- a/plugins/web-ui/src/timeline.ts+++ b/plugins/web-ui/src/timeline.ts@@ -13,6 +13,7 @@ export interface ToolPayload {tool?: string;command?: string;+ background?: boolean;purpose?: string;path?: string;bytes?: number;@@ -72,6 +73,7 @@ function isTerminalWorkStatus(status: WorkBlock["status"]): boolean {export type ToolRowKind = "running" | "ok" | "failed" | "attempted" | "approval";export function toolCategory(payload: ToolPayload): string {+ if (payload.tool === "execute" && payload.background === true) return "background";if (payload.tool === "files") {if (payload.action === "read" || payload.action === "write") return payload.action;return "share";diff --git a/plugins/web-ui/test/timeline.test.ts b/plugins/web-ui/test/timeline.test.tsindex 9f52fa846..cf190a215 100644--- a/plugins/web-ui/test/timeline.test.ts+++ b/plugins/web-ui/test/timeline.test.ts@@ -494,3 +494,8 @@ test("ordinary and hidden user events do not become steering markers", () => {};assert.deepEqual(buildTimeline(work), []);});++test("detached execution uses process presentation rather than foreground output suppression", () => {+ assert.equal(toolCategory({ tool: "execute", background: true }), "background");+ assert.equal(toolCategory({ tool: "execute", background: false }), "execute");+});diff --git a/skills-seed/browse/SKILL.md b/skills-seed/browse/SKILL.mdindex 191ea3f5c..d3fb77542 100644--- a/skills-seed/browse/SKILL.md+++ b/skills-seed/browse/SKILL.md@@ -76,7 +76,7 @@ becoming the default):so that key is already set in every shell — skip straight to the profile check below. Aperson's own provider key and their profile name never arrive in your env by default: findtheir handles in your keychain manifest and name them in `credentials` on every `execute`-and background start that needs them. Never echo the values.+(including `background:true`) that needs them. Never echo the values.**If the browser provider key is in neither your env nor your handles, don't dead-end on"no grant"** — the keychain has a path for every case, and a person-typed turn can use all@@ -198,9 +198,9 @@ PY(The `tee` matters: the outcome JSON lands in `/tmp/browse-out.txt`, which is how a wall URLgets into later commands as data instead of being pasted into shell source.)-For a task likely to run past a couple of minutes, launch it with the `background` tool and+For a task likely to run past a couple of minutes, launch it with `execute(background:true)` andpoll its output instead of blocking `execute`. Pass the same `credentials` handles to the-background start: org-configured keys are already in every shell's env, but a run without+execute call: org-configured keys are already in every shell's env, but a run withoutits keychain keys fails every step with "Could not resolve authentication method", whichlooks exactly like the flaky-auth race but isn't.diff --git a/skills-seed/interactive-login/SKILL.md b/skills-seed/interactive-login/SKILL.mdindex 02c46a2b4..72241b6ba 100644--- a/skills-seed/interactive-login/SKILL.md+++ b/skills-seed/interactive-login/SKILL.md@@ -10,7 +10,7 @@ to the keychain with the script shipped with this skill. Never log in against th`$HOME`, and never treat a token or config already in `$HOME` as a usable login: only akeychain handle is.-1. Make a fresh directory and start the login as a background job with every config+1. Make a fresh directory and start the login with `execute(background:true)` with every configlocation pointed into it. Copy in any config the CLI needs first (for AWS, the`[profile …]`/`[sso-session …]` blocks in `.aws/config`); everything under thatdirectory becomes the saved login.@@ -43,8 +43,7 @@ keychain handle is.Saving the same service again replaces that entry in place: its id, handle, owner andgrants stay the same.-4. Use the login only by naming the handle in `credentials` on `execute` or a background- start, including to check that it works. The files are staged in a private home for+4. Use the login only by naming the handle in `credentials` on `execute` (including `background:true`), including to check that it works. The files are staged in a private home forthat command or job, and refreshes the CLI writes are saved back when it ends.Never print token files or paste their contents into the conversation. If the login failsdiff --git a/skills-seed/publish/SKILL.md b/skills-seed/publish/SKILL.mdindex e1edb8b28..315d0c66b 100644--- a/skills-seed/publish/SKILL.md+++ b/skills-seed/publish/SKILL.md@@ -12,8 +12,7 @@ ends; publishing ships your files to a separate, long-lived runtime that keeps rand gets a stable link.Publish with the `apps` tool, action `publish`. Build the app in the workspace with-`files` actions `write` / `read`; install dependencies and test with `sandbox` action-`exec` (`execute` before sandbox-resource activation). Then publish the directory.+`files` actions `write` / `read`; install dependencies and test with `execute`. Then publish the directory.The app must listen on the `PORT` env var (the runtime sets it).## Match the house style (the default)@@ -96,8 +95,7 @@ the same as the app _working_. So for anything browsable, sanity-check it locallpublish:1. Run it locally. Start the server in the background on a port — e.g.- `PORT=8080 node server.js` via `sandbox` action `start_process` with `purpose: "App preview server"` (`background` action `start`- before sandbox-resource activation), so it keeps serving while you check.+ `PORT=8080 node server.js` via `execute` with `background:true` and `purpose: "App preview server"`, so it keeps serving while you check.2. Probe it with `curl` — confirm it answers, returns the status you expect, and the mainpage/endpoint is actually there (real content, not a stack trace or a blank 500):diff --git a/skills-seed/taste-skill/SKILL.md b/skills-seed/taste-skill/SKILL.mdindex 14a6c2bc2..866221132 100644--- a/skills-seed/taste-skill/SKILL.md+++ b/skills-seed/taste-skill/SKILL.md@@ -39,8 +39,8 @@ workspace, verify it locally, and when it should outlive the turn ship it with t`publish` skill.- **`files` actions `write` / `read`** — author and inspect workspace files.-- **`sandbox` action `exec`** — install deps and run build steps (`execute` before sandbox-resource activation).-- **`sandbox` action `start_process`** — run a dev server (`PORT=8080 node server.js`, `purpose: "App preview server"`) so you can look at it (`background` action `start` before activation).+- **`execute`** — install deps and run build steps.+- **`execute` with `background:true`** — run a dev server (`PORT=8080 node server.js`, `purpose: "App preview server"`) so you can look at it.- **local headless Chromium** — confirm the page renders, the content is there, no consoleerrors, layout and links intact: `chromium --headless --no-sandbox --disable-gpu--dump-dom http://localhost:<port>` (or `--screenshot=/tmp/page.png`, then use `files` action `read` on thediff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.tsindex faf9e3ad4..888a37e72 100644--- a/src/harness/agent-tools.ts+++ b/src/harness/agent-tools.ts@@ -6,7 +6,7 @@ import { createGrindMeter, grindState } from "./grind.ts";import type { HarnessHandoff, RuntimeRequest } from "./runtime-types.ts";import { defineTool, type ToolDefinition } from "@earendil-works/pi-coding-agent";import { Type, type TSchema } from "typebox";-import { Check, Clone } from "typebox/value";+import { Check } from "typebox/value";import { CONFIG_DEFAULTS, type Config } from "../config.ts";import type { ClientToolDeclaration, CronFireLogEntry, EntryType, ScopeId } from "../types.ts";import type { ToolContext, PublishInput, PublishAudienceDescriptor } from "../tools/primitives.ts";@@ -393,26 +393,6 @@ export function pauseStampAfterToolCall(}export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions): ToolDefinition[] {- const processActions = {- start_process: "start",- read_process: "poll",- write_stdin: "send_input",- signal_process: "stop",- list_processes: "list",- watch_process: "watch",- unwatch_process: "unwatch",- } as const;- const sandboxLog = (payload: Record<string, unknown>): Record<string, unknown> => {- if (!opts?.sandboxResources) return payload;- if (payload.tool === "execute") return { ...payload, tool: "sandbox", action: "exec" };- if (payload.tool === "background")- return {- ...payload,- tool: "sandbox",- action: Object.entries(processActions).find(([, action]) => action === payload.action)?.[0],- };- return payload;- };const scratchExec = !!opts?.scratchExec;const ownerAuthExec = !!opts?.ownerAuthExec;const reachExec = !!opts?.reachExec;@@ -451,7 +431,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):const recordCall = (callId: string, payload: Record<string, unknown>): Promise<void> => {const mark = retryMarks.get(callId);return log("tool_call", {- ...sandboxLog(payload),+ ...payload,callId,...(mark ? { retrySafe: mark.safe, ...(mark.rerun ? { rerun: mark.rerun } : {}) } : {}),});@@ -471,7 +451,6 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):): Promise<T> =>resultQueue("result", async () => {const originalTool = String(summary.tool ?? "");- summary = sandboxLog(summary);const t = ret.content.filter((c) => c.type === "text").map((c) => c.text ?? "")@@ -621,13 +600,19 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):"higher for builds/installs/tsc/test runs that legitimately take minutes, or lower for " +"commands you expect to be quick so a hang frees the machine fast. For work that " +`legitimately exceeds the ${execCeilingSec}s ceiling (long builds, installs, test suites, servers), use ` +- "the `background` tool to run it detached and poll for the result across turns. " +- "Always start servers with the background tool, not shell ampersand: inherited output streams can keep execute waiting even after its shell exits. " ++ "execute with background:true to run it detached, then use background to poll or watch the result across turns. " ++ "Always start servers with execute background:true, not shell ampersand: inherited output streams can keep execute waiting even after its shell exits. " +"If commands hang or fail with transport errors that nothing you ran explains, the computer itself may be " +"wedged — use sandbox action=status to inspect it out-of-band and action=restart to recover it. If a restart or two does not bring the shell back, stop restarting: create a fresh sandbox, set it as the default, and retry there, recovering work from git or Files.";const executeBaseParams = {command: Type.String({ description: "The shell command to run." }),+ background: Type.Optional(+ Type.Boolean({+ description:+ "Run detached and return a process_id. Use background to poll, send input, stop, or watch the process. Only scoped execution supports background jobs.",+ }),+ ),sandbox_id: Type.Optional(Type.String({minLength: 1,@@ -644,7 +629,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):Type.Integer({minimum: 1,description:- `Max wall-clock seconds before the command is killed (exit 124). Default ${execTimeoutSec}, max ${execCeilingSec}. ` ++ `Max wall-clock seconds before the command is killed (exit 124). Default ${execTimeoutSec}, max ${execCeilingSec}; background:true uses a job lifetime (default ${bgTtlSec}, max ${bgTtlMaxSec}). ` +"Raise this for builds/installs/tsc/test runs that legitimately take minutes; lower it " +"for commands you expect to be quick so a hang frees the machine fast.",}),@@ -762,7 +747,8 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):);}await log("tool_result", {- ...sandboxLog({ tool: "execute", ...scopeNote }),+ tool: "execute",+ ...scopeNote,callId,isError: true,result: `Command execution failed: ${redactSecrets(errMessage(e))}`,@@ -779,7 +765,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):const SCOPED_EPHEMERAL_ERROR ='[error] the scoped computer is always durable today — re-run with durable:true (or omit `durable`), or use scope:"scratch" for disposable local working files.';const FILE_SEND_GUIDANCE =- "The files and apps tools use the default sandbox; execute and background can target sandbox_id. To send a file, write it to a workspace path and name that path to whichever tool sends: the surface `post` action's `files` when you have `post` (the only way there — a file needs a thread), otherwise `attach`, which rides it out with your reply. The tool result tells you what actually went. A background job can't deliver; have it write to the workspace and attach that from a live turn. ";+ "The files and apps tools use the default sandbox; execute can target sandbox_id. To send a file, write it to a workspace path and name that path to whichever tool sends: the surface `post` action's `files` when you have `post` (the only way there — a file needs a thread), otherwise `attach`, which rides it out with your reply. The tool result tells you what actually went. A background job can't deliver; have it write to the workspace and attach that from a live turn. ";const DURABLE_PARAM_DESC ="Retain working state for later turns within provider recovery limits? Scoped retains working state; scratch lasts for the turn; owner is invocation-only. Publish durable code to git and artifacts to Files.";@@ -879,6 +865,11 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):return runExecute(callId, params, { reachTarget: scope });};+ const runCommand = (+ callId: string,+ params: Parameters<typeof runScopedExecute>[1] & { background?: boolean; sandbox_id?: string },+ ) => (params.background ? runBackgroundExecute(callId, params) : runScopedExecute(callId, params));+let execute: ToolDefinition;if (reachExec) {execute = defineTool({@@ -896,7 +887,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):}: {}),}),- execute: (callId, params) => runScopedExecute(callId, params as Parameters<typeof runScopedExecute>[1]),+ execute: (callId, params) => runCommand(callId, params as Parameters<typeof runCommand>[1]),});} else if (scratchExec || ownerAuthExec) {execute = defineTool({@@ -920,7 +911,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):),durable: Type.Optional(Type.Boolean({ description: DURABLE_PARAM_DESC })),}),- execute: (callId, params) => runScopedExecute(callId, params as Parameters<typeof runScopedExecute>[1]),+ execute: (callId, params) => runCommand(callId, params as Parameters<typeof runCommand>[1]),});} else {execute = defineTool({@@ -928,7 +919,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):label: "execute",description: legacyDescription,parameters: Type.Object(executeBaseParams),- execute: (callId, params) => runExecute(callId, params as Parameters<typeof runExecute>[1]),+ execute: (callId, params) => runCommand(callId, params as Parameters<typeof runCommand>[1]),});}@@ -1809,13 +1800,77 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):},});+ const runBackgroundExecute = async (callId: string, params: Parameters<typeof runCommand>[1]) => {+ const tc = ref.current;+ if (!tc) return text("[error] no active tool context");+ await recordCall(callId, { ...params, tool: "execute", background: true });+ if (+ (params.scope ?? "scoped").trim().toLowerCase() !== "scoped" ||+ params.durable === false ||+ params.sandbox_id === null+ )+ return invalidExecute(+ callId,+ { tool: "execute", background: true },+ '[error] background jobs require scope:"scoped" with durable storage; use sandbox_id to select their computer.',+ );+ try {+ if (!params.command)+ return recordResult(+ callId,+ { tool: "execute", background: true, error: "start requires command" },+ text("[error] execute background:true requires `command`."),+ true,+ );+ if (!params.purpose?.trim())+ return recordResult(+ callId,+ { tool: "execute", background: true, error: "start requires purpose" },+ text("[error] execute background:true requires `purpose`: a short description of the job, about 5 words."),+ true,+ );+ const r = await tc.backgroundStart(params.command, {+ purpose: params.purpose,+ ...(params.timeout_seconds ? { ttlSeconds: params.timeout_seconds } : {}),+ ...(params.sandbox_id ? { sandboxId: params.sandbox_id } : {}),+ ...(params.credentials?.length ? { credentials: params.credentials } : {}),+ });+ return recordResult(+ callId,+ { tool: "execute", background: true, ...r },+ {+ content: [+ {+ type: "text" as const,+ text: `started ${r.processId}${r.reattached ? " (reattached)" : ""}\n${r.output}\n[cursor ${r.cursor} | ${fmtStatus(r.status)}]`,+ },+ ],+ details: r,+ },+ false,+ undefined,+ false,+ undefined,+ { provenance: "external" },+ );+ } catch (e) {+ if (e instanceof NeedsApproval) return blockOnApproval(callId, e, params.purpose);+ if (e instanceof CommandDenied)+ return recordResult(+ callId,+ { tool: "execute", background: true, denied: true, reason: e.message },+ text(`[denied by policy] ${e.message}`),+ true,+ );+ throw e;+ }+ };+const background = defineTool({name: "background",label: "background",description:- "Run a long shell command in the background on your computer when it would exceed the 300s " +- "`execute` ceiling (big builds, installs, full test suites, data jobs, long-running " +- "servers/dev servers). action=start launches it and returns a process_id immediately — the " ++ "Manage a command launched with execute background:true, which returns a process_id immediately. The " +"command keeps running across turns, even after you reply. action=poll reads new output and " +"tells you whether it's still running or has exited (with its exit code); pass the cursor " +"from your last poll as since_cursor to get only what's new, and call again to drain more " +@@ -1824,27 +1879,26 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):"action=watch turns a running job into a push notifier for THIS conversation: instead of you " +"polling, new output (optionally only lines matching `pattern`) wakes you here as a new turn, " +"and you're woken once more when the job exits — use it to keep the user posted on long work " +- "(builds, deploys, data jobs) without anyone asking. Pass the cursor from start/poll as " ++ "(builds, deploys, data jobs) without anyone asking. Pass the cursor from execute/poll as " +"since_cursor so the first wake carries only output you haven't seen, and `instructions` to " +"remind your future self what to do with each wake. action=unwatch (with monitor_id from " +`watch) disarms it. Each job has a hard time-to-live (default ${bgTtlMin} minutes, max ${bgTtlMaxMin}) after which ` +"it's stopped automatically (a watch survives just long enough to tell you) — for anything " +- `that finishes within ${execCeilingSec}s, just use \`execute\`. Available on the default sandbox or an authorized explicit sandbox_id; ` ++ `that finishes within ${execCeilingSec}s, just use \`execute\`. Start jobs with execute background:true on the default sandbox or an authorized explicit sandbox_id; ` +"elsewhere, use `execute`. A background job carries the same environment a foreground `execute` " +`does — $AGENT_API_URL, $AGENT_API_TOKEN and $AGENT_CREDENTIAL_TOKEN all work, so self-API calls and shared-credential broker calls run fine from background work. ${capabilityExpiry}, and a background job cannot deliver a file itself, so write results to ordinary workspace paths and attach them from a live turn after polling.\n` +"INTERACTIVE LOGINS: device-flow logins (`gh auth login`, " +"`glab auth login`, `gcloud auth login`, and anything that prints a verification URL/code then " +- "blocks waiting on a human) belong here, NOT in `execute`. Run them with action=start, read the " ++ "blocks waiting on a human) need execute background:true. Read the " +"URL/code from the returned output and relay it to the user, then `watch` (or `poll`) until the " +"command exits — that's when the login is done. If a prompt needs an answer typed in, use " +- "action=send_input. Never run a login with `execute` (it blocks the whole turn) and never `stop`/kill a " ++ "action=send_input. Never run a login with foreground execute (it blocks the whole turn) and never `stop`/kill a " +"login mid-flight — that throws away the pending approval and wedges it. Read the `interactive-login` skill " +"before starting one and run it as the skill says: under a temporary home, never this computer's $HOME, then " +"saved to the keychain.",parameters: Type.Object({action: Type.Union([- Type.Literal("start"),Type.Literal("poll"),Type.Literal("send_input"),Type.Literal("stop"),@@ -1854,18 +1908,17 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):],{description:- "start a long command, poll its output by id, send_input to its stdin, stop it, list your background jobs, watch a job so its output/exit wakes you in this conversation, or unwatch.",+ "poll output by id, send_input to its stdin, stop it, list your background jobs, watch a job so its output/exit wakes you in this conversation, or unwatch.",},),purpose: Type.Optional(Type.String({description:- "Short job description, about 5 words (e.g. 'App preview server'). Required for start; displayed to the user instead of code.",+ "Short job description, about 5 words (e.g. 'App preview server'). Optional context for approval requests.",}),),- command: Type.Optional(Type.String({ description: "start only: the shell command to run in the background." })),process_id: Type.Optional(- Type.String({ description: "poll/send_input/stop/watch only: the id start returned." }),+ Type.String({ description: "poll/send_input/stop/watch only: the process_id execute returned." }),),data: Type.Optional(Type.String({@@ -1911,23 +1964,6 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):{ description: "stop only: default TERM; use KILL to force." },),),- sandbox_id: Type.Optional(- Type.String({- description: "start only: exact sandbox to run on; later operations use the job’s saved target.",- }),- ),- credentials: Type.Optional(- Type.Array(Type.String(), {- description:- "start only: exact authorized credential handles, as for execute. They stay staged until the job exits, then refreshes are saved back.",- }),- ),- timeout_seconds: Type.Optional(- Type.Integer({- minimum: 1,- description: `start only: hard lifetime in seconds before auto-stop (default ${bgTtlSec}, max ${bgTtlMaxSec}).`,- }),- ),}),async execute(callId, params) {const tc = ref.current;@@ -1936,54 +1972,18 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):tool: "background",action: params.action,purpose: params.purpose,- command: params.command,process_id: params.process_id,- ...(params.sandbox_id ? { sandbox_id: params.sandbox_id } : {}),...(params.monitor_id ? { monitor_id: params.monitor_id } : {}),- ...(params.credentials?.length ? { credentials: params.credentials } : {}),});try {switch (params.action) {- case "start": {- if (!params.command)- return recordResult(- callId,- { tool: "background", action: params.action, error: "start requires command" },- text("[error] background start requires `command`."),- true,- );- if (!params.purpose?.trim())- return recordResult(- callId,- { tool: "background", action: params.action, error: "start requires purpose" },- text("[error] background start requires `purpose`: a short description of the job, about 5 words."),- true,- );- const r = await tc.backgroundStart(params.command, {- purpose: params.purpose,- ...(params.timeout_seconds ? { ttlSeconds: params.timeout_seconds } : {}),- ...(params.sandbox_id ? { sandboxId: params.sandbox_id } : {}),- ...(params.credentials?.length ? { credentials: params.credentials } : {}),- });+ default:return recordResult(callId,- { tool: "background", action: params.action, ...r },- {- content: [- {- type: "text" as const,- text: `started ${r.processId}${r.reattached ? " (reattached)" : ""}\n${r.output}\n[cursor ${r.cursor} | ${fmtStatus(r.status)}]`,- },- ],- details: r,- },- false,- undefined,- false,- undefined,- { provenance: "external" },+ { tool: "background", action: params.action, invalid: true },+ text("[error] unsupported background action"),+ true,);- }case "poll": {if (!params.process_id)return recordResult(@@ -2202,155 +2202,6 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):},});- const processFieldDescription = (description: string) =>- description.replace(- /\b(start|poll|send_input|stop|watch|unwatch)\b/g,- (action) => Object.entries(processActions).find(([, legacy]) => legacy === action)?.[0] ?? action,- );- const schemas = (tool: ToolDefinition) => (tool.parameters as { properties: Record<string, TSchema> }).properties;- const sandboxProperties = {- ...Object.fromEntries(- Object.entries(schemas(background)).map(([key, schema]) => {- const description = (schema as TSchema & { description?: string }).description;- return [- key,- description ? Object.assign(Clone(schema), { description: processFieldDescription(description) }) : schema,- ];- }),- ),- ...schemas(execute),- ...schemas(sandboxManagement),- command: Type.Optional(executeBaseParams.command),- purpose: Type.Optional(- Type.String({- description:- "Human-readable intent label, about 5 words (e.g. 'App preview server'). Describe what the job does, not the code. Required for exec, management actions, and start_process; optional for other process actions.",- }),- ),- timeout_seconds: Type.Optional(- Type.Integer({- minimum: 1,- description: `exec: wall-clock timeout (default ${execTimeoutSec}s, max ${execCeilingSec}s). start_process: job lifetime (default ${bgTtlSec}s, max ${bgTtlMaxSec}s).`,- }),- ),- action: Type.String({ enum: [...sandboxActions, "exec", ...Object.keys(processActions)] }),- };- const actionFields: Record<string, string[]> = {- status: ["sandbox_id"],- restart: ["sandbox_id"],- list: [],- create: ["backend", "name"],- set_default: ["sandbox_id"],- retire: ["sandbox_id"],- exec: Object.keys(schemas(execute)),- start_process: ["command", "sandbox_id", "timeout_seconds", "credentials"],- read_process: ["process_id", "since_cursor", "wait_seconds", "max_bytes"],- write_stdin: ["process_id", "data"],- signal_process: ["process_id", "signal"],- list_processes: [],- watch_process: ["process_id", "since_cursor", "pattern", "instructions"],- unwatch_process: ["monitor_id"],- };- const requiredFields: Record<string, string[]> = {- status: ["purpose"],- restart: ["purpose"],- list: ["purpose"],- create: ["purpose", "backend"],- set_default: ["purpose", "sandbox_id"],- retire: ["purpose", "sandbox_id"],- exec: ["purpose", "command"],- start_process: ["purpose", "command"],- read_process: ["process_id"],- write_stdin: ["process_id", "data"],- signal_process: ["process_id"],- watch_process: ["process_id"],- unwatch_process: ["monitor_id"],- };- const actionSchemas = Object.fromEntries(- Object.entries(actionFields).map(([action, fields]) => [- action,- Type.Object(- Object.fromEntries(- [...new Set(["action", "purpose", ...fields])].map((field) => [- field,- sandboxProperties[field as keyof typeof sandboxProperties],- ]),- ),- { additionalProperties: false },- ),- ]),- );- const describeSandbox = (description: string) =>- description- .replaceAll("action=start", "action=start_process")- .replaceAll("action=poll", "action=read_process")- .replaceAll("action=send_input", "action=write_stdin")- .replaceAll("action=stop", "action=signal_process")- .replaceAll("action=list", "action=list_processes")- .replaceAll("action=watch", "action=watch_process")- .replaceAll("action=unwatch", "action=unwatch_process")- .replaceAll("`execute`", "sandbox action=exec")- .replaceAll("`background`", "sandbox action=start_process")- .replaceAll("execute and background", "exec and start_process")- .replaceAll("`watch`", "watch_process")- .replaceAll("`poll`", "read_process")- .replaceAll("`stop`", "signal_process");- const sandbox =- opts?.sandboxResources && !delegateWork- ? defineTool({- name: "sandbox",- label: "sandbox",- description:- sandboxManagement.description +- "\nexec: " +- describeSandbox(execute.description) +- "\nProcess actions: " +- describeSandbox(background.description) +- "\nProcess IDs retain their original sandbox target; route changes do not move running jobs. Fields are action-specific; do not pass a sandbox_id to process operations after start_process.",- parameters: Type.Object(sandboxProperties, { additionalProperties: false }),- async execute(callId, params, signal, onUpdate, ctx) {- const action = params.action;- const schema = Object.hasOwn(actionSchemas, action) ? actionSchemas[action] : undefined;- const missing = (Object.hasOwn(requiredFields, action) ? requiredFields[action]! : []).find((field) => {- const value = (params as Record<string, unknown>)[field];- return value === undefined || (typeof value === "string" && field !== "data" && !value.trim());- });- if (- !schema ||- missing ||- !Check(schema, params) ||- ((params as Record<string, unknown>).sandbox_id === null && action !== "set_default")- ) {- await recordCall(callId, { tool: "sandbox", action, purpose: params.purpose });- return recordResult(- callId,- { tool: "sandbox", action, invalid: true },- text(- !schema- ? "[error] unsupported sandbox action"- : `[error] sandbox ${action}: ${missing ? `requires ${missing}` : "invalid or unrelated parameters"}`,- ),- true,- );- }- const { action: _, ...input } = params;- if (action === "exec") return execute.execute(callId, input, signal, onUpdate, ctx);- if (Object.hasOwn(processActions, action))- return background.execute(- callId,- {- ...input,- action: processActions[action as keyof typeof processActions],- },- signal,- onUpdate,- ctx,- );- return sandboxManagement.execute(callId, params, signal, onUpdate, ctx);- },- })- : sandboxManagement;-const unavailable = (callId: string, tool: string) =>recordResult(callId,@@ -4375,7 +4226,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):});const tools = [- ...(!opts?.sandboxResources && !delegateWork ? [execute] : []),+ ...(!delegateWork ? [execute] : []),resourceTool("skills", {read: skill,...(controlTools ? { share: sharingTool("skill"), move: sharingTool("skill", true) } : {}),@@ -4387,9 +4238,9 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):}),memory,history,- ...(!opts?.sandboxResources && !delegateWork ? [background] : []),+ ...(!delegateWork ? [background] : []),...(opts?.sessionTools === false ? [] : [subagentTool, ...(sidebarSessions ? [sessionTool] : [])]),- sandbox,+ sandboxManagement,...(controlTools? [resourceTool("cron", {@@ -4413,11 +4264,84 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):...mcpTools,...clientTools,];+ const operationFields: Record<string, Record<string, string[]>> = {+ sandbox: {+ status: ["sandbox_id"],+ restart: ["sandbox_id"],+ list: [],+ create: ["backend", "name"],+ set_default: ["sandbox_id"],+ retire: ["sandbox_id"],+ },+ background: {+ poll: ["process_id", "since_cursor", "wait_seconds", "max_bytes"],+ send_input: ["process_id", "data"],+ stop: ["process_id", "signal"],+ list: [],+ watch: ["process_id", "since_cursor", "pattern", "instructions"],+ unwatch: ["monitor_id"],+ },+ };+ const validateSandboxTool = (tool: ToolDefinition): ToolDefinition => {+ if (!["execute", "background", "sandbox"].includes(tool.name)) return tool;+ const properties = (tool.parameters as { properties: Record<string, TSchema> }).properties;+ const schema = Type.Object(properties, { additionalProperties: false });+ return {+ ...tool,+ parameters: schema,+ async execute(callId, params, signal, onUpdate, ctx) {+ const action = isObj(params) ? String(params.action) : "";+ const operations = operationFields[tool.name];+ const fields = operations && Object.hasOwn(operations, action) ? operations[action] : undefined;+ let required: string[];+ if (tool.name === "execute") required = ["command", "purpose"];+ else if (tool.name === "sandbox") {+ required = ["purpose"];+ if (["set_default", "retire"].includes(action)) required.push("sandbox_id");+ if (action === "create") required.push("backend");+ } else {+ required = action === "list" ? [] : ["process_id"];+ if (action === "unwatch") required = ["monitor_id"];+ if (action === "send_input") required.push("data");+ }+ const missing = required.find(+ (key) =>+ !isObj(params) ||+ params[key] === undefined ||+ (typeof params[key] === "string" && key !== "data" && !params[key].trim()),+ );+ if (+ !Check(schema, params) ||+ missing ||+ (operations &&+ (!fields || Object.keys(params).some((key) => !["action", "purpose", ...fields].includes(key)))) ||+ (tool.name === "sandbox" && params.sandbox_id === null && action !== "set_default")+ ) {+ await recordCall(callId, {+ tool: tool.name,+ ...(isObj(params) ? { purpose: params.purpose, action: params.action } : {}),+ });+ return recordResult(+ callId,+ { tool: tool.name, invalid: true },+ text(+ `[error] invalid ${tool.name} arguments: ${missing ? `requires \`${missing}\`` : "use only the advertised fields and types for this operation"}.`,+ ),+ true,+ );+ }+ return tool.execute(callId, params, signal, onUpdate, ctx);+ },+ };+ };const mcpNames = new Set(mcpTools.map((t) => t.name));const active = opts?.readOnly ? tools.filter((t) => READ_ONLY_TOOL_NAMES.has(t.name) || mcpNames.has(t.name)) : tools;return active.map((t) =>withRetrySafety(- withRuntimeBarrier(withToolBodyTiming(withToolApprovalGate(t, ref, { recordCall, recordResult }), ref), ref),+ withRuntimeBarrier(+ withToolBodyTiming(withToolApprovalGate(validateSandboxTool(t), ref, { recordCall, recordResult }), ref),+ ref,+ ),retryMarks,),);@@ -4498,12 +4422,14 @@ function withToolApprovalGate(async execute(callId: string, params: unknown) {const gate = ref.toolApprovalGate;const resourceAction =- ["sandbox", "files", "apps", "skills", "goal", "cron", "admin"].includes(tool.name) &&+ ["sandbox", "background", "files", "apps", "skills", "goal", "cron", "admin"].includes(tool.name) &&isObj(params) &&typeof params.action === "string"? params.action: undefined;- const approvalIdentity = ["sandbox", "files", "apps", "skills", "goal", "cron", "admin"].includes(tool.name)+ const approvalIdentity = ["sandbox", "background", "files", "apps", "skills", "goal", "cron", "admin"].includes(+ tool.name,+ )? `${tool.name}:${resourceAction ?? "invalid"}`: tool.name;const commandLabel = resourceAction ? `${tool.name} ${resourceAction}` : tool.name;@@ -4514,9 +4440,7 @@ function withToolApprovalGate(kind: "approval",approvalKey: `tool:${approvalIdentity}`,...(params === undefined ? {} : { summary: redactCommand(redactSecrets(JSON.stringify(params))) }),- ...(tool.name === "sandbox" && isObj(params) && typeof params.purpose === "string"- ? { purpose: params.purpose }- : {}),+ ...(isObj(params) && typeof params.purpose === "string" ? { purpose: params.purpose } : {}),});ref.pausedOnApproval = true;await rec.recordCall(callId, {diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.tsindex 4477dea74..c4b8cb0c2 100644--- a/test/agent-tools.test.ts+++ b/test/agent-tools.test.ts@@ -388,7 +388,7 @@ test("each agent tool emits a tool_call then a tool_result", async () => {const [execute, , read] = createAgentTools(ref, { controlTools: true });const write = read;- await call(execute, { command: "echo hi" });+ await call(execute, { command: "echo hi", purpose: "Run test command" });await call(read, { action: "read", path: "a.txt" });await call(write, { action: "write", path: "out.txt", data: "xyz" });await call(write, { action: "share", path: "out.txt", scope: "org" });@@ -434,7 +434,7 @@ test("sandbox manages the box out-of-band instead of running a command", async (const ref: ToolContextRef = { current: tc, emit: () => {}, scopeLabel: "personal:U1" };const execute = createAgentTools(ref).find((t) => t.name === "sandbox")!;- const status = (await call(execute, { command: "", action: "status", purpose: "p" })) as {+ const status = (await call(execute, { action: "status", purpose: "p" })) as {content: Array<{ text?: string }>;};assert.match(@@ -448,7 +448,7 @@ test("sandbox manages the box out-of-band instead of running a command", async ("a provisioned machine with a dead guest is called out as wedged, not left as two contradicting fields",);- const restart = (await call(execute, { command: "", action: "restart", purpose: "p" })) as {+ const restart = (await call(execute, { action: "restart", purpose: "p" })) as {content: Array<{ text?: string }>;};assert.equal(restarted.length, 1);@@ -460,7 +460,7 @@ test("sandbox manages the box out-of-band instead of running a command", async (throw new Error("this computer's substrate (local) does not support restarting the computer");},};- const err = (await call(execute, { command: "", action: "restart", purpose: "p" })) as {+ const err = (await call(execute, { action: "restart", purpose: "p" })) as {content: Array<{ text?: string }>;};assert.match(err.content[0]!.text!, /does not support restarting/);@@ -471,23 +471,9 @@ test("sandbox advertises available management actions and retires migrate", asynconst enabled = createAgentTools(ref, { sandboxResources: true });const sandbox = enabled.find((t) => t.name === "sandbox")!;const properties = (sandbox.parameters as { properties: Record<string, { enum?: string[] }> }).properties;- assert.deepEqual(properties.action!.enum, [- "status",- "restart",- "list",- "create",- "set_default",- "retire",- "exec",- "start_process",- "read_process",- "write_stdin",- "signal_process",- "list_processes",- "watch_process",- "unwatch_process",- ]);- assert.ok(!enabled.some((t) => t.name === "execute" || t.name === "background"));+ assert.deepEqual(properties.action!.enum, ["status", "restart", "list", "create", "set_default", "retire"]);+ assert.ok(enabled.some((t) => t.name === "execute"));+ assert.ok(enabled.some((t) => t.name === "background"));const execute = createAgentTools(ref).find((t) => t.name === "execute")!;assert.equal("computer" in (execute.parameters as { properties: object }).properties, false);assert.equal("to" in (execute.parameters as { properties: object }).properties, false);@@ -496,8 +482,8 @@ test("sandbox advertises available management actions and retires migrate", asyn"status","restart",]);- assert.match(textOut(await call(sandbox, { action: "migrate", purpose: "p" })), /unsupported sandbox action/);- await assert.rejects(() => call(execute, { command: "", computer: "migrate" }), /migrate has been retired/);+ assert.match(textOut(await call(sandbox, { action: "migrate", purpose: "p" })), /invalid sandbox arguments/);+ assert.match(textOut(await call(execute, { command: "", computer: "migrate" })), /invalid execute arguments/);});test("sandbox tells the agent to provision a missing default before reporting a blocker", () => {@@ -558,7 +544,7 @@ test("computer status surfaces list-view disagreement and guest pressure", async};const ref: ToolContextRef = { current: tc, emit: () => {}, scopeLabel: "personal:U1" };const execute = createAgentTools(ref).find((t) => t.name === "sandbox")!;- const status = (await call(execute, { command: "", action: "status", purpose: "p" })) as {+ const status = (await call(execute, { action: "status", purpose: "p" })) as {content: Array<{ text?: string }>;};assert.match(status.content[0]!.text!, /machine: healthy \(listed: cold\)/);@@ -589,7 +575,7 @@ test("computer status exposes paused lifecycle and recovery deadlines without clscopeLabel: "personal:U1",};const execute = createAgentTools(ref).find((t) => t.name === "sandbox")!;- const out = (await call(execute, { command: "", action: "status", purpose: "p" })) as {+ const out = (await call(execute, { action: "status", purpose: "p" })) as {content: Array<{ text?: string }>;};const output = out.content[0]!.text!;@@ -636,7 +622,7 @@ test("computer status verdicts: answering guest is ok, dead guest without a machscopeLabel: "personal:U1",};const execute = createAgentTools(ref).find((t) => t.name === "sandbox")!;- const out = (await call(execute, { command: "", action: "status", purpose: "p" })) as {+ const out = (await call(execute, { action: "status", purpose: "p" })) as {content: Array<{ text?: string }>;};assert.equal(@@ -719,7 +705,9 @@ test("a giant tool result is capped for the model, keeping the tail and matching};const [execute] = createAgentTools(ref);- const ret = (await call(execute, { command: "curl big" })) as { content: Array<{ type: string; text: string }> };+ const ret = (await call(execute, { command: "curl big", purpose: "Run test command" })) as {+ content: Array<{ type: string; text: string }>;+ };const seen = ret.content.map((c) => c.text).join("\n");assert.ok(seen.length <= 100_000, `model-facing text stays within the declared cap (got ${seen.length} chars)`);assert.ok(seen.includes("…[truncated — full result was"), "truncation notice names the full size");@@ -756,7 +744,7 @@ test("Auto can quarantine a tool result before the model or durable replay sees},};const [execute] = createAgentTools(ref);- const result = (await call(execute, { command: "curl https://example.invalid" })) as {+ const result = (await call(execute, { command: "curl https://example.invalid", purpose: "Run test command" })) as {content: Array<{ text?: string }>;};assert.equal(result.content[0]?.text, "[tool output quarantined by the security screen]");@@ -789,7 +777,7 @@ test("a strict tool-result verdict routes through HiLo approval instead of silenscreenToolResult: async () => ({ outcome: "quarantine" }),};const [execute] = createAgentTools(ref);- const result = (await call(execute, { command: "curl https://example.invalid" })) as {+ const result = (await call(execute, { command: "curl https://example.invalid", purpose: "Run test command" })) as {content: Array<{ text?: string }>;terminate?: boolean;};@@ -828,7 +816,7 @@ test("quarantine_pending with no approvals sink falls back to the legacy silentscreenToolResult: async () => ({ outcome: "quarantine" }),};const [execute] = createAgentTools(ref);- const result = (await call(execute, { command: "echo hi" })) as {+ const result = (await call(execute, { command: "echo hi", purpose: "Run test command" })) as {content: Array<{ text?: string }>;terminate?: boolean;};@@ -856,7 +844,9 @@ test("classifier downtime fails open — the output passes through tagged unscre},};const [execute] = createAgentTools(ref);- const result = (await call(execute, { command: "echo hi" })) as { content: Array<{ text?: string }> };+ const result = (await call(execute, { command: "echo hi", purpose: "Run test command" })) as {+ content: Array<{ text?: string }>;+ };assert.match(result.content[0]?.text ?? "",/NOT security-screened/,@@ -891,7 +881,10 @@ test("the screen never rewrites a policy notice — an approval gate stays legibscreenToolResult: async () => ({ outcome: "quarantine" }),};const [execute] = createAgentTools(ref);- const result = (await call(execute, { command: "acmectl secrets set github token" })) as {+ const result = (await call(execute, {+ command: "acmectl secrets set github token",+ purpose: "Run test command",+ })) as {content: Array<{ text?: string }>;};assert.match(result.content[0]?.text ?? "", /\[blocked: needs human approval\] writes a credential/);@@ -919,7 +912,9 @@ test("the screen never rewrites a policy denial either", async () => {screenToolResult: async () => ({ outcome: "quarantine" }),};const [execute] = createAgentTools(ref);- const result = (await call(execute, { command: "mkfs /dev/sda" })) as { content: Array<{ text?: string }> };+ const result = (await call(execute, { command: "mkfs /dev/sda", purpose: "Run test command" })) as {+ content: Array<{ text?: string }>;+ };assert.match(result.content[0]?.text ?? "", /\[denied by policy\]/);const persisted = emitted.find((entry) => entry.type === "tool_result")!.payload;assert.equal(persisted.denied, true);@@ -940,7 +935,7 @@ test("a real tool result on the same session is still screened", async () => {screenToolResult: async () => ({ outcome: "quarantine" }),};const [execute] = createAgentTools(ref);- await call(execute, { command: "curl https://example.invalid" });+ await call(execute, { command: "curl https://example.invalid", purpose: "Run test command" });const persisted = emitted.find((entry) => entry.type === "tool_result")!.payload;assert.equal(persisted.quarantined,@@ -963,7 +958,9 @@ test("the screen never rewrites a strict-posture per-tool gate", async () => {screenToolResult: async () => ({ outcome: "quarantine" }),};const [execute] = createAgentTools(ref);- const result = (await call(execute, { command: "echo hi" })) as { content: Array<{ text?: string }> };+ const result = (await call(execute, { command: "echo hi", purpose: "Run test command" })) as {+ content: Array<{ text?: string }>;+ };assert.match(result.content[0]?.text ?? "", /\[blocked: needs human approval\] strict posture/);const persisted = emitted.find((entry) => entry.type === "tool_result")!.payload;assert.equal(persisted.blocked, "needs_approval");@@ -1524,7 +1521,7 @@ test("a cross-scope read's tool_result keeps the SOURCE scope label so the audieawait call(read, { action: "read", path: "a.txt" });await call(read, { action: "read", path: "missing.txt" });- await call(execute, { command: "echo hi" });+ await call(execute, { command: "echo hi", purpose: "Run test command" });const labelOf = (type: EntryType, match: (p: any) => boolean) =>emitted.find((e) => e.type === type && match(e.payload))?.scopeLabel;@@ -1589,7 +1586,7 @@ test("a cross-scope result's classified label is recorded by callId for the tapeawait callWith(read, "call-private", { action: "read", path: "a.txt" });await callWith(read, "call-missing", { action: "read", path: "missing.txt" });- await callWith(execute, "call-exec", { command: "echo hi" });+ await callWith(execute, "call-exec", { command: "echo hi", purpose: "Run test command" });assert.equal(ref.tapeResultScopes?.get("call-private"), "personal:U1", "the tape row gets the source scope");assert.equal(ref.tapeResultScopes?.has("call-missing"), false, "session-scoped results are not recorded");@@ -1607,7 +1604,7 @@ test("tool entries carry the call id + faithful model-facing result (WAL replay};const [execute, , read, , memory] = createAgentTools(ref);- await callWith(execute, "call-exec", { command: "echo hi" });+ await callWith(execute, "call-exec", { command: "echo hi", purpose: "Run test command" });await callWith(read, "call-read", { action: "read", path: "a.txt" });await callWith(memory, "call-recall", { action: "search", query: "billing" });@@ -1773,7 +1770,7 @@ test("not-found read and denied command record isError + the faithful error textscopeLabel: "org:default-org",};const [execute, , read] = createAgentTools(ref);- await callWith(execute, "c1", { command: "rm -rf /" });+ await callWith(execute, "c1", { command: "rm -rf /", purpose: "Run test command" });await callWith(read, "c2", { action: "read", path: "missing.txt" });const denied = emitted.find((e) => e.type === "tool_result" && e.payload.tool === "execute")!.payload;@@ -1804,7 +1801,7 @@ test("a denied command still emits a tool_result (denied), and a missing read re};const [execute, , read] = createAgentTools(ref);- await call(execute, { command: "rm -rf /" });+ await call(execute, { command: "rm -rf /", purpose: "Run test command" });await call(read, { action: "read", path: "missing.txt" });const denied = emitted.find((e) => e.type === "tool_result" && e.payload.tool === "execute");@@ -1815,7 +1812,7 @@ test("a denied command still emits a tool_result (denied), and a missing read retest("no emit sink → tools still run, nothing logged (unit path)", async () => {const [execute] = createAgentTools({ current: fakeToolContext() });- const r = await call(execute, { command: "echo ok" });+ const r = await call(execute, { command: "echo ok", purpose: "Run test command" });assert.ok(r);});@@ -1823,25 +1820,22 @@ test("execute forwards the agent's timeout_seconds into tc.execute; omitting itconst sink: { lastExecOpts?: { timeoutSeconds?: number } | undefined } = {};const [execute] = createAgentTools({ current: fakeToolContext(sink) });- await call(execute, { command: "npm ci", timeout_seconds: 240 });+ await call(execute, { command: "npm ci", timeout_seconds: 240, purpose: "Run test command" });assert.deepEqual(sink.lastExecOpts, { timeoutSeconds: 240 });- await call(execute, { command: "echo hi" });+ await call(execute, { command: "echo hi", purpose: "Run test command" });assert.equal(sink.lastExecOpts, undefined);});test('execute scope:"owner" routes only when the owner-auth surface is enabled', async () => {const sink: { lastExecOpts?: Parameters<ToolContext["execute"]>[1] } = {};const execute = createAgentTools({ current: fakeToolContext(sink) }, { ownerAuthExec: true })[0]!;- await call(execute, { command: "acmecli me", scope: "owner" });+ await call(execute, { command: "acmecli me", scope: "owner", purpose: "Run test command" });assert.deepEqual(sink.lastExecOpts, { ownerAuth: true });const unavailable = createAgentTools({ current: fakeToolContext() }, { scratchExec: true })[0]!;- const result = await call(unavailable, { command: "acmecli me", scope: "owner" });- assert.match(- (result as { content: Array<{ text: string }> }).content[0]?.text ?? "",- /owner-auth box is not available/,- );+ const result = await call(unavailable, { command: "acmecli me", scope: "owner", purpose: "Run test command" });+ assert.match((result as { content: Array<{ text: string }> }).content[0]?.text ?? "", /invalid execute arguments/);});test("publish instructions prevent malformed app configs", () => {@@ -1970,7 +1964,10 @@ test("background dispatches each action and emits tool_call/tool_result", asyncassert.match(background.description, /expire 48 hours after the turn/);const started = textOf(- await call(background, { action: "start", command: "npm run build", purpose: "Run background tests" }),+ await call(+ createAgentTools(ref).find((t) => t.name === "execute"),+ { background: true, command: "npm run build", purpose: "Run background tests" },+ ),);assert.match(started, /started bg-1/);assert.match(started, /running/);@@ -1991,7 +1988,8 @@ test("background dispatches each action and emits tool_call/tool_result", asyncassert.match(listed, /bg: npm test/);const bg = emitted.filter((e) => e.payload.tool === "background");- assert.equal(bg.length, 10);+ assert.equal(bg.length, 8);+ assert.equal(emitted.filter((e) => e.payload.tool === "execute").length, 2);});test("background watch reports an already exited job as a successful tail result", async () => {@@ -2032,7 +2030,7 @@ test("background per-action validation returns a crisp [error] instead of throwiconst background = createAgentTools({ current: fakeToolContext() }).find((t) => t.name === "background");assert.ok(background);- assert.match(textOf(await call(background, { action: "start" })), /\[error\].*requires `command`/);+ assert.match(textOf(await call(background, { action: "start" })), /invalid background arguments/);assert.match(textOf(await call(background, { action: "poll" })), /\[error\].*requires `process_id`/);assert.match(textOf(await call(background, { action: "stop" })), /\[error\].*requires `process_id`/);assert.match(@@ -2053,8 +2051,8 @@ test("background surfaces a policy denial/approval as a tool_result, not a throw};const out = textOf(await call(- createAgentTools({ current: denyTC }).find((t) => t.name === "background"),- { action: "start", command: "rm -rf /", purpose: "Run background tests" },+ createAgentTools({ current: denyTC }).find((t) => t.name === "execute"),+ { background: true, command: "rm -rf /", purpose: "Run background tests" },),);assert.match(out, /\[denied by policy\]/);@@ -2070,8 +2068,8 @@ test("background surfaces a policy denial/approval as a tool_result, not a throwconst ref: ToolContextRef = { current: approvalTC, pendingApprovals: pending };const out2 = textOf(await call(- createAgentTools(ref).find((t) => t.name === "background"),- { action: "start", command: "deploy prod", purpose: "Run background tests" },+ createAgentTools(ref).find((t) => t.name === "execute"),+ { background: true, command: "deploy prod", purpose: "Run background tests" },),);assert.match(out2, /\[blocked: needs human approval\]/);@@ -2599,7 +2597,7 @@ test("a blocking command approval terminates the agent loop and flags pausedOnAp};const ref: ToolContextRef = { current: pauseTC, pendingApprovals: [], scopeLabel: "org:default-org" };const [execute] = createAgentTools(ref);- const r = (await callWith(execute, "c1", { command: "git push --force" })) as {+ const r = (await callWith(execute, "c1", { command: "git push --force", purpose: "Run test command" })) as {terminate?: boolean;content: Array<{ text?: string }>;};@@ -2692,7 +2690,10 @@ test("background job output is external while background bookkeeping stays inter},};const background = createAgentTools(ref).find((t) => t.name === "background")!;- await call(background, { action: "start", command: "npm test", purpose: "Run background tests" });+ await call(+ createAgentTools(ref).find((t) => t.name === "execute"),+ { background: true, command: "npm test", purpose: "Run background tests" },+ );await call(background, { action: "poll", process_id: "bg-1" });await call(background, { action: "poll", process_id: "bg-net" });await call(background, { action: "list" });@@ -2720,7 +2721,7 @@ test("execute output from a reached room is external even for a local-looking co},};const [execute] = createAgentTools(ref, { reachExec: true });- await call(execute, { command: "cat notes.md", scope: "channel:C2" });+ await call(execute, { command: "cat notes.md", scope: "channel:C2", purpose: "Run test command" });assert.deepEqual(seen, [{ provenance: "external", source: "reached room" }]);});@@ -2741,7 +2742,10 @@ test("sandbox management and explicit execution preserve independent target arguconst sandbox = tools.find((t) => t.name === "sandbox")!;await call(sandbox, { action: "create", backend: "modal", name: "build", purpose: "p" });await call(sandbox, { action: "set_default", sandbox_id: null, purpose: "p" });- await call(sandbox, { action: "exec", command: "pwd", sandbox_id: "box-a", purpose: "p" });+ await call(+ tools.find((t) => t.name === "execute")!,+ { command: "pwd", sandbox_id: "box-a", purpose: "p" },+ );assert.deepEqual(operations, [{ action: "create", input: { backend: "modal", name: "build", sandboxId: undefined } },{ action: "default", input: { backend: undefined, name: undefined, sandboxId: null } },@@ -2749,7 +2753,7 @@ test("sandbox management and explicit execution preserve independent target arguassert.equal(sink.lastExecOpts?.sandboxId, "box-a");});-test("unified sandbox dispatches every process action and preserves cursors, signals, targets and watches", async () => {+test("execute and background dispatch every process action and preserves cursors, signals, targets and watches", async () => {const calls: Array<{ method: string; args: unknown[] }> = [];const entries: Array<Record<string, unknown>> = [];const screens: Array<{ tool: string; provenance: string }> = [];@@ -2763,7 +2767,7 @@ test("unified sandbox dispatches every process action and preserves cursors, sig};},});- const tool = createAgentTools(+ const tools = createAgentTools({current: tc,scopeLabel: "personal:U1",@@ -2776,33 +2780,46 @@ test("unified sandbox dispatches every process action and preserves cursors, sig},},{ sandboxResources: true },- ).find((t) => t.name === "sandbox")!;+ );const actions = [{- action: "start_process",+ background: true,command: "npm test",purpose: "Run background tests",sandbox_id: "box-a",timeout_seconds: 123,+ credentials: ["test-login"],},- { action: "read_process", process_id: "bg-1", since_cursor: 7, wait_seconds: 2, max_bytes: 99 },- { action: "write_stdin", process_id: "bg-1", data: "yes\n" },- { action: "signal_process", process_id: "bg-1", signal: "INT" },- { action: "list_processes" },+ { action: "poll", process_id: "bg-1", since_cursor: 7, wait_seconds: 2, max_bytes: 99 },+ { action: "send_input", process_id: "bg-1", data: "yes\n" },+ { action: "stop", process_id: "bg-1", signal: "INT" },+ { action: "list" },{- action: "watch_process",+ action: "watch",process_id: "bg-1",since_cursor: 18,pattern: "FAILED",instructions: "Report failures",},- { action: "unwatch_process", monitor_id: "mon-1" },+ { action: "unwatch", monitor_id: "mon-1" },];- for (const action of actions) assert.doesNotMatch(textOut(await call(tool, action)), /\[error\]/);+ for (const action of actions)+ assert.doesNotMatch(+ textOut(+ await call(+ tools.find((t) => t.name === ("background" in action ? "execute" : "background")),+ action,+ ),+ ),+ /\[error\]/,+ );assert.deepEqual(calls, [{method: "backgroundStart",- args: ["npm test", { purpose: "Run background tests", ttlSeconds: 123, sandboxId: "box-a" }],+ args: [+ "npm test",+ { purpose: "Run background tests", ttlSeconds: 123, sandboxId: "box-a", credentials: ["test-login"] },+ ],},{ method: "backgroundPoll", args: ["bg-1", { sinceCursor: 7, waitSeconds: 2, maxBytes: 99 }] },{ method: "backgroundWrite", args: ["bg-1", "yes\n"] },@@ -2817,81 +2834,76 @@ test("unified sandbox dispatches every process action and preserves cursors, sigassert.deepEqual(entries.map((e) => [e.tool, e.action]),actions.flatMap((a) => [- ["sandbox", a.action],- ["sandbox", a.action],+ ["background" in a ? "execute" : "background", a.action],+ ["background" in a ? "execute" : "background", a.action],]),);- assert.ok(screens.every((s) => s.tool === "sandbox"));+ assert.deepEqual(+ screens.map((s) => s.tool),+ ["execute", ...Array(6).fill("background")],+ );assert.deepEqual(screens.slice(0, 2).map((s) => s.provenance),["external", "external"],);});-test("unified sandbox advertised schemas and handlers accept minimal arguments for every action", async () => {- const actions = [- { action: "status", purpose: "Check health" },- { action: "restart", purpose: "Recover the computer" },- { action: "list", purpose: "List computers" },- { action: "create", backend: "modal", purpose: "Create a computer" },- { action: "set_default", sandbox_id: null, purpose: "Clear the default" },- { action: "retire", sandbox_id: "box-a", purpose: "Retire a computer" },- { action: "exec", command: "echo ok", purpose: "Check execution" },- { action: "start_process", command: "echo ok", purpose: "Run background tests" },- { action: "read_process", process_id: "bg-1" },- { action: "write_stdin", process_id: "bg-1", data: "" },- { action: "signal_process", process_id: "bg-1" },- { action: "list_processes" },- { action: "watch_process", process_id: "bg-1" },- { action: "unwatch_process", monitor_id: "mon-1" },- ];+test("only execute advertises command starts and sandbox is lifecycle-only", async () => {+ let dispatched = 0;+ const current = {+ ...fakeToolContext(),+ execute: async () => {+ dispatched++;+ throw new Error("must not execute");+ },+ backgroundStart: async () => {+ dispatched++;+ throw new Error("must not start");+ },+ };for (const options of [{}, { scratchExec: true }, { ownerAuthExec: true }, { reachExec: true }]) {- const tool = createAgentTools(- { current: { ...fakeToolContext(), sandboxResources: async () => ({ ok: true }) }, scopeLabel: "personal:U1" },- { ...options, sandboxResources: true },- ).find((t) => t.name === "sandbox")!;- const advertised = JSON.parse(JSON.stringify(tool.parameters));- assert.deepEqual(advertised.required, ["action"]);- for (const input of actions) {- assert.equal(Check(advertised, input), true, `${JSON.stringify(options)}: ${input.action}`);- assert.doesNotMatch(textOut(await call(tool, input)), /\[error\]/, input.action);+ const tools = createAgentTools({ current }, { ...options, sandboxResources: true });+ const execute = tools.find((t) => t.name === "execute")!;+ const sandbox = tools.find((t) => t.name === "sandbox")!;+ const background = tools.find((t) => t.name === "background")!;+ for (const detached of [false, true])+ assert.equal(+ Check(execute.parameters, {+ command: "pwd",+ purpose: "Check computer",+ sandbox_id: "box-a",+ background: detached,+ }),+ true,+ );+ for (const tool of [sandbox, background]) {+ assert.equal("command" in (tool.parameters as { properties: object }).properties, false);+ for (const action of ["exec", "start", "start_process"]) {+ assert.equal(Check(tool.parameters, { action, command: "forbidden", purpose: "Test old route" }), false);+ assert.match(+ textOut(await call(tool, { action, command: "forbidden", purpose: "Test old route" })),+ /invalid (sandbox|background) arguments/,+ );+ }}+ for (const input of [+ { scope: "scratch" },+ { scope: "owner" },+ { scope: "#room" },+ { durable: false },+ { sandbox_id: null },+ ])+ assert.match(+ textOut(+ await call(execute, { command: "forbidden", purpose: "Test invalid routing", background: true, ...input }),+ ),+ /background jobs require|invalid execute arguments/,+ );}-});--test("unified sandbox rejects missing, mistyped and unrelated action fields before dispatch", async () => {- let dispatched = 0;- const tc = new Proxy(fakeToolContext(), {- get(target, key, receiver) {- const value = Reflect.get(target, key, receiver);- if (typeof value !== "function") return value;- return () => {- dispatched++;- throw new Error("must not dispatch");- };- },- });- const tool = createAgentTools({ current: tc }, { sandboxResources: true }).find((t) => t.name === "sandbox")!;- for (const input of [- { action: "__proto__" },- { action: "constructor" },- { action: "exec", purpose: "test" },- { action: "start_process", command: " ", purpose: "Run background tests" },- { action: "read_process", process_id: "job", sandbox_id: "other-box" },- { action: "write_stdin", process_id: "job" },- { action: "signal_process", process_id: "job", signal: "NOPE" },- { action: "watch_process", process_id: "job", since_cursor: -1 },- { action: "unwatch_process", monitor_id: null },- { action: "list_processes", command: "ignored" },- { action: "start_process", command: "echo ok", purpose: "Run background tests", scope: "scratch" },- { action: "retire", sandbox_id: null, purpose: "test" },- { action: "create", backend: "modal", command: "ignored", purpose: "test" },- ])- assert.match(textOut(await call(tool, input)), /\[error\]/);assert.equal(dispatched, 0);});-test("unified exec preserves routing, credentials, abort and external output provenance", async () => {+test("execute preserves routing, credentials, abort and external output provenance", async () => {const sink: { lastExecOpts?: Parameters<ToolContext["execute"]>[1] } = {};const abort = new AbortController();const screens: unknown[] = [];@@ -2911,7 +2923,7 @@ test("unified exec preserves routing, credentials, abort and external output proreachExec: true,commandCredentialHandles: ["git"],},- ).find((t) => t.name === "sandbox")!;+ ).find((t) => t.name === "execute")!;for (const [scope, route] of [["scoped", {}],["scratch", { scratch: true }],@@ -2919,7 +2931,6 @@ test("unified exec preserves routing, credentials, abort and external output pro["#room", { reachTarget: "#room" }],] as const) {await call(tool, {- action: "exec",scope,command: "pwd",purpose: "verify routing",@@ -2930,12 +2941,12 @@ test("unified exec preserves routing, credentials, abort and external output pro}assert.deepEqual(screens,- Array.from({ length: 4 }, () => ["sandbox", "external"]),+ Array.from({ length: 4 }, () => ["execute", "external"]),);});-test("unified exec and process approvals preserve intent and action identity", async () => {- for (const action of ["exec", "start_process"]) {+test("execute and process approvals preserve intent and action identity", async () => {+ for (const background of [false, true]) {const entries: Array<Record<string, unknown>> = [];const tc = fakeToolContext();tc.execute = tc.backgroundStart = async () => {@@ -2952,20 +2963,20 @@ test("unified exec and process approvals preserve intent and action identity", aentries.push(entry.payload as Record<string, unknown>);},};- const tool = createAgentTools(ref, { sandboxResources: true }).find((t) => t.name === "sandbox")!;+ const tool = createAgentTools(ref, { sandboxResources: true }).find((t) => t.name === "execute")!;assert.match(- textOut(await call(tool, { action, command: "danger", purpose: "Verify protected operation" })),+ textOut(await call(tool, { background, command: "danger", purpose: "Verify protected operation" })),/needs human approval/,);assert.equal(ref.pausedOnApproval, true);assert.equal(ref.pendingApprovals?.[0]?.command, "danger");- assert.ok(entries.every((e) => e.tool === "sandbox" && e.action === action));+ assert.ok(entries.every((e) => e.tool === "execute"));assert.equal(ref.pendingApprovals?.[0]?.purpose, "Verify protected operation");assert.deepEqual(ref.pendingApprovals?.[0]?.grantModes, { session: false, always: false });}});-test("unified sandbox keeps strict approval and quarantined output associated with the called action", async () => {+test("execute keeps strict approval and quarantined output associated with the called action", async () => {const entries: Array<Record<string, unknown>> = [];const ref: ToolContextRef = {current: fakeToolContext(),@@ -2976,24 +2987,24 @@ test("unified sandbox keeps strict approval and quarantined output associated wi},toolApprovalGate: () => false,};- const tool = createAgentTools(ref, { sandboxResources: true }).find((t) => t.name === "sandbox")!;- await call(tool, { action: "start_process", command: "test", purpose: "Run background tests" });- assert.equal(ref.pendingApprovals?.[0]?.approvalKey, "tool:sandbox:start_process");+ const tool = createAgentTools(ref, { sandboxResources: true }).find((t) => t.name === "execute")!;+ await call(tool, { background: true, command: "test", purpose: "Run background tests" });+ assert.equal(ref.pendingApprovals?.[0]?.approvalKey, "tool:execute");assert.deepEqual(entries.map((e) => [e.tool, e.action]),[- ["sandbox", "start_process"],- ["sandbox", "start_process"],+ ["execute", undefined],+ ["execute", undefined],],);ref.toolApprovalGate = () => true;ref.pausedOnApproval = false;ref.screenToolResult = async () => ({ outcome: "quarantine", reason: "untrusted output" });entries.length = 0;- const result = await call(tool, { action: "exec", command: "cat untrusted.txt", purpose: "inspect input" });+ const result = await call(tool, { command: "cat untrusted.txt", purpose: "inspect input" });assert.match(textOut(result), /quarantined/);- assert.equal(entries[1]?.tool, "sandbox");- assert.equal(entries[1]?.action, "exec");+ assert.equal(entries[1]?.tool, "execute");+ assert.equal(entries[1]?.action, undefined);assert.equal(entries[1]?.quarantined, true);});@@ -3004,10 +3015,10 @@ test("strict approval records carry the gated call's redacted arguments", asyncscopeLabel: "personal:U1",toolApprovalGate: () => false,};- const tool = createAgentTools(ref, { sandboxResources: true }).find((t) => t.name === "sandbox")!;- await call(tool, { action: "exec", command: "ls /tmp" });- await call(tool, { action: "exec", command: "curl --token s3cr3t-value https://example.com" });- await call(tool, { action: "exec", command: "env", api_key: "k3y-value" });+ const tool = createAgentTools(ref, { sandboxResources: true }).find((t) => t.name === "execute")!;+ await call(tool, { command: "ls /tmp", purpose: "Run test command" });+ await call(tool, { command: "curl --token s3cr3t-value https://example.com", purpose: "Run test command" });+ await call(tool, { command: "env", api_key: "k3y-value", purpose: "Run test command" });const [a, b, c] = ref.pendingApprovals!;assert.equal(a?.command, b?.command);assert.match(a?.summary ?? "", /ls \/tmp/);@@ -3016,7 +3027,7 @@ test("strict approval records carry the gated call's redacted arguments", asyncassert.doesNotMatch(c?.summary ?? "", /k3y-value/);});-test("unscreened unified output retains the called action in the durable transcript", async () => {+test("unscreened background output retains the called action in the durable transcript", async () => {const entries: Array<Record<string, unknown>> = [];const tool = createAgentTools({@@ -3028,10 +3039,10 @@ test("unscreened unified output retains the called action in the durable transcrscreenToolResult: async () => ({ outcome: "unscreened" }),},{ sandboxResources: true },- ).find((t) => t.name === "sandbox")!;- await call(tool, { action: "read_process", process_id: "job" });- assert.equal(entries[1]?.tool, "sandbox");- assert.equal(entries[1]?.action, "read_process");+ ).find((t) => t.name === "background")!;+ await call(tool, { action: "poll", process_id: "job" });+ assert.equal(entries[1]?.tool, "background");+ assert.equal(entries[1]?.action, "poll");assert.equal(entries[1]?.unscreened, true);});@@ -3055,28 +3066,25 @@ test("sandbox strict approvals remain action-scoped across resource activation",const legacy = createAgentTools(ref).find((t) => t.name === "sandbox")!;assert.doesNotMatch(textOut(await call(legacy, { action: "status", purpose: "Check health" })), /blocked/);assert.equal(checked.at(-1), "sandbox:status");- const unified = createAgentTools(ref, { sandboxResources: true }).find((t) => t.name === "sandbox")!;- for (const action of ["exec", "start_process"]) {+ const execute = createAgentTools(ref, { sandboxResources: true }).find((t) => t.name === "execute")!;+ for (const background of [false, true]) {ref.pausedOnApproval = false;assert.match(- textOut(await call(unified, { action, command: "echo ok", purpose: "Verify the build" })),+ textOut(await call(execute, { background, command: "echo ok", purpose: "Verify the build" })),/needs human approval/,);- assert.equal(ref.pendingApprovals?.at(-1)?.approvalKey, `tool:sandbox:${action}`);- assert.equal(ref.pendingApprovals?.at(-1)?.command, `sandbox ${action}`);+ assert.equal(ref.pendingApprovals?.at(-1)?.approvalKey, "tool:execute");+ assert.equal(ref.pendingApprovals?.at(-1)?.command, "execute");assert.equal(ref.pendingApprovals?.at(-1)?.purpose, "Verify the build");}assert.equal(executions, 0);- grants.add("tool:sandbox:exec");+ grants.add("tool:execute");ref.pausedOnApproval = false;for (let i = 0; i < 2; i++)- assert.doesNotMatch(- textOut(await call(unified, { action: "exec", command: "echo ok", purpose: "Verify the build" })),- /blocked/,- );+ assert.doesNotMatch(textOut(await call(execute, { command: "echo ok", purpose: "Verify the build" })), /blocked/);assert.equal(executions, 2);assert.match(- textOut(await call(unified, { action: "retire", sandbox_id: "box-a", purpose: "Retire finished work" })),+ textOut(await call(legacy, { action: "retire", sandbox_id: "box-a", purpose: "Retire finished work" })),/needs human approval/,);assert.equal(ref.pendingApprovals?.at(-1)?.approvalKey, "tool:sandbox:retire");@@ -3098,8 +3106,8 @@ for (const outcome of ["unscreened", "quarantine"] as const)screenToolResult: async () => ({ outcome }),},{ sandboxResources: true },- ).find((t) => t.name === "sandbox")!;- await call(tool, { action: "exec", command: "exit 7", sandbox_id: "box-a", purpose: "Check failure rendering" });+ ).find((t) => t.name === "execute")!;+ await call(tool, { command: "exit 7", sandbox_id: "box-a", purpose: "Check failure rendering" });const input = entries.find((e) => e.type === "tool_call")!.payload;const output = entries.find((e) => e.type === "tool_result")!.payload;assert.equal(input.sandbox_id, "box-a");@@ -3129,12 +3137,11 @@ test("sandbox call transcripts retain explicit process and lifecycle targets", a},{ sandboxResources: true },).find((t) => t.name === "sandbox")!;- for (const action of ["start_process", "status", "restart", "retire", "set_default"]) {+ for (const action of ["status", "restart", "retire", "set_default"]) {await call(tool, {action,sandbox_id: "box-a",purpose: "Inspect target",- ...(action === "start_process" ? { command: "sleep 1" } : {}),});assert.equal(entries.filter((e) => e.type === "tool_call").at(-1)!.payload.sandbox_id, "box-a");}@@ -3470,13 +3477,13 @@ test("conversation coordinators cannot execute commands through any command toolconst sandbox = tools.find((tool) => tool.name === "sandbox")!;assert.match(textOut(await call(sandbox, { action: "exec", command: "echo forbidden" })),- /unsupported sandbox action/,+ /invalid sandbox arguments/,);assert.match(textOut(await call(sandbox, { action: "start_process", command: "echo forbidden", purpose: "Run background tests" }),),- /unsupported sandbox action/,+ /invalid sandbox arguments/,);assert.ok(tools.some((tool) => tool.name === "subagents"));}@@ -3787,7 +3794,7 @@ test("the retired credential tool is absent and execute accepts credential handlassert.ok(tools.some((tool) => tool.name === "execute"));});-test("sandbox call traces preserve purpose across execution, management, processes, and invalid routes", async () => {+test("command and management call traces preserve purpose", async () => {const calls: Record<string, unknown>[] = [];const ref: ToolContextRef = {current: fakeToolContext(),@@ -3796,18 +3803,20 @@ test("sandbox call traces preserve purpose across execution, management, processif (event.type === "tool_call") calls.push(event.payload as Record<string, unknown>);},};- const sandbox = createAgentTools(ref, { sandboxResources: true }).find((tool) => tool.name === "sandbox")!;- for (const params of [- { action: "exec", command: "pwd" },- { action: "status" },- { action: "start_process", command: "echo ready", purpose: "Run background tests" },- { action: "exec", command: "pwd", scope: "scratch" },- { action: "exec" },- ]) {- await call(sandbox, { ...params, purpose: "Inspect the demo workspace" });- }+ const tools = createAgentTools(ref, { sandboxResources: true });+ for (const [name, params] of [+ ["execute", { command: "pwd" }],+ ["sandbox", { action: "status" }],+ ["execute", { command: "echo ready", background: true }],+ ["execute", { command: "pwd", scope: "scratch" }],+ ["sandbox", { action: "exec" }],+ ] as const)+ await call(+ tools.find((t) => t.name === name),+ { ...params, purpose: "Inspect demo workspace" },+ );assert.equal(calls.length, 5);- assert.ok(calls.every((entry) => entry.purpose === "Inspect the demo workspace"));+ assert.ok(calls.every((entry) => entry.purpose === "Inspect demo workspace"));});const clientTool = (name: string, timeoutMs?: number): ClientToolDeclaration => ({@@ -4003,10 +4012,9 @@ test("command exit codes are data; timeouts and thrown tool errors are failures"},},{ sandboxResources },- ).find((t) => t.name === (sandboxResources ? "sandbox" : "execute"))!;+ ).find((t) => t.name === "execute")!;const run = () =>call(tool, {- ...(sandboxResources ? { action: "exec" } : {}),command: "[ -d dir ]",purpose: "Check directory",});@@ -4059,8 +4067,8 @@ test("thrown execution errors leave pending child messages for the next delivere},};const tools = createAgentTools({ current: context }, { sandboxResources });- const tool = tools.find((t) => t.name === (sandboxResources ? "sandbox" : "execute"))!;- const input = { ...(sandboxResources ? { action: "exec" } : {}), command: "true", purpose: "Check provider" };+ const tool = tools.find((t) => t.name === "execute")!;+ const input = { command: "true", purpose: "Check provider" };await assert.rejects(() => call(tool, input), /provider unavailable/);assert.equal(pending, true);context.execute = async () => ({ stdout: "ok", stderr: "", code: 0, timedOut: false });@@ -4238,8 +4246,8 @@ test("background starts require a nonblank purpose as a repairable tool result",},};for (const [name, action, options] of [- ["background", "start", {}],- ["sandbox", "start_process", { sandboxResources: true }],+ ["execute", true, {}],+ ["execute", true, { sandboxResources: true }],] as const) {const events: Array<Record<string, unknown>> = [];const tool = createAgentTools(@@ -4254,11 +4262,11 @@ test("background starts require a nonblank purpose as a repairable tool result",).find((t) => t.name === name)!;for (const purpose of [undefined, "", " \n "]) {const result = await call(tool, {- action,+ background: action,command: "node server.js",...(purpose === undefined ? {} : { purpose }),});- assert.match(textOut(result), /requires.*purpose/);+ assert.match(textOut(result), /requires.*purpose|invalid execute arguments/);assert.equal(events.at(-1)?.isError, true);}}@@ -4272,8 +4280,141 @@ test("background list labels jobs by purpose and retains commands and legacy fal{ ...legacy, purpose: "Run regression tests" },{ ...legacy, processId: "old-job" },];- const tool = createAgentTools({ current }, { sandboxResources: true }).find((t) => t.name === "sandbox")!;- const result = textOut(await call(tool, { action: "list_processes" }));+ const tool = createAgentTools({ current }, { sandboxResources: true }).find((t) => t.name === "background")!;+ const result = textOut(await call(tool, { action: "list" }));assert.match(result, /Run regression tests\n {2}bg: npm test/);assert.match(result, /old-job[^\n]*bg: npm test/);});++test("background read approval cannot authorize process input or termination", async () => {+ let mutations = 0;+ const ref: ToolContextRef = {+ current: {+ ...fakeToolContext(),+ backgroundWrite: async () => {+ mutations++;+ throw new Error("must not write");+ },+ backgroundStop: async () => {+ mutations++;+ throw new Error("must not stop");+ },+ },+ pendingApprovals: [],+ toolApprovalGate: (id) => id === "background:poll",+ };+ const background = createAgentTools(ref, { sandboxResources: true }).find((t) => t.name === "background")!;+ assert.match(textOut(await call(background, { action: "poll", process_id: "bg-1" })), /more output/);+ for (const action of ["send_input", "stop"]) {+ ref.pausedOnApproval = false;+ assert.match(+ textOut(await call(background, { action, process_id: "bg-1", data: "danger" })),+ /needs human approval/,+ );+ assert.equal(ref.pendingApprovals?.at(-1)?.approvalKey, `tool:background:${action}`);+ }+ assert.equal(mutations, 0);+});++test("invalid execution arguments cannot dispatch commands or retarget process operations", async () => {+ let dispatched = 0;+ const current = {+ ...fakeToolContext(),+ execute: async () => {+ dispatched++;+ throw new Error("unexpected command");+ },+ backgroundStart: async () => {+ dispatched++;+ throw new Error("unexpected start");+ },+ backgroundPoll: async () => {+ dispatched++;+ throw new Error("unexpected poll");+ },+ };+ const tools = createAgentTools({ current }, { sandboxResources: true });+ for (const params of [+ {},+ { command: "pwd", purpose: "Check computer", background: "false" },+ { command: "pwd", purpose: "Check computer", sandbox_id: "" },+ ])+ assert.match(+ textOut(+ await call(+ tools.find((t) => t.name === "execute"),+ params,+ ),+ ),+ /invalid execute arguments/,+ );+ assert.match(+ textOut(+ await call(+ tools.find((t) => t.name === "background"),+ { action: "poll", process_id: "job-a", sandbox_id: "box-b" },+ ),+ ),+ /invalid background arguments/,+ );+ assert.equal(dispatched, 0);+});++test("split sandbox tools reject missing, mistyped, blank and unrelated fields without dispatch", async () => {+ let dispatched = 0;+ const tc = new Proxy(+ { ...fakeToolContext(), sandboxResources: async () => ({ ok: true }) },+ {+ get(target, key, receiver) {+ const value = Reflect.get(target, key, receiver);+ if (typeof value !== "function") return value;+ return () => {+ dispatched++;+ throw new Error("must not dispatch");+ };+ },+ },+ );+ const tools = createAgentTools({ current: tc }, { sandboxResources: true });+ const inputs: Record<string, object[]> = {+ sandbox: [+ { action: "__proto__" },+ { action: "constructor" },+ { action: "retire", sandbox_id: null, purpose: "test" },+ { action: "retire", sandbox_id: " ", purpose: "test" },+ { action: "status", sandbox_id: null, purpose: "test" },+ { action: "create", backend: "modal", command: "ignored", purpose: "test" },+ { action: "create", backend: 42, purpose: "test" },+ { action: "create", backend: " ", purpose: "test" },+ { action: "set_default", purpose: "test" },+ { action: "list", purpose: " " },+ ],+ execute: [+ { command: "", purpose: "test" },+ { command: " ", purpose: "test", background: true },+ { command: "pwd", purpose: " " },+ { command: "pwd", purpose: " ", background: true },+ ],+ background: [+ { action: "poll", process_id: "job", sandbox_id: "other-box" },+ { action: "poll", process_id: " " },+ { action: "send_input", process_id: "job" },+ { action: "stop", process_id: "job", signal: "NOPE" },+ { action: "watch", process_id: "job", since_cursor: -1 },+ { action: "unwatch", monitor_id: null },+ { action: "list", command: "ignored" },+ ],+ };+ for (const [name, cases] of Object.entries(inputs))+ for (const input of cases)+ assert.match(+ textOut(+ await call(+ tools.find((t) => t.name === name),+ input,+ ),+ ),+ /\[error\]/,+ );+ assert.equal(dispatched, 0);+});diff --git a/test/execute-scratch.test.ts b/test/execute-scratch.test.tsindex cda17309f..7dc2612f1 100644--- a/test/execute-scratch.test.ts+++ b/test/execute-scratch.test.ts@@ -88,6 +88,7 @@ test("flag OFF: the execute surface is exactly the legacy one (no scope/durable,const [execute] = createAgentTools({ current: tc });assert.deepEqual(schemaProps(execute!), ["command",+ "background","sandbox_id","purpose","timeout_seconds",@@ -95,7 +96,7 @@ test("flag OFF: the execute surface is exactly the legacy one (no scope/durable,"retrySafe",]);assert.deepEqual(schemaRequired(execute!), ["command", "purpose"]);- await call(execute, { command: "echo hi" });+ await call(execute, { command: "echo hi", purpose: "Run test command" });assert.deepEqual(seen, [{ command: "echo hi", opts: undefined }]);});@@ -105,6 +106,7 @@ test("flag ON: scope defaults to the durable scoped box; scratch is an explicitconst [execute] = createAgentTools(ref, { scratchExec: true });assert.deepEqual(schemaProps(execute!), ["command",+ "background","sandbox_id","purpose","timeout_seconds",@@ -114,20 +116,26 @@ test("flag ON: scope defaults to the durable scoped box; scratch is an explicit"retrySafe",]);- await call(execute, { command: "echo hi" });+ await call(execute, { command: "echo hi", purpose: "Run test command" });assert.deepEqual(seen.at(-1),{ command: "echo hi", opts: undefined },"omitted scope = durable scoped (follow-ups must work)",);- await call(execute, { command: "echo hi", scope: "scratch" });+ await call(execute, { command: "echo hi", scope: "scratch", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts, { scratch: true });- await call(execute, { command: "echo hi", scope: "scoped" });+ await call(execute, { command: "echo hi", scope: "scoped", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts, undefined, "a scoped run carries no scratch opt (today's path)");- await call(execute, { command: "echo hi", scope: "scoped", durable: true, timeout_seconds: 9 });+ await call(execute, {+ command: "echo hi",+ scope: "scoped",+ durable: true,+ timeout_seconds: 9,+ purpose: "Run test command",+ });assert.deepEqual(seen.at(-1)!.opts, { timeoutSeconds: 9 });});@@ -135,10 +143,14 @@ test("flag ON: unsupported scope/durable pairings return a crisp [error] withoutconst { tc, seen } = sinkToolContext();const [execute] = createAgentTools({ current: tc }, { scratchExec: true });- const e1 = textOf(await call(execute, { command: "echo hi", scope: "scratch", durable: true }));+ const e1 = textOf(+ await call(execute, { command: "echo hi", scope: "scratch", durable: true, purpose: "Run test command" }),+ );assert.match(e1, /\[error\] a scratch box cannot be made durable yet/);- const e2 = textOf(await call(execute, { command: "echo hi", scope: "scoped", durable: false }));+ const e2 = textOf(+ await call(execute, { command: "echo hi", scope: "scoped", durable: false, purpose: "Run test command" }),+ );assert.match(e2, /\[error\] the scoped computer is always durable today/);assert.equal(seen.length, 0, "invalid pairings never reach the sandbox");@@ -155,8 +167,8 @@ test("flag ON: the tool_call/tool_result entries record which box ran the commanscopeLabel: scopeId("personal", "U1"),};const [execute] = createAgentTools(ref, { scratchExec: true });- await call(execute, { command: "echo hi", scope: "scratch" });- await call(execute, { command: "echo hi" });+ await call(execute, { command: "echo hi", scope: "scratch", purpose: "Run test command" });+ await call(execute, { command: "echo hi", purpose: "Run test command" });assert.deepEqual(emitted.map((e) => `${e.type}:${e.payload.scope}`),["tool_call:scratch", "tool_result:scratch", "tool_call:scoped", "tool_result:scoped"],@@ -302,6 +314,7 @@ test("execute schema lists exact command credential handles", async () => {const [execute] = createAgentTools({ current: tc }, { commandCredentialHandles: ["kc_github12345"] });assert.deepEqual(schemaProps(execute!), ["command",+ "background","sandbox_id","purpose","timeout_seconds",@@ -309,7 +322,7 @@ test("execute schema lists exact command credential handles", async () => {"retrySafe",]);- await call(execute, { command: "gh api user", credentials: ["kc_github12345"] });+ await call(execute, { command: "gh api user", credentials: ["kc_github12345"], purpose: "Run test command" });assert.deepEqual(seen.at(-1)?.opts, { credentials: ["kc_github12345"] });});@@ -339,7 +352,11 @@ test("execute masks credential output before model delivery, screening, and tran},{ commandCredentialHandles: ["kc_test123456"] },);- const result = await call(execute, { command: "diagnose", credentials: ["kc_test123456"] });+ const result = await call(execute, {+ command: "diagnose",+ credentials: ["kc_test123456"],+ purpose: "Run test command",+ });const all = JSON.stringify({ result, emitted, screened });assert.ok(!all.includes(secret));assert.ok(all.includes("useful diagnostics"));@@ -410,7 +427,7 @@ test("execute records a safe provider-error result for native replay", async ()entries.push(entry);},});- const result = await call(execute, { command: "diagnose" });+ const result = await call(execute, { command: "diagnose", purpose: "Run test command" });assert.match(textOf(result), /<redacted:credential>/);assert.ok(!JSON.stringify({ result, entries }).includes(secret));assert.ok(entries.some((entry) => (entry as { type?: string }).type === "tool_result"));diff --git a/test/live-slack-sandbox-providers.test.ts b/test/live-slack-sandbox-providers.test.tsindex 9bf5081d0..5a56c7a20 100644--- a/test/live-slack-sandbox-providers.test.ts+++ b/test/live-slack-sandbox-providers.test.ts@@ -10,10 +10,10 @@ import type { Ctx } from "./live-slack/harness.ts";function evidence(sandboxId = "box", stdout = "nonce\n"): unknown[] {return [- { type: "tool_call", payload: { tool: "sandbox", action: "exec", sandbox_id: sandboxId, callId: "call" } },+ { type: "tool_call", payload: { tool: "execute", sandbox_id: sandboxId, callId: "call" } },{type: "tool_result",- payload: { tool: "sandbox", action: "exec", callId: "call", isError: false, code: 0, timedOut: false, stdout },+ payload: { tool: "execute", callId: "call", isError: false, code: 0, timedOut: false, stdout },},];}@@ -22,7 +22,7 @@ test("provider execution requires correlated success on the exact sandbox", () =assert.doesNotThrow(() => assertSandboxExecution(evidence(), "box", "nonce\n"));for (const patch of [{ tool: "read" },- { action: "start_process" },+ { background: true },{ callId: "unrelated" },{ isError: true },{ code: 1 },@@ -40,7 +40,7 @@ test("provider execution requires correlated success on the exact sandbox", () =test("projected sandbox results require exact successful execution evidence", () => {const entries = evidence() as Array<{ type: string; payload: Record<string, unknown> }>;- entries[1]!.payload = { tool: "sandbox", callId: "call", isError: false, result: "nonce\n\n[exit 0]" };+ entries[1]!.payload = { tool: "execute", callId: "call", isError: false, result: "nonce\n\n[exit 0]" };assert.doesNotThrow(() => assertSandboxExecution(entries, "box", "nonce\n"));for (const patch of [{ result: "nonce\n" },@@ -52,7 +52,7 @@ test("projected sandbox results require exact successful execution evidence", (){ callId: "unrelated" },{ code: 1 },{ timedOut: true },- { action: "start_process" },+ { background: true },]) {const changed = [entries[0], { ...entries[1], payload: { ...entries[1]!.payload, ...patch } }];assert.throws(() => assertSandboxExecution(changed, "box", "nonce\n"));diff --git a/test/live-slack/README.md b/test/live-slack/README.mdindex e7c2d21f9..014a68387 100644--- a/test/live-slack/README.md+++ b/test/live-slack/README.md@@ -205,7 +205,7 @@ self-explanations; read the transcript.## Sandbox-provider release qualificationSet `LIVE_E2E_SANDBOX_PROVIDERS=all` with `LIVE_E2E_GATE=1` to require a real-agent `sandbox exec` on every implemented provider: Sprites, AWS, local Docker,+agent `execute` on every implemented provider: Sprites, AWS, local Docker,Smolmachines, E2B, Modal, Porter, and Agent37. These eight scenarios run concurrentlyin their own lane alongside the selected catalog. The source type requires acoverage entry when a provider is added. Missing providers, skips, retries,diff --git a/test/live-slack/local-provider.ts b/test/live-slack/local-provider.tsindex 2759aa31b..ddf6964a2 100644--- a/test/live-slack/local-provider.ts+++ b/test/live-slack/local-provider.ts@@ -49,7 +49,7 @@ async function main(): Promise<void> {surface: "qualification",actor: { externalId: actorId },conversation: { kind: "dm", threadRef: `qualification:${randomUUID()}` },- text: `Use sandbox action exec with sandbox_id ${sandbox.id} to run exactly: printf '%s%s\\n' '${left}' '${right}'. Set timeout_seconds to 30. Report the result.`,+ text: `Use execute with sandbox_id ${sandbox.id} to run exactly: printf '%s%s\\n' '${left}' '${right}'. Set timeout_seconds to 30. Report the result.`,});assert.equal(result.status, "ok", result.reason ?? result.reply);assert.ok(result.sessionId);diff --git a/test/live-slack/scenarios-sandbox-providers.ts b/test/live-slack/scenarios-sandbox-providers.tsindex 8e7183c90..a4ec2f0f3 100644--- a/test/live-slack/scenarios-sandbox-providers.ts+++ b/test/live-slack/scenarios-sandbox-providers.ts@@ -25,8 +25,8 @@ export function assertSandboxExecution(entries: readonly unknown[], sandboxId: sfor (const entry of entries) {if (!isObj(entry) || !isObj(entry.payload)) continue;const p = entry.payload;- if (p.tool !== "sandbox" || typeof p.callId !== "string") continue;- if (entry.type === "tool_call" && p.action === "exec" && p.sandbox_id === sandboxId) {+ if (p.tool !== "execute" || p.background === true || typeof p.callId !== "string") continue;+ if (entry.type === "tool_call" && p.background !== true && p.sandbox_id === sandboxId) {calls.add(p.callId);continue;}@@ -34,13 +34,13 @@ export function assertSandboxExecution(entries: readonly unknown[], sandboxId: sconst structured = "code" in p || "timedOut" in p || "stdout" in p || "action" in p;if (structured- ? p.action === "exec" && p.code === 0 && p.timedOut === false && p.stdout === stdout+ ? p.background !== true && p.code === 0 && p.timedOut === false && p.stdout === stdout: p.result === `${stdout}\n[exit 0]`)executed = true;}- assert.ok(calls.size, `no sandbox exec call targeted ${sandboxId}`);- assert.ok(executed, `no successful sandbox exec result with exact stdout on ${sandboxId}`);+ assert.ok(calls.size, `no execute call targeted ${sandboxId}`);+ assert.ok(executed, `no successful execute result with exact stdout on ${sandboxId}`);}export const sandboxProviderScenarios: Scenario[] = sandboxProviders.map((backend) => ({@@ -68,7 +68,7 @@ export const sandboxProviderScenarios: Scenario[] = sandboxProviders.map((backenconst left = randomUUID();const right = randomUUID();const root = await ch.mention(- `Use the sandbox tool with action exec and sandbox_id ${sandbox.id} to run exactly this command: printf '%s%s\\n' '${left}' '${right}'. Set timeout_seconds to 30. Report the result. Do not use another sandbox or a background process.`,+ `Use the execute tool with sandbox_id ${sandbox.id} to run exactly this command: printf '%s%s\\n' '${left}' '${right}'. Set timeout_seconds to 30. Report the result. Do not use another sandbox or a background process.`,);await ch.waitForBotReply(root, { timeoutMs: 3 * 60_000 });const session = await core.findSessionByThread(ch.id, root);diff --git a/test/opencode-harness.test.ts b/test/opencode-harness.test.tsindex 3f83a6557..09b6f1a73 100644--- a/test/opencode-harness.test.ts+++ b/test/opencode-harness.test.ts@@ -465,8 +465,7 @@ test("OpenCode advertises aliases only for tools available on the turn", async (await harness.turns.runTurn(turnInput([], []));const { systemPrompt } = JSON.parse(readFileSync(captured, "utf8")) as { systemPrompt: string };assert.doesNotMatch(systemPrompt, /workspace_read|workspace_write/);- if (sandboxResources) assert.doesNotMatch(systemPrompt, /workspace_execute/);- else assert.match(systemPrompt, /workspace_execute is execute/);+ assert.match(systemPrompt, /workspace_execute is execute/);}});diff --git a/test/scope-reach.test.ts b/test/scope-reach.test.tsindex 6f6f49e2d..0b982edd0 100644--- a/test/scope-reach.test.ts+++ b/test/scope-reach.test.ts@@ -244,6 +244,7 @@ test("reachExec ON (no scratch): scope is a free string; a room routes to reachTconst [execute] = createAgentTools({ current: tc }, { reachExec: true });assert.deepEqual(schemaProps(execute!), ["command",+ "background","sandbox_id","purpose","timeout_seconds",@@ -251,13 +252,13 @@ test("reachExec ON (no scratch): scope is a free string; a room routes to reachT"scope","retrySafe",]);- await call(execute, { command: "cat x", scope: "#project-alpha" });+ await call(execute, { command: "cat x", scope: "#project-alpha", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts, { reachTarget: "#project-alpha" });- await call(execute, { command: "echo hi" });+ await call(execute, { command: "echo hi", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts, undefined, "omitted scope = the scoped box");- await call(execute, { command: "echo hi", scope: "scoped" });+ await call(execute, { command: "echo hi", scope: "scoped", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts, undefined);- const err = textOf(await call(execute, { command: "x", scope: "scratch" }));+ const err = textOf(await call(execute, { command: "x", scope: "scratch", purpose: "Run test command" }));assert.match(err, /scratch box isn't available here/);});@@ -266,6 +267,7 @@ test("reachExec ON + scratchExec ON: scope accepts scoped, scratch, AND a room",const [execute] = createAgentTools({ current: tc }, { reachExec: true, scratchExec: true });assert.deepEqual(schemaProps(execute!), ["command",+ "background","sandbox_id","purpose","timeout_seconds",@@ -274,24 +276,24 @@ test("reachExec ON + scratchExec ON: scope accepts scoped, scratch, AND a room","durable","retrySafe",]);- await call(execute, { command: "x", scope: "scratch" });+ await call(execute, { command: "x", scope: "scratch", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts, { scratch: true });- await call(execute, { command: "x", scope: "#ops" });+ await call(execute, { command: "x", scope: "#ops", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts, { reachTarget: "#ops" });- await call(execute, { command: "x" });+ await call(execute, { command: "x", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts, undefined);- const e = textOf(await call(execute, { command: "x", scope: "scratch", durable: true }));+ const e = textOf(await call(execute, { command: "x", scope: "scratch", durable: true, purpose: "Run test command" }));assert.match(e, /scratch box cannot be made durable/);});test("reachExec ON: the scoped/scratch keywords match case-insensitively, never routed as a room", async () => {const { tc, seen } = sinkToolContext();const [execute] = createAgentTools({ current: tc }, { reachExec: true, scratchExec: true });- await call(execute, { command: "x", scope: "Scoped" });+ await call(execute, { command: "x", scope: "Scoped", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts, undefined, '"Scoped" is the scoped box, not a reach target');- await call(execute, { command: "x", scope: "SCRATCH" });+ await call(execute, { command: "x", scope: "SCRATCH", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts, { scratch: true }, '"SCRATCH" is the scratch box, not a reach target');- await call(execute, { command: "x", scope: "#project-alpha" });+ await call(execute, { command: "x", scope: "#project-alpha", purpose: "Run test command" });assert.deepEqual(seen.at(-1)!.opts,{ reachTarget: "#project-alpha" },@@ -318,7 +320,7 @@ test("Trap 1: a reach result prefixes provenance and keeps the SESSION scope laborgScopeId: scopeId("org", "default-org"),};const [execute] = createAgentTools(ref, { reachExec: true });- const r = await call(execute, { command: "cat x", scope: "#project-alpha" });+ const r = await call(execute, { command: "cat x", scope: "#project-alpha", purpose: "Run test command" });assert.match(textOf(r), /\[ran on #project-alpha's computer\]/);const toolResult = emitted.find((e) => e.type === "tool_result")!;assert.equal(diff --git a/test/screening-release.test.ts b/test/screening-release.test.tsindex 7d28a9497..68e6d46aa 100644--- a/test/screening-release.test.ts+++ b/test/screening-release.test.ts@@ -58,7 +58,9 @@ mock.module("../src/harness/mock-harness.ts", {) => Promise<{ content: Array<{ text?: string }> }>;const result = await execute("fixture-call",- sharedRead ? { action: "read", path: "private.txt" } : { command: "printf SCREENING_FIXTURE_BLOCK" },+ sharedRead+ ? { action: "read", path: "private.txt" }+ : { command: "printf SCREENING_FIXTURE_BLOCK", purpose: "Check output screening" },);const reply = result.content.map((part) => part.text ?? "").join("\n");await turn.emit({ type: "assistant", payload: { text: reply }, scopeLabel: turn.scopeLabel });