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
@@ -338,17 +338,36 @@ export async function loadKernel(cwd, boardKey) {
338
338
  const snapshot = await readKernelSnapshot(cwd, boardKey);
339
339
  if (snapshot !== null)
340
340
  return snapshot;
341
- const tasks = await rebuildFromEvents(cwd, boardKey);
342
- const comments = await rebuildCommentsFromEvents(cwd, boardKey);
343
- const runs = await rebuildRunsFromEvents(cwd, boardKey);
344
- const proposalReceipts = {};
345
- for (const event of await taskLedgerEvents(cwd, boardKey)) {
346
- const receipt = event.payload?.proposalReceipt;
347
- if (typeof receipt?.key === 'string' && typeof receipt.taskId === 'string')
348
- proposalReceipts[receipt.key] = receipt.taskId;
349
- }
350
- await saveKernel(cwd, { tasks, comments, runs, proposalReceipts }, boardKey).catch(() => { });
351
- return { tasks, comments, runs, proposalReceipts };
341
+ return rebuildKernelOnce(cwd, boardKey);
342
+ }
343
+ // Without a snapshot the board is folded from every conversation's log in the
344
+ // project. Reconnecting tabs of one project each ask for the board at once, so
345
+ // concurrent requests share one rebuild: N tabs used to start N rebuilds, each
346
+ // reading all N logs again, and the server answered none of them for many
347
+ // seconds on a project with long histories.
348
+ const kernelRebuilds = new Map();
349
+ function rebuildKernelOnce(cwd, boardKey) {
350
+ const key = `${cwd}\0${sanitizeBoardKey(boardKey) ?? ''}`;
351
+ const running = kernelRebuilds.get(key);
352
+ if (running)
353
+ return running;
354
+ const started = (async () => {
355
+ // One pass over the logs gives the tasks, comments, runs and receipts.
356
+ const events = await taskLedgerEvents(cwd, boardKey);
357
+ const tasks = foldTasks(events);
358
+ const comments = foldComments(events);
359
+ const runs = foldRuns(events);
360
+ const proposalReceipts = {};
361
+ for (const event of events) {
362
+ const receipt = event.payload?.proposalReceipt;
363
+ if (typeof receipt?.key === 'string' && typeof receipt.taskId === 'string')
364
+ proposalReceipts[receipt.key] = receipt.taskId;
365
+ }
366
+ await saveKernel(cwd, { tasks, comments, runs, proposalReceipts }, boardKey).catch(() => { });
367
+ return { tasks, comments, runs, proposalReceipts };
368
+ })().finally(() => { kernelRebuilds.delete(key); });
369
+ kernelRebuilds.set(key, started);
370
+ return started;
352
371
  }
353
372
  export async function saveKernel(cwd, state, boardKey) {
354
373
  if (!cwd)
@@ -461,25 +480,7 @@ export function formatBoardForModel(tasks) {
461
480
  function eventBelongsToBoard(ev, boardKey) {
462
481
  return sanitizeBoardKey(ev.boardKey) === sanitizeBoardKey(boardKey);
463
482
  }
464
- export async function rebuildFromEvents(cwd, boardKey) {
465
- if (!cwd)
466
- return [];
467
- const metas = await listWorkflowMetas(cwd).catch(() => []);
468
- const events = [];
469
- for (const meta of metas) {
470
- const msgs = await replayEvents(cwd, meta.workflowId, 0).catch(() => []);
471
- for (const m of msgs) {
472
- if (m.type !== 'task_ledger_event')
473
- continue;
474
- const ev = m;
475
- // Only fold events for THIS cwd (a workflow's log is cwd-local, but the
476
- // event carries cwd explicitly — guard against a moved log).
477
- if (ev.cwd !== cwd || !eventBelongsToBoard(ev, boardKey))
478
- continue;
479
- events.push({ ...ev, seq: ev.seq ?? 0 });
480
- }
481
- }
482
- events.sort((a, b) => (a.at - b.at) || (a.seq - b.seq));
483
+ function foldTasks(events) {
483
484
  const byId = new Map();
484
485
  for (const ev of events) {
485
486
  if (ev.op === 'delete') {
@@ -492,6 +493,11 @@ export async function rebuildFromEvents(cwd, boardKey) {
492
493
  }
493
494
  return [...byId.values()].sort((a, b) => a.createdAt - b.createdAt);
494
495
  }
496
+ export async function rebuildFromEvents(cwd, boardKey) {
497
+ if (!cwd)
498
+ return [];
499
+ return foldTasks(await taskLedgerEvents(cwd, boardKey));
500
+ }
495
501
  async function taskLedgerEvents(cwd, boardKey) {
496
502
  if (!cwd)
497
503
  return [];
@@ -511,9 +517,9 @@ async function taskLedgerEvents(cwd, boardKey) {
511
517
  events.sort((a, b) => (a.at - b.at) || (a.seq - b.seq));
512
518
  return events;
513
519
  }
514
- export async function rebuildCommentsFromEvents(cwd, boardKey) {
520
+ function foldComments(events) {
515
521
  const comments = [];
516
- for (const ev of await taskLedgerEvents(cwd, boardKey)) {
522
+ for (const ev of events) {
517
523
  const comment = ev.payload?.comment;
518
524
  if (isTaskComment(comment)) {
519
525
  comments.push(normalizeComment(comment));
@@ -522,9 +528,12 @@ export async function rebuildCommentsFromEvents(cwd, boardKey) {
522
528
  comments.sort((a, b) => a.createdAt - b.createdAt);
523
529
  return comments;
524
530
  }
525
- export async function rebuildRunsFromEvents(cwd, boardKey) {
531
+ export async function rebuildCommentsFromEvents(cwd, boardKey) {
532
+ return foldComments(await taskLedgerEvents(cwd, boardKey));
533
+ }
534
+ function foldRuns(events) {
526
535
  const byId = new Map();
527
- for (const ev of await taskLedgerEvents(cwd, boardKey)) {
536
+ for (const ev of events) {
528
537
  const run = ev.payload?.run;
529
538
  if ((ev.op === 'run_started'
530
539
  || ev.op === 'run_completed'
@@ -539,6 +548,9 @@ export async function rebuildRunsFromEvents(cwd, boardKey) {
539
548
  }
540
549
  return [...byId.values()].sort((a, b) => a.startedAt - b.startedAt);
541
550
  }
551
+ export async function rebuildRunsFromEvents(cwd, boardKey) {
552
+ return foldRuns(await taskLedgerEvents(cwd, boardKey));
553
+ }
542
554
  // ── mutation helpers (pure — caller persists + emits the event) ──────────────
543
555
  export function newTask(input) {
544
556
  const now = Date.now();
@@ -7,5 +7,9 @@ export interface ResolvedProviderAccount {
7
7
  export declare function expandHomePath(p: string): string;
8
8
  export declare function accountShortLabel(profile: ProviderAccountProfile): string;
9
9
  export declare function configuredAccounts(provider: 'codex' | 'claude', cwd?: string): Promise<ProviderAccountProfile[]>;
10
+ export declare class ClaudeNativeAccountUnavailableError extends Error {
11
+ constructor();
12
+ }
13
+ export declare function requireClaudeNativeAccount(accountRef?: string): Promise<string>;
10
14
  export declare function resolveProviderAccount(provider: ProviderName, accountRef: string | undefined, cwd?: string): Promise<ResolvedProviderAccount | null>;
11
15
  export declare function ensureCodexAccountHome(codexHome: string): Promise<void>;
@@ -1,7 +1,7 @@
1
1
  import { mkdir, readFile, writeFile } from 'fs/promises';
2
2
  import { dirname, join, resolve } from 'path';
3
3
  import { homedir } from 'os';
4
- import { TERMINAL_CODEX_ACCOUNT } from '@arco/shared';
4
+ import { DEFAULT_CLAUDE_NATIVE_ACCOUNT, isClaudeNativeProfileId, TERMINAL_CODEX_ACCOUNT } from '@arco/shared';
5
5
  import { readSettings } from './settings.js';
6
6
  import { arcoHome } from './arcoHome.js';
7
7
  export function expandHomePath(p) {
@@ -22,6 +22,25 @@ export async function configuredAccounts(provider, cwd) {
22
22
  const settings = await readSettings(cwd).catch(() => null);
23
23
  return settings?.providerAccounts?.[provider] ?? [];
24
24
  }
25
+ export class ClaudeNativeAccountUnavailableError extends Error {
26
+ constructor() {
27
+ super('The saved Claude Native account is unavailable. Choose an account in CONFIG before sending again.');
28
+ this.name = 'ClaudeNativeAccountUnavailableError';
29
+ }
30
+ }
31
+ // Native keeps the original store for unbound workflows. Legacy Claude labels
32
+ // were never credential bindings and cannot opt an old tab into a new sign-in.
33
+ export async function requireClaudeNativeAccount(accountRef) {
34
+ if (accountRef === undefined || accountRef === DEFAULT_CLAUDE_NATIVE_ACCOUNT)
35
+ return DEFAULT_CLAUDE_NATIVE_ACCOUNT;
36
+ if (isClaudeNativeProfileId(accountRef)) {
37
+ const settings = await readSettings();
38
+ if (settings.providerAccounts?.claudeNative?.some(profile => profile.id === accountRef)
39
+ && !settings.providerAccounts.claude?.some(profile => profile.id === accountRef))
40
+ return accountRef;
41
+ }
42
+ throw new ClaudeNativeAccountUnavailableError();
43
+ }
25
44
  export async function resolveProviderAccount(provider, accountRef, cwd) {
26
45
  if (provider !== 'codex' && provider !== 'claude')
27
46
  return null;
@@ -0,0 +1,23 @@
1
+ export declare function geminiSessionKey(file: string): string | null | undefined;
2
+ export declare function collectGeminiArtifacts(opts: {
3
+ sessionId: string;
4
+ storeCwd: string;
5
+ workflowId: string;
6
+ }): Promise<void>;
7
+ export declare function listGeminiArtifacts(cwd: string, workflowId: string): Promise<{
8
+ id: string;
9
+ path: string;
10
+ name: string;
11
+ size: number;
12
+ mtime: number;
13
+ }[]>;
14
+ export declare function openGeminiArtifact(cwd: string, workflowId: string, selector: {
15
+ key: string;
16
+ } | {
17
+ id: string;
18
+ }): Promise<{
19
+ id: string;
20
+ handle: import("fs/promises").FileHandle;
21
+ info: import("fs").Stats;
22
+ file: string;
23
+ }>;
@@ -0,0 +1,140 @@
1
+ // The CLI owns its session files. Only names observed at turn completion are
2
+ // recorded, independently of writable project metadata. No Gemini directory
3
+ // becomes a general file, media, editor or download root.
4
+ import { createHash } from 'node:crypto';
5
+ import { homedir } from 'node:os';
6
+ import path from 'node:path';
7
+ import { readdir, realpath } from 'node:fs/promises';
8
+ import { arcoHome } from '../../arcoHome.js';
9
+ import { atomicWriteFile, withFileLock } from '../../atomicFile.js';
10
+ import { openCheckedFile } from '../../checkedFile.js';
11
+ import { assertSpellingSafe, FileAccessError } from '../../fileAccessPolicy.js';
12
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+ const MAX_BYTES = 25 * 1024 * 1024;
14
+ const skipped = new Set(['scratch', 'logs', 'worktrees', 'raw-tools']);
15
+ const digest = (value) => createHash('sha256').update(value).digest('hex');
16
+ function validName(key) {
17
+ const [session, ...parts] = key.split('/');
18
+ // Apply ordinary browser filename rules below the one authorized provider
19
+ // directory. Its parent is deliberately outside the general browser roots.
20
+ try {
21
+ assertSpellingSafe('/' + key, path.posix);
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ return UUID.test(session) && parts.length >= 1 && parts.length <= 4 && parts.every(part => part.length > 0 && !part.startsWith('.') && !/[\\:\x00-\x1f]/.test(part)
27
+ && !/[. ]$/.test(part) && !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)
28
+ && !/\.metadata\.json$|\.resolved(?:\.\d+)?$/i.test(part))
29
+ && parts.slice(0, -1).every(part => !skipped.has(part.toLowerCase()));
30
+ }
31
+ export function geminiSessionKey(file) {
32
+ const match = /[\\/]\.gemini[\\/]antigravity-cli[\\/]brain[\\/](.*)$/i.exec(file);
33
+ if (!match)
34
+ return undefined;
35
+ const [session, ...parts] = match[1].split(/[\\/]/);
36
+ const key = [session.toLowerCase(), ...parts].join('/');
37
+ return validName(key) ? key : null;
38
+ }
39
+ async function manifest(cwd, workflowId) {
40
+ return path.join(arcoHome(), 'gemini-artifacts-' + digest(JSON.stringify([await realpath(cwd), workflowId])) + '.json');
41
+ }
42
+ async function names(file) {
43
+ const handle = await openCheckedFile(file).catch(error => {
44
+ if (error.code !== 'ENOENT')
45
+ throw error;
46
+ return null;
47
+ });
48
+ if (!handle)
49
+ return [];
50
+ try {
51
+ if ((await handle.stat()).size > 8 * 1024 * 1024)
52
+ throw new FileAccessError();
53
+ const rows = JSON.parse(await handle.readFile('utf8'));
54
+ if (!Array.isArray(rows) || rows.length > 2000 || !rows.every(row => typeof row === 'string' && validName(row)))
55
+ throw new FileAccessError();
56
+ return rows;
57
+ }
58
+ finally {
59
+ await handle.close();
60
+ }
61
+ }
62
+ async function brainRoot() {
63
+ return path.join(await realpath(homedir()), '.gemini', 'antigravity-cli', 'brain');
64
+ }
65
+ // Recheck the spelling, link count and size for each listing and each read.
66
+ // Callers serve bytes from this same handle, up to the checked size.
67
+ async function openArtifact(root, key) {
68
+ const file = path.join(root, ...key.split('/'));
69
+ const handle = await openCheckedFile(file);
70
+ try {
71
+ const info = await handle.stat();
72
+ if (info.nlink !== 1 || info.size > MAX_BYTES)
73
+ throw new FileAccessError();
74
+ return { handle, info, file };
75
+ }
76
+ catch (error) {
77
+ await handle.close();
78
+ throw error;
79
+ }
80
+ }
81
+ export async function collectGeminiArtifacts(opts) {
82
+ const session = opts.sessionId.toLowerCase();
83
+ if (!UUID.test(session))
84
+ return;
85
+ const root = await brainRoot();
86
+ const found = [];
87
+ async function walk(prefix, depth) {
88
+ const dir = path.join(root, ...prefix.split('/'));
89
+ if (await realpath(dir).catch(() => '') !== dir)
90
+ return;
91
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
92
+ if (found.length >= 200)
93
+ break;
94
+ const key = prefix + '/' + entry.name;
95
+ if (!validName(key))
96
+ continue;
97
+ if (entry.isDirectory() && depth < 3 && !skipped.has(entry.name.toLowerCase()))
98
+ await walk(key, depth + 1);
99
+ else if (entry.isFile()) {
100
+ const opened = await openArtifact(root, key).catch(() => null);
101
+ if (opened) {
102
+ await opened.handle.close();
103
+ found.push(key);
104
+ }
105
+ }
106
+ }
107
+ }
108
+ await walk(session, 0);
109
+ const file = await manifest(opts.storeCwd, opts.workflowId);
110
+ await withFileLock(file, async () => {
111
+ const previous = await names(file);
112
+ const next = previous.filter(key => !key.startsWith(session + '/')).concat(found).slice(-2000);
113
+ if (JSON.stringify(next) !== JSON.stringify(previous))
114
+ await atomicWriteFile(file, JSON.stringify(next), { mode: 0o600, skipMkdir: true });
115
+ });
116
+ }
117
+ const idFor = (key) => 'gemini-' + digest(key);
118
+ export async function listGeminiArtifacts(cwd, workflowId) {
119
+ const keys = await names(await manifest(cwd, workflowId));
120
+ const rows = [];
121
+ if (keys.length) {
122
+ const root = await brainRoot();
123
+ for (const key of keys) {
124
+ const opened = await openArtifact(root, key).catch(() => null);
125
+ if (!opened)
126
+ continue;
127
+ await opened.handle.close();
128
+ rows.push({ id: idFor(key), path: opened.file, name: path.basename(opened.file), size: opened.info.size, mtime: opened.info.mtimeMs });
129
+ }
130
+ }
131
+ return rows;
132
+ }
133
+ export async function openGeminiArtifact(cwd, workflowId, selector) {
134
+ const keys = await names(await manifest(cwd, workflowId));
135
+ const key = keys.find(item => 'key' in selector ? item === selector.key : idFor(item) === selector.id);
136
+ if (!key)
137
+ throw new FileAccessError();
138
+ return { ...await openArtifact(await brainRoot(), key), id: idFor(key) };
139
+ }
140
+ //# sourceMappingURL=artifacts.js.map
@@ -1,3 +1,6 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
1
4
  import { resolve as resolvePath } from 'node:path';
2
5
  import { findDiagnosticExecutable } from '../../diagnostics/executableLookup.js';
3
6
  import { loadResearch, researcherFor } from '../../research/researchState.js';
@@ -9,8 +12,9 @@ import { GEMINI_RESEARCH_SIGN_IN_NEEDED, noteGeminiResearchSignInExpired, readGe
9
12
  import { historyBinding } from '../handoffHistoryBinding.js';
10
13
  import { ensureClusterLoopbackMcp, closeClusterLoopbackMcp } from '../../mcp/clusterMcpLoopback.js';
11
14
  import { prepareProviderAttachments } from '../providerFileContent.js';
15
+ import { collectGeminiArtifacts } from './artifacts.js';
12
16
  import { noteAntigravityTurnSuccess, noteAntigravitySignInRequired } from './status.js';
13
- import { lstat, realpath } from 'node:fs/promises';
17
+ import { mkdir, mkdtemp, rm, writeFile, lstat, realpath } from 'node:fs/promises';
14
18
  import { dirname, isAbsolute, relative, sep } from 'node:path';
15
19
  import { arcoHome } from '../../arcoHome.js';
16
20
  import { isIncognitoChatCwd, antigravityChatWorkspace } from '../../chatMode.js';
@@ -22,6 +26,7 @@ import { resolveCommand } from '../../windowsCommand.js';
22
26
  import { killProcessTree } from '../../workers/processKill.js';
23
27
  import { probeVersion } from '../../capabilities.js';
24
28
  import { compareVersions } from '../../updateCheck.js';
29
+ import { askGeminiQuestion } from './questions.js';
25
30
  export class AntigravitySubagentNotice {
26
31
  version;
27
32
  shown = false;
@@ -39,6 +44,28 @@ export class AntigravitySubagentNotice {
39
44
  }
40
45
  }
41
46
  export function permittedAgyModel(id) { return /^gemini-[a-z0-9.-]+$/.test(id); }
47
+ // ACP applies a selected custom agent to session/new. Loading an old session
48
+ // restores its original tools. Summaries therefore use a fresh private
49
+ // workspace, a unique reply-only agent, and the bounded transcript as input.
50
+ async function createHandoffWriter() {
51
+ const cwd = await mkdtemp(join(tmpdir(), 'arco-handoff-'));
52
+ const name = 'handoff-' + randomUUID();
53
+ const dir = join(cwd, '.agents', 'agents');
54
+ try {
55
+ await mkdir(dir, { recursive: true });
56
+ await writeFile(join(dir, name + '.md'), [
57
+ '---', 'name: ' + name, 'description: Write a handoff document.',
58
+ 'mainAgent: true', 'subagent: false', 'tools: [send_message]',
59
+ 'inheritMcp: false', 'inheritCustomizations: false', 'commandExecutionPolicy: "off"',
60
+ '---', 'Write the document from the supplied conversation and return it as text.',
61
+ ].join('\n'), { mode: 0o600 });
62
+ return { cwd, name };
63
+ }
64
+ catch (error) {
65
+ await rm(cwd, { recursive: true, force: true });
66
+ throw error;
67
+ }
68
+ }
42
69
  class AntigravityTurn extends EventEmitter {
43
70
  id;
44
71
  config;
@@ -50,6 +77,8 @@ class AntigravityTurn extends EventEmitter {
50
77
  startedAt = 0;
51
78
  contextSize;
52
79
  contextUsed;
80
+ sessionId;
81
+ artifactsCollected = false;
53
82
  constructor(id, config) {
54
83
  super();
55
84
  this.id = id;
@@ -74,6 +103,7 @@ class AntigravityTurn extends EventEmitter {
74
103
  noteAntigravitySignInRequired();
75
104
  }
76
105
  cancelAcpPermissions(this.config.workflowId ?? '');
106
+ void this.collectArtifacts();
77
107
  if (this.config.workflowId)
78
108
  closeClusterLoopbackMcp(this.config.workflowId);
79
109
  this.rpc?.close('turn finished');
@@ -82,6 +112,20 @@ class AntigravityTurn extends EventEmitter {
82
112
  this.emit('error', message);
83
113
  }
84
114
  kill() { this.fail(new Error('Turn cancelled.')); }
115
+ // Finished filenames of this session are registered for this workflow once
116
+ // per turn. A researcher's session lives in its fenced home and is skipped.
117
+ async collectArtifacts() {
118
+ const workflowId = this.config.workflowId, storeCwd = this.config.persistenceCwd ?? this.config.cwd;
119
+ if (this.config.antigravityHandoffWriter || this.artifactsCollected || !this.sessionId || !workflowId || !storeCwd || this.config.clusterAccessMode === 'researcher')
120
+ return;
121
+ this.artifactsCollected = true;
122
+ try {
123
+ await collectGeminiArtifacts({ sessionId: this.sessionId, storeCwd, workflowId });
124
+ }
125
+ catch {
126
+ this.emit('system_notice', 'Gemini artifacts from this turn could not be listed in Outputs.');
127
+ }
128
+ }
85
129
  // docs/RESEARCH.md "Gemini researchers": a researcher runs only inside the
86
130
  // worker fence, with its own copy of the separate research sign-in.
87
131
  async prepareFence(workflowId) {
@@ -109,14 +153,19 @@ class AntigravityTurn extends EventEmitter {
109
153
  }
110
154
  async run(prompt) {
111
155
  const workflowId = this.config.workflowId;
112
- if (!workflowId || this.config.antigravityInteractive !== true || this.config.interactionMode !== 'agent' || this.config.sandbox || this.config.voiceOperator)
113
- throw new Error('Antigravity runs only on an interactive message the operator sent.');
156
+ const writer = this.config.antigravityHandoffWriter === true;
157
+ const authorized = writer
158
+ ? this.config.sandbox === 'read-only' && !this.config.resumeSessionId && !this.config.clusterId && !this.config.clusterAccessMode
159
+ : this.config.antigravityInteractive === true && this.config.interactionMode === 'agent' && !this.config.sandbox;
160
+ if (!workflowId || !authorized || this.config.voiceOperator || this.config.incognito)
161
+ throw new Error('Antigravity runs only on an interactive message the operator sent or a requested handoff.');
114
162
  if (!permittedAgyModel(this.config.model))
115
163
  throw new Error('Antigravity requires a Gemini model.');
116
164
  const subagentNotice = new AntigravitySubagentNotice(await probeVersion('agy'));
117
165
  if (this.finished)
118
166
  return;
119
167
  const researcher = this.config.clusterAccessMode === 'researcher';
168
+ const supportsQuestions = !writer && !researcher && !this.config.clusterResearchDirector && prompt.trim() !== '/compact';
120
169
  let fenced;
121
170
  let cwd;
122
171
  if (researcher) {
@@ -144,9 +193,20 @@ class AntigravityTurn extends EventEmitter {
144
193
  throw new Error('The Antigravity Chat working folder does not match this Chat.');
145
194
  this.startedAt = Date.now();
146
195
  }
196
+ const writerWorkspace = writer ? await createHandoffWriter() : undefined;
197
+ if (writerWorkspace)
198
+ cwd = writerWorkspace.cwd;
199
+ const removeWriter = () => writerWorkspace && rm(writerWorkspace.cwd, { recursive: true, force: true }).catch(() => { });
200
+ if (this.finished) {
201
+ await removeWriter();
202
+ await fenced?.close();
203
+ return;
204
+ }
147
205
  const proc = fenced
148
206
  ? spawn(fenced.command.file, fenced.command.args, { cwd: '/', env: { PATH: '/usr/bin:/bin' }, stdio: ['pipe', 'pipe', 'pipe'], detached: true })
149
- : (() => { const agy = resolveCommand('agy', ['acp'], { fresh: true }); return spawn(agy.command, agy.args, { cwd, ...(agy.env ? { env: agy.env } : {}), stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32' }); })();
207
+ : (() => { const agy = resolveCommand('agy', writerWorkspace ? ['acp', '--agent', writerWorkspace.name] : ['acp'], { fresh: true }); return spawn(agy.command, agy.args, { cwd, ...(agy.env ? { env: agy.env } : {}), stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32' }); })();
208
+ if (writerWorkspace)
209
+ proc.once('close', () => { void removeWriter(); });
150
210
  if (fenced) {
151
211
  const launch = fenced;
152
212
  proc.once('close', () => { void launch.close().catch(() => this.emit('system_notice', 'Worker isolation cleanup failed.')); });
@@ -159,9 +219,23 @@ class AntigravityTurn extends EventEmitter {
159
219
  if (!proc.stdin || !proc.stdout)
160
220
  throw new Error('Antigravity ACP streams unavailable.');
161
221
  const rpc = this.rpc = new AcpJsonRpcClient(proc.stdin, proc.stdout);
222
+ let questionPending = false;
162
223
  rpc.onRequest = async (request) => {
224
+ if (writer && request.method === 'session/request_permission')
225
+ return { outcome: { outcome: 'cancelled' } };
163
226
  if (request.method === 'session/request_permission')
164
227
  return requestAcpPermission(workflowId, request.params, this.config.skipPermissions === true);
228
+ if (request.method === 'elicitation/create' && supportsQuestions && this.sessionId && this._status === 'running') {
229
+ if (questionPending)
230
+ return { action: 'decline' };
231
+ questionPending = true;
232
+ try {
233
+ return await askGeminiQuestion(rpc, workflowId, this.sessionId, request.params);
234
+ }
235
+ finally {
236
+ questionPending = false;
237
+ }
238
+ }
165
239
  throw new AcpReplyError(-32601, `Method not supported: ${request.method}`);
166
240
  };
167
241
  rpc.on('notification', (notification) => {
@@ -187,8 +261,8 @@ class AntigravityTurn extends EventEmitter {
187
261
  this.emit('tool_use', { id: update.toolCallId, name: update.name === 'invoke_subagent' ? 'invoke_subagent' : update.title ?? 'Antigravity tool', input: JSON.stringify(update.rawInput ?? {}), status: update.status === 'completed' ? 'completed' : update.status === 'failed' ? 'failed' : 'in_progress', ...(update.rawOutput !== undefined ? { output: JSON.stringify(update.rawOutput) } : {}) });
188
262
  }
189
263
  });
190
- await rpc.request('initialize', { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: 'Arco', version: '1' } });
191
- const bridge = fenced ? { name: 'arco-cluster', url: fenced.mailUrl } : await ensureClusterLoopbackMcp({
264
+ await rpc.request('initialize', { protocolVersion: 1, clientCapabilities: supportsQuestions ? { elicitation: { form: {} } } : {}, clientInfo: { name: 'Arco', version: '1' } });
265
+ const bridge = writer ? undefined : fenced ? { name: 'arco-cluster', url: fenced.mailUrl } : await ensureClusterLoopbackMcp({
192
266
  workflowId, clusterId: this.config.clusterId ?? '', cwd,
193
267
  arcoPort: parseInt(process.env.ARCO_PORT || '3001', 10),
194
268
  taskBoardAttached: this.config.clusterTaskBoardAttached === true,
@@ -202,7 +276,7 @@ class AntigravityTurn extends EventEmitter {
202
276
  closeClusterLoopbackMcp(workflowId);
203
277
  return;
204
278
  }
205
- const args = { cwd, mcpServers: [{ type: 'http', name: bridge.name, url: bridge.url, headers: [] }] };
279
+ const args = { cwd, mcpServers: bridge ? [{ type: 'http', name: bridge.name, url: bridge.url, headers: [] }] : [] };
206
280
  const result = await rpc.request(this.config.resumeSessionId ? 'session/load' : 'session/new', this.config.resumeSessionId ? { ...args, sessionId: this.config.resumeSessionId } : args);
207
281
  const mode = result.configOptions?.find(x => x.id === 'mode');
208
282
  if (mode?.options?.some(x => x.value === 'default'))
@@ -218,6 +292,7 @@ class AntigravityTurn extends EventEmitter {
218
292
  throw new Error('This thinking level is not offered for the selected Antigravity model.');
219
293
  if (effort)
220
294
  await rpc.request('session/set_config_option', { sessionId: result.sessionId, configId: 'thought_level', value: this.config.effort });
295
+ this.sessionId = result.sessionId;
221
296
  this._status = 'running';
222
297
  this.emit('init', { model: this.config.model, sessionId: result.sessionId });
223
298
  if (fenced && this.config.clusterId)
@@ -227,6 +302,9 @@ class AntigravityTurn extends EventEmitter {
227
302
  const answer = await rpc.request('session/prompt', { sessionId: result.sessionId, prompt: content });
228
303
  if (answer.stopReason === 'cancelled')
229
304
  throw new Error('Turn cancelled.');
305
+ if (this.finished)
306
+ return;
307
+ await this.collectArtifacts();
230
308
  if (this.finished)
231
309
  return;
232
310
  this.finished = true;
@@ -0,0 +1,2 @@
1
+ import { AcpJsonRpcClient } from '../acp/acpJsonRpc.js';
2
+ export declare function askGeminiQuestion(rpc: AcpJsonRpcClient, workflowId: string, sessionId: string, params: unknown): Promise<unknown>;
@@ -0,0 +1,58 @@
1
+ import { AcpReplyError } from '../acp/acpJsonRpc.js';
2
+ import { openGeminiOperatorQuestion } from '../codex-appserver/operatorQuestions.js';
3
+ const record = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
4
+ export async function askGeminiQuestion(rpc, workflowId, sessionId, params) {
5
+ if (!record(params) || params.mode !== 'form' || params.sessionId !== sessionId || typeof params.message !== 'string' || !params.message.trim() || params.message.length > 32768) {
6
+ throw new AcpReplyError(-32602, 'Invalid Gemini question request.');
7
+ }
8
+ const schema = params.requestedSchema;
9
+ if (!record(schema) || schema.type !== 'object' || !record(schema.properties))
10
+ return { action: 'decline' };
11
+ const fields = Object.entries(schema.properties);
12
+ if (!fields.length || fields.length > 6)
13
+ return { action: 'decline' };
14
+ const required = schema.required ?? [];
15
+ if (!Array.isArray(required) || required.some(id => typeof id !== 'string' || !Object.hasOwn(schema.properties, id)))
16
+ return { action: 'decline' };
17
+ const questions = [];
18
+ const values = new Map();
19
+ for (const [id, field] of fields) {
20
+ if (!id || id.length > 256 || Object.hasOwn(Object.prototype, id) || !record(field) || field.type !== 'string' || field.pattern !== undefined || field.format !== undefined || field.minLength !== undefined || field.maxLength !== undefined)
21
+ return { action: 'decline' };
22
+ const title = typeof field.title === 'string' ? field.title : '';
23
+ const description = typeof field.description === 'string' ? field.description : '';
24
+ const prompt = fields.length === 1 ? params.message : [title || id, description].filter(Boolean).join('\n');
25
+ if (title.length > 1024 || prompt.length > 32768)
26
+ return { action: 'decline' };
27
+ const choices = field.oneOf ?? (Array.isArray(field.enum) ? field.enum.map(value => ({ const: value })) : field.enum);
28
+ const labels = new Map();
29
+ if (choices !== undefined) {
30
+ if (!Array.isArray(choices) || !choices.length || choices.length > 20)
31
+ return { action: 'decline' };
32
+ for (const choice of choices) {
33
+ if (!record(choice) || typeof choice.const !== 'string' || !choice.const.trim() || choice.const.length > 4096)
34
+ return { action: 'decline' };
35
+ const label = typeof choice.title === 'string' ? choice.title : choice.const;
36
+ if (!label.trim() || label.length > 4096 || labels.has(label))
37
+ return { action: 'decline' };
38
+ labels.set(label, choice.const);
39
+ }
40
+ values.set(id, labels);
41
+ }
42
+ questions.push({ id, header: fields.length === 1 ? title : questions.length === 0 ? params.message.slice(0, 1024) : '', question: prompt,
43
+ options: labels.size ? [...labels.keys()].map(label => ({ label, description: '' })) : undefined, allowOther: false, secret: false, optional: !required.includes(id) });
44
+ }
45
+ return new Promise(resolve => {
46
+ const cancel = openGeminiOperatorQuestion(workflowId, sessionId, questions, answers => {
47
+ rpc.off('close', onClose);
48
+ const content = answers && Object.fromEntries(Object.entries(answers).map(([id, [answer]]) => [id, values.get(id)?.get(answer) ?? answer]));
49
+ resolve(content ? { action: 'accept', content } : { action: 'decline' });
50
+ });
51
+ function onClose() {
52
+ cancel();
53
+ resolve({ action: 'cancel' });
54
+ }
55
+ rpc.once('close', onClose);
56
+ });
57
+ }
58
+ //# sourceMappingURL=questions.js.map
@@ -1,4 +1,4 @@
1
- import type { ClaudeCredentialBinding } from '@arco/shared';
1
+ import { type ClaudeCredentialBinding } from '@arco/shared';
2
2
  export interface ClaudeNativeTokens {
3
3
  accessToken: string;
4
4
  refreshToken: string;
@@ -7,10 +7,11 @@ export interface ClaudeNativeTokens {
7
7
  scope: string;
8
8
  obtainedAt: number;
9
9
  }
10
- export declare function nativeCredentialBinding(tokens?: ClaudeNativeTokens | null): ClaudeCredentialBinding;
11
- export declare function loadTokens(): Promise<ClaudeNativeTokens | null>;
12
- export declare function saveTokens(next: ClaudeNativeTokens): Promise<void>;
13
- export declare function clearTokens(): Promise<void>;
14
- export declare function withAuthLock<T>(fn: () => Promise<T>): Promise<T>;
15
- export declare function readTokensUnlocked(): Promise<ClaudeNativeTokens | null>;
16
- export declare function writeTokensUnlocked(next: ClaudeNativeTokens): Promise<void>;
10
+ export declare function nativeCredentialBinding(tokens?: ClaudeNativeTokens | null, accountRef?: string): ClaudeCredentialBinding;
11
+ export declare function withAuthLock<T>(fn: () => Promise<T>, accountRef?: string): Promise<T>;
12
+ export declare function loadTokens(accountRef?: string): Promise<ClaudeNativeTokens | null>;
13
+ export declare function saveTokens(next: ClaudeNativeTokens, accountRef?: string): Promise<void>;
14
+ export declare function clearTokens(accountRef?: string): Promise<void>;
15
+ export declare function clearTokensUnlocked(accountRef?: string): Promise<void>;
16
+ export declare const readTokensUnlocked: typeof loadTokens;
17
+ export declare function writeTokensUnlocked(next: ClaudeNativeTokens, accountRef?: string): Promise<void>;