Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: let a signed-in ChatGPT subscription serve PortOS text workflows (#5590)
[._.]/ Adam Eivy8f733061dc97
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.jsindex 9d8b3be7ea..ca2ff87677 100644--- a/client/src/services/apiProviders.js+++ b/client/src/services/apiProviders.js@@ -73,3 +73,11 @@ export const cancelCodexLogin = (loginId, options) => request('/providers/codex/...options,});export const codexLogout = (options) => request('/providers/codex/account/logout', { method: 'POST', ...options });+// The models this subscription may run, from the app-server catalog (#5590).+// Resolves to { models, fetchedAt, error }. `models: null` means NEVER FETCHED+// and `[]` means fetched-and-empty; when `error` is set the list is the+// last-known-good one, so render that rather than emptying the picker.+export const getCodexModels = (options = {}) => {+ const { fresh = false, ...rest } = options;+ return request(`/providers/codex/models${fresh ? '?fresh=1' : ''}`, rest);+};diff --git a/data.reference/providers.json b/data.reference/providers.jsonindex d98f9c91a2..a34ed1f2ac 100644--- a/data.reference/providers.json+++ b/data.reference/providers.json@@ -69,6 +69,7 @@"heavyModel": "gpt-5.6-sol","timeout": 300000,"enabled": true,+ "textTransport": "codex-app-server","envVars": {}},"antigravity-cli": {diff --git a/docs/API.md b/docs/API.mdindex 6b50c76deb..06a8625605 100644--- a/docs/API.md+++ b/docs/API.md@@ -121,6 +121,7 @@ own wire contract in [FEDERATED_MEDIA_PROVIDERS.md](./FEDERATED_MEDIA_PROVIDERS.| POST | `/providers/codex/account/login` | Start an explicit ChatGPT sign-in. Returns `{ login }` — a bounded `loginId` plus `authUrl` (browser flow) or `verificationUrl` + `userCode` (device-code flow, via `{ "deviceCode": true }`). A POST because it begins an OAuth flow; never a side effect of a read. 409s while another sign-in is already pending. || POST | `/providers/codex/account/login/cancel` | Abandon the pending sign-in named by `{ loginId }`, then re-read. 409s for an id that is not the pending login, so a stale tab cannot cancel a flow the user started afterwards. || POST | `/providers/codex/account/logout` | Sign out of ChatGPT and re-read. Codex drops its own credentials; PortOS holds none to clear. |+| GET | `/providers/codex/models?fresh=1` | Which models this ChatGPT subscription may run, from the app-server's own `model/list` rather than a hard-coded table. Answers `{ models, fetchedAt, error }`. The sentinels are load-bearing: `models: null` = NEVER FETCHED, `[]` = fetched and the plan genuinely has none, and a failed read returns the LAST-KNOWN-GOOD list alongside `error` — so one timeout can never empty the picker. Lazy like `/codex/account`; `fresh=1` skips the 10m TTL after a plan change or a sign-in. || GET | `/providers/opencode/installation` | **Legacy alias**, kept so a stale client bundle still renders: `{ installed, npmAvailable }` for the `opencode` runtime. New code uses `/providers/runtimes`. || POST | `/providers/opencode/install` | **Legacy alias** for `/providers/runtimes/install?runtime=opencode`. |diff --git a/scripts/migrations/331-codex-text-transport.js b/scripts/migrations/331-codex-text-transport.jsnew file mode 100644index 0000000000..e90008886a--- /dev/null+++ b/scripts/migrations/331-codex-text-transport.js@@ -0,0 +1,77 @@+/**+ * Advertise the ChatGPT-subscription text transport on the installed `codex`+ * provider (#5590).+ *+ * Phase 1 (#5589) taught PortOS to read the Codex account; this is the record+ * flag that lets the same `codex` record ALSO serve plain text through the+ * app-server, so a signed-in subscriber can point Brain / JIRA / Identity at+ * their subscription instead of buying an OpenAI API key.+ *+ * Two things this migration deliberately does NOT do:+ *+ * - **It never sets `textTransportEnabled`.** Advertising the capability is+ * not permission to bill a subscription; the user turns it on themselves.+ * A migration that enabled it would make an install start routing existing+ * background features through ChatGPT the moment it updated.+ * - **It never touches a record the user has already pointed somewhere else.**+ * A `codex` entry whose `command` is no longer the `codex` binary, or that+ * already carries a `textTransport`, is left exactly as it is.+ *+ * Kept in lockstep with data.reference/providers.json and+ * server/lib/aiToolkit/defaults/providers.sample.json. Later default changes+ * require a new migration.+ */++import { basename } from 'path';++import { readProvidersDoc, writeJsonAtomic } from './_lib.js';++const TRANSPORT = 'codex-app-server';+const CODEX_COMMAND = 'codex';++// Logged relative, never as `doc.path` — that is an absolute path carrying the+// operator's home directory, and a boot line is the wrong place to print it.+const PROVIDERS_REL_PATH = 'data/providers.json';++// `readProvidersDoc` is deliberately silent so each caller can say what ITS skip+// costs the user; this is 331's copy of that message.+const SKIP_REASONS = {+ 'no-file': 'not present (a fresh install seeds Codex from data.reference)',+ unreadable: 'is not valid JSON',+ 'bad-shape': 'has no providers map',+};++/**+ * Is this record still the shipped Codex CLI/TUI harness?+ *+ * Keyed on the COMMAND rather than the id, matching `isCodexSubscriptionProvider`+ * in server/lib/codexAccount.js: a user who renamed the record still runs the+ * same binary against the same ChatGPT sign-in, while a record repointed at a+ * different binary must not inherit a Codex-only capability.+ */+const isCodexHarness = (provider) => {+ if (provider?.type !== 'cli' && provider?.type !== 'tui') return false;+ if (provider.textTransport) return false;+ const command = typeof provider.command === 'string' ? provider.command.trim() : '';+ if (command === '') return false;+ return basename(command).replace(/\.(exe|cmd|bat)$/i, '') === CODEX_COMMAND;+};++export default {+ async up({ rootDir }) {+ const doc = await readProvidersDoc({ rootDir });+ if (!doc.ok) {+ const why = SKIP_REASONS[doc.reason] ?? 'could not be read';+ console.log(`📄 ${PROVIDERS_REL_PATH} ${why} — skipping the Codex text-transport flag`);+ return { ok: false, reason: doc.reason, updated: 0 };+ }++ const provider = doc.providers.codex;+ if (!isCodexHarness(provider)) return { ok: true, reason: 'already-current-or-custom', updated: 0 };++ provider.textTransport = TRANSPORT;+ await writeJsonAtomic(doc.path, doc.config);+ console.log(`📝 ${PROVIDERS_REL_PATH}: the codex provider now advertises the ChatGPT subscription text transport (off until enabled)`);+ return { ok: true, reason: 'updated', updated: 1 };+ },+};diff --git a/scripts/migrations/331-codex-text-transport.test.js b/scripts/migrations/331-codex-text-transport.test.jsnew file mode 100644index 0000000000..2d6d44ba7a--- /dev/null+++ b/scripts/migrations/331-codex-text-transport.test.js@@ -0,0 +1,78 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './331-codex-text-transport.js';++const CODEX = {+ id: 'codex', name: 'Codex CLI', type: 'cli', command: 'codex', enabled: true,+};++describe('migration 331 — codex text transport', () => {+ let rootDir;+ let providersPath;++ const writeProviders = (providers) => {+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ writeFileSync(providersPath, `${JSON.stringify({ activeProvider: 'codex', providers }, null, 2)}\n`);+ };+ const readProviders = () => JSON.parse(readFileSync(providersPath, 'utf8')).providers;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-331-'));+ providersPath = join(rootDir, 'data', 'providers.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('skips a fresh install with no providers.json (data.reference already ships the flag)', async () => {+ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: false, reason: 'no-file', updated: 0 });+ });++ it('advertises the transport without enabling it', async () => {+ writeProviders({ codex: { ...CODEX } });++ await expect(migration.up({ rootDir })).resolves.toEqual({ ok: true, reason: 'updated', updated: 1 });++ const codex = readProviders().codex;+ expect(codex.textTransport).toBe('codex-app-server');+ // The capability must stay OFF: a migration that enabled it would start+ // routing existing background features at the user's ChatGPT subscription+ // the moment they updated.+ expect(codex.textTransportEnabled).toBeUndefined();+ expect(codex).toMatchObject(CODEX);+ });++ it('matches a renamed clone by its command, and leaves other providers alone', async () => {+ writeProviders({+ codex: { ...CODEX, command: '/opt/bin/codex', name: 'My Codex' },+ openrouter: { id: 'openrouter', type: 'api', endpoint: 'https://example.com/v1', apiKey: 'secret' },+ });++ await migration.up({ rootDir });++ const providers = readProviders();+ expect(providers.codex.textTransport).toBe('codex-app-server');+ expect(providers.openrouter).toEqual({+ id: 'openrouter', type: 'api', endpoint: 'https://example.com/v1', apiKey: 'secret',+ });+ });++ it('leaves a record the user repointed at a different binary untouched', async () => {+ writeProviders({ codex: { ...CODEX, command: 'my-wrapper' } });++ await expect(migration.up({ rootDir })).resolves.toEqual({+ ok: true, reason: 'already-current-or-custom', updated: 0,+ });+ expect(readProviders().codex.textTransport).toBeUndefined();+ });++ it('is a no-op on a second run', async () => {+ writeProviders({ codex: { ...CODEX } });+ await migration.up({ rootDir });++ await expect(migration.up({ rootDir })).resolves.toEqual({+ ok: true, reason: 'already-current-or-custom', updated: 0,+ });+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex a5c5685f0c..1a72433959 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -193,6 +193,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (model flag only — non-interactive mode is implicit in `--prompt`, and kimi has no `--print`/`--afk` and refuses approval flags alongside `--prompt`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). || `runners.js` | Image-runner family constants (`RUNNER_FAMILIES`, `loraCompatKey`), video LoRA families, MiniMax H3 runtime predicates, and the shared `AUDIO_TO_VIDEO_RUNTIMES` / `isAudioToVideoRuntime` capability gate (LTX plus H3 Ref2VA). Mirrored to `client/src/lib/runnerFamilies.js`. || `codexAccount.js` | The ChatGPT-subscription half of the Codex providers (#5589), pure. The fixed `codex app-server` invocation, the `account/*` method + notification names, `CODEX_ACCOUNT_STATUS` (`runtime-missing` / `unknown` / `signed-out` / `login-pending` / `ready` / `quota-exhausted` / `reauth-required`) and `CODEX_ERROR_CODES`, `isCodexSubscriptionProvider` (keyed on the `codex` COMMAND, so a renamed clone still resolves), the `normalizeCodexAccount` / `normalizeCodexRateLimits` / `normalizeCodexLoginStart` payload normalizers, `redactCodexPayload` (every log/error/response path runs through it, so "PortOS never writes down a Codex token" is one function rather than a rule per call site), and `deriveCodexAccountStatus`. Sentinels are load-bearing: `runtimeInstalled: null` = NOT PROBED, `accountFetched: false` ≠ signed out, `rateLimits: null` (failed fetch) ≠ a fetched window with nothing to report. The process half is `services/codexAppServer.js`. |+| `codexTurn.js` | The INFERENCE half of the Codex ChatGPT-subscription provider (#5590), pure. The `thread/start` / `turn/start` / `turn/interrupt` / `model/list` method names and the turn notifications, `CODEX_TEXT_TRANSPORT` plus `providerDeclaresCodexTextTransport` (advertises) vs `isCodexTextTransportEnabled` (the explicit opt-in that actually permits routing), the `CODEX_TEXT_THREAD_CONFIG` safety envelope a generic text call runs under (empty throwaway cwd, read-only no-network sandbox, fail-closed approvals, no MCP servers, no web search), `normalizeCodexModels` / `normalizeCodexTokenUsage` / `resolveCodexEffort`, the `createTurnAccumulator` → `applyCodexTurnEvent` → `finalizeCodexTurn` projection (a non-`completed` turn yields an error, NEVER the partial text), and `classifyCodexTurnError` / `classifyCodexTransportError`, which fold both failure shapes onto the shared `ERROR_CATEGORIES` the cooldown policy reads. `models: null` = never fetched, `[]` = fetched-and-empty. The process half is `services/codexAppServer.js`. || `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. || `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. || `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex 4c7760c5c4..894fdca8da 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -422,6 +422,7 @@"contextWindow": 1000000,"timeout": 300000,"enabled": true,+ "textTransport": "codex-app-server","envVars": {},"secretEnvVars": []},diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex dac844695c..3037c6a70a 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -631,6 +631,12 @@ export function createProviderService(config = {}) {...modelContextWindowPatch(providerData.modelContextWindows),timeout: providerData.timeout || 300000,enabled: providerData.enabled !== false,+ // Subscription text-transport capability + its explicit opt-in. Only+ // persisted when set, so every existing HTTP/CLI record stays byte-identical+ // and an older install reading this file sees nothing new.+ ...(typeof providerData.textTransport === 'string' && providerData.textTransport+ ? { textTransport: providerData.textTransport } : {}),+ ...(providerData.textTransportEnabled === true ? { textTransportEnabled: true } : {}),// Claude Ollama marker — preserve so adopting the sample via POST drives// ollama-backed model refresh (see isOllamaBackedProvider)....(providerData.ollamaBacked === true ? { ollamaBacked: true } : {}),diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex ff600a133e..b858b932aa 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -128,6 +128,17 @@ export const providerSchema = z.object({modelContextWindows: z.record(z.number().int().min(512).max(33554432)).optional(),timeout: z.number().int().min(MIN_TIMEOUT).max(MAX_TIMEOUT).optional(),enabled: z.boolean().optional(),+ // A CLI/TUI provider that can ALSO serve plain text through a non-HTTP+ // transport — today only `codex-app-server`, the ChatGPT-subscription+ // endpoint. A string rather than a boolean so a second transport is a new+ // value instead of a second flag that can contradict the first. Declaring it+ // only ADVERTISES the capability.+ textTransport: z.enum(['codex-app-server']).nullable().optional(),+ // The explicit opt-in that makes the advertised transport usable. Separate+ // from `enabled` (which governs the CLI harness) and defaulted off, so a+ // fresh install never bills a subscription for a background feature the user+ // has not knowingly pointed at it.+ textTransportEnabled: z.boolean().optional(),// Marks a `claude` CLI/TUI provider whose ANTHROPIC_BASE_URL points at a// local Ollama daemon — the "Claude Ollama" pattern. Drives model refresh to// pull tool-use-capable Ollama models instead of the static Anthropic list.diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex b8f01a736b..1fc08aab95 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -18575,7 +18575,7 @@},{"source": "server/routes/providers.js",- "line": 169+ "line": 170}]},@@ -18590,7 +18590,7 @@},{"source": "server/routes/providers.js",- "line": 750+ "line": 767}]},@@ -18616,7 +18616,7 @@},{"source": "server/routes/providers.js",- "line": 704+ "line": 721}]},@@ -18631,7 +18631,7 @@},{"source": "server/routes/providers.js",- "line": 716+ "line": 733}]},@@ -18653,7 +18653,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 664+ "line": 681}]},@@ -18664,7 +18664,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 672+ "line": 689}]},@@ -18686,7 +18686,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 683+ "line": 700}]},@@ -18697,7 +18697,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 678+ "line": 695}]},@@ -18708,7 +18708,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 697+ "line": 714}]},@@ -18723,7 +18723,7 @@},{"source": "server/routes/providers.js",- "line": 189+ "line": 190}]},@@ -18738,7 +18738,7 @@},{"source": "server/routes/providers.js",- "line": 196+ "line": 197}]},@@ -18749,7 +18749,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 263+ "line": 264}]},@@ -18760,7 +18760,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 275+ "line": 276}]},@@ -18771,7 +18771,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 284+ "line": 285}]},@@ -18782,7 +18782,18 @@"sources": [{"source": "server/routes/providers.js",- "line": 290+ "line": 307+ }+ ]+ },+ {+ "method": "GET",+ "path": "/api/providers/codex/models",+ "mountPath": "/api/providers",+ "sources": [+ {+ "source": "server/routes/providers.js",+ "line": 302}]},@@ -18793,7 +18804,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 629+ "line": 646}]},@@ -18804,7 +18815,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 624+ "line": 641}]},@@ -18815,7 +18826,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 240+ "line": 241}]},@@ -18826,7 +18837,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 542+ "line": 559}]},@@ -18837,7 +18848,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 444+ "line": 461}]},@@ -18848,7 +18859,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 221+ "line": 222}]},@@ -18859,7 +18870,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 617+ "line": 634}]},@@ -18874,7 +18885,7 @@},{"source": "server/routes/providers.js",- "line": 209+ "line": 210}]},@@ -18885,7 +18896,7 @@"sources": [{"source": "server/routes/providers.js",- "line": 651+ "line": 668}]},@@ -23853,8 +23864,8 @@],"stats": {"mounts": 147,- "operations": 2152,- "declarations": 2155,+ "operations": 2153,+ "declarations": 2156,"sourceFiles": 229}}diff --git a/server/lib/codexTurn.js b/server/lib/codexTurn.jsnew file mode 100644index 0000000000..c64487018a--- /dev/null+++ b/server/lib/codexTurn.js@@ -0,0 +1,394 @@+/**+ * The INFERENCE half of the Codex ChatGPT-subscription provider (#5590), pure.+ *+ * `codexAccount.js` answers "is this subscription usable"; this module answers+ * "what can it run, and what did a run produce". It owns the thread/turn/model+ * slice of the documented Codex app-server protocol: which methods and+ * notifications PortOS speaks, the fixed safety envelope a generic text call+ * runs under, and the normalizers that turn protocol frames into PortOS's own+ * `{ text, usage, error }` contract. The process half is+ * `services/codexAppServer.js`.+ *+ * Two boundaries this file exists to hold:+ *+ * - **A text call is not a coding agent.** The `codex` provider stays a+ * file-writing CLI/TUI harness for CoS tasks; that path is untouched. When+ * the SAME record is selected as a text transport it runs under+ * {@link CODEX_TEXT_THREAD_CONFIG}: an empty throwaway cwd, a read-only+ * sandbox with no network, approvals that can only deny, no MCP servers,+ * and no web search. Nothing about the PortOS checkout or `data/` is+ * reachable from a Brain or JIRA summary call.+ * - **Partial output is not an answer.** A turn that is interrupted, fails,+ * or never reaches `turn/completed` yields an error, never the text+ * accumulated so far — a half-streamed JSON object that parsed would be+ * silently wrong data.+ *+ * Sentinel discipline (AGENTS.md) carries over from `codexAccount.js`:+ * `models: null` = NEVER FETCHED and `models: []` = fetched and genuinely+ * empty, so a catalog read that fails can never overwrite a last-known-good+ * list with "this account has no models".+ */++import { ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';+import { commandBasename } from './providerModels.js';+import { CODEX_APP_SERVER_COMMAND, CODEX_ERROR_CODES } from './codexAccount.js';++/**+ * The value a provider record carries to advertise that it can serve generic+ * text through the app-server. One string rather than a boolean so a future+ * second transport is a new value, not a second flag that can contradict the+ * first.+ */+export const CODEX_TEXT_TRANSPORT = 'codex-app-server';++/** Thread/turn/model JSON-RPC methods. Read + run; nothing that mutates state. */+export const CODEX_TURN_RPC = Object.freeze({+ threadStart: 'thread/start',+ turnStart: 'turn/start',+ turnInterrupt: 'turn/interrupt',+ modelList: 'model/list',+});++/** Server notifications a running turn projects into text/usage. */+export const CODEX_TURN_NOTIFICATIONS = Object.freeze({+ agentMessageDelta: 'item/agentMessage/delta',+ itemCompleted: 'item/completed',+ turnCompleted: 'turn/completed',+ tokenUsage: 'thread/tokenUsage/updated',+ error: 'error',+});++/**+ * The safety envelope every generic text turn runs under.+ *+ * `approvalPolicy: 'never'` is FAIL-CLOSED here, not permissive: paired with a+ * read-only sandbox it means an escalation request is refused outright rather+ * than queued for a human who is not watching a Brain summary. `ephemeral`+ * keeps the thread out of the user's Codex history, and the empty `mcp_servers`+ * / disabled web search strip every tool the model could otherwise reach for.+ *+ * The `cwd` is supplied per call (a fresh empty directory outside the PortOS+ * checkout) because it is a runtime path, not a constant.+ */+export const CODEX_TEXT_THREAD_CONFIG = Object.freeze({+ approvalPolicy: 'never',+ sandbox: 'read-only',+ ephemeral: true,+ config: Object.freeze({+ mcp_servers: {},+ tools: { web_search: false },+ web_search: false,+ }),+});++/** The per-turn sandbox override, restated so a turn cannot inherit a wider one. */+export const CODEX_TEXT_TURN_SANDBOX = Object.freeze({ type: 'readOnly', networkAccess: false });++/** Typed failures the transport raises, alongside `CODEX_ERROR_CODES`. */+export const CODEX_TURN_ERROR_CODES = Object.freeze({+ turnFailed: 'CODEX_TURN_FAILED',+ turnInterrupted: 'CODEX_TURN_INTERRUPTED',+ turnEmpty: 'CODEX_TURN_EMPTY',+ quotaExhausted: 'CODEX_QUOTA_EXHAUSTED',+ transportBenched: 'CODEX_TRANSPORT_BENCHED',+});++/**+ * Does this record ADVERTISE the subscription text transport?+ *+ * Advertising is not permission — see {@link isCodexTextTransportEnabled}. The+ * shipped seed advertises it so the Providers page has something to offer,+ * while the capability stays off until the user turns it on.+ */+export const providerDeclaresCodexTextTransport = (provider) => {+ if (provider?.textTransport !== CODEX_TEXT_TRANSPORT) return false;+ if (provider.type !== 'cli' && provider.type !== 'tui') return false;+ const command = typeof provider.command === 'string' ? provider.command.trim() : '';+ return command !== '' && commandBasename(command) === CODEX_APP_SERVER_COMMAND;+};++/**+ * May PortOS actually route a text call here?+ *+ * Requires the explicit opt-in, so a fresh install that has never signed in+ * cannot have a background feature quietly start billing a subscription — the+ * epic's "keep the capability off until the user enables it" rule, enforced at+ * the one place every caller passes through.+ */+export const isCodexTextTransportEnabled = (provider) =>+ providerDeclaresCodexTextTransport(provider)+ && provider.enabled !== false+ && provider.textTransportEnabled === true;++const trimmed = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : null);++const finiteInt = (value) => (typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : null);++/**+ * The non-secret shape of one `model/list` entry, or `null` when the entry has+ * no usable id.+ */+const normalizeModel = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ const id = trimmed(raw.id) || trimmed(raw.model);+ if (!id) return null;+ const supportedEfforts = Array.isArray(raw.supportedReasoningEfforts)+ ? raw.supportedReasoningEfforts+ .map((entry) => trimmed(typeof entry === 'string' ? entry : entry?.reasoningEffort))+ .filter(Boolean)+ : [];+ return {+ id,+ displayName: trimmed(raw.displayName) || id,+ description: trimmed(raw.description),+ isDefault: raw.isDefault === true,+ hidden: raw.hidden === true,+ defaultEffort: trimmed(raw.defaultReasoningEffort),+ supportedEfforts,+ contextWindow: finiteInt(raw.contextWindow),+ };+};++/**+ * The non-secret shape of `model/list`.+ *+ * THROWS for a response that is not a catalog, so a failed read stays `null`+ * at the call site and the last-known-good list survives. A catalog that is+ * genuinely empty returns `[]`, which is a real answer and must not be+ * re-labelled as a failed fetch.+ *+ * Hidden models are dropped: they are not in Codex's own picker, so offering+ * them in PortOS would surface ids the account cannot actually run.+ */+export const normalizeCodexModels = (result) => {+ if (!result || typeof result !== 'object') throw new Error('model/list returned a non-object result');+ const data = Array.isArray(result.data) ? result.data : (Array.isArray(result.models) ? result.models : null);+ if (!data) throw new Error('model/list returned no model array');+ return {+ models: data.map(normalizeModel).filter((model) => model !== null && !model.hidden),+ nextCursor: trimmed(result.nextCursor),+ };+};++/**+ * One token-usage breakdown, normalized to PortOS's field names, or `null`+ * when the payload carries no counts.+ *+ * `source: 'chatgpt-subscription'` is the attribution the criterion asks for:+ * the tokens are real, the dollar cost is NOT — a subscription turn has no+ * per-call price, and inventing one would corrupt the savings/quota views that+ * consume these records.+ */+export const normalizeCodexTokenUsage = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ const breakdown = raw.last ?? raw.total ?? raw;+ if (!breakdown || typeof breakdown !== 'object') return null;+ const inputTokens = finiteInt(breakdown.inputTokens);+ const outputTokens = finiteInt(breakdown.outputTokens);+ const totalTokens = finiteInt(breakdown.totalTokens);+ if (inputTokens === null && outputTokens === null && totalTokens === null) return null;+ return {+ inputTokens: inputTokens ?? 0,+ outputTokens: outputTokens ?? 0,+ cachedInputTokens: finiteInt(breakdown.cachedInputTokens) ?? 0,+ reasoningOutputTokens: finiteInt(breakdown.reasoningOutputTokens) ?? 0,+ totalTokens: totalTokens ?? ((inputTokens ?? 0) + (outputTokens ?? 0)),+ modelContextWindow: finiteInt(raw.modelContextWindow),+ source: 'chatgpt-subscription',+ };+};++/**+ * Which reasoning effort a turn should carry.+ *+ * The rule mirrors the existing Codex provider's visible clamp: an effort the+ * model does not advertise is reported as clamped to the model's own default+ * rather than silently sent and rejected mid-turn. A model whose catalog entry+ * PortOS has never fetched (`supportedEfforts: []`) is NOT evidence that the+ * effort is unsupported, so the request passes through untouched.+ */+export const resolveCodexEffort = (requested, model = null) => {+ const want = trimmed(requested);+ if (!want) return { effort: null, clamped: false, reason: null };+ const supported = Array.isArray(model?.supportedEfforts) ? model.supportedEfforts : [];+ if (supported.length === 0 || supported.includes(want)) return { effort: want, clamped: false, reason: null };+ const fallback = trimmed(model?.defaultEffort);+ return {+ effort: fallback,+ clamped: true,+ reason: `${model?.id || 'the selected model'} does not support "${want}" reasoning effort`+ + (fallback ? ` — using "${fallback}"` : ' — using the model default'),+ };+};++/**+ * Codex error identifiers that mean the SUBSCRIPTION is spent rather than the+ * request being wrong. Both spellings the protocol uses are listed because a+ * miss here degrades to a generic bench, which is the safe side.+ */+const QUOTA_ERROR_INFO = new Set(['usageLimitExceeded', 'sessionBudgetExceeded']);+const RATE_LIMIT_ERROR_INFO = new Set(['rateLimitExceeded', 'serverOverloaded']);+const AUTH_ERROR_INFO = new Set(['unauthorized']);++const errorInfoTag = (error) => {+ const info = error?.codexErrorInfo;+ if (typeof info === 'string') return info;+ if (info && typeof info === 'object') return Object.keys(info)[0] ?? null;+ return null;+};++/**+ * Map a `TurnError` (or a thrown transport error) onto the error category the+ * shared cooldown/fallback policy already understands.+ *+ * Returning a category rather than a bench duration keeps the policy in+ * `lib/providerCooldown.js` — one table, so a quota exhaustion benches for the+ * same window whichever path noticed it.+ */+export const classifyCodexTurnError = (error) => {+ const tag = errorInfoTag(error);+ const message = trimmed(error?.message) || 'The Codex turn failed';+ if (QUOTA_ERROR_INFO.has(tag)) return { category: ERROR_CATEGORIES.USAGE_LIMIT, message };+ if (RATE_LIMIT_ERROR_INFO.has(tag)) return { category: ERROR_CATEGORIES.RATE_LIMIT, message };+ if (AUTH_ERROR_INFO.has(tag)) return { category: ERROR_CATEGORIES.AUTH_ERROR, message };+ // 'context-length' is one of providerCooldown's SCHEMA_TYPE categories rather+ // than an ERROR_CATEGORIES member: an oversized prompt is REQUEST-specific, so+ // it must shrink and retry, never bench the subscription for every other call.+ if (tag === 'contextWindowExceeded') return { category: 'context-length', message };+ if (tag === 'cyberPolicy' || tag === 'misalignmentPolicyViolation') {+ return { category: ERROR_CATEGORIES.CONTENT_REFUSAL, message };+ }+ if (tag === 'httpConnectionFailed' || tag === 'responseStreamConnectionFailed'+ || tag === 'responseStreamDisconnected' || tag === 'responseTooManyFailedAttempts') {+ return { category: ERROR_CATEGORIES.NETWORK_ERROR, message };+ }+ if (tag === 'badRequest') return { category: ERROR_CATEGORIES.MODEL_NOT_FOUND, message };+ // No structured tag: fall back to the account module's text heuristics for+ // the one case that must not be missed — a sign-in that is simply gone.+ if (/\b(401|unauthorized|unauthenticated|invalid[_ -]?grant|token (?:expired|revoked)|re-?authenticate)\b/i.test(message)) {+ return { category: ERROR_CATEGORIES.AUTH_ERROR, message };+ }+ if (/\busage limit|quota (?:exceeded|exhausted)|out of credits\b/i.test(message)) {+ return { category: ERROR_CATEGORIES.USAGE_LIMIT, message };+ }+ return { category: ERROR_CATEGORIES.UNKNOWN, message };+};++/**+ * The error category for anything the transport can throw — a protocol/process+ * failure as well as a model-side `TurnError`.+ *+ * Two failure shapes reach a caller: a typed `ServerError` from the app-server+ * client (the binary is missing, the child died, a request timed out) and a+ * classified turn failure carried on `context.category`. Folding both here+ * means the cooldown/fallback decision reads ONE vocabulary — the same+ * `ERROR_CATEGORIES` every other provider path uses.+ */+export const classifyCodexTransportError = (err) => {+ const carried = err?.context?.category;+ if (typeof carried === 'string' && carried) return carried;+ switch (err?.code) {+ case CODEX_ERROR_CODES.runtimeMissing:+ case CODEX_ERROR_CODES.startFailed:+ case CODEX_ERROR_CODES.exited:+ return ERROR_CATEGORIES.SPAWN_ERROR;+ case CODEX_ERROR_CODES.timeout:+ return ERROR_CATEGORIES.TIMEOUT;+ case CODEX_ERROR_CODES.authRevoked:+ return ERROR_CATEGORIES.AUTH_ERROR;+ case CODEX_TURN_ERROR_CODES.turnInterrupted:+ return ERROR_CATEGORIES.CANCELED;+ default:+ return classifyCodexTurnError({ message: err?.message }).category;+ }+};++/** A fresh accumulator for one turn. */+export const createTurnAccumulator = (turnId = null) => ({+ turnId,+ deltas: [],+ finalText: null,+ usage: null,+ error: null,+ status: 'inProgress',+});++const appendText = (acc, text) => {+ if (typeof text !== 'string' || text === '') return;+ acc.deltas.push(text);+};++/**+ * Fold one server notification into the accumulator.+ *+ * Frames for another thread or another turn are ignored rather than merged —+ * one app-server connection is shared by every caller, so a concurrent turn's+ * deltas must never leak into this one's answer.+ *+ * Returns `true` when the turn has reached a terminal state.+ */+export const applyCodexTurnEvent = (acc, method, params) => {+ if (!acc || acc.status !== 'inProgress') return acc?.status !== 'inProgress';+ if (!params || typeof params !== 'object') return false;+ if (acc.turnId && typeof params.turnId === 'string' && params.turnId !== acc.turnId) return false;++ switch (method) {+ case CODEX_TURN_NOTIFICATIONS.agentMessageDelta:+ appendText(acc, params.delta);+ return false;+ case CODEX_TURN_NOTIFICATIONS.itemCompleted:+ // The completed item is AUTHORITATIVE for its own text; the deltas were a+ // progress signal. Replacing rather than appending is what keeps a+ // retried/repaired stream from producing doubled prose.+ if (params.item?.type === 'agentMessage' && typeof params.item.text === 'string') {+ acc.finalText = acc.finalText === null ? params.item.text : `${acc.finalText}${params.item.text}`;+ }+ return false;+ case CODEX_TURN_NOTIFICATIONS.tokenUsage:+ acc.usage = normalizeCodexTokenUsage(params.tokenUsage) ?? acc.usage;+ return false;+ case CODEX_TURN_NOTIFICATIONS.error:+ // `willRetry` means the app-server is still working the turn — recording+ // it as terminal here would abandon a run that is about to succeed.+ if (params.willRetry === true) return false;+ acc.error = classifyCodexTurnError(params.error);+ acc.status = 'failed';+ return true;+ case CODEX_TURN_NOTIFICATIONS.turnCompleted: {+ const turn = params.turn;+ if (acc.turnId && turn?.id && turn.id !== acc.turnId) return false;+ acc.status = typeof turn?.status === 'string' ? turn.status : 'completed';+ if (acc.status === 'failed') acc.error = classifyCodexTurnError(turn?.error);+ return true;+ }+ default:+ return false;+ }+};++/**+ * The finished turn as PortOS's `{ text, usage }` contract, or a thrown-shaped+ * `{ error }`.+ *+ * A non-`completed` status NEVER yields text. That is the "partial output is+ * never accepted as complete structured data" rule: an interrupted turn's+ * half-written JSON would parse into plausible, wrong data, so the caller gets+ * an error and its own fallback path instead.+ */+export const finalizeCodexTurn = (acc) => {+ if (!acc) return { error: 'The Codex turn produced no result', category: ERROR_CATEGORIES.UNKNOWN };+ if (acc.status === 'failed') {+ return { error: acc.error?.message || 'The Codex turn failed', category: acc.error?.category || ERROR_CATEGORIES.UNKNOWN };+ }+ if (acc.status === 'interrupted') {+ return { error: 'The Codex turn was cancelled', category: ERROR_CATEGORIES.CANCELED, canceled: true };+ }+ if (acc.status !== 'completed') {+ return { error: 'The Codex turn ended without completing', category: ERROR_CATEGORIES.UNKNOWN };+ }+ const text = acc.finalText !== null ? acc.finalText : acc.deltas.join('');+ if (!text.trim()) {+ return { error: 'Codex returned an empty completion', category: ERROR_CATEGORIES.UNKNOWN };+ }+ return { text, usage: acc.usage };+};diff --git a/server/lib/codexTurn.test.js b/server/lib/codexTurn.test.jsnew file mode 100644index 0000000000..2e2a86e0f6--- /dev/null+++ b/server/lib/codexTurn.test.js@@ -0,0 +1,279 @@+import { describe, it, expect } from 'vitest';++import { ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';+import { CODEX_ERROR_CODES } from './codexAccount.js';+import {+ CODEX_TEXT_THREAD_CONFIG,+ CODEX_TURN_ERROR_CODES,+ CODEX_TURN_NOTIFICATIONS,+ applyCodexTurnEvent,+ classifyCodexTransportError,+ createTurnAccumulator,+ finalizeCodexTurn,+ isCodexTextTransportEnabled,+ normalizeCodexModels,+ normalizeCodexTokenUsage,+ providerDeclaresCodexTextTransport,+ resolveCodexEffort,+} from './codexTurn.js';++const CODEX_CLI = { id: 'codex', type: 'cli', command: 'codex', textTransport: 'codex-app-server' };++describe('the transport capability gate', () => {+ it('separates advertising the capability from being allowed to use it', () => {+ // The shipped seed carries `textTransport` so the Providers page has+ // something to offer; without the explicit opt-in nothing may route here,+ // or updating PortOS would start billing a ChatGPT plan on its own.+ expect(providerDeclaresCodexTextTransport(CODEX_CLI)).toBe(true);+ expect(isCodexTextTransportEnabled(CODEX_CLI)).toBe(false);+ expect(isCodexTextTransportEnabled({ ...CODEX_CLI, textTransportEnabled: true })).toBe(true);+ });++ it('refuses a record that is not the Codex harness, however it is labelled', () => {+ const enabled = { ...CODEX_CLI, textTransportEnabled: true };+ // An API record authenticates with its own stored key and has nothing to do+ // with a subscription.+ expect(isCodexTextTransportEnabled({ ...enabled, type: 'api' })).toBe(false);+ // Repointed at another binary — the flag must not carry over.+ expect(isCodexTextTransportEnabled({ ...enabled, command: 'my-wrapper' })).toBe(false);+ expect(isCodexTextTransportEnabled({ ...enabled, command: '' })).toBe(false);+ expect(isCodexTextTransportEnabled({ ...enabled, enabled: false })).toBe(false);+ expect(isCodexTextTransportEnabled(null)).toBe(false);+ });++ it('matches a renamed clone by its command path', () => {+ expect(isCodexTextTransportEnabled({+ ...CODEX_CLI, id: 'codex-review', command: '/opt/homebrew/bin/codex', textTransportEnabled: true,+ })).toBe(true);+ });+});++describe('the generic-text safety envelope', () => {+ it('runs read-only, offline, tool-free, and fail-closed', () => {+ // Every clause here is a boundary a Brain/JIRA summary must not cross —+ // asserted as a unit so loosening one is a deliberate edit, not a drift.+ expect(CODEX_TEXT_THREAD_CONFIG).toMatchObject({+ approvalPolicy: 'never',+ sandbox: 'read-only',+ ephemeral: true,+ config: { mcp_servers: {}, tools: { web_search: false }, web_search: false },+ });+ });+});++describe('normalizeCodexModels', () => {+ it('throws for a non-catalog so a FAILED read can stay null at the call site', () => {+ // The whole sentinel discipline rests on this: a thrown read leaves the+ // last-known-good list alone, where a returned [] would erase it.+ expect(() => normalizeCodexModels(null)).toThrow();+ expect(() => normalizeCodexModels({})).toThrow();+ expect(() => normalizeCodexModels({ data: 'nope' })).toThrow();+ });++ it('returns [] for a catalog that is genuinely empty', () => {+ expect(normalizeCodexModels({ data: [] })).toEqual({ models: [], nextCursor: null });+ });++ it('keeps the pickable models and drops hidden ones', () => {+ const { models } = normalizeCodexModels({+ data: [+ {+ id: 'model-alpha',+ model: 'model-alpha',+ displayName: 'Model Alpha',+ description: 'A test model',+ isDefault: true,+ hidden: false,+ defaultReasoningEffort: 'medium',+ supportedReasoningEfforts: [{ reasoningEffort: 'low' }, { reasoningEffort: 'medium' }],+ },+ { id: 'model-hidden', hidden: true, supportedReasoningEfforts: [] },+ { displayName: 'no id at all' },+ ],+ });++ expect(models).toEqual([{+ id: 'model-alpha',+ displayName: 'Model Alpha',+ description: 'A test model',+ isDefault: true,+ hidden: false,+ defaultEffort: 'medium',+ supportedEfforts: ['low', 'medium'],+ contextWindow: null,+ }]);+ });+});++describe('resolveCodexEffort', () => {+ const model = { id: 'model-alpha', defaultEffort: 'medium', supportedEfforts: ['low', 'medium'] };++ it('passes a supported effort through', () => {+ expect(resolveCodexEffort('low', model)).toMatchObject({ effort: 'low', clamped: false });+ });++ it('clamps visibly to the model default rather than sending a rejected value', () => {+ const resolved = resolveCodexEffort('xhigh', model);+ expect(resolved).toMatchObject({ effort: 'medium', clamped: true });+ expect(resolved.reason).toMatch(/does not support "xhigh"/);+ });++ it('does not clamp against a catalog it has never fetched', () => {+ // `supportedEfforts: []` means UNKNOWN, not "supports nothing" — clamping on+ // it would silently downgrade every call made before the first model/list.+ expect(resolveCodexEffort('xhigh', { id: 'x', supportedEfforts: [] })).toMatchObject({+ effort: 'xhigh', clamped: false,+ });+ expect(resolveCodexEffort('xhigh', null)).toMatchObject({ effort: 'xhigh', clamped: false });+ });++ it('treats an unset effort as "use the provider default"', () => {+ expect(resolveCodexEffort('', model)).toMatchObject({ effort: null, clamped: false });+ expect(resolveCodexEffort(null, model)).toMatchObject({ effort: null, clamped: false });+ });+});++describe('turn projection', () => {+ const delta = (acc, text, extra = {}) =>+ applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.agentMessageDelta, { threadId: 't', delta: text, ...extra });+ const complete = (acc, turn) =>+ applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.turnCompleted, { threadId: 't', turn });++ it('joins deltas when no completed item supersedes them', () => {+ const acc = createTurnAccumulator('turn-1');+ delta(acc, 'Hello, ');+ delta(acc, 'world');+ expect(complete(acc, { id: 'turn-1', status: 'completed' })).toBe(true);++ expect(finalizeCodexTurn(acc)).toEqual({ text: 'Hello, world', usage: null });+ });++ it('prefers the completed item text over the deltas that previewed it', () => {+ const acc = createTurnAccumulator('turn-1');+ delta(acc, '{"partial"');+ applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.itemCompleted, {+ threadId: 't', turnId: 'turn-1', item: { type: 'agentMessage', text: '{"whole":true}' },+ });+ complete(acc, { id: 'turn-1', status: 'completed' });++ expect(finalizeCodexTurn(acc).text).toBe('{"whole":true}');+ });++ it('ignores frames belonging to another turn on the same connection', () => {+ const acc = createTurnAccumulator('turn-1');+ delta(acc, 'mine');+ delta(acc, 'SOMEBODY ELSE', { turnId: 'turn-2' });+ complete(acc, { id: 'turn-1', status: 'completed' });++ expect(finalizeCodexTurn(acc).text).toBe('mine');+ });++ it('keeps running through a retryable error', () => {+ const acc = createTurnAccumulator('turn-1');+ const terminal = applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.error, {+ threadId: 't', turnId: 'turn-1', willRetry: true, error: { message: 'transient' },+ });+ expect(terminal).toBe(false);++ delta(acc, 'recovered');+ complete(acc, { id: 'turn-1', status: 'completed' });+ expect(finalizeCodexTurn(acc).text).toBe('recovered');+ });++ it('NEVER hands back the partial text of an interrupted turn', () => {+ // A half-streamed JSON object that happened to parse would be silently wrong+ // data — worse than a failed call, which the caller can fall back from.+ const acc = createTurnAccumulator('turn-1');+ delta(acc, '{"answer": "half');+ complete(acc, { id: 'turn-1', status: 'interrupted' });++ expect(finalizeCodexTurn(acc)).toMatchObject({+ category: ERROR_CATEGORIES.CANCELED, canceled: true,+ });+ expect(finalizeCodexTurn(acc).text).toBeUndefined();+ });++ it('NEVER hands back the partial text of a failed turn, and carries its category', () => {+ const acc = createTurnAccumulator('turn-1');+ delta(acc, 'as much as I got');+ complete(acc, {+ id: 'turn-1',+ status: 'failed',+ error: { message: 'You have hit your usage limit.', codexErrorInfo: 'usageLimitExceeded' },+ });++ const result = finalizeCodexTurn(acc);+ expect(result.text).toBeUndefined();+ expect(result.category).toBe(ERROR_CATEGORIES.USAGE_LIMIT);+ });++ it('treats a completed-but-empty turn as a failure, not a successful blank answer', () => {+ const acc = createTurnAccumulator('turn-1');+ delta(acc, ' \n ');+ complete(acc, { id: 'turn-1', status: 'completed' });++ expect(finalizeCodexTurn(acc)).toMatchObject({ error: expect.stringMatching(/empty completion/i) });+ });++ it('records token usage under the subscription, with no invented dollar cost', () => {+ const acc = createTurnAccumulator('turn-1');+ applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.tokenUsage, {+ threadId: 't',+ turnId: 'turn-1',+ tokenUsage: {+ last: { inputTokens: 120, outputTokens: 40, cachedInputTokens: 10, reasoningOutputTokens: 5, totalTokens: 160 },+ modelContextWindow: 400000,+ },+ });+ delta(acc, 'answer');+ complete(acc, { id: 'turn-1', status: 'completed' });++ expect(finalizeCodexTurn(acc).usage).toEqual({+ inputTokens: 120,+ outputTokens: 40,+ cachedInputTokens: 10,+ reasoningOutputTokens: 5,+ totalTokens: 160,+ modelContextWindow: 400000,+ source: 'chatgpt-subscription',+ });+ expect(finalizeCodexTurn(acc).usage.cost).toBeUndefined();+ });++ it('normalizes a usage payload with no counts to null rather than a row of zeros', () => {+ expect(normalizeCodexTokenUsage({ last: {} })).toBeNull();+ expect(normalizeCodexTokenUsage(null)).toBeNull();+ });+});++describe('classifyCodexTransportError', () => {+ const cases = [+ ['a quota-exhausted turn', { context: { category: ERROR_CATEGORIES.USAGE_LIMIT } }, ERROR_CATEGORIES.USAGE_LIMIT],+ ['a missing runtime', { code: CODEX_ERROR_CODES.runtimeMissing }, ERROR_CATEGORIES.SPAWN_ERROR],+ ['a lost child process', { code: CODEX_ERROR_CODES.exited }, ERROR_CATEGORIES.SPAWN_ERROR],+ ['a request that never answered', { code: CODEX_ERROR_CODES.timeout }, ERROR_CATEGORIES.TIMEOUT],+ ['a revoked sign-in', { code: CODEX_ERROR_CODES.authRevoked }, ERROR_CATEGORIES.AUTH_ERROR],+ ['a cancelled turn', { code: CODEX_TURN_ERROR_CODES.turnInterrupted }, ERROR_CATEGORIES.CANCELED],+ ];++ it.each(cases)('maps %s onto the shared category vocabulary', (_label, error, expected) => {+ expect(classifyCodexTransportError(error)).toBe(expected);+ });++ it('falls back to the message when there is no structured tag', () => {+ expect(classifyCodexTransportError({ message: 'HTTP 401 unauthorized' })).toBe(ERROR_CATEGORIES.AUTH_ERROR);+ expect(classifyCodexTransportError({ message: 'something odd' })).toBe(ERROR_CATEGORIES.UNKNOWN);+ });++ it('classifies an oversized prompt as request-specific so it cannot bench the plan', () => {+ // 'context-length' is a SCHEMA_TYPE category — `isRequestSpecificCategory`+ // returns true for it, so the caller shrinks and retries instead of taking+ // the subscription offline for every other call.+ const acc = createTurnAccumulator('turn-1');+ applyCodexTurnEvent(acc, CODEX_TURN_NOTIFICATIONS.turnCompleted, {+ threadId: 't',+ turn: { id: 'turn-1', status: 'failed', error: { message: 'too long', codexErrorInfo: 'contextWindowExceeded' } },+ });+ expect(finalizeCodexTurn(acc).category).toBe('context-length');+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 69db5e0d63..efb3ac94e3 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -129,6 +129,7 @@ export * from './cliProviderArgs.js';export * from './cliProviderRun.js';export * from './codex.js';export * from './codexAccount.js';+export * from './codexTurn.js';export * from './codexAssistantExtract.js';export * from './codexCliOutput.js';export * from './contextBudget.js';diff --git a/server/lib/providerCooldown.js b/server/lib/providerCooldown.jsindex d8afb4fabc..c712d748b6 100644--- a/server/lib/providerCooldown.js+++ b/server/lib/providerCooldown.js@@ -43,6 +43,9 @@ export const COOLDOWN_MS_BY_CATEGORY = {[ERROR_CATEGORIES.UNKNOWN]: 60 * 1000,};export const DEFAULT_COOLDOWN_MS = 60 * 1000;+// A usage limit with no parsed reset window. Matches QUOTA_EXCEEDED's hour:+// both mean "the plan is spent", and retrying inside the hour is futile.+export const DEFAULT_USAGE_LIMIT_COOLDOWN_MS = 60 * 60 * 1000;// Categories the tiered cascade classifies as schema/type (mirrors// autoFixer.CATEGORY_TO_TIER's SCHEMA_TYPE entries; kept out of the CoS stack so@@ -103,3 +106,30 @@ export function resolveProviderBench(analysis) {waitTimeMs: COOLDOWN_MS_BY_CATEGORY[category] ?? DEFAULT_COOLDOWN_MS,};}++/**+ * How long a bench should actually last, in milliseconds.+ *+ * `resolveProviderBench` deliberately returns the `usage-limit` marker WITHOUT a+ * duration, because `providerStatus.markUsageLimit` parses its own window out of+ * the provider's error text. A caller that benches something other than a whole+ * provider record — the ChatGPT-subscription text transport, say — has no such+ * parser, and needs a number.+ *+ * `resetsAt` is the provider's own stated recovery time when one is known (Codex+ * reports it on the rate-limit window). It wins over the category table because+ * it is the truth rather than an estimate, but only when it is a real future+ * timestamp: a past or unparseable value would otherwise resolve to "unbench+ * immediately", which is exactly the failure a bench exists to prevent.+ *+ * @param {ReturnType<typeof resolveProviderBench>} bench+ * @param {{ resetsAt?: string|number|Date|null, now?: number }} [options]+ * @returns {number} milliseconds; `0` when `bench` is null (don't bench)+ */+export function resolveBenchWaitMs(bench, { resetsAt = null, now = Date.now() } = {}) {+ if (!bench) return 0;+ const resetMs = resetsAt == null ? NaN : new Date(resetsAt).getTime();+ if (Number.isFinite(resetMs) && resetMs > now) return resetMs - now;+ if (bench.marker === 'usage-limit') return DEFAULT_USAGE_LIMIT_COOLDOWN_MS;+ return bench.waitTimeMs ?? DEFAULT_COOLDOWN_MS;+}diff --git a/server/lib/providerCooldown.test.js b/server/lib/providerCooldown.test.jsindex ba01ebc9fd..07066c9945 100644--- a/server/lib/providerCooldown.test.js+++ b/server/lib/providerCooldown.test.js@@ -1,10 +1,13 @@import { describe, it, expect } from 'vitest';+import { ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';import {COOLDOWN_MS_BY_CATEGORY,DEFAULT_COOLDOWN_MS,+ DEFAULT_USAGE_LIMIT_COOLDOWN_MS,isRequestSpecificCategory,isSchemaTypeCategory,+ resolveBenchWaitMs,resolveProviderBench,} from './providerCooldown.js';@@ -78,3 +81,32 @@ describe('resolveProviderBench', () => {});});});++describe('resolveBenchWaitMs', () => {+ const NOW = 1_700_000_000_000;++ it('prefers the reset time the provider itself reported', () => {+ const bench = resolveProviderBench({ category: ERROR_CATEGORIES.USAGE_LIMIT });+ const resetsAt = new Date(NOW + 42 * 60_000).toISOString();++ expect(resolveBenchWaitMs(bench, { resetsAt, now: NOW })).toBe(42 * 60_000);+ });++ it('falls back to the category table when the reset time is missing, past, or junk', () => {+ // A past or unparseable timestamp resolving to "unbench now" is exactly the+ // failure a bench exists to prevent, so it must never win.+ const usage = resolveProviderBench({ category: ERROR_CATEGORIES.USAGE_LIMIT });+ expect(resolveBenchWaitMs(usage, { now: NOW })).toBe(DEFAULT_USAGE_LIMIT_COOLDOWN_MS);+ expect(resolveBenchWaitMs(usage, { resetsAt: new Date(NOW - 60_000).toISOString(), now: NOW }))+ .toBe(DEFAULT_USAGE_LIMIT_COOLDOWN_MS);+ expect(resolveBenchWaitMs(usage, { resetsAt: 'not a date', now: NOW }))+ .toBe(DEFAULT_USAGE_LIMIT_COOLDOWN_MS);++ const auth = resolveProviderBench({ category: ERROR_CATEGORIES.AUTH_ERROR });+ expect(resolveBenchWaitMs(auth, { now: NOW })).toBe(COOLDOWN_MS_BY_CATEGORY[ERROR_CATEGORIES.AUTH_ERROR]);+ });++ it('is zero for a failure that must not bench anything', () => {+ expect(resolveBenchWaitMs(resolveProviderBench({ category: ERROR_CATEGORIES.CONTENT_REFUSAL }))).toBe(0);+ });+});diff --git a/server/routes/providers.codexAccount.test.js b/server/routes/providers.codexAccount.test.jsindex 5a09ba9d5d..59900138dc 100644--- a/server/routes/providers.codexAccount.test.js+++ b/server/routes/providers.codexAccount.test.js@@ -13,6 +13,7 @@ vi.mock('../services/codexAppServer.js', () => ({cancelCodexChatGptLogin: vi.fn(),codexLogout: vi.fn(),peekCodexAccountReadiness: vi.fn(() => null),+ listCodexModels: vi.fn(),}));vi.mock('../services/providerRuntimeInstaller.js', async (importOriginal) => ({...(await importOriginal()),@@ -185,3 +186,39 @@ describe('GET /api/providers decorates the Codex cards', () => {expect(cards.codex.prerequisitesMet).toBe(true);});});++describe('GET /api/providers/codex/models', () => {+ it('returns the catalog and honours ?fresh=1', async () => {+ codexAppServer.listCodexModels.mockResolvedValue({+ models: [{ id: 'model-alpha', displayName: 'Alpha', supportedEfforts: ['low', 'medium'] }],+ fetchedAt: 1_700_000_000_000,+ error: null,+ });++ const res = await request(appWith()).get('/api/providers/codex/models');+ expect(res.status).toBe(200);+ expect(res.body.models).toHaveLength(1);+ expect(codexAppServer.listCodexModels).toHaveBeenCalledWith({ fresh: false });++ await request(appWith()).get('/api/providers/codex/models?fresh=1');+ expect(codexAppServer.listCodexModels).toHaveBeenLastCalledWith({ fresh: true });+ });++ it('passes the failed-fetch sentinel through instead of publishing an empty picker', async () => {+ // `models` here is the LAST-KNOWN-GOOD list plus an `error` — the client+ // must be able to tell that from a plan that genuinely has no models (`[]`)+ // and from never having asked (`null`).+ codexAppServer.listCodexModels.mockResolvedValue({+ models: [{ id: 'model-alpha' }],+ fetchedAt: 1_700_000_000_000,+ error: { code: 'CODEX_APP_SERVER_TIMEOUT', message: 'timed out' },+ });++ const res = await request(appWith()).get('/api/providers/codex/models');+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({+ models: [{ id: 'model-alpha' }],+ error: { code: 'CODEX_APP_SERVER_TIMEOUT' },+ });+ });+});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 23983e2703..4a3d989aa2 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -31,6 +31,7 @@ import {cancelCodexChatGptLogin,peekCodexAccountReadiness,codexLogout,+ listCodexModels,getCodexAccountReadiness,startCodexChatGptLogin,} from '../services/codexAppServer.js';@@ -286,6 +287,22 @@ export function createPortOSProviderRoutes(aiToolkit) {res.json({ readiness: await cancelCodexChatGptLogin(loginId) });}));+ /**+ * Which models this ChatGPT subscription may run, from the app-server's own+ * catalog rather than a hard-coded list — so the picker reflects the account's+ * actual plan.+ *+ * LAZY, like `/codex/account`: only an explicit page fetch reaches it.+ * `?fresh=1` skips the TTL after a plan change or a sign-in.+ *+ * `models: null` means NEVER FETCHED, `[]` means fetched-and-empty, and a read+ * that fails returns the last-known-good list alongside `error` — the client+ * must not repaint an empty picker because one call timed out.+ */+ router.get('/codex/models', asyncHandler(async (req, res) => {+ res.json(await listCodexModels({ fresh: req.query.fresh === '1' }));+ }));+/** Sign out. Codex drops its own credentials; PortOS has none to clear. */router.post('/codex/account/logout', asyncHandler(async (_req, res) => {res.json({ readiness: await codexLogout() });diff --git a/server/services/aiProvider.js b/server/services/aiProvider.jsindex 8dc14c4e01..47f7238a6b 100644--- a/server/services/aiProvider.js+++ b/server/services/aiProvider.js@@ -12,10 +12,25 @@ import { ensureMtplxProviderReady, isMtplxProvider } from './mtplxServerManager.// eagerly import fileUtils `PATHS`) into every aiProvider consumer's module// graph, breaking suites that partial-mock fileUtils without PATHS.import { readResponseJson } from '../lib/readResponseJson.js';+// The PURE half of the Codex subscription transport only. The process half+// (services/codexAppServer.js) is lazy-imported at its call site below, so a+// consumer of this module never pulls a child-process graph it will not use —+// and suites that partial-mock this file's deps keep working.+import { classifyCodexTransportError, isCodexTextTransportEnabled } from '../lib/codexTurn.js';+import { resolveBenchWaitMs, resolveProviderBench } from '../lib/providerCooldown.js';+import { ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';import { evaluateSecretEndpoint } from '../lib/aiToolkit/internal/endpointGuard.js';import { withCreativeLatitude } from '../lib/creativeLatitude.js';const isAPI = (p) => p && p.type === 'api' && p.enabled !== false;+/**+ * A CLI/TUI record the user has explicitly pointed at a non-HTTP text+ * transport — today only the Codex ChatGPT subscription. It can serve the same+ * bounded prompts an API provider can, without an API key.+ */+const isSubscriptionText = (p) => isCodexTextTransportEnabled(p);+/** Anything this module can run a prompt through. */+const isTextCapable = (p) => isAPI(p) || isSubscriptionText(p);// LM Studio auto-recovery timeouts. Listing downloaded models is a quick local// HTTP call; loading a model into VRAM can take a while on a cold start.@@ -26,18 +41,26 @@ const LM_STUDIO_LOAD_TIMEOUT_MS = 120000;const DEFAULT_PROVIDER_TIMEOUT_MS = 300000;/**- * Resolve an API-type provider for features that can only run against an API- * endpoint (CLI providers don't support the simple chat-completions call path).+ * Resolve a provider for features that need a bounded text call rather than a+ * coding agent.** Resolution order:- * 1. The requested provider (if API-type)- * 2. The user's active provider (if API-type)+ * 1. The requested provider (if it can serve text)+ * 2. The user's active provider (if it can serve text)* 3. The first enabled API provider configured*- * Returns null when no API provider is configured — callers should surface a+ * Steps 1 and 2 accept the Codex ChatGPT-subscription transport, because both+ * name a provider the user chose. Step 3 stays **API-ONLY on purpose**: it is a+ * blind sweep of whatever happens to be configured, and letting it land on a+ * subscription would silently move a background feature's billing from an API+ * key the user is already paying for onto their ChatGPT plan (and, in the other+ * direction, an unavailable subscription must not silently start spending an+ * API key). Switching billing source is a decision, not a fallback.+ *+ * Returns null when nothing is configured — callers should surface a* "configure an API provider" hint rather than re-throwing.*/-export async function resolveAPIProvider(requestedProviderId) {+export async function resolveTextProvider(requestedProviderId) {// One read of providers.json — getAllProviders returns both the active id// and the full list, so we don't need separate getProviderById/getActiveProvider// round-trips for each step of the fallback chain.@@ -48,15 +71,20 @@ export async function resolveAPIProvider(requestedProviderId) {if (requestedProviderId) {const requested = providers.find(p => p.id === requestedProviderId);- if (isAPI(requested)) return requested;+ if (isTextCapable(requested)) return requested;}if (all?.activeProvider) {const active = providers.find(p => p.id === all.activeProvider);- if (isAPI(active)) return active;+ if (isTextCapable(active)) return active;}return providers.find(isAPI) || null;}+// The name every existing caller imports. Kept as a permanent alias rather than+// a codemod: other installs and forks call it, and renaming a public export in+// place would break them on their own upgrade schedule.+export { resolveTextProvider as resolveAPIProvider };+// LM Studio's chat-completions endpoint returns this when no model is in// memory. The error is identical regardless of which model name the request// asked for, so retrying with a different name is pointless — we have to@@ -194,6 +222,140 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_to};}+/**+ * Resolve the ONE provider the user explicitly nominated as this provider's+ * fallback, when it can serve text on its own credentials.+ *+ * Only `fallbackProvider` counts — never a sweep of whatever else is+ * configured. A subscription going quiet must not silently start spending an+ * API key the user never pointed at this work.+ */+async function resolveExplicitFallback(provider) {+ const fallbackId = typeof provider.fallbackProvider === 'string' ? provider.fallbackProvider.trim() : '';+ if (!fallbackId) return null;+ const all = await getAllProviders().catch(() => null);+ const providers = Array.isArray(all?.providers) ? all.providers : Object.values(all?.providers || {});+ const fallback = providers.find(p => p.id === fallbackId);+ // A subscription-backed fallback would just re-enter the same benched+ // transport, so only an API record is a real escape hatch here.+ if (!isAPI(fallback)) return null;+ return fallback;+}++/**+ * Run a bounded text prompt through the user's ChatGPT subscription.+ *+ * Returns the same `{ text }` / `{ error }` shape the HTTP path does, so no+ * caller has to know which transport served it.+ *+ * Failure handling has three steps, in this order:+ *+ * 1. Classify the failure with the same category vocabulary every other+ * provider path uses.+ * 2. Bench the TRANSPORT — not the `codex` provider record. An exhausted+ * subscription window must not take the CLI coding harness offline as a+ * side effect; that is a separate capability of the same record. The+ * duration comes from the shared cooldown policy, preferring the reset+ * time Codex itself reported.+ * 3. Retry once on the provider's EXPLICIT fallback, if it named one.+ *+ * `temperature` / `max_tokens` have no app-server equivalent and are dropped+ * rather than approximated: the turn is governed by the model and its reasoning+ * effort, and inventing a mapping would make two providers disagree about what+ * the same options mean.+ */+async function callCodexSubscription(provider, model, prompt, {+ statusOp, doneLabel, elapsedSec, throughput, timeout, responseSchema, signal,+}) {+ const {+ benchCodexTextTransport,+ getCodexTextTransportBench,+ peekCodexAccountReadiness,+ runCodexTextTurn,+ } = await import('./codexAppServer.js');++ // An active bench short-circuits the wire: the transport already knows it+ // cannot serve this window, so there is no point paying for the round trip.+ const benched = getCodexTextTransportBench();+ // Why the subscription can't serve this call. Set either by that bench or by+ // the turn that just failed — it is the message the user sees when there is+ // no fallback, so it must be the real one, never a generic stand-in.+ let reason = benched?.message ?? 'The ChatGPT subscription is temporarily unavailable.';++ if (!benched) {+ statusOp.update('provider:starting', 'Running through the ChatGPT subscription…', { providerId: provider.id });+ const turn = await runCodexTextTurn({+ prompt,+ model: model || provider.defaultModel || null,+ effort: provider.effort || null,+ timeoutMs: timeout,+ responseSchema,+ signal,+ }).catch((err) => ({ error: err }));++ if (!turn.error) {+ if (turn.effortClamped) statusOp.update('model:corrected', turn.clampReason, { model: turn.model });+ statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, throughput(turn.usage?.outputTokens));+ return { text: turn.text, usage: turn.usage };+ }++ reason = turn.error.message;+ const category = classifyCodexTransportError(turn.error);+ // A caller who pressed Stop is not a provider fault. Benching would take the+ // subscription off the board for work the user never abandoned, and burning+ // the fallback would pay for an answer nobody is waiting for.+ if (category === ERROR_CATEGORIES.CANCELED) {+ statusOp.error(reason, { providerId: provider.id });+ return { error: reason, canceled: true };+ }+ const bench = resolveProviderBench({ category, message: reason });+ if (bench) {+ benchCodexTextTransport({+ waitMs: resolveBenchWaitMs(bench, { resetsAt: reportedResetsAt(peekCodexAccountReadiness()) }),+ category,+ message: reason,+ });+ }+ }++ const fallback = await resolveExplicitFallback(provider);+ if (!fallback) {+ statusOp.error(reason, { providerId: provider.id });+ return { error: reason };+ }++ const fallbackModel = provider.fallbackModel || fallback.defaultModel || null;+ statusOp.update('start', `Falling back to ${fallback.name || fallback.id}…`, {+ providerId: fallback.id, model: fallbackModel,+ });+ const retry = await postChatCompletion(fallback, fallbackModel, prompt, {+ temperature: 0.3,+ max_tokens: 1000,+ timeout: fallback.timeout || DEFAULT_PROVIDER_TIMEOUT_MS,+ });+ if (retry.error) {+ statusOp.error(retry.error, { providerId: fallback.id, model: fallbackModel });+ return { error: retry.error };+ }+ statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, {+ providerId: fallback.id, model: fallbackModel, ...throughput(retry.tokens),+ });+ return { text: retry.text };+}++/**+ * The reset time Codex last reported for the spent window, or `null`.+ *+ * Read from the CACHED readiness only — a failing call is the wrong moment to+ * spawn an account probe, and a stale-or-absent answer just falls back to the+ * category's own cooldown.+ */+const reportedResetsAt = (readiness) => {+ const windows = [readiness?.rateLimits?.primary, readiness?.rateLimits?.secondary];+ const spent = windows.find((w) => typeof w?.usedPercent === 'number' && w.usedPercent >= 100 && w.resetsAt);+ return spent?.resetsAt ?? null;+};+/*** Call an API-based AI provider with a simple prompt.* Returns { text } on success, { error } on failure.@@ -219,8 +381,18 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_to* so the beam's thickness can track tokens/sec.*/export async function callProviderAISimple(provider, model, prompt, options = {}) {- const { temperature = 0.3, max_tokens = 1000, op, opLabel, appId, workspacePath, background, creative } = options;- if (provider.type !== 'api') {+ const {+ temperature = 0.3, max_tokens = 1000, op, opLabel, appId, workspacePath, background, creative,+ // A JSON Schema the answer must match. Only the Codex subscription transport+ // can enforce it (the app-server constrains the final message); the HTTP path+ // ignores it, exactly as it has always ignored unknown options.+ responseSchema = null,+ // Aborting stops the active Codex turn instead of leaving it to burn+ // subscription quota for an answer nobody is waiting for. The HTTP path+ // manages its own AbortController from `timeout`.+ signal = null,+ } = options;+ if (provider.type !== 'api' && !isSubscriptionText(provider)) {return { error: 'This operation requires an API-based provider' };}// This helper is a THIRD LLM transport — it posts to /chat/completions itself@@ -267,6 +439,15 @@ export async function callProviderAISimple(provider, model, prompt, options = {}return { tokens, tokensPerSec: Math.round(tokens / secs) };};+ // The subscription transport speaks JSON-RPC over a child process, not HTTP,+ // so it takes over here — before the local-backend warm-ups, which are all+ // `/chat/completions` concerns.+ if (isSubscriptionText(provider)) {+ return callCodexSubscription(provider, model, body, {+ statusOp, doneLabel, elapsedSec, throughput, timeout: opts.timeout, responseSchema, signal,+ });+ }+if (isOllamaProvider(provider)) {statusOp.update('provider:starting', 'Starting Ollama if needed…', { providerId: provider.id });const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));diff --git a/server/services/aiProvider.test.js b/server/services/aiProvider.test.jsindex 7cf4a2acd0..afafe81b5f 100644--- a/server/services/aiProvider.test.js+++ b/server/services/aiProvider.test.js@@ -150,3 +150,182 @@ describe('callProviderAISimple completion classification', () => {expect(statusOp.error).not.toHaveBeenCalled();});});++// ---------------------------------------------------------------------------+// Codex ChatGPT subscription as a text transport (#5590)+// ---------------------------------------------------------------------------++const { getAllProviders } = await import('./providers.js');+const { resolveTextProvider, resolveAPIProvider } = await import('./aiProvider.js');+const { ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');+const codexAppServer = await import('./codexAppServer.js');++const CODEX_ENABLED = {+ id: 'codex',+ name: 'Codex CLI',+ type: 'cli',+ command: 'codex',+ textTransport: 'codex-app-server',+ textTransportEnabled: true,+ defaultModel: 'model-alpha',+};+const CODEX_ADVERTISED_ONLY = { ...CODEX_ENABLED, textTransportEnabled: undefined };+const OPENAI_API = {+ id: 'openai', name: 'OpenAI', type: 'api', endpoint: 'https://api.example.com/v1',+};++describe('resolveTextProvider', () => {+ const withProviders = (providers, activeProvider = null) =>+ getAllProviders.mockResolvedValue({ activeProvider, providers });++ it('accepts the subscription when the caller or the user named it', async () => {+ withProviders([CODEX_ENABLED, OPENAI_API], 'codex');++ await expect(resolveTextProvider('codex')).resolves.toMatchObject({ id: 'codex' });+ await expect(resolveTextProvider(null)).resolves.toMatchObject({ id: 'codex' });+ });++ it('never lands on a subscription through the blind sweep', async () => {+ // Step 3 is "whatever happens to be configured". Letting it choose the+ // subscription would move a background feature's billing onto the user's+ // ChatGPT plan without them ever choosing it.+ withProviders([CODEX_ENABLED, OPENAI_API], null);++ await expect(resolveTextProvider('does-not-exist')).resolves.toMatchObject({ id: 'openai' });+ });++ it('ignores a record that only advertises the transport', async () => {+ withProviders([CODEX_ADVERTISED_ONLY, OPENAI_API], 'codex');++ await expect(resolveTextProvider('codex')).resolves.toMatchObject({ id: 'openai' });+ });++ it('is still reachable under its original name', () => {+ expect(resolveAPIProvider).toBe(resolveTextProvider);+ });+});++describe('callProviderAISimple through the ChatGPT subscription', () => {+ const runTurn = vi.spyOn(codexAppServer, 'runCodexTextTurn');+ const bench = vi.spyOn(codexAppServer, 'benchCodexTextTransport');+ const peekBench = vi.spyOn(codexAppServer, 'getCodexTextTransportBench');+ const peekAccount = vi.spyOn(codexAppServer, 'peekCodexAccountReadiness');++ beforeEach(() => {+ statusOp.update.mockClear();+ statusOp.complete.mockClear();+ statusOp.error.mockClear();+ runTurn.mockReset();+ bench.mockReset();+ peekBench.mockReset().mockReturnValue(null);+ peekAccount.mockReset().mockReturnValue(null);+ getAllProviders.mockResolvedValue({ activeProvider: 'codex', providers: [CODEX_ENABLED, OPENAI_API] });+ });++ afterEach(() => vi.unstubAllGlobals());++ it('runs the prompt as a turn and returns its text and usage', async () => {+ runTurn.mockResolvedValue({+ text: 'a subscription answer',+ usage: { outputTokens: 12, source: 'chatgpt-subscription' },+ });++ const result = await callProviderAISimple(CODEX_ENABLED, 'model-alpha', 'Summarize this.', {});++ expect(result).toMatchObject({ text: 'a subscription answer' });+ expect(result.usage.source).toBe('chatgpt-subscription');+ expect(runTurn).toHaveBeenCalledWith(expect.objectContaining({+ prompt: 'Summarize this.', model: 'model-alpha',+ }));+ expect(statusOp.complete).toHaveBeenCalledTimes(1);+ });++ it('refuses a codex record whose transport the user has not enabled', async () => {+ const result = await callProviderAISimple(CODEX_ADVERTISED_ONLY, 'model-alpha', 'hi', {});++ expect(result.error).toMatch(/requires an API-based provider/i);+ expect(runTurn).not.toHaveBeenCalled();+ });++ it('benches only the transport on quota exhaustion, using the reset time Codex reported', async () => {+ const resetsAt = new Date(Date.now() + 90 * 60_000).toISOString();+ peekAccount.mockReturnValue({ rateLimits: { primary: { usedPercent: 100, resetsAt }, secondary: null } });+ runTurn.mockRejectedValue(Object.assign(new Error('You have hit your usage limit.'), {+ code: 'CODEX_TURN_FAILED',+ context: { category: ERROR_CATEGORIES.USAGE_LIMIT },+ }));++ await callProviderAISimple(CODEX_ENABLED, 'model-alpha', 'hi', {});++ expect(bench).toHaveBeenCalledWith(expect.objectContaining({+ category: ERROR_CATEGORIES.USAGE_LIMIT,+ // Codex's own reset window, not the category's estimate.+ waitMs: expect.any(Number),+ }));+ expect(bench.mock.calls[0][0].waitMs).toBeGreaterThan(80 * 60_000);+ });++ it('retries on the EXPLICIT fallback provider, and only that one', async () => {+ runTurn.mockRejectedValue(Object.assign(new Error('quota'), {+ context: { category: ERROR_CATEGORIES.USAGE_LIMIT },+ }));+ vi.stubGlobal('fetch', vi.fn(async () => ({+ ok: true,+ status: 200,+ text: async () => JSON.stringify({ choices: [{ message: { content: 'fallback answer' } }] }),+ })));++ const result = await callProviderAISimple(+ { ...CODEX_ENABLED, fallbackProvider: 'openai', fallbackModel: 'fallback-model' },+ 'model-alpha', 'hi', {},+ );++ expect(result).toMatchObject({ text: 'fallback answer' });+ expect(globalThis.fetch.mock.calls[0][0]).toBe('https://api.example.com/v1/chat/completions');+ expect(JSON.parse(globalThis.fetch.mock.calls[0][1].body).model).toBe('fallback-model');+ });++ it('fails closed when the provider named no fallback — never picks an API key on its own', async () => {+ runTurn.mockRejectedValue(Object.assign(new Error('quota'), {+ context: { category: ERROR_CATEGORIES.USAGE_LIMIT },+ }));+ vi.stubGlobal('fetch', vi.fn());++ const result = await callProviderAISimple(CODEX_ENABLED, 'model-alpha', 'hi', {});++ expect(result.error).toMatch(/quota/);+ expect(result.text).toBeUndefined();+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('does not bench or fall back when the CALLER cancelled', async () => {+ runTurn.mockRejectedValue(Object.assign(new Error('The Codex turn was cancelled.'), {+ code: 'CODEX_TURN_INTERRUPTED',+ }));+ vi.stubGlobal('fetch', vi.fn());++ const result = await callProviderAISimple(+ { ...CODEX_ENABLED, fallbackProvider: 'openai' }, 'model-alpha', 'hi', {},+ );++ expect(result).toMatchObject({ canceled: true });+ expect(bench).not.toHaveBeenCalled();+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('skips the turn entirely while the transport is benched and goes straight to the fallback', async () => {+ peekBench.mockReturnValue({ until: Date.now() + 60_000, category: ERROR_CATEGORIES.USAGE_LIMIT, message: 'plan spent' });+ vi.stubGlobal('fetch', vi.fn(async () => ({+ ok: true,+ status: 200,+ text: async () => JSON.stringify({ choices: [{ message: { content: 'fallback answer' } }] }),+ })));++ const result = await callProviderAISimple(+ { ...CODEX_ENABLED, fallbackProvider: 'openai' }, 'model-alpha', 'hi', {},+ );++ expect(runTurn).not.toHaveBeenCalled();+ expect(result).toMatchObject({ text: 'fallback answer' });+ });+});diff --git a/server/services/codexAppServer.js b/server/services/codexAppServer.jsindex 9c0f0844a8..b58bbc50d9 100644--- a/server/services/codexAppServer.js+++ b/server/services/codexAppServer.js@@ -31,6 +31,10 @@* cache.*/+import { mkdtemp, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { spawn } from '../lib/childProcess.js';import { ServerError } from '../lib/errorHandler.js';import { createLineReader } from '../lib/streamLines.js';@@ -41,6 +45,7 @@ import {CODEX_ERROR_CODES,CODEX_NOTIFICATIONS,CODEX_RPC,+ CODEX_ACCOUNT_STATUS,deriveCodexAccountStatus,describeCodexAccountStatus,isCodexAuthError,@@ -49,6 +54,18 @@ import {normalizeCodexRateLimits,redactCodexPayload,} from '../lib/codexAccount.js';+import {+ CODEX_TEXT_THREAD_CONFIG,+ CODEX_TEXT_TURN_SANDBOX,+ CODEX_TURN_ERROR_CODES,+ CODEX_TURN_NOTIFICATIONS,+ CODEX_TURN_RPC,+ applyCodexTurnEvent,+ createTurnAccumulator,+ finalizeCodexTurn,+ normalizeCodexModels,+ resolveCodexEffort,+} from '../lib/codexTurn.js';/** The app-server answers a local read in milliseconds; a stall is a fault. */const REQUEST_TIMEOUT_MS = 15_000;@@ -79,6 +96,23 @@ let connectingTarget = null;let readinessCache = null;/** `{ loginId, startedAt, expiresAt, timer }` for a PortOS-initiated login. */let pendingLogin = null;+/**+ * Live text turns, keyed by threadId. One app-server connection serves every+ * caller, so notifications are routed by thread rather than broadcast — a+ * concurrent turn's deltas must never leak into another caller's answer.+ */+const activeTurns = new Map();+/**+ * `{ at, models }` — the last successful `model/list`. `null` = NEVER FETCHED,+ * which is not the same as a fetched catalog that is genuinely empty; a failed+ * read leaves the last-known-good list in place rather than publishing "this+ * account has no models".+ */+let modelsCache = null;+/** `{ until, category, message }` while the TEXT transport is benched. */+let textTransportBench = null;+/** The empty scratch directory generic text turns run in. Created lazily. */+let textTurnCwd = null;const codexError = (code, message, options = {}) => new ServerError(message, {status: options.status ?? 502,@@ -107,9 +141,25 @@ const teardown = (target, error) => {target.pending.clear();target.closed = true;for (const entry of pendingEntries) entry.reject(error);+ // A turn whose `turn/start` already answered has no pending request to+ // reject, so losing the child would otherwise leave it waiting on a+ // notification that can never arrive.+ failActiveTurns(error);if (connection === target) connection = null;};+/**+ * Fail every live text turn with `error`.+ *+ * Each entry is removed before it is settled, so a caller that immediately+ * retries cannot observe the same thread id twice.+ */+function failActiveTurns(error) {+ const turns = [...activeTurns.values()];+ activeTurns.clear();+ for (const turn of turns) turn.fail(error);+}+/** Reject the target and terminate its child unless it already stopped. */const stopTarget = (target, error) => {if (!target || target.closed) return;@@ -139,6 +189,7 @@ const settleLogin = (reason) => {* merging a partial payload would invent state PortOS was not told.*/const handleNotification = (method, params) => {+ routeTurnNotification(method, params);if (method === CODEX_NOTIFICATIONS.accountUpdated || method === CODEX_NOTIFICATIONS.rateLimitsUpdated) {readinessCache = null;return;@@ -152,6 +203,35 @@ const handleNotification = (method, params) => {settleLogin(params?.success === false ? 'failed' : 'completed');};+/**+ * Hand one server notification to the turn that owns its thread.+ *+ * Runs BEFORE the account handling so a turn keeps streaming even while an+ * account notification is invalidating the readiness cache. A frame for a+ * thread PortOS is not running is dropped, not logged: the app-server also+ * streams a coding agent's own thread over this connection.+ */+const routeTurnNotification = (method, params) => {+ const threadId = typeof params?.threadId === 'string' ? params.threadId : null;+ if (!threadId) return;+ const turn = activeTurns.get(threadId);+ if (!turn) return;+ // The accumulator is pure; a malformed frame can still throw inside a+ // normalizer, and this runs on a stdout event handler where an uncaught+ // throw would take down the node process.+ let terminal = false;+ try {+ if (turn.onDelta && method === CODEX_TURN_NOTIFICATIONS.agentMessageDelta && typeof params.delta === 'string') {+ turn.onDelta(params.delta);+ }+ terminal = applyCodexTurnEvent(turn.acc, method, params);+ } catch (err) {+ console.error(`❌ Codex turn event ${method} could not be applied: ${err.message}`);+ return;+ }+ if (terminal) turn.settle();+};+/** One decoded stdout line. Malformed input is logged and dropped, never thrown. */const handleFrame = (target, line) => {const text = line.trim();@@ -365,7 +445,14 @@ const readReadiness = async () => {}}- return buildReadiness({ runtimeInstalled: true, accountFetched, account, rateLimits, error });+ const readiness = buildReadiness({ runtimeInstalled: true, accountFetched, account, rateLimits, error });+ // A fresh read that says the subscription is ready is the evidence a bench was+ // waiting for — the window reset, or the user signed back in — so the text+ // transport comes back without waiting out the rest of a cooldown. Any other+ // verdict leaves the bench alone: it must expire on its own, not on a probe+ // that merely failed to contradict it.+ if (readiness.status === CODEX_ACCOUNT_STATUS.ready) clearCodexTextTransportBench();+ return readiness;};/**@@ -460,6 +547,241 @@ export async function codexLogout() {return getCodexAccountReadiness({ fresh: true });}+/* ------------------------------------------------------------------------- *+ * Text inference (#5590)+ *+ * Everything below serves the SUBSCRIPTION TEXT TRANSPORT — the second, opt-in+ * capability of the `codex` provider record. It is deliberately separate from+ * the CLI/TUI coding harness: a Brain or JIRA summary runs here, in an empty+ * throwaway directory under a read-only no-network sandbox with no MCP servers+ * and no web search, while a CoS coding task keeps going through+ * `executeCliRun` with the workspace it was given.+ * ------------------------------------------------------------------------- */++/** A turn is a network round trip against a frontier model — not a local read. */+const TURN_TIMEOUT_MS = 300_000;+/** The catalog changes when a plan does. Long enough to not re-list per call. */+const MODELS_TTL_MS = 10 * 60_000;++/**+ * The empty directory every generic text turn runs in.+ *+ * Outside the PortOS checkout and outside `data/`, so even a sandbox escape+ * would land somewhere with nothing in it. Created once per process and reused;+ * `mkdtemp` guarantees it is fresh and unshared.+ */+const ensureTextTurnCwd = async () => {+ if (textTurnCwd) return textTurnCwd;+ textTurnCwd = await mkdtemp(join(tmpdir(), 'portos-codex-text-'));+ return textTurnCwd;+};++/**+ * Is the text transport benched right now?+ *+ * Returns `null` when it is usable, or `{ until, category, message }` while a+ * quota/auth failure is still in its cooldown. Benching is SCOPED TO THE+ * TRANSPORT on purpose: an exhausted subscription window must not take the+ * `codex` coding harness — which the user may still want for a task that is+ * already mid-flight — off the board as a side effect.+ */+export function getCodexTextTransportBench() {+ if (!textTransportBench) return null;+ if (Date.now() >= textTransportBench.until) {+ textTransportBench = null;+ return null;+ }+ return { ...textTransportBench };+}++/**+ * Bench the text transport for `waitMs`.+ *+ * The DURATION is the caller's, resolved from the shared cooldown policy in+ * `lib/providerCooldown.js`, so a quota exhaustion waits the same window here+ * as it does on every other path. A longer bench never shortens an existing+ * one.+ */+export function benchCodexTextTransport({ waitMs, category, message } = {}) {+ const until = Date.now() + Math.max(Number(waitMs) || 0, 0);+ if (textTransportBench && textTransportBench.until >= until) return getCodexTextTransportBench();+ textTransportBench = { until, category: category || null, message: message || null };+ console.log(`⚠️ Codex subscription text transport benched for ${Math.round((until - Date.now()) / 60000)}m: ${category || 'unknown'}`);+ return getCodexTextTransportBench();+}++/** Clear the bench — used when the account is re-read as ready, and by tests. */+export function clearCodexTextTransportBench() {+ textTransportBench = null;+}++/**+ * The models this ChatGPT account may run, from the app-server catalog.+ *+ * `null` means NEVER FETCHED and `[]` means fetched-and-empty; a failed read+ * returns the last-known-good list rather than either. That distinction is what+ * lets the Providers page tell "we have not asked yet" from "this plan really+ * has no models", and stops one transient failure from emptying a good picker.+ *+ * LAZY: only an explicit request reaches this. Nothing on the boot path may.+ */+export async function listCodexModels({ fresh = false } = {}) {+ if (!fresh && modelsCache && Date.now() - modelsCache.at < MODELS_TTL_MS) {+ return { models: modelsCache.models, fetchedAt: modelsCache.at, error: null };+ }+ try {+ const { models } = normalizeCodexModels(await call(CODEX_TURN_RPC.modelList, {}));+ modelsCache = { at: Date.now(), models };+ return { models, fetchedAt: modelsCache.at, error: null };+ } catch (err) {+ console.error(`❌ Codex model/list failed: ${err.message}`);+ return {+ models: modelsCache ? modelsCache.models : null,+ fetchedAt: modelsCache ? modelsCache.at : null,+ error: { code: err.code || CODEX_ERROR_CODES.protocol, message: err.message },+ };+ }+}++/** The cached catalog without spawning anything. `null` = never fetched. */+export function peekCodexModels() {+ return modelsCache ? { models: modelsCache.models, fetchedAt: modelsCache.at } : null;+}++/** The catalog entry for `modelId`, or `null` when the catalog is unknown. */+const cachedModelEntry = (modelId) => {+ if (!modelId || !modelsCache?.models) return null;+ return modelsCache.models.find((entry) => entry.id === modelId) ?? null;+};++/**+ * Run ONE bounded text turn against the ChatGPT subscription.+ *+ * Resolves `{ text, usage, model, effort, effortClamped }`, or rejects with a+ * typed `ServerError`. It never resolves with partial text: an interrupted or+ * failed turn rejects, so a caller parsing JSON can't be handed half an object.+ *+ * @param {object} options+ * @param {string} options.prompt — the only thing the model is given+ * @param {string|null} [options.model] — a catalog id; null uses Codex's default+ * @param {string|null} [options.effort] — clamped against the model's catalog entry+ * @param {number} [options.timeoutMs]+ * @param {AbortSignal|null} [options.signal] — aborting interrupts the turn+ * @param {(delta: string) => void} [options.onDelta] — live progress+ * @param {object|null} [options.responseSchema] — JSON Schema constraining the+ * final assistant message, when the caller needs structured output+ */+export async function runCodexTextTurn({+ prompt,+ model = null,+ effort = null,+ timeoutMs = TURN_TIMEOUT_MS,+ signal = null,+ onDelta = null,+ responseSchema = null,+} = {}) {+ if (typeof prompt !== 'string' || prompt.trim() === '') {+ throw codexError(CODEX_ERROR_CODES.protocol, 'A Codex text turn needs a prompt.', { status: 400 });+ }+ // An already-aborted signal fires no 'abort' event when a listener is added+ // later, so the caller's cancellation has to be honoured here or the turn runs+ // (and bills) for an answer nobody is waiting for.+ if (signal?.aborted) {+ throw codexError(CODEX_TURN_ERROR_CODES.turnInterrupted, 'The Codex turn was cancelled.', { status: 499 });+ }+ const benched = getCodexTextTransportBench();+ if (benched) {+ throw codexError(+ CODEX_TURN_ERROR_CODES.transportBenched,+ benched.message || 'The ChatGPT subscription is temporarily unavailable.',+ { status: 503, context: { category: benched.category, until: benched.until } },+ );+ }++ const cwd = await ensureTextTurnCwd();+ const { effort: resolvedEffort, clamped, reason } = resolveCodexEffort(effort, cachedModelEntry(model));+ if (clamped) console.log(`⚠️ Codex effort clamped: ${reason}`);++ const started = await call(CODEX_TURN_RPC.threadStart, {+ ...CODEX_TEXT_THREAD_CONFIG,+ cwd,+ ...(model ? { model } : {}),+ });+ const threadId = typeof started?.thread?.id === 'string' ? started.thread.id : null;+ if (!threadId) {+ throw codexError(CODEX_ERROR_CODES.protocol, 'Codex started a thread with no id.');+ }++ const acc = createTurnAccumulator();+ let settle = null;+ let fail = null;+ const finished = new Promise((resolve, reject) => { settle = resolve; fail = reject; });+ // `finished` is not awaited until `turn/start` answers, and it can be rejected+ // before then (a lost child, an abort, the deadline). Without this parked+ // handler that rejection is an UNHANDLED one — which is a process-level crash+ // under Node's default policy, not a test-only nuisance. The real error still+ // surfaces from the `await finished` below.+ finished.catch(() => {});+ // Registered BEFORE `turn/start` is sent: the first delta can arrive before+ // that request's own response does, and an unregistered thread drops frames.+ activeTurns.set(threadId, {+ acc,+ settle: () => settle(),+ fail: (err) => fail(err),+ onDelta: typeof onDelta === 'function' ? onDelta : null,+ });++ const timer = setTimeout(() => {+ fail(codexError(CODEX_ERROR_CODES.timeout, `The Codex turn did not finish within ${Math.round(timeoutMs / 1000)}s.`));+ }, timeoutMs);+ timer.unref?.();++ const onAbort = () => fail(codexError(CODEX_TURN_ERROR_CODES.turnInterrupted, 'The Codex turn was cancelled.', { status: 499 }));+ signal?.addEventListener('abort', onAbort, { once: true });++ try {+ const response = await call(CODEX_TURN_RPC.turnStart, {+ threadId,+ input: [{ type: 'text', text: prompt }],+ sandboxPolicy: { ...CODEX_TEXT_TURN_SANDBOX },+ approvalPolicy: CODEX_TEXT_THREAD_CONFIG.approvalPolicy,+ ...(model ? { model } : {}),+ ...(resolvedEffort ? { effort: resolvedEffort } : {}),+ ...(responseSchema ? { outputSchema: responseSchema } : {}),+ }, timeoutMs);+ const turnId = typeof response?.turn?.id === 'string' ? response.turn.id : null;+ if (turnId) acc.turnId = turnId;+ // A turn that completed before its own response was read leaves the+ // accumulator terminal with nobody to settle it.+ if (acc.status !== 'inProgress') settle();++ await finished;+ const result = finalizeCodexTurn(acc);+ if (result.error) {+ throw codexError(+ result.canceled ? CODEX_TURN_ERROR_CODES.turnInterrupted : CODEX_TURN_ERROR_CODES.turnFailed,+ result.error,+ { context: { category: result.category } },+ );+ }+ // The model Codex ACTUALLY ran, which is the thread's answer rather than the+ // request's — a caller that passed `null` still gets told what served it.+ const ranModel = typeof started.model === 'string' && started.model ? started.model : (model ?? null);+ return { ...result, model: ranModel, effort: resolvedEffort, effortClamped: clamped, clampReason: reason };+ } finally {+ clearTimeout(timer);+ signal?.removeEventListener('abort', onAbort);+ activeTurns.delete(threadId);+ // Best-effort: tell the app-server to stop working a turn PortOS has+ // abandoned, so a cancelled request does not keep burning subscription+ // quota. A thread that already completed answers with an error we ignore.+ if (acc.status === 'inProgress' && acc.turnId) {+ call(CODEX_TURN_RPC.turnInterrupt, { threadId, turnId: acc.turnId })+ .catch((err) => console.error(`❌ Codex turn interrupt failed: ${err.message}`));+ }+ }+}+/*** Terminate the app-server child, if one is running.*@@ -469,6 +791,13 @@ export async function codexLogout() {export async function stopCodexAppServer() {settleLogin(null);readinessCache = null;+ modelsCache = null;+ const scratch = textTurnCwd;+ textTurnCwd = null;+ if (scratch) {+ await rm(scratch, { recursive: true, force: true })+ .catch((err) => console.error(`❌ Failed to remove the Codex text scratch directory: ${err.message}`));+ }const target = connection || connectingTarget;connection = null;if (!target || target.closed) return;@@ -484,4 +813,8 @@ export function __resetCodexAppServer() {connection = null;connecting = null;connectingTarget = null;+ activeTurns.clear();+ modelsCache = null;+ textTransportBench = null;+ textTurnCwd = null;}diff --git a/server/services/codexAppServer.turn.test.js b/server/services/codexAppServer.turn.test.jsnew file mode 100644index 0000000000..4b1f1bd57f--- /dev/null+++ b/server/services/codexAppServer.turn.test.js@@ -0,0 +1,272 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';++// The inference half of the app-server client (#5590). Like its account-side+// sibling, a fake child speaks the protocol back — so this suite asserts the+// TRANSPORT contract (safety envelope, event projection, cancellation, quota+// and auth handling, catalog sentinels, process loss) without a real Codex, a+// real ChatGPT account, or a single provider call.+vi.mock('../lib/childProcess.js', async (importOriginal) => ({+ ...(await importOriginal()),+ spawn: vi.fn(),+}));+vi.mock('../lib/processEnv.js', async (importOriginal) => ({+ ...(await importOriginal()),+ findCommandOnPath: vi.fn(() => '/usr/local/bin/codex'),+}));++const { spawn } = await import('../lib/childProcess.js');+const { findCommandOnPath } = await import('../lib/processEnv.js');+const { ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');+const { CODEX_ERROR_CODES } = await import('../lib/codexAccount.js');+const { CODEX_TURN_ERROR_CODES } = await import('../lib/codexTurn.js');+const {+ __resetCodexAppServer,+ benchCodexTextTransport,+ getCodexTextTransportBench,+ listCodexModels,+ peekCodexModels,+ runCodexTextTurn,+ stopCodexAppServer,+} = await import('./codexAppServer.js');++const makeChild = () => {+ const child = new EventEmitter();+ child.written = [];+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.stdin = Object.assign(new EventEmitter(), {+ destroyed: false,+ write: (line, cb) => { child.written.push(JSON.parse(line)); cb?.(); return true; },+ });+ child.kill = vi.fn(() => { child.emit('exit', null, 'SIGTERM'); });+ child.emitFrame = (frame) => child.stdout.emit('data', `${JSON.stringify(frame)}\n`);+ child.notify = (method, params) => child.emitFrame({ jsonrpc: '2.0', method, params });+ child.cursor = 0;+ child.take = (method) => {+ const index = child.written.findIndex((f, i) => i >= child.cursor && f.method === method);+ if (index === -1) return null;+ child.cursor = index + 1;+ return child.written[index];+ };+ child.lastRequest = (method) => [...child.written].reverse().find((f) => f.method === method);+ child.reply = (frame, result) => child.emitFrame({ jsonrpc: '2.0', id: frame.id, result });+ child.replyError = (frame, error) => child.emitFrame({ jsonrpc: '2.0', id: frame.id, error });+ return child;+};++/** Wait for PortOS to write `method`, then run `answer` against that frame. */+const awaitRequest = async (child, method, answer) => {+ let frame = null;+ await vi.waitFor(() => { frame = child.take(method); expect(frame).toBeTruthy(); });+ if (typeof answer === 'function') answer(frame);+ else child.reply(frame, answer);+ return frame;+};++/** Drive a text turn to a `turn/completed` with `status`, streaming `deltas`. */+const driveTurn = async (child, { deltas = [], status = 'completed', item = null, error = null, usage = null } = {}) => {+ await awaitRequest(child, 'thread/start', { thread: { id: 'thread-1' }, model: 'model-alpha' });+ await awaitRequest(child, 'turn/start', { turn: { id: 'turn-1', items: [], status: 'inProgress' } });+ for (const delta of deltas) {+ child.notify('item/agentMessage/delta', { threadId: 'thread-1', turnId: 'turn-1', itemId: 'i1', delta });+ }+ if (item) child.notify('item/completed', { threadId: 'thread-1', turnId: 'turn-1', completedAtMs: 1, item });+ if (usage) child.notify('thread/tokenUsage/updated', { threadId: 'thread-1', turnId: 'turn-1', tokenUsage: usage });+ child.notify('turn/completed', { threadId: 'thread-1', turn: { id: 'turn-1', items: [], status, error } });+};++let child = null;++beforeEach(() => {+ vi.clearAllMocks();+ __resetCodexAppServer();+ child = makeChild();+ spawn.mockReturnValue(child);+ findCommandOnPath.mockReturnValue('/usr/local/bin/codex');+});++afterEach(async () => {+ await stopCodexAppServer().catch(() => {});+ __resetCodexAppServer();+});++const handshake = async () => awaitRequest(child, 'initialize', {});++describe('running a text turn', () => {+ it('confines the turn to an empty directory with no tools, no network, and no writes', async () => {+ // This is the boundary that lets a Brain/JIRA summary use the same record+ // as the coding harness: nothing about the PortOS checkout is reachable.+ const promise = runCodexTextTurn({ prompt: 'Summarize this.' });+ await handshake();+ await driveTurn(child, { deltas: ['ok'] });+ await promise;++ const start = child.lastRequest('thread/start').params;+ expect(start.sandbox).toBe('read-only');+ expect(start.approvalPolicy).toBe('never');+ expect(start.ephemeral).toBe(true);+ expect(start.config).toEqual({ mcp_servers: {}, tools: { web_search: false }, web_search: false });+ expect(start.cwd).toEqual(expect.stringContaining('portos-codex-text-'));+ expect(start.cwd.includes('PortOS')).toBe(false);++ const turn = child.lastRequest('turn/start').params;+ expect(turn.sandboxPolicy).toEqual({ type: 'readOnly', networkAccess: false });+ expect(turn.approvalPolicy).toBe('never');+ expect(turn.input).toEqual([{ type: 'text', text: 'Summarize this.' }]);+ });++ it('returns the assembled text plus subscription-attributed usage', async () => {+ const promise = runCodexTextTurn({ prompt: 'hi', model: 'model-alpha' });+ await handshake();+ await driveTurn(child, {+ deltas: ['Hello, ', 'world'],+ usage: { last: { inputTokens: 9, outputTokens: 3, cachedInputTokens: 0, reasoningOutputTokens: 0, totalTokens: 12 } },+ });++ await expect(promise).resolves.toMatchObject({+ text: 'Hello, world',+ usage: { outputTokens: 3, totalTokens: 12, source: 'chatgpt-subscription' },+ model: 'model-alpha',+ });+ });++ it('passes a response schema through so structured output is constrained', async () => {+ const schema = { type: 'object', properties: { verdict: { type: 'string' } } };+ const promise = runCodexTextTurn({ prompt: 'classify', responseSchema: schema });+ await handshake();+ await driveTurn(child, { item: { type: 'agentMessage', id: 'i1', text: '{"verdict":"ok"}' } });++ await expect(promise).resolves.toMatchObject({ text: '{"verdict":"ok"}' });+ expect(child.lastRequest('turn/start').params.outputSchema).toEqual(schema);+ });++ it('rejects rather than returning the partial text of an interrupted turn', async () => {+ const promise = runCodexTextTurn({ prompt: 'long one' });+ await handshake();+ await driveTurn(child, { deltas: ['{"answer":"hal'], status: 'interrupted' });++ await expect(promise).rejects.toMatchObject({ code: CODEX_TURN_ERROR_CODES.turnInterrupted });+ });++ it('interrupts the live turn when the caller aborts, instead of leaving it to burn quota', async () => {+ const controller = new AbortController();+ const promise = runCodexTextTurn({ prompt: 'long one', signal: controller.signal });+ await handshake();+ await awaitRequest(child, 'thread/start', { thread: { id: 'thread-1' } });+ await awaitRequest(child, 'turn/start', { turn: { id: 'turn-1', items: [], status: 'inProgress' } });++ controller.abort();++ await expect(promise).rejects.toMatchObject({ code: CODEX_TURN_ERROR_CODES.turnInterrupted });+ await vi.waitFor(() => expect(child.lastRequest('turn/interrupt')).toBeTruthy());+ expect(child.lastRequest('turn/interrupt').params).toEqual({ threadId: 'thread-1', turnId: 'turn-1' });+ });++ it('carries a quota failure out as a usage-limit category', async () => {+ const promise = runCodexTextTurn({ prompt: 'hi' });+ await handshake();+ await driveTurn(child, {+ status: 'failed',+ error: { message: 'You have hit your usage limit.', codexErrorInfo: 'usageLimitExceeded' },+ });++ await expect(promise).rejects.toMatchObject({+ code: CODEX_TURN_ERROR_CODES.turnFailed,+ context: { category: ERROR_CATEGORIES.USAGE_LIMIT },+ });+ });++ it('surfaces an expired sign-in as an auth failure from the RPC itself', async () => {+ const promise = runCodexTextTurn({ prompt: 'hi' });+ await handshake();+ await awaitRequest(child, 'thread/start', (frame) =>+ child.replyError(frame, { code: -32000, message: 'HTTP 401 unauthorized — please re-authenticate' }));++ await expect(promise).rejects.toMatchObject({ code: CODEX_ERROR_CODES.authRevoked });+ });++ it('ignores a malformed event rather than crashing the stdout handler', async () => {+ const promise = runCodexTextTurn({ prompt: 'hi' });+ await handshake();+ await awaitRequest(child, 'thread/start', { thread: { id: 'thread-1' } });+ await awaitRequest(child, 'turn/start', { turn: { id: 'turn-1', items: [], status: 'inProgress' } });++ child.stdout.emit('data', 'not json at all\n');+ child.notify('item/agentMessage/delta', { threadId: 'thread-1', turnId: 'turn-1' });+ child.notify('thread/tokenUsage/updated', { threadId: 'thread-1', turnId: 'turn-1', tokenUsage: 'nope' });+ child.notify('item/agentMessage/delta', { threadId: 'thread-1', turnId: 'turn-1', delta: 'still fine' });+ child.notify('turn/completed', { threadId: 'thread-1', turn: { id: 'turn-1', items: [], status: 'completed' } });++ await expect(promise).resolves.toMatchObject({ text: 'still fine', usage: null });+ });++ it('fails a turn whose app-server died mid-stream instead of hanging forever', async () => {+ // `turn/start` already answered, so there is no pending request to reject —+ // without the teardown hook this call would wait on a notification that can+ // never arrive.+ const promise = runCodexTextTurn({ prompt: 'hi' });+ await handshake();+ await awaitRequest(child, 'thread/start', { thread: { id: 'thread-1' } });+ await awaitRequest(child, 'turn/start', { turn: { id: 'turn-1', items: [], status: 'inProgress' } });++ child.emit('exit', 1, null);++ await expect(promise).rejects.toMatchObject({ code: CODEX_ERROR_CODES.exited });+ });++ it('refuses to run while the transport is benched, without touching the wire', async () => {+ benchCodexTextTransport({ waitMs: 60_000, category: ERROR_CATEGORIES.USAGE_LIMIT, message: 'plan spent' });++ await expect(runCodexTextTurn({ prompt: 'hi' })).rejects.toMatchObject({+ code: CODEX_TURN_ERROR_CODES.transportBenched,+ });+ expect(spawn).not.toHaveBeenCalled();+ });+});++describe('the transport bench', () => {+ it('expires on its own and never shortens an existing bench', () => {+ benchCodexTextTransport({ waitMs: 60_000, category: ERROR_CATEGORIES.USAGE_LIMIT, message: 'long' });+ benchCodexTextTransport({ waitMs: 1_000, category: ERROR_CATEGORIES.RATE_LIMIT, message: 'short' });+ expect(getCodexTextTransportBench().message).toBe('long');++ vi.useFakeTimers();+ vi.setSystemTime(Date.now() + 61_000);+ expect(getCodexTextTransportBench()).toBeNull();+ vi.useRealTimers();+ });+});++describe('model discovery', () => {+ it('caches a genuinely empty catalog instead of re-listing on every call', async () => {+ const promise = listCodexModels();+ await handshake();+ await awaitRequest(child, 'model/list', { data: [] });++ await expect(promise).resolves.toMatchObject({ models: [], error: null });+ // [] is a real answer: a second read must be served from cache.+ await expect(listCodexModels()).resolves.toMatchObject({ models: [] });+ expect(child.written.filter((f) => f.method === 'model/list')).toHaveLength(1);+ });++ it('keeps the last-known-good list when a refresh fails', async () => {+ const first = listCodexModels();+ await handshake();+ await awaitRequest(child, 'model/list', {+ data: [{ id: 'model-alpha', displayName: 'Alpha', supportedReasoningEfforts: [] }],+ });+ await first;++ const refresh = listCodexModels({ fresh: true });+ await awaitRequest(child, 'model/list', (frame) => child.replyError(frame, { message: 'upstream down' }));++ const result = await refresh;+ expect(result.models).toEqual([expect.objectContaining({ id: 'model-alpha' })]);+ expect(result.error.message).toMatch(/upstream down/);+ });++ it('peeks null before anything has ever asked', () => {+ expect(peekCodexModels()).toBeNull();+ });+});