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/2874-pi-loaded-extensions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-backend-pi": patch
---

A pi worker with extension discovery on now proves its curated reads, writes and host bridge calls when its own loader loaded no extension. The worker reports that count before its prompt; any loaded extension or load error, or no report, keeps every result observed as before.
39 changes: 35 additions & 4 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -1568,12 +1568,43 @@ 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:29-37`). It reports nothing at
`packages/ui-backend-pi/src/worker-session.ts:30-38`). 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: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
(`const extensionFree`, `packages/ui-backend-pi/src/worker-session.ts:143`).
With extensions loaded every result is observed as before.

Whether a worker loaded any is read from the worker's own loader, not only
from its configuration (#2874). The curated default
(`export function discoversPiExtensions`,
`packages/ui-backend-pi/src/extension-inspection.ts:64-66`) loads none. A
worker with discovery on counts every extension, extension load error and
extension runner path its session holds (`export function loadedPiExtensions`,
`packages/ui-backend-pi/src/native-session-runtime.ts:136-139`) and sends
that count in its `ready` frame, before the prompt and before any
model-directed code runs. The host accepts a count of zero as extension-free
and any other count as unproven, whatever the configuration said; a worker
that sends no count keeps the configuration's answer
(`function createExecutionProof`,
`packages/ui-backend-pi/src/worker-session.ts:253-259`). An installed or
repo-local extension is counted, and the managed worker then refuses the turn
anyway (`function unqualifiedResources`,
`packages/ui-backend-pi/src/native-session-runtime.ts:143-145`).

The count cannot change during the turn. In pi 0.99.2 the loaded set changes
only in `AgentSession.reload()`, which reloads the settings and the resource
loader and builds a new extension runner. Its only callers are pi's
interactive `/reload` and an extension command's `ctx.reload()`, which pi's
modes bind through `bindExtensions`. A managed worker runs no pi mode and
binds nothing, and a `/` prompt reaches only commands that loaded extensions
registered. With none loaded nothing can reach `reload()`. A turn that writes `.pi/extensions/`, a
settings file or a package changes only what a later worker loads. A worker
whose set can change, which is any worker with an extension loaded, proves
nothing. The guard before each model request rechecks the set as a backstop
(`export function installPiToolSafety`,
`packages/ui-backend-pi/src/tool-safety.ts:27-42`).

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`,
an index tool that loads `brain.config.ts`, an application tool), or starts a
call under a running call's identity, it reports nothing more until it exits.
Expand Down
32 changes: 20 additions & 12 deletions packages/ui-backend-pi/src/native-session-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,12 @@ import { resolveModelSpec, toModel } from "./profiles.js";
import type { TurnContext } from "./turn-context.js";
import type { createSessionResources } from "./session-resources.js";

/** An opened session, and what its loader loaded (`loadedPiExtensions`, #2874). */
export interface OpenedNativeSession { session: PiSessionLike; turnContext: TurnContext; loadedExtensions: number }

export interface SessionRuntime {
newSession(
profileId: string | undefined,
env: SessionEnv
): Promise<{ session: PiSessionLike; turnContext: TurnContext }>;
openSession(
sessionId: string,
env: SessionEnv
): Promise<{ session: PiSessionLike; turnContext: TurnContext }>;
newSession(profileId: string | undefined, env: SessionEnv): Promise<OpenedNativeSession>;
openSession(sessionId: string, env: SessionEnv): Promise<OpenedNativeSession>;
}

export function createSessionRuntime(options: {
Expand Down Expand Up @@ -86,7 +83,7 @@ export function createSessionRuntime(options: {
...(spec?.thinkingLevel ? { thinkingLevel: spec.thinkingLevel } : {}),
});
installPiToolSafety(session.agent,options.toolSafety,()=>unqualifiedResources(loaded.loader,session));
return { session, turnContext: toolkit.turnContext };
return { session, turnContext: toolkit.turnContext, loadedExtensions: loadedPiExtensions(loaded.loader, session) };
},

async openSession(sessionId, env) {
Expand Down Expand Up @@ -124,14 +121,25 @@ export function createSessionRuntime(options: {
);
}
installPiToolSafety(session.agent,options.toolSafety,()=>unqualifiedResources(loaded.loader,session));
return { session, turnContext: toolkit.turnContext };
return { session, turnContext: toolkit.turnContext, loadedExtensions: loadedPiExtensions(loaded.loader, session) };
},
};
}

/**
* What a session's loader loaded: every extension, every extension load error
* and every path its extension runner holds (#2874). The worker reports this
* count before its prompt. Pi changes the set only in `AgentSession.reload()`,
* which a managed worker reaches only through a loaded extension's
* `ctx.reload()`, so zero stays zero for the worker's lifetime.
*/
export function loadedPiExtensions(loader: ResourceLoader, session?: AgentSession): number {
const result = loader.getExtensions();
return result.extensions.length + result.errors.length + (session?.extensionRunner.getExtensionPaths().length ?? 0);
}

/** No extension identity/name/path is exempt: all extension code can add input
* outside the collector. Failed extension loading is unknown coverage too. */
function unqualifiedResources(loader: ResourceLoader,session?:AgentSession):boolean {
const result=loader.getExtensions();
return result.extensions.length>0||result.errors.length>0||(session?.extensionRunner.getExtensionPaths().length??0)>0;
return loadedPiExtensions(loader, session) > 0;
}
4 changes: 3 additions & 1 deletion packages/ui-backend-pi/src/worker-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,9 @@ async function initialize(init: Init): Promise<void> {
});
send({ type: "ready", sessionId: session.sessionId, append: renderedAppend, ...(session.model ? { model: session.model } : {}),
...(session.thinkingLevel ? { thinkingLevel: session.thinkingLevel } : {}),
levels: session.getAvailableThinkingLevels?.() ?? [], cost: session.getSessionStats().cost });
levels: session.getAvailableThinkingLevels?.() ?? [], cost: session.getSessionStats().cost,
// Before any model-directed code runs: the host's evidence for an extension-free worker (#2874).
loadedExtensions: opened.loadedExtensions });
}

async function syncAuth(): Promise<void> {
Expand Down
4 changes: 3 additions & 1 deletion packages/ui-backend-pi/src/worker-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,10 @@ export const piWorkerMessage = z.discriminatedUnion("type", [
gitStatusIncluded: z.boolean().nullable(), coverage: z.literal("assembled_inputs"),
}).strict() }).strict(),
z.object({ type: z.literal("startup_timing"), phase: z.enum(["worker_started", "resources", "session", "initialize"]), durationMs: usageNumber }).strict(),
// `loadedExtensions`: what the worker's own loader loaded, extensions and
// load errors, counted before the prompt (#2874). Absent is no evidence.
z.object({ type: z.literal("ready"), sessionId: z.string().uuid(), append: z.string().optional(), model: input.optional(),
thinkingLevel: text.optional(), levels: z.array(text), cost: usageNumber }).strict(),
thinkingLevel: text.optional(), levels: z.array(text), cost: usageNumber, loadedExtensions: z.number().int().nonnegative().optional() }).strict(),
z.object({ type: z.literal("event"), event: piWorkerEvent }).strict(),
z.object({ type: z.literal("rpc"), id, method: z.enum(["permission", "admission", "bridge", "apply", "readBase", "syncAuth", "lock", "unlock", "fileObservation", "safetyResult", "safetyUnavailable"]),
toolCallId: text, toolName: text, input }).strict(),
Expand Down
3 changes: 2 additions & 1 deletion packages/ui-backend-pi/src/worker-reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export interface PiWorkerReader {
resumedIds: ReadonlySet<unknown>;
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<typeof provenToolExecution> };
proof: { loaded(count: number | undefined): void; started(toolCallId: string): void; ended(toolName: string, toolCallId: string): ReturnType<typeof provenToolExecution> };
toolExecution: SessionEnv["toolExecution"];
dispatch(msg: PiWorkerRpc): Promise<unknown>;
send(value: unknown): void;
Expand All @@ -78,6 +78,7 @@ export async function readPiWorkerProtocol(reader: PiWorkerReader): Promise<void
if (promptContext && msg.append !== undefined) promptContext.retainAppend(msg.append, sessionBudgetLimits ? { limits: sessionBudgetLimits } : {});
state.model = msg.model as Model<any> | undefined;
state.cost = msg.cost; state.thinkingLevel = msg.thinkingLevel as ThinkingLevel; state.levels = msg.levels as ThinkingLevel[];
proof.loaded(msg.loadedExtensions);
ready.resolve();
} else if (msg.type === "prompt_prefix") {
if (!state.active) throw new Error("Pi worker emitted a prefix outside the turn");
Expand Down
28 changes: 20 additions & 8 deletions packages/ui-backend-pi/src/worker-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,13 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi
child.kill("SIGKILL");
}
// 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
// other code (bash, grep, brain-owned configuration through an index tool,
// an application tool) or starts a call under a running call's identity:
// from then on the worker's own reports are no evidence.
// only a worker that loads none can prove a call's execution path. A
// configuration without discovery loads none; with discovery on, the
// worker's own loader reports what it loaded before the prompt (#2874).
// Proof also ends, for the worker's lifetime, once it admits a call that
// can run other code (bash, grep, brain-owned configuration through an
// index tool, 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 || !discoversPiExtensions(backend);
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,
Expand Down Expand Up @@ -239,28 +241,38 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi
* 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.
*
* `extensionFree` is what the configuration proves. A discovering worker
* becomes extension-free only when its own loader reports none loaded in its
* `ready` frame (#2874), which the reader accepts once, before the prompt.
* Any loaded extension or load error ends proof, whatever the configuration
* said; no report leaves the configuration's answer. The set cannot change
* after that report: only `AgentSession.reload()` reloads it, and a managed
* worker reaches that only through a loaded extension's `ctx.reload()`.
*/
function createExecutionProof(extensionFree: boolean, provableTools: ReadonlySet<string>) {
let provable = extensionFree;
let loadedNone = extensionFree, provable = true;
const running = new Set<string>();
const executions = new Map<string, CallExecution>();
const proves = () => loadedNone && provable;
return {
loaded: (count: number | undefined): void => { if (count !== undefined) loadedNone = count === 0; },
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;
},
canFinalize: (toolName:string,toolCallId:string):boolean => provable&&running.has(toolCallId)&&provenToolExecution(toolName,executions.get(toolCallId))!==undefined,
canFinalize: (toolName:string,toolCallId:string):boolean => proves()&&running.has(toolCallId)&&provenToolExecution(toolName,executions.get(toolCallId))!==undefined,
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<typeof provenToolExecution> => {
const started = running.delete(toolCallId);
const proven = provable && started ? provenToolExecution(toolName, executions.get(toolCallId)) : undefined;
const proven = proves() && started ? provenToolExecution(toolName, executions.get(toolCallId)) : undefined;
executions.delete(toolCallId);
return proven;
},
Expand Down
50 changes: 50 additions & 0 deletions packages/ui-backend-pi/tests/extension-inspection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { createBrainAccess } from "../src/brain-access";
import { discoversPiExtensions, gateUnsupportedConfiguration, inspectPiExtensions, type PiExtensionInspection } from "../src/extension-inspection";
import { backendModule } from "../src/module";
import { createSessionResources } from "../src/session-resources";
import { createSessionRuntime, loadedPiExtensions } from "../src/native-session-runtime";
import { PiInputSafetyUnavailableError } from "../src/worker-protocol";
import { toolLockFromKeyed } from "../src/tools";

/**
Expand Down Expand Up @@ -177,3 +179,51 @@ test("in the curated default only a missing package or an inspection failure blo
await expect(unknown.startTurn(turn().req), "PI_CURATED_UNKNOWN_REFUSES").rejects.toBeInstanceOf(BackendRequestError);
expect(started.length, "PI_CURATED_UNKNOWN_NEVER_RUNS").toBe(1);
});

/**
* #2874: a discovering worker reports what its own loader loaded. An
* installed (user) or repo-local extension is counted, so the host proves
* nothing for it; only an empty directory set reports zero.
*/
test("a discovering worker's loader counts each installed or repo-local extension it loaded", async () => {
const caps = { askUser: false, askUserList: false, askUserRank: false, location: false, activity: false, mask: false };
const count = async (loadExtensions: boolean) => {
const resources = createSessionResources({
backend: { brainPath: brain }, brain: createBrainAccess(brain), lock: toolLockFromKeyed(createKeyedLock()),
allowedTools: new Set(), confirmPatterns: [], loadExtensions, managedToolSafety: true,
});
return loadedPiExtensions((await resources.build(resources.buildToolkit(caps), { caps })).loader);
};
expect(await count(false), "PI_CURATED_REPORTS_NONE").toBe(0);
rmSync(join(agent, "extensions/aeolus.ts"));
expect(await count(true), "PI_REPO_LOCAL_EXTENSION_COUNTED").toBe(1);
rmSync(join(brain, ".pi/extensions/loom.ts"));
writeFileSync(join(agent, "extensions/aeolus.ts"), "export default function () {}\n");
expect(await count(true), "PI_INSTALLED_EXTENSION_COUNTED").toBe(1);
rmSync(join(agent, "extensions/aeolus.ts"));
expect(await count(true), "PI_DISCOVERY_WITH_NONE_REPORTS_NONE").toBe(0);
});

test("a discovering worker's session reports zero only when it loaded no extension, and refuses one", async () => {
const caps = { askUser: false, askUserList: false, askUserRank: false, location: false, activity: false, mask: false };
const open = () => {
const backend = { brainPath: brain, loadExtensions: true };
const resources = createSessionResources({ backend, brain: createBrainAccess(brain), lock: toolLockFromKeyed(createKeyedLock()),
allowedTools: new Set(), confirmPatterns: [], loadExtensions: true, managedToolSafety: true });
const stopped: string[] = [];
const runtime = createSessionRuntime({ backend, sessionDir: join(root, "sessions"), resources,
toolSafety: { permission: async () => { throw new Error("Construction-only fixture cannot execute tools"); },
result: async () => { throw new Error("Construction-only fixture cannot deliver results"); }, stop() { stopped.push("stop"); } },
sessionId: "11111111-1111-4111-8111-111111111111", observeManager: () => {},
modelRuntimeOptions: { authPath: join(root, "auth.json"), modelsPath: join(root, "models.json"), modelsStorePath: join(root, "models-cache.json") } });
return { opened: runtime.newSession(undefined, { caps }), stopped };
};
rmSync(join(agent, "extensions/aeolus.ts"));
const loaded = open();
expect(await loaded.opened.catch(error => error), "PI_LOADED_EXTENSION_REFUSED").toBeInstanceOf(PiInputSafetyUnavailableError);
expect(loaded.stopped, "PI_LOADED_EXTENSION_STOPPED").toEqual(["stop"]);
rmSync(join(brain, ".pi/extensions/loom.ts"));
const { session, loadedExtensions } = await open().opened;
try { expect(loadedExtensions, "PI_EXTENSION_FREE_SESSION_REPORTS_NONE").toBe(0); }
finally { session.dispose(); }
});
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,12 @@ async function run(prompt: string) {
}
for await (const message of pipeMessages(process.stdin)) {
const value = message as any;
if (value.type === "init") { init = value; send({ type: "ready", sessionId: value.sessionId, levels: [], cost: 0 }); }
if (value.type === "init") {
init = value;
// What this worker's loader loaded, as the real entry reports it (#2874); unset sends no report.
const loaded = process.env.ODYSSEUS_LOADED_EXTENSIONS;
send({ type: "ready", sessionId: value.sessionId, levels: [], cost: 0, ...(loaded === undefined ? {} : { loadedExtensions: Number(loaded) }) });
}
else if (value.type === "prompt") void run(value.text.split("\n", 1)[0]).catch(error => { send({ type: "error", message: error.message }); });
else if (value.type === "answer") {
const waiter = pending.get(value.id); pending.delete(value.id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ mock.module("../../src/native-session-runtime.js", () => ({
},
async abort() {}, dispose() {}, getSessionStats: () => ({ cost: 0 }),
};
return { newSession: async () => ({ session }) };
// A count no real worker reaches: the ready frame must carry the runtime's own (#2874).
return { newSession: async () => ({ session, loadedExtensions: 3 }) };
},
}));
await import("../../src/worker-entry.js");
Loading
Loading