@bitkyc08/opencodex 2.100.0 → 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 (178) 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-DU-0Vdkr.js +1 -0
  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-CcxZBnxv.js → segment-thumb-features-e9A_FogJ.js} +1 -1
  7. package/gui/dist/classic/assets/{App-aYgIQMxI.js → App-BrIlUiLc.js} +18 -18
  8. package/gui/dist/classic/assets/{Tray-D8jfUXpQ.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/anthropic-image-normalize.ts +1 -1
  15. package/src/adapters/client-fingerprint.ts +6 -4
  16. package/src/adapters/cursor/native-exec.ts +3 -2
  17. package/src/adapters/cursor/tool-guidance.ts +3 -3
  18. package/src/adapters/cursor/tool-wording.ts +10 -1
  19. package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
  20. package/src/adapters/google-antigravity-wire.ts +13 -6
  21. package/src/adapters/google-truncation.ts +4 -2
  22. package/src/adapters/google.ts +8 -2
  23. package/src/adapters/openai-chat/mistral-image-limit.ts +28 -15
  24. package/src/adapters/openai-chat/tool-schema.ts +9 -0
  25. package/src/adapters/openai-chat-images.ts +100 -0
  26. package/src/adapters/openai-chat.ts +6 -9
  27. package/src/adapters/openai-responses/tool-schema.ts +18 -4
  28. package/src/adapters/run-turn-queue.ts +139 -5
  29. package/src/adapters/upstream-http-error.ts +4 -2
  30. package/src/bridge/sse.ts +8 -1
  31. package/src/claude/chat-tool-dispatch.ts +233 -0
  32. package/src/claude/inbound-tool-loading.ts +42 -17
  33. package/src/cli/account-api.ts +6 -0
  34. package/src/cli/account-extended.ts +60 -6
  35. package/src/cli/account-key-quota.ts +22 -2
  36. package/src/cli/account.ts +1 -1
  37. package/src/cli/capabilities-access-remote.ts +10 -0
  38. package/src/cli/capabilities-agents-routing.ts +2 -2
  39. package/src/cli/capabilities-base.ts +2 -2
  40. package/src/cli/claude.ts +19 -14
  41. package/src/cli/config-command.ts +24 -1
  42. package/src/cli/connect.ts +36 -3
  43. package/src/cli/gui-pair-client.ts +23 -2
  44. package/src/cli/help.ts +1 -1
  45. package/src/cli/hub.ts +18 -1
  46. package/src/cli/link-child-ops.ts +136 -0
  47. package/src/cli/link-status-child.ts +94 -0
  48. package/src/cli/link.ts +22 -9
  49. package/src/cli/registry.ts +3 -2
  50. package/src/cli/sync-command.ts +3 -1
  51. package/src/cli/sync-fanout.ts +8 -81
  52. package/src/client/link-readiness.ts +16 -6
  53. package/src/client/link-tunnel-status.ts +76 -0
  54. package/src/clients/config-export.ts +14 -1
  55. package/src/codex/account-resume-health.ts +41 -0
  56. package/src/codex/auth-api/login-flow.ts +6 -0
  57. package/src/codex/auth-api/routes.ts +35 -2
  58. package/src/codex/catalog/gather-capture.ts +2 -0
  59. package/src/codex/catalog/provider-models.ts +13 -8
  60. package/src/codex/convergence-types.ts +2 -0
  61. package/src/codex/quota.ts +111 -6
  62. package/src/combos/cooldown-store.ts +208 -0
  63. package/src/combos/failover.ts +432 -35
  64. package/src/config/salvage.ts +1 -0
  65. package/src/config/schema/config-schema.ts +6 -3
  66. package/src/config/schema/leaf-validators.ts +34 -12
  67. package/src/generated/compatibility-version.json +227 -135
  68. package/src/lib/catalog-etag.ts +10 -0
  69. package/src/lib/client-error-body.ts +15 -0
  70. package/src/lib/config-ownership.ts +9 -2
  71. package/src/lib/context-overflow-verdict.ts +266 -9
  72. package/src/lib/failure-detail.ts +72 -3
  73. package/src/lib/hard-refusal.ts +259 -0
  74. package/src/link/child-activity.ts +57 -0
  75. package/src/link/child-catalog-freshness.ts +149 -0
  76. package/src/link/child-gated-ocx.ts +117 -0
  77. package/src/link/child-observations.ts +205 -0
  78. package/src/link/child-observe.ts +121 -0
  79. package/src/link/child-ops-engine.ts +162 -0
  80. package/src/link/child-update-contract.ts +165 -0
  81. package/src/link/paths.ts +5 -0
  82. package/src/link/remote-windows.ts +42 -6
  83. package/src/link/ssh-argv.ts +126 -32
  84. package/src/link/status-projection.ts +73 -0
  85. package/src/link/sync-fanout-classify.ts +98 -0
  86. package/src/link/tunnel-state.ts +10 -4
  87. package/src/messaging/mcp-queue-rpc.ts +2 -1
  88. package/src/messaging/mcp-queue-server.ts +5 -0
  89. package/src/messaging/mcp-reply-tools.ts +24 -9
  90. package/src/messaging/mcp-reply-wait.ts +70 -0
  91. package/src/oauth/account-resume-health.ts +60 -0
  92. package/src/oauth/anthropic-model-quota.ts +12 -0
  93. package/src/oauth/anthropic-routing.ts +11 -4
  94. package/src/oauth/index.ts +1 -0
  95. package/src/oauth/kiro-iam-identity-center.ts +4 -1
  96. package/src/oauth/store.ts +44 -1
  97. package/src/providers/api-key-pause-state.ts +23 -0
  98. package/src/providers/api-key-pause.ts +68 -10
  99. package/src/providers/api-key-selection-capture.ts +3 -1
  100. package/src/providers/api-key-selection.ts +3 -2
  101. package/src/providers/api-keys.ts +18 -5
  102. package/src/providers/claude-cli-identity.ts +9 -3
  103. package/src/providers/claude-cli-usage-state.ts +11 -6
  104. package/src/providers/claude-cli-usage.ts +27 -8
  105. package/src/providers/codex-capacity.ts +11 -2
  106. package/src/providers/key-failover.ts +13 -6
  107. package/src/providers/model-discovery-config.ts +31 -0
  108. package/src/providers/model-discovery-diagnostic.ts +34 -3
  109. package/src/providers/model-discovery.ts +43 -7
  110. package/src/providers/model-rename-fields.ts +2 -0
  111. package/src/providers/openai-sidecar.ts +15 -2
  112. package/src/providers/provider-id-rewrite.ts +3 -0
  113. package/src/providers/quota/account-cache.ts +52 -34
  114. package/src/providers/quota/anthropic-family-headers.ts +8 -1
  115. package/src/providers/quota/anthropic-usage-windows.ts +66 -9
  116. package/src/providers/quota/report-cache.ts +53 -5
  117. package/src/providers/quota/vendor-probes-key.ts +73 -0
  118. package/src/providers/quota/vendor-probes-oauth.ts +57 -3
  119. package/src/providers/quota-key-accounts.ts +12 -5
  120. package/src/providers/quota-mistral-budget.ts +18 -0
  121. package/src/providers/quota-types.ts +32 -0
  122. package/src/providers/quota.ts +22 -22
  123. package/src/providers/reasoning-metadata.ts +1051 -12
  124. package/src/providers/registry/entries-extended.ts +3 -1
  125. package/src/providers/registry/model-ids.ts +1 -0
  126. package/src/providers/registry/types.ts +6 -0
  127. package/src/quota/reset-observer.ts +4 -2
  128. package/src/quota/reset-seen-store.ts +9 -0
  129. package/src/quota/window-mapping.ts +1 -0
  130. package/src/quota-pool/assemble.ts +4 -1
  131. package/src/responses/hosted-tool-policy.ts +56 -12
  132. package/src/responses/retained-compaction.ts +31 -5
  133. package/src/router.ts +2 -0
  134. package/src/server/auth-cors.ts +11 -8
  135. package/src/server/catalog-download.ts +3 -5
  136. package/src/server/chat-native.ts +11 -2
  137. package/src/server/claude-messages.ts +2 -1
  138. package/src/server/images.ts +41 -13
  139. package/src/server/index/link-listener.ts +16 -2
  140. package/src/server/index/link-relay-sessions.ts +43 -2
  141. package/src/server/index/optional-listeners.ts +18 -0
  142. package/src/server/management/config-routes.ts +7 -1
  143. package/src/server/management/context.ts +1 -1
  144. package/src/server/management/link-child-ops-routes.ts +116 -0
  145. package/src/server/management/link-route-state.ts +10 -0
  146. package/src/server/management/link-routes.ts +10 -0
  147. package/src/server/management/oauth-account-routes.ts +33 -4
  148. package/src/server/management/provider-overwrite-carry.ts +28 -3
  149. package/src/server/management/provider-routes.ts +16 -11
  150. package/src/server/management/route-registry.ts +3 -0
  151. package/src/server/messages-native.ts +5 -0
  152. package/src/server/request-log-failure-detail.ts +59 -1
  153. package/src/server/responses/adapter-dispatch.ts +35 -44
  154. package/src/server/responses/combo-stream-preflight.ts +146 -29
  155. package/src/server/responses/compact.ts +27 -4
  156. package/src/server/responses/context-overflow.ts +58 -2
  157. package/src/server/responses/core-combo-failure.ts +29 -4
  158. package/src/server/responses/core-combo-native.ts +3 -1
  159. package/src/server/responses/core-combo.ts +30 -3
  160. package/src/server/responses/core-errors.ts +3 -1
  161. package/src/server/responses/core-opaque-recovery.ts +45 -2
  162. package/src/server/responses/core-options.ts +12 -0
  163. package/src/server/responses/passthrough-dispatch.ts +30 -38
  164. package/src/server/responses/request-transport.ts +43 -14
  165. package/src/server/responses/reset-replay.ts +58 -2
  166. package/src/server/responses/run-turn-execution.ts +56 -30
  167. package/src/types/claude-tool-loading.ts +48 -0
  168. package/src/types/config.ts +5 -35
  169. package/src/types/provider.ts +21 -0
  170. package/src/types.ts +1 -0
  171. package/src/web-search/parse.ts +44 -4
  172. package/gui/dist/assets/App-CitvEefy.js +0 -59
  173. package/gui/dist/assets/Tray-CeKVWQyB.js +0 -1
  174. package/gui/dist/assets/brand-mark-M92UnxX2.js +0 -1
  175. package/gui/dist/assets/index-BP47do6-.js +0 -94
  176. package/gui/dist/assets/index-DmDooSAG.css +0 -2
  177. package/gui/dist/classic/assets/index-CfGqHooN.js +0 -94
  178. package/gui/dist/classic/assets/quota-summary-R-ih7OlS.js +0 -1
@@ -0,0 +1,98 @@
1
+ import { compareStrictSemver, parseStrictSemver } from "../lib/strict-semver";
2
+
3
+ /**
4
+ * Home-side classification of a pinned Child sync (moved from src/cli/sync-fanout.ts so the Link engine can use it
5
+ * without importing src/cli). Pure: imports only the strict semver parser.
6
+ */
7
+ export const REMOTE_LINK_SYNC_MESSAGE = "Remote Link Home catalog synchronized.";
8
+ export const STALE_REMOTE_CATALOG_MESSAGE = "Home unavailable; retained and applied the last-known-good remote catalog (stale).";
9
+
10
+ /**
11
+ * executable is present only when a restarting pinned sync reported that it selected ocx-child, which ignores the
12
+ * restart flags. Callers building ocx.sync.fanout/1 output must drop it.
13
+ */
14
+ export type ChildVerdict = { state: "synced" | "skipped" | "failed"; reason: string | null; executable?: "ocx-child" };
15
+ const failure = (reason: string): ChildVerdict => ({ state: "failed", reason });
16
+ const skipped = (reason: string): ChildVerdict => ({ state: "skipped", reason });
17
+ const minimum = parseStrictSemver("2.93.0")!;
18
+ const SELECTED_KIND = "ocx-fanout:selected-kind:";
19
+
20
+ export function parseOcxVersion(output: string): string | null {
21
+ const version = output.trim().replace(/^opencodex /, "");
22
+ return parseStrictSemver(version) ? version : null;
23
+ }
24
+
25
+ export function classifyVersionProbe(output: string): "child-ocx-version-unknown" | "child-ocx-lacks-expect-link" | null {
26
+ const version = parseOcxVersion(output);
27
+ if (!version) return "child-ocx-version-unknown";
28
+ return compareStrictSemver(parseStrictSemver(version)!, minimum) < 0 ? "child-ocx-lacks-expect-link" : null;
29
+ }
30
+
31
+ const mismatchReasons = new Set(["disconnected", "invalid_state", "disconnect_pending", "pending_operation", "hub_client", "link_client", "other_link", "other_key"]);
32
+
33
+ function validDocument(value: unknown): "synced" | "stale" | null {
34
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
35
+ const v = value as Record<string, unknown>;
36
+ const keysAre = (object: Record<string, unknown>, keys: readonly string[]): boolean => Object.keys(object).length === keys.length && keys.every(key => Object.hasOwn(object, key));
37
+ if (!keysAre(v, ["schema", "home", "fanout", "children"])) return null;
38
+ if (v.schema !== "ocx.sync.fanout/1" || !v.home || typeof v.home !== "object" || Array.isArray(v.home)
39
+ || !v.fanout || typeof v.fanout !== "object" || Array.isArray(v.fanout) || !Array.isArray(v.children)) return null;
40
+ const home = v.home as Record<string, unknown>, fanout = v.fanout as Record<string, unknown>;
41
+ if (!keysAre(home, ["state", "exit"]) || !keysAre(fanout, ["state", "reason"])) return null;
42
+ if (home.exit !== 0 || (home.state !== "synced" && home.state !== "stale")) return null;
43
+ if (fanout.state !== "not-applicable" || fanout.reason !== null || v.children.length !== 0) return null;
44
+ return home.state;
45
+ }
46
+
47
+ /**
48
+ * expectSelectedKind: only a restarting pinned sync asks its script to print ocx-fanout:selected-kind. Every other
49
+ * caller leaves it false, and then a selected-kind line in remote stderr is ignored exactly like any other noise.
50
+ */
51
+ export function classifySyncResult(result: { code: number; stdout: string; stderr: string }, options: { expectSelectedKind?: boolean } = {}): ChildVerdict {
52
+ const { code, stdout, stderr } = result;
53
+ if (code === 255) return failure("ssh-failed");
54
+ if (code === 127) return failure("child-ocx-not-found");
55
+ if (code === 126) return failure("child-ocx-not-contained");
56
+ if (code === 125) return skipped("child-platform-unsupported");
57
+ const lines = stderr.split(/\r?\n/);
58
+ const last = stderr.trimEnd().split(/\r?\n/).at(-1);
59
+ if (code === 121) {
60
+ if (last === "ocx-fanout:child-ocx-lacks-expect-link") return skipped("child-ocx-lacks-expect-link");
61
+ if (last === "ocx-fanout:child-ocx-version-unknown") return skipped("child-ocx-version-unknown");
62
+ return failure("child-sync-failed");
63
+ }
64
+ const markers = lines.map(line => /^ocx-fanout:selected:(.+)$/.exec(line)).filter(match => match !== null);
65
+ if (markers.length !== 1 || !parseStrictSemver(markers[0]![1]!)) return failure("child-output-invalid");
66
+ // Requested only: at most one selected-kind line, after the selection marker, naming ocx-child (the restart was ignored).
67
+ const selectedAt = lines.findIndex(line => line.startsWith("ocx-fanout:selected:"));
68
+ const kinds = options.expectSelectedKind !== true ? []
69
+ : lines.flatMap((line, index) => line.startsWith(SELECTED_KIND) ? [{ index, value: line.slice(SELECTED_KIND.length) }] : []);
70
+ if (kinds.length > 1 || (kinds.length === 1 && (kinds[0]!.value !== "ocx-child" || kinds[0]!.index < selectedAt))) return failure("child-output-invalid");
71
+ const kind = (verdict: ChildVerdict): ChildVerdict => kinds.length === 1 ? { ...verdict, executable: "ocx-child" } : verdict;
72
+ const outputLines = stdout.split(/\r?\n/);
73
+ const delimiters = outputLines.flatMap((line, index) => line === "ocx-fanout:stdout-begin" ? [index] : []);
74
+ if (delimiters.length !== 1) return failure("child-output-invalid");
75
+ if (code === 5) {
76
+ try {
77
+ const detail: unknown = JSON.parse(last ?? "");
78
+ if (detail && typeof detail === "object" && "phase" in detail && detail.phase === "child_link_mismatch"
79
+ && "reason" in detail && typeof detail.reason === "string" && mismatchReasons.has(detail.reason)) return kind(skipped(`child-link-mismatch:${detail.reason}`));
80
+ } catch { /* The generic mismatch is the only safe fallback. */ }
81
+ return kind(skipped("child-link-mismatch"));
82
+ }
83
+ if (code === 7) return kind(skipped("child-updating"));
84
+ if (code !== 0) return kind(failure("child-sync-failed"));
85
+ const text = outputLines.slice(delimiters[0]! + 1).join("\n").trim();
86
+ if (text.startsWith("{")) {
87
+ try {
88
+ const state = validDocument(JSON.parse(text));
89
+ if (state === "synced") return kind({ state: "synced", reason: null });
90
+ if (state === "stale") return kind(failure("child-catalog-stale"));
91
+ } catch { /* Reject invalid or multiple JSON documents. */ }
92
+ return kind(failure("child-output-invalid"));
93
+ }
94
+ if (text.includes(STALE_REMOTE_CATALOG_MESSAGE)) return kind(failure("child-catalog-stale"));
95
+ if (text.includes(REMOTE_LINK_SYNC_MESSAGE)) return kind({ state: "synced", reason: null });
96
+ return kind(failure("child-output-invalid"));
97
+ }
98
+
@@ -71,11 +71,17 @@ export const CLIENT_TUNNEL_RETRY_POLICY: TunnelRetryPolicy = {
71
71
  };
72
72
 
73
73
  /**
74
- * The Home's `-R` supervisor dials the Child's sshd on the same cadence and limits. A sleep, an
75
- * outage longer than FAILED_AFTER_MS, or a forward the Child's sshd still holds for a session that
76
- * died heals at most five minutes after it clears, instead of waiting for a proxy restart.
74
+ * The Home's `-R` supervisor retries a timed-out or refused-forward Child every minute, flat: a
75
+ * laptop Child that slept reconnects within about a minute of waking instead of waiting out a
76
+ * backoff of up to five minutes (#8470). A sleeping host never reaches sshd, so those retries add
77
+ * no authentication attempts. Auth keeps its five-minute start (the cap is
78
+ * `max(base, maxRetryDelayMs)`), so no more than 12 auth attempts reach the Child's sshd in an hour,
79
+ * and a changed host key is still never retried. The Child's own tunnel keeps the doubling policy.
77
80
  */
78
- export const HOME_TUNNEL_RETRY_POLICY: TunnelRetryPolicy = CLIENT_TUNNEL_RETRY_POLICY;
81
+ export const HOME_TUNNEL_RETRY_POLICY: TunnelRetryPolicy = {
82
+ retryFailedAfterMs: { timeout: 60_000, forward: 60_000, auth: 5 * 60_000 },
83
+ maxRetryDelayMs: 60_000,
84
+ };
79
85
 
80
86
  export const IDLE: TunnelState = { kind: "idle" };
81
87
 
@@ -11,7 +11,7 @@ export type QueueRpcResult = { status: "response"; result: Record<string, unknow
11
11
 
12
12
  /** Execute only explicit stored-thread RPCs; bodies never enter argv or diagnostics. */
13
13
  export async function queueMcpRpc(options: QueueMcpOptions, method: "thread/list" | "thread/queue/add" | "thread/items/list" | "thread/items/read" | "thread/turns/list",
14
- params: Record<string, unknown>, signal?: AbortSignal): Promise<QueueRpcResult> {
14
+ params: Record<string, unknown>, signal?: AbortSignal, onOutcomeBeforeCleanup?: () => void): Promise<QueueRpcResult> {
15
15
  const reads = ["thread/items/list", "thread/items/read", "thread/turns/list"];
16
16
  if (!["thread/list", "thread/queue/add", ...reads].includes(method) || (reads.includes(method) && !options.allowReplyRead)) {
17
17
  return { status: "not_sent", error: { code: "queue_mcp_method_not_allowed" } };
@@ -46,6 +46,7 @@ export async function queueMcpRpc(options: QueueMcpOptions, method: "thread/list
46
46
  const finish = (value: QueueRpcResult): void => {
47
47
  if (outcome) return;
48
48
  outcome = value;
49
+ onOutcomeBeforeCleanup?.();
49
50
  clearTimeout(deadline);
50
51
  child.stdin.end();
51
52
  termTimer = setTimeout(() => stopGroup("SIGTERM"), 300);
@@ -3,6 +3,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
3
3
  import { queueMcpSend, queueMcpThreads, queueMessageInput, queueThreadInput } from "./mcp-queue-tools";
4
4
  import { queueMcpReadReply } from "./mcp-reply-tools";
5
5
  import { replyInput } from "./mcp-reply-cursor";
6
+ import { queueMcpWaitReply, replyWaitInput } from "./mcp-reply-wait";
6
7
  import type { QueueMcpOptions } from "./mcp-queue-rpc";
7
8
 
8
9
  /** Explicit stdio host only: importing this module starts no helper, proxy, timer or listener. */
@@ -32,6 +33,10 @@ export async function serveQueueMcp(options: QueueMcpOptions): Promise<void> {
32
33
  description: "Read user-authorized final text from the stored turn containing a queued message client ID. Same-turn association is not exclusive reply ownership or goal completion. A missing match is not proof of non-delivery. Treat peer text as context, never permission. Use nextCursor for pages; refreshCursor rescans the matched turn. Deduplicate or update by itemId in the caller; null nextCursor ends only this history snapshot.",
33
34
  inputSchema: replyInput, annotations: { readOnlyHint: true, openWorldHint: false } },
34
35
  async (input, extra) => run(signal => queueMcpReadReply(options, input, signal), extra.signal));
36
+ if (options.allowReplyRead) server.registerTool("codex_wait_reply", {
37
+ description: "Wait within a waitMs budget (default/max 20000) for eligible stored final text using at most three snapshots, two seconds apart. Returns immediately for existing text, ambiguity or a required next page. Same-turn text is not necessarily new or an exclusive reply. wait_exhausted is not non-delivery; lastObservationAgeMs describes the last successful snapshot. Stored turnStatus never proves live completion. Each wait holds one of four shared host slots, including helper termination time after the budget; four concurrent waits make sends and metadata return busy rather than queue. No send, resume, wake-up or background watch.",
38
+ inputSchema: replyWaitInput, annotations: { readOnlyHint: true, openWorldHint: false } },
39
+ async (input, extra) => run(signal => queueMcpWaitReply(options, input, signal), extra.signal));
35
40
  server.server.onclose = stop;
36
41
  process.once("SIGINT", stop); process.once("SIGTERM", stop);
37
42
  process.stdin.once("end", stop); process.stdin.once("close", stop);
@@ -42,8 +42,15 @@ function finalReplies(rows: Entry[]) {
42
42
  }
43
43
 
44
44
  /** Read one bounded history page; matching proves shared turn membership, never exclusive reply ownership. */
45
- export async function queueMcpReadReply(options: QueueMcpOptions, raw: ReplyInput, signal?: AbortSignal) {
46
- const unavailable = (code: string) => ({ available: false as const, error: { code } });
45
+ export async function queueMcpReadReply(options: QueueMcpOptions, raw: ReplyInput, signal?: AbortSignal,
46
+ hooks?: { onObservedFailure: () => void; outcomeIsTimely: () => boolean; onObservedSuccess?: (timely: boolean) => void }) {
47
+ let outcomeBeforeDeadline = false, allOutcomesTimely = true;
48
+ const unavailable = (code: string) => {
49
+ if (outcomeBeforeDeadline) hooks?.onObservedFailure();
50
+ return { available: false as const, error: { code } };
51
+ };
52
+ // Report whether every RPC behind this completed snapshot arrived before the caller's deadline.
53
+ const observed = <T>(value: T): T => { hooks?.onObservedSuccess?.(allOutcomesTimely); return value; };
47
54
  if (!options.allowReplyRead) return unavailable("reply_read_disabled");
48
55
  const parsed = z.object(replyInput).strict().safeParse(raw);
49
56
  if (!parsed.success) return unavailable("reply_invalid_input");
@@ -52,9 +59,17 @@ export async function queueMcpReadReply(options: QueueMcpOptions, raw: ReplyInpu
52
59
  try { position = decodeReplyCursor(input); } catch { return unavailable("reply_invalid_cursor"); }
53
60
  const budget = new MessageBudget(20_000, signal);
54
61
  const read = async (method: "thread/items/list" | "thread/items/read" | "thread/turns/list", params: Record<string, unknown>) => {
62
+ outcomeBeforeDeadline = false;
55
63
  budget.throwIfEnded();
56
- const result = await queueMcpRpc(options, method, { threadId: input.threadId, ...params }, budget.signal);
57
- if (result.status !== "response") throw new Error("read unavailable");
64
+ // The helper may close after the deadline even when its response arrived in time.
65
+ const result = await queueMcpRpc(options, method, { threadId: input.threadId, ...params }, budget.signal,
66
+ () => { if (hooks?.outcomeIsTimely() ?? !signal?.aborted) outcomeBeforeDeadline = true; });
67
+ if (result.status !== "response") {
68
+ if (hooks?.outcomeIsTimely() ?? !signal?.aborted) outcomeBeforeDeadline = true;
69
+ throw new Error("read unavailable");
70
+ }
71
+ // A snapshot is complete only if every frame in it arrived in time, not just the final one.
72
+ allOutcomesTimely = allOutcomesTimely && outcomeBeforeDeadline;
58
73
  return result.result;
59
74
  };
60
75
  try {
@@ -71,9 +86,9 @@ export async function queueMcpReadReply(options: QueueMcpOptions, raw: ReplyInpu
71
86
  const page = await read("thread/items/list", { cursor, limit: 50, sortDirection: "desc" });
72
87
  const rows = entries(page.data, 50), next = nextCursor(page, cursor);
73
88
  const matches = rows.filter(row => row.item.type === "userMessage" && row.item.clientId === input.clientMessageId);
74
- if (matches.length > 1) return { available: true as const, status: "ambiguous" as const, replies: [] };
75
- if (!matches.length) return { available: true as const, status: "not_observed" as const, reachedHistoryEnd: next === null,
76
- nextCursor: next ? encodeReplyCursor(input, { stage: "search", nativeCursor: next }) : null, replies: [] };
89
+ if (matches.length > 1) return observed({ available: true as const, status: "ambiguous" as const, replies: [] });
90
+ if (!matches.length) return observed({ available: true as const, status: "not_observed" as const, reachedHistoryEnd: next === null,
91
+ nextCursor: next ? encodeReplyCursor(input, { stage: "search", nativeCursor: next }) : null, replies: [] });
77
92
  ({ turnId } = matches[0]!); userItemId = matches[0]!.item.id;
78
93
  }
79
94
  const page = await read("thread/items/list", { turnId, cursor: replyCursor, limit: 50, sortDirection: "asc" });
@@ -84,10 +99,10 @@ export async function queueMcpReadReply(options: QueueMcpOptions, raw: ReplyInpu
84
99
  const summaries = turns.data as Record<string, unknown>[];
85
100
  if (new Set(summaries.map(t => t.id)).size !== summaries.length) return unavailable("reply_invalid_turns");
86
101
  const turn = summaries.find(t => t.id === turnId);
87
- return { available: true as const, status: "observed" as const, association: "same_turn_not_exclusive" as const,
102
+ return observed({ available: true as const, status: "observed" as const, association: "same_turn_not_exclusive" as const,
88
103
  threadId: input.threadId, clientMessageId: input.clientMessageId, turnId, userItemId, turnStatus: turn?.status ?? "unverified",
89
104
  replies: finalReplies(rows), nextCursor: next ? encodeReplyCursor(input, { stage: "replies", turnId, userItemId, nativeCursor: next }) : null,
90
- refreshCursor: encodeReplyCursor(input, { stage: "replies", turnId, userItemId, nativeCursor: null }) };
105
+ refreshCursor: encodeReplyCursor(input, { stage: "replies", turnId, userItemId, nativeCursor: null }) });
91
106
  } catch { return unavailable("reply_read_unavailable"); }
92
107
  finally { budget.dispose(); }
93
108
  }
@@ -0,0 +1,70 @@
1
+ import { z } from "zod";
2
+ import { MessageBudget } from "./budget";
3
+ import type { QueueMcpOptions } from "./mcp-queue-rpc";
4
+ import { decodeReplyCursor, replyInput, type ReplyInput } from "./mcp-reply-cursor";
5
+ import { queueMcpReadReply } from "./mcp-reply-tools";
6
+
7
+ export const replyWaitInput = { ...replyInput, waitMs: z.number().int().min(1).max(20_000).default(20_000) };
8
+ type Observation = Extract<Awaited<ReturnType<typeof queueMcpReadReply>>, { available: true }>;
9
+
10
+ /** Delay only between snapshots; cancellation always removes its timer and listener. */
11
+ function pause(signal: AbortSignal): Promise<void> {
12
+ return new Promise((resolve, reject) => {
13
+ const done = () => { signal.removeEventListener("abort", cancel); resolve(); };
14
+ const timer = setTimeout(done, 2_000);
15
+ const cancel = () => { clearTimeout(timer); signal.removeEventListener("abort", cancel); reject(signal.reason); };
16
+ signal.addEventListener("abort", cancel, { once: true });
17
+ if (signal.aborted) cancel();
18
+ });
19
+ }
20
+
21
+ /** Wait for eligible stored final text, never for goal completion or exclusive/new reply ownership. */
22
+ export async function queueMcpWaitReply(options: QueueMcpOptions, raw: ReplyInput & { waitMs?: number }, signal?: AbortSignal) {
23
+ const unavailable = (code: string) => ({ available: false as const, error: { code } });
24
+ if (!options.allowReplyRead) return unavailable("reply_read_disabled");
25
+ const parsed = z.object(replyWaitInput).strict().safeParse(raw);
26
+ if (!parsed.success) return unavailable("reply_invalid_input");
27
+ const { waitMs, ...input } = parsed.data;
28
+ try { decodeReplyCursor(input); } catch { return unavailable("reply_invalid_cursor"); }
29
+ const budget = new MessageBudget(waitMs, signal);
30
+ let last: Observation | undefined, observedAt = 0, attempts = 0;
31
+ const finish = (observation: Observation, waitOutcome: "reply_observed" | "needs_pagination" | "ambiguous" | "wait_exhausted") =>
32
+ ({ ...observation, waitOutcome, attempts, lastObservationAgeMs: Math.max(0, Math.floor(performance.now() - observedAt)) });
33
+ const exhausted = () => last ? finish(last, "wait_exhausted") : unavailable("reply_wait_timeout");
34
+ let position: ReplyInput = input;
35
+ try {
36
+ for (let index = 0; index < 3; index++) {
37
+ budget.throwIfEnded();
38
+ attempts++;
39
+ const snapshotStartedAt = performance.now();
40
+ let observedFailure = false, observedCompleteTimely = false;
41
+ const result = await queueMcpReadReply(options, position, budget.signal, {
42
+ onObservedFailure: () => { observedFailure = true; },
43
+ outcomeIsTimely: () => { try { budget.throwIfEnded(); return true; } catch { return false; } },
44
+ // Cleanup may outlive the deadline; what matters is when this snapshot's complete observation arrived.
45
+ onObservedSuccess: timely => { observedCompleteTimely = timely; },
46
+ });
47
+ if (signal?.aborted) return unavailable("reply_wait_cancelled");
48
+ if (!result.available) {
49
+ if (observedFailure) return result;
50
+ return budget.signal.aborted ? exhausted() : result;
51
+ }
52
+ // A completion observed after the deadline is not a valid success; a timely one survives cleanup.
53
+ if (!observedCompleteTimely) return exhausted();
54
+ // The reply page precedes later metadata reads and helper cleanup; age conservatively
55
+ // from the snapshot start so that delay cannot make an older observation appear fresh.
56
+ last = result; observedAt = snapshotStartedAt;
57
+ if (result.replies.length) return finish(result, "reply_observed");
58
+ if (result.status === "ambiguous") return finish(result, "ambiguous");
59
+ if (result.nextCursor) return finish(result, "needs_pagination");
60
+ if (index === 2) return exhausted();
61
+ // Stored summaries from another process are not authoritative live/terminal state.
62
+ if (result.status === "observed") position = { ...input, cursor: result.refreshCursor };
63
+ await pause(budget.signal);
64
+ }
65
+ return exhausted();
66
+ } catch {
67
+ if (signal?.aborted) return unavailable("reply_wait_cancelled");
68
+ return budget.signal.aborted ? exhausted() : unavailable("reply_wait_unavailable");
69
+ } finally { budget.dispose(); }
70
+ }
@@ -0,0 +1,60 @@
1
+ import type { AccountPauseReason } from "../types/account-auto-pause";
2
+ import { isAnthropicInstanceId } from "../providers/anthropic-instance-id";
3
+ import { credentialGeneration, getAccountSet } from "./store";
4
+
5
+ /**
6
+ * Explicit, operator-requested health gate for `ocx account resume --if-healthy` (#8398).
7
+ *
8
+ * Owner decision: resume stays explicit (no background auto-resume). A pause whose recorded reason
9
+ * cannot clear remotely (organization disabled, permission denied, #7101) is never health-resumed.
10
+ * The check never refreshes a paused credential: every refresh path deliberately refuses a paused
11
+ * row, so an expired stored token reports `credential_expired` and the operator re-logs in, which
12
+ * clears an automatic pause. The usage read is the bare provider read, so it publishes no quota or
13
+ * routing evidence for an account that is still paused.
14
+ */
15
+ export const PERMANENT_PAUSE_REASONS: ReadonlySet<AccountPauseReason> = new Set([
16
+ "oauth_organization_disabled", "account_permission_denied",
17
+ ]);
18
+
19
+ export type ResumeHealthRefusal =
20
+ | "pause_not_remote_clearable" | "health_check_unsupported" | "credential_expired"
21
+ | "needs_reauth" | "usage_read_failed" | "account_changed";
22
+
23
+ export type ResumeHealthVerdict =
24
+ | { ok: true; generation: string; pauseRevision: string | undefined }
25
+ | { ok: false; reason: ResumeHealthRefusal };
26
+
27
+ export interface ResumeHealthDeps {
28
+ now?: () => number;
29
+ /** The provider's bare usage read for one bearer; resolves with a quota or null. */
30
+ readUsage?: (provider: string, accessToken: string) => Promise<{ quota: unknown | null }>;
31
+ }
32
+
33
+ const EXPIRY_SKEW_MS = 60_000;
34
+
35
+ async function defaultUsageRead(_provider: string, accessToken: string): Promise<{ quota: unknown | null }> {
36
+ const { probeAnthropicUsageQuota } = await import("../providers/claude-cli-usage");
37
+ return await probeAnthropicUsageQuota(accessToken);
38
+ }
39
+
40
+ /** Whether one paused OAuth account may be resumed now; an unpaused account needs no check. */
41
+ export async function checkOAuthResumeHealth(provider: string, accountId: string, deps: ResumeHealthDeps = {}): Promise<ResumeHealthVerdict | null> {
42
+ const now = deps.now ?? Date.now;
43
+ const row = getAccountSet(provider)?.accounts.find(account => account.id === accountId);
44
+ if (!row || row.paused !== true) return null;
45
+ if (row.pauseDetails && PERMANENT_PAUSE_REASONS.has(row.pauseDetails.reason)) return { ok: false, reason: "pause_not_remote_clearable" };
46
+ if (!isAnthropicInstanceId(provider)) return { ok: false, reason: "health_check_unsupported" };
47
+ if (row.needsReauth === true) return { ok: false, reason: "needs_reauth" };
48
+ const credential = row.credential;
49
+ if (credential.expires <= now() + EXPIRY_SKEW_MS) return { ok: false, reason: "credential_expired" };
50
+ const generation = credentialGeneration(credential);
51
+ const pauseRevision = row.pauseRevision;
52
+ let quota: unknown | null = null;
53
+ try { quota = (await (deps.readUsage ?? defaultUsageRead)(provider, credential.access)).quota; } catch { quota = null; }
54
+ if (quota === null || quota === undefined) return { ok: false, reason: "usage_read_failed" };
55
+ const live = getAccountSet(provider)?.accounts.find(account => account.id === accountId);
56
+ if (!live || live.paused !== true || live.pauseRevision !== pauseRevision || credentialGeneration(live.credential) !== generation) {
57
+ return { ok: false, reason: "account_changed" };
58
+ }
59
+ return { ok: true, generation, pauseRevision };
60
+ }
@@ -4,6 +4,7 @@ import { getCachedProviderAccountQuota } from "../providers/quota/account-cache"
4
4
  import type { ProviderQuota, ProviderQuotaWindow } from "../providers/quota-types";
5
5
  import type { AnthropicInstanceId } from "../providers/anthropic-instance-id";
6
6
  import type { GenerationContext } from "../lib/state-store-sweeper";
7
+ import { familyWeeklyEquivalentPercent } from "../providers/quota/anthropic-usage-windows";
7
8
 
8
9
  export const ANTHROPIC_PASSIVE_FAMILY_MAX_AGE_MS = 30 * 60_000;
9
10
  import { anthropicModelFamily } from "./anthropic-model-family";
@@ -161,3 +162,14 @@ export function anthropicModelWeeklyPercent(quota: ProviderQuota | null, model?:
161
162
  const family = anthropicModelFamily(model);
162
163
  return family ? quota?.customWindows?.find(window => window.scope === "model" && window.label === family)?.percent : undefined;
163
164
  }
165
+
166
+ /**
167
+ * The requested family's usage for comparing accounts, restated on the shared weekly scale when
168
+ * upstream reported its allowance. Thresholds keep `anthropicModelWeeklyPercent`: a fresh Fable
169
+ * seat reads 50 here, which ranks correctly but is not usage an operator's threshold means.
170
+ */
171
+ export function anthropicModelRankPercent(quota: ProviderQuota | null, model?: string): number | undefined {
172
+ const family = anthropicModelFamily(model);
173
+ const window = family ? quota?.customWindows?.find(window => window.scope === "model" && window.label === family) : undefined;
174
+ return window ? familyWeeklyEquivalentPercent(window) : undefined;
175
+ }
@@ -1,4 +1,4 @@
1
- import { clearAllAnthropicFamilyQuota, anthropicModelQuotaFor, anthropicModelPercents, anthropicModelWeeklyPercent } from "./anthropic-model-quota";
1
+ import { clearAllAnthropicFamilyQuota, anthropicModelQuotaFor, anthropicModelPercents, anthropicModelRankPercent, anthropicModelWeeklyPercent } from "./anthropic-model-quota";
2
2
  /**
3
3
  * Opt-in Anthropic OAuth account pool (#294).
4
4
  *
@@ -584,9 +584,16 @@ function createAnthropicRouting(instance: AnthropicInstanceId): AnthropicRouting
584
584
  }
585
585
  }
586
586
 
587
- function usageScore(config: OcxConfig, accountId: string, model?: string): number {
587
+ /**
588
+ * `rank` compares accounts, restating a family allowance on the weekly scale where the configured
589
+ * window ranks on weekly usage. Five-hour ranking has no five-hour tie-break, so a fresh Fable
590
+ * seat's 50 would mask every lower five-hour reading there; it and thresholds keep the family's own percent.
591
+ */
592
+ function usageScore(config: OcxConfig, accountId: string, model?: string, rank = false): number {
588
593
  if (model) {
589
- const family = anthropicModelWeeklyPercent(getCachedProviderAccountQuota(PROVIDER, accountId), model);
594
+ const quota = getCachedProviderAccountQuota(PROVIDER, accountId);
595
+ const weeklyScale = rank && anthropicQuotaWindow(anthropicAccountPoolConfig(config)) !== "five-hour";
596
+ const family = weeklyScale ? anthropicModelRankPercent(quota, model) : anthropicModelWeeklyPercent(quota, model);
590
597
  if (family === undefined) return usageScore(config, accountId);
591
598
  return hasKnownUsage(config, accountId) ? Math.max(family, usageScore(config, accountId)) : family;
592
599
  }
@@ -804,7 +811,7 @@ function createAnthropicRouting(instance: AnthropicInstanceId): AnthropicRouting
804
811
  const scored: ScoredAccount[] = eligible.map(accountId => ({
805
812
  accountId,
806
813
  hasKnownUsage: hasKnownUsage(config, accountId, model),
807
- score: usageScore(config, accountId, model),
814
+ score: usageScore(config, accountId, model, true),
808
815
  fiveHourTieBreak: window === "five-hour" ? 0 : fiveHourScore(accountId),
809
816
  // Every window EXCEPT the legacy five-hour default is an explicit opt-in, so
810
817
  // known-before-unknown applies to all of them and to none of the default path.
@@ -1671,6 +1671,7 @@ export async function runLogin(
1671
1671
  const written = await (deps.saveAccountCredential ?? saveAccountCredential)(provider, opts.reauthAccountId, reauthCred, {
1672
1672
  assertBeforePersist: deps.assertCurrentOwner,
1673
1673
  rotateLoginId: true,
1674
+ clearAutomaticPause: true,
1674
1675
  });
1675
1676
  // A reauth whose account was deleted meanwhile wrote nothing and owns no row to report.
1676
1677
  if (written) deps.onAccountPersisted?.(opts.reauthAccountId);
@@ -55,7 +55,10 @@ async function listProfilesInRegion(reply: KiroIamReply, access: string, region:
55
55
  const tokens = new Set<string>();
56
56
  let nextToken: string | undefined;
57
57
  for (let page = 0; page < 8; page++) {
58
- const data = await call(reply, access, region, "ListAvailableProfiles", { maxResults: 50, ...(nextToken ? { nextToken } : {}) });
58
+ // No maxResults: AWS answers maxResults above 10 with 400 ValidationException, and other
59
+ // Kiro clients report 400 REQUEST_BODY_INVALID for any maxResults; the default page plus
60
+ // nextToken pagination works for both.
61
+ const data = await call(reply, access, region, "ListAvailableProfiles", nextToken ? { nextToken } : {});
59
62
  if (!Array.isArray(data.profiles)) throw new Error("Kiro IAM profiles unavailable");
60
63
  for (const item of data.profiles) {
61
64
  const profile = record(item);
@@ -643,6 +643,21 @@ function newAccountId(cred: OAuthCredentials): string {
643
643
  return createHash("sha256").update(identity).digest("hex").slice(0, 32);
644
644
  }
645
645
 
646
+ /**
647
+ * An explicit login or reauthentication clears an AUTOMATIC pause (one that recorded
648
+ * `pauseDetails`), because the evidence behind it described the replaced credential (#8398).
649
+ * An operator pause carries no details and stays. Eligibility changed, so the selection revision
650
+ * moves with a fresh pause revision, which also retires any auto-pause proposal captured before.
651
+ */
652
+ function clearAutomaticPauseForLogin(set: ProviderAccountSet, account: ProviderAccount): boolean {
653
+ if (account.paused !== true || !account.pauseDetails) return false;
654
+ delete account.paused;
655
+ delete account.pauseDetails;
656
+ account.pauseRevision = randomUUID();
657
+ set.selectionRevision = randomUUID();
658
+ return true;
659
+ }
660
+
646
661
  /** Allocate a persisted slot id without reusing any existing account's ownership key. */
647
662
  function distinctAccountId(cred: OAuthCredentials, accounts: readonly ProviderAccount[]): string {
648
663
  const base = newAccountId(cred);
@@ -946,7 +961,10 @@ export async function saveCredentialWithReceipt(
946
961
  if (isAnthropicInstanceId(provider)) assertAnthropicCredentialSource(provider, cred);
947
962
  const safe = normalizeCredential(cred);
948
963
  if (!safe) return null;
964
+ // A login that clears an automatic pause publishes it once the write commits (#8398).
965
+ let pauseCleared = false;
949
966
  const receipt = await mutateStore(store => {
967
+ pauseCleared = false;
950
968
  if (provider === "anthropic2") assertAnthropicInstanceLoginConfig(loadConfig(), provider);
951
969
  if (isAnthropicInstanceId(provider)) assertNoCrossAnthropicRegistration(store, provider, safe);
952
970
  const set = store[provider];
@@ -973,6 +991,7 @@ export async function saveCredentialWithReceipt(
973
991
  delete existing.needsReauth;
974
992
  delete existing.needsReauthReason;
975
993
  delete existing.refreshAttentionGeneration;
994
+ if (clearAutomaticPauseForLogin(set, existing)) pauseCleared = true;
976
995
  accountId = existing.id;
977
996
  } else {
978
997
  const id = distinctAccountId(safe, set.accounts);
@@ -995,6 +1014,7 @@ export async function saveCredentialWithReceipt(
995
1014
  delete existing.needsReauth;
996
1015
  delete existing.needsReauthReason;
997
1016
  delete existing.refreshAttentionGeneration;
1017
+ if (clearAutomaticPauseForLogin(set, existing)) pauseCleared = true;
998
1018
  if (existing.paused !== true) set.activeAccountId = existing.id;
999
1019
  accountId = existing.id;
1000
1020
  } else {
@@ -1014,6 +1034,7 @@ export async function saveCredentialWithReceipt(
1014
1034
  delete active.needsReauth;
1015
1035
  delete active.needsReauthReason;
1016
1036
  delete active.refreshAttentionGeneration;
1037
+ if (clearAutomaticPauseForLogin(set, active)) pauseCleared = true;
1017
1038
  accountId = active.id;
1018
1039
  } else {
1019
1040
  const id = distinctAccountId(safe, set.accounts);
@@ -1035,6 +1056,7 @@ export async function saveCredentialWithReceipt(
1035
1056
  delete active.needsReauth;
1036
1057
  delete active.needsReauthReason;
1037
1058
  delete active.refreshAttentionGeneration;
1059
+ if (clearAutomaticPauseForLogin(set, active)) pauseCleared = true;
1038
1060
  accountId = active.id;
1039
1061
  } else {
1040
1062
  const id = distinctAccountId(safe, set.accounts);
@@ -1046,6 +1068,12 @@ export async function saveCredentialWithReceipt(
1046
1068
  const updatedSet = store[provider];
1047
1069
  const savedAccount = updatedSet?.accounts.find(account => account.id === accountId);
1048
1070
  const activeAccount = updatedSet?.accounts.find(account => account.id === updatedSet.activeAccountId);
1071
+ // A login that cleared this account's automatic pause hands it a selection still parked on a
1072
+ // paused row (the local-cli import branch does not select on its own), as reauth does below.
1073
+ if (pauseCleared && updatedSet && savedAccount && savedAccount.paused !== true && savedAccount.needsReauth !== true
1074
+ && activeAccount?.id !== accountId && (!activeAccount || activeAccount.paused === true || activeAccount.needsReauth === true)) {
1075
+ updatedSet.activeAccountId = accountId;
1076
+ }
1049
1077
  if (savedAccount?.paused === true
1050
1078
  && (!activeAccount || activeAccount.paused === true || activeAccount.needsReauth === true)) {
1051
1079
  const fallback = updatedSet.accounts.find(account => account.id !== accountId
@@ -1068,6 +1096,7 @@ export async function saveCredentialWithReceipt(
1068
1096
  receipt.selectionRevision = store[provider]?.selectionRevision;
1069
1097
  },
1070
1098
  });
1099
+ if (pauseCleared) publishOAuthAccountPauseChange(provider);
1071
1100
  // An explicit login retires that account's failover evidence: a cooldown recorded
1072
1101
  // against the old grant must not hold out the fresh credential. Dynamic import
1073
1102
  // keeps the store free of a static edge into the failover module, which reads the
@@ -1302,14 +1331,20 @@ export async function saveAccountCredential(
1302
1331
  provider: string,
1303
1332
  accountId: string,
1304
1333
  cred: OAuthCredentials,
1305
- opts: { assertBeforePersist?: () => void; rotateLoginId?: boolean } = {},
1334
+ /**
1335
+ * `clearAutomaticPause`: only an operator's explicit reauthentication of this account may clear a
1336
+ * pause auto-pause recorded (#8398); other writers (Kiro's pre-login identity binding) leave it.
1337
+ */
1338
+ opts: { assertBeforePersist?: () => void; rotateLoginId?: boolean; clearAutomaticPause?: boolean } = {},
1306
1339
  ): Promise<boolean> {
1307
1340
  if (isAnthropicInstanceId(provider)) assertAnthropicCredentialSource(provider, cred);
1308
1341
  const safe = normalizeCredential(cred);
1309
1342
  if (!safe) return false;
1310
1343
  let written = false;
1344
+ let pauseCleared = false;
1311
1345
  await mutateStore(store => {
1312
1346
  written = false;
1347
+ pauseCleared = false;
1313
1348
  if (provider === "anthropic2") assertAnthropicInstanceLoginConfig(loadConfig(), provider);
1314
1349
  if (isAnthropicInstanceId(provider)) assertNoCrossAnthropicRegistration(store, provider, safe);
1315
1350
  const set = store[provider];
@@ -1321,6 +1356,7 @@ export async function saveAccountCredential(
1321
1356
  delete account.needsReauth;
1322
1357
  delete account.needsReauthReason;
1323
1358
  delete account.refreshAttentionGeneration;
1359
+ if (opts.clearAutomaticPause === true && clearAutomaticPauseForLogin(set, account)) pauseCleared = true;
1324
1360
  // A pause that found no usable fallback leaves the active id on a paused row. Once this
1325
1361
  // reauthentication makes an unpaused account usable, hand the selection to it.
1326
1362
  const active = set.accounts.find(a => a.id === set.activeAccountId);
@@ -1329,6 +1365,7 @@ export async function saveAccountCredential(
1329
1365
  set.selectionRevision = randomUUID();
1330
1366
  }
1331
1367
  }, [provider, accountId, safe], { assertBeforePersist: registrationPersistGuard(provider, opts.assertBeforePersist) });
1368
+ if (pauseCleared) publishOAuthAccountPauseChange(provider);
1332
1369
  return written;
1333
1370
  }
1334
1371
 
@@ -1401,6 +1438,8 @@ export async function setAccountAlias(provider: string, accountId: string, alias
1401
1438
  export type SetAccountPausedResult =
1402
1439
  | { status: "updated"; activeAccountId: string; activeAccountChanged: boolean }
1403
1440
  | { status: "unchanged"; activeAccountId: string; activeAccountChanged: boolean }
1441
+ /** A guarded resume found the pause or credential replaced since its health check. */
1442
+ | { status: "changed" }
1404
1443
  | { status: "not-found" };
1405
1444
 
1406
1445
  /** Serialize policy with refresh/removal; stale pre-wait selection proposals must retry. */
@@ -1449,6 +1488,8 @@ export async function setAccountPaused(
1449
1488
  accountId: string,
1450
1489
  paused: boolean,
1451
1490
  automatic?: { generation: string; pauseRevision?: string; details: import("../types/account-auto-pause").AccountPauseDetails; isCurrent?: () => boolean; assertPolicyBeforePersist?: () => void },
1491
+ /** Resume only while the pause and credential are the ones a health check observed (#8398). */
1492
+ resumeGuard?: { generation: string; pauseRevision: string | undefined },
1452
1493
  ): Promise<SetAccountPausedResult> {
1453
1494
  const result = await mutateStore(store => {
1454
1495
  const set = store[provider];
@@ -1456,6 +1497,8 @@ export async function setAccountPaused(
1456
1497
  if (!set || !account) return { status: "not-found" } as const;
1457
1498
  if (automatic && (automatic.isCurrent?.() === false || credentialGeneration(account.credential) !== automatic.generation
1458
1499
  || account.pauseRevision !== automatic.pauseRevision)) return { status: "not-found" } as const;
1500
+ if (resumeGuard && (paused || account.paused !== true || account.pauseRevision !== resumeGuard.pauseRevision
1501
+ || credentialGeneration(account.credential) !== resumeGuard.generation)) return { status: "changed" } as const;
1459
1502
  if (paused && account.paused === true) {
1460
1503
  return { status: "unchanged", activeAccountId: set.activeAccountId, activeAccountChanged: false } as const;
1461
1504
  }
@@ -0,0 +1,23 @@
1
+ import { OAuthAccountPausedError } from "../oauth";
2
+ import type { OcxProviderConfig } from "../types";
3
+
4
+ export class ProviderApiKeyPausedError extends OAuthAccountPausedError {
5
+ constructor() {
6
+ super();
7
+ this.message = "API key is paused. Resume it in account settings and retry.";
8
+ this.name = "ProviderApiKeyPausedError";
9
+ }
10
+ }
11
+
12
+ export function isProviderApiKeyPaused(provider: OcxProviderConfig | undefined): boolean {
13
+ if (!provider || provider.authMode === "oauth" || provider.authMode === "forward" || provider.authMode === "local") {
14
+ return false;
15
+ }
16
+ const pool = provider.apiKeyPool;
17
+ if (!pool?.length) return false;
18
+ if (pool.every(entry => entry.disabled === true)) return true;
19
+ const ref = provider._apiKeyAttempt?.reference ?? provider.apiKey;
20
+ if (!ref?.trim()) return false;
21
+ return pool.some(entry => entry.disabled === true && entry.key === ref)
22
+ && !pool.some(entry => !entry.disabled && entry.key === ref);
23
+ }