Skip to content

Commit 2db3495

Browse files
committed
feat(agents): contract filesystem tools for code mode
1 parent 6aee641 commit 2db3495

13 files changed

Lines changed: 375 additions & 36 deletions

‎docs/tools/code-mode.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -525,18 +525,21 @@ export default defineToolPlugin({
525525
For `api.registerTool(...)` or a factory tool, put the same `outputSchema`
526526
property on the returned `AnyAgentTool` object.
527527

528-
Current built-in contracts include `agents_list`, `conversations_list`,
529-
`conversations_send`, `conversations_turn`, `openclaw`, `screen`,
530-
`sessions_search`, `spawn_task`, `terminal`, `web_fetch`, and `web_search`.
528+
Current built-in contracts include `agents_list`, `apply_patch`,
529+
`conversations_list`, `conversations_send`, `conversations_turn`, `edit`,
530+
`openclaw`, `read`, `screen`, `sessions_search`, `spawn_task`, `terminal`,
531+
`web_fetch`, and `web_search`.
531532
Exact passthroughs can reuse their owning protocol schema instead of
532533
duplicating a model-only contract. For example, the conversation tools expose
533534
the same Gateway result schemas used by `conversations.list`,
534535
`conversations.send`, and `conversations.turn`; `web_fetch` owns a tool-local
535536
schema whose hint exposes stable metadata, text, cache state, and nested spill
536537
metadata; `web_search` declares its exact normalized results/answer/error/raw
537-
union as a complete quick-index hint. When the quick index declares the
538-
fields, one cell can compose discovery and delivery without a separate
539-
inspection turn:
538+
union as a complete quick-index hint. Filesystem contracts return structured
539+
read text, image, truncation, and optional-not-found outcomes; explicit edit
540+
change state plus diff/patch data; and apply-patch path summaries. When the
541+
quick index declares the fields, one cell can compose discovery and delivery
542+
without a separate inspection turn:
540543

541544
```javascript
542545
const listed = await tools.conversations_list({ query: "build bot" });

‎src/agents/agent-tools.read.ts‎

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,13 @@ import { toRelativeWorkspacePath } from "./path-policy.js";
3838
import type { AgentToolResult } from "./runtime/index.js";
3939
import { assertSandboxPath } from "./sandbox-paths.js";
4040
import type { SandboxFsBridge } from "./sandbox/fs-bridge.js";
41-
import { createEditTool, createReadTool, createWriteTool } from "./sessions/index.js";
41+
import {
42+
createEditTool,
43+
createReadTool,
44+
createWriteTool,
45+
type ReadToolDetails,
46+
type ReadToolTruncationDetails,
47+
} from "./sessions/index.js";
4248
import { sanitizeToolResultImages } from "./tool-images.js";
4349

4450
// NOTE(steipete): Upstream read now does file-magic MIME detection; we keep the wrapper
@@ -437,6 +443,56 @@ async function normalizeReadImageResult(
437443
return { ...result, content: nextContent };
438444
}
439445

446+
function normalizeReadResultDetails(
447+
result: AgentToolResult<unknown>,
448+
): AgentToolResult<ReadToolDetails> {
449+
const currentDetails =
450+
result.details && typeof result.details === "object"
451+
? (result.details as Record<string, unknown>)
452+
: undefined;
453+
if (
454+
currentDetails?.status === "not_found" &&
455+
typeof currentDetails.path === "string" &&
456+
currentDetails.optional === true
457+
) {
458+
return {
459+
...result,
460+
details: {
461+
kind: "not_found",
462+
status: "not_found",
463+
path: currentDetails.path,
464+
optional: true,
465+
},
466+
};
467+
}
468+
469+
const content = Array.isArray(result.content) ? result.content : [];
470+
const text = getToolResultText(result) ?? "";
471+
const image = content.find(
472+
(block): block is ImageContentBlock =>
473+
Boolean(block) &&
474+
typeof block === "object" &&
475+
(block as { type?: unknown }).type === "image" &&
476+
typeof (block as { mimeType?: unknown }).mimeType === "string",
477+
);
478+
if (image) {
479+
return { ...result, details: { kind: "image", content: text, mimeType: image.mimeType } };
480+
}
481+
482+
const truncation = currentDetails?.truncation;
483+
if (truncation && typeof truncation === "object") {
484+
return {
485+
...result,
486+
details: {
487+
kind: "truncated",
488+
content: text,
489+
truncation: truncation as ReadToolTruncationDetails,
490+
},
491+
};
492+
}
493+
return { ...result, details: { kind: "text", content: text } };
494+
}
495+
440496
/** Wrap a file tool so path params stay inside the workspace root. */
441497
export function wrapToolWorkspaceRootGuard(tool: AnyAgentTool, root: string): AnyAgentTool {
442498
return wrapToolWorkspaceRootGuardWithOptions(tool, root);
@@ -895,11 +951,12 @@ export function createOpenClawReadTool(
895951
typeof normalizedRecord?.path === "string" ? normalizedRecord.path : "<unknown>";
896952
const strippedDetailsResult = stripReadTruncationContentDetails(result);
897953
const normalizedResult = await normalizeReadImageResult(strippedDetailsResult, filePath);
898-
return sanitizeToolResultImages(
954+
const sanitizedResult = await sanitizeToolResultImages(
899955
normalizedResult,
900956
`read:${filePath}`,
901957
options?.imageSanitization,
902958
);
959+
return normalizeReadResultDetails(sanitizedResult);
903960
},
904961
};
905962
}

‎src/agents/agent-tools.workspace-only-false.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ describe("FS tools with workspaceOnly=false", () => {
176176
},
177177
],
178178
details: {
179+
kind: "not_found",
179180
status: "not_found",
180181
path: "memory/2026-05-15.md",
181182
optional: true,

‎src/agents/apply-patch.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,20 @@ const applyPatchSchema = Type.Object({
9797
}),
9898
});
9999

100+
const ApplyPatchToolOutputSchema = Type.Object(
101+
{
102+
summary: Type.Object(
103+
{
104+
added: Type.Array(Type.String()),
105+
modified: Type.Array(Type.String()),
106+
deleted: Type.Array(Type.String()),
107+
},
108+
{ additionalProperties: false },
109+
),
110+
},
111+
{ additionalProperties: false },
112+
);
113+
100114
/** Create the agent tool wrapper for applying patch-envelope input. */
101115
export function createApplyPatchTool(
102116
options: { cwd?: string; sandbox?: SandboxApplyPatchConfig; workspaceOnly?: boolean } = {},
@@ -110,6 +124,7 @@ export function createApplyPatchTool(
110124
label: "apply_patch",
111125
description: "Patch one/many files. Input requires *** Begin Patch and *** End Patch.",
112126
parameters: applyPatchSchema,
127+
outputSchema: ApplyPatchToolOutputSchema,
113128
execute: async (_toolCallId, args, signal) => {
114129
const params = args as { input?: string };
115130
const input = typeof params.input === "string" ? params.input : "";

‎src/agents/code-mode.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import { isRecord } from "../../packages/normalization-core/src/record-coerce.js";
77
import { setPluginToolMeta } from "../plugins/tools.js";
88
import { buildBlockedToolResult } from "./agent-tools.before-tool-call.js";
9+
import { createOpenClawReadTool } from "./agent-tools.read.js";
910
import {
1011
clearCodeModeNamespacesForPlugin,
1112
createCodeModeNamespaceTool,
@@ -23,6 +24,7 @@ import {
2324
resolveCodeModeConfig,
2425
} from "./code-mode.js";
2526
import { testing } from "./code-mode.test-support.js";
27+
import { createReadTool } from "./sessions/index.js";
2628
import { createToolSearchCatalogRef, type ToolSearchCatalogRef } from "./tool-search.js";
2729
import {
2830
TOOL_CALL_RAW_TOOL_NAME,
@@ -1004,6 +1006,36 @@ describe("Code Mode", () => {
10041006
expect(ticket.execute).toHaveBeenCalledTimes(1);
10051007
});
10061008

1009+
it("returns ordinary read content through tools.callValue", async () => {
1010+
const { config, catalogRef, tools: codeModeTools } = createCodeModeHarness();
1011+
const read = createOpenClawReadTool(
1012+
createReadTool("/workspace", {
1013+
operations: {
1014+
access: async () => {},
1015+
detectImageMimeType: async () => null,
1016+
readFile: async () => Buffer.from("ordinary file content"),
1017+
},
1018+
}) as unknown as Parameters<typeof createOpenClawReadTool>[0],
1019+
);
1020+
applyCodeModeCatalog({
1021+
tools: [...codeModeTools, read],
1022+
config,
1023+
sessionId: "session-code-mode",
1024+
sessionKey: "agent:main:main",
1025+
runId: "run-code-mode",
1026+
catalogRef,
1027+
});
1028+
1029+
const details = await runUntilCompleted({
1030+
execTool: expectDefined(codeModeTools[0], "codeModeTools[0] test invariant"),
1031+
waitTool: expectDefined(codeModeTools[1], "codeModeTools[1] test invariant"),
1032+
code: `return await tools.callValue("openclaw:core:read", { path: "notes.txt" });`,
1033+
});
1034+
1035+
expect(details.status).toBe("completed");
1036+
expect(details.value).toEqual({ kind: "text", content: "ordinary file content" });
1037+
});
1038+
10071039
it("resolves sequential bridge tool calls inline within one exec instead of a wait per call", async () => {
10081040
const catalogRef = createToolSearchCatalogRef();
10091041
// maxPendingToolCalls stays a per-batch concurrency cap; five sequential
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { Value } from "typebox/value";
5+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
6+
import { createOpenClawReadTool } from "./agent-tools.read.js";
7+
import type { AnyAgentTool } from "./agent-tools.types.js";
8+
import { createApplyPatchTool } from "./apply-patch.js";
9+
import { createEditTool, createReadTool } from "./sessions/index.js";
10+
import { DEFAULT_MAX_BYTES } from "./sessions/tools/truncate.js";
11+
import { compactToolOutputHint } from "./tool-schema-hints.js";
12+
13+
const ONE_PIXEL_PNG_BASE64 =
14+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=";
15+
16+
function expectContract(tool: AnyAgentTool, details: unknown): void {
17+
expect(tool.outputSchema).toBeDefined();
18+
expect(Value.Check(tool.outputSchema!, details)).toBe(true);
19+
}
20+
21+
describe("filesystem tool output contracts", () => {
22+
let tmpDir = "";
23+
24+
beforeEach(async () => {
25+
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-filesystem-contract-"));
26+
});
27+
28+
afterEach(async () => {
29+
await fs.rm(tmpDir, { recursive: true, force: true });
30+
});
31+
32+
it("validates read text, image, truncation, and optional-not-found results", async () => {
33+
await fs.writeFile(path.join(tmpDir, "notes.txt"), "ordinary text\n", "utf8");
34+
await fs.writeFile(path.join(tmpDir, "pixel.png"), Buffer.from(ONE_PIXEL_PNG_BASE64, "base64"));
35+
await fs.writeFile(path.join(tmpDir, "long.txt"), "x".repeat(DEFAULT_MAX_BYTES + 1), "utf8");
36+
37+
const tool = createOpenClawReadTool(
38+
createReadTool(tmpDir, { autoResizeImages: false }) as unknown as AnyAgentTool,
39+
);
40+
const text = await tool.execute("read-text", { path: "notes.txt", limit: 10 });
41+
const image = await tool.execute("read-image", { path: "pixel.png", limit: 10 });
42+
const truncated = await tool.execute("read-truncated", { path: "long.txt", limit: 10 });
43+
const notFound = await tool.execute("read-not-found", { path: "memory/2026-07-17.md" });
44+
45+
for (const result of [text, image, truncated, notFound]) {
46+
expectContract(tool, result.details);
47+
}
48+
expect(text.details).toEqual({ kind: "text", content: "ordinary text\n" });
49+
expect(image.details).toMatchObject({ kind: "image", mimeType: "image/png" });
50+
expect(truncated.details).toMatchObject({ kind: "truncated" });
51+
expect(notFound.details).toEqual({
52+
kind: "not_found",
53+
status: "not_found",
54+
path: "memory/2026-07-17.md",
55+
optional: true,
56+
});
57+
expect(compactToolOutputHint(tool.outputSchema)).toBe(
58+
'{ content: string; kind: "text" } | { content: string; kind: "image"; mimeType: string } | { content: string; kind: "truncated"; truncation: { firstLineExceedsLimit: boolean; lastLinePartial: boolean; maxBytes: number; maxLines: number; outputBytes: number; outputLines: number; totalBytes: number; totalLines: number; truncated: true; truncatedBy: "lines" | "bytes" } } | { kind: "not_found"; optional: true; path: string; status: "not_found" }',
59+
);
60+
});
61+
62+
it("validates edit changed and no-op results", async () => {
63+
const filePath = path.join(tmpDir, "edit.txt");
64+
await fs.writeFile(filePath, "before\n", "utf8");
65+
const tool = createEditTool(tmpDir) as unknown as AnyAgentTool;
66+
const changed = await tool.execute("edit-changed", {
67+
path: filePath,
68+
edits: [{ oldText: "before", newText: "after" }],
69+
});
70+
const noOp = await tool.execute("edit-no-op", {
71+
path: filePath,
72+
edits: [{ oldText: "after", newText: "after" }],
73+
});
74+
75+
expectContract(tool, changed.details);
76+
expectContract(tool, noOp.details);
77+
expect(changed.details).toMatchObject({ changed: true });
78+
expect(noOp.details).toEqual({ changed: false });
79+
expect(compactToolOutputHint(tool.outputSchema)).toBe(
80+
"{ changed: false } | { changed: true; diff: string; patch: string; firstChangedLine?: number }",
81+
);
82+
});
83+
84+
it("validates apply_patch path summaries", async () => {
85+
const tool = createApplyPatchTool({ cwd: tmpDir }) as unknown as AnyAgentTool;
86+
const result = await tool.execute("patch-add", {
87+
input: "*** Begin Patch\n*** Add File: added.txt\n+added\n*** End Patch",
88+
});
89+
90+
expectContract(tool, result.details);
91+
expect(result.details).toEqual({
92+
summary: { added: ["added.txt"], modified: [], deleted: [] },
93+
});
94+
expect(compactToolOutputHint(tool.outputSchema)).toBe(
95+
"{ summary: { added: Array<string>; deleted: Array<string>; modified: Array<string> } }",
96+
);
97+
});
98+
});

‎src/agents/sessions/extensions/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -503,6 +503,8 @@ export interface ToolDefinition<
503503
promptGuidelines?: string[];
504504
/** Parameter schema (TypeBox) */
505505
parameters: TParams;
506+
/** Exact schema for the structured value returned in AgentToolResult.details. */
507+
outputSchema?: TSchema;
506508
/** Controls whether ToolExecutionComponent renders the standard colored shell or the tool renders its own framing. */
507509
renderShell?: "default" | "self";
508510

‎src/agents/sessions/tools/edit.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,10 @@ describe("edit tool", () => {
199199
].join("\n");
200200
await expect(fs.readFile(filePath, "utf-8")).resolves.toBe(expected);
201201
const details = result.details as EditToolDetails;
202+
expect(details.changed).toBe(true);
203+
if (!details.changed) {
204+
throw new Error("expected changed edit details");
205+
}
202206
expect(applyPatch(original, details.patch)).toBe(expected);
203207
});
204208

@@ -219,6 +223,10 @@ describe("edit tool", () => {
219223
const expected = "after\nafter \n";
220224
await expect(fs.readFile(filePath, "utf-8")).resolves.toBe(expected);
221225
const details = result.details as EditToolDetails;
226+
expect(details.changed).toBe(true);
227+
if (!details.changed) {
228+
throw new Error("expected changed edit details");
229+
}
222230
expect(applyPatch(original, details.patch)).toBe(expected);
223231
});
224232

0 commit comments

Comments
 (0)