Multiplayer agent harness for work.
Individual model auth: per-user Claude/ChatGPT accounts drive each turn (#707)
Sina Matian23e537334f36
diff --git a/.codex/skills/dev-instance/SKILL.md b/.codex/skills/dev-instance/SKILL.mdindex 6f1c1b655..3bcf5ba14 100644--- a/.codex/skills/dev-instance/SKILL.md+++ b/.codex/skills/dev-instance/SKILL.md@@ -119,8 +119,14 @@ The dev instance should exercise the real system:- real LLM: needs a model credential for the harness you run. Core supports several(`HARNESS=pi|opencode|codex|claude`); the launcher picks one from the credentials it- finds and honours an explicit `HARNESS`. Set the key your chosen harness expects, or- pass `DEV_INSTANCE_ALLOW_MOCK=1` for a deliberate no-model wiring check+ finds and honours an explicit `HARNESS`. Set the key your chosen harness expects. For+ Codex, a ChatGPT OAuth session is also supported: `HARNESS=codex` discovers a valid+ `$HOME/.codex/auth.json`, or you can set `CODEX_AUTH_FILE` to another auth file. Core+ refreshes OAuth tokens centrally and hands the Codex child ephemeral material (no+ refresh token). Pass `DEV_INSTANCE_ALLOW_MOCK=1` for a deliberate no-model wiring+ check. The auth-file path is for local dev instances; deployed production processes+ use an API key or a keychain credential (`CODEX_AUTH_CREDENTIAL` /+ `CLAUDE_AUTH_CREDENTIAL`), whose secret lives encrypted in its owner's keychain.- real durability: uses `DATABASE_URL` when supplied; otherwise starts/reuses a localDocker Postgres container and runs core with `SESSION_STORE=postgres` and`RUN_STORE=postgres`diff --git a/.env.example b/.env.exampleindex b5d83f83a..7fb0a747f 100644--- a/.env.example+++ b/.env.example@@ -1,5 +1,13 @@HARNESS=pi+# Subscription-backed harness auth. Production path: point at a keychain+# credential id (the login lives encrypted in its owner's keychain; core+# refreshes it centrally and hands harnesses ephemeral derived material).+#CODEX_AUTH_CREDENTIAL=+#CLAUDE_AUTH_CREDENTIAL=+# Local-dev fallback only: a Codex CLI auth.json on this machine+# (defaults to ~/.codex/auth.json when HARNESS=codex). Not allowed in production.+CODEX_AUTH_FILE=HARNESS_SECURITY_POSTURE=auto#ANTHROPIC_API_KEY=sk-ant-...diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex becbb6f75..161c64c20 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -4397,6 +4397,30 @@><span class="status" id="st-interactive-fast-mode"></span></div></section>+ <section class="card setting-row hidden" id="card-individual-model-auth">+ <div class="head">+ <h2>Individual authorization for AI usage</h2>+ <p>+ Org-wide, default off. When on, each user must connect their own Claude or Codex account (API key+ or subscription login) before using the assistant. The org's shared model credentials are not used+ for their turns.+ </p>+ </div>+ <div class="body">+ <label class="setting-toggle">+ <input type="checkbox" id="individual-model-auth" />+ <span class="setting-switch" aria-hidden="true"></span>+ <span class="setting-copy"+ ><strong>Require each user to connect their own model account</strong+ ><small>New users are prompted to sign in with Claude or Codex on first use.</small></span+ >+ </label>+ </div>+ <div class="foot">+ <button class="primary" data-save="individual-model-auth">Apply</button+ ><span class="status" id="st-individual-model-auth"></span>+ </div>+ </section><section class="card setting-row hidden" id="card-base-model"><div class="head"><h2>Default harness and model</h2>@@ -6427,6 +6451,9 @@const showInteractiveFastMode = scope.startsWith("org:") && "interactiveFastMode" in r.data;$("card-interactive-fast-mode").classList.toggle("hidden", !showInteractiveFastMode);if (showInteractiveFastMode) $("interactive-fast-mode").checked = r.data.interactiveFastMode === true;+ const showIndividualModelAuth = scope.startsWith("org:") && "individualModelAuth" in r.data;+ $("card-individual-model-auth").classList.toggle("hidden", !showIndividualModelAuth);+ if (showIndividualModelAuth) $("individual-model-auth").checked = r.data.individualModelAuth === true;const showHeaderPinDefault = scope.startsWith("org:") && "channelHeaderPinDefault" in r.data;$("card-channel-header-pin-default").classList.toggle("hidden", !showHeaderPinDefault);if (showHeaderPinDefault) $("channel-header-pin-default").checked = !!r.data.channelHeaderPinDefault;@@ -7253,19 +7280,20 @@const baseModel = config.data.baseModel || config.data.baseModelDefault || "";const baseProvider = onboardingProviderForModel(baseModel);const baseStatus = onboardingModelStatuses.find((item) => item.provider === baseProvider);- onboardingBadge(- "onboarding-model-badge",- baseStatus?.configured ? "Ready" : "Needs a key",- Boolean(baseStatus?.configured),- );+ const harnessAuth = models.data.harnessAuth;+ const baseHarnessAuth = Boolean(harnessAuth && harnessAuth.provider === baseProvider);+ const baseReady = Boolean(baseModel) && (Boolean(baseStatus?.configured) || baseHarnessAuth);+ onboardingBadge("onboarding-model-badge", baseReady ? "Ready" : "Needs a key", baseReady);$("onboarding-model-summary").textContent = !baseModel? "No base model is configured yet — pick a provider and model below.": baseStatus?.configured? baseModel + " · " + (baseStatus.source === "admin" ? "admin-managed key" : "deployment key")- : baseModel +- " cannot run until its " +- (MODEL_PROVIDER_LABELS[baseProvider] || connectorName(baseProvider)) +- " key is configured.";+ : baseHarnessAuth+ ? baseModel + " · authenticated by the " + harnessAuth.harnessId + " harness — no API key needed."+ : baseModel ++ " cannot run until its " ++ (MODEL_PROVIDER_LABELS[baseProvider] || connectorName(baseProvider)) ++ " key is configured.";renderOnboardingProviderOptions(baseProvider);renderOnboardingModelOptions(baseModel);@@ -8140,6 +8168,7 @@"external-slack-participants": () => ({ on: $("external-slack-participants").checked }),"org-ambient": () => ({ on: $("org-ambient").checked }),"interactive-fast-mode": () => ({ on: $("interactive-fast-mode").checked }),+ "individual-model-auth": () => ({ on: $("individual-model-auth").checked }),"channel-header-pin-default": () => ({ on: $("channel-header-pin-default").checked }),runtime: () => ({ harnessId: $("base-harness").value, modelId: $("base-model").value }),"approved-harnesses": () => ({@@ -8175,6 +8204,7 @@"external-slack-participants": "st-external-slack-participants","org-ambient": "st-org-ambient","interactive-fast-mode": "st-interactive-fast-mode",+ "individual-model-auth": "st-individual-model-auth","channel-header-pin-default": "st-channel-header-pin-default",runtime: "st-runtime","approved-harnesses": "st-approved-harnesses",diff --git a/plugins/admin/test/onboarding-view.test.ts b/plugins/admin/test/onboarding-view.test.tsindex c7fe9b4fc..406390c21 100644--- a/plugins/admin/test/onboarding-view.test.ts+++ b/plugins/admin/test/onboarding-view.test.ts@@ -28,6 +28,98 @@ function resolveView(pathname: string, search: string): string {return vm.runInContext(src, context);}+interface FakeElement {+ textContent: string;+ className: string;+ value: string;+ placeholder: string;+ disabled: boolean;+ href: string;+ options: Array<{ value?: string; textContent?: string }>;+ appendChild(option: { value?: string; textContent?: string }): void;+}++async function runLoadOnboarding(modelProviders: unknown): Promise<Record<string, FakeElement>> {+ const src = slice("let onboardingModels = {};", '$("onboarding-model-provider").onchange') + "\nloadOnboarding();";+ const elements: Record<string, FakeElement> = {};+ const fixtures: Record<string, unknown> = {+ "/api/model-providers": modelProviders,+ "/api/slack-installation": { configured: false },+ "/api/connector-catalog": { catalog: [] },+ "/api/scopes/org%3Adefault-org": { baseModel: "claude-opus-5" },+ };+ const context = vm.createContext({+ $: (id: string) =>+ (elements[id] ??= {+ textContent: "",+ className: "",+ value: "",+ placeholder: "",+ disabled: false,+ href: "",+ options: [],+ appendChild(option) {+ this.options.push(option);+ },+ }),+ api: async (_method: string, path: string) => ({ ok: true, data: fixtures[path] ?? {} }),+ orgScope: () => "org:default-org",+ encodeURIComponent,+ setStatus: () => {},+ connectorName: (id: string) => id,+ viewLoadedAt: {},+ Date,+ document: { createElement: () => ({}) },+ });+ await vm.runInContext(src, context);+ return elements;+}++const UNCONFIGURED_PROVIDERS = [+ { provider: "anthropic", configured: false, source: "absent" },+ { provider: "openai", configured: false, source: "absent" },+ { provider: "openrouter", configured: false, source: "absent" },+];+const ANTHROPIC_MODELS = [{ id: "claude-opus-5", name: "Claude Opus 5", provider: "anthropic" }];++test("harness-carried auth shows the model step as ready without a stored key", async () => {+ const elements = await runLoadOnboarding({+ providers: UNCONFIGURED_PROVIDERS,+ models: ANTHROPIC_MODELS,+ harnessAuth: { harnessId: "claude", provider: "anthropic" },+ });+ assert.equal(elements["onboarding-model-badge"]!.textContent, "Ready");+ assert.equal(elements["onboarding-model-badge"]!.className, "badge ok");+ assert.equal(+ elements["onboarding-model-summary"]!.textContent,+ "claude-opus-5 · authenticated by the claude harness — no API key needed.",+ );+});++test("without harness auth an unconfigured provider still needs a key", async () => {+ const elements = await runLoadOnboarding({+ providers: UNCONFIGURED_PROVIDERS,+ models: ANTHROPIC_MODELS,+ });+ assert.equal(elements["onboarding-model-badge"]!.textContent, "Needs a key");+ assert.equal(elements["onboarding-model-badge"]!.className, "badge warn");+ assert.match(elements["onboarding-model-summary"]!.textContent, /cannot run until its Anthropic key is configured/);+});++test("a stored key keeps its summary even when the harness also carries auth", async () => {+ const elements = await runLoadOnboarding({+ providers: [+ { provider: "anthropic", configured: true, source: "admin" },+ { provider: "openai", configured: false, source: "absent" },+ { provider: "openrouter", configured: false, source: "absent" },+ ],+ models: ANTHROPIC_MODELS,+ harnessAuth: { harnessId: "claude", provider: "anthropic" },+ });+ assert.equal(elements["onboarding-model-badge"]!.textContent, "Ready");+ assert.equal(elements["onboarding-model-summary"]!.textContent, "claude-opus-5 · admin-managed key");+});+test("onboarding is a navigable view", () => {assert.match(html, /\{ label: "Admin", views: \["onboarding",/);});diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex 3bc374989..389ebb386 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -805,14 +805,32 @@ const apiRoutes: readonly WebRoute[] = [handle: async (c) => {const { req, res, user } = c;res.setHeader("set-cookie", sessionCookie(user));- const permissions = await userPermissions();+ const [permissions, workspaceUrl, authStatus] = await Promise.all([+ userPermissions(),+ slackWorkspaceUrl(),+ coreFetch("GET", `/v1/user-model-auth/status?principalId=${encodeURIComponent(user)}`, "", 5_000).catch(+ () => null,+ ),+ ]);+ if (authStatus === null || authStatus.status !== 200) {+ return json(res, 503, {+ error: "unavailable",+ message: "the assistant is briefly unavailable — retry shortly",+ });+ }+ const parsed = JSON.parse(authStatus.text) as {+ individualModelAuth?: boolean;+ connections?: { provider: string }[];+ };return json(res, 200, {user,org: ORG,mode: AUTH_MODE,- slackWorkspaceUrl: await slackWorkspaceUrl(),+ slackWorkspaceUrl: workspaceUrl,impersonatedBy: resolveIdentity(req)?.impersonator ?? null,permissions,+ individualModelAuth: parsed.individualModelAuth === true,+ modelAuthConnected: (parsed.connections?.length ?? 0) > 0,});},},@@ -1455,6 +1473,64 @@ const apiRoutes: readonly WebRoute[] = [return relayCore(res, "GET", `/v1/connectors/oauth/status?principalId=${encodeURIComponent(user)}`);},},+ {+ method: "GET",+ path: "/api/user-model-auth/status",+ handle: async (c) =>+ relayCore(c.res, "GET", `/v1/user-model-auth/status?principalId=${encodeURIComponent(c.user)}`),+ },+ {+ method: "POST",+ path: "/api/user-model-auth/api-key",+ handle: async (c) => {+ const p = JSON.parse((await readBody(c.req)) || "{}") as { provider?: unknown; apiKey?: unknown };+ const body = JSON.stringify({ principalId: c.user, provider: p.provider, apiKey: p.apiKey });+ return relayCore(c.res, "POST", "/v1/user-model-auth/api-key", body);+ },+ },+ {+ method: "POST",+ path: "/api/user-model-auth/disconnect",+ handle: async (c) => {+ const p = JSON.parse((await readBody(c.req)) || "{}") as { provider?: unknown };+ return relayCore(+ c.res,+ "POST",+ "/v1/user-model-auth/disconnect",+ JSON.stringify({ principalId: c.user, provider: p.provider }),+ );+ },+ },+ {+ method: "POST",+ path: "/api/user-model-auth/chatgpt/start",+ handle: async (c) =>+ relayCore(c.res, "POST", "/v1/user-model-auth/chatgpt/start", JSON.stringify({ principalId: c.user })),+ },+ {+ method: "POST",+ path: "/api/user-model-auth/chatgpt/poll",+ handle: async (c) => {+ const p = JSON.parse((await readBody(c.req)) || "{}") as { deviceAuthId?: unknown; userCode?: unknown };+ const body = JSON.stringify({ principalId: c.user, deviceAuthId: p.deviceAuthId, userCode: p.userCode });+ return relayCore(c.res, "POST", "/v1/user-model-auth/chatgpt/poll", body);+ },+ },+ {+ method: "POST",+ path: "/api/user-model-auth/claude/start",+ handle: async (c) =>+ relayCore(c.res, "POST", "/v1/user-model-auth/claude/start", JSON.stringify({ principalId: c.user })),+ },+ {+ method: "POST",+ path: "/api/user-model-auth/claude/complete",+ handle: async (c) => {+ const p = JSON.parse((await readBody(c.req)) || "{}") as { code?: unknown; verifier?: unknown };+ const body = JSON.stringify({ principalId: c.user, code: p.code, verifier: p.verifier });+ return relayCore(c.res, "POST", "/v1/user-model-auth/claude/complete", body);+ },+ },{method: "POST",path: "/api/connectors/:provider/start",diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.tsindex 5e28600d1..c757ee01b 100644--- a/plugins/web-ui/src/composer.ts+++ b/plugins/web-ui/src/composer.ts@@ -409,6 +409,68 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {} else if (composerState.error) {composerNotice = html`<div class="composer-error">${composerState.error}</div>`;}+ let runtimeControls: TemplateResult | typeof nothing = nothing;+ if (!appState.me?.individualModelAuth) {+ runtimeControls = ctx.pane+ ? settingsControl(agent, selectedModel, inputBlocked)+ : html`+ ${+ runtimeToggled+ ? html`<button+ class="runtime-default-btn"+ type="button"+ aria-label="Make default"+ data-mobile-label="Default"+ title="Use this harness, model, effort, and fast setting as the default for this scope"+ ?disabled=${inputBlocked}+ @click=${() => changeScopeRuntime({ harnessId: selectedModel.harnessId, modelId: selectedModel.model.id, effortLevel: composerState.effortLevel, fastMode: fastOn }, agent)}+ >+ Make default+ </button>`+ : nothing+ }+ ${+ runtimeToggled && activeRuntimeConfig?.scopeOverride+ ? html`<button+ class="runtime-default-btn"+ type="button"+ aria-label="Use org default"+ data-mobile-label="Org default"+ ?disabled=${inputBlocked}+ @click=${() => changeScopeRuntime({ inherit: true }, agent)}+ >+ Use org default+ </button>`+ : nothing+ }+ ${menuControl({+ kind: "model",+ label: selectedModel.buttonLabel,+ suffix: `· ${effortLabel(composerState.effortLevel)}`,+ title: "Model",+ selected: selectedModel.value,+ align: "right",+ searchable: true,+ options: getModelOptionsForHarness(selectedModel.harnessId, scopeKey()).map((option) => ({+ value: option.value,+ label: option.label,+ groupLabel: option.groupLabel,+ })),+ disabled: inputBlocked,+ onSelect: (value: string) => selectModel(value, agent),+ })}+ ${menuControl({+ kind: "harness",+ label: selectedModel.harnessLabel,+ title: "Harness",+ selected: selectedModel.harnessId,+ align: "right",+ options: getHarnessOptions(scopeKey()),+ disabled: inputBlocked,+ onSelect: (value: string) => selectHarness(value, agent),+ })}+ `;+ }return html`<form class="composer-wrap" @submit=${(e: Event) => submitComposer(e, agent)}>${slashMenu(agent)}@@ -545,70 +607,7 @@ export function createComposerSurface(ctx: ConvCtx): ComposerSurface {`}</div>- <div class="composer-right">- ${- ctx.pane- ? settingsControl(agent, selectedModel, inputBlocked)- : html`- ${- runtimeToggled- ? html`<button- class="runtime-default-btn"- type="button"- aria-label="Make default"- data-mobile-label="Default"- title="Use this harness, model, effort, and fast setting as the default for this scope"- ?disabled=${inputBlocked}- @click=${() => changeScopeRuntime({ harnessId: selectedModel.harnessId, modelId: selectedModel.model.id, effortLevel: composerState.effortLevel, fastMode: fastOn }, agent)}- >- Make default- </button>`- : nothing- }- ${- runtimeToggled && activeRuntimeConfig?.scopeOverride- ? html`<button- class="runtime-default-btn"- type="button"- aria-label="Use org default"- data-mobile-label="Org default"- ?disabled=${inputBlocked}- @click=${() => changeScopeRuntime({ inherit: true }, agent)}- >- Use org default- </button>`- : nothing- }- ${menuControl({- kind: "model",- label: selectedModel.buttonLabel,- suffix: `· ${effortLabel(composerState.effortLevel)}`,- title: "Model",- selected: selectedModel.value,- align: "right",- searchable: true,- options: getModelOptionsForHarness(selectedModel.harnessId, scopeKey()).map((option) => ({- value: option.value,- label: option.label,- groupLabel: option.groupLabel,- })),- disabled: inputBlocked,- onSelect: (value: string) => selectModel(value, agent),- })}- ${menuControl({- kind: "harness",- label: selectedModel.harnessLabel,- title: "Harness",- selected: selectedModel.harnessId,- align: "right",- options: getHarnessOptions(scopeKey()),- disabled: inputBlocked,- onSelect: (value: string) => selectHarness(value, agent),- })}- `- }- ${sendControls(agent)}- </div>+ <div class="composer-right">${runtimeControls} ${sendControls(agent)}</div></div>${composerNotice}</form>diff --git a/plugins/web-ui/src/model-connect.ts b/plugins/web-ui/src/model-connect.tsnew file mode 100644index 000000000..6821cc948--- /dev/null+++ b/plugins/web-ui/src/model-connect.ts@@ -0,0 +1,531 @@+import { html, render, nothing, type TemplateResult } from "lit";+import { api } from "./core-bridge";+import { errMessage } from "../../chassis/src/errors";+import { brandMark, brandName } from "./ui";++type ProviderKey = "claude" | "chatgpt";+type ConnKind = "apikey" | "oauth";++interface ProviderMeta {+ key: ProviderKey;+ name: string;+ apiName: "anthropic" | "openai";+ mark: TemplateResult;+ markClass: string;+ keyPlaceholder: string;+ subscription: string;+ keyConsole: string;+ keyConsoleUrl: string;+}++const ANTHROPIC_MARK = html`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true">+ <path+ d="M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5527h3.7442L10.5363 3.541Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z"+ />+</svg>`;++const OPENAI_MARK = html`<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true">+ <path+ d="M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.073zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.8956zm16.5963 3.8558-5.8334-3.3874L15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654 2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z"+ />+</svg>`;++const PROVIDERS: ProviderMeta[] = [+ {+ key: "claude",+ name: "Claude",+ apiName: "anthropic",+ mark: ANTHROPIC_MARK,+ markClass: "mc-mark-claude",+ keyPlaceholder: "sk-ant-…",+ subscription: "Claude Pro or Max",+ keyConsole: "platform.claude.com",+ keyConsoleUrl: "https://platform.claude.com",+ },+ {+ key: "chatgpt",+ name: "ChatGPT",+ apiName: "openai",+ mark: OPENAI_MARK,+ markClass: "mc-mark-chatgpt",+ keyPlaceholder: "sk-…",+ subscription: "ChatGPT Plus or Pro",+ keyConsole: "platform.openai.com",+ keyConsoleUrl: "https://platform.openai.com",+ },+];++interface DevicePrompt {+ deviceAuthId: string;+ userCode: string;+ verificationUrl: string;+ intervalMs: number;+ expiresAt: number;+}++interface StatusResponse {+ individualModelAuth: boolean;+ connections: { provider: "anthropic" | "openai"; kind: ConnKind }[];+}++type Mode = "gate" | "manager";+type Method = "subscription" | "apikey";+type Flow =+ | { kind: "pick" }+ | { kind: "claude"; authorizeUrl: string; verifier: string; code: string }+ | { kind: "chatgpt"; device: DevicePrompt }+ | { kind: "apikey"; value: string };++interface State {+ mode: Mode;+ required: boolean;+ loading: boolean;+ error: string;+ busy: boolean;+ connections: Partial<Record<ProviderKey, ConnKind>>;+ open: ProviderKey | null;+ method: Method | null;+ flow: Flow;+ copied: boolean;+ pollTimer: ReturnType<typeof setTimeout> | null;+}++let s: State;+let overlay: HTMLElement | null = null;+let deviceCache: DevicePrompt | null = null;++function fresh(mode: Mode): State {+ return {+ mode,+ required: false,+ loading: true,+ error: "",+ busy: false,+ connections: {},+ open: null,+ method: null,+ flow: { kind: "pick" },+ copied: false,+ pollTimer: null,+ };+}++function target(): HTMLElement | null {+ return s.mode === "gate" ? document.getElementById("app") : overlay;+}++function stopPolling(): void {+ if (s.pollTimer) clearTimeout(s.pollTimer);+ s.pollTimer = null;+}++function resetFlow(): void {+ stopPolling();+ s.flow = { kind: "pick" };+ s.method = null;+ s.busy = false;+ s.error = "";+}++async function load(): Promise<void> {+ s.loading = true;+ paint();+ try {+ const status = await api<StatusResponse>("/api/user-model-auth/status");+ s.required = status.individualModelAuth === true;+ s.connections = {};+ for (const c of status.connections ?? []) {+ s.connections[c.provider === "anthropic" ? "claude" : "chatgpt"] = c.kind;+ }+ s.error = "";+ } catch (e) {+ s.error = friendly(e);+ }+ s.loading = false;+ paint();+}++function friendly(e: unknown): string {+ const raw = errMessage(e);+ if (/invalid_api_key|rejected this API key/i.test(raw)) return "That API key was rejected — check it and try again.";+ if (/oauth_start_failed|oauth_poll_failed|oauth_complete_failed/i.test(raw))+ return "Sign-in didn't complete. Try again — the code may have expired.";+ if (/network|fetch failed|timeout/i.test(raw))+ return "Couldn't reach the sign-in service. Check your connection and try again.";+ return raw;+}++function afterConnect(): void {+ stopPolling();+ deviceCache = null;+ if (s.mode === "gate") {+ location.reload();+ return;+ }+ const mode = s.mode;+ s = fresh(mode);+ void load();+}++async function pickSubscription(p: ProviderMeta): Promise<void> {+ s.method = "subscription";+ s.error = "";+ s.busy = true;+ paint();+ try {+ if (p.key === "claude") {+ const start = await api<{ authorizeUrl: string; verifier: string }>("/api/user-model-auth/claude/start", {+ method: "POST",+ });+ s.flow = { kind: "claude", ...start, code: "" };+ } else {+ if (!deviceCache || deviceCache.expiresAt - 30_000 <= Date.now()) {+ deviceCache = await api<DevicePrompt>("/api/user-model-auth/chatgpt/start", { method: "POST" });+ }+ stopPolling();+ s.flow = { kind: "chatgpt", device: deviceCache };+ s.busy = false;+ paint();+ pollChatGPT();+ return;+ }+ } catch (e) {+ s.error = friendly(e);+ s.method = null;+ }+ s.busy = false;+ paint();+}++function pickApiKey(): void {+ stopPolling();+ s.method = "apikey";+ s.flow = { kind: "apikey", value: "" };+ s.error = "";+ paint();+}++async function copyCode(code: string): Promise<void> {+ try {+ await navigator.clipboard.writeText(code);+ s.copied = true;+ paint();+ setTimeout(() => {+ s.copied = false;+ paint();+ }, 1600);+ } catch {+ s.copied = false;+ }+}++async function finishClaude(): Promise<void> {+ if (s.flow.kind !== "claude" || !s.flow.code.trim() || s.busy) return;+ s.error = "";+ s.busy = true;+ paint();+ try {+ await api("/api/user-model-auth/claude/complete", {+ method: "POST",+ body: JSON.stringify({ code: s.flow.code.trim(), verifier: s.flow.verifier }),+ });+ return afterConnect();+ } catch (e) {+ s.busy = false;+ s.error = friendly(e);+ paint();+ }+}++async function pollChatGPT(): Promise<void> {+ if (s.flow.kind !== "chatgpt") return;+ const device = s.flow.device;+ if (Date.now() > device.expiresAt) {+ deviceCache = null;+ resetFlow();+ s.error = "That code expired — start the sign-in again.";+ paint();+ return;+ }+ try {+ const r = await api<{ status: string }>("/api/user-model-auth/chatgpt/poll", {+ method: "POST",+ body: JSON.stringify({ deviceAuthId: device.deviceAuthId, userCode: device.userCode }),+ });+ if (r.status === "connected") return afterConnect();+ } catch (e) {+ s.error = friendly(e);+ deviceCache = null;+ resetFlow();+ paint();+ return;+ }+ if (s.flow.kind === "chatgpt") s.pollTimer = setTimeout(pollChatGPT, device.intervalMs || 5000);+}++async function saveKey(p: ProviderMeta): Promise<void> {+ if (s.flow.kind !== "apikey" || !s.flow.value.trim() || s.busy) return;+ s.error = "";+ s.busy = true;+ paint();+ try {+ await api("/api/user-model-auth/api-key", {+ method: "POST",+ body: JSON.stringify({ provider: p.key, apiKey: s.flow.value.trim() }),+ });+ return afterConnect();+ } catch (e) {+ s.busy = false;+ s.error = friendly(e);+ paint();+ }+}++async function disconnect(p: ProviderMeta): Promise<void> {+ if (s.busy) return;+ s.error = "";+ s.busy = true;+ paint();+ try {+ await api("/api/user-model-auth/disconnect", { method: "POST", body: JSON.stringify({ provider: p.key }) });+ resetFlow();+ await load();+ } catch (e) {+ s.busy = false;+ s.error = friendly(e);+ paint();+ }+}++function methodRow(title: string, detail: string, selected: boolean, onPick: () => void): TemplateResult {+ return html`+ <button type="button" class="mc-method ${selected ? "selected" : ""}" ?disabled=${s.busy} @click=${onPick}>+ <span class="mc-method-radio" aria-hidden="true"></span>+ <span class="mc-method-text">+ <span class="mc-method-title">${title}</span>+ <span class="mc-method-detail">${detail}</span>+ </span>+ </button>+ `;+}++function claudeSteps(): TemplateResult {+ if (s.flow.kind !== "claude") return html``;+ const flow = s.flow;+ return html`+ <ol class="mc-steps">+ <li>+ <a class="btn" href=${flow.authorizeUrl} target="_blank" rel="noopener">Open claude.ai and approve ↗</a>+ </li>+ <li>+ <label class="mc-field">+ <span>Paste the code Claude shows you</span>+ <input+ .value=${flow.code}+ placeholder="Code from claude.ai"+ autocomplete="off"+ spellcheck="false"+ @input=${(e: Event) => {+ flow.code = (e.target as HTMLInputElement).value;+ paint();+ }}+ @keydown=${(e: KeyboardEvent) => e.key === "Enter" && finishClaude()}+ />+ </label>+ </li>+ <li>+ <button class="btn primary" ?disabled=${!flow.code.trim() || s.busy} @click=${finishClaude}>+ ${s.busy ? "Connecting…" : "Finish"}+ </button>+ </li>+ </ol>+ `;+}++function chatgptSteps(): TemplateResult {+ if (s.flow.kind !== "chatgpt") return html``;+ const device = s.flow.device;+ return html`+ <ol class="mc-steps">+ <li>+ <button+ type="button"+ class="mc-code-btn ${s.copied ? "copied" : ""}"+ title="Copy code to clipboard"+ @click=${() => copyCode(device.userCode)}+ >+ <span class="mc-code">${device.userCode}</span>+ <span class="mc-copy-hint">${s.copied ? "Copied ✓" : "Click to copy"}</span>+ </button>+ </li>+ <li>+ <a class="btn" href=${device.verificationUrl} target="_blank" rel="noopener">Open chatgpt.com and paste it ↗</a>+ </li>+ <li>+ <span class="mc-waiting"><span class="mc-spinner" aria-hidden="true"></span>Waiting for your approval…</span>+ </li>+ </ol>+ `;+}++function apikeySteps(p: ProviderMeta): TemplateResult {+ if (s.flow.kind !== "apikey") return html``;+ const flow = s.flow;+ return html`+ <div class="mc-keyform">+ <label class="mc-field">+ <span>API key · from <a href=${p.keyConsoleUrl} target="_blank" rel="noopener">${p.keyConsole}</a></span>+ <input+ type="password"+ .value=${flow.value}+ placeholder=${p.keyPlaceholder}+ autocomplete="off"+ @input=${(e: Event) => {+ flow.value = (e.target as HTMLInputElement).value;+ paint();+ }}+ @keydown=${(e: KeyboardEvent) => e.key === "Enter" && saveKey(p)}+ />+ </label>+ <button class="btn primary" ?disabled=${!flow.value.trim() || s.busy} @click=${() => saveKey(p)}>+ ${s.busy ? "Checking…" : "Connect"}+ </button>+ </div>+ `;+}++function connectBody(p: ProviderMeta): TemplateResult {+ let subscriptionSteps: TemplateResult | typeof nothing = nothing;+ if (s.method === "subscription") subscriptionSteps = p.key === "claude" ? claudeSteps() : chatgptSteps();+ return html`+ <div class="mc-connect">+ ${methodRow(+ `Sign in with ${p.name}`,+ `Uses your ${p.subscription} subscription — nothing extra to pay.`,+ s.method === "subscription",+ () => void pickSubscription(p),+ )}+ ${subscriptionSteps}+ ${methodRow(+ "Use an API key",+ `Paste a key from ${p.keyConsole} — usage is billed to the key.`,+ s.method === "apikey",+ pickApiKey,+ )}+ ${s.method === "apikey" ? apikeySteps(p) : nothing}+ </div>+ `;+}++function providerRow(p: ProviderMeta): TemplateResult {+ const kind = s.connections[p.key];+ const open = s.open === p.key;+ let statusLine = `Chat with ${p.name} on your own account`;+ if (kind === "oauth") statusLine = `Connected with your ${p.name} subscription`;+ else if (kind === "apikey") statusLine = "Connected with your API key";+ let action: TemplateResult | typeof nothing = nothing;+ if (kind) {+ action = html`<button class="btn mc-quiet-danger" ?disabled=${s.busy} @click=${() => disconnect(p)}>+ ${s.busy ? "…" : "Disconnect"}+ </button>`;+ } else if (!open) {+ action = html`<button+ class="btn"+ ?disabled=${s.busy}+ @click=${() => {+ resetFlow();+ s.open = p.key;+ paint();+ }}+ >+ Connect+ </button>`;+ }+ return html`+ <section class="mc-provider ${kind ? "connected" : ""} ${open ? "open" : ""}">+ <div class="mc-provider-row">+ <span class="mc-mark ${p.markClass}" aria-hidden="true">${p.mark}</span>+ <div class="mc-provider-text">+ <strong>${p.name}</strong>+ <small>${statusLine}</small>+ </div>+ ${action}+ </div>+ ${open && !kind ? connectBody(p) : nothing}+ </section>+ `;+}++function view(): TemplateResult {+ const anyConnected = Object.keys(s.connections).length > 0;+ let cta: TemplateResult | typeof nothing = nothing;+ if (anyConnected) {+ cta =+ s.mode === "gate"+ ? html`<button class="btn primary mc-cta" @click=${() => location.reload()}>Start chatting</button>`+ : html`<button class="btn primary mc-cta" @click=${closeManager}>Done</button>`;+ }+ const body = s.loading+ ? html`<div class="mc-waiting"><span class="mc-spinner" aria-hidden="true"></span>Loading…</div>`+ : html`+ ${s.error ? html`<div class="mc-error" role="alert">${s.error}</div>` : nothing}+ <div class="mc-providers">${PROVIDERS.map((p) => providerRow(p))}</div>+ ${cta}+ `;+ let subCopy = "Chats run on the account you connect here, billed to you — not the organization.";+ if (s.mode === "gate") {+ subCopy =+ "Your organization has each person chat on their own AI account. Connect one to get started — you can switch any time.";+ } else if (s.required && !s.loading && !anyConnected) {+ subCopy =+ "Chats run on the account you connect here, billed to you — not the organization. Connect at least one to keep using the assistant.";+ }+ return html`+ <div class="signin">+ <div class="signin-panel mc-panel">+ ${+ s.mode === "manager" && !anyConnected && !s.loading+ ? html`<button type="button" class="mc-close" aria-label="Close" title="Close" @click=${closeManager}>+ ×+ </button>`+ : nothing+ }+ ${s.mode === "gate" ? html`<div class="signin-brand">${brandMark()}<span>${brandName()}</span></div>` : nothing}+ <h1>${s.mode === "gate" ? "Connect your AI account" : "Your AI account"}</h1>+ <p class="signin-body">${subCopy}</p>+ ${body}+ </div>+ </div>+ `;+}++function paint(): void {+ const el = target();+ if (el) render(view(), el);+}++function closeManager(): void {+ stopPolling();+ overlay?.remove();+ overlay = null;+ if (s.required && Object.keys(s.connections).length === 0) location.reload();+}++export function renderModelConnectGate(): void {+ s = fresh("gate");+ paint();+ void load();+}++export function openModelConnectManager(): void {+ if (overlay) return;+ overlay = document.createElement("div");+ overlay.className = "mc-overlay";+ overlay.addEventListener("click", (e) => {+ if (e.target === overlay) closeManager();+ });+ document.body.appendChild(overlay);+ s = fresh("manager");+ paint();+ void load();+}diff --git a/plugins/web-ui/src/shell-state.ts b/plugins/web-ui/src/shell-state.tsindex 0fbc99e52..ba9c273eb 100644--- a/plugins/web-ui/src/shell-state.ts+++ b/plugins/web-ui/src/shell-state.ts@@ -7,6 +7,8 @@ export interface Me {slackWorkspaceUrl?: string | null;impersonatedBy?: string | null;permissions?: string[];+ individualModelAuth?: boolean;+ modelAuthConnected?: boolean;}const VIEWS = ["chats", "contexts", "webhooks", "crons", "files", "keychain", "deploys", "memory", "skills"] as const;diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 109768e8a..c8099a131 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -7659,3 +7659,321 @@ h3.ambient-field-label {height: 22px;border-radius: 6px;}++.mc-panel {+ width: 520px;+ gap: 6px;+}+.mc-panel .signin-body {+ margin-bottom: 14px;+}+.mc-overlay {+ position: fixed;+ inset: 0;+ background: color-mix(in srgb, var(--foreground) 24%, transparent);+ z-index: 1000;+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: auto;+}+.mc-overlay .signin {+ height: auto;+ min-height: 0;+ padding: 32px 24px;+}+.mc-overlay .signin-panel {+ background: var(--background);+ border: 1px solid var(--border);+ border-radius: var(--radius-lg);+ padding: 28px;+}+.mc-providers {+ display: flex;+ flex-direction: column;+ gap: 12px;+}+.mc-provider {+ border: 1px solid var(--border);+ border-radius: 12px;+ background: var(--secondary);+ transition:+ border-color 140ms ease,+ background 140ms ease;+}+.mc-provider.connected {+ border-color: color-mix(in srgb, #1a7f37 40%, var(--border));+ background: color-mix(in srgb, #1a7f37 8%, var(--secondary));+}+.mc-provider.open {+ background: var(--background);+ border-color: var(--muted-foreground);+}+.mc-provider-row {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 14px 16px;+}+.mc-mark {+ flex: none;+ width: 34px;+ height: 34px;+ border-radius: var(--radius-sm);+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 15px;+ font-weight: 700;+ color: #fff;+}+.mc-mark-claude {+ background: #d97757;+}+.mc-mark-chatgpt {+ background: #10a37f;+}+.mc-provider-text {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ line-height: 1.35;+}+.mc-provider-text strong {+ font-size: 14px;+ font-weight: 600;+}+.mc-provider-text small {+ font-size: 12.5px;+ color: var(--muted-foreground);+}+.mc-provider.connected .mc-provider-text small {+ color: color-mix(in srgb, #1a7f37 75%, var(--foreground));+}+.mc-quiet-danger {+ color: var(--destructive, #b42318);+}+.mc-quiet-danger:hover {+ border-color: var(--destructive, #b42318);+ background: color-mix(in srgb, var(--destructive, #b42318) 6%, var(--background));+}+.mc-connect {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 2px 16px 16px;+}+.mc-method {+ display: flex;+ align-items: flex-start;+ gap: 11px;+ text-align: left;+ font: inherit;+ padding: 12px 14px;+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ background: var(--background);+ color: var(--foreground);+ cursor: pointer;+ transition: border-color 140ms ease;+}+.mc-method:hover {+ border-color: var(--muted-foreground);+}+.mc-method.selected {+ border-color: var(--foreground);+}+.mc-method:disabled {+ opacity: 0.6;+ cursor: default;+}+.mc-method-radio {+ flex: none;+ width: 15px;+ height: 15px;+ margin-top: 2px;+ border-radius: 50%;+ border: 1.5px solid var(--muted-foreground);+}+.mc-method.selected .mc-method-radio {+ border-color: var(--foreground);+ background: radial-gradient(circle at center, var(--foreground) 0 4px, transparent 5px);+}+.mc-method-text {+ display: flex;+ flex-direction: column;+ gap: 2px;+ line-height: 1.4;+}+.mc-method-title {+ font-size: 13.5px;+ font-weight: 600;+}+.mc-method-detail {+ font-size: 12.5px;+ color: var(--muted-foreground);+}+.mc-panel {+ position: relative;+}+.mc-steps {+ margin: 2px 0 14px;+ padding: 2px 0 2px 4px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ counter-reset: mcstep;+ list-style: none;+}+.mc-steps > li {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ counter-increment: mcstep;+}+.mc-steps > li::before {+ content: counter(mcstep);+ flex: none;+ width: 20px;+ height: 20px;+ margin-top: 3px;+ border-radius: 50%;+ border: 1px solid var(--border);+ color: var(--muted-foreground);+ font-size: 11px;+ font-weight: 600;+ display: flex;+ align-items: center;+ justify-content: center;+}+.mc-steps > li > * {+ min-width: 0;+}+.mc-field {+ display: flex;+ flex-direction: column;+ gap: 5px;+ flex: 1;+}+.mc-field > span {+ font-size: 12px;+ color: var(--muted-foreground);+}+.mc-field > span a {+ color: inherit;+}+.mc-field input {+ font: inherit;+ font-size: 13px;+ padding: 8px 10px;+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ background: var(--background);+ color: var(--foreground);+ width: 100%;+ box-sizing: border-box;+}+.mc-field input:focus-visible {+ outline: 2px solid var(--foreground);+ outline-offset: -1px;+}+.mc-keyform {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 2px 0;+}+.mc-code {+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 22px;+ font-weight: 700;+ letter-spacing: 3px;+ padding: 2px 0;+ user-select: all;+}+.mc-waiting {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-size: 13px;+ color: var(--muted-foreground);+ padding: 4px 0;+}+.mc-spinner {+ width: 14px;+ height: 14px;+ flex: none;+ border-radius: 50%;+ border: 2px solid var(--border);+ border-top-color: var(--foreground);+ animation: mc-spin 0.7s linear infinite;+}+@keyframes mc-spin {+ to {+ transform: rotate(360deg);+ }+}+.mc-close {+ position: absolute;+ top: 12px;+ right: 12px;+ width: 28px;+ height: 28px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 20px;+ line-height: 1;+ color: var(--muted-foreground);+ background: none;+ border: 0;+ border-radius: var(--radius-sm);+ cursor: pointer;+}+.mc-close:hover {+ color: var(--foreground);+ background: var(--secondary);+}+.mc-code-btn {+ align-self: flex-start;+ display: inline-flex;+ align-items: baseline;+ gap: 12px;+ font: inherit;+ padding: 9px 14px;+ border: 1px dashed var(--border);+ border-radius: var(--radius-sm);+ background: var(--secondary);+ color: var(--foreground);+ cursor: pointer;+ transition: border-color 140ms ease;+}+.mc-code-btn:hover {+ border-color: var(--muted-foreground);+}+.mc-code-btn.copied {+ border-color: #1a7f37;+ border-style: solid;+}+.mc-copy-hint {+ font-size: 11.5px;+ color: var(--muted-foreground);+ white-space: nowrap;+}+.mc-code-btn.copied .mc-copy-hint {+ color: #1a7f37;+}+.mc-error {+ font-size: 13px;+ color: var(--destructive, #b42318);+ border: 1px solid color-mix(in srgb, var(--destructive, #b42318) 35%, var(--border));+ background: color-mix(in srgb, var(--destructive, #b42318) 6%, var(--background));+ border-radius: var(--radius-sm);+ padding: 9px 12px;+ margin-bottom: 12px;+}+.mc-cta {+ margin-top: 16px;+ align-self: flex-start;+}diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex 2f288e39e..7ff182933 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -15,6 +15,7 @@ import {Rocket,Search,ShieldCheck,+ Sparkles,Webhook,type IconNode,} from "lucide";@@ -70,6 +71,7 @@ import { openChatSearch, SEARCH_HOTKEY_LABEL } from "./search";import { hideTooltip, showTooltip } from "./tooltip";import { clearConnectorNotice, noteConnectorResult, renderConnectors, resetKeychainState } from "./connectors";import { renderDeploys } from "./deploys";+import { openModelConnectManager, renderModelConnectGate } from "./model-connect";import { renderMemory, resetMemoryState } from "./memory";import { renderSkills } from "./skills";import { contextsState, ensureContexts, renderContexts, resetContextsState, resolveProjectScope } from "./contexts";@@ -455,6 +457,18 @@ export function mountShell(): void {<span class="avatar">${initials(appState.me?.user ?? "?")}</span><span class="user-name">${appState.me?.user ?? ""}</span></div>+ ${+ appState.me?.individualModelAuth+ ? html`<button+ class="icon-btn subtle"+ title="Manage AI account"+ aria-label="Manage AI account"+ @click=${openModelConnectManager}+ >+ ${icon(Sparkles, 17)}+ </button>`+ : nothing+ }<theme-toggle .includeSystem=${true} title="Color scheme: light / dark / system"></theme-toggle><button class="icon-btn subtle" title="Sign out" aria-label="Sign out" @click=${signOut}>${icon(LogOut, 17)}@@ -876,6 +890,11 @@ export async function boot(): Promise<void> {appState.me = (await r.json()) as Me;authMode = appState.me.mode ?? "portal";clearPortalAttempt();+ if (appState.me.individualModelAuth && !appState.me.modelAuthConnected) {+ shellMounted = false;+ renderModelConnectGate();+ return;+ }const personalScope = `personal:${appState.me.user}`;const runtimeConfig = await fetchRuntimeConfig(personalScope);if (runtimeConfig) {diff --git a/plugins/web-ui/test/composer-source.test.ts b/plugins/web-ui/test/composer-source.test.tsindex cf7ecb296..45e22c81a 100644--- a/plugins/web-ui/test/composer-source.test.ts+++ b/plugins/web-ui/test/composer-source.test.ts@@ -13,7 +13,7 @@ test("scope-default buttons render when any runtime setting differs from the sco});test("composer-right keeps its control order: make default, use org default, model, harness, send", () => {- const right = composer.slice(composer.indexOf('class="composer-right"'));+ const right = composer.slice(composer.indexOf("let runtimeControls"));const makeDefault = right.indexOf("Make default");const orgDefault = right.indexOf("Use org default");const model = right.indexOf('kind: "model"');@@ -32,6 +32,10 @@ test("composer-right keeps its control order: make default, use org default, modassert.ok(orgDefault < model, "Use org default should precede the model picker");assert.ok(model < harness, "the model picker should precede the harness picker");assert.ok(harness < send, "the harness picker should precede the send controls");+ const rendered = composer.slice(composer.indexOf('class="composer-right"'));+ const controlsAt = rendered.indexOf("${runtimeControls}");+ assert.ok(controlsAt >= 0, "runtimeControls must be rendered inside composer-right");+ assert.ok(controlsAt < rendered.indexOf("sendControls(agent)"), "runtime controls render before send controls");});test("attaching files is allowed while a turn is streaming", () => {diff --git a/scripts/dev/lib/envctx.ts b/scripts/dev/lib/envctx.tsindex e22d460ed..e2be0aa51 100644--- a/scripts/dev/lib/envctx.ts+++ b/scripts/dev/lib/envctx.ts@@ -4,11 +4,13 @@ import { dirname, join } from "node:path";import { liveEnvPath } from "./pool.ts";import { bestEffort, readEnvFile, sha256Hex } from "./util.ts";import { run } from "./proc.ts";+import { codexAuthFileForEnv, readCodexOAuthAuthFile } from "../../../src/harness/codex-auth-file.ts";export interface AssembledEnv {env: Record<string, string>;anthropicKeySource: string;openaiKeySource: string;+ codexAuthSource: string;harness: "pi" | "mock" | "opencode" | "codex" | "claude";liveEnvFile: string;warnings: string[];@@ -100,6 +102,7 @@ export async function assembleEnv(opts: {for (const [k, v] of Object.entries(readEnvFile(liveEnvFile))) {if (!env[k]) env[k] = v;}+ const wtEnv = readEnvFile(join(opts.worktree, ".env"));let anthropicKeySource = "";if (opts.callerEnv.ANTHROPIC_API_KEY) anthropicKeySource = "your shell export";@@ -112,7 +115,6 @@ export async function assembleEnv(opts: {anthropicKeySource = liveEnvFile;}}- const wtEnv = readEnvFile(join(opts.worktree, ".env"));if (!env.ANTHROPIC_API_KEY && wtEnv.ANTHROPIC_API_KEY) {env.ANTHROPIC_API_KEY = wtEnv.ANTHROPIC_API_KEY;anthropicKeySource = "the worktree .env";@@ -125,13 +127,22 @@ export async function assembleEnv(opts: {openaiKeySource = "the worktree .env";}+ if (!env.CODEX_AUTH_FILE && wtEnv.CODEX_AUTH_FILE) env.CODEX_AUTH_FILE = wtEnv.CODEX_AUTH_FILE;+ let codexAuthSource = "";+ const codexAuthCandidate = codexAuthFileForEnv({ ...env, ...opts.callerEnv }, true);+ const codexOAuthConfigured = Boolean(codexAuthCandidate && readCodexOAuthAuthFile(codexAuthCandidate));+ if (codexOAuthConfigured && codexAuthCandidate) {+ env.CODEX_AUTH_FILE = codexAuthCandidate;+ codexAuthSource = codexAuthCandidate;+ }+let harness: "pi" | "mock" | "opencode" | "codex" | "claude";if (opts.callerEnv.HARNESS === "codex" || opts.callerEnv.HARNESS === "claude") {harness = opts.callerEnv.HARNESS;env.HARNESS = harness;- if (harness === "codex" && !env.OPENAI_API_KEY) {+ if (harness === "codex" && !env.OPENAI_API_KEY && !codexOAuthConfigured) {throw new Error(- "HARNESS=codex needs OPENAI_API_KEY (its CLI cannot do browser OAuth in a container) -- export it, or add it to the live env file or the worktree .env",+ "HARNESS=codex needs OPENAI_API_KEY or a readable ChatGPT OAuth auth.json via CODEX_AUTH_FILE (or ~/.codex/auth.json)",);}} else if (env.ANTHROPIC_API_KEY) {@@ -155,7 +166,7 @@ export async function assembleEnv(opts: {if (!env[k] && wtEnv[k]) env[k] = wtEnv[k];}- return { env, anthropicKeySource, openaiKeySource, harness, liveEnvFile, warnings };+ return { env, anthropicKeySource, openaiKeySource, codexAuthSource, harness, liveEnvFile, warnings };}export function envFileGet(path: string, key: string): string {diff --git a/scripts/dev/supervisor/main.ts b/scripts/dev/supervisor/main.tsindex cd057da87..56c5d3f61 100644--- a/scripts/dev/supervisor/main.ts+++ b/scripts/dev/supervisor/main.ts@@ -318,7 +318,9 @@ async function assembleAndPrepare(spec: BootSpec): Promise<SpecInputs> {let harnessDetail = `live ${assembled.harness} turns (anthropic key from ${assembled.anthropicKeySource})`;if (assembled.harness === "mock") harnessDetail = "mock turns";else if (assembled.harness === "codex") {- harnessDetail = `live codex turns (openai key from ${assembled.openaiKeySource || "the environment"})`;+ harnessDetail = assembled.codexAuthSource+ ? "live codex turns (ChatGPT OAuth auth.json)"+ : `live codex turns (openai key from ${assembled.openaiKeySource || "the environment"})`;} else if (assembled.harness === "claude") harnessDetail = "live claude turns (native CLI authentication)";phase("env", "ok", harnessDetail);diff --git a/scripts/dev/supervisor/specs.ts b/scripts/dev/supervisor/specs.tsindex 33c0b364c..5d8867f52 100644--- a/scripts/dev/supervisor/specs.ts+++ b/scripts/dev/supervisor/specs.ts@@ -21,6 +21,10 @@ export interface SpecInputs {export function buildChildSpecs(i: SpecInputs): ChildSpec[] {const watchArgs = i.watch ? ["--watch"] : [];const base = { ...i.baseEnv, ...i.sandboxEnv };+ const siblingBase = Object.fromEntries(+ Object.entries(base).filter(([key]) => key !== "HOME" && key !== "CODEX_HOME"),+ );+ siblingBase.CODEX_AUTH_FILE = "";const orgId = i.baseEnv.DEV_INSTANCE_ORG_ID || "acme";const signing: Record<string, string> = i.coreSigningSecret ? { CORE_SIGNING_SECRET: i.coreSigningSecret } : {};return [@@ -58,7 +62,7 @@ export function buildChildSpecs(i: SpecInputs): ChildSpec[] {cwd: join(i.worktree, "plugins/web-ui"),argv: ["node", "--env-file-if-exists=.env", "server/index.ts"],env: {- ...base,+ ...siblingBase,...signing,PORT: String(i.ports.web),CORE_API_URL: `http://localhost:${i.ports.core}`,@@ -78,7 +82,7 @@ export function buildChildSpecs(i: SpecInputs): ChildSpec[] {cwd: join(i.worktree, "plugins/admin"),argv: ["node", `--env-file-if-exists=${join(i.worktree, ".env")}`, ...watchArgs, "src/index.ts"],env: {- ...base,+ ...siblingBase,...signing,PORT: String(i.ports.admin),CORE_API_URL: `http://localhost:${i.ports.core}`,@@ -95,7 +99,7 @@ export function buildChildSpecs(i: SpecInputs): ChildSpec[] {cwd: join(i.worktree, "plugins/portal"),argv: ["node", ...watchArgs, "src/index.ts"],env: {- ...base,+ ...siblingBase,...signing,PORT: String(i.ports.portal),PORTAL_PUBLIC_URL: `http://localhost:${i.ports.portal}`,diff --git a/src/api/app-turn.ts b/src/api/app-turn.tsindex 889a7a1f2..0117a1b70 100644--- a/src/api/app-turn.ts+++ b/src/api/app-turn.ts@@ -123,6 +123,7 @@ export function createTurnMethods(return (await deps.projects.withVersion(conversationRef, projectVersion, fn)) ?? null;}+ const individualAuth = !!deps.userModelCredentials && (await deps.config.getIndividualModelAuthDurable());if (req.surface === "web") {const threadRef = req.conversation.threadRef;const existing = await deps.sessions.getByThread(threadRef);@@ -147,62 +148,64 @@ export function createTurnMethods(harnessId: fallbackHarness,modelId: defaultModelForHarness(fallbackHarness),};- const configuredKeys = deps.providerKeys ??- deps.modelProviders ?? { anthropic: false, openai: false, openrouter: false };- const managedKeys = deps.modelCredentials ? await deps.modelCredentials.availability() : configuredKeys;- let orgRuntime;- let configuredRuntime;- let runtime;- try {- orgRuntime = await resolveRuntimeChoiceDurable(deps.config, org, org, runtimeFallback);- configuredRuntime =- targetScope === org- ? orgRuntime- : await resolveRuntimeChoiceDurable(deps.config, org, targetScope, runtimeFallback);- runtime =- req.harness || req.model- ? await resolveRuntimeChoiceDurable(deps.config, org, targetScope, runtimeFallback, {- ...(req.harness && isHarnessId(req.harness) ? { harnessId: req.harness } : {}),- ...(req.model ? { modelId: req.model } : {}),- })- : configuredRuntime;- } catch (error) {- return { status: "refused", reason: errMessage(error) };- }- if (req.harness && !isHarnessId(req.harness)) {- return { status: "refused", reason: `runtime ${req.harness} is not approved` };- }- let providers = deps.modelProviders;- if (deps.modelCredentials) {- providers = modelProviderAvailabilityFor(runtime.harnessId, configuredKeys, managedKeys);- } else if (deps.providerKeys) {- providers = modelProviderAvailabilityFor(runtime.harnessId, configuredKeys);- }- if (providers && !modelServiceable(runtime.modelId, providers)) {- return {- status: "refused",- reason: "that model isn't available on this deployment (its provider isn't configured)",- };- }- const configuredWebuiModels = await deps.config.getWebuiModelsDurable(org);- let enabledWebuiModels: string[] | null = null;- if (configuredWebuiModels?.length) {- enabledWebuiModels = [...new Set([...configuredWebuiModels, orgRuntime.modelId])];- } else if (providers?.openrouter) {- enabledWebuiModels = [- ...new Set([- ...selectableCatalogForHarness(- await selectableModelCatalog(deps.modelCredentialFetch),- runtime.harnessId,- ).map((model) => model.id),- ...(orgRuntime.harnessId === runtime.harnessId ? [orgRuntime.modelId] : []),- ]),- ];+ if (!individualAuth) {+ const configuredKeys = deps.providerKeys ??+ deps.modelProviders ?? { anthropic: false, openai: false, openrouter: false };+ const managedKeys = deps.modelCredentials ? await deps.modelCredentials.availability() : configuredKeys;+ let orgRuntime;+ let configuredRuntime;+ let runtime;+ try {+ orgRuntime = await resolveRuntimeChoiceDurable(deps.config, org, org, runtimeFallback);+ configuredRuntime =+ targetScope === org+ ? orgRuntime+ : await resolveRuntimeChoiceDurable(deps.config, org, targetScope, runtimeFallback);+ runtime =+ req.harness || req.model+ ? await resolveRuntimeChoiceDurable(deps.config, org, targetScope, runtimeFallback, {+ ...(req.harness && isHarnessId(req.harness) ? { harnessId: req.harness } : {}),+ ...(req.model ? { modelId: req.model } : {}),+ })+ : configuredRuntime;+ } catch (error) {+ return { status: "refused", reason: errMessage(error) };+ }+ if (req.harness && !isHarnessId(req.harness)) {+ return { status: "refused", reason: `runtime ${req.harness} is not approved` };+ }+ let providers = deps.modelProviders;+ if (deps.modelCredentials) {+ providers = modelProviderAvailabilityFor(runtime.harnessId, configuredKeys, managedKeys);+ } else if (deps.providerKeys) {+ providers = modelProviderAvailabilityFor(runtime.harnessId, configuredKeys);+ }+ if (providers && !modelServiceable(runtime.modelId, providers)) {+ return {+ status: "refused",+ reason: "that model isn't available on this deployment (its provider isn't configured)",+ };+ }+ const configuredWebuiModels = await deps.config.getWebuiModelsDurable(org);+ let enabledWebuiModels: string[] | null = null;+ if (configuredWebuiModels?.length) {+ enabledWebuiModels = [...new Set([...configuredWebuiModels, orgRuntime.modelId])];+ } else if (providers?.openrouter) {+ enabledWebuiModels = [+ ...new Set([+ ...selectableCatalogForHarness(+ await selectableModelCatalog(deps.modelCredentialFetch),+ runtime.harnessId,+ ).map((model) => model.id),+ ...(orgRuntime.harnessId === runtime.harnessId ? [orgRuntime.modelId] : []),+ ]),+ ];+ }+ const invalidModelOption =+ validateWebTurnModelOptions(req, enabledWebuiModels, providers) ??+ webTurnRuntimeModelRefusal(runtime.modelId, orgRuntime.modelId, configuredWebuiModels);+ if (invalidModelOption) return { status: "refused", reason: invalidModelOption };}- const invalidModelOption =- validateWebTurnModelOptions(req, enabledWebuiModels, providers) ??- webTurnRuntimeModelRefusal(runtime.modelId, orgRuntime.modelId, configuredWebuiModels);- if (invalidModelOption) return { status: "refused", reason: invalidModelOption };}const rawAudience = req.conversation.audience ?? [req.actor];@@ -251,8 +254,8 @@ export function createTurnMethods(...(req.detectOpener ? { detectOpener: req.detectOpener } : {}),...(req.attachments?.length ? { attachments: req.attachments } : {}),...(req.inboundNotes?.length ? { inboundNotes: req.inboundNotes } : {}),- ...(req.harness ? { harness: req.harness } : {}),- ...(req.model ? { model: req.model } : {}),+ ...(!individualAuth && req.harness ? { harness: req.harness } : {}),+ ...(!individualAuth && req.model ? { model: req.model } : {}),...turnModelOptions(req),...(req.readOnly ? { readOnly: true } : {}),...(req.skipMemory ? { skipMemory: true } : {}),diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex e33509529..29b284487 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -27,6 +27,7 @@ import type { RunSignal, RunSignalStore } from "../runs/run-signal-store.ts";import type { TaskStore, TaskStatus } from "../tasks/task-store.ts";import type { ModelGateway } from "../model/model-gateway.ts";import type { ModelCredentialStore } from "../model/model-credential-store.ts";+import type { UserModelCredentialStore } from "../model/user-model-credential-store.ts";import type { CustomProviderStore } from "../model/custom-provider-store.ts";import type { McpServerStore } from "../mcp/mcp-server-store.ts";import type { McpToolService } from "../mcp/mcp-tool-service.ts";@@ -519,6 +520,7 @@ export interface AppDeps {tasks?: TaskStore;modelGateway: ModelGateway;modelCredentials?: ModelCredentialStore;+ userModelCredentials?: UserModelCredentialStore;mcpServers?: McpServerStore;mcpToolService?: McpToolService;modelCredentialFetch?: typeof fetch;diff --git a/src/api/deps.ts b/src/api/deps.tsindex 7e0b60d0c..d0dadd549 100644--- a/src/api/deps.ts+++ b/src/api/deps.ts@@ -1,5 +1,6 @@-import type { ModelProviderAvailability } from "../model/pi-models.ts";+import type { ModelProvider, ModelProviderAvailability } from "../model/pi-models.ts";import type { ModelCredentialStore } from "../model/model-credential-store.ts";+import type { UserModelCredentialStore } from "../model/user-model-credential-store.ts";import type { CustomProviderStore } from "../model/custom-provider-store.ts";import type { McpServerStore } from "../mcp/mcp-server-store.ts";import type { McpToolService } from "../mcp/mcp-tool-service.ts";@@ -87,6 +88,7 @@ export interface ServerDeps {modelProviders?: ModelProviderAvailability;providerKeys?: ModelProviderAvailability;modelCredentials?: ModelCredentialStore;+ userModelCredentials?: UserModelCredentialStore;mcpServers?: McpServerStore;mcpToolService?: McpToolService;modelCredentialFetch?: typeof fetch;@@ -94,6 +96,7 @@ export interface ServerDeps {refreshCustomProviders?: () => Promise<void>;brandingDefault?: OrgBranding;harnessId?: string;+ harnessCarriedModelAuth?: ModelProvider;admin?: AdminService;rateLimiter?: RateLimiter;sessions?: SessionStore;diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.tsindex def730c7e..2b9d09f4d 100644--- a/src/api/routes/admin-resources.ts+++ b/src/api/routes/admin-resources.ts@@ -361,6 +361,23 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [(deps, _scope, on) => deps.config!.setInteractiveFastMode(on),),},+ {+ id: "individual-model-auth",+ kind: "boolean",+ target: "org",+ label:+ "Individual authorization for AI usage org-wide: on means each user must connect their own Claude or Codex account (API key or subscription login) before using the assistant; the org's shared model credentials are not used for their turns.",+ readKey: "individualModelAuth",+ get: (deps, scope) => (parseScopeId(scope).kind === "org" ? deps.config!.getIndividualModelAuth() : undefined),+ apply: generic<boolean>(+ (body, { scope }) => {+ const bad = orgOnly(scope, "the individual-authorization switch is org-wide");+ if (bad) return bad;+ return boolBody(body);+ },+ (deps, _scope, on) => deps.config!.setIndividualModelAuth(on),+ ),+ },{id: "base-model",kind: "enum",diff --git a/src/api/routes/admin/model-providers.ts b/src/api/routes/admin/model-providers.tsindex a43806558..77a44da66 100644--- a/src/api/routes/admin/model-providers.ts+++ b/src/api/routes/admin/model-providers.ts@@ -36,7 +36,7 @@ async function actor(ctx: ApiCtx) {return authorizeAdmin(ctx, scope);}-async function validate(ctx: ApiCtx, provider: ModelProvider, apiKey: string): Promise<boolean> {+export async function validateProviderApiKey(ctx: ApiCtx, provider: ModelProvider, apiKey: string): Promise<boolean> {try {const response = await (ctx.deps.modelCredentialFetch ?? fetch)(validationUrl(provider), {headers: VALIDATION_REQUESTS[provider].headers(apiKey),@@ -61,6 +61,9 @@ export async function getModelProviders(ctx: ApiCtx): Promise<void> {return sendJson(ctx.res, 200, {providers: await ctx.deps.modelCredentials.statuses(),models: await selectableModelCatalog(ctx.deps.modelCredentialFetch),+ ...(ctx.deps.harnessCarriedModelAuth+ ? { harnessAuth: { harnessId: ctx.deps.harnessId ?? "pi", provider: ctx.deps.harnessCarriedModelAuth } }+ : {}),});}@@ -74,7 +77,7 @@ export async function putModelProvider(ctx: ApiCtx): Promise<void> {if (typeof apiKey !== "string" || !apiKey.trim()) {return sendJson(ctx.res, 400, { error: "bad_request", message: "API key is required" });}- if (!(await validate(ctx, provider, apiKey.trim()))) {+ if (!(await validateProviderApiKey(ctx, provider, apiKey.trim()))) {return sendJson(ctx.res, 400, { error: "invalid_api_key", message: `${provider} rejected this API key` });}await ctx.deps.modelCredentials.set(provider, apiKey.trim(), authorized.id);diff --git a/src/api/routes/index.ts b/src/api/routes/index.tsindex c6b54f744..28503004f 100644--- a/src/api/routes/index.ts+++ b/src/api/routes/index.ts@@ -25,6 +25,7 @@ import { contextPolicyRoutes } from "./context-policy.ts";import { deploymentLayerRoutes } from "./deployment-layer.ts";import { egressAuditRoutes } from "./egress-audit.ts";import { authBrokerRoutes } from "./auth-broker.ts";+import { userModelAuthRoutes } from "./user-model-auth.ts";export const rawRoutes: ReadonlyArray<Route<BaseCtx>> = [{ method: "GET", path: "/healthz", auth: "public", handle: ({ res }) => sendJson(res, 200, { ok: true }) },@@ -64,4 +65,5 @@ export const apiRoutes: ReadonlyArray<Route<ApiCtx>> = [...deploymentRoutes,...egressAuditRoutes,...authBrokerRoutes,+ ...userModelAuthRoutes,];diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex 39690ed4a..5172511cb 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -1062,6 +1062,8 @@ async function getSurfaceConfig(ctx: ApiCtx): Promise<void> {]);const harnessId = deps.harnessId ?? "pi";const managedKeys = deps.modelCredentials ? await deps.modelCredentials.availability() : null;+ const configuredKeys = deps.providerKeys ?? managedKeys;+ const providerStatus = harnessId === "pi" && managedKeys ? managedKeys : configuredKeys;const catalog = managedKeys?.openrouter? await selectableModelCatalog(deps.modelCredentialFetch): builtInModelCatalog();@@ -1079,7 +1081,9 @@ async function getSurfaceConfig(ctx: ApiCtx): Promise<void> {webuiModels: configuredPicker.length ? configuredPicker : allowed,baseModel: resolvedBase,harnessId,- ...(managedKeys ? { modelProviderConfigured: Object.values(managedKeys).some(Boolean) } : {}),+ ...(providerStatus && {+ modelProviderConfigured: Object.values(providerStatus).some(Boolean) || Boolean(deps.harnessCarriedModelAuth),+ }),externalSlackParticipants,...(Object.keys(resolvedBranding).length ? { branding: resolvedBranding } : {}),});diff --git a/src/api/routes/user-model-auth.ts b/src/api/routes/user-model-auth.tsnew file mode 100644index 000000000..0e3a6e8ce--- /dev/null+++ b/src/api/routes/user-model-auth.ts@@ -0,0 +1,144 @@+import type { ModelProvider } from "../../model/pi-models.ts";+import { completeClaudeLogin, startClaudeLogin } from "../../model/subscription-oauth.ts";+import { createCodexDeviceLogin } from "../../model/codex-device-login.ts";+import { errMessage } from "../../util/errors.ts";+import { sendJson } from "../http.ts";+import { validateProviderApiKey } from "./admin/model-providers.ts";+import type { ApiCtx, Route } from "./route.ts";+import { audit } from "./shared.ts";++function caller(ctx: ApiCtx): string | null {+ return ctx.actor?.p ?? null;+}++function bodyObj(ctx: ApiCtx): Record<string, unknown> {+ return typeof ctx.body === "object" && ctx.body !== null ? (ctx.body as Record<string, unknown>) : {};+}++function connectProvider(raw: unknown): ModelProvider | null {+ if (raw === "anthropic" || raw === "claude") return "anthropic";+ if (raw === "openai" || raw === "chatgpt" || raw === "codex") return "openai";+ return null;+}++async function getStatus(ctx: ApiCtx): Promise<void> {+ const principal = caller(ctx);+ if (!principal) return sendJson(ctx.res, 401, { error: "unauthorized" });+ const required = (await ctx.deps.config?.getIndividualModelAuthDurable()) ?? false;+ const connections = (await ctx.deps.userModelCredentials?.connections(principal)) ?? [];+ return sendJson(ctx.res, 200, { individualModelAuth: required, connections });+}++async function disconnect(ctx: ApiCtx): Promise<void> {+ const principal = caller(ctx);+ if (!principal) return sendJson(ctx.res, 401, { error: "unauthorized" });+ if (!ctx.deps.userModelCredentials) return sendJson(ctx.res, 404, { error: "not_found" });+ const provider = connectProvider(bodyObj(ctx).provider);+ if (!provider) return sendJson(ctx.res, 400, { error: "bad_request", message: "provider must be claude or chatgpt" });+ await ctx.deps.userModelCredentials.delete(principal, provider);+ audit(ctx.deps, {+ principalId: principal,+ action: "user-model-auth.disconnect",+ resource: provider,+ scopeLabel: principal,+ });+ return sendJson(ctx.res, 200, { ok: true });+}++async function putApiKey(ctx: ApiCtx): Promise<void> {+ const principal = caller(ctx);+ if (!principal) return sendJson(ctx.res, 401, { error: "unauthorized" });+ if (!ctx.deps.userModelCredentials) return sendJson(ctx.res, 404, { error: "not_found" });+ const body = bodyObj(ctx);+ const provider = connectProvider(body.provider);+ const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";+ if (!provider) return sendJson(ctx.res, 400, { error: "bad_request", message: "provider must be claude or chatgpt" });+ if (!apiKey) return sendJson(ctx.res, 400, { error: "bad_request", message: "API key is required" });+ if (!(await validateProviderApiKey(ctx, provider, apiKey))) {+ return sendJson(ctx.res, 400, { error: "invalid_api_key", message: `${provider} rejected this API key` });+ }+ await ctx.deps.userModelCredentials.setApiKey(principal, provider, apiKey);+ audit(ctx.deps, {+ principalId: principal,+ action: "user-model-auth.api-key",+ resource: provider,+ scopeLabel: principal,+ });+ return sendJson(ctx.res, 200, { ok: true });+}++// ChatGPT device-code login is delegated to the vendored Codex binary's own+// login RPCs (supported, version-matched surface) rather than a hand-rolled+// flow against undocumented endpoints.+const codexDeviceLogin = createCodexDeviceLogin();++async function chatgptStart(ctx: ApiCtx): Promise<void> {+ if (!caller(ctx)) return sendJson(ctx.res, 401, { error: "unauthorized" });+ try {+ const prompt = await codexDeviceLogin.start();+ return sendJson(ctx.res, 200, prompt);+ } catch (e) {+ return sendJson(ctx.res, 502, { error: "oauth_start_failed", message: errMessage(e) });+ }+}++async function chatgptPoll(ctx: ApiCtx): Promise<void> {+ const principal = caller(ctx);+ if (!principal) return sendJson(ctx.res, 401, { error: "unauthorized" });+ if (!ctx.deps.userModelCredentials) return sendJson(ctx.res, 404, { error: "not_found" });+ const body = bodyObj(ctx);+ const deviceAuthId = typeof body.deviceAuthId === "string" ? body.deviceAuthId : "";+ if (!deviceAuthId) return sendJson(ctx.res, 400, { error: "bad_request" });+ try {+ const result = await codexDeviceLogin.poll(deviceAuthId);+ if (result === "pending") return sendJson(ctx.res, 200, { status: "pending" });+ await ctx.deps.userModelCredentials.setOAuth(principal, "openai", result);+ audit(ctx.deps, {+ principalId: principal,+ action: "user-model-auth.oauth",+ resource: "openai",+ scopeLabel: principal,+ });+ return sendJson(ctx.res, 200, { status: "connected" });+ } catch (e) {+ return sendJson(ctx.res, 502, { error: "oauth_poll_failed", message: errMessage(e) });+ }+}++async function claudeStart(ctx: ApiCtx): Promise<void> {+ if (!caller(ctx)) return sendJson(ctx.res, 401, { error: "unauthorized" });+ return sendJson(ctx.res, 200, startClaudeLogin());+}++async function claudeComplete(ctx: ApiCtx): Promise<void> {+ const principal = caller(ctx);+ if (!principal) return sendJson(ctx.res, 401, { error: "unauthorized" });+ if (!ctx.deps.userModelCredentials) return sendJson(ctx.res, 404, { error: "not_found" });+ const body = bodyObj(ctx);+ const code = typeof body.code === "string" ? body.code : "";+ const verifier = typeof body.verifier === "string" ? body.verifier : "";+ if (!code || !verifier) return sendJson(ctx.res, 400, { error: "bad_request" });+ try {+ const tokens = await completeClaudeLogin(code, verifier);+ await ctx.deps.userModelCredentials.setOAuth(principal, "anthropic", tokens);+ audit(ctx.deps, {+ principalId: principal,+ action: "user-model-auth.oauth",+ resource: "anthropic",+ scopeLabel: principal,+ });+ return sendJson(ctx.res, 200, { ok: true });+ } catch (e) {+ return sendJson(ctx.res, 502, { error: "oauth_complete_failed", message: errMessage(e) });+ }+}++export const userModelAuthRoutes: ReadonlyArray<Route<ApiCtx>> = [+ { method: "GET", path: "/v1/user-model-auth/status", auth: "source", handle: getStatus },+ { method: "POST", path: "/v1/user-model-auth/api-key", auth: "source", handle: putApiKey },+ { method: "POST", path: "/v1/user-model-auth/disconnect", auth: "source", handle: disconnect },+ { method: "POST", path: "/v1/user-model-auth/chatgpt/start", auth: "source", handle: chatgptStart },+ { method: "POST", path: "/v1/user-model-auth/chatgpt/poll", auth: "source", handle: chatgptPoll },+ { method: "POST", path: "/v1/user-model-auth/claude/start", auth: "source", handle: claudeStart },+ { method: "POST", path: "/v1/user-model-auth/claude/complete", auth: "source", handle: claudeComplete },+];diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.tsindex bf2bd3f42..67fa06471 100644--- a/src/api/user-scoped-routes.ts+++ b/src/api/user-scoped-routes.ts@@ -53,6 +53,13 @@ const USER_SCOPED: Rule[] = [pat("GET", "/v1/crons/:id/runs", { in: "query", name: "principalId" }),pat("GET", "/v1/deployments", { in: "query", name: "principalId" }),pat("POST", "/v1/deployments", { in: "body", name: "createdBy" }),+ pat("GET", "/v1/user-model-auth/status", { in: "query", name: "principalId" }),+ pat("POST", "/v1/user-model-auth/api-key", { in: "body", name: "principalId" }),+ pat("POST", "/v1/user-model-auth/disconnect", { in: "body", name: "principalId" }),+ pat("POST", "/v1/user-model-auth/chatgpt/start", { in: "body", name: "principalId" }),+ pat("POST", "/v1/user-model-auth/chatgpt/poll", { in: "body", name: "principalId" }),+ pat("POST", "/v1/user-model-auth/claude/start", { in: "body", name: "principalId" }),+ pat("POST", "/v1/user-model-auth/claude/complete", { in: "body", name: "principalId" }),pat("GET", "/v1/connectors/oauth/:provider/start", { in: "query", name: "principalId" }),pat("GET", "/v1/connectors/oauth/status", { in: "query", name: "principalId" }),pat("POST", "/v1/connectors/token", { in: "body", name: "principalId" }),diff --git a/src/config.ts b/src/config.tsindex 29ec33cf8..6acc29e2c 100644--- a/src/config.ts+++ b/src/config.ts@@ -14,6 +14,7 @@ import { validateCoreSecretEnv } from "./deployment/secret-schema.ts";import { DEFAULT_CAPTURE_QUIET_MS } from "./memory/strategies/per-turn.ts";import { parseSecurityPosture, type SecurityPosture } from "./security/security-posture.ts";import { slackPluginConfigFromEnv, type SlackPluginConfig } from "./slack/config.ts";+import { codexAuthFileForEnv, readCodexOAuthAuthFile } from "./harness/codex-auth-file.ts";import {MODEL_PROVIDERS,defaultModelForProvider,@@ -44,6 +45,11 @@ export interface Config {opencodeModel?: string;codexModel?: string;codexBinPath?: string;+ codexAuthFile?: string;+ /** Keychain credential id holding the Codex ChatGPT OAuth auth.json (production path). */+ codexAuthCredential?: string;+ /** Keychain credential id holding a Claude Code subscription token (production path). */+ claudeAuthCredential?: string;codexProcessEnv: NodeJS.ProcessEnv;claudeModel?: string;claudeBinPath?: string;@@ -164,6 +170,7 @@ export function providerKeysPresent(config: Config): ModelProviderAvailability {anthropic: Boolean(config.anthropicApiKey),openai: Boolean(config.openaiApiKey),openrouter: Boolean(config.openrouterApiKey),+ ...(config.harness === "codex" && (config.codexAuthFile || config.codexAuthCredential) ? { codexOAuth: true } : {}),};}@@ -171,6 +178,19 @@ export function baseModelProviders(config: Config): ModelProviderAvailability |return config.modelProvider ? onlyProvider(config.modelProvider) : undefined;}+export function harnessCarriedModelAuth(config: Config): ModelProvider | undefined {+ if (+ config.harness === "claude" &&+ (config.claudeAuthCredential ||+ config.claudeProcessEnv.CLAUDE_CODE_OAUTH_TOKEN ||+ config.claudeProcessEnv.ANTHROPIC_AUTH_TOKEN)+ )+ return "anthropic";+ if (config.harness === "codex" && (config.codexAuthCredential || config.codexProcessEnv.CODEX_ACCESS_TOKEN))+ return "openai";+ return undefined;+}+interface AwsSandboxEnv {region: string;profile?: string;@@ -611,10 +631,29 @@ function modelProviderEnvStrict(env: NodeJS.ProcessEnv): ModelProvider | undefin}export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {- const missingSecrets = validateCoreSecretEnv(env);+ const harness = harnessEnvStrict(env.HARNESS);+ const codexAuthCredential = env.CODEX_AUTH_CREDENTIAL?.trim() || undefined;+ const claudeAuthCredential = env.CLAUDE_AUTH_CREDENTIAL?.trim() || undefined;+ const codexAuthCandidate = harness === "codex" && !codexAuthCredential ? codexAuthFileForEnv(env, true) : undefined;+ const codexOAuthConfigured = Boolean(codexAuthCandidate && readCodexOAuthAuthFile(codexAuthCandidate));+ const secretEnv =+ codexOAuthConfigured && codexAuthCandidate+ ? { ...env, CODEX_AUTH_FILE: codexAuthCandidate }+ : { ...env, CODEX_AUTH_FILE: undefined };+ const missingSecrets = validateCoreSecretEnv(secretEnv);if (missingSecrets.length) {throw new Error(`missing or insecure required core secrets: ${missingSecrets.join(", ")}`);}+ if (harness === "codex" && !env.OPENAI_API_KEY?.trim() && !codexOAuthConfigured && !codexAuthCredential) {+ throw new Error(+ "HARNESS=codex needs OPENAI_API_KEY, a keychain credential via CODEX_AUTH_CREDENTIAL, or a readable ChatGPT OAuth auth.json via CODEX_AUTH_FILE (or ~/.codex/auth.json)",+ );+ }+ if (env.NODE_ENV === "production" && codexOAuthConfigured) {+ throw new Error(+ "CODEX_AUTH_FILE is supported for local Codex harnesses only; production must use CODEX_AUTH_CREDENTIAL (keychain custody)",+ );+ }const modelProvider = modelProviderEnvStrict(env);for (const key of ["SESSION_STORE", "RUN_STORE", "ARTIFACT_STORE"] as const) {if (env[key] === "sqlite") {@@ -701,6 +740,9 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {}let runStore: "memory" | "postgres" = env.SESSION_STORE === "postgres" ? "postgres" : "memory";if (env.RUN_STORE === "memory" || env.RUN_STORE === "postgres") runStore = env.RUN_STORE;+ const codexEnv = { ...env };+ if (codexOAuthConfigured && codexAuthCandidate) codexEnv.CODEX_AUTH_FILE = codexAuthCandidate;+ else delete codexEnv.CODEX_AUTH_FILE;const providerBaseUrls = providerBaseUrlsFromEnv(env);const codexProcessEnv = Object.fromEntries([@@ -719,7 +761,8 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {"CODEX_ACCESS_TOKEN","HOME","CODEX_HOME",- ].flatMap((name) => (env[name] === undefined ? [] : [[name, env[name]]])),+ "CODEX_AUTH_FILE",+ ].flatMap((name) => (codexEnv[name] === undefined ? [] : [[name, codexEnv[name]]])),) as NodeJS.ProcessEnv;const claudeProcessEnv = Object.fromEntries([@@ -757,7 +800,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {...(env.DATABASE_URL ? { databaseUrl: env.DATABASE_URL } : {}),...(env.DATABASE_CA_CERT ? { databaseCaCert: env.DATABASE_CA_CERT } : {}),...(env.DATABASE_CA_CERT_FILE ? { databaseCaCertFile: env.DATABASE_CA_CERT_FILE } : {}),- harness: harnessEnvStrict(env.HARNESS),+ harness,securityPosture: securityPostureEnvStrict(env.HARNESS_SECURITY_POSTURE),securityScreenBackend,...(securityScreenBackend === "proxy"@@ -785,6 +828,9 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {...(env.OPENCODE_MODEL || env.PI_MODEL ? { opencodeModel: env.OPENCODE_MODEL || env.PI_MODEL } : {}),...(env.CODEX_MODEL ? { codexModel: env.CODEX_MODEL } : {}),...(env.CODEX_BIN ? { codexBinPath: env.CODEX_BIN } : {}),+ ...(codexOAuthConfigured && codexAuthCandidate ? { codexAuthFile: codexAuthCandidate } : {}),+ ...(codexAuthCredential ? { codexAuthCredential } : {}),+ ...(claudeAuthCredential ? { claudeAuthCredential } : {}),codexProcessEnv,...(env.CLAUDE_MODEL ? { claudeModel: env.CLAUDE_MODEL } : {}),...(env.CLAUDE_BIN ? { claudeBinPath: env.CLAUDE_BIN } : {}),diff --git a/src/core/individual-auth-routing.ts b/src/core/individual-auth-routing.tsnew file mode 100644index 000000000..60c958629--- /dev/null+++ b/src/core/individual-auth-routing.ts@@ -0,0 +1,76 @@+import {+ codexSubscriptionModelId,+ DEFAULT_AGENT_MODEL_ID,+ DEFAULT_CODEX_MODEL_ID,+ defaultModelForHarness,+ defaultModelForProvider,+ resolveModel,+ type ModelProvider,+} from "../model/pi-models.ts";+import type { UserModelCredential } from "../model/user-model-credential-store.ts";++export type IndividualAuthRouting =+ | { kind: "apikey"; provider: ModelProvider; harness: "pi"; model: string | undefined; apiKey: string }+ | { kind: "oauth"; provider: "anthropic"; harness: "claude"; model: string }+ | { kind: "oauth"; provider: "openai"; harness: "codex"; model: string }+ | { kind: "oauth"; provider: "openai"; harness: "pi"; model: string }+ | null;++export function resolveIndividualAuthRouting(+ anthCred: UserModelCredential | null,+ oaiCred: UserModelCredential | null,+ requestedModel: string | undefined,+ preferredHarness?: string,+): IndividualAuthRouting {+ const requestedProvider = requestedModel ? resolveModel(requestedModel)?.provider : undefined;+ const pick = ((): { provider: "anthropic" | "openai"; cred: UserModelCredential } | null => {+ if (requestedProvider === "anthropic" && anthCred) return { provider: "anthropic", cred: anthCred };+ if (requestedProvider === "openai" && oaiCred) return { provider: "openai", cred: oaiCred };+ if (anthCred) return { provider: "anthropic", cred: anthCred };+ if (oaiCred) return { provider: "openai", cred: oaiCred };+ return null;+ })();+ if (!pick) return null;+ if (pick.cred.kind === "apikey" && pick.cred.apiKey) {+ return {+ kind: "apikey",+ provider: pick.provider,+ harness: "pi",+ apiKey: pick.cred.apiKey,+ model:+ requestedModel && requestedProvider === pick.provider+ ? requestedModel+ : defaultModelForProvider("pi", pick.provider),+ };+ }+ if (pick.cred.kind === "oauth" && pick.cred.oauth) {+ if (pick.provider === "anthropic") {+ return {+ kind: "oauth",+ provider: "anthropic",+ harness: "claude",+ model: defaultModelForHarness("claude", DEFAULT_AGENT_MODEL_ID),+ };+ }+ if (preferredHarness === "pi") {+ // pi-on-ChatGPT: the org runs the pi harness, so serve the+ // subscription through pi-ai's Codex provider instead of switching+ // the person onto the codex harness.+ return {+ kind: "oauth",+ provider: "openai",+ harness: "pi",+ model: codexSubscriptionModelId(+ requestedModel && requestedProvider === "openai" ? requestedModel : DEFAULT_CODEX_MODEL_ID,+ ),+ };+ }+ return {+ kind: "oauth",+ provider: "openai",+ harness: "codex",+ model: defaultModelForHarness("codex", DEFAULT_CODEX_MODEL_ID),+ };+ }+ return null;+}diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex b19b393fa..904a92941 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -133,7 +133,10 @@ import { randomUUID } from "node:crypto";import { LRUCache } from "lru-cache";import type { SkillResolution, GrantedSkillRef } from "../skills/skill-store.ts";import type { Orchestrator, OrchestratorDeps, OrchestratorInput } from "./orchestrator/types.ts";-import { resolveModel } from "../model/pi-models.ts";+import { resolveModel, CODEX_SUBSCRIPTION_PROVIDER } from "../model/pi-models.ts";+import type { ProviderKeys } from "../harness/pi-harness.ts";+import type { CodexTurnAuth } from "../harness/harness.ts";+import { resolveIndividualAuthRouting } from "./individual-auth-routing.ts";import {MAX_AUTO_ATTACHMENT_SCREEN_BYTES,approvalGrantId,@@ -347,8 +350,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {actor.id,scopeLabel,sessionId- ? async (rec) => {- await deps.sessions.recordLlmRequest(sessionId, { ...rec, scopeLabel });+ ? async (rec, signal) => {+ await deps.sessions.recordLlmRequest(sessionId, { ...rec, scopeLabel }, signal);}: undefined,{ hook: "user_input", surface: "steer", origin: "ambient" },@@ -526,13 +529,13 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {);const screenSession: { id?: string } = {};const pendingScreenRequests: HarnessLlmRequestRecord[] = [];- const recordScreenRequest = async (rec: HarnessLlmRequestRecord): Promise<void> => {+ const recordScreenRequest = async (rec: HarnessLlmRequestRecord, signal?: AbortSignal): Promise<void> => {if (!screenSession.id) {pendingScreenRequests.push(rec);return;}try {- await deps.sessions.recordLlmRequest(screenSession.id, { ...rec, scopeLabel: scopeId });+ await deps.sessions.recordLlmRequest(screenSession.id, { ...rec, scopeLabel: scopeId }, signal);} catch (err) {console.error("[orchestrator] failed to persist security screen request snapshot:", errMessage(err));}@@ -714,7 +717,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {try {await withManagedRosterVersion(async () => {await reconcileSessionParticipants(session.id);- await Promise.all(pendingScreenRequests.splice(0).map(recordScreenRequest));+ await Promise.all(pendingScreenRequests.splice(0).map((rec) => recordScreenRequest(rec)));for (const overheard of screenedOverheard) {const imported = await deps.sessions.append(lease, {type: "user",@@ -1409,7 +1412,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {try {await withManagedRosterVersion(async () => {await reconcileSessionParticipants(session.id);- await Promise.all(pendingScreenRequests.splice(0).map(recordScreenRequest));+ await Promise.all(pendingScreenRequests.splice(0).map((rec) => recordScreenRequest(rec)));return true;});if (input.approval) {@@ -2320,6 +2323,85 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const wantsOrgFastMode =typeof input.fastMode !== "boolean" && humanTurn && (await deps.config?.getInteractiveFastModeDurable());const effectiveFastMode = resolveTurnFastMode(input.fastMode, humanTurn, wantsOrgFastMode === true);+ let userProviderKeys: ProviderKeys | undefined;+ let userModelOverride: string | undefined;+ let userHarnessOverride: string | undefined;+ let claudeOauthToken: string | undefined;+ let codexTurnAuth: CodexTurnAuth | undefined;+ const userCredStore = deps.userModelCredentials;+ if (userCredStore && humanTurn && (await deps.config?.getIndividualModelAuthDurable())) {+ const [anthCred, oaiCred] = await Promise.all([+ userCredStore.get(actor.id, "anthropic"),+ userCredStore.get(actor.id, "openai"),+ ]);+ // The org's harness choice decides how a ChatGPT subscription is+ // served: pi orgs stay on pi (Codex provider inside pi-ai), others+ // hop to the codex harness.+ const orgRuntime = await deps.config?.getRuntimeSelectionDurable(resolution.orgScopeId);+ const preferredHarness = input.harness ?? orgRuntime?.harnessId ?? deps.defaultHarness;+ const routing = resolveIndividualAuthRouting(+ anthCred ?? null,+ oaiCred ?? null,+ input.model,+ preferredHarness,+ );+ if (routing?.kind === "apikey") {+ userHarnessOverride = "pi";+ userProviderKeys = { [routing.provider]: routing.apiKey };+ userModelOverride = routing.model;+ } else if (routing?.kind === "oauth" && routing.provider === "anthropic" && anthCred?.oauth) {+ // Derived material only — the keychain refreshes centrally+ // (single-flight, CAS) and the refresh token never leaves it.+ const derived = await userCredStore.derivedOAuth(actor.id, "anthropic");+ if (derived) {+ claudeOauthToken = derived.accessToken;+ userHarnessOverride = routing.harness;+ userModelOverride = routing.model;+ }+ } else if (+ routing?.kind === "oauth" &&+ routing.provider === "openai" &&+ routing.harness === "pi" &&+ oaiCred?.oauth+ ) {+ // pi-on-ChatGPT: pi-ai's openai-codex provider takes the access+ // token as its key (the account claim rides inside the JWT).+ const derived = await userCredStore.derivedOAuth(actor.id, "openai");+ if (derived) {+ userProviderKeys = { [CODEX_SUBSCRIPTION_PROVIDER]: derived.accessToken };+ userHarnessOverride = routing.harness;+ userModelOverride = routing.model;+ }+ } else if (routing?.kind === "oauth" && routing.provider === "openai" && oaiCred?.oauth) {+ const derived = await userCredStore.derivedOAuth(actor.id, "openai");+ if (derived?.idToken) {+ codexTurnAuth = {+ accessToken: derived.accessToken,+ idToken: derived.idToken,+ ...(derived.accountId ? { accountId: derived.accountId } : {}),+ ...(derived.expiresAt !== undefined ? { expiresAt: derived.expiresAt } : {}),+ };+ userHarnessOverride = routing.harness;+ userModelOverride = routing.model;+ }+ }+ if (!userHarnessOverride) {+ throw new NonRetryableTurnError(+ "This organization has each person chat on their own AI account, and yours isn't connected yet. Open the web app and connect Claude or ChatGPT from the AI account panel, then try again.",+ );+ }+ }+ const effectiveModel = userModelOverride ?? input.model;+ const effectiveHarness = userHarnessOverride ?? input.harness;+ if (userHarnessOverride) {+ let authLabel = "api-key";+ if (claudeOauthToken) authLabel = "claude-oauth";+ else if (codexTurnAuth) authLabel = "codex-oauth";+ else if (userProviderKeys?.[CODEX_SUBSCRIPTION_PROVIDER]) authLabel = "codex-oauth-pi";+ console.log(+ `[individual-auth] user=${actor.id} harness=${userHarnessOverride} model=${effectiveModel} auth=${authLabel}`,+ );+ }const runHarnessTurn = (harnessInput: string,extras: {@@ -2344,6 +2426,10 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {}return deps.harness.turns.runTurn({session,+ ...(userProviderKeys ? { providerKeys: userProviderKeys } : {}),+ ...(claudeOauthToken ? { claudeOauthToken } : {}),+ ...(userHarnessOverride ? { runtimePinned: true } : {}),+ ...(codexTurnAuth ? { codexAuth: codexTurnAuth } : {}),...(input.runId ? { runId: input.runId } : {}),...(input.cancel ? { cancel: input.cancel } : {}),input: harnessInput,@@ -2354,8 +2440,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {...(extras.overheard?.length ? { overheard: extras.overheard } : {}),...(extras.attachments?.length ? { attachments: extras.attachments } : {}),...(extras.images?.length ? { images: extras.images } : {}),- ...(input.harness ? { harness: input.harness } : {}),- ...(input.model ? { model: input.model } : {}),+ ...(effectiveHarness ? { harness: effectiveHarness } : {}),+ ...(effectiveModel ? { model: effectiveModel } : {}),...(input.thinkingLevel ? { thinkingLevel: input.thinkingLevel } : {}),...(typeof effectiveFastMode === "boolean" ? { fastMode: effectiveFastMode } : {}),...(strictReadOnly ? { readOnly: true } : {}),@@ -2583,9 +2669,9 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {deps.modelGateway.recordCall({ at: Date.now(), scopeLabel: scopeId, ...rec });void deps.budget?.record(actor.id, estimateCostUsd(rec.inputTokens));},- recordLlmRequest: async (rec) => {+ recordLlmRequest: async (rec, signal) => {try {- await deps.sessions.recordLlmRequest(session.id, { ...rec, scopeLabel: scopeId });+ await deps.sessions.recordLlmRequest(session.id, { ...rec, scopeLabel: scopeId }, signal);} catch (err) {console.error("[orchestrator] failed to persist LLM request snapshot:", errMessage(err));}diff --git a/src/core/orchestrator/security-screen.ts b/src/core/orchestrator/security-screen.tsindex 845d3fbd5..ae0d3437e 100644--- a/src/core/orchestrator/security-screen.ts+++ b/src/core/orchestrator/security-screen.ts@@ -21,7 +21,7 @@ export type SecurityClassifier = (payload: string,actorId: string,scopeLabel: ScopeId,- recordLlmRequest?: (rec: HarnessLlmRequestRecord) => void | Promise<void>,+ recordLlmRequest?: (rec: HarnessLlmRequestRecord, signal?: AbortSignal) => void | Promise<void>,context?: {hook?: SecurityScreenHook;surface?: string;diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.tsindex a68404b8a..efe4b1e1a 100644--- a/src/core/orchestrator/types.ts+++ b/src/core/orchestrator/types.ts@@ -12,6 +12,7 @@ import type { TurnOrigin } from "../turn-origin.ts";import type { IdentityService } from "../../identity/identity-service.ts";import type { ResolutionService } from "../../resolution/resolution-service.ts";import type { OrgBranding, ScopedConfigStore } from "../../resolution/config-store.ts";+import type { UserModelCredentialStore } from "../../model/user-model-credential-store.ts";import type { ManagedGroupDirectory } from "../../resolution/scope-membership.ts";import type { DirectoryStore } from "../../directory/directory-store.ts";import type { EnvironmentStore } from "../../environments/environment-store.ts";@@ -96,6 +97,9 @@ export interface OrchestratorDeps {identity: IdentityService;resolution: ResolutionService;config?: ScopedConfigStore;+ /** The deployment's fallback harness (wiring's config.harness) — used when no org runtime selection exists. */+ defaultHarness?: string;+ userModelCredentials?: UserModelCredentialStore;brandingDefault?: OrgBranding;resolveBaseModelId?: () => string | undefined;sessionTapeMode?: "shadow" | "serve";diff --git a/src/credentials/connector-token.ts b/src/credentials/connector-token.tsindex 48429716b..c62977321 100644--- a/src/credentials/connector-token.ts+++ b/src/credentials/connector-token.ts@@ -22,6 +22,8 @@ export function withOperatorTokenFallback(store.deleteConnectorToken(host, principalId, accountType),connectorTokenStatus: (host, principalId, accountType) =>store.connectorTokenStatus(host, principalId, accountType),+ connectorDerivedAuth: (host, principalId, accountType) =>+ store.connectorDerivedAuth(host, principalId, accountType),async connectorAccessToken(host, principalId, accountType) {const token = await store.connectorAccessToken(host, principalId, accountType);if (token !== null) return token;diff --git a/src/credentials/harness-auth-env.ts b/src/credentials/harness-auth-env.tsnew file mode 100644index 000000000..a475b10d0--- /dev/null+++ b/src/credentials/harness-auth-env.ts@@ -0,0 +1,33 @@+import type { Keychain } from "./keychain.ts";++/**+ * Resolve a keychain env credential (e.g. a CLAUDE_CODE_OAUTH_TOKEN saved by+ * `claude setup-token`) into the env vars a harness child should receive.+ * Resolved fresh on every call, so a rotated or revoked credential takes+ * effect on the next session with no restart. Returns {} when the credential+ * is missing, expired, or not env-shaped, so the harness falls back to+ * whatever static configuration it has.+ */+export function keychainHarnessAuthEnv(+ keychain: Keychain,+ credentialId: string,+ allowedEnvKeys: readonly string[],+): () => Promise<NodeJS.ProcessEnv> {+ return async () => {+ try {+ const meta = await keychain.getCredential(credentialId);+ if (!meta || meta.kind !== "env") return {};+ if (typeof meta.expiresAt === "number" && meta.expiresAt < Date.now()) return {};+ const creds = await keychain.materializeOwn(meta.ownerId);+ const cred = creds.find((c) => c.credentialId === credentialId);+ if (!cred) return {};+ const env: NodeJS.ProcessEnv = {};+ for (const { key, value } of cred.env) {+ if (allowedEnvKeys.includes(key)) env[key] = value;+ }+ return env;+ } catch {+ return {};+ }+ };+}diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.tsindex d7b088fa6..f64c761e6 100644--- a/src/credentials/keychain.ts+++ b/src/credentials/keychain.ts@@ -31,6 +31,8 @@ interface BrokerDelivery {interface CredentialRefresh {refreshTokenEnc?: string;+ idTokenEnc?: string;+ accountId?: string;accountType?: string;clientRef?: string;grantedScopes?: string[];@@ -199,6 +201,18 @@ export interface OAuthToken {clientRef?: string;accountType?: string;orgId?: string;+ /** OIDC id token, for providers whose API needs it alongside the access token (e.g. Codex). */+ idToken?: string;+ /** Provider-side account identifier carried with the token (e.g. ChatGPT account id). */+ accountId?: string;+}++/** Derived, sandbox-safe view of a connector token: never carries the refresh token. */+export interface DerivedOAuthAuth {+ accessToken: string;+ idToken?: string;+ accountId?: string;+ expiresAt?: number;}export interface OAuthTokenStatus {@@ -233,6 +247,12 @@ export interface ConnectorTokenStore {deleteConnectorToken(host: string, principalId: string, accountType?: string): Promise<void>;connectorTokenStatus(host: string, principalId: string, accountType?: string): Promise<OAuthTokenStatus>;connectorAccessToken(host: string, principalId: string, accountType?: string): Promise<string | null>;+ /**+ * Fresh derived material for the connector token (access + id token ++ * account id), refreshing single-flight if stale. The refresh token never+ * leaves the keychain record.+ */+ connectorDerivedAuth(host: string, principalId: string, accountType?: string): Promise<DerivedOAuthAuth | null>;}interface SaveCredentialInput {@@ -326,6 +346,8 @@ export interface Keychain extends ServiceCredentialStore, ConnectorTokenStore {listByOwners(ownerIds: string[]): Promise<Map<string, KeychainCredentialMeta[]>>;listConnectorsByOwners(ownerIds: string[]): Promise<Map<string, ConnectorMeta[]>>;getCredential(id: string): Promise<KeychainCredentialMeta | null>;+ /** Decrypt an env credential the caller OWNS — no grant machinery, never someone else's. */+ readOwnSecret(ownerId: string, credentialId: string): Promise<string | null>;remove(ownerId: string, id: string): Promise<boolean>;createGrant(input: CreateGrantInput): Promise<KeychainGrant>;@@ -595,6 +617,8 @@ export function createKeychain(deps: {...(token.expiresAt !== undefined ? { expiresAt: token.expiresAt } : {}),refresh: {...(token.refreshToken ? { refreshTokenEnc: encryptSecret(token.refreshToken, deps.key) } : {}),+ ...(token.idToken ? { idTokenEnc: encryptSecret(token.idToken, deps.key) } : {}),+ ...(token.accountId ? { accountId: token.accountId } : {}),...(at ? { accountType: at } : {}),...(token.clientRef ? { clientRef: token.clientRef } : {}),...(token.grantedScopes ? { grantedScopes: token.grantedScopes } : {}),@@ -619,6 +643,8 @@ export function createKeychain(deps: {return {accessToken: decryptSecret(rec.secretEnc, deps.key),...(rec.refresh?.refreshTokenEnc ? { refreshToken: decryptSecret(rec.refresh.refreshTokenEnc, deps.key) } : {}),+ ...(rec.refresh?.idTokenEnc ? { idToken: decryptSecret(rec.refresh.idTokenEnc, deps.key) } : {}),+ ...(rec.refresh?.accountId ? { accountId: rec.refresh.accountId } : {}),...(rec.expiresAt !== undefined ? { expiresAt: rec.expiresAt } : {}),...(rec.refresh?.grantedScopes ? { grantedScopes: rec.refresh.grantedScopes } : {}),...(rec.refresh?.clientRef ? { clientRef: rec.refresh.clientRef } : {}),@@ -661,8 +687,17 @@ export function createKeychain(deps: {...(stored.clientRef ? { clientRef: stored.clientRef } : {}),...(stored.accountType ? { accountType: stored.accountType } : {}),...(stored.orgId ? { orgId: stored.orgId } : {}),+ ...(stored.idToken ? { idToken: stored.idToken } : {}),+ ...(stored.accountId ? { accountId: stored.accountId } : {}),...fresh,};+ // Compare-and-set: if another flight already rotated this credential,+ // keep its result rather than clobbering a newer refresh token.+ const current = await deps.creds.get(rec.id);+ if (current && (current.updatedAt !== rec.updatedAt || current.fingerprint !== rec.fingerprint)) {+ const latest = tryDecrypt(current, recToOAuthToken);+ return latest?.accessToken ?? null;+ }await putConnectorToken(host, principalId, merged, accountType);return merged.accessToken;} catch (e) {@@ -895,6 +930,12 @@ export function createKeychain(deps: {return rec ? toMeta(rec) : null;},+ async readOwnSecret(ownerId, id) {+ const rec = await getOwned(ownerId, id);+ if (!rec || rec.kind !== "env") return null;+ return tryDecrypt(rec, (r) => decryptSecret(r.secretEnc, deps.key));+ },+async remove(ownerId, id) {const rec = await getOwned(ownerId, id);if (!rec) return false;@@ -1167,6 +1208,23 @@ export function createKeychain(deps: {return connectorTokenForRecord(rec);},+ async connectorDerivedAuth(host, principalId, accountType) {+ const rec = await connectorRecord(host, principalId, accountType);+ if (!rec) return null;+ const accessToken = await connectorTokenForRecord(rec);+ if (accessToken === null) return null;+ // Re-read: a refresh inside connectorTokenForRecord may have rotated the record.+ const fresh = (await connectorRecord(host, principalId, accountType)) ?? rec;+ const token = tryDecrypt(fresh, recToOAuthToken);+ if (!token) return null;+ return {+ accessToken: token.accessToken,+ ...(token.idToken ? { idToken: token.idToken } : {}),+ ...(token.accountId ? { accountId: token.accountId } : {}),+ ...(token.expiresAt !== undefined ? { expiresAt: token.expiresAt } : {}),+ };+ },+async listConnectorsByOwners(ownerIds) {const t = now();return bucketByOwner(diff --git a/src/deployment/secret-schema.ts b/src/deployment/secret-schema.tsindex 4fce5abd6..f89b322f4 100644--- a/src/deployment/secret-schema.ts+++ b/src/deployment/secret-schema.ts@@ -45,7 +45,7 @@ export const CORE_SECRET_SPECS: readonly RuntimeSecretSpec[] = [const GATE_PREDICATES: Readonly<Record<SecretGate, (env: NodeJS.ProcessEnv) => boolean>> = {production: (env) => env.NODE_ENV === "production",- codex: (env) => env.HARNESS?.trim() === "codex",+ codex: (env) => env.HARNESS?.trim() === "codex" && !env.CODEX_AUTH_FILE?.trim() && !env.CODEX_AUTH_CREDENTIAL?.trim(),postgres: (env) => env.SESSION_STORE === "postgres" || env.RUN_STORE === "postgres",sprites: (env) => env.SANDBOX_BACKEND === "sprites" || env.SANDBOX_SECONDARY_BACKEND === "sprites",smolmachines: (env) => env.SANDBOX_BACKEND === "smolmachines" || env.SANDBOX_SECONDARY_BACKEND === "smolmachines",@@ -57,7 +57,9 @@ const GATE_PREDICATES: Readonly<Record<SecretGate, (env: NodeJS.ProcessEnv) => b"linear-oauth": (env) => Boolean(env.LINEAR_OAUTH_CLIENT_ID),"email-auth": (env) => env.AUTH_ALLOWED_EMAILS !== undefined,"model-anthropic": (env) => env.MODEL_PROVIDER?.trim() === "anthropic",- "model-openai": (env) => env.MODEL_PROVIDER?.trim() === "openai",+ "model-openai": (env) =>+ env.MODEL_PROVIDER?.trim() === "openai" &&+ !(env.HARNESS?.trim() === "codex" && (env.CODEX_AUTH_FILE?.trim() || env.CODEX_AUTH_CREDENTIAL?.trim())),"model-openrouter": (env) => env.MODEL_PROVIDER?.trim() === "openrouter",};diff --git a/src/harness/claude-harness.ts b/src/harness/claude-harness.tsindex 2edbb26eb..392c42f55 100644--- a/src/harness/claude-harness.ts+++ b/src/harness/claude-harness.ts@@ -59,6 +59,12 @@ export interface ClaudeHarnessOptions {execTimeoutCeilingMs?: number;backgroundJobTtlMs?: number;backgroundJobTtlMaxMs?: number;+ /**+ * Custodian of subscription auth (e.g. a keychain-held CLAUDE_CODE_OAUTH_TOKEN).+ * Resolved fresh per session start; merged over static env so the secret+ * never lives in process env or on the core host's disk.+ */+ authEnv?: () => Promise<NodeJS.ProcessEnv>;signals?: RunSignalStore;tasks?: TaskStore;}@@ -129,6 +135,15 @@ export function claudeChildEnv(source: NodeJS.ProcessEnv, jail: string): NodeJS.return env;}+function perUserClaudeEnv(env: NodeJS.ProcessEnv, oauthToken: string | undefined): NodeJS.ProcessEnv {+ if (!oauthToken) return env;+ const scoped = { ...env };+ delete scoped.ANTHROPIC_API_KEY;+ delete scoped.ANTHROPIC_AUTH_TOKEN;+ scoped.CLAUDE_CODE_OAUTH_TOKEN = oauthToken;+ return scoped;+}+export function claudeProcessIdentity(uid = process.getuid?.()): { uid: number; gid: number } | undefined {return uid === 0 ? { uid: 65534, gid: 65534 } : undefined;}@@ -433,12 +448,16 @@ export function createClaudeHarness(opts: ClaudeHarnessOptions = {}): Harness {swallow("claude: tape append", error);}};+ const authEnv = opts.authEnv ? await opts.authEnv() : undefined;const sdkQuery = query({prompt: queue,options: {abortController: controller,cwd: jail,- env: claudeChildEnv(opts.env ?? {}, jail),+ env: perUserClaudeEnv(+ claudeChildEnv(authEnv ? { ...opts.env, ...authEnv } : (opts.env ?? {}), jail),+ turn.claudeOauthToken,+ ),tools: allowSubagents ? ["Agent"] : [],skills: [],settingSources: [],diff --git a/src/harness/codex-app-server.ts b/src/harness/codex-app-server.tsindex 6eb7607e6..e65f3182e 100644--- a/src/harness/codex-app-server.ts+++ b/src/harness/codex-app-server.ts@@ -18,6 +18,104 @@ type JsonRpcMessage = {error?: { code?: number; message?: string; data?: unknown };};+type JsonRpcResultValidator<T> = (value: unknown) => value is T;+const MAX_CANCELLED_REQUEST_IDS = 256;++function isJsonRpcId(value: unknown): value is JsonRpcId {+ return (typeof value === "string" && value.length > 0) || (typeof value === "number" && Number.isFinite(value));+}++function isJsonRpcMessage(value: unknown): value is JsonRpcMessage {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const message = value as Record<string, unknown>;+ const hasId = "id" in message && message.id !== undefined;+ const hasMethod = "method" in message;+ const hasResult = "result" in message;+ const hasError = "error" in message;+ if (!hasId && !hasMethod) return false;+ if (hasId && !isJsonRpcId(message.id)) return false;+ if (hasMethod && typeof message.method !== "string") return false;+ if (hasMethod && (hasResult || hasError)) return false;+ if (!hasMethod && (!hasId || !(hasResult || hasError))) return false;+ if (hasResult && hasError) return false;+ if (hasError) {+ const error = message.error;+ if (!error || typeof error !== "object" || Array.isArray(error)) return false;+ const errorRecord = error as Record<string, unknown>;+ if (typeof errorRecord.code !== "number" || typeof errorRecord.message !== "string") return false;+ }+ return true;+}++const CODEX_DIAGNOSTIC_SENSITIVE_KEYS = new Set([+ "accesstoken",+ "refreshtoken",+ "idtoken",+ "apikey",+ "clientsecret",+ "credential",+ "credentials",+ "password",+ "passphrase",+ "secret",+ "token",+ "authorization",+ "proxyauthorization",+ "cookie",+ "setcookie",+]);++function diagnosticKeyIsSensitive(key: string): boolean {+ return CODEX_DIAGNOSTIC_SENSITIVE_KEYS.has(key.toLowerCase().replace(/[^a-z]/g, ""));+}++function redactStructuredDiagnosticsValue(value: unknown, sensitive = false): unknown {+ if (sensitive) return "[redacted]";+ if (Array.isArray(value)) return value.map((item) => redactStructuredDiagnosticsValue(item));+ if (!value || typeof value !== "object") return value;+ return Object.fromEntries(+ Object.entries(value).map(([key, item]) => [+ key,+ redactStructuredDiagnosticsValue(item, diagnosticKeyIsSensitive(key)),+ ]),+ );+}++function redactStructuredDiagnostics(value: string): string {+ try {+ const parsed: unknown = JSON.parse(value);+ if (!parsed || typeof parsed !== "object") return value;+ return JSON.stringify(redactStructuredDiagnosticsValue(parsed));+ } catch {+ return value;+ }+}++export function redactCodexDiagnostics(value: string): string {+ return redactStructuredDiagnostics(value)+ .replace(+ /(["']?(?:access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|apikey|client[_-]?secret|credential|credentials|password|passphrase|secret|token|authorization|proxy-authorization|cookie|set-cookie)["']?\s*[:=]\s*)\[[\s\S]*?(?:\]|$)/gi,+ "$1[redacted]",+ )+ .replace(+ /(["']?(?:access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|apikey|client[_-]?secret|credential|credentials|password|passphrase|secret|token|authorization|proxy-authorization|cookie|set-cookie)["']?\s*[:=]\s*)\{[\s\S]*$/gi,+ "$1{redacted}",+ )+ .replace(+ /(["']?(?:access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|apikey|client[_-]?secret|credential|credentials|password|passphrase|secret|token|authorization|proxy-authorization|cookie|set-cookie)["']?\s*[:=]\s*)(["'])(?:(?:\\[\s\S])|(?!\2)[\s\S])*(?:\2|$)/gi,+ "$1$2[redacted]$2",+ )+ .replace(+ /(["']?(?:access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|apikey|client[_-]?secret|credential|credentials|password|passphrase|secret|token|authorization|proxy-authorization|cookie|set-cookie)["']?\s*[:=]\s*)(?!(?:["']|\[))[^,\r\n}\]]+/gi,+ "$1[redacted]",+ )+ .replace(/\b(?:Basic|Digest)\s+\S+/gi, "[redacted]")+ .replace(/\bBearer\s+\S+/gi, "Bearer [redacted]")+ .replace(/\bsk-[A-Za-z0-9._-]{8,}/g, "[redacted]")+ .replace(/\b[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, "[redacted]")+ .replace(/\b(?=[A-Za-z0-9_-]*\d)[A-Za-z0-9_-]{32,}\b/g, "[redacted]");+}+export interface CodexAppServerOptions {binaryPath: string;cwd: string;@@ -30,7 +128,11 @@ export class CodexAppServer {readonly process: ChildProcess;private readonly options: CodexAppServerOptions;private nextId = 1;- private readonly pending = new Map<JsonRpcId, { resolve(value: unknown): void; reject(error: Error): void }>();+ private readonly pending = new Map<+ JsonRpcId,+ { resolve(value: unknown): void; reject(error: Error): void; validate?: JsonRpcResultValidator<unknown> }+ >();+ private readonly cancelledRequestIds = new Set<JsonRpcId>();private writeTail = Promise.resolve();private eventTail = Promise.resolve();private stderr = "";@@ -69,8 +171,9 @@ export class CodexAppServer {});this.process.once("close", (code, signal) => {this.closed = true;+ const stderr = redactCodexDiagnostics(this.stderr.trim());this.closeError = new Error(- `Codex app-server exited (${code ?? signal ?? "unknown"})${this.stderr.trim() ? `: ${this.stderr.trim()}` : ""}`,+ `Codex app-server exited (${code ?? signal ?? "unknown"})${stderr ? `: ${stderr}` : ""}`,);this.failAll(this.closeError);resolveProcessClosed();@@ -89,12 +192,47 @@ export class CodexAppServer {await this.notify("initialized");}- request<T = unknown>(method: string, params?: unknown): Promise<T> {+ request(method: string, params?: unknown, signal?: AbortSignal): Promise<unknown>;+ request<T>(method: string, params: unknown, validate: JsonRpcResultValidator<T>, signal?: AbortSignal): Promise<T>;+ request<T>(+ method: string,+ params?: unknown,+ validateOrSignal?: JsonRpcResultValidator<T> | AbortSignal,+ signal?: AbortSignal,+ ): Promise<unknown> {if (this.closed) return Promise.reject(new Error("Codex app-server is closed"));+ const validate = typeof validateOrSignal === "function" ? validateOrSignal : undefined;+ let requestSignal: AbortSignal | undefined;+ if (validate) requestSignal = signal;+ else if (typeof validateOrSignal !== "function") requestSignal = validateOrSignal;+ if (requestSignal?.aborted) return Promise.reject(new Error("Codex app-server request cancelled"));const id = this.nextId++;- const result = new Promise<T>((resolve, reject) => {- this.pending.set(id, { resolve: (value) => resolve(value as T), reject });+ let rejectResult!: (error: Error) => void;+ const result = new Promise<unknown>((resolve, reject) => {+ rejectResult = reject;+ this.pending.set(id, {+ resolve,+ reject,+ ...(validate ? { validate: validate as JsonRpcResultValidator<unknown> } : {}),+ });});+ if (requestSignal) {+ const onAbort = () => {+ if (!this.pending.delete(id)) return;+ if (this.cancelledRequestIds.size >= MAX_CANCELLED_REQUEST_IDS) {+ this.failAll(new CodexRpcError("Codex app-server exceeded its cancelled request limit"));+ this.process.kill("SIGTERM");+ } else {+ this.cancelledRequestIds.add(id);+ }+ rejectResult(new Error("Codex app-server request cancelled"));+ };+ requestSignal.addEventListener("abort", onAbort, { once: true });+ void result.then(+ () => requestSignal.removeEventListener("abort", onAbort),+ () => requestSignal.removeEventListener("abort", onAbort),+ );+ }void this.send({ id, method, ...(params === undefined ? {} : { params }) }).catch((error) => {const waiter = this.pending.get(id);this.pending.delete(id);@@ -120,21 +258,38 @@ export class CodexAppServer {if (!line.trim()) return;let message: JsonRpcMessage;try {- message = JSON.parse(line) as JsonRpcMessage;+ const parsed: unknown = JSON.parse(line);+ if (!isJsonRpcMessage(parsed)) throw new Error("Codex app-server emitted an invalid JSON-RPC message");+ message = parsed;} catch {- throw new Error(`Codex app-server emitted invalid JSON: ${line.slice(0, 500)}`);+ throw new Error(redactCodexDiagnostics(`Codex app-server emitted invalid JSON: ${line.slice(0, 500)}`));}if (message.id !== undefined && !message.method) {const waiter = this.pending.get(message.id);- if (!waiter) return;+ if (!waiter) {+ if (this.cancelledRequestIds.delete(message.id)) return;+ throw new CodexRpcError(`Codex app-server sent an unknown response id ${String(message.id)}`);+ }this.pending.delete(message.id);- if (message.error)+ if ("error" in message) {+ if (!message.error || typeof message.error !== "object") {+ waiter.reject(new CodexRpcError("Codex app-server response has an invalid error"));+ return;+ }waiter.reject(new CodexRpcError(- `Codex ${message.error.code ?? "error"}: ${message.error.message ?? JSON.stringify(message.error.data)}`,+ redactCodexDiagnostics(+ `Codex ${message.error.code ?? "error"}: ${message.error.message ?? JSON.stringify(message.error.data)}`,+ ),),);- else waiter.resolve(message.result);+ } else if ("result" in message) {+ if (waiter.validate && !waiter.validate(message.result)) {+ waiter.reject(new CodexRpcError("Codex app-server response has an invalid result"));+ return;+ }+ waiter.resolve(message.result);+ } else waiter.reject(new CodexRpcError("Codex app-server response is missing result or error"));return;}if (!message.method) return;@@ -165,5 +320,6 @@ export class CodexAppServer {private failAll(error: Error): void {for (const waiter of this.pending.values()) waiter.reject(error);this.pending.clear();+ this.cancelledRequestIds.clear();}}diff --git a/src/harness/codex-auth-file.ts b/src/harness/codex-auth-file.tsnew file mode 100644index 000000000..b5149914f--- /dev/null+++ b/src/harness/codex-auth-file.ts@@ -0,0 +1,102 @@+import { readFileSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve } from "node:path";++export type JsonObject = Record<string, unknown>;++const CODEX_OAUTH_MODES = new Set(["chatgpt", "chatgptAuthTokens"]);+export const CODEX_OAUTH_ISSUER = "https://auth.openai.com";++export function asObject(value: unknown): JsonObject | null {+ return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonObject) : null;+}++export function codexOAuthJwtAccountIdFromToken(value: unknown): string | undefined {+ if (typeof value !== "string" || value.split(".").length !== 3) return undefined;+ try {+ const payload = asObject(JSON.parse(Buffer.from(value.split(".")[1] ?? "", "base64url").toString("utf8")));+ const claims = payload ? asObject(payload["https://api.openai.com/auth"]) : null;+ return typeof claims?.chatgpt_account_id === "string" && claims.chatgpt_account_id+ ? claims.chatgpt_account_id+ : undefined;+ } catch {+ return undefined;+ }+}++export function codexOAuthJwtAccountId(value: unknown): string | undefined {+ const auth = asObject(value);+ const tokens = auth ? asObject(auth.tokens) : null;+ return codexOAuthJwtAccountIdFromToken(tokens?.id_token);+}++function readJsonFile(path: string): JsonObject | null {+ try {+ return asObject(JSON.parse(readFileSync(path, "utf8")));+ } catch {+ return null;+ }+}++function expandPath(path: string): string {+ if (path === "~") return homedir();+ if (path.startsWith("~/")) return join(homedir(), path.slice(2));+ return resolve(path);+}++export function codexAuthFileForEnv(env: NodeJS.ProcessEnv, includeDefault = false): string | undefined {+ const explicit = env.CODEX_AUTH_FILE?.trim();+ if (explicit) return expandPath(explicit);+ if (!includeDefault) return undefined;+ const codexHome = env.CODEX_HOME?.trim();+ if (codexHome) return join(expandPath(codexHome), "auth.json");+ const home = env.HOME?.trim();+ return home ? join(expandPath(home), ".codex", "auth.json") : undefined;+}++function isCodexOAuthAuth(value: unknown): value is JsonObject {+ const auth = asObject(value);+ if (!auth || typeof auth.auth_mode !== "string" || !CODEX_OAUTH_MODES.has(auth.auth_mode)) return false;+ const tokens = asObject(auth.tokens);+ return Boolean(+ tokens &&+ typeof tokens.access_token === "string" &&+ tokens.access_token &&+ typeof tokens.refresh_token === "string" &&+ tokens.refresh_token &&+ codexOAuthJwtAccountId(auth),+ );+}++export function readCodexOAuthAuthFile(path: string): JsonObject | null {+ try {+ if (statSync(path).mode & 0o077) return null;+ } catch {+ return null;+ }+ const auth = readJsonFile(path);+ return isCodexOAuthAuth(auth) ? auth : null;+}++export function sanitizedCodexOAuthAuth(auth: JsonObject): JsonObject {+ const copy: JsonObject = {};+ for (const key of ["auth_mode", "last_refresh", "tokens"] as const) {+ if (key === "tokens") {+ const tokens = asObject(auth.tokens);+ if (tokens) {+ copy.tokens = Object.fromEntries(+ ["access_token", "refresh_token", "id_token", "account_id"].flatMap((token) =>+ typeof tokens[token] === "string" ? [[token, tokens[token]]] : [],+ ),+ );+ }+ } else if (key in auth) copy[key] = auth[key];+ }+ return copy;+}++export function codexOAuthRefreshToken(value: unknown): string | undefined {+ const auth = asObject(value);+ const tokens = auth ? asObject(auth.tokens) : null;+ return typeof tokens?.refresh_token === "string" && tokens.refresh_token ? tokens.refresh_token : undefined;+}diff --git a/src/harness/codex-auth-store.ts b/src/harness/codex-auth-store.tsnew file mode 100644index 000000000..e4fad7390--- /dev/null+++ b/src/harness/codex-auth-store.ts@@ -0,0 +1,284 @@+import { CODEX_OAUTH_ISSUER, asObject, codexOAuthJwtAccountId, type JsonObject } from "./codex-auth-file.ts";+import { codexOAuthRefreshToken, readCodexOAuthAuthFile, sanitizedCodexOAuthAuth } from "./codex-auth-file.ts";+import type { CredentialFile, Keychain } from "../credentials/keychain.ts";+import { swallow } from "../util/errors.ts";+import { acquireCodexOAuthAuthLock, writeCodexOAuthAuthFile } from "./codex-auth.ts";++/**+ * A CodexAuthStore is the custodian of a ChatGPT-subscription Codex login.+ *+ * The store — not the harness, and never the child process — owns the+ * refresh token and the refresh loop. `load()` returns auth that is fresh+ * enough to hand to a child; the store refreshes centrally (and persists the+ * rotated tokens back to its backing storage) before returning when the+ * access token is near expiry. Children receive derived, ephemeral material+ * only (see `childCodexOAuthAuth`), so nothing a child does can rotate or+ * leak the long-lived credential.+ */+export interface CodexAuthStore {+ /** Where the credential lives, for logs and errors. Never includes secrets. */+ readonly description: string;+ /** Current auth, centrally refreshed when the access token is stale. Null when unavailable. */+ load(): Promise<JsonObject | null>;+}++/** The Codex CLI's public OAuth client id (auth.openai.com device/PKCE client). */+const CODEX_OAUTH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";++/** Refresh when the access token has less than this long to live. */+const REFRESH_SKEW_MS = 5 * 60_000;++const CODEX_AUTH_FILE_PATHS = [".codex/auth.json", "codex/auth.json"];++function jwtExpiryMs(token: unknown): number | undefined {+ if (typeof token !== "string" || token.split(".").length !== 3) return undefined;+ try {+ const payload = asObject(JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8")));+ return typeof payload?.exp === "number" ? payload.exp * 1000 : undefined;+ } catch {+ return undefined;+ }+}++/** Epoch ms when this auth's access token expires, if it carries an exp claim. */+export function codexOAuthAccessTokenExpiresAt(auth: JsonObject | null): number | undefined {+ return jwtExpiryMs(asObject(auth?.tokens)?.access_token);+}++/** Validate an already-parsed auth.json value the same way readCodexOAuthAuthFile validates a file. */+export function codexOAuthAuthFromValue(value: unknown): JsonObject | null {+ const auth = asObject(value);+ if (!auth) return null;+ const tokens = asObject(auth.tokens);+ const mode = typeof auth.auth_mode === "string" ? auth.auth_mode : "";+ if (!["chatgpt", "chatgptAuthTokens"].includes(mode)) return null;+ if (+ !tokens ||+ typeof tokens.access_token !== "string" ||+ !tokens.access_token ||+ typeof tokens.refresh_token !== "string" ||+ !tokens.refresh_token ||+ !codexOAuthJwtAccountId(auth)+ )+ return null;+ return auth;+}++/**+ * The material a Codex child process receives: the sanitized auth WITHOUT the+ * refresh token. The child can use the access token until it expires; only the+ * store may refresh. The next turn's `load()` re-materializes fresh tokens.+ */+/**+ * Child auth.json built straight from derived per-turn material (no refresh+ * token ever existed in this shape). Returns null unless the id/access token+ * carries a trusted ChatGPT account claim.+ */+export function childCodexAuthFromDerived(derived: {+ accessToken: string;+ idToken: string;+ accountId?: string;+}): JsonObject | null {+ const auth: JsonObject = {+ auth_mode: "chatgpt",+ tokens: {+ access_token: derived.accessToken,+ id_token: derived.idToken,+ ...(derived.accountId ? { account_id: derived.accountId } : {}),+ },+ };+ if (!derived.accessToken || !codexOAuthJwtAccountId(auth)) return null;+ return auth;+}++export function childCodexOAuthAuth(auth: JsonObject): JsonObject {+ const sanitized = sanitizedCodexOAuthAuth(auth);+ const tokens = asObject(sanitized.tokens);+ if (tokens) {+ const { refresh_token: _refresh, ...rest } = tokens;+ sanitized.tokens = rest;+ }+ return sanitized;+}++async function refreshCodexOAuth(auth: JsonObject, fetchImpl: typeof fetch): Promise<JsonObject | null> {+ const refreshToken = codexOAuthRefreshToken(auth);+ if (!refreshToken) return null;+ const response = await fetchImpl(`${CODEX_OAUTH_ISSUER}/oauth/token`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ client_id: CODEX_OAUTH_CLIENT_ID,+ grant_type: "refresh_token",+ refresh_token: refreshToken,+ scope: "openid profile email",+ }),+ });+ if (!response.ok) throw new Error(`Codex OAuth refresh failed: HTTP ${response.status}`);+ const body = asObject(await response.json().catch(() => null));+ if (!body || typeof body.access_token !== "string" || !body.access_token) {+ throw new Error("Codex OAuth refresh returned no access token");+ }+ const tokens = asObject(auth.tokens) ?? {};+ const next: JsonObject = {+ ...auth,+ last_refresh: new Date().toISOString(),+ tokens: {+ ...tokens,+ access_token: body.access_token,+ ...(typeof body.id_token === "string" && body.id_token ? { id_token: body.id_token } : {}),+ ...(typeof body.refresh_token === "string" && body.refresh_token ? { refresh_token: body.refresh_token } : {}),+ },+ };+ // The refreshed identity must stay on the same ChatGPT account.+ return codexOAuthAuthFromValue(next) && codexOAuthJwtAccountId(next) === codexOAuthJwtAccountId(auth) ? next : null;+}++function authNeedsRefresh(auth: JsonObject, now: number): boolean {+ const expiresAt = codexOAuthAccessTokenExpiresAt(auth);+ return typeof expiresAt === "number" && expiresAt - now < REFRESH_SKEW_MS;+}++interface KeychainCodexAuthStoreDeps {+ keychain: Keychain;+ /** Keychain credential id of the user's Codex ChatGPT login (a file credential holding auth.json). */+ credentialId: string;+ fetchImpl?: typeof fetch;+ now?: () => number;+}++function codexAuthFromFiles(files: CredentialFile[]): { path: string; auth: JsonObject } | null {+ for (const file of files) {+ const normalized = file.path.replace(/^\.\//, "");+ if (!CODEX_AUTH_FILE_PATHS.includes(normalized) && !normalized.endsWith("/auth.json")) continue;+ try {+ const auth = codexOAuthAuthFromValue(JSON.parse(Buffer.from(file.contentBase64, "base64").toString("utf8")));+ if (auth) return { path: file.path, auth };+ } catch {+ // fall through to the next candidate file+ }+ }+ return null;+}++/**+ * Keychain-backed Codex subscription auth. The credential (a file bundle+ * holding the Codex CLI's auth.json) lives encrypted in its owner's keychain;+ * core is the single writer. Refreshed tokens are persisted back to the+ * keychain with a compare-and-set against the refresh token they replaced, so+ * a concurrent rotation loses cleanly instead of clobbering.+ */+export function keychainCodexAuthStore(deps: KeychainCodexAuthStoreDeps): CodexAuthStore {+ const fetchImpl = deps.fetchImpl ?? fetch;+ const now = deps.now ?? Date.now;+ let refreshing: Promise<JsonObject | null> | null = null;++ const readCurrent = async (): Promise<{+ ownerId: string;+ service: string;+ path: string;+ auth: JsonObject;+ } | null> => {+ const meta = await deps.keychain.getCredential(deps.credentialId);+ if (!meta || meta.kind !== "file") return null;+ const bundles = await deps.keychain.materializeOwnFiles(meta.ownerId);+ const bundle = bundles.find((b) => b.credentialId === deps.credentialId);+ if (!bundle) return null;+ const found = codexAuthFromFiles(bundle.files);+ return found ? { ownerId: meta.ownerId, service: meta.service, ...found } : null;+ };++ const persist = async (+ current: { ownerId: string; service: string; path: string },+ replacedRefreshToken: string | undefined,+ next: JsonObject,+ ): Promise<boolean> => {+ // Compare-and-set: re-read and refuse if someone else rotated first.+ const latest = await readCurrent();+ if (!latest || codexOAuthRefreshToken(latest.auth) !== replacedRefreshToken) return false;+ await deps.keychain.save({+ ownerId: current.ownerId,+ service: current.service,+ files: [{ path: current.path, contentBase64: Buffer.from(JSON.stringify(next), "utf8").toString("base64") }],+ ...(codexOAuthAccessTokenExpiresAt(next) !== undefined+ ? { expiresAt: codexOAuthAccessTokenExpiresAt(next) }+ : {}),+ });+ return true;+ };++ return {+ description: `keychain credential ${deps.credentialId}`,+ async load(): Promise<JsonObject | null> {+ const current = await readCurrent();+ if (!current) return null;+ if (!authNeedsRefresh(current.auth, now())) return current.auth;+ // Single refresh in flight per store; concurrent loads share it.+ refreshing ??= (async () => {+ try {+ const next = await refreshCodexOAuth(current.auth, fetchImpl);+ if (!next) return null;+ await persist(current, codexOAuthRefreshToken(current.auth), next);+ return next;+ } finally {+ refreshing = null;+ }+ })();+ try {+ const refreshed = await refreshing;+ if (refreshed) return refreshed;+ } catch (error) {+ swallow("codex: central oauth refresh", error);+ }+ // A stale access token is still worth handing out: the provider decides.+ return (await readCurrent())?.auth ?? current.auth;+ },+ };+}++/**+ * File-backed store for local development: the operator's own+ * ~/.codex/auth.json (or CODEX_AUTH_FILE). Core refreshes centrally and writes+ * the rotated tokens back atomically under the file lock; children never see+ * the refresh token, so no child state ever syncs back.+ */+export function fileCodexAuthStore(+ path: string,+ fetchImpl: typeof fetch = fetch,+ now: () => number = Date.now,+): CodexAuthStore {+ let refreshing: Promise<JsonObject | null> | null = null;+ return {+ description: `auth file ${path}`,+ async load(): Promise<JsonObject | null> {+ const current = readCodexOAuthAuthFile(path);+ if (!current) return null;+ if (!authNeedsRefresh(current, now())) return current;+ refreshing ??= (async () => {+ try {+ const next = await refreshCodexOAuth(current, fetchImpl);+ if (!next) return null;+ const lock = await acquireCodexOAuthAuthLock(path, undefined, 10_000, 25);+ try {+ const latest = readCodexOAuthAuthFile(path);+ // Compare-and-set: refuse if another process rotated first.+ if (!latest || codexOAuthRefreshToken(latest) !== codexOAuthRefreshToken(current)) return latest;+ writeCodexOAuthAuthFile(path, next);+ } finally {+ await lock.release();+ }+ return next;+ } finally {+ refreshing = null;+ }+ })();+ try {+ const refreshed = await refreshing;+ if (refreshed) return refreshed;+ } catch (error) {+ swallow("codex: file oauth refresh", error);+ }+ return readCodexOAuthAuthFile(path) ?? current;+ },+ };+}diff --git a/src/harness/codex-auth.ts b/src/harness/codex-auth.tsnew file mode 100644index 000000000..f825cbed7--- /dev/null+++ b/src/harness/codex-auth.ts@@ -0,0 +1,175 @@+import { randomBytes } from "node:crypto";+import { open as openFile } from "node:fs/promises";+import {+ chmodSync,+ existsSync,+ mkdirSync,+ readFileSync,+ renameSync,+ rmSync,+ statSync,+ unlinkSync,+ writeFileSync,+} from "node:fs";+import { dirname, join } from "node:path";+import { swallow } from "../util/errors.ts";+import type { JsonObject } from "./codex-auth-file.ts";++export { codexAuthFileForEnv, readCodexOAuthAuthFile } from "./codex-auth-file.ts";++const heldOAuthLockPaths = new Set<string>();++function writeJsonAtomically(path: string, value: JsonObject): void {+ const directory = dirname(path);+ mkdirSync(directory, { recursive: true });+ const temporary = join(directory, `.qm-codex-auth-${process.pid}-${randomBytes(8).toString("hex")}.tmp`);+ try {+ writeFileSync(temporary, JSON.stringify(value), { mode: 0o600 });+ chmodSync(temporary, 0o600);+ renameSync(temporary, path);+ } finally {+ rmSync(temporary, { force: true });+ }+}++/** Atomically replace a Codex auth.json with 0600 permissions. */+export function writeCodexOAuthAuthFile(path: string, auth: JsonObject): void {+ writeJsonAtomically(path, auth);+}++function lockPath(sourcePath: string): string {+ return `${sourcePath}.lock`;+}++export interface CodexOAuthAuthLock {+ path: string;+ isHeld(): boolean;+ release(): Promise<void>;+}++function processAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return Boolean(error && typeof error === "object" && "code" in error && error.code !== "ESRCH");+ }+}++function removeStaleLock(path: string): boolean {+ let contents: string;+ try {+ contents = readFileSync(path, "utf8");+ const owner = Number(contents.trim().split(":", 1)[0]);+ if (Number.isInteger(owner) && owner > 0) {+ if (owner === process.pid && heldOAuthLockPaths.has(path)) return false;+ if (owner === process.pid) {+ if (Date.now() - statSync(path).mtimeMs <= 60_000) return false;+ } else if (processAlive(owner)) return false;+ } else if (Date.now() - statSync(path).mtimeMs <= 60_000) return false;+ } catch {+ return true;+ }+ const detached = `${path}.stale-${process.pid}-${randomBytes(6).toString("hex")}`;+ try {+ renameSync(path, detached);+ } catch {+ return true;+ }+ try {+ if (readFileSync(detached, "utf8") !== contents) {+ if (!existsSync(path)) renameSync(detached, path);+ return false;+ }+ unlinkSync(detached);+ return true;+ } catch {+ if (!existsSync(path)) {+ try {+ renameSync(detached, path);+ } catch (error) {+ swallow("codex: stale lock restore", error);+ }+ }+ return true;+ }+}++export async function acquireCodexOAuthAuthLock(+ sourcePath: string,+ signal?: AbortSignal,+ timeoutMs = 120_000,+ pollMs = 100,+): Promise<CodexOAuthAuthLock> {+ const path = lockPath(sourcePath);+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (signal?.aborted) throw new Error("Codex OAuth auth lock acquisition cancelled");+ try {+ const handle = await openFile(path, "wx", 0o600);+ const owner = `${process.pid}:${randomBytes(8).toString("hex")}`;+ try {+ await handle.writeFile(owner);+ heldOAuthLockPaths.add(path);+ } catch (error) {+ await handle.close().catch(() => undefined);+ try {+ unlinkSync(path);+ } catch (cleanupError) {+ swallow("codex: oauth lock creation cleanup", cleanupError);+ }+ throw error;+ }+ let released = false;+ return {+ path,+ isHeld() {+ if (released) return false;+ try {+ return readFileSync(path, "utf8") === owner;+ } catch {+ return false;+ }+ },+ async release() {+ if (released) return;+ released = true;+ await handle.close().catch(() => undefined);+ for (let attempt = 0; attempt < 3; attempt += 1) {+ try {+ if (readFileSync(path, "utf8") !== owner) {+ heldOAuthLockPaths.delete(path);+ return;+ }+ unlinkSync(path);+ heldOAuthLockPaths.delete(path);+ return;+ } catch (error) {+ if (attempt === 2) {+ heldOAuthLockPaths.delete(path);+ throw error;+ } else await new Promise<void>((resolveWait) => setTimeout(resolveWait, 10));+ }+ }+ },+ };+ } catch (error) {+ const code = error && typeof error === "object" && "code" in error ? error.code : undefined;+ if (code !== "EEXIST") throw error;+ removeStaleLock(path);+ await new Promise<void>((resolveWait) => {+ const onAbort = () => {+ clearTimeout(timer);+ signal?.removeEventListener("abort", onAbort);+ resolveWait();+ };+ const timer = setTimeout(() => {+ signal?.removeEventListener("abort", onAbort);+ resolveWait();+ }, pollMs);+ signal?.addEventListener("abort", onAbort, { once: true });+ });+ }+ }+ throw new Error("timed out acquiring the Codex OAuth auth lock");+}diff --git a/src/harness/codex-harness.ts b/src/harness/codex-harness.tsindex 46d79a12b..22cb1de34 100644--- a/src/harness/codex-harness.ts+++ b/src/harness/codex-harness.ts@@ -13,7 +13,14 @@ import type { ScopeId, SessionEntry } from "../types.ts";import { swallow } from "../util/errors.ts";import { countTokens } from "../util/tokens.ts";import { parseSecurityScreenVerdict, SECURITY_SCREEN_SYSTEM_PROMPT } from "../security/security-posture.ts";-import { CodexAppServer, CodexRpcError } from "./codex-app-server.ts";+import { CodexAppServer, CodexRpcError, redactCodexDiagnostics } from "./codex-app-server.ts";+import { codexAuthFileForEnv, readCodexOAuthAuthFile } from "./codex-auth.ts";+import {+ childCodexAuthFromDerived,+ childCodexOAuthAuth,+ fileCodexAuthStore,+ type CodexAuthStore,+} from "./codex-auth-store.ts";import { defineHarness, type Harness, type HarnessTurnInput, type HarnessTurnResult } from "./harness.ts";import { coreToolOptions, createPiTools, type PiToolsOptions, type ToolContextRef } from "./pi-tools.ts";import type { McpToolDescriptor } from "../mcp/mcp-tool-service.ts";@@ -36,6 +43,10 @@ export interface CodexHarnessOptions {backgroundJobTtlMs?: number;backgroundJobTtlMaxMs?: number;appServerStartTimeoutMs?: number;+ /** Cap on simultaneous per-user app-server launches (default 8). */+ maxConcurrentUserServers?: number;+ /** Custodian of the ChatGPT-subscription Codex login (keychain-backed in production). */+ authStore?: CodexAuthStore;signals?: RunSignalStore;tasks?: TaskStore;}@@ -80,7 +91,59 @@ type BridgedTool = {type CodexItem = Record<string, unknown> & { type: string };type CodexTurn = { id: string; status: string; error?: { message?: string } | null; items?: CodexItem[] };+const CODEX_TERMINAL_TURN_STATUSES = new Set(["completed", "failed", "interrupted", "cancelled", "canceled"]);++function isCodexThreadStart(value: unknown): value is { thread: { id: string }; model?: string } {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const response = value as Record<string, unknown>;+ const thread = response.thread;+ return Boolean(+ thread &&+ typeof thread === "object" &&+ !Array.isArray(thread) &&+ typeof (thread as Record<string, unknown>).id === "string" &&+ (!("model" in response) || typeof response.model === "string"),+ );+}++function isCodexTurnStart(value: unknown): value is { turn: CodexTurn } {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const turn = (value as Record<string, unknown>).turn;+ if (!turn || typeof turn !== "object" || Array.isArray(turn)) return false;+ const response = turn as Record<string, unknown>;+ return typeof response.id === "string" && typeof response.status === "string";+}++function isCodexTurn(value: unknown): value is CodexTurn {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const turn = value as Record<string, unknown>;+ if (typeof turn.id !== "string" || typeof turn.status !== "string") return false;+ if (!CODEX_TERMINAL_TURN_STATUSES.has(turn.status)) return false;+ if (+ "items" in turn &&+ (!Array.isArray(turn.items) ||+ turn.items.some(+ (item) =>+ !item ||+ typeof item !== "object" ||+ Array.isArray(item) ||+ typeof (item as Record<string, unknown>).type !== "string" ||+ !(item as Record<string, unknown>).type,+ ))+ )+ return false;+ const error = turn.error;+ return (+ error === undefined ||+ error === null ||+ (typeof error === "object" &&+ !Array.isArray(error) &&+ (!("message" in error) || typeof (error as Record<string, unknown>).message === "string"))+ );+}+type ActiveTurn = {+ server: CodexAppServer;threadId: string;turn: HarnessTurnInput;tools: Map<string, BridgedTool>;@@ -102,7 +165,15 @@ type ActiveTurn = {stopped: boolean;};-type Runtime = { server: CodexAppServer; jail: string };+type Runtime = {+ server: CodexAppServer;+ jail: string;+};+type StartingRuntime = {+ promise: Promise<Runtime>;+ abort: AbortController;+ waiters: number;+};const CODEX_START_TIMEOUT_MS = 30_000;const CODEX_NON_RETRYABLE_PATTERN =@@ -113,7 +184,8 @@ export function codexNonRetryable(message: string): boolean {}export function codexProviderFailure(message: string): Error {- return codexNonRetryable(message) ? new NonRetryableTurnError(message) : new Error(message);+ const safe = redactCodexDiagnostics(message);+ return codexNonRetryable(safe) ? new NonRetryableTurnError(safe) : new Error(safe);}const CODEX_CHILD_TOOL_NAMES = new Set(["execute", "read", "write", "publish", "memory", "history", "background"]);@@ -187,20 +259,41 @@ const CODEX_ENV_PASSTHROUGH = ["CODEX_ACCESS_TOKEN",] as const;-export function codexChildEnv(source: NodeJS.ProcessEnv, jail: string): NodeJS.ProcessEnv {+export function codexChildEnv(+ source: NodeJS.ProcessEnv,+ jail: string,+ auth?: Record<string, unknown> | null,+): NodeJS.ProcessEnv {const env: NodeJS.ProcessEnv = {HOME: jail,CODEX_HOME: join(jail, "codex-home"),};+ const authPath = codexAuthFileForEnv(source, true);+ const fileAuth = () => (authPath ? readCodexOAuthAuthFile(authPath) : null);+ const oauthAuth = auth !== undefined ? auth : fileAuth();for (const name of CODEX_ENV_PASSTHROUGH) {+ if (oauthAuth && (name === "OPENAI_API_KEY" || name === "OPENAI_BASE_URL" || name === "CODEX_ACCESS_TOKEN"))+ continue;if (source[name] !== undefined) env[name] = source[name];}return env;}-export function prepareCodexHome(source: NodeJS.ProcessEnv, jail: string): string {+export function prepareCodexHome(+ source: NodeJS.ProcessEnv,+ jail: string,+ auth?: Record<string, unknown> | null,+): string {const target = join(jail, "codex-home");mkdirSync(target, { recursive: true });+ const authPath = codexAuthFileForEnv(source, true);+ const fileAuth = () => (authPath ? readCodexOAuthAuthFile(authPath) : null);+ const oauthAuth = auth !== undefined ? auth : fileAuth();+ if (oauthAuth) {+ // The child receives derived, ephemeral material only: no refresh token.+ writeFileSync(join(target, "auth.json"), JSON.stringify(childCodexOAuthAuth(oauthAuth)), { mode: 0o600 });+ return target;+ }if (source.OPENAI_API_KEY) {writeFileSync(join(target, "auth.json"),@@ -356,9 +449,37 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {DEFAULT_CODEX_MODEL_ID,].find((id): id is string => modelSupportedByHarness(id, "codex"))!;const defaultTurnWallClockMs = opts.turnWallClockMs ?? CONFIG_DEFAULTS.turnWallClockSec * 1000;+ const sourceEnv = opts.env ?? {};+ const authPath = codexAuthFileForEnv(sourceEnv, true);+ const authStore: CodexAuthStore | undefined =+ opts.authStore ?? (authPath && readCodexOAuthAuthFile(authPath) ? fileCodexAuthStore(authPath) : undefined);+ const oauthConfigured = Boolean(authStore);+ const closeAbort = new AbortController();let runtime: Runtime | null = null;- let starting: Promise<Runtime> | null = null;+ let starting: StartingRuntime | null = null;let startingServer: CodexAppServer | null = null;+ let setupUsers = 0;+ let runtimeCleanupRequested = false;+ // Per-user turns get their own short-lived app-server (own jail, own auth) —+ // measured at ~0.5s/9MB per spawn — so accounts never share a process and+ // org turns are never serialized behind them. The semaphore only bounds+ // simultaneous process launches.+ const ephemeralServers = new Set<CodexAppServer>();+ const maxConcurrentSpawns = opts.maxConcurrentUserServers ?? 8;+ let activeSpawns = 0;+ const spawnWaiters: Array<() => void> = [];+ const acquireSpawnSlot = async (): Promise<() => void> => {+ while (activeSpawns >= maxConcurrentSpawns)+ await new Promise<void>((resolveWait) => spawnWaiters.push(resolveWait));+ activeSpawns += 1;+ let released = false;+ return () => {+ if (released) return;+ released = true;+ activeSpawns -= 1;+ spawnWaiters.shift()?.();+ };+ };const processCollabItem = async (state: ActiveTurn, item: CodexItem): Promise<void> => {if (item.type !== "collabAgentToolCall") return;@@ -421,231 +542,483 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {}};- const ensureRuntime = async (): Promise<Runtime> => {- if (runtime && runtime.server.process.exitCode === null) return runtime;- if (starting) return await starting;- starting = (async () => {- const jail = mkdtempSync(join(tmpdir(), "qm-codex-"));- const sourceEnv = opts.env ?? {};- prepareCodexHome(sourceEnv, jail);- const binaryPath = opts.binaryPath ?? resolve("node_modules/.bin/codex");- const server = new CodexAppServer({- binaryPath,- cwd: jail,- env: codexChildEnv(sourceEnv, jail),- onNotification: async (method, params) => {- const p = (params ?? {}) as Record<string, unknown>;- const threadId = typeof p.threadId === "string" ? p.threadId : "";- const state = active.get(threadId);- if (!state) return;- if (method === "thread/tokenUsage/updated") {- const totals = codexUsageTotals(p);- if (totals) state.usageByThread.set(threadId, totals);- const usage = codexTokenUsageUpdate(p, state.usageInputTotals.get(threadId));- if (!usage) return;- state.usageInputTotals.set(threadId, usage.totalInputTokens);- state.modelCalls++;- state.turn.recordModelCall({- model: state.model,- inputTokens: usage.inputTokens,- entryCount: state.turn.history.length,- });- }- if (method === "item/agentMessage/delta" && threadId === state.threadId && typeof p.delta === "string") {- state.firstOutputAt ??= Date.now();- state.turn.onDelta?.(p.delta);- }- if ((method === "item/started" || method === "item/completed") && p.item && typeof p.item === "object") {- const item = p.item as CodexItem;- if (method === "item/completed") {- state.completedItems.push(item);- if (state.turn.tape) {- try {- await state.turn.tape({- kind: "message",- harness: "codex",- scopeLabel: state.turn.scopeLabel,- payload: item,- });- } catch (error) {- state.tapeWriteFailed = true;- swallow("codex: tape append", error);- }+ const buildServer = (jail: string, childEnv: NodeJS.ProcessEnv): CodexAppServer => {+ const binaryPath = opts.binaryPath ?? resolve("node_modules/.bin/codex");+ const server: CodexAppServer = new CodexAppServer({+ binaryPath,+ cwd: jail,+ env: childEnv,+ onNotification: async (method, params) => {+ const p = (params ?? {}) as Record<string, unknown>;+ const threadId = typeof p.threadId === "string" ? p.threadId : "";+ const state = active.get(threadId);+ if (!state || state.server !== server) return;+ if (method === "thread/tokenUsage/updated") {+ const totals = codexUsageTotals(p);+ if (totals) state.usageByThread.set(threadId, totals);+ const usage = codexTokenUsageUpdate(p, state.usageInputTotals.get(threadId));+ if (!usage) return;+ state.usageInputTotals.set(threadId, usage.totalInputTokens);+ state.modelCalls++;+ state.turn.recordModelCall({+ model: state.model,+ inputTokens: usage.inputTokens,+ entryCount: state.turn.history.length,+ });+ }+ if (method === "item/agentMessage/delta" && threadId === state.threadId && typeof p.delta === "string") {+ state.firstOutputAt ??= Date.now();+ state.turn.onDelta?.(p.delta);+ }+ if ((method === "item/started" || method === "item/completed") && p.item && typeof p.item === "object") {+ const item = p.item as CodexItem;+ if (method === "item/completed") {+ state.completedItems.push(item);+ if (state.turn.tape) {+ try {+ await state.turn.tape({+ kind: "message",+ harness: "codex",+ scopeLabel: state.turn.scopeLabel,+ payload: item,+ });+ } catch (error) {+ state.tapeWriteFailed = true;+ swallow("codex: tape append", error);}}- await processCollabItem(state, item);}- if (method === "turn/completed" && threadId === state.threadId) {- const completed = p.turn as CodexTurn | undefined;- if (completed)- state.resolve(completed.items?.length ? completed : { ...completed, items: state.completedItems });+ await processCollabItem(state, item);+ }+ if (method === "turn/completed" && threadId === state.threadId) {+ const completed = p.turn as CodexTurn | undefined;+ if (!isCodexTurn(completed)) {+ state.reject(new CodexRpcError("Codex app-server sent an invalid turn/completed payload"));+ return;}- },- onRequest: async (method, params) => {- if (method !== "item/tool/call") throw new Error(`unsupported Codex request ${method}`);- const p = (params ?? {}) as Record<string, unknown>;- const threadId = String(p.threadId ?? "");- const state = active.get(threadId);- if (!state) throw new Error("inactive Codex thread");- const name = String(p.tool ?? "");- const callId = String(p.callId ?? "");- if (threadId !== state.threadId && !codexChildToolAllowed(name))- throw new Error(`Codex child requested unavailable tool ${name}`);- const tool = state.tools.get(name);- if (!tool) throw new Error(`Codex requested unavailable tool ${name}`);- state.responseItems.push({- type: "function_call",- call_id: callId,- name,- arguments: JSON.stringify(p.arguments ?? {}),+ state.resolve(completed.items?.length ? completed : { ...completed, items: state.completedItems });+ }+ },+ onRequest: async (method, params) => {+ if (method !== "item/tool/call") throw new Error(`unsupported Codex request ${method}`);+ const p = (params ?? {}) as Record<string, unknown>;+ const threadId = String(p.threadId ?? "");+ const state = active.get(threadId);+ if (!state || state.server !== server) throw new Error("inactive Codex thread");+ const name = String(p.tool ?? "");+ const callId = String(p.callId ?? "");+ if (threadId !== state.threadId && !codexChildToolAllowed(name))+ throw new Error(`Codex child requested unavailable tool ${name}`);+ const tool = state.tools.get(name);+ if (!tool) throw new Error(`Codex requested unavailable tool ${name}`);+ state.responseItems.push({+ type: "function_call",+ call_id: callId,+ name,+ arguments: JSON.stringify(p.arguments ?? {}),+ });+ try {+ const result = await tool.execute(callId, p.arguments ?? {});+ const output = toolText(result);+ state.responseItems.push({ type: "function_call_output", call_id: callId, output });+ if (result.terminate || state.turn.cancel?.aborted)+ setImmediate(() => {+ const requestingTurnId = String(p.turnId ?? "");+ if (threadId !== state.threadId && requestingTurnId) {+ void server.request("turn/interrupt", { threadId, turnId: requestingTurnId }).catch(() => undefined);+ }+ void state.interrupt?.();+ });+ return { contentItems: [{ type: "inputText", text: output }], success: true };+ } catch (error) {+ const output = error instanceof Error ? error.message : String(error);+ state.responseItems.push({ type: "function_call_output", call_id: callId, output });+ return { contentItems: [{ type: "inputText", text: output }], success: false };+ }+ },+ });+ return server;+ };++ const ensureRuntime = async (+ registerCancel?: (release: () => void) => void,+ startupDeadline = 0,+ ): Promise<Runtime> => {+ if (runtime && runtime.server.process.exitCode === null) return runtime;+ if (runtime) {+ const stale = runtime;+ runtime = null;+ runtimeCleanupRequested = false;+ const staleError = stale.server.error() ?? new Error("Codex app-server exited during a turn");+ for (const [threadId, state] of active) {+ if (state.server !== stale.server) continue;+ state.reject(staleError);+ active.delete(threadId);+ }+ await stale.server.close().catch(() => undefined);+ rmSync(stale.jail, { recursive: true, force: true });+ }+ let startup = starting;+ if (startup?.abort.signal.aborted) {+ if (starting === startup) starting = null;+ startup = null;+ }+ if (!startup) {+ const startupAbort = new AbortController();+ const promise = (async () => {+ const jail = mkdtempSync(join(tmpdir(), "qm-codex-"));+ const sourceAuth = authStore ? await authStore.load() : null;+ let server!: CodexAppServer;+ try {+ if (oauthConfigured && !sourceAuth)+ throw new Error(`Codex OAuth auth is unavailable (${authStore!.description})`);+ prepareCodexHome(sourceEnv, jail, oauthConfigured ? sourceAuth : undefined);+ if (startupAbort.signal.aborted) throw new Error("Codex app-server startup cancelled");+ server = buildServer(jail, codexChildEnv(sourceEnv, jail, oauthConfigured ? sourceAuth : undefined));+ startingServer = server;+ if (startupAbort.signal.aborted) throw new Error("Codex app-server startup cancelled");+ } catch (error) {+ await server?.close().catch(() => undefined);+ rmSync(jail, { recursive: true, force: true });+ throw error;+ }+ let startTimer: NodeJS.Timeout | undefined;+ try {+ const initializationTimeout = startupDeadline+ ? Math.min(+ opts.appServerStartTimeoutMs ?? CODEX_START_TIMEOUT_MS,+ Math.max(1, startupDeadline - Date.now()),+ )+ : (opts.appServerStartTimeoutMs ?? CODEX_START_TIMEOUT_MS);+ await Promise.race([+ server.initialize(),+ new Promise<never>((_, reject) => {+ startTimer = setTimeout(+ () => reject(new Error("Codex app-server initialization timed out")),+ initializationTimeout,+ );+ }),+ ]);+ } catch (error) {+ await server.close().catch(() => undefined);+ rmSync(jail, { recursive: true, force: true });+ throw error;+ } finally {+ if (startTimer) clearTimeout(startTimer);+ if (startingServer === server) startingServer = null;+ }+ runtime = { server, jail };+ runtimeCleanupRequested = false;+ server.process.once("close", () => {+ void (async () => {+ const currentRuntime = runtime?.server === server;+ const closeError = server.error() ?? new Error("Codex app-server exited during a turn");+ for (const [threadId, state] of active) {+ if (state.server !== server) continue;+ state.reject(closeError);+ active.delete(threadId);+ }+ if (!currentRuntime) {+ rmSync(jail, { recursive: true, force: true });+ return;+ }+ runtime = null;+ runtimeCleanupRequested = false;+ if (!closeAbort.signal.aborted) rmSync(jail, { recursive: true, force: true });+ })().catch((error) => {+ swallow("codex: provider close cleanup", error);+ try {+ rmSync(jail, { recursive: true, force: true });+ } catch (cleanupError) {+ swallow("codex: provider close jail cleanup", cleanupError);+ }});- try {- const result = await tool.execute(callId, p.arguments ?? {});- const output = toolText(result);- state.responseItems.push({ type: "function_call_output", call_id: callId, output });- if (result.terminate || state.turn.cancel?.aborted)- setImmediate(() => {- const requestingTurnId = String(p.turnId ?? "");- if (threadId !== state.threadId && requestingTurnId) {- void server.request("turn/interrupt", { threadId, turnId: requestingTurnId }).catch(() => undefined);- }- void state.interrupt?.();- });- return { contentItems: [{ type: "inputText", text: output }], success: true };- } catch (error) {- const output = error instanceof Error ? error.message : String(error);- state.responseItems.push({ type: "function_call_output", call_id: callId, output });- return { contentItems: [{ type: "inputText", text: output }], success: false };- }+ });+ return runtime;+ })();+ startup = { promise, abort: startupAbort, waiters: 0 };+ starting = startup;+ const current = startup;+ void promise.then(+ () => {+ if (starting === current) starting = null;},- });- startingServer = server;- let startTimer: NodeJS.Timeout | undefined;- try {- await Promise.race([- server.initialize(),- new Promise<never>((_, reject) => {- startTimer = setTimeout(- () => reject(new Error("Codex app-server initialization timed out")),- opts.appServerStartTimeoutMs ?? CODEX_START_TIMEOUT_MS,- );- }),- ]);- } catch (error) {- await server.close().catch(() => undefined);- rmSync(jail, { recursive: true, force: true });- throw error;- } finally {- if (startTimer) clearTimeout(startTimer);- if (startingServer === server) startingServer = null;+ () => {+ if (starting === current) starting = null;+ },+ );+ }+ const current = startup;+ current.waiters += 1;+ let released = false;+ const release = () => {+ if (released) return;+ released = true;+ current.waiters -= 1;+ if (current.waiters === 0 && starting === current) {+ current.abort.abort();+ void startingServer?.close().catch(() => undefined);}- runtime = { server, jail };- server.process.once("close", () => {- if (runtime?.server !== server) return;- for (const state of active.values())- state.reject(server.error() ?? new Error("Codex app-server exited during a turn"));- active.clear();- runtime = null;- rmSync(jail, { recursive: true, force: true });- });- return runtime;- })();+ };+ registerCancel?.(release);try {- return await starting;+ return await current.promise;} finally {- starting = null;+ release();+ }+ };++ const closeIdleRuntime = async (): Promise<void> => {+ const current = runtime;+ if (!current) return;+ if (active.size || setupUsers) {+ runtimeCleanupRequested = true;+ return;}+ runtimeCleanupRequested = false;+ if (runtime === current) runtime = null;+ await current.server.close().catch(() => undefined);+ rmSync(current.jail, { recursive: true, force: true });};const runPrompt = async (turn: HarnessTurnInput, toolsEnabled = true): Promise<HarnessTurnResult> => {if (turn.cancel?.aborted) return { reply: "", stopped: true };+ setupUsers += 1;+ let setupUserReleased = false;+ const releaseSetupUser = () => {+ if (setupUserReleased) return;+ setupUserReleased = true;+ setupUsers -= 1;+ };const wallMs = turn.turnWallClockMs ?? defaultTurnWallClockMs;const deadline = wallMs > 0 ? Date.now() + wallMs : 0;+ const runtimeRecoveryDeadline = Date.now() + Math.max(wallMs, CODEX_START_TIMEOUT_MS);const setupCancelled = new Error("Codex setup cancelled");const setupTimedOut = new NonRetryableTurnError(`Codex turn exceeded ${Math.round(wallMs / 1000)}s wall clock`);let rejectSetup!: (error: Error) => void;let setupSettled = false;+ let releaseStartupWaiter: () => void = () => {};+ const authAcquireAbort = new AbortController();const setupStop = new Promise<never>((_, reject) => {rejectSetup = reject;});const stopSetup = (error: Error) => {if (setupSettled) return;setupSettled = true;+ releaseStartupWaiter();+ authAcquireAbort.abort();rejectSetup(error);};const onSetupCancel = () => stopSetup(setupCancelled);turn.cancel?.addEventListener("abort", onSetupCancel, { once: true });const setupTimer = wallMs > 0 ? setTimeout(() => stopSetup(setupTimedOut), wallMs) : undefined;- const awaitSetup = <T>(operation: Promise<T>): Promise<T> => Promise.race([operation, setupStop]);- let rt: Runtime;- try {- rt = await awaitSetup(ensureRuntime());- } catch (error) {+ const finishSetup = () => {setupSettled = true;if (setupTimer) clearTimeout(setupTimer);turn.cancel?.removeEventListener("abort", onSetupCancel);+ releaseSetupUser();+ };+ const awaitSetup = <T>(operation: Promise<T>): Promise<T> => Promise.race([operation, setupStop]);+ let ephemeral: Runtime | undefined;+ let releaseSpawnSlot: (() => void) | undefined;+ const closeEphemeral = async (): Promise<void> => {+ const current = ephemeral;+ ephemeral = undefined;+ try {+ if (current) {+ ephemeralServers.delete(current.server);+ await current.server.close().catch(() => undefined);+ rmSync(current.jail, { recursive: true, force: true });+ }+ } finally {+ releaseSpawnSlot?.();+ releaseSpawnSlot = undefined;+ }+ };+ let rt: Runtime;+ if (turn.codexAuth) {+ // Per-user turn: a dedicated short-lived app-server on this user's+ // account. No shared jail, no cross-account serialization — the org+ // runtime is never touched.+ const userAuth = childCodexAuthFromDerived(turn.codexAuth);+ if (!userAuth) {+ finishSetup();+ throw new NonRetryableTurnError(+ "Your ChatGPT connection is incomplete — disconnect and sign in again from the AI account panel.",+ );+ }+ const jail = mkdtempSync(join(tmpdir(), "qm-codex-user-"));+ try {+ releaseSpawnSlot = await awaitSetup(acquireSpawnSlot());+ prepareCodexHome(sourceEnv, jail, userAuth);+ const server = buildServer(jail, codexChildEnv(sourceEnv, jail, userAuth));+ ephemeral = { server, jail };+ ephemeralServers.add(server);+ server.process.once("close", () => {+ const closeError = server.error() ?? new Error("Codex app-server exited during a turn");+ for (const [threadId, state] of active) {+ if (state.server !== server) continue;+ state.reject(closeError);+ active.delete(threadId);+ }+ });+ let startTimer: NodeJS.Timeout | undefined;+ try {+ await awaitSetup(+ Promise.race([+ server.initialize(),+ new Promise<never>((_, reject) => {+ startTimer = setTimeout(+ () => reject(new Error("Codex app-server initialization timed out")),+ opts.appServerStartTimeoutMs ?? CODEX_START_TIMEOUT_MS,+ );+ }),+ ]),+ );+ } finally {+ if (startTimer) clearTimeout(startTimer);+ }+ rt = ephemeral;+ } catch (error) {+ if (!ephemeral) rmSync(jail, { recursive: true, force: true });+ await closeEphemeral();+ finishSetup();+ if (error === setupCancelled) return { reply: "", stopped: true };+ throw error;+ }+ } else {+ try {+ rt = await awaitSetup(+ ensureRuntime((release) => {+ releaseStartupWaiter = release;+ }),+ );+ } catch (error) {+ finishSetup();+ await closeIdleRuntime();+ if (error === setupCancelled) return { reply: "", stopped: true };+ throw error;+ }+ }+ const failSetup = async (error: unknown): Promise<HarnessTurnResult> => {+ await closeEphemeral();+ finishSetup();+ await closeIdleRuntime();if (error === setupCancelled) return { reply: "", stopped: true };throw error;+ };+ try {+ if (!ephemeral && oauthConfigured) {+ // Re-materialize fresh, centrally refreshed tokens for this turn. The+ // store owns the refresh token; the child jail only ever holds+ // short-lived derived material.+ const sourceAuth = await awaitSetup(authStore!.load());+ if (!sourceAuth) {+ rmSync(join(rt.jail, "codex-home", "auth.json"), { force: true });+ throw new NonRetryableTurnError(`Codex OAuth auth is unavailable (${authStore!.description})`);+ }+ if (runtime !== rt || rt.server.process.exitCode !== null) {+ if (Date.now() >= runtimeRecoveryDeadline)+ throw new NonRetryableTurnError("Codex OAuth runtime recovery timed out");+ rt = await awaitSetup(+ ensureRuntime((release) => {+ releaseStartupWaiter = release;+ }, runtimeRecoveryDeadline),+ );+ } else {+ prepareCodexHome(sourceEnv, rt.jail, sourceAuth);+ }+ }+ } catch (error) {+ return failSetup(error);}- const ref = codexToolContext(turn);- const toolAbort = new AbortController();- ref.abortSignal = toolAbort.signal;- const tools = toolsEnabled ? asTools(ref, toolOptions(opts, turn)) : [];- const dynamicTools = tools.map((tool) => ({- type: "function",- name: tool.name,- description: tool.description,- inputSchema: tool.parameters,- }));- const model = modelSupportedByHarness(turn.model, "codex") ? turn.model! : resolveModelId(turn.scopeLabel);- const threadStartRequest = {- ...(model ? { model } : {}),- cwd: rt.jail,- approvalPolicy: "never",- sandbox: "read-only",- ephemeral: true,- baseInstructions: turn.systemPrompt,- developerInstructions:- "Use the supplied dynamic tools for all workspace, execution, memory, history, and surface operations. The built-in working directory is an empty read-only control jail, not the user's workspace.",- dynamicTools,- experimentalRawEvents: true,- environments: [],- config: {- web_search: "disabled",- ...(codexReasoningEffort(turn.thinkingLevel)- ? { model_reasoning_effort: codexReasoningEffort(turn.thinkingLevel) }- : {}),- features: {- shell_tool: false,- unified_exec: false,- shell_snapshot: false,- apps: false,- plugins: false,- browser_use: false,- browser_use_external: false,- computer_use: false,- image_generation: false,- in_app_browser: false,- multi_agent: !turn.readOnly,- request_permissions_tool: false,- tool_suggest: false,+ let ref!: ToolContextRef;+ let toolAbort!: AbortController;+ let tools!: BridgedTool[];+ let dynamicTools!: Array<Record<string, unknown>>;+ let model: string | undefined;+ let threadStartRequest!: Record<string, unknown>;+ try {+ ref = codexToolContext(turn);+ toolAbort = new AbortController();+ ref.abortSignal = toolAbort.signal;+ tools = toolsEnabled ? asTools(ref, toolOptions(opts, turn)) : [];+ dynamicTools = tools.map((tool) => ({+ type: "function",+ name: tool.name,+ description: tool.description,+ inputSchema: tool.parameters,+ }));+ model = modelSupportedByHarness(turn.model, "codex") ? turn.model! : resolveModelId(turn.scopeLabel);+ threadStartRequest = {+ ...(model ? { model } : {}),+ cwd: rt.jail,+ approvalPolicy: "never",+ sandbox: "read-only",+ ephemeral: true,+ baseInstructions: turn.systemPrompt,+ developerInstructions:+ "Use the supplied dynamic tools for all workspace, execution, memory, history, and surface operations. The built-in working directory is an empty read-only control jail, not the user's workspace.",+ dynamicTools,+ experimentalRawEvents: true,+ environments: [],+ config: {+ web_search: "disabled",+ ...(codexReasoningEffort(turn.thinkingLevel)+ ? { model_reasoning_effort: codexReasoningEffort(turn.thinkingLevel) }+ : {}),+ features: {+ shell_tool: false,+ unified_exec: false,+ shell_snapshot: false,+ apps: false,+ plugins: false,+ browser_use: false,+ browser_use_external: false,+ computer_use: false,+ image_generation: false,+ in_app_browser: false,+ multi_agent: !turn.readOnly,+ request_permissions_tool: false,+ tool_suggest: false,+ },},- },- };+ };+ } catch (error) {+ return failSetup(error);+ }let started: { thread: { id: string }; model?: string };try {- started = await awaitSetup(rt.server.request("thread/start", threadStartRequest));+ const requestTimeoutMs = deadline ? Math.max(1, deadline - Date.now()) : CODEX_START_TIMEOUT_MS;+ let requestTimer: NodeJS.Timeout | undefined;+ const requestAbort = new AbortController();+ started = await awaitSetup(+ Promise.race([+ rt.server.request(+ "thread/start",+ threadStartRequest,+ isCodexThreadStart,+ AbortSignal.any([authAcquireAbort.signal, closeAbort.signal, requestAbort.signal]),+ ),+ new Promise<never>((_, reject) => {+ requestTimer = setTimeout(() => {+ requestAbort.abort();+ reject(new NonRetryableTurnError("Codex thread/start request timed out"));+ }, requestTimeoutMs);+ }),+ ]).finally(() => {+ if (requestTimer) clearTimeout(requestTimer);+ }),+ );} catch (error) {- setupSettled = true;- if (setupTimer) clearTimeout(setupTimer);- turn.cancel?.removeEventListener("abort", onSetupCancel);- if (error === setupCancelled) return { reply: "", stopped: true };- throw error;+ return failSetup(error);}- const threadId = started.thread.id;- const replay = replayItems(reconstructMessagesFromHistory(turn.history));- let userEntry: SessionEntry;+ let threadId!: string;+ let replay!: ReturnType<typeof replayItems>;+ let userEntry!: SessionEntry;try {+ threadId = started.thread.id;+ replay = replayItems(reconstructMessagesFromHistory(turn.history));if (replay.length) await awaitSetup(rt.server.request("thread/inject_items", { threadId, items: replay }));userEntry = await awaitSetup(turn.emit({@@ -659,51 +1032,56 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {}),);} catch (error) {- setupSettled = true;- if (setupTimer) clearTimeout(setupTimer);- turn.cancel?.removeEventListener("abort", onSetupCancel);- if (error === setupCancelled) return { reply: "", stopped: true };- throw error;+ return failSetup(error);}- setupSettled = true;- if (setupTimer) clearTimeout(setupTimer);- turn.cancel?.removeEventListener("abort", onSetupCancel);let resolveCompleted!: (value: CodexTurn) => void;let rejectCompleted!: (error: Error) => void;- const completed = new Promise<CodexTurn>((resolveTurn, rejectTurn) => {- resolveCompleted = resolveTurn;- rejectCompleted = rejectTurn;- });- const inputText = codexTurnInputText(turn);- const input = [- userInput(inputText),- ...(turn.images ?? []).map((image) => ({- type: "image",- url: `data:${image.mimeType};base64,${image.dataBase64}`,- })),- ];- const selectedModel = model ?? started.model ?? "codex-default";- const state: ActiveTurn = {- threadId,- turn,- tools: new Map(tools.map((tool) => [tool.name, tool])),- resolve: resolveCompleted,- reject: rejectCompleted,- responseItems: [],- completedItems: [],- taskIds: new Map(),- taskStatuses: new Map(),- taskResults: new Set(),- model: selectedModel,- modelCalls: 0,- usageInputTotals: new Map(),- usageByThread: new Map(),- firstOutputAt: null,- fallbackInputTokens: countTokens(JSON.stringify({ replay, input })),- tapeWriteFailed: false,- stopped: false,- };+ let completed!: Promise<CodexTurn>;+ let inputText!: string;+ let input!: Array<Record<string, unknown>>;+ let selectedModel!: string;+ let state!: ActiveTurn;+ try {+ completed = new Promise<CodexTurn>((resolveTurn, rejectTurn) => {+ resolveCompleted = resolveTurn;+ rejectCompleted = rejectTurn;+ });+ void completed.catch(() => undefined);+ inputText = codexTurnInputText(turn);+ input = [+ userInput(inputText),+ ...(turn.images ?? []).map((image) => ({+ type: "image",+ url: `data:${image.mimeType};base64,${image.dataBase64}`,+ })),+ ];+ selectedModel = model ?? started.model ?? "codex-default";+ state = {+ server: rt.server,+ threadId,+ turn,+ tools: new Map(tools.map((tool) => [tool.name, tool])),+ resolve: resolveCompleted,+ reject: rejectCompleted,+ responseItems: [],+ completedItems: [],+ taskIds: new Map(),+ taskStatuses: new Map(),+ taskResults: new Set(),+ model: selectedModel,+ modelCalls: 0,+ usageInputTotals: new Map(),+ usageByThread: new Map(),+ firstOutputAt: null,+ fallbackInputTokens: countTokens(JSON.stringify({ replay, input })),+ tapeWriteFailed: false,+ stopped: false,+ };+ } catch (error) {+ return failSetup(error);+ }active.set(threadId, state);+ finishSetup();const promptEnvelope = {threadStart: {...threadStartRequest,@@ -713,20 +1091,35 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {const startedAt = Date.now();const recordRequest = async (): Promise<void> => {if (!turn.recordLlmRequest) return;+ const recordAbort = new AbortController();+ let recordTimer: NodeJS.Timeout | undefined;try {- await turn.recordLlmRequest({- turnSeq: userEntry.seq,- step: 0,- model: selectedModel,- promptEnvelope,- truncated: Boolean(turn.images?.length),- transport: { modelId: selectedModel },- ttftMs: state.firstOutputAt ? state.firstOutputAt - startedAt : null,- durationMs: Date.now() - startedAt,- usage: sumUsage(state.usageByThread),- });+ await Promise.race([+ turn.recordLlmRequest(+ {+ turnSeq: userEntry.seq,+ step: 0,+ model: selectedModel,+ promptEnvelope,+ truncated: Boolean(turn.images?.length),+ transport: { modelId: selectedModel },+ ttftMs: state.firstOutputAt ? state.firstOutputAt - startedAt : null,+ durationMs: Date.now() - startedAt,+ usage: sumUsage(state.usageByThread),+ },+ recordAbort.signal,+ ),+ new Promise<never>((_, reject) => {+ recordTimer = setTimeout(() => {+ recordAbort.abort();+ reject(new Error("Codex llm request recording timed out"));+ }, 5_000);+ }),+ ]);} catch (error) {swallow("codex: llm request record", error);+ } finally {+ if (recordTimer) clearTimeout(recordTimer);}};if (turn.tape) {@@ -766,7 +1159,8 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {};state.interrupt = () => interrupt(false);const onCancel = () => {- void interrupt(false);+ runtimeCleanupRequested = true;+ void interrupt(true);};if (turn.cancel) {if (turn.cancel.aborted) onCancel();@@ -792,10 +1186,40 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {): null;let timer: NodeJS.Timeout | undefined;+ const turnStartAbort = new AbortController();+ let turnStartTimedOut = false;+ const cleanupErrors: unknown[] = [];+ let turnResult: HarnessTurnResult | undefined;try {- const response = await rt.server- .request<{ turn: CodexTurn }>("turn/start", { threadId, input, ...(model ? { model } : {}) })+ const turnStartSignals = [closeAbort.signal, turnStartAbort.signal];+ if (turn.cancel) turnStartSignals.push(turn.cancel);+ const turnStartTimeoutMs = deadline ? Math.max(1, deadline - Date.now()) : CODEX_START_TIMEOUT_MS;+ let turnStartTimer: NodeJS.Timeout | undefined;+ const response = await Promise.race([+ rt.server.request<{ turn: CodexTurn }>(+ "turn/start",+ { threadId, input, ...(model ? { model } : {}) },+ isCodexTurnStart,+ AbortSignal.any(turnStartSignals),+ ),+ new Promise<never>((_, reject) => {+ turnStartTimer = setTimeout(() => {+ turnStartTimedOut = true;+ runtimeCleanupRequested = true;+ turnStartAbort.abort();+ reject(new NonRetryableTurnError("Codex turn/start request timed out"));+ }, turnStartTimeoutMs);+ }),+ ])+ .finally(() => {+ if (turnStartTimer) clearTimeout(turnStartTimer);+ }).catch((error: unknown) => {+ if (turnStartTimedOut) {+ const timeoutError = new NonRetryableTurnError("Codex turn/start request timed out");+ timeoutError.cause = error;+ throw timeoutError;+ }throw error instanceof CodexRpcError ? codexProviderFailure(error.message) : error;});turnId = response.turn.id;@@ -807,6 +1231,7 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {completed,new Promise<never>((_, reject) => {timer = setTimeout(() => {+ runtimeCleanupRequested = true;void interrupt(false);reject(setupTimedOut);}, remainingWallMs);@@ -822,39 +1247,68 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {});}if (result.status === "failed") throw codexProviderFailure(result.error?.message ?? "Codex turn failed");- const terminal = ref.silentRequested || ref.pausedOnApproval;- const reply = terminal ? "" : textFromTurn(result);- for (const thinking of reasoningFromTurn(result))- await turn.emit({ type: "thinking", payload: { thinking }, scopeLabel: turn.scopeLabel });- if (reply && !terminal)- await turn.emit({- type: "assistant",- payload: { text: reply, stopped: state.stopped || undefined },- scopeLabel: turn.scopeLabel,- });- return {- reply,- ...(state.stopped ? { stopped: true as const } : {}),- ...(ref.silentRequested ? { silent: true } : {}),- ...(ref.pendingApprovals?.length ? { pendingApprovals: ref.pendingApprovals } : {}),- ...(ref.pausedOnApproval ? { pausedOnApproval: true } : {}),- modelCalls: state.modelCalls,- ...(state.tapeWriteFailed ? { tapeWriteFailed: true } : {}),- };+ if (turn.cancel?.aborted) {+ runtimeCleanupRequested = true;+ turnResult = { reply: "", stopped: true };+ } else {+ const terminal = ref.silentRequested || ref.pausedOnApproval;+ const reply = terminal ? "" : textFromTurn(result);+ for (const thinking of reasoningFromTurn(result))+ await turn.emit({ type: "thinking", payload: { thinking }, scopeLabel: turn.scopeLabel });+ if (reply && !terminal)+ await turn.emit({+ type: "assistant",+ payload: { text: reply, stopped: state.stopped || undefined },+ scopeLabel: turn.scopeLabel,+ });+ turnResult = {+ reply,+ ...(state.stopped ? { stopped: true as const } : {}),+ ...(ref.silentRequested ? { silent: true } : {}),+ ...(ref.pendingApprovals?.length ? { pendingApprovals: ref.pendingApprovals } : {}),+ ...(ref.pausedOnApproval ? { pausedOnApproval: true } : {}),+ modelCalls: state.modelCalls,+ ...(state.tapeWriteFailed ? { tapeWriteFailed: true } : {}),+ };+ }+ } catch (error) {+ if (turn.cancel?.aborted) {+ runtimeCleanupRequested = true;+ turnResult = { reply: "", stopped: true };+ } else {+ throw error;+ }} finally {if (timer) clearTimeout(timer);- await stopSignals?.();- await recordRequest();+ try {+ await stopSignals?.();+ } catch (error) {+ cleanupErrors.push(error);+ }turn.cancel?.removeEventListener("abort", onCancel);for (const [taskId, status] of state.taskStatuses) {if (status === "pending" || status === "in_progress") {- await transitionTask(opts.tasks, taskId, status, "failed", turn.runId ?? turn.session.id);+ try {+ await transitionTask(opts.tasks, taskId, status, "failed", turn.runId ?? turn.session.id);+ } catch (error) {+ cleanupErrors.push(error);+ }}}for (const [activeThreadId, activeState] of active) {if (activeState === state) active.delete(activeThreadId);}+ try {+ await closeEphemeral();+ } catch (error) {+ swallow("codex: ephemeral runtime close", error);+ }+ if (runtimeCleanupRequested) await closeIdleRuntime();+ await recordRequest();}+ if (cleanupErrors.length) throw cleanupErrors[0];+ if (!turnResult) throw new Error("Codex turn did not produce a result");+ return turnResult;};const single = async (@@ -908,12 +1362,19 @@ export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {{runTurn: runPrompt,close: async () => {+ closeAbort.abort();await startingServer?.close().catch(() => undefined);- await starting?.catch(() => undefined);+ await starting?.promise.catch(() => undefined);+ for (const server of ephemeralServers) {+ ephemeralServers.delete(server);+ await server.close().catch(() => undefined);+ }const current = runtime;- if (current) {+ if (current || active.size) {for (const state of active.values()) state.reject(new Error("Codex harness closed during a turn"));active.clear();+ }+ if (current) {await current.server.close();rmSync(current.jail, { recursive: true, force: true });if (runtime === current) runtime = null;diff --git a/src/harness/harness.ts b/src/harness/harness.tsindex 77940e80a..0fb73ecae 100644--- a/src/harness/harness.ts+++ b/src/harness/harness.ts@@ -10,6 +10,7 @@ import type {} from "../sessions/session-store.ts";export type { GapWork } from "../sessions/session-store.ts";import type { OverheardEntryPayload } from "./replay.ts";+import type { ProviderKeys } from "./pi-harness.ts";import type { ToolContext } from "../tools/primitives.ts";import type { SecurityScreenVerdict } from "../security/security-posture.ts";@@ -43,7 +44,18 @@ interface HarnessSecurityScreenInput {payload: string;signal: AbortSignal;recordModelCall(rec: { model: string; inputTokens: number; entryCount: number }): void;- recordLlmRequest?(rec: HarnessLlmRequestRecord): void | Promise<void>;+ recordLlmRequest?(rec: HarnessLlmRequestRecord, signal?: AbortSignal): void | Promise<void>;+}++/**+ * Derived per-turn Codex auth: access + id token only. The refresh token+ * stays in the keychain; the harness (and its jail) never see it.+ */+export interface CodexTurnAuth {+ accessToken: string;+ idToken: string;+ accountId?: string;+ expiresAt?: number;}export interface HarnessTurnInput {@@ -85,8 +97,12 @@ export interface HarnessTurnInput {tapeFold?: unknown[];scopeLabel: ScopeId;orgScopeId: ScopeId;+ providerKeys?: ProviderKeys;+ runtimePinned?: boolean;+ claudeOauthToken?: string;+ codexAuth?: CodexTurnAuth;recordModelCall(rec: { model: string; inputTokens: number; entryCount: number }): void;- recordLlmRequest?(rec: HarnessLlmRequestRecord): void | Promise<void>;+ recordLlmRequest?(rec: HarnessLlmRequestRecord, signal?: AbortSignal): void | Promise<void>;onProgress?(p: { toolCalls: number; tokens?: number }): void;onGapWork?(sink: (work: GapWork) => void): void;onDelta?(chunk: string): void;diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.tsindex 73ff2ba74..bf887b988 100644--- a/src/harness/pi-harness.ts+++ b/src/harness/pi-harness.ts@@ -1285,6 +1285,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {tapeMode?: "shadow" | "serve",tapeFold?: unknown[],tape?: HarnessTurnInput["tape"],+ turnProviderKeys?: ProviderKeys,): Promise<{ entry: TurnSession; compileMs: number; tapeWriteFailed: boolean }> {const compileStart = Date.now();const cacheBoundary =@@ -1324,7 +1325,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {const composedPrompt = systemPrompt + (seedPlan === "preamble" ? replayPreamble(history) : "");const model = getRequiredModel(resolveModelId(turnScope));- const modelRuntime = await buildModelRuntime(await resolveProviderKeys());+ const modelRuntime = await buildModelRuntime(turnProviderKeys ?? (await resolveProviderKeys()));const ref: ToolContextRef = { current: null };const { resourceLoader, cwd, agentDir } = await createIsolatedResources(tempDirPrefix, composedPrompt);const compileMs = Date.now() - compileStart;@@ -1503,6 +1504,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {turn.tapeMode,turn.tapeFold,turn.tape,+ turn.providerKeys,);try {const turnWallClockMs = turn.turnWallClockMs ?? defaultTurnWallClockMs;diff --git a/src/model/codex-device-login.ts b/src/model/codex-device-login.tsnew file mode 100644index 000000000..421dccb5c--- /dev/null+++ b/src/model/codex-device-login.ts@@ -0,0 +1,164 @@+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { CodexAppServer } from "../harness/codex-app-server.ts";+import { codexOAuthAuthFromValue } from "../harness/codex-auth-store.ts";+import { asObject, codexOAuthJwtAccountId, type JsonObject } from "../harness/codex-auth-file.ts";+import type { UserOAuthTokens } from "./user-model-credential-store.ts";+import type { ChatGPTDevicePrompt } from "./subscription-oauth.ts";++const LOGIN_TTL_MS = 15 * 60 * 1000;+const START_TIMEOUT_MS = 30_000;++interface PendingLogin {+ server: CodexAppServer;+ home: string;+ loginId: string;+ expiresAt: number;+ outcome: Promise<UserOAuthTokens>;+ settled: boolean;+}++function tokensFromAuthJson(home: string): UserOAuthTokens {+ const raw = JSON.parse(readFileSync(join(home, "auth.json"), "utf8")) as unknown;+ const auth = codexOAuthAuthFromValue(raw);+ if (!auth) throw new Error("Codex login completed but wrote no usable ChatGPT auth");+ const tokens = asObject((auth as JsonObject).tokens)!;+ const accessToken = tokens.access_token as string;+ const idToken = typeof tokens.id_token === "string" ? tokens.id_token : undefined;+ const accountId = codexOAuthJwtAccountId(auth) ?? undefined;+ return {+ accessToken,+ refreshToken: tokens.refresh_token as string,+ ...(idToken ? { idToken } : {}),+ ...(accountId ? { accountId } : {}),+ };+}++/**+ * ChatGPT device-code login driven through the vendored Codex binary's own+ * login RPCs (`account/login/start` type `chatgptDeviceCode`) instead of a+ * hand-rolled flow against undocumented endpoints. The app-server runs with a+ * throwaway CODEX_HOME; on completion we harvest the auth.json it wrote and+ * tear everything down — the tokens' durable home is the keychain.+ */+export function createCodexDeviceLogin(opts: { binaryPath?: string; env?: NodeJS.ProcessEnv } = {}) {+ const pending = new Map<string, PendingLogin>();++ const cleanup = async (login: PendingLogin): Promise<void> => {+ pending.delete(login.loginId);+ await login.server.close().catch(() => undefined);+ rmSync(login.home, { recursive: true, force: true });+ };++ const sweep = (): void => {+ const now = Date.now();+ for (const login of pending.values()) {+ if (now > login.expiresAt) void cleanup(login);+ }+ };++ return {+ async start(): Promise<ChatGPTDevicePrompt> {+ sweep();+ const home = mkdtempSync(join(tmpdir(), "qm-codex-login-"));+ const binaryPath = opts.binaryPath ?? resolve("node_modules/.bin/codex");+ let completed!: (tokens: UserOAuthTokens) => void;+ let failed!: (error: Error) => void;+ const outcome = new Promise<UserOAuthTokens>((resolvePromise, rejectPromise) => {+ completed = resolvePromise;+ failed = rejectPromise;+ });+ const server = new CodexAppServer({+ binaryPath,+ cwd: home,+ env: { ...opts.env, CODEX_HOME: home },+ onNotification: async (method, params) => {+ if (method !== "account/login/completed") return;+ const p = (params ?? {}) as Record<string, unknown>;+ if (p.success === true) {+ try {+ completed(tokensFromAuthJson(home));+ } catch (error) {+ failed(error instanceof Error ? error : new Error(String(error)));+ }+ } else {+ failed(new Error(typeof p.error === "string" && p.error ? p.error : "ChatGPT login failed"));+ }+ },+ onRequest: async (method) => {+ throw new Error(`unsupported Codex request ${method}`);+ },+ });+ try {+ let startTimer: NodeJS.Timeout | undefined;+ try {+ await Promise.race([+ server.initialize(),+ new Promise<never>((_, reject) => {+ startTimer = setTimeout(+ () => reject(new Error("Codex app-server initialization timed out")),+ START_TIMEOUT_MS,+ );+ }),+ ]);+ } finally {+ if (startTimer) clearTimeout(startTimer);+ }+ const raw = await server.request("account/login/start", { type: "chatgptDeviceCode" });+ const result = (raw ?? {}) as { loginId?: string; verificationUrl?: string; userCode?: string };+ if (!result.loginId || !result.verificationUrl || !result.userCode)+ throw new Error("Codex device login response missing fields");+ const login: PendingLogin = {+ server,+ home,+ loginId: result.loginId,+ expiresAt: Date.now() + LOGIN_TTL_MS,+ outcome,+ settled: false,+ };+ // Settle-once bookkeeping and teardown on completion either way.+ void outcome+ .catch(() => undefined)+ .finally(() => {+ login.settled = true;+ });+ pending.set(result.loginId, login);+ return {+ deviceAuthId: result.loginId,+ userCode: result.userCode,+ verificationUrl: result.verificationUrl,+ intervalMs: 5_000,+ expiresAt: login.expiresAt,+ };+ } catch (error) {+ await server.close().catch(() => undefined);+ rmSync(home, { recursive: true, force: true });+ throw error;+ }+ },++ /** Poll a pending login: tokens when done, "pending" while waiting. */+ async poll(loginId: string): Promise<UserOAuthTokens | "pending"> {+ sweep();+ const login = pending.get(loginId);+ if (!login) throw new Error("login expired or unknown — start again");+ if (!login.settled) {+ const raced = await Promise.race([login.outcome.catch((e: Error) => e), Promise.resolve("pending" as const)]);+ if (raced === "pending" && !login.settled) return "pending";+ }+ try {+ const tokens = await login.outcome;+ await cleanup(login);+ return tokens;+ } catch (error) {+ await cleanup(login);+ throw error;+ }+ },++ async close(): Promise<void> {+ for (const login of pending.values()) await cleanup(login);+ },+ };+}diff --git a/src/model/pi-models.ts b/src/model/pi-models.tsindex b23d86c01..05bb1602c 100644--- a/src/model/pi-models.ts+++ b/src/model/pi-models.ts@@ -7,6 +7,18 @@ const getModel = getBuiltinModel as unknown as (provider: string, id: string) =>export const DEFAULT_AGENT_MODEL_ID = "claude-opus-5";export const DEFAULT_CODEX_MODEL_ID = "gpt-5.6-sol";+/**+ * pi-ai's ChatGPT-subscription provider: the same model ids as "openai",+ * served from the Codex backend and authenticated with a ChatGPT OAuth+ * access token instead of an API key. Model ids are namespaced "codex/<id>"+ * so an id can never silently flip between metered and subscription serving.+ */+export const CODEX_SUBSCRIPTION_PROVIDER = "openai-codex";+const CODEX_SUBSCRIPTION_PREFIX = "codex/";++export function codexSubscriptionModelId(id: string): string {+ return id.startsWith(CODEX_SUBSCRIPTION_PREFIX) ? id : CODEX_SUBSCRIPTION_PREFIX + id;+}export const THINKING_LEVELS = ["auto", "low", "medium", "high", "xhigh", "max", "ultracode"] as const;export const HARNESS_IDS = ["pi", "opencode", "codex", "claude", "mock"] as const;export type HarnessId = (typeof HARNESS_IDS)[number];@@ -163,6 +175,12 @@ export function registerOpenRouterCatalogModel(definition: OpenRouterCatalogMode}export function resolveModel(id: string): PiModel | undefined {+ if (id.startsWith(CODEX_SUBSCRIPTION_PREFIX)) {+ const m = getModel(CODEX_SUBSCRIPTION_PROVIDER, id.slice(CODEX_SUBSCRIPTION_PREFIX.length));+ // Keep the namespaced id: pi resolves the turn's model by this string,+ // and the un-prefixed id belongs to the metered "openai" provider.+ return m ? { ...m, id } : undefined;+ }const entry = REGISTRY_BY_ID.get(id);if (entry?.clone) {const template = builtinModel(entry.clone.template);@@ -234,6 +252,11 @@ export interface ModelProviderAvailability {anthropic: boolean;openai: boolean;openrouter: boolean;+ codexOAuth?: boolean;+}++function providerFlags(value: ModelProviderAvailability): ModelProviderAvailability {+ return { anthropic: value.anthropic, openai: value.openai, openrouter: value.openrouter };}export function modelServiceable(id: string, providers: ModelProviderAvailability): boolean {@@ -257,9 +280,10 @@ export function modelProviderAvailabilityFor(configKeys: ModelProviderAvailability,managedKeys: ModelProviderAvailability = configKeys,): ModelProviderAvailability {- if (harness === "pi") return managedKeys;- if (harness === "opencode") return { ...configKeys, openrouter: false };- if (harness === "codex") return configKeys;+ if (harness === "pi") return providerFlags(managedKeys);+ if (harness === "opencode") return { ...providerFlags(configKeys), openrouter: false };+ if (harness === "codex")+ return { ...providerFlags(configKeys), openai: configKeys.openai || Boolean(configKeys.codexOAuth) };return ALL_PROVIDERS_AVAILABLE;}diff --git a/src/model/subscription-oauth.ts b/src/model/subscription-oauth.tsnew file mode 100644index 000000000..c98379e0b--- /dev/null+++ b/src/model/subscription-oauth.ts@@ -0,0 +1,133 @@+import { codeChallengeS256, generateCodeVerifier } from "../connectors/oauth.ts";+import { CODEX_OAUTH_ISSUER, codexOAuthJwtAccountIdFromToken } from "../harness/codex-auth-file.ts";+import type { UserOAuthTokens } from "./user-model-credential-store.ts";++const CHATGPT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";+const CHATGPT_SCOPE = "openid profile email offline_access";++const CLAUDE_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";+const CLAUDE_AUTHORIZE = "https://claude.ai/oauth/authorize";+const CLAUDE_TOKEN = "https://console.anthropic.com/v1/oauth/token";+const CLAUDE_REDIRECT = "https://platform.claude.com/oauth/code/callback";+const CLAUDE_SCOPE = "org:create_api_key user:profile user:inference";++function decodeJwtClaims(jwt: string | undefined): Record<string, unknown> | undefined {+ if (!jwt) return undefined;+ const part = jwt.split(".")[1];+ if (!part) return undefined;+ try {+ return JSON.parse(Buffer.from(part, "base64url").toString("utf8"));+ } catch {+ return undefined;+ }+}++function chatgptAccountId(tokens: { idToken?: string; accessToken: string }): string | undefined {+ return codexOAuthJwtAccountIdFromToken(tokens.idToken) ?? codexOAuthJwtAccountIdFromToken(tokens.accessToken);+}++function tokenExpiry(raw: { expires_in?: number; access_token?: string }): number | undefined {+ if (typeof raw.expires_in === "number") return Date.now() + raw.expires_in * 1000;+ const claims = decodeJwtClaims(raw.access_token);+ const exp = claims?.exp;+ return typeof exp === "number" ? exp * 1000 : undefined;+}++export interface ChatGPTDevicePrompt {+ deviceAuthId: string;+ userCode: string;+ verificationUrl: string;+ intervalMs: number;+ expiresAt: number;+}++export async function refreshChatGPTTokens(refreshToken: string): Promise<UserOAuthTokens> {+ const res = await fetch(`${CODEX_OAUTH_ISSUER}/oauth/token`, {+ method: "POST",+ headers: { "Content-Type": "application/json", Accept: "application/json" },+ body: JSON.stringify({+ grant_type: "refresh_token",+ refresh_token: refreshToken,+ client_id: CHATGPT_CLIENT_ID,+ scope: CHATGPT_SCOPE,+ }),+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new Error(`chatgpt refresh failed (${res.status})`);+ const raw = (await res.json()) as {+ access_token?: string;+ refresh_token?: string;+ id_token?: string;+ expires_in?: number;+ };+ if (!raw.access_token) throw new Error("chatgpt refresh missing access_token");+ return {+ accessToken: raw.access_token,+ refreshToken: raw.refresh_token ?? refreshToken,+ idToken: raw.id_token,+ accountId: chatgptAccountId({ idToken: raw.id_token, accessToken: raw.access_token }),+ expiresAt: tokenExpiry(raw),+ };+}++export interface ClaudeAuthStart {+ authorizeUrl: string;+ verifier: string;+}++export function startClaudeLogin(): ClaudeAuthStart {+ const verifier = generateCodeVerifier();+ const challenge = codeChallengeS256(verifier);+ const url = new URL(CLAUDE_AUTHORIZE);+ url.searchParams.set("code", "true");+ url.searchParams.set("client_id", CLAUDE_CLIENT_ID);+ url.searchParams.set("response_type", "code");+ url.searchParams.set("redirect_uri", CLAUDE_REDIRECT);+ url.searchParams.set("scope", CLAUDE_SCOPE);+ url.searchParams.set("code_challenge", challenge);+ url.searchParams.set("code_challenge_method", "S256");+ url.searchParams.set("state", verifier);+ return { authorizeUrl: url.toString(), verifier };+}++export async function completeClaudeLogin(pastedCode: string, verifier: string): Promise<UserOAuthTokens> {+ const [code, state] = pastedCode.trim().split("#");+ const res = await fetch(CLAUDE_TOKEN, {+ method: "POST",+ headers: { "Content-Type": "application/json", Accept: "application/json" },+ body: JSON.stringify({+ grant_type: "authorization_code",+ client_id: CLAUDE_CLIENT_ID,+ code,+ state: state ?? verifier,+ code_verifier: verifier,+ redirect_uri: CLAUDE_REDIRECT,+ }),+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new Error(`claude token exchange failed (${res.status})`);+ const raw = (await res.json()) as { access_token?: string; refresh_token?: string; expires_in?: number };+ if (!raw.access_token) throw new Error("claude token response missing access_token");+ return {+ accessToken: raw.access_token,+ refreshToken: raw.refresh_token,+ expiresAt: tokenExpiry(raw),+ };+}++export async function refreshClaudeTokens(refreshToken: string): Promise<UserOAuthTokens> {+ const res = await fetch(CLAUDE_TOKEN, {+ method: "POST",+ headers: { "Content-Type": "application/json", Accept: "application/json" },+ body: JSON.stringify({ grant_type: "refresh_token", refresh_token: refreshToken, client_id: CLAUDE_CLIENT_ID }),+ signal: AbortSignal.timeout(15_000),+ });+ if (!res.ok) throw new Error(`claude refresh failed (${res.status})`);+ const raw = (await res.json()) as { access_token?: string; refresh_token?: string; expires_in?: number };+ if (!raw.access_token) throw new Error("claude refresh missing access_token");+ return {+ accessToken: raw.access_token,+ refreshToken: raw.refresh_token ?? refreshToken,+ expiresAt: tokenExpiry(raw),+ };+}diff --git a/src/model/user-model-credential-store.ts b/src/model/user-model-credential-store.tsnew file mode 100644index 000000000..c52bc5244--- /dev/null+++ b/src/model/user-model-credential-store.ts@@ -0,0 +1,164 @@+import type { DerivedOAuthAuth, Keychain } from "../credentials/keychain.ts";+import type { ModelProvider } from "./pi-models.ts";++type UserCredentialKind = "apikey" | "oauth";++export interface UserOAuthTokens {+ accessToken: string;+ refreshToken?: string;+ idToken?: string;+ accountId?: string;+ expiresAt?: number;+}++/** Connection summary. Never carries token material. */+export interface UserModelCredential {+ provider: ModelProvider;+ kind: UserCredentialKind;+ apiKey?: string;+ oauth?: { accountId?: string; expiresAt?: number; needsReconnect?: boolean };+ updatedAt: number;+}++interface UserCredentialConnection {+ provider: ModelProvider;+ kind: UserCredentialKind;+}++export interface UserModelCredentialStore {+ get(userId: string, provider: ModelProvider): Promise<UserModelCredential | null>;+ connections(userId: string): Promise<UserCredentialConnection[]>;+ setApiKey(userId: string, provider: ModelProvider, apiKey: string): Promise<void>;+ setOAuth(userId: string, provider: ModelProvider, tokens: UserOAuthTokens): Promise<void>;+ /**+ * Fresh derived material for the user's subscription login (access + id+ * token + account id) — refreshed inside the keychain (single-flight, CAS)+ * when stale. The refresh token never leaves the keychain record.+ */+ derivedOAuth(userId: string, provider: ModelProvider): Promise<DerivedOAuthAuth | null>;+ delete(userId: string, provider: ModelProvider): Promise<void>;+}++const PROVIDERS: ModelProvider[] = ["anthropic", "openai"];+const ORIGIN = "individual-model-auth";+/**+ * OAuth logins are keyed by the provider's auth host, so the keychain's own+ * connector-token machinery (encryption, expiry margin, single-flight refresh+ * via the wired refresh dispatch) covers them with no parallel implementation.+ */+const AI_OAUTH_HOSTS: Record<"anthropic" | "openai", string> = {+ anthropic: "claude.ai",+ openai: "auth.openai.com",+};+/** Segregates AI subscription logins from any other connector use of the same host. */+const AI_ACCOUNT_TYPE = "individual-model";++function serviceFor(provider: ModelProvider): string {+ return `model-${provider}`;+}++function oauthHostFor(provider: ModelProvider): string | null {+ return provider === "anthropic" || provider === "openai" ? AI_OAUTH_HOSTS[provider] : null;+}++/**+ * Per-user AI-account custody, backed by the org keychain — NOT a parallel+ * secret store.+ *+ * - Subscription (OAuth) logins are keychain connector tokens: the keychain+ * encrypts them, tracks expiry, and refreshes them centrally; callers only+ * ever receive derived material without the refresh token.+ * - API keys are ordinary keychain credentials owned by the user (service+ * `model-<provider>`, origin `individual-model-auth`), so admin visibility+ * and "remove my credentials" apply.+ */+export function createUserModelCredentialStore(input: { keychain: Keychain }): UserModelCredentialStore {+ const { keychain } = input;++ async function findApiKey(userId: string, provider: ModelProvider) {+ const all = await keychain.listByOwner(userId);+ return all.find((c) => c.service === serviceFor(provider) && c.origin === ORIGIN) ?? null;+ }++ async function oauthCredential(userId: string, provider: ModelProvider): Promise<UserModelCredential | null> {+ const host = oauthHostFor(provider);+ if (!host) return null;+ const status = await keychain.connectorTokenStatus(host, userId, AI_ACCOUNT_TYPE);+ if (!status.connected) return null;+ return {+ provider,+ kind: "oauth",+ oauth: {+ ...(status.expiresAt !== undefined ? { expiresAt: status.expiresAt } : {}),+ ...(status.needsReconnect ? { needsReconnect: true } : {}),+ },+ updatedAt: 0,+ };+ }++ async function apiKeyCredential(userId: string, provider: ModelProvider): Promise<UserModelCredential | null> {+ const meta = await findApiKey(userId, provider);+ if (!meta) return null;+ const apiKey = await keychain.readOwnSecret(userId, meta.id);+ if (!apiKey) return null;+ return { provider, kind: "apikey", apiKey, updatedAt: meta.updatedAt };+ }++ return {+ async get(userId, provider) {+ return (await oauthCredential(userId, provider)) ?? (await apiKeyCredential(userId, provider));+ },++ async connections(userId) {+ const found: UserCredentialConnection[] = [];+ for (const provider of PROVIDERS) {+ const cred = (await oauthCredential(userId, provider)) ?? (await apiKeyCredential(userId, provider));+ if (cred) found.push({ provider, kind: cred.kind });+ }+ return found;+ },++ async setApiKey(userId, provider, apiKey) {+ const secret = apiKey.trim();+ if (!secret) throw new Error("API key is required");+ // One connection per provider: an API key replaces a subscription login.+ const host = oauthHostFor(provider);+ if (host) await keychain.deleteConnectorToken(host, userId, AI_ACCOUNT_TYPE);+ await keychain.save({ ownerId: userId, service: serviceFor(provider), secret, origin: ORIGIN });+ },++ async setOAuth(userId, provider, tokens) {+ if (!tokens.accessToken?.trim()) throw new Error("access token is required");+ const host = oauthHostFor(provider);+ if (!host) throw new Error(`no subscription login host for provider ${provider}`);+ await keychain.setConnectorToken(+ host,+ userId,+ {+ accessToken: tokens.accessToken,+ ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),+ ...(tokens.idToken ? { idToken: tokens.idToken } : {}),+ ...(tokens.accountId ? { accountId: tokens.accountId } : {}),+ ...(tokens.expiresAt !== undefined ? { expiresAt: tokens.expiresAt } : {}),+ },+ AI_ACCOUNT_TYPE,+ );+ // One connection per provider: a subscription login replaces an API key.+ const apiKeyMeta = await findApiKey(userId, provider);+ if (apiKeyMeta) await keychain.remove(userId, apiKeyMeta.id);+ },++ async derivedOAuth(userId, provider) {+ const host = oauthHostFor(provider);+ if (!host) return null;+ return keychain.connectorDerivedAuth(host, userId, AI_ACCOUNT_TYPE);+ },++ async delete(userId, provider) {+ const host = oauthHostFor(provider);+ if (host) await keychain.deleteConnectorToken(host, userId, AI_ACCOUNT_TYPE);+ const meta = await findApiKey(userId, provider);+ if (meta) await keychain.remove(userId, meta.id);+ },+ };+}diff --git a/src/persistence/pg-pool.ts b/src/persistence/pg-pool.tsindex 8c5ef21b1..5ad4f3d7e 100644--- a/src/persistence/pg-pool.ts+++ b/src/persistence/pg-pool.ts@@ -7,10 +7,14 @@ export type { Pool, PoolClient };export type Rows = Record<string, unknown>[];+export interface PgQueryOptions {+ signal?: AbortSignal;+}+export interface PgPool {pool(): Promise<Pool>;- q(text: string, params?: unknown[]): Promise<Rows>;- query(text: string, params?: unknown[]): Promise<{ rows: Rows; rowCount: number }>;+ q(text: string, params?: unknown[], options?: PgQueryOptions): Promise<Rows>;+ query(text: string, params?: unknown[], options?: PgQueryOptions): Promise<{ rows: Rows; rowCount: number }>;schema?(schemaSql: string): Promise<void>;close(): Promise<void>;}@@ -127,12 +131,59 @@ export function createPgPool(connectionString: string, statements: string[]): Pg}return poolP;}- async function query(text: string, params: unknown[] = []): Promise<{ rows: Rows; rowCount: number }> {- const res = await (await pool()).query(text, params);- return { rows: res.rows as Rows, rowCount: res.rowCount ?? 0 };+ async function query(+ text: string,+ params: unknown[] = [],+ options: PgQueryOptions = {},+ ): Promise<{ rows: Rows; rowCount: number }> {+ const p = await pool();+ if (!options.signal) {+ const res = await p.query(text, params);+ return { rows: res.rows as Rows, rowCount: res.rowCount ?? 0 };+ }+ if (options.signal.aborted) throw new DOMException("Postgres query cancelled", "AbortError");+ const connectPromise = p.connect();+ let connectAbort: (() => void) | undefined;+ const connectAbortPromise = new Promise<never>((_, reject) => {+ connectAbort = () => reject(new DOMException("Postgres query cancelled", "AbortError"));+ options.signal!.addEventListener("abort", connectAbort, { once: true });+ });+ let client: PoolClient;+ try {+ client = await Promise.race([connectPromise, connectAbortPromise]);+ } catch (error) {+ void connectPromise+ .then(+ (lateClient) => lateClient.release(error instanceof Error ? error : new Error(String(error))),+ () => undefined,+ )+ .catch(() => undefined);+ throw error;+ } finally {+ if (connectAbort) options.signal.removeEventListener("abort", connectAbort);+ }+ let queryError: Error | undefined;+ let released = false;+ const cancel = () => {+ if (released) return;+ released = true;+ client.release(new Error("Postgres query cancelled"));+ };+ options.signal.addEventListener("abort", cancel, { once: true });+ try {+ if (released) throw new Error("Postgres query cancelled");+ const res = await client.query({ text, values: params });+ return { rows: res.rows as Rows, rowCount: res.rowCount ?? 0 };+ } catch (error) {+ queryError = error instanceof Error ? error : new Error(String(error));+ throw error;+ } finally {+ options.signal?.removeEventListener("abort", cancel);+ if (!released) client.release(queryError);+ }}- async function q(text: string, params: unknown[] = []): Promise<Rows> {- return (await query(text, params)).rows;+ async function q(text: string, params: unknown[] = [], options?: PgQueryOptions): Promise<Rows> {+ return (await query(text, params, options)).rows;}async function close(): Promise<void> {if (poolP) await (await poolP).end();diff --git a/src/resolution/config-store.ts b/src/resolution/config-store.tsindex 9b3cf64e4..dddbeefc7 100644--- a/src/resolution/config-store.ts+++ b/src/resolution/config-store.ts@@ -189,6 +189,9 @@ export interface ScopedConfigStore {getInteractiveFastMode(): boolean;setInteractiveFastMode(on: boolean): void;getInteractiveFastModeDurable(): Promise<boolean>;+ getIndividualModelAuth(): boolean;+ setIndividualModelAuth(on: boolean): void;+ getIndividualModelAuthDurable(): Promise<boolean>;getBaseModelOwnDurable(id: ScopeId): Promise<string | null>;getWebuiModels(id: ScopeId): string[] | null;setWebuiModels(id: ScopeId, ids: string[] | null): void;@@ -235,6 +238,7 @@ export function createMemoryConfigStore(approvedHarnesses?: DurableMap<PersistedApprovedHarnesses>;orgAmbient?: DurableMap<PersistedScopedFlag>;interactiveFastMode?: DurableMap<PersistedScopedFlag>;+ individualModelAuth?: DurableMap<PersistedScopedFlag>;webuiModels?: DurableMap<PersistedWebuiModels>;peopleDirectoryUrls?: DurableMap<PersistedPeopleDirectoryUrl>;ackEmoji?: DurableMap<PersistedAckEmoji>;@@ -261,6 +265,7 @@ export function createMemoryConfigStore(let approvedHarnesses: string[] | null = null;let orgAmbient = true;let interactiveFastMode = false;+ let individualModelAuth = false;const webuiModels = new Map<ScopeId, string[]>();const peopleDirectoryUrls = new Map<ScopeId, string>();const ackEmoji = new Map<ScopeId, string[]>();@@ -281,6 +286,7 @@ export function createMemoryConfigStore(const approvedHarnessStore = opts.approvedHarnesses ?? createMemoryMap<PersistedApprovedHarnesses>();const orgAmbientStore = opts.orgAmbient ?? createMemoryMap<PersistedScopedFlag>();const interactiveFastModeStore = opts.interactiveFastMode ?? createMemoryMap<PersistedScopedFlag>();+ const individualModelAuthStore = opts.individualModelAuth ?? createMemoryMap<PersistedScopedFlag>();const webuiModelStore = opts.webuiModels ?? createMemoryMap<PersistedWebuiModels>();const peopleDirectoryUrlStore = opts.peopleDirectoryUrls ?? createMemoryMap<PersistedPeopleDirectoryUrl>();const ackEmojiStore = opts.ackEmoji ?? createMemoryMap<PersistedAckEmoji>();@@ -433,6 +439,7 @@ export function createMemoryConfigStore(approvedHarnesses = (await approvedHarnessStore.get(org))?.ids ?? null;orgAmbient = (await orgAmbientStore.get(org))?.on ?? true;interactiveFastMode = (await interactiveFastModeStore.get(org))?.on ?? false;+ individualModelAuth = (await individualModelAuthStore.get(org))?.on ?? false;for (const r of await webuiModelStore.all()) webuiModels.set(r.scopeId, r.ids);for (const r of await peopleDirectoryUrlStore.all()) peopleDirectoryUrls.set(r.scopeId, r.url);for (const r of await ackEmojiStore.all()) ackEmoji.set(r.scopeId, r.names);@@ -806,6 +813,14 @@ export function createMemoryConfigStore();},getInteractiveFastModeDurable: async () => (await interactiveFastModeStore.get(org))?.on ?? false,+ getIndividualModelAuth: () => individualModelAuth,+ setIndividualModelAuth(on) {+ individualModelAuth = on;+ persist(`individualModelAuth:${org}`, "individual model auth switch", () =>+ individualModelAuthStore.put(org, { scopeId: org, on }),+ );+ },+ getIndividualModelAuthDurable: async () => (await individualModelAuthStore.get(org))?.on ?? false,getBaseModelOwnDurable: async (id) => (await baseModelStore.get(id))?.modelId ?? null,getBaseModelDurable: async (id) =>(await baseModelStore.get(id))?.modelId ??@@ -969,6 +984,7 @@ export function createMemoryConfigStore(brandingRow,orgAmbientRow,interactiveFastModeRow,+ individualModelAuthRow,channelHeaderPinRow,] = await Promise.all([soulStore.get(id),@@ -983,6 +999,7 @@ export function createMemoryConfigStore(brandingStore.get(id),id === org ? orgAmbientStore.get(org) : null,id === org ? interactiveFastModeStore.get(org) : null,+ id === org ? individualModelAuthStore.get(org) : null,channelHeaderPinStore.get(id),]);let refreshedSoul = soul;@@ -1022,6 +1039,7 @@ export function createMemoryConfigStore(if (id === org) approvedHarnesses = approved?.ids ?? null;if (id === org) orgAmbient = orgAmbientRow?.on ?? true;if (id === org) interactiveFastMode = interactiveFastModeRow?.on ?? false;+ if (id === org) individualModelAuth = individualModelAuthRow?.on ?? false;if (brandingRow) branding.set(id, brandingRow.branding);else branding.delete(id);if (channelHeaderPinRow) channelHeaderPin.set(id, channelHeaderPinRow.on);@@ -1038,10 +1056,16 @@ export function createMemoryConfigStore(`model:${id}`,`turnWallClock:${id}`,`branding:${id}`,- ...(id === org ? [`approvedHarnesses:${org}`, `orgAmbient:${org}`, `interactiveFastMode:${org}`] : []),+ ...(id === org+ ? [+ `approvedHarnesses:${org}`,+ `orgAmbient:${org}`,+ `interactiveFastMode:${org}`,+ `individualModelAuth:${org}`,+ ]+ : []),`channelHeaderPin:${id}`,`ackEmoji:${id}`,- ...(id === org ? [`approvedHarnesses:${org}`, `orgAmbient:${org}`] : []),];await Promise.all(keys.map(async (key) => {diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.tsindex 7c1abafbb..1c0cdc2bb 100644--- a/src/sessions/postgres-session-store.ts+++ b/src/sessions/postgres-session-store.ts@@ -544,14 +544,14 @@ export function createPostgresSessionStore(connectionString: string, opts: Storereturn rows.map(rowToEntry);},- async recordLlmRequest(sessionId, rec: NewLlmRequest): Promise<LlmRequestRecord> {+ async recordLlmRequest(sessionId, rec: NewLlmRequest, signal?: AbortSignal): Promise<LlmRequestRecord> {const envelope = promptEnvelopeBody(rec.promptEnvelope);if (envelope) {- await q("INSERT INTO llm_prompt_envelopes(hash, body, created_at) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING", [- envelope.hash,- envelope.body,- now(),- ]);+ await q(+ "INSERT INTO llm_prompt_envelopes(hash, body, created_at) VALUES ($1,$2,$3) ON CONFLICT DO NOTHING",+ [envelope.hash, envelope.body, now()],+ { signal },+ );}const full: LlmRequestRecord = {id: randomUUID(),@@ -593,6 +593,7 @@ export function createPostgresSessionStore(connectionString: string, opts: Storefull.transport ? JSON.stringify(full.transport) : null,full.gapPhases ? JSON.stringify(full.gapPhases) : null,],+ { signal },);return full;},diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.tsindex 9724fe26a..36675e995 100644--- a/src/sessions/session-store.ts+++ b/src/sessions/session-store.ts@@ -457,7 +457,7 @@ export interface SessionStore {getTape(sessionId: string, opts?: GetTapeOptions): Promise<TapeRecord[]>;tapeCoverage(sessionId: string): Promise<number>;- recordLlmRequest(sessionId: string, rec: NewLlmRequest): Promise<LlmRequestRecord>;+ recordLlmRequest(sessionId: string, rec: NewLlmRequest, signal?: AbortSignal): Promise<LlmRequestRecord>;listLlmRequests(sessionId: string, opts?: ListLlmRequestsOptions): Promise<LlmRequestRecord[]>;addParticipant(sessionId: string, principalId: string, title?: string, opts?: AddParticipantOptions): Promise<void>;diff --git a/src/wiring.ts b/src/wiring.tsindex f37513cea..7b8d4c749 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -1,7 +1,13 @@import { mkdirSync } from "node:fs";import { randomBytes, randomUUID } from "node:crypto";import { join, resolve } from "node:path";-import { baseModelProviders, configuredModelForHarness, providerKeysPresent, type Config } from "./config.ts";+import {+ baseModelProviders,+ configuredModelForHarness,+ harnessCarriedModelAuth,+ providerKeysPresent,+ type Config,+} from "./config.ts";import type { ServerDeps } from "./api/deps.ts";import { createIdentityService, type DeactivationRecord, type IdentityService } from "./identity/identity-service.ts";import {@@ -130,6 +136,7 @@ import {import {createKeychain,type ConnectorTokenStore,+ type OAuthToken,type Keychain,type KeychainAsk,type KeychainCredential,@@ -170,6 +177,8 @@ import { createPostgresEgressAuditSink } from "./admin/postgres-egress-audit-sinimport { createConsentLinkStore, type ConsentLinkStore, type ConsentLinkRecord } from "./connectors/consent-link.ts";import { createModelGateway, type ModelGateway } from "./model/model-gateway.ts";import { createModelCredentialStore, type ModelCredentialStore } from "./model/model-credential-store.ts";+import { refreshChatGPTTokens, refreshClaudeTokens } from "./model/subscription-oauth.ts";+import { createUserModelCredentialStore, type UserModelCredentialStore } from "./model/user-model-credential-store.ts";import { setProviderBaseUrls } from "./model/provider-endpoints.ts";import { setCustomProviders } from "./model/custom-providers.ts";import { createCustomProviderStore, type CustomProviderStore } from "./model/custom-provider-store.ts";@@ -179,6 +188,8 @@ import type { SessionStore } from "./sessions/session-store.ts";import { createMockHarness } from "./harness/mock-harness.ts";import { createOpenCodeHarness, openCodeHarnessConfigOptions } from "./harness/opencode-harness.ts";import { createCodexHarness, codexHarnessConfigOptions } from "./harness/codex-harness.ts";+import { keychainCodexAuthStore } from "./harness/codex-auth-store.ts";+import { keychainHarnessAuthEnv } from "./credentials/harness-auth-env.ts";import { createClaudeHarness, claudeHarnessConfigOptions } from "./harness/claude-harness.ts";import { createPiHarness, piHarnessConfigOptions } from "./harness/pi-harness.ts";import { createHarnessRouter, resolveRuntimeChoiceDurable } from "./harness/harness-router.ts";@@ -252,6 +263,7 @@ import {auxiliaryModelFor,auxiliaryModelForProvider,defaultModelForHarness,+ isHarnessId,modelProviderAvailabilityFor,type HarnessId,} from "./model/pi-models.ts";@@ -334,6 +346,7 @@ export interface BuiltApp {secretDrops: SecretDropStore;modelGateway: ModelGateway;modelCredentials: ModelCredentialStore;+ userModelCredentials: UserModelCredentialStore;customProviders: CustomProviderStore;refreshCustomProviders: () => Promise<void>;mcpServers: McpServerStore;@@ -455,6 +468,7 @@ export function buildApp(approvedHarnesses: artifactMap<PersistedApprovedHarnesses>("approved_harness_configs"),orgAmbient: artifactMap<PersistedScopedFlag>("org_ambient_flag"),interactiveFastMode: artifactMap<PersistedScopedFlag>("interactive_fast_mode_flag"),+ individualModelAuth: artifactMap<PersistedScopedFlag>("individual_model_auth_flag"),webuiModels: artifactMap<PersistedWebuiModels>("webui_model_configs"),peopleDirectoryUrls: artifactMap<PersistedPeopleDirectoryUrl>("people_directory_urls"),ackEmoji: artifactMap<PersistedAckEmoji>("ack_emoji"),@@ -702,8 +716,40 @@ export function buildApp(grants: artifactMap<KeychainGrant>("keychain_grants"),asks: artifactMap<KeychainAsk>("keychain_asks"),key: credentialKey,- refreshConnector: makeRefresh({ resolveClient }),+ refreshConnector: (() => {+ const base = makeRefresh({ resolveClient });+ // AI subscription logins ride the same connector-refresh machinery:+ // the keychain calls this single-flight when a token is stale.+ return async (host: string, token: OAuthToken, ctx?: { accountType?: string; clientRef?: string }) => {+ if (token.refreshToken && host === "auth.openai.com") {+ const fresh = await refreshChatGPTTokens(token.refreshToken);+ return oauthTokenFromUserTokens(fresh);+ }+ if (token.refreshToken && host === "claude.ai") {+ const fresh = await refreshClaudeTokens(token.refreshToken);+ return oauthTokenFromUserTokens(fresh);+ }+ return base(host, token, ctx);+ };+ })(),});+ const oauthTokenFromUserTokens = (fresh: {+ accessToken: string;+ refreshToken?: string;+ idToken?: string;+ accountId?: string;+ expiresAt?: number;+ }): OAuthToken => ({+ accessToken: fresh.accessToken,+ ...(fresh.refreshToken ? { refreshToken: fresh.refreshToken } : {}),+ ...(fresh.idToken ? { idToken: fresh.idToken } : {}),+ ...(fresh.accountId ? { accountId: fresh.accountId } : {}),+ ...(fresh.expiresAt !== undefined ? { expiresAt: fresh.expiresAt } : {}),+ });+ // Per-user AI accounts live in the keychain itself (unified custody):+ // same encryption, ownership, admin visibility, and removal flows as+ // every other personal credential.+ const userModelCredentials = createUserModelCredentialStore({ keychain: credentialStore });const keychain: Keychain | undefined = keychainKeyMaterial ? credentialStore : undefined;const browserSessionStore: BrowserSessionStore | undefined = keychainKeyMaterial? createBrowserSessionStore({ sessions: artifactMap<StoredBrowserSession>("browser_sessions"), key: credentialKey })@@ -807,8 +853,39 @@ export function buildApp(},}),],- ["codex", createCodexHarness({ ...codexHarnessConfigOptions(config), signals: runSignals, tasks, mcpTools })],- ["claude", createClaudeHarness({ ...claudeHarnessConfigOptions(config), signals: runSignals, tasks, mcpTools })],+ [+ "codex",+ createCodexHarness({+ ...codexHarnessConfigOptions(config),+ // Keychain custody: the subscription login lives encrypted in its+ // owner's keychain; core refreshes it centrally and hands the harness+ // ephemeral derived material. The credential can be (re)registered at+ // runtime — resolution happens on every load.+ ...(config.codexAuthCredential && keychain+ ? { authStore: keychainCodexAuthStore({ keychain, credentialId: config.codexAuthCredential }) }+ : {}),+ signals: runSignals,+ tasks,+ mcpTools,+ }),+ ],+ [+ "claude",+ createClaudeHarness({+ ...claudeHarnessConfigOptions(config),+ ...(config.claudeAuthCredential && keychain+ ? {+ authEnv: keychainHarnessAuthEnv(keychain, config.claudeAuthCredential, [+ "CLAUDE_CODE_OAUTH_TOKEN",+ "ANTHROPIC_AUTH_TOKEN",+ ]),+ }+ : {}),+ signals: runSignals,+ tasks,+ mcpTools,+ }),+ ],["mock", createMockHarness()],]);const fallbackHarness = config.harness as HarnessId;@@ -827,8 +904,11 @@ export function buildApp(if (!(await modelCredentials.availability()).openrouter) return undefined;return selectableModelCatalog(overrides.modelCredentialFetch);};- const harness = createHarnessRouter(adapters, adapters.get(fallbackHarness)!, (input) =>- resolveRuntimeChoiceDurable(+ const harness = createHarnessRouter(adapters, adapters.get(fallbackHarness)!, (input) => {+ if (input.runtimePinned && input.harness && isHarnessId(input.harness) && input.model) {+ return { harnessId: input.harness, modelId: input.model };+ }+ return resolveRuntimeChoiceDurable(configStore,runtimeOrgScope,input.scopeLabel,@@ -838,8 +918,8 @@ export function buildApp(...(input.model ? { modelId: input.model } : {}),},hydrateModelCatalog,- ),- );+ );+ });const leaseTtlMs = config.leaseTtlMs;const maxAttempts = config.maxAttempts;@@ -1007,6 +1087,8 @@ export function buildApp(identity,resolution,config: configStore,+ defaultHarness: fallbackHarness,+ userModelCredentials,...(config.brandingDefault ? { brandingDefault: config.brandingDefault } : {}),sessionTapeMode: config.sessionTapeMode,sessions,@@ -1174,6 +1256,7 @@ export function buildApp(tasks,modelGateway,modelCredentials,+ userModelCredentials,customProviders,refreshCustomProviders,mcpServers,@@ -1533,6 +1616,7 @@ export function buildApp(secretDrops,modelGateway,modelCredentials,+ userModelCredentials,customProviders,refreshCustomProviders,mcpServers,@@ -1590,6 +1674,7 @@ export function serverDeps(slackEnvBotToken?: string,): Omit<ServerDeps, "control"> {const configuredModel = configuredModelForHarness(config, config.harness);+ const carriedModelAuth = harnessCarriedModelAuth(config);return {production: config.production,allowUnauthenticatedCore: config.allowUnauthenticatedCore,@@ -1600,9 +1685,11 @@ export function serverDeps(...(built.replayDedupe ? { replayDedupe: built.replayDedupe } : {}),config: built.config,...(configuredModel ? { baseModelDefault: configuredModel } : {}),+ ...(carriedModelAuth ? { harnessCarriedModelAuth: carriedModelAuth } : {}),modelProviders: modelProviderAvailabilityFor(config.harness, providerKeysPresent(config)),providerKeys: providerKeysPresent(config),modelCredentials: built.modelCredentials,+ userModelCredentials: built.userModelCredentials,customProviders: built.customProviders,refreshCustomProviders: built.refreshCustomProviders,mcpServers: built.mcpServers,diff --git a/test/base-model-serviceability.test.ts b/test/base-model-serviceability.test.tsindex 8b7c766e6..386d9350a 100644--- a/test/base-model-serviceability.test.ts+++ b/test/base-model-serviceability.test.ts@@ -9,7 +9,7 @@ import type { AddressInfo } from "node:net";import { createInsecureTestServer } from "../src/api/server.ts";import { buildApp } from "../src/wiring.ts";import { baseModelProviders, configuredModelForHarness, providerKeysPresent } from "../src/config.ts";-import { defaultModelForHarness } from "../src/model/pi-models.ts";+import { defaultModelForHarness, modelProviderAvailabilityFor } from "../src/model/pi-models.ts";import { testConfig } from "./support/test-config.ts";const ADMIN = { "content-type": "application/json", "x-admin-actor": "admin-alice@default-org" };@@ -60,6 +60,23 @@ test("base-model set rejects a model whose provider key is absent (would fail pr}});+test("ChatGPT OAuth is serviceable for Codex without advertising OpenAI to Pi", () => {+ const config = testConfig({ harness: "codex", codexAuthFile: "/tmp/codex-auth.json" });+ const configured = providerKeysPresent(config);+ assert.equal(configured.openai, false);+ assert.equal(+ modelProviderAvailabilityFor("codex", configured).openai,+ true,+ "Codex can use its harness OAuth session",+ );+ assert.equal(modelProviderAvailabilityFor("opencode", configured).openai, false);+ assert.equal(+ modelProviderAvailabilityFor("pi", configured, { anthropic: false, openai: false, openrouter: false }).openai,+ false,+ "Pi still requires an API-key credential",+ );+});+test("a deployment that declares a provider runs that provider's base model", async () => {for (const [modelProvider, key, expected] of [["anthropic", "anthropicApiKey", "claude-opus-5"],diff --git a/test/codex-auth-store.test.ts b/test/codex-auth-store.test.tsnew file mode 100644index 000000000..83b7cf658--- /dev/null+++ b/test/codex-auth-store.test.ts@@ -0,0 +1,232 @@+import assert from "node:assert/strict";+import test from "node:test";+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import {+ childCodexOAuthAuth,+ codexOAuthAccessTokenExpiresAt,+ codexOAuthAuthFromValue,+ fileCodexAuthStore,+ keychainCodexAuthStore,+} from "../src/harness/codex-auth-store.ts";+import type { CredentialFile, Keychain, KeychainCredentialMeta } from "../src/credentials/keychain.ts";++function jwt(payload: Record<string, unknown>, header: Record<string, unknown> = { alg: "RS256" }): string {+ const enc = (v: unknown) => Buffer.from(JSON.stringify(v)).toString("base64url");+ return `${enc(header)}.${enc(payload)}.sig`;+}++function idToken(accountId: string): string {+ return jwt({+ iss: "https://auth.openai.com",+ "https://api.openai.com/auth": { chatgpt_account_id: accountId },+ });+}++function accessToken(accountId: string, expSec: number, marker = "a"): string {+ return jwt({+ iss: "https://auth.openai.com",+ exp: expSec,+ marker,+ "https://api.openai.com/auth": { chatgpt_account_id: accountId },+ });+}++function authJson(+ accountId: string,+ expSec: number,+ refreshToken = "refresh-1",+ marker = "a",+): Record<string, unknown> {+ return {+ auth_mode: "chatgpt",+ tokens: {+ access_token: accessToken(accountId, expSec, marker),+ refresh_token: refreshToken,+ id_token: idToken(accountId),+ account_id: accountId,+ },+ };+}++const NOW = 1_900_000_000_000;+const FRESH_EXP = Math.floor(NOW / 1000) + 3600;+const STALE_EXP = Math.floor(NOW / 1000) + 60;++interface FakeKeychainState {+ meta: KeychainCredentialMeta;+ files: CredentialFile[];+ saves: Array<{ ownerId: string; service: string; files?: CredentialFile[] }>;+}++function fakeKeychain(state: FakeKeychainState): Keychain {+ return {+ async getCredential(id: string) {+ return id === state.meta.id ? state.meta : null;+ },+ async materializeOwnFiles(ownerId: string) {+ if (ownerId !== state.meta.ownerId) return [];+ return [{ credentialId: state.meta.id, ownerId, service: state.meta.service, files: state.files }];+ },+ async save(input: { ownerId: string; service: string; files?: CredentialFile[] }) {+ state.saves.push(input);+ if (input.files) state.files = input.files;+ return state.meta;+ },+ } as unknown as Keychain;+}++function credFiles(auth: Record<string, unknown>): CredentialFile[] {+ return [{ path: ".codex/auth.json", contentBase64: Buffer.from(JSON.stringify(auth)).toString("base64") }];+}++const META = {+ id: "cred-1",+ ownerId: "[email protected]",+ service: "codex-chatgpt",+ kind: "file",+ fingerprint: "f",+ createdAt: 0,+ updatedAt: 0,+} as KeychainCredentialMeta;++test("child auth material never includes the refresh token", () => {+ const auth = authJson("acct", FRESH_EXP);+ const child = childCodexOAuthAuth(auth);+ const tokens = child.tokens as Record<string, unknown>;+ assert.equal(tokens.refresh_token, undefined);+ assert.equal(tokens.access_token, (auth.tokens as Record<string, unknown>).access_token);+ assert.equal(tokens.id_token, (auth.tokens as Record<string, unknown>).id_token);+ assert.equal(child.auth_mode, "chatgpt");+});++test("codexOAuthAuthFromValue validates shape and account binding", () => {+ assert.ok(codexOAuthAuthFromValue(authJson("acct", FRESH_EXP)));+ assert.equal(codexOAuthAuthFromValue({ auth_mode: "apikey" }), null);+ const missingRefresh = authJson("acct", FRESH_EXP);+ delete (missingRefresh.tokens as Record<string, unknown>).refresh_token;+ assert.equal(codexOAuthAuthFromValue(missingRefresh), null);+});++test("keychain store returns fresh auth without refreshing", async () => {+ const state: FakeKeychainState = { meta: META, files: credFiles(authJson("acct", FRESH_EXP)), saves: [] };+ const store = keychainCodexAuthStore({+ keychain: fakeKeychain(state),+ credentialId: "cred-1",+ now: () => NOW,+ fetchImpl: () => {+ throw new Error("must not refresh");+ },+ });+ const auth = await store.load();+ assert.ok(auth);+ assert.equal(state.saves.length, 0);+});++test("keychain store refreshes a stale access token centrally and persists rotation", async () => {+ const state: FakeKeychainState = {+ meta: META,+ files: credFiles(authJson("acct", STALE_EXP, "refresh-1")),+ saves: [],+ };+ const calls: Array<Record<string, unknown>> = [];+ const store = keychainCodexAuthStore({+ keychain: fakeKeychain(state),+ credentialId: "cred-1",+ now: () => NOW,+ fetchImpl: (async (_url: string, init: { body: string }) => {+ calls.push(JSON.parse(init.body) as Record<string, unknown>);+ return {+ ok: true,+ json: async () => ({+ access_token: accessToken("acct", FRESH_EXP, "refreshed"),+ id_token: idToken("acct"),+ refresh_token: "refresh-2",+ }),+ };+ }) as unknown as typeof fetch,+ });+ const auth = await store.load();+ assert.ok(auth);+ assert.equal(calls.length, 1);+ assert.equal(calls[0]?.grant_type, "refresh_token");+ assert.equal(calls[0]?.refresh_token, "refresh-1");+ const tokens = auth!.tokens as Record<string, unknown>;+ assert.equal(tokens.refresh_token, "refresh-2");+ assert.equal(state.saves.length, 1);+ const persisted = JSON.parse(+ Buffer.from(state.saves[0]!.files![0]!.contentBase64, "base64").toString("utf8"),+ ) as Record<string, unknown>;+ assert.equal((persisted.tokens as Record<string, unknown>).refresh_token, "refresh-2");+});++test("keychain store refuses a refresh that switches accounts", async () => {+ const state: FakeKeychainState = { meta: META, files: credFiles(authJson("acct", STALE_EXP)), saves: [] };+ const store = keychainCodexAuthStore({+ keychain: fakeKeychain(state),+ credentialId: "cred-1",+ now: () => NOW,+ fetchImpl: (async () => ({+ ok: true,+ json: async () => ({+ access_token: accessToken("other-acct", FRESH_EXP),+ id_token: idToken("other-acct"),+ refresh_token: "refresh-2",+ }),+ })) as unknown as typeof fetch,+ });+ const auth = await store.load();+ // Falls back to the (stale) stored auth rather than adopting a different account.+ assert.ok(auth);+ assert.equal((auth!.tokens as Record<string, unknown>).refresh_token, "refresh-1");+ assert.equal(state.saves.length, 0);+});++test("keychain store surfaces null when the credential is missing", async () => {+ const state: FakeKeychainState = { meta: META, files: credFiles(authJson("acct", FRESH_EXP)), saves: [] };+ const store = keychainCodexAuthStore({ keychain: fakeKeychain(state), credentialId: "other", now: () => NOW });+ assert.equal(await store.load(), null);+});++test("file store refreshes a stale token and writes back under the lock with compare-and-set", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-store-file-"));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const path = join(dir, "auth.json");+ writeFileSync(path, JSON.stringify(authJson("acct", STALE_EXP, "refresh-1")));+ chmodSync(path, 0o600);+ const store = fileCodexAuthStore(+ path,+ (async () => ({+ ok: true,+ json: async () => ({+ access_token: accessToken("acct", FRESH_EXP, "refreshed"),+ id_token: idToken("acct"),+ refresh_token: "refresh-2",+ }),+ })) as unknown as typeof fetch,+ () => NOW,+ );+ const auth = await store.load();+ assert.ok(auth);+ assert.equal((auth!.tokens as Record<string, unknown>).refresh_token, "refresh-2");+ const persisted = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;+ assert.equal((persisted.tokens as Record<string, unknown>).refresh_token, "refresh-2");+ assert.equal(codexOAuthAccessTokenExpiresAt(persisted), FRESH_EXP * 1000);+});++test("file store keeps serving current auth when the refresh endpoint fails", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-store-file-fail-"));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const path = join(dir, "auth.json");+ writeFileSync(path, JSON.stringify(authJson("acct", STALE_EXP, "refresh-1")));+ chmodSync(path, 0o600);+ const store = fileCodexAuthStore(+ path,+ (async () => ({ ok: false, status: 503 })) as unknown as typeof fetch,+ () => NOW,+ );+ const auth = await store.load();+ assert.ok(auth);+ assert.equal((auth!.tokens as Record<string, unknown>).refresh_token, "refresh-1");+});diff --git a/test/codex-device-login.test.ts b/test/codex-device-login.test.tsnew file mode 100644index 000000000..28e75d05c--- /dev/null+++ b/test/codex-device-login.test.ts@@ -0,0 +1,82 @@+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 { test } from "node:test";+import { createCodexDeviceLogin } from "../src/model/codex-device-login.ts";++function idToken(accountId: string): string {+ const seg = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64url");+ return `${seg({ alg: "RS256", typ: "JWT" })}.${seg({ "https://api.openai.com/auth": { chatgpt_account_id: accountId } })}.sig`;+}++/** Fake `codex app-server` that serves the device-login RPCs and writes auth.json on approval. */+function loginBinary(dir: string, opts: { succeed: boolean; delayMs?: number }): string {+ const path = join(dir, `codex-login-${opts.succeed ? "ok" : "fail"}`);+ writeFileSync(+ path,+ `#!${process.execPath}+const fs = require("node:fs");+const path = require("node:path");+const readline = require("node:readline");+const send = (value) => process.stdout.write(JSON.stringify(value) + "\\n");+const rl = readline.createInterface({ input: process.stdin });+rl.on("line", (line) => {+ const msg = JSON.parse(line);+ if (msg.method === "initialize") return send({ id: msg.id, result: {} });+ if (msg.method === "initialized") return;+ if (msg.method === "account/login/start") {+ send({ id: msg.id, result: { type: "chatgptDeviceCode", loginId: "login-1", verificationUrl: "https://auth.openai.com/codex/device", userCode: "ABCD-1234" } });+ return setTimeout(() => {+ if (${JSON.stringify(opts.succeed)}) {+ fs.writeFileSync(path.join(process.env.CODEX_HOME, "auth.json"), JSON.stringify({+ auth_mode: "chatgpt",+ tokens: { access_token: "acc-1", refresh_token: "ref-1", id_token: ${JSON.stringify(idToken("acct_9"))}, account_id: "acct_9" },+ }));+ send({ method: "account/login/completed", params: { loginId: "login-1", success: true, error: null } });+ } else {+ send({ method: "account/login/completed", params: { loginId: "login-1", success: false, error: "denied by user" } });+ }+ }, ${opts.delayMs ?? 30});+ }+});+`,+ );+ chmodSync(path, 0o755);+ return path;+}++test("device login: start returns the prompt, poll is pending then yields tokens without exposing internals", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-device-login-test-"));+ const login = createCodexDeviceLogin({ binaryPath: loginBinary(dir, { succeed: true, delayMs: 120 }) });+ t.after(async () => {+ await login.close();+ rmSync(dir, { recursive: true, force: true });+ });+ const prompt = await login.start();+ assert.equal(prompt.userCode, "ABCD-1234");+ assert.equal(prompt.verificationUrl, "https://auth.openai.com/codex/device");+ assert.equal(await login.poll(prompt.deviceAuthId), "pending");+ await new Promise((r) => setTimeout(r, 200));+ const tokens = await login.poll(prompt.deviceAuthId);+ assert.notEqual(tokens, "pending");+ if (tokens === "pending") return;+ assert.equal(tokens.accessToken, "acc-1");+ assert.equal(tokens.refreshToken, "ref-1");+ assert.equal(tokens.accountId, "acct_9");+ // The login is one-shot: after harvest it is gone.+ await assert.rejects(() => login.poll(prompt.deviceAuthId), /expired or unknown/);+});++test("device login: a denied login surfaces the provider error and cleans up", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-device-login-test-"));+ const login = createCodexDeviceLogin({ binaryPath: loginBinary(dir, { succeed: false, delayMs: 20 }) });+ t.after(async () => {+ await login.close();+ rmSync(dir, { recursive: true, force: true });+ });+ const prompt = await login.start();+ await new Promise((r) => setTimeout(r, 120));+ await assert.rejects(() => login.poll(prompt.deviceAuthId), /denied by user/);+ await assert.rejects(() => login.poll(prompt.deviceAuthId), /expired or unknown/);+});diff --git a/test/codex-harness.test.ts b/test/codex-harness.test.tsindex 9b9cf957e..76cf0b34c 100644--- a/test/codex-harness.test.ts+++ b/test/codex-harness.test.ts@@ -1,7 +1,16 @@import test from "node:test";import assert from "node:assert/strict";-import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { homedir, tmpdir } from "node:os";+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { createRequire } from "node:module";import {@@ -23,8 +32,10 @@ import type { HarnessLlmRequestRecord, HarnessTurnInput } from "../src/harness/himport { NonRetryableTurnError } from "../src/core/turn-error.ts";import type { ScopeId, Session, SessionEntry } from "../src/types.ts";import { createMemoryTaskStore } from "../src/tasks/memory-task-store.ts";-import { CodexAppServer } from "../src/harness/codex-app-server.ts";+import { CodexAppServer, redactCodexDiagnostics } from "../src/harness/codex-app-server.ts";import { DEFAULT_CODEX_MODEL_ID } from "../src/model/pi-models.ts";+import { readCodexOAuthAuthFile } from "../src/harness/codex-auth.ts";+import { acquireCodexOAuthAuthLock } from "../src/harness/codex-auth.ts";const replaySmokeItems = [{ type: "message", role: "user", content: [{ type: "input_text", text: "earlier question" }] },@@ -33,6 +44,21 @@ const replaySmokeItems = [{ type: "function_call_output", call_id: "call-1", output: "[exit 0]" },];+function testHarnessEnv(home: string): NodeJS.ProcessEnv {+ return { ...process.env, HOME: home, CODEX_HOME: join(home, "codex-home") };+}++function oauthIdToken(accountId: string, marker = ""): string {+ const payload = Buffer.from(+ JSON.stringify({ "https://api.openai.com/auth": { chatgpt_account_id: accountId }, marker }),+ ).toString("base64url");+ return `header.${payload}.signature`;+}++function oauthAccessToken(accountId: string, marker = "access"): string {+ return oauthIdToken(accountId, marker);+}+test("Codex replay keeps paired tool ids within the provider's 64-character limit", () => {const longId = "tool-call-".repeat(9);const normalized = codexReplayCallId(longId);@@ -164,6 +190,259 @@ process.stdin.resume();return path;}+function startupCancellationCodexBinary(dir: string): string {+ const path = join(dir, "startup-cancellation-codex");+ writeFileSync(+ path,+ `#!${process.execPath}+const fs = require("node:fs");+fs.appendFileSync(${JSON.stringify(join(dir, "starts"))}, "start\\n");+process.on("SIGTERM", () => {+ fs.writeFileSync(${JSON.stringify(join(dir, "closed"))}, "closed");+ process.exit(0);+});+process.stdin.resume();+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function pendingTurnStartCodexBinary(dir: string): string {+ const path = join(dir, "pending-turn-start-codex");+ writeFileSync(+ path,+ `#!${process.execPath}+const fs = require("node:fs");+const readline = require("node:readline");+const rl = readline.createInterface({ input: process.stdin });+const send = (value) => process.stdout.write(JSON.stringify(value) + "\\n");+rl.on("line", (line) => {+ const msg = JSON.parse(line);+ if (msg.method === "initialize") return send({ id: msg.id, result: {} });+ if (msg.method === "initialized") return;+ if (msg.method === "thread/start") return send({ id: msg.id, result: { thread: { id: "thread-pending" } } });+ if (msg.method === "turn/start") fs.writeFileSync(${JSON.stringify(join(dir, "turn-started"))}, "started");+});+process.on("SIGTERM", () => {+ fs.writeFileSync(${JSON.stringify(join(dir, "closed"))}, "closed");+ process.exit(0);+});+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function refreshThenNonresponsiveCodexBinary(dir: string): string {+ const path = join(dir, "refresh-then-nonresponsive-codex");+ const accessToken = oauthAccessToken("startup-account", "startup-after");+ writeFileSync(+ path,+ `#!${process.execPath}+const fs = require("node:fs");+const path = require("node:path");+const authPath = path.join(process.env.CODEX_HOME, "auth.json");+const auth = JSON.parse(fs.readFileSync(authPath, "utf8"));+auth.tokens.access_token = ${JSON.stringify(accessToken)};+fs.writeFileSync(authPath, JSON.stringify(auth));+process.stdin.resume();+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function malformedCodexBinary(dir: string): string {+ const path = join(dir, "malformed-codex");+ writeFileSync(+ path,+ `#!${process.execPath}+process.stdout.write('{"access_token":"oauth-secret-123456789"\\n');+process.stdin.resume();+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function incompleteResponseCodexBinary(dir: string): string {+ const path = join(dir, "incomplete-response-codex");+ writeFileSync(+ path,+ `#!${process.execPath}+process.stdout.write('{"id":1}\\n');+process.stdin.resume();+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function arrayMessageCodexBinary(dir: string): string {+ const path = join(dir, "array-message-codex");+ writeFileSync(+ path,+ `#!${process.execPath}+process.stdout.write('[]\\n');+process.stdin.resume();+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function invalidJsonRpcBinary(dir: string): string {+ const path = join(dir, "invalid-json-rpc-codex");+ writeFileSync(+ path,+ `#!${process.execPath}+process.stdout.write('{"id":true,"result":{}}\\n');+process.stdin.resume();+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function noIdResponseCodexBinary(dir: string): string {+ const path = join(dir, "no-id-response-codex");+ writeFileSync(+ path,+ `#!${process.execPath}+process.stdout.write('{"result":{}}\\n');+process.stdin.resume();+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function unknownResponseCodexBinary(dir: string): string {+ const path = join(dir, "unknown-response-codex");+ writeFileSync(+ path,+ `#!${process.execPath}+process.stdout.write('{"id":999,"result":{}}\\n');+process.stdin.resume();+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function malformedTurnCompletedCodexBinary(dir: string): string {+ const path = join(dir, "malformed-turn-completed-codex");+ writeFileSync(+ path,+ `#!${process.execPath}+const readline = require("node:readline");+const rl = readline.createInterface({ input: process.stdin });+const send = value => process.stdout.write(JSON.stringify(value) + "\\n");+rl.on("line", line => {+ const msg = JSON.parse(line);+ if (msg.method === "initialize") return send({ id: msg.id, result: {} });+ if (msg.method === "initialized") return;+ if (msg.method === "thread/start") return send({ id: msg.id, result: { thread: { id: "malformed-thread" } } });+ if (msg.method === "turn/start") {+ send({ id: msg.id, result: { turn: { id: "malformed-turn", status: "inProgress", items: [] } } });+ return send({ method: "turn/completed", params: { threadId: "malformed-thread", turn: {} } });+ }+});+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function oauthTurnBinary(dir: string, token: string, delayMs: number): string {+ const path = join(dir, `oauth-${token}`);+ const events = join(dir, "oauth-events");+ const accessToken = oauthAccessToken("shared-account", token);+ writeFileSync(+ path,+ `#!${process.execPath}+const fs = require("node:fs");+const path = require("node:path");+const readline = require("node:readline");+const authPath = path.join(process.env.CODEX_HOME, "auth.json");+const send = (value) => process.stdout.write(JSON.stringify(value) + "\\n");+const rl = readline.createInterface({ input: process.stdin });+rl.on("line", (line) => {+ const msg = JSON.parse(line);+ if (msg.method === "initialize") return send({ id: msg.id, result: {} });+ if (msg.method === "initialized") return;+ if (msg.method === "thread/start") return send({ id: msg.id, result: { thread: { id: "thread-${token}" } } });+ if (msg.method === "turn/start") {+ const auth = JSON.parse(fs.readFileSync(authPath, "utf8"));+ auth.tokens.access_token = ${JSON.stringify(accessToken)};+ fs.writeFileSync(authPath, JSON.stringify(auth));+ fs.appendFileSync(${JSON.stringify(events)}, ${JSON.stringify(`${token}\n`)});+ send({ id: msg.id, result: { turn: { id: "turn-${token}", status: "inProgress", items: [] } } });+ return setTimeout(() => send({ method: "turn/completed", params: { threadId: "thread-${token}", turn: { id: "turn-${token}", status: "completed", items: [{ type: "agentMessage", text: ${JSON.stringify(token)}, phase: "final_answer" }] } } }), ${delayMs});+ }+ if (msg.method === "turn/interrupt") return send({ id: msg.id, result: {} });+});+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function accountEchoCodexBinary(dir: string, name: string, delayMs = 1): string {+ const path = join(dir, `account-echo-${name}`);+ writeFileSync(+ path,+ `#!${process.execPath}+const fs = require("node:fs");+const path = require("node:path");+const readline = require("node:readline");+const authPath = path.join(process.env.CODEX_HOME, "auth.json");+const send = (value) => process.stdout.write(JSON.stringify(value) + "\\n");+const rl = readline.createInterface({ input: process.stdin });+rl.on("line", (line) => {+ const msg = JSON.parse(line);+ if (msg.method === "initialize") return send({ id: msg.id, result: {} });+ if (msg.method === "initialized") return;+ if (msg.method === "thread/start") return send({ id: msg.id, result: { thread: { id: "thread-" + process.pid } } });+ if (msg.method === "turn/start") {+ const auth = JSON.parse(fs.readFileSync(authPath, "utf8"));+ const reply = String(auth.tokens.account_id ?? "none") + ":" + String("refresh_token" in auth.tokens);+ send({ id: msg.id, result: { turn: { id: "turn-" + process.pid, status: "inProgress", items: [] } } });+ return setTimeout(() => send({ method: "turn/completed", params: { threadId: "thread-" + process.pid, turn: { id: "turn-" + process.pid, status: "completed", items: [{ type: "agentMessage", text: reply, phase: "final_answer" }] } } }), ${delayMs});+ }+ if (msg.method === "turn/interrupt") return send({ id: msg.id, result: {} });+});+`,+ );+ chmodSync(path, 0o755);+ return path;+}++function exitingCodexBinary(dir: string): string {+ const path = join(dir, "exiting-codex");+ writeFileSync(+ path,+ `#!${process.execPath}+const readline = require("node:readline");+const rl = readline.createInterface({ input: process.stdin });+const send = (value) => process.stdout.write(JSON.stringify(value) + "\\n");+rl.on("line", (line) => {+ const msg = JSON.parse(line);+ if (msg.method === "initialize") return send({ id: msg.id, result: {} });+ if (msg.method === "initialized") return;+ if (msg.method === "thread/start") return send({ id: msg.id, result: { thread: { id: "thread-exit" } } });+ if (msg.method === "turn/start") {+ send({ id: msg.id, result: { turn: { id: "turn-exit", status: "inProgress", items: [] } } });+ setTimeout(() => process.exit(17), 50);+ }+});+`,+ );+ chmodSync(path, 0o755);+ return path;+}+test("Codex forwards external-content screening into its native tool bridge", () => {const screenExternalContent: NonNullable<HarnessTurnInput["screenExternalContent"]> = async () => ({decision: "auto",@@ -175,7 +454,7 @@ test("Codex forwards external-content screening into its native tool bridge", ()test("Codex harness drives app-server JSON-RPC with a read-only jail", async (t) => {const dir = mkdtempSync(join(tmpdir(), "qm-codex-test-"));const tasks = createMemoryTaskStore();- const harness = createCodexHarness({ binaryPath: fakeCodexBinary(dir), env: process.env, tasks });+ const harness = createCodexHarness({ binaryPath: fakeCodexBinary(dir), env: testHarnessEnv(dir), tasks });t.after(async () => {await harness.turns.close?.();rmSync(dir, { recursive: true, force: true });@@ -292,7 +571,7 @@ test("Codex child environment excludes core credentials and user homes", () => {test("Codex materializes API-key auth into its isolated home, and never an ambient login", (t) => {const jail = mkdtempSync(join(tmpdir(), "qm-codex-auth-test-"));t.after(() => rmSync(jail, { recursive: true, force: true }));- const home = prepareCodexHome({ OPENAI_API_KEY: "sk-test" }, jail);+ const home = prepareCodexHome({ CODEX_HOME: join(jail, "empty-source"), OPENAI_API_KEY: "sk-test" }, jail);assert.deepEqual(JSON.parse(readFileSync(join(home, "auth.json"), "utf8")), {auth_mode: "apikey",OPENAI_API_KEY: "sk-test",@@ -300,7 +579,332 @@ test("Codex materializes API-key auth into its isolated home, and never an ambieconst bare = mkdtempSync(join(tmpdir(), "qm-codex-auth-bare-"));t.after(() => rmSync(bare, { recursive: true, force: true }));- assert.equal(existsSync(join(prepareCodexHome({ HOME: homedir() }, bare), "auth.json")), false);+ assert.equal(+ existsSync(join(prepareCodexHome({ CODEX_HOME: join(bare, "empty-source") }, bare), "auth.json")),+ false,+ );+});++test("Codex materializes ChatGPT OAuth auth as ephemeral child material without the refresh token", async (t) => {+ const source = mkdtempSync(join(tmpdir(), "qm-codex-oauth-source-"));+ const jail = mkdtempSync(join(tmpdir(), "qm-codex-oauth-jail-"));+ t.after(() => {+ rmSync(source, { recursive: true, force: true });+ rmSync(jail, { recursive: true, force: true });+ });+ const authFile = join(source, "auth.json");+ writeFileSync(+ authFile,+ JSON.stringify({+ auth_mode: "chatgpt",+ OPENAI_API_KEY: "ambient-api-key",+ tokens: {+ access_token: oauthAccessToken("account-before", "before"),+ refresh_token: "refresh-before",+ account_id: "account-before",+ id_token: oauthIdToken("account-before"),+ },+ }),+ );+ chmodSync(authFile, 0o600);+ const sourceEnv = {+ CODEX_AUTH_FILE: authFile,+ OPENAI_API_KEY: "ambient-api-key",+ OPENAI_BASE_URL: "https://untrusted.example/v1",+ CODEX_ACCESS_TOKEN: "ambient-codex-token",+ };+ assert.deepEqual(codexChildEnv(sourceEnv, jail), {+ HOME: jail,+ CODEX_HOME: join(jail, "codex-home"),+ });+ const home = prepareCodexHome(sourceEnv, jail);+ const childAuthFile = join(home, "auth.json");+ const childAuth = JSON.parse(readFileSync(childAuthFile, "utf8")) as Record<string, unknown>;+ assert.equal(childAuth.OPENAI_API_KEY, undefined);+ assert.equal(+ (childAuth.tokens as Record<string, unknown>).access_token,+ oauthAccessToken("account-before", "before"),+ );+ assert.equal((childAuth.tokens as Record<string, unknown>).account_id, "account-before");+ // The child never receives the long-lived credential: only the store refreshes.+ assert.equal((childAuth.tokens as Record<string, unknown>).refresh_token, undefined);+ // Nothing a child writes ever flows back to the source of truth.+ writeFileSync(+ childAuthFile,+ JSON.stringify({+ ...childAuth,+ tokens: {+ access_token: oauthAccessToken("account-before", "after"),+ refresh_token: "refresh-forged",+ account_id: "account-before",+ id_token: oauthIdToken("account-before"),+ },+ }),+ );+ const persisted = JSON.parse(readFileSync(authFile, "utf8")) as Record<string, unknown>;+ assert.equal((persisted.tokens as Record<string, unknown>).refresh_token, "refresh-before");+ assert.equal(+ (persisted.tokens as Record<string, unknown>).access_token,+ oauthAccessToken("account-before", "before"),+ );+ // A stale lock left behind by a dead process is recovered, not honored forever.+ const liveLock = `${authFile}.lock`;+ writeFileSync(liveLock, String(process.pid));+ utimesSync(liveLock, new Date(0), new Date(0));+ const recoveredLock = await acquireCodexOAuthAuthLock(authFile, undefined, 1_000);+ assert.equal(recoveredLock.isHeld(), true);+ await recoveredLock.release();+ assert.equal(existsSync(liveLock), false);++ const defaultSource = mkdtempSync(join(tmpdir(), "qm-codex-oauth-default-source-"));+ const defaultJail = mkdtempSync(join(tmpdir(), "qm-codex-oauth-default-jail-"));+ t.after(() => {+ rmSync(defaultSource, { recursive: true, force: true });+ rmSync(defaultJail, { recursive: true, force: true });+ });+ mkdirSync(join(defaultSource, ".codex"), { recursive: true });+ writeFileSync(+ join(defaultSource, ".codex", "auth.json"),+ JSON.stringify({+ auth_mode: "chatgpt",+ tokens: {+ access_token: "default-access",+ refresh_token: "default-refresh",+ account_id: "default-account",+ id_token: oauthIdToken("default-account"),+ },+ }),+ );+ chmodSync(join(defaultSource, ".codex", "auth.json"), 0o600);+ const defaultEnv = { HOME: defaultSource, OPENAI_API_KEY: "ambient-default-api-key" };+ assert.equal(codexChildEnv(defaultEnv, defaultJail).OPENAI_API_KEY, undefined);+ assert.equal(existsSync(join(prepareCodexHome(defaultEnv, defaultJail), "auth.json")), true);+});++test("Codex diagnostics redact credential-shaped stderr", () => {+ assert.equal(+ redactCodexDiagnostics(+ '{"access_token":"access-secret","refresh_token":"refresh-secret"} Bearer bearer-secret-123456789 sk-secret-value',+ ),+ '{"access_token":"[redacted]","refresh_token":"[redacted]"} Bearer [redacted] [redacted]',+ );+ const diagnostics = redactCodexDiagnostics(+ "Authorization: Basic basic-secret-123456 Cookie: session-cookie-secret; Set-Cookie: refresh-cookie-secret; X-Api-Key: api-secret-123456 accessToken=camel-secret-123456 token=generic-secret-123456",+ );+ for (const secret of [+ "basic-secret-123456",+ "session-cookie-secret",+ "refresh-cookie-secret",+ "api-secret-123456",+ "camel-secret-123456",+ "generic-secret-123456",+ ])+ assert.equal(diagnostics.includes(secret), false, secret);+ const structured = redactCodexDiagnostics('authorization=["Bearer array-secret"] access_token="unterminated-secret');+ assert.equal(structured.includes("array-secret"), false);+ assert.equal(structured.includes("unterminated-secret"), false);+ const arrayDiagnostics = redactCodexDiagnostics('access_token=["first-array-secret","second-array-secret"]');+ assert.equal(arrayDiagnostics.includes("first-array-secret"), false);+ assert.equal(arrayDiagnostics.includes("second-array-secret"), false);+ const malformedArray = redactCodexDiagnostics('access_token=["first-array-secret",\n"second-array-secret"');+ assert.equal(malformedArray.includes("first-array-secret"), false);+ assert.equal(malformedArray.includes("second-array-secret"), false);+ const malformedObject = redactCodexDiagnostics('access_token={"a":"first-object-secret","b":"second-object-secret"}');+ assert.equal(malformedObject.includes("first-object-secret"), false);+ assert.equal(malformedObject.includes("second-object-secret"), false);+ const nested = redactCodexDiagnostics(+ JSON.stringify({+ nested: { authorization: { header: "Bearer nested-secret" } },+ tokens: { access_token: ["one-secret"] },+ }),+ );+ assert.equal(nested.includes("nested-secret"), false);+ assert.equal(nested.includes("one-secret"), false);+ assert.equal(redactCodexDiagnostics("id_token=header.payload.signature").includes("header.payload.signature"), false);+ const generic = redactCodexDiagnostics(+ JSON.stringify({+ secret: "generic-secret",+ password: "generic-password",+ opaque: "opaque-secret-value-123456789012345678901234",+ }),+ );+ assert.equal(generic.includes("generic-secret"), false);+ assert.equal(generic.includes("generic-password"), false);+ assert.equal(generic.includes("opaque-secret-value-123456789012345678901234"), false);+});++test("Codex ignores OAuth auth files that are readable by other users", (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-oauth-mode-test-"));+ const authFile = join(dir, "auth.json");+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ writeFileSync(+ authFile,+ JSON.stringify({+ auth_mode: "chatgpt",+ tokens: {+ access_token: "mode-access",+ refresh_token: "mode-refresh",+ account_id: "mode-account",+ id_token: oauthIdToken("mode-account"),+ },+ }),+ { mode: 0o600 },+ );+ assert.deepEqual(readCodexOAuthAuthFile(authFile), {+ auth_mode: "chatgpt",+ tokens: {+ access_token: "mode-access",+ refresh_token: "mode-refresh",+ account_id: "mode-account",+ id_token: oauthIdToken("mode-account"),+ },+ });+ chmodSync(authFile, 0o644);+ assert.equal(readCodexOAuthAuthFile(authFile), null);+});++test("Codex rejects OAuth auth files without a trusted account claim", (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-oauth-optional-account-test-"));+ const authFile = join(dir, "auth.json");+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ writeFileSync(+ authFile,+ JSON.stringify({+ auth_mode: "chatgpt",+ tokens: { access_token: "optional-access", refresh_token: "optional-refresh" },+ }),+ { mode: 0o600 },+ );+ assert.equal(readCodexOAuthAuthFile(authFile), null);+});++test("Codex diagnostics redact malformed app-server output at the protocol boundary", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-malformed-test-"));+ const server = new CodexAppServer({+ binaryPath: malformedCodexBinary(dir),+ cwd: dir,+ env: { PATH: process.env.PATH },+ onNotification: () => {},+ onRequest: async () => ({}),+ });+ t.after(async () => {+ await server.close().catch(() => undefined);+ rmSync(dir, { recursive: true, force: true });+ });+ await assert.rejects(server.initialize(), (error: unknown) => {+ const message = error instanceof Error ? error.message : String(error);+ assert.equal(message.includes("oauth-secret-123456789"), false);+ assert.equal(message.includes("[redacted]"), true);+ return true;+ });+});++test("Codex rejects incomplete JSON-RPC responses", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-incomplete-response-test-"));+ const server = new CodexAppServer({+ binaryPath: incompleteResponseCodexBinary(dir),+ cwd: dir,+ env: { PATH: process.env.PATH },+ onNotification: () => {},+ onRequest: async () => ({}),+ });+ t.after(async () => {+ await server.close().catch(() => undefined);+ rmSync(dir, { recursive: true, force: true });+ });+ await assert.rejects(server.initialize(), /invalid JSON/);+});++test("Codex rejects response messages without ids", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-no-id-response-test-"));+ const server = new CodexAppServer({+ binaryPath: noIdResponseCodexBinary(dir),+ cwd: dir,+ env: { PATH: process.env.PATH },+ onNotification: () => {},+ onRequest: async () => ({}),+ });+ t.after(async () => {+ await server.close().catch(() => undefined);+ rmSync(dir, { recursive: true, force: true });+ });+ await assert.rejects(server.initialize(), /invalid JSON/);+});++test("Codex rejects JSON arrays at the JSON-RPC boundary", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-array-message-test-"));+ const server = new CodexAppServer({+ binaryPath: arrayMessageCodexBinary(dir),+ cwd: dir,+ env: { PATH: process.env.PATH },+ onNotification: () => {},+ onRequest: async () => ({}),+ });+ t.after(async () => {+ await server.close().catch(() => undefined);+ rmSync(dir, { recursive: true, force: true });+ });+ await assert.rejects(server.initialize(), /invalid JSON/);+});++test("Codex rejects malformed JSON-RPC field types", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-invalid-json-rpc-test-"));+ const server = new CodexAppServer({+ binaryPath: invalidJsonRpcBinary(dir),+ cwd: dir,+ env: { PATH: process.env.PATH },+ onNotification: () => {},+ onRequest: async () => ({}),+ });+ t.after(async () => {+ await server.close().catch(() => undefined);+ rmSync(dir, { recursive: true, force: true });+ });+ await assert.rejects(server.initialize(), /invalid JSON/);+});++test("Codex rejects unknown JSON-RPC response ids", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-unknown-response-test-"));+ const server = new CodexAppServer({+ binaryPath: unknownResponseCodexBinary(dir),+ cwd: dir,+ env: { PATH: process.env.PATH },+ onNotification: () => {},+ onRequest: async () => ({}),+ });+ t.after(async () => {+ await server.close().catch(() => undefined);+ rmSync(dir, { recursive: true, force: true });+ });+ await assert.rejects(server.initialize(), /unknown response id/);+});++test("Codex rejects malformed turn completion payloads", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-malformed-turn-test-"));+ const harness = createCodexHarness({+ binaryPath: malformedTurnCompletedCodexBinary(dir),+ env: testHarnessEnv(dir),+ turnWallClockMs: 2_000,+ });+ t.after(async () => {+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ const scope = { kind: "org", id: "test" } as unknown as ScopeId;+ await assert.rejects(+ harness.turns.runTurn({+ session: { id: "malformed-turn" } as Session,+ input: "hi",+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ emit: async (entry) => ({ ...entry, sessionId: "malformed-turn", seq: 1, createdAt: Date.now() }) as SessionEntry,+ recordModelCall: () => {},+ }),+ /invalid turn\/completed payload/,+ );});test("Codex children cannot use parent surface, control, or terminal tools", () => {@@ -315,7 +919,7 @@ test("Codex interrupts the provider after a terminal QM tool", async (t) => {const dir = mkdtempSync(join(tmpdir(), "qm-codex-stop-test-"));const harness = createCodexHarness({binaryPath: terminatingCodexBinary(dir),- env: process.env,+ env: testHarnessEnv(dir),turnWallClockMs: 2_000,});t.after(async () => {@@ -382,7 +986,7 @@ test("Codex discards a nonresponsive startup so a later turn can retry", async (const dir = mkdtempSync(join(tmpdir(), "qm-codex-startup-test-"));const harness = createCodexHarness({binaryPath: nonresponsiveCodexBinary(dir),- env: process.env,+ env: testHarnessEnv(dir),appServerStartTimeoutMs: 1_000,turnWallClockMs: 6_000,});@@ -409,11 +1013,282 @@ test("Codex discards a nonresponsive startup so a later turn can retry", async (assert.equal(readFileSync(join(dir, "starts"), "utf8"), "start\nstart\n");});+test("Codex preserves OAuth auth before discarding a failed startup", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-startup-oauth-test-"));+ const authFile = join(dir, "auth.json");+ writeFileSync(+ authFile,+ JSON.stringify({+ auth_mode: "chatgpt",+ tokens: {+ access_token: "startup-access-before",+ refresh_token: "startup-refresh-before",+ account_id: "startup-account",+ id_token: oauthIdToken("startup-account"),+ },+ }),+ );+ chmodSync(authFile, 0o600);+ const harness = createCodexHarness({+ binaryPath: refreshThenNonresponsiveCodexBinary(dir),+ env: { CODEX_AUTH_FILE: authFile },+ appServerStartTimeoutMs: 1_000,+ turnWallClockMs: 3_000,+ });+ t.after(async () => {+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ const scope = { kind: "org", id: "test" } as unknown as ScopeId;+ await assert.rejects(+ harness.turns.runTurn({+ session: { id: "startup-oauth" } as Session,+ input: "hi",+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ emit: async (entry) => ({ ...entry, sessionId: "startup-oauth", seq: 1, createdAt: Date.now() }) as SessionEntry,+ recordModelCall: () => {},+ }),+ (error: unknown) => /timed out|exited|closed/i.test(error instanceof Error ? error.message : String(error)),+ );+ const persisted = JSON.parse(readFileSync(authFile, "utf8")) as Record<string, unknown>;+ assert.equal((persisted.tokens as Record<string, unknown>).access_token, "startup-access-before");+});++test("cancelling an OAuth startup after spawn closes the provider", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-cancel-startup-child-test-"));+ const authFile = join(dir, "auth.json");+ writeFileSync(+ authFile,+ JSON.stringify({+ auth_mode: "chatgpt",+ tokens: {+ access_token: "cancel-child-access",+ refresh_token: "cancel-child-refresh",+ account_id: "cancel-child-account",+ id_token: oauthIdToken("cancel-child-account"),+ },+ }),+ { mode: 0o600 },+ );+ const harness = createCodexHarness({+ binaryPath: startupCancellationCodexBinary(dir),+ env: { CODEX_AUTH_FILE: authFile },+ appServerStartTimeoutMs: 1_000,+ turnWallClockMs: 3_000,+ });+ t.after(async () => {+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ const cancel = new AbortController();+ const scope = { kind: "org", id: "test" } as unknown as ScopeId;+ const turn = harness.turns.runTurn({+ session: { id: "cancel-startup-child" } as Session,+ input: "hi",+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ cancel: cancel.signal,+ emit: async (entry) =>+ ({ ...entry, sessionId: "cancel-startup-child", seq: 1, createdAt: Date.now() }) as SessionEntry,+ recordModelCall: () => {},+ });+ for (let attempt = 0; attempt < 50 && !existsSync(join(dir, "starts")); attempt += 1)+ await new Promise((resolve) => setTimeout(resolve, 10));+ assert.equal(existsSync(join(dir, "starts")), true);+ cancel.abort();+ assert.deepEqual(await turn, { reply: "", stopped: true });+ for (let attempt = 0; attempt < 100 && !existsSync(join(dir, "closed")); attempt += 1)+ await new Promise((resolve) => setTimeout(resolve, 10));+ assert.equal(readFileSync(join(dir, "closed"), "utf8"), "closed");+});++test("cancelling a pending Codex turn/start stops and closes the runtime", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-cancel-turn-start-test-"));+ const harness = createCodexHarness({+ binaryPath: pendingTurnStartCodexBinary(dir),+ env: testHarnessEnv(dir),+ turnWallClockMs: 3_000,+ });+ t.after(async () => {+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ const cancel = new AbortController();+ const scope = { kind: "org", id: "test" } as unknown as ScopeId;+ const turn = harness.turns.runTurn({+ session: { id: "cancel-turn-start" } as Session,+ input: "hi",+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ cancel: cancel.signal,+ emit: async (entry) =>+ ({ ...entry, sessionId: "cancel-turn-start", seq: 1, createdAt: Date.now() }) as SessionEntry,+ recordModelCall: () => {},+ });+ for (let attempt = 0; attempt < 100 && !existsSync(join(dir, "turn-started")); attempt += 1)+ await new Promise((resolve) => setTimeout(resolve, 10));+ assert.equal(existsSync(join(dir, "turn-started")), true);+ cancel.abort();+ assert.deepEqual(await turn, { reply: "", stopped: true });+ for (let attempt = 0; attempt < 100 && !existsSync(join(dir, "closed")); attempt += 1)+ await new Promise((resolve) => setTimeout(resolve, 10));+ assert.equal(readFileSync(join(dir, "closed"), "utf8"), "closed");+});++test("per-user Codex turns run on their own app-server with derived auth, never the shared jail", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-per-user-test-"));+ const orgAuthFile = join(dir, "auth.json");+ writeFileSync(+ orgAuthFile,+ JSON.stringify({+ auth_mode: "chatgpt",+ tokens: {+ access_token: "org-access",+ refresh_token: "org-refresh",+ account_id: "org-account",+ id_token: oauthIdToken("org-account"),+ },+ }),+ { mode: 0o600 },+ );+ const orgAuthBefore = readFileSync(orgAuthFile, "utf8");+ const harness = createCodexHarness({+ binaryPath: accountEchoCodexBinary(dir, "per-user"),+ env: { CODEX_AUTH_FILE: orgAuthFile },+ turnWallClockMs: 5_000,+ });+ t.after(async () => {+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ const scope = { kind: "org", id: "test" } as unknown as ScopeId;+ const run = (id: string, accountId?: string) =>+ harness.turns.runTurn({+ session: { id } as Session,+ input: id,+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ ...(accountId+ ? {+ codexAuth: {+ accessToken: `${accountId}-access`,+ idToken: oauthIdToken(accountId),+ accountId,+ },+ }+ : {}),+ emit: async (entry) => ({ ...entry, sessionId: id, seq: 1, createdAt: Date.now() }) as SessionEntry,+ recordModelCall: () => {},+ });+ // Two different users' turns and an org turn, all concurrent.+ const [alice, bob, org] = await Promise.all([+ run("alice-turn", "acct-alice"),+ run("bob-turn", "acct-bob"),+ run("org-turn"),+ ]);+ // Each per-user turn saw its OWN account, and no jail ever held a refresh token.+ assert.equal(alice.reply, "acct-alice:false");+ assert.equal(bob.reply, "acct-bob:false");+ assert.equal(org.reply, "org-account:false");+ // The org credential on disk was never touched by per-user turns.+ assert.equal(readFileSync(orgAuthFile, "utf8"), orgAuthBefore);+});++test("Codex fails closed when OAuth auth is removed after startup", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-oauth-delete-test-"));+ const authFile = join(dir, "auth.json");+ writeFileSync(+ authFile,+ JSON.stringify({+ auth_mode: "chatgpt",+ tokens: {+ access_token: "delete-access",+ refresh_token: "delete-refresh",+ account_id: "delete-account",+ id_token: oauthIdToken("delete-account"),+ },+ }),+ { mode: 0o600 },+ );+ const harness = createCodexHarness({+ binaryPath: oauthTurnBinary(dir, "delete", 1),+ env: { CODEX_AUTH_FILE: authFile },+ turnWallClockMs: 3_000,+ });+ t.after(async () => {+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ const scope = { kind: "org", id: "test" } as unknown as ScopeId;+ const run = (id: string) =>+ harness.turns.runTurn({+ session: { id } as Session,+ input: id,+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ emit: async (entry) => ({ ...entry, sessionId: id, seq: 1, createdAt: Date.now() }) as SessionEntry,+ recordModelCall: () => {},+ });+ assert.equal((await run("before-delete")).reply, "delete");+ rmSync(authFile);+ await assert.rejects(run("after-delete"), /OAuth auth is unavailable/);+});++test("Codex app-server exits reject turns without unhandled rejections", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-exit-test-"));+ const harness = createCodexHarness({+ binaryPath: exitingCodexBinary(dir),+ env: testHarnessEnv(dir),+ turnWallClockMs: 3_000,+ });+ const unhandled: unknown[] = [];+ const onUnhandled = (error: unknown) => unhandled.push(error);+ process.on("unhandledRejection", onUnhandled);+ t.after(async () => {+ process.off("unhandledRejection", onUnhandled);+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ const scope = { kind: "org", id: "test" } as unknown as ScopeId;+ await assert.rejects(+ harness.turns.runTurn({+ session: { id: "exit-turn" } as Session,+ input: "hi",+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ emit: async (entry) => ({ ...entry, sessionId: "exit-turn", seq: 1, createdAt: Date.now() }) as SessionEntry,+ recordModelCall: () => {},+ }),+ /exited \(17\)/,+ );+ await new Promise((resolve) => setTimeout(resolve, 25));+ assert.deepEqual(unhandled, []);+});+test("cancelling one Codex setup does not kill another active turn", async (t) => {const dir = mkdtempSync(join(tmpdir(), "qm-codex-concurrent-test-"));const harness = createCodexHarness({binaryPath: concurrentCodexBinary(dir),- env: process.env,+ env: testHarnessEnv(dir),turnWallClockMs: 2_000,});t.after(async () => {@@ -496,6 +1371,10 @@ test("Codex never classifies its own infrastructure failures as terminal", () =>}assert.equal(codexProviderFailure("Codex turn failed").message, "Codex turn failed");assert.ok(!(codexProviderFailure("socket hang up") instanceof NonRetryableTurnError));+ assert.equal(+ codexProviderFailure("401 access_token=provider-secret-123456").message.includes("provider-secret"),+ false,+ );});test("Codex reads cumulative usage totals off the app-server's token notification", () => {@@ -543,7 +1422,7 @@ for (const mode of ["turnFailed", "startRejected"] as const) {const dir = mkdtempSync(join(tmpdir(), "qm-codex-fail-test-"));const harness = createCodexHarness({binaryPath: failingProviderCodexBinary(dir, mode),- env: process.env,+ env: testHarnessEnv(dir),turnWallClockMs: 5_000,});t.after(async () => {@@ -573,7 +1452,7 @@ test("Codex records one llm row per turn carrying real timings and usage, even wconst records: HarnessLlmRequestRecord[] = [];const scope = { kind: "org", id: "test" } as unknown as ScopeId;const runWith = async (binaryPath: string, id: string) => {- const harness = createCodexHarness({ binaryPath, env: process.env, turnWallClockMs: 5_000 });+ const harness = createCodexHarness({ binaryPath, env: testHarnessEnv(dir), turnWallClockMs: 5_000 });t.after(async () => await harness.turns.close?.());return await harness.turns.runTurn({session: { id } as Session,@@ -605,6 +1484,87 @@ test("Codex records one llm row per turn carrying real timings and usage, even wassert.ok(typeof records[1]!.durationMs === "number");});+test("Codex waits for the bounded durable llm record before completing a turn", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-telemetry-order-test-"));+ const scope = { kind: "org", id: "test" } as unknown as ScopeId;+ const harness = createCodexHarness({+ binaryPath: fakeCodexBinary(dir),+ env: testHarnessEnv(dir),+ turnWallClockMs: 5_000,+ });+ t.after(async () => {+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ let recorded = false;+ const startedAt = Date.now();+ const result = await harness.turns.runTurn({+ session: { id: "telemetry-order" } as Session,+ input: "hi",+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ emit: async (entry) => ({ ...entry, sessionId: "telemetry-order", seq: 1, createdAt: Date.now() }) as SessionEntry,+ recordModelCall: () => {},+ recordLlmRequest: async () => {+ await new Promise((resolve) => setTimeout(resolve, 50));+ recorded = true;+ },+ });+ assert.equal(result.reply, "hello");+ assert.equal(recorded, true);+ assert.ok(Date.now() - startedAt >= 45);+});++test("Codex aborts a durable llm record that exceeds its bound", async (t) => {+ const dir = mkdtempSync(join(tmpdir(), "qm-codex-telemetry-timeout-test-"));+ const scope = { kind: "org", id: "test" } as unknown as ScopeId;+ const harness = createCodexHarness({+ binaryPath: fakeCodexBinary(dir),+ env: testHarnessEnv(dir),+ turnWallClockMs: 12_000,+ });+ t.after(async () => {+ await harness.turns.close?.();+ rmSync(dir, { recursive: true, force: true });+ });+ let aborted = false;+ const result = await harness.turns.runTurn({+ session: { id: "telemetry-timeout" } as Session,+ input: "hi",+ systemPrompt: "be concise",+ history: [],+ tools: {} as HarnessTurnInput["tools"],+ scopeLabel: scope,+ orgScopeId: scope,+ emit: async (entry) =>+ ({ ...entry, sessionId: "telemetry-timeout", seq: 1, createdAt: Date.now() }) as SessionEntry,+ recordModelCall: () => {},+ recordLlmRequest: async (_record, signal) => {+ if (!signal) throw new Error("missing record cancellation signal");+ await new Promise<void>((resolve) => {+ if (signal.aborted) {+ aborted = true;+ resolve();+ return;+ }+ signal.addEventListener(+ "abort",+ () => {+ aborted = true;+ resolve();+ },+ { once: true },+ );+ });+ },+ });+ assert.equal(result.reply, "hello");+ assert.equal(aborted, true);+});+const realCodexBinary = (() => {try {return join(dirname(createRequire(import.meta.url).resolve("@openai/codex/package.json")), "bin/codex.js");@@ -623,7 +1583,7 @@ test(const server = new CodexAppServer({binaryPath: realCodexBinary!,cwd: jail,- env: codexChildEnv({ PATH: process.env.PATH }, jail),+ env: codexChildEnv({ PATH: process.env.PATH, CODEX_HOME: join(jail, "empty-source") }, jail),onNotification: () => {},onRequest: async (method) => {requests.push(method);@@ -636,43 +1596,56 @@ test(});await server.initialize();- const started = await server.request<{ thread: { id: string } }>("thread/start", {- model: DEFAULT_CODEX_MODEL_ID,- cwd: jail,- approvalPolicy: "never",- sandbox: "read-only",- ephemeral: true,- baseInstructions: "be concise",- developerInstructions: "use the supplied dynamic tools",- dynamicTools: [- {- type: "function",- name: "execute",- description: "run a command",- inputSchema: { type: "object", properties: {} },- },- ],- experimentalRawEvents: true,- environments: [],- config: {- web_search: "disabled",- features: {- shell_tool: false,- unified_exec: false,- shell_snapshot: false,- apps: false,- plugins: false,- browser_use: false,- browser_use_external: false,- computer_use: false,- image_generation: false,- in_app_browser: false,- multi_agent: true,- request_permissions_tool: false,- tool_suggest: false,+ const started = await server.request(+ "thread/start",+ {+ model: DEFAULT_CODEX_MODEL_ID,+ cwd: jail,+ approvalPolicy: "never",+ sandbox: "read-only",+ ephemeral: true,+ baseInstructions: "be concise",+ developerInstructions: "use the supplied dynamic tools",+ dynamicTools: [+ {+ type: "function",+ name: "execute",+ description: "run a command",+ inputSchema: { type: "object", properties: {} },+ },+ ],+ experimentalRawEvents: true,+ environments: [],+ config: {+ web_search: "disabled",+ features: {+ shell_tool: false,+ unified_exec: false,+ shell_snapshot: false,+ apps: false,+ plugins: false,+ browser_use: false,+ browser_use_external: false,+ computer_use: false,+ image_generation: false,+ in_app_browser: false,+ multi_agent: true,+ request_permissions_tool: false,+ tool_suggest: false,+ },},},- });+ (value: unknown): value is { thread: { id: string } } => {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const thread = (value as Record<string, unknown>).thread;+ return Boolean(+ thread &&+ typeof thread === "object" &&+ !Array.isArray(thread) &&+ typeof (thread as Record<string, unknown>).id === "string",+ );+ },+ );assert.ok(started.thread.id, "the real app-server returned a thread id for our start shape");await server.request("thread/inject_items", {threadId: started.thread.id,diff --git a/test/dev-cli-lib.test.ts b/test/dev-cli-lib.test.tsindex 3b0dd58b1..8b5271c49 100644--- a/test/dev-cli-lib.test.ts+++ b/test/dev-cli-lib.test.ts@@ -1,6 +1,6 @@import { test } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import { chmodSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { envSha, formatAge, readEnvFile } from "../scripts/dev/lib/util.ts";@@ -30,7 +30,7 @@ import {} from "../scripts/dev/lib/lease.ts";import { assembleEnv, completeDevSecuritySecrets } from "../scripts/dev/lib/envctx.ts";import { buildChildSpecs, type SpecInputs } from "../scripts/dev/supervisor/specs.ts";-import { loadConfig, OPENCODE_RUNTIME_VERSION } from "../src/config.ts";+import { loadConfig, OPENCODE_RUNTIME_VERSION, providerKeysPresent } from "../src/config.ts";import type { LeaseInfo } from "../scripts/dev/lib/types.ts";function tmpStore(): string {@@ -39,6 +39,13 @@ function tmpStore(): string {return store;}+function oauthIdToken(accountId: string): string {+ const payload = Buffer.from(+ JSON.stringify({ "https://api.openai.com/auth": { chatgpt_account_id: accountId } }),+ ).toString("base64url");+ return `header.${payload}.signature`;+}+function addSlot(store: string, n: number, extra = ""): void {writeFileSync(join(store, `pool${n}.env`),@@ -214,9 +221,39 @@ test("env assembly precedence: caller > login shell > dev.env > worktree .env; hassert.equal(openCode.env.PI_CAPTURE_REQUESTS, undefined);await assert.rejects(- assembleEnv({ worktree, callerEnv: { HARNESS: "codex" }, allowMock: false, log, probeLoginShell: async () => "" }),+ assembleEnv({+ worktree,+ callerEnv: { HARNESS: "codex", CODEX_HOME: join(worktree, "empty-codex") },+ allowMock: false,+ log,+ probeLoginShell: async () => "",+ }),/HARNESS=codex needs OPENAI_API_KEY/,);+ const oauthAuthFile = join(worktree, "codex-auth.json");+ writeFileSync(+ oauthAuthFile,+ JSON.stringify({+ auth_mode: "chatgpt",+ tokens: {+ access_token: "access",+ refresh_token: "refresh",+ account_id: "account",+ id_token: oauthIdToken("account"),+ },+ }),+ );+ chmodSync(oauthAuthFile, 0o600);+ const codexOAuth = await assembleEnv({+ worktree,+ callerEnv: { HARNESS: "codex", CODEX_AUTH_FILE: oauthAuthFile },+ allowMock: false,+ log,+ probeLoginShell: async () => "",+ });+ assert.equal(codexOAuth.harness, "codex");+ assert.equal(codexOAuth.env.CODEX_AUTH_FILE, oauthAuthFile);+ assert.equal(codexOAuth.codexAuthSource, oauthAuthFile);const codex = await assembleEnv({worktree,callerEnv: { HARNESS: "codex", OPENAI_API_KEY: "sk-openai" },@@ -315,6 +352,31 @@ test("OpenCode config is strict, pinned, and inherits the Pi model", () => {"claude-opus-4-8",);assert.equal(loadConfig({ HARNESS: "claude", CLAUDE_BIN: "/bin/claude" }).claudeBinPath, "/bin/claude");+ const source = mkdtempSync(join(tmpdir(), "qm-codex-config-"));+ const authFile = join(source, "auth.json");+ writeFileSync(+ authFile,+ JSON.stringify({+ auth_mode: "chatgpt",+ tokens: {+ access_token: "access",+ refresh_token: "refresh",+ account_id: "account",+ id_token: oauthIdToken("account"),+ },+ }),+ );+ chmodSync(authFile, 0o600);+ const oauthConfig = loadConfig({ HARNESS: "codex", CODEX_AUTH_FILE: authFile });+ assert.equal(oauthConfig.codexAuthFile, authFile);+ assert.equal(providerKeysPresent(oauthConfig).openai, false);+ assert.equal(providerKeysPresent(oauthConfig).codexOAuth, true);+ assert.throws(+ () =>+ loadConfig({ HARNESS: "codex", CODEX_AUTH_FILE: join(source, "missing.json"), OPENAI_API_KEY: "placeholder" }),+ /OPENAI_API_KEY/,+ );+ rmSync(source, { recursive: true, force: true });assert.throws(() => loadConfig({ HARNESS: "bogus" }), /use mock, pi, opencode, codex, or claude/);assert.throws(() => loadConfig({ HARNESS: "PI" }), /use mock, pi, opencode, codex, or claude/);});@@ -349,7 +411,12 @@ test("supervised children share the selected dev org", () => {const inputs: SpecInputs = {worktree: "/tmp/worktree",ports: slotPorts("pool1"),- baseEnv: { DEV_INSTANCE_ORG_ID: "beta" },+ baseEnv: {+ DEV_INSTANCE_ORG_ID: "beta",+ CODEX_AUTH_FILE: "/tmp/codex-auth.json",+ HOME: "/tmp/home",+ CODEX_HOME: "/tmp/home/.codex",+ },watch: false,webUiBasePath: "/",slack: { botToken: "xoxb-test", appToken: "xapp-test" },@@ -364,6 +431,12 @@ test("supervised children share the selected dev org", () => {};const specs = buildChildSpecs(inputs);assert.equal(specs.find((spec) => spec.name === "core")!.env.ORG_ID, "beta");+ assert.equal(specs.find((spec) => spec.name === "core")!.env.CODEX_AUTH_FILE, "/tmp/codex-auth.json");+ for (const spec of specs.filter((spec) => spec.name !== "core")) {+ assert.equal(spec.env.CODEX_AUTH_FILE, "");+ assert.equal(spec.env.HOME, undefined);+ assert.equal(spec.env.CODEX_HOME, undefined);+ }for (const spec of specs) assert.equal(spec.env.CORE_ORG_ID, "beta");inputs.baseEnv = {};assert.equal(buildChildSpecs(inputs).find((spec) => spec.name === "core")!.env.ORG_ID, "acme");diff --git a/test/model-credential-route.test.ts b/test/model-credential-route.test.tsindex a23343525..483f844b1 100644--- a/test/model-credential-route.test.ts+++ b/test/model-credential-route.test.ts@@ -8,6 +8,7 @@ import { join } from "node:path";import { test } from "node:test";import { createInsecureTestServer } from "../src/api/server.ts";import { buildApp, type BuiltApp } from "../src/wiring.ts";+import { providerKeysPresent, harnessCarriedModelAuth } from "../src/config.ts";import { testConfig } from "./support/test-config.ts";import { createModelCredentialStore, type StoredModelCredential } from "../src/model/model-credential-store.ts";import { createMemoryMap } from "../src/persistence/durable-map.ts";@@ -23,23 +24,18 @@ function start(built: BuiltApp;close: () => Promise<void>;} {- const built = buildApp(- testConfig({- dataDir: mkdtempSync(join(tmpdir(), "model-credential-route-")),- ...config,- }),- { modelCredentialFetch },- );+ const appConfig = testConfig({+ dataDir: mkdtempSync(join(tmpdir(), "model-credential-route-")),+ ...config,+ });+ const built = buildApp(appConfig, { modelCredentialFetch });const server = createInsecureTestServer(built.app, {config: built.config,modelCredentials: built.modelCredentials,modelCredentialFetch,harnessId: config.harness ?? "pi",- providerKeys: {- anthropic: Boolean(config.anthropicApiKey),- openai: Boolean(config.openaiApiKey),- openrouter: Boolean(config.openrouterApiKey),- },+ ...(harnessCarriedModelAuth(appConfig) ? { harnessCarriedModelAuth: harnessCarriedModelAuth(appConfig) } : {}),+ providerKeys: providerKeysPresent(appConfig),admin: built.admin,auditLog: built.auditLog,});@@ -421,6 +417,75 @@ test("surface-config reports whether any model provider is configured", async ()}});+test("surface-config respects an admin-disabled environment provider", async () => {+ const srv = start({ anthropicApiKey: "deployment-anthropic-key" });+ try {+ const before = await fetch(`${srv.base}/v1/surface-config`);+ assert.equal(((await before.json()) as { modelProviderConfigured?: boolean }).modelProviderConfigured, true);+ const disabled = await fetch(`${srv.base}/v1/admin/model-providers/anthropic`, {+ method: "DELETE",+ headers: ADMIN,+ });+ assert.equal(disabled.status, 200);+ const after = await fetch(`${srv.base}/v1/surface-config`);+ assert.equal(((await after.json()) as { modelProviderConfigured?: boolean }).modelProviderConfigured, false);+ } finally {+ await srv.close();+ }+});++test("surface-config reports Codex ChatGPT OAuth without making it a Pi credential", async () => {+ const srv = start({ harness: "codex", codexAuthFile: "/tmp/codex-auth.json" });+ try {+ const surface = await fetch(`${srv.base}/v1/surface-config`);+ assert.equal(surface.status, 200);+ assert.equal(((await surface.json()) as { modelProviderConfigured?: boolean }).modelProviderConfigured, true);+ } finally {+ await srv.close();+ }+});++test("a claude harness with an OAuth token counts as configured without corrupting store statuses", async () => {+ const srv = start({+ harness: "claude",+ claudeProcessEnv: { CLAUDE_CODE_OAUTH_TOKEN: "sk-ant-oat-test" } as NodeJS.ProcessEnv,+ });+ try {+ const surface = await fetch(`${srv.base}/v1/surface-config`);+ assert.equal(surface.status, 200);+ assert.equal(((await surface.json()) as { modelProviderConfigured?: boolean }).modelProviderConfigured, true);++ const providers = await fetch(`${srv.base}/v1/admin/model-providers`, { headers: ADMIN });+ assert.equal(providers.status, 200);+ const body = (await providers.json()) as {+ providers: Array<{ provider: string; configured: boolean; source: string }>;+ harnessAuth?: { harnessId: string; provider: string };+ };+ assert.deepEqual(body.harnessAuth, { harnessId: "claude", provider: "anthropic" });+ assert.deepEqual(+ body.providers.find((item) => item.provider === "anthropic"),+ { provider: "anthropic", configured: false, source: "absent" },+ );+ } finally {+ await srv.close();+ }+});++test("a claude harness without any token stays unconfigured", async () => {+ const srv = start({ harness: "claude" });+ try {+ const surface = await fetch(`${srv.base}/v1/surface-config`);+ assert.equal(surface.status, 200);+ assert.equal(((await surface.json()) as { modelProviderConfigured?: boolean }).modelProviderConfigured, false);++ const providers = await fetch(`${srv.base}/v1/admin/model-providers`, { headers: ADMIN });+ assert.equal(providers.status, 200);+ assert.equal("harnessAuth" in ((await providers.json()) as Record<string, unknown>), false);+ } finally {+ await srv.close();+ }+});+test("admin model credentials survive a second app instance on the same durable store", async () => {const backing = createMemoryMap<StoredModelCredential>();const first = createModelCredentialStore({ backing, keyMaterial: "shared-model-key" });diff --git a/test/user-model-auth-injection.test.ts b/test/user-model-auth-injection.test.tsnew file mode 100644index 000000000..70f0dec02--- /dev/null+++ b/test/user-model-auth-injection.test.ts@@ -0,0 +1,233 @@+import assert from "node:assert/strict";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { test } from "node:test";+import { createMemoryMap } from "../src/persistence/durable-map.ts";+import { createKeychain } from "../src/credentials/keychain.ts";+import { deriveConnectorKey } from "../src/connectors/connector-client-store.ts";+import { createUserModelCredentialStore } from "../src/model/user-model-credential-store.ts";+import { readFileSync } from "node:fs";+import { prepareCodexHome } from "../src/harness/codex-harness.ts";+import { codexOAuthAuthFromValue } from "../src/harness/codex-auth-store.ts";+import { resolveIndividualAuthRouting } from "../src/core/individual-auth-routing.ts";+import { resolveModel } from "../src/model/pi-models.ts";+import type { UserModelCredential } from "../src/model/user-model-credential-store.ts";++const apikey = (provider: "anthropic" | "openai", apiKey: string): UserModelCredential => ({+ provider,+ kind: "apikey",+ apiKey,+ updatedAt: 0,+});+const oauth = (provider: "anthropic" | "openai"): UserModelCredential => ({+ provider,+ kind: "oauth",+ oauth: {},+ updatedAt: 0,+});++function fakeIdToken(accountId: string): string {+ const seg = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64url");+ return `${seg({ alg: "RS256", typ: "JWT" })}.${seg({ "https://api.openai.com/auth": { chatgpt_account_id: accountId } })}.sig`;+}++const KEY_MATERIAL = "test-key-material-that-is-long-enough";++function testStore() {+ const keychain = createKeychain({+ creds: createMemoryMap(),+ grants: createMemoryMap(),+ asks: createMemoryMap(),+ key: deriveConnectorKey(KEY_MATERIAL),+ });+ return { keychain, store: createUserModelCredentialStore({ keychain }) };+}++test("user model credential store round-trips api key and oauth per user+provider", async () => {+ const { keychain, store } = testStore();+ await store.setApiKey("u1", "anthropic", "sk-ant-abc");+ const anth = await store.get("u1", "anthropic");+ assert.equal(anth?.kind, "apikey");+ assert.equal(anth?.apiKey, "sk-ant-abc");++ await store.setOAuth("u1", "openai", {+ accessToken: "acc",+ refreshToken: "ref",+ idToken: fakeIdToken("acct_1"),+ accountId: "acct_1",+ expiresAt: Date.now() + 3_600_000,+ });+ const oai = await store.get("u1", "openai");+ assert.equal(oai?.kind, "oauth");++ // The subscription login is a keychain CONNECTOR token: the keychain owns+ // encryption, expiry, and central refresh. Callers only ever get derived+ // material — never the refresh token.+ const derived = await store.derivedOAuth("u1", "openai");+ assert.equal(derived?.accessToken, "acc");+ assert.equal(derived?.idToken, fakeIdToken("acct_1"));+ assert.equal(derived?.accountId, "acct_1");+ assert.ok(!("refreshToken" in (derived ?? {})));+ assert.equal(await store.derivedOAuth("stranger", "openai"), null);++ assert.deepEqual(await store.connections("u1"), [+ { provider: "anthropic", kind: "apikey" },+ { provider: "openai", kind: "oauth" },+ ]);+ assert.deepEqual(await store.connections("stranger"), []);++ // API keys are ordinary user-owned keychain credentials (admin-visible,+ // covered by "remove my credentials").+ const owned = await keychain.listByOwner("u1");+ assert.deepEqual(+ owned.map((c) => c.service),+ ["model-anthropic"],+ );+ assert.ok(owned.every((c) => c.origin === "individual-model-auth"));+ assert.ok(!("secretEnc" in owned[0]!));+ // A stranger cannot read the owner's secret through the store's path.+ assert.equal(await keychain.readOwnSecret("stranger", owned[0]!.id), null);++ // One connection per provider: an API key replaces a subscription login.+ await store.setApiKey("u1", "openai", "sk-oai-xyz");+ assert.equal((await store.get("u1", "openai"))?.kind, "apikey");+ assert.equal(await store.derivedOAuth("u1", "openai"), null);+ // ...and a subscription login replaces an API key.+ await store.setOAuth("u1", "openai", { accessToken: "acc2", idToken: fakeIdToken("acct_1") });+ assert.equal((await store.get("u1", "openai"))?.kind, "oauth");++ await store.delete("u1", "anthropic");+ assert.equal(await store.get("u1", "anthropic"), null);+ await store.delete("u1", "openai");+ assert.equal(await store.get("u1", "openai"), null);+ assert.deepEqual(await store.connections("u1"), []);+});++test("stale subscription tokens refresh once (single-flight) inside the keychain", async () => {+ let refreshCalls = 0;+ const keychain = createKeychain({+ creds: createMemoryMap(),+ grants: createMemoryMap(),+ asks: createMemoryMap(),+ key: deriveConnectorKey(KEY_MATERIAL),+ refreshConnector: async (host, token) => {+ refreshCalls += 1;+ assert.equal(host, "auth.openai.com");+ assert.equal(token.refreshToken, "ref-0");+ await new Promise((resolveWait) => setTimeout(resolveWait, 20));+ return {+ accessToken: "acc-1",+ refreshToken: "ref-1",+ idToken: fakeIdToken("acct_1"),+ expiresAt: Date.now() + 3_600_000,+ };+ },+ });+ const store = createUserModelCredentialStore({ keychain });+ await store.setOAuth("u1", "openai", {+ accessToken: "acc-0",+ refreshToken: "ref-0",+ idToken: fakeIdToken("acct_1"),+ accountId: "acct_1",+ expiresAt: Date.now() - 1_000,+ });+ // Two concurrent turns for the same user: exactly one provider refresh.+ const [a, b] = await Promise.all([store.derivedOAuth("u1", "openai"), store.derivedOAuth("u1", "openai")]);+ assert.equal(refreshCalls, 1);+ assert.equal(a?.accessToken, "acc-1");+ assert.equal(b?.accessToken, "acc-1");+ // The rotated id token and preserved account id both survived the refresh.+ assert.equal(a?.idToken, fakeIdToken("acct_1"));+ assert.equal(a?.accountId, "acct_1");+ // A later read needs no further refresh.+ assert.equal((await store.derivedOAuth("u1", "openai"))?.accessToken, "acc-1");+ assert.equal(refreshCalls, 1);+});++test("routing: anthropic api key -> pi harness with a claude model", () => {+ const r = resolveIndividualAuthRouting(apikey("anthropic", "sk-ant-x"), null, undefined);+ assert.equal(r?.kind, "apikey");+ assert.equal(r?.harness, "pi");+ assert.equal(r?.provider, "anthropic");+ assert.equal((r as { apiKey: string }).apiKey, "sk-ant-x");+});++test("routing: anthropic OAuth login -> claude harness (not pi)", () => {+ const r = resolveIndividualAuthRouting(oauth("anthropic"), null, undefined);+ assert.equal(r?.kind, "oauth");+ assert.equal(r?.harness, "claude");+ assert.equal(r?.model, "claude-opus-5");+});++test("routing: openai OAuth login -> codex harness (not pi)", () => {+ const r = resolveIndividualAuthRouting(null, oauth("openai"), undefined);+ assert.equal(r?.kind, "oauth");+ assert.equal(r?.harness, "codex");+ assert.equal(r?.model, "gpt-5.6-sol");+});++test("routing: requested model provider wins when that provider is connected", () => {+ const r = resolveIndividualAuthRouting(oauth("anthropic"), oauth("openai"), "gpt-5.6-sol");+ assert.equal(r?.harness, "codex");+});++test("routing: openai OAuth + pi org -> pi harness on the Codex subscription provider", () => {+ const r = resolveIndividualAuthRouting(null, oauth("openai"), undefined, "pi");+ assert.equal(r?.kind, "oauth");+ assert.equal(r?.harness, "pi");+ assert.equal(r?.model, "codex/gpt-5.6-sol");+});++test("routing: pi org keeps a requested openai model, namespaced to the subscription provider", () => {+ const r = resolveIndividualAuthRouting(null, oauth("openai"), "gpt-5.6-terra", "pi");+ assert.equal(r?.harness, "pi");+ assert.equal(r?.model, "codex/gpt-5.6-terra");+});++test("routing: a non-pi org still hops to the codex harness", () => {+ const r = resolveIndividualAuthRouting(null, oauth("openai"), undefined, "codex");+ assert.equal(r?.harness, "codex");+});++test("routing: pi org with an anthropic OAuth login still uses the claude harness", () => {+ const r = resolveIndividualAuthRouting(oauth("anthropic"), null, undefined, "pi");+ assert.equal(r?.harness, "claude");+});++test("codex-subscription model ids resolve to pi-ai's openai-codex provider", () => {+ const m = resolveModel("codex/gpt-5.6-sol");+ assert.ok(m, "codex/gpt-5.6-sol must resolve");+ assert.equal(String(m?.provider), "openai-codex");+ assert.equal(String((m as { api?: string })?.api), "openai-codex-responses");+ assert.equal(m?.id, "codex/gpt-5.6-sol");+ // The un-prefixed id keeps resolving to the metered openai provider.+ assert.equal(String(resolveModel("gpt-5.6-sol")?.provider), "openai");+});++test("routing: no credentials -> null (falls through to gate, no deployment key)", () => {+ assert.equal(resolveIndividualAuthRouting(null, null, undefined), null);+});++test("per-user codex child auth is derived material: valid chatgpt auth without the refresh token", () => {+ const userAuth = codexOAuthAuthFromValue({+ auth_mode: "chatgpt",+ tokens: {+ access_token: "acc-token",+ refresh_token: "ref-token",+ id_token: fakeIdToken("acct_9"),+ account_id: "acct_9",+ },+ });+ assert.ok(userAuth, "per-user tokens must satisfy the codex auth validator");+ const jail = mkdtempSync(join(tmpdir(), "codex-inject-"));+ prepareCodexHome({}, jail, userAuth);+ const child = JSON.parse(readFileSync(join(jail, "codex-home", "auth.json"), "utf8")) as {+ auth_mode?: string;+ tokens?: Record<string, unknown>;+ };+ assert.equal(child.auth_mode, "chatgpt");+ assert.equal(child.tokens?.access_token, "acc-token");+ assert.equal(child.tokens?.refresh_token, undefined);+ assert.ok(child.tokens?.id_token);+});