Skip to content

Commit d371ea1

Browse files
authored
perf(agents): wave-1 tool output contracts for code mode (#110215)
* feat(agents): keep output contracts complete across opaque schema leaves * test(agents): add code mode schema-hint hot-path micro-benchmark * test(agents): count raw-first inspection execs per tool in live bench * feat(agents): expand compact output contract hints * feat(agents): declare wave one tool output contracts * docs(tools): list built-in output contracts * fix(agents): bound union scans before literal-union analysis * fix(agents): keep wave-1 contract schemas module-local and type-exact
1 parent ec8f6e5 commit d371ea1

17 files changed

Lines changed: 519 additions & 16 deletions

‎config/knip.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ const rootEntries = [
102102
"src/agents/compaction-planning.worker.ts!",
103103
"scripts/print-cli-backend-live-metadata.ts!",
104104
"scripts/repro/code-mode-namespace-live.ts!",
105+
"scripts/repro/tool-schema-hint-bench.ts!",
105106
"scripts/repro/tool-surface-live-bench.ts!",
106107
// Workflow/package-script entrypoints are not imported from production modules.
107108
"scripts/openclaw-cross-os-release-checks.ts!",

‎docs/tools/code-mode.md‎

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

528-
Built-in tools can reuse their owning protocol schema instead of duplicating a
529-
model-only contract. For example, the conversation tools expose the same
530-
Gateway result schemas used by `conversations.list`, `conversations.send`, and
531-
`conversations.turn`. When the quick index declares the fields, one cell can
532-
compose discovery and delivery without a separate inspection turn:
528+
Current built-in contracts include `agents_list`, `conversations_list`,
529+
`conversations_send`, `conversations_turn`, `openclaw`, `screen`,
530+
`sessions_search`, `spawn_task`, and `terminal`. Exact passthroughs can reuse
531+
their owning protocol schema instead of duplicating a model-only contract. For
532+
example, the conversation tools expose the same Gateway result schemas used by
533+
`conversations.list`, `conversations.send`, and `conversations.turn`. When the
534+
quick index declares the fields, one cell can compose discovery and delivery
535+
without a separate inspection turn:
533536

534537
```javascript
535538
const listed = await tools.conversations_list({ query: "build bot" });
Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
#!/usr/bin/env -S node --import tsx
2+
// Micro-benchmark for the Code Mode catalog hot path: schema hint compaction,
3+
// full-catalog quick-index assembly, and declared-output validation. These run
4+
// per agent run attempt, so regressions here tax every Code Mode turn.
5+
import { performance } from "node:perf_hooks";
6+
import { Type } from "typebox";
7+
import { applyCodeModeCatalog, createCodeModeTools } from "../../src/agents/code-mode.js";
8+
import { compactToolInputHint, compactToolOutputHint } from "../../src/agents/tool-schema-hints.js";
9+
import {
10+
compactToolSearchCatalogEntry,
11+
createToolSearchCatalogRef,
12+
} from "../../src/agents/tool-search.js";
13+
import { jsonResult, type AnyAgentTool } from "../../src/agents/tools/common.js";
14+
import { validateJsonSchemaValue } from "../../src/plugins/schema-validator.js";
15+
import { setPluginToolMeta } from "../../src/plugins/tools.js";
16+
17+
const WARMUP_ITERATIONS = 50;
18+
const BATCHES = 7;
19+
const CATALOG_TOOL_COUNT = 72;
20+
21+
const TypicalInputSchema = Type.Object({
22+
channel: Type.Optional(Type.String({ minLength: 1 })),
23+
query: Type.Optional(Type.String()),
24+
limit: Type.Optional(Type.Integer({ minimum: 1 })),
25+
});
26+
27+
const TypicalOutputSchema = Type.Union([
28+
Type.Object(
29+
{
30+
status: Type.Literal("replied"),
31+
messageId: Type.String(),
32+
reply: Type.Object(
33+
{
34+
text: Type.String(),
35+
timestamp: Type.Number(),
36+
threadId: Type.Optional(Type.String()),
37+
},
38+
{ additionalProperties: false },
39+
),
40+
},
41+
{ additionalProperties: false },
42+
),
43+
Type.Object(
44+
{ status: Type.Literal("timeout"), messageId: Type.String() },
45+
{ additionalProperties: false },
46+
),
47+
Type.Object(
48+
{ status: Type.Literal("error"), error: Type.String() },
49+
{ additionalProperties: false },
50+
),
51+
]);
52+
53+
const TypicalOutputValue = {
54+
status: "replied",
55+
messageId: "m-1",
56+
reply: { text: "done", timestamp: 1_700_000_000_000, threadId: "t-9" },
57+
};
58+
59+
function buildAdversarialSchema(): Record<string, unknown> {
60+
// Attacker-sized MCP metadata: wide property map, deep nesting, giant enum.
61+
const wide: Record<string, unknown> = {};
62+
for (let index = 0; index < 5_000; index += 1) {
63+
wide[`property_${index}_${"x".repeat(24)}`] = { type: "string" };
64+
}
65+
let deep: Record<string, unknown> = { type: "string" };
66+
for (let index = 0; index < 40; index += 1) {
67+
deep = { type: "object", properties: { child: deep } };
68+
}
69+
return {
70+
type: "object",
71+
properties: {
72+
...wide,
73+
deep,
74+
bigEnum: { enum: Array.from({ length: 10_000 }, (_unused, index) => `value-${index}`) },
75+
},
76+
};
77+
}
78+
79+
function buildCatalogTools(): AnyAgentTool[] {
80+
const tools: AnyAgentTool[] = [];
81+
for (let index = 0; index < CATALOG_TOOL_COUNT; index += 1) {
82+
const declareOutput = index % 3 === 0;
83+
const name = `bench_tool_${String(index).padStart(2, "0")}`;
84+
const tool = {
85+
name,
86+
label: name,
87+
description: `Benchmark tool ${index} exercising catalog compaction cost.`,
88+
parameters: TypicalInputSchema,
89+
...(declareOutput ? { outputSchema: TypicalOutputSchema } : {}),
90+
execute: async (_toolCallId: string, _params: unknown) => jsonResult({ ok: true }),
91+
} satisfies AnyAgentTool;
92+
setPluginToolMeta(tool, { pluginId: "bench-hints", optional: true });
93+
tools.push(tool);
94+
}
95+
return tools;
96+
}
97+
98+
const CODE_MODE_SESSION = {
99+
sessionId: "bench-hints",
100+
sessionKey: "agent:bench-hints:main",
101+
agentId: "bench",
102+
runId: "run-bench-hints",
103+
};
104+
const CODE_MODE_CONFIG = { tools: { codeMode: { enabled: true, timeoutMs: 20_000 } } };
105+
106+
function applyCodeModeSurface(tools: AnyAgentTool[]) {
107+
const catalogRef = createToolSearchCatalogRef();
108+
const codeModeTools = createCodeModeTools({
109+
config: CODE_MODE_CONFIG,
110+
runtimeConfig: CODE_MODE_CONFIG,
111+
...CODE_MODE_SESSION,
112+
catalogRef,
113+
});
114+
return {
115+
catalogRef,
116+
applied: applyCodeModeCatalog({
117+
tools: [...codeModeTools, ...tools],
118+
config: CODE_MODE_CONFIG,
119+
...CODE_MODE_SESSION,
120+
catalogRef,
121+
}),
122+
};
123+
}
124+
125+
type BenchCase = { name: string; iterations: number; run: () => void };
126+
127+
function median(values: number[]): number {
128+
const sorted = [...values].toSorted((a, b) => a - b);
129+
return sorted[Math.floor(sorted.length / 2)] ?? 0;
130+
}
131+
132+
function bench(benchCase: BenchCase): { name: string; nsPerOp: number; opsPerSec: number } {
133+
for (let index = 0; index < WARMUP_ITERATIONS; index += 1) {
134+
benchCase.run();
135+
}
136+
const perBatchNs: number[] = [];
137+
for (let batch = 0; batch < BATCHES; batch += 1) {
138+
const start = performance.now();
139+
for (let index = 0; index < benchCase.iterations; index += 1) {
140+
benchCase.run();
141+
}
142+
perBatchNs.push(((performance.now() - start) * 1e6) / benchCase.iterations);
143+
}
144+
const nsPerOp = median(perBatchNs);
145+
return { name: benchCase.name, nsPerOp, opsPerSec: 1e9 / nsPerOp };
146+
}
147+
148+
async function main(): Promise<void> {
149+
const adversarial = buildAdversarialSchema();
150+
const tools = buildCatalogTools();
151+
const { catalogRef, applied } = applyCodeModeSurface(tools);
152+
const entries = catalogRef.current?.entries ?? [];
153+
if (entries.length < CATALOG_TOOL_COUNT) {
154+
throw new Error(`catalog only registered ${entries.length} entries`);
155+
}
156+
// Warm the validator cache once so the loop measures the steady-state hit.
157+
validateJsonSchemaValue({
158+
schema: TypicalOutputSchema as never,
159+
cacheKey: "bench:typical-output",
160+
value: TypicalOutputValue,
161+
});
162+
163+
const cases: BenchCase[] = [
164+
{
165+
name: "hint: typical input",
166+
iterations: 20_000,
167+
run: () => void compactToolInputHint(TypicalInputSchema),
168+
},
169+
{
170+
name: "hint: typical output union",
171+
iterations: 20_000,
172+
run: () => void compactToolOutputHint(TypicalOutputSchema),
173+
},
174+
{
175+
name: "hint: adversarial 5k-prop schema",
176+
iterations: 200,
177+
run: () => void compactToolInputHint(adversarial),
178+
},
179+
{
180+
name: `catalog: compact ${CATALOG_TOOL_COUNT} entries`,
181+
iterations: 2_000,
182+
run: () => {
183+
for (const entry of entries) {
184+
compactToolSearchCatalogEntry(entry);
185+
}
186+
},
187+
},
188+
{
189+
name: "validate: declared output warm hit",
190+
iterations: 20_000,
191+
run: () =>
192+
void validateJsonSchemaValue({
193+
schema: TypicalOutputSchema as never,
194+
cacheKey: "bench:typical-output",
195+
value: TypicalOutputValue,
196+
}),
197+
},
198+
{
199+
name: "surface: full applyCodeModeCatalog",
200+
iterations: 500,
201+
run: () => void applyCodeModeSurface(tools),
202+
},
203+
];
204+
205+
process.stdout.write(
206+
`tool-schema-hint-bench catalogTools=${entries.length} visibleTools=${applied.tools.length}\n`,
207+
);
208+
for (const benchCase of cases) {
209+
const result = bench(benchCase);
210+
const usPerOp = (result.nsPerOp / 1_000).toFixed(2);
211+
const ops = Math.round(result.opsPerSec).toLocaleString("en-US");
212+
process.stdout.write(
213+
`${result.name.padEnd(36)} ${usPerOp.padStart(10)} us/op ${ops.padStart(12)} ops/s\n`,
214+
);
215+
}
216+
}
217+
218+
await main();

0 commit comments

Comments
 (0)