Skip to content

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

fix: repair two regressions the first review round introduced, plus six more

[._.]/ Adam Eivyc94f5fe2d93c
diff --git a/scripts/migrations/331-codex-text-transport.js b/scripts/migrations/331-codex-text-transport.js
index a4b33dc225..5b8ef1360d 100644
--- a/scripts/migrations/331-codex-text-transport.js
+++ b/scripts/migrations/331-codex-text-transport.js
@@ -22,8 +22,6 @@
* require a new migration.
*/
-import { basename } from 'path';
-
import { readProvidersDoc, writeJsonAtomic } from './_lib.js';
const TRANSPORT = 'codex-app-server';
@@ -54,7 +52,12 @@ const isCodexHarness = (provider) => {
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;
+ // Byte-for-byte the rule `lib/providerModels.commandBasename` applies (inlined
+ // because a migration is a frozen snapshot and must not drift when that helper
+ // changes). Case-INSENSITIVE, and only `.exe` is stripped: a record this
+ // stamps but the runtime gate then rejects would advertise a capability that
+ // can never be switched on, and one it skips never gets the flag at all.
+ return command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '') === CODEX_COMMAND;
};
export default {
diff --git a/scripts/migrations/331-codex-text-transport.test.js b/scripts/migrations/331-codex-text-transport.test.js
index bea4c0211d..2c1c3409df 100644
--- a/scripts/migrations/331-codex-text-transport.test.js
+++ b/scripts/migrations/331-codex-text-transport.test.js
@@ -64,6 +64,27 @@ describe('migration 331 — codex text transport', () => {
});
});
+ it('matches the runtime predicate exactly on command spelling', async () => {
+ // A record this stamps but `providerDeclaresCodexTextTransport` then rejects
+ // advertises a capability the toggle can never switch on; one it skips never
+ // gets the flag at all. Both halves must apply the same rule: lowercase the
+ // basename, strip only `.exe`.
+ writeProviders({
+ codex: { ...CODEX, command: 'Codex' },
+ 'codex-exe': { id: 'codex-exe', type: 'cli', command: 'C:\\bin\\CODEX.EXE', enabled: true },
+ 'codex-cmd': { id: 'codex-cmd', type: 'cli', command: 'codex.cmd', enabled: true },
+ });
+
+ await migration.up({ rootDir });
+
+ const providers = readProviders();
+ expect(providers.codex.textTransport).toBe('codex-app-server');
+ expect(providers['codex-exe'].textTransport).toBe('codex-app-server');
+ // `.cmd` is not directly spawnable and the runtime gate rejects it, so the
+ // migration must not advertise it either.
+ expect(providers['codex-cmd'].textTransport).toBeUndefined();
+ });
+
it('leaves a record the user repointed at a different binary untouched', async () => {
writeProviders({ codex: { ...CODEX, command: 'my-wrapper' } });
diff --git a/server/lib/codexAccount.js b/server/lib/codexAccount.js
index ec67cd76cd..89abdfdf49 100644
--- a/server/lib/codexAccount.js
+++ b/server/lib/codexAccount.js
@@ -151,12 +151,22 @@ export const redactCodexPayload = (value, depth = 0) => {
export const redactCodexMessage = (value) => {
if (typeof value !== 'string' || value.trim() === '') return null;
const masked = value
- // key=value / key: value, where the key is credential-shaped
- .replace(/\b([A-Za-z0-9_-]*(?:token|secret|password|credential|api[_-]?key|access[_-]?key|cookie)[A-Za-z0-9_-]*)\s*[=:]\s*\S+/gi, '$1=' + REDACTED)
- // an inline bearer/basic credential
- .replace(/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi, '$1 ' + REDACTED)
- // a bare OpenAI-style key, which carries no label at all
- .replace(/\bsk-[A-Za-z0-9._-]{8,}/g, REDACTED);
+ // `key=<value>` / `key: <value>` where the key is credential-shaped AND the
+ // value LOOKS like a credential — long, and not plain prose. Requiring both
+ // is what keeps "The secret: sauce" intact while masking
+ // "refresh_token: eyJhbGciOi…". A short value cannot carry a usable secret.
+ .replace(
+ /\b([A-Za-z0-9_-]*(?:token|secret|password|passwd|credential|api[_-]?key|access[_-]?key|cookie|signature)[A-Za-z0-9_-]*)(\s*[=:]\s*)("?)([A-Za-z0-9._~+/=-]{12,})\3/gi,
+ (match, key, sep, quote, secret) => (/^[A-Za-z]+$/.test(secret) ? match : `${key}${sep}${quote}${REDACTED}${quote}`),
+ )
+ // An inline authorization credential under ANY scheme — Bearer, Basic,
+ // Token, and whatever a future provider invents. Anchored on the header
+ // name, so an ordinary sentence containing "token" is untouched.
+ .replace(/\b(authorization|proxy-authorization)(\s*[=:]\s*)(\S+\s+)?\S+/gi, `$1$2${REDACTED}`)
+ .replace(/\b(bearer|basic|token)\s+[A-Za-z0-9._~+/=-]{12,}/gi, `$1 ${REDACTED}`)
+ // A bare vendor key, which carries no label at all to key on.
+ .replace(/\b(sk|pk|rk)-[A-Za-z0-9._-]{8,}/g, REDACTED)
+ .replace(/\beyJ[A-Za-z0-9._-]{16,}/g, REDACTED);
return masked.length > 400 ? `${masked.slice(0, 400)}…` : masked;
};
diff --git a/server/lib/codexAccount.test.js b/server/lib/codexAccount.test.js
index 87a114c703..405db6085d 100644
--- a/server/lib/codexAccount.test.js
+++ b/server/lib/codexAccount.test.js
@@ -9,6 +9,7 @@ import {
normalizeCodexAccount,
normalizeCodexLoginStart,
normalizeCodexRateLimits,
+ redactCodexMessage,
redactCodexPayload,
} from './codexAccount.js';
@@ -178,3 +179,41 @@ describe('isCodexAuthError', () => {
expect(isCodexAuthError(null)).toBe(false);
});
});
+
+describe('redactCodexMessage', () => {
+ it('masks a credential-shaped value under any label or scheme', () => {
+ // These messages are logged AND returned to the browser by the `/codex/*`
+ // routes, and the payload redactor keys on FIELD NAMES a free-text message
+ // does not have.
+ for (const [message, secret] of [
+ ['access_token=sk-live-ABCDEFGH1234 expired', 'sk-live-ABCDEFGH1234'],
+ ['refresh_token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 rejected', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'],
+ ['Authorization: Bearer abcdefghijklmnopqrst', 'abcdefghijklmnopqrst'],
+ // Not just Bearer/Basic — a scheme PortOS has never seen must not slip past.
+ ['Authorization: Token eyJhbGciOiJIUzI1NiJ9abcd', 'eyJhbGciOiJIUzI1NiJ9abcd'],
+ ]) {
+ const masked = redactCodexMessage(message);
+ expect(masked).not.toContain(secret);
+ expect(masked).toContain('[redacted]');
+ }
+ });
+
+ it('leaves an ordinary message alone', () => {
+ // A redactor that mangles prose makes every error harder to act on, so the
+ // value has to look like a credential — not merely follow a scary word.
+ for (const message of [
+ 'The secret: sauce',
+ 'The secret is safe',
+ 'GET /v1/secrets:read failed',
+ 'Codex app-server did not answer account/read within 15s.',
+ ]) {
+ expect(redactCodexMessage(message)).toBe(message);
+ }
+ });
+
+ it('reports nothing to say as null, not an empty string', () => {
+ expect(redactCodexMessage('')).toBeNull();
+ expect(redactCodexMessage(null)).toBeNull();
+ expect(redactCodexMessage(42)).toBeNull();
+ });
+});
diff --git a/server/lib/codexTurn.js b/server/lib/codexTurn.js
index e1f481a020..18a2dae58f 100644
--- a/server/lib/codexTurn.js
+++ b/server/lib/codexTurn.js
@@ -30,7 +30,7 @@
*/
import { ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';
-import { CODEX_ERROR_CODES, isCodexSubscriptionProvider } from './codexAccount.js';
+import { CODEX_ERROR_CODES, isCodexSubscriptionProvider, redactCodexMessage } from './codexAccount.js';
/**
* The value a provider record carries to advertise that it can serve generic
@@ -192,7 +192,11 @@ export const normalizeCodexModels = (result) => {
*/
export const normalizeCodexTokenUsage = (raw) => {
if (!raw || typeof raw !== 'object') return null;
- const breakdown = raw.last ?? raw.total ?? raw;
+ // `total` first: PortOS's threads are ephemeral and carry exactly one turn, so
+ // the thread total IS this turn's usage, while `last` counts only the final
+ // model request. A turn that took a reasoning step then answered would
+ // otherwise under-report by an order of magnitude.
+ const breakdown = raw.total ?? raw.last ?? raw;
if (!breakdown || typeof breakdown !== 'object') return null;
const inputTokens = finiteInt(breakdown.inputTokens);
const outputTokens = finiteInt(breakdown.outputTokens);
@@ -258,7 +262,10 @@ const errorInfoTag = (error) => {
*/
export const classifyCodexTurnError = (error) => {
const tag = errorInfoTag(error);
- const message = trimmed(error?.message) || 'The Codex turn failed';
+ // Scrubbed at the boundary: this message becomes a thrown error's text, which
+ // `aiProvider` logs, reports through `ai:status`, and hands back to the caller
+ // as `{ error }` — and an upstream failure can quote the credential.
+ const message = redactCodexMessage(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 };
@@ -382,7 +389,10 @@ export const applyCodexTurnEvent = (acc, method, params) => {
return true;
case CODEX_TURN_NOTIFICATIONS.turnCompleted: {
const turn = params.turn;
- if (acc.turnId && turn?.id && turn.id !== acc.turnId) return false;
+ // Once the id is latched, a completion must name it. An anonymous
+ // `turn/completed` would otherwise finish somebody else's turn — and hand
+ // this caller the partial text streamed so far as a success.
+ if (acc.turnId && turn?.id !== acc.turnId) return false;
// A frame with no status is MALFORMED, and defaulting it to 'completed'
// would hand the caller whatever text had streamed so far as a finished
// answer. `finalizeCodexTurn` errors on anything that is not 'completed',
diff --git a/server/lib/codexTurn.test.js b/server/lib/codexTurn.test.js
index 6c62461cd3..fe47e22116 100644
--- a/server/lib/codexTurn.test.js
+++ b/server/lib/codexTurn.test.js
@@ -266,13 +266,41 @@ describe('turn projection', () => {
expect(finalizeCodexTurn(acc).text).toBe('message one. message two.');
});
+ it('refuses an anonymous completion once the turn id is latched', () => {
+ // An unnamed `turn/completed` would otherwise finish somebody else's turn and
+ // hand this caller the partial text streamed so far as a success.
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
+ delta(acc, '{"answer":"hal');
+ expect(complete(acc, { status: 'completed' })).toBe(false);
+
+ complete(acc, { id: 'turn-1', status: 'failed', error: { message: 'nope' } });
+ expect(finalizeCodexTurn(acc).text).toBeUndefined();
+ });
+
+ it('scrubs a credential quoted by a failed turn before it becomes an error', () => {
+ // The message becomes a thrown error's text, which aiProvider logs, reports
+ // over `ai:status`, and returns to the caller as `{ error }`.
+ const acc = createTurnAccumulator({ threadId: 't', turnId: 'turn-1' });
+ complete(acc, {
+ id: 'turn-1',
+ status: 'failed',
+ error: { message: 'upstream rejected access_token=sk-live-ABCDEFGH1234' },
+ });
+
+ expect(finalizeCodexTurn(acc).error).not.toContain('sk-live-ABCDEFGH1234');
+ });
+
it('records token usage under the subscription, with no invented dollar cost', () => {
const acc = createTurnAccumulator({ threadId: 't', turnId: '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 },
+ // `last` counts only the FINAL model request; a turn that took a
+ // reasoning step first would under-report by an order of magnitude.
+ // PortOS's threads are ephemeral and carry one turn, so `total` is it.
+ last: { inputTokens: 20, outputTokens: 4, cachedInputTokens: 0, reasoningOutputTokens: 0, totalTokens: 24 },
+ total: { inputTokens: 120, outputTokens: 40, cachedInputTokens: 10, reasoningOutputTokens: 5, totalTokens: 160 },
modelContextWindow: 400000,
},
});
diff --git a/server/services/aiProvider.js b/server/services/aiProvider.js
index cc7d9a610d..d085e33894 100644
--- a/server/services/aiProvider.js
+++ b/server/services/aiProvider.js
@@ -322,7 +322,7 @@ async function callCodexSubscription(provider, model, prompt, {
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 };
+ return { result: { text: turn.text, usage: turn.usage } };
}
reason = turn.error.message;
@@ -332,7 +332,7 @@ async function callCodexSubscription(provider, model, prompt, {
// 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 };
+ return { result: { error: reason, canceled: true } };
}
const bench = resolveProviderBench({ category, message: reason });
if (bench) {
@@ -347,26 +347,20 @@ async function callCodexSubscription(provider, model, prompt, {
const fallback = await resolveExplicitFallback(provider);
if (!fallback) {
statusOp.error(reason, { providerId: provider.id });
- return { error: reason };
+ return { result: { 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 };
+ // Handed BACK rather than posted here: re-entering `callProviderAISimple` is
+ // what gives the fallback the local-backend warm-ups (Ollama / MTPLX), the LM
+ // Studio no-models-loaded auto-load-and-retry, and the caller's own
+ // `temperature` / `max_tokens` — all of which a direct `postChatCompletion`
+ // silently drops, making the fallback least reliable exactly when it is
+ // needed. The recursion terminates: an explicit fallback must be API-type.
+ return { fallback, fallbackModel };
}
/**
@@ -469,9 +463,16 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
// 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, {
+ const attempt = await callCodexSubscription(provider, model, body, {
statusOp, doneLabel, elapsedSec, throughput, timeout: opts.timeout, responseSchema, signal,
});
+ if (attempt.result) return attempt.result;
+ // The subscription could not serve this call and the user named an explicit
+ // fallback. Re-enter with the ORIGINAL prompt and options so the fallback
+ // gets the same treatment any direct call would — including the creative
+ // stamp, which is applied per-transport rather than carried on `body`. The
+ // shared `op` groups both attempts under one toast.
+ return callProviderAISimple(attempt.fallback, attempt.fallbackModel, prompt, options);
}
if (isOllamaProvider(provider)) {
diff --git a/server/services/aiProvider.test.js b/server/services/aiProvider.test.js
index 1efc404033..eeea9f543f 100644
--- a/server/services/aiProvider.test.js
+++ b/server/services/aiProvider.test.js
@@ -297,12 +297,18 @@ describe('callProviderAISimple through the ChatGPT subscription', () => {
const result = await callProviderAISimple(
{ ...CODEX_ENABLED, fallbackProvider: 'openai', fallbackModel: 'fallback-model' },
- 'model-alpha', 'hi', {},
+ 'model-alpha', 'hi', { max_tokens: 1500, temperature: 0.9 },
);
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');
+ const sent = JSON.parse(globalThis.fetch.mock.calls[0][1].body);
+ expect(sent.model).toBe('fallback-model');
+ // The caller's generation options survive the handoff. A fallback that
+ // silently capped at the defaults would truncate the very summaries a caller
+ // raised `max_tokens` for — and only ever on the failure path, where nobody
+ // is watching.
+ expect(sent).toMatchObject({ max_tokens: 1500, temperature: 0.9 });
});
it('fails closed when the provider named no fallback — never picks an API key on its own', async () => {
diff --git a/server/services/codexAppServer.js b/server/services/codexAppServer.js
index 0630893d09..dff25e6461 100644
--- a/server/services/codexAppServer.js
+++ b/server/services/codexAppServer.js
@@ -691,7 +691,13 @@ export async function listCodexModels({ fresh = false } = {}) {
cursor = result.nextCursor;
if (!cursor) break;
}
- if (cursor) console.error(`❌ Codex model/list stopped after ${MODEL_LIST_MAX_PAGES} pages with a cursor still pending`);
+ if (cursor) {
+ // A truncated catalog is not a successful read: caching it would replace a
+ // complete last-known-good list with a partial one, and reporting
+ // `error: null` would tell the client the picker is authoritative.
+ console.error(`❌ Codex model/list stopped after ${MODEL_LIST_MAX_PAGES} pages with a cursor still pending`);
+ throw new Error(`model/list did not finish paginating within ${MODEL_LIST_MAX_PAGES} pages`);
+ }
modelsCache = { at: Date.now(), models };
return { models, fetchedAt: modelsCache.at, error: null };
} catch (err) {
@@ -835,9 +841,12 @@ export async function runCodexTextTurn({
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 })
+ // quota. Sent on the LIVE connection directly rather than through `call`,
+ // which would `connect()` — spawning a whole new app-server to interrupt a
+ // thread that only existed in the one that just died.
+ const live = connection;
+ if (acc.status === 'inProgress' && acc.turnId && live && !live.closed) {
+ sendRequest(live, CODEX_TURN_RPC.turnInterrupt, { threadId, turnId: acc.turnId })
.catch((err) => console.error(`❌ Codex turn interrupt failed: ${err.message}`));
}
}
@@ -861,9 +870,16 @@ export async function stopCodexAppServer() {
.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;
+ if (!target || target.closed) {
+ connection = null;
+ return;
+ }
+ // `teardown` decides whether to fail live turns by comparing `connection` to
+ // the dying target — so `connection` must still point at it here. Nulling
+ // first left every in-flight turn waiting on a notification that could never
+ // arrive, until its own 5-minute deadline.
stopTarget(target, codexError(CODEX_ERROR_CODES.exited, 'PortOS is shutting down the Codex app-server.'));
+ connection = null;
console.log('🔌 Codex app-server stopped');
}
diff --git a/server/services/codexAppServer.turn.test.js b/server/services/codexAppServer.turn.test.js
index 2ff59d2504..c14fdf29e3 100644
--- a/server/services/codexAppServer.turn.test.js
+++ b/server/services/codexAppServer.turn.test.js
@@ -350,3 +350,41 @@ describe('progress hooks', () => {
expect(seen).toEqual(['mine']);
});
});
+
+describe('shutdown while a turn is live', () => {
+ it('fails the turn instead of leaving it to time out, and never respawns the child', async () => {
+ // `turn/start` already answered, so there is no pending RPC to reject — only
+ // the teardown hook can settle this. If shutdown drops the live handle first,
+ // the turn hangs for its full 5-minute deadline and its cleanup then spawns a
+ // WHOLE NEW app-server just to interrupt a thread that no longer exists.
+ 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' } });
+ expect(spawn).toHaveBeenCalledTimes(1);
+
+ await stopCodexAppServer();
+
+ await expect(promise).rejects.toMatchObject({ code: CODEX_ERROR_CODES.exited });
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('a catalog that will not stop paginating', () => {
+ it('reports an error rather than caching a partial list as authoritative', async () => {
+ // Caching a truncated catalog would replace a complete last-known-good list
+ // with a partial one, and `error: null` would tell the client it is whole.
+ const promise = listCodexModels();
+ await handshake();
+ for (let page = 0; page < 20; page += 1) {
+ await awaitRequest(child, 'model/list', {
+ data: [{ id: `model-${page}`, supportedReasoningEfforts: [] }], nextCursor: `page-${page + 1}`,
+ });
+ }
+
+ const result = await promise;
+ expect(result.models).toBeNull();
+ expect(result.error.message).toMatch(/paginating/i);
+ expect(peekCodexModels()).toBeNull();
+ });
+});