@bitkyc08/opencodex 2.94.0 → 2.95.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.
Files changed (249) hide show
  1. package/gui/dist/assets/App-8yedBkhm.js +58 -0
  2. package/gui/dist/assets/App-B4j-Txmb.css +1 -0
  3. package/gui/dist/assets/{Tray-CZatQdoF.js → Tray-erSMzxPG.js} +1 -1
  4. package/gui/dist/assets/index-D7DCm5eQ.js +94 -0
  5. package/gui/dist/assets/quota-summary-BK4VuQNc.js +1 -0
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/anthropic.ts +10 -3
  9. package/src/adapters/command-code-project-context.ts +3 -3
  10. package/src/adapters/kiro/adapter.ts +4 -1
  11. package/src/adapters/kiro/stream.ts +1 -0
  12. package/src/adapters/kiro-events.ts +1 -0
  13. package/src/adapters/openai-chat/messages.ts +20 -7
  14. package/src/adapters/openai-chat/passthrough.ts +4 -2
  15. package/src/adapters/openai-chat/single-system.ts +24 -0
  16. package/src/adapters/openai-responses/muse-tool-catalog.ts +87 -0
  17. package/src/adapters/openai-responses/passthrough.ts +42 -7
  18. package/src/adapters/openai-responses/prompt-cache.ts +3 -1
  19. package/src/adapters/openai-responses/request-strips.ts +23 -4
  20. package/src/adapters/openai-responses/tool-output-recovery.ts +21 -8
  21. package/src/adapters/openai-responses/tool-schema.ts +20 -8
  22. package/src/adapters/opencode-go-additional-tools.ts +39 -6
  23. package/src/adapters/routed-agent-messages.ts +3 -0
  24. package/src/adapters/xai-web-search.ts +6 -3
  25. package/src/adapters/zed-additional-tools.ts +7 -7
  26. package/src/adapters/zed.ts +1 -6
  27. package/src/advisor/consult.ts +22 -10
  28. package/src/advisor/runtime.ts +10 -4
  29. package/src/bridge/max-output-completion.ts +41 -0
  30. package/src/bridge/response-json.ts +9 -4
  31. package/src/bridge/sse.ts +13 -2
  32. package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +5 -0
  33. package/src/chatgpt/app-server-shim/launcher.ts +40 -6
  34. package/src/claude/compatibility.ts +5 -1
  35. package/src/claude/desktop-3p.ts +27 -6
  36. package/src/claude/desktop-model-visibility.ts +141 -0
  37. package/src/claude/desktop-remote-store-io.ts +8 -8
  38. package/src/claude/inbound-content-options.ts +11 -1
  39. package/src/claude/intercept/proxy-auth.ts +16 -16
  40. package/src/cli/account-main.ts +3 -2
  41. package/src/cli/capabilities-provider-models.ts +7 -0
  42. package/src/cli/chatgpt-command.ts +1 -1
  43. package/src/cli/codex-launcher.ts +20 -8
  44. package/src/cli/codex-shim-autorestore.ts +19 -1
  45. package/src/cli/dispatch.ts +6 -6
  46. package/src/cli/doctor.ts +5 -5
  47. package/src/cli/index.ts +4 -9
  48. package/src/cli/init.ts +2 -2
  49. package/src/cli/internal-command.ts +29 -2
  50. package/src/cli/provider-cc-switch-import.ts +185 -0
  51. package/src/cli/provider.ts +5 -0
  52. package/src/cli/registry.ts +1 -0
  53. package/src/cli/restart-scope.ts +2 -2
  54. package/src/cli/root.ts +6 -6
  55. package/src/cli/stop-approval.ts +15 -1
  56. package/src/cli/v2.ts +69 -19
  57. package/src/client/machine-api.ts +2 -2
  58. package/src/clients/config-export.ts +14 -3
  59. package/src/codex/account-cooldown-response.ts +18 -0
  60. package/src/codex/app-server-restart-service.ts +2 -2
  61. package/src/codex/auth-api/login-flow.ts +2 -2
  62. package/src/codex/auth-api/pool-quota-probe.ts +2 -2
  63. package/src/codex/auth-context.ts +4 -4
  64. package/src/codex/catalog/bundled.ts +10 -3
  65. package/src/codex/catalog/metadata.ts +4 -5
  66. package/src/codex/catalog/native-omission.ts +28 -0
  67. package/src/codex/catalog/native-template.ts +58 -0
  68. package/src/codex/catalog/parsing.ts +3 -29
  69. package/src/codex/catalog/provider-models.ts +2 -1
  70. package/src/codex/catalog/retained-sync.ts +15 -5
  71. package/src/codex/catalog/write-audit.ts +18 -18
  72. package/src/codex/cli-install-provenance.ts +46 -45
  73. package/src/codex/cli-update-artifacts.ts +8 -6
  74. package/src/codex/cli-update-job-store-windows.ts +99 -27
  75. package/src/codex/cli-update-job-worker.ts +3 -11
  76. package/src/codex/cli-update-recovery.ts +54 -8
  77. package/src/codex/cli-update-selection-gate.ts +74 -4
  78. package/src/codex/cli-windows-plan-provenance.ts +37 -19
  79. package/src/codex/codex-home-owner.ts +9 -8
  80. package/src/codex/convergence.ts +13 -3
  81. package/src/codex/coordinator-doctor.ts +14 -8
  82. package/src/codex/desktop-app/handoff.ts +1 -1
  83. package/src/codex/desktop-app-restart.ts +11 -1
  84. package/src/codex/exec-boundary.ts +26 -5
  85. package/src/codex/history-provider.ts +11 -10
  86. package/src/codex/inject/bounded-config-reader.ts +14 -13
  87. package/src/codex/main-account.ts +6 -6
  88. package/src/codex/native-main-lock-file.ts +13 -12
  89. package/src/codex/native-residue.ts +18 -14
  90. package/src/codex/orca-auth-source.ts +8 -7
  91. package/src/codex/quota-types.ts +5 -0
  92. package/src/codex/quota.ts +49 -7
  93. package/src/codex/role-auto-assign.ts +50 -26
  94. package/src/codex/role-capability.ts +160 -0
  95. package/src/codex/role-sizing.ts +24 -6
  96. package/src/codex/routing/cooldown-math.ts +3 -2
  97. package/src/codex/runtime.ts +43 -3
  98. package/src/codex/shim-fingerprint.ts +11 -9
  99. package/src/codex/shim-inspect.ts +3 -2
  100. package/src/codex/shim-restore-lock.ts +11 -14
  101. package/src/codex/shim-state-file.ts +22 -14
  102. package/src/codex/shim-wrapper-write.ts +7 -6
  103. package/src/codex/shim.ts +25 -2
  104. package/src/codex/transition-state.ts +5 -4
  105. package/src/combos/failover.ts +43 -4
  106. package/src/config/atomic-write.ts +38 -7
  107. package/src/config/diagnostics.ts +3 -0
  108. package/src/config/initialize.ts +6 -6
  109. package/src/config/load-degrade.ts +2 -0
  110. package/src/config/process-state.ts +23 -5
  111. package/src/config/salvage.ts +1 -0
  112. package/src/config/schema/config-schema.ts +29 -1
  113. package/src/config/schema/leaf-validators.ts +7 -0
  114. package/src/config/schema/workflow-budget.ts +43 -0
  115. package/src/config/tracked-runtime-inspection.ts +188 -0
  116. package/src/generated/compatibility-version.json +313 -213
  117. package/src/integrations/aside-profile-context.ts +1 -1
  118. package/src/integrations/droid-settings.ts +4 -4
  119. package/src/integrations/hermes-profiles.ts +3 -3
  120. package/src/lib/bounded-file-read.ts +3 -9
  121. package/src/lib/bun-runtime-preflight.ts +9 -8
  122. package/src/lib/file-identity.ts +15 -0
  123. package/src/lib/local-chat-completion.ts +8 -6
  124. package/src/lib/local-destinations.ts +32 -3
  125. package/src/lib/redact-folding.ts +9 -0
  126. package/src/lib/spend-pool-alias-validation.ts +6 -6
  127. package/src/lib/state-store-registrations.ts +2 -0
  128. package/src/lib/test-home-guard.ts +37 -9
  129. package/src/lib/windows-secret-acl.ts +47 -29
  130. package/src/lib/workflow-budget-config.ts +39 -0
  131. package/src/local-credentials/generation.ts +6 -2
  132. package/src/local-credentials/inventory.ts +132 -8
  133. package/src/messaging/remote-forward-failure.ts +35 -0
  134. package/src/messaging/remote-ports.ts +27 -5
  135. package/src/messaging/remote-process.ts +30 -4
  136. package/src/messaging/remote-tunnels.ts +80 -15
  137. package/src/oauth/antigravity-discovery-diagnostics.ts +65 -0
  138. package/src/oauth/google-antigravity.ts +23 -10
  139. package/src/oauth/index.ts +2 -0
  140. package/src/oauth/kiro-device-login.ts +87 -30
  141. package/src/oauth/kiro-iam-identity-center.ts +107 -0
  142. package/src/oauth/store.ts +9 -7
  143. package/src/providers/account-quota-disk.ts +18 -4
  144. package/src/providers/cc-switch-import-bytes.ts +991 -0
  145. package/src/providers/cc-switch-import-source.ts +1083 -0
  146. package/src/providers/cc-switch-import.ts +942 -0
  147. package/src/providers/derive.ts +6 -0
  148. package/src/providers/model-discovery-diagnostic.ts +4 -0
  149. package/src/providers/model-discovery.ts +4 -4
  150. package/src/providers/model-rename-fields.ts +2 -0
  151. package/src/providers/model-rename-migration.ts +41 -6
  152. package/src/providers/quota/report-cache.ts +17 -4
  153. package/src/providers/quota.ts +2 -2
  154. package/src/providers/reasoning-metadata.ts +31 -15
  155. package/src/providers/registry/entries-core.ts +1 -1
  156. package/src/providers/registry/entries-extended.ts +1 -1
  157. package/src/providers/registry/model-ids.ts +1 -0
  158. package/src/providers/registry/model-seeds.ts +2 -1
  159. package/src/providers/registry/types.ts +3 -1
  160. package/src/providers/resolved-model-policy.ts +2 -2
  161. package/src/providers/routed-config.ts +2 -0
  162. package/src/providers/stale-model-roster-migration.ts +5 -1
  163. package/src/providers/xai-transport.ts +4 -4
  164. package/src/remote-control/workspace-codex-runtime.ts +2 -2
  165. package/src/remote-control/workspace-executor.ts +14 -13
  166. package/src/responses/custom-tool-compat.ts +2 -1
  167. package/src/responses/item-provenance.ts +79 -0
  168. package/src/responses/namespace-tool-compat.ts +21 -3
  169. package/src/router.ts +21 -2
  170. package/src/routing/analytics.ts +3 -5
  171. package/src/routing/fallback-policy.ts +7 -3
  172. package/src/routing/health.ts +5 -3
  173. package/src/routing/history/build-file.ts +6 -0
  174. package/src/routing/history/indexer.ts +158 -31
  175. package/src/routing/history/ingest.ts +1 -1
  176. package/src/routing/history/integrity.ts +208 -0
  177. package/src/routing/history/rebuild-job.ts +20 -6
  178. package/src/routing/history/rebuild-protocol.ts +2 -1
  179. package/src/routing/history/rebuild-worker.ts +18 -0
  180. package/src/routing/history/sqlite-errors.ts +9 -0
  181. package/src/server/admission-model-scope.ts +21 -4
  182. package/src/server/advisor-admission-scope.ts +29 -0
  183. package/src/server/auth-cors.ts +5 -2
  184. package/src/server/capture-admission-policy.ts +91 -0
  185. package/src/server/chat-completions.ts +33 -7
  186. package/src/server/claude-messages.ts +90 -2
  187. package/src/server/codex-model-list.ts +2 -1
  188. package/src/server/configured-credentials.ts +5 -0
  189. package/src/server/index/serve-options.ts +12 -2
  190. package/src/server/index/websocket-handler.ts +3 -0
  191. package/src/server/management/agent-settings-routes.ts +34 -9
  192. package/src/server/management/codex-agent-role-routes.ts +1 -0
  193. package/src/server/management/codex-role-auto-assign.ts +50 -6
  194. package/src/server/management/config-routes.ts +15 -4
  195. package/src/server/management/context.ts +3 -0
  196. package/src/server/management/native-integration-routes.ts +22 -0
  197. package/src/server/management/oauth-account-routes.ts +20 -4
  198. package/src/server/management/provider-overwrite-carry.ts +21 -0
  199. package/src/server/management/provider-routes.ts +3 -1
  200. package/src/server/management/route-registry.ts +2 -0
  201. package/src/server/management/shared.ts +17 -1
  202. package/src/server/management/workflow-budget-routes.ts +70 -3
  203. package/src/server/messages-native-eligibility.ts +6 -5
  204. package/src/server/messages-native-scope.ts +6 -1
  205. package/src/server/messages-shared.ts +57 -17
  206. package/src/server/persistent-gui-session.ts +4 -4
  207. package/src/server/request-log.ts +30 -2
  208. package/src/server/responses/adapter-delivery.ts +4 -0
  209. package/src/server/responses/advisor-plan-slot.ts +4 -0
  210. package/src/server/responses/advisor-slot.ts +73 -46
  211. package/src/server/responses/codex-auth-error.ts +5 -1
  212. package/src/server/responses/combo-required-tool-contract.ts +27 -0
  213. package/src/server/responses/compact.ts +4 -1
  214. package/src/server/responses/core-combo-failure.ts +2 -0
  215. package/src/server/responses/core-combo.ts +66 -5
  216. package/src/server/responses/core-lifetime.ts +4 -0
  217. package/src/server/responses/core-options.ts +9 -0
  218. package/src/server/responses/core.ts +2 -0
  219. package/src/server/responses/jev-model-invoke.ts +4 -2
  220. package/src/server/responses/passthrough-dispatch.ts +5 -4
  221. package/src/server/responses/policy-fallback.ts +2 -0
  222. package/src/server/responses/request-prepare.ts +4 -5
  223. package/src/server/responses/request-send-budget.ts +2 -1
  224. package/src/server/responses/request-sidecar-auth.ts +1 -0
  225. package/src/server/responses/request-transport.ts +2 -3
  226. package/src/server/responses/run-turn-execution.ts +4 -0
  227. package/src/server/responses/sidecar-execution.ts +21 -5
  228. package/src/server/responses-snapshot-repair.ts +18 -4
  229. package/src/server/responses-undeclared-tool-guard.ts +4 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/service/state-lock.ts +12 -11
  232. package/src/service-manager-probe.ts +53 -8
  233. package/src/types/admission-policy.ts +13 -0
  234. package/src/types/config.ts +25 -0
  235. package/src/types/provider.ts +10 -0
  236. package/src/types/request.ts +7 -0
  237. package/src/types.ts +1 -0
  238. package/src/update/job.ts +20 -0
  239. package/src/update/worker-launch.ts +71 -1
  240. package/src/usage/log.ts +25 -4
  241. package/src/vision/index.ts +2 -0
  242. package/src/vision/plan.ts +4 -0
  243. package/src/vision/routed-describe.ts +38 -23
  244. package/src/web-search/loop.ts +104 -9
  245. package/src/web-search/parse.ts +10 -2
  246. package/gui/dist/assets/App-DMps4OLk.css +0 -1
  247. package/gui/dist/assets/App-DmvwlhQq.js +0 -58
  248. package/gui/dist/assets/index-3EPO_KbX.js +0 -94
  249. package/gui/dist/assets/quota-summary-BHvWg9mi.js +0 -1
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Measured capability per task domain, so role auto-assign can tier candidates by what they score
3
+ * instead of what they cost. Artificial Analysis is read live when configured:
4
+ *
5
+ * - Artificial Analysis (https://artificialanalysis.ai/api-reference), when the user configures
6
+ * their own API key. Its terms allow that user's internal use with attribution and forbid
7
+ * redistributing the raw data, so its scores never leave this process.
8
+ *
9
+ * Each domain maps to one published index. The source names a model by display name
10
+ * with one row per reasoning setting ("Claude Opus 5.5 (High)"); capabilityModelKey drops the
11
+ * setting and folds the rest to a slug, which matches a catalog id once its provider prefix is
12
+ * gone ("cpa/claude-opus-5-5"). The best setting's score stands for the model, since a role can
13
+ * be given that setting. A candidate with no row is unmeasured, never guessed.
14
+ */
15
+ import { resolveProviderApiKey } from "../providers/api-key-resolve";
16
+ import type { OcxConfig } from "../types";
17
+ import type { SizingDomain } from "./role-sizing";
18
+
19
+ export interface CapabilitySource {
20
+ readonly name: string;
21
+ readonly url: string;
22
+ readonly license: string;
23
+ /** Whether the terms let a response carry the raw scores. */
24
+ readonly redistributable: boolean;
25
+ }
26
+
27
+ export const ARTIFICIAL_ANALYSIS_SOURCE: CapabilitySource = {
28
+ name: "Artificial Analysis",
29
+ url: "https://artificialanalysis.ai",
30
+ license: "Artificial Analysis API terms: internal use, attribution required, no redistribution",
31
+ redistributable: false,
32
+ };
33
+
34
+ const ARTIFICIAL_ANALYSIS_URL = "https://artificialanalysis.ai/api/v2/data/llms/models";
35
+
36
+ /** Per domain, the indexes to read in order; the first one the response carries is used. */
37
+ const INTELLIGENCE_INDEX = "artificial_analysis_intelligence_index";
38
+ const ARTIFICIAL_ANALYSIS_INDEXES: Record<SizingDomain, readonly string[]> = {
39
+ coding: ["artificial_analysis_coding_index", INTELLIGENCE_INDEX],
40
+ agentic: ["artificial_analysis_agentic_index", INTELLIGENCE_INDEX],
41
+ reasoning: ["artificial_analysis_math_index", INTELLIGENCE_INDEX],
42
+ writing: [INTELLIGENCE_INDEX],
43
+ knowledge: [INTELLIGENCE_INDEX],
44
+ general: [INTELLIGENCE_INDEX],
45
+ };
46
+
47
+ const FETCH_TIMEOUT_MS = 30_000;
48
+ /** Each published table is under 1 MB today; 16 MB leaves room to grow and still bounds memory. */
49
+ export const MAX_TABLE_BYTES = 16 * 1024 * 1024;
50
+
51
+ export interface CapabilityTable {
52
+ readonly source: CapabilitySource | null;
53
+ readonly publishedAt: string | null;
54
+ /** Per domain: model key to its best published score. */
55
+ readonly domains: Partial<Record<SizingDomain, ReadonlyMap<string, number>>>;
56
+ /** Why a configured source was passed over for this one. */
57
+ readonly fallbackReason?: string;
58
+ }
59
+
60
+ export type LoadCapability = (config: OcxConfig) => Promise<CapabilityTable>;
61
+
62
+ export function capabilityModelKey(name: string): string {
63
+ return name.toLowerCase().replace(/\([^)]*\)/g, " ").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
64
+ }
65
+
66
+ export function candidateModelKey(slug: string): string {
67
+ return capabilityModelKey(slug.slice(slug.lastIndexOf("/") + 1));
68
+ }
69
+
70
+ function keepBest(scores: Map<string, number>, key: string, value: number) {
71
+ if (key) scores.set(key, Math.max(value, scores.get(key) ?? -Infinity));
72
+ }
73
+
74
+ export function capabilityTableFromArtificialAnalysis(body: unknown): CapabilityTable {
75
+ const rows = (body as { data?: unknown } | null)?.data;
76
+ if (!Array.isArray(rows)) throw new Error("Artificial Analysis returned no model list");
77
+ const domains: Partial<Record<SizingDomain, Map<string, number>>> = {};
78
+ for (const [domain, indexes] of Object.entries(ARTIFICIAL_ANALYSIS_INDEXES) as [SizingDomain, readonly string[]][]) {
79
+ for (const index of indexes) {
80
+ const scores = new Map<string, number>();
81
+ for (const row of rows as Record<string, unknown>[]) {
82
+ const value = (row?.evaluations as Record<string, unknown> | undefined)?.[index];
83
+ if (typeof value !== "number" || !Number.isFinite(value)) continue;
84
+ if (typeof row.name === "string") keepBest(scores, capabilityModelKey(row.name), value);
85
+ if (typeof row.slug === "string") keepBest(scores, capabilityModelKey(row.slug), value);
86
+ }
87
+ if (scores.size > 0) {
88
+ domains[domain] = scores;
89
+ break;
90
+ }
91
+ }
92
+ }
93
+ return { source: ARTIFICIAL_ANALYSIS_SOURCE, publishedAt: null, domains };
94
+ }
95
+
96
+ /** The body's bytes, refused once they pass maxBytes, whatever the transport declared. */
97
+ export async function readBoundedBytes(response: Response, maxBytes: number): Promise<ArrayBuffer> {
98
+ const chunks: Uint8Array[] = [];
99
+ let length = 0;
100
+ const reader = response.body?.getReader();
101
+ if (!reader) return new ArrayBuffer(0);
102
+ for (;;) {
103
+ const { done, value } = await reader.read();
104
+ if (done) break;
105
+ if (length + value.byteLength > maxBytes) {
106
+ await reader.cancel();
107
+ throw new Error("response exceeded byte bound");
108
+ }
109
+ chunks.push(value);
110
+ length += value.byteLength;
111
+ }
112
+ const out = new Uint8Array(length);
113
+ let offset = 0;
114
+ for (const chunk of chunks) {
115
+ out.set(chunk, offset);
116
+ offset += chunk.byteLength;
117
+ }
118
+ return out.buffer;
119
+ }
120
+
121
+ export async function fetchArtificialAnalysisTable(apiKey: string, fetchImpl: typeof fetch = fetch): Promise<CapabilityTable> {
122
+ const response = await fetchImpl(ARTIFICIAL_ANALYSIS_URL, {
123
+ redirect: "error",
124
+ headers: { "x-api-key": apiKey },
125
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
126
+ });
127
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
128
+ const bytes = await readBoundedBytes(response, MAX_TABLE_BYTES);
129
+ return capabilityTableFromArtificialAnalysis(JSON.parse(new TextDecoder().decode(bytes)));
130
+ }
131
+
132
+ /** One fetch per period key; a failed fetch is forgotten so the next request retries. */
133
+ function periodCache() {
134
+ let slot: { key: string; table: Promise<CapabilityTable> } | null = null;
135
+ return (key: string, fetchTable: () => Promise<CapabilityTable>): Promise<CapabilityTable> => {
136
+ if (slot?.key === key) return slot.table;
137
+ const table = fetchTable();
138
+ slot = { key, table };
139
+ table.catch(() => { if (slot?.table === table) slot = null; });
140
+ return table;
141
+ };
142
+ }
143
+
144
+ const artificialAnalysisCache = periodCache();
145
+
146
+ /**
147
+ * Artificial Analysis when the user's key resolves, read once per UTC day to stay inside the
148
+ * free tier's daily request quota. Absent or unavailable scores leave price ranking in charge.
149
+ */
150
+ export const loadCapabilityTable: LoadCapability = async config => {
151
+ const now = new Date().toISOString();
152
+ const unavailable = (fallbackReason: string): CapabilityTable => ({ source: null, publishedAt: null, domains: {}, fallbackReason });
153
+ const apiKey = resolveProviderApiKey(config.codexRoleCapability?.artificialAnalysis?.apiKey)?.trim();
154
+ if (!apiKey) return unavailable("benchmark data was unavailable: no Artificial Analysis key is configured");
155
+ try {
156
+ return await artificialAnalysisCache(`${now.slice(0, 10)} ${apiKey}`, () => fetchArtificialAnalysisTable(apiKey));
157
+ } catch {
158
+ return unavailable("Artificial Analysis could not be read");
159
+ }
160
+ };
@@ -43,6 +43,10 @@ export type SizingTier = typeof SIZING_TIERS[number];
43
43
  export const SIZING_EFFORTS = ["glance", "measured", "thorough", "exhaustive"] as const;
44
44
  export type SizingEffort = typeof SIZING_EFFORTS[number];
45
45
 
46
+ /** Task domains, the kind of capability a tier is measured in. A label, never a model or a vendor. */
47
+ export const SIZING_DOMAINS = ["coding", "agentic", "reasoning", "writing", "knowledge", "general"] as const;
48
+ export type SizingDomain = typeof SIZING_DOMAINS[number];
49
+
46
50
  const MAX_FIELD_CHARS = 400;
47
51
 
48
52
  export const ROLE_SIZING_SYSTEM_PROMPT = [
@@ -66,6 +70,15 @@ export const ROLE_SIZING_SYSTEM_PROMPT = [
66
70
  "or a strong model needs only a quick call. Effort buys deliberation, never capability, and more",
67
71
  "effort is not more correct.",
68
72
  "",
73
+ "Task domain names the kind of capability the tier is measured in. It sizes nothing; it tells the",
74
+ "mapping which measured strength matters, because models of one price class differ by domain:",
75
+ "- coding: writing, changing, or reviewing code in a repository.",
76
+ "- agentic: long multi-step tool use, where the work is completing a run of actions without derailing.",
77
+ "- reasoning: math, logic, planning, or analysis whose answer is derived rather than looked up.",
78
+ "- writing: prose meant for a reader: documents, messages, copy.",
79
+ "- knowledge: research and factual recall across sources.",
80
+ "- general: none of the above dominates. Pick it rather than guess.",
81
+ "",
69
82
  "Assess risk and complexity once for both dials:",
70
83
  "- file, module, or ownership boundary crossing;",
71
84
  "- reversibility and blast radius;",
@@ -86,8 +99,8 @@ export const ROLE_SIZING_SYSTEM_PROMPT = [
86
99
  "- Use only the neutral words above. Do not name concrete model products, vendors, versions, or vendor effort levels anywhere in the answer.",
87
100
  "",
88
101
  "Answer with one JSON object and nothing else, no prose and no code fence:",
89
- '{"roles":{"<role name>":{"tier":"fast|standard|frontier","effort":"glance|measured|thorough|exhaustive","rationale":"<one sentence covering both dials>","move_up_if":"<signals that would justify a stronger tier or higher effort>","move_down_if":"<signals that would justify a cheaper tier or lower effort>"}}}',
90
- "Include every role you were given, keyed by its exact name, with exactly those five fields.",
102
+ '{"roles":{"<role name>":{"tier":"fast|standard|frontier","effort":"glance|measured|thorough|exhaustive","domain":"coding|agentic|reasoning|writing|knowledge|general","rationale":"<one sentence covering both dials>","move_up_if":"<signals that would justify a stronger tier or higher effort>","move_down_if":"<signals that would justify a cheaper tier or lower effort>"}}}',
103
+ "Include every role you were given, keyed by its exact name, with exactly those six fields.",
91
104
  ].join("\n");
92
105
 
93
106
  /**
@@ -105,6 +118,7 @@ export const DELEGATED_WORK_SIZING_SYSTEM_PROMPT = [
105
118
  export interface RoleSizing {
106
119
  readonly tier: SizingTier;
107
120
  readonly effort: SizingEffort;
121
+ readonly domain: SizingDomain;
108
122
  readonly rationale: string;
109
123
  readonly moveUpIf: string;
110
124
  readonly moveDownIf: string;
@@ -167,13 +181,16 @@ function validateEntry(entry: unknown): RoleSizingOutcome {
167
181
  const fields = entry as Record<string, unknown>;
168
182
  if (!isMember(SIZING_TIERS, fields.tier)) return { unsized: "the sizing answer has no valid tier" };
169
183
  if (!isMember(SIZING_EFFORTS, fields.effort)) return { unsized: "the sizing answer has no valid effort" };
184
+ // A missing or unknown domain still sizes the role on the overall scale: the domain only picks
185
+ // which measured capability ranks the candidates, and "general" is the rubric's own no-signal answer.
186
+ const domain = isMember(SIZING_DOMAINS, fields.domain) ? fields.domain : "general";
170
187
  const rationale = oneLine(fields.rationale);
171
188
  const moveUpIf = oneLine(fields.move_up_if);
172
189
  const moveDownIf = oneLine(fields.move_down_if);
173
190
  if (rationale === null || moveUpIf === null || moveDownIf === null) {
174
191
  return { unsized: "the sizing answer is missing a rationale or a move trigger" };
175
192
  }
176
- return { sizing: { tier: fields.tier, effort: fields.effort, rationale, moveUpIf, moveDownIf } };
193
+ return { sizing: { tier: fields.tier, effort: fields.effort, domain, rationale, moveUpIf, moveDownIf } };
177
194
  }
178
195
 
179
196
  const CODE_FENCE = /^\x60{3}(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\x60{3}$/i;
@@ -183,9 +200,10 @@ const CODE_FENCE = /^\x60{3}(?:json)?[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\x60{3}$/i;
183
200
  *
184
201
  * The answer must be one JSON object of the shape the rubric asks for. Two leniencies, both for
185
202
  * content the mapping never reads: a single surrounding code fence, which models add out of habit,
186
- * and keys beyond the five fields in a role's entry, which are ignored. Every one of the five must
187
- * still be present and valid. Anything else wrong marks the affected role, or every role when the
188
- * whole answer is unusable, as unsized with the reason.
203
+ * and keys beyond the six fields in a role's entry, which are ignored. Tier, effort, rationale and
204
+ * both move triggers must still be present and valid; a missing domain falls back to "general".
205
+ * Anything else wrong marks the affected role, or every role when the whole answer is unusable,
206
+ * as unsized with the reason.
189
207
  */
190
208
  export function parseRoleSizingResponse(text: string, roles: readonly string[]): Map<string, RoleSizingOutcome> {
191
209
  const out = new Map<string, RoleSizingOutcome>();
@@ -3,7 +3,7 @@ import {
3
3
  CODEX_UNKNOWN_USAGE_SCORE,
4
4
  } from "../quota";
5
5
  import { isThirtyDayOnlyCodexPlan } from "../plan";
6
- import { hasSpendableCodexCredits, isTerminalShortWindow, type CodexSpendableCredits } from "../quota-types";
6
+ import { hasElapsedShortWindow, hasSpendableCodexCredits, isTerminalShortWindow, type CodexSpendableCredits } from "../quota-types";
7
7
  import type { CodexQuotaScope } from "./health-store";
8
8
  import type { TransientProbeGrant } from "./thread-affinity";
9
9
  import type { MainQuotaDispatch } from "../main-account-cache";
@@ -136,7 +136,8 @@ export function computeCodexUsageScore(quota: {
136
136
  ? (allowCredits && hasSpendableCodexCredits(quota, now)) ? CODEX_EXHAUSTED_USAGE_PERCENT - 1 : CODEX_EXHAUSTED_USAGE_PERCENT
137
137
  : CODEX_UNKNOWN_USAGE_SCORE;
138
138
  }
139
- const values = finite(quota.shortPercent) ? [...knownLong, quota.shortPercent] : knownLong;
139
+ const values = finite(quota.shortPercent) && !hasElapsedShortWindow(quota.shortResetAt, now)
140
+ ? [...knownLong, quota.shortPercent] : knownLong;
140
141
  const score = Math.max(...values);
141
142
  // Keep included-capacity accounts ahead of a paid overage account, but do not
142
143
  // classify the latter as exhausted solely from its subscription percentages.
@@ -13,6 +13,7 @@ import {
13
13
  import { macCodexAppBundleFor, macCodexAppCommands } from "./mac-app-bundle";
14
14
  import {
15
15
  beginCodexCliSelectionParentWrite,
16
+ withCodexCliSelectionParentWriteAsync,
16
17
  CodexCliSelectionMutationBusyError,
17
18
  } from "./cli-update-selection-gate";
18
19
  import { resolveCodexHomeDir } from "./home";
@@ -406,7 +407,7 @@ export function persistCodexRuntime(
406
407
  // window, so a held gate is an immediate busy rather than a wait. Checked
407
408
  // BEFORE the mkdir and the resolve-cache invalidation so a busy refusal
408
409
  // changes nothing at all.
409
- const selectionWrite = beginCodexCliSelectionParentWrite();
410
+ const selectionWrite = beginCodexCliSelectionParentWrite(deps.configDir);
410
411
  if (!selectionWrite.entered) throw new CodexCliSelectionMutationBusyError();
411
412
  try {
412
413
  const configDir = deps.configDir ?? getConfigDir();
@@ -438,7 +439,7 @@ export function clearPersistedCodexRuntime(deps: ResolveCodexRuntimeDeps = {}):
438
439
  // Same gate as persistCodexRuntime, checked before the cache invalidation
439
440
  // and outside the swallowing catch: a busy refusal must stay an error, not
440
441
  // become a silent "already removed".
441
- const selectionWrite = beginCodexCliSelectionParentWrite();
442
+ const selectionWrite = beginCodexCliSelectionParentWrite(deps.configDir);
442
443
  if (!selectionWrite.entered) throw new CodexCliSelectionMutationBusyError();
443
444
  try {
444
445
  const configDir = deps.configDir ?? getConfigDir();
@@ -461,6 +462,14 @@ export function clearPersistedCodexRuntime(deps: ResolveCodexRuntimeDeps = {}):
461
462
  }
462
463
  }
463
464
 
465
+ export async function persistCodexRuntimeAsync(runtime: ResolvedCodexRuntime, deps: ResolveCodexRuntimeDeps = {},
466
+ origin: CodexRuntimePinOrigin = "pinned"): Promise<void> {
467
+ await withCodexCliSelectionParentWriteAsync(() => persistCodexRuntime(runtime, deps, origin), deps);
468
+ }
469
+ export async function clearPersistedCodexRuntimeAsync(deps: ResolveCodexRuntimeDeps = {}): Promise<void> {
470
+ await withCodexCliSelectionParentWriteAsync(() => clearPersistedCodexRuntime(deps), deps);
471
+ }
472
+
464
473
  type VersionProbeResult = { ok: true; version: string | null; macAppBundle?: boolean } | { ok: false; reason: string };
465
474
 
466
475
  /** Checks that need no exec; a non-null answer settles the candidate without running `--version`. */
@@ -1415,7 +1424,38 @@ export async function resolveAndPersistCodexRuntimeAsync(
1415
1424
  if (deps.signal?.aborted || !isCurrent() || observation.epoch === null || observation.epoch !== resolveCacheEpoch
1416
1425
  || observation.inputs !== codexRuntimeSelectionIdentity(deps)) return null;
1417
1426
  if (deps.signal?.aborted) return null;
1418
- return cloneAndDeepFreeze(persistResolvedCodexRuntime(observation.result, deps));
1427
+ if (resolvedRuntimeMutation(observation.result, deps) === null) return cloneAndDeepFreeze(observation.result);
1428
+ try {
1429
+ return await withCodexCliSelectionParentWriteAsync(() => {
1430
+ // Admission can await Windows ACL subprocesses. Re-prove all selection
1431
+ // inputs after that await, in the same turn as the persisted mutation.
1432
+ if (deps.signal?.aborted || !isCurrent() || observation.epoch !== resolveCacheEpoch
1433
+ || observation.inputs !== codexRuntimeSelectionIdentity(deps)) return null;
1434
+ return cloneAndDeepFreeze(persistResolvedCodexRuntime(observation.result, deps));
1435
+ }, deps);
1436
+ } catch (error) {
1437
+ if (deps.signal?.aborted) return null;
1438
+ if (error instanceof CodexCliSelectionMutationBusyError) {
1439
+ // A recovery denial also followed an await. Never return the obsolete
1440
+ // selection as a usable result merely because no commit callback ran.
1441
+ if (!isCurrent() || observation.epoch !== resolveCacheEpoch
1442
+ || observation.inputs !== codexRuntimeSelectionIdentity(deps)) return null;
1443
+ if (observation.result.runtime.source !== "fallback") {
1444
+ return cloneAndDeepFreeze({ ...observation.result, persistError: error.message });
1445
+ }
1446
+ }
1447
+ throw error;
1448
+ }
1449
+ }
1450
+
1451
+ function resolvedRuntimeMutation(result: ResolveCodexRuntimeResult, deps: ResolveCodexRuntimeDeps): "persist" | "clear" | null {
1452
+ const persisted = loadPersistedCodexRuntime(deps);
1453
+ const unchanged = persisted !== null && persisted.command === result.runtime.command
1454
+ && persisted.source === result.runtime.source && (persisted.selectedVersion ?? null) === (result.runtime.version ?? null);
1455
+ if (result.runtime.command && result.runtime.source !== "fallback" && !unchanged) return "persist";
1456
+ if (result.runtime.source === "fallback" && persisted?.command && result.failures.some(failure =>
1457
+ failure.command.trim() === persisted.command.trim() && failure.reason === PATH_MISSING_REASON)) return "clear";
1458
+ return null;
1419
1459
  }
1420
1460
 
1421
1461
  function persistResolvedCodexRuntime(
@@ -13,6 +13,7 @@ import {
13
13
  unlinkSync,
14
14
  } from "node:fs";
15
15
  import { posix, win32 } from "node:path";
16
+ import { sameFileIdentity, statTimeMs, type FileIdentity } from "../lib/file-identity";
16
17
  import { SHIM_MARKER, UNIX_SHIM_REVISION_MARKER, WINDOWS_SHIM_REVISION_MARKER } from "./shim-templates";
17
18
  import type { ShimFileState } from "./shim-state-file";
18
19
 
@@ -21,6 +22,7 @@ const CODEX_SHIM_PROBE_BYTES = 16 * 1024;
21
22
  interface ShimPathFingerprint {
22
23
  dev: number;
23
24
  ino: number;
25
+ identity: FileIdentity;
24
26
  kind: "file" | "symlink";
25
27
  mode: number;
26
28
  size: number;
@@ -48,16 +50,17 @@ function readShimProbePrefix(path: string): string {
48
50
 
49
51
  function statFingerprint(path: string, follow: boolean): Omit<ShimPathFingerprint, "target"> | null {
50
52
  try {
51
- const stat = follow ? statSync(path) : lstatSync(path);
53
+ const stat = follow ? statSync(path, { bigint: true }) : lstatSync(path, { bigint: true });
52
54
  if (follow ? !stat.isFile() : (!stat.isFile() && !stat.isSymbolicLink())) return null;
53
55
  return {
54
- dev: stat.dev,
55
- ino: stat.ino,
56
+ dev: Number(stat.dev),
57
+ ino: Number(stat.ino),
58
+ identity: { dev: stat.dev, ino: stat.ino },
56
59
  kind: stat.isSymbolicLink() ? "symlink" : "file",
57
- mode: stat.mode,
58
- size: stat.size,
59
- mtimeMs: stat.mtimeMs,
60
- ctimeMs: stat.ctimeMs,
60
+ mode: Number(stat.mode),
61
+ size: Number(stat.size),
62
+ mtimeMs: statTimeMs(stat.mtimeNs),
63
+ ctimeMs: statTimeMs(stat.ctimeNs),
61
64
  };
62
65
  } catch {
63
66
  return null;
@@ -68,8 +71,7 @@ function sameFingerprint(
68
71
  left: ShimPathFingerprint | Omit<ShimPathFingerprint, "target">,
69
72
  right: ShimPathFingerprint | Omit<ShimPathFingerprint, "target">,
70
73
  ): boolean {
71
- return left.dev === right.dev
72
- && left.ino === right.ino
74
+ return !!left.identity && !!right.identity && sameFileIdentity(left.identity, right.identity)
73
75
  && left.kind === right.kind
74
76
  && left.mode === right.mode
75
77
  && left.size === right.size
@@ -1,6 +1,7 @@
1
1
  import { lstatSync } from "node:fs";
2
2
  import { extname, join, posix, win32 } from "node:path";
3
3
  import { getConfigDir } from "../config";
4
+ import { sameFileIdentity } from "../lib/file-identity";
4
5
  import { fileErrorCode, readStateResult, stateFiles } from "./shim-state-file";
5
6
  import {
6
7
  isHealthyShimProbe,
@@ -111,7 +112,7 @@ export function inspectCodexShimBackingForCommand(
111
112
  const sameEffectiveIdentity = (fingerprint: ShimPathFingerprint | null): boolean => {
112
113
  if (!fingerprint) return false;
113
114
  const identity = fingerprint.target ?? fingerprint;
114
- return identity.dev === selectedIdentity.dev && identity.ino === selectedIdentity.ino;
115
+ return sameFileIdentity(identity.identity, selectedIdentity.identity);
115
116
  };
116
117
  const matches = files.flatMap(file => {
117
118
  const backingPath = file.realPath ?? file.backupPath;
@@ -151,7 +152,7 @@ export function inspectCodexShimBackingForCommand(
151
152
  });
152
153
  }
153
154
  const wrapperIdentity = wrapperProbe.fingerprint.target ?? wrapperProbe.fingerprint;
154
- if (backing.dev === wrapperIdentity.dev && backing.ino === wrapperIdentity.ino) {
155
+ if (sameFileIdentity(backing.identity, wrapperIdentity.identity)) {
155
156
  return Object.freeze({ status: "unknown" as const, reason: "backing_mismatch" as const });
156
157
  }
157
158
  const wrapperExt = extname(file.wrapperPath).toLowerCase();
@@ -10,11 +10,12 @@ import {
10
10
  rmdirSync,
11
11
  unlinkSync,
12
12
  writeFileSync,
13
- type Stats,
13
+ type BigIntStats,
14
14
  } from "node:fs";
15
15
  import { join } from "node:path";
16
16
  import { getConfigDir } from "../config";
17
17
  import { isProcessAlive } from "../lib/process-control";
18
+ import { sameFileIdentity, type FileIdentity } from "../lib/file-identity";
18
19
  import { sameFingerprint, stableShimPathProbe, type ShimPathFingerprint } from "./shim-fingerprint";
19
20
  import { fileErrorCode } from "./shim-state-file";
20
21
 
@@ -34,7 +35,7 @@ interface ShimRestoreLockRecord {
34
35
  interface ShimRestoreLockSnapshot {
35
36
  record: ShimRestoreLockRecord;
36
37
  ownerPath: string;
37
- lockIdentity: Pick<Stats, "dev" | "ino">;
38
+ lockIdentity: FileIdentity;
38
39
  fingerprint: ShimPathFingerprint;
39
40
  }
40
41
 
@@ -42,15 +43,11 @@ function restoreLockPath(): string {
42
43
  return join(getConfigDir(), "codex-shim.autorestore.lock");
43
44
  }
44
45
 
45
- function sameFileIdentity(left: Pick<Stats, "dev" | "ino">, right: Pick<Stats, "dev" | "ino">): boolean {
46
- return left.dev === right.dev && left.ino === right.ino;
47
- }
48
-
49
46
  function readShimRestoreLockSnapshot(path: string): ShimRestoreLockSnapshot | null {
50
- let lockIdentity: Stats;
47
+ let lockIdentity: BigIntStats;
51
48
  let entries: string[];
52
49
  try {
53
- lockIdentity = lstatSync(path);
50
+ lockIdentity = lstatSync(path, { bigint: true });
54
51
  if (!lockIdentity.isDirectory()) return null;
55
52
  entries = readdirSync(path);
56
53
  } catch {
@@ -66,7 +63,7 @@ function readShimRestoreLockSnapshot(path: string): ShimRestoreLockSnapshot | nu
66
63
  || typeof value.pid !== "number" || !Number.isSafeInteger(value.pid) || value.pid <= 0
67
64
  || typeof value.createdAt !== "number" || !Number.isFinite(value.createdAt)) return null;
68
65
  if (entries[0] !== `${value.token}.json`) return null;
69
- const currentLockIdentity = lstatSync(path);
66
+ const currentLockIdentity = lstatSync(path, { bigint: true });
70
67
  if (!currentLockIdentity.isDirectory() || !sameFileIdentity(lockIdentity, currentLockIdentity)) return null;
71
68
  return {
72
69
  record: value as ShimRestoreLockRecord,
@@ -112,7 +109,7 @@ function tryAcquireShimRestoreLock(beforeStaleDelete?: () => void): ShimRestoreL
112
109
  const path = restoreLockPath();
113
110
  for (let attempt = 0; attempt < 2; attempt += 1) {
114
111
  let fd: number | null = null;
115
- let identity: Stats | null = null;
112
+ let identity: BigIntStats | null = null;
116
113
  let createdDirectory = false;
117
114
  const record: ShimRestoreLockRecord = {
118
115
  version: 1,
@@ -125,9 +122,9 @@ function tryAcquireShimRestoreLock(beforeStaleDelete?: () => void): ShimRestoreL
125
122
  mkdirSync(path, { mode: 0o700 });
126
123
  createdDirectory = true;
127
124
  fd = openSync(ownerPath, "wx", 0o600);
128
- identity = fstatSync(fd);
125
+ identity = fstatSync(fd, { bigint: true });
129
126
  writeFileSync(fd, `${JSON.stringify(record)}\n`, "utf8");
130
- identity = fstatSync(fd);
127
+ identity = fstatSync(fd, { bigint: true });
131
128
  let released = false;
132
129
  return {
133
130
  release(): void {
@@ -137,7 +134,7 @@ function tryAcquireShimRestoreLock(beforeStaleDelete?: () => void): ShimRestoreL
137
134
  try {
138
135
  const current = readShimRestoreLockSnapshot(path);
139
136
  if (identity && current && current.record.token === record.token
140
- && sameFileIdentity(identity, current.fingerprint)) {
137
+ && sameFileIdentity(identity, current.fingerprint.identity)) {
141
138
  unlinkSync(ownerPath);
142
139
  rmdirSync(path);
143
140
  }
@@ -150,7 +147,7 @@ function tryAcquireShimRestoreLock(beforeStaleDelete?: () => void): ShimRestoreL
150
147
  try {
151
148
  const current = readShimRestoreLockSnapshot(path);
152
149
  if (identity && current && current.record.token === record.token
153
- && sameFileIdentity(identity, current.fingerprint)) {
150
+ && sameFileIdentity(identity, current.fingerprint.identity)) {
154
151
  unlinkSync(ownerPath);
155
152
  rmdirSync(path);
156
153
  }
@@ -10,12 +10,14 @@ import {
10
10
  renameSync,
11
11
  unlinkSync,
12
12
  writeFileSync,
13
+ type BigIntStats,
13
14
  type Stats,
14
15
  } from "node:fs";
15
16
  import { randomUUID } from "node:crypto";
16
17
  import { dirname, isAbsolute, join, resolve } from "node:path";
17
18
  import { getConfigDir } from "../config";
18
19
  import { recordOwnedConfigPath } from "../lib/config-ownership";
20
+ import { sameFileIdentity, statTimeMs } from "../lib/file-identity";
19
21
 
20
22
  export const CODEX_SHIM_STATE_MAX_BYTES = 1024 * 1024;
21
23
 
@@ -99,9 +101,9 @@ function fileErrorCode(error: unknown): string | undefined {
99
101
  }
100
102
 
101
103
  function readBoundedRegularFile(path: string, maxBytes: number): { bytes: Buffer; content: string; stat: Stats } | { warning: string } | null {
102
- let lexicalBefore: Stats;
104
+ let lexicalBefore: BigIntStats;
103
105
  try {
104
- lexicalBefore = lstatSync(path);
106
+ lexicalBefore = lstatSync(path, { bigint: true });
105
107
  if (lexicalBefore.isSymbolicLink() || !lexicalBefore.isFile()) {
106
108
  return { warning: `Codex shim state is not a direct regular file at ${path}; auto-restore skipped.` };
107
109
  }
@@ -117,12 +119,12 @@ function readBoundedRegularFile(path: string, maxBytes: number): { bytes: Buffer
117
119
  return { warning: `Codex shim state could not be opened as a regular file at ${path}.` };
118
120
  }
119
121
  try {
120
- const before = fstatSync(fd);
122
+ const before = fstatSync(fd, { bigint: true });
121
123
  if (!before.isFile()) return { warning: `Codex shim state is not a regular file at ${path}; auto-restore skipped.` };
122
124
  if (before.size > maxBytes) {
123
125
  return { warning: `Codex shim state exceeds the 1 MiB startup limit at ${path}; auto-restore skipped.` };
124
126
  }
125
- const buffer = Buffer.allocUnsafe(before.size);
127
+ const buffer = Buffer.allocUnsafe(Number(before.size));
126
128
  let offset = 0;
127
129
  while (offset < buffer.length) {
128
130
  const bytesRead = readSync(fd, buffer, offset, buffer.length - offset, offset);
@@ -133,25 +135,31 @@ function readBoundedRegularFile(path: string, maxBytes: number): { bytes: Buffer
133
135
  if (readSync(fd, extra, 0, 1, offset) !== 0) {
134
136
  return { warning: `Codex shim state exceeds the 1 MiB startup limit at ${path}; auto-restore skipped.` };
135
137
  }
136
- const after = fstatSync(fd);
137
- let lexicalAfter: Stats;
138
+ const after = fstatSync(fd, { bigint: true });
139
+ let lexicalAfter: BigIntStats;
138
140
  try {
139
- lexicalAfter = lstatSync(path);
141
+ lexicalAfter = lstatSync(path, { bigint: true });
140
142
  } catch {
141
143
  return { warning: `Codex shim state changed while being read at ${path}; auto-restore skipped.` };
142
144
  }
143
- if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size
144
- || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs
145
+ if (!sameFileIdentity(before, after) || before.size !== after.size
146
+ || statTimeMs(before.mtimeNs) !== statTimeMs(after.mtimeNs) || statTimeMs(before.ctimeNs) !== statTimeMs(after.ctimeNs)
145
147
  || before.mode !== after.mode || before.uid !== after.uid
146
- || lexicalBefore.dev !== before.dev || lexicalBefore.ino !== before.ino
148
+ || !sameFileIdentity(lexicalBefore, before)
147
149
  || lexicalBefore.mode !== before.mode || lexicalBefore.uid !== before.uid
148
- || lexicalBefore.size !== before.size || lexicalBefore.mtimeMs !== before.mtimeMs || lexicalBefore.ctimeMs !== before.ctimeMs
149
- || !lexicalAfter.isFile() || lexicalAfter.isSymbolicLink() || lexicalAfter.dev !== after.dev || lexicalAfter.ino !== after.ino
150
+ || lexicalBefore.size !== before.size || statTimeMs(lexicalBefore.mtimeNs) !== statTimeMs(before.mtimeNs) || statTimeMs(lexicalBefore.ctimeNs) !== statTimeMs(before.ctimeNs)
151
+ || !lexicalAfter.isFile() || lexicalAfter.isSymbolicLink() || !sameFileIdentity(lexicalAfter, after)
150
152
  || lexicalAfter.mode !== after.mode || lexicalAfter.uid !== after.uid
151
- || lexicalAfter.size !== after.size || lexicalAfter.mtimeMs !== after.mtimeMs || lexicalAfter.ctimeMs !== after.ctimeMs) {
153
+ || lexicalAfter.size !== after.size || statTimeMs(lexicalAfter.mtimeNs) !== statTimeMs(after.mtimeNs) || statTimeMs(lexicalAfter.ctimeNs) !== statTimeMs(after.ctimeNs)) {
152
154
  return { warning: `Codex shim state changed while being read at ${path}; auto-restore skipped.` };
153
155
  }
154
- return { bytes: buffer, content: buffer.toString("utf8"), stat: after };
156
+ const stat = Object.assign(Object.create(Object.getPrototypeOf(after)), after, {
157
+ dev: Number(after.dev), ino: Number(after.ino), mode: Number(after.mode), nlink: Number(after.nlink),
158
+ uid: Number(after.uid), gid: Number(after.gid), rdev: Number(after.rdev), size: Number(after.size),
159
+ blksize: Number(after.blksize), blocks: Number(after.blocks), atimeMs: statTimeMs(after.atimeNs),
160
+ mtimeMs: statTimeMs(after.mtimeNs), ctimeMs: statTimeMs(after.ctimeNs), birthtimeMs: statTimeMs(after.birthtimeNs),
161
+ }) as Stats;
162
+ return { bytes: buffer, content: buffer.toString("utf8"), stat };
155
163
  } finally {
156
164
  closeSync(fd);
157
165
  }
@@ -10,6 +10,7 @@ import { randomUUID } from "node:crypto";
10
10
  import { chmodSync, lstatSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
11
11
  import { basename, dirname, join } from "node:path";
12
12
  import { durableBunRuntime, type BunRuntimeSource, type DurableBunRuntime } from "../lib/bun-runtime";
13
+ import { sameFileIdentity, type FileIdentity } from "../lib/file-identity";
13
14
  import { serviceApiTokenFilePath } from "../lib/service-secrets";
14
15
  import {
15
16
  buildUnixCodexShim,
@@ -54,7 +55,7 @@ export function windowsShimContent(wrapperPath: string, realCodexPath: string, r
54
55
  return buildUnixCodexShim(gitBashPath(realCodexPath), gitBashPath(bun), gitBashPath(cli), bunRuntimeSource, gitBashPath(serviceApiTokenFilePath()));
55
56
  }
56
57
 
57
- export function writeShim(wrapperPath: string, realCodexPath: string, runtime?: DurableBunRuntime): { dev: number; ino: number } | undefined {
58
+ export function writeShim(wrapperPath: string, realCodexPath: string, runtime?: DurableBunRuntime): FileIdentity | undefined {
58
59
  const { bun, bunRuntimeSource, cli } = cliEntry(runtime);
59
60
  if (process.platform === "win32") {
60
61
  writeFileSync(wrapperPath, windowsShimContent(wrapperPath, realCodexPath, runtime), "utf8");
@@ -74,7 +75,7 @@ export function writeShim(wrapperPath: string, realCodexPath: string, runtime?:
74
75
  try {
75
76
  // "wx" fails if the staging path somehow exists, so we never inherit a file.
76
77
  writeFileSync(staged, buildUnixCodexShim(realCodexPath, bun, cli, bunRuntimeSource), { encoding: "utf8", flag: "wx", mode: 0o600 });
77
- const stagedStat = lstatSync(staged);
78
+ const stagedStat = lstatSync(staged, { bigint: true });
78
79
  chmodSync(staged, 0o755);
79
80
  renameSync(staged, wrapperPath);
80
81
  renamed = true;
@@ -96,14 +97,14 @@ export function writeShim(wrapperPath: string, realCodexPath: string, runtime?:
96
97
  */
97
98
  export function ownedWrapperFingerprint(
98
99
  wrapperPath: string,
99
- written: { dev: number; ino: number } | undefined,
100
+ written: FileIdentity | undefined,
100
101
  ): ShimPathFingerprint | undefined {
101
102
  const probe = stableShimPathProbe(wrapperPath);
102
103
  if (!probe) return undefined;
103
104
  // Platforms that still write in place (Windows) have no staged identity; fall
104
105
  // back to the marker check they have always used.
105
106
  if (!written) return probe.prefix.includes(SHIM_MARKER) ? probe.fingerprint : undefined;
106
- if (probe.fingerprint.dev !== written.dev || probe.fingerprint.ino !== written.ino) return undefined;
107
+ if (!sameFileIdentity(probe.fingerprint.identity, written)) return undefined;
107
108
  return probe.fingerprint;
108
109
  }
109
110
 
@@ -118,11 +119,11 @@ export function ownedWrapperFingerprint(
118
119
  */
119
120
  export function wrapperInodeIsOurs(
120
121
  wrapper: StableShimPathProbe,
121
- written: { dev: number; ino: number } | undefined,
122
+ written: FileIdentity | undefined,
122
123
  recorded: ShimPathFingerprint | undefined,
123
124
  ): boolean {
124
125
  // A different inode is conclusive: someone renamed their own file over ours.
125
- if (written && (wrapper.fingerprint.dev !== written.dev || wrapper.fingerprint.ino !== written.ino)) {
126
+ if (written && !sameFileIdentity(wrapper.fingerprint.identity, written)) {
126
127
  return false;
127
128
  }
128
129
  // Same inode is not sufficient on its own — an in-place truncation (shell `>`,