@bitkyc08/opencodex 2.95.0 → 2.97.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ocx.mjs +214 -19
- package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
- package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
- package/gui/dist/assets/index-CynE_Rue.js +94 -0
- package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
- package/gui/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/adapters/command-code.ts +15 -16
- package/src/adapters/cursor/transport-retry.ts +2 -2
- package/src/adapters/devin/cloud-direct/chat.ts +15 -6
- package/src/adapters/kiro/stream.ts +63 -4
- package/src/adapters/kiro-constants.ts +15 -1
- package/src/adapters/kiro-events.ts +31 -1
- package/src/adapters/kiro-retry.ts +3 -3
- package/src/adapters/ollama-native.ts +21 -7
- package/src/adapters/openai-responses/canonical-forward.ts +50 -13
- package/src/adapters/openai-responses/empty-assistant.ts +15 -3
- package/src/adapters/openai-responses/passthrough.ts +8 -8
- package/src/adapters/openai-responses/reasoning.ts +9 -4
- package/src/adapters/openai-responses/request-strips.ts +1 -1
- package/src/adapters/openai-responses/transport.ts +17 -26
- package/src/adapters/physical-send.ts +3 -3
- package/src/adapters/qoder/adapter.ts +1 -1
- package/src/adapters/qoder/image-input.ts +5 -2
- package/src/adapters/zed-openai-stream.ts +2 -1
- package/src/bridge/errors.ts +11 -2
- package/src/bridge/response-json.ts +2 -1
- package/src/bridge/sse.ts +14 -6
- package/src/chat/failure-verdict.ts +21 -0
- package/src/chat/outbound.ts +139 -21
- package/src/claude/outbound.ts +49 -2
- package/src/cli/agent.ts +44 -15
- package/src/cli/capabilities-agents-routing.ts +9 -0
- package/src/cli/capabilities-base.ts +25 -3
- package/src/cli/capabilities-command.ts +12 -3
- package/src/cli/capability-contracts.ts +2 -0
- package/src/cli/codex-launch-auth.ts +30 -1
- package/src/cli/codex-launcher.ts +12 -5
- package/src/cli/codex-shim-autorestore.ts +5 -4
- package/src/cli/dispatch.ts +11 -176
- package/src/cli/ensure-desired-integrations.ts +4 -3
- package/src/cli/help.ts +2 -2
- package/src/cli/index.ts +9 -2
- package/src/cli/link.ts +1 -1
- package/src/cli/message-command.ts +2 -1
- package/src/cli/message-mcp-command.ts +29 -0
- package/src/cli/registry.ts +12 -4
- package/src/cli/root.ts +8 -0
- package/src/cli/sync-command.ts +243 -0
- package/src/cli/sync-fanout-process.ts +92 -0
- package/src/cli/sync-fanout.ts +150 -0
- package/src/cli/sync-flags.ts +10 -0
- package/src/cli/sync-link-status.ts +39 -0
- package/src/cli/sync-update-guard.ts +18 -0
- package/src/client/connect.ts +31 -14
- package/src/client/link-home.ts +3 -2
- package/src/client/machine-listener.ts +3 -0
- package/src/client/restore-ownership.ts +19 -1
- package/src/client/runtime-restart.ts +12 -4
- package/src/client/runtime.ts +40 -11
- package/src/client/stop-routing.ts +62 -0
- package/src/client/sync-runtime.ts +65 -0
- package/src/clients/config-export.ts +32 -3
- package/src/codex/account-store.ts +1 -0
- package/src/codex/auth-context-provider.ts +15 -0
- package/src/codex/auth-context.ts +59 -122
- package/src/codex/catalog/antigravity-discovery.ts +16 -5
- package/src/codex/catalog/provider-models.ts +6 -8
- package/src/codex/forward-transport-headers.ts +65 -36
- package/src/codex/inject/config-toml.ts +88 -0
- package/src/codex/inject/multi-agent-v2.ts +30 -4
- package/src/codex/inject/plan.ts +34 -7
- package/src/codex/inject-coordination.ts +11 -0
- package/src/codex/inject.ts +18 -7
- package/src/codex/installation-id.ts +72 -0
- package/src/codex/lineage.ts +13 -7
- package/src/codex/quota.ts +22 -6
- package/src/codex/request-owned-affinity-key.ts +11 -0
- package/src/codex/request-owned-affinity.ts +118 -0
- package/src/codex/request-owned-main-pin.ts +86 -0
- package/src/codex/role-capability.ts +52 -41
- package/src/codex/routing/active-account.ts +13 -5
- package/src/codex/routing/selection.ts +40 -1
- package/src/codex/routing/thread-affinity-store.ts +916 -0
- package/src/codex/routing/thread-affinity.ts +90 -12
- package/src/codex/toml-source-lines.ts +72 -13
- package/src/combos/failover.ts +6 -109
- package/src/combos/request.ts +2 -2
- package/src/combos/resolve.ts +29 -11
- package/src/config/process-state.ts +5 -0
- package/src/config/schema/leaf-validators.ts +1 -0
- package/src/generated/compatibility-version.json +496 -192
- package/src/grok/sync.ts +10 -1
- package/src/images/loop.ts +2 -1
- package/src/lib/client-error-body.ts +184 -0
- package/src/lib/client-retry-after.ts +66 -0
- package/src/lib/config-ownership.ts +4 -0
- package/src/lib/context-overflow-verdict.ts +113 -0
- package/src/lib/desktop-cli-handoff.d.mts +1 -1
- package/src/lib/desktop-cli-handoff.mjs +11 -1
- package/src/lib/empty-tool-catalog.ts +25 -3
- package/src/lib/error-destination.ts +47 -0
- package/src/lib/failure-detail.ts +66 -0
- package/src/lib/model-identity.ts +44 -0
- package/src/lib/private-sqlite-path.ts +124 -0
- package/src/lib/response-service-tier.ts +17 -0
- package/src/lib/retry-after.ts +3 -0
- package/src/lib/spend-ledger-owner.ts +43 -4
- package/src/lib/upstream-condition.ts +142 -0
- package/src/lib/upstream-retry.ts +14 -11
- package/src/lib/windows-owner-acl.ts +13 -6
- package/src/lib/windows-secret-acl.ts +2 -2
- package/src/link/remote-platform.ts +14 -0
- package/src/link/remote-windows.ts +51 -9
- package/src/link/ssh-argv.ts +63 -10
- package/src/messaging/mcp-queue-rpc.ts +102 -0
- package/src/messaging/mcp-queue-server.ts +42 -0
- package/src/messaging/mcp-queue-tools.ts +39 -0
- package/src/oauth/anthropic-identity.ts +2 -6
- package/src/oauth/generic-account-failover.ts +13 -11
- package/src/oauth/index.ts +41 -74
- package/src/oauth/oauth-errors.ts +67 -0
- package/src/oauth/store.ts +1 -1
- package/src/protocols/codecs/ollama.ts +197 -0
- package/src/protocols/encoders/adapter-events.ts +4 -0
- package/src/protocols/encoders/chat.ts +18 -10
- package/src/protocols/trace.ts +18 -0
- package/src/providers/anthropic-subscription.ts +25 -0
- package/src/providers/claude-cli-usage.ts +15 -67
- package/src/providers/fastwire.ts +3 -2
- package/src/providers/quota/anthropic-decision-windows.ts +5 -19
- package/src/providers/quota/anthropic-usage-windows.ts +65 -0
- package/src/providers/quota/vendor-probes-key.ts +60 -24
- package/src/providers/request-pacing.ts +3 -2
- package/src/responses/apply-patch-envelope.ts +45 -19
- package/src/responses/compaction-history-framing.ts +5 -1
- package/src/responses/freeform-wrapper-scan.ts +5 -3
- package/src/responses/parser-tools.ts +1 -0
- package/src/responses/progressive-freeform-input.ts +354 -45
- package/src/responses/schema.ts +5 -2
- package/src/routing/fallback-policy.ts +3 -1
- package/src/server/admission-model-scope.ts +17 -6
- package/src/server/admitted-http-turn.ts +56 -0
- package/src/server/audio-dictation.ts +3 -0
- package/src/server/audio-live.ts +8 -2
- package/src/server/audio-upstream.ts +2 -0
- package/src/server/auth-cors.ts +5 -0
- package/src/server/chat-completions.ts +45 -20
- package/src/server/chat-native-sse.ts +52 -7
- package/src/server/chat-native.ts +60 -35
- package/src/server/claude-bridge-pool-session.ts +59 -0
- package/src/server/claude-messages.ts +57 -27
- package/src/server/context-history.ts +14 -7
- package/src/server/images.ts +14 -5
- package/src/server/inbound-body-admission.ts +11 -4
- package/src/server/index/live-sideband.ts +16 -2
- package/src/server/index/ollama-routes.ts +89 -0
- package/src/server/index/serve-options.ts +22 -4
- package/src/server/index/websocket-handler.ts +5 -3
- package/src/server/index.ts +6 -36
- package/src/server/inference/client-encoder-delivery.ts +4 -2
- package/src/server/json-serialized-bytes.ts +44 -0
- package/src/server/live.ts +30 -5
- package/src/server/management/agent-settings-routes.ts +24 -21
- package/src/server/management/codex-cli-update-routes.ts +2 -1
- package/src/server/management/route-registry.ts +1 -1
- package/src/server/messages-native-scope.ts +2 -1
- package/src/server/messages-native-tool-guard.ts +1 -1
- package/src/server/messages-native.ts +12 -7
- package/src/server/messages-shared.ts +6 -2
- package/src/server/native-final-log.ts +93 -0
- package/src/server/ollama-inbound.ts +349 -0
- package/src/server/ollama-native-paths.ts +21 -0
- package/src/server/ollama-route-policy.ts +73 -0
- package/src/server/relay.ts +22 -3
- package/src/server/request-decompress.ts +4 -2
- package/src/server/request-log-failure-attribution.ts +22 -0
- package/src/server/request-log-failure-detail.ts +80 -0
- package/src/server/request-log-terminal-status.ts +4 -2
- package/src/server/request-log.ts +79 -42
- package/src/server/response-log-body.ts +6 -1
- package/src/server/responses/account-change-state.ts +17 -6
- package/src/server/responses/adapter-continuation.ts +9 -4
- package/src/server/responses/adapter-delivery.ts +5 -4
- package/src/server/responses/adapter-dispatch.ts +36 -30
- package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
- package/src/server/responses/codex-auth-error.ts +22 -17
- package/src/server/responses/codex-ws-exchange.ts +11 -8
- package/src/server/responses/codex-ws-metadata.ts +94 -21
- package/src/server/responses/codex-ws-request.ts +3 -1
- package/src/server/responses/combo-required-tool-contract.ts +24 -12
- package/src/server/responses/compact.ts +89 -41
- package/src/server/responses/compaction-recovery.ts +4 -2
- package/src/server/responses/compaction-routing.ts +9 -4
- package/src/server/responses/core-auth.ts +32 -14
- package/src/server/responses/core-codex-account.ts +34 -12
- package/src/server/responses/core-combo-failure.ts +5 -1
- package/src/server/responses/core-combo-native.ts +2 -1
- package/src/server/responses/core-combo.ts +51 -33
- package/src/server/responses/core-errors.ts +22 -20
- package/src/server/responses/core-lifetime.ts +6 -3
- package/src/server/responses/core-normalize.ts +8 -1
- package/src/server/responses/core-options.ts +7 -0
- package/src/server/responses/core-pipeline.ts +4 -3
- package/src/server/responses/fetch-helpers.ts +7 -1
- package/src/server/responses/input-admission.ts +28 -2
- package/src/server/responses/native-injection.ts +1 -1
- package/src/server/responses/native-response-json.ts +13 -4
- package/src/server/responses/native-response-output.ts +1 -2
- package/src/server/responses/non-replayable-error.ts +2 -1
- package/src/server/responses/pacing-overload.ts +3 -2
- package/src/server/responses/passthrough-build-error.ts +36 -0
- package/src/server/responses/passthrough-delivery.ts +55 -14
- package/src/server/responses/passthrough-dispatch.ts +26 -39
- package/src/server/responses/passthrough-error.ts +9 -9
- package/src/server/responses/policy-fallback.ts +2 -1
- package/src/server/responses/request-prepare.ts +67 -48
- package/src/server/responses/request-sidecar-auth.ts +3 -1
- package/src/server/responses/request-transport.ts +35 -31
- package/src/server/responses/run-turn-execution.ts +6 -6
- package/src/server/responses/sidecar-execution.ts +16 -12
- package/src/server/responses/spend-storage-error.ts +2 -1
- package/src/server/responses/ws-upstream.ts +9 -0
- package/src/server/responses-custom-tool-repair.ts +14 -3
- package/src/server/responses-terminal-repair.ts +5 -2
- package/src/server/responses-undeclared-tool-guard.ts +39 -16
- package/src/server/safe-response-headers.ts +162 -13
- package/src/server/search.ts +13 -4
- package/src/server/turn-state-handles.ts +164 -0
- package/src/server/workflow-refusal.ts +2 -1
- package/src/server/ws-bridge.ts +5 -2
- package/src/service/ownership-mutation-lease.d.mts +11 -2
- package/src/service/ownership-mutation-lease.mjs +53 -11
- package/src/types/config.ts +2 -0
- package/src/update/index.ts +133 -25
- package/src/update/npm-install.d.mts +8 -0
- package/src/update/npm-install.mjs +20 -1
- package/src/update/orchestrated-admission.d.mts +4 -0
- package/src/update/orchestrated-admission.mjs +12 -0
- package/src/update/orchestrated-arguments.d.mts +12 -0
- package/src/update/orchestrated-arguments.mjs +64 -0
- package/src/update/orchestrated-child.d.mts +12 -0
- package/src/update/orchestrated-child.mjs +70 -0
- package/src/update/orchestrated-entry.ts +234 -0
- package/src/update/orchestrated-identity-probe-entry.ts +20 -0
- package/src/update/orchestrated-identity.ts +53 -0
- package/src/update/orchestrated-live-identity.ts +48 -0
- package/src/update/orchestrated-node-driver.mjs +99 -0
- package/src/update/orchestrated-outcome.d.mts +21 -0
- package/src/update/orchestrated-outcome.mjs +40 -0
- package/src/update/orchestrated-plan.ts +49 -0
- package/src/update/orchestrated-pnpm.d.mts +8 -0
- package/src/update/orchestrated-pnpm.mjs +33 -0
- package/src/update/orchestrated-session.d.mts +37 -0
- package/src/update/orchestrated-session.mjs +264 -0
- package/src/update/orchestrated-token.d.mts +10 -0
- package/src/update/orchestrated-token.mjs +21 -0
- package/src/update/orchestrated-token.ts +3 -0
- package/src/update/orchestrated-tree.d.mts +1 -0
- package/src/update/orchestrated-tree.mjs +14 -0
- package/src/update/pnpm-global-install.d.mts +6 -0
- package/src/update/pnpm-global-install.mjs +9 -2
- package/src/update/posix-install-supervisor-entry.mjs +6 -0
- package/src/update/posix-install-supervisor.d.mts +10 -0
- package/src/update/posix-install-supervisor.mjs +88 -0
- package/src/update/sync-update-mutex.d.mts +10 -0
- package/src/update/sync-update-mutex.mjs +164 -0
- package/src/update/sync-update-mutex.ts +1 -0
- package/src/update/test-home-guard.mjs +33 -0
- package/src/update/transactional-install.mjs +2 -2
- package/src/usage/error-detail.ts +225 -0
- package/src/usage/log.ts +60 -27
- package/src/vision/describe.ts +4 -7
- package/src/web-search/executor.ts +4 -7
- package/src/web-search/loop.ts +31 -5
- package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, realpathSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { acquireOwnershipMutationLease, inspectOwnershipMutationLease, ownershipMutationLeasePath } from "../service/ownership-mutation-lease.mjs";
|
|
4
|
+
import { serviceStateFilesFor } from "../service/install-state-contract.mjs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { assertNotRealHomeUnderTest, isTestHomeGuardArmed } from "./test-home-guard.mjs";
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
function paths(home) { return [join(home, "sync-update")]; }
|
|
10
|
+
function ensureHome(home) {
|
|
11
|
+
try { lstatSync(home); return; } catch (error) { if (error?.code !== "ENOENT") throw error; }
|
|
12
|
+
const parent = dirname(home);
|
|
13
|
+
if (parent === home) throw new Error("missing home authority");
|
|
14
|
+
ensureHome(parent);
|
|
15
|
+
try { mkdirSync(home, { mode: 0o700 }); }
|
|
16
|
+
catch (error) { if (error?.code !== "EEXIST") throw error; }
|
|
17
|
+
const stat = lstatSync(home);
|
|
18
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("home creation was replaced");
|
|
19
|
+
}
|
|
20
|
+
function missingHome(home) {
|
|
21
|
+
let current = home;
|
|
22
|
+
for (;;) {
|
|
23
|
+
try { lstatSync(current); realpathSync.native(current); return current !== home; }
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (error?.code !== "ENOENT") throw error;
|
|
26
|
+
// A dangling symlink is not evidence that the home is absent.
|
|
27
|
+
try { lstatSync(current); throw new Error("unresolved home authority"); }
|
|
28
|
+
catch (again) { if (again?.code !== "ENOENT") throw again; }
|
|
29
|
+
const parent = dirname(current);
|
|
30
|
+
if (parent === current) throw new Error("missing home authority");
|
|
31
|
+
current = parent;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function mutexPath(home) {
|
|
36
|
+
const canonicalHome = realpathSync.native(home);
|
|
37
|
+
try { lstatSync(join(canonicalHome, "sync-update")); throw new Error("mutex authority path is occupied"); }
|
|
38
|
+
catch (error) { if (error?.code !== "ENOENT") throw error; }
|
|
39
|
+
return join(canonicalHome, "sync-update.mutation.lock");
|
|
40
|
+
}
|
|
41
|
+
function holderKind(holder) {
|
|
42
|
+
return holder?.alive === true && (holder.holderKind === "sync" || holder.holderKind === "update")
|
|
43
|
+
? holder.holderKind : "unknown";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Non-blocking and never joins the separate service-ownership lease. */
|
|
47
|
+
export function tryAcquireUpdateSyncMutex(home, kind, deps = {}) {
|
|
48
|
+
assertNotRealHomeUnderTest(home);
|
|
49
|
+
try {
|
|
50
|
+
ensureHome(home);
|
|
51
|
+
const lease = acquireOwnershipMutationLease(paths(home), { ...deps, waitMs: 0, isolated: true, holderKind: kind, processImage: () => null, lockPath: mutexPath(home) });
|
|
52
|
+
return { kind: "acquired", addDelegate: pid => lease.addDelegate(pid), release: () => lease.release() };
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (error && typeof error === "object" && "holder" in error) {
|
|
55
|
+
return { kind: "busy", holder: holderKind(error.holder) };
|
|
56
|
+
}
|
|
57
|
+
return { kind: "busy", holder: "unknown" };
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Read only: absence is accepted only after an explicit filesystem absence check. */
|
|
62
|
+
export function inspectUpdateSyncMutex(home) {
|
|
63
|
+
assertNotRealHomeUnderTest(home);
|
|
64
|
+
try {
|
|
65
|
+
if (missingHome(home)) return "free";
|
|
66
|
+
const lock = mutexPath(home);
|
|
67
|
+
try { lstatSync(lock); } catch (error) {
|
|
68
|
+
return error?.code === "ENOENT" ? "free" : "unknown";
|
|
69
|
+
}
|
|
70
|
+
return holderKind(inspectOwnershipMutationLease(paths(home), { processImage: () => null, lockPath: lock }));
|
|
71
|
+
} catch { return "unknown"; }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A delegated child may reuse only its live parent's sync lease. */
|
|
75
|
+
export function parentHoldsSyncMutex(home, claimedPid = process.env.OCX_SYNC_MUTEX_HELD_BY) {
|
|
76
|
+
if (!claimedPid) return false;
|
|
77
|
+
try {
|
|
78
|
+
const holder = inspectOwnershipMutationLease(paths(home), { processImage: () => null, lockPath: mutexPath(home) });
|
|
79
|
+
return holder?.alive === true && holder.record === "complete" && holder.holderKind === "sync" && String(holder.pid) === claimedPid && holder.delegatePid === process.pid;
|
|
80
|
+
} catch { return false; }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Shared wire format for launcher and Bun sync admission refusals. */
|
|
84
|
+
export function refuseSync(reason, args) {
|
|
85
|
+
const exit = reason === "sync-in-progress" ? 1 : 7;
|
|
86
|
+
console.error(reason);
|
|
87
|
+
if (args.includes("--json")) console.log(JSON.stringify({ schema: "ocx.sync.fanout/1", home: { state: "skipped", exit }, fanout: { state: "not-applicable", reason }, children: [] }));
|
|
88
|
+
return exit;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function acquireSyncGuard(home, args) {
|
|
92
|
+
const lease = tryAcquireUpdateSyncMutex(home, "sync");
|
|
93
|
+
if (lease.kind !== "acquired") return { kind: "refused", exit: refuseSync(lease.holder === "sync" ? "sync-in-progress" : "update-in-flight", args) };
|
|
94
|
+
if (inspectUpdateMarker(home) !== "free") {
|
|
95
|
+
lease.release();
|
|
96
|
+
return { kind: "refused", exit: refuseSync("update-in-flight", args) };
|
|
97
|
+
}
|
|
98
|
+
return lease;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function inspectOwnershipLease(home) {
|
|
102
|
+
try {
|
|
103
|
+
const statePaths = serviceStateFilesFor(home, isTestHomeGuardArmed() ? home : join(homedir(), ".opencodex"));
|
|
104
|
+
const path = ownershipMutationLeasePath(statePaths);
|
|
105
|
+
try { lstatSync(path); } catch (error) {
|
|
106
|
+
return error?.code === "ENOENT" ? "free" : "unknown";
|
|
107
|
+
}
|
|
108
|
+
const holder = inspectOwnershipMutationLease(statePaths, { processImage: () => null });
|
|
109
|
+
return holder?.alive === true ? "active" : holder?.alive === false ? "free" : "unknown";
|
|
110
|
+
} catch { return "unknown"; }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function inspectUpdateMarker(home, { now = Date.now } = {}) {
|
|
114
|
+
const path = join(home, "update-orchestrated.json");
|
|
115
|
+
let found = false;
|
|
116
|
+
let fd;
|
|
117
|
+
try {
|
|
118
|
+
const before = lstatSync(path);
|
|
119
|
+
found = true;
|
|
120
|
+
if (!before.isFile() || before.size > 4096) return "unknown";
|
|
121
|
+
fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
122
|
+
const opened = fstatSync(fd);
|
|
123
|
+
if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== before.size) return "unknown";
|
|
124
|
+
const buffer = Buffer.alloc(4097);
|
|
125
|
+
const count = readSync(fd, buffer, 0, buffer.length, 0);
|
|
126
|
+
if (count > 4096 || count !== opened.size) return "unknown";
|
|
127
|
+
const raw = buffer.subarray(0, count).toString("utf8");
|
|
128
|
+
const after = lstatSync(path);
|
|
129
|
+
if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs) return "unknown";
|
|
130
|
+
const value = JSON.parse(raw);
|
|
131
|
+
if (!value || typeof value !== "object") return "unknown";
|
|
132
|
+
const marker = value;
|
|
133
|
+
if (!Number.isSafeInteger(marker.pid) || Number(marker.pid) <= 0 || typeof marker.phase !== "string"
|
|
134
|
+
|| !Number.isSafeInteger(marker.startedAt) || Number(marker.startedAt) <= 0) return "unknown";
|
|
135
|
+
const terminal = ["installed", "failed", "refused"].includes(marker.phase);
|
|
136
|
+
if (!terminal && !["preflight", "mutating", "overrun"].includes(marker.phase)) return "unknown";
|
|
137
|
+
if (marker.terminationUnconfirmed !== undefined && marker.terminationUnconfirmed !== true) return "unknown";
|
|
138
|
+
if (marker.fenceUntil !== undefined && (!Number.isSafeInteger(marker.fenceUntil) || marker.fenceUntil < marker.startedAt)) return "unknown";
|
|
139
|
+
if (marker.fenceUntil !== undefined && now() < marker.fenceUntil) return "active";
|
|
140
|
+
const ids = [];
|
|
141
|
+
if (!terminal) ids.push(marker.pid);
|
|
142
|
+
for (const key of ["installerPid", "installerPgid"]) {
|
|
143
|
+
if (marker[key] === undefined) continue;
|
|
144
|
+
if (!Number.isSafeInteger(marker[key]) || marker[key] <= 0 || (key === "installerPgid" && process.platform === "win32")) return "unknown";
|
|
145
|
+
ids.push(key === "installerPgid" ? -marker[key] : marker[key]);
|
|
146
|
+
}
|
|
147
|
+
let unknown = false;
|
|
148
|
+
for (const id of ids) {
|
|
149
|
+
try { process.kill(id, 0); return "active"; }
|
|
150
|
+
catch (error) { if (error?.code !== "ESRCH") unknown = true; }
|
|
151
|
+
}
|
|
152
|
+
return unknown || (marker.terminationUnconfirmed && marker.installerPgid === undefined) ? "unknown" : "free";
|
|
153
|
+
} catch (error) { return !found && error?.code === "ENOENT" ? "free" : "unknown"; }
|
|
154
|
+
finally { if (fd !== undefined) closeSync(fd); }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** False requires positive absence of an update across all three read-only observations. */
|
|
158
|
+
export function isUpdateInFlight(home, deps = { mutex: inspectUpdateSyncMutex, ownershipLease: inspectOwnershipLease, marker: inspectUpdateMarker }) {
|
|
159
|
+
try {
|
|
160
|
+
const mutex = deps.mutex(home);
|
|
161
|
+
if (mutex !== "free" && mutex !== "sync") return true;
|
|
162
|
+
return deps.ownershipLease(home) !== "free" || deps.marker(home) !== "free";
|
|
163
|
+
} catch { return true; }
|
|
164
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./sync-update-mutex.mjs";
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Match the test home guard in ../lib/test-home-guard.ts for the Node launcher.
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
+
import { realpathSync } from "node:fs";
|
|
5
|
+
|
|
6
|
+
function canonicalize(path) {
|
|
7
|
+
let current = resolve(path);
|
|
8
|
+
const remaining = [];
|
|
9
|
+
for (;;) {
|
|
10
|
+
try { return join(realpathSync.native(current), ...remaining.reverse()); }
|
|
11
|
+
catch {
|
|
12
|
+
const parent = dirname(current);
|
|
13
|
+
if (parent === current) return resolve(path);
|
|
14
|
+
remaining.push(current.slice(parent.length + 1)); current = parent;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const protectedHome = canonicalize(join(process.env.OCX_REAL_HOME?.trim() || homedir(), ".opencodex"));
|
|
19
|
+
export function isTestHomeGuardArmed() {
|
|
20
|
+
if (process.env.OCX_TEST_HOME_GUARD === "1") return true;
|
|
21
|
+
if (process.env.OCX_TEST_HOME_GUARD === "0") return false;
|
|
22
|
+
const entry = globalThis.Bun?.main ?? process.argv[1];
|
|
23
|
+
return typeof entry === "string" && /[._](?:test|spec)\.[cm]?[jt]sx?$/i.test(basename(entry));
|
|
24
|
+
}
|
|
25
|
+
if (process.env.OCX_TEST_HOME_GUARD !== "0" && process.env.OCX_TEST_HOME_GUARD !== "1" && isTestHomeGuardArmed()) {
|
|
26
|
+
process.env.OCX_TEST_HOME_GUARD = "1";
|
|
27
|
+
}
|
|
28
|
+
export function assertNotRealHomeUnderTest(home) {
|
|
29
|
+
if (!isTestHomeGuardArmed()) return;
|
|
30
|
+
const path = canonicalize(home);
|
|
31
|
+
const normalize = value => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
|
|
32
|
+
if (normalize(path) === normalize(protectedHome)) throw new Error("refusing to write the real OpenCodex home from a test process");
|
|
33
|
+
}
|
|
@@ -449,7 +449,7 @@ function* npmUpdateTransaction({
|
|
|
449
449
|
const detail = install.error
|
|
450
450
|
? [install.error.code, install.error.message].filter(Boolean).join(": ")
|
|
451
451
|
: install.signal ?? install.status ?? "?";
|
|
452
|
-
return { ok: false, phase: "stage", error: "npm staging install failed (" + detail + ")" };
|
|
452
|
+
return { ok: false, phase: "stage", ...(install.processTreeExited === false ? { processTreeExited: false } : {}), error: "npm staging install failed (" + detail + ")" };
|
|
453
453
|
}
|
|
454
454
|
const stagedPackage = stagedCandidatesIn(stageRoot).find(dir => existsSync(join(dir, "package.json")));
|
|
455
455
|
if (!stagedPackage) {
|
|
@@ -556,7 +556,7 @@ export async function transactionalNpmUpdateAsync(options) {
|
|
|
556
556
|
let install;
|
|
557
557
|
try { install = await options.runNpm(step.value); }
|
|
558
558
|
catch (error) { install = { status: null, error, processTreeExited: false }; }
|
|
559
|
-
if (install.processTreeExited !== true) install = { ...install, status: null, processTreeExited: false,
|
|
559
|
+
if (install.processTreeExited !== true && !(install.groupExited === true && typeof install.status === "number")) install = { ...install, status: null, processTreeExited: false,
|
|
560
560
|
error: install.error ?? { code: "EINSTALLJOIN", message: "npm process-tree exit was not confirmed" } };
|
|
561
561
|
return transaction.next(install).value;
|
|
562
562
|
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error detail kept on request-log rows (live ring, /api/logs, usage.jsonl and hydration).
|
|
3
|
+
*
|
|
4
|
+
* Rows carry only proxy-owned error facts: a code from a closed vocabulary, a classified upstream
|
|
5
|
+
* condition, and, for one provider, a numeric quota reset time. Upstream-authored error text and
|
|
6
|
+
* tokens are read here once to derive those facts and are never retained.
|
|
7
|
+
*/
|
|
8
|
+
import { classifyUpstreamCondition, isUpstreamCondition, type UpstreamCondition } from "../lib/upstream-condition";
|
|
9
|
+
import { boundedFailureDetail, type FailureDetail, type FailureDetailCode } from "../lib/failure-detail";
|
|
10
|
+
import { boundedServiceTier } from "../lib/response-service-tier";
|
|
11
|
+
|
|
12
|
+
export { boundedServiceTier };
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Every error code a row may carry. Codes outside this set (an upstream-supplied code that reached a
|
|
16
|
+
* writer, a future writer's typo) collapse to the status fallback below. http_NNN codes are formatted
|
|
17
|
+
* by the proxy from a numeric status and stay valid.
|
|
18
|
+
*/
|
|
19
|
+
export const LOG_ERROR_CODES: ReadonlySet<string> = new Set([
|
|
20
|
+
// classifyError and requestLogErrorCode outputs
|
|
21
|
+
"spend_ledger_storage_unavailable", "previous_response_not_found", "client_cancelled", "client_closed_request",
|
|
22
|
+
"cyber_policy", "input_admission_refused", "inbound_body_too_large", "context_length_exceeded",
|
|
23
|
+
"tool_catalog_too_large", "rate_limit_exceeded", "insufficient_quota", "request_send_budget_exhausted",
|
|
24
|
+
"origin_rejected", "upstream_server_error", "invalid_api_key", "permission_denied", "location_not_supported",
|
|
25
|
+
"subscription_required", "server_is_overloaded", "invalid_request_error", "upstream_error",
|
|
26
|
+
// local refusals and proxy decisions
|
|
27
|
+
"server_busy", "unsupported_feature", "usage_limit_reached", "undeclared_tool_call", "outbound_body_too_large",
|
|
28
|
+
"codex_no_account", "upstream_reset_replay_refused", "memory_model_target_unavailable",
|
|
29
|
+
"intercept_target_unavailable", "observation_barrier_timeout", "claude_thread_unsupported",
|
|
30
|
+
"claude_compatibility_configuration", "claude_compatibility_unsupported",
|
|
31
|
+
"unsupported_credential_domain", "unsupported_synthetic_selector", "unsupported_shadow_rewrite",
|
|
32
|
+
// workflow budget refusals
|
|
33
|
+
"workflow_sends_exhausted", "workflow_children_exhausted", "workflow_concurrency_exhausted",
|
|
34
|
+
"workflow_spend_exhausted", "workflow_tracking_exhausted", "workflow_send_replayed",
|
|
35
|
+
"workflow_pool_history_unresolved", "workflow_spend_undurable",
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
const HTTP_CODE = /^http_[1-5][0-9]{2}$/;
|
|
39
|
+
|
|
40
|
+
function statusFallbackCode(status: number | undefined): string | undefined {
|
|
41
|
+
if (status === undefined || !Number.isInteger(status) || status < 400) return undefined;
|
|
42
|
+
if (status === 499) return "client_closed_request";
|
|
43
|
+
if (status === 400 || status === 409) return "invalid_request_error";
|
|
44
|
+
if (status === 401) return "invalid_api_key";
|
|
45
|
+
if (status === 403) return "permission_denied";
|
|
46
|
+
if (status === 429) return "rate_limit_exceeded";
|
|
47
|
+
if (status === 503) return "server_is_overloaded";
|
|
48
|
+
if (status >= 500) return "upstream_server_error";
|
|
49
|
+
return `http_${status}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A code from the closed vocabulary, or the proxy's own code for the status, or nothing. */
|
|
53
|
+
export function normalizeLogErrorCode(code: unknown, status?: number): string | undefined {
|
|
54
|
+
if (typeof code === "string" && (LOG_ERROR_CODES.has(code) || HTTP_CODE.test(code))) return code;
|
|
55
|
+
return typeof code === "string" && code ? statusFallbackCode(status) ?? "upstream_error" : undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Meta Muse states its quota window in one fixed sentence. The reset time is kept as a number so
|
|
59
|
+
// the dashboard needs no message text.
|
|
60
|
+
const MUSE_PROVIDER = "meta-muse";
|
|
61
|
+
const MUSE_RESET_SENTENCE = /^Subscription quota exhausted\. Your usage window resets at (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)\.$/;
|
|
62
|
+
export const RATE_LIMIT_RESET_MAX_MS = 8 * 24 * 60 * 60 * 1000;
|
|
63
|
+
|
|
64
|
+
/** A reset time is kept only when it is a finite epoch-ms value after the request and within 8 days. */
|
|
65
|
+
export function boundedRateLimitResetAt(value: unknown, timestamp: unknown): number | undefined {
|
|
66
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value)) return undefined;
|
|
67
|
+
if (typeof timestamp !== "number" || !Number.isFinite(timestamp)) return undefined;
|
|
68
|
+
return value > timestamp && value - timestamp <= RATE_LIMIT_RESET_MAX_MS ? value : undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function deriveRateLimitResetAt(entry: {
|
|
72
|
+
provider?: unknown; status?: unknown; errorCode?: unknown; upstreamError?: unknown; timestamp?: unknown;
|
|
73
|
+
}): number | undefined {
|
|
74
|
+
if (entry.provider !== MUSE_PROVIDER || entry.status !== 429 || entry.errorCode !== "rate_limit_exceeded") return undefined;
|
|
75
|
+
if (typeof entry.upstreamError !== "string") return undefined;
|
|
76
|
+
const match = MUSE_RESET_SENTENCE.exec(entry.upstreamError);
|
|
77
|
+
if (!match) return undefined;
|
|
78
|
+
const parsed = Date.parse(match[1]!);
|
|
79
|
+
return boundedRateLimitResetAt(Number.isFinite(parsed) ? parsed : undefined, entry.timestamp);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The fields an error-detail projection reads; all optional so legacy rows qualify. */
|
|
83
|
+
export interface ErrorDetailSource {
|
|
84
|
+
status?: unknown;
|
|
85
|
+
timestamp?: unknown;
|
|
86
|
+
provider?: unknown;
|
|
87
|
+
errorCode?: unknown;
|
|
88
|
+
terminalStatus?: unknown;
|
|
89
|
+
upstreamError?: unknown;
|
|
90
|
+
upstreamErrorCode?: unknown;
|
|
91
|
+
upstreamErrorType?: unknown;
|
|
92
|
+
upstreamCondition?: unknown;
|
|
93
|
+
rateLimitResetAt?: unknown;
|
|
94
|
+
failureDetail?: unknown;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface ErrorDetail {
|
|
98
|
+
errorCode?: string;
|
|
99
|
+
upstreamCondition?: UpstreamCondition;
|
|
100
|
+
rateLimitResetAt?: number;
|
|
101
|
+
failureDetail?: FailureDetail;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const str = (value: unknown): string | undefined => typeof value === "string" ? value : undefined;
|
|
105
|
+
|
|
106
|
+
// Sentences this proxy writes into a relayed error body (web-search and image-bridge loops, body
|
|
107
|
+
// inactivity guard). The request log only sees them as captured error text, so a match becomes a
|
|
108
|
+
// closed code with the parsed number; the number is bounded so no credential-length value can fit.
|
|
109
|
+
const PROXY_SENTENCES: ReadonlyArray<readonly [RegExp, FailureDetailCode]> = [
|
|
110
|
+
[/^Provider response-header timeout after (\d{1,7})ms during (?:web-search|image-bridge)$/, "header_timeout"],
|
|
111
|
+
[/^Upstream response body stalled for (\d{1,7})ms$/, "body_stall"],
|
|
112
|
+
[/^Routed model generation timeout after (\d{1,7})ms without response bytes during web-search$/, "generation_timeout"],
|
|
113
|
+
[/^runTurn inactivity timeout after (\d{1,7})ms during image-bridge$/, "turn_inactivity"],
|
|
114
|
+
[/^Provider connect timeout after (\d{1,7})ms$/, "connect_timeout"],
|
|
115
|
+
[/^client closed request during web-search$/, "client_closed"],
|
|
116
|
+
];
|
|
117
|
+
|
|
118
|
+
function proxySentenceDetail(text: string | undefined): FailureDetail | undefined {
|
|
119
|
+
if (text === undefined) return undefined;
|
|
120
|
+
for (const [pattern, code] of PROXY_SENTENCES) {
|
|
121
|
+
const match = pattern.exec(text);
|
|
122
|
+
if (match) return match[1] === undefined ? { code } : { code, value: Number(match[1]) };
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Derive the proxy-owned error facts for one row. An existing condition or reset time is kept only
|
|
129
|
+
* when valid; otherwise both are derived from upstream evidence, which the caller then drops.
|
|
130
|
+
* A condition is derived only when the row carries upstream evidence, so local refusals get none.
|
|
131
|
+
*/
|
|
132
|
+
export function errorDetailFor(entry: ErrorDetailSource): ErrorDetail {
|
|
133
|
+
const status = typeof entry.status === "number" ? entry.status : undefined;
|
|
134
|
+
const errorCode = normalizeLogErrorCode(entry.errorCode, status);
|
|
135
|
+
// The HTTP status decides when present: a 200 that stopped at the requested output limit is an
|
|
136
|
+
// incomplete terminal but a successful request, not an upstream failure.
|
|
137
|
+
const failed = status !== undefined ? status >= 400 : typeof entry.terminalStatus === "string" && entry.terminalStatus !== "completed";
|
|
138
|
+
// A client that closed the request is not an upstream condition.
|
|
139
|
+
const clientClosed = status === 499 || errorCode === "client_closed_request" || errorCode === "client_cancelled";
|
|
140
|
+
// A recorded condition is kept under the same rules that derive one: failed and not a client close.
|
|
141
|
+
let upstreamCondition: UpstreamCondition | undefined = failed && !clientClosed && isUpstreamCondition(entry.upstreamCondition)
|
|
142
|
+
? entry.upstreamCondition : undefined;
|
|
143
|
+
const evidence = str(entry.upstreamError) ?? str(entry.upstreamErrorCode) ?? str(entry.upstreamErrorType);
|
|
144
|
+
if (!upstreamCondition && failed && !clientClosed && evidence !== undefined && status !== undefined) {
|
|
145
|
+
upstreamCondition = classifyUpstreamCondition({
|
|
146
|
+
status,
|
|
147
|
+
code: str(entry.upstreamErrorCode),
|
|
148
|
+
type: str(entry.upstreamErrorType),
|
|
149
|
+
message: str(entry.upstreamError),
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
const rateLimitResetAt = boundedRateLimitResetAt(entry.rateLimitResetAt, entry.timestamp)
|
|
153
|
+
?? deriveRateLimitResetAt({ ...entry, errorCode });
|
|
154
|
+
// A closed code with bounded parameters; free text (a legacy or edited row) is dropped.
|
|
155
|
+
const failureDetail = boundedFailureDetail(entry.failureDetail) ?? proxySentenceDetail(str(entry.upstreamError));
|
|
156
|
+
return {
|
|
157
|
+
...(errorCode ? { errorCode } : {}),
|
|
158
|
+
...(upstreamCondition ? { upstreamCondition } : {}),
|
|
159
|
+
...(rateLimitResetAt !== undefined ? { rateLimitResetAt } : {}),
|
|
160
|
+
...(failureDetail ? { failureDetail } : {}),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Upstream-authored fields that never leave the request context. */
|
|
165
|
+
export const UPSTREAM_TEXT_FIELDS = ["upstreamError", "upstreamErrorCode", "upstreamErrorType", "upstreamRequestId"] as const;
|
|
166
|
+
|
|
167
|
+
type ProjectableEntry = ErrorDetailSource & {
|
|
168
|
+
attempts?: unknown; attemptNormalizationDropped?: unknown; responseServiceTier?: unknown; tierOutcome?: unknown;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
/** A tier outcome whose recorded response tier is a closed member (or absent); same object when unchanged. */
|
|
172
|
+
function boundedTierOutcome(outcome: unknown): unknown {
|
|
173
|
+
if (!outcome || typeof outcome !== "object" || !("responseServiceTier" in outcome)) return outcome;
|
|
174
|
+
const record = outcome as Record<string, unknown>;
|
|
175
|
+
const tier = boundedServiceTier(record.responseServiceTier);
|
|
176
|
+
if (tier === record.responseServiceTier) return outcome;
|
|
177
|
+
const { responseServiceTier: _dropped, ...rest } = record;
|
|
178
|
+
return tier === undefined ? rest : { ...rest, responseServiceTier: tier };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The live-row form of {@link errorDetailFor}: attach the proxy-owned facts and remove upstream text.
|
|
183
|
+
* Returns the same object when nothing changes, so callers that rely on identity keep it. Attempt
|
|
184
|
+
* codes outside the vocabulary are corrected, and upstream text fields removed, in place (attempts
|
|
185
|
+
* keep their identity too).
|
|
186
|
+
*/
|
|
187
|
+
export function projectErrorDetail<T extends ProjectableEntry>(entry: T): T {
|
|
188
|
+
if (Array.isArray(entry.attempts)) {
|
|
189
|
+
for (const attempt of entry.attempts as unknown[]) {
|
|
190
|
+
if (!attempt || typeof attempt !== "object") continue;
|
|
191
|
+
const record = attempt as Record<string, unknown>;
|
|
192
|
+
for (const field of UPSTREAM_TEXT_FIELDS) if (field in record) delete record[field];
|
|
193
|
+
if ("tierOutcome" in record) record.tierOutcome = boundedTierOutcome(record.tierOutcome);
|
|
194
|
+
if (typeof record.errorCode !== "string") continue;
|
|
195
|
+
const code = normalizeLogErrorCode(record.errorCode, typeof record.status === "number" ? record.status : undefined);
|
|
196
|
+
if (code !== record.errorCode) {
|
|
197
|
+
if (code === undefined) delete record.errorCode;
|
|
198
|
+
else record.errorCode = code;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const detail = errorDetailFor(entry);
|
|
203
|
+
const responseServiceTier = boundedServiceTier(entry.responseServiceTier);
|
|
204
|
+
const tierOutcome = boundedTierOutcome(entry.tierOutcome);
|
|
205
|
+
const unchanged = UPSTREAM_TEXT_FIELDS.every(field => entry[field as keyof ErrorDetailSource] === undefined)
|
|
206
|
+
&& entry.responseServiceTier === responseServiceTier && entry.tierOutcome === tierOutcome
|
|
207
|
+
&& entry.errorCode === detail.errorCode
|
|
208
|
+
&& entry.upstreamCondition === detail.upstreamCondition
|
|
209
|
+
&& entry.rateLimitResetAt === detail.rateLimitResetAt
|
|
210
|
+
&& entry.failureDetail === detail.failureDetail;
|
|
211
|
+
if (unchanged) return entry;
|
|
212
|
+
const out = { ...entry } as Record<string, unknown>;
|
|
213
|
+
// A non-enumerable marker does not survive a spread; carry it explicitly.
|
|
214
|
+
if (entry.attemptNormalizationDropped === true) out.attemptNormalizationDropped = true;
|
|
215
|
+
for (const field of UPSTREAM_TEXT_FIELDS) delete out[field];
|
|
216
|
+
if (responseServiceTier === undefined) delete out.responseServiceTier;
|
|
217
|
+
else out.responseServiceTier = responseServiceTier;
|
|
218
|
+
if (tierOutcome === undefined) delete out.tierOutcome;
|
|
219
|
+
else out.tierOutcome = tierOutcome;
|
|
220
|
+
for (const field of ["errorCode", "upstreamCondition", "rateLimitResetAt", "failureDetail"] as const) {
|
|
221
|
+
if (detail[field] === undefined) delete out[field];
|
|
222
|
+
else out[field] = detail[field];
|
|
223
|
+
}
|
|
224
|
+
return out as T;
|
|
225
|
+
}
|
package/src/usage/log.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import type { FailureDetail } from "../lib/failure-detail";
|
|
2
|
+
import { boundedModelIdentity, knownModelIdentity } from "../lib/model-identity";
|
|
3
|
+
import { boundedServiceTier } from "../lib/response-service-tier";
|
|
1
4
|
import { createHash, type Hash } from "node:crypto";
|
|
2
5
|
import { chmodSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, appendFileSync } from "node:fs";
|
|
3
6
|
import { join } from "node:path";
|
|
@@ -5,7 +8,7 @@ import { getConfigDir } from "../config";
|
|
|
5
8
|
import type { CodexAffinityMove, CodexAffinityReason } from "../codex/routing";
|
|
6
9
|
import { enforceAppOwnedMemoryBudget } from "../lib/app-owned-memory";
|
|
7
10
|
import { recordOwnedConfigPath } from "../lib/config-ownership";
|
|
8
|
-
import {
|
|
11
|
+
import { sanitizeLogMetadataString } from "../lib/redact";
|
|
9
12
|
import { usageDisplayTotalTokens } from "./totals";
|
|
10
13
|
import {
|
|
11
14
|
normalizePersistedJevDecision,
|
|
@@ -23,6 +26,8 @@ import { normalizeRouteDecisionTrace, type RouteDecisionTraceV1 } from "../routi
|
|
|
23
26
|
import { parseProtocolTraceV1, type ProtocolTraceV1 } from "../protocols/dto";
|
|
24
27
|
import { ACCOUNT_LOG_LABEL_RE, CODEX_ACCOUNT_LOG_LABEL_RE } from "../codex/account-label";
|
|
25
28
|
import { claudeCompatibilityReason, normalizeClaudeFeatureCodes, type ClaudeFeatureCode } from "../claude/compatibility";
|
|
29
|
+
import type { UpstreamCondition } from "../lib/upstream-condition";
|
|
30
|
+
import { errorDetailFor, normalizeLogErrorCode } from "./error-detail";
|
|
26
31
|
import type { CodexWsStageRecord, CodexWsTerminalEvent } from "../server/responses/codex-ws-wire";
|
|
27
32
|
import {
|
|
28
33
|
ATTEMPT_RECOVERY_KIND_ROSTER,
|
|
@@ -370,8 +375,17 @@ export interface PersistedUsageEntry {
|
|
|
370
375
|
*/
|
|
371
376
|
terminalStatus?: RequestTerminalStatus;
|
|
372
377
|
closeReason?: RequestCloseReason;
|
|
373
|
-
/**
|
|
378
|
+
/**
|
|
379
|
+
* Legacy input only: older rows carried upstream error text here. It is read once on load to
|
|
380
|
+
* derive upstreamCondition / rateLimitResetAt and is never written or returned.
|
|
381
|
+
*/
|
|
374
382
|
upstreamError?: string;
|
|
383
|
+
/** Proxy-classified upstream condition (src/lib/upstream-condition.ts); a closed enum. */
|
|
384
|
+
upstreamCondition?: UpstreamCondition;
|
|
385
|
+
/** Provider quota window end in epoch ms, derived server-side and bounded (src/usage/error-detail.ts). */
|
|
386
|
+
rateLimitResetAt?: number;
|
|
387
|
+
/** Proxy-authored failure text (src/server/request-log-failure-detail.ts), never upstream text. */
|
|
388
|
+
failureDetail?: FailureDetail;
|
|
375
389
|
/** Where the terminal/failure was observed; absent on historic rows. */
|
|
376
390
|
transportPhase?: "pre_headers" | "mid_stream" | "terminal_sse";
|
|
377
391
|
/** Whether the terminal came from upstream or a proxy-generated tail. */
|
|
@@ -507,10 +521,10 @@ export function isKnownTerminalSource(value: unknown): value is NonNullable<Pers
|
|
|
507
521
|
* call site and it never reached disk for exactly that reason.
|
|
508
522
|
*/
|
|
509
523
|
const KNOWN_AFFINITY_MOVES = new Set<NonNullable<PersistedUsageEntry["affinity"]>>([
|
|
510
|
-
"reused", "held", "detour", "rebound", "new_bind", "cleared",
|
|
524
|
+
"reused", "held", "detour", "rebound", "new_bind", "cleared", "unbound",
|
|
511
525
|
]);
|
|
512
526
|
const KNOWN_AFFINITY_REASONS = new Set<NonNullable<PersistedUsageEntry["affinityReason"]>>([
|
|
513
|
-
"healthy", "quota_headroom", "quota_refusal", "transient", "transient_hold_expired",
|
|
527
|
+
"healthy", "no_conversation", "request_owned", "quota_headroom", "quota_refusal", "transient", "transient_hold_expired",
|
|
514
528
|
"unusable", "paused", "plan_excluded", "credits_off", "cooldown", "quota_avoided", "generation",
|
|
515
529
|
"expired", "model_lane",
|
|
516
530
|
]);
|
|
@@ -672,7 +686,7 @@ function normalizeAttemptTierOutcome(raw: unknown): AttemptTierOutcome | null {
|
|
|
672
686
|
if ("responseServiceTier" in outcome && typeof outcome.responseServiceTier !== "string") return null;
|
|
673
687
|
if ("responseTierAuthoritative" in outcome && typeof outcome.responseTierAuthoritative !== "boolean") return null;
|
|
674
688
|
const wireValue = sanitizeLogMetadataString(outcome.wireValue);
|
|
675
|
-
const responseServiceTier =
|
|
689
|
+
const responseServiceTier = boundedServiceTier(outcome.responseServiceTier);
|
|
676
690
|
return {
|
|
677
691
|
...(outcome.canonical === "priority" ? { canonical: "priority" as const } : {}),
|
|
678
692
|
...(outcome.wireKind === null
|
|
@@ -750,6 +764,7 @@ function normalizeUsageAttempt(raw: unknown): PersistedUsageAttempt | null {
|
|
|
750
764
|
&& ATTEMPT_RECOVERY_WITHHELD.has(value as AttemptRecoveryWithheld),
|
|
751
765
|
))]
|
|
752
766
|
: [];
|
|
767
|
+
const attemptErrorCode = normalizeLogErrorCode(attempt.errorCode, attempt.status as number);
|
|
753
768
|
return {
|
|
754
769
|
ordinal: attempt.ordinal as number,
|
|
755
770
|
provider: attempt.provider,
|
|
@@ -781,7 +796,7 @@ function normalizeUsageAttempt(raw: unknown): PersistedUsageAttempt | null {
|
|
|
781
796
|
...(isNonNegativeFiniteNumber(attempt.totalTokens)
|
|
782
797
|
? { totalTokens: attempt.totalTokens }
|
|
783
798
|
: {}),
|
|
784
|
-
...(
|
|
799
|
+
...(attemptErrorCode ? { errorCode: attemptErrorCode } : {}),
|
|
785
800
|
...(isKnownCacheTelemetryProvenance(attempt.cacheProvenance)
|
|
786
801
|
? { cacheProvenance: attempt.cacheProvenance }
|
|
787
802
|
: {}),
|
|
@@ -896,19 +911,9 @@ function capMetadataString(s: string): string {
|
|
|
896
911
|
return s.length > MAX_METADATA_STRING_LEN ? s.slice(0, MAX_METADATA_STRING_LEN) : s;
|
|
897
912
|
}
|
|
898
913
|
|
|
899
|
-
|
|
900
|
-
/**
|
|
901
|
-
* An upstream model is an identifier, never free-form text to truncate into one. A value the
|
|
902
|
-
* secret redactor would change is dropped rather than logged, because credential-shaped text can
|
|
903
|
-
* fit the identifier alphabet.
|
|
904
|
-
*/
|
|
914
|
+
/** Served and resolved models on a row use the shared model-identity bound (src/lib/model-identity.ts). */
|
|
905
915
|
export function sanitizeServedModel(value: unknown): string | undefined {
|
|
906
|
-
return
|
|
907
|
-
&& value.length <= MAX_SERVED_MODEL_LENGTH
|
|
908
|
-
&& /^[A-Za-z0-9._:/@+-]+$/.test(value)
|
|
909
|
-
&& redactSecretString(value) === value
|
|
910
|
-
? value
|
|
911
|
-
: undefined;
|
|
916
|
+
return boundedModelIdentity(value);
|
|
912
917
|
}
|
|
913
918
|
|
|
914
919
|
/** The identity fields that decide whether a response model is ocx's own echo. */
|
|
@@ -941,28 +946,56 @@ export function isClientSelectorEcho(source: ServedModelEchoSource, served: stri
|
|
|
941
946
|
|
|
942
947
|
/** Record a response-body model as the served model when it is a real upstream observation. */
|
|
943
948
|
export function recordObservedServedModel(
|
|
944
|
-
target: ServedModelEchoSource & { servedModel?: string; resolvedModel?: string; preserveResolvedModelFromRoute?: boolean },
|
|
949
|
+
target: ServedModelEchoSource & { servedModel?: string; resolvedModel?: string; preserveResolvedModelFromRoute?: boolean; attempts?: unknown },
|
|
945
950
|
value: unknown,
|
|
946
951
|
): void {
|
|
947
|
-
const servedModel =
|
|
952
|
+
const servedModel = knownModelIdentity(value, routeKnownModels(target), target.provider);
|
|
948
953
|
if (!servedModel || isClientSelectorEcho(target, servedModel)) return;
|
|
949
954
|
target.servedModel = servedModel;
|
|
950
955
|
if (!target.preserveResolvedModelFromRoute) target.resolvedModel = servedModel;
|
|
951
956
|
}
|
|
952
957
|
|
|
958
|
+
/**
|
|
959
|
+
* Model ids a row's own route already names, which an upstream-reported served or resolved model
|
|
960
|
+
* must equal to be recorded: the routed model (also without its provider prefix), the wire model,
|
|
961
|
+
* the requested model and alias, and each attempt's target. The bundled Codex catalog is checked
|
|
962
|
+
* by {@link knownModelIdentity} itself.
|
|
963
|
+
*/
|
|
964
|
+
export function routeKnownModels(source: ServedModelEchoSource & { attempts?: unknown }): string[] {
|
|
965
|
+
const known: string[] = [];
|
|
966
|
+
const add = (value: unknown) => { if (typeof value === "string" && value) known.push(value); };
|
|
967
|
+
add(source.model);
|
|
968
|
+
if (typeof source.model === "string" && source.model.includes("/")) add(source.model.slice(source.model.indexOf("/") + 1));
|
|
969
|
+
add(source.wireModel);
|
|
970
|
+
add(source.requestedModel);
|
|
971
|
+
add(source.requestedAlias);
|
|
972
|
+
if (Array.isArray(source.attempts)) {
|
|
973
|
+
for (const attempt of source.attempts as unknown[]) {
|
|
974
|
+
if (attempt && typeof attempt === "object") {
|
|
975
|
+
add((attempt as { model?: unknown }).model);
|
|
976
|
+
add((attempt as { wireModel?: unknown }).wireModel);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
return known;
|
|
981
|
+
}
|
|
982
|
+
|
|
953
983
|
/**
|
|
954
984
|
* Model identity fields for a log row. The served model is sanitized, and a resolvedModel that
|
|
955
985
|
* only echoed a dropped served model is dropped with it, so the rejected value cannot survive
|
|
956
986
|
* under the other name. A client-selector echo is dropped the same way, which also repairs
|
|
957
|
-
* rows persisted before the echo was filtered at capture.
|
|
987
|
+
* rows persisted before the echo was filtered at capture. Both are kept only when they equal a
|
|
988
|
+
* model id the row's route already names (or the bundled catalog pins); see {@link knownModelIdentity}.
|
|
958
989
|
*/
|
|
959
|
-
export function modelIdentityLogFields(source: ServedModelEchoSource & { resolvedModel?: string; servedModel?: unknown }): {
|
|
990
|
+
export function modelIdentityLogFields(source: ServedModelEchoSource & { resolvedModel?: string; servedModel?: unknown; attempts?: unknown }): {
|
|
960
991
|
resolvedModel?: string; servedModel?: string; wireModel?: string;
|
|
961
992
|
} {
|
|
962
|
-
const
|
|
993
|
+
const known = routeKnownModels(source);
|
|
994
|
+
const sanitized = knownModelIdentity(source.servedModel, known, source.provider);
|
|
963
995
|
const servedModel = isClientSelectorEcho(source, sanitized) ? undefined : sanitized;
|
|
996
|
+
// The resolved model passes the same validator on its own; it also leaves with a dropped served echo.
|
|
964
997
|
const resolvedModel = source.servedModel !== undefined && source.resolvedModel === source.servedModel && !servedModel
|
|
965
|
-
? undefined : source.resolvedModel;
|
|
998
|
+
? undefined : knownModelIdentity(source.resolvedModel, known, source.provider);
|
|
966
999
|
return {
|
|
967
1000
|
...(resolvedModel ? { resolvedModel } : {}),
|
|
968
1001
|
...(servedModel ? { servedModel } : {}),
|
|
@@ -979,7 +1012,7 @@ function normalizeUsageEntry(entry: PersistedUsageEntry): PersistedUsageEntry {
|
|
|
979
1012
|
const attempts = normalizedAttempts(entry.attempts);
|
|
980
1013
|
const tierOutcome = entry.tierOutcome ? normalizeAttemptTierOutcome(entry.tierOutcome) : undefined;
|
|
981
1014
|
const callerServiceTier = sanitizeLogMetadataString(entry.callerServiceTier);
|
|
982
|
-
const responseServiceTier =
|
|
1015
|
+
const responseServiceTier = boundedServiceTier(entry.responseServiceTier);
|
|
983
1016
|
const shadowCallRewrittenFrom = sanitizeLogMetadataString(entry.shadowCallRewrittenFrom);
|
|
984
1017
|
const { servedModel, resolvedModel } = modelIdentityLogFields(entry);
|
|
985
1018
|
const claudeCompatibility = normalizeClaudeCompatibilityUsageLog(entry.claudeCompatibility);
|
|
@@ -1086,13 +1119,13 @@ function normalizeUsageEntry(entry: PersistedUsageEntry): PersistedUsageEntry {
|
|
|
1086
1119
|
...(affinity ? { affinity } : {}),
|
|
1087
1120
|
...(affinityReason ? { affinityReason } : {}),
|
|
1088
1121
|
...(conversationStateScrub ? { conversationStateScrub } : {}),
|
|
1089
|
-
|
|
1122
|
+
// Closed code, classified condition and numeric reset only; upstream text is never kept.
|
|
1123
|
+
...errorDetailFor(entry),
|
|
1090
1124
|
// Validated rather than copied on truthiness, like the inbound protocol and transport phase
|
|
1091
1125
|
// above. Harmless while these were only rendered; not harmless once the terminal status is
|
|
1092
1126
|
// a grouping-key slot, because the string is assembled from an upstream frame.
|
|
1093
1127
|
...(isRequestTerminalStatus(entry.terminalStatus) ? { terminalStatus: entry.terminalStatus } : {}),
|
|
1094
1128
|
...(isRequestCloseReason(entry.closeReason) ? { closeReason: entry.closeReason } : {}),
|
|
1095
|
-
...(entry.upstreamError ? { upstreamError: entry.upstreamError } : {}),
|
|
1096
1129
|
...(routeDecision ? { routeDecision } : {}),
|
|
1097
1130
|
...(jevDecision ? { jevDecision } : {}),
|
|
1098
1131
|
...(claudeCompatibility ? { claudeCompatibility } : {}),
|