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();