Public: anyone can read this; the crew can change it.
Talk never reads none of a large answer: past 40,000 characters the agent gets its shape and head, and how to ask narrower #16877
Check · Review · Land · Live done — Landed and live in production.
talk/oversize-results → main 0 commits
5 files
changed +240
−3
docs/MCP.md +7
| @@ -101,6 +101,13 @@ tool no longer busts one response, but `test/mcp-size.test.ts` still holds | ||
| 101 | 101 | each page to a 40,000-byte ceiling and a 38,500-byte headroom. Measure before you push with `bun test test/mcp-size.test.ts`; |
| 102 | 102 | a failure names the bytes over and the longest descriptions. |
| 103 | 103 | |
| 104 | That ceiling is the tool list's. A tool's answer has its own: the forge's own agent (a via token) | |
| 105 | is sent at most 40,000 characters of one answer, escapes included (`ANSWER_CHARS_MAX` in | |
| 106 | `src/http/mcp/oversize.ts`), under Claude Code's cap on one tool result. A longer answer comes as | |
| 107 | `{ cut, chars, says, shape, head }`: its keys and array lengths with their first items, its first | |
| 108 | part, and which of the tool's paging arguments (`limit`, `cursor`, `offset`, `page`, `fields`, | |
| 109 | `since`, `q`) read the rest. A person's own token gets every answer whole. | |
| 110 | ||
| 104 | 111 | - A new door is an `action` or `kind` on the tool that already owns the |
| 105 | 112 | resource before it is a new tool. |
| 106 | 113 | Example: `profile` with `action: "export"` answers `GET /api/v1/user/export` (admin scope; a size summary and the link past 16,000 bytes). |
src/crew/conversation_brief.ts +1 −1
| @@ -38,7 +38,7 @@ export const VOICE: readonly string[] = [ | ||
| 38 | 38 | "Speak as the person speaks. Answer in the language they write in and stay in it. Use the forge's own nouns (issue, pull request, repository, branch, crew, autonomy, deploy) only with someone who used them first; with anyone else say what it means for them (\"I have started your game\", \"it is private: only people you invite can open it\"). Put the answer or the next step in the first two lines: someone on a phone reads no further.", |
| 39 | 39 | "When they ask what it costs, how long it takes, who can see it or whether it can be undone, answer that first and plainly from what you can read (their budget, their app's access, what is running). If you cannot read it, say what you do know and where the figure lives; never answer such a question with only that you cannot say. Until something exists that they can open, say when it will and what they will see.", |
| 40 | 40 | "Do the work rather than offer it: start the build, make the change, write the note, then say in a line what you did and how it is undone. Before you start, check that they may do it (their role, their access to that repository); when they may not, say so once with what they can do instead, and never propose it or ask them to approve it. Do not close a reply with an offer they did not ask for.", |
| 41 | "Describe only what you have seen. Read again before you call something current, or say when you read it. After an action, read its result before you describe it; when you cannot see the outcome, say that, and never guess a cause.", | |
| 41 | "Describe only what you have seen. Read again before you call something current, or say when you read it. After an action, read its result before you describe it; when you cannot see the outcome, say that, and never guess a cause. When a fresh read fails or comes back cut, say so and read again narrower; never give figures from earlier turns as current.", | |
| 42 | 42 | "Look for the next useful thing. When it is small and can be undone, do it and say so; when it is larger, say in one line what you would do and why. Keep them updated in a line as work moves, and when they return after time away, begin with where they left off, what changed since, and what needs them.", |
| 43 | 43 | "Keep working until the plan is done or something truly blocks it; never stop to ask whether to continue, and never end a turn on a question the plan already answers. Reversible steps (filing an issue, a comment, labels, an assignee, closing or reopening, an edit, opening a pull) run at once and leave a receipt with Undo; a step held for their yes is asked once, and the rest of the plan goes on around it.", |
| 44 | 44 | ]; |
src/http/mcp.ts +6 −2
| @@ -60,6 +60,7 @@ import { DEFAULT_TOOLS, GUEST_TOOLS, talkLists, wantsAll } from "./mcp/catalog.t | ||
| 60 | 60 | import { roleOf, type Role } from "../core/roles.ts"; |
| 61 | 61 | import { OFFER_TOOL, offerAnswer } from "./mcp/offer.ts"; |
| 62 | 62 | import { OFFER_REQUEST_MAX } from "../actions/offer.ts"; |
| 63 | import { fitAnswer } from "./mcp/oversize.ts"; | |
| 63 | 64 | |
| 64 | 65 | const PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"] as const; |
| 65 | 66 | /** |
| @@ -377,6 +378,8 @@ function rpcOne( | ||
| 377 | 378 | const before = writing ? beforeDirect(ctx, tool.name, args) : undefined; |
| 378 | 379 | readThrough(ctx); |
| 379 | 380 | return Promise.resolve(tool.run(ctx, user, args)).then((ran) => { |
| 381 | // A person's own token, not the forge's own agent: the answer whole, and its card. | |
| 382 | const own = ctx.auth.through === undefined; | |
| 380 | 383 | const unkept = writing && ran.ok ? noteDirect(ctx, user, via, tool.name, args, ran.value, before) : undefined; |
| 381 | 384 | const answer = fenceAnswer(ctx, ran); |
| 382 | 385 | // A card drawn for the forge's own agent is kept for its conversation; the agent reads its |
| @@ -393,9 +396,10 @@ function rpcOne( | ||
| 393 | 396 | return reply( |
| 394 | 397 | answer.ok |
| 395 | 398 | ? { |
| 396 | content: [{ type: "text", text: JSON.stringify(answer.value) }, ...shown], | |
| 399 | // The forge's own agent is never sent more than it can read at once (`mcp/oversize.ts`). | |
| 400 | content: [{ type: "text", text: own ? JSON.stringify(answer.value) : fitAnswer(answer.value, tool) }, ...shown], | |
| 397 | 401 | // The forge's agent reads the fenced text, never a card drawn around it. |
| 398 | ...(ctx.auth.through === undefined | |
| 402 | ...(own | |
| 399 | 403 | ? cardResult(String(params["name"]), answer.value, ctx.url.origin, answer.card) |
| 400 | 404 | : {}), |
| 401 | 405 | } |
src/http/mcp/oversize.ts added +89
| @@ -0,0 +1,89 @@ | ||
| 1 | /** | |
| 2 | * An answer too large for the forge's own agent to read at once is never unreadable. Talk's | |
| 3 | * harness saves a tool result past its limit to a file and hands the agent only the path, and the | |
| 4 | * agent has no shell to open it (v0.7.676: an 86,581-character `cloud_accounts` answer was "read | |
| 5 | * none of it", and the turn fell back on figures from earlier). So past `ANSWER_CHARS_MAX` the | |
| 6 | * agent gets, in one answer it can read: what was cut and how to ask narrower, the answer's shape | |
| 7 | * (each key, each array's length and its first items) and the first part of the answer itself. | |
| 8 | * The bound is on the text sent, escapes and all: the head shrinks until the whole fits. | |
| 9 | * | |
| 10 | * The value given is the fenced one (`fenceAnswer`): every string someone else wrote stays inside | |
| 11 | * its data block in the shape and in the head alike. Plain data in, plain data out. | |
| 12 | */ | |
| 13 | ||
| 14 | /** | |
| 15 | * Most characters of one answer, fenced, the forge's own agent is sent: under Claude Code's cap on | |
| 16 | * one tool result (about 50,000 characters, `MAX_MCP_OUTPUT_TOKENS` 25,000 tokens), and a bound for | |
| 17 | * every runner. `docs/MCP.md` states it beside the tool list's page ceiling. | |
| 18 | */ | |
| 19 | export const ANSWER_CHARS_MAX = 40_000; | |
| 20 | ||
| 21 | /** Characters of the answer's own text the head starts from; it shrinks until the whole fits. */ | |
| 22 | export const HEAD_CHARS = 20_000; | |
| 23 | ||
| 24 | /** Items of each array shown in the shape, and characters of each. */ | |
| 25 | const ITEMS_SHOWN = 3; | |
| 26 | const ITEM_CHARS = 400; | |
| 27 | ||
| 28 | /** Arguments that page or narrow a read: named back to the agent when the tool takes them. */ | |
| 29 | const NARROWING = ["limit", "cursor", "offset", "page", "fields", "since", "q", "query"]; | |
| 30 | ||
| 31 | /** What `fitAnswer` reads of a tool: its name and the arguments its schema names. */ | |
| 32 | export interface Fitted { | |
| 33 | readonly name: string; | |
| 34 | readonly inputSchema: Record<string, unknown>; | |
| 35 | } | |
| 36 | ||
| 37 | const clip = (text: string, max: number): string => (text.length <= max ? text : `${text.slice(0, max)}…`); | |
| 38 | ||
| 39 | /** The value's shape, two levels deep: keys with their kinds, arrays with their length and first items. */ | |
| 40 | export function shapeOf(value: unknown, depth = 0): unknown { | |
| 41 | if (Array.isArray(value)) | |
| 42 | return { | |
| 43 | items: value.length, | |
| 44 | first: value.slice(0, ITEMS_SHOWN).map((v) => (depth >= 1 ? clip(JSON.stringify(v) ?? "null", ITEM_CHARS) : shapeOf(v, depth + 1))), | |
| 45 | }; | |
| 46 | if (value !== null && typeof value === "object") { | |
| 47 | if (depth >= 2) return clip(JSON.stringify(value) ?? "null", ITEM_CHARS); | |
| 48 | return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, shapeOf(v, depth + 1)])); | |
| 49 | } | |
| 50 | return typeof value === "string" ? clip(value, ITEM_CHARS) : value; | |
| 51 | } | |
| 52 | ||
| 53 | /** The top level alone: each key with its kind, an array's length. The shape when the full one is too large. */ | |
| 54 | const keysOf = (value: unknown): unknown => | |
| 55 | Array.isArray(value) | |
| 56 | ? { items: value.length } | |
| 57 | : value !== null && typeof value === "object" | |
| 58 | ? Object.fromEntries(Object.entries(value).map(([k, v]) => [clip(k, 100), Array.isArray(v) ? { items: v.length } : v === null ? "null" : typeof v])) | |
| 59 | : typeof value; | |
| 60 | ||
| 61 | /** | |
| 62 | * The text the agent is sent for this answer: as it is when it fits, else one readable object | |
| 63 | * with `cut`, `chars`, `says`, `shape` and `head`, never longer than `ANSWER_CHARS_MAX`. | |
| 64 | */ | |
| 65 | export function fitAnswer(value: unknown, tool: Fitted): string { | |
| 66 | const whole = JSON.stringify(value) ?? "null"; | |
| 67 | if (whole.length <= ANSWER_CHARS_MAX) return whole; | |
| 68 | const properties = (tool.inputSchema["properties"] ?? {}) as Record<string, unknown>; | |
| 69 | const narrows = NARROWING.filter((k) => k in properties); | |
| 70 | const how = | |
| 71 | narrows.length > 0 | |
| 72 | ? `call \`${tool.name}\` again with ${narrows.map((k) => `\`${k}\``).join(", ")} to read the rest a part at a time` | |
| 73 | : `call \`${tool.name}\` again asking for less, or a tool that reads the one thing you need`; | |
| 74 | const says = `This answer is ${String(whole.length)} characters, more than one read holds, so here are its shape and its first part. Read what you need from them; for the rest, ${how}. Never answer from figures read earlier instead.`; | |
| 75 | const build = (shape: unknown, head: number): string => JSON.stringify({ cut: true, chars: whole.length, says, shape, head: whole.slice(0, head) }); | |
| 76 | // The fullest shape that leaves room for a head, then the top level alone, then none. | |
| 77 | const shapes = [shapeOf(value), keysOf(value), null]; | |
| 78 | for (const shape of shapes) { | |
| 79 | let head = HEAD_CHARS; | |
| 80 | let text = build(shape, head); | |
| 81 | // Escapes grow the head inside its string: shrink it by what is over until the whole fits. | |
| 82 | while (text.length > ANSWER_CHARS_MAX && head > 0) { | |
| 83 | head = Math.max(0, Math.floor(head * (ANSWER_CHARS_MAX / text.length) * 0.98) - 1); | |
| 84 | text = build(shape, head); | |
| 85 | } | |
| 86 | if (text.length <= ANSWER_CHARS_MAX && (head > 0 || shape === null)) return text; | |
| 87 | } | |
| 88 | return build(null, 0); | |
| 89 | } |
test/mcp-oversize.test.ts added +137
| @@ -0,0 +1,137 @@ | ||
| 1 | /** | |
| 2 | * An answer too large for the forge's own agent to read at once is never unreadable | |
| 3 | * (`http/mcp/oversize.ts`): v0.7.676 sent Talk an 86,581-character `cloud_accounts` answer, its | |
| 4 | * harness saved it to a file the agent could not open, and the turn "read none of it" and fell back | |
| 5 | * on old figures. Now a ~90 KB answer reaches the agent as one readable object: what was cut and how | |
| 6 | * to ask narrower, the answer's shape and its head. Anyone else (a person's own token) still gets | |
| 7 | * the whole answer. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 10 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 15 | import { createConversation } from "../src/core/conversations.ts"; | |
| 16 | import { getRepo } from "../src/core/repos.ts"; | |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 18 | import { createUser, type User } from "../src/core/users.ts"; | |
| 19 | import { mintViaToken } from "../src/core/via_token.ts"; | |
| 20 | import { ANSWER_CHARS_MAX, fitAnswer, HEAD_CHARS } from "../src/http/mcp/oversize.ts"; | |
| 21 | import { CONVERSATION_BRIEF } from "../src/crew/conversation_brief.ts"; | |
| 22 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 23 | import { promote } from "./helpers/members.ts"; | |
| 24 | ||
| 25 | let dataDir: string; | |
| 26 | let app: App; | |
| 27 | let servers: Servers; | |
| 28 | let alice: User; | |
| 29 | let rpcId = 1; | |
| 30 | ||
| 31 | const call = async (token: string, name: string, args: Record<string, unknown>) => { | |
| 32 | const res = await fetch(`${servers.url}/mcp`, { | |
| 33 | method: "POST", | |
| 34 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, | |
| 35 | body: JSON.stringify({ jsonrpc: "2.0", id: rpcId++, method: "tools/call", params: { name, arguments: args } }), | |
| 36 | }); | |
| 37 | const body = (await res.json()) as { result?: { content?: { text?: string }[]; isError?: boolean } }; | |
| 38 | return { text: String(body.result?.content?.[0]?.text ?? ""), isError: body.result?.isError === true }; | |
| 39 | }; | |
| 40 | ||
| 41 | /** Something like the production answer: ninety-odd kilobytes of accounts and machines. */ | |
| 42 | const big = () => ({ | |
| 43 | accounts: Array.from({ length: 44 }, (_, i) => ({ | |
| 44 | name: `account-${i}`, | |
| 45 | monthly: `$${i}.00`, | |
| 46 | machines: Array.from({ length: 12 }, (_, j) => ({ name: `test${i}-${j}`, state: j % 2 === 0 ? "running" : "retired", billing: "its kept disk still bills $1.00 a month ".repeat(3) })), | |
| 47 | })), | |
| 48 | total: "$812.00", | |
| 49 | }); | |
| 50 | ||
| 51 | beforeAll(async () => { | |
| 52 | dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-oversize-")); | |
| 53 | app = createApp({ dataDir, port: 0 }); | |
| 54 | servers = await serve(app); | |
| 55 | const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 56 | if (!u.ok) throw new Error(u.error); | |
| 57 | promote(app.db, u.value); | |
| 58 | alice = u.value; | |
| 59 | }, 30_000); | |
| 60 | ||
| 61 | afterAll(async () => { | |
| 62 | servers.stop(); | |
| 63 | app.close(); | |
| 64 | await rm(dataDir, { recursive: true, force: true }); | |
| 65 | }); | |
| 66 | ||
| 67 | test("a ~90 KB answer becomes one readable object: what was cut, how to ask narrower, its shape and its head", () => { | |
| 68 | const value = big(); | |
| 69 | const whole = JSON.stringify(value); | |
| 70 | expect(whole.length).toBeGreaterThan(85_000); | |
| 71 | const text = fitAnswer(value, { name: "cloud_accounts", inputSchema: { properties: { limit: {}, names: {}, cursor: {} } } }); | |
| 72 | expect(text.length).toBeLessThanOrEqual(ANSWER_CHARS_MAX); | |
| 73 | const fitted = JSON.parse(text) as { cut: boolean; chars: number; says: string; shape: { accounts: { items: number; first: unknown[] }; total: string }; head: string }; | |
| 74 | expect(fitted.cut).toBe(true); | |
| 75 | expect(fitted.chars).toBe(whole.length); | |
| 76 | expect(fitted.says).toContain("again with `limit`, `cursor` to read the rest"); | |
| 77 | expect(fitted.says).not.toContain("`names`"); | |
| 78 | expect(fitted.says).toContain("Never answer from figures read earlier"); | |
| 79 | expect(fitted.shape.accounts.items).toBe(44); | |
| 80 | expect(fitted.shape.accounts.first).toHaveLength(3); | |
| 81 | expect(fitted.shape.total).toBe("$812.00"); | |
| 82 | expect(whole.startsWith(fitted.head)).toBe(true); | |
| 83 | expect(fitted.head.length).toBeGreaterThan(5_000); | |
| 84 | expect(text).not.toContain("read none of it"); | |
| 85 | }); | |
| 86 | ||
| 87 | test("an answer that fits is sent as it is", () => { | |
| 88 | expect(fitAnswer({ a: 1 }, { name: "x", inputSchema: {} })).toBe('{"a":1}'); | |
| 89 | }); | |
| 90 | ||
| 91 | test("quote-dense answers stay under the bound with the escapes counted, and keys past counting too", () => { | |
| 92 | const tool = { name: "issues", inputSchema: { properties: { repo: {}, state: {} } } }; | |
| 93 | // Many short string-heavy objects: every quote and backslash doubles inside the head's string. | |
| 94 | const dense = Array.from({ length: 4_000 }, (_, i) => ({ t: `"${i}"`, b: '\\"q"\\', l: ["\"a\"", "\"b\""] })); | |
| 95 | const text = fitAnswer(dense, tool); | |
| 96 | expect(text.length).toBeLessThanOrEqual(ANSWER_CHARS_MAX); | |
| 97 | const fitted = JSON.parse(text) as { cut: boolean; head: string; says: string }; | |
| 98 | expect(fitted.cut).toBe(true); | |
| 99 | expect(fitted.head.length).toBeGreaterThan(1_000); | |
| 100 | expect(JSON.stringify(dense).startsWith(fitted.head)).toBe(true); | |
| 101 | // Identifiers are not paging: a tool with only those is told to ask for less. | |
| 102 | expect(fitted.says).toContain("call `issues` again asking for less"); | |
| 103 | // An object of thousands of keys: its shape alone is too large, and the answer still fits. | |
| 104 | const wide = Object.fromEntries(Array.from({ length: 6_000 }, (_, i) => [`key"${i}"`, `v"${i}"`])); | |
| 105 | const out = fitAnswer(wide, tool); | |
| 106 | expect(out.length).toBeLessThanOrEqual(ANSWER_CHARS_MAX); | |
| 107 | expect((JSON.parse(out) as { cut: boolean }).cut).toBe(true); | |
| 108 | }); | |
| 109 | ||
| 110 | test("through MCP: the forge's own agent gets the head and the shape of a ~90 KB file; a person's token gets it whole", async () => { | |
| 111 | const made = await createRepo(app, alice, { name: "big", visibility: "private" }); | |
| 112 | if (!made.ok) throw new Error(String(made.error)); | |
| 113 | const content = JSON.stringify(big(), null, 1); | |
| 114 | expect(content.length).toBeGreaterThan(85_000); | |
| 115 | const done = await commitToBranch(app, alice, getRepo(app.db, "alice", "big")!, { branch: "main", message: "Big", files: [{ path: "accounts.json", content }] }); | |
| 116 | expect(done.ok).toBe(true); | |
| 117 | const conversation = createConversation(app.db, alice.id); | |
| 118 | if (!conversation.ok) throw new Error(conversation.error); | |
| 119 | const via = mintViaToken(app.db, alice.id, `conversation:${conversation.value.id}`, "what does it cost?", new Date(Date.now() + 600_000).toISOString()); | |
| 120 | if (!via.ok) throw new Error(via.error); | |
| 121 | const agent = await call(via.value.token, "read_file", { repo: "alice/big", path: "accounts.json" }); | |
| 122 | expect(agent.isError).toBe(false); | |
| 123 | expect(agent.text.length).toBeLessThanOrEqual(ANSWER_CHARS_MAX); | |
| 124 | const fitted = JSON.parse(agent.text) as { cut: boolean; says: string; head: string }; | |
| 125 | expect(fitted.cut).toBe(true); | |
| 126 | expect(fitted.head.length).toBeGreaterThan(5_000); | |
| 127 | expect(fitted.head.length).toBeLessThanOrEqual(HEAD_CHARS); | |
| 128 | // read_file takes repo, path and ref: none of them pages, so the hint is to ask for less. | |
| 129 | expect(fitted.says).toContain("call `read_file` again asking for less"); | |
| 130 | expect(agent.text).not.toContain("read none of it"); | |
| 131 | const person = await call(createToken(app.db, alice.id, "own", "rw").token, "read_file", { repo: "alice/big", path: "accounts.json" }); | |
| 132 | expect(person.text.length).toBeGreaterThan(85_000); | |
| 133 | }); | |
| 134 | ||
| 135 | test("the brief tells Talk to say a read came back cut and read narrower, never to give old figures as current", () => { | |
| 136 | expect(CONVERSATION_BRIEF).toContain("When a fresh read fails or comes back cut, say so and read again narrower; never give figures from earlier turns as current."); | |
| 137 | }); |
new above
offline