@bitkyc08/opencodex 2.96.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-bwugJRKn.js → App-DuNhggE1.js} +15 -15
  3. package/gui/dist/assets/{Tray-BOPQyDbH.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-6HsrHQAy.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +11 -1
  16. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  17. package/src/adapters/openai-responses/passthrough.ts +5 -4
  18. package/src/adapters/openai-responses/reasoning.ts +9 -4
  19. package/src/adapters/openai-responses/request-strips.ts +1 -1
  20. package/src/adapters/physical-send.ts +3 -3
  21. package/src/adapters/zed-openai-stream.ts +2 -1
  22. package/src/bridge/errors.ts +11 -2
  23. package/src/bridge/response-json.ts +2 -1
  24. package/src/bridge/sse.ts +14 -6
  25. package/src/chat/failure-verdict.ts +21 -0
  26. package/src/chat/outbound.ts +139 -21
  27. package/src/claude/outbound.ts +49 -2
  28. package/src/cli/capabilities-base.ts +25 -3
  29. package/src/cli/capabilities-command.ts +12 -3
  30. package/src/cli/capability-contracts.ts +2 -0
  31. package/src/cli/codex-launch-auth.ts +30 -1
  32. package/src/cli/codex-launcher.ts +12 -5
  33. package/src/cli/codex-shim-autorestore.ts +5 -4
  34. package/src/cli/dispatch.ts +11 -176
  35. package/src/cli/help.ts +2 -2
  36. package/src/cli/index.ts +5 -1
  37. package/src/cli/link.ts +1 -1
  38. package/src/cli/registry.ts +11 -3
  39. package/src/cli/root.ts +8 -0
  40. package/src/cli/sync-command.ts +243 -0
  41. package/src/cli/sync-fanout-process.ts +92 -0
  42. package/src/cli/sync-fanout.ts +150 -0
  43. package/src/cli/sync-flags.ts +10 -0
  44. package/src/cli/sync-link-status.ts +39 -0
  45. package/src/cli/sync-update-guard.ts +18 -0
  46. package/src/client/connect.ts +31 -14
  47. package/src/client/link-home.ts +3 -2
  48. package/src/client/machine-listener.ts +3 -0
  49. package/src/client/restore-ownership.ts +19 -1
  50. package/src/client/runtime-restart.ts +12 -4
  51. package/src/client/runtime.ts +40 -11
  52. package/src/client/stop-routing.ts +62 -0
  53. package/src/client/sync-runtime.ts +65 -0
  54. package/src/clients/config-export.ts +32 -3
  55. package/src/codex/auth-context.ts +49 -103
  56. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  57. package/src/codex/catalog/provider-models.ts +6 -8
  58. package/src/codex/forward-transport-headers.ts +35 -6
  59. package/src/codex/inject/config-toml.ts +88 -0
  60. package/src/codex/inject/multi-agent-v2.ts +30 -4
  61. package/src/codex/inject/plan.ts +34 -7
  62. package/src/codex/inject-coordination.ts +11 -0
  63. package/src/codex/inject.ts +18 -7
  64. package/src/codex/lineage.ts +13 -7
  65. package/src/codex/quota.ts +22 -6
  66. package/src/codex/request-owned-affinity-key.ts +11 -0
  67. package/src/codex/request-owned-affinity.ts +118 -0
  68. package/src/codex/request-owned-main-pin.ts +86 -0
  69. package/src/codex/role-capability.ts +52 -41
  70. package/src/codex/routing/active-account.ts +13 -5
  71. package/src/codex/routing/selection.ts +40 -1
  72. package/src/codex/routing/thread-affinity-store.ts +916 -0
  73. package/src/codex/routing/thread-affinity.ts +90 -12
  74. package/src/codex/toml-source-lines.ts +72 -13
  75. package/src/combos/failover.ts +6 -109
  76. package/src/combos/request.ts +2 -2
  77. package/src/combos/resolve.ts +29 -11
  78. package/src/config/process-state.ts +5 -0
  79. package/src/config/schema/leaf-validators.ts +1 -0
  80. package/src/generated/compatibility-version.json +433 -165
  81. package/src/images/loop.ts +2 -1
  82. package/src/lib/client-error-body.ts +184 -0
  83. package/src/lib/client-retry-after.ts +66 -0
  84. package/src/lib/config-ownership.ts +4 -0
  85. package/src/lib/context-overflow-verdict.ts +113 -0
  86. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  87. package/src/lib/desktop-cli-handoff.mjs +11 -1
  88. package/src/lib/empty-tool-catalog.ts +25 -3
  89. package/src/lib/error-destination.ts +47 -0
  90. package/src/lib/failure-detail.ts +66 -0
  91. package/src/lib/model-identity.ts +44 -0
  92. package/src/lib/private-sqlite-path.ts +124 -0
  93. package/src/lib/response-service-tier.ts +17 -0
  94. package/src/lib/retry-after.ts +3 -0
  95. package/src/lib/spend-ledger-owner.ts +43 -4
  96. package/src/lib/upstream-condition.ts +142 -0
  97. package/src/lib/upstream-retry.ts +14 -11
  98. package/src/lib/windows-owner-acl.ts +13 -6
  99. package/src/link/remote-platform.ts +14 -0
  100. package/src/link/remote-windows.ts +51 -9
  101. package/src/link/ssh-argv.ts +63 -10
  102. package/src/oauth/generic-account-failover.ts +13 -11
  103. package/src/oauth/index.ts +36 -74
  104. package/src/oauth/oauth-errors.ts +67 -0
  105. package/src/oauth/store.ts +1 -1
  106. package/src/protocols/codecs/ollama.ts +197 -0
  107. package/src/protocols/encoders/adapter-events.ts +4 -0
  108. package/src/protocols/encoders/chat.ts +18 -10
  109. package/src/protocols/trace.ts +18 -0
  110. package/src/providers/fastwire.ts +3 -2
  111. package/src/providers/quota/anthropic-usage-windows.ts +13 -3
  112. package/src/providers/quota/vendor-probes-key.ts +60 -24
  113. package/src/providers/request-pacing.ts +3 -2
  114. package/src/responses/apply-patch-envelope.ts +45 -19
  115. package/src/responses/compaction-history-framing.ts +5 -1
  116. package/src/responses/freeform-wrapper-scan.ts +5 -3
  117. package/src/responses/progressive-freeform-input.ts +354 -45
  118. package/src/routing/fallback-policy.ts +3 -1
  119. package/src/server/admission-model-scope.ts +17 -6
  120. package/src/server/admitted-http-turn.ts +56 -0
  121. package/src/server/auth-cors.ts +5 -0
  122. package/src/server/chat-completions.ts +45 -20
  123. package/src/server/chat-native-sse.ts +52 -7
  124. package/src/server/chat-native.ts +60 -35
  125. package/src/server/claude-bridge-pool-session.ts +59 -0
  126. package/src/server/claude-messages.ts +51 -24
  127. package/src/server/context-history.ts +5 -1
  128. package/src/server/inbound-body-admission.ts +11 -4
  129. package/src/server/index/ollama-routes.ts +89 -0
  130. package/src/server/index/serve-options.ts +21 -4
  131. package/src/server/index/websocket-handler.ts +4 -2
  132. package/src/server/index.ts +6 -36
  133. package/src/server/inference/client-encoder-delivery.ts +4 -2
  134. package/src/server/json-serialized-bytes.ts +44 -0
  135. package/src/server/management/agent-settings-routes.ts +24 -21
  136. package/src/server/management/codex-cli-update-routes.ts +2 -1
  137. package/src/server/management/route-registry.ts +1 -1
  138. package/src/server/messages-native-scope.ts +2 -1
  139. package/src/server/messages-native-tool-guard.ts +1 -1
  140. package/src/server/messages-native.ts +12 -7
  141. package/src/server/messages-shared.ts +6 -2
  142. package/src/server/native-final-log.ts +93 -0
  143. package/src/server/ollama-inbound.ts +349 -0
  144. package/src/server/ollama-native-paths.ts +21 -0
  145. package/src/server/ollama-route-policy.ts +73 -0
  146. package/src/server/relay.ts +22 -3
  147. package/src/server/request-decompress.ts +4 -2
  148. package/src/server/request-log-failure-attribution.ts +22 -0
  149. package/src/server/request-log-failure-detail.ts +80 -0
  150. package/src/server/request-log-terminal-status.ts +4 -2
  151. package/src/server/request-log.ts +79 -42
  152. package/src/server/response-log-body.ts +6 -1
  153. package/src/server/responses/account-change-state.ts +17 -6
  154. package/src/server/responses/adapter-continuation.ts +9 -4
  155. package/src/server/responses/adapter-delivery.ts +5 -4
  156. package/src/server/responses/adapter-dispatch.ts +31 -30
  157. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  158. package/src/server/responses/codex-auth-error.ts +19 -18
  159. package/src/server/responses/codex-ws-exchange.ts +11 -8
  160. package/src/server/responses/codex-ws-metadata.ts +94 -21
  161. package/src/server/responses/codex-ws-request.ts +3 -1
  162. package/src/server/responses/compact.ts +53 -23
  163. package/src/server/responses/compaction-recovery.ts +4 -2
  164. package/src/server/responses/compaction-routing.ts +9 -4
  165. package/src/server/responses/core-auth.ts +32 -14
  166. package/src/server/responses/core-codex-account.ts +17 -6
  167. package/src/server/responses/core-combo-failure.ts +5 -1
  168. package/src/server/responses/core-combo-native.ts +2 -1
  169. package/src/server/responses/core-combo.ts +41 -27
  170. package/src/server/responses/core-errors.ts +22 -20
  171. package/src/server/responses/core-lifetime.ts +6 -3
  172. package/src/server/responses/core-normalize.ts +1 -0
  173. package/src/server/responses/core-options.ts +7 -0
  174. package/src/server/responses/core-pipeline.ts +4 -3
  175. package/src/server/responses/fetch-helpers.ts +7 -1
  176. package/src/server/responses/input-admission.ts +28 -2
  177. package/src/server/responses/native-injection.ts +1 -1
  178. package/src/server/responses/native-response-json.ts +13 -4
  179. package/src/server/responses/native-response-output.ts +1 -2
  180. package/src/server/responses/non-replayable-error.ts +2 -1
  181. package/src/server/responses/pacing-overload.ts +3 -2
  182. package/src/server/responses/passthrough-delivery.ts +55 -14
  183. package/src/server/responses/passthrough-dispatch.ts +19 -17
  184. package/src/server/responses/passthrough-error.ts +9 -9
  185. package/src/server/responses/policy-fallback.ts +2 -1
  186. package/src/server/responses/request-prepare.ts +67 -48
  187. package/src/server/responses/request-transport.ts +35 -31
  188. package/src/server/responses/run-turn-execution.ts +6 -6
  189. package/src/server/responses/sidecar-execution.ts +16 -12
  190. package/src/server/responses/spend-storage-error.ts +2 -1
  191. package/src/server/responses/ws-upstream.ts +9 -0
  192. package/src/server/responses-custom-tool-repair.ts +14 -3
  193. package/src/server/responses-terminal-repair.ts +5 -2
  194. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  195. package/src/server/safe-response-headers.ts +162 -13
  196. package/src/server/turn-state-handles.ts +164 -0
  197. package/src/server/workflow-refusal.ts +2 -1
  198. package/src/service/ownership-mutation-lease.d.mts +11 -2
  199. package/src/service/ownership-mutation-lease.mjs +53 -11
  200. package/src/types/config.ts +2 -0
  201. package/src/update/index.ts +133 -25
  202. package/src/update/npm-install.d.mts +8 -0
  203. package/src/update/npm-install.mjs +20 -1
  204. package/src/update/orchestrated-admission.d.mts +4 -0
  205. package/src/update/orchestrated-admission.mjs +12 -0
  206. package/src/update/orchestrated-arguments.d.mts +12 -0
  207. package/src/update/orchestrated-arguments.mjs +64 -0
  208. package/src/update/orchestrated-child.d.mts +12 -0
  209. package/src/update/orchestrated-child.mjs +70 -0
  210. package/src/update/orchestrated-entry.ts +234 -0
  211. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  212. package/src/update/orchestrated-identity.ts +53 -0
  213. package/src/update/orchestrated-live-identity.ts +48 -0
  214. package/src/update/orchestrated-node-driver.mjs +99 -0
  215. package/src/update/orchestrated-outcome.d.mts +21 -0
  216. package/src/update/orchestrated-outcome.mjs +40 -0
  217. package/src/update/orchestrated-plan.ts +49 -0
  218. package/src/update/orchestrated-pnpm.d.mts +8 -0
  219. package/src/update/orchestrated-pnpm.mjs +33 -0
  220. package/src/update/orchestrated-session.d.mts +37 -0
  221. package/src/update/orchestrated-session.mjs +264 -0
  222. package/src/update/orchestrated-token.d.mts +10 -0
  223. package/src/update/orchestrated-token.mjs +21 -0
  224. package/src/update/orchestrated-token.ts +3 -0
  225. package/src/update/orchestrated-tree.d.mts +1 -0
  226. package/src/update/orchestrated-tree.mjs +14 -0
  227. package/src/update/pnpm-global-install.d.mts +6 -0
  228. package/src/update/pnpm-global-install.mjs +9 -2
  229. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  230. package/src/update/posix-install-supervisor.d.mts +10 -0
  231. package/src/update/posix-install-supervisor.mjs +88 -0
  232. package/src/update/sync-update-mutex.d.mts +10 -0
  233. package/src/update/sync-update-mutex.mjs +164 -0
  234. package/src/update/sync-update-mutex.ts +1 -0
  235. package/src/update/test-home-guard.mjs +33 -0
  236. package/src/update/transactional-install.mjs +2 -2
  237. package/src/usage/error-detail.ts +225 -0
  238. package/src/usage/log.ts +60 -27
  239. package/src/web-search/loop.ts +31 -5
  240. package/gui/dist/assets/index-ebuVUtB7.js +0 -94
@@ -0,0 +1,164 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHash } from "node:crypto";
3
+
4
+ /**
5
+ * Proxy-owned handles for the Codex turn-state token.
6
+ *
7
+ * Codex reads `x-codex-turn-state` from a response (or the WebSocket upgrade) and sends it back on
8
+ * later requests of the same turn, so the upstream can keep the turn on one backend. The client
9
+ * receives a random handle this proxy generates instead of the upstream bytes. Each handle is bound
10
+ * at issuance to the admitted caller, the selected provider and the outbound account, and maps back
11
+ * to the upstream token here, in process memory, only at the physical send of a request with the
12
+ * same binding. A mismatched, unknown or expired handle is not forwarded. The map is bounded (oldest
13
+ * entries are evicted) and entries expire. Handles, tokens and bindings are never logged.
14
+ */
15
+
16
+ export const TURN_STATE_HEADER = "x-codex-turn-state";
17
+ /** Where the provider fetch attaches a send's binding on the RequestInit it hands the WebSocket upstream. */
18
+ export const TURN_STATE_BINDING_INIT: unique symbol = Symbol("opencodex.turn-state-binding");
19
+ const HANDLE_PREFIX = "ocx-ts-";
20
+ const HANDLE = /^ocx-ts-[0-9a-f]{32}$/;
21
+ const MAX_HANDLES = 4096;
22
+ const HANDLE_TTL_MS = 6 * 60 * 60 * 1000;
23
+
24
+ type Entry = { value: string; binding: string; expiresAt: number };
25
+ const byHandle = new Map<string, Entry>();
26
+ const byBoundValue = new Map<string, string>();
27
+
28
+ // The admitted caller of the request being served. Admission records it; the provider fetch reads it.
29
+ type CallerScope = { caller?: string };
30
+ const callerScope = new AsyncLocalStorage<CallerScope>();
31
+
32
+ /** Run one request (or one WebSocket frame) with its own caller slot. */
33
+ export function runTurnStateCallerScope<T>(run: () => T): T {
34
+ return callerScope.run({}, run);
35
+ }
36
+
37
+ /** Record the admitted caller for the current request: a configured key id, an environment principal, or loopback. */
38
+ export function noteTurnStateCaller(admission: { kind: string; keyId?: string; contextPrincipalId?: string }): void {
39
+ const scope = callerScope.getStore();
40
+ if (!scope) return;
41
+ scope.caller = admission.kind === "configured" ? `configured:${admission.keyId ?? ""}`
42
+ : admission.kind === "environment" ? `environment:${admission.contextPrincipalId ?? ""}` : admission.kind;
43
+ }
44
+
45
+ /**
46
+ * The binding of an outbound send: a digest of the admitted caller, the provider name and the account
47
+ * the send goes out as (the ChatGPT account id, or the outbound credential when there is none).
48
+ */
49
+ export function turnStateBinding(providerName: string, headers: Headers): string {
50
+ const account = headers.get("chatgpt-account-id")?.trim() ?? "";
51
+ const credential = account ? "" : headers.get("authorization") ?? "";
52
+ return createHash("sha256")
53
+ .update(JSON.stringify([callerScope.getStore()?.caller ?? "unadmitted", providerName, account, credential]))
54
+ .digest("hex");
55
+ }
56
+
57
+ function randomHandle(): string {
58
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
59
+ return HANDLE_PREFIX + Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
60
+ }
61
+
62
+ function boundKey(entry: { binding: string; value: string }): string {
63
+ return entry.binding + "\0" + entry.value;
64
+ }
65
+
66
+ function live(handle: string, now: number): Entry | undefined {
67
+ const entry = byHandle.get(handle);
68
+ if (!entry) return undefined;
69
+ if (entry.expiresAt > now) return entry;
70
+ byHandle.delete(handle);
71
+ if (byBoundValue.get(boundKey(entry)) === handle) byBoundValue.delete(boundKey(entry));
72
+ return undefined;
73
+ }
74
+
75
+ /** True for a handle this proxy issued that has not expired. */
76
+ export function isLiveTurnStateHandle(value: string, now = Date.now()): boolean {
77
+ return HANDLE.test(value) && live(value, now) !== undefined;
78
+ }
79
+
80
+ /** The handle a client receives for an upstream turn-state token under `binding`; a live handle is returned as is. */
81
+ export function issueTurnStateHandle(value: string, binding: string, now = Date.now()): string {
82
+ if (isLiveTurnStateHandle(value, now)) return value;
83
+ const key = boundKey({ binding, value });
84
+ const existing = byBoundValue.get(key);
85
+ if (existing && live(existing, now)) return existing;
86
+ const handle = randomHandle();
87
+ byHandle.set(handle, { value, binding, expiresAt: now + HANDLE_TTL_MS });
88
+ byBoundValue.set(key, handle);
89
+ while (byHandle.size > MAX_HANDLES) {
90
+ const [oldest, entry] = byHandle.entries().next().value as [string, Entry];
91
+ byHandle.delete(oldest);
92
+ if (byBoundValue.get(boundKey(entry)) === oldest) byBoundValue.delete(boundKey(entry));
93
+ }
94
+ return handle;
95
+ }
96
+
97
+ export type TurnStateResolution = { value: string } | { dropped: "unknown" | "mismatch" };
98
+
99
+ /**
100
+ * What to forward for an inbound turn-state under `binding`: the upstream token for a live handle
101
+ * with the same binding, nothing for an unknown, expired or differently bound handle, and any other
102
+ * value unchanged (it did not come from a handle).
103
+ */
104
+ export function resolveTurnStateHandle(value: string, binding: string, now = Date.now()): TurnStateResolution {
105
+ if (!value.startsWith(HANDLE_PREFIX)) return { value };
106
+ const entry = live(value, now);
107
+ if (!entry) return { dropped: "unknown" };
108
+ return entry.binding === binding ? { value: entry.value } : { dropped: "mismatch" };
109
+ }
110
+
111
+ /** Fixed service-log flag for a handle presented under a different binding; it never names the handle. */
112
+ export const TURN_STATE_MISMATCH_NOTICE = "[opencodex] turn_state_binding_mismatch: a turn-state handle was not forwarded";
113
+ const MISMATCH_NOTICE_INTERVAL_MS = 60_000;
114
+ let lastMismatchNotice = 0;
115
+
116
+ function redeem(value: string, binding: string): string | undefined {
117
+ const resolution = resolveTurnStateHandle(value, binding);
118
+ if ("value" in resolution) return resolution.value;
119
+ if (resolution.dropped === "mismatch" && Date.now() - lastMismatchNotice >= MISMATCH_NOTICE_INTERVAL_MS) {
120
+ lastMismatchNotice = Date.now();
121
+ console.warn(TURN_STATE_MISMATCH_NOTICE);
122
+ }
123
+ return undefined;
124
+ }
125
+
126
+ function record(value: unknown): value is Record<string, unknown> {
127
+ return value !== null && typeof value === "object" && !Array.isArray(value);
128
+ }
129
+
130
+ /**
131
+ * Translate turn-state handles in an outbound send, after admission and routing: the request header
132
+ * and `client_metadata["x-codex-turn-state"]` in a JSON body. The init is returned unchanged when it
133
+ * carries no handle, so ordinary sends keep their exact headers and body bytes.
134
+ */
135
+ export function redeemOutboundTurnState(init: RequestInit | undefined, binding: string): RequestInit | undefined {
136
+ if (!init) return init;
137
+ let next: RequestInit = init;
138
+ const headers = new Headers(init.headers);
139
+ const header = headers.get(TURN_STATE_HEADER);
140
+ if (header !== null && header.startsWith(HANDLE_PREFIX)) {
141
+ const value = redeem(header, binding);
142
+ if (value === undefined) headers.delete(TURN_STATE_HEADER); else headers.set(TURN_STATE_HEADER, value);
143
+ next = { ...next, headers };
144
+ }
145
+ if (typeof init.body === "string" && init.body.includes(HANDLE_PREFIX)) {
146
+ let body: unknown;
147
+ try { body = JSON.parse(init.body); } catch { return next; }
148
+ const metadata = record(body) ? body.client_metadata : undefined;
149
+ const handle = record(metadata) ? metadata[TURN_STATE_HEADER] : undefined;
150
+ if (record(body) && record(metadata) && typeof handle === "string" && handle.startsWith(HANDLE_PREFIX)) {
151
+ const value = redeem(handle, binding);
152
+ const nextMetadata = { ...metadata };
153
+ if (value === undefined) delete nextMetadata[TURN_STATE_HEADER]; else nextMetadata[TURN_STATE_HEADER] = value;
154
+ next = { ...next, body: JSON.stringify({ ...body, client_metadata: nextMetadata }) };
155
+ }
156
+ }
157
+ return next;
158
+ }
159
+
160
+ export function resetTurnStateHandlesForTests(): void {
161
+ byHandle.clear();
162
+ byBoundValue.clear();
163
+ lastMismatchNotice = 0;
164
+ }
@@ -1,3 +1,4 @@
1
+ import { markProxyError } from "../lib/client-error-body";
1
2
  import { sharedPoolContinuityDenial } from "../lib/spend-reservation-ledger";
2
3
  /**
3
4
  * The one place that knows how this proxy refuses a turn on its own workflow budget.
@@ -98,7 +99,7 @@ export function workflowRefusalResponse(
98
99
  // Without this a browser dashboard cannot read the header at all: the data plane never sets
99
100
  // Access-Control-Expose-Headers, so a cross-origin reader sees only the CORS-safelisted ones.
100
101
  refusal.headers.set("Access-Control-Expose-Headers", WORKFLOW_LOCAL_REFUSAL_HEADER);
101
- return refusal;
102
+ return markProxyError(refusal);
102
103
  }
103
104
 
104
105
  /** Render the approved conservative-overlay explanation after a dispatch reservation refuses. */
@@ -7,6 +7,11 @@ export interface OwnershipMutationLeaseOptions {
7
7
  readonly joinToken?: string;
8
8
  /** Names the current executable at the recorded PID, identity unverified; uses `ps` on POSIX and omits the default image lookup on Windows. */
9
9
  readonly processImage?: (pid: number) => string | null;
10
+ /** Isolated locks cannot re-enter or inherit ownership delegation. */
11
+ readonly isolated?: boolean;
12
+ readonly holderKind?: "sync" | "update";
13
+ /** Explicit canonical lock path for isolated callers with no state-file authority. */
14
+ readonly lockPath?: string;
10
15
  }
11
16
 
12
17
  /** The recorded lease owner, identity unverified, read for diagnostics; never used to reclaim it. */
@@ -14,8 +19,11 @@ export interface OwnershipMutationLeaseHolder {
14
19
  readonly path: string;
15
20
  /** The recorded PID; null when the directory holds no parseable owner. */
16
21
  readonly pid: number | null;
22
+ readonly delegatePid: number | null;
23
+ readonly holderAlive: boolean | null;
17
24
  /** Liveness of the current process at the recorded PID; identity is not verified. */
18
25
  readonly alive: boolean | null;
26
+ readonly holderKind: "sync" | "update" | null;
19
27
  /** The current executable at the recorded PID when alive and readable; identity is not verified. */
20
28
  readonly image: string | null;
21
29
  /** Milliseconds since the owner was written, on the clock stale recovery uses. */
@@ -23,9 +31,10 @@ export interface OwnershipMutationLeaseHolder {
23
31
  readonly record: "complete" | "incomplete" | "empty" | "unreadable";
24
32
  }
25
33
 
26
- export interface OwnershipMutationLease { readonly token: string; release(): void }
34
+ export interface OwnershipMutationLease { readonly token: string; addDelegate(pid: number): void; release(): void }
27
35
 
28
36
  export declare const OWNERSHIP_MUTATION_LEASE_TOKEN_ENV: "OCX_OWNERSHIP_MUTATION_LEASE_TOKEN";
37
+ export declare function ownershipMutationLeasePath(statePaths: readonly string[]): string;
29
38
 
30
39
  export declare function ownershipMutationLeaseChildEnvironment(
31
40
  environment: NodeJS.ProcessEnv,
@@ -49,7 +58,7 @@ export declare function withOwnershipMutationLease<T>(
49
58
 
50
59
  export declare function inspectOwnershipMutationLease(
51
60
  statePaths: readonly string[],
52
- options?: Pick<OwnershipMutationLeaseOptions, "now" | "processAlive" | "processImage">,
61
+ options?: Pick<OwnershipMutationLeaseOptions, "now" | "processAlive" | "processImage" | "lockPath">,
53
62
  ): OwnershipMutationLeaseHolder | null;
54
63
 
55
64
  export declare function ownershipMutationLeaseStatusLine(
@@ -10,6 +10,7 @@ import {
10
10
  readFileSync,
11
11
  readdirSync,
12
12
  realpathSync,
13
+ renameSync,
13
14
  rmdirSync,
14
15
  unlinkSync,
15
16
  writeFileSync,
@@ -51,6 +52,9 @@ function leasePath(statePaths) {
51
52
  }
52
53
  }
53
54
 
55
+ /** The same path used by acquisition, for conservative read-only inspection. */
56
+ export function ownershipMutationLeasePath(statePaths) { return leasePath(statePaths); }
57
+
54
58
  function ownerName(record) {
55
59
  return `v1-${record.pid}-${record.processInstance}-${record.token}.json`;
56
60
  }
@@ -138,12 +142,18 @@ function leaseHolder(path, now, alive, image) {
138
142
  if (!observed && !incomplete && !existsSync(path)) return null;
139
143
  const pid = observed?.record.pid ?? incomplete?.pid ?? null;
140
144
  const since = observed ? Math.max(observed.record.createdAt, observed.mtimeMs) : incomplete?.mtimeMs ?? null;
141
- const live = pid === null ? null : alive(pid);
145
+ const delegate = observed?.record.delegatePid;
146
+ const delegateValid = delegate === undefined || (Number.isSafeInteger(delegate) && delegate > 0);
147
+ const holderAlive = pid === null ? null : alive(pid);
148
+ const live = !delegateValid ? null : holderAlive === null ? null : holderAlive || (delegate !== undefined && alive(delegate));
142
149
  return {
143
150
  path,
144
151
  pid,
152
+ delegatePid: delegateValid ? delegate ?? null : null,
153
+ holderAlive,
145
154
  alive: live,
146
- image: live ? image(pid) : null,
155
+ holderKind: observed?.record.holderKind ?? null,
156
+ image: holderAlive ? image(pid) : null,
147
157
  ageMs: since === null ? null : Math.max(0, now() - since),
148
158
  record: observed ? "complete" : incomplete?.ownerPath ? "incomplete" : incomplete ? "empty" : "unreadable",
149
159
  };
@@ -153,16 +163,21 @@ function describeHolder(holder) {
153
163
  const age = holder.ageMs === null ? "" : `, lease age ${Math.round(holder.ageMs / 1_000)}s`;
154
164
  if (holder.record === "unreadable") return "holder unknown: the lock directory does not hold exactly one owner file";
155
165
  if (holder.record === "empty") return `no owner file written yet${age}`;
156
- const state = holder.alive ? ["alive", ...(holder.image ? [holder.image] : [])].join(", ") : "not alive";
166
+ const state = holder.holderAlive ? ["alive", ...(holder.image ? [holder.image] : [])].join(", ") : "not alive";
157
167
  const partial = holder.record === "incomplete" ? ", owner record incomplete" : "";
158
- return `recorded PID ${holder.pid} [${state}, identity unverified${partial}]${age}`;
168
+ const delegate = holder.delegatePid === null ? "" : `, delegate PID ${holder.delegatePid} (identity unverified)`;
169
+ return `recorded PID ${holder.pid} [${state}, identity unverified${partial}]${delegate}${age}`;
159
170
  }
160
171
 
161
172
  const RECLAIM_HINT = `stale leases are reclaimed after ${STALE_MS / 1_000}s once the recorded PID is no longer alive`;
173
+ function reclaimHint(holder) {
174
+ return holder.delegatePid !== null || (holder.record === "complete" && holder.alive === null)
175
+ ? `${RECLAIM_HINT} and any delegate is known absent or no longer alive` : RECLAIM_HINT;
176
+ }
162
177
 
163
178
  /** The recorded lease owner for `statePaths`, identity unverified, or null if free. Reads only; never reclaims. */
164
179
  export function inspectOwnershipMutationLease(statePaths, options = {}) {
165
- return leaseHolder(leasePath(statePaths), options.now ?? Date.now, options.processAlive ?? processAlive,
180
+ return leaseHolder(options.lockPath ?? leasePath(statePaths), options.now ?? Date.now, options.processAlive ?? processAlive,
166
181
  options.processImage ?? processImage);
167
182
  }
168
183
 
@@ -171,13 +186,32 @@ export function ownershipMutationLeaseStatusLine(statePaths, options = {}) {
171
186
  const holder = inspectOwnershipMutationLease(statePaths, options);
172
187
  if (!holder) return null;
173
188
  return `Runtime mutation lease busy at ${holder.path} (${describeHolder(holder)}); `
174
- + `opencodex waits for it to start or change service state, and ${RECLAIM_HINT}.`;
189
+ + `opencodex waits for it to start or change service state, and ${reclaimHint(holder)}.`;
175
190
  }
176
191
 
177
192
  function createLeaseHandle(path, generation, token, options) {
178
193
  let released = false;
179
194
  return {
180
195
  token,
196
+ addDelegate: pid => {
197
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("invalid mutation lease delegate pid");
198
+ const current = held.get(path);
199
+ const observed = readOwner(path);
200
+ if (released || !current || current.generation !== generation || current.delegated || !observed || !sameOwner(current.snapshot, observed)) throw new Error("mutation lease is no longer held");
201
+ const temporary = `${path}.${randomUUID()}.tmp`;
202
+ let created = false;
203
+ try {
204
+ writeFileSync(temporary, `${JSON.stringify({ ...observed.record, delegatePid: pid })}\n`, { flag: "wx", mode: 0o600 });
205
+ created = true;
206
+ renameSync(temporary, observed.ownerPath);
207
+ created = false;
208
+ const updated = readOwner(path);
209
+ if (!updated || updated.record.token !== token || updated.record.delegatePid !== pid) throw new Error("mutation lease delegate could not be verified");
210
+ current.snapshot = updated;
211
+ } finally {
212
+ if (created) { try { unlinkSync(temporary); } catch (error) { if (error?.code !== "ENOENT") throw error; } }
213
+ }
214
+ },
181
215
  release: () => {
182
216
  if (released) return;
183
217
  released = true;
@@ -192,6 +226,8 @@ function reclaim(path, now, alive) {
192
226
  if (!observed && !incomplete) return false;
193
227
  const createdAt = observed ? Math.max(observed.record.createdAt, observed.mtimeMs) : incomplete.mtimeMs;
194
228
  const pid = observed?.record.pid ?? incomplete.pid;
229
+ const delegate = observed?.record.delegatePid;
230
+ if (delegate !== undefined && (!Number.isSafeInteger(delegate) || delegate <= 0 || alive(delegate))) return false;
195
231
  if (now() - createdAt <= STALE_MS || (pid !== null && alive(pid))) return false;
196
232
  if (observed) {
197
233
  const current = readOwner(path);
@@ -209,17 +245,23 @@ export function acquireOwnershipMutationLease(
209
245
  statePaths,
210
246
  options = {},
211
247
  ) {
212
- const path = leasePath(statePaths);
248
+ const path = options.lockPath ?? leasePath(statePaths);
213
249
  const nested = held.get(path);
214
250
  if (nested) {
251
+ if (options.isolated) {
252
+ const error = new Error("another operation owns the isolated mutation lease");
253
+ error.code = "OWNERSHIP_MUTATION_LEASE_BUSY";
254
+ error.holder = leaseHolder(path, options.now ?? Date.now, options.processAlive ?? processAlive, options.processImage ?? processImage);
255
+ throw error;
256
+ }
215
257
  nested.depth += 1;
216
258
  return createLeaseHandle(path, nested.generation, nested.snapshot.record.token, options);
217
259
  }
218
260
  const now = options.now ?? Date.now;
219
261
  const alive = options.processAlive ?? processAlive;
220
262
  const explicitJoinToken = options.joinToken;
221
- const envJoinToken = process.env[OWNERSHIP_MUTATION_LEASE_TOKEN_ENV];
222
- const joinToken = explicitJoinToken ?? envJoinToken ?? delegatedTokens.get(path);
263
+ const envJoinToken = options.isolated ? undefined : process.env[OWNERSHIP_MUTATION_LEASE_TOKEN_ENV];
264
+ const joinToken = options.isolated ? undefined : explicitJoinToken ?? envJoinToken ?? delegatedTokens.get(path);
223
265
  if (joinToken) {
224
266
  const owner = readOwner(path);
225
267
  if (owner?.record.token === joinToken && alive(owner.record.pid)) {
@@ -237,7 +279,7 @@ export function acquireOwnershipMutationLease(
237
279
  const deadline = now() + wait;
238
280
  if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
239
281
  for (;;) {
240
- const record = { version: 1, pid: process.pid, processInstance: PROCESS_INSTANCE, token: randomUUID(), createdAt: now() };
282
+ const record = { version: 1, pid: process.pid, processInstance: PROCESS_INSTANCE, token: randomUUID(), createdAt: now(), ...(options.holderKind ? { holderKind: options.holderKind } : {}) };
241
283
  const ownerPath = join(path, ownerName(record));
242
284
  let madeDirectory = false;
243
285
  let descriptor = null;
@@ -265,7 +307,7 @@ export function acquireOwnershipMutationLease(
265
307
  if (now() >= deadline) {
266
308
  const holder = leaseHolder(path, now, alive, options.processImage ?? processImage);
267
309
  const error = new Error(`another process owns the runtime mutation lease at ${path}`
268
- + (holder ? ` (${describeHolder(holder)}; ${RECLAIM_HINT})` : ""));
310
+ + (holder ? ` (${describeHolder(holder)}; ${reclaimHint(holder)})` : ""));
269
311
  error.code = "OWNERSHIP_MUTATION_LEASE_BUSY";
270
312
  error.holder = holder;
271
313
  throw error;
@@ -1851,6 +1851,8 @@ export interface OcxWebSearchSidecarConfig {
1851
1851
  export interface OcxCodexPoolConfig {
1852
1852
  /** Start idle Codex windows when the pool is initialized. */
1853
1853
  startIdleWindows?: boolean;
1854
+ /** Enable process-local affinity for caller-owned credentials; defaults off. */
1855
+ requestOwnedAffinity?: boolean;
1854
1856
  /**
1855
1857
  * Plan keys ordinary rotation skips, matched case-insensitively against the plan stored on each
1856
1858
  * account. Absent or empty means no policy.