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
25 changes: 14 additions & 11 deletions experiments/pi-schema-measurement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import {createPiSchemaReplay} from "../scripts/pi-schema-replay.ts";
import { mkdtempSync, cpSync, mkdirSync, readFileSync, writeFileSync, symlinkSync, rmSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { measurementSchema, measurementForm, nativeCredential, replaceExactly, PI_SCHEMA_ARMS, PI_SCHEMA_PROMPT, measurementFixtureGuard, measurementHostedPrompt, measurementPreparedPrompt, adoptMeasurementPreparedPrompt, measurementPromptReceipt } from "../scripts/pi-schema-measurement.ts";
import { measurementSchema, measurementForm, nativeCredential, replaceExactly, PI_SCHEMA_ARMS, PI_SCHEMA_PROMPT, measurementToolSafety, measurementHostedPrompt, measurementPreparedPrompt, adoptMeasurementPreparedPrompt, measurementPromptReceipt } from "../scripts/pi-schema-measurement.ts";
import { SCHEMA_ARMS } from "../scripts/show-block-schema-forms.ts";
import { showBlockInputSchema } from "../packages/ui-sdk/src/tool-contracts/blocks.ts";
import { toolInputJsonSchema, SHOW_BLOCK_DESCRIPTION } from "@schlessera/brain-ui-sdk/server";
import { toolInputJsonSchema, SHOW_BLOCK_DESCRIPTION, type PermissionDecision } from "@schlessera/brain-ui-sdk/server";
import { validatePiSchemaRequest, validateTerminalUsage, observeCodexBilling } from "../scripts/pi-schema-capture.ts";
import { acceptMeasurementFiles } from "../scripts/pi-schema-worker-receipts.ts";

Expand Down Expand Up @@ -97,19 +97,22 @@ test("prepared host receipt preserves the reviewed original and rejects changed
}
});

test("actual inline tool admission refuses shell/writes and outside symlink reads", async () => {
test("actual tool-safety admission refuses shell/writes and outside symlink reads", async () => {
const scratch=mkdtempSync(join(tmpdir(),"pi-schema-guard-"));
try {
writeFileSync(join(scratch,"inside.md"),"Odysseus");
symlinkSync("/etc/hostname",join(scratch,"outside.md"));
let handler:any;const extension=measurementFixtureGuard(scratch);
if (typeof extension === "function") throw new Error("Named inline measurement extension expected.");
extension.factory({on(_name:string,fn:any){handler=fn;}} as any);
expect(await handler({toolName:"show_block",input:{}})).toBeUndefined();
expect(await handler({toolName:"read_file",input:{path:"inside.md"}})).toBeUndefined();
expect((await handler({toolName:"bash",input:{command:"printf unsafe"}})).block).toBe(true);
expect((await handler({toolName:"write_file",input:{path:"inside.md"}})).block).toBe(true);
expect((await handler({toolName:"read_file",input:{path:"outside.md"}})).block).toBe(true);
const results:string[]=[];
const host={async permission(_name:string,_id:string,_input:Record<string,unknown>):Promise<PermissionDecision>{return {behavior:"allow"};},async result(_name:string,id:string){results.push(id);},stop(){results.push("stopped");}};
const safety=measurementToolSafety(host,scratch);
const handler=async(toolName:string,input:Record<string,unknown>)=>safety.permission(toolName,toolName,input);
expect((await handler("show_block",{})).behavior).toBe("allow");
expect((await handler("read_file",{path:"inside.md"})).behavior).toBe("allow");
expect((await handler("bash",{command:"printf unsafe"})).behavior).toBe("deny");
expect((await handler("write_file",{path:"inside.md"})).behavior).toBe("deny");
expect((await handler("read_file",{path:"outside.md"})).behavior).toBe("deny");
expect(results,"each denied call records its reason as the host result").toEqual(["bash","write_file","read_file"]);
safety.stop();expect(results.at(-1)).toBe("stopped");
expect(readFileSync(join(scratch,"inside.md"),"utf8")).toBe("Odysseus");
} finally {rmSync(scratch,{recursive:true,force:true});}
});
Expand Down
45 changes: 29 additions & 16 deletions scripts/pi-schema-measurement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { showBlockInputSchema } from "../packages/ui-sdk/src/tool-contracts/bloc
import type { SchemaArm } from "./show-block-schema-forms.ts";
import { appendFileSync, mkdirSync, realpathSync, symlinkSync, writeFileSync } from "node:fs";
import { resolve, sep } from "node:path";
import type { InlineExtension } from "@earendil-works/pi-coding-agent";
import type { PermissionDecision } from "../packages/ui-sdk/src/server/backend.ts";

// Synchronous counterpart of #336's frozen options: its MCP-listing module
// has top-level await and cannot be loaded through the server descriptor's
Expand Down Expand Up @@ -59,22 +59,35 @@ export function measurementPromptReceipt(): MeasurementPromptReceipt {
export const PI_SCHEMA_REQUEST_LIMIT = 5;
export const PI_SCHEMA_MODEL = "gpt-6.1-sol";

/** Same read-only execution policy in every form; model-visible roster unchanged. */
export function measurementFixtureGuard(brain: string): InlineExtension {
/** Same read-only execution policy in every form; model-visible roster unchanged.
* Wraps the worker's host tool-safety hook rather than loading a Pi extension:
* the managed worker refuses any loaded extension as uncollected input. A
* denied call records its reason as the host result, as Pi's blocked path does. */
export function measurementToolSafety<T extends {
permission(name: string, id: string, input: Record<string, unknown>): Promise<PermissionDecision>;
result(name: string, id: string, content: Array<{ type: "text"; text: string }>): Promise<void>;
}>(safety: T, brain: string): T {
const root = realpathSync(brain), allowed = new Set(["read_file", "grep", "brain_search", "brain_context", "brain_read", "brain_list", "brain_graph", "show_block"]);
return { name: "measurement-fixture-only", factory(pi) {
pi.on("tool_call", async event => {
let reason: string | null = allowed.has(event.toolName) ? null : "Measurement denies writes, shell, delegation and external capabilities.";
const input = event.input as Record<string, unknown>;
if (!reason && typeof input?.path === "string") {
try { const path = realpathSync(resolve(root, input.path)); if (path !== root && !path.startsWith(root + sep)) reason = "Measurement path is outside fixture corpus."; }
catch { reason = "Measurement path cannot be resolved inside fixture corpus."; }
}
const out = process.env.BRAIN_MEASURE_PI_RECEIPTS;
if (out) appendFileSync(resolve(out, "tool-admission.jsonl"), JSON.stringify({toolName:event.toolName, input:event.input, allowed:!reason, reason}) + "\n", {mode:0o600});
return reason ? {block:true,reason} : undefined;
});
}};
const admit = (toolName: string, input: Record<string, unknown>): string | null => {
let reason: string | null = allowed.has(toolName) ? null : "Measurement denies writes, shell, delegation and external capabilities.";
if (!reason && typeof input?.path === "string") {
try { const path = realpathSync(resolve(root, input.path)); if (path !== root && !path.startsWith(root + sep)) reason = "Measurement path is outside fixture corpus."; }
catch { reason = "Measurement path cannot be resolved inside fixture corpus."; }
}
const out = process.env.BRAIN_MEASURE_PI_RECEIPTS;
if (out) appendFileSync(resolve(out, "tool-admission.jsonl"), JSON.stringify({toolName, input, allowed:!reason, reason}) + "\n", {mode:0o600});
return reason;
};
return Object.assign(Object.create(safety) as T, {
async permission(name: string, id: string, input: Record<string, unknown>): Promise<PermissionDecision> {
const decision = await safety.permission(name, id, input);
if (decision.behavior === "deny") return decision;
const reason = admit(name, decision.updatedInput ?? input);
if (!reason) return decision;
await safety.result(name, id, [{ type: "text", text: reason }]);
return { behavior: "deny", message: reason };
},
});
}

/** Fresh fixture plumbing only: immutable source runtime, no dependency sharing. */
Expand Down
15 changes: 13 additions & 2 deletions scripts/pi-schema-offline-preload.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
/** Native control, always fake: no provider transport delegates to real fetch. */
// The host loads this first; the worker inherits the marker and imports it again.
const inWorker = process.env.BRAIN_MEASURE_PI_WORKER_OFFLINE === "1";
process.env.BRAIN_MEASURE_PI_WORKER_OFFLINE = "1";
import { writeFileSync,readFileSync } from "node:fs";
import { resolve } from "node:path";
import { existsSync,writeFileSync,readFileSync } from "node:fs";
import { join,resolve } from "node:path";
import {plugin} from "bun";
import { createHash } from "node:crypto";
// Only this offline preload substitutes app storage; the provider-enabled entry
Expand All @@ -19,12 +21,21 @@ plugin({ name: "offline-pi-native-app-fixture", setup(build) {
if(process.env.BRAIN_MEASURE_PI_OFFLINE_MUTATION==="replay-history")plugin({name:"offline-replay-history-negative",setup(build){build.onLoad({filter:/\/pi-ai\/dist\/api\/openai-codex-responses\.js$/},({path})=>{const source=readFileSync(path,"utf8"),anchor=" const bodyJson = JSON.stringify(body);";if(source.split(anchor).length!==2)throw new Error("Offline real provider payload anchor drift.");return {contents:source.replace(anchor,' if(body.input.some(item=>item.type==="function_call_output"))body.input=body.input.filter(item=>item.type!=="function_call"&&item.type!=="function_call_output");\n'+anchor),loader:"js"};});}});
if(process.env.BRAIN_MEASURE_PI_OFFLINE_MUTATION==="preterminal-cancel")plugin({name:"offline-preterminal-consumer-cancel",setup(build){build.onLoad({filter:/\/pi-ai\/dist\/api\/openai-codex-responses\.js$/},({path})=>{const source=readFileSync(path,"utf8"),anchor=" yield event;\n }\n}\nfunction normalizeCodexStatus";if(source.split(anchor).length!==2)throw new Error("Offline terminal consumer anchor drift.");return {contents:source.replace(anchor,' if(event.type==="response.created")return;\n'+anchor),loader:"js"};});}});
const {decodePiRequest}=await import("./pi-schema-capture.ts");
const {nativeCredential}=await import("./pi-schema-measurement.ts");
const accountId = "fictional-odysseus-account";
const payload = { exp: Math.floor(Date.now() / 1000) + 3600, "https://api.openai.com/auth": { chatgpt_account_id: accountId } };
process.env.BRAIN_MEASURE_CODEX_ACCESS_TOKEN = `offline.${Buffer.from(JSON.stringify(payload)).toString("base64url")}.fictional`;
process.env.BRAIN_MEASURE_CODEX_ACCOUNT_ID = accountId;
process.env.BRAIN_MEASURE_CODEX_MODEL = "gpt-6.1-sol"; // fictional credential, exact ruled model identity only
for (const key of ["OPENAI_API_KEY", "OPENAI_CODEX_API_KEY", "CODEX_API_KEY", "ANTHROPIC_API_KEY", "ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "TYPESAFE_API_KEY"]) delete process.env[key];
// The host inference relay resolves the turn's credential from pi's auth store
// before the worker launches (#4031). Provision the same fictional identity
// into the fresh fixture agent directory, never over an existing store.
if (!inWorker) {
const agentDir = process.env.PI_CODING_AGENT_DIR;
if (!agentDir || existsSync(join(agentDir, "auth.json"))) throw new Error("Offline host fixture credential needs a fresh PI_CODING_AGENT_DIR.");
writeFileSync(join(agentDir, "auth.json"), JSON.stringify({ "openai-codex": nativeCredential() }), { mode: 0o600, flag: "wx" });
}
const original = globalThis.fetch.bind(globalThis);
let sequence = process.env.BRAIN_MEASURE_PI_REPLAY_ROOT ? 1 : 0;
globalThis.fetch = (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
Expand Down
22 changes: 13 additions & 9 deletions scripts/pi-schema-preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,27 @@ const workerPreload = new URL("./pi-schema-worker-preload.ts", import.meta.url).
plugin({
name: "measure-pi-schema-and-native-auth",
setup(build) {
build.onLoad({ filter: /\/(ui-backend-pi\/src\/(bridge-tools|worker-session)|ui-server\/src\/ws\/run-session)\.ts$/ }, ({ path }) => {
build.onLoad({ filter: /\/(ui-backend-pi\/src\/(bridge-tools|worker-session|worker-launch|worker-reader)|ui-server\/src\/ws\/session-run\/backend-entry)\.ts$/ }, ({ path }) => {
let source = readFileSync(path, "utf8");
if (path.endsWith("run-session.ts")) {
if (path.endsWith("backend-entry.ts")) {
source = `import { measurementHostedPrompt } from ${helper};\n` + source;
source = replaceExactly(source, '\n prompt,\n',
'\n prompt: measurementHostedPrompt(prompt, host.budgets && governedHold ? host.budgets.receipt(turn.turnId) : undefined),\n');
source = replaceExactly(source, '\n prompt,\n',
'\n prompt: measurementHostedPrompt(prompt, host.budgets && governedHold ? host.budgets.receipt(turn.turnId) : undefined),\n');
} else if (path.endsWith("bridge-tools.ts")) {
source = `import { measurementSchema } from ${helper};\nconst __measurementSchema = measurementSchema(process.env.BRAIN_MEASURE_PI_SCHEMA_FORM);\n` + source;
source = replaceExactly(source, "parameters: toPiParameters(SHOW_BLOCK_INPUT_SCHEMA)", "parameters: toPiParameters(__measurementSchema)");
source = replaceExactly(source, "handleShowBlock(SHOW_BLOCK_INPUT_SCHEMA.parse(input))", "handleShowBlock(__measurementSchema.parse(input))");
} else {
source = `import { acceptMeasurementFiles, measurementWorkerEnv } from ${receipts};\nimport { measurementPreparedPrompt } from ${helper};\n` + source;
source = replaceExactly(source, 'send({ type: "prompt", text: ownedPrompt?.text ?? text, options })',
'send({ type: "prompt", text: ownedPrompt?.text ?? text, options, __measurementPrompt: measurementPreparedPrompt(text, preparedPrompt) })');
} else if (path.endsWith("worker-session.ts")) {
source = `import { measurementPreparedPrompt } from ${helper};\n` + source;
source = replaceExactly(source, 'send({ type: "prompt", text: state.ownedPrompt?.text ?? text, options })',
'send({ type: "prompt", text: state.ownedPrompt?.text ?? text, options, __measurementPrompt: measurementPreparedPrompt(text, preparedPrompt) })');
} else if (path.endsWith("worker-launch.ts")) {
source = `import { measurementWorkerEnv } from ${receipts};\n` + source;
source = replaceExactly(source, 'command: [process.execPath,', `command: [process.execPath, "--preload", ${JSON.stringify(workerPreload)},`);
source = replaceExactly(source, 'env: workerEnv, credentialEnv, sandbox,', 'env: { ...workerEnv, ...measurementWorkerEnv() }, credentialEnv, sandbox,');
source = replaceExactly(source, 'if (msg.event.type === "tool_execution_end") {', 'if (acceptMeasurementFiles(msg.event)) continue;\n if (msg.event.type === "tool_execution_end") {');
} else if (path.endsWith("worker-reader.ts")) {
source = `import { acceptMeasurementFiles } from ${receipts};\n` + source;
source = replaceExactly(source, 'if (msg.event.type === "tool_execution_end") {', 'if (acceptMeasurementFiles(msg.event)) continue;\n if (msg.event.type === "tool_execution_end") {');
}
return { contents: source, loader: "ts" };
});
Expand Down
8 changes: 6 additions & 2 deletions scripts/pi-schema-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ only through the isolated child's environment and public Pi memory-store API.
No credential file is copied; no login, refresh, models discovery, Claude OAuth,
alternate API key or paid API fallback is admitted. Catalogue presence and auth
selectors establish readiness, not account entitlement or invoice evidence.
The keyless offline fixture alone writes its fictional credential into a fresh
Pi agent directory, because the host inference relay reads the turn's
credential from that store before the worker launches.
Every physical request must use the protected token/account, Pi identity, ruled
model and exact non-strict `show_block` parameters. Only the Codex Responses
endpoint is admitted. Compressed request bytes are forwarded unchanged; the
Expand All @@ -43,8 +46,9 @@ cache/reasoning and total counters; provisional/default SDK values are insuffici
The same empty HOME, Pi settings and freshly copied corpus apply to every arm.
Compaction, retry, cache warming, external extensions, skills, prompt templates
and telemetry are disabled. The model-visible tool roster is retained; a real
inline execution hook admits fixture reads/searches and block calls, refusing
shell, writes, delegation and external capabilities. Path resolution refuses
execution hook on the worker's tool-safety path, not a Pi extension, admits
fixture reads/searches and block calls, refusing shell, writes, delegation and
external capabilities. Path resolution refuses
external symlink targets. Source/runtime are mounted read-only by bwrap; actual
personal home is absent. Public source and system runtime remain admitted for
execution, so this is private-data isolation, not proof of no public-source
Expand Down
5 changes: 2 additions & 3 deletions scripts/pi-schema-worker-preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,20 @@ plugin({ name: "measure-pi-native-worker", setup(build) {
source = replaceExactly(source, "parameters: toPiParameters(SHOW_BLOCK_INPUT_SCHEMA)", "parameters: toPiParameters(__measurementSchema)");
source = replaceExactly(source, "handleShowBlock(SHOW_BLOCK_INPUT_SCHEMA.parse(input))", "handleShowBlock(__measurementSchema.parse(input))");
} else if (path.endsWith("native-session-runtime.ts")) {
source = `import { createMeasurementModelRuntime } from ${helper};\n` + source;
source = `import { createMeasurementModelRuntime, measurementToolSafety } from ${helper};\n` + source;
source = replaceExactly(source, "await ModelRuntime.create(options.modelRuntimeOptions)", "await createMeasurementModelRuntime()", 2);
source = replaceExactly(source, "installPiToolSafety(session.agent,options.toolSafety,", "installPiToolSafety(session.agent,measurementToolSafety(options.toolSafety,brainPath),", 2);
} else if (path.endsWith("worker-entry.ts")) {
source = `import { adoptMeasurementPreparedPrompt } from ${helper};\nimport { waitPiSchemaCaptures } from ${capture};\nimport { flushMeasurementFiles } from ${receipts};\n` + source;
source = replaceExactly(source, 'void session!.prompt(msg.text, msg.options)',
'adoptMeasurementPreparedPrompt(msg.__measurementPrompt);\n void session!.prompt(msg.text, msg.options)');
source = replaceExactly(source, "await syncAuth();", "await waitPiSchemaCaptures(); flushMeasurementFiles(); await syncAuth();", 2);
} else {
source = `import { measurementFixtureGuard } from ${helper};\n` + source;
const start = source.indexOf(" const settingsManager = ");
const end = source.indexOf(" const subagentTool =", start);
if (start < 0 || end < 0) throw new Error("Measurement settings source anchor drift.");
source = source.slice(0, start) + ' const settingsManager = SettingsManager.inMemory({ transport: "sse", compaction: { enabled: false }, retry: { enabled: false, maxRetries: 0, provider: { maxRetries: 0, timeoutMs: 180000 } }, cacheWarming: "off", packages: [], extensions: [], skills: [], prompts: [], enableAnalytics: false, enableInstallTelemetry: false });\n' + source.slice(end);
source = replaceExactly(source, "noExtensions: !loadExtensions,", "noExtensions: true, noSkills: true, noPromptTemplates: true,");
source = replaceExactly(source, "extensionFactories: [", "extensionFactories: [measurementFixtureGuard(brainPath),");
}
return { contents: source, loader: "ts" };
});
Expand Down
Loading