diff --git a/.changeset/readonly-exec.md b/.changeset/readonly-exec.md new file mode 100644 index 00000000..622f8aad --- /dev/null +++ b/.changeset/readonly-exec.md @@ -0,0 +1,5 @@ +--- +"@cloudflare/computer": patch +--- + +A `readonly: true` tool set offers `exec` on backends that can't change the Workspace, such as a `CodemodeBackend` with `access: "read"`, which `runtime.backends()` now reports as `access`; see [`exec`](https://github.com/cloudflare/computer/blob/main/docs/09_tool_interface.md#exec). diff --git a/docs/05_runtime_interface.md b/docs/05_runtime_interface.md index 5401b63f..d7f6aa8f 100644 --- a/docs/05_runtime_interface.md +++ b/docs/05_runtime_interface.md @@ -140,6 +140,7 @@ workspace.runtime.backends(); - `protocol` says what `exec` source means there: a shell command (`"command"`) or module source (`"module"`). - `callable` says whether the backend takes structured `input` and returns a `value`. - `description`, when present, is what the backend tells a model about itself. `CodemodeBackend` lists its source language and every module code can import, and `WorkerShellBackend` and `ContainerBackend` describe what they can run. The `exec` tool builds its description from these. +- `access` is `"read"` when the backend's execs can't change the Workspace, such as a `CodemodeBackend` with `access: "read"`, and `"read-write"` otherwise. A read-only tool set offers `exec` only on backends with `"read"`. The list is fixed when the Workspace is constructed. A client from `getWorkspace()` takes a copy of it when the client loads, so once awaited the answer is the same locally and over RPC. Before then, the client reports no backends. diff --git a/docs/09_tool_interface.md b/docs/09_tool_interface.md index 6f410707..b7e1bc21 100644 --- a/docs/09_tool_interface.md +++ b/docs/09_tool_interface.md @@ -182,7 +182,7 @@ createAITools({ | Option | Default | Notes | | --- | --- | --- | | `workspace` | required | A `Workspace` or structural equivalent. | -| `readonly` | `false` | Omit `write`, `edit`, `delete`, `exec`, and `publish`. Search remains available. | +| `readonly` | `false` | Omit `write`, `edit`, `delete`, and `publish`, and offer `exec` only on backends that can't change the Workspace. Search remains available. | | `root` | none | Confine the file tools and `publish` to one directory. See [Root](#root). | | `assets` | `true` | Set to `false` to omit `publish`. | | `read` | default caps | Options passed to `createReadTool`. | @@ -418,7 +418,7 @@ With `detach`, the tool returns once a call in the run waits for an answer, and, The tool doesn't deliver the outcome itself. The backend's `onDetachedExit` hears it, and the app finds the conversation through the run's `metadata` and gives the agent a new message with it. `detach` needs a runtime with `pending()` and `detachExec()`, which a `Workspace`, `workspace.stub()` and a `getWorkspace()` client have. -Wire this tool carefully: it executes arbitrary shell commands inside the configured backend. Treat its output as untrusted text when including it in later model input. Pass `exec: { backends: {} }` or `readonly: true` when command execution is not part of the agent's job, and list backends explicitly when the Workspace has one the model should not use directly. +Wire this tool carefully: it executes arbitrary shell commands inside the configured backend. Treat its output as untrusted text when including it in later model input. Pass `exec: { backends: {} }` when command execution is not part of the agent's job, and list backends explicitly when the Workspace has one the model should not use directly. A `readonly: true` set offers `exec` only on backends whose `runtime.backends()` entry has `access: "read"`, such as a `CodemodeBackend` built with `access: "read"`, whose code can read the Workspace but not change it; with none, it has no `exec`. Its `exec` saves nothing either: long output and large return values come back cut, with no file, because the runtime writes those files from the host, past the backend's guard. `createExecTool({ saveOutput: false })` does the same for any exec tool. A read-only set keeps `exec.detach` only if a backend it kept can detach. ## `publish` diff --git a/packages/computer/src/backends/codemode/codemode.test.ts b/packages/computer/src/backends/codemode/codemode.test.ts index f1a63559..2191106b 100644 --- a/packages/computer/src/backends/codemode/codemode.test.ts +++ b/packages/computer/src/backends/codemode/codemode.test.ts @@ -51,6 +51,22 @@ async function evaluateResult( } describe("CodemodeBackend", () => { + it("reports its access through runtime.backends()", () => { + const loader = { load: vi.fn() }; + const workspace = new Workspace({ + storage: new SQLiteTestStorage(), + backends: [ + new CodemodeBackend({ id: "reads", loader, access: "read" }), + new CodemodeBackend({ id: "writes", loader }), + ], + }); + + expect(workspace.runtime.backends().map(({ id, access }) => ({ id, access }))).toEqual([ + { id: "reads", access: "read" }, + { id: "writes", access: "read-write" }, + ]); + }); + it("blocks ambient egress by default", async () => { const load = vi.fn(() => ({ getEntrypoint() { diff --git a/packages/computer/src/backends/codemode/codemode.ts b/packages/computer/src/backends/codemode/codemode.ts index c428f68c..caa78714 100644 --- a/packages/computer/src/backends/codemode/codemode.ts +++ b/packages/computer/src/backends/codemode/codemode.ts @@ -355,6 +355,7 @@ export class CodemodeBackend implements WorkspaceModuleBackend { readonly callable = true; // Execs detach only when their exits have somewhere to go. readonly detachable: boolean; + readonly access: WorkspaceRuntimeAccess; readonly id: string; readonly #options: ResolvedCodemodeBackendOptions; readonly #header: string; @@ -362,6 +363,7 @@ export class CodemodeBackend implements WorkspaceModuleBackend { constructor(options: CodemodeBackendOptions) { this.id = options.id ?? "codemode"; this.detachable = options.onDetachedExit !== undefined; + this.access = options.access ?? "read-write"; if (options.egress !== undefined && options.globalOutbound !== undefined) { throw new Error("CodemodeBackend cannot use globalOutbound together with egress."); } @@ -435,7 +437,7 @@ export class CodemodeBackend implements WorkspaceModuleBackend { modules: parseModules(options.modules ?? {}, scheme), scheme, root: options.root ?? WORKSPACE_ROOT, - access: options.access ?? "read-write", + access: this.access, defaultTimeoutMs, maxTimeoutMs, maxCpuMs, diff --git a/packages/computer/src/runtime/runtime.ts b/packages/computer/src/runtime/runtime.ts index b20494cc..2e5fd19a 100644 --- a/packages/computer/src/runtime/runtime.ts +++ b/packages/computer/src/runtime/runtime.ts @@ -8,6 +8,7 @@ import { type ModuleExecutionEnvelope, type WorkspaceModuleBackendHandle, type WorkspaceRegisteredBackend, + type WorkspaceRuntimeAccess, type WorkspaceRuntimeDisposeOptions, type WorkspaceRuntimeEvent, type WorkspaceRuntimeExecHandle, @@ -59,6 +60,12 @@ export interface WorkspaceBackendInfo { * can't. */ readonly detachable?: boolean; + /** + * What its execs may do to the Workspace: `"read"` when they can't + * change it, such as a `CodemodeBackend` with `access: "read"`. + * Missing means they can. + */ + readonly access?: WorkspaceRuntimeAccess; } /** Where `saveResult` put a value, or why it could not. */ @@ -92,6 +99,7 @@ export class WorkspaceRuntime { callable: backend.callable === true, ...(backend.description === undefined ? {} : { description: backend.description }), detachable: this.#detachable(backend), + access: isModuleBackend(backend) ? (backend.access ?? "read-write") : "read-write", })); } diff --git a/packages/computer/src/runtime/types.ts b/packages/computer/src/runtime/types.ts index 731919e6..48d21123 100644 --- a/packages/computer/src/runtime/types.ts +++ b/packages/computer/src/runtime/types.ts @@ -457,6 +457,11 @@ export interface WorkspaceModuleBackend { * backend supports it and has somewhere to send their exits. */ readonly detachable?: boolean; + /** + * What its execs may do to the Workspace: `"read"` when they can't + * change it. Missing means they can. + */ + readonly access?: WorkspaceRuntimeAccess; connect(host: WorkspaceModuleBackendHost): Promise; } diff --git a/packages/computer/src/tools/ai-sdk/index.test.ts b/packages/computer/src/tools/ai-sdk/index.test.ts index b4e317fa..c2d55ef0 100644 --- a/packages/computer/src/tools/ai-sdk/index.test.ts +++ b/packages/computer/src/tools/ai-sdk/index.test.ts @@ -356,6 +356,17 @@ describe("createAITools filesystem tools", () => { expect(Object.keys(tools).sort()).toEqual(["find", "grep", "ls", "read"]); }); + it("keeps exec when readonly and a backend only reads", () => { + const workspace = makeWorkspace(); + (workspace.runtime as unknown as Record).backends = () => [ + { id: "codemode-readonly", protocol: "module", callable: true, access: "read" }, + ]; + + const tools = createAITools({ workspace, readonly: true }); + + expect(Object.keys(tools).sort()).toEqual(["exec", "find", "grep", "ls", "read"]); + }); + it("reads, lists, writes, and edits workspace files", async () => { const workspace = makeWorkspace(); const tools = createAITools({ workspace }); diff --git a/packages/computer/src/tools/ai-sdk/index.ts b/packages/computer/src/tools/ai-sdk/index.ts index 96ea3ddb..8cbcda48 100644 --- a/packages/computer/src/tools/ai-sdk/index.ts +++ b/packages/computer/src/tools/ai-sdk/index.ts @@ -32,9 +32,10 @@ export { /** * Build the AI SDK tool set for a Workspace: `read`, `ls`, `find`, and - * `grep`, plus `write`, `edit`, `delete`, `exec`, and `publish` unless - * the set is read-only. `exec` offers every backend the Workspace has - * unless `exec.backends` lists them. + * `grep`, plus `write`, `edit`, `delete`, and `publish` unless the set + * is read-only, and `exec`. `exec` offers every backend the Workspace + * has unless `exec.backends` lists them; a read-only set offers it only + * on backends that can't change the Workspace. * * @param options - The Workspace and per-tool options. * @returns An AI SDK `ToolSet` for `generateText`, `streamText`, or an agent's `getTools()`. @@ -50,11 +51,11 @@ export function createAITools(options: CreateAIToolsOptions): ToolSet { grep: createGrepTool({ workspace }), }; - if (resolved.readonly) return tools; - - tools.write = createWriteTool(resolved.write); - tools.edit = createEditTool(resolved.edit); - tools.delete = createDeleteTool(resolved.delete); + if (!resolved.readonly) { + tools.write = createWriteTool(resolved.write); + tools.edit = createEditTool(resolved.edit); + tools.delete = createDeleteTool(resolved.delete); + } if (resolved.exec !== undefined) { tools.exec = createExecTool(resolved.exec); diff --git a/packages/computer/src/tools/common/exec.test.ts b/packages/computer/src/tools/common/exec.test.ts index 26317c28..4145764e 100644 --- a/packages/computer/src/tools/common/exec.test.ts +++ b/packages/computer/src/tools/common/exec.test.ts @@ -94,6 +94,39 @@ describe("defineExec metadata", () => { }); }); +describe("defineExec saveOutput", () => { + it("saves nothing to the Workspace when turned off", async () => { + const outputs: unknown[] = []; + const saved: string[] = []; + const workspace: ExecWorkspaceLike = { + runtime: { + async exec(_command, options) { + outputs.push(options.output); + return { + result: async () => ({ exitCode: 0, stdout: "", stderr: "", value: "x".repeat(200) }), + }; + }, + async saveResult(name) { + saved.push(name); + return { saved: true, path: `/out/${name}` }; + }, + backends: () => [{ id: "js", protocol: "module", callable: true }], + }, + }; + const exec = defineExec({ workspace, maxBytes: 100, saveOutput: false }); + + const output = await last(exec.execute({ command: "x" }, { toolCallId: "c1" })); + + expect(exec.description).toContain("the rest isn't kept"); + expect(exec.description).not.toContain("saved to a file"); + expect(outputs).toEqual([false]); + expect(saved).toEqual([]); + expect(output).toMatchObject({ + result: { truncated: true, note: expect.stringContaining("not saved") }, + }); + }); +}); + describe("defineExec result bound", () => { it("saves a return value past the output limit to a file", async () => { const written: Array<{ path: string; size: number }> = []; diff --git a/packages/computer/src/tools/common/exec.ts b/packages/computer/src/tools/common/exec.ts index 4888ceab..4ca64222 100644 --- a/packages/computer/src/tools/common/exec.ts +++ b/packages/computer/src/tools/common/exec.ts @@ -69,7 +69,7 @@ export interface ExecWorkspaceLike { env?: Record; input?: WorkspaceRuntimeValue; metadata?: Record; - output?: { maxBytes: number; maxLines: number }; + output?: { maxBytes: number; maxLines: number } | false; }, ): Promise; // Calls waiting in ctx.interrupt(), by execution id, and noting @@ -156,6 +156,13 @@ export interface ExecToolOptions { * `onDetachedExit`. */ detach?: ExecDetachOptions; + /** + * Save output too long to show, and return values too large to show, + * to files in the Workspace, which the reply names. Defaults to + * `true`. With `false` the model sees them cut, and nothing is + * written: a read-only tool set turns it off. + */ + saveOutput?: boolean; // Clock backing the running-snapshot coalescing floor. Defaults to // Date.now; injectable so tests can drive the interval deterministically. now?: () => number; @@ -238,6 +245,7 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { "createExecTool", ); const now = options.now ?? Date.now; + const saveOutput = options.saveOutput ?? true; const runtime = options.workspace.runtime; const detach = options.detach; const afterMs = typeof detach === "object" ? detach.afterMs : undefined; @@ -279,7 +287,7 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { } } const description = [ - describeTool(backends, limits), + describeTool(backends, limits, saveOutput), detach === undefined ? "" : detachHint(afterMs, detachable.size === backends.length ? undefined : [...detachable]), @@ -424,7 +432,7 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { ...(metadata === undefined ? {} : { metadata }), // The runtime cuts and saves by the same limits the tool // shows, so whatever the model does not see is in the file. - output: limits, + output: saveOutput ? limits : false, }); } catch (err) { yield { ...base, error: errorMessage(err) }; @@ -467,6 +475,9 @@ export function defineExec(options: ExecToolOptions): ExecDefinition { const preview = decoder.decode(bytes.slice(0, Math.min(limits.maxBytes, 8192))); const shown = { truncated: true, totalBytes: bytes.length, preview }; const runtime = options.workspace.runtime; + if (!saveOutput) { + return { ...shown, note: "Full result was not saved: this tool doesn't write files." }; + } if (runtime.saveResult === undefined) { return { ...shown, note: "Full result was not saved: the workspace cannot save output." }; } @@ -651,12 +662,19 @@ function detachHint( const FILE_TOOLS_HINT = "Prefer the dedicated read, write, and edit tools for file operations."; // How the reply cuts long output, and where the rest goes. -function outputHint(limits: OutputLimits): string { - return `Each of stdout and stderr is cut to its last ${limits.maxLines} lines or ${formatSize(limits.maxBytes)}, whichever is hit first; when it is, the full output is saved to a file the reply names, which the read and grep tools can open.`; +function outputHint(limits: OutputLimits, saved: boolean): string { + const cut = `Each of stdout and stderr is cut to its last ${limits.maxLines} lines or ${formatSize(limits.maxBytes)}, whichever is hit first`; + return saved + ? `${cut}; when it is, the full output is saved to a file the reply names, which the read and grep tools can open.` + : `${cut}, and the rest isn't kept, so print only what you need.`; } const SHELL_HINT = "Use for builds, test runs, typechecks, formatters, and git plumbing."; -const CALLABLE_HINT = - "Pass an `input` object to hand the module structured values, and read its return value back from the `result` field. A return value over the output limit is saved to a file and `result` holds its path and a preview, so write large data to a file instead of returning it."; +const callableHint = (saved: boolean) => + `Pass an \`input\` object to hand the module structured values, and read its return value back from the \`result\` field. ${ + saved + ? "A return value over the output limit is saved to a file and `result` holds its path and a preview, so write large data to a file instead of returning it." + : "A return value over the output limit comes back as a preview only, so return only what you need." + }`; interface DescribedBackend { readonly id: string; @@ -666,8 +684,12 @@ interface DescribedBackend { // With one backend the description is about what it does. With several // it lists them and explains how to choose. -function describeTool(backends: readonly DescribedBackend[], limits: OutputLimits): string { - const output = outputHint(limits); +function describeTool( + backends: readonly DescribedBackend[], + limits: OutputLimits, + saved: boolean, +): string { + const output = outputHint(limits, saved); const [only, ...others] = backends; if (only !== undefined && others.length === 0) { return only.callable @@ -676,7 +698,7 @@ function describeTool(backends: readonly DescribedBackend[], limits: OutputLimit "", only.text, "", - CALLABLE_HINT, + callableHint(saved), `${FILE_TOOLS_HINT} ${output}`, ].join("\n") : [ @@ -703,7 +725,7 @@ function describeTool(backends: readonly DescribedBackend[], limits: OutputLimit ? [] : [ "", - `Callable backends (${callable.join(", ")}) run \`command\` as module source rather than a shell command. ${CALLABLE_HINT} Other backends reject \`input\`.`, + `Callable backends (${callable.join(", ")}) run \`command\` as module source rather than a shell command. ${callableHint(saved)} Other backends reject \`input\`.`, ]), ].join("\n"); } diff --git a/packages/computer/src/tools/common/options.ts b/packages/computer/src/tools/common/options.ts index f55ac8a5..dee303b9 100644 --- a/packages/computer/src/tools/common/options.ts +++ b/packages/computer/src/tools/common/options.ts @@ -15,7 +15,11 @@ import type { PublishWorkspaceLike } from "./publish"; /** Options every tool set takes: `createAITools`, `createPiTools`, and `createTanStackTools`. */ export interface CreateToolsOptions { workspace: FileWorkspaceLike & Partial & Partial; - /** Omit `write`, `edit`, `delete`, `exec`, and `publish`. */ + /** + * Omit `write`, `edit`, `delete`, and `publish`, and offer `exec` only + * on backends that can't change the Workspace, such as a + * `CodemodeBackend` with `access: "read"`. + */ readonly?: boolean; root?: string; /** Set `false` to omit `publish` even when assets are configured. */ @@ -74,7 +78,10 @@ export interface ResolvedToolOptions { write: WriteToolOptions; edit: EditToolOptions; delete: { store: WorkspaceFileStore }; - /** Absent when the set is read-only, the Workspace has no runtime, or no backend is selected. */ + /** + * Absent when the Workspace has no runtime or no backend is selected, + * which for a read-only set means none that only reads. + */ exec?: ExecToolOptions; publish: boolean; readonly: boolean; @@ -95,7 +102,7 @@ export function resolveToolOptions(options: CreateToolsOptions): ResolvedToolOpt write: { store, ...options.write }, edit: { store, ...options.edit }, delete: { store }, - exec: readonly ? undefined : execOptions(options), + exec: execOptions(options, readonly), publish: !readonly && options.assets !== false && workspace.assets !== undefined, readonly, workspace, @@ -122,22 +129,48 @@ function checkExec(exec: ExecToolSetOptions | undefined): void { } // Turn `exec`, or the deprecated `shell`, into exec tool options. -function execOptions(options: CreateToolsOptions): ExecToolOptions | undefined { +function execOptions(options: CreateToolsOptions, readonly: boolean): ExecToolOptions | undefined { const runtime = options.workspace.runtime; if (runtime === undefined) return undefined; const selected = selectExec(options, runtime); - if (Object.keys(selected.backends).length === 0) return undefined; - const { output, metadata, detach } = options.exec ?? {}; + const backends = readonly ? readOnlyBackends(selected.backends, runtime) : selected.backends; + if (Object.keys(backends).length === 0) return undefined; + const { output, metadata } = options.exec ?? {}; + // A read-only set keeps `detach` only if a backend it kept can + // detach, as it would have left out exec, detach and all, before. + const detach = readonly && !canDetach(backends, runtime) ? undefined : options.exec?.detach; return { workspace: { runtime }, ...selected, + backends, ...(output?.maxBytes === undefined ? {} : { maxBytes: output.maxBytes }), ...(output?.maxLines === undefined ? {} : { maxLines: output.maxLines }), ...(metadata === undefined ? {} : { metadata }), ...(detach === undefined ? {} : { detach }), + // The runtime writes saved output from the host, past the backend's + // read-only guard, so a read-only set saves none. + ...(readonly ? { saveOutput: false } : {}), }; } +function canDetach(backends: ExecBackends, runtime: ExecWorkspaceLike["runtime"]): boolean { + return (runtime.backends?.() ?? []).some( + (info) => info.detachable === true && info.id in backends, + ); +} + +// A read-only set's exec runs only on backends that can't change the +// Workspace. The backend enforces it, so exec can't write either. +function readOnlyBackends( + backends: ExecBackends, + runtime: ExecWorkspaceLike["runtime"], +): ExecBackends { + const reading = new Set( + (runtime.backends?.() ?? []).filter((info) => info.access === "read").map((info) => info.id), + ); + return Object.fromEntries(Object.entries(backends).filter(([id]) => reading.has(id))); +} + function selectExec( options: CreateToolsOptions, runtime: ExecWorkspaceLike["runtime"], diff --git a/packages/computer/src/tools/pi-ai/index.test.ts b/packages/computer/src/tools/pi-ai/index.test.ts index 40d6bc9f..9f42e263 100644 --- a/packages/computer/src/tools/pi-ai/index.test.ts +++ b/packages/computer/src/tools/pi-ai/index.test.ts @@ -106,6 +106,49 @@ describe("createPiTools declarations", () => { expect(() => createPiTools({ workspace, exec: oldMap })).toThrow(/under `exec.backends`/); }); + it("keeps exec in a read-only set on the backends that only read", async () => { + const ran: Array<{ backend?: string; output?: unknown }> = []; + const workspace = makeWorkspace(); + (workspace.runtime as unknown as Record).exec = async ( + _command: string, + options: { backend?: string; output?: unknown }, + ) => { + ran.push({ backend: options.backend, output: options.output }); + return { result: async () => ({ exitCode: 0, stdout: "", stderr: "" }) }; + }; + fakeBackends(workspace, [ + { id: "codemode-readonly", protocol: "module", callable: true, access: "read" }, + { id: "codemode", protocol: "module", callable: true, access: "read-write" }, + { id: "sh", protocol: "command", callable: false }, + ]); + const names = (exec?: { backends: Record }) => + createPiTools({ workspace, readonly: true, exec }).tools.map((tool) => tool.name); + + expect(names()).toEqual(["read", "ls", "find", "grep", "exec"]); + const tools = createPiTools({ workspace, readonly: true }); + expect(declaration(tools, "exec").parameters.properties).not.toHaveProperty("backend"); + await tools.execute({ id: "1", name: "exec", arguments: { command: "export default 1" } }); + // The runtime would save long output from the host, past the + // backend's guard, so a read-only set saves none. + expect(ran).toEqual([{ backend: "codemode-readonly", output: false }]); + expect(names({ backends: { "codemode-readonly": {} } })).toContain("exec"); + expect(names({ backends: { codemode: {}, sh: {} } })).not.toContain("exec"); + }); + + it("keeps a read-only set's exec, without detach, when no backend it keeps can detach", () => { + const workspace = makeWorkspace(); + (workspace.runtime as unknown as Record).pending = async () => []; + (workspace.runtime as unknown as Record).detachExec = async () => true; + fakeBackends(workspace, [ + { id: "codemode-readonly", protocol: "module", callable: true, access: "read" }, + { id: "codemode", protocol: "module", callable: true, detachable: true }, + ]); + + const tools = createPiTools({ workspace, readonly: true, exec: { detach: true } }); + + expect(declaration(tools, "exec").description).not.toContain("comes back early"); + }); + it("leaves exec out for `exec: { backends: {} }` and for a read-only set", () => { const workspace = makeWorkspace(); fakeBackends(workspace, [{ id: "worker-shell", callable: false }]); diff --git a/packages/computer/src/tools/pi-ai/index.ts b/packages/computer/src/tools/pi-ai/index.ts index 69966c94..ee577fa9 100644 --- a/packages/computer/src/tools/pi-ai/index.ts +++ b/packages/computer/src/tools/pi-ai/index.ts @@ -146,34 +146,35 @@ function piToolEntries(options: CreateToolsOptions): PiToolEntry[] { } as PiToolEntry, ]; - // These four are the tools a readonly set keeps. bindings.ts marks the - // same names read-only for codemode:tools, so keep the two lists in step. - if (resolved.readonly) return entries; - - entries.push( - { - name: "write", - description: writeDescription, - inputSchema: writeInputSchema, - // The whole file body travels as one string argument. - strictArguments: true, - execute: (input) => writeToStore(resolved.write, input), - } as PiToolEntry, - { - name: "edit", - description: editDescription, - inputSchema: editInputSchema, - // A nested array of exact-match strings is easy to malform. - strictArguments: true, - execute: (input) => editInStore(resolved.edit, input), - } as PiToolEntry, - { - name: "delete", - description: deleteDescription, - inputSchema: deleteInputSchema, - execute: (input) => deleteFromStore(resolved.delete, input), - } as PiToolEntry, - ); + // These four are the file tools a readonly set keeps. bindings.ts marks + // the same names read-only for codemode:tools, so keep the two lists in + // step. + if (!resolved.readonly) { + entries.push( + { + name: "write", + description: writeDescription, + inputSchema: writeInputSchema, + // The whole file body travels as one string argument. + strictArguments: true, + execute: (input) => writeToStore(resolved.write, input), + } as PiToolEntry, + { + name: "edit", + description: editDescription, + inputSchema: editInputSchema, + // A nested array of exact-match strings is easy to malform. + strictArguments: true, + execute: (input) => editInStore(resolved.edit, input), + } as PiToolEntry, + { + name: "delete", + description: deleteDescription, + inputSchema: deleteInputSchema, + execute: (input) => deleteFromStore(resolved.delete, input), + } as PiToolEntry, + ); + } if (resolved.exec !== undefined) { const exec = defineExec(resolved.exec); diff --git a/packages/computer/src/tools/tanstack-ai/index.test.ts b/packages/computer/src/tools/tanstack-ai/index.test.ts index c5b84100..ae456e6f 100644 --- a/packages/computer/src/tools/tanstack-ai/index.test.ts +++ b/packages/computer/src/tools/tanstack-ai/index.test.ts @@ -136,6 +136,25 @@ describe("createTanStackTools", () => { expect(tools.map((tool) => tool.name).sort()).toEqual(["find", "grep", "ls", "read"]); }); + it("keeps exec when readonly and a backend only reads", () => { + const workspace = makeWorkspace(); + (workspace.runtime as unknown as Record).backends = () => [ + { id: "codemode-readonly", protocol: "module", callable: true, access: "read" }, + ]; + + const tools = createTanStackTools({ workspace, readonly: true }); + + expect(tools.map((tool) => tool.name).sort()).toEqual(["exec", "find", "grep", "ls", "read"]); + // It can't change anything, so "mutating" doesn't gate it. + const gated = createTanStackTools({ + workspace, + readonly: true, + approve: "mutating", + format: "object", + }); + expect(gated.exec.needsApproval).toBeUndefined(); + }); + it("passes the Zod schema through untouched for standard-schema validation", () => { const tools = createTanStackTools({ workspace: makeWorkspace(), format: "object" }); diff --git a/packages/computer/src/tools/tanstack-ai/index.ts b/packages/computer/src/tools/tanstack-ai/index.ts index 44c50812..c724b9a2 100644 --- a/packages/computer/src/tools/tanstack-ai/index.ts +++ b/packages/computer/src/tools/tanstack-ai/index.ts @@ -175,39 +175,40 @@ export function createTanStackTools mutates: true, run: async (input: never) => plain(await deleteFromStore(resolved.delete, input)), }); + } - if (resolved.exec !== undefined) { - const exec = defineExec(resolved.exec); - add({ - name: "exec", - description: exec.description, - inputSchema: exec.inputSchema, - mutates: true, - streams: true, - run: async (input: never, context?: TanStackToolExecutionContext) => { - const returned = exec.execute(input, { - abortSignal: context?.abortSignal, - toolCallId: context?.toolCallId, - }); - const output = options.streamEventName - ? await settleWithEvents(returned, options.streamEventName, context) - : await settle(returned); - return plain(output); - }, - }); - } + if (resolved.exec !== undefined) { + const exec = defineExec(resolved.exec); + add({ + name: "exec", + description: exec.description, + inputSchema: exec.inputSchema, + // Read-only, it runs on backends that can't write and saves no output. + mutates: !resolved.readonly, + streams: true, + run: async (input: never, context?: TanStackToolExecutionContext) => { + const returned = exec.execute(input, { + abortSignal: context?.abortSignal, + toolCallId: context?.toolCallId, + }); + const output = options.streamEventName + ? await settleWithEvents(returned, options.streamEventName, context) + : await settle(returned); + return plain(output); + }, + }); + } - if (resolved.publish) { - const executor = createPublishExecutor(workspace as PublishWorkspaceLike); - add({ - name: "publish", - description: publishDescription, - inputSchema: publishInputSchema, - outputSchema: publishOutputSchema, - mutates: true, - run: async (input: never) => plain(await executor(input)), - }); - } + if (resolved.publish) { + const executor = createPublishExecutor(workspace as PublishWorkspaceLike); + add({ + name: "publish", + description: publishDescription, + inputSchema: publishInputSchema, + outputSchema: publishOutputSchema, + mutates: true, + run: async (input: never) => plain(await executor(input)), + }); } if (options.format === "object") {