Join P3 harness context to landed P2 admission with private same-key delivery
This commit is contained in:
1 parent
fbdd8c164c
commit
ee1f926ceb
94 files changed
+5386
-62
No files matched your search
@@ -1,6 +1,6 @@
|
||||
// REQ-LIMIT-1: editable concurrency policy, never a compiled-in capacity ceiling.
|
||||
import { requireObject, requireId, requireString, rejectUnknownKeys } from "./util.mjs";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { BusinessError, refuse } from "./errors.mjs";
|
||||
|
||||
const name = (value, at) => requireString(value, at, { max: 200 });
|
||||
const count = (value, at) => {
|
||||
@@ -15,10 +15,19 @@ export function checkModels(value, where = "launch.models") {
|
||||
return Object.fromEntries(Object.entries(value).map(([key, entry]) => {
|
||||
requireId(key, where);
|
||||
requireObject(entry, `${where}.${key}`);
|
||||
rejectUnknownKeys(entry, ["provider", "model"], `${where}.${key}`);
|
||||
rejectUnknownKeys(entry, entry.provider === "proxy" ? ["provider", "model", "route"] : ["provider", "model"], `${where}.${key}`);
|
||||
if (entry.provider === "proxy") {
|
||||
const missing = !Object.hasOwn(entry, "route");
|
||||
if (missing || !["anthropic", "glm", "codex"].includes(entry.route)) {
|
||||
throw Object.assign(new BusinessError(`${where}.${key}.route must name anthropic, glm or codex`), {
|
||||
code: missing ? "proxy-route-missing" : "proxy-route-unknown",
|
||||
});
|
||||
}
|
||||
}
|
||||
return [key, {
|
||||
provider: name(entry.provider, `${where}.${key}.provider`),
|
||||
model: name(entry.model, `${where}.${key}.model`),
|
||||
...(entry.provider === "proxy" && Object.hasOwn(entry, "route") ? { route: entry.route } : {}),
|
||||
}];
|
||||
}));
|
||||
}
|
||||
@@ -82,7 +91,7 @@ export function checkAccount(value, where = "launch.account") {
|
||||
requireObject(value, where);
|
||||
rejectUnknownKeys(value, ["name", "credential"], where);
|
||||
const accountName = requireId(value.name, `${where}.name`);
|
||||
if (typeof value.credential !== "string" || !CREDENTIAL.test(value.credential)) {
|
||||
if (typeof value.credential !== "string" || (value.credential !== "proxy" && !CREDENTIAL.test(value.credential))) {
|
||||
refuse(`${where}.credential must name environment variables, joined with "+"`);
|
||||
}
|
||||
return { name: accountName, credential: value.credential };
|
||||
|
||||
@@ -38,11 +38,11 @@ test('REQ-ROLE-3 writer: pre-rename fault leaves old file, post-rename recovery
|
||||
test('REQ-LIMIT-1 / decision145 migration prints only, preserves values, rejects ambiguity, and is idempotent',async()=>{
|
||||
const {migrateLaunch}=await import('../src/migrate-launch.mjs');const f=fixture(),old=structuredClone(f.doc);old.roles.pm.vars.model='claude-opus-5-5';for(const [name,r] of Object.entries(old.roles))if(name!=='pm')r.vars.model='claude-sonnet-5-5';old.launch={by:'chief',instances:['coder','reviewer'],max:{opus:4,sonnet:4}};writeJson(f.file,old);const bytes=readFileSync(f.file,'utf8'),mtime=statSync(f.file).mtimeMs;
|
||||
const mapping={models:f.doc.launch.models,families:{opus:'opus',sonnet:'sonnet'}};const next=migrateLaunch(old,mapping,f.file,{rolesDir:f.rolesDir});assert.deepEqual(next.launch.limits, f.doc.launch.limits);assert.equal(next.roles.pm.vars.model,'opus');assert.equal(next.roles.coder.vars.model,'sonnet');assert.deepEqual(migrateLaunch(next,mapping,f.file,{rolesDir:f.rolesDir}),next);
|
||||
assert.throws(()=>migrateLaunch(old,{...mapping,families:{opus:'missing',sonnet:'sonnet'}},f.file,{rolesDir:f.rolesDir}));assert.throws(()=>migrateLaunch(old,{...mapping,families:{opus:'opus',sonnet:'opus'}},f.file,{rolesDir:f.rolesDir}),/ambiguous/);assert.throws(()=>migrateLaunch(old,{...mapping,models:{...mapping.models,proxy:{provider:'proxy',model:'claude-opus-5-5'}},instances:{pm:'proxy'}},f.file,{rolesDir:f.rolesDir}),/ambiguous/);const onlyOpus=structuredClone(old);onlyOpus.launch.max={opus:4};assert.throws(()=>migrateLaunch(onlyOpus,mapping,f.file,{rolesDir:f.rolesDir}),/unknown or ambiguous/);const allOpus=structuredClone(old);for(const r of Object.values(allOpus.roles))r.vars.model='claude-opus-5-5';assert.throws(()=>migrateLaunch(allOpus,{...mapping,families:{opus:'opus',sonnet:'opus'}},f.file,{rolesDir:f.rolesDir}),/ambiguous/);assert.equal(readFileSync(f.file,'utf8'),bytes);assert.equal(statSync(f.file).mtimeMs,mtime);
|
||||
assert.throws(()=>migrateLaunch(old,{...mapping,families:{opus:'missing',sonnet:'sonnet'}},f.file,{rolesDir:f.rolesDir}));assert.throws(()=>migrateLaunch(old,{...mapping,families:{opus:'opus',sonnet:'opus'}},f.file,{rolesDir:f.rolesDir}),/ambiguous/);assert.throws(()=>migrateLaunch(old,{...mapping,models:{...mapping.models,proxy:{provider:'proxy',route:'anthropic',model:'claude-opus-5-5'}},instances:{pm:'proxy'}},f.file,{rolesDir:f.rolesDir}),/ambiguous/);const onlyOpus=structuredClone(old);onlyOpus.launch.max={opus:4};assert.throws(()=>migrateLaunch(onlyOpus,mapping,f.file,{rolesDir:f.rolesDir}),/unknown or ambiguous/);const allOpus=structuredClone(old);for(const r of Object.values(allOpus.roles))r.vars.model='claude-opus-5-5';assert.throws(()=>migrateLaunch(allOpus,{...mapping,families:{opus:'opus',sonnet:'opus'}},f.file,{rolesDir:f.rolesDir}),/ambiguous/);assert.equal(readFileSync(f.file,'utf8'),bytes);assert.equal(statSync(f.file).mtimeMs,mtime);
|
||||
});
|
||||
test('REQ-LIMIT-1 shared settings validates the complete proposed selection and logs exact actor',async()=>{
|
||||
const {launchSettings}=await import('../src/launch-settings.mjs');const f=fixture(),system={environment:'development',dataRoot:join(f.root,'data'),'execution.backend':'docker','execution.provider':'anthropic','execution.model':'sonnet','execution.adapter':'pi'};const settings=launchSettings({dir:f.root,rolesDir:f.rolesDir,system,sessions:()=>[{business:'acme',provider:'anthropic',model:'claude-opus-5-5'}]});const view=settings.read('acme');assert.equal(view.usage.total,1);assert.equal(view.instances.pm.modelKey,'opus');
|
||||
const result=settings.set('acme',{revision:view.revision,limits:{total:0},instances:{coder:'opus'}},'jason');assert.equal(result.limits.total,0);assert.equal(result.instances.coder.modelKey,'opus');const models=structuredClone(result.models);models.opus.provider='proxy';const updated=settings.set('acme',{revision:result.revision,models},'jason');assert.equal(updated.instances.pm.provider,'proxy');assert.throws(()=>settings.set('acme',{revision:result.revision,instances:{coder:'ghost'}},'jason'));assert.throws(()=>settings.set('acme',{revision:result.revision,roles:{}},'jason'));
|
||||
const result=settings.set('acme',{revision:view.revision,limits:{total:0},instances:{coder:'opus'}},'jason');assert.equal(result.limits.total,0);assert.equal(result.instances.coder.modelKey,'opus');const models=structuredClone(result.models);models.opus.provider='proxy';models.opus.route='anthropic';const updated=settings.set('acme',{revision:result.revision,models},'jason');assert.equal(updated.instances.pm.provider,'proxy');assert.throws(()=>settings.set('acme',{revision:result.revision,instances:{coder:'ghost'}},'jason'));assert.throws(()=>settings.set('acme',{revision:result.revision,roles:{}},'jason'));
|
||||
});
|
||||
test('REQ-LIMIT-1 provider is table data: another provider routes separately and aliases share exact counts',async()=>{
|
||||
const {limitHit}=await import('../src/launch.mjs');const {sessionModel}=await import('../../harness/src/bundle.mjs');
|
||||
@@ -151,14 +151,14 @@ test('B7 kept instance: the models keys it names and the instances key are the h
|
||||
const chief='chief-of-staff.chief';let {revision}=settings.read('acme');
|
||||
const models=structuredClone(settings.read('acme').models);
|
||||
const key=doc.roles.coder.vars.model;
|
||||
const moved={...models,[key]:{provider:'proxy',model:'claude-sonnet-5-5'}};
|
||||
const moved={...models,[key]:{provider:'proxy',route:'anthropic',model:'claude-sonnet-5-5'}};
|
||||
for(const actor of [chief,'tester']){
|
||||
const bytes=file();
|
||||
assert.throws(()=>settings.set('acme',{revision,models:moved},actor),code('instance-kept'),actor);
|
||||
assert.throws(()=>settings.set('acme',{revision,instances:{coder:'opus'}},actor),code('instance-kept'),actor);
|
||||
assert.equal(file(),bytes,actor);
|
||||
}
|
||||
({revision}=settings.set('acme',{revision,models:{...models,spare:{provider:'proxy',model:'claude-opus-5-5'}}},chief));
|
||||
({revision}=settings.set('acme',{revision,models:{...models,spare:{provider:'proxy',route:'anthropic',model:'claude-opus-5-5'}}},chief));
|
||||
({revision}=settings.set('acme',{revision,models:{...settings.read('acme').models,[key]:moved[key]}},'jason'));
|
||||
settings.set('acme',{revision,instances:{coder:'opus'}},'jason');
|
||||
assert.equal(JSON.parse(file()).roles.coder.vars.model,'opus');
|
||||
@@ -185,7 +185,7 @@ test('M10 creative instance: models keys it names, the instances key and its rou
|
||||
const g={...f,doc};const {settings}=await routeSettings(g);const file=()=>readFileSync(f.file,'utf8');
|
||||
const chief='chief-of-staff.chief';let {revision}=settings.read('acme');
|
||||
const models=structuredClone(settings.read('acme').models);
|
||||
const sonnet={...models,sonnet:{provider:'proxy',model:'claude-sonnet-5-5'}};
|
||||
const sonnet={...models,sonnet:{provider:'proxy',route:'anthropic',model:'claude-sonnet-5-5'}};
|
||||
for(const actor of [chief,'tester']){
|
||||
const bytes=file();
|
||||
assert.throws(()=>settings.set('acme',{revision,models:sonnet},actor),code('organization-creative-human-only'),actor);
|
||||
@@ -195,7 +195,7 @@ test('M10 creative instance: models keys it names, the instances key and its rou
|
||||
assert.equal(file(),bytes,actor);
|
||||
}
|
||||
// A key no creative instance names stays the chief's.
|
||||
({revision}=settings.set('acme',{revision,models:{...models,opus:{provider:'proxy',model:'claude-opus-5-5'}}},chief));
|
||||
({revision}=settings.set('acme',{revision,models:{...models,opus:{provider:'proxy',route:'anthropic',model:'claude-opus-5-5'}}},chief));
|
||||
assert.throws(()=>settings.set('acme',{revision,instances:{bean:'opus'}},'jason'),code('organization-creative-instance'));
|
||||
({revision}=settings.set('acme',{revision,models:sonnet},'jason'));
|
||||
({revision}=settings.setRoutes('acme',{revision,routes:{bean:{harness:'pi',model:'sonnet',thinking:'high',fallback:{harness:'pi',model:'opus',thinking:'low'}}}},'jason'));
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// P3: the proxy account is a declared credential source, never a secret value.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { checkAccount, checkModels } from '../src/launch.mjs';
|
||||
|
||||
test('P3 proxy model validation preserves each explicit wire route and the proxy model id', () => {
|
||||
for (const route of ['anthropic', 'glm', 'codex']) {
|
||||
const models = { selected: { provider: 'proxy', model: 'proxy-only-id', route } };
|
||||
assert.deepEqual(checkModels(models), models, route);
|
||||
}
|
||||
});
|
||||
|
||||
test('P3 a proxy model without route refuses proxy-route-missing', () => {
|
||||
assert.throws(() => checkModels({ selected: { provider: 'proxy', model: 'proxy-only-id' } }), {
|
||||
code: 'proxy-route-missing',
|
||||
});
|
||||
});
|
||||
|
||||
test('P3 an unknown proxy route refuses proxy-route-unknown', () => {
|
||||
for (const route of ['openai-codex', 'unknown', '', null, 7]) {
|
||||
assert.throws(() => checkModels({ selected: { provider: 'proxy', model: 'proxy-only-id', route } }), {
|
||||
code: 'proxy-route-unknown',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('P3 nonproxy models retain their provider/model-only shape and reject route metadata', () => {
|
||||
assert.deepEqual(checkModels({ selected: { provider: 'zai', model: 'glm-fixture' } }), {
|
||||
selected: { provider: 'zai', model: 'glm-fixture' },
|
||||
});
|
||||
assert.throws(() => checkModels({ selected: { provider: 'zai', model: 'glm-fixture', route: 'glm' } }), /unsupported/);
|
||||
});
|
||||
|
||||
test('P3 launch.account accepts the proxy credential source without naming host variables', () => {
|
||||
assert.deepEqual(checkAccount({ name: 'proxy', credential: 'proxy' }), { name: 'proxy', credential: 'proxy' });
|
||||
});
|
||||
|
||||
test('P3 existing environment-set accounts retain their validated representation', () => {
|
||||
for (const credential of ['CLAUDE_CODE_OAUTH_TOKEN', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN+ANTHROPIC_BASE_URL']) {
|
||||
assert.deepEqual(checkAccount({ name: 'max', credential }), { name: 'max', credential });
|
||||
}
|
||||
for (const credential of ['', 'fx332-fake', 'proxy+ANTHROPIC_API_KEY', 'PROXY+proxy']) {
|
||||
assert.throws(() => checkAccount({ name: 'proxy', credential }), /launch\.account\.credential/);
|
||||
}
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
@@ -74,7 +74,19 @@ export const hasFallback = (resolved) => Object.hasOwn(resolved.vars, "fallback.
|
||||
// "fallback". A missing var refuses no-route and names it. models is launch.models: the model var
|
||||
// is one of its keys, and the entry gives the provider and model; without a table the var is the
|
||||
// model and the provider is unknown.
|
||||
export function sessionModel(resolved, models = null, which = "primary") {
|
||||
export function proxyRouteFor(entry) {
|
||||
if (entry.provider === "proxy") {
|
||||
const missing = !Object.hasOwn(entry, "route");
|
||||
if (missing || !["anthropic", "glm", "codex"].includes(entry.route))
|
||||
throw new BundleError("proxy model needs an explicit anthropic, glm or codex route", missing ? "proxy-route-missing" : "proxy-route-unknown");
|
||||
return entry.route;
|
||||
}
|
||||
if (entry.provider === "anthropic") return "anthropic";
|
||||
if (entry.provider === "zai") return "glm";
|
||||
throw new BundleError("provider is unsupported by the supplied model proxy context", "proxy-provider-unsupported");
|
||||
}
|
||||
|
||||
export function sessionModel(resolved, models = null, which = "primary", { proxy = false } = {}) {
|
||||
const v = resolved.vars;
|
||||
const [harness, model, thinking] = ROUTE_VARS[which].map((name) => {
|
||||
if (typeof v[name] !== "string" || !v[name]) throw new BundleError(`instance ${resolved.instance}: no ${name} var`, "no-route", name);
|
||||
@@ -83,7 +95,8 @@ export function sessionModel(resolved, models = null, which = "primary") {
|
||||
if (models === null) return { harness, provider: null, model, thinking };
|
||||
const entry = Object.hasOwn(models, model) ? models[model] : null;
|
||||
if (!entry) throw new BundleError(`instance ${resolved.instance}: unknown model table selection ${model}`);
|
||||
return { harness, provider: entry.provider, model: entry.model, modelKey: model, thinking };
|
||||
return { harness, provider: entry.provider, model: entry.model, modelKey: model, thinking,
|
||||
...(entry.provider === "proxy" || proxy ? { proxyRoute: proxyRouteFor(entry) } : {}) };
|
||||
}
|
||||
|
||||
// Row 91 (#1585): the project clones the host made or kept in the workspace.
|
||||
@@ -309,10 +322,14 @@ function prompt({ contract, resolved, session, tools, untyped, builtins, persona
|
||||
// personaDir <configDir>/personas, where a creative instance's persona file is read from
|
||||
// (row 213); an instance with persona.sha256 and no personaDir refuses
|
||||
// Returns { manifest, files, policy, tools, env } with absolute paths; env is the module's
|
||||
// adapter variables, which the host writes into session.json.
|
||||
export function buildBundle({ dir, resolved, contract, arbiter = false, tracker = false, library = false, credentials = [], session, harness, route = "primary", routeReason = null, harnessVersion = null, models = null, land = false, skillsDir = null, personaDir = null }) {
|
||||
// adapter variables. In proxy mode the host splits credentials into its
|
||||
// transient spawn environment before writing the remaining variables to session.json.
|
||||
export function buildBundle({ dir, resolved, contract, arbiter = false, tracker = false, library = false, credentials = [], session, harness, route = "primary", routeReason = null, harnessVersion = null, models = null, land = false, skillsDir = null, personaDir = null, proxy = null }) {
|
||||
if (route !== "primary" && route !== "fallback") throw new BundleError(`route ${JSON.stringify(route)} isn't primary or fallback`);
|
||||
const model = sessionModel(resolved, models, route);
|
||||
const model = sessionModel(resolved, models, route, { proxy: Boolean(proxy) });
|
||||
if (model.provider === "proxy" && !proxy) throw new BundleError("proxy model needs its own session credential", "no-session-credential");
|
||||
if (proxy && (typeof proxy.key !== "string" || !proxy.key || typeof proxy.baseUrl !== "string"
|
||||
|| !/^http:\/\/127\.0\.0\.1:[0-9]+$/.test(proxy.baseUrl))) throw new BundleError("invalid session proxy context");
|
||||
const web = webPlan(resolved, model.harness, harness.builtinWeb());
|
||||
const tools = typedTools({ resolved, arbiter, tracker, library, projects: (session.checkouts ?? []).map((c) => c.project), webTyped: !web.builtin, land });
|
||||
const untyped = untypedActions(resolved, tools);
|
||||
@@ -346,7 +363,7 @@ export function buildBundle({ dir, resolved, contract, arbiter = false, tracker
|
||||
write("tools.json", JSON.stringify(tools, null, 2) + "\n"),
|
||||
];
|
||||
// The module's own files. A name the bundle already wrote refuses at write (flag wx).
|
||||
const own = harness.bundle({ dir, files: { ...files }, session, write, quote });
|
||||
const own = harness.bundle({ dir, files: { ...files }, session: { ...session, ...model }, write, quote, models, proxy });
|
||||
Object.assign(files, own.files);
|
||||
digests.push(...own.digests);
|
||||
const sources = { gate: SOURCES.gate, tools: SOURCES.tools, ...own.sources };
|
||||
@@ -373,6 +390,6 @@ export function buildBundle({ dir, resolved, contract, arbiter = false, tracker
|
||||
sources: Object.fromEntries(Object.entries(sources).map(([k, p]) => [k, { path: p, sha256: sha256(readFileSync(p)) }])),
|
||||
};
|
||||
writeFileSync(files.manifest, JSON.stringify(manifest, null, 2) + "\n", { mode: 0o600, flag: "wx" });
|
||||
const env = harness.env({ files, policy, tools, session: { ...session, ...model } });
|
||||
const env = harness.env({ files, policy, tools, session: { ...session, ...model }, models, proxy });
|
||||
return { manifest, files, policy, tools, env };
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// P3: generate real harness config through buildBundle; credentials never enter disk artifacts.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { buildBundle } from '../src/bundle.mjs';
|
||||
import { HARNESS, REPO_SKILLS, resolvedFor, scratch } from './helpers.mjs';
|
||||
|
||||
const models = {
|
||||
a: { provider: 'proxy', model: 'claude-fixture', route: 'anthropic' },
|
||||
z: { provider: 'proxy', model: 'glm-fixture', route: 'glm' },
|
||||
g: { provider: 'proxy', model: 'gpt-fixture', route: 'codex' },
|
||||
};
|
||||
function build(t, selection, proxy, declared) {
|
||||
const root = scratch(t, 'p332-'), runDir = join(root, 'run');
|
||||
mkdirSync(runDir, { mode: 0o700 });
|
||||
const valid = resolvedFor(t, 'pm');
|
||||
assert.ok(Object.hasOwn(declared, selection), 'fixture selection must exist in declared launch.models');
|
||||
const resolved = { ...valid, vars: { ...valid.vars, harness: 'pi', model: selection } };
|
||||
const bundle = buildBundle({
|
||||
dir: join(runDir, 'bundle'), resolved, models: declared,
|
||||
contract: '# Fixture\n', harness: HARNESS.pi, harnessVersion: 'fixture',
|
||||
skillsDir: REPO_SKILLS, proxy,
|
||||
session: { run: 'r332', launchedBy: 'chief', workspace: join(root, 'ws'),
|
||||
toolSocket: join(runDir, 'tools.sock'), turnMarker: join(runDir, 'turn.done') },
|
||||
});
|
||||
const file = join(runDir, 'home', '.pi', 'agent', 'models.json');
|
||||
return { ...bundle, file, runDir, text: readFileSync(file, 'utf8') };
|
||||
}
|
||||
function assertSafe(value) {
|
||||
if (typeof value === 'string') assert.ok(!value.startsWith('!'), value);
|
||||
else if (value && typeof value === 'object') for (const item of Object.values(value)) assertSafe(item);
|
||||
}
|
||||
|
||||
test('P3 Anthropic route uses messages at proxy root and the declared model id', t => {
|
||||
const b = build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { a: models.a });
|
||||
const { anthropic } = JSON.parse(b.text).providers;
|
||||
assert.equal(anthropic.api, 'anthropic-messages');
|
||||
assert.equal(anthropic.baseUrl, 'http://127.0.0.1:12345');
|
||||
assert.deepEqual(anthropic.models.map(m => m.id), ['claude-fixture']);
|
||||
assert.equal(b.env.PI_PROVIDER, 'anthropic');
|
||||
assert.equal(b.env.PI_MODEL, 'claude-fixture');
|
||||
});
|
||||
|
||||
test('P3 omitted route refuses proxy-route-missing before model config generation', t => {
|
||||
assert.throws(() => build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, {
|
||||
a: { provider: 'proxy', model: 'claude-fixture' },
|
||||
}), { code: 'proxy-route-missing' });
|
||||
});
|
||||
|
||||
test('P3 GLM route uses completions at proxy /v1 with explicit z.ai compatibility', t => {
|
||||
const b = build(t, 'z', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { z: models.z });
|
||||
const glm = JSON.parse(b.text).providers['mosaic-proxy-glm'];
|
||||
assert.equal(glm.api, 'openai-completions');
|
||||
assert.equal(glm.baseUrl, 'http://127.0.0.1:12345/v1');
|
||||
assert.deepEqual(glm.models.map(m => m.id), ['glm-fixture']);
|
||||
assert.equal(glm.compat.thinkingFormat, 'zai');
|
||||
assert.equal(glm.compat.zaiToolStream, true);
|
||||
assert.equal(b.env.PI_PROVIDER, 'mosaic-proxy-glm');
|
||||
});
|
||||
|
||||
test('P3 GPT route selects a stack-owned provider instead of pi Codex OAuth', t => {
|
||||
const b = build(t, 'g', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { g: models.g });
|
||||
const providers = JSON.parse(b.text).providers;
|
||||
assert.equal(Object.hasOwn(providers, 'openai-codex'), false);
|
||||
const gpt = providers['mosaic-proxy-codex'];
|
||||
assert.equal(gpt.api, 'openai-responses');
|
||||
assert.equal(gpt.baseUrl, 'http://127.0.0.1:12345/v1');
|
||||
assert.deepEqual(gpt.models.map(m => m.id), ['gpt-fixture']);
|
||||
assert.equal(b.env.PI_PROVIDER, 'mosaic-proxy-codex');
|
||||
});
|
||||
|
||||
test('P3 a declared Codex route generates only the single build-time responses provider', t => {
|
||||
const b = build(t, 'g', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, {
|
||||
g: models.g,
|
||||
});
|
||||
const providers = JSON.parse(b.text).providers;
|
||||
assert.deepEqual(Object.keys(providers), ['mosaic-proxy-codex']);
|
||||
assert.equal(providers['mosaic-proxy-codex'].api, 'openai-responses');
|
||||
assert.equal(providers['mosaic-proxy-codex'].apiKey, '$ANTHROPIC_API_KEY');
|
||||
});
|
||||
|
||||
test('P3 models file is private, references the one session key, and stores no executable values or keys', t => {
|
||||
const key = 'fx332-agent-a';
|
||||
const b = build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key }, { a: models.a, z: models.z });
|
||||
const document = JSON.parse(b.text);
|
||||
assert.deepEqual(Object.keys(document.providers).sort(), ['anthropic', 'mosaic-proxy-glm']);
|
||||
for (const provider of Object.values(document.providers)) assert.equal(provider.apiKey, '$ANTHROPIC_API_KEY');
|
||||
assertSafe(document);
|
||||
assert.ok(!b.text.includes(key));
|
||||
assert.equal(b.env.ANTHROPIC_API_KEY, key);
|
||||
assert.equal(statSync(b.file).mode & 0o777, 0o600);
|
||||
for (const dir of ['home', 'home/.pi', 'home/.pi/agent']) assert.equal(statSync(join(b.runDir, dir)).mode & 0o777, 0o700);
|
||||
for (const file of Object.values(b.files)) assert.ok(!readFileSync(file, 'utf8').includes(key), file);
|
||||
assert.ok(!JSON.stringify(b.manifest).includes(key));
|
||||
});
|
||||
|
||||
test('P3 every launch regenerates proxy port, declared models and own key without caching', t => {
|
||||
const first = build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { a: models.a, z: models.z });
|
||||
const second = build(t, 'a', { baseUrl: 'http://127.0.0.1:23456', key: 'fx332-agent-b' }, {
|
||||
a: { provider: 'proxy', model: 'changed-model-id', route: 'anthropic' },
|
||||
z: { provider: 'proxy', model: 'changed-glm-id', route: 'glm' },
|
||||
});
|
||||
assert.equal(second.env.ANTHROPIC_API_KEY, 'fx332-agent-b');
|
||||
assert.ok(!JSON.stringify(second).includes('fx332-agent-a'));
|
||||
const { providers } = JSON.parse(second.text);
|
||||
assert.deepEqual(Object.keys(providers), ['anthropic', 'mosaic-proxy-glm']);
|
||||
assert.equal(providers.anthropic.baseUrl, 'http://127.0.0.1:23456');
|
||||
assert.deepEqual(providers.anthropic.models.map(m => m.id), ['changed-model-id']);
|
||||
assert.equal(providers['mosaic-proxy-glm'].baseUrl, 'http://127.0.0.1:23456/v1');
|
||||
assert.deepEqual(providers['mosaic-proxy-glm'].models.map(m => m.id), ['changed-glm-id']);
|
||||
assert.equal(JSON.parse(first.text).providers.anthropic.baseUrl, 'http://127.0.0.1:12345');
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
// Mos1961: existing provider identities are translated only with supplied proxy context.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { sessionModel } from '../src/bundle.mjs';
|
||||
const resolved = { instance: 'fixture', vars: { harness: 'pi', model: 'selected', thinking: 'low' } };
|
||||
for (const [provider, model, expected] of [
|
||||
['anthropic', 'glm-looking-id', 'anthropic'],
|
||||
['zai', 'gpt-looking-id', 'glm'],
|
||||
]) {
|
||||
test(`joined proxy context maps provider ${provider} by identity, not model name`, () => {
|
||||
const selected = sessionModel(resolved, { selected: { provider, model } }, 'primary', { proxy: true });
|
||||
assert.equal(selected.proxyRoute, expected);
|
||||
assert.equal(selected.provider, provider, 'public/accounting provider identity is retained');
|
||||
assert.equal(selected.model, model);
|
||||
});
|
||||
}
|
||||
test('no proxy context preserves an arbitrary nonproxy provider and original route shape', () => {
|
||||
assert.deepEqual(sessionModel(resolved, { selected: { provider: 'custom-provider', model: 'fixture-id' } }), {
|
||||
harness: 'pi', provider: 'custom-provider', model: 'fixture-id', modelKey: 'selected', thinking: 'low',
|
||||
});
|
||||
});
|
||||
test('joined proxy context refuses unsupported provider rather than using an upstream credential or guessed API', () => {
|
||||
assert.throws(() => sessionModel(resolved, { selected: { provider: 'custom-provider', model: 'claude-looking-id' } }, 'primary', { proxy: true }), {
|
||||
code: 'proxy-provider-unsupported',
|
||||
});
|
||||
});
|
||||
test('provider proxy still requires an explicit route inside joined context', () => {
|
||||
assert.throws(() => sessionModel(resolved, { selected: { provider: 'proxy', model: 'claude-looking-id' } }, 'primary', { proxy: true }), {
|
||||
code: 'proxy-route-missing',
|
||||
});
|
||||
assert.throws(() => sessionModel(resolved, { selected: { provider: 'proxy', model: 'fixture', route: 'custom' } }, 'primary', { proxy: true }), {
|
||||
code: 'proxy-route-unknown',
|
||||
});
|
||||
assert.equal(sessionModel(resolved, { selected: { provider: 'proxy', model: 'claude-looking-id', route: 'codex' } }, 'primary', { proxy: true }).proxyRoute, 'codex');
|
||||
});
|
||||
@@ -327,3 +327,41 @@ organization file or unavailable bus.
|
||||
For the re-pin introducing this kind, Jason enables both channels through
|
||||
plugins.set immediately after activate in Mos's window, then smokes CLI thread
|
||||
listing and Console chat. No development seat performs that live step.
|
||||
|
||||
## Per-session proxy context (P3)
|
||||
|
||||
The launcher's injected `proxy` is either a `{ baseUrl, key }` context supplied by
|
||||
P2, or a stand-in factory receiving `{ business, instance }`. With `system.proxy`
|
||||
enabled, the real launch uses only the trusted host's `modelPreflight` result;
|
||||
the stand-in option cannot override it. Metadata is checked before acquisition,
|
||||
then the single admitted context reaches final harness preflight, bundle and
|
||||
spawn. Its key id is retained for P2 ownership, binding and stall monitoring.
|
||||
P3 does not issue or revoke keys. No context means existing nonproxy routing
|
||||
and environment behavior; a selected proxy model without context refuses.
|
||||
|
||||
The harness `preflight`, `bundle` and `env` calls receive an optional `proxy`
|
||||
argument; `bundle` and `env` also receive the declared model table. In proxy
|
||||
mode the launcher removes instance provider variables, then separates the
|
||||
harness's credential variables from `harnessEnv` before writing `session.json`.
|
||||
Only the spawned runner's environment receives those variables.
|
||||
|
||||
A proxy `launch.models` entry requires `route: anthropic|glm|codex`. Omission
|
||||
refuses `proxy-route-missing`; unknown routes refuse `proxy-route-unknown`. Other providers
|
||||
retain provider/model-only entries. `launch.account.credential: proxy` names the
|
||||
proxy credential source. Pi needs its own provider key or a supplied proxy key;
|
||||
Claude OAuth alone cannot satisfy pi preflight.
|
||||
|
||||
Inside an actual proxy context, existing provider `anthropic` selects messages
|
||||
and `zai` selects GLM completions. This uses provider identity only, preserving
|
||||
the declared provider for accounting. Unsupported provider identities refuse
|
||||
`proxy-provider-unsupported` before launch rather than trying a fallback or an
|
||||
upstream credential. A `proxy` entry still needs its explicit route.
|
||||
|
||||
Pi writes private, fresh run-local `home/.pi/agent/models.json`, with
|
||||
`$ANTHROPIC_API_KEY` references. Anthropic uses messages at the proxy root; GLM
|
||||
uses completions at `/v1` with z.ai compatibility fields. GPT uses the stack-owned
|
||||
`mosaic-proxy-codex` provider, never pi's Codex OAuth provider. Its build-time API
|
||||
value is `openai-responses` per Sage's sage-4331 ruling: both shapes passed the
|
||||
pinned offline probe, so this is a reasoning-based tie-break rather than an
|
||||
evidence-decided pick. Row209 phase A step7 verifies the first real Codex turn.
|
||||
There is no runtime API selection or fallback.
|
||||
@@ -53,8 +53,8 @@ function binary(env) {
|
||||
}
|
||||
|
||||
// A session needs a credential from the host's environment and the binary it runs.
|
||||
export function preflight({ env }) {
|
||||
if (!hasSessionCredential(env)) {
|
||||
export function preflight({ env, proxy = null }) {
|
||||
if (!(typeof proxy?.key === "string" && proxy.key) && !hasSessionCredential(env)) {
|
||||
const names = SESSION_CREDENTIALS.map((set) => set.join(" with ")).join(", ");
|
||||
return { code: "no-session-credential", message: `the bus host has none of ${names}; the bus unit's EnvironmentFile sets one when the bus starts` };
|
||||
}
|
||||
@@ -116,12 +116,13 @@ export function bundle({ dir, files: core, session, write, quote }) {
|
||||
return { files, digests, sources: { claudeGate: GATE, mcpServer: MCP_SERVER, ...UNSLOP } };
|
||||
}
|
||||
|
||||
export function env({ files, policy, session }) {
|
||||
export function env({ files, policy, session, proxy = null }) {
|
||||
return {
|
||||
MOSAIC_TOOLS: claudeBuiltins(policy).join(","),
|
||||
MOSAIC_CLAUDE_SETTINGS: files.settings,
|
||||
MOSAIC_CLAUDE_MCP_CONFIG: files.mcp,
|
||||
MOSAIC_THINKING: session.thinking,
|
||||
...(proxy ? { ANTHROPIC_BASE_URL: proxy.baseUrl, ANTHROPIC_AUTH_TOKEN: proxy.key } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3,15 +3,21 @@
|
||||
// Pi extension, which stays in packages/harness (a module can't change that boundary). The
|
||||
// launcher, the bundle and the usage reader call these on the host; the runner gets the answers
|
||||
// as data in session.json. packages/plugins/README.md lists the interface.
|
||||
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { proxyRouteFor } from "../../../harness/src/bundle.mjs";
|
||||
|
||||
export const interfaceVersion = 1;
|
||||
|
||||
const REPO = fileURLToPath(new URL("../../../../", import.meta.url));
|
||||
const PACKAGE = "@earendil-works/pi-coding-agent";
|
||||
const BIN = join(REPO, "node_modules", ".bin", "pi");
|
||||
// Sage sage-4331: reasoning-based tie-break; both pinned-proxy shapes passed.
|
||||
// First real Codex verification remains row209 phase A step7. No runtime switch.
|
||||
const PROXY_CODEX_API = "openai-responses";
|
||||
const PROXY_PROVIDERS = Object.freeze({ anthropic: "anthropic", glm: "mosaic-proxy-glm", codex: "mosaic-proxy-codex" });
|
||||
const EXTENSION = fileURLToPath(new URL("../../../harness/src/pi-extension.mjs", import.meta.url));
|
||||
// Row 66 (#1559): the unslop check, loaded as a second extension. It logs to MOSAIC_UNSLOP_LOG,
|
||||
// which the runner sets, and the runner tells the operator.
|
||||
@@ -30,7 +36,11 @@ export const adapter = () => join(REPO, "adapters", "pi", "adapter.sh");
|
||||
export const levels = () => LEVELS;
|
||||
|
||||
// The session runs pi from the repository's node_modules, which the sandbox mounts.
|
||||
export function preflight() {
|
||||
export function preflight({ env = {}, proxy = null } = {}) {
|
||||
if (!(typeof proxy?.key === "string" && proxy.key)
|
||||
&& !["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY", "ZAI_API_KEY"].some(name => Boolean(env[name]))) {
|
||||
return { code: "no-session-credential", message: "pi needs its own provider key or a session proxy key" };
|
||||
}
|
||||
if (!existsSync(BIN)) return { code: "harness-binary-missing", message: `pi isn't installed at ${BIN}; run npm ci in the repository` };
|
||||
return null;
|
||||
}
|
||||
@@ -57,16 +67,51 @@ export const builtins = ({ tools }) => [...tools];
|
||||
export const typedName = (name) => name;
|
||||
export const reliesOn = () => RELIES_ON;
|
||||
export const gateTimeout = () => null;
|
||||
export const bundle = () => ({ files: {}, digests: [], sources: { piExtension: EXTENSION, ...UNSLOP } });
|
||||
export function bundle({ dir, models, proxy = null }) {
|
||||
const sources = { piExtension: EXTENSION, ...UNSLOP };
|
||||
if (!proxy) return { files: {}, digests: [], sources };
|
||||
const providers = {};
|
||||
for (const entry of Object.values(models ?? {})) {
|
||||
const route = proxyRouteFor(entry);
|
||||
if (!Object.hasOwn(PROXY_PROVIDERS, route)) throw new Error("proxy model has no supported route");
|
||||
const provider = PROXY_PROVIDERS[route];
|
||||
if (typeof entry.model !== "string" || !entry.model || entry.model.startsWith("!")) throw new Error("unsafe proxy model id");
|
||||
const api = route === "anthropic" ? "anthropic-messages"
|
||||
: route === "glm" ? "openai-completions" : PROXY_CODEX_API;
|
||||
providers[provider] ??= {
|
||||
baseUrl: proxy.baseUrl + (route === "anthropic" ? "" : "/v1"),
|
||||
api, apiKey: "$ANTHROPIC_API_KEY",
|
||||
...(route === "glm" ? { compat: { thinkingFormat: "zai", zaiToolStream: true } } : {}),
|
||||
models: [],
|
||||
};
|
||||
if (!providers[provider].models.some(model => model.id === entry.model)) {
|
||||
providers[provider].models.push({ id: entry.model, reasoning: true });
|
||||
}
|
||||
}
|
||||
const text = JSON.stringify({ providers }, null, 2) + "\n";
|
||||
// Even an accidental collision between a configured model id and the key fails closed.
|
||||
if (typeof proxy.key !== "string" || !proxy.key || text.includes(proxy.key)) throw new Error("unsafe proxy model configuration");
|
||||
const runDir = dirname(dir);
|
||||
for (const part of ["home", "home/.pi", "home/.pi/agent"]) {
|
||||
const path = join(runDir, part);
|
||||
mkdirSync(path, { recursive: true, mode: 0o700 });
|
||||
const stat = lstatSync(path);
|
||||
if (!stat.isDirectory() || (stat.mode & 0o777) !== 0o700) throw new Error("pi proxy config needs private run-local directories");
|
||||
}
|
||||
const file = join(runDir, "home", ".pi", "agent", "models.json");
|
||||
writeFileSync(file, text, { mode: 0o600, flag: "wx" });
|
||||
return { files: { proxyModels: file }, digests: [["../home/.pi/agent/models.json", createHash("sha256").update(text).digest("hex")]], sources };
|
||||
}
|
||||
|
||||
// The tool limit is the built-ins plus the typed tools, which the extension serves.
|
||||
export function env({ policy, tools, session }) {
|
||||
export function env({ policy, tools, session, proxy = null }) {
|
||||
return {
|
||||
MOSAIC_TOOLS: [...policy.tools, ...tools.map((t) => t.name)].join(","),
|
||||
MOSAIC_EXTENSIONS: [EXTENSION, UNSLOP.unslopExtension].join(","),
|
||||
PI_PROVIDER: session.provider ?? "",
|
||||
PI_PROVIDER: proxy ? PROXY_PROVIDERS[session.proxyRoute] : session.provider ?? "",
|
||||
PI_MODEL: session.model,
|
||||
MOSAIC_THINKING: session.thinking,
|
||||
...(proxy ? { ANTHROPIC_API_KEY: proxy.key } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -97,9 +97,9 @@ test("row 65 claude-code version asks MOSAIC_CLAUDE_BIN when set, else claude on
|
||||
assert.equal(claude.version({ env: { PATH: join(dir, "none") } }), null);
|
||||
});
|
||||
|
||||
test("row 65 pi preflight passes with the repository's pi, and its version is the package pin", async () => {
|
||||
test("row 65 pi preflight refuses missing credentials, and its version is the package pin", async () => {
|
||||
const pi = await load("pi");
|
||||
assert.equal(pi.preflight({ env: {} }), null);
|
||||
assert.equal(pi.preflight({ env: {} }).code, "no-session-credential");
|
||||
const pkg = JSON.parse(readFileSync(join(REPO, "package.json"), "utf8"));
|
||||
assert.equal(pi.version({ env: {} }), pkg.dependencies?.["@earendil-works/pi-coding-agent"] ?? pkg.devDependencies?.["@earendil-works/pi-coding-agent"]);
|
||||
// Row 66: the unslop extension's files, bound read-only at their own paths.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// P3: run real harness exports through the plug-in loader, with made-up session keys only.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createLoader } from '../src/loader.mjs';
|
||||
import { sessionEnv } from '../../seat/src/session.mjs';
|
||||
|
||||
async function harness(name) {
|
||||
const loader = createLoader({ log() {} });
|
||||
const result = await loader.load({ harness: [name] });
|
||||
assert.deepEqual(result.refused, []);
|
||||
return loader.modules('harness')[0];
|
||||
}
|
||||
function scratch(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'p332-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
return root;
|
||||
}
|
||||
const policy = { tools: [], typed: [] };
|
||||
const session = { model: 'claude-fixture', thinking: 'low' };
|
||||
|
||||
test('P3 Claude env receives the session proxy URL and key, without another agent or host credential', async () => {
|
||||
const claude = await harness('claude-code');
|
||||
const host = { CLAUDE_CODE_OAUTH_TOKEN: 'fx332-host', OPENAI_API_KEY: 'fx332-upstream' };
|
||||
for (const [run, key] of [['r332a', 'fx332-agent-a'], ['r332b', 'fx332-agent-b']]) {
|
||||
const proxy = { baseUrl: 'http://127.0.0.1:12345', key };
|
||||
const env = { ...sessionEnv(host, run, proxy), ...claude.env({ files: {}, policy, session, proxy }) };
|
||||
assert.equal(env.ANTHROPIC_BASE_URL, 'http://127.0.0.1:12345');
|
||||
assert.equal(env.ANTHROPIC_AUTH_TOKEN, key);
|
||||
assert.equal(Object.hasOwn(env, 'CLAUDE_CODE_OAUTH_TOKEN'), false);
|
||||
assert.equal(Object.hasOwn(env, 'OPENAI_API_KEY'), false);
|
||||
const other = run === 'r332a' ? 'fx332-agent-b' : 'fx332-agent-a';
|
||||
assert.ok(!Object.values(env).includes(other));
|
||||
}
|
||||
});
|
||||
|
||||
test('P3 Claude preflight accepts a proxy key without a host provider credential', async t => {
|
||||
const claude = await harness('claude-code');
|
||||
const root = scratch(t), binary = join(root, 'claude');
|
||||
writeFileSync(binary, '#!/bin/sh\nexit 0\n');
|
||||
chmodSync(binary, 0o700);
|
||||
assert.equal(claude.preflight({ env: { MOSAIC_CLAUDE_BIN: binary }, proxy: {
|
||||
baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a',
|
||||
} }), null);
|
||||
});
|
||||
|
||||
test('P3 pi refuses no-session-credential with no provider key', async () => {
|
||||
const pi = await harness('pi');
|
||||
assert.equal(pi.preflight({ env: {} })?.code, 'no-session-credential');
|
||||
});
|
||||
|
||||
test('P3 pi refuses no-session-credential with only a Claude OAuth token', async () => {
|
||||
const pi = await harness('pi');
|
||||
assert.equal(pi.preflight({ env: { CLAUDE_CODE_OAUTH_TOKEN: 'fx332-oauth' } })?.code, 'no-session-credential');
|
||||
});
|
||||
|
||||
test('P3 pi accepts its own provider key or a session proxy key', async () => {
|
||||
const pi = await harness('pi');
|
||||
for (const name of ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'ZAI_API_KEY']) {
|
||||
assert.equal(pi.preflight({ env: { [name]: 'fx332-own' } }), null, name);
|
||||
}
|
||||
assert.equal(pi.preflight({ env: {}, proxy: { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' } }), null);
|
||||
});
|
||||
@@ -253,9 +253,13 @@ export const ENV_ALLOW = Object.freeze([
|
||||
export const SESSION_CREDENTIALS = Object.freeze([["CLAUDE_CODE_OAUTH_TOKEN"], ["ANTHROPIC_API_KEY"], ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"]].map((set) => Object.freeze(set)));
|
||||
export const hasSessionCredential = (env) => SESSION_CREDENTIALS.some((set) => set.every((k) => Boolean(env[k])));
|
||||
|
||||
export function sessionEnv(env, run) {
|
||||
// Used again at the serialization boundary: provider credentials are transient.
|
||||
export const isProviderVariable = (name) => name.startsWith("ANTHROPIC_")
|
||||
|| ["CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "OPENROUTER_API_KEY", "ZAI_API_KEY"].includes(name);
|
||||
|
||||
export function sessionEnv(env, run, proxy = null) {
|
||||
const out = {};
|
||||
for (const k of ENV_ALLOW) if (env[k] !== undefined) out[k] = env[k];
|
||||
for (const k of ENV_ALLOW) if (env[k] !== undefined && !(proxy && isProviderVariable(k))) out[k] = env[k];
|
||||
out.PATH = [join(REPO, "node_modules", ".bin"), env.PATH ?? "/usr/bin:/bin"].join(":");
|
||||
out.MOSAIC_RUN_ID = run;
|
||||
return out;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// P3: catches the named OAuth-leak mutant and reuse of another session's key.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { ENV_ALLOW, sessionEnv } from '../src/session.mjs';
|
||||
|
||||
const instance = {
|
||||
HOME: '/fixture-home', USER: 'fixture', PATH: '/usr/bin', LANG: 'C',
|
||||
CLAUDE_CODE_OAUTH_TOKEN: 'fx332-oauth', ANTHROPIC_API_KEY: 'fx332-anthropic',
|
||||
ANTHROPIC_AUTH_TOKEN: 'fx332-auth', ANTHROPIC_BASE_URL: 'http://upstream.invalid',
|
||||
OPENAI_API_KEY: 'fx332-openai', OPENROUTER_API_KEY: 'fx332-router', ZAI_API_KEY: 'fx332-zai',
|
||||
MOSAIC_CLAUDE_BIN: '/fixture/claude', GITEA_TOKEN: 'fx332-gitea',
|
||||
};
|
||||
const forbidden = ['CLAUDE_CODE_OAUTH_TOKEN', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN',
|
||||
'ANTHROPIC_BASE_URL', 'OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'ZAI_API_KEY'];
|
||||
|
||||
test('P3 proxy sessionEnv removes every instance provider credential without widening ENV_ALLOW', () => {
|
||||
const original = [...ENV_ALLOW];
|
||||
const env = sessionEnv(instance, 'r332a', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' });
|
||||
for (const name of forbidden) assert.equal(Object.hasOwn(env, name), false, name);
|
||||
assert.equal(env.USER, 'fixture');
|
||||
assert.equal(env.MOSAIC_CLAUDE_BIN, '/fixture/claude');
|
||||
assert.equal(Object.hasOwn(env, 'GITEA_TOKEN'), false);
|
||||
assert.equal(env.MOSAIC_RUN_ID, 'r332a');
|
||||
assert.deepEqual([...ENV_ALLOW], original);
|
||||
});
|
||||
|
||||
test('P3 no proxy retains the full existing allowlist and run environment', () => {
|
||||
const env = sessionEnv(instance, 'r332b');
|
||||
assert.deepEqual(env, {
|
||||
HOME: '/fixture-home', USER: 'fixture', LANG: 'C',
|
||||
CLAUDE_CODE_OAUTH_TOKEN: 'fx332-oauth', ANTHROPIC_API_KEY: 'fx332-anthropic',
|
||||
ANTHROPIC_AUTH_TOKEN: 'fx332-auth', ANTHROPIC_BASE_URL: 'http://upstream.invalid',
|
||||
OPENAI_API_KEY: 'fx332-openai', OPENROUTER_API_KEY: 'fx332-router', ZAI_API_KEY: 'fx332-zai',
|
||||
MOSAIC_CLAUDE_BIN: '/fixture/claude', PATH: env.PATH, MOSAIC_RUN_ID: 'r332b',
|
||||
});
|
||||
assert.ok(env.PATH.endsWith('node_modules/.bin:/usr/bin'));
|
||||
});
|
||||
Reference in new issue
Block a user