Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/readonly-exec.md
Original file line number Diff line number Diff line change
@@ -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).
1 change: 1 addition & 0 deletions docs/05_runtime_interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 2 additions & 2 deletions docs/09_tool_interface.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`. |
Expand Down Expand Up @@ -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`

Expand Down
16 changes: 16 additions & 0 deletions packages/computer/src/backends/codemode/codemode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,22 @@ async function evaluateResult(
}

describe("CodemodeBackend", () => {
it("reports its access through runtime.backends()", () => {
const loader = { load: vi.fn<WorkspaceRuntimeLoader["load"]>() };
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<WorkspaceRuntimeLoader["load"]>(() => ({
getEntrypoint() {
Expand Down
4 changes: 3 additions & 1 deletion packages/computer/src/backends/codemode/codemode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,13 +355,15 @@ 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;

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.");
}
Expand Down Expand Up @@ -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,
Expand Down
8 changes: 8 additions & 0 deletions packages/computer/src/runtime/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
type ModuleExecutionEnvelope,
type WorkspaceModuleBackendHandle,
type WorkspaceRegisteredBackend,
type WorkspaceRuntimeAccess,
type WorkspaceRuntimeDisposeOptions,
type WorkspaceRuntimeEvent,
type WorkspaceRuntimeExecHandle,
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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",
}));
}

Expand Down
5 changes: 5 additions & 0 deletions packages/computer/src/runtime/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<WorkspaceModuleBackendHandle>;
}

Expand Down
11 changes: 11 additions & 0 deletions packages/computer/src/tools/ai-sdk/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>).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 });
Expand Down
17 changes: 9 additions & 8 deletions packages/computer/src/tools/ai-sdk/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()`.
Expand All @@ -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);
}
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

if (resolved.exec !== undefined) {
tools.exec = createExecTool(resolved.exec);
Expand Down
33 changes: 33 additions & 0 deletions packages/computer/src/tools/common/exec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }> = [];
Expand Down
44 changes: 33 additions & 11 deletions packages/computer/src/tools/common/exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export interface ExecWorkspaceLike {
env?: Record<string, string>;
input?: WorkspaceRuntimeValue;
metadata?: Record<string, string>;
output?: { maxBytes: number; maxLines: number };
output?: { maxBytes: number; maxLines: number } | false;
},
): Promise<ExecRuntimeHandle>;
// Calls waiting in ctx.interrupt(), by execution id, and noting
Expand Down Expand Up @@ -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;
Comment on lines +159 to +165

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Read-only example still saves output

The RLM executor uses a read-only backend but leaves saveOutput at its default. The example does not demonstrate the new option for callers who build an exec tool directly.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

// Clock backing the running-snapshot coalescing floor. Defaults to
// Date.now; injectable so tests can drive the interval deterministically.
now?: () => number;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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]),
Expand Down Expand Up @@ -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) };
Expand Down Expand Up @@ -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." };
}
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -676,7 +698,7 @@ function describeTool(backends: readonly DescribedBackend[], limits: OutputLimit
"",
only.text,
"",
CALLABLE_HINT,
callableHint(saved),
`${FILE_TOOLS_HINT} ${output}`,
].join("\n")
: [
Expand All @@ -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");
}
Expand Down
Loading
Loading