Join P3 harness context to landed P2 admission with private same-key delivery

This commit is contained in:
jason.woltje committed 2026-10-26 18:06:28 -05:00
1 parent fbdd8c164c
commit ee1f926ceb
94 files changed
+5386 -62

No files matched your search

+64 -25
View File
@@ -159,6 +159,7 @@ import {
runnerOf,
SESSION_CREDENTIALS,
sessionEnv,
isProviderVariable,
sessionExit,
sessionStore,
sessionWorkspace,
@@ -218,6 +219,9 @@ export function createLauncher({
host,
system,
env = process.env,
// P2 supplies only {baseUrl,key}; a factory may supply the current agent's
// context per check. P3 never reads a key store or calls the proxy itself.
proxy = null,
tracker = false,
launches = true,
makeLoader = createLoader,
@@ -333,7 +337,7 @@ export function createLauncher({
// nothing else launches for one. Row 194 (#1692, V2): `human` is the
// human's launch request, which may name any declared instance. The listing
// limits the chief, not the human. launch.by still takes the `pm` branch.
async function check(instance, { pm = false, thread = null, session = null, human = false } = {}) {
async function check(instance, { pm = false, thread = null, session = null, human = false, proxyContext = null, proxyReady = false } = {}) {
const admissionGeneration = admission().generation;
try { b=loadBusiness(host.business,{dir:configDir(env),rolesDir:rolesDir(env)}); } catch(e){throw new Refusal("organization-refused",e.message);}
if (!b.launch) throw new Refusal("launch-not-configured", `business ${b.id} has no launch block`);
@@ -356,9 +360,10 @@ export function createLauncher({
// Row 65 (#1558): the route's harness, model and thinking come from the instance's vars only.
const routeOf = (which) => {
try {
return sessionModel(resolved, b.launch.models, which);
return sessionModel(resolved, b.launch.models, which, { proxy: Boolean(system.proxy || proxyContext) });
} catch (e) {
throw new Refusal(e instanceof BundleError && e.code === "no-route" ? "no-route" : "unsupported-harness", e.message);
const code = e instanceof BundleError && (e.code === "no-route" || e.code.startsWith("proxy-")) ? e.code : "unsupported-harness";
throw new Refusal(code, e.message);
}
};
const primary = routeOf("primary");
@@ -390,7 +395,23 @@ export function createLauncher({
let harness = await harnessOf(primary);
let route = "primary";
let routeReason = null;
const failed = call(primary.harness, "preflight", () => harness.preflight({ env }));
// The first check validates the request before authorization/workspace work.
// Managed credentials are acquired once in startLocked, then supplied to
// the final check. Never reject proxy-only login using upstream host env.
if (system.proxy && !proxyReady)
return { resolved, model, account: null, harness, route, routeReason, admissionGeneration };
const proxyFor = async (selected) => {
if (!system.proxy && selected.provider !== "proxy") return null;
const context = system.proxy ? proxyContext : typeof proxy === "function" ? await proxy({ business: b.id, instance }) : proxy;
if (!context || typeof context.key !== "string" || !context.key
|| typeof context.baseUrl !== "string" || !/^http:\/\/127\.0\.0\.1:[0-9]+$/.test(context.baseUrl)) {
throw new Refusal("no-session-credential", "proxy model needs its own session proxy context");
}
// Copy only the agreed seam; never keep a store or management handle.
return { baseUrl: context.baseUrl, key: context.key };
};
let sessionProxy = await proxyFor(primary);
const failed = call(primary.harness, "preflight", () => harness.preflight({ env: sessionProxy ? sessionEnv(env, "preflight", sessionProxy) : env, proxy: sessionProxy }));
if (failed) {
if (!fallback) throw new Refusal(failed.code, failed.message);
// The fallback only on a failed primary preflight, and only at launch (row 65). Any refusal of
@@ -399,7 +420,8 @@ export function createLauncher({
if (e instanceof Refusal) e.message += ` (primary ${primary.harness}: ${failed.message})`;
throw e;
});
const also = call(fallback.harness, "preflight", () => second.preflight({ env }));
sessionProxy = await proxyFor(fallback);
const also = call(fallback.harness, "preflight", () => second.preflight({ env: sessionProxy ? sessionEnv(env, "preflight", sessionProxy) : env, proxy: sessionProxy }));
if (also) throw new Refusal(also.code, `fallback ${fallback.harness}: ${also.message} (primary ${primary.harness}: ${failed.message})`);
[model, harness, route, routeReason] = [fallback, second, "fallback", failed.code];
}
@@ -410,12 +432,18 @@ export function createLauncher({
if (account !== null) {
// The usage records keep this name (bus schema 3i), so it must never be a credential's value.
const holds = [...new Set(SESSION_CREDENTIALS.flat())].filter((k) => env[k] === account);
if (sessionProxy?.key === account) holds.push("session proxy key");
if (holds.length) throw new Refusal("account-is-credential", `launch.account.name is the value of ${holds.join(", ")}; it names the account, never its credential`);
const named = b.launch.account.credential.split("+");
if (!SESSION_CREDENTIALS.some((set) => set.join("+") === named.join("+")) || !named.every((k) => Boolean(env[k])))
throw new Refusal("account-credential-missing", `account ${account} names ${named.join(" with ")}, which the bus host doesn't hold as a session login`);
const other = [...new Set(SESSION_CREDENTIALS.flat())].filter((k) => !named.includes(k) && Boolean(env[k]));
if (other.length) throw new Refusal("account-credential-ambiguous", `account ${account} names ${named.join(" with ")}, but the bus host also sets ${other.join(", ")}`);
if (sessionProxy || b.launch.account.credential === "proxy") {
if (!sessionProxy || b.launch.account.credential !== "proxy")
throw new Refusal("account-credential-missing", `account ${account} needs the declared proxy credential`);
} else {
const named = b.launch.account.credential.split("+");
if (!SESSION_CREDENTIALS.some((set) => set.join("+") === named.join("+")) || !named.every((k) => Boolean(env[k])))
throw new Refusal("account-credential-missing", `account ${account} names ${named.join(" with ")}, which the bus host doesn't hold as a session login`);
const other = [...new Set(SESSION_CREDENTIALS.flat())].filter((k) => !named.includes(k) && Boolean(env[k]));
if (other.length) throw new Refusal("account-credential-ambiguous", `account ${account} names ${named.join(" with ")}, but the bus host also sets ${other.join(", ")}`);
}
}
const unavailable = sandboxProblem({ bwrap });
if (unavailable) throw new Refusal("sandbox-unavailable", unavailable);
@@ -434,7 +462,7 @@ export function createLauncher({
throw new Refusal("limit-check-failed", `${may?.check ?? "bus"}: ${may?.code ?? "malformed-answer"}`);
}
admission(admissionGeneration);
return { resolved, model, account, harness, route, routeReason, admissionGeneration };
return { resolved, model, account, harness, route, routeReason, admissionGeneration, sessionProxy };
}
// Bundle, spawn, bind, register, hand over the capability.
@@ -505,16 +533,21 @@ export function createLauncher({
if (c.outcome === "kept") record({ event: "checkout-kept", instance, project: c.project, reason: c.reason });
else if (c.outcome === "fetched") record({ event: "checkout-fetched", instance, project: c.project, reason: c.reason });
}
let harness, route, routeReason;
({resolved,model,account,harness,route,routeReason}=await check(instance,{pm:instance===b.launch.by,thread,session,human}));
// Retain P2's real admission/ownership operation; do not substitute the
// old stand-in option or acquire again in each metadata/preflight check.
let admittedProxy = null;
if (system.proxy) {
try { admittedProxy = await host.op({ op: 'modelPreflight', business: b.id, role: instance }); }
catch (error) { throw new Refusal(error.code ?? 'proxy-down', error.code ?? 'proxy-down'); }
if (!admittedProxy || typeof admittedProxy.key !== 'string' || !admittedProxy.key || admittedProxy.baseUrl !== `http://127.0.0.1:${system.proxy.port}`) throw new Refusal('proxy-down', 'proxy-down');
}
let harness, route, routeReason, sessionProxy;
({resolved,model,account,harness,route,routeReason,sessionProxy}=await check(instance,{pm:instance===b.launch.by,thread,session,human,proxyContext:admittedProxy,proxyReady:true}));
admission(admissionGeneration);
const { run, runDir } = newRun(dataRoot, b.id);
let proxy = null, modelKeyId;
if (system.proxy) {
try { proxy = await host.op({ op: 'modelPreflight', business: b.id, role: instance }); }
catch (error) { throw new Refusal(error.code ?? 'proxy-down', error.code ?? 'proxy-down'); }
if (!proxy || typeof proxy.key !== 'string' || proxy.baseUrl !== `http://127.0.0.1:${system.proxy.port}`) throw new Refusal('proxy-down', 'proxy-down');
modelKeyId = createHash('sha256').update(proxy.key).digest('hex').slice(0, 12);
let modelKeyId;
if (admittedProxy) {
modelKeyId = createHash('sha256').update(sessionProxy.key).digest('hex').slice(0, 12);
// Internal opt-in only: no session.json, user environment or config field.
try { writeFileSync(join(runDir, 'proxy-first-turn-enabled'), 'enabled\n', { flag: 'wx', mode: 0o600 }); }
catch { throw new Refusal('launch-failed', 'first-turn protocol setup failed'); }
@@ -534,10 +567,10 @@ export function createLauncher({
const holding = holders?.filter((h) => h.instance === instance) ?? null;
const land = thread ? await host.op({ op: "landHeld", record: { business: b.id, role: instance, thread } }) : holding.length > 0;
const bundle = buildBundle({
...(proxy ? { proxy } : {}),
dir: join(runDir, "bundle"),
resolved,
models: b.launch.models,
proxy: sessionProxy,
contract: readFileSync(resolved.contract, "utf8"),
arbiter: Object.values(b.arbiters).includes(instance),
tracker,
@@ -561,6 +594,12 @@ export function createLauncher({
// Row 199 (D11): or publishes it, once a reviewed commit routes git.push.remote within-role.
const held = [...resolved.limits.authority.withinRole, ...resolved.limits.authority.crossRole];
const git = land || ["git.push.working", "review.verdict", "git.push.remote"].some((a) => held.includes(a)) ? gitSocketPath(dataRoot) : null;
// Secrets go only to spawn, never session.json. Keep this split at the
// actual serialization boundary, even if a harness adds another key.
const harnessEnv = {}, transientEnv = {};
for (const [name, value] of Object.entries(bundle.env)) {
(sessionProxy && isProviderVariable(name) ? transientEnv : harnessEnv)[name] = value;
}
writeSessionFile(runDir, {
...sessionDefaults,
business: b.id,
@@ -578,7 +617,7 @@ export function createLauncher({
sessionDir,
adapter,
bundle: files,
harnessEnv: bundle.env,
harnessEnv,
turnEnd,
toolSocket,
turnMarker,
@@ -602,7 +641,7 @@ export function createLauncher({
try {
admission(admissionGeneration);
spawnedAt.set(run, Date.now());
child = spawnSession({ runDir, env: sessionEnv(env, run), paths, business: b.id, role: instance, bwrap });
child = spawnSession({ runDir, env: { ...sessionEnv(env, run, sessionProxy), ...transientEnv }, paths, business: b.id, role: instance, bwrap });
} catch (e) {
spawnedAt.delete(run);
unregisterRuntime(dataRoot, managed.id);
@@ -624,13 +663,13 @@ export function createLauncher({
admission(admissionGeneration);
if (!outerStart) throw new Error("the session process exited at once");
lock?.update({ run, runPid: child.pid, runStartTime: outerStart });
const launch = await host.bindLaunch({ business: b.id, role: instance, run, harness: model.harness, provider: model.provider, model: model.model, account, transcript, pid: child.pid, startTime: outerStart, ...(thread ? { thread, session } : {}), ...(proxy ? { modelKeyId } : {}) });
const launch = await host.bindLaunch({ business: b.id, role: instance, run, harness: model.harness, provider: model.provider, model: model.model, account, transcript, pid: child.pid, startTime: outerStart, ...(thread ? { thread, session } : {}), ...(admittedProxy ? { modelKeyId } : {}) });
bound = true;
admission(admissionGeneration);
entry = {
business: b.id, instance, ...(thread ? { thread, session, workspace } : {}), run, launchedBy, harness: model.harness, model: model.model, provider: model.provider, modelKey: model.modelKey,
pid: child.pid, startTime: outerStart, runnerPid: runner.pid, runnerStartTime: runner.startTime, runDir, startedAt: new Date().toISOString(),
...(proxy ? { modelKeyId } : {}),
...(admittedProxy ? { modelKeyId } : {}),
};
registry.add(entry);
// Row 156: one start per decision, whichever launch wrote it into landing.
@@ -648,7 +687,7 @@ export function createLauncher({
throw new Refusal("launch-failed", e.message);
}
children.set(run, exited);
const outputWatch = proxy ? watchModelOutput({ runDir, armAtFirstTurn: true, keyId: modelKeyId, seconds: system.proxy.firstOutputSeconds ?? 120,
const outputWatch = admittedProxy ? watchModelOutput({ runDir, armAtFirstTurn: true, keyId: modelKeyId, seconds: system.proxy.firstOutputSeconds ?? 120,
stop: () => host.op({ op: 'modelStall', business: b.id, role: instance, run, keyId: modelKeyId }), receipt: record }) : null;
exited.then(async ({ code, signal }) => {
outputWatch?.cancel();
+32 -5
View File
@@ -82,6 +82,8 @@ function prepare(t, more = (doc) => doc) {
const f = fixture(root, "acme", (doc) => more(edit(doc)));
for (const k of SESSION_CREDENTIALS.flat()) delete f.env[k];
f.env.CLAUDE_CODE_OAUTH_TOKEN = "stand-in";
if (f.doc.roles.chief.vars.harness === "pi" || f.doc.roles.chief.vars["fallback.harness"] === "pi")
f.env.ZAI_API_KEY = "fx332-pi";
// The project root is a repository on main, so each launch can clone it.
const project = f.doc.projects.stack.root;
gitIn(project, "init", "-q", "-b", "main");
@@ -145,6 +147,29 @@ function ask(path, line) {
const log = (f) => readFileSync(launchLogFile(f.dataRoot, "acme"), "utf8").trim().split("\n").map((l) => JSON.parse(l));
// Named mutant: proxy key serialized into session.json. Keep the real launcher,
// harness env generation, session writer and runner; only the model adapter is fake.
test('P3 proxy key reaches the spawned runner but never session.json or the bundle', { skip, timeout: 30000 }, async t => {
const proxy = { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' };
const prepared = prepare(t, doc => {
doc.launch.models['claude-opus-5-5'] = { provider: 'proxy', model: 'claude-fixture', route: 'anthropic' };
return doc;
});
const { launcher, f, close } = await setup(t, doc => doc, prepared, { proxy });
const launched = await launcher.launchPm();
const session = readSessions(f.dataRoot).find(s => s.run === launched.run);
assert.ok(session);
const environ = readFileSync(`/proc/${session.runnerPid}/environ`, 'utf8').split('\0');
assert.ok(environ.includes(`ANTHROPIC_API_KEY=${proxy.key}`));
assert.ok(!environ.some(value => value.startsWith('CLAUDE_CODE_OAUTH_TOKEN=')));
const stored = readFileSync(join(session.runDir, 'session.json'), 'utf8');
assert.ok(!stored.includes(proxy.key), 'session.json must never persist the proxy key');
const bundleFiles = readdirSync(join(session.runDir, 'bundle'), { recursive: true, withFileTypes: true })
.filter(entry => entry.isFile()).map(entry => join(entry.parentPath, entry.name));
for (const file of bundleFiles) assert.ok(!readFileSync(file, 'utf8').includes(proxy.key), file);
assert.equal(await close(), 0);
});
test("bus start --pm: the launcher instance (the chief of staff) runs under its own PID namespace, registered, with a manifest", { skip, timeout: 30000 }, async (t) => {
// Row 122: uncertain write receipts cannot prevent the window's first chief launch.
const prepared = prepare(t);
@@ -672,14 +697,15 @@ test("a Claude Code launch with no session credential refuses before it starts",
assert.deepEqual(readdirSync(join(f.dataRoot, "launches")), ["acme.jsonl"], "no run was made");
});
test("a pi launch needs no session credential: pi logs in through its own ENV_ALLOW variables", { skip, timeout: 30000 }, async (t) => {
test("a pi launch with no own credential refuses no-session-credential", { skip, timeout: 30000 }, async (t) => {
const given = prepare(t);
delete given.f.env.CLAUDE_CODE_OAUTH_TOKEN;
delete given.f.env.ZAI_API_KEY;
assert.deepEqual(SESSION_CREDENTIALS.flat().filter((k) => k in given.f.env), []);
const { f, launcher } = await setup(t, undefined, given);
const chief = await launcher.launchPm();
assert.equal(chief.harness, "pi");
assert.deepEqual(log(f).map((e) => [e.event, e.instance]), [["launch", "chief"]]);
await assert.rejects(launcher.launchPm(), /PM launch refused: no-session-credential/);
assert.deepEqual(log(f).map((e) => [e.event, e.code]), [["refused", "no-session-credential"]]);
assert.deepEqual(readSessions(f.dataRoot), []);
});
// Row 65: a harness module no core file names, switched on in the organization file, runs a real
@@ -696,6 +722,7 @@ test("row 65 a failed primary preflight launches the fallback on a fixture harne
write("harness", "down", `export * from ${pi};\nexport const preflight = () => ({ code: "fixture-down", message: "fixture preflight fails" });\n`);
write("harness", "fixture", `export * from ${pi};\nexport const adapter = () => ${JSON.stringify(given.adapter)};\n`);
});
given.f.env.ZAI_API_KEY = "fx332-pi";
const { f, launcher } = await setup(t, undefined, given, { makeLoader });
const chief = await launcher.launchPm();
assert.deepEqual({ ...chief, run: undefined }, { run: undefined, instance: "chief", harness: "fixture", model: "claude-sonnet-5-5" });
@@ -825,7 +852,7 @@ test("row 64 on Claude Code a role skill that isn't enabled refuses the same way
// API, runs one Bash call that tries the founder's stand-ins, another run
// and the checkout. No real credential and no real model.
const which = spawnSync("sh", ["-c", "command -v claude"], { encoding: "utf8" });
const CLAUDE = which.status === 0 ? which.stdout.trim() : null;
const CLAUDE = process.env.MOSAIC_CLAUDE_BIN ?? (which.status === 0 ? which.stdout.trim() : null);
test("a real Claude Code coder's shell can't read a stand-in secret or anything else its sandbox doesn't hold", { skip: skip || (CLAUDE ? false : "claude is not on PATH"), timeout: 180000 }, async (t) => {
const script = [];
@@ -15,13 +15,16 @@ import { readSessions, runsDir, sessionsFile, SESSIONS_VERSION, launchLogFile }
export const waitFor = async (read, message, ms=15000) => { const end=Date.now()+ms;while(Date.now()<end){const value=await read();if(value)return value;await new Promise(r=>setTimeout(r,20));}throw Error(message); };
export const pause = ms => new Promise(r=>setTimeout(r,ms));
const id = value => createHash('sha256').update(value).digest('hex').slice(0,12);
export async function managedLaunchFixture(t,{proxy=true,launches=true,refuseProbe=false}={}){
export async function managedLaunchFixture(t,{proxy=true,launches=true,refuseProbe=false,harness='pi'}={}){
const root=fs.mkdtempSync(join(tmpdir(),'ml653-')),closers=[],history=new Set(['fx653-manage']),proxyReceipts=[],logs=[];
let server,bus,launcher,stderr;const trace={preflightAttempts:0,successfulPreflights:0,enableBeforeSpawn:[],bindings:[],stalls:[]};
const checkHistory=entries=>{const text=JSON.stringify(entries);for(const value of history)if(text.includes(value))throw Error('fixture credential leaked');};
t.after(async()=>{const failures=[];for(const close of [...closers].reverse()){try{await close();}catch{failures.push('owned-close');}}try{server?.closeAllConnections();if(server?.listening)await new Promise((resolve,reject)=>server.close(e=>e?reject(e):resolve()));}catch{failures.push('owned-server-close');}try{checkHistory({logs,proxyReceipts,trace});}catch{failures.push('value-free-receipts');}if(stderr)process.stderr.write=stderr;try{fs.rmSync(root,{recursive:true,force:true});}catch{failures.push('owned-root-close');}if(failures.length)throw new AggregateError(failures.map(code=>Error(code)),'owned managed fixture cleanup failed');});
const f=fixture(root,'acme',doc=>{doc.plugins={...doc.plugins,harness:['pi']};for(const role of Object.values(doc.roles))role.vars={...role.vars,harness:'pi'};doc.roles.chief.vars.model='claude-opus-5-5';return doc;});
const f=fixture(root,'acme',doc=>{doc.plugins={...doc.plugins,harness:[harness]};for(const role of Object.values(doc.roles))role.vars={...role.vars,harness};doc.roles.chief.vars.model='claude-opus-5-5';return doc;});
const env={PATH:process.env.PATH,HOME:process.env.HOME,TMPDIR:process.env.TMPDIR,MOSAIC_CONFIG:f.config,MOSAIC_ROLES_DIR:f.roles};
// The nonproxy positive fixture supplies its own fake pi login. Managed
// proxy fixtures deliberately hold no upstream credential at all.
if(!proxy)env.ZAI_API_KEY='fx653-pi';
const configDir=join(root,'config'),prefix=`msk-${id(configDir)}-`,sentinel=prefix+'sentinel-'+randomBytes(32).toString('base64url');history.add(sentinel);
const state={keys:[sentinel],calls:[],refuseProbe};
server=http.createServer(async(req,res)=>{try{
@@ -78,7 +81,7 @@ export async function managedLaunchFixture(t,{proxy=true,launches=true,refusePro
return actualOp(m);
},
bindLaunch:async record=>{const result=bus.bindLaunch(record);trace.bindings.push({run:record.run,pid:record.pid,startTime:record.startTime,modelKeyId:record.modelKeyId});return result;}};
const makeLoader=await fakeHarnesses({after:close=>closers.push(close)},{pi:adapter});
const makeLoader=await fakeHarnesses({after:close=>closers.push(close)},{[harness]:adapter});
launcher=createLauncher({host,system,env,launches,makeLoader,sessionDefaults:{pollInterval:50},harnessVersion:'0.85.1',log:line=>logs.push(line)});
// The existing trusted host hook owns all launcher-created children. No registry
// PID is signalled by fixture teardown; normal bounded launcher close is used.
@@ -87,6 +90,7 @@ export async function managedLaunchFixture(t,{proxy=true,launches=true,refusePro
const launchLog=()=>fs.existsSync(launchLogFile(f.dataRoot,'acme'))?fs.readFileSync(launchLogFile(f.dataRoot,'acme'),'utf8').trim().split('\n').filter(Boolean).map(l=>JSON.parse(l)):[];
const valueFree=()=>checkHistory({logs,proxyReceipts,launch:launchLog(),trace});
return {root,f,state,trace,proxyReceipts,logs,launcher,bus,launchLog,expectedKeyId:()=>expectedKeyId,valueFree,
upstreamCredentialNames:Object.keys(env).filter(name=>['ANTHROPIC_API_KEY','ANTHROPIC_AUTH_TOKEN','CLAUDE_CODE_OAUTH_TOKEN','OPENAI_API_KEY','OPENROUTER_API_KEY','ZAI_API_KEY'].includes(name)),
runDirectories:()=>fs.existsSync(runsDir(f.dataRoot,'acme'))?fs.readdirSync(runsDir(f.dataRoot,'acme')).map(name=>join(runsDir(f.dataRoot,'acme'),name)):[],
sessions:()=>readSessions(f.dataRoot),send:body=>bus.broker.request(human,{verb:'message.send',args:{to:'chief',body,class:'REQUEST'}}),
reply:sent=>waitFor(()=>bus.broker.request(human,{verb:'message.receive'}).find(m=>m.in_reply_to===sent.id),'real managed reply observed'),
@@ -0,0 +1,112 @@
// Mos1961: exercise the actual P2 runtime -> launcher -> P3 harness/runner path.
// Only management/model HTTP and the model adapter are local stand-ins.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { join } from 'node:path';
import { sandboxProblem } from '../../seat/src/sandbox.mjs';
import { managedLaunchFixture } from './model-managed-launch-fixture.mjs';
const skip = sandboxProblem() ?? false;
function editBusiness(f, update) {
const path = join(f.root, 'config', 'businesses', 'acme.json');
const document = JSON.parse(fs.readFileSync(path, 'utf8'));
update(document);
fs.writeFileSync(path, JSON.stringify(document) + '\n', { mode: 0o600 });
}
function runnerEnv(session) {
return Object.fromEntries(fs.readFileSync(`/proc/${session.runnerPid}/environ`, 'utf8')
.split('\0').filter(Boolean).map(entry => {
const at = entry.indexOf('='); return [entry.slice(0, at), entry.slice(at + 1)];
}));
}
function privateArtifacts(f, session, keys) {
const text = fs.readFileSync(join(session.runDir, 'session.json'), 'utf8');
const saved = JSON.parse(text);
for (const key of keys) assert.equal(text.includes(key), false, 'session.json contains no credential value');
for (const name of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN', 'ZAI_API_KEY'])
assert.equal(Object.hasOwn(saved.harnessEnv, name), false, 'harnessEnv persists no provider credential');
for (const entry of fs.readdirSync(join(session.runDir, 'bundle'), { withFileTypes: true, recursive: true })) {
if (!entry.isFile()) continue;
const bytes = fs.readFileSync(join(entry.parentPath, entry.name), 'utf8');
for (const key of keys) assert.equal(bytes.includes(key), false, 'bundle contains no credential value');
}
f.valueFree();
}
for (const [provider, route, generated, api] of [
['zai', null, 'mosaic-proxy-glm', 'openai-completions'],
['anthropic', null, 'anthropic', 'anthropic-messages'],
['proxy', 'anthropic', 'anthropic', 'anthropic-messages'],
['proxy', 'glm', 'mosaic-proxy-glm', 'openai-completions'],
['proxy', 'codex', 'mosaic-proxy-codex', 'openai-responses'],
]) {
test(`P3 joined managed ${provider}${route ? ':' + route : ''} uses its one admitted P2 key and private run-local config`, { skip, timeout: 30000 }, async t => {
const f = await managedLaunchFixture(t);
assert.deepEqual(f.upstreamCredentialNames, [], 'managed proxy fixture has no inherited fake upstream credential');
editBusiness(f, doc => {
doc.launch.models['claude-opus-5-5'].provider = provider;
if (route) doc.launch.models['claude-opus-5-5'].route = route;
});
const answer = await f.launcher.launchPm();
const session = f.sessions().find(value => value.run === answer.run);
assert.ok(session?.live, 'same real confined runner is live');
assert.equal(f.trace.successfulPreflights, 1, 'one actual P2 acquisition, not one per check');
const own = f.bus.credentials.modelRecord('acme/chief');
assert.ok(own);
assert.equal(session.modelKeyId, own.keyId, 'binding/stall identity matches admitted generation');
assert.equal(f.trace.bindings[0].modelKeyId, own.keyId);
const other = await f.bus.modelPreflight({ business: 'acme', role: 'coder' });
assert.equal(other.key === own.key, false, 'different agent receives a different key');
const env = runnerEnv(session);
assert.equal(env.ANTHROPIC_API_KEY === own.key, true, 'runner gets exactly the admitted key');
assert.equal(Object.values(env).includes(other.key), false, 'another agent key never enters runner');
for (const name of ['CLAUDE_CODE_OAUTH_TOKEN', 'ANTHROPIC_AUTH_TOKEN', 'OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'ZAI_API_KEY'])
assert.equal(Object.hasOwn(env, name), false, `${name} absent from managed runner`);
const path = join(session.runDir, 'home', '.pi', 'agent', 'models.json');
const text = fs.readFileSync(path, 'utf8');
const models = JSON.parse(text);
assert.equal(models.providers[generated].api, api);
assert.equal(models.providers[generated].baseUrl,
other.baseUrl + (api === 'anthropic-messages' ? '' : '/v1'));
assert.equal(models.providers[generated].models.some(model => model.id === 'claude-opus-5-5'), true);
for (const value of Object.values(models.providers)) assert.equal(value.apiKey, '$ANTHROPIC_API_KEY');
for (const key of [own.key, other.key]) assert.equal(text.includes(key), false, 'models contain no key value');
assert.equal(fs.statSync(path).mode & 0o777, 0o600);
for (const part of ['home', 'home/.pi', 'home/.pi/agent'])
assert.equal(fs.statSync(join(session.runDir, part)).mode & 0o777, 0o700);
privateArtifacts(f, session, [own.key, other.key]);
});
}
test('P3 joined Claude harness receives the admitted P2 key only through transient auth env', { skip, timeout: 30000 }, async t => {
const f = await managedLaunchFixture(t, { harness: 'claude-code' });
assert.deepEqual(f.upstreamCredentialNames, [], 'Claude proxy fixture holds no upstream credential');
editBusiness(f, doc => { doc.launch.models['claude-opus-5-5'].provider = 'anthropic'; });
const answer = await f.launcher.launchPm();
const session = f.sessions().find(value => value.run === answer.run);
assert.ok(session?.live);
assert.equal(f.trace.successfulPreflights, 1);
const own = f.bus.credentials.modelRecord('acme/chief');
const env = runnerEnv(session);
assert.equal(env.ANTHROPIC_AUTH_TOKEN === own.key, true, 'Claude receives admitted key without host login');
assert.equal(env.ANTHROPIC_BASE_URL?.startsWith('http://127.0.0.1:'), true);
assert.equal(Object.hasOwn(env, 'ANTHROPIC_API_KEY'), false);
assert.equal(Object.hasOwn(env, 'CLAUDE_CODE_OAUTH_TOKEN'), false);
assert.equal(session.modelKeyId, own.keyId);
privateArtifacts(f, session, [own.key]);
});
test('P3 joined unsupported provider refuses with no key acquisition, fallback, or spawned session', { skip, timeout: 30000 }, async t => {
const f = await managedLaunchFixture(t);
editBusiness(f, doc => {
doc.launch.models['claude-opus-5-5'].provider = 'unknown-wire';
Object.assign(doc.roles.chief.vars, { 'fallback.harness': 'pi', 'fallback.model': 'glm-5.3-flash', 'fallback.thinking': 'low' });
});
await assert.rejects(f.launcher.launchPm(), error => error.code === 'proxy-provider-unsupported');
assert.equal(f.trace.preflightAttempts, 0);
assert.equal(f.trace.bindings.length, 0);
assert.equal(f.sessions().length, 0);
assert.equal(f.runDirectories().length, 0);
f.valueFree();
});