@bitkyc08/opencodex 2.95.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
  3. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-BK4VuQNc.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 +21 -7
  16. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  17. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  18. package/src/adapters/openai-responses/passthrough.ts +8 -8
  19. package/src/adapters/openai-responses/reasoning.ts +9 -4
  20. package/src/adapters/openai-responses/request-strips.ts +1 -1
  21. package/src/adapters/openai-responses/transport.ts +17 -26
  22. package/src/adapters/physical-send.ts +3 -3
  23. package/src/adapters/qoder/adapter.ts +1 -1
  24. package/src/adapters/qoder/image-input.ts +5 -2
  25. package/src/adapters/zed-openai-stream.ts +2 -1
  26. package/src/bridge/errors.ts +11 -2
  27. package/src/bridge/response-json.ts +2 -1
  28. package/src/bridge/sse.ts +14 -6
  29. package/src/chat/failure-verdict.ts +21 -0
  30. package/src/chat/outbound.ts +139 -21
  31. package/src/claude/outbound.ts +49 -2
  32. package/src/cli/agent.ts +44 -15
  33. package/src/cli/capabilities-agents-routing.ts +9 -0
  34. package/src/cli/capabilities-base.ts +25 -3
  35. package/src/cli/capabilities-command.ts +12 -3
  36. package/src/cli/capability-contracts.ts +2 -0
  37. package/src/cli/codex-launch-auth.ts +30 -1
  38. package/src/cli/codex-launcher.ts +12 -5
  39. package/src/cli/codex-shim-autorestore.ts +5 -4
  40. package/src/cli/dispatch.ts +11 -176
  41. package/src/cli/ensure-desired-integrations.ts +4 -3
  42. package/src/cli/help.ts +2 -2
  43. package/src/cli/index.ts +9 -2
  44. package/src/cli/link.ts +1 -1
  45. package/src/cli/message-command.ts +2 -1
  46. package/src/cli/message-mcp-command.ts +29 -0
  47. package/src/cli/registry.ts +12 -4
  48. package/src/cli/root.ts +8 -0
  49. package/src/cli/sync-command.ts +243 -0
  50. package/src/cli/sync-fanout-process.ts +92 -0
  51. package/src/cli/sync-fanout.ts +150 -0
  52. package/src/cli/sync-flags.ts +10 -0
  53. package/src/cli/sync-link-status.ts +39 -0
  54. package/src/cli/sync-update-guard.ts +18 -0
  55. package/src/client/connect.ts +31 -14
  56. package/src/client/link-home.ts +3 -2
  57. package/src/client/machine-listener.ts +3 -0
  58. package/src/client/restore-ownership.ts +19 -1
  59. package/src/client/runtime-restart.ts +12 -4
  60. package/src/client/runtime.ts +40 -11
  61. package/src/client/stop-routing.ts +62 -0
  62. package/src/client/sync-runtime.ts +65 -0
  63. package/src/clients/config-export.ts +32 -3
  64. package/src/codex/account-store.ts +1 -0
  65. package/src/codex/auth-context-provider.ts +15 -0
  66. package/src/codex/auth-context.ts +59 -122
  67. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  68. package/src/codex/catalog/provider-models.ts +6 -8
  69. package/src/codex/forward-transport-headers.ts +65 -36
  70. package/src/codex/inject/config-toml.ts +88 -0
  71. package/src/codex/inject/multi-agent-v2.ts +30 -4
  72. package/src/codex/inject/plan.ts +34 -7
  73. package/src/codex/inject-coordination.ts +11 -0
  74. package/src/codex/inject.ts +18 -7
  75. package/src/codex/installation-id.ts +72 -0
  76. package/src/codex/lineage.ts +13 -7
  77. package/src/codex/quota.ts +22 -6
  78. package/src/codex/request-owned-affinity-key.ts +11 -0
  79. package/src/codex/request-owned-affinity.ts +118 -0
  80. package/src/codex/request-owned-main-pin.ts +86 -0
  81. package/src/codex/role-capability.ts +52 -41
  82. package/src/codex/routing/active-account.ts +13 -5
  83. package/src/codex/routing/selection.ts +40 -1
  84. package/src/codex/routing/thread-affinity-store.ts +916 -0
  85. package/src/codex/routing/thread-affinity.ts +90 -12
  86. package/src/codex/toml-source-lines.ts +72 -13
  87. package/src/combos/failover.ts +6 -109
  88. package/src/combos/request.ts +2 -2
  89. package/src/combos/resolve.ts +29 -11
  90. package/src/config/process-state.ts +5 -0
  91. package/src/config/schema/leaf-validators.ts +1 -0
  92. package/src/generated/compatibility-version.json +496 -192
  93. package/src/grok/sync.ts +10 -1
  94. package/src/images/loop.ts +2 -1
  95. package/src/lib/client-error-body.ts +184 -0
  96. package/src/lib/client-retry-after.ts +66 -0
  97. package/src/lib/config-ownership.ts +4 -0
  98. package/src/lib/context-overflow-verdict.ts +113 -0
  99. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  100. package/src/lib/desktop-cli-handoff.mjs +11 -1
  101. package/src/lib/empty-tool-catalog.ts +25 -3
  102. package/src/lib/error-destination.ts +47 -0
  103. package/src/lib/failure-detail.ts +66 -0
  104. package/src/lib/model-identity.ts +44 -0
  105. package/src/lib/private-sqlite-path.ts +124 -0
  106. package/src/lib/response-service-tier.ts +17 -0
  107. package/src/lib/retry-after.ts +3 -0
  108. package/src/lib/spend-ledger-owner.ts +43 -4
  109. package/src/lib/upstream-condition.ts +142 -0
  110. package/src/lib/upstream-retry.ts +14 -11
  111. package/src/lib/windows-owner-acl.ts +13 -6
  112. package/src/lib/windows-secret-acl.ts +2 -2
  113. package/src/link/remote-platform.ts +14 -0
  114. package/src/link/remote-windows.ts +51 -9
  115. package/src/link/ssh-argv.ts +63 -10
  116. package/src/messaging/mcp-queue-rpc.ts +102 -0
  117. package/src/messaging/mcp-queue-server.ts +42 -0
  118. package/src/messaging/mcp-queue-tools.ts +39 -0
  119. package/src/oauth/anthropic-identity.ts +2 -6
  120. package/src/oauth/generic-account-failover.ts +13 -11
  121. package/src/oauth/index.ts +41 -74
  122. package/src/oauth/oauth-errors.ts +67 -0
  123. package/src/oauth/store.ts +1 -1
  124. package/src/protocols/codecs/ollama.ts +197 -0
  125. package/src/protocols/encoders/adapter-events.ts +4 -0
  126. package/src/protocols/encoders/chat.ts +18 -10
  127. package/src/protocols/trace.ts +18 -0
  128. package/src/providers/anthropic-subscription.ts +25 -0
  129. package/src/providers/claude-cli-usage.ts +15 -67
  130. package/src/providers/fastwire.ts +3 -2
  131. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  132. package/src/providers/quota/anthropic-usage-windows.ts +65 -0
  133. package/src/providers/quota/vendor-probes-key.ts +60 -24
  134. package/src/providers/request-pacing.ts +3 -2
  135. package/src/responses/apply-patch-envelope.ts +45 -19
  136. package/src/responses/compaction-history-framing.ts +5 -1
  137. package/src/responses/freeform-wrapper-scan.ts +5 -3
  138. package/src/responses/parser-tools.ts +1 -0
  139. package/src/responses/progressive-freeform-input.ts +354 -45
  140. package/src/responses/schema.ts +5 -2
  141. package/src/routing/fallback-policy.ts +3 -1
  142. package/src/server/admission-model-scope.ts +17 -6
  143. package/src/server/admitted-http-turn.ts +56 -0
  144. package/src/server/audio-dictation.ts +3 -0
  145. package/src/server/audio-live.ts +8 -2
  146. package/src/server/audio-upstream.ts +2 -0
  147. package/src/server/auth-cors.ts +5 -0
  148. package/src/server/chat-completions.ts +45 -20
  149. package/src/server/chat-native-sse.ts +52 -7
  150. package/src/server/chat-native.ts +60 -35
  151. package/src/server/claude-bridge-pool-session.ts +59 -0
  152. package/src/server/claude-messages.ts +57 -27
  153. package/src/server/context-history.ts +14 -7
  154. package/src/server/images.ts +14 -5
  155. package/src/server/inbound-body-admission.ts +11 -4
  156. package/src/server/index/live-sideband.ts +16 -2
  157. package/src/server/index/ollama-routes.ts +89 -0
  158. package/src/server/index/serve-options.ts +22 -4
  159. package/src/server/index/websocket-handler.ts +5 -3
  160. package/src/server/index.ts +6 -36
  161. package/src/server/inference/client-encoder-delivery.ts +4 -2
  162. package/src/server/json-serialized-bytes.ts +44 -0
  163. package/src/server/live.ts +30 -5
  164. package/src/server/management/agent-settings-routes.ts +24 -21
  165. package/src/server/management/codex-cli-update-routes.ts +2 -1
  166. package/src/server/management/route-registry.ts +1 -1
  167. package/src/server/messages-native-scope.ts +2 -1
  168. package/src/server/messages-native-tool-guard.ts +1 -1
  169. package/src/server/messages-native.ts +12 -7
  170. package/src/server/messages-shared.ts +6 -2
  171. package/src/server/native-final-log.ts +93 -0
  172. package/src/server/ollama-inbound.ts +349 -0
  173. package/src/server/ollama-native-paths.ts +21 -0
  174. package/src/server/ollama-route-policy.ts +73 -0
  175. package/src/server/relay.ts +22 -3
  176. package/src/server/request-decompress.ts +4 -2
  177. package/src/server/request-log-failure-attribution.ts +22 -0
  178. package/src/server/request-log-failure-detail.ts +80 -0
  179. package/src/server/request-log-terminal-status.ts +4 -2
  180. package/src/server/request-log.ts +79 -42
  181. package/src/server/response-log-body.ts +6 -1
  182. package/src/server/responses/account-change-state.ts +17 -6
  183. package/src/server/responses/adapter-continuation.ts +9 -4
  184. package/src/server/responses/adapter-delivery.ts +5 -4
  185. package/src/server/responses/adapter-dispatch.ts +36 -30
  186. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  187. package/src/server/responses/codex-auth-error.ts +22 -17
  188. package/src/server/responses/codex-ws-exchange.ts +11 -8
  189. package/src/server/responses/codex-ws-metadata.ts +94 -21
  190. package/src/server/responses/codex-ws-request.ts +3 -1
  191. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  192. package/src/server/responses/compact.ts +89 -41
  193. package/src/server/responses/compaction-recovery.ts +4 -2
  194. package/src/server/responses/compaction-routing.ts +9 -4
  195. package/src/server/responses/core-auth.ts +32 -14
  196. package/src/server/responses/core-codex-account.ts +34 -12
  197. package/src/server/responses/core-combo-failure.ts +5 -1
  198. package/src/server/responses/core-combo-native.ts +2 -1
  199. package/src/server/responses/core-combo.ts +51 -33
  200. package/src/server/responses/core-errors.ts +22 -20
  201. package/src/server/responses/core-lifetime.ts +6 -3
  202. package/src/server/responses/core-normalize.ts +8 -1
  203. package/src/server/responses/core-options.ts +7 -0
  204. package/src/server/responses/core-pipeline.ts +4 -3
  205. package/src/server/responses/fetch-helpers.ts +7 -1
  206. package/src/server/responses/input-admission.ts +28 -2
  207. package/src/server/responses/native-injection.ts +1 -1
  208. package/src/server/responses/native-response-json.ts +13 -4
  209. package/src/server/responses/native-response-output.ts +1 -2
  210. package/src/server/responses/non-replayable-error.ts +2 -1
  211. package/src/server/responses/pacing-overload.ts +3 -2
  212. package/src/server/responses/passthrough-build-error.ts +36 -0
  213. package/src/server/responses/passthrough-delivery.ts +55 -14
  214. package/src/server/responses/passthrough-dispatch.ts +26 -39
  215. package/src/server/responses/passthrough-error.ts +9 -9
  216. package/src/server/responses/policy-fallback.ts +2 -1
  217. package/src/server/responses/request-prepare.ts +67 -48
  218. package/src/server/responses/request-sidecar-auth.ts +3 -1
  219. package/src/server/responses/request-transport.ts +35 -31
  220. package/src/server/responses/run-turn-execution.ts +6 -6
  221. package/src/server/responses/sidecar-execution.ts +16 -12
  222. package/src/server/responses/spend-storage-error.ts +2 -1
  223. package/src/server/responses/ws-upstream.ts +9 -0
  224. package/src/server/responses-custom-tool-repair.ts +14 -3
  225. package/src/server/responses-terminal-repair.ts +5 -2
  226. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  227. package/src/server/safe-response-headers.ts +162 -13
  228. package/src/server/search.ts +13 -4
  229. package/src/server/turn-state-handles.ts +164 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/server/ws-bridge.ts +5 -2
  232. package/src/service/ownership-mutation-lease.d.mts +11 -2
  233. package/src/service/ownership-mutation-lease.mjs +53 -11
  234. package/src/types/config.ts +2 -0
  235. package/src/update/index.ts +133 -25
  236. package/src/update/npm-install.d.mts +8 -0
  237. package/src/update/npm-install.mjs +20 -1
  238. package/src/update/orchestrated-admission.d.mts +4 -0
  239. package/src/update/orchestrated-admission.mjs +12 -0
  240. package/src/update/orchestrated-arguments.d.mts +12 -0
  241. package/src/update/orchestrated-arguments.mjs +64 -0
  242. package/src/update/orchestrated-child.d.mts +12 -0
  243. package/src/update/orchestrated-child.mjs +70 -0
  244. package/src/update/orchestrated-entry.ts +234 -0
  245. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  246. package/src/update/orchestrated-identity.ts +53 -0
  247. package/src/update/orchestrated-live-identity.ts +48 -0
  248. package/src/update/orchestrated-node-driver.mjs +99 -0
  249. package/src/update/orchestrated-outcome.d.mts +21 -0
  250. package/src/update/orchestrated-outcome.mjs +40 -0
  251. package/src/update/orchestrated-plan.ts +49 -0
  252. package/src/update/orchestrated-pnpm.d.mts +8 -0
  253. package/src/update/orchestrated-pnpm.mjs +33 -0
  254. package/src/update/orchestrated-session.d.mts +37 -0
  255. package/src/update/orchestrated-session.mjs +264 -0
  256. package/src/update/orchestrated-token.d.mts +10 -0
  257. package/src/update/orchestrated-token.mjs +21 -0
  258. package/src/update/orchestrated-token.ts +3 -0
  259. package/src/update/orchestrated-tree.d.mts +1 -0
  260. package/src/update/orchestrated-tree.mjs +14 -0
  261. package/src/update/pnpm-global-install.d.mts +6 -0
  262. package/src/update/pnpm-global-install.mjs +9 -2
  263. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  264. package/src/update/posix-install-supervisor.d.mts +10 -0
  265. package/src/update/posix-install-supervisor.mjs +88 -0
  266. package/src/update/sync-update-mutex.d.mts +10 -0
  267. package/src/update/sync-update-mutex.mjs +164 -0
  268. package/src/update/sync-update-mutex.ts +1 -0
  269. package/src/update/test-home-guard.mjs +33 -0
  270. package/src/update/transactional-install.mjs +2 -2
  271. package/src/usage/error-detail.ts +225 -0
  272. package/src/usage/log.ts +60 -27
  273. package/src/vision/describe.ts +4 -7
  274. package/src/web-search/executor.ts +4 -7
  275. package/src/web-search/loop.ts +31 -5
  276. package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
@@ -1,3 +1,7 @@
1
+ import { boundedServiceTier } from "../lib/response-service-tier";
2
+ import { isLikelyRealAnthropicThinkingSignature } from "../responses/reasoning-envelope";
3
+ import { ownedChatErrorPayload, CLIENT_ERROR_CONTRACTS, hasProxyErrorMessage, hasProxyIncomplete, type ClientErrorContract } from "../lib/client-error-body";
4
+ import { legacyFailureVerdict, legacyStreamErrorStatus as streamErrorStatus, type FailureVerdictSink } from "./failure-verdict";
1
5
  /**
2
6
  * Chat Completions outbound: internal /v1/responses output -> OpenAI Chat Completions shapes.
3
7
  *
@@ -126,16 +130,6 @@ export function isChatCompletionsStreamError(err: unknown): err is ChatCompletio
126
130
  return err instanceof ChatCompletionsStreamError;
127
131
  }
128
132
 
129
- function streamErrorStatus(message: string): number {
130
- const lower = message.toLowerCase();
131
- if (isCyberPolicyMessage(lower)) return 400;
132
- if (lower.includes("truncated")) return 502;
133
- if (lower.includes("rate") || lower.includes("429")) return 429;
134
- if (lower.includes("unauthor") || lower.includes("401") || lower.includes("api key")) return 401;
135
- if (lower.includes("not found") || lower.includes("404")) return 404;
136
- if (lower.includes("invalid") || lower.includes("400")) return 400;
137
- return 502;
138
- }
139
133
 
140
134
  export function dataFrame(payload: Rec | "[DONE]"): string {
141
135
  if (payload === "[DONE]") return "data: [DONE]\n\n";
@@ -169,6 +163,8 @@ export function appendedUtf8Bytes(previous: string, previousBytes: number, fragm
169
163
 
170
164
  /** Details a streamed Chat failure carries into its error frame. */
171
165
  export interface ChatCompletionsStreamFailure {
166
+ contract?: ClientErrorContract;
167
+ proxyAuthored?: boolean;
172
168
  code?: string | null;
173
169
  type?: string;
174
170
  status?: number;
@@ -179,7 +175,7 @@ export interface ChatCompletionsStreamFailure {
179
175
  * fixed, bounded failures that must be delivered even when the translation budget is exhausted.
180
176
  * Provider text is redacted; the two fixed failures carry no provider text at all.
181
177
  */
182
- export function chatCompletionsStreamErrorPayload(
178
+ function legacyChatCompletionsStreamErrorPayload(
183
179
  message: string,
184
180
  details?: ChatCompletionsStreamFailure,
185
181
  ): { payload: Rec; bounded: boolean } {
@@ -224,6 +220,25 @@ export function chatCompletionsStreamErrorPayload(
224
220
  };
225
221
  }
226
222
 
223
+ export function chatCompletionsStreamErrorPayload(message: string, details?: ChatCompletionsStreamFailure) {
224
+ const legacy = legacyChatCompletionsStreamErrorPayload(message, details);
225
+ const verdict = legacyFailureVerdict(legacy.payload);
226
+ const error = legacy.payload.error as { message: string; type: string; code: string | null };
227
+ return { bounded: legacy.bounded, verdict, payload: details?.proxyAuthored ? legacy.payload : ownedChatErrorPayload({
228
+ status: verdict.status, type: error.type, code: error.code, contract: details?.contract,
229
+ evidence: { status: verdict.status, type: error.type, code: error.code ?? undefined, message },
230
+ }) };
231
+ }
232
+
233
+ export function ownedChatErrorResponse(status: number, message: string, type?: string, code?: string | null, contract?: ClientErrorContract, proxyAuthored = false): Response {
234
+ const legacyBody = chatCompletionsErrorBody(status, message, type, code);
235
+ const legacy = legacyBody.error as { type: string; code: string | null };
236
+ const finalStatus = legacy.code === CYBER_POLICY_ERROR_CODE ? 400 : status;
237
+ return new Response(JSON.stringify(proxyAuthored ? legacyBody : ownedChatErrorPayload({ status: finalStatus, type: legacy.type, code: legacy.code, contract,
238
+ evidence: { status: finalStatus, type, code: code ?? undefined, message } })),
239
+ { status: finalStatus, headers: { "Content-Type": "application/json" } });
240
+ }
241
+
227
242
  /** How a Responses `response.failed` error object becomes a streamed Chat failure. */
228
243
  export function chatCompletionsFailedResponse(error: Rec): { message: string; details: ChatCompletionsStreamFailure } {
229
244
  const message = typeof error.message === "string" ? error.message : "upstream request failed";
@@ -250,7 +265,7 @@ export function chatCompletionsFailedResponse(error: Rec): { message: string; de
250
265
  export function chatCompletionsIncompleteOutcome(
251
266
  reason: unknown,
252
267
  message: unknown,
253
- ): { finishReason: "length" | "content_filter" } | { failMessage: string } {
268
+ ): { finishReason: "length" | "content_filter" } | { failMessage: string; originalFailMessage: string } {
254
269
  // Upstream Responses endpoints do not all use OpenAI's `max_output_tokens`: Volcengine Ark
255
270
  // (Coding Plan `/responses`) sends `incomplete_details.reason: "length"` for a hit output cap.
256
271
  // Read the reason through the shared truncation vocabulary so such a turn ends with
@@ -261,7 +276,8 @@ export function chatCompletionsIncompleteOutcome(
261
276
  if (truncation === "content_filter") return { finishReason: "content_filter" };
262
277
  const why = typeof reason === "string" ? reason : "unknown";
263
278
  return {
264
- failMessage: typeof message === "string" && message.length > 0
279
+ failMessage: CLIENT_ERROR_CONTRACTS.stream_incomplete,
280
+ originalFailMessage: typeof message === "string" && message.length > 0
265
281
  ? message
266
282
  : `upstream stream ended early (${why})`,
267
283
  };
@@ -281,7 +297,7 @@ function refusalTranslationError(): ChatCompletionsStreamError {
281
297
  export function responsesSseToChatCompletionsSse(
282
298
  upstream: ReadableStream<Uint8Array>,
283
299
  model: string,
284
- opts: { translatorBudget: TranslatorBudget },
300
+ opts: { translatorBudget: TranslatorBudget; failureVerdictSink?: FailureVerdictSink; proxyErrorContext?: object },
285
301
  ): ReadableStream<Uint8Array> {
286
302
  const translatorBudget = opts.translatorBudget;
287
303
  const encoder = new TextEncoder();
@@ -610,7 +626,7 @@ export function responsesSseToChatCompletionsSse(
610
626
  terminated = true;
611
627
  releaseRefusals();
612
628
  };
613
- const fail = (message: string, details?: { code?: string | null; type?: string; status?: number }) => {
629
+ const fail = (message: string, details?: ChatCompletionsStreamFailure) => {
614
630
  if (terminated) return;
615
631
  terminated = true;
616
632
  failed = true;
@@ -623,13 +639,14 @@ export function responsesSseToChatCompletionsSse(
623
639
  // Deliver the error frame then close the stream abnormally (no [DONE]).
624
640
  // Do not controller.error() — that can drop already-enqueued bytes from consumers
625
641
  // like response.text().
626
- const { payload, bounded } = chatCompletionsStreamErrorPayload(message, details);
642
+ const { payload, bounded, verdict } = chatCompletionsStreamErrorPayload(message, details);
627
643
  try {
628
644
  const frame = encoder.encode(dataFrame(payload));
629
645
  // These fixed, bounded failures must survive even when decoder-owned input
630
646
  // still fills the budget. They contain no provider text or IDs.
631
647
  if (bounded) controller.enqueue(frame);
632
648
  else enqueueLiveFrame(frame);
649
+ if (opts.failureVerdictSink) { opts.failureVerdictSink.verdict = verdict; opts.failureVerdictSink.contract = details?.contract; opts.failureVerdictSink.proxyAuthored = details?.proxyAuthored; }
633
650
  emittedFrames++;
634
651
  } catch {
635
652
  /* controller may already be closed */
@@ -789,14 +806,15 @@ export function responsesSseToChatCompletionsSse(
789
806
  // upstream_stall_timeout / adapter_eof / proxy-synthesized incompletes are
790
807
  // failures, not early finishes: emit an error frame and close WITHOUT
791
808
  // [DONE] instead of a success-looking stop/tool_calls + [DONE].
792
- fail(outcome.failMessage);
809
+ fail(outcome.originalFailMessage, { contract: "stream_incomplete",
810
+ proxyAuthored: hasProxyIncomplete(opts.proxyErrorContext ?? upstream, details.reason, details.message) });
793
811
  }
794
812
  break;
795
813
  }
796
814
  case "response.failed": {
797
815
  const response = isRec(data.response) ? data.response : {};
798
816
  const failure = chatCompletionsFailedResponse(isRec(response.error) ? response.error : {});
799
- fail(failure.message, failure.details);
817
+ fail(failure.message, { ...failure.details, proxyAuthored: hasProxyErrorMessage(opts.proxyErrorContext, failure.message, failure.details) });
800
818
  break;
801
819
  }
802
820
  default:
@@ -1003,11 +1021,105 @@ export function responsesJsonToChatCompletion(json: unknown, model: string, tran
1003
1021
  };
1004
1022
  }
1005
1023
 
1024
+ function flatNumericFields(value: unknown, fields: readonly string[]): Rec {
1025
+ const out: Rec = {};
1026
+ if (isRec(value)) for (const field of fields) {
1027
+ const number = value[field];
1028
+ if (typeof number === "number" && Number.isFinite(number) && number >= 0) out[field] = number;
1029
+ }
1030
+ return out;
1031
+ }
1032
+ function flatCollectorUsage(value: unknown): Rec | undefined {
1033
+ if (!isRec(value)) return undefined;
1034
+ const out = flatNumericFields(value, ["prompt_tokens", "completion_tokens", "total_tokens"]);
1035
+ for (const [field, counters] of [
1036
+ ["prompt_tokens_details", ["cached_tokens", "audio_tokens"]],
1037
+ ["completion_tokens_details", ["reasoning_tokens", "audio_tokens", "accepted_prediction_tokens", "rejected_prediction_tokens"]],
1038
+ ] as const) {
1039
+ const details = flatNumericFields(value[field], counters);
1040
+ if (Object.keys(details).length > 0) out[field] = details;
1041
+ }
1042
+ return out;
1043
+ }
1044
+ const FLAT_FINISH_REASONS: ReadonlyMap<string, string> = new Map([
1045
+ ["stop", "stop"], ["length", "length"], ["tool_calls", "tool_calls"], ["content_filter", "content_filter"],
1046
+ ["function_call", "function_call"], ["error", "error"],
1047
+ ]);
1048
+ function flatCollectorChoices(value: unknown): Rec[] | undefined {
1049
+ if (!Array.isArray(value)) return undefined;
1050
+ const first = value[0];
1051
+ if (!isRec(first)) return [];
1052
+ const choice: Rec = {};
1053
+ if (typeof first.finish_reason === "string") choice.finish_reason = FLAT_FINISH_REASONS.get(first.finish_reason) ?? "error";
1054
+ if (!isRec(first.delta)) return [choice];
1055
+ const original = first.delta;
1056
+ const delta: Rec = {};
1057
+ for (const field of ["content", "reasoning_content"]) if (typeof original[field] === "string") delta[field] = original[field];
1058
+ if (original.refusal !== undefined) {
1059
+ // Preserve the collector's invalid-refusal verdict without retaining an invalid object.
1060
+ delta.refusal = typeof original.refusal === "string" || original.refusal === null ? original.refusal : false;
1061
+ }
1062
+ if (Array.isArray(original.reasoning_details)) delta.reasoning_details = original.reasoning_details.filter(isRec).flatMap(detail => {
1063
+ const type = detail.type === "reasoning.text" ? "reasoning.text" : detail.type === "reasoning.encrypted" ? "reasoning.encrypted"
1064
+ : detail.type === "reasoning.summary" ? "reasoning.summary" : undefined;
1065
+ if (!type) return [];
1066
+ const entry: Rec = { type };
1067
+ if (type === "reasoning.text") {
1068
+ if (typeof detail.text === "string") entry.text = detail.text;
1069
+ if (typeof detail.signature === "string" && isLikelyRealAnthropicThinkingSignature(detail.signature)) entry.signature = detail.signature;
1070
+ } else if (type === "reasoning.summary") {
1071
+ if (typeof detail.summary !== "string") return [];
1072
+ entry.summary = detail.summary;
1073
+ } else if (typeof detail.data === "string") entry.data = detail.data;
1074
+ if (typeof detail.format === "string" && /^[A-Za-z][A-Za-z0-9._-]{0,95}-v[1-9][0-9]{0,3}$/.test(detail.format)) entry.format = detail.format;
1075
+ if (typeof detail.id === "string" && detail.id.length <= 128
1076
+ && /^(?:reasoning[-_]|summary[-_]|rs[-_])[A-Za-z0-9._:-]+$/.test(detail.id)) entry.id = detail.id;
1077
+ if (typeof detail.index === "number" && Number.isSafeInteger(detail.index) && detail.index >= 0) entry.index = detail.index;
1078
+ return [entry];
1079
+ });
1080
+ if (Array.isArray(original.tool_calls)) delta.tool_calls = original.tool_calls.filter(isRec).map(tool => {
1081
+ const call: Rec = {};
1082
+ if (typeof tool.index === "number" && Number.isSafeInteger(tool.index) && tool.index >= 0) call.index = tool.index;
1083
+ if (typeof tool.id === "string") call.id = tool.id;
1084
+ const fn: Rec = {};
1085
+ if (isRec(tool.function)) for (const field of ["name", "arguments"]) if (typeof tool.function[field] === "string") fn[field] = tool.function[field];
1086
+ call.function = fn;
1087
+ return call;
1088
+ });
1089
+ choice.delta = delta;
1090
+ return [choice];
1091
+ }
1092
+
1093
+ /** Client fields from ordinary chunks needed only by a buffered native collector. */
1094
+ export class ChatCompletionsCollectorSource {
1095
+ private pending: Array<{ wire: string; fields: string; bytes: number }> = [];
1096
+ constructor(private readonly budget: TranslatorBudget) {}
1097
+ retain(wire: string, chunk: Rec): void {
1098
+ const fields = JSON.stringify({ usage: flatCollectorUsage(chunk.usage), service_tier: boundedServiceTier(chunk.service_tier), choices: flatCollectorChoices(chunk.choices) });
1099
+ const bytes = Buffer.byteLength(wire) + Buffer.byteLength(fields) + 64;
1100
+ this.budget.chargeRetained(bytes, { kind: "retained_collectors" });
1101
+ this.pending.push({ wire, fields, bytes });
1102
+ }
1103
+ take(wire: string): Rec | undefined {
1104
+ const next = this.pending[0];
1105
+ if (!next || next.wire !== wire) return undefined;
1106
+ this.pending.shift();
1107
+ this.budget.releaseRetained(next.bytes, { kind: "retained_collectors" });
1108
+ return JSON.parse(next.fields) as Rec;
1109
+ }
1110
+ clear(): void {
1111
+ for (const entry of this.pending) this.budget.releaseRetained(entry.bytes, { kind: "retained_collectors" });
1112
+ this.pending.length = 0;
1113
+ }
1114
+ }
1115
+
1006
1116
  /** Fold a Chat Completions SSE stream into a final completion JSON. */
1007
1117
  export async function collectChatCompletion(
1008
1118
  stream: ReadableStream<Uint8Array>,
1009
1119
  model: string,
1010
1120
  translatorBudget: TranslatorBudget,
1121
+ failureVerdictSink?: FailureVerdictSink,
1122
+ collectorSource?: ChatCompletionsCollectorSource,
1011
1123
  ): Promise<Rec> {
1012
1124
  const reader = stream.getReader();
1013
1125
  const decoder = new TextDecoder();
@@ -1055,10 +1167,15 @@ export async function collectChatCompletion(
1055
1167
  for (let frame = buffer.next(); frame; frame = buffer.next()) {
1056
1168
  const data = sseDataPayload(frame.block)?.trim();
1057
1169
  if (!data || data === "[DONE]") continue;
1058
- let parsed: unknown;
1059
- try { parsed = JSON.parse(data); } catch { continue; }
1060
- if (!isRec(parsed)) continue;
1170
+ let decoded: unknown;
1171
+ try { decoded = JSON.parse(data); } catch { continue; }
1172
+ if (!isRec(decoded)) continue;
1173
+ const parsed = collectorSource?.take(data) ?? decoded;
1061
1174
  if (isRec(parsed.error)) {
1175
+ if (failureVerdictSink?.verdict) {
1176
+ const verdict = failureVerdictSink.verdict;
1177
+ throw new ChatCompletionsStreamError(verdict.message, verdict);
1178
+ }
1062
1179
  const message = typeof parsed.error.message === "string"
1063
1180
  ? parsed.error.message
1064
1181
  : "upstream request failed";
@@ -1157,6 +1274,7 @@ export async function collectChatCompletion(
1157
1274
  // Preserve the previous EOF contract: only delimiter-terminated events are collected.
1158
1275
  // A partial final frame is discarded, with its retained input ownership released.
1159
1276
  buffer.clear();
1277
+ collectorSource?.clear();
1160
1278
  reader.releaseLock();
1161
1279
  }
1162
1280
 
@@ -132,6 +132,53 @@ export function isThroughputLimitText(message: string): boolean {
132
132
  return THROUGHPUT_LIMIT_TEXT_RE.test(message);
133
133
  }
134
134
 
135
+ /** Codes that say nothing about the cause, so the message decides (#8127). */
136
+ const GENERIC_FAILURE_CODES: ReadonlySet<string> = new Set(["server_error", "upstream_error", "api_error", "internal_error"]);
137
+ const NON_OVERFLOW_ERROR_TYPES: ReadonlySet<string> = new Set(["rate_limit_error", "authentication_error", "permission_error"]);
138
+ const NON_OVERFLOW_STATUSES: ReadonlySet<number> = new Set([401, 403, 429]);
139
+ /**
140
+ * Wording that asserts the request itself is over a size limit. Narrower than
141
+ * CONTEXT_OVERFLOW_TEXT_RE on purpose: without a code, a message that only mentions the context
142
+ * window (for example a configuration failure or a validation error) must not make Claude Code
143
+ * compact. Quoted values are removed first, a stated maximum counts only when the stated request
144
+ * is larger, and a negated verdict ("does not exceed") never counts.
145
+ */
146
+ const TOO_LONG_TEXT_RE = /\b(?:prompt|input) is too long\b([^.\n]{0,60})/i;
147
+ const CONDITIONAL_LEAD_RE = /\b(?:if|whether|unless)\b[^.\n]{0,40}$/i;
148
+ const STATED_COUNTS_RE = /maximum context length is (\d+)[^]{0,200}?\b(?:resulted in|you requested|requested) (\d+) tokens/i;
149
+ const EXCEEDS_TEXT_RE = /\b(?:input|prompt|request|messages?|conversation)\b[^.\n]{0,60}\bexceed(?:s|ed|ing)?\b[^.\n]{0,40}\b(?:context (?:window|length)|maximum context|token limit)/i;
150
+ const NEGATION_RE = /\b(?:not|never|no|neither|nor)\b|n['\u2019]t\b/i;
151
+ /** A quoted value inside a message (a field, enum or tool name), ASCII or typographic; an apostrophe inside a word does not open one. */
152
+ const QUOTED_SPAN_RE = /(?<!\w)(['"`])[^'"`\n]{1,200}\1(?!\w)|\u2018[^\u2019\n]{1,200}\u2019|\u201c[^\u201d\n]{1,200}\u201d/g;
153
+
154
+ function assertsOverflow(message: string): boolean {
155
+ const text = message.replace(QUOTED_SPAN_RE, " ");
156
+ const tooLong = TOO_LONG_TEXT_RE.exec(text);
157
+ if (tooLong && !NEGATION_RE.test(tooLong[1] ?? "") && !CONDITIONAL_LEAD_RE.test(text.slice(0, tooLong.index))) return true;
158
+ const counts = STATED_COUNTS_RE.exec(text);
159
+ if (counts && Number(counts[2]) > Number(counts[1])) return true;
160
+ const exceeds = EXCEEDS_TEXT_RE.exec(text);
161
+ return exceeds !== null && !NEGATION_RE.test(exceeds[0]);
162
+ }
163
+
164
+ /**
165
+ * Whether a translated refusal is an oversized-input refusal. A coded context_length_exceeded
166
+ * always is. Some Responses upstreams send the refusal uncoded or as a generic server_error
167
+ * ("Your input exceeds the context window of this model"); as a 502 Claude Code retries it
168
+ * instead of compacting (#8127). Those count only when the wording is an overflow, is not a
169
+ * throughput limit, and the type is not a rate-limit or credential refusal. Any other specific
170
+ * code keeps its own classification.
171
+ */
172
+ export function isContextOverflowError(error: { type?: unknown; code?: unknown }, message: string): boolean {
173
+ const code = error.code;
174
+ if (code === "context_length_exceeded") return true;
175
+ if (code != null && !(typeof code === "string" && GENERIC_FAILURE_CODES.has(code))) return false;
176
+ if (typeof error.type === "string" && NON_OVERFLOW_ERROR_TYPES.has(error.type)) return false;
177
+ const status = (error as { status?: unknown }).status;
178
+ if (typeof status === "number" && NON_OVERFLOW_STATUSES.has(status)) return false;
179
+ return assertsOverflow(message) && !isThroughputLimitText(message);
180
+ }
181
+
135
182
  export function anthropicErrorBody(status: number, message: string, type?: string, code?: string): Rec {
136
183
  const overflow = code === "context_length_exceeded" && !isThroughputLimitText(message);
137
184
  const text = overflow ? claudePromptTooLongMessage(message) : message;
@@ -333,7 +380,7 @@ export function anthropicIncompleteOutcome(
333
380
  */
334
381
  export function anthropicFailedStatus(error: Rec, message: string): number {
335
382
  const code = typeof error.code === "string" ? error.code : undefined;
336
- if (code === "context_length_exceeded") return 400;
383
+ if (isContextOverflowError(error, message)) return 400;
337
384
  return code === "translation_buffer_limit"
338
385
  ? 413
339
386
  : typeof error.status === "number"
@@ -852,7 +899,7 @@ export function responsesSseToAnthropicSse(
852
899
  status,
853
900
  message,
854
901
  !deterministic,
855
- deterministic || code === "context_length_exceeded" ? code : undefined,
902
+ deterministic ? code : isContextOverflowError(error, message) ? "context_length_exceeded" : undefined,
856
903
  );
857
904
  break;
858
905
  }
package/src/cli/agent.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  CliUsageError,
3
+ RuntimeApiError,
3
4
  csv,
4
5
  desktopSwitchApplyReason,
5
6
  printData,
@@ -345,27 +346,48 @@ async function suggestRoles(args: string[], wantsJson: boolean, deps: RuntimeApi
345
346
  );
346
347
  const proposals = result.proposals ?? [];
347
348
  const applied: Array<{ role: string; model: string; effort?: string }> = [];
348
- const skipped: string[] = [];
349
+ const skipped = apply ? proposals.filter(p => p.status === "proposed" && p.proposedModel && proposalAlreadySet(p)).map(p => p.role) : [];
350
+ const changes = proposals.filter((p): p is CodexRoleProposal & { proposedModel: string } =>
351
+ p.status === "proposed" && !!p.proposedModel && !proposalAlreadySet(p));
352
+ const { ROLE_HISTORY_LIMIT } = await import("../codex/role-model-history");
349
353
  const omoJsoncNotWritten: Array<{ role: string; status: string }> = [];
354
+ let batch: string | undefined;
355
+ let failure: { cause: unknown; unconfirmedRole: string; unattemptedRoles: string[] } | undefined;
350
356
  if (apply) {
351
- for (const proposal of proposals) {
352
- if (proposal.status !== "proposed" || !proposal.proposedModel) continue;
353
- if (proposalAlreadySet(proposal)) {
354
- skipped.push(proposal.role);
355
- continue;
357
+ // Splitting into several batches would hide earlier changes from the bounded Restore list.
358
+ if (changes.length > ROLE_HISTORY_LIMIT) {
359
+ const message = `${changes.length} changed proposals exceed the ${ROLE_HISTORY_LIMIT}-role batch limit. No role files were written. Preview without --apply and use 'ocx agent roles set' for individual changes.`;
360
+ printData({ ...result, applied, skipped, omoJsoncNotWritten, complete: false,
361
+ refusal: { code: "too_many_role_changes", limit: ROLE_HISTORY_LIMIT, count: changes.length },
362
+ unattemptedRoles: changes.map(p => p.role) }, wantsJson, [message]);
363
+ throw new RuntimeApiError(message, 409, null);
364
+ }
365
+ for (const [index, proposal] of changes.entries()) {
366
+ const body = {
367
+ model: proposal.proposedModel,
368
+ ...(proposal.proposedEffort ? { effort: proposal.proposedEffort } : {}),
369
+ ...(batch ? { batch } : {}),
370
+ };
371
+ let written: { batch?: string; omoJsonc?: { status?: string } } | null;
372
+ try {
373
+ written = await runtimeRequest<typeof written>(
374
+ `/api/codex-agent-roles/${encodeURIComponent(proposal.role)}`,
375
+ { method: "PUT", body: JSON.stringify(body) },
376
+ deps,
377
+ );
378
+ } catch (cause) {
379
+ // A lost response can follow a persisted write: report uncertainty and do not replay it.
380
+ failure = { cause, unconfirmedRole: proposal.role, unattemptedRoles: changes.slice(index + 1).map(p => p.role) };
381
+ break;
356
382
  }
357
- const body = { model: proposal.proposedModel, ...(proposal.proposedEffort ? { effort: proposal.proposedEffort } : {}) };
358
- const written = await runtimeRequest<{ omoJsonc?: { status?: string } } | null>(
359
- `/api/codex-agent-roles/${encodeURIComponent(proposal.role)}`,
360
- { method: "PUT", body: JSON.stringify(body) },
361
- deps,
362
- );
363
- applied.push({ role: proposal.role, ...body });
383
+ batch = written?.batch ?? batch;
384
+ applied.push({ role: proposal.role, model: body.model, ...(proposal.proposedEffort ? { effort: proposal.proposedEffort } : {}) });
364
385
  const omoStatus = written?.omoJsonc?.status;
365
386
  if (omoStatus && OMO_JSONC_NOT_WRITTEN.has(omoStatus)) omoJsoncNotWritten.push({ role: proposal.role, status: omoStatus });
366
387
  }
367
388
  }
368
- printData(apply ? { ...result, applied, skipped, omoJsoncNotWritten } : result, wantsJson, [
389
+ printData(apply ? { ...result, applied, skipped, omoJsoncNotWritten, ...(batch ? { batch } : {}),
390
+ ...(failure ? { complete: false, unconfirmedRole: failure.unconfirmedRole, unattemptedRoles: failure.unattemptedRoles } : {}) } : result, wantsJson, [
369
391
  `Sized with ${result.sizingModel ?? "unknown"}.`,
370
392
  ...proposals.map(p => p.status === "unsized"
371
393
  ? `${p.role}: not sized (${p.reason ?? "unknown"})`
@@ -374,9 +396,16 @@ async function suggestRoles(args: string[], wantsJson: boolean, deps: RuntimeApi
374
396
  : `${p.role}: ${p.model ?? "(no pin)"} -> ${p.proposedModel}${p.proposedEffort ? ` (${p.proposedEffort})` : ""} [${p.tier}/${p.effortIntent}] ${p.rationale ?? ""}`),
375
397
  apply
376
398
  ? `Applied ${applied.length} of ${proposals.length} roles.${skipped.length > 0 ? ` Skipped ${skipped.length} already set: ${skipped.join(", ")}.` : ""}`
377
- : "Nothing was written; rerun with --apply to write every proposal that differs from the role's current pin.",
399
+ : `Nothing was written; --apply accepts up to ${ROLE_HISTORY_LIMIT} changed roles in one batch. Use 'ocx agent roles set' for individual changes.`,
378
400
  ...omoJsoncNotWritten.map(entry => `${entry.role}: omo.jsonc not written (${entry.status}); the role TOML was updated.`),
401
+ ...(batch ? [`Recorded history batch: ${batch}. Restore uses the retained changes in the dashboard's Change history.`] : []),
402
+ ...(failure ? [
403
+ `Confirmed writes: ${applied.map(p => p.role).join(", ") || "none"}.`,
404
+ `Write not confirmed for ${failure.unconfirmedRole}; it may have been saved. Not attempted: ${failure.unattemptedRoles.join(", ") || "none"}.`,
405
+ "Earlier writes remain applied. Inspect 'ocx agent roles --json' before retrying.",
406
+ ] : []),
379
407
  ]);
408
+ if (failure) throw failure.cause;
380
409
  }
381
410
 
382
411
  async function roles(argv: string[], deps: RuntimeApiDeps): Promise<void> {
@@ -26,6 +26,15 @@ export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [
26
26
  "queued means submitted, not processed. unknown must not be replayed; no automatic retry, daemon start or thread resume.",
27
27
  "Exit 0: queued; 1: not sent; 3: unknown; 64: invalid usage. No Claude transport, native lifecycle mutation or skill installation."],
28
28
  },
29
+ {
30
+ command: ["message", "mcp"], usage: "ocx message mcp --codex <absolute-cli-path> --codex-home <absolute-existing-home>",
31
+ summary: "Serve opt-in MCP tools for stored Codex metadata and queued text delivery over stdio.",
32
+ routes: [], mutates: true, json: "none",
33
+ flags: [{ name: "--codex", value: "string", required: true, summary: "Explicit local Codex CLI executable." },
34
+ { name: "--codex-home", value: "string", required: true, summary: "Explicit existing Codex home; no creation or login." }],
35
+ details: ["macOS/Linux only. No proxy/control socket required. Starts bounded stdio helpers only when a tool is called; existing sessions/send behavior stays unchanged.",
36
+ "Stored threads are not verified live sessions. queued is not processing; unknown is never replayed. No daemon start, thread resume, steer, automatic replies or registration."],
37
+ },
29
38
  {
30
39
  command: ["advisor"],
31
40
  summary: "Inspect and configure the advisor sidecar (expert consultation for routed workers).",
@@ -215,12 +215,30 @@ export const CAPABILITIES: readonly Capability[] = [
215
215
  "A rotation left pending by a crash is resumed here — startup and status stop rather than guess which key generation is live.",
216
216
  ],
217
217
  },
218
+ {
219
+ command: ["update"],
220
+ summary: "Plan or apply an OpenCodex update.",
221
+ routes: [],
222
+ flags: [
223
+ { name: "--plan", value: "boolean", summary: "Preview an orchestrated update with --json." },
224
+ { name: "--yes", value: "boolean", summary: "Apply an orchestrated update with --json." },
225
+ { name: "--json", value: "boolean", summary: "Emit a versioned plan or result." },
226
+ { name: "--tag", value: "string", summary: "Select latest or preview for the legacy update or plan." },
227
+ { name: "--version", value: "string", summary: "Select an exact version for a plan or apply." },
228
+ { name: "--expect-plan", value: "string", summary: "Require the apply plan to match this planToken." },
229
+ { name: "--not-after", value: "string", summary: "Refuse mutation after this Unix millisecond deadline." },
230
+ ],
231
+ mutates: true,
232
+ json: "envelope",
233
+ details: ["Orchestrated exit codes: 0 verified or up-to-date; 10 refused; 11 previous version verified; 12 uncertain; 64 usage."],
234
+ },
218
235
  {
219
236
  command: ["capabilities"],
220
237
  summary: "List the declared CLI capabilities and the management routes they drive.",
221
238
  routes: [],
222
239
  flags: [
223
240
  { name: "--json", value: "boolean", summary: "Emit the full capability table as JSON." },
241
+ { name: "--contracts", value: "boolean", summary: "List supported versioned contracts." },
224
242
  { name: "--mutating-only", value: "boolean", summary: "Restrict output to capabilities that mutate state." },
225
243
  { name: "--route", value: "string", summary: "Show which capabilities drive a management route." },
226
244
  ],
@@ -618,7 +636,7 @@ export const CAPABILITIES: readonly Capability[] = [
618
636
  routes: [],
619
637
  flags: [{ name: "--plan-id", value: "string", summary: "Required 32-hex id from the current plan." }, { name: "--yes", value: "boolean", summary: "Required confirmation." }, { name: "--request-id", value: "string", summary: "Optional stable retry key." }, { name: "--json", value: "boolean", summary: "Emit the public job status." }],
620
638
  mutates: true, json: "envelope",
621
- details: ["Local counterpart of POST /api/codex/cli-update/apply: invokes the same durable job owner with --yes confirmation; HTTP admission separately requires a trusted loopback GUI session.", "Admission is stored under the protected current-user config root before the installer can run.", "Exit 0 requires an applied job; refused, not_applied, ambiguous and pending duplicate jobs exit 1, including with --json.", "Only POSIX npm-global managed installs are currently supported; Windows, shims and other managers remain refused."],
639
+ details: ["Local counterpart of POST /api/codex/cli-update/apply: invokes the same durable job owner with --yes confirmation; HTTP admission separately requires a current paired dashboard session on trusted loopback ingress, matching origin, CSRF and confirmed: true.", "Standalone HTTP pairing requires the configured literal 127.0.0.1 or ::1 origin; localhost aliases, wildcard binds and connected-client roles use the local CLI --yes path instead.", "Admission is stored under the protected current-user config root before the installer can run.", "Exit 0 requires an applied job; refused, not_applied, ambiguous and pending duplicate jobs exit 1, including with --json.", "Only POSIX npm-global managed installs are currently supported; Windows, shims and other managers remain refused."],
622
640
  usage: "ocx system codex-cli-update apply --plan-id <32-hex> --yes [--request-id <key>] [--json]",
623
641
  },
624
642
  {
@@ -752,6 +770,8 @@ export const CAPABILITIES: readonly Capability[] = [
752
770
  summary: "Synchronize client catalogs, including Aside profiles through the running server's mutation owner.",
753
771
  routes: [{ method: "POST", path: "/api/client-integrations/aside/sync" }],
754
772
  flags: [
773
+ { name: "--local-only", value: "boolean", summary: "Do not fan out the Home sync to linked Children." },
774
+ { name: "--json", value: "boolean", summary: "Emit the sync fan-out result as JSON." },
755
775
  { name: "--restart-codex", value: "boolean", summary: "Restart the Codex app-servers and fully quit and relaunch the Codex desktop app after a catalog, cache, or changed configuration write, on macOS, Linux and Windows." },
756
776
  { name: "--restart-app-server-only", value: "boolean", summary: "Restart only the Codex app-servers and leave the desktop app running; wins over --restart-codex when both are given." },
757
777
  { name: "--restart-desktop-app", value: "boolean", summary: "Deprecated alias of --restart-codex." },
@@ -759,12 +779,14 @@ export const CAPABILITIES: readonly Capability[] = [
759
779
  { name: "--expect-hub-key", value: "string", summary: "Sync only when this machine is a hub client connected with this API key id; otherwise exit 5 with nothing changed." },
760
780
  ],
761
781
  mutates: true,
762
- json: "none",
782
+ json: "payload",
763
783
  details: [
764
784
  "The Aside refresh uses the live server; other catalog synchronization also performs local work.",
785
+ "An update in flight or an unavailable update/sync mutex refuses without changes: update-in-flight, exit 7. Another sync reports sync-in-progress, exit 1.",
786
+ "A current Home catalog fans out to linked Children. Fan-out never requests a Codex app or app-server restart on a Child; use GOAT or ocx sync --restart-codex there. Applying changed Home settings may restart the Child's own OpenCodex client runtime.",
765
787
  "--expect-link/--expect-hub-key are checked under the lock that selects the sync path. A mismatch writes nothing, never falls back to local providers, exits 5, and ends stderr with {\"phase\":\"child_link_mismatch\"|\"hub_client_mismatch\",\"reason\":...}; reasons are disconnected, invalid_state, disconnect_pending, pending_operation, hub_client, link_client, other_link and other_key. Usage errors exit 2.",
766
788
  ],
767
- usage: "ocx sync [--expect-link <linkId> | --expect-hub-key <apiKeyId>] [--restart-codex] [--restart-app-server-only]",
789
+ usage: "ocx sync [--expect-link <linkId> | --expect-hub-key <apiKeyId>] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]",
768
790
  },
769
791
  {
770
792
  command: ["agent","subagents","force"],
@@ -13,6 +13,7 @@ import {
13
13
  type Capability,
14
14
  } from "./capabilities";
15
15
  import { takeFlag } from "./runtime-api";
16
+ import { CAPABILITY_CONTRACTS } from "./capability-contracts";
16
17
 
17
18
  function takeValueFlag(args: string[], flag: string): string | undefined {
18
19
  // Order-independent by construction: scan for the flag anywhere in argv rather than
@@ -49,14 +50,21 @@ function renderHuman(caps: readonly Capability[], includeHead: boolean): void {
49
50
  export async function runCapabilities(argv: string[]): Promise<number> {
50
51
  const args = [...argv];
51
52
  const json = takeFlag(args, "--json");
53
+ const contracts = takeFlag(args, "--contracts");
52
54
  const mutatingOnly = takeFlag(args, "--mutating-only");
53
55
  const route = takeValueFlag(args, "--route");
54
56
 
55
- if (args.length > 0 || (route !== undefined && route.trim().length === 0)) {
56
- console.error("Usage: ocx capabilities [--json] [--mutating-only] [--route <path>]");
57
+ if (args.length > 0 || (route !== undefined && route.trim().length === 0) || (contracts && (mutatingOnly || route !== undefined))) {
58
+ console.error("Usage: ocx capabilities [--json] [--contracts] [--mutating-only] [--route <path>]");
57
59
  return 64;
58
60
  }
59
61
 
62
+ if (contracts) {
63
+ if (json) console.log(JSON.stringify({ schemaVersion: 1, contracts: CAPABILITY_CONTRACTS }));
64
+ else for (const contract of CAPABILITY_CONTRACTS) console.log(contract);
65
+ return 0;
66
+ }
67
+
60
68
  let selected: readonly Capability[] = route === undefined ? CAPABILITIES : capabilitiesForRoute(route);
61
69
  if (mutatingOnly) selected = selected.filter(cap => cap.mutates);
62
70
 
@@ -64,7 +72,7 @@ export async function runCapabilities(argv: string[]): Promise<number> {
64
72
  // An unmatched route is a real answer, not an error: the route may be exempt or may
65
73
  // not exist. Say which, rather than exiting 0 with silence.
66
74
  if (json) {
67
- console.log(JSON.stringify({ schemaVersion: 1, route, capabilities: [] }, null, 2));
75
+ console.log(JSON.stringify({ schemaVersion: 1, contracts: CAPABILITY_CONTRACTS, route, capabilities: [] }, null, 2));
68
76
  } else {
69
77
  console.error(`No CLI capability drives ${route}.`);
70
78
  }
@@ -74,6 +82,7 @@ export async function runCapabilities(argv: string[]): Promise<number> {
74
82
  if (json) {
75
83
  console.log(JSON.stringify({
76
84
  schemaVersion: 1,
85
+ contracts: CAPABILITY_CONTRACTS,
77
86
  ...(route === undefined ? {} : { route }),
78
87
  capabilities: selected.map(cap => ({
79
88
  command: cap.command,
@@ -0,0 +1,2 @@
1
+ /** Versioned machine contracts implemented by this CLI. */
2
+ export const CAPABILITY_CONTRACTS = ["sync.home-fanout/1", "update.orchestrated/1"] as const;
@@ -7,10 +7,34 @@ import { readBoundedCodexConfig } from "../codex/inject/bounded-config-reader";
7
7
  import { buildProviderTableBlockForTarget } from "../codex/inject/config-toml";
8
8
  import { standaloneCodexRoutingTarget, validateCodexRoutingTarget } from "../codex/inject/routing-target";
9
9
  import { readClientConnectionState } from "../client/state";
10
+ import { normalizeBindHostname } from "../server/bind-host";
11
+ import { probeHostname, proveLiveProxyOwnedByHome, type LiveProxy } from "../server/proxy-liveness";
10
12
  import { codexHasOtherTokenConsumers, codexTokenConfigShapeIsSafe } from "./codex-launch-policy";
11
13
  import { codexLaunchHomeIsOwned, codexLaunchProjectAliasIsOwned, codexLaunchSystemNamespaceIsSafe } from "./codex-launch-ownership";
12
14
  import type { CodexTokenRefusal, CodexTokenRefusalReporter } from "./codex-launch-diagnostics";
13
15
 
16
+ export type CodexRuntimeAttestation = Readonly<{ origin: string }>;
17
+
18
+ /** Retain the exact dial endpoint that answered the ownership challenge, not just its verdict. */
19
+ export async function attestCodexRuntime(
20
+ live: LiveProxy,
21
+ prove: typeof proveLiveProxyOwnedByHome = proveLiveProxyOwnedByHome,
22
+ ): Promise<CodexRuntimeAttestation | null> {
23
+ // Probe the address the listener actually binds: a configured localhost binds 127.0.0.1,
24
+ // which is also what the standalone Codex target dials.
25
+ const snapshot = Object.freeze({ ...live, probeHostname: normalizeBindHostname(live.probeHostname ?? live.hostname) });
26
+ try {
27
+ const origin = new URL(`http://${probeHostname(snapshot.probeHostname)}:${snapshot.port}`).origin;
28
+ return await prove(snapshot) === "proven" ? Object.freeze({ origin }) : null;
29
+ } catch { return null; }
30
+ }
31
+
32
+ /** IPv4 and IPv6 listeners are distinct recipients, even when their ports are equal. */
33
+ export function codexRuntimeAttestationMatchesTarget(baseUrl: string, proof: CodexRuntimeAttestation | null | undefined): boolean {
34
+ try { return proof !== null && proof !== undefined && new URL(baseUrl).origin === proof.origin; }
35
+ catch { return false; }
36
+ }
37
+
14
38
  /** Resolve once; the credential verifier and child must use this exact directory. */
15
39
  export function resolveCodexLaunchHome(env: Record<string, string | undefined>): string | null {
16
40
  try {
@@ -28,7 +52,7 @@ export function resolveCodexLaunchHome(env: Record<string, string | undefined>):
28
52
  }
29
53
 
30
54
  /** Config classification is a startup hint; credentials need an independently bound destination. */
31
- export function codexCredentialDestinationIsTrusted(home: string, systemNamespaceDirectory?: string, report?: CodexTokenRefusalReporter): boolean {
55
+ export function codexCredentialDestinationIsTrusted(home: string, systemNamespaceDirectory?: string, report?: CodexTokenRefusalReporter, runtimeAttestation?: CodexRuntimeAttestation | null): boolean {
32
56
  const refuse = (reason: CodexTokenRefusal): false => { report?.(reason); return false; };
33
57
  try {
34
58
  if (!codexLaunchHomeIsOwned(home)) return refuse("ownership");
@@ -43,15 +67,20 @@ export function codexCredentialDestinationIsTrusted(home: string, systemNamespac
43
67
  if (diagnostics.error || diagnostics.source === "fallback") return refuse("installationConfig");
44
68
  const cfg = diagnostics.config;
45
69
  let target = standaloneCodexRoutingTarget(cfg.port, cfg);
70
+ // A direct client's proof comes from its own machine listener, never from the hub it
71
+ // dials, so only a standalone destination can be compared with the proven origin.
72
+ let destinationIsProvenListener = true;
46
73
  if (cfg.runtimeRole === "client") {
47
74
  // Direct clients bind to persisted connection state; link clients use an authless relay.
48
75
  const connection = readClientConnectionState();
49
76
  if (connection.kind !== "connected" || connection.value.transport === "link") return refuse("connection");
50
77
  target = validateCodexRoutingTarget({ baseUrl: `${connection.value.serverUrl}/v1`, requiresAdmissionToken: true, tokenEnv: "OPENCODEX_API_AUTH_TOKEN" });
78
+ destinationIsProvenListener = false;
51
79
  }
52
80
  const url = new URL(target.baseUrl);
53
81
  if (!target.requiresAdmissionToken) return refuse("admission");
54
82
  if (url.protocol !== "http:" || !["127.0.0.1", "[::1]"].includes(url.hostname)) return refuse("loopback");
83
+ if (destinationIsProvenListener && !codexRuntimeAttestationMatchesTarget(target.baseUrl, runtimeAttestation)) return refuse("destination");
55
84
  const content = readBoundedCodexConfig(join(home, "config.toml"));
56
85
  if (content === null) return refuse("configRead");
57
86
  const config = Bun.TOML.parse(content) as Record<string, unknown>;