diff --git a/.changeset/pi-worker-session-tools-split.md b/.changeset/pi-worker-session-tools-split.md new file mode 100644 index 0000000000..97712430f1 --- /dev/null +++ b/.changeset/pi-worker-session-tools-split.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-backend-pi": patch +--- + +The pi backend's worker session is now split into worker launch, a table of RPC handlers with one per method, receipt persistence and the protocol reader. Its curated tools are now one named factory per tool, grouped into file tools, brain tools and the routing for application tools. Turns behave as before: tool names, schemas, results, permission decisions and the worker protocol are unchanged. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 5671220372..b9bcbf8ccf 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1337,7 +1337,7 @@ classification: `Write`/`Edit`/`NotebookEdit` disallow is lifted (`disallowedTools`, `packages/ui-backend-claude/src/sdk-options.ts:405`). In pi, the direct tools and a `bash` whose working directory is the brain root - return (`const bash`, `packages/ui-backend-pi/src/tools.ts:549`). + return (`export function bashTool`, `packages/ui-backend-pi/src/file-tools.ts:151`). - **Approvals do not change.** Confirmation patterns and destructive-operation approvals still run in the permission hooks. The journal adds the ability to undo; it removes no approval. @@ -1443,10 +1443,10 @@ evidence is unproven. The pi backend reports evidence only from its own record of each call's RPCs. A call that names two tools, takes the write lock as a read, or reports only part of its read proves nothing (`export function provenToolExecution`, -`packages/ui-backend-pi/src/worker-session.ts:48-56`). It reports nothing at +`packages/ui-backend-pi/src/worker-session.ts:29-37`). It reports nothing at all for a worker that loads extensions. Extension handlers run on every tool event, bridge reads included, and can write at any time -(`const extensionFree`, `packages/ui-backend-pi/src/worker-session.ts:457`). +(`const extensionFree`, `packages/ui-backend-pi/src/worker-session.ts:139`). With extensions loaded, which is pi's default, every result is observed as before. The worker's reports are evidence only while it has run nothing but curated code. Once it admits a call outside the provable set (`bash`, `grep`, @@ -2763,7 +2763,7 @@ every turn without a proven recipient: document's text there. - Pi resumes that session's own entries (`readPiSession`, - `packages/ui-backend-pi/src/worker-session.ts:99-105`), together with + `packages/ui-backend-pi/src/worker-session.ts:75-81`), together with that session's fixed system-prompt append. Its stored native file observations are content hashes, not text. Pi has no memory folder; its worker receives only `settings.json` (with `auth.json` and `models.json` @@ -3641,7 +3641,7 @@ the accepted cancellation (`cancelAcquiredSession`, runner awaits abort when cancellation prevents prompting. The signal handler may already have requested it, so the worker session shares one abort promise: `ended` revokes work but does not confirm teardown (`abort()`, -`packages/ui-backend-pi/src/worker-session.ts:758-774`). Its inactive path +`packages/ui-backend-pi/src/worker-session.ts:212-228`). Its inactive path awaits exit and protocol consumption, the awaited turn-temp close above, then stdio release even if exit or cleanup refuses. Failed cleanup keeps the reservation charged and remains retryable. Disposal and Stop signalling keep diff --git a/docs/decisions/module-mcp-tools.md b/docs/decisions/module-mcp-tools.md index 777bcf965f..ddb43e12a5 100644 --- a/docs/decisions/module-mcp-tools.md +++ b/docs/decisions/module-mcp-tools.md @@ -413,7 +413,7 @@ failed. - **The pi backend.** It does not use `brain mcp`. It builds its brain tools in-process with its own names (`export const TOOL_RISK`, - `packages/ui-backend-pi/src/tools.ts:226`), and it keeps `bash`, so + `packages/ui-backend-pi/src/tools.ts:117`), and it keeps `bash`, so `brain jobs review` is reachable there already. Serving module tools on pi would need collision rules against pi's flat namespace (`read_file`, `ask_user` and `web_search` all parse as `_`). It needs its diff --git a/docs/plans/host-owned-web-search.md b/docs/plans/host-owned-web-search.md index e49b4b54e4..899f41a06b 100644 --- a/docs/plans/host-owned-web-search.md +++ b/docs/plans/host-owned-web-search.md @@ -216,7 +216,7 @@ runtime authority or a public plugin seam. Both candidates need them: Current source confirms why a bridge is needed: ordinary initialization copies only auth/models/settings (`const init`, -`packages/ui-backend-pi/src/worker-session.ts:178-180`), then selects private Pi +`packages/ui-backend-pi/src/worker-launch.ts:114-116`), then selects private Pi state. The worker RPC schema has an existing bounded, grant-checked bridge but no search method (`export const piWorkerMessage`, `packages/ui-backend-pi/src/worker-protocol.ts:64-75`). Resource discovery remains diff --git a/packages/ui-backend-pi/src/application-tools.ts b/packages/ui-backend-pi/src/application-tools.ts new file mode 100644 index 0000000000..26059e1650 --- /dev/null +++ b/packages/ui-backend-pi/src/application-tools.ts @@ -0,0 +1,76 @@ +/** + * The application-routing layer (#2517): each brain application operation + * becomes a tool that sends its input to the server's authoritative + * `applyBrain`, falling back to the legacy in-process tool of the same name + * only when the turn has no server route. `brain_read_base` supplies the + * same-turn base a routed write needs. + */ +import type { z } from "zod"; +import type { ToolDefinition } from "@earendil-works/pi-coding-agent"; +import { brainApplicationInput, brainReadBaseInput, brainReadBaseResult, BRAIN_APPLICATION_TOOLS, BRAIN_APPLICATION_DESCRIPTIONS, + BRAIN_READ_BASE_DESCRIPTION, type BackendBridge, type BrainReadBaseInput } from "@schlessera/brain-ui-sdk/server"; + +import { toPiParameters } from "./bridge-tools.js"; +import { textResult, type BrainToolKit } from "./tool-kit.js"; + +type ApplicationSchema = (typeof brainApplicationInput.options)[number]; + +/** The routed application tools, in schema order; a direct-write roster keeps its own write and edit. */ +export function routedApplicationTools(kit: BrainToolKit, tools: readonly ToolDefinition[]): ToolDefinition[] { + const { deps } = kit; + return brainApplicationInput.options.filter(schema => !deps.directWrites || !["write", "edit"].includes(schema.shape.operation.value)).map(schema => routedApplicationTool(kit, schema, tools)); +} + +/** One application operation's routed tool; `tools` supplies the legacy tool it replaces. */ +export function routedApplicationTool(kit: BrainToolKit, schema: ApplicationSchema, tools: readonly ToolDefinition[]): ToolDefinition { + const { turn, bases } = kit; + const operation = schema.shape.operation.value; + const name = BRAIN_APPLICATION_TOOLS[operation]; + const legacy = tools.find(t => t.name === name); + const shape = (schema as z.ZodObject).omit({ operation: true }); + // Existing pi inputs gain an optional base; a preceding read in this + // same turn supplies it when absent. No read receipt crosses turns. + const parameters = "expectedBaseHash" in shape.shape + ? shape.extend({ expectedBaseHash: brainApplicationInput.options[0].shape.expectedBaseHash.optional() }) : shape; + return { + name, label: legacy?.label ?? "Apply staged changes", description: BRAIN_APPLICATION_DESCRIPTIONS[operation], + parameters: toPiParameters(parameters), + async execute(id: string, params: Record, signal, onUpdate, ctx) { + const bridge = turn.bridge; + if (!bridge?.applyBrain) { + if (!legacy) throw new Error("No authoritative server application route is available for this turn."); + return legacy.execute(id, params, signal, onUpdate, ctx); + } + const input = { ...params, operation }; + if ("expectedBaseHash" in schema.shape && params.expectedBaseHash === undefined && typeof params.path === "string") { + const receipt = bases.get(bridge)?.get(params.path); + if (receipt === undefined && operation !== "write") throw new Error("Read brain_read_base or read_file first and use that document's exact base hash."); + Object.assign(input, { expectedBaseHash: receipt ?? null }); + } + const pending = bridge.applyBrain(input as Parameters>[0]); + turn.pendingMutations?.add(pending); + let result; + try { result = await pending; } + finally { turn.pendingMutations?.delete(pending); } + if (!result.ok) throw new Error(JSON.stringify(result)); + return textResult(JSON.stringify(result), result); + }, + } satisfies ToolDefinition; +} + +/** `brain_read_base`: the server's base of one document, remembered for this turn's writes. */ +export function brainReadBaseTool(kit: BrainToolKit): ToolDefinition { + const { turn, rememberHash } = kit; + return { + name: "brain_read_base", label: "Read document base", + description: BRAIN_READ_BASE_DESCRIPTION, + parameters: toPiParameters(brainReadBaseInput), + async execute(_id: string, params: BrainReadBaseInput) { + if (!turn.bridge?.readBrainBase) throw new Error("No server document-base reader is available."); + const base = await turn.bridge.readBrainBase(params.path); + rememberHash(params.path, base.expectedBaseHash); + const result = brainReadBaseResult(base, { offset: params.offset, limit: params.limit, column: params.column }); + return textResult(JSON.stringify(result), result); + }, + } satisfies ToolDefinition; +} diff --git a/packages/ui-backend-pi/src/brain-tools.ts b/packages/ui-backend-pi/src/brain-tools.ts new file mode 100644 index 0000000000..2e79c5af63 --- /dev/null +++ b/packages/ui-backend-pi/src/brain-tools.ts @@ -0,0 +1,436 @@ +/** + * The curated brain tools (#2517): the read paths of the brain MCP surface + * (`brain_search`, `brain_context`, `brain_read`, `brain_list`, + * `brain_graph`) and the legacy in-process writers (`brain_add`, + * `brain_update`, `brain_archive`), one named factory each. + */ +import { Type } from "typebox"; +import { readFileSync } from "fs"; + +import type { ToolDefinition } from "@earendil-works/pi-coding-agent"; +import { BRAIN_LOCK_KEY } from "@schlessera/brain-ui-sdk/server"; +import { isIsoDate, readDocumentPart, SEARCH_SORTS, type SearchOptions } from "@schlessera/brain/internal"; + +import { clip, MAX_OUTPUT_BYTES, MAX_READ_BYTES, PI_BRAIN_UPDATE_TOOL_NAME, textResult, type BrainToolKit } from "./tool-kit.js"; + +/** The input `brain_search` accepts, in the names the model sends. */ +interface BrainSearchParams { + query: string; + type?: string; + tag?: string; + limit?: number; + updated_since?: string; + updated_before?: string; + deadline_from?: string; + deadline_to?: string; + sort?: SearchOptions["sort"]; + upcoming?: boolean; +} + +/** + * The longest JSON a listing or a graph returns: the budget text output is + * clipped at. JSON is never clipped as text, which would not parse; it is + * cut by structure instead, whole rows or whole edges at a time. + */ +const MAX_JSON_CHARS = MAX_OUTPUT_BYTES; + +/** Width of the largest omission count, so the reserved size is never short. */ +const COUNT_PLACEHOLDER = Number.MAX_SAFE_INTEGER; + +/** + * A listing within MAX_JSON_CHARS: the rows in order while they fit, then + * `truncated: true` and how many rows were left out. + */ +function fitListing(documents: T[]): { documents: T[]; truncated?: true; omitted?: number } { + const whole = { documents }; + if (JSON.stringify(whole).length <= MAX_JSON_CHARS) return whole; + let size = JSON.stringify({ documents: [], truncated: true, omitted: COUNT_PLACEHOLDER }).length; + const kept: T[] = []; + for (const doc of documents) { + const cost = JSON.stringify(doc).length + (kept.length > 0 ? 1 : 0); + if (size + cost > MAX_JSON_CHARS) break; + kept.push(doc); + size += cost; + } + return { documents: kept, truncated: true, omitted: documents.length - kept.length }; +} + +/** + * A graph within MAX_JSON_CHARS: edges in walk order while they and the + * nodes of their endpoints fit, then `truncated: true` and how many edges + * were left out. Every returned edge keeps its endpoint nodes; nodes stay in + * path order. + */ +function fitGraph( + edges: E[], + nodes: N[] +): { edges: E[]; nodes: N[]; truncated?: true; omitted_edges?: number } { + const whole = { edges, nodes }; + if (JSON.stringify(whole).length <= MAX_JSON_CHARS) return whole; + const byPath = new Map(nodes.map((n) => [n.path, n])); + let size = JSON.stringify({ edges: [], nodes: [], truncated: true, omitted_edges: COUNT_PLACEHOLDER }).length; + const kept: E[] = []; + const keptNodes = new Set(); + for (const edge of edges) { + const fresh = [edge.source, ...(edge.resolved ? [edge.target] : [])].filter( + (p, i, all) => !keptNodes.has(p) && byPath.has(p) && all.indexOf(p) === i + ); + let cost = JSON.stringify(edge).length + (kept.length > 0 ? 1 : 0); + for (const path of fresh) cost += JSON.stringify(byPath.get(path)).length + (keptNodes.size > 0 || path !== fresh[0] ? 1 : 0); + if (size + cost > MAX_JSON_CHARS) break; + kept.push(edge); + for (const path of fresh) keptNodes.add(path); + size += cost; + } + return { + edges: kept, + nodes: nodes.filter((n) => keptNodes.has(n.path)), + truncated: true, + omitted_edges: edges.length - kept.length, + }; +} + +/** `brain_search`: hybrid search with explicit date filters and sorts. */ +export function brainSearchTool(kit: BrainToolKit): ToolDefinition { + const { brain } = kit; + return { + name: "brain_search", + label: "Search brain", + description: + "Hybrid (full-text + vector) search across the knowledge base. Prefer this " + + "over grep for finding notes by meaning. Returns ranked results with snippets. " + + "For questions about time (\"what is due next\", \"what changed this week\"), turn the " + + "dates into the date filters yourself (YYYY-MM-DD, inclusive) and pick a sort; " + + "upcoming is a shortcut for deadline_from today, sort deadline.", + parameters: Type.Object({ + query: Type.String({ description: "Natural-language or keyword query." }), + type: Type.Optional(Type.String({ description: "Filter by document type." })), + tag: Type.Optional(Type.String({ description: "Filter by tag." })), + limit: Type.Optional(Type.Number({ description: "Max results (default 10)." })), + updated_since: Type.Optional(Type.String({ description: "Only documents updated on or after this date (YYYY-MM-DD)." })), + updated_before: Type.Optional(Type.String({ description: "Only documents updated on or before this date (YYYY-MM-DD)." })), + deadline_from: Type.Optional(Type.String({ description: "Only documents with a deadline on or after this date (YYYY-MM-DD)." })), + deadline_to: Type.Optional(Type.String({ description: "Only documents with a deadline on or before this date (YYYY-MM-DD)." })), + sort: Type.Optional( + Type.Union(SEARCH_SORTS.map((s) => Type.Literal(s)), { + description: "Result order: score (default), updated (newest first) or deadline (earliest first, undated last).", + }) + ), + upcoming: Type.Optional( + Type.Boolean({ description: "Same as deadline_from today and sort deadline; an explicit deadline_from or sort wins." }) + ), + }), + async execute(_id: string, params: BrainSearchParams) { + // Core also refuses a bad date or sort; checking the dates here names the + // input the model sent (deadline_from, not deadlineFrom). + for (const key of ["updated_since", "updated_before", "deadline_from", "deadline_to"] as const) { + const value = params[key]; + if (value !== undefined && (typeof value !== "string" || !isIsoDate(value))) { + throw new Error(`${key} must be a date written YYYY-MM-DD, got ${JSON.stringify(value)}`); + } + } + const { results, warnings } = await brain.search({ + query: params.query, + type: params.type, + tag: params.tag, + limit: params.limit ?? 10, + updatedSince: params.updated_since, + updatedBefore: params.updated_before, + deadlineFrom: params.deadline_from ?? (params.upcoming ? new Date().toISOString().slice(0, 10) : undefined), + deadlineTo: params.deadline_to, + sort: params.sort ?? (params.upcoming ? "deadline" : undefined), + }); + const lines: string[] = []; + for (const w of warnings) lines.push(`> ${w}`); + if (results.length === 0) lines.push("No results found."); + for (const r of results) { + lines.push( + `- ${r.path} — ${r.title} [${r.type}]` + + (r.snippet ? `\n ${r.snippet}` : "") + ); + } + return textResult(clip(lines.join("\n")), { count: results.length }); + }, + } satisfies ToolDefinition; +} + +/** `brain_context`: a token-limited context block for a query. */ +export function brainContextTool(kit: BrainToolKit): ToolDefinition { + const { brain } = kit; + return { + name: "brain_context", + label: "Assemble context", + description: + "Assemble a token-limited markdown context block of the most relevant notes " + + "for a query. Use to ground an answer in the knowledge base.", + parameters: Type.Object({ + query: Type.String({ description: "What to gather context about." }), + maxTokens: Type.Optional(Type.Number({ description: "Token budget (default 4000)." })), + }), + async execute(_id: string, params: { query: string; maxTokens?: number }) { + const block = await brain.context(params.query, params.maxTokens ?? 4000); + return textResult(block || "No relevant context found.", { query: params.query }); + }, + } satisfies ToolDefinition; +} + +/** `brain_read`: one document, a section of it or its outline. */ +export function brainReadTool(kit: BrainToolKit): ToolDefinition { + const { resolveOrThrow, rememberBase } = kit; + return { + name: "brain_read", + label: "Read brain document", + description: + "Read a specific document from the brain knowledge base by its relative path. " + + "By default returns the whole file, frontmatter included, clipped only at the tool's output limit. " + + "Pass `section` to get one section by its heading (matched on its visible text, ignoring case; " + + "the first of two equal headings wins), or `max_tokens` to get the frontmatter and an outline of " + + "headings with their token counts instead of a file larger than that. `max_tokens` is the threshold " + + "for switching to the outline, not a cap on the output.", + parameters: Type.Object({ + path: Type.String({ description: 'Repo-relative document path, e.g. "me/identity.md".' }), + section: Type.Optional( + Type.String({ + description: + "Heading text of one section to return, from its heading to the next heading of the same or higher level.", + }) + ), + max_tokens: Type.Optional( + Type.Integer({ + minimum: 1, + description: + "Threshold, not a cap: when the result would be larger than this, return the frontmatter and an outline instead.", + }) + ), + }), + async execute(_id: string, params: { path: string; section?: string; max_tokens?: number }) { + const abs = resolveOrThrow(params.path); + // The same reader as the MCP tool and `brain read`; with neither option + // it returns the file untouched, so the default read is unchanged. The + // byte clip applies to what it selected, so a section past the clip + // point of the whole file is still reachable. + const raw = readFileSync(abs, "utf-8"); + rememberBase(params.path, raw); + const text = readDocumentPart(raw, { + section: params.section, + maxTokens: params.max_tokens, + sectionHint: 'section: ""', + }); + return textResult(clip(text, MAX_READ_BYTES), { path: params.path }); + }, + } satisfies ToolDefinition; +} + +/** `brain_list`: document metadata, cut by whole rows. */ +export function brainListTool(kit: BrainToolKit): ToolDefinition { + const { brain } = kit; + return { + name: "brain_list", + label: "List brain documents", + description: + "List documents in the brain knowledge base with optional filters for type, tag, " + + "status, and relevance. Returns metadata (path, title, type, relevance, status, tags).", + parameters: Type.Object({ + type: Type.Optional(Type.String({ description: "Filter by document type." })), + tag: Type.Optional(Type.String({ description: "Filter by tag." })), + status: Type.Optional( + Type.String({ description: "Filter by status (active, archived, draft)." }) + ), + relevance: Type.Optional( + Type.String({ description: "Filter by relevance (primary, secondary, historical)." }) + ), + limit: Type.Optional(Type.Number({ description: "Max results (default 20)." })), + }), + async execute( + _id: string, + params: { type?: string; tag?: string; status?: string; relevance?: string; limit?: number } + ) { + const documents = await brain.list(params); + // Compact, and cut by whole rows to MAX_JSON_CHARS: a byte-clipped JSON + // document would not parse. + return textResult(JSON.stringify(fitListing(documents)), { + count: documents.length, + }); + }, + } satisfies ToolDefinition; +} + +/** `brain_graph`: the wiki-link graph from one document, cut by whole edges. */ +export function brainGraphTool(kit: BrainToolKit): ToolDefinition { + const { brain } = kit; + return { + name: "brain_graph", + label: "Brain link graph", + description: + "Traverse the wiki-link graph from a starting document. Returns edges " + + "(source, target, resolved) showing how documents are connected via [[wiki-links]], " + + "and nodes (path, title, type, summary, updated) for every document an edge touches. " + + "A graph too large to return whole keeps its first edges with their nodes and says " + + "`truncated: true` with `omitted_edges`.", + parameters: Type.Object({ + path: Type.String({ description: "Starting document path." }), + depth: Type.Optional(Type.Number({ description: "How many hops to traverse (default 1)." })), + direction: Type.Optional( + Type.String({ + description: 'Link direction: "outgoing", "incoming", or "both" (default).', + }) + ), + }), + async execute( + _id: string, + params: { path: string; depth?: number; direction?: string } + ) { + const direction = + params.direction === "outgoing" || params.direction === "incoming" + ? params.direction + : "both"; + const { edges, nodes } = await brain.graph({ path: params.path, depth: params.depth, direction }); + // Compact, and cut by whole edges to MAX_JSON_CHARS: a byte-clipped + // JSON document would not parse, and every returned edge keeps its + // endpoint nodes. + return textResult(JSON.stringify(fitGraph(edges, nodes)), { count: edges.length }); + }, + } satisfies ToolDefinition; +} + +/** `brain_add`: capture new content under the brain-docs lock key. */ +export function brainAddTool(kit: BrainToolKit): ToolDefinition { + const { brain, lock } = kit; + return { + name: "brain_add", + label: "Add to brain", + description: + "Capture content into the brain (classifies, writes a markdown file, reindexes). " + + "Prefer this over write_file for new notes.", + parameters: Type.Object({ + content: Type.String({ description: "The note content (first line becomes the title)." }), + type: Type.Optional(Type.String({ description: "Explicit document type." })), + title: Type.Optional(Type.String({ description: "Explicit title." })), + tags: Type.Optional(Type.Array(Type.String(), { description: "Tags." })), + }), + async execute( + _id: string, + params: { content: string; type?: string; title?: string; tags?: string[] } + ) { + // brain.add writes a markdown file and reindexes — brain-docs key. + return lock.withKey(BRAIN_LOCK_KEY, async () => { + const outcome = await brain.add({ + content: params.content, + type: params.type, + title: params.title, + tags: params.tags, + }); + const warn = outcome.indexed ? "" : ` (warning: reindex failed — ${outcome.indexError})`; + return textResult(`${outcome.action}: ${outcome.path}${warn}`, outcome); + }); + }, + } satisfies ToolDefinition; +} + +/** `brain_update`: frontmatter and appended content under the brain-docs lock key. */ +export function brainUpdateTool(kit: BrainToolKit): ToolDefinition { + const { brain, lock } = kit; + return { + name: PI_BRAIN_UPDATE_TOOL_NAME, + label: "Update brain document", + description: + "Update an existing brain document: set frontmatter fields (summary, status, " + + "relevance, tags, deadline, next_review) and/or append a markdown section to the " + + "body. Bumps the `updated` field and reindexes. Setting status to archived also " + + "demotes a primary or unset relevance to historical, as brain_archive does, " + + "including a primary passed in the same call. Does not create files — use " + + "brain_add for that.", + parameters: Type.Object({ + path: Type.String({ description: "Repo-relative document path." }), + summary: Type.Optional(Type.String({ description: "New one-line summary." })), + status: Type.Optional( + Type.String({ description: "New status: active, archived, or draft." }) + ), + relevance: Type.Optional( + Type.String({ description: "New relevance: primary, secondary, or historical." }) + ), + tags: Type.Optional( + Type.Array(Type.String(), { description: "Tags (replaces existing tags)." }) + ), + deadline: Type.Optional( + Type.String({ description: "Deadline date (ISO 8601), or empty string to remove." }) + ), + next_review: Type.Optional( + Type.String({ description: "Next review date (ISO 8601), or empty string to remove." }) + ), + append_content: Type.Optional( + Type.String({ description: "Markdown appended to the end of the document body." }) + ), + }), + async execute( + _id: string, + params: { + path: string; + summary?: string; + status?: string; + relevance?: string; + tags?: string[]; + deadline?: string; + next_review?: string; + append_content?: string; + } + ) { + const status = + params.status === "active" || params.status === "archived" || params.status === "draft" + ? params.status + : undefined; + if (params.status !== undefined && status === undefined) { + throw new Error(`Invalid status "${params.status}" — use active, archived, or draft.`); + } + const relevance = + params.relevance === "primary" || + params.relevance === "secondary" || + params.relevance === "historical" + ? params.relevance + : undefined; + if (params.relevance !== undefined && relevance === undefined) { + throw new Error( + `Invalid relevance "${params.relevance}" — use primary, secondary, or historical.` + ); + } + // Write + reindex — brain-docs key, like the other document writers. + return lock.withKey(BRAIN_LOCK_KEY, async () => { + const outcome = await brain.update({ + path: params.path, + summary: params.summary, + status, + relevance, + tags: params.tags, + deadline: params.deadline, + nextReview: params.next_review, + appendContent: params.append_content, + }); + return textResult(JSON.stringify(outcome, null, 2), outcome); + }); + }, + } satisfies ToolDefinition; +} + +/** `brain_archive`: archive one document under the brain-docs lock key. */ +export function brainArchiveTool(kit: BrainToolKit): ToolDefinition { + const { brain, lock } = kit; + return { + name: "brain_archive", + label: "Archive brain document", + description: + "Archive a brain document: sets status to archived, sets a primary or unset relevance " + + "to historical, moves projects/active/ files to projects/archive/, and reindexes. " + + "Requires user approval (an archived document drops out of search and briefings). " + + "Use dry_run to preview.", + parameters: Type.Object({ + path: Type.String({ description: "Repo-relative document path." }), + dry_run: Type.Optional(Type.Boolean({ description: "Preview without changing anything." })), + }), + async execute(_id: string, params: { path: string; dry_run?: boolean }) { + return lock.withKey(BRAIN_LOCK_KEY, async () => { + const outcome = await brain.archive(params.path, params.dry_run ?? false); + return textResult(JSON.stringify(outcome, null, 2), outcome); + }); + }, + } satisfies ToolDefinition; +} diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts new file mode 100644 index 0000000000..af9f962356 --- /dev/null +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -0,0 +1,220 @@ +/** + * The curated file and shell tools (#2517): `read_file`, `grep`, + * `write_file`, `edit_file` and `bash`, one named factory each. Every factory + * reads the shared per-roster state from its `BrainToolKit`; `createBrainTools` + * in tools.ts decides the roster order. + */ +import { spawn } from "bun"; +import { createHash } from "node:crypto"; +import { readFileSync, writeFileSync, mkdirSync } from "fs"; +import { dirname } from "path"; +import { Type } from "typebox"; + +import type { ToolDefinition } from "@earendil-works/pi-coding-agent"; +import { bashLockKey, killWrapped, rtkRewriteCommand, wrapCommand } from "@schlessera/brain-ui-sdk/server"; +import { RTK_WORKER_ENV, execWrapperSpawnOptions, WORKER_DATA_ROOT, WORKER_EGRESS_TRANSPORT_ENV } from "@schlessera/brain-ui-sdk/internal"; + +import { resolveEnabledWebSearchEnvNames, ambientExecConfig, subprocessEnv } from "./config/env.js"; +import { clip, MAX_READ_BYTES, textResult, type BrainToolKit } from "./tool-kit.js"; + +/** `read_file`: one repo-contained UTF-8 file, remembered as a same-turn base. */ +export function readFileTool(kit: BrainToolKit): ToolDefinition { + const { deps, turn, resolveOrThrow, rememberHash } = kit; + return { + name: "read_file", + label: "Read file", + description: + "Read a UTF-8 text file from the brain repository. Path is relative to the repo root.", + parameters: Type.Object({ + path: Type.String({ description: "Repo-relative file path." }), + }), + async execute(_id: string, params: { path: string }) { + const abs = resolveOrThrow(params.path); + await deps.nativeFileObservation?.("read_start", params.path, _id); + const bytes = readFileSync(abs); + await deps.nativeFileObservation?.("read_end", params.path, _id); + const hash = rememberHash(params.path, createHash("sha256").update(bytes).digest("hex")); + return textResult(clip(bytes.toString("utf-8"), MAX_READ_BYTES), { path: params.path, ...(turn.bridge?.applyBrain ? { expectedBaseHash: hash } : {}) }); + }, + } satisfies ToolDefinition; +} + +/** `grep`: a regular-expression search scoped to the repository. */ +export function grepTool(kit: BrainToolKit): ToolDefinition { + const { deps, brain, resolveOrThrow } = kit; + return { + name: "grep", + label: "Grep", + description: + "Search file contents in the brain repository with a regular expression. " + + "Returns matching lines as `path:line: text`.", + parameters: Type.Object({ + pattern: Type.String({ description: "Regular expression to search for." }), + path: Type.Optional( + Type.String({ description: "Repo-relative subtree to search (default: whole repo)." }) + ), + }), + async execute(_id: string, params: { pattern: string; path?: string }, signal?: AbortSignal) { + // Containment: scope the search path to the repo; grep runs with cwd=repo. + const rel = params.path ?? "."; + resolveOrThrow(rel); + const exec = deps.exec ?? ambientExecConfig(); + const proc = spawn(wrapCommand(["grep", "-rInE", "--", params.pattern, rel], exec.wrapper), { + cwd: brain.root, + env: subprocessEnv([...resolveEnabledWebSearchEnvNames(), ...WORKER_EGRESS_TRANSPORT_ENV]), + stdout: "pipe", + stderr: "pipe", + ...execWrapperSpawnOptions(exec.wrapper), + }); + const onAbort = () => killWrapped(proc, exec); + signal?.addEventListener("abort", onAbort, { once: true }); + const [out] = await Promise.all([new Response(proc.stdout).text(), proc.exited]); + signal?.removeEventListener("abort", onAbort); + const text = out.trim(); + return textResult(text ? clip(text) : "No matches.", { pattern: params.pattern }); + }, + } satisfies ToolDefinition; +} + +/** `write_file`: create or overwrite one file under its own path lock. */ +export function writeFileTool(kit: BrainToolKit): ToolDefinition { + const { deps, lock, resolveOrThrow, rememberBase, assertDirectBase } = kit; + return { + name: "write_file", + label: "Write file", + description: + "Create or overwrite a UTF-8 text file in the brain repository. Path is relative to the repo root.", + parameters: Type.Object({ + path: Type.String({ description: "Repo-relative file path." }), + content: Type.String({ description: "Full file contents to write." }), + }), + async execute(_id: string, params: { path: string; content: string }) { + // Per-path lock: writes to the same file serialize, different files run + // in parallel. Approval (when the gate requires one) already happened + // in the tool_call event. + const abs = resolveOrThrow(params.path); + return lock.withKey(`path:${abs}`, async () => { + await deps.nativeFileObservation?.("write_check", params.path, _id); + assertDirectBase(abs); + mkdirSync(dirname(abs), { recursive: true }); + writeFileSync(abs, params.content, "utf-8"); + rememberBase(params.path, params.content); + await deps.nativeFileObservation?.("write_end", params.path, _id); + return textResult(`Wrote ${params.content.length} bytes to ${params.path}.`, { + path: params.path, + }); + }); + }, + } satisfies ToolDefinition; +} + +/** `edit_file`: replace one unique string under the file's own path lock. */ +export function editFileTool(kit: BrainToolKit): ToolDefinition { + const { deps, lock, resolveOrThrow, rememberBase, assertDirectBase } = kit; + return { + name: "edit_file", + label: "Edit file", + description: + "Replace an exact, unique string in a brain-repo file. old_string must occur exactly once.", + parameters: Type.Object({ + path: Type.String({ description: "Repo-relative file path." }), + old_string: Type.String({ description: "Exact text to replace (must be unique)." }), + new_string: Type.String({ description: "Replacement text." }), + }), + async execute( + _id: string, + params: { path: string; old_string: string; new_string: string } + ) { + // Read-modify-write is atomic under the file's own lock key. + const abs = resolveOrThrow(params.path); + return lock.withKey(`path:${abs}`, async () => { + await deps.nativeFileObservation?.("write_check", params.path, _id); + assertDirectBase(abs); + const raw = readFileSync(abs, "utf-8"); + const occurrences = raw.split(params.old_string).length - 1; + if (occurrences === 0) throw new Error(`old_string not found in ${params.path}.`); + if (occurrences > 1) { + throw new Error( + `old_string is not unique in ${params.path} (${occurrences} matches); add more context.` + ); + } + writeFileSync(abs, raw.replace(params.old_string, params.new_string), "utf-8"); + rememberBase(params.path, raw.replace(params.old_string, params.new_string)); + await deps.nativeFileObservation?.("write_end", params.path, _id); + return textResult(`Edited ${params.path}.`, { path: params.path }); + }); + }, + } satisfies ToolDefinition; +} + +/** `bash`: one shell command under the shared bash lock-key policy. */ +export function bashTool(kit: BrainToolKit): ToolDefinition { + const { deps, brain, turn, lock } = kit; + return { + name: "bash", + label: "Run bash", + description: + (deps.shellCwd === WORKER_DATA_ROOT ? `Run a bash command in this turn's read-only data tree (${WORKER_DATA_ROOT}): the brain's documents with every change this turn applied. Write files under $BRAIN_WORKER_SCRATCH. ` + : deps.shellCwd ? "Run a bash command in writable worker scratch. The authoritative brain is read-only. " : "Run a bash command in the brain repository root. ") + "Combined stdout+stderr is " + + "returned. Destructive command shapes (recursive delete, history rewrites, " + + "brain archive) raise a confirmation card before running.", + parameters: Type.Object({ + command: Type.String({ description: "The bash command line to execute." }), + }), + async execute(_id: string, params: { command: string }, signal?: AbortSignal) { + signal = signal && turn.signal ? AbortSignal.any([signal, turn.signal]) : signal ?? turn.signal ?? undefined; + // The tool_call gate has already confirmed a destructive-pattern match + // by now (and may have edited the command via updatedInput). The rtk + // rewrite runs AFTER the gate, so confirm patterns see the command as + // the model wrote it; when rtk is absent or declines, it is untouched. + const childEnv: NodeJS.ProcessEnv = { ...subprocessEnv([...resolveEnabledWebSearchEnvNames(), ...WORKER_EGRESS_TRANSPORT_ENV]), ...RTK_WORKER_ENV }; + // A non-interactive bash sources the file BASH_ENV names (sh reads ENV), + // here and in every shell the command starts (#2960). + delete childEnv.BASH_ENV; + delete childEnv.ENV; + const cmd = await rtkRewriteCommand(params.command, childEnv); + if (signal?.aborted) throw new DOMException("Tool cancelled before lock admission", "AbortError"); + // Only commands that touch git staging/history or the brain CLI's + // write path take a lock (shared bashLockKey policy) — builds, greps, + // curls and other reads run in parallel, across sessions and across + // sibling tool calls in one message. + return lock.withKey(bashLockKey(params.command), async () => { + if (signal?.aborted) throw new DOMException("Tool cancelled before subprocess execution", "AbortError"); + const exec = deps.exec ?? ambientExecConfig(); + // Not a login shell (#2960): `-l` sourced /etc/profile and the first + // profile under HOME before every command, so their output reached + // the result and anything they exported, PATH included, overrode the + // allowlisted childEnv. --noprofile --norc reads no startup file; the + // command sees exactly childEnv. + const proc = spawn(wrapCommand(["bash", "--noprofile", "--norc", "-c", cmd], exec.wrapper), { + cwd: deps.shellCwd ?? brain.root, + env: childEnv, + stdout: "pipe", + stderr: "pipe", + ...execWrapperSpawnOptions(exec.wrapper), + }); + let killedByAbort = false; + const onAbort = () => { + killedByAbort = true; + killWrapped(proc, exec); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + const [stdout, stderr, code] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + signal?.removeEventListener("abort", onAbort); + const body = [stdout, stderr].filter(Boolean).join("\n").trim(); + // The exit line goes after the clip, so a long failing output still + // ends with it: the host classifies a nonzero exit from it (#1671). + const output = `${clip(body || "(no output)")}${code === 0 ? "" : `\n[exit ${code}]`}`; + // Pi turns thrown tool errors into Activity-visible error results. + // Keep the exit evidence, but distinguish a host abort from a command + // that independently exited with the same status (including 143). + if (killedByAbort) throw new DOMException(`Tool cancelled by abort\n${output}`, "AbortError"); + return textResult(output, { exitCode: code }); + }); + }, + } satisfies ToolDefinition; +} diff --git a/packages/ui-backend-pi/src/tool-kit.ts b/packages/ui-backend-pi/src/tool-kit.ts new file mode 100644 index 0000000000..eb65a931be --- /dev/null +++ b/packages/ui-backend-pi/src/tool-kit.ts @@ -0,0 +1,102 @@ +/** + * What every curated tool factory shares within one `createBrainTools` call + * (#2517): the turn-bound lock, repository containment and the same-turn + * read receipts that later writes use as their base. + */ +import { createHash } from "node:crypto"; +import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { NativeFileVersions, nativeFileVersion } from "@schlessera/brain-ui-sdk/internal"; + +import type { BrainAccess } from "./brain-access.js"; +import type { BrainToolDeps, ToolLock } from "./tools.js"; +import type { TurnContext } from "./turn-context.js"; + +export const MAX_READ_BYTES = 100_000; +export const MAX_OUTPUT_BYTES = 30_000; + +/** + * Name of the document update tool. Auto-allowed by DEFAULT_PI_ALLOWED_TOOLS, and gated on one + * input shape (`status: "archived"`) by the permission gate — the two must + * agree, so they read the same constant. + */ +export const PI_BRAIN_UPDATE_TOOL_NAME = "brain_update"; + +/** Result helper: pi tools return content parts + arbitrary details. */ +export function textResult(text: string, details: unknown = null) { + return { content: [{ type: "text" as const, text }], details }; +} + +export function clip(text: string, max = MAX_OUTPUT_BYTES): string { + if (text.length <= max) return text; + return text.slice(0, max) + `\n… [truncated ${text.length - max} bytes]`; +} + +export interface BrainToolKit { + deps: BrainToolDeps; + brain: BrainAccess; + turn: TurnContext; + /** `deps.lock`, admitted under the current turn's signal, priority and yield. */ + lock: ToolLock; + /** The absolute path of a repo-relative one; throws when it escapes the repository. */ + resolveOrThrow(rel: string): string; + /** Remembers the whole-document hash of `raw` as `path`'s base; returns it. */ + rememberBase(path: string, raw: string): string; + /** Remembers `hash` as `path`'s base for this turn's writes; returns it. */ + rememberHash(path: string, hash: string): string; + /** Refuses a direct write whose file changed since this roster observed it. */ + assertDirectBase(abs: string): void; + /** Same-turn read receipts, per bridge: no read receipt crosses turns. */ + bases: WeakMap>; +} + +export function createBrainToolKit(deps: BrainToolDeps): BrainToolKit { + const { brain, turn } = deps; + const lock: ToolLock = { + withKey: (key, body) => { + const pending = turn.pendingMutations; + const work = deps.lock.withKey(key, body, { + signal: turn.signal ?? undefined, + priority: turn.autonomous ? "autonomous" : "interactive", + onYield: turn.autonomous?.onYield, + yieldAfterMs: turn.autonomous?.yieldAfterMs, + timeoutMs: 30_000, + }); + pending?.add(work); + void work.then(() => pending?.delete(work), () => pending?.delete(work)); + return work; + }, + }; + + const resolveOrThrow = (rel: string): string => { + const abs = brain.resolveInRepo(rel); + if (!abs) { + throw new Error( + `Path "${rel}" escapes the brain repository and was refused.` + ); + } + return abs; + }; + + const bases = new WeakMap>(); + const directBases = new NativeFileVersions(); + const rememberBase = (path: string, raw: string): string => + rememberHash(path, createHash("sha256").update(raw, "utf8").digest("hex")); + // The receipt is always a whole-document hash: a paged brain_read_base + // remembers the server's hash, never one recomputed from its page. + const rememberHash = (path: string, hash: string): string => { + // No storage: the in-memory base is immediate and nothing is persisted. + if (deps.directWrites) void directBases.remember(resolveOrThrow(path), hash); + if (turn.bridge?.applyBrain) { + let entries = bases.get(turn.bridge); + if (!entries) { entries = new Map(); bases.set(turn.bridge, entries); } + entries.set(path, hash); + } + return hash; + }; + const assertDirectBase = (abs: string): void => { + if (!deps.directWrites || !directBases.hasObservation(abs)) return; + const refusal = directBases.check(abs, nativeFileVersion(abs)); + if (refusal) throw new Error(refusal); + }; + return { deps, brain, turn, lock, resolveOrThrow, rememberBase, rememberHash, assertDirectBase, bases }; +} diff --git a/packages/ui-backend-pi/src/tools.ts b/packages/ui-backend-pi/src/tools.ts index bf913565a8..95c400e4f1 100644 --- a/packages/ui-backend-pi/src/tools.ts +++ b/packages/ui-backend-pi/src/tools.ts @@ -1,8 +1,4 @@ -import { z } from "zod"; -import { createHash } from "node:crypto"; -import { brainApplicationInput, brainReadBaseInput, brainReadBaseResult, BRAIN_APPLICATION_TOOLS, BRAIN_APPLICATION_DESCRIPTIONS, - BRAIN_READ_BASE_DESCRIPTION, type BackendBridge, type BrainReadBaseInput } from "@schlessera/brain-ui-sdk/server"; -import { toPiParameters } from "./bridge-tools.js"; +import { ASK_USER_TOOL_NAME, BRIDGE_TOOL_POSTURE } from "@schlessera/brain-ui-sdk/server"; /** * The curated brain tool surface for the pi backend. * @@ -28,126 +24,21 @@ import { toPiParameters } from "./bridge-tools.js"; * is pinned to the repo cwd. */ -import { spawn } from "bun"; -import { readFileSync, writeFileSync, mkdirSync } from "fs"; -import { dirname } from "path"; -import { Type } from "typebox"; - import type { ToolDefinition } from "@earendil-works/pi-coding-agent"; import type { KeyedLock, KeyedLockAcquireOptions, WriteLock } from "@schlessera/brain-ui-sdk/server"; import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; -import { killWrapped } from "@schlessera/brain-ui-sdk/server"; -import { RTK_WORKER_ENV, NativeFileVersions, nativeFileVersion, execWrapperSpawnOptions, WORKER_DATA_ROOT, WORKER_EGRESS_TRANSPORT_ENV } from "@schlessera/brain-ui-sdk/internal"; -import { - ASK_USER_TOOL_NAME, BRIDGE_TOOL_POSTURE, - bashLockKey, - BRAIN_LOCK_KEY, - rtkRewriteCommand, - wrapCommand, -} from "@schlessera/brain-ui-sdk/server"; - -import { isIsoDate, readDocumentPart, SEARCH_SORTS, type SearchOptions } from "@schlessera/brain/internal"; import { createPiBridgeTools } from "./bridge-tools.js"; -import { - resolveEnabledWebSearchEnvNames, - ambientExecConfig, - subprocessEnv, -} from "./config/env.js"; +import { brainReadBaseTool, routedApplicationTools } from "./application-tools.js"; +import { brainAddTool, brainArchiveTool, brainContextTool, brainGraphTool, brainListTool, brainReadTool, brainSearchTool, brainUpdateTool } from "./brain-tools.js"; +import { bashTool, editFileTool, grepTool, readFileTool, writeFileTool } from "./file-tools.js"; +import { createBrainToolKit } from "./tool-kit.js"; import type { BrainAccess } from "./brain-access.js"; import type { TurnContext } from "./turn-context.js"; /** Risk class — documentation of which tools can mutate the working tree. */ export type RiskClass = "read" | "mutate"; -const MAX_READ_BYTES = 100_000; -const MAX_OUTPUT_BYTES = 30_000; - -/** Result helper: pi tools return content parts + arbitrary details. */ -interface BrainSearchParams { - query: string; - type?: string; - tag?: string; - limit?: number; - updated_since?: string; - updated_before?: string; - deadline_from?: string; - deadline_to?: string; - sort?: SearchOptions["sort"]; - upcoming?: boolean; -} - -function textResult(text: string, details: unknown = null) { - return { content: [{ type: "text" as const, text }], details }; -} - -/** - * The longest JSON a listing or a graph returns: the budget text output is - * clipped at. JSON is never clipped as text, which would not parse; it is - * cut by structure instead, whole rows or whole edges at a time. - */ -const MAX_JSON_CHARS = MAX_OUTPUT_BYTES; - -/** Width of the largest omission count, so the reserved size is never short. */ -const COUNT_PLACEHOLDER = Number.MAX_SAFE_INTEGER; - -/** - * A listing within MAX_JSON_CHARS: the rows in order while they fit, then - * `truncated: true` and how many rows were left out. - */ -function fitListing(documents: T[]): { documents: T[]; truncated?: true; omitted?: number } { - const whole = { documents }; - if (JSON.stringify(whole).length <= MAX_JSON_CHARS) return whole; - let size = JSON.stringify({ documents: [], truncated: true, omitted: COUNT_PLACEHOLDER }).length; - const kept: T[] = []; - for (const doc of documents) { - const cost = JSON.stringify(doc).length + (kept.length > 0 ? 1 : 0); - if (size + cost > MAX_JSON_CHARS) break; - kept.push(doc); - size += cost; - } - return { documents: kept, truncated: true, omitted: documents.length - kept.length }; -} - -/** - * A graph within MAX_JSON_CHARS: edges in walk order while they and the - * nodes of their endpoints fit, then `truncated: true` and how many edges - * were left out. Every returned edge keeps its endpoint nodes; nodes stay in - * path order. - */ -function fitGraph( - edges: E[], - nodes: N[] -): { edges: E[]; nodes: N[]; truncated?: true; omitted_edges?: number } { - const whole = { edges, nodes }; - if (JSON.stringify(whole).length <= MAX_JSON_CHARS) return whole; - const byPath = new Map(nodes.map((n) => [n.path, n])); - let size = JSON.stringify({ edges: [], nodes: [], truncated: true, omitted_edges: COUNT_PLACEHOLDER }).length; - const kept: E[] = []; - const keptNodes = new Set(); - for (const edge of edges) { - const fresh = [edge.source, ...(edge.resolved ? [edge.target] : [])].filter( - (p, i, all) => !keptNodes.has(p) && byPath.has(p) && all.indexOf(p) === i - ); - let cost = JSON.stringify(edge).length + (kept.length > 0 ? 1 : 0); - for (const path of fresh) cost += JSON.stringify(byPath.get(path)).length + (keptNodes.size > 0 || path !== fresh[0] ? 1 : 0); - if (size + cost > MAX_JSON_CHARS) break; - kept.push(edge); - for (const path of fresh) keptNodes.add(path); - size += cost; - } - return { - edges: kept, - nodes: nodes.filter((n) => keptNodes.has(n.path)), - truncated: true, - omitted_edges: edges.length - kept.length, - }; -} - -function clip(text: string, max = MAX_OUTPUT_BYTES): string { - if (text.length <= max) return text; - return text.slice(0, max) + `\n… [truncated ${text.length - max} bytes]`; -} /** * The serialization seam the tools run their mutating bodies through. `key` @@ -297,625 +188,39 @@ export const DEFAULT_PI_ALLOWED_TOOLS: readonly string[] = [ "subagent", ]; -/** - * Name of the document update tool. Auto-allowed above, and gated on one - * input shape (`status: "archived"`) by the permission gate — the two must - * agree, so they read the same constant. - */ -export const PI_BRAIN_UPDATE_TOOL_NAME = "brain_update"; +export { PI_BRAIN_UPDATE_TOOL_NAME } from "./tool-kit.js"; /** Name of pi's tappable-choice tool — also stated in the agent surface brief. From its contract, not a roster position (#2800). */ export const PI_ASK_USER_TOOL_NAME = ASK_USER_TOOL_NAME; +/** + * The curated roster in its provider-facing order: the file and brain tools, + * the host's bridge tools, then each application operation routed to the + * server (replacing the legacy tool of the same name) and `brain_read_base`. + */ export function createBrainTools(deps: BrainToolDeps): ToolDefinition[] { - const { brain, turn, capabilities } = deps; - const lock: ToolLock = { - withKey: (key, body) => { - const pending = turn.pendingMutations; - const work = deps.lock.withKey(key, body, { - signal: turn.signal ?? undefined, - priority: turn.autonomous ? "autonomous" : "interactive", - onYield: turn.autonomous?.onYield, - yieldAfterMs: turn.autonomous?.yieldAfterMs, - timeoutMs: 30_000, - }); - pending?.add(work); - void work.then(() => pending?.delete(work), () => pending?.delete(work)); - return work; - }, - }; - - const resolveOrThrow = (rel: string): string => { - const abs = brain.resolveInRepo(rel); - if (!abs) { - throw new Error( - `Path "${rel}" escapes the brain repository and was refused.` - ); - } - return abs; - }; - - const bases = new WeakMap>(); - const directBases = new NativeFileVersions(); - const rememberBase = (path: string, raw: string): string => - rememberHash(path, createHash("sha256").update(raw, "utf8").digest("hex")); - // The receipt is always a whole-document hash: a paged brain_read_base - // remembers the server's hash, never one recomputed from its page. - const rememberHash = (path: string, hash: string): string => { - // No storage: the in-memory base is immediate and nothing is persisted. - if (deps.directWrites) void directBases.remember(resolveOrThrow(path), hash); - if (turn.bridge?.applyBrain) { - let entries = bases.get(turn.bridge); - if (!entries) { entries = new Map(); bases.set(turn.bridge, entries); } - entries.set(path, hash); - } - return hash; - }; - const assertDirectBase = (abs: string): void => { - if (!deps.directWrites || !directBases.hasObservation(abs)) return; - const refusal = directBases.check(abs, nativeFileVersion(abs)); - if (refusal) throw new Error(refusal); - }; - const read_file = { - name: "read_file", - label: "Read file", - description: - "Read a UTF-8 text file from the brain repository. Path is relative to the repo root.", - parameters: Type.Object({ - path: Type.String({ description: "Repo-relative file path." }), - }), - async execute(_id: string, params: { path: string }) { - const abs = resolveOrThrow(params.path); - await deps.nativeFileObservation?.("read_start", params.path, _id); - const bytes = readFileSync(abs); - await deps.nativeFileObservation?.("read_end", params.path, _id); - const hash = rememberHash(params.path, createHash("sha256").update(bytes).digest("hex")); - return textResult(clip(bytes.toString("utf-8"), MAX_READ_BYTES), { path: params.path, ...(turn.bridge?.applyBrain ? { expectedBaseHash: hash } : {}) }); - }, - } satisfies ToolDefinition; - - const grep = { - name: "grep", - label: "Grep", - description: - "Search file contents in the brain repository with a regular expression. " + - "Returns matching lines as `path:line: text`.", - parameters: Type.Object({ - pattern: Type.String({ description: "Regular expression to search for." }), - path: Type.Optional( - Type.String({ description: "Repo-relative subtree to search (default: whole repo)." }) - ), - }), - async execute(_id: string, params: { pattern: string; path?: string }, signal?: AbortSignal) { - // Containment: scope the search path to the repo; grep runs with cwd=repo. - const rel = params.path ?? "."; - resolveOrThrow(rel); - const exec = deps.exec ?? ambientExecConfig(); - const proc = spawn(wrapCommand(["grep", "-rInE", "--", params.pattern, rel], exec.wrapper), { - cwd: brain.root, - env: subprocessEnv([...resolveEnabledWebSearchEnvNames(), ...WORKER_EGRESS_TRANSPORT_ENV]), - stdout: "pipe", - stderr: "pipe", - ...execWrapperSpawnOptions(exec.wrapper), - }); - const onAbort = () => killWrapped(proc, exec); - signal?.addEventListener("abort", onAbort, { once: true }); - const [out] = await Promise.all([new Response(proc.stdout).text(), proc.exited]); - signal?.removeEventListener("abort", onAbort); - const text = out.trim(); - return textResult(text ? clip(text) : "No matches.", { pattern: params.pattern }); - }, - } satisfies ToolDefinition; - - const brain_search = { - name: "brain_search", - label: "Search brain", - description: - "Hybrid (full-text + vector) search across the knowledge base. Prefer this " + - "over grep for finding notes by meaning. Returns ranked results with snippets. " + - "For questions about time (\"what is due next\", \"what changed this week\"), turn the " + - "dates into the date filters yourself (YYYY-MM-DD, inclusive) and pick a sort; " + - "upcoming is a shortcut for deadline_from today, sort deadline.", - parameters: Type.Object({ - query: Type.String({ description: "Natural-language or keyword query." }), - type: Type.Optional(Type.String({ description: "Filter by document type." })), - tag: Type.Optional(Type.String({ description: "Filter by tag." })), - limit: Type.Optional(Type.Number({ description: "Max results (default 10)." })), - updated_since: Type.Optional(Type.String({ description: "Only documents updated on or after this date (YYYY-MM-DD)." })), - updated_before: Type.Optional(Type.String({ description: "Only documents updated on or before this date (YYYY-MM-DD)." })), - deadline_from: Type.Optional(Type.String({ description: "Only documents with a deadline on or after this date (YYYY-MM-DD)." })), - deadline_to: Type.Optional(Type.String({ description: "Only documents with a deadline on or before this date (YYYY-MM-DD)." })), - sort: Type.Optional( - Type.Union(SEARCH_SORTS.map((s) => Type.Literal(s)), { - description: "Result order: score (default), updated (newest first) or deadline (earliest first, undated last).", - }) - ), - upcoming: Type.Optional( - Type.Boolean({ description: "Same as deadline_from today and sort deadline; an explicit deadline_from or sort wins." }) - ), - }), - async execute(_id: string, params: BrainSearchParams) { - // Core also refuses a bad date or sort; checking the dates here names the - // input the model sent (deadline_from, not deadlineFrom). - for (const key of ["updated_since", "updated_before", "deadline_from", "deadline_to"] as const) { - const value = params[key]; - if (value !== undefined && (typeof value !== "string" || !isIsoDate(value))) { - throw new Error(`${key} must be a date written YYYY-MM-DD, got ${JSON.stringify(value)}`); - } - } - const { results, warnings } = await brain.search({ - query: params.query, - type: params.type, - tag: params.tag, - limit: params.limit ?? 10, - updatedSince: params.updated_since, - updatedBefore: params.updated_before, - deadlineFrom: params.deadline_from ?? (params.upcoming ? new Date().toISOString().slice(0, 10) : undefined), - deadlineTo: params.deadline_to, - sort: params.sort ?? (params.upcoming ? "deadline" : undefined), - }); - const lines: string[] = []; - for (const w of warnings) lines.push(`> ${w}`); - if (results.length === 0) lines.push("No results found."); - for (const r of results) { - lines.push( - `- ${r.path} — ${r.title} [${r.type}]` + - (r.snippet ? `\n ${r.snippet}` : "") - ); - } - return textResult(clip(lines.join("\n")), { count: results.length }); - }, - } satisfies ToolDefinition; - - const brain_context = { - name: "brain_context", - label: "Assemble context", - description: - "Assemble a token-limited markdown context block of the most relevant notes " + - "for a query. Use to ground an answer in the knowledge base.", - parameters: Type.Object({ - query: Type.String({ description: "What to gather context about." }), - maxTokens: Type.Optional(Type.Number({ description: "Token budget (default 4000)." })), - }), - async execute(_id: string, params: { query: string; maxTokens?: number }) { - const block = await brain.context(params.query, params.maxTokens ?? 4000); - return textResult(block || "No relevant context found.", { query: params.query }); - }, - } satisfies ToolDefinition; - - const write_file = { - name: "write_file", - label: "Write file", - description: - "Create or overwrite a UTF-8 text file in the brain repository. Path is relative to the repo root.", - parameters: Type.Object({ - path: Type.String({ description: "Repo-relative file path." }), - content: Type.String({ description: "Full file contents to write." }), - }), - async execute(_id: string, params: { path: string; content: string }) { - // Per-path lock: writes to the same file serialize, different files run - // in parallel. Approval (when the gate requires one) already happened - // in the tool_call event. - const abs = resolveOrThrow(params.path); - return lock.withKey(`path:${abs}`, async () => { - await deps.nativeFileObservation?.("write_check", params.path, _id); - assertDirectBase(abs); - mkdirSync(dirname(abs), { recursive: true }); - writeFileSync(abs, params.content, "utf-8"); - rememberBase(params.path, params.content); - await deps.nativeFileObservation?.("write_end", params.path, _id); - return textResult(`Wrote ${params.content.length} bytes to ${params.path}.`, { - path: params.path, - }); - }); - }, - } satisfies ToolDefinition; - - const edit_file = { - name: "edit_file", - label: "Edit file", - description: - "Replace an exact, unique string in a brain-repo file. old_string must occur exactly once.", - parameters: Type.Object({ - path: Type.String({ description: "Repo-relative file path." }), - old_string: Type.String({ description: "Exact text to replace (must be unique)." }), - new_string: Type.String({ description: "Replacement text." }), - }), - async execute( - _id: string, - params: { path: string; old_string: string; new_string: string } - ) { - // Read-modify-write is atomic under the file's own lock key. - const abs = resolveOrThrow(params.path); - return lock.withKey(`path:${abs}`, async () => { - await deps.nativeFileObservation?.("write_check", params.path, _id); - assertDirectBase(abs); - const raw = readFileSync(abs, "utf-8"); - const occurrences = raw.split(params.old_string).length - 1; - if (occurrences === 0) throw new Error(`old_string not found in ${params.path}.`); - if (occurrences > 1) { - throw new Error( - `old_string is not unique in ${params.path} (${occurrences} matches); add more context.` - ); - } - writeFileSync(abs, raw.replace(params.old_string, params.new_string), "utf-8"); - rememberBase(params.path, raw.replace(params.old_string, params.new_string)); - await deps.nativeFileObservation?.("write_end", params.path, _id); - return textResult(`Edited ${params.path}.`, { path: params.path }); - }); - }, - } satisfies ToolDefinition; - - const bash = { - name: "bash", - label: "Run bash", - description: - (deps.shellCwd === WORKER_DATA_ROOT ? `Run a bash command in this turn's read-only data tree (${WORKER_DATA_ROOT}): the brain's documents with every change this turn applied. Write files under $BRAIN_WORKER_SCRATCH. ` - : deps.shellCwd ? "Run a bash command in writable worker scratch. The authoritative brain is read-only. " : "Run a bash command in the brain repository root. ") + "Combined stdout+stderr is " + - "returned. Destructive command shapes (recursive delete, history rewrites, " + - "brain archive) raise a confirmation card before running.", - parameters: Type.Object({ - command: Type.String({ description: "The bash command line to execute." }), - }), - async execute(_id: string, params: { command: string }, signal?: AbortSignal) { - signal = signal && turn.signal ? AbortSignal.any([signal, turn.signal]) : signal ?? turn.signal ?? undefined; - // The tool_call gate has already confirmed a destructive-pattern match - // by now (and may have edited the command via updatedInput). The rtk - // rewrite runs AFTER the gate, so confirm patterns see the command as - // the model wrote it; when rtk is absent or declines, it is untouched. - const childEnv: NodeJS.ProcessEnv = { ...subprocessEnv([...resolveEnabledWebSearchEnvNames(), ...WORKER_EGRESS_TRANSPORT_ENV]), ...RTK_WORKER_ENV }; - // A non-interactive bash sources the file BASH_ENV names (sh reads ENV), - // here and in every shell the command starts (#2960). - delete childEnv.BASH_ENV; - delete childEnv.ENV; - const cmd = await rtkRewriteCommand(params.command, childEnv); - if (signal?.aborted) throw new DOMException("Tool cancelled before lock admission", "AbortError"); - // Only commands that touch git staging/history or the brain CLI's - // write path take a lock (shared bashLockKey policy) — builds, greps, - // curls and other reads run in parallel, across sessions and across - // sibling tool calls in one message. - return lock.withKey(bashLockKey(params.command), async () => { - if (signal?.aborted) throw new DOMException("Tool cancelled before subprocess execution", "AbortError"); - const exec = deps.exec ?? ambientExecConfig(); - // Not a login shell (#2960): `-l` sourced /etc/profile and the first - // profile under HOME before every command, so their output reached - // the result and anything they exported, PATH included, overrode the - // allowlisted childEnv. --noprofile --norc reads no startup file; the - // command sees exactly childEnv. - const proc = spawn(wrapCommand(["bash", "--noprofile", "--norc", "-c", cmd], exec.wrapper), { - cwd: deps.shellCwd ?? brain.root, - env: childEnv, - stdout: "pipe", - stderr: "pipe", - ...execWrapperSpawnOptions(exec.wrapper), - }); - let killedByAbort = false; - const onAbort = () => { - killedByAbort = true; - killWrapped(proc, exec); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - const [stdout, stderr, code] = await Promise.all([ - new Response(proc.stdout).text(), - new Response(proc.stderr).text(), - proc.exited, - ]); - signal?.removeEventListener("abort", onAbort); - const body = [stdout, stderr].filter(Boolean).join("\n").trim(); - // The exit line goes after the clip, so a long failing output still - // ends with it: the host classifies a nonzero exit from it (#1671). - const output = `${clip(body || "(no output)")}${code === 0 ? "" : `\n[exit ${code}]`}`; - // Pi turns thrown tool errors into Activity-visible error results. - // Keep the exit evidence, but distinguish a host abort from a command - // that independently exited with the same status (including 143). - if (killedByAbort) throw new DOMException(`Tool cancelled by abort\n${output}`, "AbortError"); - return textResult(output, { exitCode: code }); - }); - }, - } satisfies ToolDefinition; - - const brain_add = { - name: "brain_add", - label: "Add to brain", - description: - "Capture content into the brain (classifies, writes a markdown file, reindexes). " + - "Prefer this over write_file for new notes.", - parameters: Type.Object({ - content: Type.String({ description: "The note content (first line becomes the title)." }), - type: Type.Optional(Type.String({ description: "Explicit document type." })), - title: Type.Optional(Type.String({ description: "Explicit title." })), - tags: Type.Optional(Type.Array(Type.String(), { description: "Tags." })), - }), - async execute( - _id: string, - params: { content: string; type?: string; title?: string; tags?: string[] } - ) { - // brain.add writes a markdown file and reindexes — brain-docs key. - return lock.withKey(BRAIN_LOCK_KEY, async () => { - const outcome = await brain.add({ - content: params.content, - type: params.type, - title: params.title, - tags: params.tags, - }); - const warn = outcome.indexed ? "" : ` (warning: reindex failed — ${outcome.indexError})`; - return textResult(`${outcome.action}: ${outcome.path}${warn}`, outcome); - }); - }, - } satisfies ToolDefinition; - - const brain_read = { - name: "brain_read", - label: "Read brain document", - description: - "Read a specific document from the brain knowledge base by its relative path. " + - "By default returns the whole file, frontmatter included, clipped only at the tool's output limit. " + - "Pass `section` to get one section by its heading (matched on its visible text, ignoring case; " + - "the first of two equal headings wins), or `max_tokens` to get the frontmatter and an outline of " + - "headings with their token counts instead of a file larger than that. `max_tokens` is the threshold " + - "for switching to the outline, not a cap on the output.", - parameters: Type.Object({ - path: Type.String({ description: 'Repo-relative document path, e.g. "me/identity.md".' }), - section: Type.Optional( - Type.String({ - description: - "Heading text of one section to return, from its heading to the next heading of the same or higher level.", - }) - ), - max_tokens: Type.Optional( - Type.Integer({ - minimum: 1, - description: - "Threshold, not a cap: when the result would be larger than this, return the frontmatter and an outline instead.", - }) - ), - }), - async execute(_id: string, params: { path: string; section?: string; max_tokens?: number }) { - const abs = resolveOrThrow(params.path); - // The same reader as the MCP tool and `brain read`; with neither option - // it returns the file untouched, so the default read is unchanged. The - // byte clip applies to what it selected, so a section past the clip - // point of the whole file is still reachable. - const raw = readFileSync(abs, "utf-8"); - rememberBase(params.path, raw); - const text = readDocumentPart(raw, { - section: params.section, - maxTokens: params.max_tokens, - sectionHint: 'section: ""', - }); - return textResult(clip(text, MAX_READ_BYTES), { path: params.path }); - }, - } satisfies ToolDefinition; - - const brain_list = { - name: "brain_list", - label: "List brain documents", - description: - "List documents in the brain knowledge base with optional filters for type, tag, " + - "status, and relevance. Returns metadata (path, title, type, relevance, status, tags).", - parameters: Type.Object({ - type: Type.Optional(Type.String({ description: "Filter by document type." })), - tag: Type.Optional(Type.String({ description: "Filter by tag." })), - status: Type.Optional( - Type.String({ description: "Filter by status (active, archived, draft)." }) - ), - relevance: Type.Optional( - Type.String({ description: "Filter by relevance (primary, secondary, historical)." }) - ), - limit: Type.Optional(Type.Number({ description: "Max results (default 20)." })), - }), - async execute( - _id: string, - params: { type?: string; tag?: string; status?: string; relevance?: string; limit?: number } - ) { - const documents = await brain.list(params); - // Compact, and cut by whole rows to MAX_JSON_CHARS: a byte-clipped JSON - // document would not parse. - return textResult(JSON.stringify(fitListing(documents)), { - count: documents.length, - }); - }, - } satisfies ToolDefinition; - - const brain_graph = { - name: "brain_graph", - label: "Brain link graph", - description: - "Traverse the wiki-link graph from a starting document. Returns edges " + - "(source, target, resolved) showing how documents are connected via [[wiki-links]], " + - "and nodes (path, title, type, summary, updated) for every document an edge touches. " + - "A graph too large to return whole keeps its first edges with their nodes and says " + - "`truncated: true` with `omitted_edges`.", - parameters: Type.Object({ - path: Type.String({ description: "Starting document path." }), - depth: Type.Optional(Type.Number({ description: "How many hops to traverse (default 1)." })), - direction: Type.Optional( - Type.String({ - description: 'Link direction: "outgoing", "incoming", or "both" (default).', - }) - ), - }), - async execute( - _id: string, - params: { path: string; depth?: number; direction?: string } - ) { - const direction = - params.direction === "outgoing" || params.direction === "incoming" - ? params.direction - : "both"; - const { edges, nodes } = await brain.graph({ path: params.path, depth: params.depth, direction }); - // Compact, and cut by whole edges to MAX_JSON_CHARS: a byte-clipped - // JSON document would not parse, and every returned edge keeps its - // endpoint nodes. - return textResult(JSON.stringify(fitGraph(edges, nodes)), { count: edges.length }); - }, - } satisfies ToolDefinition; - - const brain_update = { - name: PI_BRAIN_UPDATE_TOOL_NAME, - label: "Update brain document", - description: - "Update an existing brain document: set frontmatter fields (summary, status, " + - "relevance, tags, deadline, next_review) and/or append a markdown section to the " + - "body. Bumps the `updated` field and reindexes. Setting status to archived also " + - "demotes a primary or unset relevance to historical, as brain_archive does, " + - "including a primary passed in the same call. Does not create files — use " + - "brain_add for that.", - parameters: Type.Object({ - path: Type.String({ description: "Repo-relative document path." }), - summary: Type.Optional(Type.String({ description: "New one-line summary." })), - status: Type.Optional( - Type.String({ description: "New status: active, archived, or draft." }) - ), - relevance: Type.Optional( - Type.String({ description: "New relevance: primary, secondary, or historical." }) - ), - tags: Type.Optional( - Type.Array(Type.String(), { description: "Tags (replaces existing tags)." }) - ), - deadline: Type.Optional( - Type.String({ description: "Deadline date (ISO 8601), or empty string to remove." }) - ), - next_review: Type.Optional( - Type.String({ description: "Next review date (ISO 8601), or empty string to remove." }) - ), - append_content: Type.Optional( - Type.String({ description: "Markdown appended to the end of the document body." }) - ), - }), - async execute( - _id: string, - params: { - path: string; - summary?: string; - status?: string; - relevance?: string; - tags?: string[]; - deadline?: string; - next_review?: string; - append_content?: string; - } - ) { - const status = - params.status === "active" || params.status === "archived" || params.status === "draft" - ? params.status - : undefined; - if (params.status !== undefined && status === undefined) { - throw new Error(`Invalid status "${params.status}" — use active, archived, or draft.`); - } - const relevance = - params.relevance === "primary" || - params.relevance === "secondary" || - params.relevance === "historical" - ? params.relevance - : undefined; - if (params.relevance !== undefined && relevance === undefined) { - throw new Error( - `Invalid relevance "${params.relevance}" — use primary, secondary, or historical.` - ); - } - // Write + reindex — brain-docs key, like the other document writers. - return lock.withKey(BRAIN_LOCK_KEY, async () => { - const outcome = await brain.update({ - path: params.path, - summary: params.summary, - status, - relevance, - tags: params.tags, - deadline: params.deadline, - nextReview: params.next_review, - appendContent: params.append_content, - }); - return textResult(JSON.stringify(outcome, null, 2), outcome); - }); - }, - } satisfies ToolDefinition; - - const brain_archive = { - name: "brain_archive", - label: "Archive brain document", - description: - "Archive a brain document: sets status to archived, sets a primary or unset relevance " + - "to historical, moves projects/active/ files to projects/archive/, and reindexes. " + - "Requires user approval (an archived document drops out of search and briefings). " + - "Use dry_run to preview.", - parameters: Type.Object({ - path: Type.String({ description: "Repo-relative document path." }), - dry_run: Type.Optional(Type.Boolean({ description: "Preview without changing anything." })), - }), - async execute(_id: string, params: { path: string; dry_run?: boolean }) { - return lock.withKey(BRAIN_LOCK_KEY, async () => { - const outcome = await brain.archive(params.path, params.dry_run ?? false); - return textResult(JSON.stringify(outcome, null, 2), outcome); - }); - }, - } satisfies ToolDefinition; - + const kit = createBrainToolKit(deps); const tools: ToolDefinition[] = [ - read_file, - grep, - brain_search, - brain_context, - brain_read, - brain_list, - brain_graph, - write_file, - edit_file, - bash, - brain_add, - brain_update, - brain_archive, + readFileTool(kit), + grepTool(kit), + brainSearchTool(kit), + brainContextTool(kit), + brainReadTool(kit), + brainListTool(kit), + brainGraphTool(kit), + writeFileTool(kit), + editFileTool(kit), + bashTool(kit), + brainAddTool(kit), + brainUpdateTool(kit), + brainArchiveTool(kit), ...createPiBridgeTools({ - brainPath: brain.root, - turn, - capabilities, + brainPath: deps.brain.root, + turn: deps.turn, + capabilities: deps.capabilities, }), ]; - const routed = brainApplicationInput.options.filter(schema => !deps.directWrites || !["write", "edit"].includes(schema.shape.operation.value)).map(schema => { - const operation = schema.shape.operation.value; - const name = BRAIN_APPLICATION_TOOLS[operation]; - const legacy = tools.find(t => t.name === name); - const shape = (schema as z.ZodObject).omit({ operation: true }); - // Existing pi inputs gain an optional base; a preceding read in this - // same turn supplies it when absent. No read receipt crosses turns. - const parameters = "expectedBaseHash" in shape.shape - ? shape.extend({ expectedBaseHash: brainApplicationInput.options[0].shape.expectedBaseHash.optional() }) : shape; - return { - name, label: legacy?.label ?? "Apply staged changes", description: BRAIN_APPLICATION_DESCRIPTIONS[operation], - parameters: toPiParameters(parameters), - async execute(id: string, params: Record, signal, onUpdate, ctx) { - const bridge = turn.bridge; - if (!bridge?.applyBrain) { - if (!legacy) throw new Error("No authoritative server application route is available for this turn."); - return legacy.execute(id, params, signal, onUpdate, ctx); - } - const input = { ...params, operation }; - if ("expectedBaseHash" in schema.shape && params.expectedBaseHash === undefined && typeof params.path === "string") { - const receipt = bases.get(bridge)?.get(params.path); - if (receipt === undefined && operation !== "write") throw new Error("Read brain_read_base or read_file first and use that document's exact base hash."); - Object.assign(input, { expectedBaseHash: receipt ?? null }); - } - const pending = bridge.applyBrain(input as Parameters>[0]); - turn.pendingMutations?.add(pending); - let result; - try { result = await pending; } - finally { turn.pendingMutations?.delete(pending); } - if (!result.ok) throw new Error(JSON.stringify(result)); - return textResult(JSON.stringify(result), result); - }, - } satisfies ToolDefinition; - }); - const readBase = { - name: "brain_read_base", label: "Read document base", - description: BRAIN_READ_BASE_DESCRIPTION, - parameters: toPiParameters(brainReadBaseInput), - async execute(_id: string, params: BrainReadBaseInput) { - if (!turn.bridge?.readBrainBase) throw new Error("No server document-base reader is available."); - const base = await turn.bridge.readBrainBase(params.path); - rememberHash(params.path, base.expectedBaseHash); - const result = brainReadBaseResult(base, { offset: params.offset, limit: params.limit, column: params.column }); - return textResult(JSON.stringify(result), result); - }, - } satisfies ToolDefinition; + const routed = routedApplicationTools(kit, tools); + const readBase = brainReadBaseTool(kit); return [...tools.filter(t => !routed.some(r => r.name === t.name)), ...routed, readBase]; } diff --git a/packages/ui-backend-pi/src/turn-runner.ts b/packages/ui-backend-pi/src/turn-runner.ts index 1b3a97332f..5d1e5fc86f 100644 --- a/packages/ui-backend-pi/src/turn-runner.ts +++ b/packages/ui-backend-pi/src/turn-runner.ts @@ -51,26 +51,7 @@ export function createPiTurnRunner( // the same classified terminal failure as an overflow during the turn. let acquired: Awaited>; try { acquired = await pool.acquire(req); } - catch (error) { - // Acquisition now observes cancellation while preparing native inputs. - // Keep the existing terminal contract when no session was acquired. - if (req.signal.aborted && (error === req.signal.reason || error instanceof DOMException && error.name === "AbortError")) { - if (req.sessionId) req.bridge.emit({ type: "result", sessionId: req.sessionId, outcome: "cancelled", isError: false, - durationMs: Date.now() - startedAt, numTurns: 0 }); - else req.bridge.emit({ type: "error", code: "agent_error", message: "The turn was cancelled before a session was acquired." }); - return; - } - // A busy turn-temp budget (#1703) refuses the same way, with Retry. - // By class: the process ledger may come from another copy of the SDK. - const busy = (error as { errorClass?: unknown } | null)?.errorClass === FIRST_PARTY_FAILURE_CLASSES.worker_state_busy; - if (!(error instanceof SessionTooLargeError || busy)) throw error; - const failure = { errorClass: (error as { errorClass: string }).errorClass, message: (error as Error).message }; - if (req.sessionId) { - req.bridge.emit({ type: "result", sessionId: req.sessionId, outcome: "error", isError: true, - durationMs: Date.now() - startedAt, numTurns: 0, failure }); - } else req.bridge.emit({ type: "error", code: "agent_error", message: failure.message, failure }); - return; - } + catch (error) { refuseAcquisition(req, startedAt, error); return; } const { entry, isNew } = acquired; const { session, turnContext } = entry; const sessionId = session.sessionId; @@ -120,7 +101,6 @@ export function createPiTurnRunner( const completedUsage = createUsageAccumulator(); const failures = createTurnFailureTracker(); let failed = false; - let firstMainRequest = false; let thrown: TurnFailure | null = null; try { @@ -136,29 +116,7 @@ export function createPiTurnRunner( if (!req.signal.aborted) { req.signal.addEventListener("abort", onAbort, { once: true }); } - unsubscribe = session.subscribe(makeEventHandler(emit, usage, failures, (event) => { - if (event.type !== "message_start" && event.type !== "message_end") return; - const message = event.message; - if (message.role !== "assistant") return; - const completed = event.type === "message_end" && message.stopReason !== "aborted" && message.stopReason !== "error"; - - if (completed && !req.autonomous && !firstMainRequest) { - firstMainRequest = true; - const token = (v: unknown) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : null; - try { req.bridge.activity?.({ kind: "first_request_cache", usage: { - inputTokens: token(message.usage?.input), cacheReadTokens: token(message.usage?.cacheRead), - cacheCreationTokens: token(message.usage?.cacheWrite), source: "pi_main_message", coverage: "runtime_normalized", - } }); } catch { /* Observability must not fail the observed turn. */ } - } - if (completed) completedUsage.observe(event); - const receipt = completedUsage.toWire(); - if (receipt) { - if (!req.autonomous && !completed) return; - try { req.bridge.activity?.({ kind: req.autonomous?.containment === "restricted" ? "autonomous_usage" : "usage", usage: receipt, - atToolBoundary: completed && message.stopReason === "toolUse" }); } - catch { /* Observability must not fail the observed turn. */ } - } - })); + unsubscribe = session.subscribe(makeEventHandler(emit, usage, failures, observeAssistantAnswers(req, completedUsage))); // Runtime session identity is authoritative, including resumed sessions. if (!req.autonomous && session.model?.id) { try { req.bridge.activity?.({ kind: "main_model", model: session.model.id, sessionId }); } @@ -235,42 +193,106 @@ export function createPiTurnRunner( pool.finish(entry); } - const costUsd = turnCost(costBefore, snapshotCost(session)); - const wireUsage = usage.toWire(); - if (cancelled) { - emit({ type: "status", status: "cancelled" }); - emit({ - type: "result", - sessionId, - outcome: "cancelled", - ...(costUsd !== undefined ? { costUsd } : {}), - ...(wireUsage ? { usage: wireUsage } : {}), - durationMs: Date.now() - startedAt, - numTurns: 1, - isError: false, - }); - return; + emitTurnTerminal(emit, { sessionId, startedAt, cancelled, failed, thrown, failures, usage, costBefore, session }); + }; +} + +/** + * Settles a failed acquisition: a cancellation or a classified size or + * turn-temp refusal emits its terminal frame; anything else is rethrown. + */ +function refuseAcquisition(req: StartTurnRequest, startedAt: number, error: unknown): void { + // Acquisition now observes cancellation while preparing native inputs. + // Keep the existing terminal contract when no session was acquired. + if (req.signal.aborted && (error === req.signal.reason || error instanceof DOMException && error.name === "AbortError")) { + if (req.sessionId) req.bridge.emit({ type: "result", sessionId: req.sessionId, outcome: "cancelled", isError: false, + durationMs: Date.now() - startedAt, numTurns: 0 }); + else req.bridge.emit({ type: "error", code: "agent_error", message: "The turn was cancelled before a session was acquired." }); + return; + } + // A busy turn-temp budget (#1703) refuses the same way, with Retry. + // By class: the process ledger may come from another copy of the SDK. + const busy = (error as { errorClass?: unknown } | null)?.errorClass === FIRST_PARTY_FAILURE_CLASSES.worker_state_busy; + if (!(error instanceof SessionTooLargeError || busy)) throw error; + const failure = { errorClass: (error as { errorClass: string }).errorClass, message: (error as Error).message }; + if (req.sessionId) { + req.bridge.emit({ type: "result", sessionId: req.sessionId, outcome: "error", isError: true, + durationMs: Date.now() - startedAt, numTurns: 0, failure }); + } else req.bridge.emit({ type: "error", code: "agent_error", message: failure.message, failure }); +} + +/** + * Observes each assistant answer: the first completed main request reports + * its cache usage once, and completed answers accumulate the usage receipt. + */ +function observeAssistantAnswers(req: StartTurnRequest, completedUsage: TurnUsageAccumulator): (event: AgentSessionEvent) => void { + let firstMainRequest = false; + return (event) => { + if (event.type !== "message_start" && event.type !== "message_end") return; + const message = event.message; + if (message.role !== "assistant") return; + const completed = event.type === "message_end" && message.stopReason !== "aborted" && message.stopReason !== "error"; + + if (completed && !req.autonomous && !firstMainRequest) { + firstMainRequest = true; + const token = (v: unknown) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : null; + try { req.bridge.activity?.({ kind: "first_request_cache", usage: { + inputTokens: token(message.usage?.input), cacheReadTokens: token(message.usage?.cacheRead), + cacheCreationTokens: token(message.usage?.cacheWrite), source: "pi_main_message", coverage: "runtime_normalized", + } }); } catch { /* Observability must not fail the observed turn. */ } } - // A provider failure does not throw: prompt() resolves, and the turn's - // last answer is the error (#575). Its usage is already in `wireUsage`, - // counted once from its message_end like any other answer. - const failure = failures.failure(thrown ?? undefined); - if (failure) failed = true; - // Parity with the claude backend, which emits idle before its terminal - // result — the two backends must produce interchangeable frame streams. - emit({ type: "status", status: "idle" }); + if (completed) completedUsage.observe(event); + const receipt = completedUsage.toWire(); + if (receipt) { + if (!req.autonomous && !completed) return; + try { req.bridge.activity?.({ kind: req.autonomous?.containment === "restricted" ? "autonomous_usage" : "usage", usage: receipt, + atToolBoundary: completed && message.stopReason === "toolUse" }); } + catch { /* Observability must not fail the observed turn. */ } + } + }; +} + +/** The turn's closing frames: a cancelled result, or idle and its success or error result. */ +function emitTurnTerminal(emit: (msg: ServerMessage) => void, turn: { + sessionId: string; startedAt: number; cancelled: boolean; failed: boolean; thrown: TurnFailure | null; + failures: TurnFailureTracker; usage: TurnUsageAccumulator; costBefore: ReturnType; session: Parameters[0]; +}): void { + const { sessionId, startedAt, cancelled, failed, thrown, failures, usage, costBefore, session } = turn; + const costUsd = turnCost(costBefore, snapshotCost(session)); + const wireUsage = usage.toWire(); + if (cancelled) { + emit({ type: "status", status: "cancelled" }); emit({ type: "result", sessionId, - outcome: failed ? "error" : "success", + outcome: "cancelled", ...(costUsd !== undefined ? { costUsd } : {}), ...(wireUsage ? { usage: wireUsage } : {}), durationMs: Date.now() - startedAt, numTurns: 1, - isError: failed, - ...(failure ? { failure } : {}), + isError: false, }); - }; + return; + } + // A provider failure does not throw: prompt() resolves, and the turn's + // last answer is the error (#575). Its usage is already in `wireUsage`, + // counted once from its message_end like any other answer. + const failure = failures.failure(thrown ?? undefined); + const errored = failed || Boolean(failure); + // Parity with the claude backend, which emits idle before its terminal + // result — the two backends must produce interchangeable frame streams. + emit({ type: "status", status: "idle" }); + emit({ + type: "result", + sessionId, + outcome: errored ? "error" : "success", + ...(costUsd !== undefined ? { costUsd } : {}), + ...(wireUsage ? { usage: wireUsage } : {}), + durationMs: Date.now() - startedAt, + numTurns: 1, + isError: errored, + ...(failure ? { failure } : {}), + }); } /** diff --git a/packages/ui-backend-pi/src/worker-launch.ts b/packages/ui-backend-pi/src/worker-launch.ts new file mode 100644 index 0000000000..403733060c --- /dev/null +++ b/packages/ui-backend-pi/src/worker-launch.ts @@ -0,0 +1,354 @@ +/** + * Worker admission, launch and lifecycle for one pi worker session (#2517). + * Admission reads the native agent state the worker may receive, prepares + * the inference relay and reserves the worker's turn temp; launch resolves + * its sandbox and note and starts it; supervision owns what lives exactly as + * long as the worker: its turn temp, relays, locks, stderr and limit reports. + * Each step releases everything it acquired when it refuses. + */ +import { brainWorkerPath } from "@schlessera/brain-common/internal/worker-areas"; +import { workerCleanupUnconfirmed, WORKER_PROVIDER_CREDENTIAL_ENV, workerProviderCredentials } from "@schlessera/brain-ui-sdk/internal"; +import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"; +import { join, relative, isAbsolute } from "node:path"; +import { stateRoomCopy, stateRoomWarning, type StateRoomObservation } from "@schlessera/brain-ui-sdk/protocol"; +import { getAgentDir, type FileEntry } from "@earendil-works/pi-coding-agent"; +import type { Model } from "@earendil-works/pi-ai"; +import { BackendRequestError, type compileConfirmPatterns, type ExecWrapperConfig } from "@schlessera/brain-ui-sdk/server"; +import { workerOutwardNote, workerCommandPolicyNote, createLimitTracker, launchAgentWorkerAsync, launchLimits, prepareWorkerSandbox, prepareWorkerSandboxAsync, processStateLedger, retainWorkerStartupView, prepareNativeWorkerOutput, type PreparedWorkerOutput, + outputStagingLimit, requireWorkerHostAsync, resolveTurnTempLimits, restrictedReadPaths, turnTempLimit, workerNoteLimits, WorkerResourceLimitError, + workerSandboxNote, workerSandboxWarnings, WORKER_SCRATCH, WORKER_XDG_DIRS, type Reservation, type WorkerSandbox, + type LaunchedWorker, type WorkerStateHandle, type WorkerNoteFacts, type sessionPromptContext } from "@schlessera/brain-ui-sdk/internal"; + +import { piAutonomousEnvelope } from "./autonomous-envelope.js"; +import { preparePiHostInference, type PiHostInference } from "./host-inference.js"; +import type { CreatePiBackendOptions, SessionEnv } from "./backend-options.js"; +import { configuredProfiles } from "./profiles.js"; +import type { TurnContext } from "./turn-context.js"; +import { subprocessEnv, operatorAdmittedEnvNames } from "./config/env.js"; +import { piSessionDirectory } from "./session-storage.js"; +import { checkSessionSize, PI_WORKER_STATE, sendPipe } from "./worker-protocol.js"; + +/** The model a saved session last used: its latest model change, else its latest answer. */ +export function savedModel(entries: FileEntry[]): { provider: string; id: string } | undefined { + for (const entry of [...entries].reverse() as Array>) { + if (entry.type === "model_change" && typeof entry.provider === "string" && typeof entry.modelId === "string") return { provider: entry.provider, id: entry.modelId }; + const message = entry.type === "message" ? entry.message : undefined; + if (message?.role === "assistant" && typeof message.provider === "string" && typeof message.model === "string") return { provider: message.provider, id: message.model }; + } + return undefined; +} + +/** The host-only parts of a session's environment, never serialized into its worker. */ +export type PiWorkerHostEnv = Pick; + +export interface PiWorkerAdmissionRequest { + backend: CreatePiBackendOptions; + env: SessionEnv; + declared: Model | undefined; + restricted: boolean; + entries: FileEntry[] | undefined; + resumeId: string | undefined; + sessionId: string; + profileId: string | undefined; + promptContext: ReturnType | undefined; + exec: ExecWrapperConfig; +} + +/** An admitted worker: what it may receive and the reservation that admitted it. */ +export interface PiWorkerAdmission { + agentDir: string; + /** Native agent state files the worker receives, by name; syncAuth keeps auth.json current. */ + agentFiles: Record; + envelope: ReturnType | undefined; + egress: WorkerSandbox["egress"] | undefined; + hostInference: PiHostInference | undefined; + cachedNpmModules: string | undefined; + /** The worker's initialization message, without its sandbox note. */ + init: Record; + reservation: Reservation; + admissionObservation: StateRoomObservation; + identity: WorkerNoteFacts["identity"]; + hostEnv: PiWorkerHostEnv; +} + +/** + * Admits one worker: selects the native state it receives, prepares a + * governed or strict turn's inference relay and reserves its turn temp + * against the process ledger. A refusal stops every relay it started. + */ +export async function admitPiWorker(request: PiWorkerAdmissionRequest): Promise { + const { backend, env, declared, restricted, entries, resumeId, sessionId, profileId, promptContext, exec } = request; + const agentFiles: Record = {}; + const agentDir = piSessionDirectory(backend.brainPath, getAgentDir()); + // A restricted autonomous turn copies no native state into the worker: no + // stored login, provider override or settings (#676). The relay holds the key. + const envelope = restricted ? piAutonomousEnvelope(declared, agentDir) : undefined; + // A governed or strict turn on the turn proxy: the host holds the credential + // and the worker's pi reaches inference only through the relay (#1665). + const egress = !env.autonomous ? env.workerSandbox?.egress : undefined; + const relayedModel = egress ? declared ?? (entries ? savedModel(entries) : undefined) : undefined; + if (egress && !relayedModel) throw new BackendRequestError("A pi turn on the host inference relay needs a declared vendor/model profile."); + // Provider folders admitted for a proven recipient (#2695): only its relay may carry this turn. + const recipient = !env.autonomous ? env.workerSandbox?.inferenceRecipient : undefined; + if (recipient && !egress) throw new BackendRequestError("This turn's provider folders were admitted for a recipient, but it has no inference relay to hold it to."); + // Acquired inside the admission scope below, so every later failure releases it. + let hostInference: PiHostInference | undefined; + // A relayed worker gets only settings: the host keeps credentials and endpoints. + if (!envelope) for (const name of egress ? ["settings.json"] : ["auth.json", "models.json", "settings.json"]) { + const path = join(agentDir, name); + if (existsSync(path)) agentFiles[name] = readFileSync(path, "utf8"); + } + const { workerSandbox, workerProviderMasks, workerDataTree, workerLock, workerStarted, workerStartupView, workerSignal, toolExecution, ...workerSessionEnv } = env; + const npmPath = envelope ? undefined : join(agentDir, "npm", "node_modules"); + let cachedNpmModules: string | undefined; + if (npmPath && existsSync(npmPath)) { + const npmRoot = realpathSync(join(agentDir, "npm")); + cachedNpmModules = realpathSync(npmPath); + const descendant = (root: string, path: string) => { const rel = relative(root, path); return rel !== "" && rel !== ".." && !rel.startsWith("../") && !isAbsolute(rel); }; + if (!statSync(cachedNpmModules).isDirectory() || !descendant(agentDir, npmRoot) + || !descendant(npmRoot, cachedNpmModules)) { + throw new BackendRequestError("Pi prepared npm resources must be inside the selected agent directory's npm tree."); + } + } + const init = { type: "init", governed: workerSandbox?.profile === "governed", dataTree: Boolean(workerSandbox?.dataTree ?? workerDataTree), sharedLock: Boolean(workerLock), backend: { exec, brainPath: backend.brainPath, profiles: configuredProfiles(backend), model: backend.model, + loadExtensions: envelope ? false : backend.loadExtensions, systemPromptAppend: backend.systemPromptAppend }, env: workerSessionEnv, sessionId, + resume: Boolean(resumeId), entries, profileId, agentFiles, fixedAppend: promptContext?.append(), ...(cachedNpmModules ? { cachedNpmModules } : {}), ...(envelope ? { inference: envelope.inference } : {}) }; + // Every worker's /tmp is a private tmpfs of exactly this allowance, which + // holds the worker's session state too (#1703). + const turnTempLimits = resolveTurnTempLimits({ ...backend.turnTemp, + names: { allowance: "turnTemp.allowanceBytes", budget: "turnTemp.budgetBytes" } }); + let reservation: Reservation | undefined; + let admissionObservation: StateRoomObservation; + let identity: import("@schlessera/brain-ui-sdk/internal").WorkerNoteFacts["identity"]; + try { + if (egress && relayedModel) { + hostInference = await preparePiHostInference({ provider: relayedModel.provider, modelId: relayedModel.id, agentDir, + ...(recipient ? { recipientOrigin: recipient.origin } : {}), + brainPath: backend.brainPath, egress, environment: subprocessEnv(), ...(env.workerSignal ? { signal: env.workerSignal } : {}) }); + Object.assign(init, { relayed: hostInference.worker }); + } + admissionObservation = checkSessionSize(init); + const workerHost = await requireWorkerHostAsync(backend.brainPath, { restricted, turnTempBytes: turnTempLimits.allowanceBytes }); + if (workerHost?.identity === "separate_uid" && workerHost.workerUid !== undefined) identity = { kind: "separate_uid", workerUid: workerHost.workerUid }; + // Admitted against the same per-process ledger as Claude workers; a busy + // budget refuses as worker_state_busy before anything launches. + reservation = processStateLedger().reserve(undefined, turnTempLimits); + } catch (error) { envelope?.relay.stop(); hostInference?.stop(); throw error; } + return { agentDir, agentFiles, envelope, egress, hostInference, cachedNpmModules, init, reservation, admissionObservation, identity, + hostEnv: { workerSandbox, workerProviderMasks, workerDataTree, workerLock, workerStarted, workerStartupView, workerSignal, toolExecution } }; +} + +export interface PiWorkerLaunchRequest { + backend: CreatePiBackendOptions; + env: SessionEnv; + admission: PiWorkerAdmission; + restricted: boolean; + resumeId: string | undefined; + execHelpers: string[]; + confirmPatterns: ReturnType; + startupStarted: number; + turnContext: TurnContext; +} + +/** A started worker, its resolved sandbox and the note its agent reads. */ +export interface LaunchedPiWorker { + child: LaunchedWorker; + sandbox: WorkerSandbox; + sandboxNote: string; + turnTemp: WorkerStateHandle | undefined; +} + +/** + * Resolves the admitted worker's sandbox and note, then starts it. A failure + * after launch stops and drains the owned child before its native stage and + * reservation are released. + */ +export async function launchPiWorker(request: PiWorkerLaunchRequest): Promise { + const { backend, env, admission, restricted, resumeId, execHelpers, confirmPatterns, startupStarted, turnContext } = request; + const { envelope, egress, hostInference, cachedNpmModules, reservation, admissionObservation, identity } = admission; + const { workerSandbox, workerProviderMasks, workerDataTree, workerLock, workerStarted, workerStartupView, workerSignal } = admission.hostEnv; + const entry = Bun.resolveSync("./worker-entry", import.meta.dir); + const workerEnv: Record = envelope + // The restricted envelope: minimum runtime variables only, the installed + // runtime as the explicit read envelope, and the relay as the one route out. + ? { PATH: "/usr/bin:/bin", LANG: "C.UTF-8", HOME: WORKER_SCRATCH, BRAIN_ROOT: backend.brainPath } + : { ...Object.fromEntries(Object.entries(subprocessEnv()).filter((pair): pair is [string, string] => pair[1] !== undefined)), BRAIN_ROOT: backend.brainPath }; + if (!envelope) workerEnv.PATH = brainWorkerPath(backend.brainPath, workerEnv.PATH); + for (const name of hostInference?.credentialEnv ?? []) delete workerEnv[name]; + // The provider keys a governed or strict worker keeps (#1666). A relayed + // worker keeps only what an operator admits. Without the relay, pi resolves + // its own credentials in the worker and may read any of these, including + // through a models.json `$NAME`, so they stay under the ruling that hosts + // without managed native storage keep today's inference credentials (#2654). + const credentialEnv = [...(hostInference ? [] : WORKER_PROVIDER_CREDENTIAL_ENV), ...operatorAdmittedEnvNames()]; + const providerKeys = workerProviderCredentials(workerEnv, credentialEnv).kept; + workerEnv.PI_CODING_AGENT_DIR = PI_WORKER_STATE; + // SDK offline mode silently skips missing sources. Validate prepared packages + // explicitly in the child; the parent's environment remains unchanged. + delete workerEnv.PI_OFFLINE; + let child: LaunchedWorker; + let launchedChild: LaunchedWorker | undefined; + let preparedOutput: PreparedWorkerOutput | undefined; + let sandboxNote: string; + let sandbox: WorkerSandbox; + // The worker's private /tmp, through the descriptor the server holds, so + // what the answer links there can be promoted once the worker has exited + // (#1655). An autonomous turn saves no answer. + let turnTemp: WorkerStateHandle | undefined; + try { + // One resolution feeds the worker's mounts and the note its agent reads (#1626), + // and one its resource limits and the note's limits section (#1660). + sandbox = envelope ? { ...prepareWorkerSandbox(backend.brainPath, { restricted: true, maintenance: backend.maintenance }), + ...(workerProviderMasks ? { providerMasks: workerProviderMasks } : {}), ...(workerDataTree ? { dataTree: workerDataTree } : {}) } + : workerSandbox ?? await prepareWorkerSandboxAsync(backend.brainPath, { home: workerEnv.HOME, maintenance: backend.maintenance }); + if (hostInference) sandbox = { ...sandbox, maskPaths: [...sandbox.maskPaths ?? [], ...hostInference.maskPaths] }; + if (cachedNpmModules) { + if (sandbox.maskPaths?.some(path => { try { const actual = realpathSync(path); return actual === cachedNpmModules || actual.startsWith(cachedNpmModules + "/"); } catch { return false; } })) { + throw new BackendRequestError("Pi prepared npm resources cannot contain a private worker mask."); + } + sandbox = { ...sandbox, readPaths: [...(sandbox.readPaths ?? restrictedReadPaths([process.execPath, entry])), cachedNpmModules] }; + } + // Worker-local tools run the host's helpers: each file alone, never its parent. + if (execHelpers.length && !envelope) sandbox = { ...sandbox, readPaths: [...(sandbox.readPaths ?? restrictedReadPaths([process.execPath, entry])), ...execHelpers] }; + const limits = launchLimits({}); + sandboxNote = [workerSandboxNote(sandbox, { ...(identity ? { identity } : {}), ...(hostInference ? { egress: true } : {}), providerKeys, hardTimeoutMs: env.turnBudgetMs, limits: [...workerNoteLimits(limits.status), + turnTempLimit(reservation.turnTempBytes, env.caps.turnTemp === true ? "turn_temp" : undefined), + outputStagingLimit()] }), workerCommandPolicyNote(env.autonomous ? undefined : sandbox.commandPolicy, confirmPatterns), env.autonomous ? "" : workerOutwardNote(Boolean(hostInference), sandbox.commandPolicy?.taint?.())].filter(Boolean).join("\n\n"); + if (resumeId && !restricted && stateRoomWarning(admissionObservation)) { + sandboxNote += `\n\n${stateRoomCopy(admissionObservation)} Continue in a new conversation before it is full. This one stays available.`; + } + for (const warning of workerSandboxWarnings(sandbox)) backend.log?.("warn", warning); + if (workerStartupView && sandbox.profile !== "governed" && sandbox.areas.some(area => area.mount.writable)) { + preparedOutput = await prepareNativeWorkerOutput(backend.brainPath, { startupView: workerStartupView, areas: sandbox.areas.filter(area => area.mount.writable).map(area => area.rel), folderPaths: sandbox.retainedFolders, signal: workerSignal }); + } + workerSignal?.throwIfAborted(); + const spawning = performance.now(); + backend.log?.("debug", "Pi startup phase", { phase: "preparation", durationMs: spawning - startupStarted, elapsedMs: spawning - startupStarted }); + child = await launchAgentWorkerAsync({ brainPath: backend.brainPath, turnTempBytes: reservation.turnTempBytes, + ...(preparedOutput ? { preparedOutput } : workerStartupView && sandbox.profile !== "governed" ? { startupView: retainWorkerStartupView(workerStartupView) } : {}), + command: [process.execPath, entry], env: workerEnv, credentialEnv, sandbox, limits, ...(workerLock ? { outputLock: workerLock } : {}), + ...(envelope ? { restricted: { readPaths: [...restrictedReadPaths([entry]), ...execHelpers], inferenceDir: envelope.relay.dir } } : {}), + ...(hostInference && egress ? { egress: { proxyDir: egress.dir, directLoopback: true } } : {}), + }); + launchedChild = child; + backend.log?.("debug", "Pi startup phase", { phase: "spawn", durationMs: performance.now() - spawning, elapsedMs: performance.now() - startupStarted }); + turnTemp = child.turnTemp; + turnContext.configurationRoot = child.configurationRoot; + workerStarted?.(child); + } catch (error) { + // A post-launch callback can fail before the ordinary lifecycle handlers + // exist. Stop and drain this owned child before deleting its native stage. + const cleanupErrors: unknown[] = []; + const attempt = async (cleanup: () => unknown | Promise): Promise => { try { await cleanup(); return true; } catch (failure) { cleanupErrors.push(failure); return false; } }; + let workerStorageReleased = !workerCleanupUnconfirmed(error); + if (launchedChild) { + await attempt(() => launchedChild!.kill("SIGKILL")); + await attempt(() => launchedChild!.exited); + // Nothing reads its stdio yet: close the server's ends, then wait out Bun's duplicates (#2863). + await attempt(() => { launchedChild!.stdin.end(); launchedChild!.stdout.destroy(); launchedChild!.stderr.destroy(); return launchedChild!.released(); }); + workerStorageReleased = await attempt(() => launchedChild!.turnTemp?.closeAsync()); + } + if (workerStorageReleased) await attempt(() => preparedOutput?.cleanup()); + await attempt(() => envelope?.relay.stop()); + await attempt(() => hostInference?.stop()); + if (workerStorageReleased) await attempt(() => reservation.release()); + if (cleanupErrors.length) { + try { backend.log?.("warn", `Pi startup cleanup retained failures after its original refusal: ${cleanupErrors.map(String).join("; ")}`); } catch { /* Reporting cannot replace the startup error. */ } + } + throw error; + } + return { child, sandbox, sandboxNote, turnTemp }; +} + +export interface PiWorkerSupervision { + /** Frees the worker's turn temp once; a refused close is retried by the next call. */ + closeTurnTemp(): Promise; + /** Locks the worker holds, by lock id; all are released when it exits. */ + releases: Map void>; + /** The worker ran a turn: its `promote` closes turn temp, not its exit. */ + markPrompted(): void; + /** The tail of the worker's stderr. */ + diagnostic(): string; + reportLimitHits(): void; + limitEnded(): Promise; + send(value: unknown): void; + stdioReleased(): Promise; +} + +/** + * Binds everything that lives exactly as long as the started worker: its + * turn temp, relays, locks, stderr and host-limit reports. + */ +export function superviseWorker(worker: { child: LaunchedWorker; reservation: Reservation; turnTemp: WorkerStateHandle | undefined; + env: SessionEnv; turnContext: TurnContext; admission: Pick; answerText(): string }): PiWorkerSupervision { + const { child, reservation, turnTemp, env, turnContext, answerText } = worker; + const { envelope, hostInference } = worker.admission; + const held = reservation; + let turnTempClosing: Promise | undefined; + /** + * Frees the worker's turn temp: the tmpfs goes once the worker is gone and + * this descriptor is closed. The reservation is released only once a + * separate-UID worker's broker cleanup is confirmed; a refusal keeps it + * charged, and the next call tries again (#2854). + */ + const closeTurnTemp = (): Promise => turnTempClosing ??= (async () => { await turnTemp?.closeAsync(); held.release(); })() + .catch((error: unknown) => { turnTempClosing = undefined; throw error; }); + // The turn_temp tool reaches this worker's /tmp only while it runs (#1703). + let workerLive = true; + void child.exited.finally(() => { workerLive = false; }).catch(() => {}); + if (env.caps.turnTemp && turnTemp) { + const root = turnTemp.root; + turnContext.turnTemp = { + root: () => workerLive ? root : undefined, allowanceBytes: held.turnTempBytes, scratch: WORKER_SCRATCH, + exclude: [PI_WORKER_STATE], keep: [WORKER_SCRATCH, ...Object.values(WORKER_XDG_DIRS)], + linkedText: () => answerText(), + }; + } + // The relay lives exactly as long as the worker it serves. + if (envelope) void child.exited.finally(() => envelope.relay.stop()).catch(() => {}); + if (hostInference) void child.exited.finally(() => hostInference.stop()).catch(() => {}); + const releases = new Map void>(); + void child.exited.finally(() => { for (const release of releases.values()) release(); releases.clear(); }).catch(() => {}); + // A worker that never ran a turn has nothing to promote; one that did is + // cleaned up by `promote` once its answer has been read. Initialization + // failure and an inactive abort also await this close themselves. + let prompted = false; + void child.exited.finally(() => prompted ? undefined : closeTurnTemp()).catch(() => {}); + child.stdin.on("error", () => {}); + let diagnostic = ""; + child.stderr.on("data", bytes => { diagnostic = (diagnostic + String(bytes)).slice(-4000); }); + // Each new host-limit hit is reported next to the step that caused it (#1660). + const freshLimitHits = createLimitTracker(); + const reportLimitHits = (): void => { + const fresh = freshLimitHits(child.limitReport()); + if (!fresh.length) return; + try { turnContext.bridge?.activity?.({ kind: "resource_limit", limits: fresh, fatal: false }); } catch { /* observability only */ } + }; + /** + * Once the worker has exited: the limit that ended it, as the turn's + * failure. Settled once, however many paths ask, and bounded: a worker that + * closed its protocol but did not exit is not a limit's doing. + */ + let limitSettlement: Promise | undefined; + const limitEnded = (): Promise => limitSettlement ??= (async () => { + let timer: ReturnType | undefined; + const exited = await Promise.race([child.exited.then(() => true, () => true), + new Promise(resolve => { timer = setTimeout(() => resolve(false), 3_000); })]); + clearTimeout(timer); + if (!exited) return undefined; + const report = child.limitReport(); + if (!report.fatal) { reportLimitHits(); return undefined; } + try { turnContext.bridge?.activity?.({ kind: "resource_limit", limits: report.hits, fatal: true }); } catch { /* observability only */ } + return new WorkerResourceLimitError(report.hits); + })(); + const send = (value: unknown) => sendPipe(child.stdin, value); + /** + * Once the worker has exited, its stdio can still be open here (#2863): Bun + * closes its own duplicates of the FIFO descriptors on its pool after their + * streams end. Prompt, refused initialization and pre-prompt cancellation + * settle only after this, which resolves once they are closed or its bound expires. + */ + const stdioReleased = (): Promise => { child.stdin.end(); return child.released(); }; + return { closeTurnTemp, releases, markPrompted: () => { prompted = true; }, diagnostic: () => diagnostic, reportLimitHits, limitEnded, send, stdioReleased }; +} diff --git a/packages/ui-backend-pi/src/worker-reader.ts b/packages/ui-backend-pi/src/worker-reader.ts new file mode 100644 index 0000000000..c764b99137 --- /dev/null +++ b/packages/ui-backend-pi/src/worker-reader.ts @@ -0,0 +1,146 @@ +/** + * The host's reader of one pi worker's protocol (#2517). Every frame is + * validated before it is read; the reader binds the worker's identity and + * transcript to this session, answers RPCs without blocking later frames and + * settles the turn when the worker completes, refuses or breaks the protocol. + */ +import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent"; +import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; +import type { Model } from "@earendil-works/pi-ai"; +import { BackendRequestError } from "@schlessera/brain-ui-sdk/server"; +import type { LaunchedWorker, NativeFileVersions, sessionPromptContext, WorkerResourceLimitError } from "@schlessera/brain-ui-sdk/internal"; + +import type { CreatePiBackendOptions, SessionEnv } from "./backend-options.js"; +import type { TurnContext } from "./turn-context.js"; +import { pipeMessages, piWorkerMessage, SessionTooLargeError } from "./worker-protocol.js"; +import type { PiWorkerReceipts } from "./worker-receipts.js"; +import type { PiWorkerRpc } from "./worker-rpc.js"; +import type { provenToolExecution } from "./worker-session.js"; + +/** One worker session's mutable turn state, shared by its reader and its session handle. */ +export interface PiWorkerTurnState { + active: boolean; + initialized: boolean; + /** Revokes work; it does not confirm teardown. */ + ended: boolean; + /** The turn's first failure: a later path cannot reclassify it. */ + error: Error | undefined; + cost: number; + thinkingLevel: ThinkingLevel | undefined; + levels: ThinkingLevel[]; + model: Model | undefined; + /** The submitted prompt until the worker's transcript shows it delivered. */ + ownedPrompt: { id: string; text: string; images: boolean } | undefined; +} + +export interface PiWorkerReader { + child: LaunchedWorker; + state: PiWorkerTurnState; + ready: PromiseWithResolvers; + done: PromiseWithResolvers; + sessionId: string; + backend: Pick; + startupStarted: number; + promptContext: ReturnType | undefined; + sessionBudgetLimits: SessionEnv["sessionBudgetLimits"]; + autonomous: boolean; + resumed: boolean; + turnContext: TurnContext; + nativeVersions: NativeFileVersions; + receipts: PiWorkerReceipts; + /** Entries saved before this turn. */ + resumedIds: ReadonlySet; + listeners: ReadonlySet<(event: AgentSessionEvent) => void>; + /** Execution proof: a call's start, and the path its end proved, if any. */ + proof: { started(toolCallId: string): void; ended(toolName: string, toolCallId: string): ReturnType }; + toolExecution: SessionEnv["toolExecution"]; + dispatch(msg: PiWorkerRpc): Promise; + send(value: unknown): void; + fail(reason: unknown): void; + reportLimitHits(): void; + limitEnded(): Promise; + diagnostic(): string; +} + +/** Reads the worker's frames until its protocol closes; throws when it ends without completing. */ +export async function readPiWorkerProtocol(reader: PiWorkerReader): Promise { + const { child, state, ready, done, sessionId, backend, startupStarted, promptContext, sessionBudgetLimits, autonomous, resumed, + turnContext, nativeVersions, receipts, resumedIds, listeners, proof, toolExecution, dispatch, send, fail, reportLimitHits, limitEnded, diagnostic } = reader; + for await (const raw of pipeMessages(child.stdout)) { + const msg = piWorkerMessage.parse(raw); + if (state.ended) throw new Error("Pi worker sent a message after turn completion"); + if (msg.type === "startup_timing") { + backend.log?.("debug", "Pi startup phase", { phase: msg.phase, durationMs: msg.durationMs, elapsedMs: performance.now() - startupStarted }); + } else if (msg.type === "ready") { + backend.log?.("debug", "Pi startup ready", { elapsedMs: performance.now() - startupStarted }); + if (msg.sessionId !== sessionId || state.initialized || state.active) throw new Error("Pi worker changed its server session identity"); + state.initialized = true; + if (promptContext && msg.append !== undefined) promptContext.retainAppend(msg.append, sessionBudgetLimits ? { limits: sessionBudgetLimits } : {}); + state.model = msg.model as Model | undefined; + state.cost = msg.cost; state.thinkingLevel = msg.thinkingLevel as ThinkingLevel; state.levels = msg.levels as ThinkingLevel[]; + ready.resolve(); + } else if (msg.type === "prompt_prefix") { + if (!state.active) throw new Error("Pi worker emitted a prefix outside the turn"); + if (!autonomous) { + try { turnContext.bridge?.activity?.({ kind: "prompt_prefix", prefix: msg.prefix, resumed }); } + catch { /* Observability must not fail the observed turn. */ } + } + } else if (msg.type === "rpc") { + // Do not block reading: a bridge may wait for user input while other + // sibling calls, cancellation and model frames need to flow. + void dispatch(msg).then(value => { + if (!state.ended) send({ type: "answer", id: msg.id, value }); + }, refusal => { + const message = refusal instanceof Error ? refusal.message : String(refusal); + turnContext.bridge?.emit({ type: "error", code: "PI_WORKER_RPC_REFUSED", message, sessionId }); + if (!state.ended) send({ type: "answer", id: msg.id, error: message }); + }).catch(fail); + } else if (msg.type === "event") { + if (!state.active) throw new Error("Pi worker emitted an event outside the turn"); + if (msg.event.type === "tool_execution_start") proof.started(msg.event.toolCallId); + if (msg.event.type === "tool_execution_end") { + reportLimitHits(); + const proven = proof.ended(msg.event.toolName, msg.event.toolCallId); + if (proven) toolExecution?.(msg.event.toolCallId, proven); + const receipt = receipts.applications.get(msg.event.toolCallId); + if (receipt) { + msg.event.result = receipt.output ? { content: receipt.output.content.map(part => ({ ...part })), details: receipt.output.details } : { content: [{ type: "text", text: JSON.stringify(receipt.result) }], details: receipt.result }; + msg.event.isError = !receipt.result.ok; + } + } + for (const listener of listeners) listener(msg.event as AgentSessionEvent); + } else if (msg.type === "snapshot") { + if (!state.active) throw new Error("Pi worker sent transcript state outside the turn"); + const header = msg.entries[0]; + if (header?.type !== "session" || header.id !== sessionId || header.cwd !== backend.brainPath) { + throw new Error("Pi worker sent an invalid transcript identity"); + } + receipts.latestEntries = msg.entries; + if (state.ownedPrompt) { + for (const entry of receipts.latestEntries) { + if (entry.type !== "message" || resumedIds.has(entry.id)) continue; + const message = entry.message as { role?: string; content?: unknown } | undefined; + const wire = Array.isArray(message?.content) ? message.content.filter(part => part.type === "text").map(part => part.text).join("") : message?.content; + // The installed runtime appends image-normalization hints after the + // exact submitted text. Bind the full observed bytes to this owned + // turn now; replay never strips a suffix or matches host patterns. + const delivered = typeof wire === "string" && (wire === state.ownedPrompt.text + || state.ownedPrompt.images && wire.startsWith(state.ownedPrompt.text + "\n\n")); + if (message?.role === "user" && delivered && typeof entry.id === "string") { + promptContext?.acknowledge(state.ownedPrompt.id, entry.id, wire as string); + state.ownedPrompt = undefined; + break; + } + } + } + receipts.persist(); + } else if (msg.type === "done") { + if (!state.active) throw new Error("Pi worker completed an inactive turn"); + // Hits after the last tool step, or in a turn without one, still count. + reportLimitHits(); + state.cost = msg.cost; nativeVersions.cancelPending(); state.ended = true; + if (msg.error) done.reject(new Error(msg.error)); else done.resolve(); + } else throw msg.errorClass === "session_too_large" ? new SessionTooLargeError() : new BackendRequestError(msg.message); + } + if (!state.ended) throw (await limitEnded()) ?? new Error(`Pi worker exited before completion: ${diagnostic() || "protocol closed"}`); +} diff --git a/packages/ui-backend-pi/src/worker-receipts.ts b/packages/ui-backend-pi/src/worker-receipts.ts new file mode 100644 index 0000000000..b3640020b8 --- /dev/null +++ b/packages/ui-backend-pi/src/worker-receipts.ts @@ -0,0 +1,145 @@ +/** + * Receipt persistence and replay for one pi worker session (#2517). The host + * keeps every server-applied effect's receipt, anchors it to the transcript + * the worker reports, saves that transcript and retains its display mappings + * outside it. A committed effect whose call the runtime left unanswered is + * recovered with its own result once the worker has exited. + */ +import { randomUUID } from "node:crypto"; +import type { FileEntry } from "@earendil-works/pi-coding-agent"; +import type { BrainApplicationResult } from "@schlessera/brain-ui-sdk/server"; +import { createTurnTempPromoter, sessionReplay, WORKER_SCRATCH, type WorkerSandbox, type WorkerStateHandle } from "@schlessera/brain-ui-sdk/internal"; + +import type { CreatePiBackendOptions } from "./backend-options.js"; +import type { createPiBridgeTools } from "./bridge-tools.js"; +import { savePiSession } from "./session-storage.js"; +import type { TurnContext } from "./turn-context.js"; +import { PI_WORKER_STATE } from "./worker-protocol.js"; + +/** One server-applied effect: what the call asked, what the server answered and where it sits. */ +export interface PiApplicationReceipt { + name: string; + input: Record; + result: BrainApplicationResult; + anchor?: string | null; + output?: Awaited[number]["execute"]>>; +} + +export interface PiWorkerReceipts { + /** Receipts by tool call id. */ + readonly applications: Map; + /** The worker's latest reported transcript. */ + latestEntries: Record[]; + /** Saves the receipts and the latest transcript; `recoverMissing` answers orphaned committed calls. */ + persist(recoverMissing?: boolean): void; + /** The answer text of this turn's new assistant entries, as the worker has reported them. */ + answerText(): string; + /** After the worker exits: persists, promotes what the answer links in turn temp, then closes it. */ + promote(worker: { turnTemp: WorkerStateHandle | undefined; sandbox: WorkerSandbox; closeTurnTemp(): Promise }): Promise; +} + +export interface PiWorkerReceiptOptions { + sessionDir: string; + brainPath: string; + sessionId: string; + /** An autonomous turn saves no transcript and no answer. */ + autonomous: boolean; + /** The resumed transcript, if any. */ + entries: FileEntry[] | undefined; + /** Entries saved before this turn: only their own turn owns their display mappings. */ + resumedIds: Set; + turn: TurnContext; + backend: Pick; +} + +export function createPiWorkerReceipts(options: PiWorkerReceiptOptions): PiWorkerReceipts { + const { sessionDir, brainPath, sessionId, autonomous, entries, resumedIds, turn: turnContext } = options; + const replayTurnId = randomUUID(); + const display = sessionReplay(sessionDir, brainPath, sessionId); + const applications = new Map(); + let latestEntries: Record[] = []; + function persist(recoverMissing = false): void { + if (autonomous) return; + // Receipt ownership survives even when no runtime call or snapshot exists. + // Never synthesize a model call or replace a runtime-written result. + for (const [id, receipt] of applications) { + const called = latestEntries.find(entry => !resumedIds.has(entry.id) && entry.type === "message" + && (entry.message as any)?.role === "assistant" && (entry.message as any).content.some((part: any) => part.type === "toolCall" && part.id === id)); + if (typeof called?.id === "string") receipt.anchor = called.id; + else if (receipt.anchor === undefined) { + // Direct effects can precede every native message. Null is an owned + // session-root position, not an anchor to a later worker snapshot. + const prior = latestEntries.findLast(entry => entry.type === "message") + ?? entries?.findLast(entry => entry.type === "message"); + receipt.anchor = typeof prior?.id === "string" ? prior.id : null; + } + display.retainReceipt({ id, name: receipt.name, input: receipt.input, anchor: receipt.anchor, turnId: replayTurnId, + output: receipt.output?.content.filter(part => part.type === "text").map(part => part.text).join("") ?? JSON.stringify(receipt.result), + isError: !receipt.result.ok }); + } + if (!latestEntries.some(entry => entry.type === "message")) return; + const saved = [...latestEntries]; + if (recoverMissing) for (const [id, receipt] of applications) { + const called = saved.some(entry => !resumedIds.has(entry.id) && entry.type === "message" && (entry.message as any)?.role === "assistant" + && (entry.message as any).content.some((part: any) => part.type === "toolCall" && part.id === id)); + const answered = saved.some(entry => !resumedIds.has(entry.id) && entry.type === "message" && (entry.message as any)?.role === "toolResult" + && (entry.message as any).toolCallId === id); + if (!called || answered) continue; + // The installed Pi adapter repairs orphaned calls with "No result provided". + // Preserve the committed effect instead, only after the runtime has exited. + saved.push({ type: "message", id: randomUUID(), parentId: saved.at(-1)?.id ?? null, + timestamp: new Date().toISOString(), message: { role: "toolResult", toolCallId: id, toolName: receipt.name, + content: receipt.output?.content ?? [{ type: "text", text: JSON.stringify(receipt.result) }], + isError: !receipt.result.ok, timestamp: Date.now() } }); + } + savePiSession(sessionDir, sessionId, saved); + } + + /** + * Once the worker has exited, copies what this turn's answers link in turn + * temp into scratch, retains display mappings outside the transcript, and reports each + * linked file to the host (#1655). Turn temp is removed either way. + */ + async function promote({ turnTemp, sandbox, closeTurnTemp }: Parameters[0]): Promise { + try { + persist(true); + if (!turnTemp || autonomous) return; + const promoter = createTurnTempPromoter({ brain: sandbox.brain, tmp: turnTemp.root, turnId: turnContext.turnId, scratch: WORKER_SCRATCH, + exclude: [PI_WORKER_STATE], scratchWritable: sandbox.areas.some(area => area.name === "scratch" && area.mount.writable) }); + for (const entry of latestEntries) { + if (entry.type !== "message" || resumedIds.has(entry.id)) continue; + const message = entry.message as { role?: unknown; content?: unknown } | undefined; + if (message?.role !== "assistant" || !Array.isArray(message.content)) continue; + for (const [index, part] of (message.content as Array<{ type?: unknown; text?: unknown }>).entries()) { + if (part?.type !== "text" || typeof part.text !== "string") continue; + await promoter.prepareRecovery(part.text, turnContext.signal ?? undefined); + const next = promoter.rewrite(part.text); + if (typeof entry.id === "string") display.retainText(entry.id, index, part.text, next); + } + } + for (const record of promoter.records) { + try { turnContext.bridge?.activity?.(record); } catch { /* Observability must not fail the observed turn. */ } + } + } catch (failure) { + options.backend.log?.("warn", `promoting linked turn-temp files failed: ${failure instanceof Error ? failure.message : String(failure)}`); + } finally { await closeTurnTemp(); } + } + function answerText(): string { + const parts: string[] = []; + for (const entry of latestEntries) { + if (entry.type !== "message" || resumedIds.has(entry.id)) continue; + const message = entry.message as { role?: unknown; content?: unknown } | undefined; + if (message?.role !== "assistant" || !Array.isArray(message.content)) continue; + for (const part of message.content as Array<{ type?: unknown; text?: unknown }>) { + if (part?.type === "text" && typeof part.text === "string") parts.push(part.text); + } + } + return parts.join("\n"); + } + return { + applications, + get latestEntries() { return latestEntries; }, + set latestEntries(next) { latestEntries = next; }, + persist, answerText, promote, + }; +} diff --git a/packages/ui-backend-pi/src/worker-rpc.ts b/packages/ui-backend-pi/src/worker-rpc.ts new file mode 100644 index 0000000000..4dec96ca93 --- /dev/null +++ b/packages/ui-backend-pi/src/worker-rpc.ts @@ -0,0 +1,249 @@ +/** + * The host side of the pi worker's RPCs (#2517): one handler per protocol + * method, keyed by `method`. Every call first proves the turn is live and the + * request is not a replay; a method without a handler is refused. Handlers + * hold no state of their own: the worker session supplies its grants, locks, + * native file versions and receipts through `PiWorkerRpcContext`. + */ +import { randomUUID } from "node:crypto"; +import { safeResolve } from "@schlessera/brain/internal"; +import { BRAIN_APPLICATION_TOOLS, brainApplicationInput, brainReadBaseInput, bashLockKey, BRAIN_LOCK_KEY, isCompletedAutonomousToolCall, + type BackendBridge, type compileConfirmPatterns, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; +import type { LaunchedWorker, NativeFileVersions, WorkerSandbox } from "@schlessera/brain-ui-sdk/internal"; + +import type { SessionCaps } from "./backend-options.js"; +import { createPiBridgeTools, REQUEST_IMAGE_MASK_INPUT_SCHEMA } from "./bridge-tools.js"; +import { decidePiToolPermission } from "./permission-gate.js"; +import { syncPiAuth } from "./session-storage.js"; +import type { TurnContext } from "./turn-context.js"; +import type { PiWorkerMessage } from "./worker-protocol.js"; +import type { PiWorkerReceipts } from "./worker-receipts.js"; +import type { CallExecution } from "./worker-session.js"; + +export type PiWorkerRpc = Extract; +export type PiWorkerRpcMethod = PiWorkerRpc["method"]; + +/** What one worker session lends its RPC handlers. */ +export interface PiWorkerRpcContext { + brainPath: string; + turn: TurnContext; + /** Throws unless the turn is active, unrevoked and has a bridge and a live signal. */ + live(): void; + /** Server permission decisions by tool call id, each for one exact input. */ + grants: Map; + /** Held worker locks by lock id. */ + releases: Map void>; + workerLock: KeyedLock | undefined; + /** The host's record of what each call's RPCs did. */ + executed(msg: PiWorkerRpc): CallExecution; + /** Admits a permission request: a tool outside the provable set ends execution proof. */ + admitTool(toolName: string): void; + autonomous: boolean; + /** The worker's resolved sandbox; native file observations require a governed one. */ + sandbox: Pick; + /** The host-supplied sandbox, if any; a governed one keeps the native write and edit tools. */ + workerSandbox: WorkerSandbox | undefined; + observeFile(path: string): ReturnType>; + nativeVersions: NativeFileVersions; + /** The worker reaches inference through the host relay, which owns its credential state. */ + relayed: boolean; + agentDir: string; + agentFiles: Record; + allowedTools: ReadonlySet; + confirmPatterns: ReturnType; + bridgeTools: ReturnType; + capabilities: SessionCaps; + receipts: Pick; +} + +type PiWorkerRpcHandler = (msg: PiWorkerRpc, bridge: BackendBridge, context: PiWorkerRpcContext) => Promise; + +/** The path a granted brain_read_base input names; undefined unless it is a valid input. */ +function grantedReadBasePath(granted: string): string | undefined { + try { const parsed = brainReadBaseInput.safeParse(JSON.parse(granted)); return parsed.success ? parsed.data.path : undefined; } + catch { return undefined; } +} + +/** Releases one lock this session's worker holds. */ +async function unlock(msg: PiWorkerRpc, _bridge: BackendBridge, { releases }: PiWorkerRpcContext): Promise { + if (typeof msg.input.lockId !== "string" || Object.keys(msg.input).length !== 1 || !releases.has(msg.input.lockId)) throw new Error("Unknown pi worker lock"); + releases.get(msg.input.lockId)!(); releases.delete(msg.input.lockId); return { ok: true }; +} + +/** Takes the shared lock key a granted operation's exact input names. */ +async function lock(msg: PiWorkerRpc, _bridge: BackendBridge, context: PiWorkerRpcContext): Promise { + const { grants, workerLock, brainPath, turn: turnContext, live, releases, executed } = context; + const grant = grants.get(msg.toolCallId); + if (!workerLock || !grant || grant.name !== msg.toolName) throw new Error("Pi worker lock has no server permission grant"); + const input = JSON.parse(grant.input); + const fileTool = ["write_file", "edit_file"].includes(msg.toolName); + // The worker locks the canonical contained target, including an internal + // symlink or a missing leaf below an existing parent. Validate identically. + const target = fileTool && typeof input.path === "string" ? safeResolve(brainPath, input.path) : null; + const key = msg.toolName === "bash" ? bashLockKey(input.command) + : fileTool ? target && `path:${target}` : BRAIN_LOCK_KEY; + if (typeof key !== "string" || msg.input.key !== key || Object.keys(msg.input).length !== 1) throw new Error("Pi worker lock does not match the authorized operation"); + const release = await workerLock.acquire(key, { signal: turnContext.signal ?? undefined }); + try { live(); } catch (error) { release(); throw error; } + const lockId = randomUUID(); releases.set(lockId, release); executed(msg).lock = true; return { lockId }; +} + +/** Records one phase of a granted native file read or write against the worker's file view. */ +async function fileObservation(msg: PiWorkerRpc, _bridge: BackendBridge, context: PiWorkerRpcContext): Promise { + const { grants, autonomous, sandbox, observeFile, nativeVersions, executed } = context; + const grant = grants.get(msg.toolCallId); + const input = grant && JSON.parse(grant.input); + const phase = msg.input.phase; + if (autonomous || sandbox.profile !== "governed" || !grant || grant.name !== msg.toolName + || !["read_file", "write_file", "edit_file"].includes(msg.toolName) + || typeof input.path !== "string" || msg.input.path !== input.path || Object.keys(msg.input).length !== 2 + || !(msg.toolName === "read_file" ? ["read_start", "read_end"] : ["write_check", "write_end"]).includes(phase as string)) { + throw new Error("Native file observation has no matching granted operation"); + } + const observed = observeFile(input.path); + if (!observed) throw new Error("Native file observation is outside the worker file view"); + if (phase === "read_start") await nativeVersions.beginRead(msg.toolCallId, observed.key, observed.version); + else if (phase === "read_end") await nativeVersions.finishRead(msg.toolCallId, observed.version, true); + else if (phase === "write_check") { + const refusal = nativeVersions.check(observed.key, observed.version); + if (refusal) throw new Error(refusal); + await nativeVersions.beginWrite(observed.key); + } else await nativeVersions.finishWrite(observed.key, observed.version); + executed(msg).phases.add(phase as string); + return { ok: true }; +} + +/** Writes the worker's refreshed native login back to the host's store. */ +async function syncAuth(msg: PiWorkerRpc, _bridge: BackendBridge, { relayed, agentDir, agentFiles }: PiWorkerRpcContext): Promise { + // A relayed worker's auth.json is a placeholder; the host refreshes its own store. + if (relayed) throw new Error("A relayed pi worker cannot write the host's credential state"); + if (Object.keys(msg.input).length !== 1 || typeof msg.input.content !== "string") throw new Error("Malformed native pi state request"); + syncPiAuth(agentDir, agentFiles["auth.json"], msg.input.content); + agentFiles["auth.json"] = msg.input.content; + return { ok: true }; +} + +/** Decides one tool call: application tools defer to the server route, every other tool to the gate. */ +async function permission(msg: PiWorkerRpc, bridge: BackendBridge, context: PiWorkerRpcContext): Promise { + const { admitTool, turn: turnContext, workerSandbox, grants, allowedTools, confirmPatterns, live } = context; + admitTool(msg.toolName); + if (isCompletedAutonomousToolCall(turnContext.autonomous, msg.toolName, msg.input)) { + return { behavior: "deny", message: "This call already completed before yielding; inspect its retained result instead of replaying it." }; + } + const application = Object.values(BRAIN_APPLICATION_TOOLS).includes(msg.toolName as any) + && !(workerSandbox?.profile === "governed" && ["write_file", "edit_file"].includes(msg.toolName)); + if (!turnContext.autonomous && application && !bridge.applyBrain) return { behavior: "deny", message: "No server application route is available in this turn." }; + if (application && bridge.applyBrain) { + // Exact application authorization belongs to the server route. + return { behavior: "allow" }; + } + grants.delete(msg.toolCallId); + const decision = await decidePiToolPermission({ turn: turnContext, allowedTools, confirmPatterns }, msg.toolName, msg.input, msg.toolCallId); + live(); + if (decision.behavior === "allow") grants.set(msg.toolCallId, { name: msg.toolName, input: JSON.stringify(decision.updatedInput ?? msg.input) }); + return decision; +} + +/** Runs one granted bridge tool on the host; a hosted mask records its application receipt. */ +async function bridgeCall(msg: PiWorkerRpc, bridge: BackendBridge, session: PiWorkerRpcContext): Promise { + const { grants, bridgeTools, executed, live, brainPath, turn: turnContext, capabilities } = session; + const { applications, persist } = session.receipts; + const grant = grants.get(msg.toolCallId); + grants.delete(msg.toolCallId); + if (!grant || grant.name !== msg.toolName || grant.input !== JSON.stringify(msg.input)) { + throw new Error("Pi worker bridge call has no matching server permission decision."); + } + const tool = bridgeTools.find(tool => tool.name === msg.toolName); + if (!tool) throw new Error("Pi worker bridge is outside the turn's capability roster."); + executed(msg).host = true; + if (msg.toolName === "request_image_mask") { + REQUEST_IMAGE_MASK_INPUT_SCHEMA.parse(msg.input); + if (!bridge.applyImageMask) throw new Error("Hosted masks require the server-owned PNG application route."); + const context = { ...turnContext, bridge: { ...bridge, + requestMask: async (path: string, instruction?: string) => { + live(); + const png = await bridge.requestMask!(path, instruction); + live(); + return png; + }, + applyImageMask: async (proposal: Parameters>[0]) => { + live(); + const result = await bridge.applyImageMask!(proposal); + applications.set(msg.toolCallId, { name: msg.toolName, input: msg.input, result }); + persist(); + return result; + }, + } }; + const selected = createPiBridgeTools({ brainPath, turn: context, capabilities }).find(t => t.name === msg.toolName)!; + const work = selected.execute(msg.toolCallId, msg.input, turnContext.signal!, undefined, undefined as never); + turnContext.pendingMutations?.add(work); + try { + const output = await work; + const receipt = applications.get(msg.toolCallId); + if (receipt && !turnContext.signal?.aborted) { receipt.output = output; persist(); } + return output; + } finally { turnContext.pendingMutations?.delete(work); } + } + return tool.execute(msg.toolCallId, msg.input, turnContext.signal!, undefined, undefined as never); +} + +/** Reads one granted document's server base. */ +async function readBase(msg: PiWorkerRpc, bridge: BackendBridge, { grants, executed }: PiWorkerRpcContext): Promise { + if (msg.toolName !== "brain_read_base" || Object.keys(msg.input).length !== 1 || typeof msg.input.path !== "string") { + throw new Error("Malformed pi document-base request"); + } + const grant = grants.get(msg.toolCallId); + grants.delete(msg.toolCallId); + // The grant covers the whole tool input (path plus any page range); the + // server base request carries only its path, which must match exactly. + if (!grant || grant.name !== "brain_read_base" || grantedReadBasePath(grant.input) !== msg.input.path) { + throw new Error("Pi document-base request has no matching server permission decision."); + } + if (!bridge.readBrainBase) throw new Error("No server document-base reader is available."); + executed(msg).host = true; + return bridge.readBrainBase(msg.input.path); +} + +/** Sends one application to the server's authoritative route and keeps its receipt. */ +async function apply(msg: PiWorkerRpc, bridge: BackendBridge, context: PiWorkerRpcContext): Promise { + const { executed, turn: turnContext } = context; + const { applications, persist } = context.receipts; + const input = brainApplicationInput.parse(msg.input); + if (!bridge.applyBrain) throw new Error("No authoritative server application route is available for this turn."); + executed(msg).host = true; + // applyBrain binds the principal and turn on the server, validates exact + // membership/approvals/aliases and rechecks revocation under its write lock. + const pending = bridge.applyBrain(input); + turnContext.pendingMutations?.add(pending); + try { + const result = await pending; + applications.set(msg.toolCallId, { name: BRAIN_APPLICATION_TOOLS[input.operation], input: msg.input, result }); + persist(); + return result; + } + finally { turnContext.pendingMutations?.delete(pending); } +} + +/** One handler per worker RPC method. */ +export const PI_WORKER_RPC_HANDLERS: Readonly> = { + unlock, lock, fileObservation, syncAuth, permission, bridge: bridgeCall, readBase, apply, +}; + +/** + * The session's RPC dispatcher. A refused call, including one whose method + * has no handler, rejects; the worker receives the refusal as its answer. + */ +export function createPiWorkerRpcDispatcher(context: PiWorkerRpcContext): (msg: PiWorkerRpc) => Promise { + let lastRpcId = 0; + return msg => { + try { + context.live(); + if (msg.id <= lastRpcId) throw new Error("Replayed pi worker RPC"); + lastRpcId = msg.id; + const bridge = context.turn.bridge!; + const handler = Object.hasOwn(PI_WORKER_RPC_HANDLERS, msg.method) ? PI_WORKER_RPC_HANDLERS[msg.method] : undefined; + if (!handler) throw new Error(`Unknown pi worker RPC method: ${String(msg.method)}`); + return handler(msg, bridge, context); + } catch (error) { return Promise.reject(error); } + }; +} diff --git a/packages/ui-backend-pi/src/worker-session.ts b/packages/ui-backend-pi/src/worker-session.ts index f8ebfac823..d869447e81 100644 --- a/packages/ui-backend-pi/src/worker-session.ts +++ b/packages/ui-backend-pi/src/worker-session.ts @@ -1,45 +1,26 @@ -import { brainWorkerPath } from "@schlessera/brain-common/internal/worker-areas"; -import { workerCleanupUnconfirmed, sessionPromptContext, describeClient, workerExecHelpers, WORKER_PROVIDER_CREDENTIAL_ENV, workerProviderCredentials } from "@schlessera/brain-ui-sdk/internal"; -import { safeResolve } from "@schlessera/brain/internal"; -import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"; -import { join, relative, isAbsolute } from "node:path"; +import { sessionPromptContext, describeClient, NativeFileVersions, workerExecHelpers } from "@schlessera/brain-ui-sdk/internal"; +import { join } from "node:path"; import { randomUUID } from "node:crypto"; -import { stateRoomCopy, stateRoomWarning, type StateRoomObservation } from "@schlessera/brain-ui-sdk/protocol"; import { getAgentDir, SessionManager, type AgentSessionEvent } from "@earendil-works/pi-coding-agent"; -import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; -import type { Model } from "@earendil-works/pi-ai"; -import { BackendRequestError, BRAIN_APPLICATION_TOOLS, brainApplicationInput, brainReadBaseInput, type BrainApplicationResult, - compileConfirmPatterns, DEFAULT_CONFIRM_BASH_PATTERNS, isCompletedAutonomousToolCall } from "@schlessera/brain-ui-sdk/server"; -import { bashLockKey, BRAIN_LOCK_KEY } from "@schlessera/brain-ui-sdk/server"; -import { sessionReplay, NativeFileVersions, workerOutwardNote, workerCommandPolicyNote, createLimitTracker, createTurnTempPromoter, launchAgentWorkerAsync, launchLimits, prepareWorkerSandbox, prepareWorkerSandboxAsync, processStateLedger, retainWorkerStartupView, prepareNativeWorkerOutput, type PreparedWorkerOutput, - outputStagingLimit, requireWorkerHostAsync, resolveTurnTempLimits, restrictedReadPaths, turnTempLimit, workerNoteLimits, WorkerResourceLimitError, - workerSandboxNote, workerSandboxWarnings, WORKER_SCRATCH, WORKER_XDG_DIRS, type Reservation, type WorkerSandbox, - type LaunchedWorker, type WorkerStateHandle } from "@schlessera/brain-ui-sdk/internal"; +import { BackendRequestError, compileConfirmPatterns, DEFAULT_CONFIRM_BASH_PATTERNS } from "@schlessera/brain-ui-sdk/server"; -import { decidePiToolPermission } from "./permission-gate.js"; -import { piAutonomousEnvelope } from "./autonomous-envelope.js"; -import { piRelayOrigin, preparePiHostInference, type PiHostInference } from "./host-inference.js"; +import { piRelayOrigin } from "./host-inference.js"; import type { CreatePiBackendOptions, PiSessionLike, SessionEnv } from "./backend-options.js"; -import { configuredProfiles, resolveModelSpec, toModel } from "./profiles.js"; +import { resolveModelSpec, toModel } from "./profiles.js"; import { createTurnContext } from "./turn-context.js"; -import { createPiBridgeTools, REQUEST_IMAGE_MASK_INPUT_SCHEMA } from "./bridge-tools.js"; +import { createPiBridgeTools } from "./bridge-tools.js"; import { DEFAULT_PI_ALLOWED_TOOLS } from "./tools.js"; -import { subprocessEnv, ambientExecConfig, operatorAdmittedEnvNames } from "./config/env.js"; -import { savePiSession, readPiSession, piSessionDirectory, syncPiAuth } from "./session-storage.js"; -import { checkSessionSize, PI_WORKER_STATE, SessionTooLargeError, pipeMessages, sendPipe, piWorkerMessage, type PiWorkerMessage } from "./worker-protocol.js"; +import { ambientExecConfig } from "./config/env.js"; +import { readPiSession, piSessionDirectory } from "./session-storage.js"; +import { admitPiWorker, launchPiWorker, savedModel, superviseWorker } from "./worker-launch.js"; +import { readPiWorkerProtocol, type PiWorkerTurnState } from "./worker-reader.js"; +import { createPiWorkerReceipts } from "./worker-receipts.js"; +import { createPiWorkerRpcDispatcher, type PiWorkerRpc } from "./worker-rpc.js"; + +export { savedModel } from "./worker-launch.js"; -type Rpc = Extract; -/** The model a saved session last used: its latest model change, else its latest answer. */ -export function savedModel(entries: import("@earendil-works/pi-coding-agent").FileEntry[]): { provider: string; id: string } | undefined { - for (const entry of [...entries].reverse() as Array>) { - if (entry.type === "model_change" && typeof entry.provider === "string" && typeof entry.modelId === "string") return { provider: entry.provider, id: entry.modelId }; - const message = entry.type === "message" ? entry.message : undefined; - if (message?.role === "assistant" && typeof message.provider === "string" && typeof message.model === "string") return { provider: message.provider, id: message.model }; - } - return undefined; -} /** What the host saw one call do: the RPCs it made, under the name it ran as (#2834). */ -type CallExecution = { name: string; host: boolean; lock: boolean; phases: Set }; +export type CallExecution = { name: string; host: boolean; lock: boolean; phases: Set }; /** * The execution path one completed call proved, from the host's own record of * its RPCs. Only an extension-free worker's calls are ever passed here: its @@ -54,11 +35,6 @@ export function provenToolExecution(name: string, seen: CallExecution | undefine if (name === "write_file" || name === "edit_file") return seen.lock && phases === "write_check,write_end" ? "worker_write" : undefined; return undefined; } -/** The path a granted brain_read_base input names; undefined unless it is a valid input. */ -function grantedReadBasePath(granted: string): string | undefined { - try { const parsed = brainReadBaseInput.safeParse(JSON.parse(granted)); return parsed.success ? parsed.data.path : undefined; } - catch { return undefined; } -} /** * The exact origin a governed or strict turn's relay would reach (#2695): the * model `openPiWorkerSession` relays, resolved without opening a worker. A @@ -111,7 +87,6 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi } const sessionId = resumeId ?? randomUUID(); const promptContext = env.autonomous ? undefined : sessionPromptContext(sessionDir, backend.brainPath, sessionId); - let ownedPrompt: { id: string; text: string; images: boolean } | undefined; const observationStorage = { directory: join(sessionDir, "native-observations"), brainPath: backend.brainPath, sessionId }; const nativeVersions = nativeSessions.get(sessionId) ?? (!env.autonomous && resumeId ? await NativeFileVersions.restore(observationStorage) : new NativeFileVersions()); @@ -124,330 +99,37 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi const confirmPatterns = compileConfirmPatterns(backend.confirmBashPatterns ?? DEFAULT_CONFIRM_BASH_PATTERNS, () => {}); const bridgeTools = createPiBridgeTools({ brainPath: backend.brainPath, turn: turnContext, capabilities: env.caps }); const grants = new Map(); - const replayTurnId = randomUUID(); - const display = sessionReplay(sessionDir, backend.brainPath, sessionId); - const applications = new Map; result: BrainApplicationResult; anchor?: string | null; output?: Awaited> }>(); - let latestEntries: Record[] = []; + const receipts = createPiWorkerReceipts({ sessionDir, brainPath: backend.brainPath, sessionId, autonomous: Boolean(env.autonomous), entries, resumedIds, + turn: turnContext, backend }); const listeners = new Set<(event: AgentSessionEvent) => void>(); - let active = false; - let initialized = false; - let ended = false; - let cost = 0; - let thinkingLevel: ThinkingLevel | undefined; - let levels: ThinkingLevel[] = []; - let model: Model | undefined; - let lastRpcId = 0; - let error: Error | undefined; + const state: PiWorkerTurnState = { active: false, initialized: false, ended: false, error: undefined, cost: 0, + thinkingLevel: undefined, levels: [], model: undefined, ownedPrompt: undefined }; const ready = Promise.withResolvers(); const done = Promise.withResolvers(); // A rejection before prompt has no waiter yet; still retain it for prompt. void done.promise.catch(() => {}); void ready.promise.catch(() => {}); - const agentFiles: Record = {}; - const agentDir = piSessionDirectory(backend.brainPath, getAgentDir()); - // A restricted autonomous turn copies no native state into the worker: no - // stored login, provider override or settings (#676). The relay holds the key. - const envelope = restricted ? piAutonomousEnvelope(declared, agentDir) : undefined; - // A governed or strict turn on the turn proxy: the host holds the credential - // and the worker's pi reaches inference only through the relay (#1665). - const egress = !env.autonomous ? env.workerSandbox?.egress : undefined; - const relayedModel = egress ? declared ?? (entries ? savedModel(entries) : undefined) : undefined; - if (egress && !relayedModel) throw new BackendRequestError("A pi turn on the host inference relay needs a declared vendor/model profile."); - // Provider folders admitted for a proven recipient (#2695): only its relay may carry this turn. - const recipient = !env.autonomous ? env.workerSandbox?.inferenceRecipient : undefined; - if (recipient && !egress) throw new BackendRequestError("This turn's provider folders were admitted for a recipient, but it has no inference relay to hold it to."); - // Acquired inside the admission scope below, so every later failure releases it. - let hostInference: PiHostInference | undefined; - // A relayed worker gets only settings: the host keeps credentials and endpoints. - if (!envelope) for (const name of egress ? ["settings.json"] : ["auth.json", "models.json", "settings.json"]) { - const path = join(agentDir, name); - if (existsSync(path)) agentFiles[name] = readFileSync(path, "utf8"); - } - const { workerSandbox, workerProviderMasks, workerDataTree, workerLock, workerStarted, workerStartupView, workerSignal, toolExecution, ...workerSessionEnv } = env; - const npmPath = envelope ? undefined : join(agentDir, "npm", "node_modules"); - let cachedNpmModules: string | undefined; - if (npmPath && existsSync(npmPath)) { - const npmRoot = realpathSync(join(agentDir, "npm")); - cachedNpmModules = realpathSync(npmPath); - const descendant = (root: string, path: string) => { const rel = relative(root, path); return rel !== "" && rel !== ".." && !rel.startsWith("../") && !isAbsolute(rel); }; - if (!statSync(cachedNpmModules).isDirectory() || !descendant(agentDir, npmRoot) - || !descendant(npmRoot, cachedNpmModules)) { - throw new BackendRequestError("Pi prepared npm resources must be inside the selected agent directory's npm tree."); - } - } - const init = { type: "init", governed: workerSandbox?.profile === "governed", dataTree: Boolean(workerSandbox?.dataTree ?? workerDataTree), sharedLock: Boolean(workerLock), backend: { exec, brainPath: backend.brainPath, profiles: configuredProfiles(backend), model: backend.model, - loadExtensions: envelope ? false : backend.loadExtensions, systemPromptAppend: backend.systemPromptAppend }, env: workerSessionEnv, sessionId, - resume: Boolean(resumeId), entries, profileId, agentFiles, fixedAppend: promptContext?.append(), ...(cachedNpmModules ? { cachedNpmModules } : {}), ...(envelope ? { inference: envelope.inference } : {}) }; - // Every worker's /tmp is a private tmpfs of exactly this allowance, which - // holds the worker's session state too (#1703). - const turnTempLimits = resolveTurnTempLimits({ ...backend.turnTemp, - names: { allowance: "turnTemp.allowanceBytes", budget: "turnTemp.budgetBytes" } }); - let reservation: Reservation | undefined; - let admissionObservation: StateRoomObservation; - let identity: import("@schlessera/brain-ui-sdk/internal").WorkerNoteFacts["identity"]; - try { - if (egress && relayedModel) { - hostInference = await preparePiHostInference({ provider: relayedModel.provider, modelId: relayedModel.id, agentDir, - ...(recipient ? { recipientOrigin: recipient.origin } : {}), - brainPath: backend.brainPath, egress, environment: subprocessEnv(), ...(env.workerSignal ? { signal: env.workerSignal } : {}) }); - Object.assign(init, { relayed: hostInference.worker }); - } - admissionObservation = checkSessionSize(init); - const workerHost = await requireWorkerHostAsync(backend.brainPath, { restricted, turnTempBytes: turnTempLimits.allowanceBytes }); - if (workerHost?.identity === "separate_uid" && workerHost.workerUid !== undefined) identity = { kind: "separate_uid", workerUid: workerHost.workerUid }; - // Admitted against the same per-process ledger as Claude workers; a busy - // budget refuses as worker_state_busy before anything launches. - reservation = processStateLedger().reserve(undefined, turnTempLimits); - } catch (error) { envelope?.relay.stop(); hostInference?.stop(); throw error; } - const entry = Bun.resolveSync("./worker-entry", import.meta.dir); - const workerEnv: Record = envelope - // The restricted envelope: minimum runtime variables only, the installed - // runtime as the explicit read envelope, and the relay as the one route out. - ? { PATH: "/usr/bin:/bin", LANG: "C.UTF-8", HOME: WORKER_SCRATCH, BRAIN_ROOT: backend.brainPath } - : { ...Object.fromEntries(Object.entries(subprocessEnv()).filter((pair): pair is [string, string] => pair[1] !== undefined)), BRAIN_ROOT: backend.brainPath }; - if (!envelope) workerEnv.PATH = brainWorkerPath(backend.brainPath, workerEnv.PATH); - for (const name of hostInference?.credentialEnv ?? []) delete workerEnv[name]; - // The provider keys a governed or strict worker keeps (#1666). A relayed - // worker keeps only what an operator admits. Without the relay, pi resolves - // its own credentials in the worker and may read any of these, including - // through a models.json `$NAME`, so they stay under the ruling that hosts - // without managed native storage keep today's inference credentials (#2654). - const credentialEnv = [...(hostInference ? [] : WORKER_PROVIDER_CREDENTIAL_ENV), ...operatorAdmittedEnvNames()]; - const providerKeys = workerProviderCredentials(workerEnv, credentialEnv).kept; - workerEnv.PI_CODING_AGENT_DIR = PI_WORKER_STATE; - // SDK offline mode silently skips missing sources. Validate prepared packages - // explicitly in the child; the parent's environment remains unchanged. - delete workerEnv.PI_OFFLINE; - let child: LaunchedWorker; - let launchedChild: LaunchedWorker | undefined; - let preparedOutput: PreparedWorkerOutput | undefined; - let sandboxNote: string; - let sandbox: WorkerSandbox; - // The worker's private /tmp, through the descriptor the server holds, so - // what the answer links there can be promoted once the worker has exited - // (#1655). An autonomous turn saves no answer. - let turnTemp: WorkerStateHandle | undefined; - try { - // One resolution feeds the worker's mounts and the note its agent reads (#1626), - // and one its resource limits and the note's limits section (#1660). - sandbox = envelope ? { ...prepareWorkerSandbox(backend.brainPath, { restricted: true, maintenance: backend.maintenance }), - ...(workerProviderMasks ? { providerMasks: workerProviderMasks } : {}), ...(workerDataTree ? { dataTree: workerDataTree } : {}) } - : workerSandbox ?? await prepareWorkerSandboxAsync(backend.brainPath, { home: workerEnv.HOME, maintenance: backend.maintenance }); - if (hostInference) sandbox = { ...sandbox, maskPaths: [...sandbox.maskPaths ?? [], ...hostInference.maskPaths] }; - if (cachedNpmModules) { - if (sandbox.maskPaths?.some(path => { try { const actual = realpathSync(path); return actual === cachedNpmModules || actual.startsWith(cachedNpmModules + "/"); } catch { return false; } })) { - throw new BackendRequestError("Pi prepared npm resources cannot contain a private worker mask."); - } - sandbox = { ...sandbox, readPaths: [...(sandbox.readPaths ?? restrictedReadPaths([process.execPath, entry])), cachedNpmModules] }; - } - // Worker-local tools run the host's helpers: each file alone, never its parent. - if (execHelpers.length && !envelope) sandbox = { ...sandbox, readPaths: [...(sandbox.readPaths ?? restrictedReadPaths([process.execPath, entry])), ...execHelpers] }; - const limits = launchLimits({}); - sandboxNote = [workerSandboxNote(sandbox, { ...(identity ? { identity } : {}), ...(hostInference ? { egress: true } : {}), providerKeys, hardTimeoutMs: env.turnBudgetMs, limits: [...workerNoteLimits(limits.status), - turnTempLimit(reservation.turnTempBytes, env.caps.turnTemp === true ? "turn_temp" : undefined), - outputStagingLimit()] }), workerCommandPolicyNote(env.autonomous ? undefined : sandbox.commandPolicy, confirmPatterns), env.autonomous ? "" : workerOutwardNote(Boolean(hostInference), sandbox.commandPolicy?.taint?.())].filter(Boolean).join("\n\n"); - if (resumeId && !restricted && stateRoomWarning(admissionObservation)) { - sandboxNote += `\n\n${stateRoomCopy(admissionObservation)} Continue in a new conversation before it is full. This one stays available.`; - } - for (const warning of workerSandboxWarnings(sandbox)) backend.log?.("warn", warning); - if (workerStartupView && sandbox.profile !== "governed" && sandbox.areas.some(area => area.mount.writable)) { - preparedOutput = await prepareNativeWorkerOutput(backend.brainPath, { startupView: workerStartupView, areas: sandbox.areas.filter(area => area.mount.writable).map(area => area.rel), folderPaths: sandbox.retainedFolders, signal: workerSignal }); - } - workerSignal?.throwIfAborted(); - const spawning = performance.now(); - backend.log?.("debug", "Pi startup phase", { phase: "preparation", durationMs: spawning - startupStarted, elapsedMs: spawning - startupStarted }); - child = await launchAgentWorkerAsync({ brainPath: backend.brainPath, turnTempBytes: reservation.turnTempBytes, - ...(preparedOutput ? { preparedOutput } : workerStartupView && sandbox.profile !== "governed" ? { startupView: retainWorkerStartupView(workerStartupView) } : {}), - command: [process.execPath, entry], env: workerEnv, credentialEnv, sandbox, limits, ...(workerLock ? { outputLock: workerLock } : {}), - ...(envelope ? { restricted: { readPaths: [...restrictedReadPaths([entry]), ...execHelpers], inferenceDir: envelope.relay.dir } } : {}), - ...(hostInference && egress ? { egress: { proxyDir: egress.dir, directLoopback: true } } : {}), - }); - launchedChild = child; - backend.log?.("debug", "Pi startup phase", { phase: "spawn", durationMs: performance.now() - spawning, elapsedMs: performance.now() - startupStarted }); - turnTemp = child.turnTemp; - turnContext.configurationRoot = child.configurationRoot; - workerStarted?.(child); - } catch (error) { - // A post-launch callback can fail before the ordinary lifecycle handlers - // exist. Stop and drain this owned child before deleting its native stage. - const cleanupErrors: unknown[] = []; - const attempt = async (cleanup: () => unknown | Promise): Promise => { try { await cleanup(); return true; } catch (failure) { cleanupErrors.push(failure); return false; } }; - let workerStorageReleased = !workerCleanupUnconfirmed(error); - if (launchedChild) { - await attempt(() => launchedChild!.kill("SIGKILL")); - await attempt(() => launchedChild!.exited); - // Nothing reads its stdio yet: close the server's ends, then wait out Bun's duplicates (#2863). - await attempt(() => { launchedChild!.stdin.end(); launchedChild!.stdout.destroy(); launchedChild!.stderr.destroy(); return launchedChild!.released(); }); - workerStorageReleased = await attempt(() => launchedChild!.turnTemp?.closeAsync()); - } - if (workerStorageReleased) await attempt(() => preparedOutput?.cleanup()); - await attempt(() => envelope?.relay.stop()); - await attempt(() => hostInference?.stop()); - if (workerStorageReleased) await attempt(() => reservation.release()); - if (cleanupErrors.length) { - try { backend.log?.("warn", `Pi startup cleanup retained failures after its original refusal: ${cleanupErrors.map(String).join("; ")}`); } catch { /* Reporting cannot replace the startup error. */ } - } - throw error; - } - const held = reservation; - let turnTempClosing: Promise | undefined; - /** - * Frees the worker's turn temp: the tmpfs goes once the worker is gone and - * this descriptor is closed. The reservation is released only once a - * separate-UID worker's broker cleanup is confirmed; a refusal keeps it - * charged, and the next call tries again (#2854). - */ - const closeTurnTemp = (): Promise => turnTempClosing ??= (async () => { await turnTemp?.closeAsync(); held.release(); })() - .catch((error: unknown) => { turnTempClosing = undefined; throw error; }); - // The turn_temp tool reaches this worker's /tmp only while it runs (#1703). - let workerLive = true; - void child.exited.finally(() => { workerLive = false; }).catch(() => {}); - if (env.caps.turnTemp && turnTemp) { - const root = turnTemp.root; - turnContext.turnTemp = { - root: () => workerLive ? root : undefined, allowanceBytes: held.turnTempBytes, scratch: WORKER_SCRATCH, - exclude: [PI_WORKER_STATE], keep: [WORKER_SCRATCH, ...Object.values(WORKER_XDG_DIRS)], - linkedText: () => answerText(), - }; - } - // The relay lives exactly as long as the worker it serves. - if (envelope) void child.exited.finally(() => envelope.relay.stop()).catch(() => {}); - if (hostInference) void child.exited.finally(() => hostInference.stop()).catch(() => {}); - const releases = new Map void>(); - void child.exited.finally(() => { for (const release of releases.values()) release(); releases.clear(); }).catch(() => {}); - // A worker that never ran a turn has nothing to promote; one that did is - // cleaned up by `promote` once its answer has been read. Initialization - // failure and an inactive abort also await this close themselves. - let prompted = false; - void child.exited.finally(() => prompted ? undefined : closeTurnTemp()).catch(() => {}); - child.stdin.on("error", () => {}); - let diagnostic = ""; - child.stderr.on("data", bytes => { diagnostic = (diagnostic + String(bytes)).slice(-4000); }); - // Each new host-limit hit is reported next to the step that caused it (#1660). - const freshLimitHits = createLimitTracker(); - const reportLimitHits = (): void => { - const fresh = freshLimitHits(child.limitReport()); - if (!fresh.length) return; - try { turnContext.bridge?.activity?.({ kind: "resource_limit", limits: fresh, fatal: false }); } catch { /* observability only */ } - }; - /** - * Once the worker has exited: the limit that ended it, as the turn's - * failure. Settled once, however many paths ask, and bounded: a worker that - * closed its protocol but did not exit is not a limit's doing. - */ - let limitSettlement: Promise | undefined; - const limitEnded = (): Promise => limitSettlement ??= (async () => { - let timer: ReturnType | undefined; - const exited = await Promise.race([child.exited.then(() => true, () => true), - new Promise(resolve => { timer = setTimeout(() => resolve(false), 3_000); })]); - clearTimeout(timer); - if (!exited) return undefined; - const report = child.limitReport(); - if (!report.fatal) { reportLimitHits(); return undefined; } - try { turnContext.bridge?.activity?.({ kind: "resource_limit", limits: report.hits, fatal: true }); } catch { /* observability only */ } - return new WorkerResourceLimitError(report.hits); - })(); - const send = (value: unknown) => sendPipe(child.stdin, value); - /** - * Once the worker has exited, its stdio can still be open here (#2863): Bun - * closes its own duplicates of the FIFO descriptors on its pool after their - * streams end. Prompt, refused initialization and pre-prompt cancellation - * settle only after this, which resolves once they are closed or its bound expires. - */ - const stdioReleased = (): Promise => { child.stdin.end(); return child.released(); }; + const admission = await admitPiWorker({ backend, env, declared, restricted, entries, resumeId, sessionId, profileId, promptContext, exec }); + const { agentDir, agentFiles, envelope, hostInference, reservation, admissionObservation } = admission; + const { workerSandbox, workerLock, workerSignal, toolExecution } = admission.hostEnv; + const { child, sandbox, sandboxNote, turnTemp } = await launchPiWorker({ backend, env, admission, restricted, resumeId, execHelpers, confirmPatterns, + startupStarted, turnContext }); + const { closeTurnTemp, releases, markPrompted, diagnostic, reportLimitHits, limitEnded, send, stdioReleased } = superviseWorker({ child, reservation, + turnTemp, env, turnContext, admission, answerText: () => receipts.answerText() }); function live(): void { - if (!active || ended || !turnContext.bridge || !turnContext.signal || turnContext.signal.aborted) { + if (!state.active || state.ended || !turnContext.bridge || !turnContext.signal || turnContext.signal.aborted) { throw new Error("Pi worker RPC refused: turn is inactive, cancelled or revoked."); } } function fail(reason: unknown): void { // The first failure is the turn's: a later path cannot reclassify it. - if (error) return; - error = reason instanceof Error ? reason : new Error(String(reason)); + if (state.error) return; + state.error = reason instanceof Error ? reason : new Error(String(reason)); nativeVersions.cancelPending(); - ended = true; - ready.reject(error); done.reject(error); + state.ended = true; + ready.reject(state.error); done.reject(state.error); child.kill("SIGKILL"); } - function persist(recoverMissing = false): void { - if (env.autonomous) return; - // Receipt ownership survives even when no runtime call or snapshot exists. - // Never synthesize a model call or replace a runtime-written result. - for (const [id, receipt] of applications) { - const called = latestEntries.find(entry => !resumedIds.has(entry.id) && entry.type === "message" - && (entry.message as any)?.role === "assistant" && (entry.message as any).content.some((part: any) => part.type === "toolCall" && part.id === id)); - if (typeof called?.id === "string") receipt.anchor = called.id; - else if (receipt.anchor === undefined) { - // Direct effects can precede every native message. Null is an owned - // session-root position, not an anchor to a later worker snapshot. - const prior = latestEntries.findLast(entry => entry.type === "message") - ?? entries?.findLast(entry => entry.type === "message"); - receipt.anchor = typeof prior?.id === "string" ? prior.id : null; - } - display.retainReceipt({ id, name: receipt.name, input: receipt.input, anchor: receipt.anchor, turnId: replayTurnId, - output: receipt.output?.content.filter(part => part.type === "text").map(part => part.text).join("") ?? JSON.stringify(receipt.result), - isError: !receipt.result.ok }); - } - if (!latestEntries.some(entry => entry.type === "message")) return; - const saved = [...latestEntries]; - if (recoverMissing) for (const [id, receipt] of applications) { - const called = saved.some(entry => !resumedIds.has(entry.id) && entry.type === "message" && (entry.message as any)?.role === "assistant" - && (entry.message as any).content.some((part: any) => part.type === "toolCall" && part.id === id)); - const answered = saved.some(entry => !resumedIds.has(entry.id) && entry.type === "message" && (entry.message as any)?.role === "toolResult" - && (entry.message as any).toolCallId === id); - if (!called || answered) continue; - // The installed Pi adapter repairs orphaned calls with "No result provided". - // Preserve the committed effect instead, only after the runtime has exited. - saved.push({ type: "message", id: randomUUID(), parentId: saved.at(-1)?.id ?? null, - timestamp: new Date().toISOString(), message: { role: "toolResult", toolCallId: id, toolName: receipt.name, - content: receipt.output?.content ?? [{ type: "text", text: JSON.stringify(receipt.result) }], - isError: !receipt.result.ok, timestamp: Date.now() } }); - } - savePiSession(sessionDir, sessionId, saved); - } - - /** - * Once the worker has exited, copies what this turn's answers link in turn - * temp into scratch, retains display mappings outside the transcript, and reports each - * linked file to the host (#1655). Turn temp is removed either way. - */ - async function promote(): Promise { - try { - persist(true); - if (!turnTemp || env.autonomous) return; - const promoter = createTurnTempPromoter({ brain: sandbox.brain, tmp: turnTemp.root, turnId: turnContext.turnId, scratch: WORKER_SCRATCH, - exclude: [PI_WORKER_STATE], scratchWritable: sandbox.areas.some(area => area.name === "scratch" && area.mount.writable) }); - for (const entry of latestEntries) { - if (entry.type !== "message" || resumedIds.has(entry.id)) continue; - const message = entry.message as { role?: unknown; content?: unknown } | undefined; - if (message?.role !== "assistant" || !Array.isArray(message.content)) continue; - for (const [index, part] of (message.content as Array<{ type?: unknown; text?: unknown }>).entries()) { - if (part?.type !== "text" || typeof part.text !== "string") continue; - await promoter.prepareRecovery(part.text, turnContext.signal ?? undefined); - const next = promoter.rewrite(part.text); - if (typeof entry.id === "string") display.retainText(entry.id, index, part.text, next); - } - } - for (const record of promoter.records) { - try { turnContext.bridge?.activity?.(record); } catch { /* Observability must not fail the observed turn. */ } - } - } catch (failure) { - backend.log?.("warn", `promoting linked turn-temp files failed: ${failure instanceof Error ? failure.message : String(failure)}`); - } finally { await closeTurnTemp(); } - } - /** The answer text of this turn's new assistant entries, as the worker has reported them. */ - function answerText(): string { - const parts: string[] = []; - for (const entry of latestEntries) { - if (entry.type !== "message" || resumedIds.has(entry.id)) continue; - const message = entry.message as { role?: unknown; content?: unknown } | undefined; - if (message?.role !== "assistant" || !Array.isArray(message.content)) continue; - for (const part of message.content as Array<{ type?: unknown; text?: unknown }>) { - if (part?.type === "text" && typeof part.text === "string") parts.push(part.text); - } - } - return parts.join("\n"); - } // Extension code runs on every tool event and can write at any time (#2834): // only a worker that loads none can prove a call's execution path. Proof // also ends, for the worker's lifetime, once it admits a call that can run @@ -455,246 +137,18 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi // an application tool) or starts a call under a running call's identity: // from then on the worker's own reports are no evidence. const extensionFree = envelope !== undefined || backend.loadExtensions === false; - const provableTools = new Set(["read_file", "write_file", "edit_file", "brain_read_base", ...bridgeTools.map(tool => tool.name)]); - let provable = extensionFree; - const running = new Set(); - const executions = new Map(); - const executed = (msg: Rpc): CallExecution => { - let seen = executions.get(msg.toolCallId); - if (!seen) executions.set(msg.toolCallId, seen = { name: msg.toolName, host: false, lock: false, phases: new Set() }); - // A call that names two tools proves neither. - else if (seen.name !== msg.toolName) seen.name = ""; - return seen; - }; - async function dispatch(msg: Rpc): Promise { - live(); - if (msg.id <= lastRpcId) throw new Error("Replayed pi worker RPC"); - lastRpcId = msg.id; - const bridge = turnContext.bridge!; - if (msg.method === "unlock") { - if (typeof msg.input.lockId !== "string" || Object.keys(msg.input).length !== 1 || !releases.has(msg.input.lockId)) throw new Error("Unknown pi worker lock"); - releases.get(msg.input.lockId)!(); releases.delete(msg.input.lockId); return { ok: true }; - } - if (msg.method === "lock") { - const grant = grants.get(msg.toolCallId); - if (!workerLock || !grant || grant.name !== msg.toolName) throw new Error("Pi worker lock has no server permission grant"); - const input = JSON.parse(grant.input); - const fileTool = ["write_file", "edit_file"].includes(msg.toolName); - // The worker locks the canonical contained target, including an internal - // symlink or a missing leaf below an existing parent. Validate identically. - const target = fileTool && typeof input.path === "string" ? safeResolve(backend.brainPath, input.path) : null; - const key = msg.toolName === "bash" ? bashLockKey(input.command) - : fileTool ? target && `path:${target}` : BRAIN_LOCK_KEY; - if (typeof key !== "string" || msg.input.key !== key || Object.keys(msg.input).length !== 1) throw new Error("Pi worker lock does not match the authorized operation"); - const release = await workerLock.acquire(key, { signal: turnContext.signal ?? undefined }); - try { live(); } catch (error) { release(); throw error; } - const lockId = randomUUID(); releases.set(lockId, release); executed(msg).lock = true; return { lockId }; - } - if (msg.method === "fileObservation") { - const grant = grants.get(msg.toolCallId); - const input = grant && JSON.parse(grant.input); - const phase = msg.input.phase; - if (env.autonomous || sandbox.profile !== "governed" || !grant || grant.name !== msg.toolName - || !["read_file", "write_file", "edit_file"].includes(msg.toolName) - || typeof input.path !== "string" || msg.input.path !== input.path || Object.keys(msg.input).length !== 2 - || !(msg.toolName === "read_file" ? ["read_start", "read_end"] : ["write_check", "write_end"]).includes(phase as string)) { - throw new Error("Native file observation has no matching granted operation"); - } - const observed = child.observeFile?.(input.path); - if (!observed) throw new Error("Native file observation is outside the worker file view"); - if (phase === "read_start") await nativeVersions.beginRead(msg.toolCallId, observed.key, observed.version); - else if (phase === "read_end") await nativeVersions.finishRead(msg.toolCallId, observed.version, true); - else if (phase === "write_check") { - const refusal = nativeVersions.check(observed.key, observed.version); - if (refusal) throw new Error(refusal); - await nativeVersions.beginWrite(observed.key); - } else await nativeVersions.finishWrite(observed.key, observed.version); - executed(msg).phases.add(phase as string); - return { ok: true }; - } - if (msg.method === "syncAuth") { - // A relayed worker's auth.json is a placeholder; the host refreshes its own store. - if (hostInference) throw new Error("A relayed pi worker cannot write the host's credential state"); - if (Object.keys(msg.input).length !== 1 || typeof msg.input.content !== "string") throw new Error("Malformed native pi state request"); - syncPiAuth(agentDir, agentFiles["auth.json"], msg.input.content); - agentFiles["auth.json"] = msg.input.content; - return { ok: true }; - } - if (msg.method === "permission") { - if (!provableTools.has(msg.toolName)) provable = false; - if (isCompletedAutonomousToolCall(turnContext.autonomous, msg.toolName, msg.input)) { - return { behavior: "deny", message: "This call already completed before yielding; inspect its retained result instead of replaying it." }; - } - const application = Object.values(BRAIN_APPLICATION_TOOLS).includes(msg.toolName as any) - && !(workerSandbox?.profile === "governed" && ["write_file", "edit_file"].includes(msg.toolName)); - if (!turnContext.autonomous && application && !bridge.applyBrain) return { behavior: "deny", message: "No server application route is available in this turn." }; - if (application && bridge.applyBrain) { - // Exact application authorization belongs to the server route. - return { behavior: "allow" }; - } - grants.delete(msg.toolCallId); - const decision = await decidePiToolPermission({ turn: turnContext, allowedTools, confirmPatterns }, msg.toolName, msg.input, msg.toolCallId); - live(); - if (decision.behavior === "allow") grants.set(msg.toolCallId, { name: msg.toolName, input: JSON.stringify(decision.updatedInput ?? msg.input) }); - return decision; - } - if (msg.method === "bridge") { - const grant = grants.get(msg.toolCallId); - grants.delete(msg.toolCallId); - if (!grant || grant.name !== msg.toolName || grant.input !== JSON.stringify(msg.input)) { - throw new Error("Pi worker bridge call has no matching server permission decision."); - } - const tool = bridgeTools.find(tool => tool.name === msg.toolName); - if (!tool) throw new Error("Pi worker bridge is outside the turn's capability roster."); - executed(msg).host = true; - if (msg.toolName === "request_image_mask") { - REQUEST_IMAGE_MASK_INPUT_SCHEMA.parse(msg.input); - if (!bridge.applyImageMask) throw new Error("Hosted masks require the server-owned PNG application route."); - const context = { ...turnContext, bridge: { ...bridge, - requestMask: async (path: string, instruction?: string) => { - live(); - const png = await bridge.requestMask!(path, instruction); - live(); - return png; - }, - applyImageMask: async (proposal: Parameters>[0]) => { - live(); - const result = await bridge.applyImageMask!(proposal); - applications.set(msg.toolCallId, { name: msg.toolName, input: msg.input, result }); - persist(); - return result; - }, - } }; - const selected = createPiBridgeTools({ brainPath: backend.brainPath, turn: context, capabilities: env.caps }).find(t => t.name === msg.toolName)!; - const work = selected.execute(msg.toolCallId, msg.input, turnContext.signal!, undefined, undefined as never); - turnContext.pendingMutations?.add(work); - try { - const output = await work; - const receipt = applications.get(msg.toolCallId); - if (receipt && !turnContext.signal?.aborted) { receipt.output = output; persist(); } - return output; - } finally { turnContext.pendingMutations?.delete(work); } - } - return tool.execute(msg.toolCallId, msg.input, turnContext.signal!, undefined, undefined as never); - } - if (msg.method === "readBase") { - if (msg.toolName !== "brain_read_base" || Object.keys(msg.input).length !== 1 || typeof msg.input.path !== "string") { - throw new Error("Malformed pi document-base request"); - } - const grant = grants.get(msg.toolCallId); - grants.delete(msg.toolCallId); - // The grant covers the whole tool input (path plus any page range); the - // server base request carries only its path, which must match exactly. - if (!grant || grant.name !== "brain_read_base" || grantedReadBasePath(grant.input) !== msg.input.path) { - throw new Error("Pi document-base request has no matching server permission decision."); - } - if (!bridge.readBrainBase) throw new Error("No server document-base reader is available."); - executed(msg).host = true; - return bridge.readBrainBase(msg.input.path); - } - const input = brainApplicationInput.parse(msg.input); - if (!bridge.applyBrain) throw new Error("No authoritative server application route is available for this turn."); - executed(msg).host = true; - // applyBrain binds the principal and turn on the server, validates exact - // membership/approvals/aliases and rechecks revocation under its write lock. - const pending = bridge.applyBrain(input); - turnContext.pendingMutations?.add(pending); - try { - const result = await pending; - applications.set(msg.toolCallId, { name: BRAIN_APPLICATION_TOOLS[input.operation], input: msg.input, result }); - persist(); - return result; - } - finally { turnContext.pendingMutations?.delete(pending); } - } - const received = (async () => { - for await (const raw of pipeMessages(child.stdout)) { - const msg = piWorkerMessage.parse(raw); - if (ended) throw new Error("Pi worker sent a message after turn completion"); - if (msg.type === "startup_timing") { - backend.log?.("debug", "Pi startup phase", { phase: msg.phase, durationMs: msg.durationMs, elapsedMs: performance.now() - startupStarted }); - } else if (msg.type === "ready") { - backend.log?.("debug", "Pi startup ready", { elapsedMs: performance.now() - startupStarted }); - if (msg.sessionId !== sessionId || initialized || active) throw new Error("Pi worker changed its server session identity"); - initialized = true; - if (promptContext && msg.append !== undefined) promptContext.retainAppend(msg.append, env.sessionBudgetLimits ? { limits: env.sessionBudgetLimits } : {}); - model = msg.model as Model | undefined; - cost = msg.cost; thinkingLevel = msg.thinkingLevel as ThinkingLevel; levels = msg.levels as ThinkingLevel[]; - ready.resolve(); - } else if (msg.type === "prompt_prefix") { - if (!active) throw new Error("Pi worker emitted a prefix outside the turn"); - if (!env.autonomous) { - try { turnContext.bridge?.activity?.({ kind: "prompt_prefix", prefix: msg.prefix, resumed: Boolean(resumeId) }); } - catch { /* Observability must not fail the observed turn. */ } - } - } else if (msg.type === "rpc") { - // Do not block reading: a bridge may wait for user input while other - // sibling calls, cancellation and model frames need to flow. - void dispatch(msg).then(value => { - if (!ended) send({ type: "answer", id: msg.id, value }); - }, refusal => { - const message = refusal instanceof Error ? refusal.message : String(refusal); - turnContext.bridge?.emit({ type: "error", code: "PI_WORKER_RPC_REFUSED", message, sessionId }); - if (!ended) send({ type: "answer", id: msg.id, error: message }); - }).catch(fail); - } else if (msg.type === "event") { - if (!active) throw new Error("Pi worker emitted an event outside the turn"); - if (msg.event.type === "tool_execution_start") { - if (running.has(msg.event.toolCallId)) provable = false; - running.add(msg.event.toolCallId); - } - if (msg.event.type === "tool_execution_end") { - reportLimitHits(); - const started = running.delete(msg.event.toolCallId); - const proven = provable && started ? provenToolExecution(msg.event.toolName, executions.get(msg.event.toolCallId)) : undefined; - executions.delete(msg.event.toolCallId); - if (proven) toolExecution?.(msg.event.toolCallId, proven); - const receipt = applications.get(msg.event.toolCallId); - if (receipt) { - msg.event.result = receipt.output ? { content: receipt.output.content.map(part => ({ ...part })), details: receipt.output.details } : { content: [{ type: "text", text: JSON.stringify(receipt.result) }], details: receipt.result }; - msg.event.isError = !receipt.result.ok; - } - } - for (const listener of listeners) listener(msg.event as AgentSessionEvent); - } else if (msg.type === "snapshot") { - if (!active) throw new Error("Pi worker sent transcript state outside the turn"); - const header = msg.entries[0]; - if (header?.type !== "session" || header.id !== sessionId || header.cwd !== backend.brainPath) { - throw new Error("Pi worker sent an invalid transcript identity"); - } - latestEntries = msg.entries; - if (ownedPrompt) { - for (const entry of latestEntries) { - if (entry.type !== "message" || resumedIds.has(entry.id)) continue; - const message = entry.message as { role?: string; content?: unknown } | undefined; - const wire = Array.isArray(message?.content) ? message.content.filter(part => part.type === "text").map(part => part.text).join("") : message?.content; - // The installed runtime appends image-normalization hints after the - // exact submitted text. Bind the full observed bytes to this owned - // turn now; replay never strips a suffix or matches host patterns. - const delivered = typeof wire === "string" && (wire === ownedPrompt.text - || ownedPrompt.images && wire.startsWith(ownedPrompt.text + "\n\n")); - if (message?.role === "user" && delivered && typeof entry.id === "string") { - promptContext?.acknowledge(ownedPrompt.id, entry.id, wire as string); - ownedPrompt = undefined; - break; - } - } - } - persist(); - } else if (msg.type === "done") { - if (!active) throw new Error("Pi worker completed an inactive turn"); - // Hits after the last tool step, or in a turn without one, still count. - reportLimitHits(); - cost = msg.cost; nativeVersions.cancelPending(); ended = true; - if (msg.error) done.reject(new Error(msg.error)); else done.resolve(); - } else throw msg.errorClass === "session_too_large" ? new SessionTooLargeError() : new BackendRequestError(msg.message); - } - if (!ended) throw (await limitEnded()) ?? new Error(`Pi worker exited before completion: ${diagnostic || "protocol closed"}`); - })().catch(async error => { + const proof = createExecutionProof(extensionFree, new Set(["read_file", "write_file", "edit_file", "brain_read_base", ...bridgeTools.map(tool => tool.name)])); + const dispatch = createPiWorkerRpcDispatcher({ brainPath: backend.brainPath, turn: turnContext, live, grants, releases, workerLock, + executed: proof.executed, admitTool: proof.admit, autonomous: Boolean(env.autonomous), sandbox, workerSandbox, + observeFile: path => child.observeFile?.(path), nativeVersions, relayed: Boolean(hostInference), agentDir, agentFiles, allowedTools, + confirmPatterns, bridgeTools, capabilities: env.caps, receipts }); + const received = readPiWorkerProtocol({ child, state, ready, done, sessionId, backend, startupStarted, promptContext, + sessionBudgetLimits: env.sessionBudgetLimits, autonomous: Boolean(env.autonomous), resumed: Boolean(resumeId), turnContext, nativeVersions, + receipts, resumedIds, listeners, proof, toolExecution, dispatch, send, fail, reportLimitHits, limitEnded, diagnostic }).catch(async error => { // A worker a limit killed mid-message ends the protocol with a partial // message: if the worker is gone, settle the limit before blaming the // protocol. A live worker that broke the protocol is stopped at once. - if (ended) return fail(error); + if (state.ended) return fail(error); const exited = await Promise.race([child.exited.then(() => true, () => true), Bun.sleep(250).then(() => false)]); fail((exited ? await limitEnded() : undefined) ?? error); }); @@ -702,7 +156,7 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi // The reader sees the worker's last frames first: an error it parsed, or // the limit that ended the worker, outranks a generic exit. await Promise.race([received, Bun.sleep(1_000)]); - if (!ended) fail((await limitEnded()) ?? new BackendRequestError(`Pi worker exited (${code}): ${diagnostic}`)); + if (!state.ended) fail((await limitEnded()) ?? new BackendRequestError(`Pi worker exited (${code}): ${diagnostic()}`)); }).catch(fail); // Copy only native state files over the control pipe. No extension code or // SDK session is initialized in the privileged process. @@ -710,7 +164,7 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi workerSignal?.addEventListener("abort", abortInitialization, { once: true }); try { workerSignal?.throwIfAborted(); - send({ ...init, sandboxNote }); + send({ ...admission.init, sandboxNote }); const timeout = setTimeout(() => fail(new BackendRequestError("Pi worker initialization timed out")), 30_000); try { await ready.promise; } finally { clearTimeout(timeout); } } catch (error) { @@ -726,16 +180,16 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi let aborting: Promise | undefined; const session: PiSessionLike = { ...(resumeId && !restricted ? { stateRoom: admissionObservation } : {}), - reportsPromptPrefix: true, sessionId, get model() { return model; }, get thinkingLevel() { return thinkingLevel; }, - getAvailableThinkingLevels: () => levels, - setThinkingLevel(level) { thinkingLevel = level; send({ type: "thinking", level }); }, + reportsPromptPrefix: true, sessionId, get model() { return state.model; }, get thinkingLevel() { return state.thinkingLevel; }, + getAvailableThinkingLevels: () => state.levels, + setThinkingLevel(level) { state.thinkingLevel = level; send({ type: "thinking", level }); }, subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, async prompt(text, options) { if (options?.streamingBehavior === "followUp") { live(); send({ type: "followUp", text, options }); return; } - if (error) throw error; - if (active || ended) throw new Error("Pi worker turn already started or finished"); - active = true; - prompted = true; + if (state.error) throw state.error; + if (state.active || state.ended) throw new Error("Pi worker turn already started or finished"); + state.active = true; + markPrompted(); // The send is inside the lifecycle: an oversized prompt still ends the // worker and removes its turn temp. const preparedPrompt = promptContext?.prepare(text, { @@ -746,34 +200,66 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi ...(env.sessionBudgetLimits ? { limits: env.sessionBudgetLimits } : {}), ...(env.budgetContext ? { budget: env.budgetContext } : {}), }); - ownedPrompt = preparedPrompt ? { ...preparedPrompt, images: Boolean(options?.images?.length) } : undefined; - try { send({ type: "prompt", text: ownedPrompt?.text ?? text, options }); await done.promise; } + state.ownedPrompt = preparedPrompt ? { ...preparedPrompt, images: Boolean(options?.images?.length) } : undefined; + try { send({ type: "prompt", text: state.ownedPrompt?.text ?? text, options }); await done.promise; } finally { child.stdin.end(); child.kill("SIGKILL"); - try { await child.exited; await received; await promote(); } + try { await child.exited; await received; await receipts.promote({ turnTemp, sandbox, closeTurnTemp }); } finally { try { await closeTurnTemp(); } finally { await stdioReleased(); } } } - if (error) throw error; + if (state.error) throw state.error; }, abort() { // `ended` revokes work; it does not confirm teardown. The signal handler // and the runner must join even if the first abort already set it (#2880). return aborting ??= (async () => { - if (!active) { - ended = true; child.stdin.end(); child.kill("SIGKILL"); + if (!state.active) { + state.ended = true; child.stdin.end(); child.kill("SIGKILL"); try { await child.exited; await received; } finally { try { await closeTurnTemp(); } finally { await stdioReleased(); } } return; } - if (ended) return; + if (state.ended) return; send({ type: "abort" }); - const deadline = setTimeout(() => { ended = true; done.resolve(); child.kill("SIGKILL"); }, 1000); + const deadline = setTimeout(() => { state.ended = true; done.resolve(); child.kill("SIGKILL"); }, 1000); try { await done.promise.catch(() => {}); } finally { clearTimeout(deadline); child.kill("SIGKILL"); await child.exited; } })().catch((error: unknown) => { aborting = undefined; throw error; }); }, - getSessionStats: () => ({ cost }), - dispose() { ended = true; child.stdin.end(); child.kill("SIGKILL"); }, + getSessionStats: () => ({ cost: state.cost }), + dispose() { state.ended = true; child.stdin.end(); child.kill("SIGKILL"); }, }; return { session, turnContext }; } + +/** + * The host's execution proof for one worker (#2834): which tool each call ran + * as and which RPCs it made. Proof ends, for the worker's lifetime, once it + * admits a tool outside the provable set or starts a call under a running + * call's identity. + */ +function createExecutionProof(extensionFree: boolean, provableTools: ReadonlySet) { + let provable = extensionFree; + const running = new Set(); + const executions = new Map(); + return { + executed: (msg: PiWorkerRpc): CallExecution => { + let seen = executions.get(msg.toolCallId); + if (!seen) executions.set(msg.toolCallId, seen = { name: msg.toolName, host: false, lock: false, phases: new Set() }); + // A call that names two tools proves neither. + else if (seen.name !== msg.toolName) seen.name = ""; + return seen; + }, + admit: (toolName: string): void => { if (!provableTools.has(toolName)) provable = false; }, + started: (toolCallId: string): void => { + if (running.has(toolCallId)) provable = false; + running.add(toolCallId); + }, + ended: (toolName: string, toolCallId: string): ReturnType => { + const started = running.delete(toolCallId); + const proven = provable && started ? provenToolExecution(toolName, executions.get(toolCallId)) : undefined; + executions.delete(toolCallId); + return proven; + }, + }; +} diff --git a/packages/ui-backend-pi/tests/brain-read.test.ts b/packages/ui-backend-pi/tests/brain-read.test.ts index 155274e0ea..116ee164f0 100644 --- a/packages/ui-backend-pi/tests/brain-read.test.ts +++ b/packages/ui-backend-pi/tests/brain-read.test.ts @@ -78,7 +78,7 @@ describe("brain_read wrapper", () => { }); describe("brain_read wrapper on a document over the output limit", () => { - // MAX_READ_BYTES in src/tools.ts. + // MAX_READ_BYTES in src/tool-kit.ts. const LIMIT = 100_000; const filler = "Filler line for the long document.\n".repeat(Math.ceil((LIMIT * 1.5) / 35)); const LONG = diff --git a/packages/ui-backend-pi/tests/fixtures/pi-tool-roster.json b/packages/ui-backend-pi/tests/fixtures/pi-tool-roster.json new file mode 100644 index 0000000000..428f175aa2 --- /dev/null +++ b/packages/ui-backend-pi/tests/fixtures/pi-tool-roster.json @@ -0,0 +1,81 @@ +{ + "default": [ + "read_file 9051a3b2be3748a1fe11b1067aed5e2666126afb3bb84a5cffea2a71e67a1681", + "grep 616add2ee4131d1b0c5cc2448967d37fdf845a959baef8e3159241c3b3e7d90b", + "brain_search d5dc99c5314926107d75fb8366181f88e3ac81f035f64fb6f017002819ca6c90", + "brain_context 640e4ae9db31ef3f1ef17fa42ab14167bd0e566d95298e0120996db5f26f44e8", + "brain_read cf8175717bead1ef33c65214e4d895e4223b9865737bd02d82a2909de131a7c6", + "brain_list f60054b8c4924c695181d4d1671569bb8c06792316dc3ef4edfae36b2baa3b34", + "brain_graph db27c539d615c535b32e35bbdfe0a823bdd06669d3bfeaf141c5a0c83a7fc870", + "bash eabe0a02076b50c7c6b64f46fbdab0bcedcec33872170de8846f67b4b6baa67a", + "ask_user 3842ef5ed148d148376025b5a3a37cf0fb52c5a1331eff7240c7056b48d4a1da", + "ask_user_list 622b7f924a372d3d0353fab35c18d76288783dab314e82d1f44daa16f668cb2b", + "ask_user_rank 97e1a44af5237b1804078d60e7c233c1469c627c6891c7abb207e25cf7e5fa8c", + "ask_user_form efa2ee94e929e573137e4ff979d6603066a8fa855b788bea5ce85b146d910471", + "show_block e1d67e294c2ce523ec72a3d876ea53b65a3c3b117ad9a42cc5dc7646e1013781", + "write_file 38d5f85c86c2f3c0defab96735e3f193af2cca60900e6ae68365ccf357d11e98", + "edit_file 5c62ea445ca5d7f77449fc1f5de3c728961df7a884ee8d91b873921f3e5e8f18", + "apply_staged_changes d3b6f8dfa117acaae18de041d7d47d3617a45a0e2630e6c442f23dcf545f843a", + "brain_add e6eca4b78e7f3b63b713ee3bf6abe65d23493dcbfebe203cb34cc03d37fa8f81", + "brain_update a32857f5e059fe8c991f3346ccbb47cf7ca0dde6da514778e19f863d864c83d1", + "brain_archive b27ba0f7c1acf40b15da2d8d623a75c0f40ed40727f06fed52bc1227476360b4", + "brain_read_base 0bc9e9fcccd7f92bd6811a9e688957760a6981a5a150ca94b5a4b4bc2243872b" + ], + "directWorkerData": [ + "read_file 9051a3b2be3748a1fe11b1067aed5e2666126afb3bb84a5cffea2a71e67a1681", + "grep 616add2ee4131d1b0c5cc2448967d37fdf845a959baef8e3159241c3b3e7d90b", + "brain_search d5dc99c5314926107d75fb8366181f88e3ac81f035f64fb6f017002819ca6c90", + "brain_context 640e4ae9db31ef3f1ef17fa42ab14167bd0e566d95298e0120996db5f26f44e8", + "brain_read cf8175717bead1ef33c65214e4d895e4223b9865737bd02d82a2909de131a7c6", + "brain_list f60054b8c4924c695181d4d1671569bb8c06792316dc3ef4edfae36b2baa3b34", + "brain_graph db27c539d615c535b32e35bbdfe0a823bdd06669d3bfeaf141c5a0c83a7fc870", + "write_file e8037338ba387124b6214e5678a7f21cc387fbdb26460d0e2a55c257e27cd2ae", + "edit_file afdbfc1aee91351a95f1f8bdbb9881e06a75f66818e75249a8e631e024eca3dc", + "bash 0ece241f18793a7b2faaf553695d3f4b2edee7a3172aa028416ecdceb73edbc9", + "ask_user 3842ef5ed148d148376025b5a3a37cf0fb52c5a1331eff7240c7056b48d4a1da", + "ask_user_list 622b7f924a372d3d0353fab35c18d76288783dab314e82d1f44daa16f668cb2b", + "ask_user_rank 97e1a44af5237b1804078d60e7c233c1469c627c6891c7abb207e25cf7e5fa8c", + "ask_user_form efa2ee94e929e573137e4ff979d6603066a8fa855b788bea5ce85b146d910471", + "show_block e1d67e294c2ce523ec72a3d876ea53b65a3c3b117ad9a42cc5dc7646e1013781", + "propose_policy_change 1c309b015cfa70e2df1ad059ac4348ddcece4b9a8422eae611ae6a10a3a738c9", + "turn_temp 4d0cc7aaca598fc23425996577f2cf7f6bfb9f2f68959a8e0e2b3cdb3d352b74", + "get_current_location 03290da709551b4a3becab6d926005412c74caf26b8dbac8af75a6d5e80f0aa7", + "query_activity b31f60a56af51efb2d255d3ef57ef4c0c8630312c387872ccfd07697d91db374", + "request_image_mask dd331c937a66244f609a98a1df3d633a81117e9b57e065abdfc187af066a45f5", + "inbox_list e64e5a73d56cb16ac7e91741008579b947b8b491e12324cf7b29e22b4d8d148c", + "inbox_get 19797adb3d356b22b6b4e491a237bc7b3a8401ffa8c7a166d4328ec3ab0803bf", + "inbox_add 78940587a6983f93785fe8231a2cd8cbbd9250103073a12bf3db76ed7dadabd2", + "resolve_action 70b681c9b9917798f4933fa34af188acd36ea2e4918588b0d40a792460c3f001", + "complete_share 6ae9a0464ea4cda929d03a60ec6d0ff5f7cceffe6252a9304614a18b5d0b275c", + "reference_source 813115237f4fe6373691fd4c91aa48583dae479e7f6fa2377320ecd918dcffea", + "reference_worktree b53d1bf8616d9a181ced99e32dc3beb79dd0861359dad77f25e037256c6a9c44", + "apply_staged_changes d3b6f8dfa117acaae18de041d7d47d3617a45a0e2630e6c442f23dcf545f843a", + "brain_add e6eca4b78e7f3b63b713ee3bf6abe65d23493dcbfebe203cb34cc03d37fa8f81", + "brain_update a32857f5e059fe8c991f3346ccbb47cf7ca0dde6da514778e19f863d864c83d1", + "brain_archive b27ba0f7c1acf40b15da2d8d623a75c0f40ed40727f06fed52bc1227476360b4", + "brain_read_base 0bc9e9fcccd7f92bd6811a9e688957760a6981a5a150ca94b5a4b4bc2243872b" + ], + "scratchShell": [ + "read_file 9051a3b2be3748a1fe11b1067aed5e2666126afb3bb84a5cffea2a71e67a1681", + "grep 616add2ee4131d1b0c5cc2448967d37fdf845a959baef8e3159241c3b3e7d90b", + "brain_search d5dc99c5314926107d75fb8366181f88e3ac81f035f64fb6f017002819ca6c90", + "brain_context 640e4ae9db31ef3f1ef17fa42ab14167bd0e566d95298e0120996db5f26f44e8", + "brain_read cf8175717bead1ef33c65214e4d895e4223b9865737bd02d82a2909de131a7c6", + "brain_list f60054b8c4924c695181d4d1671569bb8c06792316dc3ef4edfae36b2baa3b34", + "brain_graph db27c539d615c535b32e35bbdfe0a823bdd06669d3bfeaf141c5a0c83a7fc870", + "bash f1ed7d52b4c6bece0cb490d2656a70b27760b2a0e2543ab59d55948f36671b3e", + "ask_user 3842ef5ed148d148376025b5a3a37cf0fb52c5a1331eff7240c7056b48d4a1da", + "ask_user_list 622b7f924a372d3d0353fab35c18d76288783dab314e82d1f44daa16f668cb2b", + "ask_user_rank 97e1a44af5237b1804078d60e7c233c1469c627c6891c7abb207e25cf7e5fa8c", + "ask_user_form efa2ee94e929e573137e4ff979d6603066a8fa855b788bea5ce85b146d910471", + "show_block e1d67e294c2ce523ec72a3d876ea53b65a3c3b117ad9a42cc5dc7646e1013781", + "request_image_mask dd331c937a66244f609a98a1df3d633a81117e9b57e065abdfc187af066a45f5", + "write_file 38d5f85c86c2f3c0defab96735e3f193af2cca60900e6ae68365ccf357d11e98", + "edit_file 5c62ea445ca5d7f77449fc1f5de3c728961df7a884ee8d91b873921f3e5e8f18", + "apply_staged_changes d3b6f8dfa117acaae18de041d7d47d3617a45a0e2630e6c442f23dcf545f843a", + "brain_add e6eca4b78e7f3b63b713ee3bf6abe65d23493dcbfebe203cb34cc03d37fa8f81", + "brain_update a32857f5e059fe8c991f3346ccbb47cf7ca0dde6da514778e19f863d864c83d1", + "brain_archive b27ba0f7c1acf40b15da2d8d623a75c0f40ed40727f06fed52bc1227476360b4", + "brain_read_base 0bc9e9fcccd7f92bd6811a9e688957760a6981a5a150ca94b5a4b4bc2243872b" + ] +} diff --git a/packages/ui-backend-pi/tests/tool-factories.test.ts b/packages/ui-backend-pi/tests/tool-factories.test.ts new file mode 100644 index 0000000000..f6a45ffb6d --- /dev/null +++ b/packages/ui-backend-pi/tests/tool-factories.test.ts @@ -0,0 +1,177 @@ +/** + * Direct tests of each curated tool factory (#2517), over a stub BrainAccess + * and a temporary repository: every factory runs alone, without the roster. + * The roster itself stays pinned by tool-roster-snapshot.test.ts. + */ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { tmpdir } from "node:os"; +import type { ToolDefinition } from "@earendil-works/pi-coding-agent"; +import { createKeyedLock, type BackendBridge } from "@schlessera/brain-ui-sdk/server"; + +import { brainReadBaseTool, routedApplicationTool, routedApplicationTools } from "../src/application-tools"; +import type { BrainAccess } from "../src/brain-access"; +import { brainAddTool, brainArchiveTool, brainContextTool, brainGraphTool, brainListTool, brainReadTool, brainSearchTool, brainUpdateTool } from "../src/brain-tools"; +import { bashTool, editFileTool, grepTool, readFileTool, writeFileTool } from "../src/file-tools"; +import { createBrainToolKit, type BrainToolKit } from "../src/tool-kit"; +import { toolLockFromKeyed, type BrainToolDeps } from "../src/tools"; +import { createTurnContext } from "../src/turn-context"; +import { resultText } from "./helpers"; +import { makeMockBridge } from "./mock-bridge"; + +const CTX = {} as never; +let root: string; +let calls: unknown[][]; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "pi-tool-factories-")); + mkdirSync(join(root, "notes")); + writeFileSync(join(root, "notes/ithaca.md"), "# Ithaca\n\nOdysseus sails home.\n"); + calls = []; +}); +afterEach(() => { rmSync(root, { recursive: true, force: true }); }); + +function stubBrain(): BrainAccess { + const record = (name: string, result: unknown) => async (...args: unknown[]) => { calls.push([name, ...args]); return result; }; + return { + root, dbPath: join(root, "brain.db"), + resolveInRepo: (rel: string) => { const abs = resolve(root, rel); return abs === root || abs.startsWith(root + "/") ? abs : null; }, + search: record("search", { results: [{ path: "notes/ithaca.md", title: "Ithaca", type: "note", snippet: "sails home" }], warnings: ["keyless"] }), + context: record("context", "Ithaca, home of Odysseus."), + add: record("add", { action: "created", path: "notes/penelope.md", indexed: true }), + list: record("list", [{ path: "notes/ithaca.md", title: "Ithaca" }]), + graph: record("graph", { edges: [{ source: "notes/ithaca.md", target: "notes/troy.md", resolved: true }], nodes: [{ path: "notes/ithaca.md" }, { path: "notes/troy.md" }] }), + update: record("update", { path: "notes/ithaca.md", changed: ["summary"] }), + archive: record("archive", { path: "notes/ithaca.md", archived: true }), + } as unknown as BrainAccess; +} + +function kit(deps: Partial = {}, bridge?: Partial): BrainToolKit { + const turn = createTurnContext(); + if (bridge) turn.bridge = { ...makeMockBridge({}).bridge, ...bridge }; + return createBrainToolKit({ brain: stubBrain(), turn, lock: toolLockFromKeyed(createKeyedLock()), ...deps }); +} + +const run = (tool: ToolDefinition, params: Record) => tool.execute("call-1", params as never, undefined, undefined, CTX); + +test("createBrainToolKit contains paths and keeps a same-turn base only for a server route", () => { + const plain = kit(); + expect(() => plain.resolveOrThrow("../outside.md")).toThrow("escapes the brain repository"); + plain.rememberHash("notes/ithaca.md", "a".repeat(64)); + const routed = kit({}, { applyBrain: async () => ({ ok: true }) as never }); + routed.rememberHash("notes/ithaca.md", "b".repeat(64)); + expect(routed.bases.get(routed.turn.bridge!)?.get("notes/ithaca.md")).toBe("b".repeat(64)); +}); + +test("readFileTool reads one contained file and returns its base on a routed turn", async () => { + const tools = kit({}, { applyBrain: async () => ({ ok: true }) as never }); + const result = await run(readFileTool(tools), { path: "notes/ithaca.md" }); + expect(resultText(result)).toBe("# Ithaca\n\nOdysseus sails home.\n"); + expect((result.details as { expectedBaseHash?: string }).expectedBaseHash).toMatch(/^[a-f0-9]{64}$/); + await expect(run(readFileTool(kit()), { path: "../etc/passwd" })).rejects.toThrow("escapes the brain repository"); +}); + +test("grepTool searches the repository and names each match", async () => { + const result = await run(grepTool(kit({ exec: {} })), { pattern: "Odysseus" }); + expect(resultText(result)).toBe("./notes/ithaca.md:3:Odysseus sails home."); + expect(resultText(await run(grepTool(kit({ exec: {} })), { pattern: "Cyclops" }))).toBe("No matches."); +}); + +test("writeFileTool creates a file under its path lock", async () => { + const result = await run(writeFileTool(kit()), { path: "notes/penelope.md", content: "Weaving." }); + expect(resultText(result)).toBe("Wrote 8 bytes to notes/penelope.md."); + expect(readFileSync(join(root, "notes/penelope.md"), "utf8")).toBe("Weaving."); +}); + +test("editFileTool replaces one unique string and refuses an ambiguous one", async () => { + await run(editFileTool(kit()), { path: "notes/ithaca.md", old_string: "sails home", new_string: "is home" }); + expect(readFileSync(join(root, "notes/ithaca.md"), "utf8")).toBe("# Ithaca\n\nOdysseus is home.\n"); + await expect(run(editFileTool(kit()), { path: "notes/ithaca.md", old_string: "a", new_string: "b" })).rejects.toThrow("is not unique"); +}); + +test("bashTool runs one command in the repository and keeps a nonzero exit", async () => { + const tools = kit({ exec: {} }); + expect(resultText(await run(bashTool(tools), { command: "echo Odysseus" }))).toBe("Odysseus"); + expect(resultText(await run(bashTool(tools), { command: "echo Polyphemus; exit 3" }))).toBe("Polyphemus\n[exit 3]"); + expect(bashTool(kit({ shellCwd: "/worker/scratch" })).description).toStartWith("Run a bash command in writable worker scratch."); +}); + +test("brainSearchTool maps its date filters and refuses a malformed date", async () => { + const result = await run(brainSearchTool(kit()), { query: "home", upcoming: true }); + expect(resultText(result)).toBe("> keyless\n- notes/ithaca.md — Ithaca [note]\n sails home"); + expect(calls[0]![1]).toMatchObject({ query: "home", limit: 10, sort: "deadline" }); + await expect(run(brainSearchTool(kit()), { query: "home", deadline_from: "12 July" })).rejects.toThrow("deadline_from must be a date written YYYY-MM-DD"); +}); + +test("brainContextTool assembles context with its default budget", async () => { + expect(resultText(await run(brainContextTool(kit()), { query: "Ithaca" }))).toBe("Ithaca, home of Odysseus."); + expect(calls).toEqual([["context", "Ithaca", 4000]]); +}); + +test("brainReadTool reads one section of a document", async () => { + expect(resultText(await run(brainReadTool(kit()), { path: "notes/ithaca.md", section: "Ithaca" }))).toContain("Odysseus sails home."); +}); + +test("brainListTool returns its rows as compact JSON", async () => { + const result = await run(brainListTool(kit()), { type: "note" }); + expect(JSON.parse(resultText(result))).toEqual({ documents: [{ path: "notes/ithaca.md", title: "Ithaca" }] }); + expect(calls).toEqual([["list", { type: "note" }]]); +}); + +test("brainGraphTool traverses both directions unless one is named", async () => { + const result = await run(brainGraphTool(kit()), { path: "notes/ithaca.md", direction: "sideways" }); + expect(JSON.parse(resultText(result)).edges).toHaveLength(1); + expect(calls).toEqual([["graph", { path: "notes/ithaca.md", depth: undefined, direction: "both" }]]); +}); + +test("brainAddTool captures content under the brain-docs lock", async () => { + expect(resultText(await run(brainAddTool(kit()), { content: "Penelope weaves." }))).toBe("created: notes/penelope.md"); + expect(calls).toEqual([["add", { content: "Penelope weaves.", type: undefined, title: undefined, tags: undefined }]]); +}); + +test("brainUpdateTool refuses an unknown status before writing", async () => { + await expect(run(brainUpdateTool(kit()), { path: "notes/ithaca.md", status: "lost" })).rejects.toThrow("Invalid status \"lost\""); + expect(calls).toEqual([]); + await run(brainUpdateTool(kit()), { path: "notes/ithaca.md", summary: "Home." }); + expect(calls[0]![1]).toMatchObject({ path: "notes/ithaca.md", summary: "Home." }); +}); + +test("brainArchiveTool archives for real unless asked to preview", async () => { + await run(brainArchiveTool(kit()), { path: "notes/ithaca.md" }); + expect(calls).toEqual([["archive", "notes/ithaca.md", false]]); +}); + +test("routedApplicationTools route every operation, except write and edit on a direct-write roster", () => { + expect(routedApplicationTools(kit(), []).map(tool => tool.name)) + .toEqual(["write_file", "edit_file", "apply_staged_changes", "brain_add", "brain_update", "brain_archive"]); + expect(routedApplicationTools(kit({ directWrites: true }), []).map(tool => tool.name)) + .toEqual(["apply_staged_changes", "brain_add", "brain_update", "brain_archive"]); +}); + +test("routedApplicationTool sends its input to the server with the same-turn base, and falls back without a route", async () => { + const inputs: unknown[] = []; + const tools = kit({}, { applyBrain: async input => { inputs.push(input); return { ok: true, path: "notes/ithaca.md" } as never; } }); + const edit = routedApplicationTools(tools, []).find(tool => tool.name === "edit_file")!; + await expect(run(edit, { path: "notes/ithaca.md", old_string: "sails", new_string: "is" })).rejects.toThrow("Read brain_read_base or read_file first"); + tools.rememberHash("notes/ithaca.md", "c".repeat(64)); + await run(edit, { path: "notes/ithaca.md", old_string: "sails", new_string: "is" }); + expect(inputs).toEqual([{ path: "notes/ithaca.md", old_string: "sails", new_string: "is", operation: "edit", expectedBaseHash: "c".repeat(64) }]); + const plain = kit(); + const legacy = brainAddTool(plain); + const add = routedApplicationTools(plain, [legacy]).find(tool => tool.name === "brain_add")!; + expect(add.label).toBe(legacy.label); + expect(resultText(await run(add, { content: "Penelope weaves." }))).toBe("created: notes/penelope.md"); + const staged = routedApplicationTool(plain, (await import("@schlessera/brain-ui-sdk/server")).brainApplicationInput.options[2], []); + await expect(run(staged, { files: [] })).rejects.toThrow("No authoritative server application route"); +}); + +test("brainReadBaseTool reads the server base and remembers its whole-document hash", async () => { + await expect(run(brainReadBaseTool(kit()), { path: "notes/ithaca.md" })).rejects.toThrow("No server document-base reader"); + const tools = kit({}, { + applyBrain: async () => ({ ok: true }) as never, + readBrainBase: async () => ({ content: "# Ithaca\n\nOdysseus sails home.\n", expectedBaseHash: "d".repeat(64) }) as never, + }); + const result = await run(brainReadBaseTool(tools), { path: "notes/ithaca.md" }); + expect(JSON.parse(resultText(result))).toMatchObject({ expectedBaseHash: "d".repeat(64) }); + expect(tools.bases.get(tools.turn.bridge!)?.get("notes/ithaca.md")).toBe("d".repeat(64)); +}); diff --git a/packages/ui-backend-pi/tests/tool-roster-snapshot.test.ts b/packages/ui-backend-pi/tests/tool-roster-snapshot.test.ts new file mode 100644 index 0000000000..f1eb086916 --- /dev/null +++ b/packages/ui-backend-pi/tests/tool-roster-snapshot.test.ts @@ -0,0 +1,52 @@ +/** + * Characterization of the curated pi tool roster (#2517): the names, order, + * labels, descriptions and parameter schemas `createBrainTools` returns stay + * byte-identical to the recorded fixture. The tool definitions enter the + * provider-facing system prefix, so any change to them is a cache break and + * must be a reviewed diff of the fixture, never a side effect of moving code. + */ +import { expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { WORKER_DATA_ROOT } from "@schlessera/brain-ui-sdk/internal"; + +import { createBrainAccess } from "../src/brain-access"; +import { createBrainTools, toolLockFromKeyed, type BrainToolDeps } from "../src/tools"; +import { createTurnContext } from "../src/turn-context"; +import { makeEmptyBrain } from "./helpers"; + +const FIXTURE = join(import.meta.dir, "fixtures", "pi-tool-roster.json"); + +const VARIANTS: Record> = { + default: {}, + directWorkerData: { directWrites: true, shellCwd: WORKER_DATA_ROOT, + capabilities: { location: true, activity: true, inbox: true, mask: true, policyChange: true, turnTemp: true, reference: true } }, + scratchShell: { shellCwd: "/worker/scratch", capabilities: { mask: true } }, +}; + +function roster(): string { + const brain = makeEmptyBrain(); + try { + const out: Record = {}; + for (const [name, variant] of Object.entries(VARIANTS)) { + const tools = createBrainTools({ brain: createBrainAccess(brain.root), turn: createTurnContext(), + lock: toolLockFromKeyed(createKeyedLock()), ...variant }); + // One SHA-256 per tool over its full serialized definition keeps the + // fixture small while a diff still names the tool that changed. + out[name] = tools.map(tool => { + const definition = JSON.stringify({ name: tool.name, label: tool.label, description: tool.description, + parameters: tool.parameters, keys: Object.keys(tool) }).replaceAll(brain.root, ""); + return `${tool.name} ${createHash("sha256").update(definition).digest("hex")}`; + }); + } + return JSON.stringify(out, null, 2) + "\n"; + } finally { brain.cleanup(); } +} + +test("createBrainTools returns the recorded roster, byte for byte", () => { + const actual = roster(); + if (process.env.PI_TOOL_ROSTER_RECORD === "1") writeFileSync(FIXTURE, actual); + expect(actual).toBe(readFileSync(FIXTURE, "utf8")); +}); diff --git a/packages/ui-backend-pi/tests/worker-rpc.test.ts b/packages/ui-backend-pi/tests/worker-rpc.test.ts new file mode 100644 index 0000000000..161e2d4457 --- /dev/null +++ b/packages/ui-backend-pi/tests/worker-rpc.test.ts @@ -0,0 +1,193 @@ +/** + * Direct tests of the pi worker's RPC handler table (#2517): every handler + * runs here without a worker, through the same dispatcher a session uses. + * End-to-end refusals from a real worker stay in tests/pi-worker-runtime. + */ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import type { NativeFileVersions } from "@schlessera/brain-ui-sdk/internal"; +import { bashLockKey, compileConfirmPatterns, DEFAULT_CONFIRM_BASH_PATTERNS, type BackendBridge, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; + +import type { SessionCaps } from "../src/backend-options"; +import { DEFAULT_PI_ALLOWED_TOOLS } from "../src/tools"; +import { createTurnContext } from "../src/turn-context"; +import { createPiWorkerRpcDispatcher, PI_WORKER_RPC_HANDLERS, type PiWorkerRpc, type PiWorkerRpcContext } from "../src/worker-rpc"; +import type { CallExecution } from "../src/worker-session"; +import type { PiApplicationReceipt } from "../src/worker-receipts"; +import { makeMockBridge } from "./mock-bridge"; + +let root: string; +beforeEach(() => { root = mkdtempSync(join(tmpdir(), "pi-worker-rpc-")); }); +afterEach(() => { rmSync(root, { recursive: true, force: true }); }); + +let nextId = 0; +function rpc(method: string, toolName: string, input: Record, toolCallId = "call-1"): PiWorkerRpc { + return { type: "rpc", id: ++nextId, method: method as PiWorkerRpc["method"], toolName, toolCallId, input }; +} + +function harness(overrides: Partial = {}, bridge: Partial = {}) { + const turn = createTurnContext(); + const mock = makeMockBridge({}); + turn.bridge = { ...mock.bridge, ...bridge }; + turn.signal = new AbortController().signal; + const executions = new Map(); + const admitted: string[] = []; + const observations: string[] = []; + let persisted = 0; + const applications = new Map(); + const nativeVersions = { + beginRead: async (id: string, key: string) => { observations.push(`beginRead ${id} ${key}`); }, + finishRead: async (id: string) => { observations.push(`finishRead ${id}`); }, + check: () => undefined, + beginWrite: async (key: string) => { observations.push(`beginWrite ${key}`); }, + finishWrite: async (key: string) => { observations.push(`finishWrite ${key}`); }, + } as unknown as NativeFileVersions; + const context: PiWorkerRpcContext = { + brainPath: root, turn, live: () => {}, grants: new Map(), releases: new Map(), workerLock: undefined, + executed: msg => { + let seen = executions.get(msg.toolCallId); + if (!seen) executions.set(msg.toolCallId, seen = { name: msg.toolName, host: false, lock: false, phases: new Set() }); + return seen; + }, + admitTool: name => { admitted.push(name); }, + autonomous: false, sandbox: { profile: "governed" }, workerSandbox: undefined, + observeFile: () => undefined, nativeVersions, relayed: false, agentDir: root, agentFiles: {}, + allowedTools: new Set(DEFAULT_PI_ALLOWED_TOOLS), confirmPatterns: compileConfirmPatterns(DEFAULT_CONFIRM_BASH_PATTERNS, () => {}), + bridgeTools: [], capabilities: {} as SessionCaps, + receipts: { applications, persist: () => { persisted++; } }, + ...overrides, + }; + return { context, dispatch: createPiWorkerRpcDispatcher(context), mock, executions, admitted, observations, applications, persisted: () => persisted }; +} + +test("the handler table has exactly one handler per protocol method", () => { + expect(Object.keys(PI_WORKER_RPC_HANDLERS).sort()) + .toEqual(["apply", "bridge", "fileObservation", "lock", "permission", "readBase", "syncAuth", "unlock"]); +}); + +test("a method without a handler is refused, including inherited object keys", async () => { + const { dispatch } = harness(); + for (const method of ["bogus", "toString", "__proto__", "constructor"]) { + await expect(dispatch(rpc(method, "read_file", {}))).rejects.toThrow("Unknown pi worker RPC method"); + } +}); + +test("every call proves the turn live and refuses a replayed id before its handler runs", async () => { + const refused = harness({ live: () => { throw new Error("Pi worker RPC refused: turn is inactive, cancelled or revoked."); } }); + await expect(refused.dispatch(rpc("bogus", "read_file", {}))).rejects.toThrow("turn is inactive"); + const { dispatch, context } = harness(); + let released = 0; + context.releases.set("lock-a", () => { released++; }); + const first = rpc("unlock", "bash", { lockId: "lock-a" }); + expect(await dispatch(first)).toEqual({ ok: true }); + await expect(dispatch({ ...first })).rejects.toThrow("Replayed pi worker RPC"); + expect(released).toBe(1); +}); + +test("unlock releases exactly a held lock and refuses any other", async () => { + const { dispatch, context } = harness(); + let released = 0; + context.releases.set("lock-a", () => { released++; }); + await expect(dispatch(rpc("unlock", "bash", { lockId: "lock-b" }))).rejects.toThrow("Unknown pi worker lock"); + await expect(dispatch(rpc("unlock", "bash", { lockId: "lock-a", extra: true }))).rejects.toThrow("Unknown pi worker lock"); + expect(await dispatch(rpc("unlock", "bash", { lockId: "lock-a" }))).toEqual({ ok: true }); + expect(released).toBe(1); + expect(context.releases.size).toBe(0); +}); + +test("lock takes only the key the granted operation names", async () => { + const acquired: string[] = []; + const workerLock = { acquire: async (key: string) => { acquired.push(key); return () => {}; } } as unknown as KeyedLock; + const { dispatch, context, executions } = harness({ workerLock }); + const command = "git commit -m odysseus"; + await expect(dispatch(rpc("lock", "bash", { key: bashLockKey(command) }))).rejects.toThrow("no server permission grant"); + context.grants.set("call-1", { name: "bash", input: JSON.stringify({ command }) }); + await expect(dispatch(rpc("lock", "bash", { key: "brain-docs-other" }))).rejects.toThrow("does not match the authorized operation"); + const answer = await dispatch(rpc("lock", "bash", { key: bashLockKey(command) })) as { lockId: string }; + expect(acquired).toEqual([bashLockKey(command)!]); + expect(context.releases.has(answer.lockId)).toBe(true); + expect(executions.get("call-1")?.lock).toBe(true); +}); + +test("fileObservation records a granted governed read phase and refuses outside its grant", async () => { + const { dispatch, context, observations, executions } = harness({ observeFile: path => ({ key: `key:${path}`, version: {} as never }) }); + await expect(dispatch(rpc("fileObservation", "read_file", { phase: "read_start", path: "notes/ithaca.md" }))).rejects.toThrow("no matching granted operation"); + context.grants.set("call-1", { name: "read_file", input: JSON.stringify({ path: "notes/ithaca.md" }) }); + await expect(dispatch(rpc("fileObservation", "read_file", { phase: "write_check", path: "notes/ithaca.md" }))).rejects.toThrow("no matching granted operation"); + expect(await dispatch(rpc("fileObservation", "read_file", { phase: "read_start", path: "notes/ithaca.md" }))).toEqual({ ok: true }); + expect(observations).toEqual(["beginRead call-1 key:notes/ithaca.md"]); + expect([...executions.get("call-1")!.phases]).toEqual(["read_start"]); + const ungoverned = harness({ sandbox: { profile: "strict" } as PiWorkerRpcContext["sandbox"] }); + ungoverned.context.grants.set("call-1", { name: "read_file", input: JSON.stringify({ path: "notes/ithaca.md" }) }); + await expect(ungoverned.dispatch(rpc("fileObservation", "read_file", { phase: "read_start", path: "notes/ithaca.md" }))).rejects.toThrow("no matching granted operation"); +}); + +test("syncAuth writes a native worker's login back and refuses a relayed worker", async () => { + const relayed = harness({ relayed: true }); + await expect(relayed.dispatch(rpc("syncAuth", "", { content: "{}" }))).rejects.toThrow("cannot write the host's credential state"); + const { dispatch, context } = harness(); + await expect(dispatch(rpc("syncAuth", "", { content: 7 }))).rejects.toThrow("Malformed native pi state request"); + expect(await dispatch(rpc("syncAuth", "", { content: "{\"penelope\":true}" }))).toEqual({ ok: true }); + expect(readFileSync(join(root, "auth.json"), "utf8")).toBe("{\"penelope\":true}"); + expect(context.agentFiles["auth.json"]).toBe("{\"penelope\":true}"); +}); + +test("permission allows an application tool with a server route without consulting the gate", async () => { + const { dispatch, context, mock, admitted } = harness({}, { applyBrain: async () => ({ ok: true }) as never }); + expect(await dispatch(rpc("permission", "brain_add", { content: "Ithaca" }))).toEqual({ behavior: "allow" }); + expect(mock.permissionCalls).toHaveLength(0); + expect(context.grants.size).toBe(0); + expect(admitted).toEqual(["brain_add"]); +}); + +test("permission denies an application tool without a server route, and gates every other tool", async () => { + const unrouted = harness(); + expect(await unrouted.dispatch(rpc("permission", "brain_add", { content: "Ithaca" }))) + .toEqual({ behavior: "deny", message: "No server application route is available in this turn." }); + const { dispatch, context } = harness(); + const decision = await dispatch(rpc("permission", "read_file", { path: "notes/ithaca.md" })) as { behavior: string }; + expect(decision.behavior).toBe("allow"); + expect(context.grants.get("call-1")).toEqual({ name: "read_file", input: JSON.stringify({ path: "notes/ithaca.md" }) }); + // A governed host sandbox keeps native write_file: it is gated, not routed. + const governed = harness({ workerSandbox: { profile: "governed" } as PiWorkerRpcContext["workerSandbox"] }, { applyBrain: async () => ({ ok: true }) as never }); + await governed.dispatch(rpc("permission", "write_file", { path: "notes/ithaca.md", content: "home" })); + expect(governed.context.grants.get("call-1")?.name).toBe("write_file"); +}); + +test("bridge runs a granted roster tool on the host once", async () => { + const probe = { name: "probe", execute: async () => ({ content: [{ type: "text" as const, text: "Telemachus" }], details: null }) }; + const { dispatch, context, executions } = harness({ bridgeTools: [probe] as unknown as PiWorkerRpcContext["bridgeTools"] }); + await expect(dispatch(rpc("bridge", "probe", {}))).rejects.toThrow("no matching server permission decision"); + context.grants.set("call-1", { name: "probe", input: "{}" }); + expect(await dispatch(rpc("bridge", "probe", {}))).toEqual({ content: [{ type: "text", text: "Telemachus" }], details: null }); + expect(executions.get("call-1")?.host).toBe(true); + expect(context.grants.size).toBe(0); + context.grants.set("call-2", { name: "absent", input: "{}" }); + await expect(dispatch(rpc("bridge", "absent", {}, "call-2"))).rejects.toThrow("outside the turn's capability roster"); +}); + +test("readBase reads the granted path's server base and refuses any other", async () => { + const base = { content: "Ithaca.\n", expectedBaseHash: "a".repeat(64) }; + const { dispatch, context, executions } = harness({}, { readBrainBase: async () => base as never }); + await expect(dispatch(rpc("readBase", "brain_read", { path: "notes/ithaca.md" }))).rejects.toThrow("Malformed pi document-base request"); + context.grants.set("call-1", { name: "brain_read_base", input: JSON.stringify({ path: "notes/troy.md" }) }); + await expect(dispatch(rpc("readBase", "brain_read_base", { path: "notes/ithaca.md" }))).rejects.toThrow("no matching server permission decision"); + context.grants.set("call-2", { name: "brain_read_base", input: JSON.stringify({ path: "notes/ithaca.md", offset: 1 }) }); + expect(await dispatch(rpc("readBase", "brain_read_base", { path: "notes/ithaca.md" }, "call-2"))).toEqual(base); + expect(executions.get("call-2")?.host).toBe(true); +}); + +test("apply sends one application to the server route and keeps its receipt", async () => { + const inputs: unknown[] = []; + const { dispatch, context, applications, persisted } = harness({}, { applyBrain: async input => { inputs.push(input); return { ok: true, path: "notes/ithaca.md" } as never; } }); + context.turn.pendingMutations = new Set(); + expect(await dispatch(rpc("apply", "brain_add", { operation: "add", content: "Ithaca" }))).toEqual({ ok: true, path: "notes/ithaca.md" }); + expect(inputs).toEqual([{ operation: "add", content: "Ithaca" }]); + expect(applications.get("call-1")).toEqual({ name: "brain_add", input: { operation: "add", content: "Ithaca" }, result: { ok: true, path: "notes/ithaca.md" } as never }); + expect(persisted()).toBe(1); + expect(context.turn.pendingMutations.size).toBe(0); + const unrouted = harness(); + await expect(unrouted.dispatch(rpc("apply", "brain_add", { operation: "add", content: "Ithaca" }))).rejects.toThrow("No authoritative server application route"); +}); diff --git a/packages/ui-backend-pi/tests/worker-session-units.test.ts b/packages/ui-backend-pi/tests/worker-session-units.test.ts new file mode 100644 index 0000000000..3708362b0e --- /dev/null +++ b/packages/ui-backend-pi/tests/worker-session-units.test.ts @@ -0,0 +1,112 @@ +/** + * Direct tests of the units openPiWorkerSession is assembled from (#2517): + * receipt persistence and replay, the protocol reader and the worker's + * lifecycle supervision, each without a worker process. + */ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { PassThrough } from "node:stream"; +import type { LaunchedWorker, NativeFileVersions, Reservation, WorkerStateHandle } from "@schlessera/brain-ui-sdk/internal"; + +import type { SessionEnv } from "../src/backend-options"; +import { readPiSession } from "../src/session-storage"; +import { createTurnContext } from "../src/turn-context"; +import { superviseWorker } from "../src/worker-launch"; +import { sendPipe } from "../src/worker-protocol"; +import { readPiWorkerProtocol, type PiWorkerTurnState } from "../src/worker-reader"; +import { createPiWorkerReceipts } from "../src/worker-receipts"; + +const SESSION = "22222222-2222-4222-8222-222222222222"; +let root: string, brain: string, sessionDir: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "pi-worker-units-")); + brain = join(root, "brain"); sessionDir = join(root, "sessions"); + mkdirSync(brain); mkdirSync(sessionDir); +}); +afterEach(() => { rmSync(root, { recursive: true, force: true }); }); + +const header = () => ({ type: "session", id: SESSION, cwd: brain }); +const toolCall = (id: string) => ({ type: "message", id: "a1", parentId: null, message: { role: "assistant", content: [{ type: "text", text: "Sailing." }, { type: "toolCall", id }] } }); + +function receipts(autonomous = false) { + return createPiWorkerReceipts({ sessionDir, brainPath: brain, sessionId: SESSION, autonomous, entries: undefined, resumedIds: new Set(), + turn: createTurnContext(), backend: {} }); +} + +test("persist recovers a committed call the runtime left unanswered with its own result", () => { + const store = receipts(); + store.applications.set("call-1", { name: "brain_add", input: { content: "Ithaca" }, result: { ok: true } as never }); + store.latestEntries = [header(), toolCall("call-1")]; + store.persist(); + expect(store.applications.get("call-1")?.anchor).toBe("a1"); + expect(readPiSession(join(sessionDir, `${SESSION}.jsonl`))).toHaveLength(2); + store.persist(true); + const saved = readPiSession(join(sessionDir, `${SESSION}.jsonl`)) as Array>; + expect(saved).toHaveLength(3); + expect(saved[2]!.message).toMatchObject({ role: "toolResult", toolCallId: "call-1", toolName: "brain_add", isError: false }); + expect(store.answerText()).toBe("Sailing."); +}); + +test("an autonomous session persists nothing", () => { + const store = receipts(true); + store.applications.set("call-1", { name: "brain_add", input: {}, result: { ok: true } as never }); + store.latestEntries = [header(), toolCall("call-1")]; + store.persist(true); + expect(existsSync(join(sessionDir, `${SESSION}.jsonl`))).toBe(false); +}); + +function fakeChild() { + const stdout = new PassThrough(), stderr = new PassThrough(), stdin = new PassThrough(); + const exited = Promise.withResolvers(); + const child = { stdout, stderr, stdin, exited: exited.promise, kill: () => {}, released: async () => {}, + limitReport: () => ({ hits: [], fatal: false }) } as unknown as LaunchedWorker; + return { child, stdout, stderr, stdin, exit: (code: number) => { stdout.end(); stderr.end(); exited.resolve(code); } }; +} + +test("the reader binds the worker's ready frame and refuses a protocol that closes before completion", async () => { + const { child, stdout } = fakeChild(); + const state: PiWorkerTurnState = { active: false, initialized: false, ended: false, error: undefined, cost: 0, + thinkingLevel: undefined, levels: [], model: undefined, ownedPrompt: undefined }; + const ready = Promise.withResolvers(); + const reading = readPiWorkerProtocol({ child, state, ready, done: Promise.withResolvers(), sessionId: SESSION, backend: { brainPath: brain }, + startupStarted: 0, promptContext: undefined, sessionBudgetLimits: undefined, autonomous: false, resumed: false, turnContext: createTurnContext(), + nativeVersions: {} as NativeFileVersions, receipts: receipts(), resumedIds: new Set(), listeners: new Set(), + proof: { started: () => {}, ended: () => undefined }, toolExecution: undefined, dispatch: async () => undefined, send: () => {}, + fail: () => {}, reportLimitHits: () => {}, limitEnded: async () => undefined, diagnostic: () => "" }); + sendPipe(stdout, { type: "ready", sessionId: SESSION, levels: ["low", "high"], cost: 0.25 }); + stdout.end(); + await ready.promise; + expect(state).toMatchObject({ initialized: true, cost: 0.25, levels: ["low", "high"] }); + await expect(reading).rejects.toThrow("Pi worker exited before completion: protocol closed"); +}); + +test("supervision frees an unprompted worker's turn temp once on exit, and releases its locks", async () => { + const { child, stderr, exit } = fakeChild(); + let closed = 0, released = 0, unlocked = 0; + const turnTemp = { root: join(root, "tmp"), closeAsync: async () => { closed++; } } as unknown as WorkerStateHandle; + const reservation = { turnTempBytes: 1024, release: () => { released++; } } as unknown as Reservation; + const supervision = superviseWorker({ child, reservation, turnTemp, env: { caps: {} } as SessionEnv, turnContext: createTurnContext(), + admission: { envelope: undefined, hostInference: undefined }, answerText: () => "" }); + supervision.releases.set("lock-a", () => { unlocked++; }); + stderr.write("Scylla on the left"); + exit(0); + await child.exited; await Bun.sleep(0); + expect(supervision.diagnostic()).toBe("Scylla on the left"); + expect({ closed, released, unlocked }).toEqual({ closed: 1, released: 1, unlocked: 1 }); + await supervision.closeTurnTemp(); + expect({ closed, released }).toEqual({ closed: 1, released: 1 }); +}); + +test("a prompted worker leaves its turn temp to promotion", async () => { + const { child, exit } = fakeChild(); + let closed = 0; + const turnTemp = { root: join(root, "tmp"), closeAsync: async () => { closed++; } } as unknown as WorkerStateHandle; + const supervision = superviseWorker({ child, reservation: { turnTempBytes: 1, release: () => {} } as unknown as Reservation, turnTemp, + env: { caps: {} } as SessionEnv, turnContext: createTurnContext(), admission: { envelope: undefined, hostInference: undefined }, answerText: () => "" }); + supervision.markPrompted(); + exit(0); + await child.exited; await Bun.sleep(0); + expect(closed).toBe(0); +});