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
@@ -13,9 +13,11 @@
13
13
  // in use, sandbox refusal, headless / SSH session), we surface the
14
14
  // authorize URL and accept a `{ url }` paste body to extract `code` +
15
15
  // `state`.
16
+ import { DEFAULT_CLAUDE_NATIVE_ACCOUNT } from '@arco/shared';
17
+ import { requireClaudeNativeAccount } from '../../providerAccounts.js';
16
18
  import { createServer } from 'node:http';
17
19
  import { randomBytes, createHash, randomUUID } from 'node:crypto';
18
- import { loadTokens, nativeCredentialBinding, withAuthLock, writeTokensUnlocked, readTokensUnlocked, } from './auth.js';
20
+ import { clearTokensUnlocked, loadTokens, nativeCredentialBinding, withAuthLock, writeTokensUnlocked, readTokensUnlocked, } from './auth.js';
19
21
  // `9d1c250a-e61b-44d9-88ed-5944d1962f5e` (Pi-derived) — base64-encoded.
20
22
  const CLIENT_ID_B64 = 'OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl';
21
23
  const CLIENT_ID = Buffer.from(CLIENT_ID_B64, 'base64').toString('utf8');
@@ -37,82 +39,92 @@ const SCOPES = [
37
39
  // boundary. 30s mirrors the plan-doc value.
38
40
  const REFRESH_LEAD_MS = 30_000;
39
41
  const FLOW_TTL_MS = 10 * 60_000;
40
- let pendingFlow = null;
42
+ const pendingFlows = new Map();
43
+ let callbackListener;
41
44
  const flows = new Map();
42
45
  function finishFlow(flow, status, error) {
43
46
  flow.result = { ...flow.result, status, ...(error ? { error } : {}) };
44
47
  if (flow.timer)
45
48
  clearTimeout(flow.timer);
46
- if (flow.server) {
47
- try {
48
- flow.server.close();
49
- }
50
- catch { /* already closed */ }
49
+ if (pendingFlows.get(flow.accountRef) === flow)
50
+ pendingFlows.delete(flow.accountRef);
51
+ if (pendingFlows.size === 0) {
52
+ const closing = callbackListener;
53
+ callbackListener = undefined;
54
+ void closing?.then(server => server?.close());
51
55
  }
52
- if (pendingFlow === flow)
53
- pendingFlow = null;
54
56
  }
55
57
  function currentFlow(flow) {
56
- return pendingFlow === flow && ['pending', 'exchanging'].includes(flow.result.status) && Date.now() < flow.result.expiresAt;
58
+ return pendingFlows.get(flow.accountRef) === flow && ['pending', 'exchanging'].includes(flow.result.status) && Date.now() < flow.result.expiresAt;
57
59
  }
58
60
  function sameBinding(a, b) {
59
61
  return a.source === b.source && a.storeId === b.storeId && a.revision === b.revision;
60
62
  }
61
- // One credential owner and one callback listener. Flow ids are independent of
62
- // the provider's state/verifier and contain no authorization material.
63
- export async function startBootstrap(expectedBinding, workflowId) {
63
+ // The registered callback port is shared. The OAuth state identifies the
64
+ // flow, and the flow fixes its account before any credential exchange.
65
+ function listenForCallback() {
66
+ return callbackListener ??= new Promise(resolve => {
67
+ const server = createServer((req, res) => {
68
+ let url;
69
+ try {
70
+ url = new URL(req.url || '/', REDIRECT_URI);
71
+ }
72
+ catch {
73
+ res.writeHead(400, { 'Content-Type': 'text/plain' });
74
+ res.end('Invalid callback request.');
75
+ return;
76
+ }
77
+ if (url.pathname !== CALLBACK_PATH) {
78
+ res.writeHead(404);
79
+ res.end('not found');
80
+ return;
81
+ }
82
+ const flow = [...pendingFlows.values()].find(candidate => candidate.state === url.searchParams.get('state'));
83
+ if (!flow) {
84
+ res.writeHead(400);
85
+ res.end('Sign-in flow unavailable.');
86
+ return;
87
+ }
88
+ void completeFlow(flow, url).then(() => {
89
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
90
+ 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>');
91
+ }, () => { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Sign-in did not complete. Return to Arco to review this flow.'); });
92
+ });
93
+ server.once('error', () => resolve(null));
94
+ server.listen(CALLBACK_PORT, CALLBACK_HOST, () => resolve(server));
95
+ });
96
+ }
97
+ export async function startBootstrap(expectedBinding, workflowId, requestedAccount) {
98
+ const accountRef = await requireClaudeNativeAccount(requestedAccount);
64
99
  return withAuthLock(async () => {
65
- const binding = nativeCredentialBinding(await readTokensUnlocked());
100
+ const binding = nativeCredentialBinding(await readTokensUnlocked(accountRef), accountRef);
66
101
  if (expectedBinding && !sameBinding(expectedBinding, binding))
67
102
  throw new Error('Native credentials changed. Review sign-in status before starting again.');
68
- if (pendingFlow)
69
- finishFlow(pendingFlow, 'superseded');
103
+ const previous = pendingFlows.get(accountRef);
70
104
  const verifier = randomBytes(32).toString('base64url');
71
105
  const state = randomBytes(32).toString('base64url');
72
- const flow = { state, codeVerifier: verifier, server: null, result: {
106
+ const flow = { state, codeVerifier: verifier, accountRef, result: {
73
107
  id: randomUUID(), status: 'pending', startedAt: Date.now(), expiresAt: Date.now() + FLOW_TTL_MS,
74
- bindingBefore: binding, ...(workflowId ? { workflowId } : {}),
108
+ bindingBefore: binding, ...(workflowId ? { workflowId } : {}), ...(requestedAccount ? { accountRef } : {}),
75
109
  } };
76
- pendingFlow = flow;
110
+ pendingFlows.set(accountRef, flow);
111
+ if (previous)
112
+ finishFlow(previous, 'superseded');
77
113
  flows.set(flow.result.id, flow);
78
- while (flows.size > 32)
79
- flows.delete(flows.keys().next().value);
80
- let manualReason;
81
- try {
82
- flow.server = await new Promise((resolve, reject) => {
83
- const server = createServer((req, res) => {
84
- let url;
85
- try {
86
- url = new URL(req.url || '/', REDIRECT_URI);
87
- }
88
- catch {
89
- res.writeHead(400, { 'Content-Type': 'text/plain' });
90
- res.end('Invalid callback request.');
91
- return;
92
- }
93
- if (url.pathname !== CALLBACK_PATH) {
94
- res.writeHead(404);
95
- res.end('not found');
96
- return;
97
- }
98
- void completeFlow(flow, url).then(() => {
99
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
100
- 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>');
101
- }, () => { res.writeHead(400, { 'Content-Type': 'text/plain' }); res.end('Sign-in did not complete. Return to Arco to review this flow.'); });
102
- });
103
- server.once('error', reject);
104
- server.listen(CALLBACK_PORT, CALLBACK_HOST, () => resolve(server));
105
- });
106
- }
107
- catch {
108
- manualReason = 'Local callback unavailable. Approve in the browser, then paste the redirected localhost URL.';
114
+ while (flows.size > 32) {
115
+ const finished = [...flows.values()].find(candidate => !currentFlow(candidate));
116
+ if (!finished)
117
+ break;
118
+ flows.delete(finished.result.id);
109
119
  }
120
+ const server = await listenForCallback();
121
+ const manualReason = server ? undefined : 'Local callback unavailable. Approve in the browser, then paste the redirected localhost URL.';
110
122
  flow.timer = setTimeout(() => { void cancelBootstrap(flow.result.id, 'expired'); }, FLOW_TTL_MS);
111
123
  flow.timer.unref?.();
112
124
  const params = new URLSearchParams({ code: 'true', client_id: CLIENT_ID, response_type: 'code', redirect_uri: REDIRECT_URI,
113
125
  scope: SCOPES, code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256', state });
114
- return { authorizationUrl: `${AUTHORIZE_URL}?${params}`, state, manualFallback: !flow.server, manualReason, flow: { ...flow.result } };
115
- });
126
+ return { authorizationUrl: `${AUTHORIZE_URL}?${params}`, state, manualFallback: !server, manualReason, flow: { ...flow.result } };
127
+ }, accountRef);
116
128
  }
117
129
  export async function getBootstrapFlow(id) {
118
130
  const flow = flows.get(id);
@@ -123,18 +135,28 @@ export async function getBootstrapFlow(id) {
123
135
  return { ...flow.result };
124
136
  }
125
137
  export async function cancelBootstrap(id, reason = 'cancelled') {
138
+ const flow = flows.get(id);
139
+ if (!flow)
140
+ return null;
126
141
  return withAuthLock(async () => {
127
- const flow = flows.get(id);
128
- if (!flow)
129
- return null;
130
142
  if (['pending', 'exchanging'].includes(flow.result.status))
131
143
  finishFlow(flow, reason);
132
144
  return { ...flow.result };
133
- });
145
+ }, flow.accountRef);
146
+ }
147
+ export async function cancelActiveBootstrap(accountRef = DEFAULT_CLAUDE_NATIVE_ACCOUNT) {
148
+ const flow = pendingFlows.get(accountRef);
149
+ if (flow)
150
+ await cancelBootstrap(flow.result.id);
134
151
  }
135
- export async function cancelActiveBootstrap() {
136
- await withAuthLock(async () => { if (pendingFlow)
137
- finishFlow(pendingFlow, 'cancelled'); });
152
+ export async function logout(accountRef = DEFAULT_CLAUDE_NATIVE_ACCOUNT) {
153
+ await withAuthLock(async () => {
154
+ const flow = pendingFlows.get(accountRef);
155
+ if (flow)
156
+ finishFlow(flow, 'cancelled');
157
+ await clearTokensUnlocked(accountRef);
158
+ clearClaudeAuthProblem(accountRef);
159
+ }, accountRef);
138
160
  }
139
161
  // Local callback and remote manual paste share the same validation, single
140
162
  // exchange and guarded commit. A superseded response cannot replace tokens.
@@ -156,17 +178,18 @@ function completeFlow(flow, url) {
156
178
  try {
157
179
  const tokens = await exchangeCode(code, flow.state, flow.codeVerifier);
158
180
  await withAuthLock(async () => {
181
+ await requireClaudeNativeAccount(flow.accountRef);
159
182
  if (!currentFlow(flow))
160
183
  throw new Error('Sign-in flow is no longer pending. Start again.');
161
- if (!sameBinding(flow.result.bindingBefore, nativeCredentialBinding(await readTokensUnlocked()))) {
184
+ if (!sameBinding(flow.result.bindingBefore, nativeCredentialBinding(await readTokensUnlocked(flow.accountRef), flow.accountRef))) {
162
185
  finishFlow(flow, 'superseded');
163
186
  throw new Error('Native credentials changed during sign-in. Review the current credentials.');
164
187
  }
165
- await writeTokensUnlocked(tokens);
166
- flow.result = { ...flow.result, binding: nativeCredentialBinding(tokens) };
167
- clearClaudeAuthProblem();
188
+ await writeTokensUnlocked(tokens, flow.accountRef);
189
+ flow.result = { ...flow.result, binding: nativeCredentialBinding(tokens, flow.accountRef) };
190
+ clearClaudeAuthProblem(flow.accountRef);
168
191
  finishFlow(flow, 'complete');
169
- });
192
+ }, flow.accountRef);
170
193
  return { ok: true, flow: { ...flow.result } };
171
194
  }
172
195
  catch (err) {
@@ -179,7 +202,7 @@ function completeFlow(flow, url) {
179
202
  }
180
203
  export async function completeBootstrap(rawUrl, flowId) {
181
204
  const url = new URL(rawUrl);
182
- const flow = flowId ? flows.get(flowId) : pendingFlow;
205
+ const flow = flowId ? flows.get(flowId) : pendingFlows.get(DEFAULT_CLAUDE_NATIVE_ACCOUNT);
183
206
  if (!flow)
184
207
  throw new Error('no pending OAuth flow - start one first');
185
208
  if (url.protocol !== 'http:' || !['localhost', '127.0.0.1'].includes(url.hostname) || url.port !== String(CALLBACK_PORT) || url.pathname !== CALLBACK_PATH)
@@ -201,10 +224,8 @@ async function exchangeCode(code, state, codeVerifier) {
201
224
  code_verifier: codeVerifier,
202
225
  }),
203
226
  });
204
- if (!res.ok) {
205
- const txt = await res.text().catch(() => '');
206
- throw new Error(`token exchange failed (${res.status}): ${txt.slice(0, 200)}`);
207
- }
227
+ if (!res.ok)
228
+ throw new Error(`Native token exchange failed (${res.status}).`);
208
229
  const data = await res.json();
209
230
  if (typeof data.access_token !== 'string' || !data.access_token || typeof data.refresh_token !== 'string' || !data.refresh_token
210
231
  || !Number.isFinite(data.expires_in) || data.expires_in <= 0)
@@ -221,14 +242,16 @@ async function exchangeCode(code, state, codeVerifier) {
221
242
  }
222
243
  // Refresh under the auth-file lock so two workers refreshing the same
223
244
  // token don't race. Returns the (possibly-new) tokens.
224
- export async function refreshTokens(current) {
245
+ export async function refreshTokens(_current, accountRef) {
225
246
  return withAuthLock(async () => {
226
247
  // Re-read inside the lock — another worker may have already refreshed.
227
- const fresh = await readTokensUnlocked();
228
- if (fresh && fresh.expiresAt > Date.now() + REFRESH_LEAD_MS)
248
+ const fresh = await readTokensUnlocked(accountRef);
249
+ if (!fresh)
250
+ throw new ClaudeNativeNoAuthError();
251
+ if (fresh.expiresAt > Date.now() + REFRESH_LEAD_MS)
229
252
  return fresh;
230
- return refreshUnlocked(fresh ?? current);
231
- });
253
+ return refreshUnlocked(fresh, accountRef);
254
+ }, accountRef);
232
255
  }
233
256
  // A1 (docs/REMOTE_MANAGEMENT.md) - refresh IGNORING the local
234
257
  // expiry check. The worker calls this when an API request 401s on a token
@@ -238,22 +261,22 @@ export async function refreshTokens(current) {
238
261
  // `staleObtainedAt` guards the concurrent case: if another worker already
239
262
  // rotated the on-disk tokens since the 401'ing client was built, return those
240
263
  // instead of burning a second refresh against a just-rotated chain.
241
- export async function forceRefreshTokens(staleObtainedAt) {
264
+ export async function forceRefreshTokens(staleObtainedAt, accountRef) {
242
265
  return withAuthLock(async () => {
243
- const fresh = await readTokensUnlocked();
266
+ const fresh = await readTokensUnlocked(accountRef);
244
267
  if (!fresh)
245
268
  throw new ClaudeNativeNoAuthError();
246
269
  if (fresh.obtainedAt > staleObtainedAt)
247
270
  return fresh;
248
- return refreshUnlocked(fresh);
249
- });
271
+ return refreshUnlocked(fresh, accountRef);
272
+ }, accountRef);
250
273
  }
251
274
  // The actual refresh POST + persist. Caller MUST hold the auth-file lock.
252
275
  // A rejected refresh logs its own distinct line, separating
253
276
  // "access token revoked early, chain still good" (no line ever
254
277
  // appears; forced refresh recovers silently) from "refresh chain dead, re-auth
255
278
  // genuinely required" (§10.2 diagnostics).
256
- async function refreshUnlocked(seed) {
279
+ async function refreshUnlocked(seed, accountRef) {
257
280
  const res = await fetch(TOKEN_URL, {
258
281
  method: 'POST',
259
282
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
@@ -264,9 +287,8 @@ async function refreshUnlocked(seed) {
264
287
  }),
265
288
  });
266
289
  if (!res.ok) {
267
- const txt = await res.text().catch(() => '');
268
- console.error(`[claude-native] refresh rejected (${res.status}): ${txt.slice(0, 200)}`);
269
- const err = new Error(`refresh failed (${res.status}): ${txt.slice(0, 200)}`);
290
+ console.error(`[claude-native] refresh rejected (${res.status})`);
291
+ const err = new Error(`Native refresh failed (${res.status})`);
270
292
  err.httpStatus = res.status;
271
293
  throw err;
272
294
  }
@@ -280,8 +302,8 @@ async function refreshUnlocked(seed) {
280
302
  scope: data.scope ?? seed.scope,
281
303
  obtainedAt: now,
282
304
  };
283
- await writeTokensUnlocked(next);
284
- clearClaudeAuthProblem(); // a fresh grant is proof the chain works again
305
+ await writeTokensUnlocked(next, accountRef);
306
+ clearClaudeAuthProblem(accountRef); // a fresh grant is proof the chain works again
285
307
  return next;
286
308
  }
287
309
  // -- A2 (docs/REMOTE_MANAGEMENT.md) - live auth-problem state -----
@@ -293,29 +315,30 @@ async function refreshUnlocked(seed) {
293
315
  // clears it until the next failed turn re-reports, which is the honest state.
294
316
  // The transition into "problem" emits ONE auth-expired workbench notice (J1 →
295
317
  // ntfy), so the phone learns without polling.
296
- let claudeAuthProblem = null;
318
+ const claudeAuthProblems = new Map();
297
319
  let authProblemNotify = null;
298
320
  // Wired by the server bootstrap (initHubLink) to the J1 emit() — injected so
299
321
  // this module stays free of a notifications import (and smoke-testable).
300
322
  export function setClaudeAuthProblemNotifier(fn) {
301
323
  authProblemNotify = fn;
302
324
  }
303
- export function markClaudeAuthProblem(detail) {
304
- if (claudeAuthProblem)
325
+ export function markClaudeAuthProblem(detail, accountRef = DEFAULT_CLAUDE_NATIVE_ACCOUNT) {
326
+ if (claudeAuthProblems.has(accountRef))
305
327
  return; // already alerted — don't re-notify per turn
306
- claudeAuthProblem = { since: Date.now(), detail };
328
+ claudeAuthProblems.set(accountRef, { since: Date.now(), detail });
307
329
  try {
308
- authProblemNotify?.(detail);
330
+ if (accountRef === DEFAULT_CLAUDE_NATIVE_ACCOUNT)
331
+ authProblemNotify?.(detail);
309
332
  }
310
333
  catch {
311
334
  /* notifier must never break the auth path */
312
335
  }
313
336
  }
314
- export function clearClaudeAuthProblem() {
315
- claudeAuthProblem = null;
337
+ export function clearClaudeAuthProblem(accountRef = DEFAULT_CLAUDE_NATIVE_ACCOUNT) {
338
+ claudeAuthProblems.delete(accountRef);
316
339
  }
317
- export function getClaudeAuthProblem() {
318
- return claudeAuthProblem;
340
+ export function getClaudeAuthProblem(accountRef = DEFAULT_CLAUDE_NATIVE_ACCOUNT) {
341
+ return claudeAuthProblems.get(accountRef) ?? null;
319
342
  }
320
343
  // Thrown when ~/.arco/auth.json has no claude.native key. The worker
321
344
  // catches `code === 'NO_AUTH'` and surfaces the [AUTH:claude] system_notice
@@ -330,13 +353,14 @@ export class ClaudeNativeNoAuthError extends Error {
330
353
  // Public wrapper — load tokens, refresh if expired, return the live set.
331
354
  // Throws ClaudeNativeNoAuthError on no-auth or a generic Error on refresh
332
355
  // failure (caller surfaces [AUTH:claude]).
333
- export async function ensureLiveTokens() {
334
- const tokens = await loadTokens();
356
+ export async function ensureLiveTokens(requestedAccount) {
357
+ const accountRef = await requireClaudeNativeAccount(requestedAccount);
358
+ const tokens = await loadTokens(accountRef);
335
359
  if (!tokens)
336
360
  throw new ClaudeNativeNoAuthError();
337
361
  if (tokens.expiresAt > Date.now() + REFRESH_LEAD_MS)
338
362
  return tokens;
339
- return refreshTokens(tokens);
363
+ return refreshTokens(tokens, accountRef);
340
364
  }
341
365
  export const REFRESH_LEAD_MS_EXPORT = REFRESH_LEAD_MS;
342
366
  //# sourceMappingURL=oauth.js.map
@@ -60,6 +60,7 @@ export declare class ClaudeNativeWorker extends EventEmitter {
60
60
  private inTurnCompact;
61
61
  private authRecovery;
62
62
  private clientTokenObtainedAt;
63
+ private clientBinding;
63
64
  private messages;
64
65
  private heldSteerNotices;
65
66
  private hooks;
@@ -33,6 +33,7 @@ import { basename, join } from 'node:path';
33
33
  import Anthropic from '@anthropic-ai/sdk';
34
34
  import { supportsClaudeAdaptiveThinking, isClaudeModelAlias, enforcesPreservedThinking, supportsMidConversationSystemMessages, supportsMidConversationToolChanges } from '@arco/shared';
35
35
  import { loadTokens, nativeCredentialBinding } from './auth.js';
36
+ import { ClaudeNativeAccountUnavailableError } from '../../providerAccounts.js';
36
37
  import { ensureLiveTokens, forceRefreshTokens, markClaudeAuthProblem, ClaudeNativeNoAuthError } from './oauth.js';
37
38
  import { resolveTrustStatus } from '../../projectTrust.js';
38
39
  import { isShellToolName } from '@arco/shared';
@@ -42,7 +43,7 @@ import { checkPartialReadFullWrite } from './pretoolGuards.js';
42
43
  import { firstBlockingGuard, postToolSteps, runPostToolSteps } from './toolChecks.js';
43
44
  import { evaluateGate, gateOutcome, gateSignature } from './gateReview.js';
44
45
  import { recordPendingGate, clearPendingGate, readGateStore, hasStandingApproval, addStandingApproval } from './gateStore.js';
45
- import { getCachedModelCapabilities, getCatalog, hasCatalogCache, resolveClaudeAliasFromCatalog } from './catalog.js';
46
+ import { getCachedModelCapabilities, getCatalog, resolveClaudeAliasFromCatalog } from './catalog.js';
46
47
  import { filterToolResult } from './filterToolResult.js';
47
48
  import { planTurnSpill, toolEvictEnabled, turnToolTokenBudget } from './toolResultEviction.js';
48
49
  import { outputHash } from '../outputSignature.js';
@@ -188,6 +189,7 @@ export class ClaudeNativeWorker extends EventEmitter {
188
189
  // against on-disk tokens and rebuild the client transparently.
189
190
  authRecovery = { transport: 'native', binding: nativeCredentialBinding() };
190
191
  clientTokenObtainedAt = null;
192
+ clientBinding;
191
193
  messages = [];
192
194
  heldSteerNotices = new WeakSet();
193
195
  hooks = { byEvent: {} };
@@ -621,6 +623,10 @@ export class ClaudeNativeWorker extends EventEmitter {
621
623
  // shouldn't change without a worker tear-down, but
622
624
  // appendSystemPrompt rotates per turn (skills manifest, transcript)
623
625
  // and effort/model can be live-edited.
626
+ if (this.config.providerAccountRef !== next.providerAccountRef) {
627
+ this.catalogWarmAttempted = false;
628
+ this.authFailureCount = 0;
629
+ }
624
630
  this.config = next;
625
631
  this.taskDisabled = this.taskDisabled || next.claudeNativeTaskDisabled === true;
626
632
  }
@@ -1339,20 +1345,22 @@ export class ClaudeNativeWorker extends EventEmitter {
1339
1345
  // worker built its client, ensureLiveTokens() returns the fresh set
1340
1346
  // and the obtainedAt mismatch below forces a client rebuild. Cheap:
1341
1347
  // ensureLiveTokens is a single disk read on the happy path.
1342
- const tokens = await ensureLiveTokens();
1343
- this.authRecovery = { transport: 'native', binding: nativeCredentialBinding(tokens) };
1348
+ const accountRef = this.config.providerAccountRef;
1349
+ const tokens = await ensureLiveTokens(accountRef);
1350
+ const binding = nativeCredentialBinding(tokens, accountRef);
1351
+ this.authRecovery = { transport: 'native', binding, ...(accountRef ? { accountRef } : {}) };
1344
1352
  // An alias tab can't be dispatched until the alias resolves to a concrete
1345
1353
  // id. Warm the catalog once per worker so the resolution is catalog-backed
1346
1354
  // (newest family member) rather than the static CLAUDE_ALIAS_FALLBACK.
1347
1355
  // Failure is non-fatal — the fallback still yields a real, dispatchable id.
1348
- if (!this.catalogWarmAttempted && isClaudeModelAlias(this.config.model) && !hasCatalogCache()) {
1356
+ if ((!this.catalogWarmAttempted || this.clientBinding?.revision !== binding.revision) && isClaudeModelAlias(this.config.model)) {
1349
1357
  this.catalogWarmAttempted = true;
1350
- await getCatalog(false).catch((err) => {
1358
+ await getCatalog(false, this.config.providerAccountRef).catch((err) => {
1351
1359
  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);
1352
1360
  });
1353
1361
  }
1354
1362
  const baseURL = await nativeOAuthBaseUrl();
1355
- if (this.client && this.clientTokenObtainedAt === tokens.obtainedAt && this.client.baseURL === baseURL)
1363
+ if (this.client && this.clientBinding?.storeId === binding.storeId && this.clientBinding.revision === binding.revision && this.client.baseURL === baseURL)
1356
1364
  return;
1357
1365
  const isRebuild = this.client !== null;
1358
1366
  if (isRebuild) {
@@ -1371,6 +1379,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1371
1379
  maxRetries: 0,
1372
1380
  });
1373
1381
  this.clientTokenObtainedAt = tokens.obtainedAt;
1382
+ this.clientBinding = binding;
1374
1383
  // Token-rotation rebuilds reuse the existing hooks + replayed state
1375
1384
  // and skip the worker-init emit. Hooks come from CLAUDE.md files,
1376
1385
  // unrelated to auth; replay only ever runs once per worker; 'init'
@@ -1411,7 +1420,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1411
1420
  // `not_found_error: model: opus`. Resolved per call, not cached: the operator
1412
1421
  // can live-swap the model through updateConfig mid-session.
1413
1422
  requestModel() {
1414
- return resolveClaudeAliasFromCatalog(this.config.model);
1423
+ return resolveClaudeAliasFromCatalog(this.config.model, this.config.providerAccountRef);
1415
1424
  }
1416
1425
  // Opus-5 plan Phase 2 — the model id capability decisions key on. For a
1417
1426
  // pinned concrete id this is always config.model; for an alias tab it is
@@ -1456,7 +1465,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1456
1465
  const parts = ['claude-code-20250219', 'oauth-2025-04-20'];
1457
1466
  if (shouldSendInterleavedThinkingBeta(this.capModel(), this.config.claudeNativeForceInterleavedThinkingBeta === true))
1458
1467
  parts.push('interleaved-thinking-2025-05-14');
1459
- const caps = getCachedModelCapabilities(this.capModel());
1468
+ const caps = getCachedModelCapabilities(this.capModel(), this.config.providerAccountRef);
1460
1469
  // compact is OFF by default for Native (NATIVE_COMPACTION_PLAN §1); the
1461
1470
  // beta is only attached when WorkflowConfig.claudeNativeCompact is the
1462
1471
  // explicit per-tab/global opt-in true. Once a server compaction block is
@@ -1624,7 +1633,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1624
1633
  // an empty object when no context-management feature is active so the
1625
1634
  // call site can spread it unconditionally.
1626
1635
  buildContextManagementBody() {
1627
- const caps = getCachedModelCapabilities(this.capModel());
1636
+ const caps = getCachedModelCapabilities(this.capModel(), this.config.providerAccountRef);
1628
1637
  const edits = buildContextManagementEditsForRequest(caps, this.config.claudeNativeCompact === true && !hasLeadingServerFoldBlock(this.messages));
1629
1638
  // Anthropic's server-managed compaction is an edit strategy, not a sibling
1630
1639
  // `context_management.compact` object. Let the model+server pick the
@@ -1634,17 +1643,17 @@ export class ClaudeNativeWorker extends EventEmitter {
1634
1643
  }
1635
1644
  async hydrateContextManagementCapabilities() {
1636
1645
  const model = this.capModel();
1637
- if (getCachedModelCapabilities(model))
1646
+ if (getCachedModelCapabilities(model, this.config.providerAccountRef))
1638
1647
  return;
1639
- await getCatalog(false).catch((err) => {
1648
+ await getCatalog(false, this.config.providerAccountRef).catch((err) => {
1640
1649
  console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] catalog warm-up failed:`, err instanceof Error ? err.message : err);
1641
1650
  });
1642
- if (getCachedModelCapabilities(model))
1651
+ if (getCachedModelCapabilities(model, this.config.providerAccountRef))
1643
1652
  return;
1644
1653
  if (this.forcedCatalogRefreshModels.has(model))
1645
1654
  return;
1646
1655
  this.forcedCatalogRefreshModels.add(model);
1647
- await getCatalog(true).catch((err) => {
1656
+ await getCatalog(true, this.config.providerAccountRef).catch((err) => {
1648
1657
  console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] catalog force-refresh failed for ${model}:`, err instanceof Error ? err.message : err);
1649
1658
  });
1650
1659
  }
@@ -2591,22 +2600,28 @@ export class ClaudeNativeWorker extends EventEmitter {
2591
2600
  await this.ensureStarted();
2592
2601
  }
2593
2602
  catch (err) {
2603
+ const accountRef = this.config.providerAccountRef;
2604
+ if (err instanceof ClaudeNativeAccountUnavailableError) {
2605
+ this.emit('system_notice', `[AUTH:claude] ${err.message}`, { transport: 'native', accountRef, accountUnavailable: true });
2606
+ this.emit('error', 'claude account unavailable');
2607
+ return;
2608
+ }
2594
2609
  try {
2595
- this.authRecovery = { transport: 'native', binding: nativeCredentialBinding(await loadTokens()) };
2610
+ this.authRecovery = { transport: 'native', ...(accountRef ? { accountRef } : {}), binding: nativeCredentialBinding(await loadTokens(accountRef), accountRef) };
2596
2611
  }
2597
2612
  catch {
2598
- this.authRecovery = { transport: 'native' };
2613
+ this.authRecovery = { transport: 'native', ...(accountRef ? { accountRef } : {}) };
2599
2614
  }
2600
2615
  // Pre-flight auth surface: emit the [AUTH:claude] sentinel so the
2601
2616
  // chat renderer offers RE-LOGIN instead of a raw error string.
2602
2617
  if (err instanceof ClaudeNativeNoAuthError) {
2603
- markClaudeAuthProblem('not authenticated'); // A2 — phone banner + notice
2618
+ markClaudeAuthProblem('not authenticated', accountRef); // A2 — phone banner + notice
2604
2619
  this.emit('system_notice', '[AUTH:claude] Claude Native is not authenticated. Re-login to continue.', this.authRecovery);
2605
2620
  this.emit('error', 'claude auth required');
2606
2621
  return;
2607
2622
  }
2608
2623
  const detail = err instanceof Error ? err.message : String(err);
2609
- markClaudeAuthProblem(detail); // A2 — pre-flight refresh failure
2624
+ markClaudeAuthProblem(detail, accountRef); // A2 — pre-flight refresh failure
2610
2625
  this.emit('system_notice', `[AUTH:claude] Claude Native auth failed: ${detail}. Re-login to continue.`, this.authRecovery);
2611
2626
  this.emit('error', 'claude auth failed');
2612
2627
  return;
@@ -4101,7 +4116,7 @@ export class ClaudeNativeWorker extends EventEmitter {
4101
4116
  const cwd = this.config.persistenceCwd ?? this.config.cwd;
4102
4117
  return !this.config.incognito && cwd && WFID_PATTERN.test(this.workflowId) ? join(workflowDir(cwd, this.workflowId), 'pending-subagent-approval.json') : null;
4103
4118
  }
4104
- async batchCatalog(force) { return await getCatalog(force); }
4119
+ async batchCatalog(force) { return await getCatalog(force, this.config.providerAccountRef); }
4105
4120
  async approveTaskBatch(blocks) {
4106
4121
  if (!blocks.length)
4107
4122
  return true;
@@ -4167,7 +4182,7 @@ export class ClaudeNativeWorker extends EventEmitter {
4167
4182
  }
4168
4183
  const available = current.models.map((m) => m.id);
4169
4184
  const proposed = selected ? [selected] : entries.map((e) => e.effective);
4170
- if (proposed.some((model) => !available.includes(model) && !available.includes(resolveClaudeAliasFromCatalog(model)))) {
4185
+ if (proposed.some((model) => !available.includes(model) && !available.includes(resolveClaudeAliasFromCatalog(model, this.config.providerAccountRef)))) {
4171
4186
  this.taskBatchRefusal = 'Task not started: a selected model is no longer available.';
4172
4187
  this.emit('system_notice', 'Sub-agent batch not started: a selected model is no longer available.');
4173
4188
  return false;
@@ -4301,7 +4316,7 @@ export class ClaudeNativeWorker extends EventEmitter {
4301
4316
  summary: finalText.slice(0, 200),
4302
4317
  });
4303
4318
  const overridden = spawnPolicy.model && args.model
4304
- && resolveClaudeAliasFromCatalog(spawnPolicy.model) !== resolveClaudeAliasFromCatalog(args.model);
4319
+ && resolveClaudeAliasFromCatalog(spawnPolicy.model, this.config.providerAccountRef) !== resolveClaudeAliasFromCatalog(args.model, this.config.providerAccountRef);
4305
4320
  return overridden
4306
4321
  ? `${finalText}\n\nSub-agent used ${chosenModel ?? handle.model ?? spawnPolicy.model}: the operator's model selection overrides the requested ${args.model}.`
4307
4322
  : finalText;
@@ -4370,7 +4385,7 @@ export class ClaudeNativeWorker extends EventEmitter {
4370
4385
  if (!this.forcedAuthRefreshThisTurn && attempt < MAX_RETRY_ATTEMPTS - 1) {
4371
4386
  this.forcedAuthRefreshThisTurn = true;
4372
4387
  try {
4373
- await forceRefreshTokens(this.clientTokenObtainedAt ?? 0);
4388
+ await forceRefreshTokens(this.clientTokenObtainedAt ?? 0, this.config.providerAccountRef);
4374
4389
  // On-disk tokens rotated → obtainedAt mismatch → client rebuild.
4375
4390
  await this.ensureStarted();
4376
4391
  console.log(`[claude-native:${this.workflowId.slice(0, 8)}] 401 on unexpired token — forced refresh ok, retrying`);
@@ -4385,10 +4400,10 @@ export class ClaudeNativeWorker extends EventEmitter {
4385
4400
  }
4386
4401
  }
4387
4402
  this.authFailureCount += 1;
4388
- const detail = msg || 'Invalid authentication credentials';
4403
+ const detail = 'The provider rejected this account credentials';
4389
4404
  // A2 — flip the live auth-problem flag (phone console banner + one
4390
4405
  // auth-expired notice). Cleared by a successful refresh/bootstrap.
4391
- markClaudeAuthProblem(detail);
4406
+ markClaudeAuthProblem(detail, this.config.providerAccountRef);
4392
4407
  const loud = this.authFailureCount >= AUTH_FAILURE_LOUD_THRESHOLD;
4393
4408
  const prefix = loud
4394
4409
  ? `[AUTH:claude] Repeated Claude auth failures (${this.authFailureCount}). Re-login required to continue.`
@@ -1,18 +1,20 @@
1
- import type { OperatorQuestionState } from '@arco/shared';
1
+ import type { OperatorQuestionState, OperatorQuestion } from '@arco/shared';
2
2
  import type { JsonRpcId, JsonRpcServerRequest } from './jsonRpc.js';
3
+ type Answers = Record<string, string[]>;
3
4
  type SendInput = (content: string, question: OperatorQuestionState) => Promise<void>;
4
5
  interface Pending {
5
6
  workflowId: string;
6
7
  state: OperatorQuestionState;
7
8
  rpcId?: JsonRpcId;
8
- respond?: (result: unknown) => boolean | void;
9
+ respond?: (answers: Answers | null) => boolean | void;
9
10
  publish: (state: OperatorQuestionState) => void;
10
- owner: CodexOperatorQuestions;
11
+ finish: (state: OperatorQuestionState) => void;
11
12
  sending: boolean;
12
13
  }
13
14
  declare let publisher: ((workflowId: string, state: OperatorQuestionState) => void) | undefined;
14
15
  export declare function setOperatorQuestionPublisher(publish: NonNullable<typeof publisher>): void;
15
16
  export declare function pendingOperatorQuestions(workflowId: string): OperatorQuestionState[];
17
+ export declare function openGeminiOperatorQuestion(workflowId: string, sessionId: string, questions: OperatorQuestion[], respond: NonNullable<Pending['respond']>): () => void;
16
18
  export declare function replyToOperatorQuestion(workflowId: string, requestId: string, value: unknown, sendInput?: SendInput): Promise<{
17
19
  ok: boolean;
18
20
  error?: string;