@bitkyc08/opencodex 2.94.0 → 2.96.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 (289) hide show
  1. package/gui/dist/assets/App-B4j-Txmb.css +1 -0
  2. package/gui/dist/assets/App-bwugJRKn.js +58 -0
  3. package/gui/dist/assets/{Tray-CZatQdoF.js → Tray-BOPQyDbH.js} +1 -1
  4. package/gui/dist/assets/index-ebuVUtB7.js +94 -0
  5. package/gui/dist/assets/quota-summary-6HsrHQAy.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/ollama-native.ts +10 -6
  14. package/src/adapters/openai-chat/messages.ts +20 -7
  15. package/src/adapters/openai-chat/passthrough.ts +4 -2
  16. package/src/adapters/openai-chat/single-system.ts +24 -0
  17. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  18. package/src/adapters/openai-responses/muse-tool-catalog.ts +87 -0
  19. package/src/adapters/openai-responses/passthrough.ts +45 -11
  20. package/src/adapters/openai-responses/prompt-cache.ts +3 -1
  21. package/src/adapters/openai-responses/request-strips.ts +23 -4
  22. package/src/adapters/openai-responses/tool-output-recovery.ts +21 -8
  23. package/src/adapters/openai-responses/tool-schema.ts +20 -8
  24. package/src/adapters/openai-responses/transport.ts +17 -26
  25. package/src/adapters/opencode-go-additional-tools.ts +39 -6
  26. package/src/adapters/qoder/adapter.ts +1 -1
  27. package/src/adapters/qoder/image-input.ts +5 -2
  28. package/src/adapters/routed-agent-messages.ts +3 -0
  29. package/src/adapters/xai-web-search.ts +6 -3
  30. package/src/adapters/zed-additional-tools.ts +7 -7
  31. package/src/adapters/zed.ts +1 -6
  32. package/src/advisor/consult.ts +22 -10
  33. package/src/advisor/runtime.ts +10 -4
  34. package/src/bridge/max-output-completion.ts +41 -0
  35. package/src/bridge/response-json.ts +9 -4
  36. package/src/bridge/sse.ts +13 -2
  37. package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +5 -0
  38. package/src/chatgpt/app-server-shim/launcher.ts +40 -6
  39. package/src/claude/compatibility.ts +5 -1
  40. package/src/claude/desktop-3p.ts +27 -6
  41. package/src/claude/desktop-model-visibility.ts +141 -0
  42. package/src/claude/desktop-remote-store-io.ts +8 -8
  43. package/src/claude/inbound-content-options.ts +11 -1
  44. package/src/claude/intercept/proxy-auth.ts +16 -16
  45. package/src/cli/account-main.ts +3 -2
  46. package/src/cli/agent.ts +44 -15
  47. package/src/cli/capabilities-agents-routing.ts +9 -0
  48. package/src/cli/capabilities-provider-models.ts +7 -0
  49. package/src/cli/chatgpt-command.ts +1 -1
  50. package/src/cli/codex-launcher.ts +20 -8
  51. package/src/cli/codex-shim-autorestore.ts +19 -1
  52. package/src/cli/dispatch.ts +6 -6
  53. package/src/cli/doctor.ts +5 -5
  54. package/src/cli/ensure-desired-integrations.ts +4 -3
  55. package/src/cli/index.ts +8 -10
  56. package/src/cli/init.ts +2 -2
  57. package/src/cli/internal-command.ts +29 -2
  58. package/src/cli/message-command.ts +2 -1
  59. package/src/cli/message-mcp-command.ts +29 -0
  60. package/src/cli/provider-cc-switch-import.ts +185 -0
  61. package/src/cli/provider.ts +5 -0
  62. package/src/cli/registry.ts +2 -1
  63. package/src/cli/restart-scope.ts +2 -2
  64. package/src/cli/root.ts +6 -6
  65. package/src/cli/stop-approval.ts +15 -1
  66. package/src/cli/v2.ts +69 -19
  67. package/src/client/machine-api.ts +2 -2
  68. package/src/clients/config-export.ts +14 -3
  69. package/src/codex/account-cooldown-response.ts +18 -0
  70. package/src/codex/account-store.ts +1 -0
  71. package/src/codex/app-server-restart-service.ts +2 -2
  72. package/src/codex/auth-api/login-flow.ts +2 -2
  73. package/src/codex/auth-api/pool-quota-probe.ts +2 -2
  74. package/src/codex/auth-context-provider.ts +15 -0
  75. package/src/codex/auth-context.ts +14 -23
  76. package/src/codex/catalog/bundled.ts +10 -3
  77. package/src/codex/catalog/metadata.ts +4 -5
  78. package/src/codex/catalog/native-omission.ts +28 -0
  79. package/src/codex/catalog/native-template.ts +58 -0
  80. package/src/codex/catalog/parsing.ts +3 -29
  81. package/src/codex/catalog/provider-models.ts +2 -1
  82. package/src/codex/catalog/retained-sync.ts +15 -5
  83. package/src/codex/catalog/write-audit.ts +18 -18
  84. package/src/codex/cli-install-provenance.ts +46 -45
  85. package/src/codex/cli-update-artifacts.ts +8 -6
  86. package/src/codex/cli-update-job-store-windows.ts +99 -27
  87. package/src/codex/cli-update-job-worker.ts +3 -11
  88. package/src/codex/cli-update-recovery.ts +54 -8
  89. package/src/codex/cli-update-selection-gate.ts +74 -4
  90. package/src/codex/cli-windows-plan-provenance.ts +37 -19
  91. package/src/codex/codex-home-owner.ts +9 -8
  92. package/src/codex/convergence.ts +13 -3
  93. package/src/codex/coordinator-doctor.ts +14 -8
  94. package/src/codex/desktop-app/handoff.ts +1 -1
  95. package/src/codex/desktop-app-restart.ts +11 -1
  96. package/src/codex/exec-boundary.ts +26 -5
  97. package/src/codex/forward-transport-headers.ts +33 -33
  98. package/src/codex/history-provider.ts +11 -10
  99. package/src/codex/inject/bounded-config-reader.ts +14 -13
  100. package/src/codex/installation-id.ts +72 -0
  101. package/src/codex/main-account.ts +6 -6
  102. package/src/codex/native-main-lock-file.ts +13 -12
  103. package/src/codex/native-residue.ts +18 -14
  104. package/src/codex/orca-auth-source.ts +8 -7
  105. package/src/codex/quota-types.ts +5 -0
  106. package/src/codex/quota.ts +49 -7
  107. package/src/codex/role-auto-assign.ts +50 -26
  108. package/src/codex/role-capability.ts +160 -0
  109. package/src/codex/role-sizing.ts +24 -6
  110. package/src/codex/routing/cooldown-math.ts +3 -2
  111. package/src/codex/runtime.ts +43 -3
  112. package/src/codex/shim-fingerprint.ts +11 -9
  113. package/src/codex/shim-inspect.ts +3 -2
  114. package/src/codex/shim-restore-lock.ts +11 -14
  115. package/src/codex/shim-state-file.ts +22 -14
  116. package/src/codex/shim-wrapper-write.ts +7 -6
  117. package/src/codex/shim.ts +25 -2
  118. package/src/codex/transition-state.ts +5 -4
  119. package/src/combos/failover.ts +43 -4
  120. package/src/config/atomic-write.ts +38 -7
  121. package/src/config/diagnostics.ts +3 -0
  122. package/src/config/initialize.ts +6 -6
  123. package/src/config/load-degrade.ts +2 -0
  124. package/src/config/process-state.ts +23 -5
  125. package/src/config/salvage.ts +1 -0
  126. package/src/config/schema/config-schema.ts +29 -1
  127. package/src/config/schema/leaf-validators.ts +7 -0
  128. package/src/config/schema/workflow-budget.ts +43 -0
  129. package/src/config/tracked-runtime-inspection.ts +188 -0
  130. package/src/generated/compatibility-version.json +380 -244
  131. package/src/grok/sync.ts +10 -1
  132. package/src/integrations/aside-profile-context.ts +1 -1
  133. package/src/integrations/droid-settings.ts +4 -4
  134. package/src/integrations/hermes-profiles.ts +3 -3
  135. package/src/lib/bounded-file-read.ts +3 -9
  136. package/src/lib/bun-runtime-preflight.ts +9 -8
  137. package/src/lib/file-identity.ts +15 -0
  138. package/src/lib/local-chat-completion.ts +8 -6
  139. package/src/lib/local-destinations.ts +32 -3
  140. package/src/lib/redact-folding.ts +9 -0
  141. package/src/lib/spend-pool-alias-validation.ts +6 -6
  142. package/src/lib/state-store-registrations.ts +2 -0
  143. package/src/lib/test-home-guard.ts +37 -9
  144. package/src/lib/windows-secret-acl.ts +49 -31
  145. package/src/lib/workflow-budget-config.ts +39 -0
  146. package/src/local-credentials/generation.ts +6 -2
  147. package/src/local-credentials/inventory.ts +132 -8
  148. package/src/messaging/mcp-queue-rpc.ts +102 -0
  149. package/src/messaging/mcp-queue-server.ts +42 -0
  150. package/src/messaging/mcp-queue-tools.ts +39 -0
  151. package/src/messaging/remote-forward-failure.ts +35 -0
  152. package/src/messaging/remote-ports.ts +27 -5
  153. package/src/messaging/remote-process.ts +30 -4
  154. package/src/messaging/remote-tunnels.ts +80 -15
  155. package/src/oauth/anthropic-identity.ts +2 -6
  156. package/src/oauth/antigravity-discovery-diagnostics.ts +65 -0
  157. package/src/oauth/google-antigravity.ts +23 -10
  158. package/src/oauth/index.ts +7 -0
  159. package/src/oauth/kiro-device-login.ts +87 -30
  160. package/src/oauth/kiro-iam-identity-center.ts +107 -0
  161. package/src/oauth/store.ts +9 -7
  162. package/src/providers/account-quota-disk.ts +18 -4
  163. package/src/providers/anthropic-subscription.ts +25 -0
  164. package/src/providers/cc-switch-import-bytes.ts +991 -0
  165. package/src/providers/cc-switch-import-source.ts +1083 -0
  166. package/src/providers/cc-switch-import.ts +942 -0
  167. package/src/providers/claude-cli-usage.ts +15 -67
  168. package/src/providers/derive.ts +6 -0
  169. package/src/providers/model-discovery-diagnostic.ts +4 -0
  170. package/src/providers/model-discovery.ts +4 -4
  171. package/src/providers/model-rename-fields.ts +2 -0
  172. package/src/providers/model-rename-migration.ts +41 -6
  173. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  174. package/src/providers/quota/anthropic-usage-windows.ts +55 -0
  175. package/src/providers/quota/report-cache.ts +17 -4
  176. package/src/providers/quota.ts +2 -2
  177. package/src/providers/reasoning-metadata.ts +31 -15
  178. package/src/providers/registry/entries-core.ts +1 -1
  179. package/src/providers/registry/entries-extended.ts +1 -1
  180. package/src/providers/registry/model-ids.ts +1 -0
  181. package/src/providers/registry/model-seeds.ts +2 -1
  182. package/src/providers/registry/types.ts +3 -1
  183. package/src/providers/resolved-model-policy.ts +2 -2
  184. package/src/providers/routed-config.ts +2 -0
  185. package/src/providers/stale-model-roster-migration.ts +5 -1
  186. package/src/providers/xai-transport.ts +4 -4
  187. package/src/remote-control/workspace-codex-runtime.ts +2 -2
  188. package/src/remote-control/workspace-executor.ts +14 -13
  189. package/src/responses/custom-tool-compat.ts +2 -1
  190. package/src/responses/item-provenance.ts +79 -0
  191. package/src/responses/namespace-tool-compat.ts +21 -3
  192. package/src/responses/parser-tools.ts +1 -0
  193. package/src/responses/schema.ts +5 -2
  194. package/src/router.ts +21 -2
  195. package/src/routing/analytics.ts +3 -5
  196. package/src/routing/fallback-policy.ts +7 -3
  197. package/src/routing/health.ts +5 -3
  198. package/src/routing/history/build-file.ts +6 -0
  199. package/src/routing/history/indexer.ts +158 -31
  200. package/src/routing/history/ingest.ts +1 -1
  201. package/src/routing/history/integrity.ts +208 -0
  202. package/src/routing/history/rebuild-job.ts +20 -6
  203. package/src/routing/history/rebuild-protocol.ts +2 -1
  204. package/src/routing/history/rebuild-worker.ts +18 -0
  205. package/src/routing/history/sqlite-errors.ts +9 -0
  206. package/src/server/admission-model-scope.ts +21 -4
  207. package/src/server/advisor-admission-scope.ts +29 -0
  208. package/src/server/audio-dictation.ts +3 -0
  209. package/src/server/audio-live.ts +8 -2
  210. package/src/server/audio-upstream.ts +2 -0
  211. package/src/server/auth-cors.ts +5 -2
  212. package/src/server/capture-admission-policy.ts +91 -0
  213. package/src/server/chat-completions.ts +33 -7
  214. package/src/server/claude-messages.ts +93 -2
  215. package/src/server/codex-model-list.ts +2 -1
  216. package/src/server/configured-credentials.ts +5 -0
  217. package/src/server/context-history.ts +9 -6
  218. package/src/server/images.ts +14 -5
  219. package/src/server/index/live-sideband.ts +16 -2
  220. package/src/server/index/serve-options.ts +13 -2
  221. package/src/server/index/websocket-handler.ts +4 -1
  222. package/src/server/live.ts +30 -5
  223. package/src/server/management/agent-settings-routes.ts +34 -9
  224. package/src/server/management/codex-agent-role-routes.ts +1 -0
  225. package/src/server/management/codex-role-auto-assign.ts +50 -6
  226. package/src/server/management/config-routes.ts +15 -4
  227. package/src/server/management/context.ts +3 -0
  228. package/src/server/management/native-integration-routes.ts +22 -0
  229. package/src/server/management/oauth-account-routes.ts +20 -4
  230. package/src/server/management/provider-overwrite-carry.ts +21 -0
  231. package/src/server/management/provider-routes.ts +3 -1
  232. package/src/server/management/route-registry.ts +2 -0
  233. package/src/server/management/shared.ts +17 -1
  234. package/src/server/management/workflow-budget-routes.ts +70 -3
  235. package/src/server/messages-native-eligibility.ts +6 -5
  236. package/src/server/messages-native-scope.ts +6 -1
  237. package/src/server/messages-shared.ts +57 -17
  238. package/src/server/persistent-gui-session.ts +4 -4
  239. package/src/server/request-log.ts +30 -2
  240. package/src/server/responses/adapter-delivery.ts +4 -0
  241. package/src/server/responses/adapter-dispatch.ts +5 -0
  242. package/src/server/responses/advisor-plan-slot.ts +4 -0
  243. package/src/server/responses/advisor-slot.ts +73 -46
  244. package/src/server/responses/codex-auth-error.ts +9 -1
  245. package/src/server/responses/combo-required-tool-contract.ts +39 -0
  246. package/src/server/responses/compact.ts +41 -20
  247. package/src/server/responses/core-codex-account.ts +17 -6
  248. package/src/server/responses/core-combo-failure.ts +2 -0
  249. package/src/server/responses/core-combo.ts +70 -5
  250. package/src/server/responses/core-lifetime.ts +4 -0
  251. package/src/server/responses/core-normalize.ts +7 -1
  252. package/src/server/responses/core-options.ts +9 -0
  253. package/src/server/responses/core.ts +2 -0
  254. package/src/server/responses/jev-model-invoke.ts +4 -2
  255. package/src/server/responses/passthrough-build-error.ts +36 -0
  256. package/src/server/responses/passthrough-dispatch.ts +10 -24
  257. package/src/server/responses/policy-fallback.ts +2 -0
  258. package/src/server/responses/request-prepare.ts +4 -5
  259. package/src/server/responses/request-send-budget.ts +2 -1
  260. package/src/server/responses/request-sidecar-auth.ts +4 -1
  261. package/src/server/responses/request-transport.ts +2 -3
  262. package/src/server/responses/run-turn-execution.ts +4 -0
  263. package/src/server/responses/sidecar-execution.ts +21 -5
  264. package/src/server/responses-snapshot-repair.ts +18 -4
  265. package/src/server/responses-undeclared-tool-guard.ts +4 -0
  266. package/src/server/search.ts +13 -4
  267. package/src/server/workflow-refusal.ts +2 -1
  268. package/src/server/ws-bridge.ts +5 -2
  269. package/src/service/state-lock.ts +12 -11
  270. package/src/service-manager-probe.ts +53 -8
  271. package/src/types/admission-policy.ts +13 -0
  272. package/src/types/config.ts +25 -0
  273. package/src/types/provider.ts +10 -0
  274. package/src/types/request.ts +7 -0
  275. package/src/types.ts +1 -0
  276. package/src/update/job.ts +20 -0
  277. package/src/update/worker-launch.ts +71 -1
  278. package/src/usage/log.ts +25 -4
  279. package/src/vision/describe.ts +4 -7
  280. package/src/vision/index.ts +2 -0
  281. package/src/vision/plan.ts +4 -0
  282. package/src/vision/routed-describe.ts +38 -23
  283. package/src/web-search/executor.ts +4 -7
  284. package/src/web-search/loop.ts +104 -9
  285. package/src/web-search/parse.ts +10 -2
  286. package/gui/dist/assets/App-DMps4OLk.css +0 -1
  287. package/gui/dist/assets/App-DmvwlhQq.js +0 -58
  288. package/gui/dist/assets/index-3EPO_KbX.js +0 -94
  289. package/gui/dist/assets/quota-summary-BHvWg9mi.js +0 -1
package/src/grok/sync.ts CHANGED
@@ -32,9 +32,15 @@ async function defaultFetchAllModels(config: OcxConfig): Promise<CatalogModel[]>
32
32
  export async function syncGrokConfig(
33
33
  port: number,
34
34
  config: OcxConfig,
35
- opts: { hostname?: string; probeHostname?: string; grokHome?: string; refreshOnly?: { admit: () => boolean } } = {},
35
+ opts: { hostname?: string; probeHostname?: string; grokHome?: string; refreshOnly?: { admit: () => boolean };
36
+ /** Recheck caller-owned desired state/lifecycle after asynchronous catalog work. */
37
+ admit?: () => boolean } = {},
36
38
  deps: GrokSyncDeps = { fetchAllModels: defaultFetchAllModels, injectGrokConfig },
37
39
  ): Promise<GrokInjectResult> {
40
+ const skipped = (): GrokInjectResult => ({
41
+ ok: true, changed: false, message: "Grok config sync skipped: caller admission is no longer current.",
42
+ });
43
+ if (opts.admit && !opts.admit()) return skipped();
38
44
  let projection: ReturnType<typeof projectGrokCatalog>;
39
45
  try {
40
46
  const allRouted = await deps.fetchAllModels(config);
@@ -54,6 +60,9 @@ export async function syncGrokConfig(
54
60
  unauthenticatedLoopbackListener: config.unauthenticatedLoopbackListener,
55
61
  });
56
62
  const targetUrl = new URL(target.baseUrl);
63
+ // Admission and the synchronous writer share one event-loop turn. A toggle or
64
+ // shutdown that landed while catalog discovery awaited must win over this snapshot.
65
+ if (opts.admit && !opts.admit()) return skipped();
57
66
  return deps.injectGrokConfig(Number(targetUrl.port), projection.models, {
58
67
  hostname: target.requiresAdmissionToken
59
68
  ? (opts.hostname ?? config.hostname)
@@ -74,7 +74,7 @@ function storeGuard(anchor: string, target: string): () => void {
74
74
  const identities = new Map<string, string>();
75
75
  const inspect = (path: string, directory: boolean): boolean => {
76
76
  try {
77
- const stat = lstatSync(path);
77
+ const stat = lstatSync(path, { bigint: true });
78
78
  if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) || (!directory && stat.nlink > 1)) storeUnsafe();
79
79
  if (directory) {
80
80
  const identity = `${realpathSync(path)}:${stat.dev}:${stat.ino}`;
@@ -1,5 +1,5 @@
1
1
  /** Read-only guard for competing Factory settings before a managed write. */
2
- import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, type BigIntStats } from "node:fs";
3
3
  import { join, win32 } from "node:path";
4
4
 
5
5
  const isWindowsRoot = (path: string) => /^[A-Za-z]:[\\/]|^\\\\/.test(path);
@@ -26,8 +26,8 @@ export function assertDroidSettingsUnambiguous(root: string, baseUrl?: string, m
26
26
  }
27
27
  for (const name of ["config.json", "settings.local.json"]) {
28
28
  const path = isWindowsRoot(root) ? win32.join(root, name) : join(root, name);
29
- let stat: ReturnType<typeof lstatSync>;
30
- try { stat = lstatSync(path); }
29
+ let stat: BigIntStats;
30
+ try { stat = lstatSync(path, { bigint: true }); }
31
31
  catch (error) {
32
32
  if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
33
33
  throw new Error(`Cannot inspect Factory ${name}`);
@@ -37,7 +37,7 @@ export function assertDroidSettingsUnambiguous(root: string, baseUrl?: string, m
37
37
  let fd: number | undefined;
38
38
  try {
39
39
  fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
40
- const opened = fstatSync(fd);
40
+ const opened = fstatSync(fd, { bigint: true });
41
41
  if (!opened.isFile() || opened.size > 1024 * 1024 || opened.ino !== stat.ino || opened.dev !== stat.dev) {
42
42
  throw new Error("file changed during inspection");
43
43
  }
@@ -16,7 +16,7 @@
16
16
  * `<integrations>/hermes-profiles/<name>/`, so its records, journal and snapshots
17
17
  * can never be confused with the default profile's.
18
18
  */
19
- import { lstatSync, readdirSync, type Stats } from "node:fs";
19
+ import { lstatSync, readdirSync, type BigIntStats } from "node:fs";
20
20
  import { homedir } from "node:os";
21
21
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
22
22
  import { hermesHomeDir } from "../clients/config-export";
@@ -46,8 +46,8 @@ export class HermesProfileError extends Error {
46
46
  }
47
47
  }
48
48
 
49
- function lstatOrNull(path: string): Stats | null {
50
- try { return lstatSync(path); }
49
+ function lstatOrNull(path: string): BigIntStats | null {
50
+ try { return lstatSync(path, { bigint: true }); }
51
51
  catch (error) {
52
52
  if ((error as NodeJS.ErrnoException).code === "ENOENT" || (error as NodeJS.ErrnoException).code === "ENOTDIR") return null;
53
53
  throw new HermesProfileError("hermes_profiles_unavailable", 409, "Hermes profiles cannot be read");
@@ -1,15 +1,9 @@
1
1
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs";
2
+ import { sameFileIdentity } from "./file-identity";
2
3
 
3
4
  const MAX_BOUNDED_READ_BYTES = 64 * 1024 * 1024;
4
5
  const READ_CHUNK_BYTES = 64 * 1024;
5
6
 
6
- function sameIdentity(
7
- left: { dev: bigint; ino: bigint },
8
- right: { dev: bigint; ino: bigint },
9
- ): boolean {
10
- return left.dev === right.dev && left.ino === right.ino;
11
- }
12
-
13
7
  export function readBoundedRegularFileSync(path: string, limit: number): Buffer {
14
8
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_BOUNDED_READ_BYTES) {
15
9
  throw new RangeError("invalid bounded file read limit");
@@ -25,7 +19,7 @@ export function readBoundedRegularFileSync(path: string, limit: number): Buffer
25
19
  try {
26
20
  const opened = fstatSync(fd, { bigint: true });
27
21
  if (!opened.isFile() || opened.size > BigInt(limit)) throw new Error("file is not bounded regular data");
28
- if (entryBefore && (!sameIdentity(entryBefore, opened) || opened.ino === 0n)) {
22
+ if (entryBefore && (!sameFileIdentity(entryBefore, opened) || opened.ino === 0n)) {
29
23
  throw new Error("file entry changed while opening");
30
24
  }
31
25
 
@@ -47,7 +41,7 @@ export function readBoundedRegularFileSync(path: string, limit: number): Buffer
47
41
 
48
42
  if (entryBefore) {
49
43
  const entryAfter = lstatSync(path, { bigint: true });
50
- if (entryAfter.isSymbolicLink() || !entryAfter.isFile() || !sameIdentity(opened, entryAfter)) {
44
+ if (entryAfter.isSymbolicLink() || !entryAfter.isFile() || !sameFileIdentity(opened, entryAfter)) {
51
45
  throw new Error("file entry changed while reading");
52
46
  }
53
47
  }
@@ -19,9 +19,10 @@ export class RuntimePreflightError extends Error {
19
19
  }
20
20
  }
21
21
 
22
- type DirectoryIdentity = { dev: number; ino: number; isDirectory(): boolean; isSymbolicLink(): boolean };
22
+ // bigint: NTFS file IDs exceed 2^53, where adjacent IDs are equal as numbers.
23
+ type DirectoryIdentity = { dev: bigint; ino: bigint; isDirectory(): boolean; isSymbolicLink(): boolean };
23
24
  export interface RuntimePreflightFs {
24
- lstatSync: (path: string) => DirectoryIdentity;
25
+ lstatSync: (path: string, options: { bigint: true }) => DirectoryIdentity;
25
26
  mkdirSync: (path: string, mode: number) => unknown;
26
27
  rmdirSync: (path: string) => void;
27
28
  readdirSync: (path: string) => readonly string[];
@@ -44,7 +45,7 @@ export interface RuntimePreflightDeps {
44
45
  const probeFs: RuntimePreflightFs = { lstatSync, mkdirSync, rmdirSync, readdirSync };
45
46
 
46
47
  function sameDirectory(fs: RuntimePreflightFs, path: string, owned: DirectoryIdentity): boolean {
47
- const current = fs.lstatSync(path);
48
+ const current = fs.lstatSync(path, { bigint: true });
48
49
  return current.isDirectory() && !current.isSymbolicLink()
49
50
  && current.dev === owned.dev && current.ino === owned.ino;
50
51
  }
@@ -59,7 +60,7 @@ function removeOwnedEmptyDirectory(fs: RuntimePreflightFs, path: string, owned:
59
60
  function prepareRoot(fs: RuntimePreflightFs, root: string, rootWasAbsent?: boolean): void {
60
61
  try {
61
62
  if (rootWasAbsent === undefined) {
62
- try { fs.lstatSync(root); rootWasAbsent = false; }
63
+ try { fs.lstatSync(root, { bigint: true }); rootWasAbsent = false; }
63
64
  catch (error) {
64
65
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
65
66
  rootWasAbsent = true;
@@ -73,7 +74,7 @@ function prepareRoot(fs: RuntimePreflightFs, root: string, rootWasAbsent?: boole
73
74
  // Use a concurrently created root, subject to the directory check below.
74
75
  }
75
76
  }
76
- const current = fs.lstatSync(root);
77
+ const current = fs.lstatSync(root, { bigint: true });
77
78
  if (!current.isDirectory() || current.isSymbolicLink()) throw new RuntimePreflightError("create");
78
79
  } catch {
79
80
  throw new RuntimePreflightError("create");
@@ -83,7 +84,7 @@ function prepareRoot(fs: RuntimePreflightFs, root: string, rootWasAbsent?: boole
83
84
  function probeInProcess(fs: RuntimePreflightFs, path: string): void {
84
85
  let owned: DirectoryIdentity | undefined;
85
86
  try {
86
- try { fs.mkdirSync(path, 0o700); owned = fs.lstatSync(path); }
87
+ try { fs.mkdirSync(path, 0o700); owned = fs.lstatSync(path, { bigint: true }); }
87
88
  catch { throw new RuntimePreflightError("create"); }
88
89
  try { fs.rmdirSync(path); }
89
90
  catch { throw new RuntimePreflightError("remove"); }
@@ -96,10 +97,10 @@ function probeChild(runtime: DurableBunRuntime, path: string, nonce: string, spa
96
97
  // The child emits only this invocation's nonce and a fixed result, never paths/errors.
97
98
  const script = `const fs = require("node:fs"); const path = ${JSON.stringify(path)};
98
99
  let result = "create", owned;
99
- try { fs.mkdirSync(path, 0o700); owned = fs.lstatSync(path); result = "remove";
100
+ try { fs.mkdirSync(path, 0o700); owned = fs.lstatSync(path, { bigint: true }); result = "remove";
100
101
  fs.rmdirSync(path); result = "ok";
101
102
  } catch { /* result already names the failed step; details never leave the child */ } finally {
102
- if (owned) { try { const now = fs.lstatSync(path);
103
+ if (owned) { try { const now = fs.lstatSync(path, { bigint: true });
103
104
  if (now.isDirectory() && !now.isSymbolicLink() && now.dev === owned.dev && now.ino === owned.ino
104
105
  && fs.readdirSync(path).length === 0) fs.rmdirSync(path);
105
106
  } catch { /* leave any probe entry that cannot be proven ours */ } }
@@ -0,0 +1,15 @@
1
+ /** Acquire stats with { bigint: true }; never widen a Number to form an identity. */
2
+ export type FileIdentity = Readonly<{ dev: bigint; ino: bigint }>;
3
+
4
+ /** Matches the numeric stat's *Ms value, so a bigint observation can be compared with a numeric or persisted one. */
5
+ export function statTimeMs(ns: bigint): number {
6
+ return Number(ns / 1_000_000_000n) * 1e3 + Number(ns % 1_000_000_000n) / 1e6;
7
+ }
8
+
9
+ export function sameFileIdentity(a: FileIdentity, b: FileIdentity): boolean {
10
+ return a.dev === b.dev && a.ino === b.ino;
11
+ }
12
+
13
+ export function fileIdentityKey(id: FileIdentity): string {
14
+ return `${id.dev}:${id.ino}`;
15
+ }
@@ -7,12 +7,13 @@
7
7
  *
8
8
  * Destination: the unauthenticated loopback listener when one is enabled, otherwise the bind
9
9
  * address (#4236), resolved by localInferenceDestination rather than composing 127.0.0.1 by hand.
10
- * Admission: localAdmissionToken (env token, hardened service token file, first apiKeys entry),
11
- * sent as x-opencodex-api-key and never Authorization, because an admission secret in a
12
- * forwardable header is a forwarding hazard. Never the admin token.
10
+ * Admission: selfFetchAdmissionToken (env token, hardened service token file, first apiKeys entry;
11
+ * only a recognized one when the destination requires no admission), sent as x-opencodex-api-key
12
+ * and never Authorization, because an admission secret in a forwardable header is a forwarding
13
+ * hazard. Never the admin token.
13
14
  */
14
15
  import type { OcxConfig } from "../types";
15
- import { localAdmissionToken, localInferenceDestination } from "./local-destinations";
16
+ import { localInferenceDestination, selfFetchAdmissionToken } from "./local-destinations";
16
17
  import { signalWithTimeout, cancelBodyOnAbort } from "./abort";
17
18
  import { readBoundedResponseBytes } from "./bounded-body";
18
19
  import { redactSecretString } from "./redact";
@@ -64,12 +65,13 @@ export function localChatCompletionBaseUrl(
64
65
  export async function postLocalChatCompletion(request: LocalChatCompletionRequest): Promise<LocalChatCompletionOutcome> {
65
66
  const { config, label, logTag } = request;
66
67
  const headers: Record<string, string> = { "Content-Type": "application/json", ...request.headers };
67
- const admission = localAdmissionToken(config);
68
+ const target = destination(config);
69
+ const admission = selfFetchAdmissionToken(config, target);
68
70
  if (admission) headers["x-opencodex-api-key"] = admission;
69
71
  // A bind that demands admission with no resolvable credential would return 401 with a body
70
72
  // the caller reports as a failure; naming the cause once is the difference between "it is
71
73
  // broken" and a fixable configuration note.
72
- if (!admission && !request.baseUrlOverride && destination(config).requiresAdmissionToken) {
74
+ if (!admission && !request.baseUrlOverride && target.requiresAdmissionToken) {
73
75
  console.warn(
74
76
  `[${logTag}] ${label} has no opencodex data-plane credential for `
75
77
  + `${localChatCompletionBaseUrl(config)} — the self-fetch will be refused.`,
@@ -40,6 +40,7 @@
40
40
  import { isIP } from "node:net";
41
41
  import { effectiveLoopbackListenerPort, isLoopbackHostname, isWildcardHostname, shouldInjectApiAuthHeader } from "../codex/loopback-target";
42
42
  import { probeHostname } from "../server/proxy-liveness";
43
+ import { resolveDataPlaneAdmissionSecret } from "../server/auth-cors";
43
44
  import { loadServiceTokenFromFile, serviceApiTokenFilePath } from "./service-secrets";
44
45
  import type { OcxConfig } from "../types";
45
46
 
@@ -150,8 +151,16 @@ export function localAdmissionToken(
150
151
  config: Pick<OcxConfig, "apiKeys"> | undefined,
151
152
  env: NodeJS.ProcessEnv = process.env,
152
153
  ): string | undefined {
154
+ return localAdmissionTokenCandidates(config, env)[0];
155
+ }
156
+
157
+ function localAdmissionTokenCandidates(
158
+ config: Pick<OcxConfig, "apiKeys"> | undefined,
159
+ env: NodeJS.ProcessEnv,
160
+ ): string[] {
161
+ const candidates: string[] = [];
153
162
  const envToken = env.OPENCODEX_API_AUTH_TOKEN?.trim();
154
- if (envToken) return envToken;
163
+ if (envToken) candidates.push(envToken);
155
164
  const lookup = env.OCX_API_TOKEN_FILE?.trim()
156
165
  ? env
157
166
  : { ...env, OCX_API_TOKEN_FILE: serviceApiTokenFilePath() };
@@ -160,9 +169,29 @@ export function localAdmissionToken(
160
169
  // deliberately and pass through verbatim; a path, by contrast, can be pointed at or replaced
161
170
  // by something that is not a credential at all, and sending that as one leaks file contents
162
171
  // into a request header. Configured keys are never checked, so no existing key can be broken.
163
- if (fileToken && ADMISSION_TOKEN_SHAPE.test(fileToken)) return fileToken;
172
+ if (fileToken && ADMISSION_TOKEN_SHAPE.test(fileToken)) candidates.push(fileToken);
164
173
  const configured = config?.apiKeys?.find(entry => entry.key.trim().length > 0)?.key.trim();
165
- return configured || undefined;
174
+ if (configured) candidates.push(configured);
175
+ return candidates;
176
+ }
177
+
178
+ /**
179
+ * The credential an in-process self-fetch (Advisor, routed helpers) presents to `destination`.
180
+ *
181
+ * A destination that demands admission gets the `localAdmissionToken` ladder unchanged. One that
182
+ * does not still receives the first ladder credential this data plane recognizes, because Chat
183
+ * applies that key's limits to an internal hop a loopback listener admitted without reading it
184
+ * (#7894). An unrecognized one, such as a hub client key a loopback bind deliberately left out of
185
+ * its admission credentials, is not sent: Chat refuses any credential it cannot resolve.
186
+ */
187
+ export function selfFetchAdmissionToken(
188
+ config: Pick<OcxConfig, "apiKeys"> | undefined,
189
+ destination: Pick<LocalInferenceDestination, "requiresAdmissionToken">,
190
+ env: NodeJS.ProcessEnv = process.env,
191
+ ): string | undefined {
192
+ const candidates = localAdmissionTokenCandidates(config, env);
193
+ if (destination.requiresAdmissionToken) return candidates[0];
194
+ return candidates.find(token => resolveDataPlaneAdmissionSecret(token, config ?? {}) !== null);
166
195
  }
167
196
 
168
197
  /** An admission credential is an opaque printable token — never JSON, a path, or multi-line. */
@@ -75,6 +75,15 @@ const LETTER_CONFUSABLES = new Map<string, string>([
75
75
  * not cover.
76
76
  */
77
77
  export function foldForMatching(value: string, decodeEscapes = true): { folded: string; map: number[] } {
78
+ // ASCII has no confusables, invisible format characters or NFKD changes. Without
79
+ // an escape introducer, decoding cannot change it either. Usage metadata passes
80
+ // through this fold repeatedly on ledger reads; keep its identity map without
81
+ // repeating Unicode normalization and escape matching for every character.
82
+ if (!/[^\x00-\x7f]/.test(value) && (!decodeEscapes || !/[\\%&]/.test(value))) {
83
+ const map = new Array<number>(value.length + 1);
84
+ for (let index = 0; index <= value.length; index += 1) map[index] = index;
85
+ return { folded: value, map };
86
+ }
78
87
  let folded = "";
79
88
  const map: number[] = [];
80
89
  // Serialization escapes are ALIASES for the label, not decoration: a JSON
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { constants, lstatSync, openSync, fstatSync, readFileSync, closeSync, type Stats } from "node:fs";
2
+ import { constants, lstatSync, openSync, fstatSync, readFileSync, closeSync, type BigIntStats } from "node:fs";
3
3
  import { join } from "node:path";
4
4
 
5
5
  /** Read an existing single-owner salt without creating or hardening any file. */
@@ -8,14 +8,14 @@ export function readExistingSpendSalt(home: string): string | undefined {
8
8
  let salt: string | undefined;
9
9
  try {
10
10
  const path = join(home, "spend-ledger.salt");
11
- const before = lstatSync(path);
12
- if (!before.isFile() || before.nlink !== 1) return undefined;
13
- const matches = (stat: Stats): boolean => stat.isFile() && stat.nlink === 1
11
+ const before = lstatSync(path, { bigint: true });
12
+ if (!before.isFile() || before.nlink !== 1n) return undefined;
13
+ const matches = (stat: BigIntStats): boolean => stat.isFile() && stat.nlink === 1n
14
14
  && stat.dev === before.dev && stat.ino === before.ino;
15
15
  fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
16
- if (!matches(fstatSync(fd))) return undefined;
16
+ if (!matches(fstatSync(fd, { bigint: true }))) return undefined;
17
17
  const contents = readFileSync(fd, "utf8").trim();
18
- if (matches(fstatSync(fd)) && matches(lstatSync(path)) && /^[0-9a-f]{32,}$/.test(contents)) salt = contents;
18
+ if (matches(fstatSync(fd, { bigint: true })) && matches(lstatSync(path, { bigint: true })) && /^[0-9a-f]{32,}$/.test(contents)) salt = contents;
19
19
  } catch { salt = undefined; }
20
20
  finally {
21
21
  if (fd !== undefined) {
@@ -11,6 +11,7 @@ import { reconcilePoolRotationState } from "../codex/pool-rotation";
11
11
  import { reconcileCodexQuotaAccounts } from "../codex/quota";
12
12
  import { reconcileQuotaRecovery, sweepExpiredQuotaRecovery } from "../codex/quota-401-recovery";
13
13
  import { bindUpstreamRequestCompressionConfig } from "../server/responses/request-compression";
14
+ import { bindWorkflowBudgetConfig } from "./workflow-budget-config";
14
15
  import {
15
16
  listLiveCodexAccountIds,
16
17
  reconcileCodexRoutingHealth,
@@ -82,6 +83,7 @@ export function setLiveStateStoreConfig(config: OcxConfig): void {
82
83
  // The one place the server's live config object is installed; detached configs (catalog sync)
83
84
  // never come through here, so the outbound compression opt-in follows the running server only.
84
85
  bindUpstreamRequestCompressionConfig(config);
86
+ bindWorkflowBudgetConfig(config);
85
87
  notifyLiveConfigObservers(config);
86
88
  }
87
89
 
@@ -191,7 +191,7 @@ function missingPreloadHint(): string {
191
191
  */
192
192
  export function isProtectedHomeUnderTest(dir: string): boolean {
193
193
  if (!isTestHomeGuardArmed()) return false;
194
- return canonicalize(dir) === PROTECTED_HOME;
194
+ return samePathIgnoringPlatformCase(canonicalize(dir), PROTECTED_HOME);
195
195
  }
196
196
 
197
197
  /**
@@ -204,7 +204,7 @@ export function isProtectedHomeUnderTest(dir: string): boolean {
204
204
  */
205
205
  export function assertNotRealHomeUnderTest(dir: string): void {
206
206
  if (!isTestHomeGuardArmed()) return;
207
- if (canonicalize(dir) !== PROTECTED_HOME) return;
207
+ if (!samePathIgnoringPlatformCase(canonicalize(dir), PROTECTED_HOME)) return;
208
208
  throw new Error(
209
209
  `refusing to write the real OpenCodex home (${PROTECTED_HOME}) from a test process. `
210
210
  + "Point OPENCODEX_HOME at a temp directory for this test, or inject persistence "
@@ -227,7 +227,7 @@ export function protectedLaunchAgentsDirForTests(): string {
227
227
  */
228
228
  export function assertNotRealLaunchAgentsUnderTest(dir: string): void {
229
229
  if (!isTestHomeGuardArmed()) return;
230
- if (canonicalize(dir) !== PROTECTED_LAUNCH_AGENTS) return;
230
+ if (!samePathIgnoringPlatformCase(canonicalize(dir), PROTECTED_LAUNCH_AGENTS)) return;
231
231
  throw new Error(
232
232
  `refusing to write the real LaunchAgents directory (${PROTECTED_LAUNCH_AGENTS}) from a test `
233
233
  + "process: os.homedir() ignores HOME, so rewriting HOME does not move this path. Pass an "
@@ -238,7 +238,7 @@ export function assertNotRealLaunchAgentsUnderTest(dir: string): void {
238
238
  /** Throw when an armed test process is about to write the real native Codex home. */
239
239
  export function assertNotRealCodexHomeUnderTest(dir: string): void {
240
240
  if (!isTestHomeGuardArmed()) return;
241
- if (canonicalize(dir) !== PROTECTED_CODEX_HOME) return;
241
+ if (!samePathIgnoringPlatformCase(canonicalize(dir), PROTECTED_CODEX_HOME)) return;
242
242
  throw new Error(
243
243
  `refusing to write the real Codex home (${PROTECTED_CODEX_HOME}) from a test process. `
244
244
  + "Point CODEX_HOME at a temp directory for this test before writing Codex files "
@@ -285,6 +285,15 @@ function foldPlatformCase(path: string): string {
285
285
  return process.platform === "darwin" || process.platform === "win32" ? path.toLowerCase() : path;
286
286
  }
287
287
 
288
+ /**
289
+ * Path equality as the default filesystem on this platform sees it. A not-yet-existing
290
+ * `.OPENCODEX` canonicalizes through its parent and keeps its spelling, so a plain `===`
291
+ * against the canonical home calls it a different directory on Windows and macOS (#7853).
292
+ */
293
+ function samePathIgnoringPlatformCase(a: string, b: string): boolean {
294
+ return foldPlatformCase(a) === foldPlatformCase(b);
295
+ }
296
+
288
297
  function isSameOrInsideIgnoringPlatformCase(root: string, candidate: string): boolean {
289
298
  const parent = foldPlatformCase(root);
290
299
  const child = foldPlatformCase(candidate);
@@ -322,10 +331,29 @@ export function protectedRemovalTreesForTests(): readonly string[] {
322
331
  return [PROTECTED_REAL_HOME, ...PROTECTED_TREES.map(tree => tree.path)];
323
332
  }
324
333
 
325
- /** Whether `child` sits strictly below `parent`, both already canonicalized. */
334
+ /**
335
+ * Whether `child` sits strictly below `parent`, both already canonicalized.
336
+ *
337
+ * Containment is decided per path component, with case folded where the filesystem folds it.
338
+ * A prefix test on the relative path called a direct child named `..backup` "outside", so the
339
+ * removal guard let it through (#7853).
340
+ */
326
341
  function isInside(parent: string, child: string): boolean {
342
+ return !samePathIgnoringPlatformCase(parent, child) && isSameOrInsideIgnoringPlatformCase(parent, child);
343
+ }
344
+
345
+ /**
346
+ * Whether `child` sits strictly below `parent` with case PRESERVED, deciding per path component.
347
+ *
348
+ * Only for the checkout exemption below, which LIFTS a refusal. Folding case there would let a
349
+ * running checkout at `~/.codex/worktrees/repo` exempt a distinct `~/.codex/worktrees/REPO` on a
350
+ * case-sensitive macOS volume. Protection decisions fold, because comparing too broadly only refuses
351
+ * more; an exemption must not, because the same breadth removes more.
352
+ */
353
+ function isInsidePreservingCase(parent: string, child: string): boolean {
354
+ if (parent === child) return false;
327
355
  const rel = relative(parent, child);
328
- return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
356
+ return rel !== "" && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
329
357
  }
330
358
 
331
359
  let checkoutRootSpellings: readonly string[] | undefined;
@@ -362,7 +390,7 @@ function checkoutRoots(): readonly string[] {
362
390
  * tree (one at `$HOME`, or the virtual root of a compiled build) never qualifies.
363
391
  */
364
392
  function isOwnCheckoutContent(protectedPath: string, candidate: string): boolean {
365
- return checkoutRoots().some(root => isInside(protectedPath, root) && isInside(root, candidate));
393
+ return checkoutRoots().some(root => isInsidePreservingCase(protectedPath, root) && isInsidePreservingCase(root, candidate));
366
394
  }
367
395
 
368
396
  /**
@@ -387,12 +415,12 @@ export function protectedRemovalReason(target: string): string | null {
387
415
  // form still names it. Upstream Codex makes the same distinction in its writable-root
388
416
  // handling, keeping logical and resolved forms side by side rather than collapsing to one.
389
417
  for (const candidate of [canonicalize(target), resolve(target)]) {
390
- if (candidate === PROTECTED_REAL_HOME || candidate === LEXICAL_REAL_HOME) {
418
+ if (samePathIgnoringPlatformCase(candidate, PROTECTED_REAL_HOME) || samePathIgnoringPlatformCase(candidate, LEXICAL_REAL_HOME)) {
391
419
  return `the real home directory (${PROTECTED_REAL_HOME})`;
392
420
  }
393
421
  for (const tree of PROTECTED_TREES) {
394
422
  for (const protectedPath of [tree.path, tree.lexical]) {
395
- if (candidate === protectedPath) return `${tree.label} (${protectedPath})`;
423
+ if (samePathIgnoringPlatformCase(candidate, protectedPath)) return `${tree.label} (${protectedPath})`;
396
424
  if (isInside(protectedPath, candidate) && !isOwnCheckoutContent(protectedPath, candidate)) {
397
425
  return `a path inside ${tree.label} (${protectedPath})`;
398
426
  }
@@ -660,10 +660,10 @@ export function windowsSecretAclReapPendingForPath(targetPath: string): boolean
660
660
  }
661
661
 
662
662
  /** Non-blocking removal guard for callers that must refuse rather than wait for a stuck child. */
663
- export function windowsSecretAclReapPendingAtOrBelow(rootPath: string): boolean {
663
+ export function windowsSecretAclReapPendingAtOrBelow(rootPath: string, includeAncestors = false): boolean {
664
664
  const root = captureRemovalIdentity(rootPath);
665
665
  return [...activeAsyncAclWork.values(), ...pendingAsyncIcaclsReaps.values()]
666
- .some(entries => [...entries].some(entry => retainedWorkIsAtOrBelow(entry, root)));
666
+ .some(entries => [...entries].some(entry => retainedWorkIsAtOrBelow(entry, root, includeAncestors)));
667
667
  }
668
668
 
669
669
  /**
@@ -1207,37 +1207,55 @@ function isTimeoutError(error: unknown): boolean {
1207
1207
  * which is optional and simply omitted when it is not an allowlisted code.
1208
1208
  */
1209
1209
  function sanitizeAclFailure(cause: unknown): AclFailureDiagnostics | undefined {
1210
- if (!cause || typeof cause !== "object" || !("aclFailure" in cause)) return undefined;
1211
- const raw = (cause as { aclFailure?: unknown }).aclFailure;
1212
- if (!raw || typeof raw !== "object") return undefined;
1213
- const f = raw as Record<string, unknown>;
1214
- if (typeof f.step !== "string" || !ICACLS_STEPS.has(f.step)) return undefined;
1215
- if (
1216
- f.stage !== "deadline_before_spawn" &&
1217
- f.stage !== "spawn_failed" &&
1218
- f.stage !== "runner_rejected" &&
1219
- f.stage !== "runner_watchdog" &&
1220
- f.stage !== "child_result"
1221
- ) {
1222
- return undefined;
1223
- }
1224
- if (typeof f.elapsedMs !== "number" || !Number.isFinite(f.elapsedMs)) return undefined;
1225
- if (typeof f.budgetMs !== "number" || !Number.isFinite(f.budgetMs)) return undefined;
1226
- if (typeof f.success !== "boolean" || typeof f.timedOut !== "boolean") return undefined;
1227
- if (f.exitCode !== null && (typeof f.exitCode !== "number" || !Number.isFinite(f.exitCode))) {
1210
+ // Every read off the untrusted cause — the `in` check, the `aclFailure`
1211
+ // access and each field — may be a throwing accessor or a getter that
1212
+ // returns a different value on the next read. Each field is therefore read
1213
+ // exactly once into a local, and only that local is validated and copied;
1214
+ // a read that throws drops the whole record rather than letting a raw
1215
+ // hostile exception replace the sanitized required-mode error.
1216
+ try {
1217
+ if (!cause || typeof cause !== "object" || !("aclFailure" in cause)) return undefined;
1218
+ const raw = (cause as { aclFailure?: unknown }).aclFailure;
1219
+ if (!raw || typeof raw !== "object") return undefined;
1220
+ const f = raw as Record<string, unknown>;
1221
+ const step = f.step;
1222
+ if (typeof step !== "string" || !ICACLS_STEPS.has(step)) return undefined;
1223
+ const stage = f.stage;
1224
+ if (
1225
+ stage !== "deadline_before_spawn" &&
1226
+ stage !== "spawn_failed" &&
1227
+ stage !== "runner_rejected" &&
1228
+ stage !== "runner_watchdog" &&
1229
+ stage !== "child_result"
1230
+ ) {
1231
+ return undefined;
1232
+ }
1233
+ const elapsedMs = f.elapsedMs;
1234
+ if (typeof elapsedMs !== "number" || !Number.isFinite(elapsedMs)) return undefined;
1235
+ const budgetMs = f.budgetMs;
1236
+ if (typeof budgetMs !== "number" || !Number.isFinite(budgetMs)) return undefined;
1237
+ const success = f.success;
1238
+ if (typeof success !== "boolean") return undefined;
1239
+ const timedOut = f.timedOut;
1240
+ if (typeof timedOut !== "boolean") return undefined;
1241
+ const exitCode = f.exitCode;
1242
+ if (exitCode !== null && (typeof exitCode !== "number" || !Number.isFinite(exitCode))) {
1243
+ return undefined;
1244
+ }
1245
+ const spawnErrorCode = allowlistedSpawnErrorCode(f.spawnErrorCode);
1246
+ return {
1247
+ step: step as IcaclsStep,
1248
+ stage,
1249
+ elapsedMs,
1250
+ budgetMs,
1251
+ success,
1252
+ exitCode: exitCode as number | null,
1253
+ timedOut,
1254
+ ...(spawnErrorCode !== undefined ? { spawnErrorCode } : {}),
1255
+ };
1256
+ } catch {
1228
1257
  return undefined;
1229
1258
  }
1230
- const spawnErrorCode = allowlistedSpawnErrorCode(f.spawnErrorCode);
1231
- return {
1232
- step: f.step as IcaclsStep,
1233
- stage: f.stage,
1234
- elapsedMs: f.elapsedMs,
1235
- budgetMs: f.budgetMs,
1236
- success: f.success,
1237
- exitCode: f.exitCode as number | null,
1238
- timedOut: f.timedOut,
1239
- ...(spawnErrorCode !== undefined ? { spawnErrorCode } : {}),
1240
- };
1241
1259
  }
1242
1260
 
1243
1261
  /** Preserve only the bounded machine-readable cause on a sanitized public error. */
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The workflow-budget policy the running server enforces.
3
+ *
4
+ * The ceilings in workflow-budget.ts are module defaults, and a busy install that legitimately
5
+ * runs more parallel subagents than they allow had no way to say so short of patching the
6
+ * package. This binds the live config the same way the outbound compression opt-in does: the
7
+ * object is installed once, read per decision, and a dashboard write that mutates it in place
8
+ * takes effect on the next request without a restart.
9
+ *
10
+ * Only the three count ceilings move. The window, the interactive reserve and the tracked-root
11
+ * bound stay where they are: the window fixes each root's ring geometry when the root first
12
+ * appears, so changing it live would leave existing roots measured on a scale no caller reads.
13
+ */
14
+ import { readWorkflowBudgetConfig } from "../config/schema/workflow-budget";
15
+ import type { OcxConfig } from "../types";
16
+ import { DEFAULT_WORKFLOW_BUDGET_POLICY, type WorkflowBudgetPolicy } from "./workflow-budget";
17
+
18
+ let boundConfig: Pick<OcxConfig, "workflowBudget"> | null = null;
19
+
20
+ export function bindWorkflowBudgetConfig(config: Pick<OcxConfig, "workflowBudget"> | null): void {
21
+ boundConfig = config;
22
+ }
23
+
24
+ export function resolveWorkflowBudgetPolicy(config: Pick<OcxConfig, "workflowBudget">): WorkflowBudgetPolicy {
25
+ const overrides = readWorkflowBudgetConfig(config);
26
+ return {
27
+ ...DEFAULT_WORKFLOW_BUDGET_POLICY,
28
+ ...(overrides.maxConcurrentChildren !== undefined ? { maxConcurrentChildren: overrides.maxConcurrentChildren } : {}),
29
+ ...(overrides.maxPhysicalSends !== undefined ? { maxPhysicalSends: overrides.maxPhysicalSends } : {}),
30
+ ...(overrides.maxDistinctChildren !== undefined ? { maxDistinctChildren: overrides.maxDistinctChildren } : {}),
31
+ };
32
+ }
33
+
34
+ /** Policy for the next admission or ceiling check; an unset block is the module default itself. */
35
+ export function currentWorkflowBudgetPolicy(): WorkflowBudgetPolicy {
36
+ return boundConfig?.workflowBudget === undefined
37
+ ? DEFAULT_WORKFLOW_BUDGET_POLICY
38
+ : resolveWorkflowBudgetPolicy(boundConfig);
39
+ }
@@ -212,8 +212,12 @@ export function claimCredentialObservation(home: string, scan: (accounts: readon
212
212
  });
213
213
  }
214
214
  /**
215
- * Advance on every observed event and rescan; a failed scan leaves an empty vector, which never
216
- * attests. It never waits for the fence: the runtime observer retries asynchronously instead.
215
+ * Advance on every observed coverage-relevant event and rescan; a failed scan leaves an empty
216
+ * vector, which never attests. It never waits for the fence: the runtime observer retries
217
+ * asynchronously instead. "Coverage-relevant" is the watcher's classification in inventory.ts:
218
+ * every event on a target name, credential-write residue, or ancestor structural change --
219
+ * but not an ancestor directory's last-write tick from ordinary child churn, which reports no
220
+ * credential change and would re-arm the observer's own save forever.
217
221
  */
218
222
  export function updateCredentialObservation(home: string, owner: string, scan: ((accounts: readonly string[]) => string) | null): void {
219
223
  withCredentialPublicationFence(home, () => {