@bitkyc08/opencodex 2.100.1 → 2.100.2

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 (163) hide show
  1. package/gui/dist/assets/App-BpJOzw4F.js +59 -0
  2. package/gui/dist/assets/Tray-BcaI-VCr.js +1 -0
  3. package/gui/dist/assets/{brand-mark-nr3ziR-T.js → brand-mark-DU-0Vdkr.js} +1 -1
  4. package/gui/dist/assets/index-Bbor_y80.js +94 -0
  5. package/gui/dist/assets/index-DJEkIDAi.css +2 -0
  6. package/gui/dist/assets/{segment-thumb-features-DKCVUUTi.js → segment-thumb-features-e9A_FogJ.js} +1 -1
  7. package/gui/dist/classic/assets/{App-CgPBKUP-.js → App-BrIlUiLc.js} +18 -18
  8. package/gui/dist/classic/assets/{Tray-BedmOsE7.js → Tray-DT146AhS.js} +1 -1
  9. package/gui/dist/classic/assets/index-DyJHagvT.js +94 -0
  10. package/gui/dist/classic/assets/quota-summary-CakPe9Ni.js +1 -0
  11. package/gui/dist/classic/index.html +1 -1
  12. package/gui/dist/index.html +2 -2
  13. package/package.json +2 -2
  14. package/src/adapters/client-fingerprint.ts +5 -3
  15. package/src/adapters/cursor/native-exec.ts +3 -2
  16. package/src/adapters/cursor/tool-guidance.ts +3 -3
  17. package/src/adapters/cursor/tool-wording.ts +10 -1
  18. package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
  19. package/src/adapters/google-antigravity-wire.ts +13 -6
  20. package/src/adapters/google-truncation.ts +4 -2
  21. package/src/adapters/google.ts +8 -2
  22. package/src/adapters/openai-chat/tool-schema.ts +9 -0
  23. package/src/adapters/openai-responses/tool-schema.ts +18 -4
  24. package/src/adapters/run-turn-queue.ts +139 -5
  25. package/src/adapters/upstream-http-error.ts +4 -2
  26. package/src/bridge/sse.ts +8 -1
  27. package/src/claude/chat-tool-dispatch.ts +233 -0
  28. package/src/claude/inbound-tool-loading.ts +42 -17
  29. package/src/cli/account-api.ts +6 -0
  30. package/src/cli/account-extended.ts +60 -6
  31. package/src/cli/account-key-quota.ts +22 -2
  32. package/src/cli/account.ts +1 -1
  33. package/src/cli/capabilities-access-remote.ts +10 -0
  34. package/src/cli/capabilities-agents-routing.ts +2 -2
  35. package/src/cli/capabilities-base.ts +2 -2
  36. package/src/cli/claude.ts +19 -14
  37. package/src/cli/config-command.ts +24 -1
  38. package/src/cli/connect.ts +36 -3
  39. package/src/cli/gui-pair-client.ts +23 -2
  40. package/src/cli/help.ts +1 -1
  41. package/src/cli/hub.ts +18 -1
  42. package/src/cli/link-child-ops.ts +136 -0
  43. package/src/cli/link-status-child.ts +94 -0
  44. package/src/cli/link.ts +22 -9
  45. package/src/cli/registry.ts +3 -2
  46. package/src/cli/sync-command.ts +3 -1
  47. package/src/cli/sync-fanout.ts +8 -81
  48. package/src/client/link-readiness.ts +16 -6
  49. package/src/client/link-tunnel-status.ts +76 -0
  50. package/src/clients/config-export.ts +14 -1
  51. package/src/codex/account-resume-health.ts +41 -0
  52. package/src/codex/auth-api/login-flow.ts +6 -0
  53. package/src/codex/auth-api/routes.ts +35 -2
  54. package/src/codex/catalog/gather-capture.ts +2 -0
  55. package/src/codex/catalog/provider-models.ts +13 -8
  56. package/src/codex/convergence-types.ts +2 -0
  57. package/src/codex/quota.ts +111 -6
  58. package/src/combos/cooldown-store.ts +208 -0
  59. package/src/combos/failover.ts +432 -35
  60. package/src/config/salvage.ts +1 -0
  61. package/src/config/schema/config-schema.ts +6 -3
  62. package/src/config/schema/leaf-validators.ts +34 -12
  63. package/src/generated/compatibility-version.json +213 -121
  64. package/src/lib/catalog-etag.ts +10 -0
  65. package/src/lib/client-error-body.ts +15 -0
  66. package/src/lib/context-overflow-verdict.ts +266 -9
  67. package/src/lib/failure-detail.ts +72 -3
  68. package/src/lib/hard-refusal.ts +259 -0
  69. package/src/link/child-activity.ts +57 -0
  70. package/src/link/child-catalog-freshness.ts +149 -0
  71. package/src/link/child-gated-ocx.ts +117 -0
  72. package/src/link/child-observations.ts +205 -0
  73. package/src/link/child-observe.ts +121 -0
  74. package/src/link/child-ops-engine.ts +162 -0
  75. package/src/link/child-update-contract.ts +165 -0
  76. package/src/link/paths.ts +5 -0
  77. package/src/link/remote-windows.ts +42 -6
  78. package/src/link/ssh-argv.ts +126 -32
  79. package/src/link/status-projection.ts +73 -0
  80. package/src/link/sync-fanout-classify.ts +98 -0
  81. package/src/link/tunnel-state.ts +10 -4
  82. package/src/messaging/mcp-queue-rpc.ts +2 -1
  83. package/src/messaging/mcp-queue-server.ts +5 -0
  84. package/src/messaging/mcp-reply-tools.ts +24 -9
  85. package/src/messaging/mcp-reply-wait.ts +70 -0
  86. package/src/oauth/account-resume-health.ts +60 -0
  87. package/src/oauth/index.ts +1 -0
  88. package/src/oauth/store.ts +44 -1
  89. package/src/providers/api-key-pause-state.ts +23 -0
  90. package/src/providers/api-key-pause.ts +68 -10
  91. package/src/providers/api-key-selection-capture.ts +3 -1
  92. package/src/providers/api-key-selection.ts +3 -2
  93. package/src/providers/api-keys.ts +18 -5
  94. package/src/providers/claude-cli-usage-state.ts +11 -6
  95. package/src/providers/claude-cli-usage.ts +27 -9
  96. package/src/providers/codex-capacity.ts +11 -2
  97. package/src/providers/key-failover.ts +13 -6
  98. package/src/providers/model-discovery-config.ts +31 -0
  99. package/src/providers/model-discovery-diagnostic.ts +34 -3
  100. package/src/providers/model-discovery.ts +43 -7
  101. package/src/providers/model-rename-fields.ts +2 -0
  102. package/src/providers/openai-sidecar.ts +15 -2
  103. package/src/providers/provider-id-rewrite.ts +3 -0
  104. package/src/providers/quota/account-cache.ts +52 -34
  105. package/src/providers/quota/anthropic-usage-windows.ts +19 -9
  106. package/src/providers/quota/report-cache.ts +53 -5
  107. package/src/providers/quota/vendor-probes-key.ts +73 -0
  108. package/src/providers/quota/vendor-probes-oauth.ts +57 -3
  109. package/src/providers/quota-key-accounts.ts +12 -5
  110. package/src/providers/quota-mistral-budget.ts +18 -0
  111. package/src/providers/quota-types.ts +25 -0
  112. package/src/providers/quota.ts +22 -22
  113. package/src/providers/reasoning-metadata.ts +1051 -12
  114. package/src/quota/reset-observer.ts +4 -2
  115. package/src/quota/reset-seen-store.ts +9 -0
  116. package/src/quota/window-mapping.ts +1 -0
  117. package/src/quota-pool/assemble.ts +4 -1
  118. package/src/responses/hosted-tool-policy.ts +56 -12
  119. package/src/router.ts +2 -0
  120. package/src/server/auth-cors.ts +11 -8
  121. package/src/server/catalog-download.ts +3 -5
  122. package/src/server/chat-native.ts +11 -2
  123. package/src/server/claude-messages.ts +2 -1
  124. package/src/server/images.ts +41 -13
  125. package/src/server/index/link-listener.ts +16 -2
  126. package/src/server/index/link-relay-sessions.ts +43 -2
  127. package/src/server/index/optional-listeners.ts +18 -0
  128. package/src/server/management/config-routes.ts +7 -1
  129. package/src/server/management/context.ts +1 -1
  130. package/src/server/management/link-child-ops-routes.ts +116 -0
  131. package/src/server/management/link-route-state.ts +10 -0
  132. package/src/server/management/link-routes.ts +10 -0
  133. package/src/server/management/oauth-account-routes.ts +33 -4
  134. package/src/server/management/provider-overwrite-carry.ts +28 -3
  135. package/src/server/management/provider-routes.ts +16 -11
  136. package/src/server/management/route-registry.ts +3 -0
  137. package/src/server/messages-native.ts +5 -0
  138. package/src/server/request-log-failure-detail.ts +59 -1
  139. package/src/server/responses/adapter-dispatch.ts +35 -44
  140. package/src/server/responses/combo-stream-preflight.ts +146 -29
  141. package/src/server/responses/compact.ts +16 -5
  142. package/src/server/responses/context-overflow.ts +58 -2
  143. package/src/server/responses/core-combo-failure.ts +29 -4
  144. package/src/server/responses/core-combo-native.ts +3 -1
  145. package/src/server/responses/core-combo.ts +30 -3
  146. package/src/server/responses/core-errors.ts +3 -1
  147. package/src/server/responses/core-opaque-recovery.ts +45 -2
  148. package/src/server/responses/core-options.ts +12 -0
  149. package/src/server/responses/passthrough-dispatch.ts +30 -38
  150. package/src/server/responses/request-transport.ts +43 -14
  151. package/src/server/responses/reset-replay.ts +58 -2
  152. package/src/server/responses/run-turn-execution.ts +56 -30
  153. package/src/types/claude-tool-loading.ts +48 -0
  154. package/src/types/config.ts +5 -35
  155. package/src/types/provider.ts +21 -0
  156. package/src/types.ts +1 -0
  157. package/src/web-search/parse.ts +21 -2
  158. package/gui/dist/assets/App-g3Cm2xhZ.js +0 -59
  159. package/gui/dist/assets/Tray-BMDkAiXy.js +0 -1
  160. package/gui/dist/assets/index-Bziu8gTy.css +0 -2
  161. package/gui/dist/assets/index-OYzhQUNP.js +0 -94
  162. package/gui/dist/classic/assets/index-BR-HhNrp.js +0 -94
  163. package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +0 -1
@@ -0,0 +1,94 @@
1
+ import type { ChildOp, ChildOperationSummary } from "../link/child-observations";
2
+ import type { InstallKind, UpdateRoute } from "../link/child-update-contract";
3
+ import type { LinkChildOpsStatus } from "../link/status-projection";
4
+
5
+ /** What the Child reports about its Codex app-servers (wp8); known fields only, each optional. */
6
+ export interface LinkChildCodexView {
7
+ appServers?: "fresh" | "stale" | "not_running" | "unknown"; staleCount?: number; catalogMatchesHome?: boolean | null;
8
+ catalogSyncedAt?: number | null; reportedAt?: number | null;
9
+ }
10
+
11
+ /**
12
+ * A row's `child` block as this CLI reads it. Tolerant (G1): a later Home may add keys or enum values, so unknown keys
13
+ * are dropped and an unknown enum value reads "unknown"; a known key with the wrong type is still rejected.
14
+ */
15
+ export type LinkChildOpsView = Omit<LinkChildOpsStatus, "update" | "codex" | "activeJob" | "lastOperation"> & {
16
+ update: { route: UpdateRoute | "unknown" | null; reason: string | null; observedAt: string | null };
17
+ codex: LinkChildCodexView | null;
18
+ activeJob: { jobId: string; op: ChildOp | string; state: "queued" | "running" | "unknown" } | null;
19
+ lastOperation: (Omit<ChildOperationSummary, "op"> & { op: ChildOp | string }) | null;
20
+ };
21
+
22
+ const INSTALL_KINDS: ReadonlySet<string> = new Set<InstallKind>(["npm", "pnpm", "bun", "source", "mise", "desktop-app", "goat", "standalone", "ocx-child", "unknown"]);
23
+ const ROUTES: ReadonlySet<string> = new Set<UpdateRoute>(["orchestrated", "desktop-request", "owner-action", "replant", "none"]);
24
+ const SKEWS: ReadonlySet<string> = new Set(["same", "behind", "ahead", "unknown"]);
25
+ const CATALOG_STATES: ReadonlySet<string> = new Set(["current", "behind", "unknown"]);
26
+ const APP_SERVER_STATES: ReadonlySet<string> = new Set(["fresh", "stale", "not_running", "unknown"]);
27
+
28
+ const isRecord = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
29
+
30
+ export function validateChildOps(value: unknown, index: number): LinkChildOpsView {
31
+ const fail = (field: string): never => { throw new Error(`invalid link API response: link ${index} child ${field}`); };
32
+ const record = (target: unknown, field: string): Record<string, unknown> => isRecord(target) ? target : fail(field);
33
+ const text = (target: unknown, field: string): string => typeof target === "string" && target.length <= 256 ? target : fail(field);
34
+ const nullableText = (target: unknown, field: string): string | null => target === null ? null : text(target, field);
35
+ const count = (target: unknown, field: string): number => typeof target === "number" && Number.isFinite(target) && target >= 0 ? target : fail(field);
36
+ const nullableCount = (target: unknown, field: string): number | null => target === null ? null : count(target, field);
37
+ const member = <T extends string>(set: ReadonlySet<string>, target: unknown, field: string): T | "unknown" =>
38
+ set.has(text(target, field)) ? target as T : "unknown";
39
+ const child = record(value, "");
40
+ const update = record(child.update, "update");
41
+ const catalog = record(child.catalog, "catalog");
42
+ const activity = record(child.activity, "activity");
43
+ if (typeof activity.idle !== "boolean") fail("activity.idle");
44
+ const installKind = child.installKind === null ? null : member<InstallKind>(INSTALL_KINDS, child.installKind, "installKind");
45
+ return {
46
+ homeVersion: text(child.homeVersion, "homeVersion"),
47
+ runningVersion: nullableText(child.runningVersion, "runningVersion"),
48
+ installedVersion: nullableText(child.installedVersion, "installedVersion"),
49
+ installKind: installKind as InstallKind | null,
50
+ versionSkew: member<LinkChildOpsStatus["versionSkew"]>(SKEWS, child.versionSkew, "versionSkew"),
51
+ update: {
52
+ route: update.route === null ? null : member<UpdateRoute>(ROUTES, update.route, "update.route"),
53
+ reason: nullableText(update.reason, "update.reason"),
54
+ observedAt: nullableText(update.observedAt, "update.observedAt"),
55
+ },
56
+ catalog: {
57
+ state: member<LinkChildOpsStatus["catalog"]["state"]>(CATALOG_STATES, catalog.state, "catalog.state"),
58
+ pulledAt: nullableCount(catalog.pulledAt, "catalog.pulledAt"),
59
+ homeChangedAt: nullableCount(catalog.homeChangedAt, "catalog.homeChangedAt"),
60
+ },
61
+ codex: child.codex === null ? null : validateCodex(record(child.codex, "codex"), fail, member, nullableCount, count),
62
+ activity: { idle: activity.idle as boolean, inFlight: count(activity.inFlight, "activity.inFlight"), lastDataEndAt: nullableCount(activity.lastDataEndAt, "activity.lastDataEndAt") },
63
+ activeJob: child.activeJob === null ? null : (() => {
64
+ const job = record(child.activeJob, "activeJob");
65
+ const state = text(job.state, "activeJob.state");
66
+ return { jobId: text(job.jobId, "activeJob.jobId"), op: text(job.op, "activeJob.op"), state: state === "queued" || state === "running" ? state : "unknown" as const };
67
+ })(),
68
+ lastOperation: child.lastOperation === null ? null : (() => {
69
+ const last = record(child.lastOperation, "lastOperation");
70
+ return {
71
+ op: text(last.op, "lastOperation.op"), jobId: text(last.jobId, "lastOperation.jobId"), state: text(last.state, "lastOperation.state"),
72
+ reason: nullableText(last.reason, "lastOperation.reason"),
73
+ ...(last.fromVersion === undefined ? {} : { fromVersion: text(last.fromVersion, "lastOperation.fromVersion") }),
74
+ ...(last.toVersion === undefined ? {} : { toVersion: text(last.toVersion, "lastOperation.toVersion") }),
75
+ finishedAt: text(last.finishedAt, "lastOperation.finishedAt"),
76
+ };
77
+ })(),
78
+ };
79
+ }
80
+
81
+ function validateCodex(codex: Record<string, unknown>, fail: (field: string) => never,
82
+ member: <T extends string>(set: ReadonlySet<string>, target: unknown, field: string) => T | "unknown",
83
+ nullableCount: (target: unknown, field: string) => number | null, count: (target: unknown, field: string) => number): LinkChildCodexView {
84
+ const view: LinkChildCodexView = {};
85
+ if (codex.appServers !== undefined) view.appServers = member<NonNullable<LinkChildCodexView["appServers"]>>(APP_SERVER_STATES, codex.appServers, "codex.appServers");
86
+ if (codex.staleCount !== undefined) view.staleCount = count(codex.staleCount, "codex.staleCount");
87
+ if (codex.catalogMatchesHome !== undefined) {
88
+ if (codex.catalogMatchesHome !== null && typeof codex.catalogMatchesHome !== "boolean") fail("codex.catalogMatchesHome");
89
+ view.catalogMatchesHome = codex.catalogMatchesHome as boolean | null;
90
+ }
91
+ if (codex.catalogSyncedAt !== undefined) view.catalogSyncedAt = nullableCount(codex.catalogSyncedAt, "codex.catalogSyncedAt");
92
+ if (codex.reportedAt !== undefined) view.reportedAt = nullableCount(codex.reportedAt, "codex.reportedAt");
93
+ return view;
94
+ }
package/src/cli/link.ts CHANGED
@@ -10,6 +10,8 @@ import { CODEX_SETTINGS_DIGEST_PATTERN } from "../link/codex-settings";
10
10
  import type { LinkLocalPeer, LinkPeerStatus } from "../link/compatibility";
11
11
  import { runLinkEnrollment } from "./link-enrollment";
12
12
  import { runLinkCleanup, type LinkCleanupDeps } from "./link-cleanup";
13
+ import { runLinkCheck } from "./link-child-ops";
14
+ import { validateChildOps, type LinkChildOpsView } from "./link-status-child";
13
15
  import { assertSshAlias } from "../link/ssh-argv";
14
16
  import { boundHint } from "../link/ssh-runner";
15
17
  import { linkStorePath } from "../link/paths";
@@ -42,15 +44,20 @@ export const LINK_USAGE = `Usage:
42
44
  ocx link revoke --link-id <id> [--purge] [--force --yes] [--json]
43
45
  ocx link reconnect --link-id <id> [--json]
44
46
  ocx link cleanup [--link-id <id>] [--json]
47
+ ocx link check (--link-id <id> | --all) [--no-wait] [--json]
45
48
 
46
49
  Forced revoke skips remote cleanup. Run ocx disconnect on the remote client.
47
- Cleanup reports each Child's platform with disconnect guidance; it changes nothing.`;
50
+ Cleanup reports each Child's platform with disconnect guidance; it changes nothing.
51
+ Check reads each Home-initiated Child's installed version and update route; it changes no install.`;
48
52
 
49
53
  /**
50
54
  * What `ocx link status` prints: the runtime's status DTO itself, so a field the server adds (like
51
- * `peer` or the diagnostics `tunnel`) is part of this type the moment it is part of the wire.
55
+ * `peer` or the diagnostics `tunnel`) is part of this type the moment it is part of the wire. The `child` block is
56
+ * read tolerantly, so its type is this CLI's view of it.
52
57
  */
53
- export type LinkStatusPayload = LinkStatusDto;
58
+ export type LinkStatusPayload = Omit<LinkStatusDto, "links"> & {
59
+ links: Array<Omit<LinkStatusDto["links"][number], "child"> & { child?: LinkChildOpsView }>;
60
+ };
54
61
 
55
62
  export interface LinkIssuePayload {
56
63
  linkId: string;
@@ -156,7 +163,7 @@ export function validateStatus(value: unknown): LinkStatusPayload {
156
163
  if (!isRecord(candidate)) throw new Error(`invalid link API response: link ${index}`);
157
164
  // The OCX-6 parity fields are optional on the wire (an older runtime omits them) and always
158
165
  // present in this output, null when absent.
159
- assertKeys(candidate, ["id", "alias", "direction", "state", "since", "reason", "tunnelPort"], [...PARITY_KEYS, "peer", "tunnel", "childKind"], `link ${index}`);
166
+ assertKeys(candidate, ["id", "alias", "direction", "state", "since", "reason", "tunnelPort"], [...PARITY_KEYS, "peer", "tunnel", "childKind", "child"], `link ${index}`);
160
167
  const parity = validateParity(candidate, index);
161
168
  if (typeof candidate.id !== "string" || !LINK_ID.test(candidate.id)
162
169
  || !validString(candidate.alias) || (candidate.direction !== "hub-initiated" && candidate.direction !== "client-initiated")
@@ -177,6 +184,7 @@ export function validateStatus(value: unknown): LinkStatusPayload {
177
184
  ...parity,
178
185
  ...(candidate.peer !== undefined ? { peer: validatePeer(candidate.peer, index) } : {}),
179
186
  ...(candidate.tunnel !== undefined ? { tunnel: validateTunnel(candidate.tunnel, index) } : {}),
187
+ ...(candidate.child !== undefined ? { child: validateChildOps(candidate.child, index) } : {}),
180
188
  };
181
189
  });
182
190
  let child: LinkStatusPayload["child"] = null;
@@ -305,10 +313,10 @@ async function runStatus(args: string[], deps: LinkCliDeps): Promise<void> {
305
313
  }
306
314
  throw error;
307
315
  }
308
- // A proxy older than the compatibility report or the tunnel diagnostics ignores the query and
309
- // answers without those fields.
316
+ // A proxy older than the compatibility report, the tunnel diagnostics or the Child block ignores
317
+ // the query and answers without those fields.
310
318
  const result = validateStatus(await viaLocalControlSocket(baseUrl, deps,
311
- statusDeps => linkRequest<unknown>("/api/link/status?compatibility=1&diagnostics=1", {}, statusDeps)));
319
+ statusDeps => linkRequest<unknown>("/api/link/status?compatibility=1&diagnostics=1&children=1", {}, statusDeps)));
312
320
  console.log(JSON.stringify(result));
313
321
  }
314
322
 
@@ -383,7 +391,10 @@ async function runReconnect(args: string[], deps: LinkCliDeps): Promise<void> {
383
391
  }
384
392
 
385
393
  export async function runLinkCommand(rawArgs: string[], deps: LinkCliDeps = {}): Promise<number> {
386
- return runCliAction(async () => {
394
+ // runCliAction maps thrown errors (2 usage, 4 on 404, 5 on 409, else 1) and returns 0 on success, so a
395
+ // verb's own verdict exit (check: 6 for a partial result) travels beside it.
396
+ let verdictExit = 0;
397
+ const code = await runCliAction(async () => {
387
398
  const args = [...rawArgs];
388
399
  const command = args.shift();
389
400
  if (command === "probe" || command === "add") await runLinkEnrollment(command, args, deps, linkRequest, LINK_USAGE);
@@ -393,8 +404,10 @@ export async function runLinkCommand(rawArgs: string[], deps: LinkCliDeps = {}):
393
404
  else if (command === "revoke") await runRevoke(args, deps);
394
405
  else if (command === "reconnect") await runReconnect(args, deps);
395
406
  else if (command === "cleanup") await runLinkCleanup(args, deps, LINK_USAGE);
396
- else throw new CliUsageError("link requires one of: probe, add, port, issue, status, revoke, reconnect, cleanup", LINK_USAGE);
407
+ else if (command === "check") verdictExit = await runLinkCheck(args, deps, linkRequest, LINK_USAGE);
408
+ else throw new CliUsageError("link requires one of: probe, add, port, issue, status, revoke, reconnect, cleanup, check", LINK_USAGE);
397
409
  });
410
+ return code === 0 ? verdictExit : code;
398
411
  }
399
412
 
400
413
  const PARITY_KEYS = ["lastApplyAt", "runtimeStartedAt", "appliedCodexSettingsDigest", "reportedAt"] as const;
@@ -152,7 +152,7 @@ export const CLI_COMMANDS: CliCommandEntry[] = [
152
152
  },
153
153
  {
154
154
  name: "link",
155
- usage: "ocx link <port|issue|status|revoke|reconnect|cleanup>",
155
+ usage: "ocx link <port|issue|status|revoke|reconnect|cleanup|check>",
156
156
  summary: "Allocate and manage a loopback remote home link.",
157
157
  details: [
158
158
  "Port: ocx link port [--json]",
@@ -161,7 +161,8 @@ export const CLI_COMMANDS: CliCommandEntry[] = [
161
161
  "Revoke: ocx link revoke --link-id <id> [--force --yes] [--json]",
162
162
  "Reconnect: ocx link reconnect --link-id <id> [--json]",
163
163
  "Cleanup: ocx link cleanup [--link-id <id>] [--json]",
164
- "Issue, status, revoke, and reconnect use the running proxy's loopback management API and admin token.",
164
+ "Check: ocx link check (--link-id <id> | --all) [--no-wait] [--json]",
165
+ "Issue, status, revoke, reconnect, and check use the running proxy's loopback management API and admin token.",
165
166
  ],
166
167
  },
167
168
  {
@@ -217,7 +217,9 @@ export async function runSyncCommand(deps: CliDispatchDeps): Promise<number> {
217
217
  }
218
218
  try {
219
219
  const result = await runFanoutProcess(buildExecArgv({ alias: link.alias, knownHostsFile: linkKnownHostsPath(), argv: remotePinnedSyncArgv(link.id, platform) }), { timeoutMs: Math.max(0, deadline - Date.now()) });
220
- return { ...classifySyncResult(result), exit: result.code };
220
+ // Pick the public fields: a verdict key that ocx.sync.fanout/1 does not define never reaches the document.
221
+ const { state, reason } = classifySyncResult(result);
222
+ return { state, reason, exit: result.code };
221
223
  } catch (error) {
222
224
  if (error instanceof FanoutProcessError) return { state: error.reason === "deadline-exceeded" || error.reason === "termination-unconfirmed" ? "timed-out" : "failed", reason: error.reason, exit: null };
223
225
  throw error;
@@ -1,86 +1,11 @@
1
- import { compareStrictSemver, parseStrictSemver } from "../lib/strict-semver";
2
1
  import type { LinkRecord, LinkStore } from "../link/store";
3
- import type { LinkStatusDto } from "../link/status-projection";
2
+ import type { LinkStatusPayload } from "./link";
4
3
  import { LinkStatusError } from "./sync-link-status";
5
4
 
6
- export const REMOTE_LINK_SYNC_MESSAGE = "Remote Link Home catalog synchronized.";
7
- export const STALE_REMOTE_CATALOG_MESSAGE = "Home unavailable; retained and applied the last-known-good remote catalog (stale).";
5
+ export { classifySyncResult, classifyVersionProbe, parseOcxVersion, REMOTE_LINK_SYNC_MESSAGE,
6
+ STALE_REMOTE_CATALOG_MESSAGE, type ChildVerdict } from "../link/sync-fanout-classify";
8
7
  export const SYNC_FANOUT_PARTIAL_EXIT = 6;
9
8
 
10
- export type ChildVerdict = { state: "synced" | "skipped" | "failed"; reason: string | null };
11
- const failure = (reason: string): ChildVerdict => ({ state: "failed", reason });
12
- const skipped = (reason: string): ChildVerdict => ({ state: "skipped", reason });
13
- const minimum = parseStrictSemver("2.93.0")!;
14
-
15
- export function parseOcxVersion(output: string): string | null {
16
- const version = output.trim().replace(/^opencodex /, "");
17
- return parseStrictSemver(version) ? version : null;
18
- }
19
-
20
- export function classifyVersionProbe(output: string): "child-ocx-version-unknown" | "child-ocx-lacks-expect-link" | null {
21
- const version = parseOcxVersion(output);
22
- if (!version) return "child-ocx-version-unknown";
23
- return compareStrictSemver(parseStrictSemver(version)!, minimum) < 0 ? "child-ocx-lacks-expect-link" : null;
24
- }
25
-
26
- const mismatchReasons = new Set(["disconnected", "invalid_state", "disconnect_pending", "pending_operation", "hub_client", "link_client", "other_link", "other_key"]);
27
-
28
- function validDocument(value: unknown): "synced" | "stale" | null {
29
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
30
- const v = value as Record<string, unknown>;
31
- const keysAre = (object: Record<string, unknown>, keys: readonly string[]): boolean => Object.keys(object).length === keys.length && keys.every(key => Object.hasOwn(object, key));
32
- if (!keysAre(v, ["schema", "home", "fanout", "children"])) return null;
33
- if (v.schema !== "ocx.sync.fanout/1" || !v.home || typeof v.home !== "object" || Array.isArray(v.home)
34
- || !v.fanout || typeof v.fanout !== "object" || Array.isArray(v.fanout) || !Array.isArray(v.children)) return null;
35
- const home = v.home as Record<string, unknown>, fanout = v.fanout as Record<string, unknown>;
36
- if (!keysAre(home, ["state", "exit"]) || !keysAre(fanout, ["state", "reason"])) return null;
37
- if (home.exit !== 0 || (home.state !== "synced" && home.state !== "stale")) return null;
38
- if (fanout.state !== "not-applicable" || fanout.reason !== null || v.children.length !== 0) return null;
39
- return home.state;
40
- }
41
-
42
- export function classifySyncResult(result: { code: number; stdout: string; stderr: string }): ChildVerdict {
43
- const { code, stdout, stderr } = result;
44
- if (code === 255) return failure("ssh-failed");
45
- if (code === 127) return failure("child-ocx-not-found");
46
- if (code === 126) return failure("child-ocx-not-contained");
47
- if (code === 125) return skipped("child-platform-unsupported");
48
- const lines = stderr.split(/\r?\n/);
49
- const last = stderr.trimEnd().split(/\r?\n/).at(-1);
50
- if (code === 121) {
51
- if (last === "ocx-fanout:child-ocx-lacks-expect-link") return skipped("child-ocx-lacks-expect-link");
52
- if (last === "ocx-fanout:child-ocx-version-unknown") return skipped("child-ocx-version-unknown");
53
- return failure("child-sync-failed");
54
- }
55
- const markers = lines.map(line => /^ocx-fanout:selected:(.+)$/.exec(line)).filter(match => match !== null);
56
- if (markers.length !== 1 || !parseStrictSemver(markers[0]![1]!)) return failure("child-output-invalid");
57
- const outputLines = stdout.split(/\r?\n/);
58
- const delimiters = outputLines.flatMap((line, index) => line === "ocx-fanout:stdout-begin" ? [index] : []);
59
- if (delimiters.length !== 1) return failure("child-output-invalid");
60
- if (code === 5) {
61
- try {
62
- const detail: unknown = JSON.parse(last ?? "");
63
- if (detail && typeof detail === "object" && "phase" in detail && detail.phase === "child_link_mismatch"
64
- && "reason" in detail && typeof detail.reason === "string" && mismatchReasons.has(detail.reason)) return skipped(`child-link-mismatch:${detail.reason}`);
65
- } catch { /* The generic mismatch is the only safe fallback. */ }
66
- return skipped("child-link-mismatch");
67
- }
68
- if (code === 7) return skipped("child-updating");
69
- if (code !== 0) return failure("child-sync-failed");
70
- const text = outputLines.slice(delimiters[0]! + 1).join("\n").trim();
71
- if (text.startsWith("{")) {
72
- try {
73
- const state = validDocument(JSON.parse(text));
74
- if (state === "synced") return { state: "synced", reason: null };
75
- if (state === "stale") return failure("child-catalog-stale");
76
- } catch { /* Reject invalid or multiple JSON documents. */ }
77
- return failure("child-output-invalid");
78
- }
79
- if (text.includes(STALE_REMOTE_CATALOG_MESSAGE)) return failure("child-catalog-stale");
80
- if (text.includes(REMOTE_LINK_SYNC_MESSAGE)) return { state: "synced", reason: null };
81
- return failure("child-output-invalid");
82
- }
83
-
84
9
  export type HomeResult = { state: "synced" | "stale" | "skipped" | "failed"; exit: number };
85
10
  export type ChildResult = { linkId: string; alias: string; state: "synced" | "skipped" | "failed" | "timed-out"; reason: string | null; exit: number | null; hint?: string };
86
11
  export type FanoutDocument = { schema: "ocx.sync.fanout/1"; home: HomeResult; fanout: { state: "ran" | "disabled" | "not-applicable" | "failed"; reason: string | null }; children: ChildResult[] };
@@ -98,7 +23,7 @@ function childSkipHint(reason: string | null, alias: string): string {
98
23
 
99
24
  export async function runHomeFanout(deps: {
100
25
  home: HomeResult; catalogCurrent: boolean; localOnly?: boolean; applicable?: boolean;
101
- readStore: () => LinkStore; readLinkStatus: () => Promise<LinkStatusDto>;
26
+ readStore: () => LinkStore; readLinkStatus: () => Promise<LinkStatusPayload>;
102
27
  runChild: (link: LinkRecord, deadline: number) => Promise<Omit<ChildResult, "linkId" | "alias">>;
103
28
  now?: () => number; deadlineMs?: number; concurrency?: number; terminationGraceMs?: number;
104
29
  }): Promise<FanoutDocument> {
@@ -115,7 +40,7 @@ export async function runHomeFanout(deps: {
115
40
  result.children = store.links.map(link => classify(link, "skipped", link.direction === "client-initiated" ? "client-initiated-link" : skipReason));
116
41
  return result;
117
42
  }
118
- let status: LinkStatusDto;
43
+ let status: LinkStatusPayload;
119
44
  try { status = await deps.readLinkStatus(); }
120
45
  catch (error) {
121
46
  const reason = error instanceof LinkStatusError ? error.reason : "home-link-status-unavailable";
@@ -141,7 +66,9 @@ export async function runHomeFanout(deps: {
141
66
  timer = setTimeout(() => resolve({ state: "timed-out", reason: "termination-unconfirmed", exit: null }), budget + (deps.terminationGraceMs ?? 3000));
142
67
  }),
143
68
  ]);
144
- result.children[index] = { linkId: link.id, alias: link.alias, ...child, ...(child.state === "skipped" ? { hint: childSkipHint(child.reason, link.alias) } : {}) };
69
+ // Build the row from the schema's own fields, so an extra key on a runner's result never reaches ocx.sync.fanout/1.
70
+ const hint = child.state === "skipped" ? childSkipHint(child.reason, link.alias) : child.hint;
71
+ result.children[index] = { linkId: link.id, alias: link.alias, state: child.state, reason: child.reason, exit: child.exit, ...(hint === undefined ? {} : { hint }) };
145
72
  } catch { result.children[index] = classify(link, "failed", "internal-error"); }
146
73
  finally { if (timer !== undefined) clearTimeout(timer); }
147
74
  }
@@ -17,12 +17,22 @@ import { isLinkPort } from "../link/ports";
17
17
  import { probeLinkRelayPreflight, type BoundLinkRelayTarget, type LinkRelayPreflightResult } from "./link-relay-transport";
18
18
  import type { ClientLinkSupervisorStatus } from "./link-tunnel";
19
19
 
20
- export type LinkReadinessReason =
21
- | "tunnel_idle" | "tunnel_connecting" | "tunnel_failed" | "tunnel_unavailable" | "sidecar_invalid"
22
- | "home_unreachable" | "home_unauthorized" | "link_auth_failed" | "link_credential_unavailable"
23
- | "link_unverified"
24
- /** The Child's durable connection no longer matches the one this runtime started with. */
25
- | "client_state_changed";
20
+ /**
21
+ * Every reason word /readyz may report. `client_state_changed`: the Child's durable connection no
22
+ * longer matches the one this runtime started with. A reader of /readyz (`ocx connect status`)
23
+ * accepts only these words, so nothing else a listener sends is echoed to a terminal.
24
+ */
25
+ export const LINK_READINESS_REASONS = [
26
+ "tunnel_idle", "tunnel_connecting", "tunnel_failed", "tunnel_unavailable", "sidecar_invalid",
27
+ "home_unreachable", "home_unauthorized", "link_auth_failed", "link_credential_unavailable",
28
+ "link_unverified", "client_state_changed",
29
+ ] as const;
30
+
31
+ export type LinkReadinessReason = typeof LINK_READINESS_REASONS[number];
32
+
33
+ export function isLinkReadinessReason(value: unknown): value is LinkReadinessReason {
34
+ return typeof value === "string" && (LINK_READINESS_REASONS as readonly string[]).includes(value);
35
+ }
26
36
 
27
37
  export type LinkReadiness = { ready: true } | { ready: false; reason: LinkReadinessReason };
28
38
 
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Whether this Remote Link Child's tunnel can carry a request right now, for `ocx connect status`.
3
+ *
4
+ * The durable connection record says only that this machine was linked. A Home-initiated tunnel
5
+ * drops whenever the Child sleeps, and `Connection: connected` kept reading healthy while every
6
+ * relayed request failed with 503 home_unreachable (#8470). The running Child already computes the
7
+ * verdict for its own /readyz (`src/client/link-readiness.ts`, served by the machine listener), so
8
+ * this asks it instead of probing the tunnel a second time. The answer is a fixed word: nothing a
9
+ * listener sends beyond LINK_READINESS_REASONS reaches the terminal.
10
+ */
11
+ import { LINK_RELAY_AUTH_TIMEOUT_MS } from "../link/relay-auth";
12
+ import { directLocalHttpFetch } from "../server/direct-local-http";
13
+ import { findLiveProxy, probeHostname, validateReadyzBody, type LiveProxy } from "../server/proxy-liveness";
14
+ import { isLinkReadinessReason, type LinkReadinessReason } from "./link-readiness";
15
+
16
+ export type LinkTunnelStatus =
17
+ | { state: "up" }
18
+ | { state: "down"; reason: LinkReadinessReason }
19
+ | { state: "unknown"; reason: "runtime_not_running" | "runtime_unreadable" | "link_unverified" };
20
+
21
+ export interface LinkTunnelStatusDeps {
22
+ findLive?: () => Promise<LiveProxy | null>;
23
+ fetchImpl?: typeof fetch;
24
+ /** Resolves after `ms`; the wait for a relay preflight the runtime has not finished yet. */
25
+ delay?: (ms: number) => Promise<void>;
26
+ now?: () => number;
27
+ }
28
+
29
+ /**
30
+ * /readyz answers `link_unverified` when its preflight is still running after its 500 ms wait. That
31
+ * preflight ends within LINK_RELAY_AUTH_TIMEOUT_MS of this read's start, no earlier than 500 ms in,
32
+ * and its verdict is reused for LINK_READINESS_TTL_MS (5 s). One more read timed from the FIRST
33
+ * read's start lands after the preflight can finish and inside the cached verdict: anywhere in
34
+ * [start + 5000, start + 5500] works, so this aims at the middle. Timing it from the first read's
35
+ * return instead could miss the cache and start a second Home probe (#8496 review).
36
+ */
37
+ const SECOND_READ_AFTER_START_MS = LINK_RELAY_AUTH_TIMEOUT_MS + 250;
38
+ const READ_TIMEOUT_MS = 2_000;
39
+
40
+ export async function probeLinkTunnelStatus(deps: LinkTunnelStatusDeps = {}): Promise<LinkTunnelStatus> {
41
+ let live: LiveProxy | null;
42
+ try { live = await (deps.findLive ?? findLiveProxy)(); } catch { live = null; }
43
+ // Only the Child's machine listener reports a link verdict; anything else on the port cannot.
44
+ if (!live || live.role !== "client") return { state: "unknown", reason: "runtime_not_running" };
45
+ const target = live;
46
+ const fetchImpl = deps.fetchImpl ?? directLocalHttpFetch;
47
+ const read = async (): Promise<LinkTunnelStatus> => {
48
+ try {
49
+ const host = target.probeHostname ? probeHostname(target.probeHostname) : probeHostname(target.hostname);
50
+ const response = await fetchImpl(`http://${host}:${target.port}/readyz`, {
51
+ headers: { Accept: "application/json" },
52
+ signal: AbortSignal.timeout(READ_TIMEOUT_MS),
53
+ });
54
+ const body: unknown = await response.json().catch(() => null);
55
+ const parsed = validateReadyzBody(body, target.port, target.pid ? { expectedPid: target.pid } : {});
56
+ const link = parsed ? (body as { link?: unknown }).link : undefined;
57
+ if (!parsed || !link || typeof link !== "object") return { state: "unknown", reason: "runtime_unreadable" };
58
+ const { state, reason } = link as { state?: unknown; reason?: unknown };
59
+ if (state === "available" && parsed.status === "ready" && response.status === 200) return { state: "up" };
60
+ if (state === "unavailable" && response.status === 503 && isLinkReadinessReason(reason)) return { state: "down", reason };
61
+ return { state: "unknown", reason: "runtime_unreadable" };
62
+ } catch {
63
+ return { state: "unknown", reason: "runtime_unreadable" };
64
+ }
65
+ };
66
+ const now = deps.now ?? Date.now;
67
+ const startedAt = now();
68
+ const first = await read();
69
+ if (first.state !== "down" || first.reason !== "link_unverified") return first;
70
+ const wait = Math.max(0, startedAt + SECOND_READ_AFTER_START_MS - now());
71
+ await (deps.delay ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms))))(wait);
72
+ const second = await read();
73
+ return second.state === "down" && second.reason === "link_unverified"
74
+ ? { state: "unknown", reason: "link_unverified" }
75
+ : second;
76
+ }
@@ -530,6 +530,19 @@ export function commandCodeConfigPath(env: OpencodeLaunchEnv = process.env, home
530
530
  return join(commandCodeHomeDir(env, home, platform), "providers.json");
531
531
  }
532
532
 
533
+ /**
534
+ * Command Code's credential store, next to the provider file.
535
+ *
536
+ * Only the DESKTOP app reads this before it will show a workspace; the published
537
+ * CLI is content with `apiKey: false` in `providers.json`. It is the vendor's file,
538
+ * shared with real logins and other providers' tokens, so this integration NEVER
539
+ * writes it: the desktop user signs in themselves. Exported so callers and tests
540
+ * can name the path they must leave alone.
541
+ */
542
+ export function commandCodeAuthPath(env: OpencodeLaunchEnv = process.env, home: string = homedir(), platform: NodeJS.Platform = process.platform): string {
543
+ return join(commandCodeHomeDir(env, home, platform), "auth.json");
544
+ }
545
+
533
546
  /**
534
547
  * The provider store a current ZCode reads, which is NOT the file above.
535
548
  *
@@ -1623,7 +1636,7 @@ export const EXPORT_CLIENTS: Record<ExportClientId, ExportClientSpec> = {
1623
1636
  // No env var exists behind this integration: buildCommandCodeClientConfig
1624
1637
  // writes `apiKey: false`, the documented keyless form for a loopback endpoint.
1625
1638
  apiKeyEnv: "",
1626
- exportHint: "The provider is written with `apiKey: false` — Command Code treats a keyless loopback endpoint as already authenticated. No key is stored or referenced.",
1639
+ exportHint: "The provider is written with `apiKey: false`, the keyless form the CLI accepts. The desktop app needs its own Command Code sign-in; opencodex never writes `~/.commandcode/auth.json`.",
1627
1640
  build: buildCommandCodeClientConfig,
1628
1641
  format: "json",
1629
1642
  summarize: summarizeCommandCode,
@@ -0,0 +1,41 @@
1
+ import type { OcxConfig } from "../types";
2
+ import { isCodexAccountPaused } from "./account-pause";
3
+ import { isCodexAccountGenerationLive } from "./account-store";
4
+ import { MAIN_CODEX_ACCOUNT_ID } from "./account-id";
5
+ import { PERMANENT_PAUSE_REASONS, type ResumeHealthRefusal } from "../oauth/account-resume-health";
6
+ import type { PoolQuotaResult } from "./auth-api/pool-quota-probe";
7
+
8
+ export type CodexResumeHealthVerdict = { ok: true; pauseRevision: string | undefined } | { ok: false; reason: ResumeHealthRefusal };
9
+
10
+ /** An explicit refresh probe of one pool account: forced, operator-initiated, never a cached read. */
11
+ export type CodexHealthProbe = (accountId: string, plan: string | undefined) => Promise<PoolQuotaResult>;
12
+
13
+ const defaultProbe: CodexHealthProbe = async (accountId, plan) => {
14
+ const { fetchPoolAccountQuota } = await import("./auth-api/pool-quota-probe");
15
+ return await fetchPoolAccountQuota(accountId, true, plan, undefined, false, undefined, undefined, true);
16
+ };
17
+
18
+ /**
19
+ * Health gate for `ocx account resume openai <id> --if-healthy` (#8398): the same rules as the OAuth
20
+ * gate, read through the pool's own WHAM quota probe, which may refresh a pool credential. Healthy
21
+ * means a fresh quota read by a credential generation that is still live; an exhausted window is
22
+ * still healthy, because routing already handles a spent window. Null when the account is not paused.
23
+ */
24
+ export async function checkCodexResumeHealth(config: OcxConfig, accountId: string, probe: CodexHealthProbe = defaultProbe): Promise<CodexResumeHealthVerdict | null> {
25
+ if (!isCodexAccountPaused(config, accountId)) return null;
26
+ const state = config.codexAccountPauseState?.[accountId];
27
+ if (state?.details && PERMANENT_PAUSE_REASONS.has(state.details.reason)) return { ok: false, reason: "pause_not_remote_clearable" };
28
+ if (accountId === MAIN_CODEX_ACCOUNT_ID) return { ok: false, reason: "health_check_unsupported" };
29
+ const pauseRevision = state?.revision;
30
+ const plan = (config.codexAccounts ?? []).find(account => account.id === accountId && !account.isMain)?.plan;
31
+ let result: PoolQuotaResult | undefined;
32
+ try { result = await probe(accountId, plan); } catch { result = undefined; }
33
+ if (!result) return { ok: false, reason: "usage_read_failed" };
34
+ if (result.needsReauth) return { ok: false, reason: "needs_reauth" };
35
+ const generation = result.freshCredentialGeneration;
36
+ if (!result.freshQuota || generation === undefined || !isCodexAccountGenerationLive(accountId, generation)) return { ok: false, reason: "usage_read_failed" };
37
+ if (!isCodexAccountPaused(config, accountId) || config.codexAccountPauseState?.[accountId]?.revision !== pauseRevision) {
38
+ return { ok: false, reason: "account_changed" };
39
+ }
40
+ return { ok: true, pauseRevision };
41
+ }
@@ -1,4 +1,5 @@
1
1
  import { withCodexAccountLogLabel } from "../account-label";
2
+ import { isCodexAccountPaused, setCodexAccountPaused } from "../account-pause";
2
3
  import { getCodexAccountCredential, markCodexAccountValidated, readCodexAccountRecord, saveCodexAccountCredential, CodexCredentialRefreshLockTimeoutError, CodexCredentialRefreshBusyError, CodexCredentialRefreshStaleError } from "../account-store";
3
4
  import { clearAccountQuota, isCodexQuotaExhausted, parseUsageQuota, poolWhamPolicyObservation, setAccountQuotaFromParsed } from "../quota";
4
5
  import type { StoredAccountQuota, WhamUsageResponse } from "../quota";
@@ -404,6 +405,11 @@ export async function handleCodexAuthLoginStart(req: Request, config: OcxConfig,
404
405
  isMain: false,
405
406
  }, accounts);
406
407
  latestConfig.codexAccounts = accounts;
408
+ // A successful login replaced the credential an automatic pause described (#8398);
409
+ // an operator pause carries no details and stays.
410
+ if (isCodexAccountPaused(latestConfig, accountId) && latestConfig.codexAccountPauseState?.[accountId]?.details) {
411
+ setCodexAccountPaused(latestConfig, accountId, false);
412
+ }
407
413
  saveRuntimeConfig(config, latestConfig);
408
414
  } else {
409
415
  const addedAccount = withCodexAccountLogLabel({ id: accountId, email, plan, isMain: false }, accounts);
@@ -28,6 +28,7 @@ import { getRuntimeConfig, saveRuntimeConfig, configuredPoolAccount } from "./ru
28
28
  import { captureConfigTopLevelRollback } from "../../config/rebase-provenance";
29
29
  import { getEffectiveCodexAutoSwitchThreshold, isCodexAccountAutoSwitchThresholdKey, parseCodexAutoSwitchThreshold, setCodexAccountAutoSwitchThresholdOverride } from "../account-auto-switch";
30
30
  import { withCodexAccountPauseGroup } from "./account-pause-group";
31
+ import { PERMANENT_PAUSE_REASONS } from "../../oauth/account-resume-health";
31
32
 
32
33
  export async function handleCodexAuthAPI(
33
34
  req: Request,
@@ -99,20 +100,52 @@ export async function handleCodexAuthAPI(
99
100
  }
100
101
 
101
102
  if (url.pathname === "/api/codex-auth/accounts/pause" && req.method === "PUT") {
102
- const body = await req.json().catch(() => ({})) as { id?: unknown; paused?: unknown };
103
+ const body = await req.json().catch(() => ({})) as { id?: unknown; paused?: unknown; ifHealthy?: unknown };
103
104
  const id = typeof body.id === "string" ? body.id.trim() : "";
104
105
  if (id !== MAIN_CODEX_ACCOUNT_ID && !isValidCodexAccountId(id)) {
105
106
  return jsonResponse({ error: "Invalid account id format" }, 400);
106
107
  }
107
108
  if (typeof body.paused !== "boolean") return jsonResponse({ error: "paused must be a boolean" }, 400);
109
+ if (body.ifHealthy !== undefined && typeof body.ifHealthy !== "boolean") return jsonResponse({ error: "ifHealthy must be a boolean" }, 400);
110
+ if (body.ifHealthy === true && body.paused !== false) return jsonResponse({ error: "ifHealthy applies only to a resume (paused: false)" }, 400);
108
111
 
109
- const runtimeConfig = getRuntimeConfig(config);
112
+ let runtimeConfig = getRuntimeConfig(config);
110
113
  const exists = id === MAIN_CODEX_ACCOUNT_ID
111
114
  || (runtimeConfig.codexAccounts ?? []).some(account => isSelectableCodexPoolAccount(account) && account.id === id);
112
115
  if (!exists) return jsonResponse({ error: "Account not found" }, 404);
116
+ let healthPauseRevision: string | undefined;
117
+ if (body.ifHealthy === true) {
118
+ // Explicit resume gated on a forced pool quota read (#8398); the read can take a while, so
119
+ // the pause is committed against the configuration as it is after the read.
120
+ const { checkCodexResumeHealth } = await import("../account-resume-health");
121
+ const verdict = await checkCodexResumeHealth(runtimeConfig, id);
122
+ runtimeConfig = getRuntimeConfig(config);
123
+ const refusal = verdict && !verdict.ok ? verdict.reason
124
+ : verdict && (!isCodexAccountPaused(runtimeConfig, id) || runtimeConfig.codexAccountPauseState?.[id]?.revision !== verdict.pauseRevision)
125
+ ? "account_changed" : undefined;
126
+ if (refusal) return jsonResponse({ error: `account was not resumed: ${refusal}`, code: "resume_refused", reason: refusal, id }, 409);
127
+ // Not paused when checked: a no-op that never enters the pause group.
128
+ if (!verdict) return jsonResponse({ ok: true, id, paused: false, unchanged: true, activeCodexAccountId: getEffectiveActiveCodexAccountId(runtimeConfig) ?? null });
129
+ if (verdict.ok) healthPauseRevision = verdict.pauseRevision;
130
+ }
113
131
 
114
132
  const paused = body.paused;
115
133
  return withCodexAccountPauseGroup(runtimeConfig, id, accountIds => {
134
+ if (body.ifHealthy === true) {
135
+ // Recheck right before the write: the pause-group claim above can wait, and an operator
136
+ // re-pause meanwhile must not be overwritten by this health-gated resume.
137
+ runtimeConfig = getRuntimeConfig(config);
138
+ if (!isCodexAccountPaused(runtimeConfig, id) || runtimeConfig.codexAccountPauseState?.[id]?.revision !== healthPauseRevision) {
139
+ return jsonResponse({ error: "account was not resumed: account_changed", code: "resume_refused", reason: "account_changed", id }, 409);
140
+ }
141
+ }
142
+ // A linked account resumes with the named one, so a permanent reason on any of them refuses (#8398).
143
+ if (body.ifHealthy === true && accountIds.some(accountId => {
144
+ const reason = runtimeConfig.codexAccountPauseState?.[accountId]?.details?.reason;
145
+ return reason !== undefined && PERMANENT_PAUSE_REASONS.has(reason);
146
+ })) {
147
+ return jsonResponse({ error: "account was not resumed: pause_not_remote_clearable", code: "resume_refused", reason: "pause_not_remote_clearable", id }, 409);
148
+ }
116
149
  // Publish every exclusion before reconciling: a duplicate must never become the fallback.
117
150
  for (const accountId of accountIds) setCodexAccountPaused(runtimeConfig, accountId, paused);
118
151
  if (paused) {
@@ -414,6 +414,7 @@ export function captureProviderGather(
414
414
  ...(resolved.spec ? { spec: resolved.spec } : {}),
415
415
  maxResponseBytes: resolved.maxResponseBytes,
416
416
  maxModels: resolved.maxModels,
417
+ ...(resolved.skipInvalidRows ? { skipInvalidRows: true as const } : {}),
417
418
  });
418
419
  const trustedOpenAiApi = captureTrustedOpenAiApiPolicy(name, registryTransportMatch);
419
420
  const policy = detachedFrozen({
@@ -431,6 +432,7 @@ export function captureProviderGather(
431
432
  preferFirst: capturedField(discovery.spec, "preferFirst"),
432
433
  maxResponseBytes: discovery.maxResponseBytes,
433
434
  maxModels: discovery.maxModels,
435
+ skipInvalidRows: discovery.skipInvalidRows === true,
434
436
  trustedOpenAiApi,
435
437
  });
436
438
  const effectiveAlias = effectiveProviderAliasDecision(name, configured, config);