@bitkyc08/opencodex 2.33.0 → 2.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +3 -3
  2. package/gui/dist/assets/index-C4TMRloX.js +112 -0
  3. package/gui/dist/assets/index-DQ-Ie18T.css +1 -0
  4. package/gui/dist/index.html +2 -2
  5. package/package.json +1 -1
  6. package/src/adapters/anthropic.ts +79 -2
  7. package/src/adapters/command-code.ts +40 -3
  8. package/src/adapters/cursor/call-id.ts +44 -0
  9. package/src/adapters/cursor/checkpoint-store.ts +15 -10
  10. package/src/adapters/cursor/discovery.ts +60 -2
  11. package/src/adapters/cursor/effort-map.ts +79 -1
  12. package/src/adapters/cursor/envelope-echo.ts +162 -0
  13. package/src/adapters/cursor/live-models.ts +7 -2
  14. package/src/adapters/cursor/live-transport.ts +14 -0
  15. package/src/adapters/cursor/message-mapper.ts +4 -1
  16. package/src/adapters/cursor/native-exec-desktop.ts +23 -0
  17. package/src/adapters/cursor/native-exec-fs.ts +2 -2
  18. package/src/adapters/cursor/native-exec-network.ts +1 -1
  19. package/src/adapters/cursor/native-exec-shell.ts +5 -2
  20. package/src/adapters/cursor/native-exec.ts +20 -0
  21. package/src/adapters/cursor/protobuf-request.ts +68 -14
  22. package/src/adapters/cursor/request-builder.ts +29 -6
  23. package/src/adapters/cursor/tool-definitions.ts +11 -2
  24. package/src/adapters/cursor/tool-result-normalize.ts +32 -1
  25. package/src/adapters/cursor/types.ts +20 -0
  26. package/src/adapters/cursor.ts +189 -37
  27. package/src/adapters/google-antigravity-replay.ts +102 -23
  28. package/src/adapters/google-errors.ts +44 -12
  29. package/src/adapters/google.ts +115 -16
  30. package/src/adapters/image.ts +1 -1
  31. package/src/adapters/kiro-constants.ts +15 -0
  32. package/src/adapters/kiro-tools.ts +43 -15
  33. package/src/adapters/kiro.ts +54 -9
  34. package/src/adapters/openai-chat.ts +286 -242
  35. package/src/adapters/openai-responses.ts +334 -24
  36. package/src/adapters/tool-catalog-nudge.ts +2 -2
  37. package/src/adapters/xai-tool-schema.ts +436 -0
  38. package/src/bridge.ts +67 -24
  39. package/src/chat/inbound.ts +14 -1
  40. package/src/chat/outbound.ts +15 -7
  41. package/src/claude/agents-inject.ts +8 -1
  42. package/src/claude/outbound.ts +10 -8
  43. package/src/cli/account-api.ts +32 -4
  44. package/src/cli/account-extended.ts +1 -1
  45. package/src/cli/account.ts +29 -5
  46. package/src/cli/alias.ts +66 -0
  47. package/src/cli/claude.ts +26 -1
  48. package/src/cli/dispatch.ts +13 -1
  49. package/src/cli/help.ts +1 -0
  50. package/src/cli/init.ts +1 -0
  51. package/src/cli/models-runtime.ts +95 -0
  52. package/src/cli/models.ts +13 -7
  53. package/src/cli/provider-runtime.ts +16 -2
  54. package/src/cli/registry.ts +6 -1
  55. package/src/cli/v2.ts +34 -10
  56. package/src/codex/account-pause.ts +2 -1
  57. package/src/codex/account-priority.ts +3 -2
  58. package/src/codex/app-server-processes.ts +80 -6
  59. package/src/codex/auth-api.ts +46 -8
  60. package/src/codex/auth-context.ts +21 -18
  61. package/src/codex/catalog/aggregation.ts +6 -0
  62. package/src/codex/catalog/native-models.ts +5 -2
  63. package/src/codex/catalog/parsing.ts +16 -0
  64. package/src/codex/catalog/provider-fetch.ts +20 -3
  65. package/src/codex/catalog/sync.ts +127 -2
  66. package/src/codex/catalog.ts +1 -1
  67. package/src/codex/codex-write-lock.ts +3 -1
  68. package/src/codex/convergence-types.ts +1 -1
  69. package/src/codex/convergence.ts +22 -2
  70. package/src/codex/desired-state.ts +2 -2
  71. package/src/codex/desktop-app-restart.ts +18 -5
  72. package/src/codex/inject-coordination.ts +83 -0
  73. package/src/codex/inject.ts +14 -1
  74. package/src/codex/log-guard/inspect.ts +22 -4
  75. package/src/codex/model-entitlements.ts +9 -2
  76. package/src/codex/prompt-layers.ts +371 -25
  77. package/src/codex/prompt-text-probe.ts +238 -0
  78. package/src/codex/quota.ts +91 -10
  79. package/src/codex/routing.ts +9 -0
  80. package/src/codex/subagent-model-fallback.ts +104 -25
  81. package/src/codex/transition-state.ts +107 -8
  82. package/src/combos/types.ts +10 -0
  83. package/src/compatibility/openai-responses.ts +33 -1
  84. package/src/config/rebase-provenance.ts +68 -0
  85. package/src/config.ts +107 -9
  86. package/src/generated/compatibility-version.json +191 -139
  87. package/src/images/loop.ts +5 -4
  88. package/src/lab/conformance/fixtures/protocol-v1-cases.json +1 -1
  89. package/src/lab/fabric/producer-child.ts +1 -1
  90. package/src/lib/config-ownership.ts +20 -0
  91. package/src/lib/errors.ts +11 -2
  92. package/src/lib/package-tree-integrity.ts +101 -0
  93. package/src/oauth/generic-account-failover.ts +231 -0
  94. package/src/oauth/index.ts +57 -5
  95. package/src/oauth/key-providers.ts +10 -1
  96. package/src/oauth/kiro.ts +45 -0
  97. package/src/oauth/types.ts +15 -0
  98. package/src/providers/command-code-efforts.ts +38 -6
  99. package/src/providers/context-cap.ts +4 -3
  100. package/src/providers/default-aliases.ts +65 -0
  101. package/src/providers/derive.ts +28 -0
  102. package/src/providers/fastwire.ts +7 -1
  103. package/src/providers/model-presets.ts +119 -0
  104. package/src/providers/new-model-policy.ts +146 -0
  105. package/src/providers/provider-id-rewrite.ts +2 -1
  106. package/src/providers/quota.ts +65 -7
  107. package/src/providers/registry.ts +160 -68
  108. package/src/providers/slug-codec.ts +52 -0
  109. package/src/responses/code-mode-helper-compat.ts +50 -0
  110. package/src/responses/custom-tool-compat.ts +34 -10
  111. package/src/responses/parser.ts +4 -0
  112. package/src/responses/schema.ts +5 -1
  113. package/src/responses/thought-signature-replay.ts +17 -0
  114. package/src/router.ts +40 -2
  115. package/src/routing/analytics.ts +1 -0
  116. package/src/routing/quota.ts +10 -0
  117. package/src/server/auth-cors.ts +4 -0
  118. package/src/server/chat-completions.ts +24 -16
  119. package/src/server/chat-native-sse.ts +3 -3
  120. package/src/server/chat-native.ts +30 -11
  121. package/src/server/claude-messages.ts +1 -1
  122. package/src/server/index.ts +77 -11
  123. package/src/server/lifecycle.ts +52 -1
  124. package/src/server/management/agent-settings-routes.ts +31 -15
  125. package/src/server/management/codex-prompt-routes.ts +570 -0
  126. package/src/server/management/combo-routes.ts +2 -1
  127. package/src/server/management/config-routes.ts +27 -9
  128. package/src/server/management/context.ts +9 -0
  129. package/src/server/management/model-routes.ts +266 -0
  130. package/src/server/management/provider-routes.ts +6 -0
  131. package/src/server/management/routing-profile-routes.ts +2 -2
  132. package/src/server/management-api.ts +2 -0
  133. package/src/server/relay-eager.ts +147 -20
  134. package/src/server/relay.ts +251 -19
  135. package/src/server/request-log-conversation.ts +21 -0
  136. package/src/server/request-log.ts +41 -15
  137. package/src/server/responses/collaboration.ts +37 -3
  138. package/src/server/responses/combo-stream-preflight.ts +10 -3
  139. package/src/server/responses/core.ts +494 -114
  140. package/src/server/responses/empty-completion-guard.ts +35 -0
  141. package/src/server/responses/fetch-helpers.ts +2 -1
  142. package/src/server/responses/input-admission.ts +3 -1
  143. package/src/server/responses/passthrough-error.ts +33 -9
  144. package/src/server/responses/responses-field-backfill.ts +105 -13
  145. package/src/server/responses-custom-tool-repair.ts +52 -7
  146. package/src/server/responses-terminal-repair.ts +25 -4
  147. package/src/server/sse-frame-buffer.ts +31 -4
  148. package/src/server/ws-bridge.ts +14 -2
  149. package/src/types/config.ts +53 -0
  150. package/src/types/provider.ts +64 -0
  151. package/src/types/request.ts +11 -3
  152. package/src/types/tools.ts +7 -5
  153. package/src/types.ts +1 -0
  154. package/src/usage/expected-prices.ts +43 -24
  155. package/src/usage/log.ts +3 -0
  156. package/src/web-search/exa-executor.ts +40 -9
  157. package/src/web-search/loop.ts +5 -4
  158. package/gui/dist/assets/index-23-Lf7jR.js +0 -102
  159. package/gui/dist/assets/index-DxJMDyOr.css +0 -1
@@ -258,10 +258,11 @@ export interface ImageBridgeDeps {
258
258
  /** Raw adapter usage at the terminal event, pre wire-normalization (see bridgeToResponsesSSE onUsage). */
259
259
  onUsage?: (usage: OcxUsage | undefined) => void;
260
260
  /**
261
- * Optional 429 key-failover for the routed (non-xAI) model. Return a rebuilt adapter for the
262
- * rotated key, or null when the pool is exhausted.
261
+ * Optional 429 failover for the routed (non-xAI) model. Return a rebuilt adapter for the
262
+ * rotated credential, or null when the pool is exhausted. Async hooks support OAuth refresh;
263
+ * existing synchronous key-pool hooks remain valid.
263
264
  */
264
- on429?: (retryAfterHeader: string | null) => ProviderAdapter | null;
265
+ on429?: (retryAfterHeader: string | null) => ProviderAdapter | null | Promise<ProviderAdapter | null>;
265
266
  /** Opt-in same-target 429 policy (key-auth providers). When present, 429 replays on the SAME key before on429 rotation. */
266
267
  retryOn429Policy?: Required<RateLimitRetryPolicy> | null;
267
268
  /** Called when the bridged Responses stream completes (parity with runTurn / routed paths). */
@@ -572,7 +573,7 @@ export async function runWithImageBridge(deps: ImageBridgeDeps): Promise<Respons
572
573
  }
573
574
  // 429 key-failover parity with web-search / normal routed path.
574
575
  while (prepared.response.status === 429 && deps.on429) {
575
- const rotated = deps.on429(prepared.response.headers.get("retry-after"));
576
+ const rotated = await deps.on429(prepared.response.headers.get("retry-after"));
576
577
  if (!rotated) break;
577
578
  try { void prepared.response.body?.cancel().catch(() => {}); } catch { /* already closed */ }
578
579
  adapter = rotated;
@@ -274,7 +274,7 @@
274
274
  "assertions": [
275
275
  { "id": "text", "operator": "normalized_text_equals", "selector": "/client/response/normalizedText", "expected": "OK", "required": true },
276
276
  { "id": "terminal", "operator": "terminal_signal_equals", "selector": "/client/response/terminal", "expected": "completed", "required": true },
277
- { "id": "phase", "operator": "json_path_equals", "selector": "/client/response/events/6/data/item/phase", "expected": "final_answer", "required": true }
277
+ { "id": "phase", "operator": "json_path_equals", "selector": "/client/response/events/7/data/item/phase", "expected": "final_answer", "required": true }
278
278
  ]
279
279
  },
280
280
  {
@@ -128,7 +128,7 @@ async function main(): Promise<void> {
128
128
  writeLine({ type: "result", patch });
129
129
  }
130
130
 
131
- main().catch((error: unknown) => {
131
+ await main().catch((error: unknown) => {
132
132
  writeLine({
133
133
  type: "error",
134
134
  code: "harness_failure",
@@ -40,6 +40,7 @@ const INITIAL_OWNED_PATHS = [
40
40
  "artifacts",
41
41
  "auth.json",
42
42
  "auth.store.lock",
43
+ "admin-api-token",
43
44
  "catalog-backup.json",
44
45
  "claude-env.sh",
45
46
  "codex-accounts.json",
@@ -333,6 +334,25 @@ export function removeOwnedConfigState(configDir: string): ConfigRemovalResult {
333
334
  }
334
335
  }
335
336
 
337
+ // Per-catalog backups are named `catalog-backup-<16 hex>.json` (catalogBackupPathFor), one per
338
+ // CODEX_HOME, so they cannot be enumerated as literal manifest entries the way every other
339
+ // owned file can. Without this, `ocx uninstall` always reported "unowned files remain" and
340
+ // refused to remove a home OpenCodex created itself — the file is unambiguously ours, produced
341
+ // by our own writer, and the strict hex shape keeps the match from widening.
342
+ for (const name of readdirSync(configDir)) {
343
+ if (!/^catalog-backup-[0-9a-f]{16}\.json$/.test(name)) continue;
344
+ const path = join(configDir, name);
345
+ try {
346
+ removeOwnedEntry(rootPath, path);
347
+ } catch (error) {
348
+ return {
349
+ status: "partial",
350
+ reason: `could not remove owned path ${name}: ${error instanceof Error ? error.message : String(error)}`,
351
+ residualPaths: [path],
352
+ };
353
+ }
354
+ }
355
+
336
356
  try {
337
357
  unlinkSync(join(configDir, CONFIG_UNINSTALL_MANIFEST));
338
358
  unlinkSync(join(configDir, CONFIG_OWNER_FILE));
package/src/lib/errors.ts CHANGED
@@ -6,11 +6,18 @@ export interface OcxErrorPayload {
6
6
 
7
7
  /** OpenAI / Codex hard block for high-risk cybersecurity activity (HTTP 400 or mid-stream). */
8
8
  export const CYBER_POLICY_ERROR_CODE = "cyber_policy";
9
+ export const CYBER_POLICY_FALLBACK_MESSAGE = "Request blocked by the upstream cybersecurity policy.";
9
10
 
10
11
  export function isCyberPolicyCode(code: string | null | undefined): boolean {
11
12
  return code === CYBER_POLICY_ERROR_CODE;
12
13
  }
13
14
 
15
+ /** Preserve a structured upstream error type; otherwise use the dedicated policy identity. */
16
+ export function cyberPolicyErrorType(type: string | null | undefined): string {
17
+ const trimmed = typeof type === "string" ? type.trim() : "";
18
+ return trimmed || CYBER_POLICY_ERROR_CODE;
19
+ }
20
+
14
21
  /**
15
22
  * Detect OpenAI cyber-policy refusals from message text when structured `code` was stripped.
16
23
  * Matches Codex fallback copy and Cursor/API agent wording (session evidence 2026-07-24).
@@ -139,9 +146,11 @@ export function classifyError(status: number, type: string, message: string): Oc
139
146
  return { message, type: "invalid_request_error", code: "client_closed_request" };
140
147
  }
141
148
  // Codex only shows the dedicated cyber UI when error.code === "cyber_policy".
142
- // Prefer that code (and invalid_request_error) over generic remaps / 502 upstream_server_error.
149
+ // The public wire does not establish invalid_request_error as the canonical type, so
150
+ // message-only classification keeps the dedicated identity instead of inventing one.
151
+ // Structured callers re-apply their real upstream type with cyberPolicyErrorType().
143
152
  if (type === CYBER_POLICY_ERROR_CODE || isCyberPolicyMessage(text)) {
144
- return { message, type: "invalid_request_error", code: CYBER_POLICY_ERROR_CODE };
153
+ return { message, type: CYBER_POLICY_ERROR_CODE, code: CYBER_POLICY_ERROR_CODE };
145
154
  }
146
155
  // A LOCAL preflight refusal keeps its own code (#1524). The message necessarily says
147
156
  // "context window" -- that is what it is refusing on -- so the generic remap below would
@@ -0,0 +1,101 @@
1
+ import { statSync } from "node:fs";
2
+
3
+ export interface PackageTreeObservation {
4
+ readonly device: bigint;
5
+ readonly inode: bigint;
6
+ readonly contentTimeNs: bigint;
7
+ readonly size: bigint;
8
+ }
9
+
10
+ export type PackageTreeIntegrityStatus =
11
+ | { readonly ok: true }
12
+ | { readonly ok: false; readonly reason: "package_tree_replaced" | "package_tree_unreadable" };
13
+
14
+ export interface PackageTreeIntegrityGuard {
15
+ status(): PackageTreeIntegrityStatus;
16
+ }
17
+
18
+ type ObservePackageTree = () => PackageTreeObservation | null;
19
+ type PackageTreeRuntimeInstall = "bun" | "npm" | "source";
20
+
21
+ const packageManifestUrl = new URL("../../package.json", import.meta.url);
22
+
23
+ function observePackageManifest(): PackageTreeObservation | null {
24
+ try {
25
+ const stat = statSync(packageManifestUrl, { bigint: true });
26
+ return {
27
+ device: stat.dev,
28
+ inode: stat.ino,
29
+ // mtimeNs, NOT ctimeNs. An inode-change time moves for METADATA writes that
30
+ // replace nothing: chmod, chown, touch, an editor normalizing permissions, a
31
+ // backup tool restoring modes. Each of those left device, inode and size
32
+ // identical, so the comparison below called the manifest "replaced" and every
33
+ // /v1/* request answered 503 until the process was restarted. Measured on
34
+ // macOS: chmod alone moved ctimeNs and left mtimeNs untouched.
35
+ //
36
+ // mtimeNs still catches every real replacement. An in-place rewrite of the
37
+ // same byte length moves mtimeNs while inode and size hold; an atomic
38
+ // install (write-then-rename, which is what a package manager does) changes
39
+ // the inode as well. Both were measured before this change was made.
40
+ contentTimeNs: stat.mtimeNs,
41
+ size: stat.size,
42
+ };
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ function sameObservation(left: PackageTreeObservation, right: PackageTreeObservation): boolean {
49
+ return left.device === right.device
50
+ && left.inode === right.inode
51
+ && left.contentTimeNs === right.contentTimeNs
52
+ && left.size === right.size;
53
+ }
54
+
55
+ /**
56
+ * How long an `ok` observation is reused before the manifest is stat'd again.
57
+ *
58
+ * `status()` runs on `/healthz`, `/readyz` and every `/v1/*` request, so an unthrottled guard
59
+ * adds a filesystem syscall to the proxy's hot path to detect an event that happens at most
60
+ * once per install. A replaced tree is not time-critical either: the process is already
61
+ * serving broken imports, and one more second of that is not worse than a syscall per turn
62
+ * forever.
63
+ *
64
+ * A NEGATIVE result is never cached — once the tree looks wrong, every later request re-checks,
65
+ * so a repaired install recovers on its own instead of staying refused for a window.
66
+ */
67
+ const PACKAGE_TREE_RECHECK_MS = 1_000;
68
+
69
+ export function createPackageTreeIntegrityGuard(
70
+ observe: ObservePackageTree = observePackageManifest,
71
+ now: () => number = Date.now,
72
+ ): PackageTreeIntegrityGuard {
73
+ const boot = observe();
74
+ let lastOkAt: number | null = null;
75
+ return {
76
+ status(): PackageTreeIntegrityStatus {
77
+ const at = now();
78
+ if (lastOkAt !== null && at - lastOkAt < PACKAGE_TREE_RECHECK_MS) return { ok: true };
79
+ const current = observe();
80
+ if (boot === null || current === null) return { ok: false, reason: "package_tree_unreadable" };
81
+ if (!sameObservation(boot, current)) return { ok: false, reason: "package_tree_replaced" };
82
+ lastOkAt = at;
83
+ return { ok: true };
84
+ },
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Installed packages fail closed when their manifest is replaced under a live process.
90
+ * A source checkout is different: editing package.json is ordinary development work, and
91
+ * Bun keeps serving the module snapshot already loaded by this process until the operator
92
+ * chooses to restart. Fencing every request there makes running dev directly impossible.
93
+ */
94
+ export function createRuntimePackageTreeIntegrityGuard(
95
+ installer: PackageTreeRuntimeInstall,
96
+ observe: ObservePackageTree = observePackageManifest,
97
+ now: () => number = Date.now,
98
+ ): PackageTreeIntegrityGuard {
99
+ if (installer === "source") return { status: () => ({ ok: true }) };
100
+ return createPackageTreeIntegrityGuard(observe, now);
101
+ }
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Generic OAuth multi-account 429 failover (#2568).
3
+ *
4
+ * The API-key twin (`providers/key-failover.ts`) rotates by default for any key provider with a
5
+ * 2+ pool, but it returns false for `authMode === "oauth"`, and the only OAuth rotator that
6
+ * exists is Anthropic's — behind its own opt-in. So xAI, Cursor, Kimi, GitHub Copilot,
7
+ * Antigravity and Nous have no recovery path on a 429 even with several accounts logged in.
8
+ *
9
+ * Deliberately narrower than the Anthropic pool: no session affinity, no quota-ranked selection,
10
+ * no probe leases. Those carry provider-specific meaning; this module only answers "the account
11
+ * that just 429'd is cooled, is there another one we may use".
12
+ *
13
+ * NOT a home for Codex (`codex/routing.ts` owns quota scopes and probe leases) or Anthropic
14
+ * (`oauth/anthropic-routing.ts` owns affinity and a fail-closed local-cli credential rule).
15
+ * Both are excluded by `isGenericFailoverProvider`.
16
+ */
17
+ import { getAccountSet } from "./store";
18
+ import { getValidAccessSnapshotForAccount, type OAuthAccessSnapshot } from "./index";
19
+ import { parseRetryAfterMs } from "../combos/failover";
20
+ import { sweepExpiredOnWrite } from "../lib/state-store-sweeper";
21
+ import type { OcxConfig, OcxProviderConfig } from "../types";
22
+
23
+ /** Cap same-request rotations so a short Retry-After cannot spin. Mirrors the Anthropic bound. */
24
+ export const GENERIC_OAUTH_MAX_FAILOVERS_PER_REQUEST = 3;
25
+
26
+ const DEFAULT_COOLDOWN_MS = 60_000;
27
+ const MAX_COOLDOWN_MS = 15 * 60_000;
28
+
29
+ /**
30
+ * How long a presence answer may be reused before the store is consulted again.
31
+ *
32
+ * `loadAuthStore` has no cache: every call chmods the config dir and the secret, reads the whole
33
+ * file, parses it and normalizes the store (store.ts:136-151). Since presence now decides
34
+ * activation, this predicate runs on paths that have not seen a 429 at all — the streaming and
35
+ * non-streaming runTurn entry points evaluate it once per request — so an uncached check would put
36
+ * a synchronous file read in front of every request for every OAuth provider.
37
+ *
38
+ * Two seconds is short enough that a login in another window is picked up before the operator can
39
+ * switch back and send a prompt, and long enough that a burst of requests shares one read. The
40
+ * cache holds a COUNT, never a credential.
41
+ */
42
+ const PRESENCE_CACHE_TTL_MS = 2_000;
43
+
44
+ /**
45
+ * Providers whose rotation is owned elsewhere and must not be handled here.
46
+ *
47
+ * `openai` is the Codex pool: quota scopes, probe leases and affinity semantics that this
48
+ * module deliberately does not reimplement. `anthropic` has its own pool with a fail-closed
49
+ * rule about background local-cli credential slots.
50
+ */
51
+ const EXCLUDED_PROVIDERS = new Set(["openai", "anthropic"]);
52
+
53
+ interface AccountHealth {
54
+ cooldownUntil: number;
55
+ cooldownSource: "retry-after" | "default";
56
+ }
57
+
58
+ interface PresenceEntry {
59
+ eligible: number;
60
+ readAt: number;
61
+ }
62
+
63
+ /** Process-local, like the Anthropic pool's: a restart is allowed to forget a cooldown. */
64
+ const health = new Map<string, AccountHealth>();
65
+
66
+ /** Provider -> recent eligible-account count. TTL-bounded; never holds credential material. */
67
+ const presence = new Map<string, PresenceEntry>();
68
+
69
+ const healthKey = (provider: string, accountId: string) => `${provider}\u0000${accountId}`;
70
+
71
+ function isCooled(provider: string, accountId: string, now: number): boolean {
72
+ const entry = health.get(healthKey(provider, accountId));
73
+ if (!entry) return false;
74
+ if (entry.cooldownUntil <= now) {
75
+ health.delete(healthKey(provider, accountId));
76
+ return false;
77
+ }
78
+ return true;
79
+ }
80
+
81
+ /** True when this provider participates in generic rotation at all. */
82
+ export function isGenericFailoverProvider(providerName: string, provider: OcxProviderConfig): boolean {
83
+ return provider.authMode === "oauth" && !EXCLUDED_PROVIDERS.has(providerName);
84
+ }
85
+
86
+ /**
87
+ * Stored accounts that could serve traffic if asked, ignoring cooldowns.
88
+ *
89
+ * Cooldowns are excluded on purpose: they are transient and per-request, while this answers the
90
+ * durable question "did the operator log in more than one account". Treating a cooled account as
91
+ * absent would switch the feature off for the rest of the cooldown, which is exactly when it is
92
+ * needed.
93
+ */
94
+ function eligibleAccountCount(providerName: string, now: number): number {
95
+ const cached = presence.get(providerName);
96
+ if (cached && now >= cached.readAt && now - cached.readAt < PRESENCE_CACHE_TTL_MS) return cached.eligible;
97
+ const set = getAccountSet(providerName);
98
+ const eligible = set ? set.accounts.filter(account => account.needsReauth !== true).length : 0;
99
+ presence.set(providerName, { eligible, readAt: now });
100
+ return eligible;
101
+ }
102
+
103
+ /**
104
+ * Presence IS consent (#2568d).
105
+ *
106
+ * `hasKeyPoolFailover` already reads a 2+ key pool as the operator asking for rotation, and a
107
+ * second OAuth login is the same statement. One account stays a strict no-op either way, so this
108
+ * only changes behaviour for someone who deliberately logged in twice.
109
+ */
110
+ export function hasFailoverAccountQuorum(providerName: string, now = Date.now()): boolean {
111
+ return eligibleAccountCount(providerName, now) >= 2;
112
+ }
113
+
114
+ /**
115
+ * Whether generic rotation is active for this provider.
116
+ *
117
+ * Precedence, most specific first:
118
+ *
119
+ * 1. `providers.<name>.oauthAccountFailover.enabled` — an operator may accept rotation on one
120
+ * provider and refuse it on another, because provider terms differ.
121
+ * 2. `oauthAccountFailover.enabled` — the global switch. Anyone who already wrote `false` keeps
122
+ * strict single-account behaviour across this change.
123
+ * 3. Presence: 2 or more eligible stored accounts (#2568d, owner decision).
124
+ *
125
+ * Only an explicit boolean overrides presence. A malformed value falls through instead of
126
+ * throwing, because a typo in a knob must not take a provider out of service.
127
+ */
128
+ export function isGenericOAuthFailoverEnabled(
129
+ config: OcxConfig,
130
+ providerName: string,
131
+ now = Date.now(),
132
+ ): boolean {
133
+ const provider = config.providers?.[providerName];
134
+ if (!provider || !isGenericFailoverProvider(providerName, provider)) return false;
135
+ const perProvider = provider.oauthAccountFailover?.enabled;
136
+ if (typeof perProvider === "boolean") return perProvider;
137
+ const global = config.oauthAccountFailover?.enabled;
138
+ if (typeof global === "boolean") return global;
139
+ return hasFailoverAccountQuorum(providerName, now);
140
+ }
141
+
142
+ /** Accounts that may serve traffic right now: not cooled, not flagged for reauth. */
143
+ export function eligibleFailoverAccounts(providerName: string, now = Date.now()): string[] {
144
+ const set = getAccountSet(providerName);
145
+ if (!set) return [];
146
+ return set.accounts
147
+ .filter(account => account.needsReauth !== true && !isCooled(providerName, account.id, now))
148
+ .map(account => account.id);
149
+ }
150
+
151
+ /**
152
+ * Cool the account that actually 429'd and name the next eligible one, or null.
153
+ *
154
+ * Returns the id only; the caller mints the credential so a failed refresh does not leave the
155
+ * cooldown applied to an account we then could not use.
156
+ */
157
+ export function rotateGenericOAuthAccountOn429(
158
+ config: OcxConfig,
159
+ providerName: string,
160
+ failedAccountId: string,
161
+ retryAfterHeader: string | null | undefined,
162
+ now = Date.now(),
163
+ ): string | null {
164
+ if (!isGenericOAuthFailoverEnabled(config, providerName)) return null;
165
+ const set = getAccountSet(providerName);
166
+ // A single stored account has nowhere to go; rotating to itself would just replay the 429.
167
+ if (!set || set.accounts.length < 2) return null;
168
+
169
+ const parsed = parseRetryAfterMs(retryAfterHeader, now);
170
+ const cooldownMs = Math.min(parsed ?? DEFAULT_COOLDOWN_MS, MAX_COOLDOWN_MS);
171
+ health.set(healthKey(providerName, failedAccountId), {
172
+ cooldownUntil: now + cooldownMs,
173
+ cooldownSource: parsed ? "retry-after" : "default",
174
+ });
175
+ sweepExpiredOnWrite(now);
176
+
177
+ const eligible = eligibleFailoverAccounts(providerName, now).filter(id => id !== failedAccountId);
178
+ if (eligible.length === 0) return null;
179
+ // A rotation means the roster in use just changed; do not answer the next activation question
180
+ // from a count read before the failure.
181
+ presence.delete(providerName);
182
+ // Deterministic: start after the failed account so repeated 429s walk the roster instead of
183
+ // hammering whichever id happens to sort first.
184
+ const order = set.accounts.map(account => account.id);
185
+ const start = order.indexOf(failedAccountId);
186
+ for (let i = 1; i <= order.length; i++) {
187
+ const candidate = order[(start + i) % order.length]!;
188
+ if (candidate !== failedAccountId && eligible.includes(candidate)) return candidate;
189
+ }
190
+ return null;
191
+ }
192
+
193
+ /**
194
+ * Full credential snapshot for a rotated account.
195
+ *
196
+ * Returns the snapshot rather than a bare bearer: Antigravity pairs an account-matched
197
+ * `projectId` with its token and Kiro carries routing metadata, so a token-only swap would mix
198
+ * one account's bearer with another's routing data.
199
+ */
200
+ export async function failoverAccountSnapshot(
201
+ providerName: string,
202
+ accountId: string,
203
+ ): Promise<OAuthAccessSnapshot> {
204
+ return getValidAccessSnapshotForAccount(providerName, accountId);
205
+ }
206
+
207
+ /** Earliest remaining cooldown, for a client-facing Retry-After when every account is cooled. */
208
+ export function genericFailoverRetryAfterSeconds(providerName: string, now = Date.now()): number | null {
209
+ const set = getAccountSet(providerName);
210
+ if (!set) return null;
211
+ let earliest: number | null = null;
212
+ for (const account of set.accounts) {
213
+ const entry = health.get(healthKey(providerName, account.id));
214
+ if (!entry || entry.cooldownUntil <= now) continue;
215
+ if (earliest === null || entry.cooldownUntil < earliest) earliest = entry.cooldownUntil;
216
+ }
217
+ return earliest === null ? null : Math.max(1, Math.ceil((earliest - now) / 1000));
218
+ }
219
+
220
+ /** Test seam and manual-recovery hook. */
221
+ export function clearGenericFailoverHealth(providerName?: string): void {
222
+ if (!providerName) {
223
+ health.clear();
224
+ presence.clear();
225
+ return;
226
+ }
227
+ presence.delete(providerName);
228
+ for (const key of [...health.keys()]) {
229
+ if (key.startsWith(`${providerName}\u0000`)) health.delete(key);
230
+ }
231
+ }
@@ -58,11 +58,20 @@ export interface OAuthAccessSnapshot {
58
58
  /** Cloud Code Assist project selected during Antigravity login. */
59
59
  projectId?: string;
60
60
  /** Safe request-routing subset; refresh-only Kiro client secrets never leave the credential store. */
61
- kiro?: Pick<KiroOAuthMetadata, "profileArn" | "apiRegion" | "ssoRegion">;
61
+ kiro?: Pick<KiroOAuthMetadata, "profileArn" | "apiRegion" | "ssoRegion" | "authType">;
62
+ /**
63
+ * Allowlisted GitHub Copilot API origin belonging to THIS account.
64
+ *
65
+ * Copilot pins its bearer to an account-scoped regional host, and the initial route already
66
+ * pairs the two (`core.ts` resolves transport with `getOAuthCredentialApiBaseUrl`). Account
67
+ * failover must carry the pairing across the rotation; without it, account B's token is sent to
68
+ * account A's origin (#2568d).
69
+ */
70
+ apiBaseUrl?: string;
62
71
  }
63
72
 
64
73
  export interface ObservedOAuthAccessSnapshot extends OAuthAccessSnapshot {
65
- /** Allowlisted provider API origin consumed by GitHub Copilot model discovery. */
74
+ /** Retained for callers that predate `apiBaseUrl` moving onto the base snapshot. */
66
75
  apiBaseUrl?: string;
67
76
  }
68
77
 
@@ -350,24 +359,43 @@ export function publicOAuthAuthenticationErrorMessage(error: unknown): string {
350
359
  }
351
360
 
352
361
  function accessSnapshot(provider: string, accountId: string, cred: OAuthCredentials): OAuthAccessSnapshot {
362
+ // Derived, not read back: a stored `authType` is trusted when present, but a credential imported
363
+ // before the field existed still routes correctly because the client pair implies SSO OIDC.
364
+ const kiroAuthType = cred.kiro?.authType
365
+ ?? (cred.kiro?.clientId && cred.kiro?.clientSecret ? "aws_sso_oidc" as const : undefined);
353
366
  const storedKiroRouting = {
354
367
  ...(cred.kiro?.profileArn ? { profileArn: cred.kiro.profileArn } : {}),
355
368
  ...(cred.kiro?.apiRegion ? { apiRegion: cred.kiro.apiRegion } : {}),
356
369
  ...(cred.kiro?.ssoRegion ? { ssoRegion: cred.kiro.ssoRegion } : {}),
357
370
  };
371
+ // `authType` is a property OF the account, not routing the environment can substitute for, so it
372
+ // is merged after the environment fallback decision rather than counting as stored routing.
373
+ // Folding it into `storedKiroRouting` would make a client-pair-only credential look non-empty
374
+ // and silently disable `environmentKiroRoutingMetadata()` for it.
375
+ const kiroAuthTypeRouting = kiroAuthType ? { authType: kiroAuthType } : {};
376
+ // Validated here, not at the call site: an unvalidated origin from a legacy or crafted
377
+ // credential must never travel with a bearer, and dropping it makes the transport fall back to
378
+ // the canonical host rather than to whatever the previous account was using.
379
+ const copilotApiBaseUrl = provider === "github-copilot"
380
+ ? validateCopilotApiBaseUrl(cred.apiBaseUrl)
381
+ : undefined;
358
382
  return {
359
383
  provider,
360
384
  accountId,
361
385
  generation: credentialGeneration(cred),
362
386
  accessToken: cred.access,
363
387
  ...(cred.projectId ? { projectId: cred.projectId } : {}),
388
+ ...(copilotApiBaseUrl ? { apiBaseUrl: copilotApiBaseUrl } : {}),
364
389
  // Stored account metadata remains authoritative. Metadata-less legacy/environment credentials
365
390
  // may use explicit environment routing, but never borrow the currently signed-in local CLI account.
366
391
  ...(provider === "kiro"
367
392
  ? {
368
- kiro: Object.keys(storedKiroRouting).length > 0
369
- ? storedKiroRouting
370
- : environmentKiroRoutingMetadata() ?? {},
393
+ kiro: {
394
+ ...(Object.keys(storedKiroRouting).length > 0
395
+ ? storedKiroRouting
396
+ : environmentKiroRoutingMetadata() ?? {}),
397
+ ...kiroAuthTypeRouting,
398
+ },
371
399
  }
372
400
  : {}),
373
401
  };
@@ -490,6 +518,22 @@ export async function getValidAccessTokenForAccount(provider: string, accountId:
490
518
  return (await resolveAccessSnapshotForAccount(provider, accountId)).accessToken;
491
519
  }
492
520
 
521
+ /**
522
+ * Account-scoped resolver returning the FULL snapshot, not just the bearer.
523
+ *
524
+ * A rotator that swaps only the token silently mixes credential generations: Antigravity pairs
525
+ * an account-matched `projectId` with its token (see the pairing comment in
526
+ * server/responses/core.ts), Kiro carries routing metadata, and Copilot's observed snapshot
527
+ * carries an account-specific API origin. Reading those back from "whichever account is active"
528
+ * after a rotation is exactly the mixing this returns in one piece to prevent (#2568).
529
+ */
530
+ export async function getValidAccessSnapshotForAccount(
531
+ provider: string,
532
+ accountId: string,
533
+ ): Promise<OAuthAccessSnapshot> {
534
+ return resolveAccessSnapshotForAccount(provider, accountId);
535
+ }
536
+
493
537
  /** Terminal refresh failures (revoked/rotated-away grants) — retrying cannot succeed. */
494
538
  function isTerminalRefreshError(err: unknown): boolean {
495
539
  const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
@@ -1079,6 +1123,14 @@ export function upsertOAuthProvider(config: OcxConfig, provider: string): void {
1079
1123
  if (existing?.modelCosts !== undefined) {
1080
1124
  next.modelCosts = existing.modelCosts;
1081
1125
  }
1126
+ // The per-provider account-failover opt-out is operator intent about SPENDING, and the login
1127
+ // path is exactly where losing it does damage: adding a second account both rebuilds this row
1128
+ // from the preset and creates the 2-account quorum that turns presence-driven rotation on
1129
+ // (#2568d). Dropping the opt-out here would enable the thing the operator switched off, at the
1130
+ // moment they were doing something unrelated.
1131
+ if (existing?.oauthAccountFailover !== undefined) {
1132
+ next.oauthAccountFailover = existing.oauthAccountFailover;
1133
+ }
1082
1134
  if (existing && getProviderRegistryEntry(provider)?.allowKeyAuthOverride === true) {
1083
1135
  // Shared sanitizeApiKeyValue trim / no-CRLF checks from api-key pool writes.
1084
1136
  let storedApiKey = sanitizeApiKeyValue(existing.apiKey);
@@ -19,7 +19,8 @@ export const KEY_LOGIN_PROVIDERS: Record<string, KeyLoginProvider> = deriveKeyLo
19
19
  * caller didn't already supply. Lets the vision/reasoning classification actually reach the saved
20
20
  * config (the GUI/API only send adapter/baseUrl/apiKey/defaultModel). No-op for unknown names.
21
21
  *
22
- * `modelSupportsReasoningSummaries` is deliberately excluded from what gets persisted. It is
22
+ * `modelSupportsReasoningSummaries` and the verbosity capability are deliberately excluded from
23
+ * what gets persisted. They are
23
24
  * registry-only metadata resolved at runtime, and this function feeds a config that is about to
24
25
  * be written to disk. Persisting today's registry defaults would freeze them as the user's own
25
26
  * overrides: a later registry correction — say we learn a model's backend rejects summary
@@ -30,9 +31,17 @@ export const KEY_LOGIN_PROVIDERS: Record<string, KeyLoginProvider> = deriveKeyLo
30
31
  export function enrichProviderFromCatalog(name: string, prov: OcxProviderConfig): void {
31
32
  const hadOwnSummaries = Object.hasOwn(prov, "modelSupportsReasoningSummaries");
32
33
  const submittedSummaries = prov.modelSupportsReasoningSummaries;
34
+ const hadOwnVerbosity = Object.hasOwn(prov, "modelSupportsVerbosity");
35
+ const submittedVerbosity = prov.modelSupportsVerbosity;
36
+ const hadOwnProviderVerbosity = Object.hasOwn(prov, "supportsVerbosity");
37
+ const submittedProviderVerbosity = prov.supportsVerbosity;
33
38
  enrichProviderFromRegistry(name, prov);
34
39
  if (hadOwnSummaries) prov.modelSupportsReasoningSummaries = submittedSummaries;
35
40
  else delete prov.modelSupportsReasoningSummaries;
41
+ if (hadOwnVerbosity) prov.modelSupportsVerbosity = submittedVerbosity;
42
+ else delete prov.modelSupportsVerbosity;
43
+ if (hadOwnProviderVerbosity) prov.supportsVerbosity = submittedProviderVerbosity;
44
+ else delete prov.supportsVerbosity;
36
45
  }
37
46
 
38
47
  export function isKeyLoginProvider(name: string): boolean {
package/src/oauth/kiro.ts CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  } from "./kiro-credentials";
29
29
  import { homedir } from "node:os";
30
30
  import { getAccountSet, saveAccountCredential } from "./store";
31
+ import { KIRO_BUILDER_ID_SERVICE_PROFILE_ARN } from "../adapters/kiro-constants";
31
32
 
32
33
  const DEFAULT_REGION = "us-east-1";
33
34
  const REFRESH_URL = "https://prod.{region}.auth.desktop.kiro.dev/refreshToken";
@@ -473,6 +474,50 @@ export function resolveKiroProfileArn(account?: Pick<KiroOAuthMetadata, "profile
473
474
  return readImportedKiroCredential()?.profileArn;
474
475
  }
475
476
 
477
+ /**
478
+ * Resolve the profileArn actually SENT upstream, which is not always the account's own.
479
+ *
480
+ * An AWS Builder ID account authenticates through SSO OIDC and never receives an account-scoped
481
+ * profile ARN, so gated models reject its requests with a `profileArn`-demanding
482
+ * `ValidationException`. The Kiro CLI handles this by carrying a fixed service profile on Builder
483
+ * ID requests, and this mirrors that.
484
+ *
485
+ * Deliberately separate from `resolveKiroProfileArn`: that resolver answers "what is this
486
+ * account's profile", and callers that ask it — region inference, account matching, continuation
487
+ * scoping — must keep receiving `undefined` here. Only request construction uses this function.
488
+ *
489
+ * The fallback is gated on `authType === "aws_sso_oidc"` rather than on a missing ARN, so a
490
+ * `kiro_desktop` account whose profile import failed keeps producing its actionable error instead
491
+ * of silently borrowing a service profile that does not describe it.
492
+ */
493
+ export function resolveKiroRequestProfileArn(
494
+ account?: Pick<KiroOAuthMetadata, "profileArn" | "authType">,
495
+ ): string | undefined {
496
+ return resolveKiroRequestProfile(account).profileArn;
497
+ }
498
+
499
+ /**
500
+ * The profileArn to send, together with WHY it was chosen.
501
+ *
502
+ * The request builder must decide the wire envelope from the same evaluation that produced the
503
+ * ARN. Re-deriving "is this Builder ID" from the account context alone would miss the accountless
504
+ * path, where the auth type comes from the locally imported credential instead: the fallback would
505
+ * be sent while the request was shaped as an enterprise IDE call, which is not a combination the
506
+ * vendor client ever produces.
507
+ */
508
+ export function resolveKiroRequestProfile(
509
+ account?: Pick<KiroOAuthMetadata, "profileArn" | "authType">,
510
+ ): { profileArn: string | undefined; builderIdFallback: boolean } {
511
+ const own = resolveKiroProfileArn(account);
512
+ if (own) return { profileArn: own, builderIdFallback: false };
513
+ const authType = account !== undefined
514
+ ? account.authType
515
+ : readImportedKiroCredential()?.authType;
516
+ return authType === "aws_sso_oidc"
517
+ ? { profileArn: KIRO_BUILDER_ID_SERVICE_PROFILE_ARN, builderIdFallback: true }
518
+ : { profileArn: undefined, builderIdFallback: false };
519
+ }
520
+
476
521
  async function kiroTokenRefreshError(response: Response): Promise<KiroTokenRefreshError> {
477
522
  let oauthError: string | undefined;
478
523
  try {