Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/pi-worker-session-tools-split.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 5 additions & 5 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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`,
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/module-mcp-tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<module>_<local>`). It needs its
Expand Down
2 changes: 1 addition & 1 deletion docs/plans/host-owned-web-search.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
76 changes: 76 additions & 0 deletions packages/ui-backend-pi/src/application-tools.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>, 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<NonNullable<BackendBridge["applyBrain"]>>[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;
}
Loading
Loading