@bitkyc08/opencodex 2.99.0-preview.20261108 → 2.100.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 (258) hide show
  1. package/AGENTS_INSTALL.md +19 -1
  2. package/README.md +37 -33
  3. package/SPONSORS.md +5 -1
  4. package/bin/ocx.mjs +1 -1
  5. package/gui/dist/assets/{App-C1hGwaN1.css → App-COo8Yopd.css} +1 -1
  6. package/gui/dist/assets/App-CitvEefy.js +59 -0
  7. package/gui/dist/assets/Tray-CeKVWQyB.js +1 -0
  8. package/gui/dist/assets/{brand-mark-DpiBmFGI.js → brand-mark-M92UnxX2.js} +1 -1
  9. package/gui/dist/assets/index-BP47do6-.js +94 -0
  10. package/gui/dist/assets/index-DmDooSAG.css +2 -0
  11. package/gui/dist/assets/{segment-thumb-features-JcszQ18T.js → segment-thumb-features-CcxZBnxv.js} +1 -1
  12. package/gui/dist/classic/assets/App-aYgIQMxI.js +58 -0
  13. package/gui/dist/classic/assets/{Tray-5v86r9Az.js → Tray-D8jfUXpQ.js} +1 -1
  14. package/gui/dist/classic/assets/index-CfGqHooN.js +94 -0
  15. package/gui/dist/classic/assets/quota-summary-R-ih7OlS.js +1 -0
  16. package/gui/dist/classic/index.html +1 -1
  17. package/gui/dist/index.html +2 -2
  18. package/native/ocx-child/Cargo.lock +215 -0
  19. package/native/ocx-child/Cargo.toml +31 -0
  20. package/native/ocx-child/src/cli.rs +1901 -0
  21. package/native/ocx-child/src/codex_home.rs +429 -0
  22. package/native/ocx-child/src/codex_settings.rs +231 -0
  23. package/native/ocx-child/src/daemon.rs +363 -0
  24. package/native/ocx-child/src/http_wire.rs +619 -0
  25. package/native/ocx-child/src/journal.rs +977 -0
  26. package/native/ocx-child/src/lib.rs +22 -0
  27. package/native/ocx-child/src/main.rs +9 -0
  28. package/native/ocx-child/src/parity.rs +102 -0
  29. package/native/ocx-child/src/platform.rs +1487 -0
  30. package/native/ocx-child/src/relay.rs +1288 -0
  31. package/native/ocx-child/src/relay_auth.rs +166 -0
  32. package/native/ocx-child/src/routes.rs +236 -0
  33. package/native/ocx-child/src/state.rs +190 -0
  34. package/native/ocx-child/src/test_hooks.rs +58 -0
  35. package/native/ocx-child/src/toml_surgeon.rs +1156 -0
  36. package/package.json +8 -2
  37. package/src/adapters/anthropic.ts +28 -2
  38. package/src/adapters/claude-cli/adapter.ts +5 -25
  39. package/src/adapters/claude-cli/instruction-images.ts +31 -0
  40. package/src/adapters/claude-cli/stable-replay.ts +42 -14
  41. package/src/adapters/claude-cli/usage-admission.ts +53 -64
  42. package/src/adapters/coding-agent/protocol.ts +1 -1
  43. package/src/adapters/devin/live-models.ts +3 -0
  44. package/src/adapters/google-http.ts +3 -0
  45. package/src/adapters/google-vertex-key-project.ts +10 -2
  46. package/src/adapters/google.ts +40 -8
  47. package/src/adapters/kiro/usage.ts +3 -13
  48. package/src/adapters/openai-responses/passthrough.ts +5 -2
  49. package/src/adapters/openai-responses/request-strips.ts +32 -0
  50. package/src/adapters/openai-responses/tool-schema.ts +9 -4
  51. package/src/chat/inbound.ts +1 -1
  52. package/src/claude/auth-detect.ts +26 -8
  53. package/src/claude/inbound-content-options.ts +18 -3
  54. package/src/claude/inbound.ts +5 -2
  55. package/src/cli/bundled-bun-diagnostic.ts +91 -0
  56. package/src/cli/capabilities-agents-routing.ts +2 -2
  57. package/src/cli/capabilities-observe-system.ts +60 -0
  58. package/src/cli/combo-input.ts +6 -0
  59. package/src/cli/combo-result.ts +1 -1
  60. package/src/cli/combo.ts +4 -0
  61. package/src/cli/config-command.ts +16 -2
  62. package/src/cli/connect.ts +12 -10
  63. package/src/cli/dispatch.ts +4 -0
  64. package/src/cli/doctor.ts +11 -0
  65. package/src/cli/help.ts +1 -0
  66. package/src/cli/init.ts +4 -0
  67. package/src/cli/link-enrollment.ts +152 -25
  68. package/src/cli/link-local-control.ts +49 -0
  69. package/src/cli/link.ts +37 -10
  70. package/src/cli/provider-lifecycle-runtime.ts +4 -2
  71. package/src/cli/registry.ts +13 -0
  72. package/src/cli/star-prompt.ts +2 -0
  73. package/src/cli/status.ts +1 -1
  74. package/src/cli/telemetry-profile.ts +206 -0
  75. package/src/cli/telemetry.ts +260 -0
  76. package/src/client/hub-relay.ts +26 -0
  77. package/src/client/machine-api.ts +3 -0
  78. package/src/clients/config-export/t3code.ts +44 -5
  79. package/src/clients/omo-role-models.ts +1 -1
  80. package/src/codex/catalog/bundled.ts +44 -2
  81. package/src/codex/runtime.ts +12 -0
  82. package/src/codex/shim-restore-lock.ts +67 -30
  83. package/src/combos/types.ts +21 -1
  84. package/src/config/atomic-write.ts +24 -1
  85. package/src/config/diagnostics.ts +15 -0
  86. package/src/config/live-reconcile.ts +17 -0
  87. package/src/config/load-degrade.ts +16 -0
  88. package/src/config/provider-validation.ts +29 -0
  89. package/src/config/schema/config-schema.ts +24 -0
  90. package/src/config/schema/leaf-validators.ts +17 -0
  91. package/src/config/telemetry-carry.ts +30 -0
  92. package/src/config.ts +13 -1
  93. package/src/generated/compatibility-version.json +405 -153
  94. package/src/generated/model-metadata.ts +3 -3
  95. package/src/integrations/aside-profiles.ts +7 -1
  96. package/src/integrations/owned-refresh.ts +9 -2
  97. package/src/lab/artifacts/secure-fs.ts +12 -11
  98. package/src/lab/fabric/scratch.ts +11 -9
  99. package/src/lab/public/community.ts +2 -3
  100. package/src/lab/public/file-safety.ts +18 -20
  101. package/src/lab/public/mutation-lock.ts +109 -337
  102. package/src/lab/public/private-file.ts +4 -3
  103. package/src/lib/bun-runtime-preflight.ts +1 -1
  104. package/src/lib/codex-catalog-read-only.ts +122 -0
  105. package/src/lib/config-ownership.ts +49 -18
  106. package/src/lib/errors.ts +11 -0
  107. package/src/lib/gcp-adc.ts +167 -48
  108. package/src/lib/jsonc.ts +4 -2
  109. package/src/lib/local-control-socket.ts +88 -0
  110. package/src/lib/privacy.ts +15 -0
  111. package/src/lib/provider-client-headers.ts +3 -0
  112. package/src/lib/token-estimate.ts +13 -2
  113. package/src/link/child-binary-source.ts +228 -0
  114. package/src/link/ephemeral-child.ts +45 -0
  115. package/src/link/remote-plant.ts +306 -0
  116. package/src/link/remote-windows.ts +59 -5
  117. package/src/link/ssh-argv.ts +71 -8
  118. package/src/link/status-projection.ts +2 -0
  119. package/src/link/store.ts +5 -1
  120. package/src/oauth/claude-keychain-read.ts +165 -0
  121. package/src/oauth/local-token-detect.ts +14 -17
  122. package/src/protocols/envelope.ts +20 -2
  123. package/src/providers/api-key-selection.ts +8 -2
  124. package/src/providers/claude-cli-usage-state.ts +93 -0
  125. package/src/providers/github-copilot-auto.ts +25 -5
  126. package/src/providers/meta-muse-plan-refusal.ts +94 -0
  127. package/src/providers/model-rename-fields.ts +3 -0
  128. package/src/providers/quota/vendor-probes-key.ts +23 -4
  129. package/src/providers/quota/vendor-probes-oauth.ts +59 -0
  130. package/src/providers/quota/workbuddy.ts +2 -2
  131. package/src/providers/quota.ts +25 -18
  132. package/src/providers/registry/entries-core.ts +7 -4
  133. package/src/providers/registry/entries-extended.ts +39 -7
  134. package/src/providers/registry/model-seeds.ts +10 -2
  135. package/src/providers/resolved-model-policy.ts +4 -0
  136. package/src/providers/routed-config.ts +30 -3
  137. package/src/providers/stale-no-vision-seed-migration.ts +7 -0
  138. package/src/providers/vertex-environment-authority.ts +50 -0
  139. package/src/providers/workbuddy-credit-balance.ts +38 -6
  140. package/src/quota-pool/assemble.ts +14 -6
  141. package/src/router.ts +1 -0
  142. package/src/server/adapter-resolve.ts +11 -6
  143. package/src/server/audio-dictation.ts +21 -7
  144. package/src/server/auth-cors.ts +19 -0
  145. package/src/server/background-lifecycle.ts +71 -0
  146. package/src/server/chat-completions.ts +2 -0
  147. package/src/server/claude-messages.ts +30 -3
  148. package/src/server/index/live-sideband.ts +15 -1
  149. package/src/server/index/local-control-listener.ts +515 -0
  150. package/src/server/index/optional-listeners.ts +21 -1
  151. package/src/server/index/serve-options.ts +4 -3
  152. package/src/server/index/websocket-handler.ts +2 -0
  153. package/src/server/index.ts +3 -0
  154. package/src/server/management/combo-routes.ts +6 -1
  155. package/src/server/management/context.ts +1 -0
  156. package/src/server/management/link-child-preflight.ts +74 -0
  157. package/src/server/management/link-enrollment.ts +190 -25
  158. package/src/server/management/link-route-state.ts +6 -1
  159. package/src/server/management/link-routes.ts +27 -9
  160. package/src/server/management/model-rows.ts +4 -0
  161. package/src/server/management/oauth-account-routes.ts +9 -4
  162. package/src/server/management/provider-overwrite-carry.ts +9 -2
  163. package/src/server/management/provider-routes.ts +14 -0
  164. package/src/server/management/provider-thinking-display-patch.ts +54 -0
  165. package/src/server/management/route-registry.ts +7 -0
  166. package/src/server/management/session-routes.ts +4 -1
  167. package/src/server/management/telemetry-routes.ts +37 -0
  168. package/src/server/management/usage-aggregate-cache.ts +290 -67
  169. package/src/server/management-api.ts +11 -2
  170. package/src/server/messages-native-preflight.ts +166 -0
  171. package/src/server/messages-native.ts +143 -43
  172. package/src/server/messages-shared.ts +14 -0
  173. package/src/server/proxy-liveness.ts +99 -6
  174. package/src/server/request-log-conversation.ts +18 -2
  175. package/src/server/request-log.ts +7 -2
  176. package/src/server/responses/adapter-continuation.ts +1 -0
  177. package/src/server/responses/adapter-dispatch.ts +11 -28
  178. package/src/server/responses/adapter-failure-message.ts +68 -0
  179. package/src/server/responses/combo-stream-preflight.ts +14 -2
  180. package/src/server/responses/core-auth.ts +26 -5
  181. package/src/server/responses/core-codex-account.ts +8 -1
  182. package/src/server/responses/core-combo-failure.ts +6 -1
  183. package/src/server/responses/core-combo-native.ts +150 -37
  184. package/src/server/responses/core-combo.ts +15 -9
  185. package/src/server/responses/core-normalize.ts +1 -0
  186. package/src/server/responses/core-options.ts +7 -1
  187. package/src/server/responses/core-pipeline.ts +21 -1
  188. package/src/server/responses/fetch-helpers.ts +5 -0
  189. package/src/server/responses/opengateway-completion-guard.ts +7 -3
  190. package/src/server/responses/passthrough-delivery.ts +8 -1
  191. package/src/server/responses/passthrough-error.ts +22 -0
  192. package/src/server/responses/request-prepare.ts +7 -1
  193. package/src/server/responses/request-transport.ts +28 -5
  194. package/src/server/responses/run-turn-execution.ts +13 -0
  195. package/src/server/sse-frame-buffer.ts +5 -0
  196. package/src/server/ws-bridge.ts +10 -0
  197. package/src/service/launchd.ts +78 -4
  198. package/src/telemetry/aggregate.ts +348 -0
  199. package/src/telemetry/consent.ts +128 -0
  200. package/src/telemetry/contract.ts +403 -0
  201. package/src/telemetry/disclosure.ts +19 -0
  202. package/src/telemetry/install-id.ts +226 -0
  203. package/src/telemetry/payload.ts +129 -0
  204. package/src/telemetry/profile/client.ts +150 -0
  205. package/src/telemetry/profile/contract.ts +288 -0
  206. package/src/telemetry/profile/disclosure.ts +14 -0
  207. package/src/telemetry/profile/paths.ts +13 -0
  208. package/src/telemetry/profile/routes.ts +99 -0
  209. package/src/telemetry/profile/service.ts +234 -0
  210. package/src/telemetry/profile/state.ts +189 -0
  211. package/src/telemetry/profile/sync.ts +276 -0
  212. package/src/telemetry/routes.ts +183 -0
  213. package/src/telemetry/scheduler.ts +386 -0
  214. package/src/telemetry/sender.ts +97 -0
  215. package/src/telemetry/state.ts +334 -0
  216. package/src/types/combo-jev-effort-mode.ts +11 -0
  217. package/src/types/config.ts +3 -0
  218. package/src/types/provider.ts +11 -1
  219. package/src/types/request.ts +2 -0
  220. package/src/types/telemetry.ts +15 -0
  221. package/src/types/wire.ts +10 -0
  222. package/src/types.ts +5 -0
  223. package/src/update/index.ts +7 -1
  224. package/src/update/minisign.d.mts +17 -0
  225. package/src/update/minisign.mjs +88 -0
  226. package/src/update/signed-supply.d.mts +59 -0
  227. package/src/update/signed-supply.mjs +289 -0
  228. package/src/update/trust-root.json +38 -0
  229. package/src/update/update-bounded-json.d.mts +4 -0
  230. package/src/update/update-bounded-json.mjs +113 -0
  231. package/src/update/update-bytes.d.mts +2 -0
  232. package/src/update/update-bytes.mjs +23 -0
  233. package/src/update/update-candidate-id.d.mts +2 -0
  234. package/src/update/update-candidate-id.mjs +23 -0
  235. package/src/update/update-checkpoint-codec.d.mts +33 -0
  236. package/src/update/update-checkpoint-codec.mjs +217 -0
  237. package/src/update/update-contracts.d.mts +24 -0
  238. package/src/update/update-contracts.mjs +207 -0
  239. package/src/update/update-signature-threshold.d.mts +12 -0
  240. package/src/update/update-signature-threshold.mjs +47 -0
  241. package/src/update/update-signed-version.d.mts +5 -0
  242. package/src/update/update-signed-version.mjs +25 -0
  243. package/src/update/update-trust-anchor.d.mts +2 -0
  244. package/src/update/update-trust-anchor.mjs +2 -0
  245. package/src/usage/cache-diagnostic.ts +195 -50
  246. package/src/usage/expected-prices.ts +20 -2
  247. package/src/usage/filter-index.ts +1469 -0
  248. package/src/usage/ledger-scanner.ts +245 -4
  249. package/src/usage/source-filter.ts +10 -2
  250. package/src/usage/summary.ts +16 -0
  251. package/src/web-search/parse.ts +244 -38
  252. package/gui/dist/assets/App-CWz0areF.js +0 -59
  253. package/gui/dist/assets/Tray-BosDoskm.js +0 -1
  254. package/gui/dist/assets/index-CAxjGWkm.js +0 -94
  255. package/gui/dist/assets/index-bnUWypyz.css +0 -2
  256. package/gui/dist/classic/assets/App-BOEsFmiN.js +0 -58
  257. package/gui/dist/classic/assets/index-ClZ_zZ77.js +0 -94
  258. package/gui/dist/classic/assets/quota-summary-xwvDtvu7.js +0 -1
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Claude Code Keychain reads that never kill a blocked `security` child.
3
+ *
4
+ * With a locked login keychain, `security find-generic-password -w` blocks on the
5
+ * SecurityAgent unlock prompt. Killing it while that prompt is pending hits a race in
6
+ * Apple's `securityd`, which aborts and re-locks the keychain, so the next read prompts
7
+ * again (#8161). This reader gives up on a slow read without signalling the child, keeps
8
+ * at most one child per process, and backs off after a timeout so a locked keychain does
9
+ * not get one prompt per request.
10
+ */
11
+ import { execFileSync, spawn } from "node:child_process";
12
+
13
+ export const CLAUDE_KEYCHAIN_SERVICE = "Claude Code-credentials";
14
+ export const CLAUDE_KEYCHAIN_TIMEOUT_MS = 5_000;
15
+ export const CLAUDE_KEYCHAIN_BACKOFF_MS = 60_000;
16
+ const SECURITY_ARGS = ["find-generic-password", "-s", CLAUDE_KEYCHAIN_SERVICE, "-w"] as const;
17
+ /** The credential is a small JSON blob; anything larger is not a credential. */
18
+ const MAX_STDOUT_BYTES = 1024 * 1024;
19
+
20
+ interface UnrefHandle { unref?(): unknown }
21
+
22
+ /** The subset of a spawned child the reader relies on. */
23
+ export interface KeychainChild extends UnrefHandle {
24
+ /** Set once the process exists; undefined when the spawn itself failed. */
25
+ pid?: number | undefined;
26
+ stdout: (UnrefHandle & { on(event: "data", listener: (chunk: Buffer | string) => void): unknown }) | null;
27
+ once(event: "close", listener: (code: number | null, signal: string | null) => void): unknown;
28
+ once(event: "error", listener: (error: Error) => void): unknown;
29
+ }
30
+
31
+ export interface ClaudeKeychainReaderDeps {
32
+ platform: string;
33
+ spawn(command: string, args: readonly string[]): KeychainChild;
34
+ /** Synchronous run with a timeout; returns stdout and throws on a nonzero exit or a timeout. */
35
+ execSync(command: string, args: readonly string[], timeoutMs: number): string;
36
+ now(): number;
37
+ /** Runs `fn` after `ms`; returns a cancel function. */
38
+ schedule(ms: number, fn: () => void): () => void;
39
+ timeoutMs?: number;
40
+ backoffMs?: number;
41
+ }
42
+
43
+ export interface ClaudeKeychainReader {
44
+ /** Resolves the item's secret, or null on absence, failure, timeout, backoff or a non-darwin host. */
45
+ readAsync(): Promise<string | null>;
46
+ /**
47
+ * Synchronous read. It cannot time out without killing its child, so it does not run while a
48
+ * child is still running or a backoff is active, and its own timeout starts the backoff.
49
+ */
50
+ readSync(): string | null;
51
+ /** True while a child is still running or a timeout backoff is active. */
52
+ syncReadBlocked(): boolean;
53
+ /**
54
+ * Record a timeout of another synchronous Keychain lookup (the metadata probe), so it starts
55
+ * the same backoff and no read or probe spawns again inside that window.
56
+ */
57
+ noteSyncTimeout(): void;
58
+ }
59
+
60
+ export function createClaudeKeychainReader(deps: ClaudeKeychainReaderDeps): ClaudeKeychainReader {
61
+ const timeoutMs = deps.timeoutMs ?? CLAUDE_KEYCHAIN_TIMEOUT_MS;
62
+ const backoffMs = deps.backoffMs ?? CLAUDE_KEYCHAIN_BACKOFF_MS;
63
+ let backoffUntil = 0;
64
+ // Held until the child exits, not until the caller's promise settles: a child that
65
+ // outlives its deadline is still blocked on the prompt and must not get a sibling. Only the
66
+ // owning child may release it, so a late event from an earlier child cannot free the slot.
67
+ let runningChild: KeychainChild | undefined;
68
+ let pending: Promise<string | null> | undefined;
69
+
70
+ const backingOff = (): boolean => deps.now() < backoffUntil;
71
+ const startBackoff = (): void => { backoffUntil = deps.now() + backoffMs; };
72
+
73
+ function readAsync(): Promise<string | null> {
74
+ if (deps.platform !== "darwin") return Promise.resolve(null);
75
+ if (pending) return pending;
76
+ if (runningChild || backingOff()) return Promise.resolve(null);
77
+
78
+ let child: KeychainChild;
79
+ try {
80
+ child = deps.spawn("security", SECURITY_ARGS);
81
+ } catch {
82
+ return Promise.resolve(null);
83
+ }
84
+ runningChild = child;
85
+ const release = (): void => { if (runningChild === child) runningChild = undefined; };
86
+ const read = new Promise<string | null>(resolve => {
87
+ let settled = false;
88
+ const chunks: Buffer[] = [];
89
+ let stdoutBytes = 0;
90
+ const settle = (value: string | null): void => {
91
+ if (settled) return;
92
+ settled = true;
93
+ cancelDeadline();
94
+ pending = undefined;
95
+ resolve(value);
96
+ };
97
+ const cancelDeadline = deps.schedule(timeoutMs, () => {
98
+ // Give up without signalling the child, and let it exit on its own once the
99
+ // prompt is answered or dismissed. Unref it so it cannot hold this process open.
100
+ startBackoff();
101
+ child.unref?.();
102
+ child.stdout?.unref?.();
103
+ settle(null);
104
+ });
105
+ child.stdout?.on("data", chunk => {
106
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
107
+ stdoutBytes += bytes.length;
108
+ if (stdoutBytes <= MAX_STDOUT_BYTES) chunks.push(bytes);
109
+ });
110
+ child.once("error", () => {
111
+ // Once a process exists, an error event does not prove it ended; only its own close may
112
+ // release the slot, or a second child could start beside one still blocked on the prompt.
113
+ if (child.pid === undefined) release();
114
+ settle(null);
115
+ });
116
+ // `close`, not `exit`: `exit` can fire before stdout is drained, which would truncate
117
+ // the credential. Decode once so a multi-byte character split across chunks survives.
118
+ child.once("close", code => {
119
+ release();
120
+ if (code !== 0 || stdoutBytes > MAX_STDOUT_BYTES) return settle(null);
121
+ settle(Buffer.concat(chunks).toString("utf8").trim() || null);
122
+ });
123
+ });
124
+ pending = read;
125
+ return read;
126
+ }
127
+
128
+ function readSync(): string | null {
129
+ if (deps.platform !== "darwin" || runningChild || backingOff()) return null;
130
+ try {
131
+ return deps.execSync("security", SECURITY_ARGS, timeoutMs).trim() || null;
132
+ } catch (error) {
133
+ if (isSyncTimeout(error)) startBackoff();
134
+ return null;
135
+ }
136
+ }
137
+
138
+ return {
139
+ readAsync,
140
+ readSync,
141
+ syncReadBlocked: () => runningChild !== undefined || backingOff(),
142
+ noteSyncTimeout: startBackoff,
143
+ };
144
+ }
145
+
146
+ /** `execFileSync` reports its own timeout as ETIMEDOUT or a kill signal; a nonzero exit is not one. */
147
+ export function isSyncTimeout(error: unknown): boolean {
148
+ if (!error || typeof error !== "object") return false;
149
+ const { code, signal } = error as { code?: unknown; signal?: unknown };
150
+ return code === "ETIMEDOUT" || (typeof signal === "string" && signal.length > 0);
151
+ }
152
+
153
+ /** The process-wide reader: one Keychain child and one backoff window per process. */
154
+ export const claudeKeychainReader = createClaudeKeychainReader({
155
+ platform: process.platform,
156
+ spawn: (command, args) => spawn(command, [...args], { stdio: ["ignore", "pipe", "ignore"] }),
157
+ execSync: (command, args, timeoutMs) =>
158
+ execFileSync(command, [...args], { encoding: "utf8", timeout: timeoutMs, stdio: ["pipe", "pipe", "pipe"] }),
159
+ now: () => Date.now(),
160
+ schedule(ms, fn) {
161
+ const timer = setTimeout(fn, ms);
162
+ timer.unref?.();
163
+ return () => clearTimeout(timer);
164
+ },
165
+ });
@@ -3,14 +3,13 @@
3
3
  * Read-only: never writes to external credential stores.
4
4
  * Ported from jawcode packages/ai/src/utils/oauth/local-token-detect.ts (xAI portion).
5
5
  */
6
- import { execFile, execSync } from "node:child_process";
7
6
  import { existsSync, readFileSync } from "node:fs";
8
7
  import { homedir } from "node:os";
9
8
  import { join } from "node:path";
9
+ import { claudeKeychainReader } from "./claude-keychain-read";
10
10
  import type { OAuthCredentials } from "./types";
11
11
 
12
12
  const XAI_AUTH_KEY_PREFIX = "https://auth.x.ai::";
13
- const CLAUDE_KEYCHAIN_SERVICE = "Claude Code-credentials";
14
13
 
15
14
  export function detectGrokCliToken(): OAuthCredentials | null {
16
15
  const authPath = join(process.env.HOME ?? homedir(), ".grok", "auth.json");
@@ -73,16 +72,14 @@ function claudeConfigDir(): string {
73
72
  return explicit ? explicit : join(homedir(), ".claude");
74
73
  }
75
74
 
76
- /** Read the Claude Code OAuth credential from the macOS Keychain (darwin only). */
75
+ /**
76
+ * Read the Claude Code OAuth credential from the macOS Keychain (darwin only). A synchronous
77
+ * read cannot time out without killing `security`, which can crash `securityd` while an unlock
78
+ * prompt is pending (#8161), so it does not spawn while a read is still running or backing off,
79
+ * and its own timeout starts that backoff (`claude-keychain-read.ts`).
80
+ */
77
81
  function readClaudeKeychain(): string | null {
78
- if (process.platform !== "darwin") return null;
79
- try {
80
- return execSync(`security find-generic-password -s "${CLAUDE_KEYCHAIN_SERVICE}" -w`, {
81
- encoding: "utf8", timeout: 5000, stdio: ["pipe", "pipe", "pipe"],
82
- }).trim();
83
- } catch {
84
- return null;
85
- }
82
+ return claudeKeychainReader.readSync();
86
83
  }
87
84
 
88
85
  /**
@@ -109,13 +106,13 @@ function readClaudeSecureStorage(): string | null {
109
106
  return readClaudeKeychain() ?? readClaudeCredentialsFile();
110
107
  }
111
108
 
112
- /** Non-blocking Keychain read for request paths; same item and timeout as the sync reader. */
109
+ /**
110
+ * Non-blocking Keychain read for request paths; same item and deadline as the sync reader. A
111
+ * timed-out child is left to exit on its own, concurrent reads share one child, and a timeout
112
+ * backs off before the next spawn (`claude-keychain-read.ts`).
113
+ */
113
114
  function readClaudeKeychainAsync(): Promise<string | null> {
114
- if (process.platform !== "darwin") return Promise.resolve(null);
115
- return new Promise(resolve => {
116
- execFile("security", ["find-generic-password", "-s", CLAUDE_KEYCHAIN_SERVICE, "-w"], { encoding: "utf8", timeout: 5000 },
117
- (error, stdout) => resolve(error ? null : stdout.trim() || null));
118
- });
115
+ return claudeKeychainReader.readAsync();
119
116
  }
120
117
 
121
118
  /**
@@ -17,8 +17,12 @@ export interface ProtocolEnvelope {
17
17
  readonly inbound: Protocol;
18
18
  /** The request features, scanned from the source body on the first call and cached. */
19
19
  features(): ReadonlySet<ProtocolFeature>;
20
+ /** The source body itself, uncharged, for checks that only read it; a rewrite takes `freshBody()`. */
21
+ readBody(): Readonly<Record<string, unknown>>;
20
22
  /** A structured clone of the source body, charged to the translator budget. */
21
23
  freshBody(): Record<string, unknown>;
24
+ /** Hand back the charge of a `freshBody()` copy no longer needed; later calls are no-ops. */
25
+ releaseBody(copy: Record<string, unknown>): void;
22
26
  }
23
27
 
24
28
  export function createProtocolEnvelope(input: {
@@ -28,16 +32,30 @@ export function createProtocolEnvelope(input: {
28
32
  }): ProtocolEnvelope {
29
33
  const { inbound, body, translatorBudget } = input;
30
34
  let features: ReadonlySet<ProtocolFeature> | undefined;
35
+ // The copy's own size may change once its holder rewrites it, so the charge is remembered.
36
+ const charged = new WeakMap<object, number>();
31
37
  return {
32
38
  inbound,
33
39
  features() {
34
40
  features ??= featuresFromBody(inbound, body);
35
41
  return features;
36
42
  },
43
+ readBody() {
44
+ return body;
45
+ },
37
46
  freshBody() {
38
47
  // Charged before the copy exists, so an over-budget request fails without allocating it.
39
- translatorBudget.chargeRetained(jsonUtf8Bytes(body), { kind: "request_copies" });
40
- return structuredClone(body);
48
+ const bytes = jsonUtf8Bytes(body);
49
+ translatorBudget.chargeRetained(bytes, { kind: "request_copies" });
50
+ const copy = structuredClone(body);
51
+ charged.set(copy, bytes);
52
+ return copy;
53
+ },
54
+ releaseBody(copy) {
55
+ const bytes = charged.get(copy);
56
+ if (bytes === undefined) return;
57
+ charged.delete(copy);
58
+ translatorBudget.releaseRetained(bytes, { kind: "request_copies" });
41
59
  },
42
60
  };
43
61
  }
@@ -9,6 +9,7 @@ import { routedProviderConfig } from "./routed-config";
9
9
  import { OPENCODE_GO_SESSION_HEADER } from "./opencode-go-transport";
10
10
  import { resolveProviderTransport, XAI_GROK_COMPATIBILITY, type OcxProviderTransport } from "./xai-transport";
11
11
  import { captureProviderApiKeySelection } from "./api-key-selection-capture";
12
+ import { vertexEnvironmentKeyIsCurrent } from "./vertex-environment-authority";
12
13
 
13
14
  export { captureProviderApiKeySelection } from "./api-key-selection-capture";
14
15
 
@@ -35,7 +36,8 @@ function currentKeyProvider(config: OcxConfig, name: string, selection?: Provide
35
36
  || row.apiKeyPool?.length && row.apiKeyPool.every(entry => entry.disabled)) return null;
36
37
  const current = routedProviderConfig(name, { ...row, _apiKeyAttempt: selection?.distributed ? selection : undefined });
37
38
  if (current.authMode === "oauth" || current.authMode === "forward") return null;
38
- if (current.authMode === "key" && !current.keyOptional && !current.apiKey?.trim()) return null;
39
+ if (current.authMode === "key" && !current.keyOptional && !current.apiKey?.trim()
40
+ && !(current.adapter === "google" && current.googleMode === "vertex")) return null;
39
41
  return current;
40
42
  }
41
43
 
@@ -61,10 +63,14 @@ function matchesConfiguredSelection(
61
63
  const expected = routedProvider._apiKeyAttempt;
62
64
  const current = currentKeyProvider(config, name, expected, allowCooling);
63
65
  return current !== null && expected !== undefined
66
+ && vertexEnvironmentKeyIsCurrent(expected, current)
64
67
  && (expected.distributed === true || matchesSelection(config.providers[name]!, expected))
65
68
  && current.apiKey === routedProvider.apiKey
66
69
  && current.authMode === routedProvider.authMode
67
- && current.baseUrl === routedProvider.baseUrl;
70
+ && current.baseUrl === routedProvider.baseUrl
71
+ && (current.googleMode !== "vertex" && routedProvider.googleMode !== "vertex"
72
+ || current.googleMode === routedProvider.googleMode && current.project === routedProvider.project
73
+ && current.location === routedProvider.location);
68
74
  }
69
75
 
70
76
  /** Rebuild transport from the already committed choice; never allocate or publish a selection. */
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The last Claude Code subscription observation, persisted beside the proxy's other state.
3
+ *
4
+ * The read model lives here rather than in `src/adapters/claude-cli/usage-admission.ts` because
5
+ * `/api/provider-quotas` reads it as well, and `src/providers/quota.ts` is statically reachable
6
+ * from `src/server/responses/core.ts`: importing the adapter would drag its token/Keychain and
7
+ * child-process layer into every install. The adapter owns identity resolution and gating; this
8
+ * module owns only the file.
9
+ */
10
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ import { getConfigDir } from "../config/paths";
13
+ import type { ProviderQuota } from "./quota-types";
14
+
15
+ export type ClaudeUsageSnapshot = {
16
+ identity: string;
17
+ checkedAt: number;
18
+ quota?: ProviderQuota;
19
+ refusalUntil?: number;
20
+ };
21
+
22
+ export type ClaudeUsageObservation = Readonly<ClaudeUsageSnapshot>;
23
+
24
+ const memory = new Map<string, ClaudeUsageSnapshot>();
25
+ let signedInIdentity: string | null = null;
26
+
27
+ /** The adapter records every sign-in read here, so a published report can tell it was superseded. */
28
+ export function recordClaudeSignedInIdentity(identity: string | null): void { signedInIdentity = identity; }
29
+
30
+ /** The hashed key of the last sign-in read, or null when signed out, unreadable or not yet read. */
31
+ export function claudeSignedInIdentity(): string | null { return signedInIdentity; }
32
+
33
+ export function claudeUsageStatePath(statePath?: string): string {
34
+ return statePath ?? join(getConfigDir(), "claude-usage-admission.json");
35
+ }
36
+
37
+ function finite(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value); }
38
+
39
+ /**
40
+ * The admission file, or undefined when it is missing or any field fails validation. A rejected
41
+ * file reads as "never checked", so a corrupt cache can neither admit nor refuse a launch.
42
+ */
43
+ export function loadClaudeUsageSnapshot(path: string): ClaudeUsageSnapshot | undefined {
44
+ try {
45
+ const saved = JSON.parse(readFileSync(path, "utf8"));
46
+ if (typeof saved.identity !== "string" || !Number.isFinite(saved.checkedAt)) return;
47
+ if (saved.refusalUntil !== undefined && !finite(saved.refusalUntil)) return;
48
+ if (saved.quota !== undefined) {
49
+ const q = saved.quota;
50
+ if (!q || typeof q !== "object" || !finite(q.updatedAt)) return;
51
+ for (const field of ["fiveHourPercent", "fiveHourResetAt", "weeklyPercent", "weeklyResetAt"])
52
+ if (q[field] !== undefined && !finite(q[field])) return;
53
+ if (q.customWindows !== undefined && (!Array.isArray(q.customWindows) || !q.customWindows.every((w: unknown) => {
54
+ if (!w || typeof w !== "object") return false;
55
+ const row = w as Record<string, unknown>;
56
+ return typeof row.label === "string" && finite(row.percent) && (row.resetAt === undefined || finite(row.resetAt));
57
+ }))) return;
58
+ }
59
+ return saved;
60
+ } catch { /* Missing or malformed cache is unknown, never proof of capacity. */ }
61
+ return undefined;
62
+ }
63
+
64
+ /**
65
+ * Records the snapshot in memory first, then atomically on disk (temp file plus rename, mode 0600).
66
+ * A failed disk write is swallowed: the in-memory copy still gates this process's launches.
67
+ */
68
+ export function saveClaudeUsageSnapshot(path: string, snapshot: ClaudeUsageSnapshot): void {
69
+ memory.set(path, snapshot);
70
+ try {
71
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
72
+ const temp = `${path}.${process.pid}.tmp`;
73
+ writeFileSync(temp, JSON.stringify(snapshot) + "\n", { mode: 0o600 });
74
+ renameSync(temp, path);
75
+ } catch { /* Memory still suppresses launches; no secrets or upstream text are persisted. */ }
76
+ }
77
+
78
+ /** Every snapshot this process can see for the path: the admission file and the in-memory write. */
79
+ export function readClaudeUsageSnapshots(path: string): ClaudeUsageSnapshot[] {
80
+ return [loadClaudeUsageSnapshot(path), memory.get(path)]
81
+ .filter((snapshot): snapshot is ClaudeUsageSnapshot => snapshot !== undefined);
82
+ }
83
+
84
+ /**
85
+ * The newest recorded usage snapshot, from memory or the admission file, optionally only for one
86
+ * account. Read-only: it resolves no sign-in (no Keychain read), runs no probe and writes nothing.
87
+ * `identity` is the admission's own SHA-256 account key, never the account uuid itself.
88
+ */
89
+ export function peekClaudeUsageObservation(deps: { statePath?: string; identity?: string } = {}): ClaudeUsageObservation | null {
90
+ const rows = readClaudeUsageSnapshots(claudeUsageStatePath(deps.statePath))
91
+ .filter(row => deps.identity === undefined || row.identity === deps.identity);
92
+ return rows.sort((a, b) => b.checkedAt - a.checkedAt)[0] ?? null;
93
+ }
@@ -130,15 +130,32 @@ export async function resolveCopilotAuto(provider: OcxProviderConfig, requestedM
130
130
  let models: CopilotModel[];
131
131
  try { models = await fetchCopilotAutoModels(transport, signal, beforeSend, 60_000, concurrency); }
132
132
  catch (error) {
133
- if (signal?.aborted || error instanceof ProviderOutboundSendCancelledError) throw error;
133
+ if (signal?.aborted) throw error;
134
+ // A manual account switch makes `beforeSend` return false, which cancels this
135
+ // control-plane send. That is not a client abort: fall back to the requested model
136
+ // so the dispatch path revalidates the selection and rebuilds on the new account.
137
+ if (error instanceof ProviderOutboundSendCancelledError) {
138
+ return { provider: transport, modelId: requestedModel, auto: false };
139
+ }
134
140
  // Permission discovery is additive for legacy paid configurations. A temporary
135
141
  // discovery outage must not turn a previously usable named route into a refusal.
136
142
  return { provider: transport, modelId: requestedModel, auto: false };
137
143
  }
138
144
  if (!copilotRequiresAuto(provider, models))
139
145
  return { provider: transport, modelId: requestedModel, auto: false };
140
- const session = await requestJson(transport, "/models/session", signal,
141
- { auto_mode: { model_hints: ["auto"] } }, undefined, beforeSend, concurrency);
146
+ // The same authority fence guards the later control-plane sends: a manual switch that
147
+ // lands during the session or intent step falls back too, so dispatch rebuilds on the
148
+ // new account instead of failing the whole negotiation. A client abort still rejects.
149
+ const fallBackOnSwitch = (error: unknown) => {
150
+ if (!signal?.aborted && error instanceof ProviderOutboundSendCancelledError)
151
+ return { provider: transport, modelId: requestedModel, auto: false } as const;
152
+ throw error;
153
+ };
154
+ let session: Awaited<ReturnType<typeof requestJson>>;
155
+ try {
156
+ session = await requestJson(transport, "/models/session", signal,
157
+ { auto_mode: { model_hints: ["auto"] } }, undefined, beforeSend, concurrency);
158
+ } catch (error) { return fallBackOnSwitch(error); }
142
159
  const pool = strings(session.available_models);
143
160
  if (typeof session.session_token !== "string" || !session.session_token || session.session_token.length > 32_768 || !/^[\x21-\x7e]+$/.test(session.session_token) || !pool.length)
144
161
  throw new Error("GitHub Copilot Auto session omitted its routing credentials");
@@ -153,8 +170,11 @@ export async function resolveCopilotAuto(provider: OcxProviderConfig, requestedM
153
170
  ? typeof lastUser.content === "string" ? lastUser.content : lastUser.content.flatMap(/** Extract text parts for intent negotiation without forwarding image or other multimodal payloads. */
154
171
  part => part.type === "text" ? [part.text] : []).join("\n")
155
172
  : "";
156
- const intent = await requestJson(transport, "/models/session/intent", signal,
157
- { prompt: prompt.slice(0, 32_768), available_models: pool }, session.session_token, beforeSend, concurrency);
173
+ let intent: Awaited<ReturnType<typeof requestJson>>;
174
+ try {
175
+ intent = await requestJson(transport, "/models/session/intent", signal,
176
+ { prompt: prompt.slice(0, 32_768), available_models: pool }, session.session_token, beforeSend, concurrency);
177
+ } catch (error) { return fallBackOnSwitch(error); }
158
178
  const modelId = strings(intent.candidate_models).find(/** Choose the first server-ranked candidate that belongs to this credential-bound session pool. */
159
179
  candidate => pool.includes(candidate));
160
180
  if (!modelId) throw new Error("GitHub Copilot Auto intent returned no eligible model");
@@ -0,0 +1,94 @@
1
+ import type { RequestFailureCause } from "../usage/telemetry-contract";
2
+
3
+ /**
4
+ * Meta's Muse Code subscription refusal (#8352).
5
+ *
6
+ * A Muse Code subscription key is valid, and Meta scopes it to the Muse Code client. Every request
7
+ * from another client is refused with HTTP 403 and one fixed sentence, so the credential is not
8
+ * rejected and no login can lift the restriction. Classifying it as `permission_denied` /
9
+ * `credential-rejected` sent operators to re-authenticate a key that works exactly as Meta sold it;
10
+ * the refusal is a plan restriction whose only remedy is a pay-as-you-go key.
11
+ *
12
+ * The match is deliberately narrow, in the shape of `anthropic-billing-refusal.ts`: a 403, an
13
+ * OpenAI-compatible `error` envelope, and that whole sentence. A missed match leaves the turn
14
+ * failing with Meta's own text, which is already legible; a loose match would relabel an unrelated
15
+ * permission denial that the operator fixes another way.
16
+ */
17
+
18
+ /** The envelope and message are upstream-controlled input; this bounds what is read. */
19
+ const MAX_REFUSAL_CHARS = 8 * 1024;
20
+
21
+ /** Meta's two sentences, whole. A suffix, prefix, or reworded copy is a different refusal. */
22
+ const PLAN_REFUSAL = /^This API key is billed to a Muse Code subscription\. Muse Code subscriptions cover requests from the Muse Code client only\. Use it in Muse Code, or use a pay-as-you-go API key for other clients\.?$/i;
23
+
24
+ /** Classes Meta has been observed to put on this refusal; anything else is a different verdict. */
25
+ const PERMISSION_TYPES = new Set(["permission_error", "permission_denied", "invalid_request_error"]);
26
+ const PERMISSION_CODES = new Set(["permission_denied", "permission_error", "subscription_required", "forbidden"]);
27
+
28
+ /**
29
+ * The one sentence a client sees instead of Meta's refusal.
30
+ *
31
+ * It names the restriction, the fact that no retry or re-login changes it, and the supported path.
32
+ * It is also a proxy literal that later classification passes recognize verbatim, so the Chat and
33
+ * Anthropic formatters cannot fold it back into `permission_denied`.
34
+ */
35
+ export const META_MUSE_PLAN_REFUSAL_MESSAGE = "Meta rejected this request because the configured key is billed to a Muse Code subscription, and Meta restricts Muse Code subscription keys to the Muse Code client. This is a plan restriction on a valid credential, not an expired one, so a new login cannot lift it. Use a pay-as-you-go Meta API key with the meta-model provider instead (export it as META_MODEL_API_KEY); OpenCodex cannot serve this request with a Muse Code subscription key.";
36
+
37
+ function record(value: unknown): value is Record<string, unknown> {
38
+ return value !== null && typeof value === "object" && !Array.isArray(value);
39
+ }
40
+
41
+ /** Only a 403 error envelope carrying Meta's whole sentence is evidence. */
42
+ export function isMetaMusePlanRefusal(status: number, payload: unknown): boolean {
43
+ if (status !== 403 || !record(payload) || !record(payload.error)) return false;
44
+ const error = payload.error;
45
+ if (typeof error.message !== "string" || error.message.length > MAX_REFUSAL_CHARS) return false;
46
+ if (error.type != null && (typeof error.type !== "string" || !PERMISSION_TYPES.has(error.type))) return false;
47
+ if (error.code != null && (typeof error.code !== "string" || !PERMISSION_CODES.has(error.code))) return false;
48
+ return PLAN_REFUSAL.test(error.message.trim());
49
+ }
50
+
51
+ /**
52
+ * The same evidence after HTTP error formatting, which frames the body as `Provider error 403: …`.
53
+ * A bare sentence body is accepted too: the refusal is the whole payload either way, and the
54
+ * sentence is the only thing that grants the verdict.
55
+ */
56
+ export function isMetaMusePlanFailure(status: number, message: string): boolean {
57
+ if (status !== 403 || typeof message !== "string" || message.length > MAX_REFUSAL_CHARS) return false;
58
+ let text = message.trim();
59
+ // This proxy's own copy re-enters later formatters; keep it in the same class without re-reading
60
+ // upstream bytes.
61
+ if (text === META_MUSE_PLAN_REFUSAL_MESSAGE) return true;
62
+ const prefix = `Provider error ${status}: `;
63
+ if (text.startsWith(prefix)) text = text.slice(prefix.length).trim();
64
+ if (text === META_MUSE_PLAN_REFUSAL_MESSAGE) return true;
65
+ try {
66
+ const payload: unknown = JSON.parse(text);
67
+ if (isMetaMusePlanRefusal(status, payload)) return true;
68
+ // The proxy's own error envelope carrying its own sentence: a later pass that re-parses the
69
+ // rewritten body keeps the class.
70
+ if (record(payload) && record(payload.error) && payload.error.message === META_MUSE_PLAN_REFUSAL_MESSAGE) return true;
71
+ } catch {
72
+ // A non-JSON body falls through to the whole-sentence test below.
73
+ }
74
+ return PLAN_REFUSAL.test(text);
75
+ }
76
+
77
+ /**
78
+ * Stamp the plan-restriction cause on a request row and return the client sentence, or undefined
79
+ * for any other failure.
80
+ *
81
+ * The cause is stamped at the site that proved it: the status alone cannot tell this 403 from a
82
+ * rejected credential, and `quota-exhausted` is the closed roster's plan/entitlement class, whose
83
+ * resend verdict is `refused-futile`. `causeHint` outranks the status table in
84
+ * `deriveRequestFailureCause`, so both the row and the attempt report the plan class.
85
+ */
86
+ export function stampMetaMusePlanRefusal(
87
+ logCtx: { causeHint?: RequestFailureCause },
88
+ status: number,
89
+ bodyText: string,
90
+ ): string | undefined {
91
+ if (!isMetaMusePlanFailure(status, bodyText)) return undefined;
92
+ logCtx.causeHint = "quota-exhausted";
93
+ return META_MUSE_PLAN_REFUSAL_MESSAGE;
94
+ }
@@ -103,6 +103,8 @@ export const PROVIDER_MODEL_RENAME_ROLES = {
103
103
  modelSupportsVerbosity: "record",
104
104
  supportsVerbosity: "none",
105
105
  modelReasoningSummaryDelivery: "record",
106
+ thinkingDisplay: "none",
107
+ modelThinkingDisplay: "record",
106
108
  modelPreferHostedTools: "record",
107
109
  supportsOpenAiWebSearchToolFields: "none",
108
110
  xaiResponsesXSearch: "none",
@@ -119,6 +121,7 @@ export const PROVIDER_MODEL_RENAME_ROLES = {
119
121
  noTemperatureModels: "list",
120
122
  noTopPModels: "list",
121
123
  noStopModels: "list",
124
+ arkKimiResponsesModels: "list",
122
125
  noPenaltyModels: "list",
123
126
  noStructuredOutputModels: "list",
124
127
  noJsonSchemaModels: "list",
@@ -24,7 +24,13 @@ async function quotaFetch(providerName: string, config: OcxProviderConfig, url:
24
24
  }
25
25
 
26
26
  const KIMI_CODE_BASE_URL = "https://api.kimi.com/coding/v1";
27
- const KIMI_CODE_USAGE_URL = `${KIMI_CODE_BASE_URL}/usages`;
27
+ /**
28
+ * Kimi's regional (kimi.ai) Coding API. Its `/usages` answers a Coding Plan API key the same way
29
+ * the kimi.com origin does (#8332). Only key auth may use it: the probe then calls the origin that
30
+ * already receives this key for inference, so it adds no credential destination. OAuth tokens
31
+ * stay on the kimi.com origin they were issued for.
32
+ */
33
+ const KIMI_CODE_REGIONAL_BASE_URL = "https://api.kimi.ai/coding/v1";
28
34
  const COMMAND_CODE_BASE_URL = "https://api.commandcode.ai";
29
35
  const COMMAND_CODE_WHOAMI_URL = `${COMMAND_CODE_BASE_URL}/alpha/whoami`;
30
36
  const COMMAND_CODE_CREDITS_URL = `${COMMAND_CODE_BASE_URL}/alpha/billing/credits`;
@@ -1119,6 +1125,18 @@ export function isCanonicalKimiCodeBaseUrl(baseUrl: string): boolean {
1119
1125
  return normalizedBaseUrl(baseUrl) === KIMI_CODE_BASE_URL;
1120
1126
  }
1121
1127
 
1128
+ /**
1129
+ * The Kimi Coding origin whose `/usages` a quota probe may call with this provider's bearer, or
1130
+ * null. It is always the configured inference origin, matched exactly against Kimi's own origins,
1131
+ * so a user-edited or lookalike host never receives the credential.
1132
+ */
1133
+ function kimiCodeQuotaBaseUrl(config: Pick<OcxProviderConfig, "baseUrl" | "authMode">): string | null {
1134
+ const normalized = normalizedBaseUrl(config.baseUrl);
1135
+ if (normalized === KIMI_CODE_BASE_URL) return normalized;
1136
+ if (normalized === KIMI_CODE_REGIONAL_BASE_URL && (config.authMode ?? "key") === "key") return normalized;
1137
+ return null;
1138
+ }
1139
+
1122
1140
  export function isCanonicalCommandCodeBaseUrl(baseUrl: string): boolean {
1123
1141
  const normalized = normalizedBaseUrl(baseUrl);
1124
1142
  // OAuth preset points at the API root; the Provider-API preset at /provider/v1.
@@ -1270,9 +1288,10 @@ async function resolveKimiQuotaBearer(config: OcxProviderConfig, accountId?: str
1270
1288
 
1271
1289
  export async function fetchKimiQuota(provider: string, config: OcxProviderConfig, accessToken: string): Promise<ProviderQuotaReport | null> {
1272
1290
  // Never release credentials to a user-edited or lookalike provider host.
1273
- if (!isCanonicalKimiCodeBaseUrl(config.baseUrl)) return null;
1291
+ const baseUrl = kimiCodeQuotaBaseUrl(config);
1292
+ if (!baseUrl) return null;
1274
1293
  if (!accessToken) return null;
1275
- const response = await quotaFetch(provider, config, KIMI_CODE_USAGE_URL, {
1294
+ const response = await quotaFetch(provider, config, `${baseUrl}/usages`, {
1276
1295
  headers: { Accept: "application/json", Authorization: `Bearer ${accessToken}` },
1277
1296
  redirect: "error",
1278
1297
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
@@ -1435,7 +1454,7 @@ type KeyQuotaReader = (name: string, provider: OcxProviderConfig) => Promise<Pro
1435
1454
  /** Same selector drives cheap capabilities and uncached reads; never resolves credentials. */
1436
1455
  export function keyQuotaReaderForProvider(name: string, provider: OcxProviderConfig): KeyQuotaReader | null {
1437
1456
  if (provider.disabled === true || (provider.authMode ?? "key") !== "key") return null;
1438
- if (isCanonicalKimiCodeBaseUrl(provider.baseUrl)) {
1457
+ if (kimiCodeQuotaBaseUrl(provider)) {
1439
1458
  return async (id, config) => {
1440
1459
  const bearer = await resolveKimiQuotaBearer(config);
1441
1460
  return bearer ? fetchKimiQuota(id, config, bearer) : null;