From 6f1072cc081f06b86a673bd142f03720d17afe15 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 1 Oct 2026 18:27:08 +0200 Subject: [PATCH] feat(coding-agent): shrink codemode prompt and guide scripts back from errors Move the codemode script reference, including the models API, into docs/codemode.md and keep only one line per global in the tool description. Declared tools get a one-line note on how scripts call them, and the codemode system prompt guidance and MCP server section are shorter. With the default tools a GPT-5.6 request drops from about 5,300 to 3,300 tokens. Errors now point the way back: unknown tools and models members name close matches, models.classify() and models.generateImages() validate their arguments, unknown or mistyped models point to getAvailableOfType(), store() overflow explains the store, and unshown generated images get a note. --- packages/codemode/CHANGELOG.md | 8 + packages/codemode/src/declarations.ts | 8 +- packages/codemode/src/index.ts | 1 + .../codemode/src/runtime/prelude-source.ts | 49 ++++- packages/codemode/test/sandbox.test.ts | 52 ++++- packages/coding-agent/CHANGELOG.md | 2 + packages/coding-agent/docs/cli.md | 12 +- packages/coding-agent/docs/codemode.md | 207 ++++++++++++++++++ packages/coding-agent/docs/docs.json | 4 + packages/coding-agent/docs/models.md | 4 +- packages/coding-agent/docs/settings.md | 2 +- .../coding-agent/src/core/settings-manager.ts | 4 +- .../coding-agent/src/core/system-prompt.ts | 2 +- packages/coding-agent/src/core/tools/bash.ts | 9 +- .../src/extensions/codemode/execute.ts | 185 +++++++++++++--- .../src/extensions/codemode/tool.ts | 184 +++++----------- .../coding-agent/src/extensions/mcp/index.ts | 24 +- .../test/suite/agent-session-codemode.test.ts | 68 ++++-- .../coding-agent/test/tool-search.test.ts | 4 +- 19 files changed, 607 insertions(+), 222 deletions(-) create mode 100644 packages/coding-agent/docs/codemode.md diff --git a/packages/codemode/CHANGELOG.md b/packages/codemode/CHANGELOG.md index 1805b8b4f..71b0cfde5 100644 --- a/packages/codemode/CHANGELOG.md +++ b/packages/codemode/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] +### Added + +- Added `renderToolOutputType()`, the type a tool call resolves to. + +### Changed + +- Reading a member of `tools` or of a global namespace that does not exist now throws an error naming the close matches, instead of returning `undefined`. Use `"name" in tools` to check for a tool. `store()` size errors explain what the store is for. + ## [0.99.2] - 2026-09-30 ### Changed diff --git a/packages/codemode/src/declarations.ts b/packages/codemode/src/declarations.ts index 6899b63f8..c7b57e05b 100644 --- a/packages/codemode/src/declarations.ts +++ b/packages/codemode/src/declarations.ts @@ -143,7 +143,7 @@ export function renderToolSignature( tool.inputSchema === undefined ? "unknown" : schemaToType(tool.inputSchema, { maxChars: options.inputMaxChars ?? DEFAULT_INPUT_SCHEMA_MAX_CHARS }); - return `${toCodemodeIdentifier(tool.name)}(args: ${input}): Promise<${outputType(tool.outputSchema)}>;`; + return `${toCodemodeIdentifier(tool.name)}(args: ${input}): Promise<${renderToolOutputType(tool.outputSchema)}>;`; } /** @@ -174,7 +174,11 @@ export function mcpStructuredContentSchema(schema: CodemodeJsonSchema | undefine return isObject(structuredContent) || typeof structuredContent === "boolean" ? structuredContent : true; } -function outputType(schema: CodemodeJsonSchema | undefined): string { +/** + * The type a tool call resolves to: `CallToolResult` for MCP output schemas (needs + * {@link MCP_TYPESCRIPT_PREAMBLE}), the schema's type otherwise, and `unknown` without a schema. + */ +export function renderToolOutputType(schema: CodemodeJsonSchema | undefined): string { const structured = mcpStructuredContentSchema(schema); if (structured !== undefined) { const type = schemaToType(structured); diff --git a/packages/codemode/src/index.ts b/packages/codemode/src/index.ts index 2ddb93625..e6acd3e11 100644 --- a/packages/codemode/src/index.ts +++ b/packages/codemode/src/index.ts @@ -4,6 +4,7 @@ export { mcpStructuredContentSchema, type RenderDeclarationsOptions, renderDeclarations, + renderToolOutputType, renderToolSample, renderToolSignature, schemaToType, diff --git a/packages/codemode/src/runtime/prelude-source.ts b/packages/codemode/src/runtime/prelude-source.ts index b0bc197df..7333cb849 100644 --- a/packages/codemode/src/runtime/prelude-source.ts +++ b/packages/codemode/src/runtime/prelude-source.ts @@ -113,6 +113,34 @@ export const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson Object.freeze(tools); Object.freeze(allTools); + // Reading a member that does not exist throws an error that names the close matches, instead of + // a later "not a function". \`in\` checks still work. + const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, ""); + function guard(target, label, names, hint) { + return new Proxy(target, { + get(object, property, receiver) { + if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") { + return Reflect.get(object, property, receiver); + } + const wanted = comparable(property); + const exact = names.filter((name) => comparable(name) === wanted); + const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name)))); + let message = label + "." + property + " does not exist."; + if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?"; + else if (names.length <= 20) message += " Available: " + names.join(", ") + "."; + if (hint) message += " " + hint; + message += ' Check for a member with "' + property + '" in ' + label + "."; + throw new TypeErrorCtor(message); + }, + }); + } + const toolsProxy = guard( + tools, + "tools", + allTools.map((tool) => tool.name), + "ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.", + ); + const namespaces = new Map(); for (const { name, spread } of parse(globalsJson)) { const fn = caller("global", name, spread); @@ -126,7 +154,9 @@ export const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson namespaces.get(namespace)[name.slice(dot + 1)] = fn; } for (const [namespace, members] of namespaces) { - Object.defineProperty(globalThis, namespace, { value: Object.freeze(members), enumerable: true }); + Object.freeze(members); + const value = guard(members, namespace, Object.keys(members)); + Object.defineProperty(globalThis, namespace, { value, enumerable: true }); } // key -> JSON text. Sizes count key and JSON characters. @@ -135,6 +165,9 @@ export const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson let storedChars = 0; for (const [key, json] of stored) storedChars += key.length + json.length; + const STORE_HINT = + "store() is for small state such as IDs or summaries. Show images with image(), keep large data in variables, or write it to a file with a tool."; + function checkKey(name, key) { if (typeof key !== "string") throw new TypeError(name + "() key must be a string"); } @@ -158,11 +191,17 @@ export const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable"); } if (json.length > ${MAX_STORE_VALUE_CHARS}) { - throw new RangeError("store(" + stringify(key) + ") value exceeds ${MAX_STORE_VALUE_CHARS} characters of JSON"); + throw new RangeError( + "store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. " + + STORE_HINT, + ); } const next = storedChars - previous + key.length + json.length; if (next > ${MAX_STORE_TOTAL_CHARS}) { - throw new RangeError("store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON"); + throw new RangeError( + "store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). " + + STORE_HINT, + ); } stored.set(key, json); storedChars = next; @@ -278,7 +317,7 @@ export const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson } Object.freeze(console); - Object.defineProperty(globalThis, "tools", { value: tools, enumerable: true }); + Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true }); Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true }); Object.defineProperty(globalThis, "console", { value: console, enumerable: true }); Object.defineProperty(globalThis, "text", { value: text, enumerable: true }); @@ -306,7 +345,7 @@ export const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson run(fn) { let promise; try { - promise = fn(tools, console); + promise = fn(toolsProxy, console); } catch (error) { done(false, describeError(error)); return; diff --git a/packages/codemode/test/sandbox.test.ts b/packages/codemode/test/sandbox.test.ts index 10c0302b0..ba9283ee6 100644 --- a/packages/codemode/test/sandbox.test.ts +++ b/packages/codemode/test/sandbox.test.ts @@ -332,6 +332,22 @@ describe("tools", () => { expect(aborted).toBe(true); }); + it("names close matches when a script reads a tool that does not exist", async () => { + const sandbox = createSandbox([echo, { name: "web-search", execute: () => "" }]); + const attempt = async (expression: string) => { + const result = await sandbox.execute(`return ${expression};`); + return result.ok ? result.value : result.error.message; + }; + expect(await attempt("tools.Echo")).toBe( + 'tools.Echo does not exist. Did you mean tools.echo? ALL_TOOLS lists every tool; searchTools(query) finds tools by topic. Check for a member with "Echo" in tools.', + ); + expect(await attempt("tools.websearch")).toContain("Did you mean tools.web_search?"); + expect(await attempt("tools.nothing")).toContain("Available: echo, web_search."); + expect( + await attempt("['echo' in tools, 'nothing' in tools, String(tools.toString), JSON.stringify(tools)]"), + ).toEqual([true, false, "undefined", "{}"]); + }); + it("supports register and unregister between executions", async () => { const sandbox = createSandbox(); sandbox.registerTool(echo); @@ -339,7 +355,7 @@ describe("tools", () => { expect(sandbox.tools.map((tool) => tool.name)).toEqual(["echo"]); expect(await sandbox.execute("return await tools.echo('a')")).toMatchObject({ ok: true, value: "a" }); expect(sandbox.unregisterTool("echo")).toBe(true); - expect(await sandbox.execute("return typeof tools.echo")).toMatchObject({ ok: true, value: "undefined" }); + expect(await sandbox.execute("return 'echo' in tools")).toMatchObject({ ok: true, value: false }); }); }); @@ -392,6 +408,15 @@ describe("store and load", () => { }); }); + it("explains oversized writes", async () => { + const sandbox = createSandbox(); + const result = await sandbox.execute(`store("img", "x".repeat(300 * 1024));`); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.message).toContain('store("img") value has 307202 characters of JSON'); + expect(result.error.message).toContain("Show images with image()"); + }); + it("reserves the store and load names", () => { const execute = () => undefined; expect(() => new CodemodeSandbox({ globals: [{ name: "store", execute }] })).toThrow(/Invalid global/); @@ -431,13 +456,30 @@ describe("globals", () => { await models.list("classifier", undefined, 3); await models.list(); try { models.extra = 1; } catch {} - return [Object.keys(models), await models.first("a", "ignored"), typeof models.extra]; + return [Object.keys(models), await models.first("a", "ignored"), "extra" in models]; `); - expect(result).toMatchObject({ ok: true, value: [["list", "first"], "a", "undefined"] }); + expect(result).toMatchObject({ ok: true, value: [["list", "first"], "a", false] }); // undefined array elements become null in the JSON round trip. expect(seen).toEqual([["classifier", null, 3], []]); }); + it("names the members of a namespace when a script reads one that does not exist", async () => { + const execute = () => undefined; + const sandbox = new CodemodeSandbox({ + globals: [ + { name: "models.classify", execute }, + { name: "models.generateImages", execute }, + ], + }); + sandboxes.push(sandbox); + const result = await sandbox.execute("await models.generateImage();"); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.message).toBe( + 'models.generateImage does not exist. Did you mean models.generateImages? Check for a member with "generateImage" in models.', + ); + }); + it("rejects invalid and reserved global names", () => { const execute = () => undefined; for (const name of ["a.b.c", "a.", ".a", "tools.x", "store.x", "a.not-valid"]) { @@ -640,8 +682,8 @@ describe("escape hatches", () => { try { tools.echo = () => 'nope'; } catch {} try { tools.extra = () => 'nope'; } catch {} try { globalThis.tools = null; } catch {} - return [typeof tools.extra, await tools.echo('still')]; + return ["extra" in tools, await tools.echo('still')]; `); - expect(result).toMatchObject({ ok: true, value: ["undefined", "still"] }); + expect(result).toMatchObject({ ok: true, value: [false, "still"] }); }); }); diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md index 88a580ec1..4f55427a1 100644 --- a/packages/coding-agent/CHANGELOG.md +++ b/packages/coding-agent/CHANGELOG.md @@ -14,6 +14,8 @@ - `/login` now offers "Sign in with Radius" at the top level, as the last option, with its status. After a Radius sign-in, `/login` offers to configure the Radius MCP server in the global `mcp.json` with `"auth": { "provider": "radius" }` and reloads. Cancelling a login returns to the menu it was started from. - The provider docs page is renamed to [Providers](docs/providers.md), its "Cloud Providers" section is now "Provider Specific Config", and it documents Radius first. - MCP OAuth credentials are now stored per server name and URL, so MCP servers with the same URL can sign in with different accounts. Credentials stored by URL alone move to the first server that uses them ([#10252](https://github.com/earendil-works/pi/issues/10252)). +- Codemode costs far fewer prompt tokens: with the default tools and codemode active, a GPT-5.6 request shrinks from about 5,300 to 3,300 tokens. The `codemode` description lists the script globals in one line each and points to the new [Codemode](docs/codemode.md) reference for the `models` API, which the model reads when it needs it. Declared tools say in one line how scripts call them and what the call resolves to, instead of repeating their full declaration, and the system prompt's codemode guidance and MCP server section are shorter. +- Codemode errors now say how to recover: reading a tool or `models` member that does not exist names the close matches (`tools.Bash` suggests `tools.bash`), `models.classify()` and `models.generateImages()` reject malformed arguments with the expected shape, an unknown model points to `models.getAvailableOfType()`, an oversized `store()` value explains what the store is for, and a script that generates images without showing them gets a note. Scripts that probed for a tool with `typeof tools.name` must use `"name" in tools`. ### Fixed diff --git a/packages/coding-agent/docs/cli.md b/packages/coding-agent/docs/cli.md index 97b4ee870..6ef866a9c 100644 --- a/packages/coding-agent/docs/cli.md +++ b/packages/coding-agent/docs/cli.md @@ -165,17 +165,7 @@ Codemode is useful without MCP: scripts can run several tool calls in parallel, ### How codemode works -Codemode scripts run in a QuickJS sandbox that can only reach the other tools, through `tools.(args)`; `ALL_TOOLS` lists them. Output comes from `text(value)`, `image(dataUrlOrImageContent)`, `console.*`, and a top-level `return value`; `exit()` ends the script early. The result starts with `Script completed` or `Script failed`, the wall time, and the output; a failed script keeps its partial output, followed by `Script error:` and the error. - -A script may start with an options line such as `// @options: {"max_output_tokens": 2000, "timeout_ms": 60000}`. `max_output_tokens` (default 10000) limits the output: longer output keeps its start and end, and the full text is written to a temp file whose path is included in the result. `timeout_ms` is a hard deadline, unset by default. - -While `codemode` is active, `codemode.mode` in [settings](settings.md#tools) decides how the other tools are presented. With `on` (default) declared tools keep being declared and their descriptions show how to call them from scripts. With `only` they are hidden from the model and listed in the `codemode` description instead, so the model calls them through scripts. - -The `codemode` description lists the callable tools with their TypeScript declarations, grouped by namespace (for example one MCP server). Tools with `deferred` exposure, which includes MCP tools with the default `codemode` exposure, are not listed and do not affect the description, so it stays the same while MCP servers connect. Declarations share a budget of 3000 estimated tokens (`codemode.inlineBudget` in [settings](settings.md#tools)). Scripts find the rest with `await searchTools(query, { limit, namespace })`, which ranks tools with BM25, and `await describeTool(name)`, or by filtering `ALL_TOOLS`. `await describeNamespace(name)` returns a namespace's description, its instructions (for MCP servers, the server instructions), and the names of its tools. - -Tools with an output schema resolve to structured values: `bash` to `{ output, truncated, full_output_path?, exit_code, wall_time_seconds }`, also for non-zero exit codes, and MCP tools to their `CallToolResult`. Other tools resolve to their text output. The `output` of `bash` is not limited to the 2000 lines or 50KB the model sees: it holds up to 1 MiB, and longer output keeps its first and last 512 KiB around an omission marker, with `truncated` set and the full output in `full_output_path`. - -`store(key, value)` and `load(key)` keep JSON values across `codemode` calls: each successful script that stores values appends a `codemode-store` custom entry to the session, so resumed sessions keep the values and each branch sees only the values written on its path. Scripts can also use `models`: `getModelsOfType`, `getAvailableOfType`, and `getModelOfType` list the model catalog, `classify(model, context)` runs a classifier model, and `generateImages(model, context)` runs an image model. Both use the session's credentials, with at most four such calls in flight per script. +Scripts run in a QuickJS sandbox and reach the other tools through `tools.(args)`. [Codemode](codemode.md) describes the script API, how tools are listed and found, the `store()` and `models` globals, and the limits. ### Tool search diff --git a/packages/coding-agent/docs/codemode.md b/packages/coding-agent/docs/codemode.md new file mode 100644 index 000000000..2ccee8e68 --- /dev/null +++ b/packages/coding-agent/docs/codemode.md @@ -0,0 +1,207 @@ +# Codemode + +The `codemode` tool lets the model write a JavaScript script that calls pi's other tools and runs non-LLM models, such as classifiers and image models. Only the script's output reaches the model, so a script can run calls in parallel and filter large results before the model sees them. To turn it on, see [Enable codemode](cli.md#enable-codemode). + +## Scripts + +The tool input is raw JavaScript source, not JSON and not a markdown code fence. It runs as the body of an async function in a QuickJS sandbox, so top-level `await` and `return` work. The sandbox has no Node APIs, file system, network, or timers; scripts reach the outside world only through tools and `models`. + +A script may start with an options line: + +```js +// @options: {"max_output_tokens": 2000, "timeout_ms": 60000} +``` + +- `max_output_tokens` (default 10000) limits the output. Longer output keeps its start and end, and the full text is written to a temp file whose path is included in the result. +- `timeout_ms` is a hard deadline for the whole script. It is unset by default. Image generation can take minutes, so do not set a short deadline for scripts that generate images. + +The result starts with `Script completed` or `Script failed`, the wall time, and the output. A failed script keeps its partial output, followed by `Script error:` and the error. Tool calls are real: calls made before a failure are not undone. Calls still running when the script ends are cancelled, and unawaited promises are discarded. + +## Globals + +| Global | Purpose | +|---|---| +| `tools.(args)` | Call a tool. See [Call tools](#call-tools). | +| `text(value)` | Add a text item to the output. Strings are added as is, other values as JSON. | +| `image(value)` | Add an image to the output: a base64 `data:` URL, an `{ image_url }` object, or an image block `{ type: "image", data, mimeType }` such as those returned by MCP tools and `models.generateImages()`. Remote URLs are not supported. PNG, JPEG, GIF, and WebP are accepted. | +| `console.log(...)` | Like `text()`; `info`, `warn`, `error`, and `debug` do the same. | +| `return value` | A top-level `return` adds the value like `text()`. | +| `exit()` | End the script successfully. | +| `store(key, value)` / `load(key)` | Keep small JSON values across `codemode` calls. See [Store values](#store-values). | +| `ALL_TOOLS` | Every callable tool as `{ name, description }`, including tools the description does not list. | +| `searchTools(query, { limit?, namespace? })` | Rank callable tools by relevance (BM25, default limit 8). Resolves to `{ name, description }[]`. | +| `describeTool(name)` | Resolves to a tool's description and TypeScript declaration, or `undefined`. | +| `describeNamespace(name)` | Resolves to `{ name, description?, instructions?, tools }` for a namespace such as an MCP server, or `undefined`. | +| `models` | List and run non-LLM models. See [Models](#models). | + +## Call tools + +Every tool the session can call is a method of `tools`, named by its identifier: characters that are not valid in a JavaScript identifier become `_`, so the MCP tool `mcp__dev-radius__search` is `tools.mcp__dev_radius__search`. Each method takes one object with the tool's arguments. + +What a call resolves to depends on the tool: + +- Tools with an output schema resolve to a structured value. `bash` resolves to `{ output, truncated, full_output_path?, exit_code, wall_time_seconds }`, also for non-zero exit codes. Its `output` is not limited to the 2000 lines or 50KB the model sees: it holds up to 1 MiB, and longer output keeps its first and last 512 KiB around an omission marker, with `truncated` set and the full output in `full_output_path`. +- MCP tools resolve to their `CallToolResult`, including `isError` and `structuredContent`. +- Other tools, such as `read`, `edit`, and `write`, resolve to their text output. + +A call that fails, is blocked, or gets invalid arguments rejects with an `Error` that carries the tool's error text. Use `Promise.allSettled()` to keep the results of the calls that succeed. + +The `codemode` description lists tools with their TypeScript declarations, grouped by namespace (for example one MCP server). Tools with `deferred` exposure, which includes MCP tools with the default `codemode` exposure, are not listed, so the description stays the same while MCP servers connect. Listed declarations share a budget of 3000 estimated tokens (`codemode.inlineBudget` in [settings](settings.md#tools)). Scripts find the other tools with `searchTools()`, `describeTool()`, `describeNamespace()`, or by filtering `ALL_TOOLS`. + +While `codemode` is active, `codemode.mode` in [settings](settings.md#tools) decides how the other tools are presented. With `on` (default) declared tools stay declared, and their descriptions say how to call them from scripts. With `only` they are hidden from the model and listed in the `codemode` description instead, so the model calls them through scripts. + +## Store values + +`store(key, value)` keeps a JSON value under a string key for later `codemode` calls; storing `undefined` deletes the key. `load(key)` returns the value, or `undefined`. Writes are kept only when the script succeeds: each successful script that stores values appends a `codemode-store` custom entry to the session, so resumed sessions keep the values and each branch sees only the values written on its path. + +The store is for small state such as IDs, cursors, or summaries. One value may have at most 262144 characters of JSON and all values together at most 1048576. Do not store image data; show images with `image()` or write them to a file with a tool. + +## Models + +`models` reaches the model catalog and runs non-LLM models with the session's credentials: classifiers, which answer typed questions about JSON state, and image models, which generate images. Chat models are listed but cannot be run from scripts. Which classifier and image models exist is described in [Use classifier models](models.md#use-classifier-models) and [Use image models](models.md#use-image-models). + +```ts +type ModelType = "chat" | "image" | "classifier"; + +/** A catalog entry. `provider` and `id` identify it; other fields depend on the type. */ +interface ModelInfo { + type?: ModelType; + provider: string; + id: string; + name: string; + api: string; + input: ("text" | "image")[]; + contextWindow?: number; + [key: string]: unknown; +} + +declare const models: { + /** Every known model of a type, optionally for one provider. */ + getModelsOfType(type: ModelType, provider?: string): Promise; + /** Models of a type whose provider has working credentials. */ + getAvailableOfType(type: ModelType, provider?: string): Promise; + /** One catalog entry, or undefined. */ + getModelOfType(type: ModelType, provider: string, id: string): Promise; + /** Answer `context.questions` about `context.state`; answers are in `result.answers` by question ID. */ + classify(model: ModelInfo, context: ClassifierContext): Promise; + /** Generate images from `context.input` text and image blocks; show `result.output` blocks with image(). Can take minutes. */ + generateImages(model: ModelInfo, context: ImagesContext): Promise; +}; +``` + +`classify()` and `generateImages()` use only the `provider` and `id` of `model`, so `{ provider, id }` works as well. They do not throw on provider errors: check `stopReason` and `errorMessage`. At most four such calls run at once per script; more calls wait for a free slot, so `Promise.all()` over many items is fine. Their usage is added to the `codemode` tool result and counts toward the session cost. + +Model IDs differ between providers, for example `typesafe/jev-latest` and `openrouter/typesafe/jev-1.13`. Use `models.getAvailableOfType(type)` to find the IDs that work with the current credentials. + +### Classify + +```ts +interface ClassifierContext { + /** The data to classify. */ + state: Record; + /** Questions by ID. One call answers all of them. */ + questions: Record; +} + +type ClassifierQuestion = + /** Pick one label. `criteria` maps each label to what it means. */ + | { type: "choice"; instructions: string; criteria: Record } + /** Score on an ordered scale. `criteria` describes each level, lowest first. */ + | { type: "score"; instructions: string; criteria: string[] } + /** Yes or no. */ + | { type: "bool"; instructions: string; criteria: { true: string; false: string } }; + +interface ClassifierResult { + provider: string; + model: string; + /** Answers by question ID. */ + answers: Record; + usage?: ModelUsage; + stopReason: "stop" | "error" | "aborted"; + errorMessage?: string; +} + +type ClassifierAnswer = + | { type: "choice"; choice: string; probabilities: Record; confidence: number } + /** `score` is the expected level index, from 0 to `criteria.length - 1`. */ + | { type: "score"; score: number; confidence: number } + /** Probability of `true`. */ + | { type: "bool"; probability: number }; + +/** Token counts and cost in USD, when the service reports them. */ +type ModelUsage = { input: number; output: number; totalTokens: number; cost: { total: number } }; +``` + +Classify several items by calling `classify()` once per item. This script sorts feedback messages, for example ones a tool returned earlier in the script: + +```js +const jev = await models.getModelOfType("classifier", "typesafe", "jev-latest"); +const results = await Promise.all( + messages.map((message) => + models.classify(jev, { + state: { message }, + questions: { + sentiment: { + type: "choice", + instructions: "How does the user feel about the product?", + criteria: { positive: "Satisfied or happy", negative: "Unhappy or frustrated", neutral: "Neither" }, + }, + urgency: { + type: "score", + instructions: "How urgently does this need a reply?", + criteria: ["no reply needed", "reply this week", "reply today"], + }, + }, + }), + ), +); +return results.map((result, i) => + result.stopReason === "stop" + ? { message: messages[i], sentiment: result.answers.sentiment.choice, urgency: result.answers.urgency.score } + : { message: messages[i], error: result.errorMessage }, +); +``` + +### Generate images + +```ts +interface ImagesContext { + /** The prompt as text blocks, plus image blocks to edit or use as references. */ + input: (TextBlock | ImageBlock)[]; +} + +interface ImagesResult { + provider: string; + model: string; + /** Generated images, and text blocks for models that also return text. */ + output: (TextBlock | ImageBlock)[]; + usage?: ModelUsage; + stopReason: "stop" | "error" | "aborted"; + errorMessage?: string; +} + +type TextBlock = { type: "text"; text: string }; +/** `data` is base64. */ +type ImageBlock = { type: "image"; data: string; mimeType: string }; +``` + +Show generated images with `image(block)`. Do not print `data` with `text()`, `console`, or `return`: it is large and the model cannot read it as text. Generated images are not saved to disk; to keep one, write it to a file with a tool. + +```js +// @options: {"timeout_ms": 300000} +const painter = await models.getModelOfType("image", "openrouter", "google/gemini-2.5-flash-image"); +const result = await models.generateImages(painter, { + input: [{ type: "text", text: "A red fox in the snow, watercolor" }], +}); +if (result.stopReason !== "stop") return result.errorMessage; +for (const block of result.output) { + if (block.type === "image") image(block); + else text(block.text); +} +``` + +## Limits + +- A script's VM has 256 MB of memory. Running out throws `InternalError: out of memory`; filter or aggregate large data instead of accumulating it. +- A script that waits on a promise that can never settle (no tool call pending) fails immediately, since there are no timers. +- Scripts cannot start other `codemode` scripts. diff --git a/packages/coding-agent/docs/docs.json b/packages/coding-agent/docs/docs.json index 47b9e5b4d..4382848de 100644 --- a/packages/coding-agent/docs/docs.json +++ b/packages/coding-agent/docs/docs.json @@ -136,6 +136,10 @@ "title": "CLI", "path": "cli.md" }, + { + "title": "Codemode", + "path": "codemode.md" + }, { "title": "Slash Commands", "path": "slash-commands.md" diff --git a/packages/coding-agent/docs/models.md b/packages/coding-agent/docs/models.md index d785a0385..1a866de03 100644 --- a/packages/coding-agent/docs/models.md +++ b/packages/coding-agent/docs/models.md @@ -131,6 +131,8 @@ const result = await models.classify(jev, { return result.answers; ``` +[Codemode](codemode.md#classify) describes the question and answer types. + When the service reports token counts, as all System One services do, `result.usage` carries them with their cost. Pi adds the usage of a script's classifier calls to the `codemode` tool result, so it counts toward the session cost in the footer and `/session`. The cost uses the model's catalog price; models without one, such as TypeSafe's direct `jev-latest`, report tokens at no cost. Extensions call classifiers through `ctx.modelRegistry.classify()`, without codemode. [Virtual models](virtual-models.md#route-requests) can use them to route requests; see the `jev-router.ts` example. @@ -150,7 +152,7 @@ if (result.stopReason !== "stop") return result.errorMessage; for (const block of result.output) if (block.type === "image") image(block); ``` -`input` can also contain `{ type: "image", data, mimeType }` blocks to edit or use as references. Pi adds the usage of a script's image calls to the `codemode` tool result, like classifier calls. Generated images are not saved to disk. +`input` can also contain `{ type: "image", data, mimeType }` blocks to edit or use as references. Pi adds the usage of a script's image calls to the `codemode` tool result, like classifier calls. Generated images are not saved to disk. [Codemode](codemode.md#generate-images) describes the full API. Extensions generate images through `ctx.modelRegistry.generateImages()`, without codemode. diff --git a/packages/coding-agent/docs/settings.md b/packages/coding-agent/docs/settings.md index 689c15b98..02f46e634 100644 --- a/packages/coding-agent/docs/settings.md +++ b/packages/coding-agent/docs/settings.md @@ -38,7 +38,7 @@ See [Choose a Model](models.md) for model selection and thinking controls. | Setting | Type | Default | Description | |---|---|---|---| | `defaultTools` | `string[]` | `read`, `bash`, `edit`, `write` | Tools enabled at startup. Plain names replace the defaults; `+name` adds a tool and `-name` removes one. An empty array disables all built-in tools but not extension or SDK tools. | -| `codemode.mode` | `"on"` \| `"only"` | `"on"` | How the `codemode` tool presents tools while it is active. `on`: declared tools get their `codemode` declaration appended to their description, and `codemode` lists only tools that are not declared. `only`: `codemode` lists every tool scripts can call, and active built-in and extension tools are hidden from the model, so it reaches them through `codemode`. | +| `codemode.mode` | `"on"` \| `"only"` | `"on"` | How the `codemode` tool presents tools while it is active. `on`: declared tools get a note on calling them from scripts appended to their description, and `codemode` lists only tools that are not declared. `only`: `codemode` lists every tool scripts can call, and active built-in and extension tools are hidden from the model, so it reaches them through `codemode`. | | `codemode.inlineBudget` | number | `3000` | Estimated tokens (characters / 4) the `codemode` tool's description may spend on tool declarations. Tools that do not fit are left out and found with `searchTools()`. `0` lists only namespaces. | Available built-in tools are `read`, `bash`, `powershell`, `edit`, `write`, `grep`, `find`, and `ls`. `defaultTools` can also name `codemode` and `tool_search`, which built-in extensions register inactive, and other extension tools registered inactive. diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.ts index 9ae4e53cb..6593b5238 100644 --- a/packages/coding-agent/src/core/settings-manager.ts +++ b/packages/coding-agent/src/core/settings-manager.ts @@ -93,8 +93,8 @@ export interface WarningSettings { /** * How the codemode tool presents tools while it is active. - * - `on`: declared tools that scripts can call get their codemode declaration appended to their - * description; the codemode description lists only the tools without `direct` exposure. + * - `on`: declared tools that scripts can call get a note on calling them from scripts appended to + * their description; the codemode description lists only the tools without `direct` exposure. * - `only`: the codemode description lists every tool scripts can call, and active `direct` tools are * not declared to the model. */ diff --git a/packages/coding-agent/src/core/system-prompt.ts b/packages/coding-agent/src/core/system-prompt.ts index 4970fd4ad..cd02d6cd7 100644 --- a/packages/coding-agent/src/core/system-prompt.ts +++ b/packages/coding-agent/src/core/system-prompt.ts @@ -155,7 +155,7 @@ export function buildSystemPromptSections(input: BuildSystemPromptOptions): Syst - Additional docs: ${getDocsPath()} - Examples: ${getExamplesPath()} (extensions, custom tools, SDK) - When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory -- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md) +- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md), environment variables (docs/environment-variables.md), MCP servers (docs/mcp.md), codemode scripts and non-LLM models such as classifiers and image models (docs/codemode.md) - When working on pi topics, read the docs and examples, and follow .md cross-references before implementing - Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`; } diff --git a/packages/coding-agent/src/core/tools/bash.ts b/packages/coding-agent/src/core/tools/bash.ts index 45bd9df80..4620e2464 100644 --- a/packages/coding-agent/src/core/tools/bash.ts +++ b/packages/coding-agent/src/core/tools/bash.ts @@ -54,12 +54,9 @@ export type BashToolInput = Static; * `output` is not limited like the model-facing output: callers decide how much of it reaches the model. */ const bashOutputSchema = Type.Object({ - output: Type.String({ - description: - "Combined stdout and stderr, up to 1 MiB. Longer output keeps its first and last 512 KiB around an omission marker.", - }), - truncated: Type.Boolean({ description: "Whether `output` omits part of the command output" }), - full_output_path: Type.Optional(Type.String({ description: "Temp file with the full output, when truncated" })), + output: Type.String({ description: "Combined stdout and stderr, possibly truncated" }), + truncated: Type.Boolean(), + full_output_path: Type.Optional(Type.String({ description: "Full output, when truncated" })), exit_code: Type.Number(), wall_time_seconds: Type.Number(), }); diff --git a/packages/coding-agent/src/extensions/codemode/execute.ts b/packages/coding-agent/src/extensions/codemode/execute.ts index b1317e045..3d7bdf66e 100644 --- a/packages/coding-agent/src/extensions/codemode/execute.ts +++ b/packages/coding-agent/src/extensions/codemode/execute.ts @@ -33,6 +33,7 @@ import type { SessionEntry } from "../../core/session-manager.ts"; import { combineUsage } from "../../core/usage-totals.ts"; import { Bm25Ranker, createToolSearchDocument, DEFAULT_TOOL_SEARCH_LIMIT } from "../tool-search/tool.ts"; import { + CODEMODE_DOCS_PATH, CODEMODE_STORE_ENTRY_TYPE, type CodemodeModelRuntime, type CodemodeNestedCall, @@ -41,7 +42,6 @@ import { type CodemodeToolInput, type CodemodeToolOptions, getCodemodeCallableTools, - MODEL_GLOBAL_DECLARATIONS, toCodemodeDeclaration, } from "./tool.ts"; @@ -95,6 +95,93 @@ function toModelInfo(model: AnyModel): Record { return info; } +/** `an image`, `a classifier`. */ +function withArticle(word: string): string { + return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** A script value in an error message: `undefined`, `a string`, `an array`, or its keys (`{ prompt }`). */ +function describeValue(value: unknown): string { + if (value === undefined || value === null) return String(value); + if (Array.isArray(value)) return value.length === 0 ? "an empty array" : "an array"; + if (typeof value === "object") { + const keys = Object.keys(value); + if (keys.length === 0) return "{}"; + return `{ ${keys.slice(0, 6).join(", ")}${keys.length > 6 ? ", ..." : ""} }`; + } + return typeof value === "string" ? "a string" : `a ${typeof value}`; +} + +const CLASSIFIER_CONTEXT_SHAPE = + '{ state: { ... }, questions: { : { type: "choice", instructions, criteria: {