@bitkyc08/opencodex 2.94.0 → 2.95.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 (249) hide show
  1. package/gui/dist/assets/App-8yedBkhm.js +58 -0
  2. package/gui/dist/assets/App-B4j-Txmb.css +1 -0
  3. package/gui/dist/assets/{Tray-CZatQdoF.js → Tray-erSMzxPG.js} +1 -1
  4. package/gui/dist/assets/index-D7DCm5eQ.js +94 -0
  5. package/gui/dist/assets/quota-summary-BK4VuQNc.js +1 -0
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/anthropic.ts +10 -3
  9. package/src/adapters/command-code-project-context.ts +3 -3
  10. package/src/adapters/kiro/adapter.ts +4 -1
  11. package/src/adapters/kiro/stream.ts +1 -0
  12. package/src/adapters/kiro-events.ts +1 -0
  13. package/src/adapters/openai-chat/messages.ts +20 -7
  14. package/src/adapters/openai-chat/passthrough.ts +4 -2
  15. package/src/adapters/openai-chat/single-system.ts +24 -0
  16. package/src/adapters/openai-responses/muse-tool-catalog.ts +87 -0
  17. package/src/adapters/openai-responses/passthrough.ts +42 -7
  18. package/src/adapters/openai-responses/prompt-cache.ts +3 -1
  19. package/src/adapters/openai-responses/request-strips.ts +23 -4
  20. package/src/adapters/openai-responses/tool-output-recovery.ts +21 -8
  21. package/src/adapters/openai-responses/tool-schema.ts +20 -8
  22. package/src/adapters/opencode-go-additional-tools.ts +39 -6
  23. package/src/adapters/routed-agent-messages.ts +3 -0
  24. package/src/adapters/xai-web-search.ts +6 -3
  25. package/src/adapters/zed-additional-tools.ts +7 -7
  26. package/src/adapters/zed.ts +1 -6
  27. package/src/advisor/consult.ts +22 -10
  28. package/src/advisor/runtime.ts +10 -4
  29. package/src/bridge/max-output-completion.ts +41 -0
  30. package/src/bridge/response-json.ts +9 -4
  31. package/src/bridge/sse.ts +13 -2
  32. package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +5 -0
  33. package/src/chatgpt/app-server-shim/launcher.ts +40 -6
  34. package/src/claude/compatibility.ts +5 -1
  35. package/src/claude/desktop-3p.ts +27 -6
  36. package/src/claude/desktop-model-visibility.ts +141 -0
  37. package/src/claude/desktop-remote-store-io.ts +8 -8
  38. package/src/claude/inbound-content-options.ts +11 -1
  39. package/src/claude/intercept/proxy-auth.ts +16 -16
  40. package/src/cli/account-main.ts +3 -2
  41. package/src/cli/capabilities-provider-models.ts +7 -0
  42. package/src/cli/chatgpt-command.ts +1 -1
  43. package/src/cli/codex-launcher.ts +20 -8
  44. package/src/cli/codex-shim-autorestore.ts +19 -1
  45. package/src/cli/dispatch.ts +6 -6
  46. package/src/cli/doctor.ts +5 -5
  47. package/src/cli/index.ts +4 -9
  48. package/src/cli/init.ts +2 -2
  49. package/src/cli/internal-command.ts +29 -2
  50. package/src/cli/provider-cc-switch-import.ts +185 -0
  51. package/src/cli/provider.ts +5 -0
  52. package/src/cli/registry.ts +1 -0
  53. package/src/cli/restart-scope.ts +2 -2
  54. package/src/cli/root.ts +6 -6
  55. package/src/cli/stop-approval.ts +15 -1
  56. package/src/cli/v2.ts +69 -19
  57. package/src/client/machine-api.ts +2 -2
  58. package/src/clients/config-export.ts +14 -3
  59. package/src/codex/account-cooldown-response.ts +18 -0
  60. package/src/codex/app-server-restart-service.ts +2 -2
  61. package/src/codex/auth-api/login-flow.ts +2 -2
  62. package/src/codex/auth-api/pool-quota-probe.ts +2 -2
  63. package/src/codex/auth-context.ts +4 -4
  64. package/src/codex/catalog/bundled.ts +10 -3
  65. package/src/codex/catalog/metadata.ts +4 -5
  66. package/src/codex/catalog/native-omission.ts +28 -0
  67. package/src/codex/catalog/native-template.ts +58 -0
  68. package/src/codex/catalog/parsing.ts +3 -29
  69. package/src/codex/catalog/provider-models.ts +2 -1
  70. package/src/codex/catalog/retained-sync.ts +15 -5
  71. package/src/codex/catalog/write-audit.ts +18 -18
  72. package/src/codex/cli-install-provenance.ts +46 -45
  73. package/src/codex/cli-update-artifacts.ts +8 -6
  74. package/src/codex/cli-update-job-store-windows.ts +99 -27
  75. package/src/codex/cli-update-job-worker.ts +3 -11
  76. package/src/codex/cli-update-recovery.ts +54 -8
  77. package/src/codex/cli-update-selection-gate.ts +74 -4
  78. package/src/codex/cli-windows-plan-provenance.ts +37 -19
  79. package/src/codex/codex-home-owner.ts +9 -8
  80. package/src/codex/convergence.ts +13 -3
  81. package/src/codex/coordinator-doctor.ts +14 -8
  82. package/src/codex/desktop-app/handoff.ts +1 -1
  83. package/src/codex/desktop-app-restart.ts +11 -1
  84. package/src/codex/exec-boundary.ts +26 -5
  85. package/src/codex/history-provider.ts +11 -10
  86. package/src/codex/inject/bounded-config-reader.ts +14 -13
  87. package/src/codex/main-account.ts +6 -6
  88. package/src/codex/native-main-lock-file.ts +13 -12
  89. package/src/codex/native-residue.ts +18 -14
  90. package/src/codex/orca-auth-source.ts +8 -7
  91. package/src/codex/quota-types.ts +5 -0
  92. package/src/codex/quota.ts +49 -7
  93. package/src/codex/role-auto-assign.ts +50 -26
  94. package/src/codex/role-capability.ts +160 -0
  95. package/src/codex/role-sizing.ts +24 -6
  96. package/src/codex/routing/cooldown-math.ts +3 -2
  97. package/src/codex/runtime.ts +43 -3
  98. package/src/codex/shim-fingerprint.ts +11 -9
  99. package/src/codex/shim-inspect.ts +3 -2
  100. package/src/codex/shim-restore-lock.ts +11 -14
  101. package/src/codex/shim-state-file.ts +22 -14
  102. package/src/codex/shim-wrapper-write.ts +7 -6
  103. package/src/codex/shim.ts +25 -2
  104. package/src/codex/transition-state.ts +5 -4
  105. package/src/combos/failover.ts +43 -4
  106. package/src/config/atomic-write.ts +38 -7
  107. package/src/config/diagnostics.ts +3 -0
  108. package/src/config/initialize.ts +6 -6
  109. package/src/config/load-degrade.ts +2 -0
  110. package/src/config/process-state.ts +23 -5
  111. package/src/config/salvage.ts +1 -0
  112. package/src/config/schema/config-schema.ts +29 -1
  113. package/src/config/schema/leaf-validators.ts +7 -0
  114. package/src/config/schema/workflow-budget.ts +43 -0
  115. package/src/config/tracked-runtime-inspection.ts +188 -0
  116. package/src/generated/compatibility-version.json +313 -213
  117. package/src/integrations/aside-profile-context.ts +1 -1
  118. package/src/integrations/droid-settings.ts +4 -4
  119. package/src/integrations/hermes-profiles.ts +3 -3
  120. package/src/lib/bounded-file-read.ts +3 -9
  121. package/src/lib/bun-runtime-preflight.ts +9 -8
  122. package/src/lib/file-identity.ts +15 -0
  123. package/src/lib/local-chat-completion.ts +8 -6
  124. package/src/lib/local-destinations.ts +32 -3
  125. package/src/lib/redact-folding.ts +9 -0
  126. package/src/lib/spend-pool-alias-validation.ts +6 -6
  127. package/src/lib/state-store-registrations.ts +2 -0
  128. package/src/lib/test-home-guard.ts +37 -9
  129. package/src/lib/windows-secret-acl.ts +47 -29
  130. package/src/lib/workflow-budget-config.ts +39 -0
  131. package/src/local-credentials/generation.ts +6 -2
  132. package/src/local-credentials/inventory.ts +132 -8
  133. package/src/messaging/remote-forward-failure.ts +35 -0
  134. package/src/messaging/remote-ports.ts +27 -5
  135. package/src/messaging/remote-process.ts +30 -4
  136. package/src/messaging/remote-tunnels.ts +80 -15
  137. package/src/oauth/antigravity-discovery-diagnostics.ts +65 -0
  138. package/src/oauth/google-antigravity.ts +23 -10
  139. package/src/oauth/index.ts +2 -0
  140. package/src/oauth/kiro-device-login.ts +87 -30
  141. package/src/oauth/kiro-iam-identity-center.ts +107 -0
  142. package/src/oauth/store.ts +9 -7
  143. package/src/providers/account-quota-disk.ts +18 -4
  144. package/src/providers/cc-switch-import-bytes.ts +991 -0
  145. package/src/providers/cc-switch-import-source.ts +1083 -0
  146. package/src/providers/cc-switch-import.ts +942 -0
  147. package/src/providers/derive.ts +6 -0
  148. package/src/providers/model-discovery-diagnostic.ts +4 -0
  149. package/src/providers/model-discovery.ts +4 -4
  150. package/src/providers/model-rename-fields.ts +2 -0
  151. package/src/providers/model-rename-migration.ts +41 -6
  152. package/src/providers/quota/report-cache.ts +17 -4
  153. package/src/providers/quota.ts +2 -2
  154. package/src/providers/reasoning-metadata.ts +31 -15
  155. package/src/providers/registry/entries-core.ts +1 -1
  156. package/src/providers/registry/entries-extended.ts +1 -1
  157. package/src/providers/registry/model-ids.ts +1 -0
  158. package/src/providers/registry/model-seeds.ts +2 -1
  159. package/src/providers/registry/types.ts +3 -1
  160. package/src/providers/resolved-model-policy.ts +2 -2
  161. package/src/providers/routed-config.ts +2 -0
  162. package/src/providers/stale-model-roster-migration.ts +5 -1
  163. package/src/providers/xai-transport.ts +4 -4
  164. package/src/remote-control/workspace-codex-runtime.ts +2 -2
  165. package/src/remote-control/workspace-executor.ts +14 -13
  166. package/src/responses/custom-tool-compat.ts +2 -1
  167. package/src/responses/item-provenance.ts +79 -0
  168. package/src/responses/namespace-tool-compat.ts +21 -3
  169. package/src/router.ts +21 -2
  170. package/src/routing/analytics.ts +3 -5
  171. package/src/routing/fallback-policy.ts +7 -3
  172. package/src/routing/health.ts +5 -3
  173. package/src/routing/history/build-file.ts +6 -0
  174. package/src/routing/history/indexer.ts +158 -31
  175. package/src/routing/history/ingest.ts +1 -1
  176. package/src/routing/history/integrity.ts +208 -0
  177. package/src/routing/history/rebuild-job.ts +20 -6
  178. package/src/routing/history/rebuild-protocol.ts +2 -1
  179. package/src/routing/history/rebuild-worker.ts +18 -0
  180. package/src/routing/history/sqlite-errors.ts +9 -0
  181. package/src/server/admission-model-scope.ts +21 -4
  182. package/src/server/advisor-admission-scope.ts +29 -0
  183. package/src/server/auth-cors.ts +5 -2
  184. package/src/server/capture-admission-policy.ts +91 -0
  185. package/src/server/chat-completions.ts +33 -7
  186. package/src/server/claude-messages.ts +90 -2
  187. package/src/server/codex-model-list.ts +2 -1
  188. package/src/server/configured-credentials.ts +5 -0
  189. package/src/server/index/serve-options.ts +12 -2
  190. package/src/server/index/websocket-handler.ts +3 -0
  191. package/src/server/management/agent-settings-routes.ts +34 -9
  192. package/src/server/management/codex-agent-role-routes.ts +1 -0
  193. package/src/server/management/codex-role-auto-assign.ts +50 -6
  194. package/src/server/management/config-routes.ts +15 -4
  195. package/src/server/management/context.ts +3 -0
  196. package/src/server/management/native-integration-routes.ts +22 -0
  197. package/src/server/management/oauth-account-routes.ts +20 -4
  198. package/src/server/management/provider-overwrite-carry.ts +21 -0
  199. package/src/server/management/provider-routes.ts +3 -1
  200. package/src/server/management/route-registry.ts +2 -0
  201. package/src/server/management/shared.ts +17 -1
  202. package/src/server/management/workflow-budget-routes.ts +70 -3
  203. package/src/server/messages-native-eligibility.ts +6 -5
  204. package/src/server/messages-native-scope.ts +6 -1
  205. package/src/server/messages-shared.ts +57 -17
  206. package/src/server/persistent-gui-session.ts +4 -4
  207. package/src/server/request-log.ts +30 -2
  208. package/src/server/responses/adapter-delivery.ts +4 -0
  209. package/src/server/responses/advisor-plan-slot.ts +4 -0
  210. package/src/server/responses/advisor-slot.ts +73 -46
  211. package/src/server/responses/codex-auth-error.ts +5 -1
  212. package/src/server/responses/combo-required-tool-contract.ts +27 -0
  213. package/src/server/responses/compact.ts +4 -1
  214. package/src/server/responses/core-combo-failure.ts +2 -0
  215. package/src/server/responses/core-combo.ts +66 -5
  216. package/src/server/responses/core-lifetime.ts +4 -0
  217. package/src/server/responses/core-options.ts +9 -0
  218. package/src/server/responses/core.ts +2 -0
  219. package/src/server/responses/jev-model-invoke.ts +4 -2
  220. package/src/server/responses/passthrough-dispatch.ts +5 -4
  221. package/src/server/responses/policy-fallback.ts +2 -0
  222. package/src/server/responses/request-prepare.ts +4 -5
  223. package/src/server/responses/request-send-budget.ts +2 -1
  224. package/src/server/responses/request-sidecar-auth.ts +1 -0
  225. package/src/server/responses/request-transport.ts +2 -3
  226. package/src/server/responses/run-turn-execution.ts +4 -0
  227. package/src/server/responses/sidecar-execution.ts +21 -5
  228. package/src/server/responses-snapshot-repair.ts +18 -4
  229. package/src/server/responses-undeclared-tool-guard.ts +4 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/service/state-lock.ts +12 -11
  232. package/src/service-manager-probe.ts +53 -8
  233. package/src/types/admission-policy.ts +13 -0
  234. package/src/types/config.ts +25 -0
  235. package/src/types/provider.ts +10 -0
  236. package/src/types/request.ts +7 -0
  237. package/src/types.ts +1 -0
  238. package/src/update/job.ts +20 -0
  239. package/src/update/worker-launch.ts +71 -1
  240. package/src/usage/log.ts +25 -4
  241. package/src/vision/index.ts +2 -0
  242. package/src/vision/plan.ts +4 -0
  243. package/src/vision/routed-describe.ts +38 -23
  244. package/src/web-search/loop.ts +104 -9
  245. package/src/web-search/parse.ts +10 -2
  246. package/gui/dist/assets/App-DMps4OLk.css +0 -1
  247. package/gui/dist/assets/App-DmvwlhQq.js +0 -58
  248. package/gui/dist/assets/index-3EPO_KbX.js +0 -94
  249. package/gui/dist/assets/quota-summary-BHvWg9mi.js +0 -1
@@ -43,6 +43,7 @@ import { loginKimi, refreshKimiToken } from "./kimi";
43
43
  import { loginNous, NousTokenError, refreshNousToken, clearNousRefreshIntent, RefreshIntentIOError } from "./nous";
44
44
  import { ChatGptTokenRequestError, ChatGptTokenError, loginChatGPT, refreshChatGPTToken, type ChatGPTLoginFlow } from "./chatgpt";
45
45
  import { loginAntigravity, refreshAntigravityToken } from "./google-antigravity";
46
+ import { AntigravityProjectDiscoveryError } from "./antigravity-discovery-diagnostics";
46
47
  import { loginCursor, refreshCursorToken } from "./cursor";
47
48
  import { loginZed, refreshZedToken } from "./zed";
48
49
  import { assertDevinCliAdoptionOwnership, loginDevin, refreshDevinToken } from "./devin";
@@ -512,6 +513,7 @@ class OAuthLoginSupersededError extends Error {
512
513
 
513
514
  /** Project arbitrary OAuth failures onto the small, stable public error vocabulary. */
514
515
  export function publicOAuthAuthenticationErrorMessage(error: unknown): string {
516
+ if (error instanceof AntigravityProjectDiscoveryError) return error.publicMessage;
515
517
  if (error instanceof MuseLoginError) return museLoginErrorMessage(error.kind, error.status);
516
518
  if (error instanceof OAuthMutationBusyError) {
517
519
  return error.message === "OAuth mutation queue wait timed out"
@@ -8,10 +8,11 @@ import { appendKiroAccountFromDeviceLogin, isStorableKiroClientPart, rollbackCre
8
8
  import type { OAuthCredentials } from "./types";
9
9
  import type { ManagementPrincipal } from "../server/management-auth";
10
10
  import type { OcxConfig } from "../types";
11
+ import { listKiroIamProfiles, parseKiroIamOptions, resolveKiroIamCredential, type KiroIamOptions, type KiroIamProfile } from "./kiro-iam-identity-center";
11
12
 
12
- export type KiroDeviceMethod = "builder-id" | "google" | "github";
13
+ export type KiroDeviceMethod = "builder-id" | "google" | "github" | "iam-identity-center";
13
14
  export type KiroDevicePrincipal = ManagementPrincipal;
14
- type State = "pending" | "done" | "failed" | "expired" | "cancelled";
15
+ type State = "pending" | "select-profile" | "done" | "failed" | "expired" | "cancelled";
15
16
  export interface KiroDeviceView {
16
17
  flowId: string;
17
18
  method: KiroDeviceMethod;
@@ -21,6 +22,7 @@ export interface KiroDeviceView {
21
22
  verificationUriComplete?: string;
22
23
  expiresAt?: number;
23
24
  warning?: "duplicate_profile_arn" | "manual_review_required";
25
+ profiles?: KiroIamProfile[];
24
26
  }
25
27
  interface Flow {
26
28
  view: KiroDeviceView;
@@ -36,8 +38,11 @@ interface Flow {
36
38
  commitAccepted?: boolean;
37
39
  terminalAt?: number;
38
40
  retentionTimer?: ReturnType<typeof setTimeout>;
41
+ expiryTimer?: ReturnType<typeof setTimeout>;
42
+ iam?: KiroIamOptions;
43
+ credential?: OAuthCredentials;
39
44
  }
40
- export type KiroDevicePost = (url: string, body: Record<string, unknown>) => Promise<Response>;
45
+ export type KiroDevicePost = (url: string, body: Record<string, unknown>, headers?: Record<string, string>) => Promise<Response>;
41
46
  const SOCIAL = "https://prod.us-east-1.auth.desktop.kiro.dev";
42
47
  const OIDC = "https://oidc.us-east-1.amazonaws.com";
43
48
  const MAX_KIRO_DEVICE_FLOWS = 4;
@@ -50,7 +55,7 @@ const USER_CODE = /^[A-Za-z0-9-]{4,32}$/;
50
55
  const CONTROL = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/;
51
56
  const flows = new Map<string, Flow>();
52
57
 
53
- async function defaultPost(url: string, body: Record<string, unknown>): Promise<Response> {
58
+ async function defaultPost(url: string, body: Record<string, unknown>, headers?: Record<string, string>): Promise<Response> {
54
59
  const configured = loadConfig().providers.kiro;
55
60
  return providerOutboundPost("kiro", {
56
61
  baseUrl: new URL(url).origin,
@@ -58,7 +63,7 @@ async function defaultPost(url: string, body: Record<string, unknown>): Promise<
58
63
  ...(configured?.noProxy ? { noProxy: configured.noProxy } : {}),
59
64
  ...(configured?.allowPrivateNetwork ? { allowPrivateNetwork: true } : {}),
60
65
  }, url, {
61
- headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(20_000),
66
+ headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body), signal: AbortSignal.timeout(20_000),
62
67
  });
63
68
  }
64
69
 
@@ -77,7 +82,7 @@ export function setKiroDevicePublishForTests(publish?: () => void | Promise<void
77
82
  publishConfig = publish ?? defaultPublishConfig;
78
83
  }
79
84
  export function clearKiroDeviceFlowsForTests(): void {
80
- for (const flow of flows.values()) clearTimeout(flow.retentionTimer);
85
+ for (const flow of flows.values()) { clearTimeout(flow.retentionTimer); clearTimeout(flow.expiryTimer); }
81
86
  flows.clear(); transport = defaultPost; setKiroDeviceClockForTests(); setKiroDevicePublishForTests();
82
87
  }
83
88
  export function kiroDeviceFlowCountForTests(): number { return flows.size; }
@@ -85,8 +90,8 @@ export function kiroDeviceFlowCountForTests(): number { return flows.size; }
85
90
  function object(value: unknown): Record<string, unknown> {
86
91
  return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
87
92
  }
88
- async function reply(url: string, body: Record<string, unknown>): Promise<{ status: number; data: Record<string, unknown>; errorType: string }> {
89
- const response = await transport(url, body);
93
+ async function reply(url: string, body: Record<string, unknown>, headers?: Record<string, string>): Promise<{ status: number; data: Record<string, unknown>; errorType: string }> {
94
+ const response = await transport(url, body, headers);
90
95
  // Unknown upstream bodies are bounded and never echoed into a response or error.
91
96
  const { bytes, oversized } = await readBoundedResponseBytes(response, {
92
97
  maxBytes: BOUNDED_BODY_MAX_BYTES, signal: AbortSignal.timeout(20_000),
@@ -98,13 +103,18 @@ async function reply(url: string, body: Record<string, unknown>): Promise<{ stat
98
103
  return { status: response.status, data, errorType: response.headers.get("x-amzn-errortype")?.split(":")[0] ?? "" };
99
104
  }
100
105
  function positive(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value) && value > 0; }
101
- function publicView(flow: Flow): KiroDeviceView { return { ...flow.view }; }
106
+ function publicView(flow: Flow): KiroDeviceView {
107
+ return { ...flow.view, ...(flow.view.profiles ? { profiles: flow.view.profiles.map(profile => ({ ...profile })) } : {}) };
108
+ }
109
+ function live(flow: Flow): boolean { return flow.view.state === "pending" || flow.view.state === "select-profile"; }
102
110
  function forgetFlow(id: string): void {
103
111
  const flow = flows.get(id);
104
112
  if (flow?.retentionTimer) clearTimeout(flow.retentionTimer);
113
+ if (flow?.expiryTimer) clearTimeout(flow.expiryTimer);
105
114
  flows.delete(id);
106
115
  }
107
116
  function terminal(flow: Flow, state: State, warning?: KiroDeviceView["warning"]): KiroDeviceView {
117
+ clearTimeout(flow.expiryTimer);
108
118
  flow.view.state = state;
109
119
  if (flow.terminalAt === undefined) {
110
120
  flow.terminalAt = clock();
@@ -118,16 +128,19 @@ function terminal(flow: Flow, state: State, warning?: KiroDeviceView["warning"])
118
128
  delete flow.clientId;
119
129
  delete flow.clientSecret;
120
130
  delete flow.configBaseline;
131
+ delete flow.credential;
132
+ delete flow.iam;
133
+ delete flow.view.profiles;
121
134
  return publicView(flow);
122
135
  }
123
136
  function pruneFlows(): void {
124
137
  const now = clock();
125
138
  for (const [id, flow] of flows) {
126
- if (flow.view.state === "pending" && now >= flow.deadline) terminal(flow, "expired");
139
+ if (live(flow) && now >= flow.deadline && !flow.commitAccepted) terminal(flow, "expired");
127
140
  if (flow.terminalAt !== undefined && now - flow.terminalAt >= TERMINAL_RETENTION_MS) forgetFlow(id);
128
141
  }
129
142
  while (flows.size >= MAX_KIRO_DEVICE_ENTRIES) {
130
- const oldest = [...flows].find(([, flow]) => flow.view.state !== "pending");
143
+ const oldest = [...flows].find(([, flow]) => !live(flow));
131
144
  if (!oldest) break;
132
145
  forgetFlow(oldest[0]);
133
146
  }
@@ -135,7 +148,7 @@ function pruneFlows(): void {
135
148
  function owned(flowId: string, principal: KiroDevicePrincipal): Flow | undefined {
136
149
  const flow = flows.get(flowId);
137
150
  if (!flow || flow.ownerPrincipal !== principal) return undefined;
138
- if (clock() >= flow.deadline) {
151
+ if (clock() >= flow.deadline && !flow.commitAccepted) {
139
152
  terminal(flow, "expired");
140
153
  forgetFlow(flowId);
141
154
  return undefined;
@@ -171,12 +184,21 @@ function viewFromAuthorization(flow: Flow, data: Record<string, unknown>, scale:
171
184
  ...(data.verificationUriComplete ? { verificationUriComplete: data.verificationUriComplete } : {}),
172
185
  expiresAt: flow.deadline,
173
186
  };
187
+ // An approved IAM grant may wait for a profile choice. Erase that staged credential at
188
+ // expiry even if its browser disappears and no further management request prunes flows.
189
+ flow.expiryTimer = setTimeout(() => {
190
+ if (flows.get(flow.view.flowId) === flow && live(flow) && !flow.commitAccepted) terminal(flow, "expired");
191
+ }, Math.max(0, flow.deadline - clock()));
192
+ flow.expiryTimer.unref();
174
193
  }
175
194
 
176
- export async function startKiroDeviceLogin(method: KiroDeviceMethod, principal: KiroDevicePrincipal, configBaseline?: OcxConfig): Promise<KiroDeviceView> {
195
+ export async function startKiroDeviceLogin(method: KiroDeviceMethod, principal: KiroDevicePrincipal, configBaseline?: OcxConfig,
196
+ iamInput?: unknown): Promise<KiroDeviceView> {
197
+ const iam = method === "iam-identity-center" ? parseKiroIamOptions(iamInput) : null;
198
+ if (method === "iam-identity-center" && !iam) throw new Error("Invalid Kiro IAM settings");
177
199
  // Reserve before the first await, so concurrent starts cannot evade the cap.
178
200
  pruneFlows();
179
- if ([...flows.values()].filter(flow => flow.view.state === "pending").length >= MAX_KIRO_DEVICE_FLOWS) {
201
+ if ([...flows.values()].filter(live).length >= MAX_KIRO_DEVICE_FLOWS) {
180
202
  throw new Error("Too many Kiro device logins in progress");
181
203
  }
182
204
  if (flows.size >= MAX_KIRO_DEVICE_ENTRIES) throw new Error("Too many Kiro device logins in progress");
@@ -185,12 +207,14 @@ export async function startKiroDeviceLogin(method: KiroDeviceMethod, principal:
185
207
  view: { flowId, method, state: "pending" }, ownerPrincipal: principal,
186
208
  nextPollAt: 0, intervalMs: 5_000, deadline: clock() + MAX_LIFETIME_MS,
187
209
  ...(configBaseline ? { configBaseline: structuredClone(configBaseline) } : {}),
210
+ ...(iam ? { iam } : {}),
188
211
  };
189
212
  flows.set(flowId, flow);
190
213
  let started = false;
191
214
  try {
192
- if (method === "builder-id") {
193
- const registration = await reply(`${OIDC}/client/register`, {
215
+ if (method === "builder-id" || iam) {
216
+ const oidc = iam ? `https://oidc.${iam.region}.amazonaws.com` : OIDC;
217
+ const registration = await reply(`${oidc}/client/register`, {
194
218
  clientName: "kiro-cli", clientType: "public",
195
219
  scopes: ["codewhisperer:completions", "codewhisperer:analysis", "codewhisperer:conversations"],
196
220
  });
@@ -198,8 +222,8 @@ export async function startKiroDeviceLogin(method: KiroDeviceMethod, principal:
198
222
  || !isStorableKiroClientPart(registration.data.clientSecret)) throw new Error("Kiro registration failed");
199
223
  flow.clientId = registration.data.clientId;
200
224
  flow.clientSecret = registration.data.clientSecret;
201
- const authorization = await reply(`${OIDC}/device_authorization`, {
202
- clientId: flow.clientId, clientSecret: flow.clientSecret, startUrl: "https://view.awsapps.com/start",
225
+ const authorization = await reply(`${oidc}/device_authorization`, {
226
+ clientId: flow.clientId, clientSecret: flow.clientSecret, startUrl: iam?.startUrl ?? "https://view.awsapps.com/start",
203
227
  });
204
228
  if (authorization.status < 200 || authorization.status >= 300) throw new Error("Kiro device authorization failed");
205
229
  viewFromAuthorization(flow, authorization.data, 1000);
@@ -227,9 +251,10 @@ async function poll(flow: Flow, principal: KiroDevicePrincipal): Promise<KiroDev
227
251
  const now = clock();
228
252
  flow.nextPollAt = now + flow.intervalMs;
229
253
  try {
230
- const builder = flow.view.method === "builder-id";
254
+ const builder = flow.view.method === "builder-id" || flow.view.method === "iam-identity-center";
255
+ const region = flow.iam?.region ?? "us-east-1";
231
256
  const result = builder
232
- ? await reply(`${OIDC}/token`, {
257
+ ? await reply(`https://oidc.${region}.amazonaws.com/token`, {
233
258
  clientId: flow.clientId, clientSecret: flow.clientSecret, deviceCode: flow.deviceCode,
234
259
  grantType: "urn:ietf:params:oauth:grant-type:device_code",
235
260
  })
@@ -261,15 +286,29 @@ async function poll(flow: Flow, principal: KiroDevicePrincipal): Promise<KiroDev
261
286
  expires: clock() + (positive(data.expiresIn) ? data.expiresIn * 1000 : 3600_000),
262
287
  source: "oauth",
263
288
  kiro: builder
264
- ? { clientId: flow.clientId, clientSecret: flow.clientSecret, ssoRegion: "us-east-1", apiRegion: "us-east-1" }
289
+ ? { clientId: flow.clientId, clientSecret: flow.clientSecret, ssoRegion: region, apiRegion: region }
265
290
  : { profileArn: data.profileArn as string, ssoRegion: "us-east-1", apiRegion: "us-east-1" },
266
291
  };
267
- const assertBeforePersist = () => {
268
- if (flows.get(flow.view.flowId) !== flow || flow.ownerPrincipal !== principal
269
- || flow.view.state !== "pending" || clock() >= flow.deadline) throw new Error("Kiro device flow cancelled");
292
+ if (flow.iam) {
293
+ const profiles = await listKiroIamProfiles(reply, credential.access);
294
+ if (!owned(flow.view.flowId, principal) || !live(flow)) return publicView(flow);
295
+ flow.credential = credential;
296
+ flow.view = { flowId: flow.view.flowId, method: flow.view.method, state: "select-profile", expiresAt: flow.deadline, profiles };
297
+ if (profiles.length === 1) return await commitIamProfile(flow, principal, profiles[0]!);
298
+ return publicView(flow);
299
+ }
300
+ return await commitCredential(flow, principal, credential);
301
+ } catch {
302
+ return live(flow) ? terminal(flow, "failed") : publicView(flow);
303
+ }
304
+ }
305
+
306
+ async function commitCredential(flow: Flow, principal: KiroDevicePrincipal, credential: OAuthCredentials): Promise<KiroDeviceView> {
307
+ try {
308
+ const added = await appendKiroAccountFromDeviceLogin(credential, { assertBeforePersist: () => {
309
+ if (!owned(flow.view.flowId, principal) || !live(flow)) throw new Error("Kiro device flow cancelled");
270
310
  flow.commitAccepted = true;
271
- };
272
- const added = await appendKiroAccountFromDeviceLogin(credential, { assertBeforePersist });
311
+ } });
273
312
  try {
274
313
  await publishConfig();
275
314
  } catch {
@@ -282,14 +321,32 @@ async function poll(flow: Flow, principal: KiroDevicePrincipal): Promise<KiroDev
282
321
  }
283
322
  return terminal(flow, "done", added.warning);
284
323
  } catch {
285
- return flow.view.state === "cancelled" ? publicView(flow) : terminal(flow, "failed");
324
+ return live(flow) ? terminal(flow, "failed") : publicView(flow);
286
325
  }
287
326
  }
288
327
 
328
+ async function commitIamProfile(flow: Flow, principal: KiroDevicePrincipal, profile: KiroIamProfile): Promise<KiroDeviceView> {
329
+ try {
330
+ if (!flow.credential) throw new Error("Kiro IAM grant unavailable");
331
+ const credential = await resolveKiroIamCredential(reply, flow.credential, profile);
332
+ if (!owned(flow.view.flowId, principal) || !live(flow)) return publicView(flow);
333
+ return await commitCredential(flow, principal, credential);
334
+ } catch { return live(flow) ? terminal(flow, "failed") : publicView(flow); }
335
+ }
336
+
337
+ export async function selectKiroDeviceProfile(flowId: string, principal: KiroDevicePrincipal, arn: string): Promise<KiroDeviceView | null> {
338
+ const flow = owned(flowId, principal);
339
+ const profile = flow?.view.profiles?.find(profile => profile.arn === arn);
340
+ if (!flow || flow.view.method !== "iam-identity-center" || flow.view.state !== "select-profile" || !profile) return null;
341
+ if (!flow.polling) flow.polling = commitIamProfile(flow, principal, profile).finally(() => { flow.polling = undefined; });
342
+ return flow.polling;
343
+ }
344
+
289
345
  export async function statusKiroDeviceLogin(flowId: string, principal: KiroDevicePrincipal): Promise<KiroDeviceView | null> {
290
346
  pruneFlows();
291
347
  const flow = owned(flowId, principal);
292
348
  if (!flow) return null;
349
+ if (flow.view.state === "select-profile") return publicView(flow);
293
350
  if (flow.view.state !== "pending") {
294
351
  forgetFlow(flowId);
295
352
  return publicView(flow);
@@ -297,15 +354,15 @@ export async function statusKiroDeviceLogin(flowId: string, principal: KiroDevic
297
354
  if (clock() < flow.nextPollAt) return publicView(flow);
298
355
  if (!flow.polling) flow.polling = poll(flow, principal).finally(() => { flow.polling = undefined; });
299
356
  const result = await flow.polling;
300
- if (result.state !== "pending") forgetFlow(flowId);
357
+ if (!live(flow)) forgetFlow(flowId);
301
358
  return result;
302
359
  }
303
360
 
304
361
  export function cancelKiroDeviceLogin(flowId: string, principal: KiroDevicePrincipal): KiroDeviceView | null {
305
362
  const flow = owned(flowId, principal);
306
363
  if (!flow) return null;
307
- if (flow.commitAccepted && flow.view.state === "pending") return { ...flow.view, state: "done" };
308
- if (flow.view.state === "pending") {
364
+ if (flow.commitAccepted && live(flow)) return { ...flow.view, state: "done" };
365
+ if (live(flow)) {
309
366
  terminal(flow, "cancelled");
310
367
  forgetFlow(flowId);
311
368
  }
@@ -0,0 +1,107 @@
1
+ import type { OAuthCredentials } from "./types";
2
+
3
+ export interface KiroIamOptions { startUrl: string; region: string }
4
+ export interface KiroIamProfile { arn: string; name: string; region: string }
5
+ export type KiroIamReply = (url: string, body: Record<string, unknown>, headers?: Record<string, string>) =>
6
+ Promise<{ status: number; data: Record<string, unknown>; errorType: string }>;
7
+ const REGION = /^(?:af|ap|ca|eu|il|me|mx|sa|us)-(?:central|east|north|northeast|northwest|south|southeast|southwest|west)-[1-9][0-9]?$/;
8
+ const CONTROL = /[\u0000-\u0020\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/;
9
+ const PROFILE = /^arn:aws:codewhisperer:([a-z0-9-]+):\d{12}:profile\/[A-Za-z0-9-]+$/;
10
+ // The AWS CLI profile client enumerates these two service regions independently of SSO.
11
+ const PROFILE_REGIONS = ["us-east-1", "eu-central-1"] as const;
12
+ class KiroIamRequestError extends Error {
13
+ constructor(readonly status: number) { super("Kiro IAM discovery failed"); }
14
+ }
15
+ const record = (value: unknown): Record<string, unknown> =>
16
+ value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
17
+
18
+ /** Portal URLs are arguments to AWS OIDC, never destinations fetched by the hub. */
19
+ export function parseKiroIamOptions(value: unknown): KiroIamOptions | null {
20
+ const { startUrl, region } = record(value);
21
+ if (typeof startUrl !== "string" || startUrl.length > 2048 || CONTROL.test(startUrl)
22
+ || typeof region !== "string" || !REGION.test(region)) return null;
23
+ try {
24
+ const url = new URL(startUrl);
25
+ const authority = /^https:\/\/([^/?#]+)/.exec(startUrl)?.[1];
26
+ if (!authority || authority.includes(":") || authority.includes("@") || url.protocol !== "https:"
27
+ || !/^[a-z0-9][a-z0-9-]{0,62}\.awsapps\.com$/.test(url.hostname)
28
+ || !/^\/start\/?$/.test(url.pathname) || url.search || (url.hash && url.hash !== "#/")) return null;
29
+ return { startUrl: `https://${url.hostname}/start`, region };
30
+ } catch { return null; }
31
+ }
32
+
33
+ function managementUrl(region: string): string {
34
+ if (!REGION.test(region)) throw new Error("Invalid Kiro IAM region");
35
+ if (!PROFILE_REGIONS.some(candidate => candidate === region)) throw new Error("Unsupported Kiro profile region");
36
+ return `https://q.${region}.amazonaws.com/`;
37
+ }
38
+
39
+ async function call(reply: KiroIamReply, access: string, region: string, operation: string,
40
+ body: Record<string, unknown>): Promise<Record<string, unknown>> {
41
+ const url = new URL(managementUrl(region));
42
+ // GetUsageLimits models its arguments in both the query and JSON body (the CLI contract).
43
+ if (operation === "GetUsageLimits") for (const [key, value] of Object.entries(body)) url.searchParams.set(key, String(value));
44
+ const result = await reply(url.href, body, {
45
+ authorization: `Bearer ${access}`, "content-type": "application/x-amz-json-1.0",
46
+ "x-amz-target": `AmazonCodeWhispererService.${operation}`, "x-amzn-codewhisperer-optout": "true",
47
+ });
48
+ if (result.status !== 200 || result.errorType || Object.hasOwn(result.data, "error")) throw new KiroIamRequestError(result.status);
49
+ return result.data;
50
+ }
51
+
52
+ /** Bounded pagination; a partial or ambiguous profile list is never offered as complete. */
53
+ async function listProfilesInRegion(reply: KiroIamReply, access: string, region: string): Promise<KiroIamProfile[]> {
54
+ const profiles = new Map<string, KiroIamProfile>();
55
+ const tokens = new Set<string>();
56
+ let nextToken: string | undefined;
57
+ for (let page = 0; page < 8; page++) {
58
+ const data = await call(reply, access, region, "ListAvailableProfiles", { maxResults: 50, ...(nextToken ? { nextToken } : {}) });
59
+ if (!Array.isArray(data.profiles)) throw new Error("Kiro IAM profiles unavailable");
60
+ for (const item of data.profiles) {
61
+ const profile = record(item);
62
+ const arn = typeof profile.arn === "string" ? profile.arn : "";
63
+ const match = PROFILE.exec(arn);
64
+ const name = typeof profile.profileName === "string" ? profile.profileName.trim() : "";
65
+ if (!match || arn.length > 256 || !REGION.test(match[1]!) || !name || name.length > 256
66
+ || /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/.test(name)) throw new Error("Invalid Kiro IAM profile");
67
+ profiles.set(arn, { arn, name, region: match[1]! });
68
+ if (profiles.size > 64) throw new Error("Too many Kiro IAM profiles");
69
+ }
70
+ if (data.nextToken === undefined || data.nextToken === null || data.nextToken === "") {
71
+ return [...profiles.values()];
72
+ }
73
+ if (typeof data.nextToken !== "string" || data.nextToken.length > 4096 || tokens.has(data.nextToken)) break;
74
+ nextToken = data.nextToken;
75
+ tokens.add(nextToken);
76
+ }
77
+ throw new Error("Incomplete Kiro IAM profile list");
78
+ }
79
+
80
+ export async function listKiroIamProfiles(reply: KiroIamReply, access: string): Promise<KiroIamProfile[]> {
81
+ const regional = await Promise.all(PROFILE_REGIONS.map(async region => {
82
+ try { return await listProfilesInRegion(reply, access, region); }
83
+ catch (error) {
84
+ // Organizations may grant access in only one service region. Other failures must not
85
+ // silently present a partial list as if discovery had completed.
86
+ if (error instanceof KiroIamRequestError && (error.status === 401 || error.status === 403)) return [];
87
+ throw error;
88
+ }
89
+ }));
90
+ const profiles = new Map(regional.flat().map(profile => [profile.arn, profile]));
91
+ if (!profiles.size || profiles.size > 64) throw new Error("Kiro IAM profiles unavailable");
92
+ return [...profiles.values()];
93
+ }
94
+
95
+ /** Only AWS's response to this grant can name the user; a shared organization ARN cannot. */
96
+ export async function resolveKiroIamCredential(reply: KiroIamReply, credential: OAuthCredentials,
97
+ profile: KiroIamProfile): Promise<OAuthCredentials> {
98
+ const data = await call(reply, credential.access, profile.region, "GetUsageLimits", {
99
+ origin: "CLI", isEmailRequired: true, profileArn: profile.arn,
100
+ });
101
+ const email = record(data.userInfo).email;
102
+ if (typeof email !== "string" || !email.trim() || email.length > 320 || CONTROL.test(email.trim())) {
103
+ throw new Error("Kiro IAM user identity unavailable");
104
+ }
105
+ return { ...credential, email: email.trim().toLowerCase(), accountId: profile.arn,
106
+ kiro: { ...credential.kiro, profileArn: profile.arn, apiRegion: profile.region } };
107
+ }
@@ -35,6 +35,7 @@ import { getConfigDir, atomicWriteFile, backupInvalidConfig, hardenConfigDir, ha
35
35
  import { atomicWriteFileNoFollowUnclaimed } from "../config/atomic-write";
36
36
  import { assertNotRealHomeUnderTest } from "../lib/test-home-guard";
37
37
  import { recordOwnedConfigPath } from "../lib/config-ownership";
38
+ import { statTimeMs } from "../lib/file-identity";
38
39
  import { MAX_PENDING_OAUTH_MUTATIONS } from "../lib/translator-budget";
39
40
  import { publishAccountSelection, publishOAuthAccountPauseChange, publishOAuthAccountRoutingPolicyChange } from "../lib/account-selection-events";
40
41
  import {
@@ -429,18 +430,18 @@ function persist(store: AuthStore): void {
429
430
  }
430
431
 
431
432
  export class OAuthFileLockError extends Error { readonly code = "OAUTH_FILE_LOCK_UNAVAILABLE"; constructor(message: string, options?: { cause?: unknown }) { super(message, options); this.name = "OAuthFileLockError"; } }
432
- interface LockSnapshot { bytes: string; dev: number; ino: number; mtimeMs: number; size: number }
433
+ interface LockSnapshot { bytes: string; dev: bigint; ino: bigint; mtimeMs: number; mtimeNs: bigint; size: bigint }
433
434
  export interface OAuthFileLockOptions { path: string; waitTimeoutMs?: number; staleAfterMs?: number; pollMinMs?: number; pollMaxMs?: number; sleep?: (ms: number) => Promise<void>; now?: () => number; random?: () => number; beforeStaleUnlink?: () => void; beforeReleaseUnlink?: () => void; beforeFailedCreateUnlink?: () => void; writeMetadata?: (fd: number, bytes: string) => void }
434
435
  export interface OAuthFileLockGuard { readonly ownerId: string; release(): void }
435
436
  function errorCode(error: unknown): string | undefined { return error && typeof error === "object" && "code" in error ? String((error as { code?: unknown }).code) : undefined; }
436
- function snapshot(path: string): LockSnapshot { const bytes = readFileSync(path, "utf8"); const s = statSync(path); return { bytes, dev:s.dev, ino:s.ino, mtimeMs:s.mtimeMs, size:s.size }; }
437
- function sameSnapshot(a: LockSnapshot,b: LockSnapshot): boolean { return a.bytes===b.bytes&&a.dev===b.dev&&a.ino===b.ino&&a.mtimeMs===b.mtimeMs&&a.size===b.size; }
438
- function sameFd(a: LockSnapshot,b: ReturnType<typeof fstatSync>): boolean { return a.dev===b.dev&&a.ino===b.ino&&a.mtimeMs===b.mtimeMs&&a.size===b.size; }
437
+ function snapshot(path: string): LockSnapshot { const bytes = readFileSync(path, "utf8"); const s = statSync(path, { bigint: true }); return { bytes, dev:s.dev, ino:s.ino, mtimeMs:statTimeMs(s.mtimeNs), mtimeNs:s.mtimeNs, size:s.size }; }
438
+ function sameSnapshot(a: LockSnapshot,b: LockSnapshot): boolean { return a.bytes===b.bytes&&a.dev===b.dev&&a.ino===b.ino&&a.mtimeNs===b.mtimeNs&&a.size===b.size; }
439
+ function sameFd(a: LockSnapshot,b: import("node:fs").BigIntStats): boolean { return a.dev===b.dev&&a.ino===b.ino&&a.mtimeNs===b.mtimeNs&&a.size===b.size; }
439
440
  export function createOAuthFileLock(options: OAuthFileLockOptions): { acquire(): Promise<OAuthFileLockGuard> } {
440
441
  const wait=options.waitTimeoutMs??5000, stale=options.staleAfterMs??120000, min=options.pollMinMs??25,max=options.pollMaxMs??100,sleep=options.sleep??(ms=>Bun.sleep(ms)),now=options.now??Date.now,random=options.random??Math.random,write=options.writeMetadata??((fd,b)=>writeFileSync(fd,b,"utf8"));
441
442
  if(wait<0||stale<=0||min<0||max<min) throw new OAuthFileLockError("Invalid OAuth file-lock timing options");
442
- return { async acquire() { hardenConfigDir(); recordOwnedConfigPath(getConfigDir(),options.path); if(!existsSync(getConfigDir())) mkdirSync(getConfigDir(),{recursive:true,mode:0o700}); const ownerId=randomUUID(),started=now(); for(;;){ let fd:number|undefined; try { fd=openSync(options.path,"wx",0o600); const bytes=`${JSON.stringify({version:1,ownerId,pid:process.pid,createdAt:now()})}\n`; write(fd,bytes); const fs=fstatSync(fd); closeSync(fd); fd=undefined; const owned=snapshot(options.path); if(owned.bytes!==bytes||!sameFd(owned,fs)) throw new OAuthFileLockError("OAuth lock changed during creation"); let released=false; return {ownerId,release(){if(released)return;released=true;try{const a=snapshot(options.path);if(!sameSnapshot(owned,a))return;options.beforeReleaseUnlink?.();const b=snapshot(options.path);if(sameSnapshot(owned,b))unlinkSync(options.path);}catch(e){if(errorCode(e)!=="ENOENT")console.warn(`[oauth] lock release failed: ${e instanceof Error?e.message:String(e)}`);}}}; } catch(e) { if(fd!==undefined){let fs;try{fs=fstatSync(fd);}catch{}try{closeSync(fd);}catch{}if(fs)try{const a=snapshot(options.path);if(sameFd(a,fs)){options.beforeFailedCreateUnlink?.();const b=snapshot(options.path);if(sameSnapshot(a,b)&&sameFd(b,fs))unlinkSync(options.path);}}catch{}} if(errorCode(e)!=="EEXIST")throw e instanceof OAuthFileLockError?e:new OAuthFileLockError("Could not create OAuth file lock",{cause:e}); }
443
- try{const a=snapshot(options.path);let created=a.mtimeMs;try{const p=JSON.parse(a.bytes);if(typeof p.createdAt==="number")created=Math.max(created,p.createdAt);}catch{}if(now()-created>stale){options.beforeStaleUnlink?.();const b=snapshot(options.path);if(sameSnapshot(a,b))unlinkSync(options.path);continue;}}catch(e){if(errorCode(e)==="ENOENT")continue;throw new OAuthFileLockError("Could not inspect OAuth file lock",{cause:e});} const elapsed=now()-started;if(elapsed>=wait)throw new OAuthFileLockError(`Timed out after ${wait}ms waiting for OAuth file lock`);await sleep(Math.min(wait-elapsed,min+Math.floor(random()*(max-min+1)))); } } };
443
+ return { async acquire() { hardenConfigDir(); recordOwnedConfigPath(getConfigDir(),options.path); if(!existsSync(getConfigDir())) mkdirSync(getConfigDir(),{recursive:true,mode:0o700}); const ownerId=randomUUID(),started=now(); for(;;){ let fd:number|undefined; try { fd=openSync(options.path,"wx",0o600); const bytes=`${JSON.stringify({version:1,ownerId,pid:process.pid,createdAt:now()})}\n`; write(fd,bytes); const fs=fstatSync(fd,{bigint:true}); closeSync(fd); fd=undefined; const owned=snapshot(options.path); if(owned.bytes!==bytes||!sameFd(owned,fs)) throw new OAuthFileLockError("OAuth lock changed during creation"); let released=false; return {ownerId,release(){if(released)return;released=true;try{const a=snapshot(options.path);if(!sameSnapshot(owned,a))return;options.beforeReleaseUnlink?.();const b=snapshot(options.path);if(sameSnapshot(owned,b))unlinkSync(options.path);}catch(e){if(errorCode(e)!=="ENOENT")console.warn(`[oauth] lock release failed: ${e instanceof Error?e.message:String(e)}`);}}}; } catch(e) { if(fd!==undefined){let fs;try{fs=fstatSync(fd,{bigint:true});}catch{/* best effort: no identity, no cleanup */}try{closeSync(fd);}catch{/* best effort */}if(fs)try{const a=snapshot(options.path);if(sameFd(a,fs)){options.beforeFailedCreateUnlink?.();const b=snapshot(options.path);if(sameSnapshot(a,b)&&sameFd(b,fs))unlinkSync(options.path);}}catch{/* best-effort cleanup of our own failed create */}} if(errorCode(e)!=="EEXIST")throw e instanceof OAuthFileLockError?e:new OAuthFileLockError("Could not create OAuth file lock",{cause:e}); }
444
+ try{const a=snapshot(options.path);let created=a.mtimeMs;try{const p=JSON.parse(a.bytes);if(typeof p.createdAt==="number")created=Math.max(created,p.createdAt);}catch{/* unparsable metadata: fall back to mtime */}if(now()-created>stale){options.beforeStaleUnlink?.();const b=snapshot(options.path);if(sameSnapshot(a,b))unlinkSync(options.path);continue;}}catch(e){if(errorCode(e)==="ENOENT")continue;throw new OAuthFileLockError("Could not inspect OAuth file lock",{cause:e});} const elapsed=now()-started;if(elapsed>=wait)throw new OAuthFileLockError(`Timed out after ${wait}ms waiting for OAuth file lock`);await sleep(Math.min(wait-elapsed,min+Math.floor(random()*(max-min+1)))); } } };
444
445
  }
445
446
  /** Wait long enough for slow IdP refreshes (e.g. Cursor 15s × 3 attempts) before timing out. */
446
447
  export const OAUTH_REFRESH_LOCK_WAIT_MS = 60_000;
@@ -1114,7 +1115,8 @@ export async function appendKiroAccountFromDeviceLogin(
1114
1115
  return await mutateStore(store => {
1115
1116
  const set = store.kiro;
1116
1117
  const id = distinctAccountId(safe, set?.accounts ?? []);
1117
- const warning = safe.kiro?.profileArn && set?.accounts.some(a => a.credential.kiro?.profileArn === safe.kiro?.profileArn)
1118
+ const warning = safe.kiro?.profileArn && set?.accounts.some(a => a.credential.kiro?.profileArn === safe.kiro?.profileArn
1119
+ && (!safe.email || !a.credential.email || a.credential.email.toLowerCase() === safe.email.toLowerCase()))
1118
1120
  ? "duplicate_profile_arn" as const : undefined;
1119
1121
  const account: ProviderAccount = { id, credential: safe, addedAt: Date.now(), loginId: randomUUID(), loginOrigin: "kiro-device" };
1120
1122
  if (set) set.accounts.push(account);
@@ -13,6 +13,7 @@
13
13
  import { existsSync, readFileSync } from "node:fs";
14
14
  import { join } from "node:path";
15
15
  import { atomicWriteFile, getConfigDir } from "../config";
16
+ import { withConfigDirHardeningSettled } from "../config/paths";
16
17
  import type { ProviderQuota } from "./quota-types";
17
18
  import type { KiroPersistedQuota, KiroPersistedVerdict } from "./kiro-account-state-disk";
18
19
  import { ACCOUNT_QUOTA_TTL_MS } from "./quota-wire";
@@ -41,6 +42,11 @@ type DiskFile = {
41
42
 
42
43
  let persistTimer: ReturnType<typeof setTimeout> | null = null;
43
44
  let persistStartedAt: number | null = null;
45
+ /** Bumped by cancellation so a fired callback still waiting for ACL admission writes nothing. */
46
+ let persistGeneration = 0;
47
+ let persistWrite: Promise<void> = Promise.resolve();
48
+ /** Test seam: wait for a fired persistence callback's admitted write (as settleQuotaPersistenceForTests). */
49
+ export function settleAccountQuotaPersistForTests(): Promise<void> { return persistWrite; }
44
50
 
45
51
  /** Read the snapshot. Returns an empty map for a missing, corrupt or stale file. */
46
52
  export function readPersistedAccountQuotas(now = Date.now()): Map<string, ProviderQuota> {
@@ -102,7 +108,14 @@ export function schedulePersistAccountQuotas(
102
108
  persistTimer = setTimeout(() => {
103
109
  persistTimer = null;
104
110
  persistStartedAt = null;
105
- try {
111
+ // Writes under the config root wait out an overlapping optional config-root ACL flight,
112
+ // whose inheritance can drop the fresh file's explicit grant (#7815). Rows are read inside
113
+ // the admitted callback so a late admission still writes the newest snapshot; a timeout
114
+ // skips this best-effort write.
115
+ const dir = getConfigDir();
116
+ const generation = persistGeneration;
117
+ persistWrite = withConfigDirHardeningSettled(dir, () => {
118
+ if (generation !== persistGeneration) return;
106
119
  const out: Record<string, ProviderQuota> = {};
107
120
  for (const [key, quota] of rows()) out[key] = quota;
108
121
  const kiroVerdicts: Record<string, KiroPersistedVerdict> = {};
@@ -110,10 +123,10 @@ export function schedulePersistAccountQuotas(
110
123
  if (key.startsWith("kiro\0") && /^[a-f0-9]{64}$/.test(verdict.identity)) kiroVerdicts[key] = verdict;
111
124
  }
112
125
  const body: DiskFile = { version: 1, rows: out, kiroVerdicts };
113
- atomicWriteFile(join(getConfigDir(), FILENAME), `${JSON.stringify(body)}\n`);
114
- } catch {
126
+ atomicWriteFile(join(dir, FILENAME), `${JSON.stringify(body)}\n`);
127
+ }).catch(() => {
115
128
  // Best-effort persistence only.
116
- }
129
+ });
117
130
  }, delay);
118
131
  }
119
132
 
@@ -122,4 +135,5 @@ export function cancelPendingAccountQuotaPersist(): void {
122
135
  if (persistTimer) clearTimeout(persistTimer);
123
136
  persistTimer = null;
124
137
  persistStartedAt = null;
138
+ persistGeneration += 1;
125
139
  }