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
@@ -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);
|
||||
});
|
||||
Reference in new issue
Block a user