arco-workbench 0.2.2 → 0.2.5

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 (276) hide show
  1. package/CONTRIBUTING.md +1 -1
  2. package/THIRD_PARTY_NOTICES +2 -2
  3. package/client/dist/assets/{PhosphorBackdrop-BbR3xmfD.js → PhosphorBackdrop-CLILIwOQ.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-UMjbs9ZN.js → ThemedBackgroundShaderImpl-B87chcb5.js} +1 -1
  5. package/client/dist/assets/{XtermView-n135qz-f.js → XtermView-BP_j7WSN.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-CFSke4by.js → galleryEditor-B90phoBI.js} +1 -1
  7. package/client/dist/assets/{index-DeoJbjI3.js → index-BfPp1Oup.js} +270 -270
  8. package/client/dist/index.html +1 -1
  9. package/client/dist/manifest-mobile.webmanifest +1 -0
  10. package/client/src/App.tsx +2 -2
  11. package/client/src/components/AuthReloginNotice.tsx +7 -6
  12. package/client/src/components/ChatMessage.tsx +41 -29
  13. package/client/src/components/ChatPanel.tsx +17 -4
  14. package/client/src/components/ClaudeNativeAccountPicker.tsx +32 -0
  15. package/client/src/components/ClaudeNativeAuthRow.tsx +71 -19
  16. package/client/src/components/ClusterRightPanel/AddWorkerSection.tsx +11 -281
  17. package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +1 -1
  18. package/client/src/components/ClusterRightPanel/FreshMemberForm.tsx +315 -0
  19. package/client/src/components/ClusterRightPanel/ReplaceMemberDialog.tsx +17 -7
  20. package/client/src/components/ClusterRightPanel/index.tsx +1 -1
  21. package/client/src/components/ClusterRightPanel/useFreshMemberPicker.ts +6 -4
  22. package/client/src/components/ClusterTab.tsx +2 -2
  23. package/client/src/components/Connections/Connections.tsx +7 -11
  24. package/client/src/components/Connections/model.ts +3 -1
  25. package/client/src/components/FileViewerModal.tsx +54 -17
  26. package/client/src/components/GitHubPanel/index.tsx +9 -5
  27. package/client/src/components/HandoffDialog.tsx +5 -3
  28. package/client/src/components/MobileShell.tsx +1 -33
  29. package/client/src/components/OperatorQuestionNotice.tsx +5 -4
  30. package/client/src/components/ProvidersPopover.tsx +6 -2
  31. package/client/src/components/RightPanel/ActivityTab.tsx +2 -1
  32. package/client/src/components/RightPanel/ConfigTab.tsx +23 -5
  33. package/client/src/components/RightPanel/OutputsPanel.tsx +21 -9
  34. package/client/src/components/RightPanel/outputsReconcile.ts +31 -0
  35. package/client/src/components/SettingsPanel.tsx +7 -10
  36. package/client/src/components/SpawnDialog.tsx +14 -3
  37. package/client/src/components/TabBar.tsx +2 -2
  38. package/client/src/components/TabContextMenu.tsx +73 -133
  39. package/client/src/components/TerminalInput.tsx +4 -3
  40. package/client/src/components/TranscriptWorkerDialog.tsx +14 -4
  41. package/client/src/components/UsageBar.tsx +37 -18
  42. package/client/src/components/WorkflowCreator/ClusterMembersSection.tsx +29 -3
  43. package/client/src/components/WorkflowCreator/index.tsx +29 -15
  44. package/client/src/components/WorkflowView.tsx +1 -1
  45. package/client/src/components/providerIndicator.ts +7 -3
  46. package/client/src/components/research/QuickResearchOverview.tsx +7 -3
  47. package/client/src/components/research/SavedQuickKeep.tsx +7 -3
  48. package/client/src/components/settings/GitHubAuthRow.tsx +34 -0
  49. package/client/src/explorer/ArtifactsLens.tsx +17 -8
  50. package/client/src/explorer/ExplorerApp.tsx +3 -3
  51. package/client/src/explorer/types.ts +3 -1
  52. package/client/src/help/content/cluster.tsx +10 -4
  53. package/client/src/help/content/composer.tsx +3 -2
  54. package/client/src/help/content/header.tsx +6 -3
  55. package/client/src/help/content/misc.tsx +9 -7
  56. package/client/src/help/content/rightPanel.tsx +11 -6
  57. package/client/src/help/content/settings.tsx +14 -3
  58. package/client/src/help/content/tabbar.tsx +1 -1
  59. package/client/src/help/manualSections/actions.tsx +5 -1
  60. package/client/src/help/manualSections/clusters.tsx +21 -15
  61. package/client/src/help/manualSections/configuration.tsx +6 -4
  62. package/client/src/help/manualSections/gettingStarted.tsx +4 -2
  63. package/client/src/help/manualSections/maintenance.tsx +24 -0
  64. package/client/src/help/manualSections/powerFeatures.tsx +4 -2
  65. package/client/src/help/manualSections/providers.tsx +11 -4
  66. package/client/src/help/manualSections/workspace.tsx +3 -3
  67. package/client/src/hooks/useClaudeNativeCatalog.ts +26 -0
  68. package/client/src/hooks/useClaudeNativeLogin.ts +16 -11
  69. package/client/src/hooks/useWebSocket.ts +4 -2
  70. package/client/src/layout/layoutRange.ts +14 -5
  71. package/client/src/main.tsx +2 -0
  72. package/client/src/questions/waitingQuestion.ts +2 -0
  73. package/client/src/stores/appStore.ts +5 -1
  74. package/client/src/stores/appStore.types.ts +2 -0
  75. package/client/src/stores/replayContext.ts +20 -0
  76. package/client/src/utils/chatFileLinks.ts +34 -3
  77. package/client/src/utils/claudeAuth.ts +9 -1
  78. package/client/src/ws/handleServerMessage.ts +11 -3
  79. package/docs/ARCHITECTURE.md +3 -3
  80. package/docs/BACKUP.md +1 -1
  81. package/docs/CHECKPOINTS.md +67 -3
  82. package/docs/CLIENT.md +11 -6
  83. package/docs/EXTENDING.md +1 -1
  84. package/docs/FEATURES.md +3 -3
  85. package/docs/GETTING_STARTED.md +5 -4
  86. package/docs/GIT_WORKBENCH.md +8 -0
  87. package/docs/GLOSSARY.md +2 -2
  88. package/docs/GOTCHAS.md +4 -4
  89. package/docs/HTTP_API.md +63 -30
  90. package/docs/OPERATIONS.md +11 -0
  91. package/docs/OPERATOR_ACTIONS.md +2 -2
  92. package/docs/OUTPUTS.md +48 -6
  93. package/docs/PERSISTENCE.md +1 -1
  94. package/docs/PRIMITIVES.md +4 -2
  95. package/docs/PROTOCOL_CLUSTER.md +12 -6
  96. package/docs/PROTOCOL_PRIMITIVES.md +1 -1
  97. package/docs/PROVIDERS.md +47 -10
  98. package/docs/RESEARCH.md +3 -3
  99. package/docs/SETTINGS.md +9 -4
  100. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +15 -3
  101. package/node_modules/@arco/shared/dist/protocol/clusters.js +1 -1
  102. package/node_modules/@arco/shared/dist/protocol/models.d.ts +6 -1
  103. package/node_modules/@arco/shared/dist/protocol/operatorQuestions.d.ts +2 -1
  104. package/node_modules/@arco/shared/dist/protocol/settings.d.ts +3 -0
  105. package/node_modules/@arco/shared/dist/protocol/settings.js +5 -0
  106. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
  107. package/node_modules/@arco/shared/dist/protocol/workflows.js +0 -2
  108. package/node_modules/@arco/shared/package.json +1 -1
  109. package/package.json +2 -2
  110. package/scripts/packaging/services.mjs +20 -1
  111. package/scripts/packaging/update.mjs +37 -2
  112. package/server/dist/attention.d.ts +6 -0
  113. package/server/dist/attention.js +6 -0
  114. package/server/dist/auth.d.ts +5 -0
  115. package/server/dist/auth.js +31 -20
  116. package/server/dist/clusterAutoTurn.d.ts +5 -1
  117. package/server/dist/clusterAutoTurn.js +31 -9
  118. package/server/dist/clusterPresets.js +3 -3
  119. package/server/dist/effortValidation.d.ts +2 -2
  120. package/server/dist/effortValidation.js +4 -4
  121. package/server/dist/explorerArtifacts.d.ts +1 -0
  122. package/server/dist/explorerArtifacts.js +12 -1
  123. package/server/dist/explorerDocs.d.ts +1 -0
  124. package/server/dist/explorerDocs.js +4 -4
  125. package/server/dist/geminiMembers.d.ts +7 -1
  126. package/server/dist/geminiMembers.js +28 -14
  127. package/server/dist/gitSnapshots.d.ts +1 -0
  128. package/server/dist/gitSnapshots.js +547 -83
  129. package/server/dist/http/clusterRoutes.js +9 -3
  130. package/server/dist/http/conversationFiles.d.ts +36 -0
  131. package/server/dist/http/conversationFiles.js +222 -0
  132. package/server/dist/http/fileBytes.d.ts +3 -0
  133. package/server/dist/http/fileBytes.js +33 -0
  134. package/server/dist/http/fileContentRoute.d.ts +2 -0
  135. package/server/dist/http/fileContentRoute.js +139 -0
  136. package/server/dist/http/fileRead.d.ts +54 -2
  137. package/server/dist/http/fileRead.js +31 -24
  138. package/server/dist/http/outputRoutes.js +14 -21
  139. package/server/dist/http/readConfinement.d.ts +0 -11
  140. package/server/dist/http/readConfinement.js +4 -30
  141. package/server/dist/http/router.js +41 -66
  142. package/server/dist/index.js +26 -12
  143. package/server/dist/management/initHubLink.js +1 -1
  144. package/server/dist/outputs.js +8 -0
  145. package/server/dist/primitives/exportContext.d.ts +2 -0
  146. package/server/dist/primitives/exportContext.js +13 -2
  147. package/server/dist/primitives/runCompare.d.ts +7 -1
  148. package/server/dist/primitives/runCompare.js +44 -20
  149. package/server/dist/project/taskLedger.js +46 -34
  150. package/server/dist/providerAccounts.d.ts +4 -0
  151. package/server/dist/providerAccounts.js +20 -1
  152. package/server/dist/providers/antigravity/artifacts.d.ts +23 -0
  153. package/server/dist/providers/antigravity/artifacts.js +140 -0
  154. package/server/dist/providers/antigravity/index.js +85 -7
  155. package/server/dist/providers/antigravity/questions.d.ts +2 -0
  156. package/server/dist/providers/antigravity/questions.js +58 -0
  157. package/server/dist/providers/claude-native/auth.d.ts +9 -8
  158. package/server/dist/providers/claude-native/auth.js +50 -58
  159. package/server/dist/providers/claude-native/authStatus.d.ts +2 -2
  160. package/server/dist/providers/claude-native/authStatus.js +9 -7
  161. package/server/dist/providers/claude-native/catalog.d.ts +6 -5
  162. package/server/dist/providers/claude-native/catalog.js +50 -39
  163. package/server/dist/providers/claude-native/oauth.d.ts +10 -9
  164. package/server/dist/providers/claude-native/oauth.js +120 -96
  165. package/server/dist/providers/claude-native/worker.d.ts +1 -0
  166. package/server/dist/providers/claude-native/worker.js +38 -23
  167. package/server/dist/providers/codex-appserver/operatorQuestions.d.ts +5 -3
  168. package/server/dist/providers/codex-appserver/operatorQuestions.js +27 -13
  169. package/server/dist/providers/codexChatBoundary.js +6 -1
  170. package/server/dist/research/quickPromotion.d.ts +3 -0
  171. package/server/dist/research/quickPromotion.js +26 -9
  172. package/server/dist/research/savedQuickPromotion.js +2 -11
  173. package/server/dist/server/broadcast.js +6 -0
  174. package/server/dist/settings.d.ts +1 -0
  175. package/server/dist/settings.js +39 -7
  176. package/server/dist/skills.js +1 -1
  177. package/server/dist/smartPickupAdapters.d.ts +1 -0
  178. package/server/dist/smartPickupAdapters.js +2 -2
  179. package/server/dist/smartPickupObserver.js +8 -5
  180. package/server/dist/thirdPartySkills.js +11 -5
  181. package/server/dist/turnChanges.d.ts +1 -1
  182. package/server/dist/turnChanges.js +5 -4
  183. package/server/dist/usage.d.ts +1 -1
  184. package/server/dist/usage.js +39 -27
  185. package/server/dist/workers/WorkerManager.d.ts +1 -0
  186. package/server/dist/workers/WorkerManager.js +1 -0
  187. package/server/dist/workers/processKill.js +37 -24
  188. package/server/dist/workflowMeta.js +2 -2
  189. package/server/dist/ws/clusterHandlers.d.ts +2 -2
  190. package/server/dist/ws/clusterHandlers.js +127 -113
  191. package/server/dist/ws/clusterMembers.d.ts +1 -1
  192. package/server/dist/ws/clusterMembers.js +34 -4
  193. package/server/dist/ws/compactHandlers.js +30 -14
  194. package/server/dist/ws/compareHandlers.js +53 -21
  195. package/server/dist/ws/gateHandlers.js +2 -0
  196. package/server/dist/ws/genesisHandlers.js +5 -3
  197. package/server/dist/ws/handoffHandlers.d.ts +1 -1
  198. package/server/dist/ws/handoffHandlers.js +115 -39
  199. package/server/dist/ws/transcriptWorkerHandlers.js +7 -2
  200. package/server/dist/ws/turnEngine.js +37 -19
  201. package/server/dist/ws/updatePrimaryConfig.d.ts +3 -2
  202. package/server/dist/ws/updatePrimaryConfig.js +236 -133
  203. package/server/dist/ws/workflowHandlers.js +21 -4
  204. package/server/package.json +1 -1
  205. package/server/src/attention.ts +7 -0
  206. package/server/src/auth.ts +33 -20
  207. package/server/src/clusterAutoTurn.ts +31 -11
  208. package/server/src/clusterPresets.ts +2 -2
  209. package/server/src/effortValidation.ts +4 -4
  210. package/server/src/explorerArtifacts.ts +12 -1
  211. package/server/src/explorerDocs.ts +5 -5
  212. package/server/src/geminiMembers.ts +26 -15
  213. package/server/src/gitSnapshots.ts +538 -82
  214. package/server/src/http/clusterRoutes.ts +10 -3
  215. package/server/src/http/conversationFiles.ts +231 -0
  216. package/server/src/http/fileBytes.ts +34 -0
  217. package/server/src/http/fileContentRoute.ts +123 -0
  218. package/server/src/http/fileRead.ts +30 -25
  219. package/server/src/http/outputRoutes.ts +13 -13
  220. package/server/src/http/readConfinement.ts +3 -30
  221. package/server/src/http/router.ts +39 -62
  222. package/server/src/index.ts +27 -18
  223. package/server/src/management/initHubLink.ts +1 -1
  224. package/server/src/outputs.ts +8 -0
  225. package/server/src/primitives/exportContext.ts +14 -2
  226. package/server/src/primitives/runCompare.ts +73 -46
  227. package/server/src/project/taskLedger.ts +47 -30
  228. package/server/src/providerAccounts.ts +20 -1
  229. package/server/src/providers/antigravity/artifacts.ts +121 -0
  230. package/server/src/providers/antigravity/index.ts +64 -6
  231. package/server/src/providers/antigravity/questions.ts +52 -0
  232. package/server/src/providers/claude-native/auth.ts +45 -60
  233. package/server/src/providers/claude-native/authStatus.ts +9 -8
  234. package/server/src/providers/claude-native/catalog.ts +52 -35
  235. package/server/src/providers/claude-native/oauth.ts +101 -77
  236. package/server/src/providers/claude-native/worker.ts +38 -22
  237. package/server/src/providers/codex-appserver/operatorQuestions.ts +26 -12
  238. package/server/src/providers/codexChatBoundary.ts +6 -1
  239. package/server/src/research/quickPromotion.ts +24 -6
  240. package/server/src/research/savedQuickPromotion.ts +2 -8
  241. package/server/src/server/broadcast.ts +4 -0
  242. package/server/src/settings.ts +36 -8
  243. package/server/src/skills.ts +1 -1
  244. package/server/src/smartPickupAdapters.ts +3 -2
  245. package/server/src/smartPickupObserver.ts +8 -5
  246. package/server/src/thirdPartySkills.ts +11 -5
  247. package/server/src/turnChanges.ts +5 -4
  248. package/server/src/usage.ts +30 -22
  249. package/server/src/workers/WorkerManager.ts +2 -0
  250. package/server/src/workers/processKill.ts +37 -23
  251. package/server/src/workflowMeta.ts +2 -2
  252. package/server/src/ws/clusterHandlers.ts +107 -104
  253. package/server/src/ws/clusterMembers.ts +25 -6
  254. package/server/src/ws/compactHandlers.ts +29 -15
  255. package/server/src/ws/compareHandlers.ts +59 -25
  256. package/server/src/ws/gateHandlers.ts +2 -0
  257. package/server/src/ws/genesisHandlers.ts +5 -4
  258. package/server/src/ws/handoffHandlers.ts +105 -37
  259. package/server/src/ws/transcriptWorkerHandlers.ts +6 -2
  260. package/server/src/ws/turnEngine.ts +36 -18
  261. package/server/src/ws/updatePrimaryConfig.ts +230 -132
  262. package/server/src/ws/workflowHandlers.ts +20 -4
  263. package/shared/dist/protocol/clusters.d.ts +15 -3
  264. package/shared/dist/protocol/clusters.js +1 -1
  265. package/shared/dist/protocol/models.d.ts +6 -1
  266. package/shared/dist/protocol/operatorQuestions.d.ts +2 -1
  267. package/shared/dist/protocol/settings.d.ts +3 -0
  268. package/shared/dist/protocol/settings.js +5 -0
  269. package/shared/dist/protocol/workflows.d.ts +1 -0
  270. package/shared/dist/protocol/workflows.js +0 -2
  271. package/shared/src/protocol/clusters.ts +23 -5
  272. package/shared/src/protocol/compare.ts +2 -2
  273. package/shared/src/protocol/models.ts +8 -4
  274. package/shared/src/protocol/operatorQuestions.ts +2 -1
  275. package/shared/src/protocol/settings.ts +8 -1
  276. package/shared/src/protocol/workflows.ts +1 -1
@@ -14,10 +14,12 @@
14
14
  // authorize URL and accept a `{ url }` paste body to extract `code` +
15
15
  // `state`.
16
16
 
17
- import type { ClaudeCredentialBinding, ClaudeNativeAuthFlow } from '@arco/shared';
17
+ import { DEFAULT_CLAUDE_NATIVE_ACCOUNT, type ClaudeCredentialBinding, type ClaudeNativeAuthFlow } from '@arco/shared';
18
+ import { requireClaudeNativeAccount } from '../../providerAccounts.js';
18
19
  import { createServer, type Server } from 'node:http';
19
20
  import { randomBytes, createHash, randomUUID } from 'node:crypto';
20
21
  import {
22
+ clearTokensUnlocked,
21
23
  loadTokens,
22
24
  nativeCredentialBinding,
23
25
  withAuthLock,
@@ -53,22 +55,27 @@ const FLOW_TTL_MS = 10 * 60_000;
53
55
  interface PendingFlow {
54
56
  state: string;
55
57
  codeVerifier: string;
56
- server: Server | null;
58
+ accountRef: string;
57
59
  timer?: ReturnType<typeof setTimeout>;
58
60
  result: ClaudeNativeAuthFlow;
59
61
  completion?: Promise<{ ok: true; flow: ClaudeNativeAuthFlow }>;
60
62
  }
61
- let pendingFlow: PendingFlow | null = null;
63
+ const pendingFlows = new Map<string, PendingFlow>();
64
+ let callbackListener: Promise<Server | null> | undefined;
62
65
  const flows = new Map<string, PendingFlow>();
63
66
 
64
67
  function finishFlow(flow: PendingFlow, status: ClaudeNativeAuthFlow['status'], error?: string): void {
65
68
  flow.result = { ...flow.result, status, ...(error ? { error } : {}) };
66
69
  if (flow.timer) clearTimeout(flow.timer);
67
- if (flow.server) { try { flow.server.close(); } catch { /* already closed */ } }
68
- if (pendingFlow === flow) pendingFlow = null;
70
+ if (pendingFlows.get(flow.accountRef) === flow) pendingFlows.delete(flow.accountRef);
71
+ if (pendingFlows.size === 0) {
72
+ const closing = callbackListener;
73
+ callbackListener = undefined;
74
+ void closing?.then(server => server?.close());
75
+ }
69
76
  }
70
77
  function currentFlow(flow: PendingFlow): boolean {
71
- return pendingFlow === flow && ['pending', 'exchanging'].includes(flow.result.status) && Date.now() < flow.result.expiresAt;
78
+ return pendingFlows.get(flow.accountRef) === flow && ['pending', 'exchanging'].includes(flow.result.status) && Date.now() < flow.result.expiresAt;
72
79
  }
73
80
  function sameBinding(a: ClaudeCredentialBinding, b: ClaudeCredentialBinding): boolean {
74
81
  return a.source === b.source && a.storeId === b.storeId && a.revision === b.revision;
@@ -82,47 +89,55 @@ export interface BootstrapStartResult {
82
89
  flow: ClaudeNativeAuthFlow;
83
90
  }
84
91
 
85
- // One credential owner and one callback listener. Flow ids are independent of
86
- // the provider's state/verifier and contain no authorization material.
87
- export async function startBootstrap(expectedBinding?: ClaudeCredentialBinding, workflowId?: string): Promise<BootstrapStartResult> {
92
+ // The registered callback port is shared. The OAuth state identifies the
93
+ // flow, and the flow fixes its account before any credential exchange.
94
+ function listenForCallback(): Promise<Server | null> {
95
+ return callbackListener ??= new Promise(resolve => {
96
+ const server = createServer((req, res) => {
97
+ let url: URL;
98
+ try { url = new URL(req.url || '/', REDIRECT_URI); }
99
+ catch { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Invalid callback request.'); return; }
100
+ if (url.pathname !== CALLBACK_PATH) { res.writeHead(404); res.end('not found'); return; }
101
+ const flow = [...pendingFlows.values()].find(candidate => candidate.state === url.searchParams.get('state'));
102
+ if (!flow) { res.writeHead(400); res.end('Sign-in flow unavailable.'); return; }
103
+ void completeFlow(flow, url).then(() => {
104
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
105
+ res.end('<!doctype html><meta charset="utf-8"><title>Arco Native sign-in</title><h1>Native sign-in completed.</h1><p>Return to Arco and review the originating workflow. No work was replayed.</p>');
106
+ }, () => { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Sign-in did not complete. Return to Arco to review this flow.'); });
107
+ });
108
+ server.once('error', () => resolve(null));
109
+ server.listen(CALLBACK_PORT, CALLBACK_HOST, () => resolve(server));
110
+ });
111
+ }
112
+
113
+ export async function startBootstrap(expectedBinding?: ClaudeCredentialBinding, workflowId?: string, requestedAccount?: string): Promise<BootstrapStartResult> {
114
+ const accountRef = await requireClaudeNativeAccount(requestedAccount);
88
115
  return withAuthLock(async () => {
89
- const binding = nativeCredentialBinding(await readTokensUnlocked());
116
+ const binding = nativeCredentialBinding(await readTokensUnlocked(accountRef), accountRef);
90
117
  if (expectedBinding && !sameBinding(expectedBinding, binding)) throw new Error('Native credentials changed. Review sign-in status before starting again.');
91
- if (pendingFlow) finishFlow(pendingFlow, 'superseded');
118
+ const previous = pendingFlows.get(accountRef);
92
119
  const verifier = randomBytes(32).toString('base64url');
93
120
  const state = randomBytes(32).toString('base64url');
94
- const flow: PendingFlow = { state, codeVerifier: verifier, server: null, result: {
121
+ const flow: PendingFlow = { state, codeVerifier: verifier, accountRef, result: {
95
122
  id: randomUUID(), status: 'pending', startedAt: Date.now(), expiresAt: Date.now() + FLOW_TTL_MS,
96
- bindingBefore: binding, ...(workflowId ? { workflowId } : {}),
123
+ bindingBefore: binding, ...(workflowId ? { workflowId } : {}), ...(requestedAccount ? { accountRef } : {}),
97
124
  } };
98
- pendingFlow = flow;
125
+ pendingFlows.set(accountRef, flow);
126
+ if (previous) finishFlow(previous, 'superseded');
99
127
  flows.set(flow.result.id, flow);
100
- while (flows.size > 32) flows.delete(flows.keys().next().value!);
101
- let manualReason: string | undefined;
102
- try {
103
- flow.server = await new Promise<Server>((resolve, reject) => {
104
- const server = createServer((req, res) => {
105
- let url: URL;
106
- try { url = new URL(req.url || '/', REDIRECT_URI); }
107
- catch { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Invalid callback request.'); return; }
108
- if (url.pathname !== CALLBACK_PATH) { res.writeHead(404); res.end('not found'); return; }
109
- void completeFlow(flow, url).then(() => {
110
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
111
- res.end('<!doctype html><meta charset="utf-8"><title>Arco Native sign-in</title><h1>Native sign-in completed.</h1><p>Return to Arco and review the originating workflow. No work was replayed.</p>');
112
- }, () => { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Sign-in did not complete. Return to Arco to review this flow.'); });
113
- });
114
- server.once('error', reject);
115
- server.listen(CALLBACK_PORT, CALLBACK_HOST, () => resolve(server));
116
- });
117
- } catch {
118
- manualReason = 'Local callback unavailable. Approve in the browser, then paste the redirected localhost URL.';
128
+ while (flows.size > 32) {
129
+ const finished = [...flows.values()].find(candidate => !currentFlow(candidate));
130
+ if (!finished) break;
131
+ flows.delete(finished.result.id);
119
132
  }
133
+ const server = await listenForCallback();
134
+ const manualReason = server ? undefined : 'Local callback unavailable. Approve in the browser, then paste the redirected localhost URL.';
120
135
  flow.timer = setTimeout(() => { void cancelBootstrap(flow.result.id, 'expired'); }, FLOW_TTL_MS);
121
136
  flow.timer.unref?.();
122
137
  const params = new URLSearchParams({ code: 'true', client_id: CLIENT_ID, response_type: 'code', redirect_uri: REDIRECT_URI,
123
138
  scope: SCOPES, code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256', state });
124
- return { authorizationUrl: `${AUTHORIZE_URL}?${params}`, state, manualFallback: !flow.server, manualReason, flow: { ...flow.result } };
125
- });
139
+ return { authorizationUrl: `${AUTHORIZE_URL}?${params}`, state, manualFallback: !server, manualReason, flow: { ...flow.result } };
140
+ }, accountRef);
126
141
  }
127
142
 
128
143
  export async function getBootstrapFlow(id: string): Promise<ClaudeNativeAuthFlow | null> {
@@ -133,16 +148,26 @@ export async function getBootstrapFlow(id: string): Promise<ClaudeNativeAuthFlow
133
148
  }
134
149
 
135
150
  export async function cancelBootstrap(id: string, reason: 'cancelled' | 'expired' = 'cancelled'): Promise<ClaudeNativeAuthFlow | null> {
151
+ const flow = flows.get(id);
152
+ if (!flow) return null;
136
153
  return withAuthLock(async () => {
137
- const flow = flows.get(id);
138
- if (!flow) return null;
139
154
  if (['pending', 'exchanging'].includes(flow.result.status)) finishFlow(flow, reason);
140
155
  return { ...flow.result };
141
- });
156
+ }, flow.accountRef);
157
+ }
158
+
159
+ export async function cancelActiveBootstrap(accountRef = DEFAULT_CLAUDE_NATIVE_ACCOUNT): Promise<void> {
160
+ const flow = pendingFlows.get(accountRef);
161
+ if (flow) await cancelBootstrap(flow.result.id);
142
162
  }
143
163
 
144
- export async function cancelActiveBootstrap(): Promise<void> {
145
- await withAuthLock(async () => { if (pendingFlow) finishFlow(pendingFlow, 'cancelled'); });
164
+ export async function logout(accountRef = DEFAULT_CLAUDE_NATIVE_ACCOUNT): Promise<void> {
165
+ await withAuthLock(async () => {
166
+ const flow = pendingFlows.get(accountRef);
167
+ if (flow) finishFlow(flow, 'cancelled');
168
+ await clearTokensUnlocked(accountRef);
169
+ clearClaudeAuthProblem(accountRef);
170
+ }, accountRef);
146
171
  }
147
172
 
148
173
  // Local callback and remote manual paste share the same validation, single
@@ -161,16 +186,17 @@ function completeFlow(flow: PendingFlow, url: URL): Promise<{ ok: true; flow: Cl
161
186
  try {
162
187
  const tokens = await exchangeCode(code, flow.state, flow.codeVerifier);
163
188
  await withAuthLock(async () => {
189
+ await requireClaudeNativeAccount(flow.accountRef);
164
190
  if (!currentFlow(flow)) throw new Error('Sign-in flow is no longer pending. Start again.');
165
- if (!sameBinding(flow.result.bindingBefore, nativeCredentialBinding(await readTokensUnlocked()))) {
191
+ if (!sameBinding(flow.result.bindingBefore, nativeCredentialBinding(await readTokensUnlocked(flow.accountRef), flow.accountRef))) {
166
192
  finishFlow(flow, 'superseded');
167
193
  throw new Error('Native credentials changed during sign-in. Review the current credentials.');
168
194
  }
169
- await writeTokensUnlocked(tokens);
170
- flow.result = { ...flow.result, binding: nativeCredentialBinding(tokens) };
171
- clearClaudeAuthProblem();
195
+ await writeTokensUnlocked(tokens, flow.accountRef);
196
+ flow.result = { ...flow.result, binding: nativeCredentialBinding(tokens, flow.accountRef) };
197
+ clearClaudeAuthProblem(flow.accountRef);
172
198
  finishFlow(flow, 'complete');
173
- });
199
+ }, flow.accountRef);
174
200
  return { ok: true as const, flow: { ...flow.result } };
175
201
  } catch (err) {
176
202
  if (currentFlow(flow)) finishFlow(flow, 'failed', 'Native sign-in failed. Start a new flow to try again.');
@@ -182,7 +208,7 @@ function completeFlow(flow: PendingFlow, url: URL): Promise<{ ok: true; flow: Cl
182
208
 
183
209
  export async function completeBootstrap(rawUrl: string, flowId?: string): Promise<{ ok: true; flow: ClaudeNativeAuthFlow }> {
184
210
  const url = new URL(rawUrl);
185
- const flow = flowId ? flows.get(flowId) : pendingFlow;
211
+ const flow = flowId ? flows.get(flowId) : pendingFlows.get(DEFAULT_CLAUDE_NATIVE_ACCOUNT);
186
212
  if (!flow) throw new Error('no pending OAuth flow - start one first');
187
213
  if (url.protocol !== 'http:' || !['localhost', '127.0.0.1'].includes(url.hostname) || url.port !== String(CALLBACK_PORT) || url.pathname !== CALLBACK_PATH) throw new Error('Expected the redirected localhost callback URL.');
188
214
  return completeFlow(flow, url);
@@ -203,10 +229,7 @@ async function exchangeCode(code: string, state: string, codeVerifier: string):
203
229
  code_verifier: codeVerifier,
204
230
  }),
205
231
  });
206
- if (!res.ok) {
207
- const txt = await res.text().catch(() => '');
208
- throw new Error(`token exchange failed (${res.status}): ${txt.slice(0, 200)}`);
209
- }
232
+ if (!res.ok) throw new Error(`Native token exchange failed (${res.status}).`);
210
233
  const data = await res.json() as {
211
234
  access_token: string;
212
235
  refresh_token: string;
@@ -229,13 +252,14 @@ async function exchangeCode(code: string, state: string, codeVerifier: string):
229
252
 
230
253
  // Refresh under the auth-file lock so two workers refreshing the same
231
254
  // token don't race. Returns the (possibly-new) tokens.
232
- export async function refreshTokens(current: ClaudeNativeTokens): Promise<ClaudeNativeTokens> {
255
+ export async function refreshTokens(_current: ClaudeNativeTokens, accountRef?: string): Promise<ClaudeNativeTokens> {
233
256
  return withAuthLock(async () => {
234
257
  // Re-read inside the lock — another worker may have already refreshed.
235
- const fresh = await readTokensUnlocked();
236
- if (fresh && fresh.expiresAt > Date.now() + REFRESH_LEAD_MS) return fresh;
237
- return refreshUnlocked(fresh ?? current);
238
- });
258
+ const fresh = await readTokensUnlocked(accountRef);
259
+ if (!fresh) throw new ClaudeNativeNoAuthError();
260
+ if (fresh.expiresAt > Date.now() + REFRESH_LEAD_MS) return fresh;
261
+ return refreshUnlocked(fresh, accountRef);
262
+ }, accountRef);
239
263
  }
240
264
 
241
265
  // A1 (docs/REMOTE_MANAGEMENT.md) - refresh IGNORING the local
@@ -246,13 +270,13 @@ export async function refreshTokens(current: ClaudeNativeTokens): Promise<Claude
246
270
  // `staleObtainedAt` guards the concurrent case: if another worker already
247
271
  // rotated the on-disk tokens since the 401'ing client was built, return those
248
272
  // instead of burning a second refresh against a just-rotated chain.
249
- export async function forceRefreshTokens(staleObtainedAt: number): Promise<ClaudeNativeTokens> {
273
+ export async function forceRefreshTokens(staleObtainedAt: number, accountRef?: string): Promise<ClaudeNativeTokens> {
250
274
  return withAuthLock(async () => {
251
- const fresh = await readTokensUnlocked();
275
+ const fresh = await readTokensUnlocked(accountRef);
252
276
  if (!fresh) throw new ClaudeNativeNoAuthError();
253
277
  if (fresh.obtainedAt > staleObtainedAt) return fresh;
254
- return refreshUnlocked(fresh);
255
- });
278
+ return refreshUnlocked(fresh, accountRef);
279
+ }, accountRef);
256
280
  }
257
281
 
258
282
  // The actual refresh POST + persist. Caller MUST hold the auth-file lock.
@@ -260,7 +284,7 @@ export async function forceRefreshTokens(staleObtainedAt: number): Promise<Claud
260
284
  // "access token revoked early, chain still good" (no line ever
261
285
  // appears; forced refresh recovers silently) from "refresh chain dead, re-auth
262
286
  // genuinely required" (§10.2 diagnostics).
263
- async function refreshUnlocked(seed: ClaudeNativeTokens): Promise<ClaudeNativeTokens> {
287
+ async function refreshUnlocked(seed: ClaudeNativeTokens, accountRef?: string): Promise<ClaudeNativeTokens> {
264
288
  const res = await fetch(TOKEN_URL, {
265
289
  method: 'POST',
266
290
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
@@ -271,9 +295,8 @@ async function refreshUnlocked(seed: ClaudeNativeTokens): Promise<ClaudeNativeTo
271
295
  }),
272
296
  });
273
297
  if (!res.ok) {
274
- const txt = await res.text().catch(() => '');
275
- console.error(`[claude-native] refresh rejected (${res.status}): ${txt.slice(0, 200)}`);
276
- const err = new Error(`refresh failed (${res.status}): ${txt.slice(0, 200)}`);
298
+ console.error(`[claude-native] refresh rejected (${res.status})`);
299
+ const err = new Error(`Native refresh failed (${res.status})`);
277
300
  (err as Error & { httpStatus?: number }).httpStatus = res.status;
278
301
  throw err;
279
302
  }
@@ -293,8 +316,8 @@ async function refreshUnlocked(seed: ClaudeNativeTokens): Promise<ClaudeNativeTo
293
316
  scope: data.scope ?? seed.scope,
294
317
  obtainedAt: now,
295
318
  };
296
- await writeTokensUnlocked(next);
297
- clearClaudeAuthProblem(); // a fresh grant is proof the chain works again
319
+ await writeTokensUnlocked(next, accountRef);
320
+ clearClaudeAuthProblem(accountRef); // a fresh grant is proof the chain works again
298
321
  return next;
299
322
  }
300
323
 
@@ -307,7 +330,7 @@ async function refreshUnlocked(seed: ClaudeNativeTokens): Promise<ClaudeNativeTo
307
330
  // clears it until the next failed turn re-reports, which is the honest state.
308
331
  // The transition into "problem" emits ONE auth-expired workbench notice (J1 →
309
332
  // ntfy), so the phone learns without polling.
310
- let claudeAuthProblem: { since: number; detail: string } | null = null;
333
+ const claudeAuthProblems = new Map<string, { since: number; detail: string }>();
311
334
  let authProblemNotify: ((detail: string) => void) | null = null;
312
335
 
313
336
  // Wired by the server bootstrap (initHubLink) to the J1 emit() — injected so
@@ -316,22 +339,22 @@ export function setClaudeAuthProblemNotifier(fn: (detail: string) => void): void
316
339
  authProblemNotify = fn;
317
340
  }
318
341
 
319
- export function markClaudeAuthProblem(detail: string): void {
320
- if (claudeAuthProblem) return; // already alerted — don't re-notify per turn
321
- claudeAuthProblem = { since: Date.now(), detail };
342
+ export function markClaudeAuthProblem(detail: string, accountRef = DEFAULT_CLAUDE_NATIVE_ACCOUNT): void {
343
+ if (claudeAuthProblems.has(accountRef)) return; // already alerted — don't re-notify per turn
344
+ claudeAuthProblems.set(accountRef, { since: Date.now(), detail });
322
345
  try {
323
- authProblemNotify?.(detail);
346
+ if (accountRef === DEFAULT_CLAUDE_NATIVE_ACCOUNT) authProblemNotify?.(detail);
324
347
  } catch {
325
348
  /* notifier must never break the auth path */
326
349
  }
327
350
  }
328
351
 
329
- export function clearClaudeAuthProblem(): void {
330
- claudeAuthProblem = null;
352
+ export function clearClaudeAuthProblem(accountRef = DEFAULT_CLAUDE_NATIVE_ACCOUNT): void {
353
+ claudeAuthProblems.delete(accountRef);
331
354
  }
332
355
 
333
- export function getClaudeAuthProblem(): { since: number; detail: string } | null {
334
- return claudeAuthProblem;
356
+ export function getClaudeAuthProblem(accountRef = DEFAULT_CLAUDE_NATIVE_ACCOUNT): { since: number; detail: string } | null {
357
+ return claudeAuthProblems.get(accountRef) ?? null;
335
358
  }
336
359
 
337
360
  // Thrown when ~/.arco/auth.json has no claude.native key. The worker
@@ -348,11 +371,12 @@ export class ClaudeNativeNoAuthError extends Error {
348
371
  // Public wrapper — load tokens, refresh if expired, return the live set.
349
372
  // Throws ClaudeNativeNoAuthError on no-auth or a generic Error on refresh
350
373
  // failure (caller surfaces [AUTH:claude]).
351
- export async function ensureLiveTokens(): Promise<ClaudeNativeTokens> {
352
- const tokens = await loadTokens();
374
+ export async function ensureLiveTokens(requestedAccount?: string): Promise<ClaudeNativeTokens> {
375
+ const accountRef = await requireClaudeNativeAccount(requestedAccount);
376
+ const tokens = await loadTokens(accountRef);
353
377
  if (!tokens) throw new ClaudeNativeNoAuthError();
354
378
  if (tokens.expiresAt > Date.now() + REFRESH_LEAD_MS) return tokens;
355
- return refreshTokens(tokens);
379
+ return refreshTokens(tokens, accountRef);
356
380
  }
357
381
 
358
382
  export const REFRESH_LEAD_MS_EXPORT = REFRESH_LEAD_MS;
@@ -35,6 +35,7 @@ import Anthropic from '@anthropic-ai/sdk';
35
35
  import type { WorkerConfig, ServerMessage, SteerItem } from '@arco/shared';
36
36
  import { supportsClaudeAdaptiveThinking, isClaudeModelAlias, enforcesPreservedThinking, supportsMidConversationSystemMessages, supportsMidConversationToolChanges } from '@arco/shared';
37
37
  import { loadTokens, nativeCredentialBinding } from './auth.js';
38
+ import { ClaudeNativeAccountUnavailableError } from '../../providerAccounts.js';
38
39
  import type { AuthRecoveryContext } from '@arco/shared';
39
40
  import { ensureLiveTokens, forceRefreshTokens, markClaudeAuthProblem, ClaudeNativeNoAuthError } from './oauth.js';
40
41
  import { resolveTrustStatus } from '../../projectTrust.js';
@@ -45,7 +46,7 @@ import { checkPartialReadFullWrite } from './pretoolGuards.js';
45
46
  import { firstBlockingGuard, postToolSteps, runPostToolSteps } from './toolChecks.js';
46
47
  import { evaluateGate, gateOutcome, gateSignature, type GateProposal } from './gateReview.js';
47
48
  import { recordPendingGate, clearPendingGate, readGateStore, hasStandingApproval, addStandingApproval } from './gateStore.js';
48
- import { getCachedModelCapabilities, getCatalog, hasCatalogCache, resolveClaudeAliasFromCatalog } from './catalog.js';
49
+ import { getCachedModelCapabilities, getCatalog, resolveClaudeAliasFromCatalog } from './catalog.js';
49
50
  import { filterToolResult } from './filterToolResult.js';
50
51
  import { planTurnSpill, toolEvictEnabled, turnToolTokenBudget, type EvictableResult } from './toolResultEviction.js';
51
52
  import { outputHash } from '../outputSignature.js';
@@ -387,6 +388,7 @@ export class ClaudeNativeWorker extends EventEmitter {
387
388
  // against on-disk tokens and rebuild the client transparently.
388
389
  private authRecovery: AuthRecoveryContext = { transport: 'native', binding: nativeCredentialBinding() };
389
390
  private clientTokenObtainedAt: number | null = null;
391
+ private clientBinding: AuthRecoveryContext['binding'];
390
392
  private messages: MessageParam[] = [];
391
393
  private heldSteerNotices = new WeakSet<object>();
392
394
  private hooks: HookConfig = { byEvent: {} };
@@ -844,6 +846,10 @@ export class ClaudeNativeWorker extends EventEmitter {
844
846
  // shouldn't change without a worker tear-down, but
845
847
  // appendSystemPrompt rotates per turn (skills manifest, transcript)
846
848
  // and effort/model can be live-edited.
849
+ if (this.config.providerAccountRef !== next.providerAccountRef) {
850
+ this.catalogWarmAttempted = false;
851
+ this.authFailureCount = 0;
852
+ }
847
853
  this.config = next;
848
854
  this.taskDisabled = this.taskDisabled || next.claudeNativeTaskDisabled === true;
849
855
  }
@@ -1545,20 +1551,22 @@ export class ClaudeNativeWorker extends EventEmitter {
1545
1551
  // worker built its client, ensureLiveTokens() returns the fresh set
1546
1552
  // and the obtainedAt mismatch below forces a client rebuild. Cheap:
1547
1553
  // ensureLiveTokens is a single disk read on the happy path.
1548
- const tokens = await ensureLiveTokens();
1549
- this.authRecovery = { transport: 'native', binding: nativeCredentialBinding(tokens) };
1554
+ const accountRef = this.config.providerAccountRef;
1555
+ const tokens = await ensureLiveTokens(accountRef);
1556
+ const binding = nativeCredentialBinding(tokens, accountRef);
1557
+ this.authRecovery = { transport: 'native', binding, ...(accountRef ? { accountRef } : {}) };
1550
1558
  // An alias tab can't be dispatched until the alias resolves to a concrete
1551
1559
  // id. Warm the catalog once per worker so the resolution is catalog-backed
1552
1560
  // (newest family member) rather than the static CLAUDE_ALIAS_FALLBACK.
1553
1561
  // Failure is non-fatal — the fallback still yields a real, dispatchable id.
1554
- if (!this.catalogWarmAttempted && isClaudeModelAlias(this.config.model) && !hasCatalogCache()) {
1562
+ if ((!this.catalogWarmAttempted || this.clientBinding?.revision !== binding.revision) && isClaudeModelAlias(this.config.model)) {
1555
1563
  this.catalogWarmAttempted = true;
1556
- await getCatalog(false).catch((err) => {
1564
+ await getCatalog(false, this.config.providerAccountRef).catch((err) => {
1557
1565
  console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] catalog warm for alias '${this.config.model}' failed; using static fallback:`, err instanceof Error ? err.message : err);
1558
1566
  });
1559
1567
  }
1560
1568
  const baseURL = await nativeOAuthBaseUrl();
1561
- if (this.client && this.clientTokenObtainedAt === tokens.obtainedAt && this.client.baseURL === baseURL) return;
1569
+ if (this.client && this.clientBinding?.storeId === binding.storeId && this.clientBinding.revision === binding.revision && this.client.baseURL === baseURL) return;
1562
1570
  const isRebuild = this.client !== null;
1563
1571
  if (isRebuild) {
1564
1572
  console.log(`[claude-native:${this.workflowId.slice(0, 8)}] credentials or endpoint changed - rebuilding Anthropic client`);
@@ -1576,6 +1584,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1576
1584
  maxRetries: 0,
1577
1585
  } as ConstructorParameters<typeof Anthropic>[0]);
1578
1586
  this.clientTokenObtainedAt = tokens.obtainedAt;
1587
+ this.clientBinding = binding;
1579
1588
  // Token-rotation rebuilds reuse the existing hooks + replayed state
1580
1589
  // and skip the worker-init emit. Hooks come from CLAUDE.md files,
1581
1590
  // unrelated to auth; replay only ever runs once per worker; 'init'
@@ -1615,7 +1624,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1615
1624
  // `not_found_error: model: opus`. Resolved per call, not cached: the operator
1616
1625
  // can live-swap the model through updateConfig mid-session.
1617
1626
  private requestModel(): string {
1618
- return resolveClaudeAliasFromCatalog(this.config.model);
1627
+ return resolveClaudeAliasFromCatalog(this.config.model, this.config.providerAccountRef);
1619
1628
  }
1620
1629
 
1621
1630
  // Opus-5 plan Phase 2 — the model id capability decisions key on. For a
@@ -1662,7 +1671,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1662
1671
  private buildBetaHeader(): string {
1663
1672
  const parts: string[] = ['claude-code-20250219', 'oauth-2025-04-20'];
1664
1673
  if (shouldSendInterleavedThinkingBeta(this.capModel(), this.config.claudeNativeForceInterleavedThinkingBeta === true)) parts.push('interleaved-thinking-2025-05-14');
1665
- const caps = getCachedModelCapabilities(this.capModel());
1674
+ const caps = getCachedModelCapabilities(this.capModel(), this.config.providerAccountRef);
1666
1675
  // compact is OFF by default for Native (NATIVE_COMPACTION_PLAN §1); the
1667
1676
  // beta is only attached when WorkflowConfig.claudeNativeCompact is the
1668
1677
  // explicit per-tab/global opt-in true. Once a server compaction block is
@@ -1826,7 +1835,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1826
1835
  // an empty object when no context-management feature is active so the
1827
1836
  // call site can spread it unconditionally.
1828
1837
  private buildContextManagementBody(): Record<string, unknown> {
1829
- const caps = getCachedModelCapabilities(this.capModel());
1838
+ const caps = getCachedModelCapabilities(this.capModel(), this.config.providerAccountRef);
1830
1839
  const edits = buildContextManagementEditsForRequest(caps, this.config.claudeNativeCompact === true && !hasLeadingServerFoldBlock(this.messages));
1831
1840
  // Anthropic's server-managed compaction is an edit strategy, not a sibling
1832
1841
  // `context_management.compact` object. Let the model+server pick the
@@ -1837,14 +1846,14 @@ export class ClaudeNativeWorker extends EventEmitter {
1837
1846
 
1838
1847
  private async hydrateContextManagementCapabilities(): Promise<void> {
1839
1848
  const model = this.capModel();
1840
- if (getCachedModelCapabilities(model)) return;
1841
- await getCatalog(false).catch((err) => {
1849
+ if (getCachedModelCapabilities(model, this.config.providerAccountRef)) return;
1850
+ await getCatalog(false, this.config.providerAccountRef).catch((err) => {
1842
1851
  console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] catalog warm-up failed:`, err instanceof Error ? err.message : err);
1843
1852
  });
1844
- if (getCachedModelCapabilities(model)) return;
1853
+ if (getCachedModelCapabilities(model, this.config.providerAccountRef)) return;
1845
1854
  if (this.forcedCatalogRefreshModels.has(model)) return;
1846
1855
  this.forcedCatalogRefreshModels.add(model);
1847
- await getCatalog(true).catch((err) => {
1856
+ await getCatalog(true, this.config.providerAccountRef).catch((err) => {
1848
1857
  console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] catalog force-refresh failed for ${model}:`, err instanceof Error ? err.message : err);
1849
1858
  });
1850
1859
  }
@@ -2778,17 +2787,24 @@ export class ClaudeNativeWorker extends EventEmitter {
2778
2787
  this.taskPolicy = resolveNativeSubagents(taskDefaults?.nativeSubagents, this.config.nativeSubagents);
2779
2788
  await this.ensureStarted();
2780
2789
  } catch (err) {
2781
- try { this.authRecovery = { transport: 'native', binding: nativeCredentialBinding(await loadTokens()) }; } catch { this.authRecovery = { transport: 'native' }; }
2790
+ const accountRef = this.config.providerAccountRef;
2791
+ if (err instanceof ClaudeNativeAccountUnavailableError) {
2792
+ this.emit('system_notice', `[AUTH:claude] ${err.message}`, { transport: 'native', accountRef, accountUnavailable: true });
2793
+ this.emit('error', 'claude account unavailable');
2794
+ return;
2795
+ }
2796
+ try { this.authRecovery = { transport: 'native', ...(accountRef ? { accountRef } : {}), binding: nativeCredentialBinding(await loadTokens(accountRef), accountRef) }; }
2797
+ catch { this.authRecovery = { transport: 'native', ...(accountRef ? { accountRef } : {}) }; }
2782
2798
  // Pre-flight auth surface: emit the [AUTH:claude] sentinel so the
2783
2799
  // chat renderer offers RE-LOGIN instead of a raw error string.
2784
2800
  if (err instanceof ClaudeNativeNoAuthError) {
2785
- markClaudeAuthProblem('not authenticated'); // A2 — phone banner + notice
2801
+ markClaudeAuthProblem('not authenticated', accountRef); // A2 — phone banner + notice
2786
2802
  this.emit('system_notice', '[AUTH:claude] Claude Native is not authenticated. Re-login to continue.', this.authRecovery);
2787
2803
  this.emit('error', 'claude auth required');
2788
2804
  return;
2789
2805
  }
2790
2806
  const detail = err instanceof Error ? err.message : String(err);
2791
- markClaudeAuthProblem(detail); // A2 — pre-flight refresh failure
2807
+ markClaudeAuthProblem(detail, accountRef); // A2 — pre-flight refresh failure
2792
2808
  this.emit('system_notice', `[AUTH:claude] Claude Native auth failed: ${detail}. Re-login to continue.`, this.authRecovery);
2793
2809
  this.emit('error', 'claude auth failed');
2794
2810
  return;
@@ -4272,7 +4288,7 @@ export class ClaudeNativeWorker extends EventEmitter {
4272
4288
  return !this.config.incognito && cwd && WFID_PATTERN.test(this.workflowId) ? join(workflowDir(cwd, this.workflowId), 'pending-subagent-approval.json') : null;
4273
4289
  }
4274
4290
 
4275
- private async batchCatalog(force: boolean) { return await getCatalog(force); }
4291
+ private async batchCatalog(force: boolean) { return await getCatalog(force, this.config.providerAccountRef); }
4276
4292
 
4277
4293
  private async approveTaskBatch(blocks: ToolUseBlock[]): Promise<boolean> {
4278
4294
  if (!blocks.length) return true;
@@ -4328,7 +4344,7 @@ export class ClaudeNativeWorker extends EventEmitter {
4328
4344
  }
4329
4345
  const available = current.models.map((m) => m.id);
4330
4346
  const proposed = selected ? [selected] : entries.map((e) => e.effective);
4331
- if (proposed.some((model) => !available.includes(model) && !available.includes(resolveClaudeAliasFromCatalog(model)))) {
4347
+ if (proposed.some((model) => !available.includes(model) && !available.includes(resolveClaudeAliasFromCatalog(model, this.config.providerAccountRef)))) {
4332
4348
  this.taskBatchRefusal = 'Task not started: a selected model is no longer available.';
4333
4349
  this.emit('system_notice', 'Sub-agent batch not started: a selected model is no longer available.');
4334
4350
  return false;
@@ -4453,7 +4469,7 @@ export class ClaudeNativeWorker extends EventEmitter {
4453
4469
  summary: finalText.slice(0, 200),
4454
4470
  });
4455
4471
  const overridden = spawnPolicy.model && args.model
4456
- && resolveClaudeAliasFromCatalog(spawnPolicy.model) !== resolveClaudeAliasFromCatalog(args.model);
4472
+ && resolveClaudeAliasFromCatalog(spawnPolicy.model, this.config.providerAccountRef) !== resolveClaudeAliasFromCatalog(args.model, this.config.providerAccountRef);
4457
4473
  return overridden
4458
4474
  ? `${finalText}\n\nSub-agent used ${chosenModel ?? handle.model ?? spawnPolicy.model}: the operator's model selection overrides the requested ${args.model}.`
4459
4475
  : finalText;
@@ -4524,7 +4540,7 @@ export class ClaudeNativeWorker extends EventEmitter {
4524
4540
  if (!this.forcedAuthRefreshThisTurn && attempt < MAX_RETRY_ATTEMPTS - 1) {
4525
4541
  this.forcedAuthRefreshThisTurn = true;
4526
4542
  try {
4527
- await forceRefreshTokens(this.clientTokenObtainedAt ?? 0);
4543
+ await forceRefreshTokens(this.clientTokenObtainedAt ?? 0, this.config.providerAccountRef);
4528
4544
  // On-disk tokens rotated → obtainedAt mismatch → client rebuild.
4529
4545
  await this.ensureStarted();
4530
4546
  console.log(`[claude-native:${this.workflowId.slice(0, 8)}] 401 on unexpired token — forced refresh ok, retrying`);
@@ -4538,10 +4554,10 @@ export class ClaudeNativeWorker extends EventEmitter {
4538
4554
  }
4539
4555
  }
4540
4556
  this.authFailureCount += 1;
4541
- const detail = msg || 'Invalid authentication credentials';
4557
+ const detail = 'The provider rejected this account credentials';
4542
4558
  // A2 — flip the live auth-problem flag (phone console banner + one
4543
4559
  // auth-expired notice). Cleared by a successful refresh/bootstrap.
4544
- markClaudeAuthProblem(detail);
4560
+ markClaudeAuthProblem(detail, this.config.providerAccountRef);
4545
4561
  const loud = this.authFailureCount >= AUTH_FAILURE_LOUD_THRESHOLD;
4546
4562
  const prefix = loud
4547
4563
  ? `[AUTH:claude] Repeated Claude auth failures (${this.authFailureCount}). Re-login required to continue.`
@@ -8,9 +8,9 @@ interface Pending {
8
8
  workflowId: string;
9
9
  state: OperatorQuestionState;
10
10
  rpcId?: JsonRpcId;
11
- respond?: (result: unknown) => boolean | void;
11
+ respond?: (answers: Answers | null) => boolean | void;
12
12
  publish: (state: OperatorQuestionState) => void;
13
- owner: CodexOperatorQuestions;
13
+ finish: (state: OperatorQuestionState) => void;
14
14
  sending: boolean;
15
15
  }
16
16
  // Process-local handles only. Disk/replay stores the public state, never callbacks.
@@ -39,14 +39,28 @@ export function pendingOperatorQuestions(workflowId: string): OperatorQuestionSt
39
39
  return [...pending.values()].filter((p) => p.workflowId === workflowId).map((p) => p.state);
40
40
  }
41
41
 
42
+ export function openGeminiOperatorQuestion(workflowId: string, sessionId: string, questions: OperatorQuestion[], respond: NonNullable<Pending['respond']>): () => void {
43
+ const requestId = randomUUID();
44
+ const state: OperatorQuestionState = { requestId, provider: 'antigravity-cli', threadId: sessionId, turnId: requestId,
45
+ itemId: requestId, mode: 'blocking', questions, status: 'pending', createdAt: Date.now() };
46
+ const publish = (next: OperatorQuestionState) => publisher?.(workflowId, next);
47
+ const finish = (next: OperatorQuestionState) => { pending.delete(requestId); publish(next); };
48
+ pending.set(requestId, { workflowId, state, respond, publish, finish, sending: false });
49
+ publish(state);
50
+ return () => {
51
+ if (pending.has(requestId)) finish({ ...state, status: 'cancelled', reason: 'Gemini closed this question.' });
52
+ };
53
+ }
54
+
42
55
  export async function replyToOperatorQuestion(workflowId: string, requestId: string, value: unknown, sendInput?: SendInput): Promise<{ ok: boolean; error?: string }> {
43
56
  const entry = pending.get(requestId);
44
57
  if (!entry || entry.workflowId !== workflowId) return { ok: false, error: 'This question is no longer pending.' };
45
58
  if (entry.sending) return { ok: false, error: 'An answer is already being delivered.' };
46
- if (!record(value) || Object.keys(value).length !== entry.state.questions.length) return { ok: false, error: 'Answer every question.' };
59
+ if (!record(value) || Object.keys(value).some(id => !entry.state.questions.some(q => q.id === id))) return { ok: false, error: 'Answer every required question.' };
47
60
  const answers: Answers = Object.create(null);
48
61
  for (const q of entry.state.questions) {
49
62
  const a = Object.hasOwn(value, q.id) ? value[q.id] : undefined;
63
+ if (a === undefined && q.optional) continue;
50
64
  if (!Array.isArray(a) || a.length !== 1 || !text(a[0], 16384) || !a[0].trim()) return { ok: false, error: 'Each question needs an answer.' };
51
65
  if (q.options?.length && !q.allowOther && !q.options.some((o) => o.label === a[0])) return { ok: false, error: 'Choose one of the offered options.' };
52
66
  answers[q.id] = [a[0]];
@@ -54,8 +68,7 @@ export async function replyToOperatorQuestion(workflowId: string, requestId: str
54
68
  entry.sending = true;
55
69
  try {
56
70
  if (entry.respond) {
57
- const delivered = entry.respond({ answers: Object.fromEntries(Object.entries(answers).map(([id, a]) => [id, { answers: a }])) });
58
- if (delivered === false) throw new Error('Codex connection closed.');
71
+ if (entry.respond(answers) === false) throw new Error('Agent connection closed.');
59
72
  } else {
60
73
  if (!sendInput) throw new Error('The question reply channel is unavailable.');
61
74
  // Async agent-message questions have no pending RPC. Send an ordinary
@@ -63,8 +76,8 @@ export async function replyToOperatorQuestion(workflowId: string, requestId: str
63
76
  await sendInput('Answers to your questions:\n' + entry.state.questions.map((q) => `${q.question}\nAnswer: ${answers[q.id][0]}`).join('\n\n'), entry.state);
64
77
  }
65
78
  if (pending.get(requestId) === entry) {
66
- const publicAnswers = Object.fromEntries(entry.state.questions.map((q) => [q.id, q.secret ? ['[redacted]'] : answers[q.id]]));
67
- entry.owner.finish(entry, { ...entry.state, status: 'answered', answers: publicAnswers });
79
+ const publicAnswers = Object.fromEntries(entry.state.questions.filter(q => Object.hasOwn(answers, q.id)).map(q => [q.id, q.secret ? ['[redacted]'] : answers[q.id]]));
80
+ entry.finish({ ...entry.state, status: 'answered', answers: publicAnswers });
68
81
  }
69
82
  return { ok: true };
70
83
  } catch {
@@ -78,9 +91,9 @@ export function dismissOperatorQuestion(workflowId: string, requestId: string):
78
91
  if (entry.sending) return { ok: false, error: 'An answer is already being delivered.' };
79
92
  entry.sending = true;
80
93
  try {
81
- if (entry.respond && entry.respond({ answers: {} }) === false) throw new Error('Codex connection closed.');
94
+ if (entry.respond?.(null) === false) throw new Error('Agent connection closed.');
82
95
  if (pending.get(requestId) !== entry) return { ok: false, error: 'This question is no longer pending.' };
83
- entry.owner.finish(entry, { ...entry.state, status: 'cancelled', reason: 'Dismissed by the operator.' });
96
+ entry.finish({ ...entry.state, status: 'cancelled', reason: 'Dismissed by the operator.' });
84
97
  return { ok: true };
85
98
  } catch {
86
99
  return { ok: false, error: 'The dismissal could not be delivered. The question is still pending.' };
@@ -98,7 +111,8 @@ export class CodexOperatorQuestions {
98
111
  if (p.isBlocking !== undefined && typeof p.isBlocking !== 'boolean') throw new Error('Invalid blocking flag.');
99
112
  if ([...this.ids].some((id) => pending.get(id)?.rpcId === req.id)) throw new Error('Duplicate question request.');
100
113
  const questions = parseQuestions(p.questions);
101
- this.add({ threadId: p.threadId, turnId: p.turnId, itemId: p.itemId, mode: p.isBlocking === false ? 'async' : 'blocking', questions }, respond, req.id);
114
+ this.add({ threadId: p.threadId, turnId: p.turnId, itemId: p.itemId, mode: p.isBlocking === false ? 'async' : 'blocking', questions },
115
+ (answers) => respond({ answers: Object.fromEntries(Object.entries(answers ?? {}).map(([id, a]) => [id, { answers: a }])) }), req.id);
102
116
  }
103
117
 
104
118
  acceptAsync(threadId: string, turnId: string, item: { id: string; questions?: unknown }): void {
@@ -119,7 +133,7 @@ export class CodexOperatorQuestions {
119
133
  private add(data: Pick<OperatorQuestionState, 'threadId' | 'turnId' | 'itemId' | 'mode' | 'questions'>, respond?: Pending['respond'], rpcId?: JsonRpcId): void {
120
134
  if (this.ids.size >= 16) throw new Error('Too many pending questions.');
121
135
  const state: OperatorQuestionState = { ...data, requestId: randomUUID(), provider: this.provider, status: 'pending', createdAt: Date.now() };
122
- const entry: Pending = { workflowId: this.workflowId, state, respond, rpcId, publish: this.publish, owner: this, sending: false };
136
+ const entry: Pending = { workflowId: this.workflowId, state, respond, rpcId, publish: this.publish, finish: (next) => this.finish(entry, next), sending: false };
123
137
  this.ids.add(state.requestId); pending.set(state.requestId, entry); this.publish(state);
124
138
  }
125
139
 
@@ -148,7 +162,7 @@ export class CodexOperatorQuestions {
148
162
  const p = pending.get(id);
149
163
  if (!p || (rpcOnly && p.rpcId === undefined)) continue;
150
164
  this.finish(p, { ...p.state, status: 'cancelled', reason });
151
- p.respond?.({ answers: {} });
165
+ p.respond?.(null);
152
166
  }
153
167
  }
154
168
  }