arco-workbench 0.1.3 → 0.1.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 (1441) hide show
  1. package/CONTRIBUTING.md +41 -9
  2. package/README.md +40 -22
  3. package/THIRD_PARTY_NOTICES +789 -0
  4. package/client/dist/assets/{PhosphorBackdrop-CkVIGkeX.js → PhosphorBackdrop-D6cbmLNY.js} +1 -1
  5. package/client/dist/assets/{ThemedBackgroundShaderImpl-DHF7CnpE.js → ThemedBackgroundShaderImpl-2dyerOi4.js} +1 -1
  6. package/client/dist/assets/{XtermView-SY0UcZUS.js → XtermView-AIwo7O3D.js} +2 -2
  7. package/client/dist/assets/galleryEditor-DXAuxS8D.js +702 -0
  8. package/client/dist/assets/index-8j6p-pmQ.js +610 -0
  9. package/client/dist/assets/index-DD9kFGsF.css +1 -0
  10. package/client/dist/index.html +2 -2
  11. package/client/src/App.tsx +46 -55
  12. package/client/src/alerts/desktopAlerts.ts +29 -9
  13. package/client/src/alerts/desktopTest.ts +68 -0
  14. package/client/src/alerts/focusNotice.ts +16 -0
  15. package/client/src/brief/briefFacts.ts +22 -0
  16. package/client/src/brief/briefFromStore.ts +7 -2
  17. package/client/src/buildCheck.ts +42 -2
  18. package/client/src/components/ArchitectureReviewDialog.tsx +98 -0
  19. package/client/src/components/ArtifactModal.tsx +4 -6
  20. package/client/src/components/ArtifactMoveDialog.tsx +68 -0
  21. package/client/src/components/AskUserQuestionNotice.tsx +2 -1
  22. package/client/src/components/AutomaticMessage.tsx +19 -0
  23. package/client/src/components/BriefControl.tsx +42 -49
  24. package/client/src/components/BrowserNotice.tsx +35 -0
  25. package/client/src/components/CatchMeUp.tsx +35 -29
  26. package/client/src/components/ChatMessage.tsx +15 -4
  27. package/client/src/components/ChatModeView.tsx +23 -16
  28. package/client/src/components/ChatPanel.tsx +33 -5
  29. package/client/src/components/CheckpointActions.tsx +97 -29
  30. package/client/src/components/ClusterActivityTab.tsx +4 -2
  31. package/client/src/components/ClusterComposerButtons.tsx +6 -3
  32. package/client/src/components/ClusterMemberPicker.tsx +6 -3
  33. package/client/src/components/ClusterPlanTab.tsx +108 -63
  34. package/client/src/components/ClusterRightPanel/AddWorkerSection.tsx +16 -5
  35. package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +31 -16
  36. package/client/src/components/ClusterRightPanel/MailboxModal.tsx +7 -3
  37. package/client/src/components/ClusterRightPanel/MemberRow.tsx +5 -2
  38. package/client/src/components/ClusterRightPanel/MemberSettingsFields.tsx +104 -0
  39. package/client/src/components/ClusterRightPanel/MessageGuardControl.tsx +1 -1
  40. package/client/src/components/ClusterRightPanel/ReplaceMemberDialog.tsx +85 -7
  41. package/client/src/components/ClusterRightPanel/index.tsx +90 -36
  42. package/client/src/components/ClusterRightPanel/memberSettings.ts +52 -0
  43. package/client/src/components/ClusterRightPanel/panels.ts +18 -0
  44. package/client/src/components/ClusterRightPanel/types.ts +9 -10
  45. package/client/src/components/ClusterTab.tsx +281 -61
  46. package/client/src/components/ClusterTaskBoardTab.tsx +84 -606
  47. package/client/src/components/CommandPalette.tsx +17 -6
  48. package/client/src/components/ComputerAgentPicker.tsx +1 -1
  49. package/client/src/components/ComputerPanel.tsx +4 -2
  50. package/client/src/components/Connections/Connections.tsx +5 -2
  51. package/client/src/components/Connections/EndpointEditor.tsx +2 -2
  52. package/client/src/components/Connections/connections.css +1 -1
  53. package/client/src/components/Connections/model.ts +5 -1
  54. package/client/src/components/ContextMeter.tsx +15 -4
  55. package/client/src/components/DeepSeekControls.tsx +7 -6
  56. package/client/src/components/DiagnosticsTab.tsx +3 -2
  57. package/client/src/components/DialogShell.tsx +123 -0
  58. package/client/src/components/DocsUpdateDialog.tsx +16 -42
  59. package/client/src/components/FileExplorer.tsx +8 -9
  60. package/client/src/components/FileViewerModal.tsx +37 -12
  61. package/client/src/components/FirstRun.tsx +8 -7
  62. package/client/src/components/ForwardMessages.tsx +28 -32
  63. package/client/src/components/GateApprovalNotice.tsx +4 -2
  64. package/client/src/components/GitDialog.tsx +53 -52
  65. package/client/src/components/GitHubPanel/CodeView.tsx +35 -23
  66. package/client/src/components/GitHubPanel/IssueView.tsx +6 -4
  67. package/client/src/components/GitHubPanel/PullView.tsx +7 -6
  68. package/client/src/components/GitHubPanel/RunView.tsx +7 -5
  69. package/client/src/components/GitHubPanel/shared.tsx +23 -8
  70. package/client/src/components/GitOtherWork.tsx +4 -2
  71. package/client/src/components/HandoffDialog.tsx +19 -45
  72. package/client/src/components/HandoffSeedPill.tsx +5 -5
  73. package/client/src/components/HandoffSource.tsx +54 -0
  74. package/client/src/components/HeaderAuthChip.tsx +22 -1
  75. package/client/src/components/HeaderDropdown.tsx +5 -0
  76. package/client/src/components/HeaderVersionBox.tsx +3 -0
  77. package/client/src/components/HistoryTab.tsx +59 -32
  78. package/client/src/components/Home/AddProject.tsx +1 -1
  79. package/client/src/components/Home/HomeView.tsx +59 -22
  80. package/client/src/components/Home/LocationDialog.tsx +1 -1
  81. package/client/src/components/Home/ProjectCard.tsx +5 -3
  82. package/client/src/components/Home/home.css +11 -4
  83. package/client/src/components/KeepButton.tsx +45 -0
  84. package/client/src/components/LlamacppCatalogEditor.tsx +12 -3
  85. package/client/src/components/LocalRuntimeStatus.tsx +54 -0
  86. package/client/src/components/MdTuneupDialog.tsx +55 -52
  87. package/client/src/components/MemberCard.tsx +47 -42
  88. package/client/src/components/MemberPane.tsx +12 -11
  89. package/client/src/components/ModelHealthPanel.tsx +5 -4
  90. package/client/src/components/NativeSubagentControls.tsx +64 -0
  91. package/client/src/components/NeedsYouBadge.tsx +13 -6
  92. package/client/src/components/NorthStarBar.tsx +5 -3
  93. package/client/src/components/NotificationCenter.tsx +18 -5
  94. package/client/src/components/NotificationChannelsSettings.tsx +50 -24
  95. package/client/src/components/NotificationToasts.tsx +6 -8
  96. package/client/src/components/PendingQuestionsButton.tsx +4 -1
  97. package/client/src/components/PlanBodyRenderer.tsx +1 -0
  98. package/client/src/components/PlanCandidateBanner.tsx +129 -58
  99. package/client/src/components/PlanComposerDialog.tsx +55 -87
  100. package/client/src/components/PlanReviewPicker.tsx +6 -3
  101. package/client/src/components/PreviewTab.tsx +62 -25
  102. package/client/src/components/PrimaryStatus.tsx +20 -74
  103. package/client/src/components/ProjectStateNotice.tsx +60 -0
  104. package/client/src/components/ProjectsSettings.tsx +28 -2
  105. package/client/src/components/ProviderReleasesModal.tsx +13 -3
  106. package/client/src/components/ProvidersPopover.tsx +81 -23
  107. package/client/src/components/PublicProjectBox.tsx +29 -0
  108. package/client/src/components/PurgeConversationModal.tsx +7 -2
  109. package/client/src/components/QueuedMessagesIndicator.tsx +42 -150
  110. package/client/src/components/Recall/RecallResultRow.tsx +4 -2
  111. package/client/src/components/Recall/RecallView.tsx +12 -9
  112. package/client/src/components/ResearchDialog.tsx +16 -25
  113. package/client/src/components/ReviewDialog.tsx +44 -62
  114. package/client/src/components/RightPanel/ActivityTab.tsx +32 -16
  115. package/client/src/components/RightPanel/CodebaseMemorySection.tsx +3 -1
  116. package/client/src/components/RightPanel/ConfigTab.tsx +129 -140
  117. package/client/src/components/RightPanel/GenesisTab.tsx +67 -24
  118. package/client/src/components/RightPanel/HandoffsTab.tsx +4 -0
  119. package/client/src/components/RightPanel/KnowledgeTab.tsx +1 -1
  120. package/client/src/components/RightPanel/LedgerTab.tsx +1 -1
  121. package/client/src/components/RightPanel/McpRegistrySection.tsx +7 -6
  122. package/client/src/components/RightPanel/MoveTargetModal.tsx +6 -3
  123. package/client/src/components/RightPanel/OutputsPanel.tsx +44 -17
  124. package/client/src/components/RightPanel/PlanTab.tsx +131 -111
  125. package/client/src/components/RightPanel/ReviewTab.tsx +7 -4
  126. package/client/src/components/RightPanel/UsageTab.tsx +92 -3
  127. package/client/src/components/RightPanel/format.ts +3 -1
  128. package/client/src/components/RightPanel/index.tsx +10 -2
  129. package/client/src/components/RightPanel/types.ts +4 -2
  130. package/client/src/components/RunAsPicker.tsx +5 -3
  131. package/client/src/components/RuntimeStateBanner.tsx +13 -3
  132. package/client/src/components/SavedClustersList.tsx +30 -3
  133. package/client/src/components/ServicesTab.tsx +17 -34
  134. package/client/src/components/SettingsPanel.tsx +101 -337
  135. package/client/src/components/ShortcutCheatSheet.tsx +6 -4
  136. package/client/src/components/SkillEditorDialog.tsx +40 -74
  137. package/client/src/components/SkillsSettings.tsx +307 -0
  138. package/client/src/components/SpawnDialog.tsx +22 -44
  139. package/client/src/components/SpawnSeedPill.tsx +5 -4
  140. package/client/src/components/StaleBuildBanner.tsx +3 -1
  141. package/client/src/components/StorageWarnings.tsx +23 -0
  142. package/client/src/components/SystemHeader.tsx +19 -12
  143. package/client/src/components/SystemModal.tsx +6 -5
  144. package/client/src/components/TabBar.tsx +20 -10
  145. package/client/src/components/TabContextMenu.tsx +36 -10
  146. package/client/src/components/TaskCard.tsx +16 -11
  147. package/client/src/components/TasksPanel.tsx +13 -11
  148. package/client/src/components/Terminal/XtermView.tsx +2 -0
  149. package/client/src/components/TerminalInput.tsx +251 -446
  150. package/client/src/components/TerminalSessions.tsx +1 -1
  151. package/client/src/components/TidyComposer.tsx +24 -41
  152. package/client/src/components/TokenBadge.tsx +20 -17
  153. package/client/src/components/ToolCallPill.tsx +5 -3
  154. package/client/src/components/ToolboxMenu.tsx +5 -5
  155. package/client/src/components/TranscriptSendDialog.tsx +151 -202
  156. package/client/src/components/TurnTimer.tsx +21 -0
  157. package/client/src/components/UpdateAction.tsx +4 -1
  158. package/client/src/components/UsageBar.tsx +32 -126
  159. package/client/src/components/UserManual/index.tsx +6 -4
  160. package/client/src/components/UtilityAgentPicker.tsx +4 -2
  161. package/client/src/components/VoiceMenu.tsx +5 -1
  162. package/client/src/components/VoiceSetupSettings.tsx +21 -11
  163. package/client/src/components/WorkerCard.tsx +7 -1
  164. package/client/src/components/WorkerDetailModal.tsx +7 -3
  165. package/client/src/components/WorkflowCreator/ClusterMembersSection.tsx +6 -6
  166. package/client/src/components/WorkflowCreator/ProjectPicker.tsx +13 -12
  167. package/client/src/components/WorkflowCreator/index.tsx +238 -77
  168. package/client/src/components/WorkflowCreator/types.ts +5 -3
  169. package/client/src/components/WorkflowStatusChip.tsx +93 -13
  170. package/client/src/components/WorkflowView.tsx +59 -25
  171. package/client/src/components/WorkspaceRename.tsx +11 -1
  172. package/client/src/components/activityTime.ts +4 -0
  173. package/client/src/components/clusterNeedsYou.ts +35 -3
  174. package/client/src/components/compare/CompareDialog.tsx +32 -5
  175. package/client/src/components/compare/CompareOverlay.tsx +10 -3
  176. package/client/src/components/composer/submitComposer.ts +191 -0
  177. package/client/src/components/diff/ChangesPanel.tsx +4 -2
  178. package/client/src/components/diff/LiveChangesPanel.tsx +18 -2
  179. package/client/src/components/editor/CodeEditor.tsx +17 -2
  180. package/client/src/components/headerPopoverState.ts +15 -0
  181. package/client/src/components/help/DocViewer.tsx +6 -4
  182. package/client/src/components/help/HelpCard.tsx +3 -2
  183. package/client/src/components/help/HelpPopover.tsx +3 -1
  184. package/client/src/components/media/AudioEditor/AudioOpsPanel.tsx +16 -2
  185. package/client/src/components/media/DirectoryPicker.tsx +18 -11
  186. package/client/src/components/media/ImageEditor/ImageEditor.tsx +2 -2
  187. package/client/src/components/media/MediaModalHost.tsx +7 -15
  188. package/client/src/components/media/MediaStemsControls.tsx +16 -2
  189. package/client/src/components/media/VideoEditor/VideoOpsPanel.tsx +16 -2
  190. package/client/src/components/media/launchers.ts +4 -0
  191. package/client/src/components/plans/PlanChooser.tsx +135 -0
  192. package/client/src/components/plans/PlanRefsSection.tsx +47 -28
  193. package/client/src/components/plans/planBodySave.ts +17 -0
  194. package/client/src/components/plans/planRefs.ts +21 -11
  195. package/client/src/components/plans/startPlanGenesis.ts +37 -0
  196. package/client/src/components/primitives/Panel.tsx +1 -0
  197. package/client/src/components/providerPanelState.ts +17 -0
  198. package/client/src/components/settings/AppVersionSection.tsx +5 -5
  199. package/client/src/components/settings/AppWindowBrowserSection.tsx +88 -0
  200. package/client/src/components/settings/PreviewPortsSection.tsx +31 -0
  201. package/client/src/components/settings/SettingsLayout.tsx +1 -1
  202. package/client/src/components/settings/appWindowBrowserReport.ts +23 -0
  203. package/client/src/components/settings/navigation.ts +5 -1
  204. package/client/src/components/settings/settings.css +6 -0
  205. package/client/src/components/terminalInput/planDraft.ts +34 -5
  206. package/client/src/components/usageVisibility.ts +3 -2
  207. package/client/src/components/utilityResult.ts +5 -1
  208. package/client/src/components/workSurface/WorkSurfaceControls.tsx +125 -10
  209. package/client/src/components/workSurface/workSurface.css +10 -2
  210. package/client/src/explorer/ArtifactsLens.tsx +53 -17
  211. package/client/src/explorer/ExplorerApp.tsx +12 -7
  212. package/client/src/explorer/PlansLens.tsx +140 -39
  213. package/client/src/explorer/RecentsLens.tsx +22 -61
  214. package/client/src/explorer/StorageLens.tsx +281 -0
  215. package/client/src/explorer/changedAttribution.ts +23 -0
  216. package/client/src/explorer/launch.ts +6 -3
  217. package/client/src/explorer/plansGrouping.ts +15 -0
  218. package/client/src/explorer/treeReveal.ts +21 -0
  219. package/client/src/explorer/types.ts +3 -3
  220. package/client/src/help/content/chat.tsx +17 -10
  221. package/client/src/help/content/cluster.tsx +175 -109
  222. package/client/src/help/content/composer.tsx +149 -48
  223. package/client/src/help/content/gitOps.tsx +19 -19
  224. package/client/src/help/content/github.tsx +9 -4
  225. package/client/src/help/content/header.tsx +82 -61
  226. package/client/src/help/content/media.tsx +20 -20
  227. package/client/src/help/content/misc.tsx +475 -156
  228. package/client/src/help/content/recall.tsx +12 -12
  229. package/client/src/help/content/rightPanel.tsx +210 -97
  230. package/client/src/help/content/settings.tsx +120 -47
  231. package/client/src/help/content/shared.tsx +1 -1
  232. package/client/src/help/content/tabbar.tsx +1 -1
  233. package/client/src/help/manualSections/actions.tsx +43 -21
  234. package/client/src/help/manualSections/chat.tsx +28 -5
  235. package/client/src/help/manualSections/clusters.tsx +222 -147
  236. package/client/src/help/manualSections/configuration.tsx +236 -50
  237. package/client/src/help/manualSections/deepseek.tsx +7 -5
  238. package/client/src/help/manualSections/gettingStarted.tsx +74 -12
  239. package/client/src/help/manualSections/maintenance.tsx +84 -15
  240. package/client/src/help/manualSections/media.tsx +14 -12
  241. package/client/src/help/manualSections/plans.tsx +192 -15
  242. package/client/src/help/manualSections/powerFeatures.tsx +146 -51
  243. package/client/src/help/manualSections/providers.tsx +237 -42
  244. package/client/src/help/manualSections/reference.tsx +24 -10
  245. package/client/src/help/manualSections/strata.tsx +6 -6
  246. package/client/src/help/manualSections/troubleshooting.tsx +14 -8
  247. package/client/src/help/manualSections/voice.tsx +12 -7
  248. package/client/src/help/manualSections/workflows.tsx +76 -19
  249. package/client/src/help/manualSections/workspace.tsx +179 -48
  250. package/client/src/help/shortcuts.ts +1 -0
  251. package/client/src/hooks/useWebSocket.ts +49 -25
  252. package/client/src/layout/SlideOut.tsx +77 -0
  253. package/client/src/layout/ToolbarOverflow.tsx +97 -0
  254. package/client/src/layout/keepInWindow.ts +216 -0
  255. package/client/src/layout/layoutRange.ts +129 -0
  256. package/client/src/main.tsx +2 -0
  257. package/client/src/phosphor-demo/Demo.tsx +5 -13
  258. package/client/src/phosphor-demo/demo.css +1 -1
  259. package/client/src/stores/appStore.ts +75 -15
  260. package/client/src/stores/appStore.types.ts +37 -16
  261. package/client/src/stores/docEditStore.ts +13 -21
  262. package/client/src/stores/draftStore.ts +28 -4
  263. package/client/src/stores/knowledgeDistillStore.ts +4 -2
  264. package/client/src/stores/mdTuneupStore.ts +12 -6
  265. package/client/src/stores/memoryTrim.ts +18 -2
  266. package/client/src/stores/notificationChannelsStore.ts +21 -11
  267. package/client/src/stores/planGenesisStore.ts +67 -0
  268. package/client/src/stores/recallStore.ts +6 -0
  269. package/client/src/stores/storageWarningStore.ts +18 -0
  270. package/client/src/stores/terminalStore.ts +1 -1
  271. package/client/src/styles/global.css +72 -0
  272. package/client/src/styles/matrix.css +7 -0
  273. package/client/src/themes/apply.ts +3 -3
  274. package/client/src/themes/bootstrap.ts +3 -0
  275. package/client/src/utils/activeProject.ts +6 -0
  276. package/client/src/utils/activityPresentation.ts +51 -0
  277. package/client/src/utils/browserFamily.ts +22 -0
  278. package/client/src/utils/chatFileLinks.ts +3 -2
  279. package/client/src/utils/chatText.ts +14 -6
  280. package/client/src/utils/checkedJson.ts +11 -0
  281. package/client/src/utils/checkpointChanges.ts +18 -0
  282. package/client/src/utils/clusterCreation.ts +39 -0
  283. package/client/src/utils/clusterNudge.ts +31 -0
  284. package/client/src/utils/displayMessages.ts +45 -7
  285. package/client/src/utils/effortDefaults.ts +4 -3
  286. package/client/src/utils/format.ts +11 -4
  287. package/client/src/utils/gateArgs.ts +3 -2
  288. package/client/src/utils/gitDialogMemory.ts +26 -0
  289. package/client/src/utils/handoffSeeds.ts +13 -0
  290. package/client/src/utils/historyEvents.ts +22 -12
  291. package/client/src/utils/homeModel.ts +38 -3
  292. package/client/src/utils/memberReviewScope.ts +6 -0
  293. package/client/src/utils/outputNavigation.ts +16 -0
  294. package/client/src/utils/outputStyleText.ts +8 -0
  295. package/client/src/utils/publicProject.ts +130 -0
  296. package/client/src/utils/queuedMessageEdit.ts +40 -0
  297. package/client/src/utils/requestGeneration.ts +8 -0
  298. package/client/src/utils/rewindSupport.ts +17 -0
  299. package/client/src/utils/settingsRequests.ts +36 -0
  300. package/client/src/utils/settingsResponse.ts +8 -0
  301. package/client/src/utils/wsSession.ts +12 -5
  302. package/client/src/vendor/odysseus-editor/editor/clipboard-and-drop.js +9 -9
  303. package/client/src/vendor/odysseus-editor/editor/keyboard-shortcuts.js +2 -2
  304. package/client/src/vendor/odysseus-editor/editor/state.js +8 -0
  305. package/client/src/vendor/odysseus-editor/editor.css +13 -5
  306. package/client/src/vendor/odysseus-editor/galleryEditor.d.ts +1 -1
  307. package/client/src/vendor/odysseus-editor/galleryEditor.js +16 -5
  308. package/client/src/voice/executor.ts +4 -3
  309. package/client/src/voice/panels.ts +14 -3
  310. package/client/src/voice/screen.ts +48 -6
  311. package/client/src/voice/setupAudio.ts +5 -3
  312. package/client/src/ws/handleServerMessage.ts +158 -35
  313. package/client/src/ws/operatorQuestions.ts +2 -2
  314. package/docs/ARCHITECTURE.md +95 -55
  315. package/docs/ARCHITECTURE_REVIEW.md +47 -0
  316. package/docs/BACKUP.md +5 -2
  317. package/docs/CHAT.md +48 -37
  318. package/docs/CHECKPOINTS.md +45 -16
  319. package/docs/CLIENT.md +242 -88
  320. package/docs/CODEX_GPT56_CLUSTER_INCOMPAT.md +1 -1
  321. package/docs/DEEPSEEK.md +6 -6
  322. package/docs/DIAGNOSTICS.md +12 -7
  323. package/docs/EXTENDING.md +52 -48
  324. package/docs/FEATURES.md +42 -26
  325. package/docs/GENESIS.md +42 -6
  326. package/docs/GETTING_STARTED.md +63 -29
  327. package/docs/GIT_WORKBENCH.md +15 -9
  328. package/docs/GLOSSARY.md +44 -42
  329. package/docs/GOTCHAS.md +73 -59
  330. package/docs/HTTP_API.md +167 -39
  331. package/docs/INDEX.md +3 -4
  332. package/docs/KNOWLEDGE.md +6 -4
  333. package/docs/LOCAL_SERVICES.md +6 -6
  334. package/docs/LSP.md +4 -3
  335. package/docs/MCP_REGISTRY.md +16 -12
  336. package/docs/MEDIA_STUDIO.md +23 -16
  337. package/docs/NOTIFICATIONS.md +60 -28
  338. package/docs/OPERATIONS.md +237 -120
  339. package/docs/OPERATOR_ACTIONS.md +44 -25
  340. package/docs/OUTPUTS.md +35 -9
  341. package/docs/PERSISTENCE.md +117 -33
  342. package/docs/PHOSPHOR_DEMO.md +4 -4
  343. package/docs/PLAN_OR_BOARD.md +13 -1
  344. package/docs/PREVIEW_VERIFY.md +10 -8
  345. package/docs/PRIMITIVES.md +92 -89
  346. package/docs/PROTOCOL.md +113 -32
  347. package/docs/PROTOCOL_CLUSTER.md +80 -16
  348. package/docs/PROTOCOL_PRIMITIVES.md +9 -9
  349. package/docs/PROVIDERS.md +471 -82
  350. package/docs/RECALL.md +17 -12
  351. package/docs/REMOTE_MANAGEMENT.md +69 -8
  352. package/docs/REPO_LAYOUT.md +1 -1
  353. package/docs/RESUME_INDEX.md +16 -17
  354. package/docs/SERVICE_MODE.md +50 -11
  355. package/docs/SETTINGS.md +66 -13
  356. package/docs/STORAGE_PLAN.md +329 -0
  357. package/docs/STRATA.md +4 -4
  358. package/docs/TASK_LEDGER.md +38 -16
  359. package/docs/TERMINAL.md +14 -12
  360. package/docs/THIRD_PARTY.md +1 -3
  361. package/docs/VOICE.md +15 -7
  362. package/native/darwin-arm64/manifest.json +1 -1
  363. package/native/linux-arm64/manifest.json +1 -1
  364. package/native/win32-arm64/manifest.json +1 -1
  365. package/node_modules/@arco/shared/dist/clusterCoordination.js +15 -7
  366. package/node_modules/@arco/shared/dist/clusterRolePresets.js +8 -6
  367. package/node_modules/@arco/shared/dist/codexChat.d.ts +2 -0
  368. package/node_modules/@arco/shared/dist/codexChat.js +5 -0
  369. package/node_modules/@arco/shared/dist/folderName.d.ts +1 -0
  370. package/node_modules/@arco/shared/dist/folderName.js +18 -0
  371. package/node_modules/@arco/shared/dist/index.d.ts +8 -0
  372. package/node_modules/@arco/shared/dist/index.js +8 -0
  373. package/node_modules/@arco/shared/dist/localRuntimeStatus.d.ts +23 -0
  374. package/node_modules/@arco/shared/dist/localRuntimeStatus.js +47 -0
  375. package/node_modules/@arco/shared/dist/notificationTitle.d.ts +9 -0
  376. package/node_modules/@arco/shared/dist/notificationTitle.js +23 -0
  377. package/node_modules/@arco/shared/dist/outputStyle.d.ts +10 -0
  378. package/node_modules/@arco/shared/dist/outputStyle.js +28 -0
  379. package/node_modules/@arco/shared/dist/outputs.d.ts +1 -0
  380. package/node_modules/@arco/shared/dist/protocol/autoPickup.d.ts +3 -1
  381. package/node_modules/@arco/shared/dist/protocol/autoPickup.js +1 -1
  382. package/node_modules/@arco/shared/dist/protocol/chat.d.ts +4 -0
  383. package/node_modules/@arco/shared/dist/protocol/checkpoints.d.ts +25 -2
  384. package/node_modules/@arco/shared/dist/protocol/checkpoints.js +1 -0
  385. package/node_modules/@arco/shared/dist/protocol/clientMessages.d.ts +9 -14
  386. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +23 -5
  387. package/node_modules/@arco/shared/dist/protocol/clusters.js +3 -3
  388. package/node_modules/@arco/shared/dist/protocol/connections.d.ts +2 -0
  389. package/node_modules/@arco/shared/dist/protocol/diagnostics.js +1 -1
  390. package/node_modules/@arco/shared/dist/protocol/genesis.d.ts +9 -0
  391. package/node_modules/@arco/shared/dist/protocol/index.d.ts +1 -0
  392. package/node_modules/@arco/shared/dist/protocol/index.js +1 -0
  393. package/node_modules/@arco/shared/dist/protocol/mcp.d.ts +1 -0
  394. package/node_modules/@arco/shared/dist/protocol/mcp.js +8 -5
  395. package/node_modules/@arco/shared/dist/protocol/mdTuneup.d.ts +8 -0
  396. package/node_modules/@arco/shared/dist/protocol/models.d.ts +3 -1
  397. package/node_modules/@arco/shared/dist/protocol/models.js +19 -8
  398. package/node_modules/@arco/shared/dist/protocol/notifications.d.ts +4 -2
  399. package/node_modules/@arco/shared/dist/protocol/notifications.js +18 -5
  400. package/node_modules/@arco/shared/dist/protocol/plans.d.ts +4 -1
  401. package/node_modules/@arco/shared/dist/protocol/remoteManagement.d.ts +6 -0
  402. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +70 -10
  403. package/node_modules/@arco/shared/dist/protocol/settings.d.ts +16 -4
  404. package/node_modules/@arco/shared/dist/protocol/settings.js +17 -1
  405. package/node_modules/@arco/shared/dist/protocol/storage.d.ts +21 -0
  406. package/node_modules/@arco/shared/dist/protocol/storage.js +3 -0
  407. package/node_modules/@arco/shared/dist/protocol/tasks.d.ts +4 -0
  408. package/node_modules/@arco/shared/dist/protocol/usage.d.ts +1 -0
  409. package/node_modules/@arco/shared/dist/protocol/utilityAgent.d.ts +2 -2
  410. package/node_modules/@arco/shared/dist/protocol/utilityAgent.js +2 -2
  411. package/node_modules/@arco/shared/dist/protocol/workers.d.ts +1 -0
  412. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +73 -14
  413. package/node_modules/@arco/shared/dist/protocol/workflows.js +66 -0
  414. package/node_modules/@arco/shared/dist/publicGuardrails.d.ts +7 -0
  415. package/node_modules/@arco/shared/dist/publicGuardrails.js +47 -0
  416. package/node_modules/@arco/shared/dist/publicSafetyRules.d.ts +1 -0
  417. package/node_modules/@arco/shared/dist/publicSafetyRules.js +6 -0
  418. package/node_modules/@arco/shared/dist/runtimeVersions.d.ts +2 -0
  419. package/node_modules/@arco/shared/dist/runtimeVersions.js +13 -0
  420. package/node_modules/@arco/shared/dist/shellTool.d.ts +2 -0
  421. package/node_modules/@arco/shared/dist/shellTool.js +9 -0
  422. package/node_modules/@arco/shared/package.json +1 -1
  423. package/node_modules/xlsx/LICENSE +201 -0
  424. package/node_modules/xlsx/dist/cpexcel.js +1506 -0
  425. package/node_modules/xlsx/package.json +69 -0
  426. package/node_modules/xlsx/xlsx.js +28103 -0
  427. package/node_modules/xlsx/xlsx.mjs +28228 -0
  428. package/package.json +23 -3
  429. package/scripts/packaging/arco.mjs +19 -3
  430. package/scripts/packaging/browsers.mjs +366 -0
  431. package/scripts/packaging/launch.mjs +34 -20
  432. package/scripts/packaging/services.mjs +36 -6
  433. package/scripts/packaging/storage.mjs +161 -0
  434. package/scripts/packaging/update.mjs +3 -3
  435. package/server/dist/appBrowsers.d.ts +45 -0
  436. package/server/dist/appBrowsers.js +73 -0
  437. package/server/dist/architectureReview.d.ts +60 -0
  438. package/server/dist/architectureReview.js +347 -0
  439. package/server/dist/architectureSkill.d.ts +8 -0
  440. package/server/dist/architectureSkill.js +70 -0
  441. package/server/dist/arcoHome.d.ts +1 -0
  442. package/server/dist/arcoHome.js +43 -3
  443. package/server/dist/artifactCopy.d.ts +29 -0
  444. package/server/dist/artifactCopy.js +475 -0
  445. package/server/dist/atomicFile.d.ts +1 -0
  446. package/server/dist/atomicFile.js +6 -1
  447. package/server/dist/attention.d.ts +6 -2
  448. package/server/dist/attention.js +37 -29
  449. package/server/dist/auth.d.ts +1 -0
  450. package/server/dist/auth.js +19 -6
  451. package/server/dist/authLoginSession.d.ts +2 -0
  452. package/server/dist/authLoginSession.js +6 -1
  453. package/server/dist/boundedRead.d.ts +26 -0
  454. package/server/dist/boundedRead.js +246 -0
  455. package/server/dist/capabilities.d.ts +4 -1
  456. package/server/dist/capabilities.js +25 -8
  457. package/server/dist/catchUp.d.ts +9 -0
  458. package/server/dist/catchUp.js +66 -24
  459. package/server/dist/checkedFile.d.ts +5 -0
  460. package/server/dist/checkedFile.js +138 -0
  461. package/server/dist/claudeTransport.d.ts +7 -0
  462. package/server/dist/claudeTransport.js +14 -0
  463. package/server/dist/clusterAutoTurn.d.ts +7 -0
  464. package/server/dist/clusterAutoTurn.js +54 -7
  465. package/server/dist/clusterBusyReminder.d.ts +7 -0
  466. package/server/dist/clusterBusyReminder.js +45 -0
  467. package/server/dist/clusterDirector.js +6 -3
  468. package/server/dist/clusterIdleNudger.d.ts +6 -0
  469. package/server/dist/clusterIdleNudger.js +5 -0
  470. package/server/dist/clusterMailbox.d.ts +4 -2
  471. package/server/dist/clusterMailbox.js +104 -24
  472. package/server/dist/clusterPeerOps.d.ts +2 -0
  473. package/server/dist/clusterPeerOps.js +11 -21
  474. package/server/dist/clusterPlanBridge.d.ts +6 -3
  475. package/server/dist/clusterPlanBridge.js +48 -45
  476. package/server/dist/clusterPresets.js +46 -32
  477. package/server/dist/clusterProgress.js +3 -0
  478. package/server/dist/clusterSnapshots.d.ts +1 -1
  479. package/server/dist/clusterSnapshots.js +39 -14
  480. package/server/dist/clusterStore.d.ts +3 -0
  481. package/server/dist/clusterStore.js +23 -13
  482. package/server/dist/clusterTurnTools.d.ts +4 -0
  483. package/server/dist/clusterTurnTools.js +9 -0
  484. package/server/dist/commandShell.d.ts +56 -0
  485. package/server/dist/commandShell.js +278 -0
  486. package/server/dist/compactionCounter.d.ts +6 -0
  487. package/server/dist/compactionCounter.js +73 -0
  488. package/server/dist/compactionReport.d.ts +8 -0
  489. package/server/dist/compactionReport.js +15 -0
  490. package/server/dist/contentSearch.js +16 -6
  491. package/server/dist/contextCalibrator.js +7 -2
  492. package/server/dist/contextEstimator.d.ts +4 -0
  493. package/server/dist/contextEstimator.js +76 -17
  494. package/server/dist/contextRefs.d.ts +1 -0
  495. package/server/dist/contextRefs.js +44 -9
  496. package/server/dist/conversationActivity.d.ts +3 -0
  497. package/server/dist/conversationActivity.js +27 -0
  498. package/server/dist/cursorUsage.js +15 -4
  499. package/server/dist/diagnostics/checks.js +4 -12
  500. package/server/dist/diagnostics/executableLookup.d.ts +2 -0
  501. package/server/dist/diagnostics/executableLookup.js +28 -0
  502. package/server/dist/diagnostics/modelHealth.js +3 -12
  503. package/server/dist/diagnostics/supportBundle.js +5 -13
  504. package/server/dist/eventLog.d.ts +74 -0
  505. package/server/dist/eventLog.js +992 -0
  506. package/server/dist/existingClusterMembers.d.ts +1 -0
  507. package/server/dist/existingClusterMembers.js +9 -0
  508. package/server/dist/explorerArtifacts.js +46 -12
  509. package/server/dist/explorerChanged.d.ts +7 -0
  510. package/server/dist/explorerChanged.js +116 -80
  511. package/server/dist/explorerDocs.d.ts +11 -0
  512. package/server/dist/explorerDocs.js +46 -48
  513. package/server/dist/explorerLaunch.d.ts +8 -1
  514. package/server/dist/explorerLaunch.js +11 -2
  515. package/server/dist/explorerPlans.d.ts +4 -0
  516. package/server/dist/explorerPlans.js +27 -2
  517. package/server/dist/fileAccessPolicy.d.ts +21 -0
  518. package/server/dist/fileAccessPolicy.js +89 -1
  519. package/server/dist/fileContent/decodeSlots.d.ts +1 -0
  520. package/server/dist/fileContent/decodeSlots.js +50 -0
  521. package/server/dist/fileContent/detect.d.ts +2 -0
  522. package/server/dist/fileContent/detect.js +55 -0
  523. package/server/dist/fileContent/externalImage.d.ts +3 -0
  524. package/server/dist/fileContent/externalImage.js +68 -0
  525. package/server/dist/fileContent/icons.d.ts +4 -0
  526. package/server/dist/fileContent/icons.js +58 -0
  527. package/server/dist/fileContent/images.d.ts +15 -0
  528. package/server/dist/fileContent/images.js +182 -0
  529. package/server/dist/fileContent/legacyText.d.ts +3 -0
  530. package/server/dist/fileContent/legacyText.js +19 -0
  531. package/server/dist/fileContent/notebook.d.ts +2 -0
  532. package/server/dist/fileContent/notebook.js +54 -0
  533. package/server/dist/fileContent/office.d.ts +3 -0
  534. package/server/dist/fileContent/office.js +349 -0
  535. package/server/dist/fileContent/pdf.d.ts +2 -0
  536. package/server/dist/fileContent/pdf.js +76 -0
  537. package/server/dist/fileContent/pngRows.d.ts +4 -0
  538. package/server/dist/fileContent/pngRows.js +118 -0
  539. package/server/dist/fileContent/svg.d.ts +3 -0
  540. package/server/dist/fileContent/svg.js +60 -0
  541. package/server/dist/fileContent/types.d.ts +8 -0
  542. package/server/dist/fileContent/types.js +43 -0
  543. package/server/dist/fileContent/worker.d.ts +1 -0
  544. package/server/dist/fileContent/worker.js +68 -0
  545. package/server/dist/fileContent.d.ts +55 -0
  546. package/server/dist/fileContent.js +81 -0
  547. package/server/dist/fileContextReceipts.d.ts +12 -0
  548. package/server/dist/fileContextReceipts.js +53 -0
  549. package/server/dist/fileFetch.d.ts +17 -0
  550. package/server/dist/fileFetch.js +191 -0
  551. package/server/dist/fileVersion.d.ts +10 -0
  552. package/server/dist/fileVersion.js +43 -0
  553. package/server/dist/genesis/creative.js +28 -36
  554. package/server/dist/genesis/prompts.js +4 -0
  555. package/server/dist/genesis/savePlan.d.ts +5 -0
  556. package/server/dist/genesis/savePlan.js +49 -0
  557. package/server/dist/genesis/stages.js +4 -4
  558. package/server/dist/gitDiff.js +25 -5
  559. package/server/dist/gitSnapshots.d.ts +18 -0
  560. package/server/dist/gitSnapshots.js +280 -149
  561. package/server/dist/gitWorking.js +15 -13
  562. package/server/dist/github.js +5 -1
  563. package/server/dist/goalRun.d.ts +1 -1
  564. package/server/dist/goalRun.js +7 -5
  565. package/server/dist/handoffHistory.d.ts +26 -0
  566. package/server/dist/handoffHistory.js +80 -0
  567. package/server/dist/handoffHistoryProtocol.d.ts +59 -0
  568. package/server/dist/handoffHistoryProtocol.js +20 -0
  569. package/server/dist/handoffHistorySupport.d.ts +2 -0
  570. package/server/dist/handoffHistorySupport.js +11 -0
  571. package/server/dist/handoffHistoryTool.d.ts +29 -0
  572. package/server/dist/handoffHistoryTool.js +235 -0
  573. package/server/dist/handoffPrompts.js +6 -4
  574. package/server/dist/handoffReplay.d.ts +9 -0
  575. package/server/dist/handoffReplay.js +14 -0
  576. package/server/dist/handoffSeedCache.d.ts +3 -0
  577. package/server/dist/handoffSeedCache.js +26 -0
  578. package/server/dist/http/appBrowserRoutes.d.ts +3 -0
  579. package/server/dist/http/appBrowserRoutes.js +16 -0
  580. package/server/dist/http/architectureReviewRoutes.d.ts +3 -0
  581. package/server/dist/http/architectureReviewRoutes.js +117 -0
  582. package/server/dist/http/clusterRoutes.js +15 -1
  583. package/server/dist/http/clusterSnapshotRoutes.js +8 -3
  584. package/server/dist/http/connectionsRoutes.js +3 -1
  585. package/server/dist/http/diffRoutes.js +37 -3
  586. package/server/dist/http/explorerRoot.d.ts +3 -0
  587. package/server/dist/http/explorerRoot.js +22 -0
  588. package/server/dist/http/explorerRoutes.js +66 -12
  589. package/server/dist/http/fileRead.js +2 -3
  590. package/server/dist/http/fileWriteRoutes.js +4 -3
  591. package/server/dist/http/gitCompareRoutes.js +4 -6
  592. package/server/dist/http/gitDiffRoutes.js +3 -3
  593. package/server/dist/http/gitOpRoutes.js +3 -5
  594. package/server/dist/http/gitWorktreeRoutes.js +3 -3
  595. package/server/dist/http/handoffHistoryRoutes.d.ts +4 -0
  596. package/server/dist/http/handoffHistoryRoutes.js +59 -0
  597. package/server/dist/http/imageWriteRoutes.js +6 -2
  598. package/server/dist/http/knowledgeRoutes.js +2 -0
  599. package/server/dist/http/mediaOpsRoutes.js +2 -3
  600. package/server/dist/http/originGuard.d.ts +1 -1
  601. package/server/dist/http/originGuard.js +95 -12
  602. package/server/dist/http/outputRoutes.js +31 -6
  603. package/server/dist/http/projectBinding.d.ts +3 -0
  604. package/server/dist/http/projectBinding.js +133 -0
  605. package/server/dist/http/providerThrottleRoutes.d.ts +8 -0
  606. package/server/dist/http/providerThrottleRoutes.js +96 -0
  607. package/server/dist/http/publicProjectRoutes.d.ts +2 -0
  608. package/server/dist/http/publicProjectRoutes.js +109 -0
  609. package/server/dist/http/readConfinement.d.ts +2 -1
  610. package/server/dist/http/readConfinement.js +17 -15
  611. package/server/dist/http/router.js +230 -62
  612. package/server/dist/http/searchRoutes.js +4 -4
  613. package/server/dist/http/sessionTransport.d.ts +2 -0
  614. package/server/dist/http/sessionTransport.js +32 -0
  615. package/server/dist/http/skillManagementRoutes.d.ts +5 -0
  616. package/server/dist/http/skillManagementRoutes.js +166 -0
  617. package/server/dist/http/storageRoutes.d.ts +2 -0
  618. package/server/dist/http/storageRoutes.js +268 -0
  619. package/server/dist/http/usageStatsRoutes.js +3 -12
  620. package/server/dist/http/utilityAgentRoutes.js +27 -5
  621. package/server/dist/http/workflowDataRoutes.js +75 -14
  622. package/server/dist/http/writeConfinement.d.ts +5 -3
  623. package/server/dist/http/writeConfinement.js +37 -11
  624. package/server/dist/http/wsAuth.d.ts +3 -2
  625. package/server/dist/http/wsAuth.js +26 -8
  626. package/server/dist/imageTokens.d.ts +7 -0
  627. package/server/dist/imageTokens.js +85 -0
  628. package/server/dist/index.js +287 -178
  629. package/server/dist/inputDeliveryHistory.d.ts +21 -0
  630. package/server/dist/inputDeliveryHistory.js +146 -0
  631. package/server/dist/keepStore.d.ts +20 -0
  632. package/server/dist/keepStore.js +167 -0
  633. package/server/dist/knowledge/store.js +28 -20
  634. package/server/dist/legacyTarRestore.d.ts +1 -0
  635. package/server/dist/legacyTarRestore.js +240 -0
  636. package/server/dist/llamacppCatalog.d.ts +8 -1
  637. package/server/dist/llamacppCatalog.js +65 -13
  638. package/server/dist/localRuntimeStatus.d.ts +35 -0
  639. package/server/dist/localRuntimeStatus.js +136 -0
  640. package/server/dist/lsp/client.js +28 -9
  641. package/server/dist/lsp/servers.js +2 -2
  642. package/server/dist/managedPath.d.ts +2 -0
  643. package/server/dist/managedPath.js +47 -0
  644. package/server/dist/management/clusterActivity.js +6 -20
  645. package/server/dist/management/hubGuard.d.ts +23 -0
  646. package/server/dist/management/hubGuard.js +118 -0
  647. package/server/dist/management/hubLink.d.ts +4 -1
  648. package/server/dist/management/hubLink.js +8 -1
  649. package/server/dist/management/initHubLink.d.ts +12 -0
  650. package/server/dist/management/initHubLink.js +54 -65
  651. package/server/dist/manualCompactCapability.d.ts +2 -0
  652. package/server/dist/manualCompactCapability.js +7 -0
  653. package/server/dist/mcp/arcoMcpServer.js +4 -0
  654. package/server/dist/mcp/client.d.ts +4 -4
  655. package/server/dist/mcp/client.js +31 -10
  656. package/server/dist/mcp/clusterMcpLoopback.d.ts +4 -0
  657. package/server/dist/mcp/clusterMcpLoopback.js +21 -1
  658. package/server/dist/mcp/clusterMcpTools.js +33 -27
  659. package/server/dist/mcp/fileContent.d.ts +8 -0
  660. package/server/dist/mcp/fileContent.js +55 -0
  661. package/server/dist/mcp/fileMcpServer.d.ts +1 -0
  662. package/server/dist/mcp/fileMcpServer.js +13 -0
  663. package/server/dist/mcp/fileMcpTools.d.ts +2 -0
  664. package/server/dist/mcp/fileMcpTools.js +54 -0
  665. package/server/dist/mcp/handoffHistoryMcpTools.d.ts +3 -0
  666. package/server/dist/mcp/handoffHistoryMcpTools.js +27 -0
  667. package/server/dist/mcp/mcpConfigWriter.d.ts +5 -0
  668. package/server/dist/mcp/mcpConfigWriter.js +44 -12
  669. package/server/dist/mcp/planMcpTools.d.ts +6 -14
  670. package/server/dist/mcp/planMcpTools.js +6 -250
  671. package/server/dist/mcp/planReadMcpServer.d.ts +1 -0
  672. package/server/dist/mcp/planReadMcpServer.js +19 -0
  673. package/server/dist/mcp/registry.js +44 -38
  674. package/server/dist/mcp/registryWiring.js +4 -5
  675. package/server/dist/media/demucs.d.ts +5 -0
  676. package/server/dist/media/demucs.js +16 -4
  677. package/server/dist/media/ffmpeg.js +24 -16
  678. package/server/dist/media/scratch.js +24 -9
  679. package/server/dist/noticeSource.d.ts +2 -0
  680. package/server/dist/noticeSource.js +11 -0
  681. package/server/dist/notifications.d.ts +4 -1
  682. package/server/dist/notifications.js +11 -6
  683. package/server/dist/npmPlatformResolve.d.ts +9 -3
  684. package/server/dist/npmPlatformResolve.js +24 -5
  685. package/server/dist/ntfyTransport.d.ts +2 -1
  686. package/server/dist/ntfyTransport.js +15 -4
  687. package/server/dist/outputGrants.d.ts +9 -0
  688. package/server/dist/outputGrants.js +63 -0
  689. package/server/dist/outputStore.d.ts +1 -0
  690. package/server/dist/outputStore.js +1 -1
  691. package/server/dist/outputs.js +117 -21
  692. package/server/dist/peerRecipientContext.js +22 -5
  693. package/server/dist/planHistory.d.ts +3 -0
  694. package/server/dist/planHistory.js +60 -0
  695. package/server/dist/planStore.d.ts +11 -2
  696. package/server/dist/planStore.js +236 -64
  697. package/server/dist/planTools.d.ts +41 -0
  698. package/server/dist/planTools.js +259 -0
  699. package/server/dist/previewAutoDetect.js +31 -23
  700. package/server/dist/previewPortConfiguration.d.ts +2 -0
  701. package/server/dist/previewPortConfiguration.js +32 -0
  702. package/server/dist/previewPorts.d.ts +1 -0
  703. package/server/dist/previewPorts.js +3 -0
  704. package/server/dist/previewProxy.d.ts +30 -9
  705. package/server/dist/previewProxy.js +226 -183
  706. package/server/dist/primaryBackgroundTracker.d.ts +15 -2
  707. package/server/dist/primaryBackgroundTracker.js +172 -63
  708. package/server/dist/primitives/exportContext.d.ts +3 -0
  709. package/server/dist/primitives/exportContext.js +77 -15
  710. package/server/dist/primitives/localFileContext.d.ts +3 -0
  711. package/server/dist/primitives/localFileContext.js +38 -0
  712. package/server/dist/primitives/reviewContent.d.ts +2 -0
  713. package/server/dist/primitives/reviewContent.js +53 -6
  714. package/server/dist/primitives/runCompare.js +1 -1
  715. package/server/dist/primitives/runDocEdit.js +1 -1
  716. package/server/dist/primitives/runMdTuneup.d.ts +7 -2
  717. package/server/dist/primitives/runMdTuneup.js +59 -32
  718. package/server/dist/primitives/runResearch.js +1 -1
  719. package/server/dist/primitives/runReviewer.d.ts +2 -0
  720. package/server/dist/primitives/runReviewer.js +5 -2
  721. package/server/dist/primitives/seedWorker.d.ts +11 -2
  722. package/server/dist/primitives/seedWorker.js +26 -12
  723. package/server/dist/project/orchestrationProposals.d.ts +1 -0
  724. package/server/dist/project/orchestrationProposals.js +5 -1
  725. package/server/dist/project/taskLedger.d.ts +5 -0
  726. package/server/dist/project/taskLedger.js +36 -11
  727. package/server/dist/projectGlob.d.ts +1 -0
  728. package/server/dist/projectGlob.js +9 -0
  729. package/server/dist/projectIgnore.d.ts +1 -0
  730. package/server/dist/projectIgnore.js +24 -0
  731. package/server/dist/projectScan.d.ts +24 -0
  732. package/server/dist/projectScan.js +101 -0
  733. package/server/dist/projectStateIgnore.d.ts +13 -0
  734. package/server/dist/projectStateIgnore.js +36 -1
  735. package/server/dist/projects.d.ts +11 -3
  736. package/server/dist/projects.js +141 -40
  737. package/server/dist/prompts.js +7 -8
  738. package/server/dist/proportionateTestingSkill.d.ts +7 -0
  739. package/server/dist/proportionateTestingSkill.js +32 -0
  740. package/server/dist/providers/attachmentLabels.d.ts +4 -0
  741. package/server/dist/providers/attachmentLabels.js +9 -0
  742. package/server/dist/providers/attachments.d.ts +1 -3
  743. package/server/dist/providers/attachments.js +58 -173
  744. package/server/dist/providers/claude-native/apiEndpoint.d.ts +2 -0
  745. package/server/dist/providers/claude-native/apiEndpoint.js +8 -0
  746. package/server/dist/providers/claude-native/appendOnlyPrefix.js +21 -1
  747. package/server/dist/providers/claude-native/catalog.js +17 -15
  748. package/server/dist/providers/claude-native/contentBlocks.d.ts +22 -2
  749. package/server/dist/providers/claude-native/contentBlocks.js +31 -8
  750. package/server/dist/providers/claude-native/contextBudget.d.ts +0 -4
  751. package/server/dist/providers/claude-native/contextBudget.js +0 -2
  752. package/server/dist/providers/claude-native/editApply.js +6 -1
  753. package/server/dist/providers/claude-native/fileContent.d.ts +15 -0
  754. package/server/dist/providers/claude-native/fileContent.js +120 -0
  755. package/server/dist/providers/claude-native/filterConfigs/bash-cargo-test.js +2 -0
  756. package/server/dist/providers/claude-native/filterConfigs/bash-jest-vitest.js +2 -0
  757. package/server/dist/providers/claude-native/filterConfigs/bash-pytest.js +2 -0
  758. package/server/dist/providers/claude-native/filterConfigs/index.js +2 -1
  759. package/server/dist/providers/claude-native/foldDigest.js +10 -2
  760. package/server/dist/providers/claude-native/gateReview.d.ts +1 -1
  761. package/server/dist/providers/claude-native/gateReview.js +0 -0
  762. package/server/dist/providers/claude-native/hookIf.d.ts +28 -0
  763. package/server/dist/providers/claude-native/hookIf.js +590 -0
  764. package/server/dist/providers/claude-native/hooks.d.ts +77 -7
  765. package/server/dist/providers/claude-native/hooks.js +344 -52
  766. package/server/dist/providers/claude-native/imageRead.d.ts +15 -0
  767. package/server/dist/providers/claude-native/imageRead.js +108 -0
  768. package/server/dist/providers/claude-native/index.d.ts +4 -1
  769. package/server/dist/providers/claude-native/index.js +32 -2
  770. package/server/dist/providers/claude-native/mediaLimits.d.ts +6 -0
  771. package/server/dist/providers/claude-native/mediaLimits.js +15 -0
  772. package/server/dist/providers/claude-native/mediaRetention.d.ts +11 -0
  773. package/server/dist/providers/claude-native/mediaRetention.js +66 -0
  774. package/server/dist/providers/claude-native/mediaRetirementNotice.d.ts +1 -0
  775. package/server/dist/providers/claude-native/mediaRetirementNotice.js +12 -0
  776. package/server/dist/providers/claude-native/modelParams.d.ts +6 -0
  777. package/server/dist/providers/claude-native/modelParams.js +21 -3
  778. package/server/dist/providers/claude-native/oauth.js +9 -8
  779. package/server/dist/providers/claude-native/outputAccumulator.d.ts +2 -0
  780. package/server/dist/providers/claude-native/outputAccumulator.js +29 -18
  781. package/server/dist/providers/claude-native/peerTools.js +5 -156
  782. package/server/dist/providers/claude-native/pretoolGuards.js +92 -9
  783. package/server/dist/providers/claude-native/registryTools.js +4 -2
  784. package/server/dist/providers/claude-native/resumeSummary.d.ts +23 -2
  785. package/server/dist/providers/claude-native/resumeSummary.js +163 -45
  786. package/server/dist/providers/claude-native/sandboxExecutor.js +26 -19
  787. package/server/dist/providers/claude-native/taskAdmission.d.ts +21 -0
  788. package/server/dist/providers/claude-native/taskAdmission.js +75 -0
  789. package/server/dist/providers/claude-native/toolChecks.d.ts +38 -0
  790. package/server/dist/providers/claude-native/toolChecks.js +96 -0
  791. package/server/dist/providers/claude-native/toolPosture.js +5 -3
  792. package/server/dist/providers/claude-native/toolResultEviction.d.ts +4 -3
  793. package/server/dist/providers/claude-native/toolResultEviction.js +18 -29
  794. package/server/dist/providers/claude-native/tools.d.ts +17 -4
  795. package/server/dist/providers/claude-native/tools.js +248 -135
  796. package/server/dist/providers/claude-native/usageContext.d.ts +30 -0
  797. package/server/dist/providers/claude-native/usageContext.js +70 -0
  798. package/server/dist/providers/claude-native/wireFingerprint.d.ts +2 -2
  799. package/server/dist/providers/claude-native/wireFingerprint.js +2 -2
  800. package/server/dist/providers/claude-native/worker.d.ts +63 -1
  801. package/server/dist/providers/claude-native/worker.js +1103 -324
  802. package/server/dist/providers/claude-native/workerHelpers.d.ts +13 -0
  803. package/server/dist/providers/claude-native/workerHelpers.js +117 -6
  804. package/server/dist/providers/claude-native/workspaceFacts.js +2 -2
  805. package/server/dist/providers/claude.d.ts +1 -0
  806. package/server/dist/providers/claude.js +69 -85
  807. package/server/dist/providers/clusterTaskToolDefinitions.d.ts +11 -0
  808. package/server/dist/providers/clusterTaskToolDefinitions.js +161 -0
  809. package/server/dist/providers/codex-appserver/catalog.js +26 -20
  810. package/server/dist/providers/codex-appserver/index.js +10 -3
  811. package/server/dist/providers/codex-appserver/jsonRpc.d.ts +2 -1
  812. package/server/dist/providers/codex-appserver/jsonRpc.js +11 -3
  813. package/server/dist/providers/codex-appserver/worker.d.ts +5 -0
  814. package/server/dist/providers/codex-appserver/worker.js +119 -81
  815. package/server/dist/providers/codex.js +55 -58
  816. package/server/dist/providers/codexChatBoundary.d.ts +11 -0
  817. package/server/dist/providers/codexChatBoundary.js +60 -0
  818. package/server/dist/providers/codexCodeMode.js +2 -2
  819. package/server/dist/providers/codexContextWindow.js +2 -2
  820. package/server/dist/providers/codexHome.d.ts +1 -0
  821. package/server/dist/providers/codexHome.js +6 -0
  822. package/server/dist/providers/codexImageTool.d.ts +6 -0
  823. package/server/dist/providers/codexImageTool.js +21 -0
  824. package/server/dist/providers/codexVersion.d.ts +1 -0
  825. package/server/dist/providers/codexVersion.js +14 -0
  826. package/server/dist/providers/codexWebSearch.d.ts +2 -0
  827. package/server/dist/providers/codexWebSearch.js +4 -0
  828. package/server/dist/providers/cursor/acpJsonRpc.d.ts +1 -0
  829. package/server/dist/providers/cursor/acpJsonRpc.js +3 -1
  830. package/server/dist/providers/cursor/authState.d.ts +10 -0
  831. package/server/dist/providers/cursor/authState.js +78 -0
  832. package/server/dist/providers/cursor/catalog.js +22 -14
  833. package/server/dist/providers/cursor/chatSandbox.d.ts +11 -0
  834. package/server/dist/providers/cursor/chatSandbox.js +81 -0
  835. package/server/dist/providers/cursor/filePlugin.d.ts +4 -0
  836. package/server/dist/providers/cursor/filePlugin.js +31 -0
  837. package/server/dist/providers/cursor/index.d.ts +1 -0
  838. package/server/dist/providers/cursor/index.js +30 -4
  839. package/server/dist/providers/cursor/modelMap.d.ts +35 -0
  840. package/server/dist/providers/cursor/modelMap.js +180 -0
  841. package/server/dist/providers/cursor/print.js +95 -30
  842. package/server/dist/providers/cursor/worker.d.ts +4 -1
  843. package/server/dist/providers/cursor/worker.js +169 -89
  844. package/server/dist/providers/errorClassifier.js +6 -2
  845. package/server/dist/providers/handoffHistoryBinding.d.ts +11 -0
  846. package/server/dist/providers/handoffHistoryBinding.js +43 -0
  847. package/server/dist/providers/index.d.ts +1 -1
  848. package/server/dist/providers/index.js +18 -18
  849. package/server/dist/providers/llamacpp.d.ts +1 -0
  850. package/server/dist/providers/llamacpp.js +102 -192
  851. package/server/dist/providers/llamacppManager.d.ts +5 -0
  852. package/server/dist/providers/llamacppManager.js +68 -32
  853. package/server/dist/providers/llamacppVersion.d.ts +1 -0
  854. package/server/dist/providers/llamacppVersion.js +5 -0
  855. package/server/dist/providers/lmstudio.d.ts +3 -3
  856. package/server/dist/providers/lmstudio.js +133 -207
  857. package/server/dist/providers/localFileMedia.d.ts +25 -0
  858. package/server/dist/providers/localFileMedia.js +302 -0
  859. package/server/dist/providers/localMcp.d.ts +17 -0
  860. package/server/dist/providers/localMcp.js +85 -0
  861. package/server/dist/providers/localProviderQueue.d.ts +2 -0
  862. package/server/dist/providers/localProviderQueue.js +11 -0
  863. package/server/dist/providers/localShellLifecycle.d.ts +7 -0
  864. package/server/dist/providers/localShellLifecycle.js +33 -0
  865. package/server/dist/providers/localToolDispatch.d.ts +28 -0
  866. package/server/dist/providers/localToolDispatch.js +90 -0
  867. package/server/dist/providers/ollama.d.ts +2 -1
  868. package/server/dist/providers/ollama.js +180 -181
  869. package/server/dist/providers/ollamaDurableCompaction.js +5 -4
  870. package/server/dist/providers/ollamaExecutionHistory.d.ts +1 -1
  871. package/server/dist/providers/ollamaExecutionHistory.js +55 -14
  872. package/server/dist/providers/ollamaFencedTools.js +10 -11
  873. package/server/dist/providers/ollamaResilience.js +9 -13
  874. package/server/dist/providers/ollamaTokens.js +3 -4
  875. package/server/dist/providers/ollamaToolSubset.d.ts +2 -0
  876. package/server/dist/providers/ollamaToolSubset.js +11 -40
  877. package/server/dist/providers/ollamaTools.d.ts +13 -0
  878. package/server/dist/providers/ollamaTools.js +225 -219
  879. package/server/dist/providers/outputStyle.d.ts +2 -1
  880. package/server/dist/providers/outputStyle.js +70 -76
  881. package/server/dist/providers/providerFileContent.d.ts +40 -0
  882. package/server/dist/providers/providerFileContent.js +151 -0
  883. package/server/dist/providers/renderedTranscript.d.ts +1 -0
  884. package/server/dist/providers/renderedTranscript.js +3 -0
  885. package/server/dist/providers/requestDeadline.d.ts +1 -0
  886. package/server/dist/providers/requestDeadline.js +26 -0
  887. package/server/dist/providers/sessionScope.d.ts +2 -0
  888. package/server/dist/providers/sessionScope.js +8 -0
  889. package/server/dist/providers/types.d.ts +1 -0
  890. package/server/dist/publicProject.d.ts +62 -0
  891. package/server/dist/publicProject.js +181 -0
  892. package/server/dist/publicProjectChoice.d.ts +4 -0
  893. package/server/dist/publicProjectChoice.js +46 -0
  894. package/server/dist/quota.d.ts +10 -7
  895. package/server/dist/quota.js +49 -19
  896. package/server/dist/recall/index.js +22 -23
  897. package/server/dist/recall/search.js +9 -32
  898. package/server/dist/recall/transcriptSearch.d.ts +4 -0
  899. package/server/dist/recall/transcriptSearch.js +29 -0
  900. package/server/dist/recentFilesLedger.js +9 -7
  901. package/server/dist/recentProjectActivity.d.ts +11 -0
  902. package/server/dist/recentProjectActivity.js +69 -0
  903. package/server/dist/scanDeadline.d.ts +4 -0
  904. package/server/dist/scanDeadline.js +48 -0
  905. package/server/dist/searchText.d.ts +1 -0
  906. package/server/dist/searchText.js +22 -0
  907. package/server/dist/server/broadcast.d.ts +2 -1
  908. package/server/dist/server/broadcast.js +177 -50
  909. package/server/dist/sessionJsonl.js +45 -19
  910. package/server/dist/settings.d.ts +6 -1
  911. package/server/dist/settings.js +183 -56
  912. package/server/dist/skillManagement.d.ts +125 -0
  913. package/server/dist/skillManagement.js +709 -0
  914. package/server/dist/skillMutation.d.ts +1 -0
  915. package/server/dist/skillMutation.js +6 -0
  916. package/server/dist/skills.d.ts +75 -1
  917. package/server/dist/skills.js +254 -75
  918. package/server/dist/smartPickup.d.ts +1 -0
  919. package/server/dist/smartPickup.js +2 -1
  920. package/server/dist/smartPickupAdapters.d.ts +8 -0
  921. package/server/dist/smartPickupAdapters.js +201 -14
  922. package/server/dist/storageActions.d.ts +50 -0
  923. package/server/dist/storageActions.js +326 -0
  924. package/server/dist/storageArchive.d.ts +24 -0
  925. package/server/dist/storageArchive.js +389 -0
  926. package/server/dist/storageOverview.d.ts +47 -0
  927. package/server/dist/storageOverview.js +197 -0
  928. package/server/dist/storageReport.d.ts +48 -0
  929. package/server/dist/storageReport.js +185 -0
  930. package/server/dist/storageRoot.d.ts +5 -0
  931. package/server/dist/storageRoot.js +38 -0
  932. package/server/dist/storageTurnWatch.d.ts +6 -0
  933. package/server/dist/storageTurnWatch.js +36 -0
  934. package/server/dist/storageWarnings.d.ts +4 -0
  935. package/server/dist/storageWarnings.js +96 -0
  936. package/server/dist/taskDispatcher.js +69 -41
  937. package/server/dist/templates/store.js +75 -59
  938. package/server/dist/terminal/ptyManager.d.ts +3 -1
  939. package/server/dist/terminal/ptyManager.js +44 -37
  940. package/server/dist/terminal/ptyPidRegistry.d.ts +4 -2
  941. package/server/dist/terminal/ptyPidRegistry.js +9 -63
  942. package/server/dist/thirdPartySkills.d.ts +4 -0
  943. package/server/dist/thirdPartySkills.js +80 -0
  944. package/server/dist/toolPath.d.ts +1 -0
  945. package/server/dist/toolPath.js +38 -0
  946. package/server/dist/toolboxWorkflow.js +2 -1
  947. package/server/dist/uploadImages.d.ts +6 -0
  948. package/server/dist/uploadImages.js +155 -0
  949. package/server/dist/voice/computerContext.js +2 -0
  950. package/server/dist/voice/conditionSchema.d.ts +1 -0
  951. package/server/dist/voice/conditionSchema.js +3 -1
  952. package/server/dist/voice/conditions.js +1 -1
  953. package/server/dist/workers/StreamParser.d.ts +3 -0
  954. package/server/dist/workers/StreamParser.js +45 -11
  955. package/server/dist/workers/WorkerManager.d.ts +9 -2
  956. package/server/dist/workers/WorkerManager.js +18 -18
  957. package/server/dist/workers/durablePidRegistry.d.ts +53 -0
  958. package/server/dist/workers/durablePidRegistry.js +289 -0
  959. package/server/dist/workers/limits.js +5 -2
  960. package/server/dist/workers/pidRegistry.d.ts +6 -9
  961. package/server/dist/workers/pidRegistry.js +13 -101
  962. package/server/dist/workers/processActivity.d.ts +6 -0
  963. package/server/dist/workers/processActivity.js +13 -0
  964. package/server/dist/workers/processKill.d.ts +30 -0
  965. package/server/dist/workers/processKill.js +174 -0
  966. package/server/dist/workers/processStartTime.d.ts +21 -5
  967. package/server/dist/workers/processStartTime.js +127 -50
  968. package/server/dist/workflowMeta.d.ts +15 -12
  969. package/server/dist/workflowMeta.js +42 -10
  970. package/server/dist/workflowStore.d.ts +3 -0
  971. package/server/dist/workflowStore.js +275 -88
  972. package/server/dist/workflows/modelTitles.js +4 -3
  973. package/server/dist/workflows/purgeWorkflow.d.ts +1 -0
  974. package/server/dist/workflows/purgeWorkflow.js +15 -2
  975. package/server/dist/workflows/sessionDiscovery.js +5 -17
  976. package/server/dist/workflows/sessionIndex.d.ts +2 -0
  977. package/server/dist/workflows/sessionIndex.js +46 -19
  978. package/server/dist/workflows/types.d.ts +15 -5
  979. package/server/dist/workspace.d.ts +1 -0
  980. package/server/dist/workspace.js +5 -0
  981. package/server/dist/ws/afterTurn.d.ts +9 -0
  982. package/server/dist/ws/afterTurn.js +25 -0
  983. package/server/dist/ws/clusterHandlers.d.ts +7 -2
  984. package/server/dist/ws/clusterHandlers.js +361 -407
  985. package/server/dist/ws/clusterMembers.d.ts +42 -0
  986. package/server/dist/ws/clusterMembers.js +165 -0
  987. package/server/dist/ws/compactHandlers.js +38 -28
  988. package/server/dist/ws/gateHandlers.js +2 -1
  989. package/server/dist/ws/genesisHandlers.js +171 -116
  990. package/server/dist/ws/handoffHandlers.d.ts +3 -1
  991. package/server/dist/ws/handoffHandlers.js +367 -196
  992. package/server/dist/ws/previewCaptureHandlers.js +1 -4
  993. package/server/dist/ws/taskLedgerHandlers.d.ts +6 -1
  994. package/server/dist/ws/taskLedgerHandlers.js +34 -13
  995. package/server/dist/ws/taskLifecycle.d.ts +15 -0
  996. package/server/dist/ws/taskLifecycle.js +39 -0
  997. package/server/dist/ws/turnEngine.d.ts +27 -8
  998. package/server/dist/ws/turnEngine.js +1790 -1637
  999. package/server/dist/ws/turnPrompt.d.ts +17 -0
  1000. package/server/dist/ws/turnPrompt.js +47 -0
  1001. package/server/dist/ws/turnSettings.d.ts +41 -0
  1002. package/server/dist/ws/turnSettings.js +61 -0
  1003. package/server/dist/ws/updatePrimaryConfig.js +63 -40
  1004. package/server/dist/ws/workflowHandlers.d.ts +2 -1
  1005. package/server/dist/ws/workflowHandlers.js +223 -182
  1006. package/server/package.json +1 -1
  1007. package/server/src/appBrowsers.ts +95 -0
  1008. package/server/src/architectureReview.ts +327 -0
  1009. package/server/src/architectureSkill.ts +71 -0
  1010. package/server/src/arcoHome.ts +42 -3
  1011. package/server/src/artifactCopy.ts +320 -0
  1012. package/server/src/atomicFile.ts +6 -1
  1013. package/server/src/attention.ts +33 -27
  1014. package/server/src/auth.ts +20 -6
  1015. package/server/src/authLoginSession.ts +7 -2
  1016. package/server/src/boundedRead.ts +172 -0
  1017. package/server/src/capabilities.ts +26 -9
  1018. package/server/src/catchUp.ts +56 -17
  1019. package/server/src/checkedFile.ts +90 -0
  1020. package/server/src/claudeTransport.ts +14 -0
  1021. package/server/src/clusterAutoTurn.ts +55 -7
  1022. package/server/src/clusterBusyReminder.ts +45 -0
  1023. package/server/src/clusterDirector.ts +6 -3
  1024. package/server/src/clusterIdleNudger.ts +6 -0
  1025. package/server/src/clusterMailbox.ts +96 -26
  1026. package/server/src/clusterPeerOps.ts +11 -19
  1027. package/server/src/clusterPlanBridge.ts +37 -45
  1028. package/server/src/clusterPresets.ts +44 -31
  1029. package/server/src/clusterProgress.ts +3 -0
  1030. package/server/src/clusterSnapshots.ts +36 -15
  1031. package/server/src/clusterStore.ts +25 -14
  1032. package/server/src/clusterTurnTools.ts +11 -0
  1033. package/server/src/commandShell.ts +287 -0
  1034. package/server/src/compactionCounter.ts +69 -0
  1035. package/server/src/compactionReport.ts +20 -0
  1036. package/server/src/contentSearch.ts +8 -3
  1037. package/server/src/contextCalibrator.ts +6 -1
  1038. package/server/src/contextEstimator.ts +71 -16
  1039. package/server/src/contextRefs.ts +41 -11
  1040. package/server/src/conversationActivity.ts +26 -0
  1041. package/server/src/cursorUsage.ts +13 -3
  1042. package/server/src/diagnostics/checks.ts +4 -11
  1043. package/server/src/diagnostics/executableLookup.ts +20 -0
  1044. package/server/src/diagnostics/modelHealth.ts +3 -11
  1045. package/server/src/diagnostics/supportBundle.ts +5 -13
  1046. package/server/src/eventLog.ts +718 -0
  1047. package/server/src/existingClusterMembers.ts +9 -0
  1048. package/server/src/explorerArtifacts.ts +27 -10
  1049. package/server/src/explorerChanged.ts +99 -67
  1050. package/server/src/explorerDocs.ts +37 -31
  1051. package/server/src/explorerLaunch.ts +11 -2
  1052. package/server/src/explorerPlans.ts +22 -2
  1053. package/server/src/fileAccessPolicy.ts +82 -1
  1054. package/server/src/fileContent/decodeSlots.ts +31 -0
  1055. package/server/src/fileContent/detect.ts +28 -0
  1056. package/server/src/fileContent/externalImage.ts +49 -0
  1057. package/server/src/fileContent/icons.ts +37 -0
  1058. package/server/src/fileContent/images.ts +140 -0
  1059. package/server/src/fileContent/legacyText.ts +16 -0
  1060. package/server/src/fileContent/notebook.ts +37 -0
  1061. package/server/src/fileContent/office.ts +234 -0
  1062. package/server/src/fileContent/pdf.ts +59 -0
  1063. package/server/src/fileContent/pngRows.ts +54 -0
  1064. package/server/src/fileContent/svg.ts +42 -0
  1065. package/server/src/fileContent/types.ts +39 -0
  1066. package/server/src/fileContent/worker.ts +43 -0
  1067. package/server/src/fileContent.ts +108 -0
  1068. package/server/src/fileContextReceipts.ts +44 -0
  1069. package/server/src/fileFetch.ts +167 -0
  1070. package/server/src/fileVersion.ts +36 -0
  1071. package/server/src/genesis/creative.ts +27 -33
  1072. package/server/src/genesis/prompts.ts +3 -0
  1073. package/server/src/genesis/savePlan.ts +45 -0
  1074. package/server/src/genesis/stages.ts +4 -4
  1075. package/server/src/gitDiff.ts +20 -5
  1076. package/server/src/gitSnapshots.ts +288 -191
  1077. package/server/src/gitWorking.ts +11 -11
  1078. package/server/src/github.ts +3 -1
  1079. package/server/src/goalRun.ts +7 -4
  1080. package/server/src/handoffHistory.ts +89 -0
  1081. package/server/src/handoffHistoryProtocol.ts +20 -0
  1082. package/server/src/handoffHistorySupport.ts +10 -0
  1083. package/server/src/handoffHistoryTool.ts +192 -0
  1084. package/server/src/handoffPrompts.ts +6 -4
  1085. package/server/src/handoffReplay.ts +20 -0
  1086. package/server/src/handoffSeedCache.ts +22 -0
  1087. package/server/src/http/appBrowserRoutes.ts +17 -0
  1088. package/server/src/http/architectureReviewRoutes.ts +86 -0
  1089. package/server/src/http/clusterRoutes.ts +17 -2
  1090. package/server/src/http/clusterSnapshotRoutes.ts +8 -3
  1091. package/server/src/http/connectionsRoutes.ts +5 -1
  1092. package/server/src/http/diffRoutes.ts +36 -3
  1093. package/server/src/http/explorerRoot.ts +20 -0
  1094. package/server/src/http/explorerRoutes.ts +60 -12
  1095. package/server/src/http/fileRead.ts +2 -1
  1096. package/server/src/http/fileWriteRoutes.ts +3 -2
  1097. package/server/src/http/gitCompareRoutes.ts +4 -5
  1098. package/server/src/http/gitDiffRoutes.ts +3 -2
  1099. package/server/src/http/gitOpRoutes.ts +3 -4
  1100. package/server/src/http/gitWorktreeRoutes.ts +3 -2
  1101. package/server/src/http/handoffHistoryRoutes.ts +42 -0
  1102. package/server/src/http/imageWriteRoutes.ts +5 -1
  1103. package/server/src/http/knowledgeRoutes.ts +2 -0
  1104. package/server/src/http/mediaOpsRoutes.ts +2 -1
  1105. package/server/src/http/originGuard.ts +71 -14
  1106. package/server/src/http/outputRoutes.ts +26 -5
  1107. package/server/src/http/projectBinding.ts +108 -0
  1108. package/server/src/http/providerThrottleRoutes.ts +76 -0
  1109. package/server/src/http/publicProjectRoutes.ts +86 -0
  1110. package/server/src/http/readConfinement.ts +16 -9
  1111. package/server/src/http/router.ts +177 -60
  1112. package/server/src/http/searchRoutes.ts +4 -4
  1113. package/server/src/http/sessionTransport.ts +27 -0
  1114. package/server/src/http/skillManagementRoutes.ts +120 -0
  1115. package/server/src/http/storageRoutes.ts +200 -0
  1116. package/server/src/http/usageStatsRoutes.ts +3 -11
  1117. package/server/src/http/utilityAgentRoutes.ts +19 -5
  1118. package/server/src/http/workflowDataRoutes.ts +68 -16
  1119. package/server/src/http/writeConfinement.ts +31 -12
  1120. package/server/src/http/wsAuth.ts +27 -9
  1121. package/server/src/imageTokens.ts +60 -0
  1122. package/server/src/index.ts +269 -178
  1123. package/server/src/inputDeliveryHistory.ts +122 -0
  1124. package/server/src/keepStore.ts +139 -0
  1125. package/server/src/knowledge/store.ts +27 -19
  1126. package/server/src/legacyTarRestore.ts +177 -0
  1127. package/server/src/llamacppCatalog.ts +47 -12
  1128. package/server/src/localRuntimeStatus.ts +121 -0
  1129. package/server/src/lsp/client.ts +19 -11
  1130. package/server/src/lsp/servers.ts +2 -2
  1131. package/server/src/managedPath.ts +38 -0
  1132. package/server/src/management/clusterActivity.ts +6 -16
  1133. package/server/src/management/hubGuard.ts +135 -0
  1134. package/server/src/management/hubLink.ts +8 -2
  1135. package/server/src/management/initHubLink.ts +54 -75
  1136. package/server/src/manualCompactCapability.ts +8 -0
  1137. package/server/src/mcp/arcoMcpServer.ts +4 -0
  1138. package/server/src/mcp/client.ts +28 -11
  1139. package/server/src/mcp/clusterMcpLoopback.ts +27 -1
  1140. package/server/src/mcp/clusterMcpTools.ts +32 -27
  1141. package/server/src/mcp/fileContent.ts +34 -0
  1142. package/server/src/mcp/fileMcpServer.ts +12 -0
  1143. package/server/src/mcp/fileMcpTools.ts +51 -0
  1144. package/server/src/mcp/handoffHistoryMcpTools.ts +21 -0
  1145. package/server/src/mcp/mcpConfigWriter.ts +43 -12
  1146. package/server/src/mcp/planMcpTools.ts +9 -285
  1147. package/server/src/mcp/planReadMcpServer.ts +19 -0
  1148. package/server/src/mcp/registry.ts +41 -35
  1149. package/server/src/mcp/registryWiring.ts +4 -5
  1150. package/server/src/media/demucs.ts +11 -4
  1151. package/server/src/media/ffmpeg.ts +21 -16
  1152. package/server/src/media/scratch.ts +17 -10
  1153. package/server/src/noticeSource.ts +11 -0
  1154. package/server/src/notifications.ts +10 -5
  1155. package/server/src/npmPlatformResolve.ts +25 -8
  1156. package/server/src/ntfyTransport.ts +12 -4
  1157. package/server/src/outputGrants.ts +53 -0
  1158. package/server/src/outputStore.ts +5 -2
  1159. package/server/src/outputs.ts +84 -17
  1160. package/server/src/peerRecipientContext.ts +16 -5
  1161. package/server/src/planHistory.ts +48 -0
  1162. package/server/src/planStore.ts +201 -55
  1163. package/server/src/planTools.ts +303 -0
  1164. package/server/src/previewAutoDetect.ts +26 -19
  1165. package/server/src/previewPortConfiguration.ts +28 -0
  1166. package/server/src/previewPorts.ts +2 -0
  1167. package/server/src/previewProxy.ts +156 -189
  1168. package/server/src/primaryBackgroundTracker.ts +151 -61
  1169. package/server/src/primitives/exportContext.ts +67 -16
  1170. package/server/src/primitives/localFileContext.ts +31 -0
  1171. package/server/src/primitives/reviewContent.ts +42 -7
  1172. package/server/src/primitives/runCompare.ts +1 -1
  1173. package/server/src/primitives/runDocEdit.ts +1 -1
  1174. package/server/src/primitives/runMdTuneup.ts +45 -25
  1175. package/server/src/primitives/runResearch.ts +1 -1
  1176. package/server/src/primitives/runReviewer.ts +6 -2
  1177. package/server/src/primitives/seedWorker.ts +36 -17
  1178. package/server/src/project/orchestrationProposals.ts +6 -1
  1179. package/server/src/project/taskLedger.ts +37 -11
  1180. package/server/src/projectGlob.ts +9 -0
  1181. package/server/src/projectIgnore.ts +19 -0
  1182. package/server/src/projectScan.ts +76 -0
  1183. package/server/src/projectStateIgnore.ts +40 -1
  1184. package/server/src/projects.ts +114 -36
  1185. package/server/src/prompts.ts +5 -8
  1186. package/server/src/proportionateTestingSkill.ts +31 -0
  1187. package/server/src/providers/attachmentLabels.ts +8 -0
  1188. package/server/src/providers/attachments.ts +52 -174
  1189. package/server/src/providers/claude-native/apiEndpoint.ts +9 -0
  1190. package/server/src/providers/claude-native/appendOnlyPrefix.ts +17 -1
  1191. package/server/src/providers/claude-native/catalog.ts +16 -14
  1192. package/server/src/providers/claude-native/contentBlocks.ts +39 -8
  1193. package/server/src/providers/claude-native/contextBudget.ts +0 -6
  1194. package/server/src/providers/claude-native/editApply.ts +6 -1
  1195. package/server/src/providers/claude-native/fileContent.ts +98 -0
  1196. package/server/src/providers/claude-native/filterConfigs/bash-cargo-test.ts +1 -0
  1197. package/server/src/providers/claude-native/filterConfigs/bash-jest-vitest.ts +1 -0
  1198. package/server/src/providers/claude-native/filterConfigs/bash-pytest.ts +1 -0
  1199. package/server/src/providers/claude-native/filterConfigs/index.ts +2 -1
  1200. package/server/src/providers/claude-native/foldDigest.ts +9 -2
  1201. package/server/src/providers/claude-native/gateReview.ts +0 -0
  1202. package/server/src/providers/claude-native/hookIf.ts +414 -0
  1203. package/server/src/providers/claude-native/hooks.ts +398 -54
  1204. package/server/src/providers/claude-native/imageRead.ts +92 -0
  1205. package/server/src/providers/claude-native/index.ts +32 -1
  1206. package/server/src/providers/claude-native/mediaLimits.ts +14 -0
  1207. package/server/src/providers/claude-native/mediaRetention.ts +49 -0
  1208. package/server/src/providers/claude-native/mediaRetirementNotice.ts +8 -0
  1209. package/server/src/providers/claude-native/modelParams.ts +23 -2
  1210. package/server/src/providers/claude-native/oauth.ts +9 -8
  1211. package/server/src/providers/claude-native/outputAccumulator.ts +29 -17
  1212. package/server/src/providers/claude-native/peerTools.ts +5 -167
  1213. package/server/src/providers/claude-native/pretoolGuards.ts +76 -9
  1214. package/server/src/providers/claude-native/registryTools.ts +4 -2
  1215. package/server/src/providers/claude-native/resumeSummary.ts +168 -44
  1216. package/server/src/providers/claude-native/sandboxExecutor.ts +24 -16
  1217. package/server/src/providers/claude-native/taskAdmission.ts +62 -0
  1218. package/server/src/providers/claude-native/toolChecks.ts +127 -0
  1219. package/server/src/providers/claude-native/toolPosture.ts +5 -3
  1220. package/server/src/providers/claude-native/toolResultEviction.ts +17 -7
  1221. package/server/src/providers/claude-native/tools.ts +228 -130
  1222. package/server/src/providers/claude-native/usageContext.ts +93 -0
  1223. package/server/src/providers/claude-native/wireFingerprint.ts +2 -2
  1224. package/server/src/providers/claude-native/worker.ts +1056 -334
  1225. package/server/src/providers/claude-native/workerHelpers.ts +133 -6
  1226. package/server/src/providers/claude-native/workspaceFacts.ts +2 -2
  1227. package/server/src/providers/claude.ts +65 -93
  1228. package/server/src/providers/clusterTaskToolDefinitions.ts +180 -0
  1229. package/server/src/providers/codex-appserver/catalog.ts +26 -19
  1230. package/server/src/providers/codex-appserver/index.ts +8 -3
  1231. package/server/src/providers/codex-appserver/jsonRpc.ts +9 -2
  1232. package/server/src/providers/codex-appserver/worker.ts +108 -77
  1233. package/server/src/providers/codex.ts +49 -57
  1234. package/server/src/providers/codexChatBoundary.ts +55 -0
  1235. package/server/src/providers/codexCodeMode.ts +2 -2
  1236. package/server/src/providers/codexContextWindow.ts +2 -2
  1237. package/server/src/providers/codexHome.ts +6 -0
  1238. package/server/src/providers/codexImageTool.ts +22 -0
  1239. package/server/src/providers/codexVersion.ts +13 -0
  1240. package/server/src/providers/codexWebSearch.ts +5 -0
  1241. package/server/src/providers/cursor/acpJsonRpc.ts +3 -1
  1242. package/server/src/providers/cursor/authState.ts +72 -0
  1243. package/server/src/providers/cursor/catalog.ts +20 -13
  1244. package/server/src/providers/cursor/chatSandbox.ts +71 -0
  1245. package/server/src/providers/cursor/filePlugin.ts +27 -0
  1246. package/server/src/providers/cursor/index.ts +29 -4
  1247. package/server/src/providers/cursor/modelMap.ts +182 -0
  1248. package/server/src/providers/cursor/print.ts +80 -27
  1249. package/server/src/providers/cursor/worker.ts +156 -84
  1250. package/server/src/providers/errorClassifier.ts +7 -2
  1251. package/server/src/providers/handoffHistoryBinding.ts +40 -0
  1252. package/server/src/providers/index.ts +14 -22
  1253. package/server/src/providers/llamacpp.ts +93 -176
  1254. package/server/src/providers/llamacppManager.ts +62 -33
  1255. package/server/src/providers/llamacppVersion.ts +4 -0
  1256. package/server/src/providers/lmstudio.ts +124 -190
  1257. package/server/src/providers/localFileMedia.ts +229 -0
  1258. package/server/src/providers/localMcp.ts +76 -0
  1259. package/server/src/providers/localProviderQueue.ts +13 -0
  1260. package/server/src/providers/localShellLifecycle.ts +30 -0
  1261. package/server/src/providers/localToolDispatch.ts +111 -0
  1262. package/server/src/providers/ollama.ts +161 -171
  1263. package/server/src/providers/ollamaCtxFallback.ts +1 -2
  1264. package/server/src/providers/ollamaDurableCompaction.ts +5 -4
  1265. package/server/src/providers/ollamaExecutionHistory.ts +40 -13
  1266. package/server/src/providers/ollamaFencedTools.ts +10 -11
  1267. package/server/src/providers/ollamaResilience.ts +10 -13
  1268. package/server/src/providers/ollamaTokens.ts +4 -7
  1269. package/server/src/providers/ollamaToolSubset.ts +14 -2
  1270. package/server/src/providers/ollamaTools.ts +212 -200
  1271. package/server/src/providers/outputStyle.ts +72 -72
  1272. package/server/src/providers/providerFileContent.ts +133 -0
  1273. package/server/src/providers/renderedTranscript.ts +2 -0
  1274. package/server/src/providers/requestDeadline.ts +27 -0
  1275. package/server/src/providers/sessionScope.ts +9 -0
  1276. package/server/src/providers/types.ts +3 -0
  1277. package/server/src/publicProject.ts +183 -0
  1278. package/server/src/publicProjectChoice.ts +39 -0
  1279. package/server/src/quota.ts +48 -23
  1280. package/server/src/recall/index.ts +4 -9
  1281. package/server/src/recall/search.ts +9 -32
  1282. package/server/src/recall/transcriptSearch.ts +27 -0
  1283. package/server/src/recentFilesLedger.ts +10 -8
  1284. package/server/src/recentProjectActivity.ts +56 -0
  1285. package/server/src/scanDeadline.ts +26 -0
  1286. package/server/src/searchText.ts +16 -0
  1287. package/server/src/server/broadcast.ts +166 -48
  1288. package/server/src/sessionJsonl.ts +31 -17
  1289. package/server/src/settings.ts +137 -41
  1290. package/server/src/skillManagement.ts +585 -0
  1291. package/server/src/skillMutation.ts +6 -0
  1292. package/server/src/skills.ts +195 -25
  1293. package/server/src/smartPickup.ts +3 -2
  1294. package/server/src/smartPickupAdapters.ts +157 -13
  1295. package/server/src/storageActions.ts +216 -0
  1296. package/server/src/storageArchive.ts +297 -0
  1297. package/server/src/storageOverview.ts +184 -0
  1298. package/server/src/storageReport.ts +210 -0
  1299. package/server/src/storageRoot.ts +30 -0
  1300. package/server/src/storageTurnWatch.ts +39 -0
  1301. package/server/src/storageWarnings.ts +84 -0
  1302. package/server/src/taskDispatcher.ts +22 -2
  1303. package/server/src/templates/store.ts +72 -57
  1304. package/server/src/terminal/ptyManager.ts +37 -27
  1305. package/server/src/terminal/ptyPidRegistry.ts +10 -58
  1306. package/server/src/thirdPartySkills.ts +79 -0
  1307. package/server/src/toolPath.ts +31 -0
  1308. package/server/src/toolboxWorkflow.ts +2 -1
  1309. package/server/src/uploadImages.ts +124 -0
  1310. package/server/src/voice/computerContext.ts +2 -1
  1311. package/server/src/voice/conditionSchema.ts +3 -1
  1312. package/server/src/voice/conditions.ts +1 -1
  1313. package/server/src/workers/StreamParser.ts +42 -11
  1314. package/server/src/workers/WorkerManager.ts +32 -35
  1315. package/server/src/workers/durablePidRegistry.ts +266 -0
  1316. package/server/src/workers/limits.ts +5 -2
  1317. package/server/src/workers/pidRegistry.ts +15 -89
  1318. package/server/src/workers/processActivity.ts +14 -0
  1319. package/server/src/workers/processKill.ts +175 -1
  1320. package/server/src/workers/processStartTime.ts +137 -49
  1321. package/server/src/workflowMeta.ts +59 -19
  1322. package/server/src/workflowStore.ts +248 -76
  1323. package/server/src/workflows/modelTitles.ts +4 -3
  1324. package/server/src/workflows/purgeWorkflow.ts +12 -3
  1325. package/server/src/workflows/sessionDiscovery.ts +5 -13
  1326. package/server/src/workflows/sessionIndex.ts +29 -12
  1327. package/server/src/workflows/types.ts +20 -10
  1328. package/server/src/workspace.ts +6 -0
  1329. package/server/src/ws/afterTurn.ts +34 -0
  1330. package/server/src/ws/clusterHandlers.ts +198 -276
  1331. package/server/src/ws/clusterMembers.ts +204 -0
  1332. package/server/src/ws/compactHandlers.ts +38 -11
  1333. package/server/src/ws/gateHandlers.ts +2 -1
  1334. package/server/src/ws/genesisHandlers.ts +49 -6
  1335. package/server/src/ws/handoffHandlers.ts +168 -53
  1336. package/server/src/ws/previewCaptureHandlers.ts +1 -4
  1337. package/server/src/ws/taskLedgerHandlers.ts +28 -14
  1338. package/server/src/ws/taskLifecycle.ts +41 -0
  1339. package/server/src/ws/turnEngine.ts +488 -366
  1340. package/server/src/ws/turnPrompt.ts +60 -0
  1341. package/server/src/ws/turnSettings.ts +95 -0
  1342. package/server/src/ws/updatePrimaryConfig.ts +55 -31
  1343. package/server/src/ws/workflowHandlers.ts +190 -160
  1344. package/shared/dist/clusterCoordination.js +15 -7
  1345. package/shared/dist/clusterRolePresets.js +8 -6
  1346. package/shared/dist/codexChat.d.ts +2 -0
  1347. package/shared/dist/codexChat.js +5 -0
  1348. package/shared/dist/folderName.d.ts +1 -0
  1349. package/shared/dist/folderName.js +18 -0
  1350. package/shared/dist/index.d.ts +8 -0
  1351. package/shared/dist/index.js +8 -0
  1352. package/shared/dist/localRuntimeStatus.d.ts +23 -0
  1353. package/shared/dist/localRuntimeStatus.js +47 -0
  1354. package/shared/dist/notificationTitle.d.ts +9 -0
  1355. package/shared/dist/notificationTitle.js +23 -0
  1356. package/shared/dist/outputStyle.d.ts +10 -0
  1357. package/shared/dist/outputStyle.js +28 -0
  1358. package/shared/dist/outputs.d.ts +1 -0
  1359. package/shared/dist/protocol/autoPickup.d.ts +3 -1
  1360. package/shared/dist/protocol/autoPickup.js +1 -1
  1361. package/shared/dist/protocol/chat.d.ts +4 -0
  1362. package/shared/dist/protocol/checkpoints.d.ts +25 -2
  1363. package/shared/dist/protocol/checkpoints.js +1 -0
  1364. package/shared/dist/protocol/clientMessages.d.ts +9 -14
  1365. package/shared/dist/protocol/clusters.d.ts +23 -5
  1366. package/shared/dist/protocol/clusters.js +3 -3
  1367. package/shared/dist/protocol/connections.d.ts +2 -0
  1368. package/shared/dist/protocol/diagnostics.js +1 -1
  1369. package/shared/dist/protocol/genesis.d.ts +9 -0
  1370. package/shared/dist/protocol/index.d.ts +1 -0
  1371. package/shared/dist/protocol/index.js +1 -0
  1372. package/shared/dist/protocol/mcp.d.ts +1 -0
  1373. package/shared/dist/protocol/mcp.js +8 -5
  1374. package/shared/dist/protocol/mdTuneup.d.ts +8 -0
  1375. package/shared/dist/protocol/models.d.ts +3 -1
  1376. package/shared/dist/protocol/models.js +19 -8
  1377. package/shared/dist/protocol/notifications.d.ts +4 -2
  1378. package/shared/dist/protocol/notifications.js +18 -5
  1379. package/shared/dist/protocol/plans.d.ts +4 -1
  1380. package/shared/dist/protocol/remoteManagement.d.ts +6 -0
  1381. package/shared/dist/protocol/serverMessages.d.ts +70 -10
  1382. package/shared/dist/protocol/settings.d.ts +16 -4
  1383. package/shared/dist/protocol/settings.js +17 -1
  1384. package/shared/dist/protocol/storage.d.ts +21 -0
  1385. package/shared/dist/protocol/storage.js +3 -0
  1386. package/shared/dist/protocol/tasks.d.ts +4 -0
  1387. package/shared/dist/protocol/usage.d.ts +1 -0
  1388. package/shared/dist/protocol/utilityAgent.d.ts +2 -2
  1389. package/shared/dist/protocol/utilityAgent.js +2 -2
  1390. package/shared/dist/protocol/workers.d.ts +1 -0
  1391. package/shared/dist/protocol/workflows.d.ts +73 -14
  1392. package/shared/dist/protocol/workflows.js +66 -0
  1393. package/shared/dist/publicGuardrails.d.ts +7 -0
  1394. package/shared/dist/publicGuardrails.js +47 -0
  1395. package/shared/dist/publicSafetyRules.d.ts +1 -0
  1396. package/shared/dist/publicSafetyRules.js +6 -0
  1397. package/shared/dist/runtimeVersions.d.ts +2 -0
  1398. package/shared/dist/runtimeVersions.js +13 -0
  1399. package/shared/dist/shellTool.d.ts +2 -0
  1400. package/shared/dist/shellTool.js +9 -0
  1401. package/shared/src/clusterCoordination.ts +12 -7
  1402. package/shared/src/clusterRolePresets.ts +8 -6
  1403. package/shared/src/codexChat.ts +8 -0
  1404. package/shared/src/folderName.ts +11 -0
  1405. package/shared/src/index.ts +11 -0
  1406. package/shared/src/localRuntimeStatus.ts +53 -0
  1407. package/shared/src/notificationTitle.ts +23 -0
  1408. package/shared/src/outputStyle.ts +35 -0
  1409. package/shared/src/outputs.ts +3 -0
  1410. package/shared/src/protocol/autoPickup.ts +3 -1
  1411. package/shared/src/protocol/chat.ts +5 -0
  1412. package/shared/src/protocol/checkpoints.ts +41 -5
  1413. package/shared/src/protocol/clientMessages.ts +11 -11
  1414. package/shared/src/protocol/clusters.ts +46 -11
  1415. package/shared/src/protocol/connections.ts +6 -0
  1416. package/shared/src/protocol/diagnostics.ts +1 -1
  1417. package/shared/src/protocol/genesis.ts +11 -0
  1418. package/shared/src/protocol/index.ts +1 -0
  1419. package/shared/src/protocol/mcp.ts +12 -7
  1420. package/shared/src/protocol/mdTuneup.ts +9 -2
  1421. package/shared/src/protocol/models.ts +22 -8
  1422. package/shared/src/protocol/notifications.ts +22 -5
  1423. package/shared/src/protocol/plans.ts +7 -7
  1424. package/shared/src/protocol/remoteManagement.ts +10 -3
  1425. package/shared/src/protocol/serverMessages.ts +90 -7
  1426. package/shared/src/protocol/settings.ts +35 -5
  1427. package/shared/src/protocol/storage.ts +35 -0
  1428. package/shared/src/protocol/tasks.ts +7 -0
  1429. package/shared/src/protocol/usage.ts +3 -3
  1430. package/shared/src/protocol/utilityAgent.ts +2 -2
  1431. package/shared/src/protocol/workers.ts +5 -0
  1432. package/shared/src/protocol/workflows.ts +133 -21
  1433. package/shared/src/publicGuardrails.ts +50 -0
  1434. package/shared/src/publicSafetyRules.ts +5 -0
  1435. package/shared/src/runtimeVersions.ts +15 -0
  1436. package/shared/src/shellTool.ts +9 -0
  1437. package/client/dist/assets/galleryEditor-Ca4F8HiM.js +0 -702
  1438. package/client/dist/assets/index-CcNtMA2y.js +0 -546
  1439. package/client/dist/assets/index-Dl8tYsSp.css +0 -1
  1440. package/client/src/components/ConversationMenu.tsx +0 -467
  1441. package/client/src/stores/sessionIndexStore.ts +0 -92
@@ -1,16 +1,22 @@
1
- import { buildMessageGuardPolicy } from '@arco/shared';
1
+ import { mintHandoffHistoryCapability } from '../http/handoffHistoryRoutes.js';
2
+ import { deliverAfterTurnRevoked } from './taskLifecycle.js';
3
+ import { resolveClaudeTransport } from '../claudeTransport.js';
4
+ import { projectLocalFileReferences } from '../primitives/localFileContext.js';
5
+ import { getEffectivePublicProjectChoice } from '../publicProjectChoice.js';
6
+ import { buildMessageGuardPolicy, storedOutputStyle } from '@arco/shared';
2
7
  import * as attention from '../attention.js';
3
8
  import { acquireCheckoutWriter, assertCheckoutAvailable, workflowWritePaths, observeCheckoutWriters } from '../checkoutOwnership.js';
4
9
  import { randomUUID } from 'node:crypto';
10
+ import path from 'node:path';
5
11
  import { projectOllamaHistory, stampOllamaExecution } from '../providers/ollamaExecutionHistory.js';
6
12
  import { publishActivity, computerProjectionChanged } from '../voice/activityBus.js';
7
13
  import { setComputerBackgroundClaim, clearComputerBackgroundClaim, isComputerBackgroundClaim } from '../voice/operatorTools.js';
8
14
  import { watchClaimed, watchSettled } from '../voice/watches.js';
9
15
  import { renderComputerHistory } from '../voice/history.js';
10
16
  import { computerReplayEvents, announceComputerSettled } from '../voice/computerContext.js';
11
- import { VOICE_OPERATOR_PROMPT } from '../voice/operatorPrompt.js';
12
17
  import { COMPUTER_TIMEOUT } from '../voice/turnWatchdog.js';
13
- import { isAutoCompactionPolicy, resolveProviderAutoCompaction } from '@arco/shared';
18
+ import { AUTO_HANDOFF_DEFAULT_COMPACTIONS, autoHandoffAvailability, clampAutoHandoffCompactions, isAutoCompactionPolicy, normalizeAutoHandoff, resolveProviderAutoCompaction } from '@arco/shared';
19
+ import { compactionsThisConversation } from '../compactionCounter.js';
14
20
  import { WebSocket } from 'ws';
15
21
  import { discoverClaudeMdFiles } from '../claudeMdDiscovery.js';
16
22
  import { buildKnowledgeBlock } from '../knowledge/store.js';
@@ -21,6 +27,7 @@ import { summarizeTurnChanges, timelyCheckpoint, shouldCaptureTurn } from '../tu
21
27
  import { isManagedBakeoffWorktree } from '../gitBakeoff.js';
22
28
  import * as clusterMailbox from '../clusterMailbox.js';
23
29
  import * as clusterPlanBridge from '../clusterPlanBridge.js';
30
+ import { clusterToolsPending, CLUSTER_TOOLS_PENDING_NOTICE, CLUSTER_TOOLS_PENDING_AGENT } from '../clusterTurnTools.js';
24
31
  import * as clusterStore from '../clusterStore.js';
25
32
  import * as clusterEfficiency from '../clusterEfficiency.js';
26
33
  import { BLIND_CLUSTER_DOCTRINE } from '../clusterAccessDoctrine.js';
@@ -47,15 +54,20 @@ import { isAvailable } from '../quota.js';
47
54
  import { resolveProviderAccount } from '../providerAccounts.js';
48
55
  import { broadcastTransient, broadcastWorkflow, notifyClusterStateForWorkflow, send } from '../server/broadcast.js';
49
56
  import { FOREIGN_WARN_DEBOUNCE_MS, FOREIGN_WRITE_BLOCK_MS, PORT, SESSION_HISTORY_PAGE_SIZE } from '../server/constants.js';
50
- import { buildLocalClusterSystemPrompt, LLAMACPP_PRIMARY_SYSTEM_PROMPT, OLLAMA_PRIMARY_SYSTEM_PROMPT, withPreviewNudge } from '../server/prompts.js';
57
+ import { buildLocalClusterSystemPrompt, LLAMACPP_PRIMARY_SYSTEM_PROMPT, OLLAMA_PRIMARY_SYSTEM_PROMPT } from '../server/prompts.js';
51
58
  import { buildGenesisSystemBlock } from '../genesis/prompts.js';
52
59
  import { CHAT_PROVIDERS, chatSystemPrompt, chatWebArmed, isChatWorkflow } from '../chatMode.js';
60
+ import { resolveNativeInTurnCompactPercent, resolveTurnSettings } from './turnSettings.js';
61
+ import { composeBasePrompts } from './turnPrompt.js';
62
+ import { runAfterTurn } from './afterTurn.js';
53
63
  import { sessions, workflows } from '../server/state.js';
54
64
  import { loadSessionJsonl, resolveSessionJsonlPath, watchSessionJsonl } from '../sessionJsonl.js';
55
65
  import { startUltracodeFleetWatcher } from '../ultracodeFleetWatcher.js';
56
66
  import { readSettings } from '../settings.js';
57
- import { buildPickedSkillsBlock, buildPinnedSkillsBlock, resolvePinnedSkills, buildSkillsManifest, listSkills, readSkillBody } from '../skills.js';
58
- import { ensureMeta, readMeta, reconcileLatestCliSession, updateMeta } from '../workflowMeta.js';
67
+ import { buildPickedSkillsBlock, buildPinnedSkillsBlock, resolvePinnedSkills, buildSkillsManifest, listSkills, readSkillBody, readBuiltinSkill, } from '../skills.js';
68
+ import { ARCHITECTURE_REVIEW_SLUG, architectureReviewFacts } from '../architectureReview.js';
69
+ import { artifactsDir } from '../workers/limits.js';
70
+ import { ensureMeta, readMeta, reconcileLatestCliSession, updateMeta, workflowDir } from '../workflowMeta.js';
59
71
  import { currentSeq as currentWorkflowSeq, replayEvents as replayWorkflowEvents } from '../workflowStore.js';
60
72
  import { latestCodexTokenSnapshot } from '../workflows/transcripts.js';
61
73
  import { foldClaudeNativeWorker } from '../providers/claude-native/index.js';
@@ -69,7 +81,14 @@ const PUBLIC_REPO_SAFETY_SYSTEM_BLOCK = [
69
81
  'Never publish sensitive material. If a file or value is ambiguous, stop and ask the operator before committing or pushing.',
70
82
  ].join('\n');
71
83
  let deps;
72
- export function initTurnEngine(d) { deps = d; }
84
+ export function initTurnEngine(d) {
85
+ deps = d;
86
+ clusterStore.setMemberJoinedListener((clusterId, workflowId) => {
87
+ if (clusterToolsPending(workflows.get(workflowId), clusterId)) {
88
+ broadcastWorkflow(workflowId, { type: 'system_notice', workflowId, content: CLUSTER_TOOLS_PENDING_NOTICE });
89
+ }
90
+ });
91
+ }
73
92
  // Extract renderable entries from a raw Claude session JSONL line. A single
74
93
  // line can produce 0..N entries: assistant messages often contain a text
75
94
  // block plus one or more tool_use blocks, and we want each to show up
@@ -195,19 +214,7 @@ export function toSessionEntries(raw) {
195
214
  }
196
215
  return out;
197
216
  }
198
- // Effective Claude transport for a workflow: sticky ultracode forces 'cli'
199
- // (the harness WorkflowTool lives only in the `claude` binary), else explicit
200
- // per-tab config wins, else the cwd's TRANSPORT DEFAULTS cascade, else 'cli'.
201
- // Same precedence as the turn dispatcher — keep the two in sync.
202
- export async function resolveClaudeTransport(wf, cwd) {
203
- if (wf.primary.provider === 'claude' && wf.config.ultracode === true)
204
- return 'cli';
205
- if (wf.config.claudeTransport === 'native' || wf.config.claudeTransport === 'cli') {
206
- return wf.config.claudeTransport;
207
- }
208
- const cascade = await readSettings(cwd).catch(() => null);
209
- return cascade?.claude?.transport === 'native' ? 'native' : 'cli';
210
- }
217
+ export { resolveClaudeTransport } from '../claudeTransport.js';
211
218
  // Start watching Claude's session JSONL for a workflow.
212
219
  // `initialWs` receives the historical entries; new entries go to all observers.
213
220
  // No-op for non-Claude providers, when primarySessionId is absent, or on the
@@ -217,23 +224,26 @@ export async function resolveClaudeTransport(wf, cwd) {
217
224
  // synthetic "No response requested." rows — render as agent replies while
218
225
  // ChatPanel's sessionChat-canonical mode hid every real finalized answer
219
226
  // otherwise stale session entries could hide finalized answers.
227
+ const sessionWatcherEpochs = new WeakMap();
220
228
  export function startSessionWatcher(workflowId, wf, cwd, initialWs) {
221
- if (wf.primary.provider !== 'claude')
222
- return;
229
+ const epoch = (sessionWatcherEpochs.get(wf) ?? 0) + 1;
230
+ sessionWatcherEpochs.set(wf, epoch);
223
231
  const sessionId = wf.primarySessionId;
224
- if (!sessionId)
225
- return;
226
232
  if (wf.sessionWatcher) {
227
233
  wf.sessionWatcher();
228
234
  wf.sessionWatcher = null;
229
235
  }
236
+ if (wf.primary.provider !== 'claude' || !sessionId)
237
+ return;
238
+ const current = () => workflows.get(workflowId) === wf && wf.primarySessionId === sessionId
239
+ && sessionWatcherEpochs.get(wf) === epoch && wf.primary.provider === 'claude';
230
240
  const path = resolveSessionJsonlPath(cwd, sessionId);
231
241
  resolveClaudeTransport(wf, cwd).then((transport) => {
232
- if (transport === 'native')
242
+ if (!current() || transport === 'native')
233
243
  return null;
234
244
  return loadSessionJsonl(path);
235
245
  }).then((loaded) => {
236
- if (!loaded)
246
+ if (!loaded || !current())
237
247
  return;
238
248
  const { entries, byteLength } = loaded;
239
249
  // Tail-first: only the last N raw entries go out immediately. Anything
@@ -267,6 +277,8 @@ export function startSessionWatcher(workflowId, wf, cwd, initialWs) {
267
277
  if (!workflows.has(workflowId))
268
278
  return; // workflow removed while loading
269
279
  const dispose = watchSessionJsonl(path, byteLength, (raw) => {
280
+ if (!current())
281
+ return;
270
282
  // Concurrent-session detection. Live writes with an entrypoint other
271
283
  // than 'sdk-cli' mean a native `claude --resume` terminal is writing
272
284
  // to this same JSONL. Flag the workflow, and emit a debounced chat
@@ -295,7 +307,7 @@ export function startSessionWatcher(workflowId, wf, cwd, initialWs) {
295
307
  }
296
308
  });
297
309
  const wfNow = workflows.get(workflowId);
298
- if (wfNow) {
310
+ if (wfNow && current()) {
299
311
  wfNow.sessionWatcher = dispose;
300
312
  }
301
313
  else {
@@ -317,17 +329,17 @@ export function derivePrimaryConfig(config) {
317
329
  };
318
330
  }
319
331
  export function deriveAutoHandoff(config) {
332
+ const saved = normalizeAutoHandoff(config.autoHandoff);
320
333
  return {
321
- enabled: config.autoHandoff?.enabled ?? false,
322
- warnAt: config.autoHandoff?.warnAt ?? 75,
323
- autoAt: config.autoHandoff?.autoAt ?? 90,
324
- warnFired: false,
325
- autoFired: false,
334
+ enabled: saved?.enabled ?? false,
335
+ afterCompactions: saved?.afterCompactions ?? AUTO_HANDOFF_DEFAULT_COMPACTIONS,
336
+ compactions: 0,
337
+ fired: false,
326
338
  // WP5 — carry through verbatim (no defaulting); resolution happens at
327
339
  // fire time so a later change to the global default still affects tabs
328
340
  // that never set a per-tab override.
329
- mode: config.autoHandoff?.mode,
330
- summarizer: config.autoHandoff?.summarizer,
341
+ mode: saved?.mode,
342
+ summarizer: saved?.summarizer,
331
343
  };
332
344
  }
333
345
  // §2.1 — mirror WorkflowConfig.autoFold into the live state shape (carrying the
@@ -345,23 +357,30 @@ export function deriveAutoFold(config) {
345
357
  };
346
358
  }
347
359
  export function applyAutoHandoffDefault(config, defaults) {
360
+ // A config from an older client or saved file may carry percent fields.
361
+ if (config.autoHandoff !== undefined) {
362
+ const saved = normalizeAutoHandoff(config.autoHandoff);
363
+ if (saved)
364
+ config.autoHandoff = saved;
365
+ else
366
+ delete config.autoHandoff;
367
+ }
348
368
  if (config.autoHandoff)
349
369
  return false;
350
370
  if (!defaults)
351
371
  return false;
352
372
  if (defaults.enabled === undefined
353
- && defaults.warnAt === undefined
354
- && defaults.autoAt === undefined
373
+ && defaults.afterCompactions === undefined
355
374
  && defaults.mode === undefined
356
375
  && defaults.summarizer === undefined)
357
376
  return false;
358
- config.autoHandoff = {
377
+ // Through normalizeAutoHandoff so the saved form carries the 0.1.4 fields too.
378
+ config.autoHandoff = normalizeAutoHandoff({
359
379
  enabled: defaults.enabled ?? false,
360
- warnAt: defaults.warnAt ?? 75,
361
- autoAt: defaults.autoAt ?? 90,
380
+ afterCompactions: clampAutoHandoffCompactions(defaults.afterCompactions),
362
381
  ...(defaults.mode !== undefined ? { mode: defaults.mode } : {}),
363
382
  ...(defaults.summarizer !== undefined ? { summarizer: defaults.summarizer } : {}),
364
- };
383
+ });
365
384
  return true;
366
385
  }
367
386
  export async function refreshCodexTokenSnapshot(workflowId, wf, codexHome, opts) {
@@ -390,8 +409,6 @@ export async function refreshCodexTokenSnapshot(workflowId, wf, codexHome, opts)
390
409
  }
391
410
  export function resetCodexContextAfterCompact(workflowId, wf, modelContextWindow) {
392
411
  wf.lastContextPercent = 0;
393
- wf.autoHandoff.warnFired = false;
394
- wf.autoHandoff.autoFired = false;
395
412
  broadcastTransient(workflowId, {
396
413
  type: 'codex_token_snapshot',
397
414
  workflowId,
@@ -429,6 +446,8 @@ export function anyObserver(workflowId) {
429
446
  let busyClaimSeq = 0;
430
447
  const busyCheckoutLeases = new WeakMap();
431
448
  const busyOwners = new WeakMap();
449
+ const storageMigrations = new WeakSet();
450
+ const incomingMessages = new WeakMap();
432
451
  const lastBusyClaim = new WeakMap();
433
452
  const busyRevocations = new WeakMap();
434
453
  export function publishWorkerActivity(wf, kind) {
@@ -440,7 +459,9 @@ export function publishWorkerActivity(wf, kind) {
440
459
  break;
441
460
  }
442
461
  }
443
- export function claimBusy(wf) {
462
+ export function claimBusy(wf, workerActivity = true) {
463
+ if (storageMigrations.has(wf))
464
+ throw new Error('Workflow storage is moving. Wait for the scaffold to finish.');
444
465
  // Keep the existing conservative restore reservation, but observe isolated
445
466
  // members at their actual scratch cwd for turn-overlap reporting.
446
467
  const wfid = [...workflows].find(([, current]) => current === wf)?.[0];
@@ -455,14 +476,32 @@ export function claimBusy(wf) {
455
476
  lastBusyClaim.set(wf, token);
456
477
  watchClaimed(wf, token);
457
478
  wf.busy = true;
479
+ wf.turnStartedAt = undefined;
480
+ if (wfid && workerActivity)
481
+ void notifyClusterStateForWorkflow(wfid);
458
482
  if (wf.config?.voiceOperator)
459
483
  wf.computerSettled = false;
460
- publishWorkerActivity(wf, 'worker_started');
484
+ if (workerActivity)
485
+ publishWorkerActivity(wf, 'worker_started');
461
486
  return token;
462
487
  }
488
+ export function isWorkflowStorageMoving(wf) { return storageMigrations.has(wf); }
489
+ export function reserveWorkflowMigration(wf) {
490
+ if (wf.busy || storageMigrations.has(wf) || incomingMessages.get(wf))
491
+ throw new Error('Workflow is busy.');
492
+ const token = claimBusy(wf, false);
493
+ storageMigrations.add(wf);
494
+ return () => { storageMigrations.delete(wf); if (!releaseBusy(wf, token, 'finished', false))
495
+ wf.busy = false; };
496
+ }
463
497
  export function ownsBusy(wf, token) {
464
498
  return busyOwners.get(wf) === token;
465
499
  }
500
+ // A released claim remains current until another claim or STOP supersedes it.
501
+ // Background completion metadata can use this without retaining busy.
502
+ export function isCurrentBusyClaim(wf, token) {
503
+ return lastBusyClaim.get(wf) === token;
504
+ }
466
505
  // Returns false (and leaves wf.busy alone) when the claim was revoked or
467
506
  // superseded — the caller is a stale holder and must not touch busy/queue.
468
507
  export function releaseBusy(wf, token, outcome = 'interrupted', workerActivity = true) {
@@ -473,6 +512,7 @@ export function releaseBusy(wf, token, outcome = 'interrupted', workerActivity =
473
512
  busyCheckoutLeases.get(wf)?.();
474
513
  busyCheckoutLeases.delete(wf);
475
514
  wf.busy = false;
515
+ wf.turnStartedAt = undefined;
476
516
  clearComputerBackgroundClaim([...workflows].find(([, current]) => current === wf)?.[0] ?? '', token);
477
517
  if (wf.config?.voiceOperator)
478
518
  computerProjectionChanged();
@@ -498,7 +538,8 @@ export function revokeBusy(wf) {
498
538
  busyOwners.delete(wf);
499
539
  busyCheckoutLeases.get(wf)?.();
500
540
  busyCheckoutLeases.delete(wf);
501
- wf.busy = false;
541
+ wf.busy = storageMigrations.has(wf);
542
+ wf.turnStartedAt = undefined;
502
543
  if (token !== undefined)
503
544
  clearComputerBackgroundClaim([...workflows].find(([, current]) => current === wf)?.[0] ?? '', token);
504
545
  if (wf.config?.voiceOperator)
@@ -597,8 +638,7 @@ export async function maybeAutoFold(workflowId, wf, cwd, onAttempt, canAttempt)
597
638
  if ((st.foldIneffectiveCount ?? 0) >= MAX_INEFFECTIVE_FOLDS)
598
639
  return false;
599
640
  // Native transport required (CLI Claude has no in-process history to fold).
600
- const cascade = await readSettings(cwd).catch(() => null);
601
- const transport = wf.config.claudeTransport ?? (cascade?.claude?.transport === 'native' ? 'native' : 'cli');
641
+ const transport = await resolveClaudeTransport(wf, cwd);
602
642
  if (transport !== 'native')
603
643
  return false;
604
644
  // Re-check after the settings await: an operator message can have claimed
@@ -645,97 +685,108 @@ export async function maybeAutoFold(workflowId, wf, cwd, onAttempt, canAttempt)
645
685
  console.log(`[arco] [${workflowId.slice(0, 8)}] auto-fold fired at ${pct}% budget, byteDelta=${res.byteDelta ?? 0}`);
646
686
  return true;
647
687
  }
648
- // Check context fill and fire warning or auto-handoff. Called after the turn
649
- // loop exits (wf.busy has been reset to false by the finally block).
688
+ // Auto-handoff after N compactions (operator decision for 0.1.5). Runs at a
689
+ // turn boundary only: called after the turn loop exits (wf.busy reset), before
690
+ // any automatic fold or compaction of that boundary. Nothing is said before
691
+ // the handoff; once it has run, one chat line names the count and links the
692
+ // handoff document. Returns true when a handoff was started.
650
693
  export async function maybeAutoHandoff(workflowId, wf, cwd) {
651
694
  // Chat tabs are projectless: a handoff re-seeds as an Agent worker (tools,
652
695
  // project context) and, for incognito, installed a cwdHandoffChain slot for
653
- // the temp root + broadcast lock snapshots. deriveAutoHandoff defaults ON,
654
- // so an Ollama chat at 90% window used to rotate into an Agent tab silently.
696
+ // the temp root + broadcast lock snapshots. Never automatically.
655
697
  if (isChatWorkflow(wf.config))
656
- return;
657
- const percentOfWindow = wf.lastContextPercent;
658
- if (typeof percentOfWindow !== 'number' || percentOfWindow <= 0)
659
- return;
698
+ return false;
660
699
  const ah = wf.autoHandoff;
661
- // Reset fired flags when context drops back to safe levels (after a handoff
662
- // the new session starts near 0%).
663
- if (percentOfWindow < Math.max(0, ah.warnAt - 5)) {
664
- ah.warnFired = false;
665
- ah.autoFired = false;
700
+ if (!ah?.enabled || ah.fired || wf.busy)
701
+ return false;
702
+ const count = compactionsThisConversation(wf);
703
+ if (count < ah.afterCompactions)
704
+ return false;
705
+ const cascade = await readSettings(cwd).catch(() => null);
706
+ if (!(await autoHandoffAvailableFor(workflowId, wf, cwd, cascade)).available)
707
+ return false;
708
+ if (wf.busy || ah.fired)
709
+ return false;
710
+ const obs = anyObserver(workflowId);
711
+ if (!obs) {
712
+ console.warn(`[arco] [${workflowId.slice(0, 8)}] auto-handoff: no observer to broadcast on`);
713
+ return false;
714
+ }
715
+ ah.fired = true;
716
+ console.log(`[arco] [${workflowId.slice(0, 8)}] auto-handoff: ${count} compactions this conversation, firing`);
717
+ // Re-use the same handoff logic as the manual button by constructing
718
+ // a synthetic message and calling the handler.
719
+ //
720
+ // Per-tab override wins over the global default; quick is the fallback.
721
+ const mode = wf.autoHandoff.mode
722
+ ?? cascade?.autoHandoffDefaults?.mode
723
+ ?? 'quick';
724
+ // Keep mode resolution in sync with manual handoff: provider-specific
725
+ // resume capability is handled by handoffHandlers, which translates the
726
+ // original-worker choice where a live session cannot be reopened.
727
+ const synthMsg = {
728
+ type: 'handoff_request',
729
+ workflowId,
730
+ mode,
731
+ };
732
+ // SUMMARIZER resolution: only matters for fresh-summarizer. Put the
733
+ // per-tab summarizer (if set) onto the synthesized message; the handler's
734
+ // chain is `msg.summarizer ?? settings.handoffSummarizer ?? primary`, so
735
+ // per-tab wins, global is the middle, primary is last. For original-worker
736
+ // we leave summarizer unset.
737
+ if (mode === 'fresh-summarizer' && wf.autoHandoff.summarizer) {
738
+ const s = wf.autoHandoff.summarizer;
739
+ synthMsg.summarizer = {
740
+ provider: s.provider,
741
+ model: s.model ?? wf.primary.model,
742
+ effort: s.effort ?? 'medium',
743
+ };
666
744
  }
667
- // Warning
668
- if (percentOfWindow >= ah.warnAt && !ah.warnFired) {
669
- ah.warnFired = true;
670
- const obs = anyObserver(workflowId);
671
- if (obs) {
672
- send(obs, {
745
+ try {
746
+ const dummySession = sessions.get(obs) ?? { id: 'auto', workflowIds: new Set([workflowId]), clusterIds: new Set(), clusterObserved: new Map() };
747
+ const done = await deps.handleHandoffRequest(obs, dummySession, synthMsg);
748
+ if (done && typeof done === 'object' && done.artifactName) {
749
+ const doc = path.join(workflowDir(cwd, workflowId), 'handoffs', done.artifactName);
750
+ broadcastWorkflow(workflowId, {
673
751
  type: 'system_notice',
674
752
  workflowId,
675
- content: `[CONTEXT] ${percentOfWindow}% — handoff recommended. Auto-handoff at ${ah.autoAt}%.`,
753
+ content: `Handed off after ${count} compaction${count === 1 ? '' : 's'}: [handoff document](${doc.split(path.sep).join('/')})`,
676
754
  });
677
755
  }
678
- console.log(`[arco] [${workflowId.slice(0, 8)}] context warning: ${percentOfWindow}% >= ${ah.warnAt}%`);
756
+ // Not completed (cancelled, refused, or failed with its own notice): no
757
+ // retry in this conversation; HANDOFF stays available.
679
758
  }
680
- // Auto-handoff
681
- if (ah.enabled && percentOfWindow >= ah.autoAt && !ah.autoFired && !wf.busy) {
682
- ah.autoFired = true;
683
- const obs = anyObserver(workflowId);
684
- if (!obs) {
685
- console.warn(`[arco] [${workflowId.slice(0, 8)}] auto-handoff: no observer to broadcast on`);
686
- return;
687
- }
688
- console.log(`[arco] [${workflowId.slice(0, 8)}] auto-handoff: context at ${percentOfWindow}%, firing`);
689
- send(obs, {
690
- type: 'system_notice',
691
- workflowId,
692
- content: `[AUTO-HANDOFF] Context at ${percentOfWindow}%. Rotating the session.`,
693
- });
694
- // Re-use the same handoff logic as the manual button by constructing
695
- // a synthetic message and calling the handler.
696
- //
697
- // Per-tab override wins over the global default; quick is the fallback.
698
- const cascade = await readSettings(cwd).catch(() => null);
699
- const mode = wf.autoHandoff.mode
700
- ?? cascade?.autoHandoffDefaults?.mode
701
- ?? 'quick';
702
- // Keep mode resolution in sync with manual handoff: provider-specific
703
- // resume capability is handled by handoffHandlers, which translates the
704
- // original-worker choice where a live session cannot be reopened.
705
- const synthMsg = {
706
- type: 'handoff_request',
707
- workflowId,
708
- mode,
709
- };
710
- // SUMMARIZER resolution: only matters for fresh-summarizer. Put the
711
- // per-tab summarizer (if set) onto the synthesized message; the handler's
712
- // chain is `msg.summarizer ?? settings.handoffSummarizer ?? primary`, so
713
- // per-tab wins, global is the middle, primary is last. For original-worker
714
- // we leave summarizer unset.
715
- if (mode === 'fresh-summarizer' && wf.autoHandoff.summarizer) {
716
- const s = wf.autoHandoff.summarizer;
717
- synthMsg.summarizer = {
718
- provider: s.provider,
719
- model: s.model ?? wf.primary.model,
720
- effort: s.effort ?? 'medium',
721
- };
722
- }
723
- try {
724
- const dummySession = sessions.get(obs) ?? { id: 'auto', workflowIds: new Set([workflowId]), clusterIds: new Set(), clusterObserved: new Map() };
725
- await deps.handleHandoffRequest(obs, dummySession, synthMsg);
726
- }
727
- catch (err) {
728
- console.error(`[arco] [${workflowId.slice(0, 8)}] auto-handoff failed:`, err);
729
- const obs2 = anyObserver(workflowId);
730
- if (obs2) {
731
- send(obs2, {
732
- type: 'system_notice',
733
- workflowId,
734
- content: `[AUTO-HANDOFF FAILED] ${err instanceof Error ? err.message : String(err)}. Click HANDOFF manually.`,
735
- });
736
- }
759
+ catch (err) {
760
+ console.error(`[arco] [${workflowId.slice(0, 8)}] auto-handoff failed:`, err);
761
+ const obs2 = anyObserver(workflowId);
762
+ if (obs2) {
763
+ send(obs2, {
764
+ type: 'system_notice',
765
+ workflowId,
766
+ content: `[AUTO-HANDOFF FAILED] ${err instanceof Error ? err.message : String(err)}. Click HANDOFF manually.`,
767
+ });
737
768
  }
738
769
  }
770
+ return true;
771
+ }
772
+ // Whether auto-handoff can count compactions for this tab now (provider,
773
+ // transport and the resolved auto-compaction policy, worker over cluster).
774
+ export async function autoHandoffAvailableFor(workflowId, wf, cwd, cascade) {
775
+ const settings = cascade === undefined ? await readSettings(cwd).catch(() => null) : cascade;
776
+ const provider = wf.primary.provider;
777
+ const claudeTransport = provider === 'claude' ? await resolveClaudeTransport(wf, cwd) : undefined;
778
+ const codexTransport = wf.config.codexTransport ?? (settings?.codex?.transport === 'appserver' ? 'appserver' : 'exec');
779
+ const clusterId = clusterStore.getClusterIdForWorkflow(workflowId);
780
+ const ollamaSaved = settings?.ollama?.compaction?.enabled !== undefined || settings?.ollama?.compaction?.threshold !== undefined;
781
+ const compaction = resolveProviderAutoCompaction(wf.config.autoCompaction, clusterId ? clusterStore.getAutoCompaction(clusterId) : undefined, provider, claudeTransport ?? '', wf.config.claudeNativeCompact === true, ollamaSaved);
782
+ return autoHandoffAvailability({
783
+ provider,
784
+ claudeTransport,
785
+ codexTransport,
786
+ chat: isChatWorkflow(wf.config),
787
+ compaction,
788
+ ollamaSavedEnabled: ollamaSaved ? settings?.ollama?.compaction?.enabled !== false : undefined,
789
+ });
739
790
  }
740
791
  export function freshAutoCompactionPercent(provider, transport, outcome) {
741
792
  if (outcome.error || !((provider === 'claude' && transport === 'native') || (provider === 'codex' && transport === 'appserver')))
@@ -791,8 +842,13 @@ export async function maybeAutoCompactPolicy(workflowId, wf, cwd, policy, readin
791
842
  export async function runExplicitContextActions(workflowId, wf, cwd, policy, reading, busyToken, ws, session) {
792
843
  if (lastBusyClaim.get(wf) !== busyToken)
793
844
  return 'stale';
794
- // Ollama compacts at the next pre-dispatch boundary. Do not start an
795
- // automatic fresh-session handoff ahead of that explicitly chosen policy.
845
+ // A due auto-handoff starts a fresh session, so this boundary needs no
846
+ // fold or compaction.
847
+ if (await maybeAutoHandoff(workflowId, wf, cwd))
848
+ return 'done';
849
+ if (lastBusyClaim.get(wf) !== busyToken)
850
+ return 'stale';
851
+ // Ollama compacts at the next pre-dispatch boundary.
796
852
  if (wf.primary.provider === 'ollama' && policy.enabled)
797
853
  return 'done';
798
854
  let foldClaim;
@@ -808,7 +864,6 @@ export async function runExplicitContextActions(workflowId, wf, cwd, policy, rea
808
864
  return 'done';
809
865
  if (await maybeAutoCompactPolicy(workflowId, wf, cwd, policy, reading, busyToken, ws, session))
810
866
  return 'compact-attempted';
811
- await maybeAutoHandoff(workflowId, wf, cwd);
812
867
  return 'done';
813
868
  }
814
869
  // NATIVE_COMPACTION_PLAN Phase 3 — the continuance prompt the opt-in auto-continue
@@ -842,7 +897,15 @@ export async function maybeAutoContinueAfterCompact(workflowId, ws, session) {
842
897
  // turn starts while calibration is running, the pty is cancelled via
843
898
  // wf.cancelCalibration (set by the primary turn handler in handleUserMessage).
844
899
  export async function maybeCalibrate(workflowId, wf, cwd) {
845
- if (wf.primary.provider !== 'claude')
900
+ const sessionId = wf.primarySessionId;
901
+ const model = wf.primary.model;
902
+ const claim = lastBusyClaim.get(wf);
903
+ const revocation = busyRevocations.get(wf);
904
+ const stillIdle = () => workflows.get(workflowId) === wf && !wf.busy
905
+ && wf.primary.provider === 'claude' && wf.primarySessionId === sessionId
906
+ && wf.primary.model === model && lastBusyClaim.get(wf) === claim
907
+ && busyRevocations.get(wf) === revocation;
908
+ if (!sessionId || !stillIdle() || wf.cancelCalibration)
846
909
  return;
847
910
  // CLI transport only. Native gets exact token counts from the API
848
911
  // (lastPromptTokens) — the byte-ratio estimator this tunes never runs for
@@ -853,8 +916,7 @@ export async function maybeCalibrate(workflowId, wf, cwd) {
853
916
  // transcript truth.
854
917
  if (await resolveClaudeTransport(wf, cwd) === 'native')
855
918
  return;
856
- const sessionId = wf.primarySessionId;
857
- if (!sessionId)
919
+ if (!stillIdle())
858
920
  return;
859
921
  const cal = wf.calibration ?? {
860
922
  ratio: BYTES_PER_TOKEN_DEFAULT,
@@ -863,14 +925,14 @@ export async function maybeCalibrate(workflowId, wf, cwd) {
863
925
  };
864
926
  // Get current estimate to detect zone crossing
865
927
  const est = await estimateContextFill(cwd, sessionId, wf.primary.model, cal).catch(() => null);
866
- if (!est)
928
+ if (!est || !stillIdle())
867
929
  return;
868
930
  const currentPercent = est.percentOfWindow;
869
931
  const prevPercent = wf.lastContextPercent;
870
932
  wf.lastContextPercent = currentPercent;
871
- // Don't calibrate at or above the auto-handoff threshold — not worth the
872
- // latency when a session rotation is imminent.
873
- if (currentPercent >= wf.autoHandoff.autoAt)
933
+ // Don't calibrate near a full window: not worth the latency when the CLI's
934
+ // own compaction is imminent.
935
+ if (currentPercent >= 90)
874
936
  return;
875
937
  // Skip when the estimator already has ground truth from the JSONL usage
876
938
  // blocks — calibration only exists to tune the byte-count ratio, and the
@@ -892,16 +954,27 @@ export async function maybeCalibrate(workflowId, wf, cwd) {
892
954
  if (!zone)
893
955
  return;
894
956
  console.log(`[arco] [${workflowId.slice(0, 8)}] calibrating zone ${zone} at ${currentPercent}%`);
957
+ if (!stillIdle() || wf.cancelCalibration)
958
+ return;
959
+ let cancelProbe;
960
+ let cancelled = false;
961
+ const cancel = () => { cancelled = true; cancelProbe?.(); };
962
+ wf.cancelCalibration = cancel;
895
963
  let result = null;
896
964
  try {
897
965
  result = await runCalibration(sessionId, wf.primary.model, cwd, est.jsonlBytes, (cancelFn) => {
898
- wf.cancelCalibration = cancelFn;
966
+ cancelProbe = cancelFn;
967
+ if (cancelled || !stillIdle())
968
+ cancelFn();
899
969
  });
900
970
  }
901
971
  catch (err) {
902
972
  console.error(`[arco] [${workflowId.slice(0, 8)}] calibration error:`, err);
903
973
  }
904
- wf.cancelCalibration = undefined;
974
+ if (wf.cancelCalibration === cancel)
975
+ wf.cancelCalibration = undefined;
976
+ if (cancelled || !stillIdle())
977
+ return;
905
978
  if (!result) {
906
979
  console.warn(`[arco] [${workflowId.slice(0, 8)}] calibration zone ${zone} failed or was cancelled`);
907
980
  return;
@@ -934,7 +1007,7 @@ export async function maybeCalibrate(workflowId, wf, cwd) {
934
1007
  // Plan-less workflows receive a single-line note describing plan creation and
935
1008
  // attachment. It preserves the parseable phase and checkbox structure and can
936
1009
  // be stripped from session replay without duplicating the user message.
937
- function planAuthoringNote(cwd, workflowId) {
1010
+ function planAuthoringNote(cwd, workflowId, publicProject = false) {
938
1011
  return (`[No project plan is attached to this Arco workflow. If asked to create/attach one, do NOT just write a ` +
939
1012
  `markdown file — a loose file is invisible to Arco. Prefer the \`plan_create\` tool (MCP server \`arco\`) ` +
940
1013
  `if you have it — one call, title + body, creates and attaches. Otherwise write the body to a scratch file, then POST it (this ` +
@@ -950,13 +1023,17 @@ function planAuthoringNote(cwd, workflowId) {
950
1023
  `docs, which hold the specs/research/design detail. After creating the plan, write each doc with \`plan_ref_write\` ` +
951
1024
  `(or as files at .arco/plans/<planId>.refs/<slug>.md — not loose design files elsewhere in the repo) and link it ` +
952
1025
  `from every task that depends on it as \`[label](ref:slug)\`; whoever works that task reads the linked ref first. ` +
1026
+ (publicProject ? `This project is public. Include a Privacy and public safety section in any new plan, fitted to this project and its risks. ` : '') +
953
1027
  `Don't create a plan unless asked.]\n\n`);
954
1028
  }
955
1029
  export async function buildPlanPrefix(cwd, wf, workflowId) {
956
1030
  if (!cwd)
957
1031
  return '';
958
- if (!wf.planId)
959
- return planAuthoringNote(cwd, workflowId);
1032
+ if (!wf.planId) {
1033
+ const isPublic = await getEffectivePublicProjectChoice(cwd).catch((error) => { if (error.code === 'ENOENT')
1034
+ return null; throw error; });
1035
+ return planAuthoringNote(cwd, workflowId, isPublic === true);
1036
+ }
960
1037
  const plan = await readPlan(cwd, wf.planId).catch(() => null);
961
1038
  if (!plan) {
962
1039
  // Plan was deleted out from under us. Detach quietly so future turns
@@ -1020,6 +1097,7 @@ export async function buildPlanPrefix(cwd, wf, workflowId) {
1020
1097
  export function projectQueue(items) {
1021
1098
  return items.map((q) => ({
1022
1099
  content: q.content,
1100
+ ...(q.automaticKind ? { automaticKind: q.automaticKind } : {}),
1023
1101
  ...(q.interrupt ? { interrupt: true } : {}),
1024
1102
  ...(q.clientMessageId ? { clientMessageId: q.clientMessageId } : {}),
1025
1103
  }));
@@ -1052,8 +1130,8 @@ export function broadcastQueueUpdate(workflowId) {
1052
1130
  // shape the post-turn drain uses. The `user_message_echo` was already
1053
1131
  // emitted at enqueue time (handleUserMessage) so we don't re-echo here;
1054
1132
  // the persisted echo at the original timestamp is the authoritative
1055
- // transcript record. Replay therefore renders the steer as a normal
1056
- // user-message at its enqueue position with `kind: 'steer'`.
1133
+ // audit record. Delivery attempt metadata places the input at its confirmed
1134
+ // boundary for provider replay and review, while the live chat keeps the echo.
1057
1135
  //
1058
1136
  // Retry safety: the drain is destructive (splice) so a same-iteration
1059
1137
  // re-call would return []. Provider-side retry loops that call drainSteer
@@ -1061,38 +1139,48 @@ export function broadcastQueueUpdate(workflowId) {
1061
1139
  // results and the next streamOneTurn) cannot double-deliver. Recovery
1062
1140
  // paths in llamacpp.ts inject their own synthetic user messages and skip
1063
1141
  // past the hook — by design.
1064
- export function drainSteerForWorker(workflowId, ws) {
1142
+ const originalSteerItems = new WeakMap();
1143
+ export function drainSteerForWorker(workflowId, ws, deliveryProvider) {
1065
1144
  const wf = workflows.get(workflowId);
1066
1145
  if (!wf || wf.queue.steering.length === 0 || wf.primaryTurn?.holdSteer || wf.queue.steering.some((q) => q.interrupt))
1067
1146
  return [];
1068
1147
  const drained = wf.queue.steering.splice(0);
1148
+ const deliveryId = randomUUID();
1069
1149
  broadcastQueueUpdate(workflowId);
1070
1150
  const drainedClientIds = drained
1071
1151
  .map((d) => d.clientMessageId)
1072
1152
  .filter((id) => typeof id === 'string' && id.length > 0);
1073
- if (drainedClientIds.length > 0 && wf.primary.provider !== 'codex') {
1074
- broadcastTransient(workflowId, { type: 'turn_messages_delivered', workflowId, clientMessageIds: drainedClientIds });
1153
+ if (drainedClientIds.length > 0 && (deliveryProvider ?? wf.primary.provider) !== 'codex') {
1154
+ broadcastWorkflow(workflowId, { type: 'turn_messages_delivered', workflowId, clientMessageIds: drainedClientIds, deliveryId });
1075
1155
  }
1076
1156
  if (drainedClientIds.length > 0) {
1077
1157
  send(ws, {
1078
1158
  type: 'queued_messages_drained',
1079
1159
  workflowId,
1160
+ deliveryId,
1080
1161
  clientMessageIds: drainedClientIds,
1081
1162
  drainedAt: Date.now(),
1082
1163
  });
1083
1164
  }
1084
1165
  console.log(`[arco] [${workflowId.slice(0, 8)}] mid-turn steer drained (${drained.length} item${drained.length === 1 ? '' : 's'}; follow-up bucket untouched)`);
1085
- return drained.map((d) => ({
1086
- // §D1 — mid-turn steer is delivered as a single `content` string through
1087
- // the provider steer APIs (SteerItem has no separate context block), so a
1088
- // steer message's expanded `@`-refs ride appended to its content. The echo
1089
- // already went out compact at enqueue; this only affects what the model
1090
- // sees mid-turn. Post-turn drain (the loop in handleUserMessage) uses the
1091
- // separate-block path instead.
1092
- content: d.expandedContext ? d.content + d.expandedContext : d.content,
1093
- ...(d.clientMessageId ? { clientMessageId: d.clientMessageId } : {}),
1094
- ...(d.attachments && d.attachments.length > 0 ? { attachments: d.attachments } : {}),
1095
- }));
1166
+ return drained.map((d) => {
1167
+ const pending = clusterToolsPending(wf, clusterStore.getClusterIdForWorkflow(workflowId));
1168
+ const raw = d.expandedContext ? d.content + d.expandedContext : d.content;
1169
+ const item = {
1170
+ deliveryId,
1171
+ // §D1 — mid-turn steer is delivered as a single `content` string through
1172
+ // the provider steer APIs (SteerItem has no separate context block), so a
1173
+ // steer message's expanded `@`-refs ride appended to its content. The echo
1174
+ // already went out compact at enqueue; this only affects what the model
1175
+ // sees mid-turn. Post-turn drain (the loop in handleUserMessage) uses the
1176
+ // separate-block path instead.
1177
+ content: pending ? (d.clusterBusyReminder ? CLUSTER_TOOLS_PENDING_AGENT : `${CLUSTER_TOOLS_PENDING_AGENT}\n\n${raw}`) : raw,
1178
+ ...(d.clientMessageId ? { clientMessageId: d.clientMessageId } : {}),
1179
+ ...(d.attachments && d.attachments.length > 0 ? { attachments: d.attachments } : {}),
1180
+ };
1181
+ originalSteerItems.set(item, d);
1182
+ return item;
1183
+ });
1096
1184
  }
1097
1185
  // Phase 6b — re-enqueue support for the Codex app-server worker. The worker
1098
1186
  // drains via `drainSteerForWorker` (destructive splice) and dispatches
@@ -1113,7 +1201,7 @@ export function requeueSteerForWorker(workflowId, ws, items, bucket) {
1113
1201
  return;
1114
1202
  const arr = bucket === 'steer' ? wf.queue.steering : wf.queue.followUp;
1115
1203
  for (const item of items) {
1116
- arr.push({
1204
+ arr.push(originalSteerItems.get(item) ?? {
1117
1205
  content: item.content,
1118
1206
  ...(item.clientMessageId ? { clientMessageId: item.clientMessageId } : {}),
1119
1207
  ...(item.attachments && item.attachments.length > 0 ? { attachments: item.attachments } : {}),
@@ -1188,6 +1276,8 @@ export async function persistInitialMeta(cwd, workflowId, config, primary, opts)
1188
1276
  ...(typeof config.claudeNativeForceInterleavedThinkingBeta === 'boolean'
1189
1277
  ? { claudeNativeForceInterleavedThinkingBeta: config.claudeNativeForceInterleavedThinkingBeta }
1190
1278
  : {}),
1279
+ nativeSubagents: config.nativeSubagents,
1280
+ claudeNativeTaskDisabled: config.claudeNativeTaskDisabled,
1191
1281
  ...(config.claudeNativeThinkingDisplay === 'omitted' || config.claudeNativeThinkingDisplay === 'summarized' || config.claudeNativeThinkingDisplay === 'updates'
1192
1282
  ? { claudeNativeThinkingDisplay: config.claudeNativeThinkingDisplay }
1193
1283
  : {}),
@@ -1220,12 +1310,10 @@ export async function persistInitialMeta(cwd, workflowId, config, primary, opts)
1220
1310
  ...(config.reviewSafeMode === 'on' || config.reviewSafeMode === 'off'
1221
1311
  ? { reviewSafeMode: config.reviewSafeMode }
1222
1312
  : {}),
1223
- ...((config.outputStyle === 'lite' || config.outputStyle === 'terse')
1224
- ? { outputStyle: config.outputStyle }
1225
- // Legacy `caveman` from a stale client → write `terse` to disk.
1226
- : config.outputStyle === 'caveman'
1227
- ? { outputStyle: 'terse' }
1228
- : {}),
1313
+ // Only a style other than the default is written; unset means
1314
+ // DEFAULT_OUTPUT_STYLE. Legacy `lite` / `caveman` from a stale client are
1315
+ // written as `plain` / `terse` (plain being the default, it stays unset).
1316
+ ...(storedOutputStyle(config.outputStyle) ? { outputStyle: storedOutputStyle(config.outputStyle) } : {}),
1229
1317
  // docs/GOTCHAS.md - persist a north-star seeded before the first turn
1230
1318
  // (e.g. a Spawn-from-here that inherited the parent's) so it survives a
1231
1319
  // restart even if the operator never re-sets it. Blank ⇒ omitted.
@@ -1249,6 +1337,16 @@ export async function writeCalibrationToMeta(cwd, workflowId, ratio, overhead, l
1249
1337
  meta.calibration = { ratio, overhead, lastGroundTruth };
1250
1338
  });
1251
1339
  }
1340
+ // Automatic busy reminders use the same steering queue as a manual nudge.
1341
+ // Losing the busy turn during async preparation drops the reminder instead
1342
+ // of creating a new turn or steering a newer generation.
1343
+ export async function enqueueBusyReminder(workflowId, content, allow) {
1344
+ let accepted = false;
1345
+ const ws = { readyState: WebSocket.CLOSED, send: () => undefined };
1346
+ const session = { id: 'busy-reminder', workflowIds: new Set([workflowId]), clusterIds: new Set(), clusterObserved: new Map() };
1347
+ await handleUserMessage(ws, session, workflowId, content, undefined, undefined, true, 'steer', undefined, undefined, { automaticKind: 'auto-pickup', clusterBusyReminder: true, busyOnly: true, busyOnlyGuard: allow, onBusyQueued: () => { accepted = true; } });
1348
+ return accepted;
1349
+ }
1252
1350
  export async function handleUserMessage(ws, session, workflowId, content, clientMessageId, attachments, interjection, kind, primitive, pickedSkills,
1253
1351
  // drainQueueIfIdle only: take the prompt from wf.queue at claim time
1254
1352
  // instead of `content` (items were echoed + expanded at enqueue).
@@ -1259,1562 +1357,1617 @@ opts) {
1259
1357
  send(ws, { type: 'error', message: `Unknown workflow ${workflowId.slice(0, 8)}` });
1260
1358
  return;
1261
1359
  }
1262
- const interruptEpoch = busyRevocations.get(wf) ?? 0;
1263
- const cwd = wf.config.workingDirectory;
1264
- if (!cwd) {
1265
- send(ws, { type: 'error', message: 'Workflow has no working directory configured.' });
1266
- return;
1267
- }
1268
- const memberClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
1269
- const chatMode = isChatWorkflow(wf.config);
1270
- const incognito = chatMode && wf.config.incognito === true;
1271
- const trackOllama = wf.primary.provider === 'ollama' && !chatMode;
1272
- if (trackOllama && !clientMessageId)
1273
- clientMessageId = randomUUID();
1274
- // Chat tabs expose no project tools; web_search/web_fetch is the one
1275
- // exception the operator can arm (default on for a saved Chat). Computed per
1276
- // turn so the header toggle takes effect on the next message, and passed
1277
- // down so each provider arms its own web surface.
1278
- const chatWeb = chatMode && chatWebArmed(wf.config, wf.primary.provider);
1279
- const clusterAccessMode = memberClusterId
1280
- ? clusterStore.getMemberAccessMode(memberClusterId, workflowId)
1281
- : 'standard';
1282
- const isolatedMember = clusterAccessMode === 'isolated';
1283
- const projectContextEnabled = !chatMode && !isolatedMember;
1284
- if (chatMode && !CHAT_PROVIDERS.has(wf.primary.provider)) {
1285
- send(ws, { type: 'error', workflowId, message: `${wf.primary.provider} is not available in Chat mode.` });
1286
- return;
1287
- }
1288
- const configuredTrustSource = wf.config.managedWorktreeSourceCwd;
1289
- const managedTrustSource = configuredTrustSource
1290
- && await isManagedBakeoffWorktree(configuredTrustSource, cwd).catch(() => false)
1291
- ? configuredTrustSource
1292
- : undefined;
1293
- if (isolatedMember && (wf.primary.provider !== 'claude' || wf.config.claudeTransport !== 'native')) {
1294
- send(ws, {
1295
- type: 'error',
1296
- message: 'isolated cluster members require the Claude Native transport',
1297
- });
1360
+ if (storageMigrations.has(wf)) {
1361
+ send(ws, { type: 'error', message: 'Message not sent: workflow storage is moving. Wait for the scaffold to finish, then resend.' });
1298
1362
  return;
1299
1363
  }
1300
- // DD10 — parameterized `/prompt` command expansion. Runs FIRST (before
1301
- // context-refs + before any echo/record) so events.jsonl carries the expanded
1302
- // turn, and so `@`-refs inside an expanded template still expand below. A
1303
- // project-scope template is gated behind DD7 trust (key on the raw decision —
1304
- // a cloned repo's `.arco/prompts/*.md` is an injection vector). No matching
1305
- // template ⇒ the text passes through untouched as a normal turn.
1306
- if (projectContextEnabled && !fromQueue) {
1307
- const invocation = parsePromptInvocation(content);
1308
- if (invocation) {
1309
- const trustStatus = await projectTrust.resolveTrustStatus(managedTrustSource ?? cwd).catch(() => 'ask');
1310
- const includeProject = trustStatus === 'always';
1311
- const expanded = await expandPromptCommand(invocation.name, invocation.argsRaw, cwd, { includeProject }).catch((err) => {
1312
- console.error(`[arco] [${workflowId.slice(0, 8)}] prompt-command expansion failed:`, err);
1313
- return null;
1364
+ incomingMessages.set(wf, (incomingMessages.get(wf) ?? 0) + 1);
1365
+ try {
1366
+ const busyOnlyClaim = lastBusyClaim.get(wf);
1367
+ if (opts?.busyOnly && !wf.busy)
1368
+ return;
1369
+ const interruptEpoch = busyRevocations.get(wf) ?? 0;
1370
+ const cwd = wf.config.workingDirectory;
1371
+ if (!cwd) {
1372
+ send(ws, { type: 'error', message: 'Workflow has no working directory configured.' });
1373
+ return;
1374
+ }
1375
+ const memberClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
1376
+ const chatMode = isChatWorkflow(wf.config);
1377
+ const incognito = chatMode && wf.config.incognito === true;
1378
+ const trackOllama = wf.primary.provider === 'ollama' && !chatMode;
1379
+ if (!clientMessageId)
1380
+ clientMessageId = randomUUID();
1381
+ // Chat tabs expose no project tools; web_search/web_fetch is the one
1382
+ // exception the operator can arm (default on for a saved Chat). Computed per
1383
+ // turn so the header toggle takes effect on the next message, and passed
1384
+ // down so each provider arms its own web surface.
1385
+ const chatWeb = chatMode && chatWebArmed(wf.config, wf.primary.provider);
1386
+ const clusterAccessMode = memberClusterId
1387
+ ? clusterStore.getMemberAccessMode(memberClusterId, workflowId)
1388
+ : 'standard';
1389
+ const isolatedMember = clusterAccessMode === 'isolated';
1390
+ const projectContextEnabled = !chatMode && !isolatedMember;
1391
+ if (chatMode && !CHAT_PROVIDERS.has(wf.primary.provider)) {
1392
+ send(ws, { type: 'error', workflowId, message: `${wf.primary.provider} is not available in Chat mode.` });
1393
+ return;
1394
+ }
1395
+ const configuredTrustSource = wf.config.managedWorktreeSourceCwd;
1396
+ const managedTrustSource = configuredTrustSource
1397
+ && await isManagedBakeoffWorktree(configuredTrustSource, cwd).catch(() => false)
1398
+ ? configuredTrustSource
1399
+ : undefined;
1400
+ if (isolatedMember && (wf.primary.provider !== 'claude' || wf.config.claudeTransport !== 'native')) {
1401
+ send(ws, {
1402
+ type: 'error',
1403
+ message: 'isolated cluster members require the Claude Native transport',
1314
1404
  });
1315
- if (expanded) {
1316
- content = expanded.expanded;
1317
- broadcastWorkflow(workflowId, {
1318
- type: 'system_notice',
1319
- workflowId,
1320
- content: `[PROMPT] Expanded /${invocation.name} (${expanded.scope}) into this turn.`,
1321
- });
1405
+ return;
1406
+ }
1407
+ // Explicit built-in slash commands are resolved before queueing, so queued
1408
+ // turns retain the same pick. A trusted project or global copy takes priority.
1409
+ if (projectContextEnabled && !fromQueue) {
1410
+ const invocation = /^\/(grill-me|grill-with-docs|wait-what|retro|improve-codebase-architecture)(?:\s|$)/i.exec(content);
1411
+ if (invocation) {
1412
+ const requested = invocation[1].toLowerCase();
1413
+ const slug = requested === 'improve-codebase-architecture' ? 'architecture-review' : requested;
1414
+ const include = await projectTrust.resolveTrustStatus(managedTrustSource ?? cwd).catch(() => 'ask') === 'always';
1415
+ const catalog = await listSkills(cwd, { includeProject: include });
1416
+ const own = [...catalog.project, ...catalog.global].find((s) => s.slug.toLowerCase() === requested || s.name.toLowerCase() === requested);
1417
+ const builtin = catalog.builtin.find((s) => s.slug === slug);
1418
+ if (own?.off || (!own && builtin?.off)) {
1419
+ send(ws, { type: 'error', workflowId, message: `/${requested} is turned off.` });
1420
+ return;
1421
+ }
1422
+ if (own)
1423
+ pickedSkills = [...(pickedSkills ?? []), { scope: own.scope, slug: own.slug }];
1424
+ else if (builtin && !builtin.replaced)
1425
+ pickedSkills = [...(pickedSkills ?? []), { scope: 'builtin', slug }];
1322
1426
  }
1323
- else if (!includeProject && await projectPromptExists(invocation.name, cwd).catch(() => false)) {
1324
- // A project template EXISTS but the repo isn't trusted — explain the
1325
- // suppression rather than silently sending the literal `/name`.
1326
- broadcastWorkflow(workflowId, {
1327
- type: 'system_notice',
1328
- workflowId,
1329
- content: `[PROMPT] /${invocation.name} is a project template but this repo isn't trusted (${trustStatus}) — it was NOT expanded. Trust the repo to enable it.`,
1427
+ }
1428
+ // DD10 — parameterized `/prompt` command expansion. Runs FIRST (before
1429
+ // context-refs + before any echo/record) so events.jsonl carries the expanded
1430
+ // turn, and so `@`-refs inside an expanded template still expand below. A
1431
+ // project-scope template is gated behind DD7 trust (key on the raw decision —
1432
+ // a cloned repo's `.arco/prompts/*.md` is an injection vector). No matching
1433
+ // template ⇒ the text passes through untouched as a normal turn.
1434
+ if (projectContextEnabled && !fromQueue) {
1435
+ const invocation = parsePromptInvocation(content);
1436
+ if (invocation) {
1437
+ const trustStatus = await projectTrust.resolveTrustStatus(managedTrustSource ?? cwd).catch(() => 'ask');
1438
+ const includeProject = trustStatus === 'always';
1439
+ const expanded = await expandPromptCommand(invocation.name, invocation.argsRaw, cwd, { includeProject }).catch((err) => {
1440
+ console.error(`[arco] [${workflowId.slice(0, 8)}] prompt-command expansion failed:`, err);
1441
+ return null;
1330
1442
  });
1443
+ if (expanded) {
1444
+ content = expanded.expanded;
1445
+ broadcastWorkflow(workflowId, {
1446
+ type: 'system_notice',
1447
+ workflowId,
1448
+ content: `[PROMPT] Expanded /${invocation.name} (${expanded.scope}) into this turn.`,
1449
+ });
1450
+ }
1451
+ else if (!includeProject && await projectPromptExists(invocation.name, cwd).catch(() => false)) {
1452
+ // A project template EXISTS but the repo isn't trusted — explain the
1453
+ // suppression rather than silently sending the literal `/name`.
1454
+ broadcastWorkflow(workflowId, {
1455
+ type: 'system_notice',
1456
+ workflowId,
1457
+ content: `[PROMPT] /${invocation.name} is a project template but this repo isn't trusted (${trustStatus}) — it was NOT expanded. Trust the repo to enable it.`,
1458
+ });
1459
+ }
1331
1460
  }
1332
1461
  }
1333
- }
1334
- // docs/ARCHITECTURE.md - context-refs expansion. Expand `@`-refs
1335
- // (`@file:`, `@diff`, `@staged`, `@git:N`; `@url:` deferred) ONCE here, before
1336
- // the busy/queue split, so queued AND immediate sends both carry the result.
1337
- // The operator's chat echo stays compact (raw `content`); the expanded block
1338
- // is appended to the MODEL prompt only (below for immediate; on the QueueItem
1339
- // for queued). A system_notice summarizes the expansion so it's visible +
1340
- // reviewable in events.jsonl (the four-question test). Never throws — the
1341
- // expander converts every failure to a notice.
1342
- const contextExpansion = !projectContextEnabled || fromQueue
1343
- ? { block: '', notices: [], expandedCount: 0 }
1344
- : await expandContextRefs(cwd, content, { windowSize: lookupCtx(wf.primary.model) }).catch((err) => {
1345
- console.error(`[arco] [${workflowId.slice(0, 8)}] context-ref expansion failed:`, err);
1346
- return { block: '', notices: [], expandedCount: 0 };
1347
- });
1348
- if (contextExpansion.notices.length > 0) {
1349
- send(ws, {
1350
- type: 'system_notice',
1351
- workflowId,
1352
- content: `[CONTEXT REFS] expanded ${contextExpansion.expandedCount} ref` +
1353
- `${contextExpansion.expandedCount === 1 ? '' : 's'} into this turn's context:\n` +
1354
- contextExpansion.notices.map((n) => ` • ${n}`).join('\n'),
1355
- });
1356
- }
1357
- let expandedContext = contextExpansion.block || undefined;
1358
- // STOP/removal during async ref/trust preparation cancels this explicit
1359
- // redirect too. A naturally completed turn still accepts it normally.
1360
- if (kind === 'interrupt' && (workflows.get(workflowId) !== wf || (busyRevocations.get(wf) ?? 0) !== interruptEpoch)) {
1361
- if (clientMessageId)
1362
- send(ws, { type: 'queued_message_cancelled', workflowId, clientMessageId });
1363
- return;
1364
- }
1365
- // Busy sends are echoed once and queued. Interrupt is a priority turn after
1366
- // provider teardown; it must keep this loop's busy claim and older queue.
1367
- //
1368
- // Phase 4 — `kind` selects steering vs follow-up bucket. Default 'follow-up'
1369
- // for back-compat with pre-Phase-4 clients (they sent `interjection: true`
1370
- // with no kind, which matched today's silent post-turn flush; follow-up is
1371
- // the closest fit). Phase 4 ships visible/rebindable; both kinds still
1372
- // drain post-turn — Phases 5–7 turn on real mid-turn delivery for steer
1373
- // per provider.
1374
- if (opts?.claimGuard && (wf.busy || wf.computerResetting))
1375
- return;
1376
- if (wf.busy || wf.computerResetting) {
1377
- if (primitive === 'plan-review') {
1378
- send(ws, { type: 'system_notice', workflowId, content: '[PLAN DRAFT NOT STARTED] Wait for the current turn to finish, then try again.' });
1379
- return;
1462
+ // docs/ARCHITECTURE.md - context-refs expansion. Expand `@`-refs
1463
+ // (`@file:`, `@diff`, `@staged`, `@git:N`; `@url:` deferred) ONCE here, before
1464
+ // the busy/queue split, so queued AND immediate sends both carry the result.
1465
+ // The operator's chat echo stays compact (raw `content`); the expanded block
1466
+ // is appended to the MODEL prompt only (below for immediate; on the QueueItem
1467
+ // for queued). A system_notice summarizes the expansion so it's visible +
1468
+ // reviewable in events.jsonl (the four-question test). Never throws — the
1469
+ // expander converts every failure to a notice.
1470
+ const contextExpansion = !projectContextEnabled || fromQueue
1471
+ ? { block: '', notices: [], expandedCount: 0 }
1472
+ : await expandContextRefs(cwd, content, { windowSize: lookupCtx(wf.primary.model) }).catch((err) => {
1473
+ console.error(`[arco] [${workflowId.slice(0, 8)}] context-ref expansion failed:`, err);
1474
+ return { block: '', notices: [], expandedCount: 0 };
1475
+ });
1476
+ if (contextExpansion.notices.length > 0) {
1477
+ send(ws, {
1478
+ type: 'system_notice',
1479
+ workflowId,
1480
+ content: `[CONTEXT REFS] expanded ${contextExpansion.expandedCount} ref` +
1481
+ `${contextExpansion.expandedCount === 1 ? '' : 's'} into this turn's context:\n` +
1482
+ contextExpansion.notices.map((n) => ` • ${n}`).join('\n'),
1483
+ });
1484
+ }
1485
+ let expandedContext = contextExpansion.block || undefined;
1486
+ const contextAttachments = contextExpansion.attachments ?? [];
1487
+ const editPickedSkills = Array.isArray(pickedSkills)
1488
+ ? pickedSkills.filter(p => p && ['project', 'global', 'builtin'].includes(p.scope) && typeof p.slug === 'string' && p.slug.length > 0)
1489
+ .filter((p, index, all) => all.findIndex(other => other.scope === p.scope && other.slug === p.slug) === index)
1490
+ .map(({ scope, slug }) => ({ scope, slug })) : undefined;
1491
+ pickedSkills = editPickedSkills;
1492
+ // A synchronous provider drain cannot load one-shot skills. Resolve them
1493
+ // before admitting a busy send; both drain paths then carry the same block.
1494
+ if (wf.busy && pickedSkills?.length) {
1495
+ const selectedBlock = await resolvePickedSkillsBlock(pickedSkills);
1496
+ if (selectedBlock)
1497
+ expandedContext = `${expandedContext ?? ''}\n\n${selectedBlock}`;
1498
+ pickedSkills = undefined;
1380
1499
  }
1381
- // A drain lost the race to another holder; that holder's loop (or its own
1382
- // drainQueueIfIdle) flushes the queue — nothing to enqueue here.
1383
- if (fromQueue)
1500
+ // STOP/removal during async ref/trust preparation revokes every pending
1501
+ // send, before it can claim a fresh busy token or enter either queue.
1502
+ if (workflows.get(workflowId) !== wf || (busyRevocations.get(wf) ?? 0) !== interruptEpoch) {
1503
+ if (clientMessageId)
1504
+ send(ws, { type: 'queued_message_cancelled', workflowId, clientMessageId });
1384
1505
  return;
1385
- if (!interjection) {
1386
- // Non-interjection arriving while busy is a client bug (didn't tag it),
1387
- // but we still queue rather than error — drops fewer operator messages.
1388
- console.warn(`[arco] [${workflowId.slice(0, 8)}] user_message while busy without interjection flag — queuing anyway`);
1389
1506
  }
1390
- const interrupt = kind === 'interrupt' && !wf.config.voiceOperator
1391
- && (wf.primary.provider === 'claude' || wf.primary.provider === 'codex')
1392
- && wf.primaryTurn !== undefined && ownsBusy(wf, wf.primaryTurn.token);
1393
- const bucket = interrupt ? 'steer'
1394
- : isComputerBackgroundClaim(workflowId) || kind === 'interrupt' ? 'follow-up' : kind ?? 'follow-up';
1395
- if (kind === 'interrupt' && !interrupt)
1396
- broadcastWorkflow(workflowId, {
1397
- type: 'system_notice', workflowId,
1398
- content: '[INTERRUPT & SEND] No interruptible Claude or Codex primary turn is running. Your message is queued as a follow-up.',
1507
+ // Busy sends are echoed once and queued. Interrupt is a priority turn after
1508
+ // provider teardown; it must keep this loop's busy claim and older queue.
1509
+ //
1510
+ // Phase 4 — `kind` selects steering vs follow-up bucket. Default 'follow-up'
1511
+ // for back-compat with pre-Phase-4 clients (they sent `interjection: true`
1512
+ // with no kind, which matched today's silent post-turn flush; follow-up is
1513
+ // the closest fit). Phase 4 ships visible/rebindable; both kinds still
1514
+ // drain post-turn — Phases 5–7 turn on real mid-turn delivery for steer
1515
+ // per provider.
1516
+ if (opts?.busyOnly && (!wf.busy || wf.computerResetting || lastBusyClaim.get(wf) !== busyOnlyClaim || (opts.busyOnlyGuard && !opts.busyOnlyGuard())))
1517
+ return;
1518
+ if (opts?.claimGuard && (wf.busy || wf.computerResetting))
1519
+ return;
1520
+ if (wf.busy || wf.computerResetting) {
1521
+ if (primitive === 'plan-review') {
1522
+ send(ws, { type: 'system_notice', workflowId, content: '[PLAN DRAFT NOT STARTED] Wait for the current turn to finish, then try again.' });
1523
+ return;
1524
+ }
1525
+ // A drain lost the race to another holder; that holder's loop (or its own
1526
+ // drainQueueIfIdle) flushes the queue — nothing to enqueue here.
1527
+ if (fromQueue)
1528
+ return;
1529
+ if (!interjection) {
1530
+ // Non-interjection arriving while busy is a client bug (didn't tag it),
1531
+ // but we still queue rather than error — drops fewer operator messages.
1532
+ console.warn(`[arco] [${workflowId.slice(0, 8)}] user_message while busy without interjection flag — queuing anyway`);
1533
+ }
1534
+ const toolsPending = clusterToolsPending(wf, clusterStore.getClusterIdForWorkflow(workflowId));
1535
+ if (opts?.clusterBusyReminder && toolsPending)
1536
+ return;
1537
+ if (toolsPending && !opts?.clusterBusyReminder && opts?.automaticKind !== 'auto-pickup' && !opts?.backgroundEvent)
1538
+ broadcastWorkflow(workflowId, {
1539
+ type: 'system_notice', workflowId, content: CLUSTER_TOOLS_PENDING_NOTICE,
1540
+ });
1541
+ const interrupt = kind === 'interrupt' && !wf.config.voiceOperator
1542
+ && (wf.primary.provider === 'claude' || wf.primary.provider === 'codex')
1543
+ && wf.primaryTurn !== undefined && ownsBusy(wf, wf.primaryTurn.token);
1544
+ const bucket = interrupt ? 'steer'
1545
+ : isComputerBackgroundClaim(workflowId) || kind === 'interrupt' ? 'follow-up' : kind ?? 'follow-up';
1546
+ if (kind === 'interrupt' && !interrupt)
1547
+ broadcastWorkflow(workflowId, {
1548
+ type: 'system_notice', workflowId,
1549
+ content: '[INTERRUPT & SEND] No interruptible Claude or Codex primary turn is running. Your message is queued as a follow-up.',
1550
+ });
1551
+ const arr = bucket === 'steer' ? wf.queue.steering : wf.queue.followUp;
1552
+ const queuedAttachments = [...new Set([...(attachments ?? []), ...contextAttachments])];
1553
+ const queuedItem = { clusterBusyReminder: opts?.clusterBusyReminder, automaticKind: opts?.automaticKind, content, attachments: isolatedMember || !queuedAttachments.length ? undefined : queuedAttachments, clientMessageId, expandedContext, pickedSkills, editPickedSkills, ollamaInputSeq: undefined, ...(interrupt ? { interrupt: true } : {}) };
1554
+ arr.push(queuedItem);
1555
+ opts?.onBusyQueued?.();
1556
+ send(ws, {
1557
+ type: 'user_message_echo',
1558
+ workflowId,
1559
+ ...(opts?.automaticKind ? { automaticKind: opts.automaticKind } : {}),
1560
+ content,
1561
+ attachments,
1562
+ clientMessageId,
1563
+ timestamp: Date.now(),
1564
+ kind: interrupt ? 'interrupt' : bucket,
1565
+ deliveryTracked: true,
1566
+ ...(trackOllama ? { ollamaReplayInput: true } : {}),
1399
1567
  });
1400
- const arr = bucket === 'steer' ? wf.queue.steering : wf.queue.followUp;
1401
- const queuedItem = { content, attachments: isolatedMember ? undefined : attachments, clientMessageId, expandedContext, pickedSkills, ollamaInputSeq: undefined, ...(interrupt ? { interrupt: true } : {}) };
1402
- arr.push(queuedItem);
1403
- send(ws, {
1404
- type: 'user_message_echo',
1405
- workflowId,
1406
- content,
1407
- attachments,
1408
- clientMessageId,
1409
- timestamp: Date.now(),
1410
- kind: interrupt ? 'interrupt' : bucket,
1411
- ...(trackOllama ? { ollamaReplayInput: true } : {}),
1412
- });
1413
- if (trackOllama)
1414
- queuedItem.ollamaInputSeq = currentWorkflowSeq(cwd, workflowId);
1415
- broadcastQueueUpdate(workflowId);
1416
- if (interrupt) {
1417
- disarmGoalRun(workflowId, wf, 'the operator interrupted with a new instruction');
1418
- broadcastWorkflow(workflowId, { type: 'system_notice', workflowId,
1419
- content: '[INTERRUPT & SEND] Interrupting the current turn. This message runs next; existing queued messages are preserved. Completed changes remain in place.' });
1420
- const active = wf.primaryTurn;
1421
- if (active?.workerId && !active.interruption) {
1422
- active.interruption = wf.manager.interrupt(active.workerId);
1423
- // Observe immediately: settlement below awaits the same promise.
1424
- void active.interruption.catch(() => { });
1568
+ if (trackOllama)
1569
+ queuedItem.ollamaInputSeq = currentWorkflowSeq(cwd, workflowId);
1570
+ broadcastQueueUpdate(workflowId);
1571
+ if (interrupt) {
1572
+ disarmGoalRun(workflowId, wf, 'the operator interrupted with a new instruction');
1573
+ broadcastWorkflow(workflowId, { type: 'system_notice', workflowId,
1574
+ content: '[INTERRUPT & SEND] Interrupting the current turn. This message runs next; existing queued messages are preserved. Completed changes remain in place.' });
1575
+ const active = wf.primaryTurn;
1576
+ if (active?.workerId && !active.interruption) {
1577
+ active.interruption = wf.manager.interrupt(active.workerId);
1578
+ // Observe immediately: settlement below awaits the same promise.
1579
+ void active.interruption.catch(() => { });
1580
+ }
1425
1581
  }
1426
- }
1427
- console.log(`[arco] [${workflowId.slice(0, 8)}] queued as ${bucket} (depth: steer=${wf.queue.steering.length}, follow-up=${wf.queue.followUp.length})`);
1428
- return;
1429
- }
1430
- // Refuse the turn if a native `claude --resume` terminal has written to
1431
- // this session JSONL recently. Two concurrent writers corrupt session
1432
- // state — the JSONL interleaves sdk-cli and cli entries, the model sees
1433
- // synthetic "Continue from where you left off" turns, and Arco's chat
1434
- // drifts from the CLI's internal state. The block clears itself
1435
- // FOREIGN_WRITE_BLOCK_MS after the last foreign write (i.e. ~60s after
1436
- // the operator closes the native terminal), without needing explicit
1437
- // state reset. A handoff remains the clean escape.
1438
- if (wf.lastForeignWriteAt && (Date.now() - wf.lastForeignWriteAt) < FOREIGN_WRITE_BLOCK_MS) {
1439
- // Queued items stay queued (already echoed); the operator resends later.
1440
- if (fromQueue)
1441
- return;
1442
- const secs = Math.ceil((FOREIGN_WRITE_BLOCK_MS - (Date.now() - wf.lastForeignWriteAt)) / 1000);
1443
- send(ws, {
1444
- type: 'system_notice',
1445
- workflowId,
1446
- content: `[TURN BLOCKED] A native \`claude --resume\` terminal is writing to this session. Close it (Arco will auto-clear the block ~${secs}s after its last write), or rotate via Handoff to continue in a clean session.`,
1447
- });
1448
- // Echo the operator's message so it isn't silently dropped; they can
1449
- // resend once the block clears.
1450
- send(ws, {
1451
- type: 'user_message_echo',
1452
- workflowId,
1453
- content,
1454
- attachments,
1455
- clientMessageId,
1456
- timestamp: Date.now(),
1457
- });
1458
- return;
1459
- }
1460
- // Cancel any in-flight calibration pty before starting the primary turn.
1461
- // Calibration is idle-only; the primary turn takes priority.
1462
- if (wf.cancelCalibration) {
1463
- wf.cancelCalibration();
1464
- wf.cancelCalibration = undefined;
1465
- }
1466
- // Drain path: splice the queue in the same synchronous span as the busy
1467
- // claim below, so nothing can slip in between the idle check and the take.
1468
- let initialInterrupt = false;
1469
- // Refuse before taking queued input: a restore admitted during preflight
1470
- // must leave the queue available for an explicit later attempt.
1471
- assertCheckoutAvailable(workflowWritePaths(wf));
1472
- let activeOllamaInputSeqs = [];
1473
- if (fromQueue) {
1474
- const drained = takeQueuedTurn(wf.queue);
1475
- if (drained.length === 0)
1582
+ console.log(`[arco] [${workflowId.slice(0, 8)}] queued as ${bucket} (depth: steer=${wf.queue.steering.length}, follow-up=${wf.queue.followUp.length})`);
1476
1583
  return;
1477
- if (!incognito)
1478
- console.log(`[arco] [${workflowId.slice(0, 8)}] idle drain: flushing ${drained.length} queued message(s) as a fresh turn`);
1479
- broadcastQueueUpdate(workflowId);
1480
- const drainedClientIds = drained
1481
- .map((d) => d.clientMessageId)
1482
- .filter((id) => typeof id === 'string' && id.length > 0);
1483
- if (drainedClientIds.length > 0) {
1484
- send(ws, { type: 'queued_messages_drained', workflowId, clientMessageIds: drainedClientIds, drainedAt: Date.now() });
1485
1584
  }
1486
- activeOllamaInputSeqs = drained.every(d => d.ollamaInputSeq) ? drained.map(d => d.ollamaInputSeq) : [];
1487
- content = drained.map((d) => d.content).join('\n\n');
1488
- const mergedAttachments = drained.flatMap((d) => d.attachments ?? []);
1489
- attachments = mergedAttachments.length > 0 ? mergedAttachments : undefined;
1490
- const mergedRefs = drained.map((d) => d.expandedContext ?? '').filter(Boolean).join('');
1491
- expandedContext = mergedRefs.length > 0 ? mergedRefs : undefined;
1492
- clientMessageId = undefined;
1493
- pickedSkills = drained.flatMap((d) => d.pickedSkills ?? []);
1494
- initialInterrupt = drained.some((d) => d.interrupt);
1495
- }
1496
- let busyToken;
1497
- if (primitive === 'plan-review')
1498
- disarmGoalRun(workflowId, wf, 'a plan review was requested');
1499
- if (opts?.claimGuard) {
1500
- let guardedToken;
1501
- await opts.claimGuard(() => {
1502
- // Async preflight may have lost to STOP, a real operator turn or removal.
1503
- // Conditional nudges must never fall into the ordinary follow-up queue.
1504
- if (workflows.get(workflowId) !== wf || wf.busy || wf.computerResetting || wf.queue.steering.length || wf.queue.followUp.length
1505
- || (wf.lastForeignWriteAt && Date.now() - wf.lastForeignWriteAt < FOREIGN_WRITE_BLOCK_MS))
1506
- return false;
1507
- guardedToken = claimBusy(wf);
1508
- return true;
1509
- });
1510
- if (guardedToken === undefined)
1585
+ // Refuse the turn if a native `claude --resume` terminal has written to
1586
+ // this session JSONL recently. Two concurrent writers corrupt session
1587
+ // state — the JSONL interleaves sdk-cli and cli entries, the model sees
1588
+ // synthetic "Continue from where you left off" turns, and Arco's chat
1589
+ // drifts from the CLI's internal state. The block clears itself
1590
+ // FOREIGN_WRITE_BLOCK_MS after the last foreign write (i.e. ~60s after
1591
+ // the operator closes the native terminal), without needing explicit
1592
+ // state reset. A handoff remains the clean escape.
1593
+ if (wf.lastForeignWriteAt && (Date.now() - wf.lastForeignWriteAt) < FOREIGN_WRITE_BLOCK_MS) {
1594
+ // Queued items stay queued (already echoed); the operator resends later.
1595
+ if (fromQueue)
1596
+ return;
1597
+ const secs = Math.ceil((FOREIGN_WRITE_BLOCK_MS - (Date.now() - wf.lastForeignWriteAt)) / 1000);
1598
+ send(ws, {
1599
+ type: 'system_notice',
1600
+ workflowId,
1601
+ content: `[TURN BLOCKED] A native \`claude --resume\` terminal is writing to this session. Close it (Arco will auto-clear the block ~${secs}s after its last write), or rotate via Handoff to continue in a clean session.`,
1602
+ });
1603
+ // Echo the operator's message so it isn't silently dropped; they can
1604
+ // resend once the block clears.
1605
+ send(ws, {
1606
+ type: 'user_message_echo',
1607
+ workflowId,
1608
+ ...(opts?.automaticKind ? { automaticKind: opts.automaticKind } : {}),
1609
+ content,
1610
+ attachments,
1611
+ clientMessageId,
1612
+ timestamp: Date.now(),
1613
+ });
1511
1614
  return;
1512
- busyToken = guardedToken;
1513
- }
1514
- else
1515
- busyToken = claimBusy(wf);
1516
- const primaryTurn = { token: busyToken, holdSteer: initialInterrupt };
1517
- wf.primaryTurn = primaryTurn;
1518
- // Drive the turn loop. On first iteration `prompt` is the incoming content;
1519
- // on subsequent iterations it's the drained interjection queue (joined so
1520
- // multiple queued messages land in a single follow-up turn). This keeps
1521
- // the CLI session alive and matches Claude Code terminal's flush-on-idle.
1522
- if (opts?.backgroundEvent)
1523
- setComputerBackgroundClaim(workflowId, busyToken);
1524
- let prompt = content;
1525
- let promptPickedSkills = pickedSkills;
1526
- let promptAttachments = isolatedMember ? undefined : attachments;
1527
- let promptClientMessageId = clientMessageId;
1528
- // §D1 — expanded `@`-context-refs for the current iteration's prompt. First
1529
- // iteration uses the immediate-send expansion; drain iterations rebuild it
1530
- // from the drained QueueItems' stored blocks. Appended to the model prompt
1531
- // (after the plan prefix) but never to the echo.
1532
- let promptExpandedContext = expandedContext;
1533
- // First iteration echoes the original message via the standard path; later
1534
- // iterations generate their own clientMessageId so the dedup on the
1535
- // originating tab doesn't accidentally swallow an auto-flushed prompt
1536
- // whose UUID was already rendered client-side.
1537
- let firstIteration = true;
1538
- // docs/GOTCHAS.md - outcome of the LAST settled turn in this drain loop.
1539
- // An armed goal run stops on an errored turn rather than looping on the same
1540
- // failure; the flag has to outlive the loop body to reach `maybeGoalRun`.
1541
- let lastTurnErrored = false;
1542
- let policyReading;
1543
- let staleLoop = false;
1544
- let watchLoopFinished = false;
1545
- let watchHadError = false;
1546
- let preserveQueue = false;
1547
- const loadQueuedPrompt = (append = false) => {
1548
- const drained = takeQueuedTurn(wf.queue);
1549
- broadcastQueueUpdate(workflowId);
1550
- const ids = drained.flatMap((d) => d.clientMessageId ? [d.clientMessageId] : []);
1551
- if (ids.length)
1552
- send(ws, { type: 'queued_messages_drained', workflowId,
1553
- clientMessageIds: ids, drainedAt: Date.now() });
1554
- activeOllamaInputSeqs = drained.every(d => d.ollamaInputSeq) ? [...(append ? activeOllamaInputSeqs : []), ...drained.map(d => d.ollamaInputSeq)] : [];
1555
- prompt = [...(append ? [prompt] : []), ...drained.map((d) => d.content)].join('\n\n');
1556
- const files = [...(append ? promptAttachments ?? [] : []), ...drained.flatMap((d) => d.attachments ?? [])];
1557
- promptAttachments = files.length ? files : undefined;
1558
- const refs = (append ? promptExpandedContext ?? '' : '') + drained.map((d) => d.expandedContext ?? '').join('');
1559
- promptExpandedContext = refs || undefined;
1560
- promptClientMessageId = undefined;
1561
- promptPickedSkills = [...(append ? promptPickedSkills ?? [] : []), ...drained.flatMap((d) => d.pickedSkills ?? [])];
1562
- primaryTurn.holdSteer = drained.some((d) => d.interrupt);
1563
- };
1564
- // DD7 — project-trust gate. Resolve ONCE per turn (stable across drain
1565
- // iterations) from USER/GLOBAL scope only — trust.json + the global
1566
- // settings.json's defaultProjectTrust — BEFORE any project-local surface is
1567
- // read below. When the repo is untrusted, `includeProject` suppresses its
1568
- // CLAUDE.md, project skills, and project settings.json from the model turn
1569
- // (the cloned-repo prompt-injection vector). The turn STILL PROCEEDS; an
1570
- // 'ask' repo additionally raises a one-time operator prompt (deduped per cwd,
1571
- // so cluster peers sharing the cwd prompt once). Decision + suppressed list
1572
- // land in events.jsonl for the four-question test's visibility leg.
1573
- const trustGate = !projectContextEnabled
1574
- ? { includeProject: false, needsPrompt: false, status: 'never', resources: [] }
1575
- : await (managedTrustSource
1576
- ? projectTrust.gateManagedWorktreeResources(cwd, managedTrustSource)
1577
- : projectTrust.gateProjectResources(cwd)).catch((err) => {
1578
- // Fail SAFE: on any gate error, suppress project resources rather than
1579
- // leaking an unvetted repo's instructions into the turn.
1580
- console.error(`[arco] [${workflowId.slice(0, 8)}] project-trust gate failed; suppressing project resources:`, err);
1581
- return { includeProject: false, needsPrompt: false, status: 'ask', resources: [] };
1582
- });
1583
- const includeProject = trustGate.includeProject;
1584
- const trustDecisionCwd = managedTrustSource ?? cwd;
1585
- // Log the suppression for the four-question test's visibility leg — but stay
1586
- // quiet for an explicit 'never' (the operator deliberately chose to suppress;
1587
- // a per-turn notice would just nag). 'ask' / fail-safe always log.
1588
- if (!includeProject && trustGate.resources.length > 0 && trustGate.status !== 'never') {
1589
- broadcastWorkflow(workflowId, {
1590
- type: 'system_notice',
1591
- workflowId,
1592
- content: `[PROJECT TRUST] This repo is not trusted (${trustGate.status}); suppressed from this turn: ` +
1593
- `${trustGate.resources.join(', ')}. Trust it to fold these in (next turn).`,
1594
- });
1595
- }
1596
- if (trustGate.needsPrompt && projectTrust.markPromptPending(trustDecisionCwd)) {
1597
- broadcastWorkflow(workflowId, {
1598
- type: 'project_trust_prompt',
1599
- workflowId,
1600
- cwd: trustDecisionCwd,
1601
- resources: trustGate.resources,
1602
- });
1603
- }
1604
- // DD8 — resolve picks for the prompt that owns them, including queued
1605
- // interrupt instructions. Picking is an explicit operator action, so it
1606
- // applies regardless
1607
- // of the DD7 trust gate above — picking IS the operator's vouch. A missing /
1608
- // unreadable skill is skipped with a notice rather than failing the turn.
1609
- async function resolvePickedSkillsBlock(picks) {
1610
- if (!projectContextEnabled || !picks?.length)
1611
- return '';
1612
- const resolved = [];
1613
- const missing = [];
1614
- for (const pick of picks) {
1615
- try {
1616
- const full = await readSkillBody(pick.scope, pick.slug, cwd);
1617
- if (full)
1618
- resolved.push({ name: full.name, scope: full.scope, body: full.body });
1619
- else
1620
- missing.push(`${pick.scope}:${pick.slug}`);
1621
- }
1622
- catch {
1623
- missing.push(`${pick.scope}:${pick.slug}`);
1615
+ }
1616
+ // Cancel any in-flight calibration pty before starting the primary turn.
1617
+ // Calibration is idle-only; the primary turn takes priority.
1618
+ if (wf.cancelCalibration) {
1619
+ wf.cancelCalibration();
1620
+ wf.cancelCalibration = undefined;
1621
+ }
1622
+ // Drain path: splice the queue in the same synchronous span as the busy
1623
+ // claim below, so nothing can slip in between the idle check and the take.
1624
+ let initialInterrupt = false;
1625
+ // Refuse before taking queued input: a restore admitted during preflight
1626
+ // must leave the queue available for an explicit later attempt.
1627
+ assertCheckoutAvailable(workflowWritePaths(wf));
1628
+ let activeOllamaInputSeqs = [];
1629
+ let activeInputClientIds = [];
1630
+ if (fromQueue) {
1631
+ const drained = takeQueuedTurn(wf.queue);
1632
+ if (drained.length === 0)
1633
+ return;
1634
+ if (!incognito)
1635
+ console.log(`[arco] [${workflowId.slice(0, 8)}] idle drain: flushing ${drained.length} queued message(s) as a fresh turn`);
1636
+ broadcastQueueUpdate(workflowId);
1637
+ const drainedClientIds = drained
1638
+ .map((d) => d.clientMessageId)
1639
+ .filter((id) => typeof id === 'string' && id.length > 0);
1640
+ if (drainedClientIds.length > 0) {
1641
+ send(ws, { type: 'queued_messages_drained', workflowId, clientMessageIds: drainedClientIds, drainedAt: Date.now() });
1624
1642
  }
1643
+ activeInputClientIds = drained.flatMap(item => item.clientMessageId ? [item.clientMessageId] : []);
1644
+ activeOllamaInputSeqs = drained.every(d => d.ollamaInputSeq) ? drained.map(d => d.ollamaInputSeq) : [];
1645
+ content = drained.map((d) => d.content).join('\n\n');
1646
+ const mergedAttachments = drained.flatMap((d) => d.attachments ?? []);
1647
+ attachments = mergedAttachments.length > 0 ? mergedAttachments : undefined;
1648
+ const mergedRefs = drained.map((d) => d.expandedContext ?? '').filter(Boolean).join('');
1649
+ expandedContext = mergedRefs.length > 0 ? mergedRefs : undefined;
1650
+ clientMessageId = undefined;
1651
+ pickedSkills = drained.flatMap((d) => d.pickedSkills ?? []);
1652
+ initialInterrupt = drained.some((d) => d.interrupt);
1625
1653
  }
1626
- const built = buildPickedSkillsBlock(resolved);
1627
- const names = resolved.map((s) => s.name).join(', ');
1628
- broadcastWorkflow(workflowId, {
1629
- type: 'system_notice',
1630
- workflowId,
1631
- content: `[SKILLS] Inlined ${resolved.length} operator-picked skill${resolved.length === 1 ? '' : 's'} ` +
1632
- `(${built.bytes} bytes) into this turn${names ? `: ${names}` : ''}.` +
1633
- (missing.length > 0 ? ` Skipped (not found): ${missing.join(', ')}.` : ''),
1634
- });
1635
- return built.text;
1636
- }
1637
- // Standing SKILLS pins are re-resolved once per primary-turn invocation.
1638
- // This keeps edits live, survives Native compaction / Handoff / restart, and
1639
- // avoids silently snapshotting stale bodies into meta.json. Like a one-shot
1640
- // pick, a project pin is an explicit operator vouch and bypasses discovery's
1641
- // project-trust suppression. Missing files fail safe and stay visible.
1642
- let pinnedSkillsBlock = '';
1643
- if (projectContextEnabled && wf.config.pinnedSkills?.length) {
1644
- const resolved = await resolvePinnedSkills(wf.config.pinnedSkills, cwd);
1645
- const built = buildPinnedSkillsBlock(resolved.skills);
1646
- pinnedSkillsBlock = built.text;
1647
- const skipped = [...resolved.missing, ...resolved.truncated];
1648
- if (skipped.length > 0) {
1654
+ let busyToken;
1655
+ if (primitive === 'plan-review')
1656
+ disarmGoalRun(workflowId, wf, 'a plan review was requested');
1657
+ if (opts?.claimGuard) {
1658
+ let guardedToken;
1659
+ await opts.claimGuard(() => {
1660
+ // Async preflight may have lost to STOP, a real operator turn or removal.
1661
+ // Conditional nudges must never fall into the ordinary follow-up queue.
1662
+ if (workflows.get(workflowId) !== wf || (busyRevocations.get(wf) ?? 0) !== interruptEpoch || wf.busy || wf.computerResetting || wf.queue.steering.length || wf.queue.followUp.length
1663
+ || (wf.lastForeignWriteAt && Date.now() - wf.lastForeignWriteAt < FOREIGN_WRITE_BLOCK_MS))
1664
+ return false;
1665
+ guardedToken = claimBusy(wf);
1666
+ return true;
1667
+ });
1668
+ if (guardedToken === undefined)
1669
+ return;
1670
+ busyToken = guardedToken;
1671
+ }
1672
+ else
1673
+ busyToken = claimBusy(wf);
1674
+ const primaryTurn = { token: busyToken, holdSteer: initialInterrupt };
1675
+ wf.primaryTurn = primaryTurn;
1676
+ // Drive the turn loop. On first iteration `prompt` is the incoming content;
1677
+ // on subsequent iterations it's the drained interjection queue (joined so
1678
+ // multiple queued messages land in a single follow-up turn). This keeps
1679
+ // the CLI session alive and matches Claude Code terminal's flush-on-idle.
1680
+ if (opts?.backgroundEvent)
1681
+ setComputerBackgroundClaim(workflowId, busyToken);
1682
+ let prompt = content;
1683
+ let promptPickedSkills = pickedSkills;
1684
+ const initialAttachments = [...new Set([...(attachments ?? []), ...contextAttachments])];
1685
+ let promptAttachments = isolatedMember || !initialAttachments.length ? undefined : initialAttachments;
1686
+ let promptClientMessageId = clientMessageId;
1687
+ // §D1 — expanded `@`-context-refs for the current iteration's prompt. First
1688
+ // iteration uses the immediate-send expansion; drain iterations rebuild it
1689
+ // from the drained QueueItems' stored blocks. Appended to the model prompt
1690
+ // (after the plan prefix) but never to the echo.
1691
+ let promptExpandedContext = expandedContext;
1692
+ // First iteration echoes the original message via the standard path; later
1693
+ // iterations generate their own clientMessageId so the dedup on the
1694
+ // originating tab doesn't accidentally swallow an auto-flushed prompt
1695
+ // whose UUID was already rendered client-side.
1696
+ let firstIteration = true;
1697
+ // docs/GOTCHAS.md - outcome of the LAST settled turn in this drain loop.
1698
+ // An armed goal run stops on an errored turn rather than looping on the same
1699
+ // failure; the flag has to outlive the loop body to reach `maybeGoalRun`.
1700
+ let lastTurnErrored = false;
1701
+ let policyReading;
1702
+ let staleLoop = false;
1703
+ let watchLoopFinished = false;
1704
+ let watchHadError = false;
1705
+ let preserveQueue = false;
1706
+ const loadQueuedPrompt = (append = false) => {
1707
+ const drained = takeQueuedTurn(wf.queue);
1708
+ broadcastQueueUpdate(workflowId);
1709
+ const ids = drained.flatMap((d) => d.clientMessageId ? [d.clientMessageId] : []);
1710
+ if (ids.length)
1711
+ send(ws, { type: 'queued_messages_drained', workflowId,
1712
+ clientMessageIds: ids, drainedAt: Date.now() });
1713
+ activeInputClientIds = [...(append ? activeInputClientIds : []), ...drained.flatMap(item => item.clientMessageId ? [item.clientMessageId] : [])];
1714
+ activeOllamaInputSeqs = drained.every(d => d.ollamaInputSeq) ? [...(append ? activeOllamaInputSeqs : []), ...drained.map(d => d.ollamaInputSeq)] : [];
1715
+ prompt = [...(append ? [prompt] : []), ...drained.map((d) => d.content)].join('\n\n');
1716
+ const files = [...(append ? promptAttachments ?? [] : []), ...drained.flatMap((d) => d.attachments ?? [])];
1717
+ promptAttachments = files.length ? files : undefined;
1718
+ const refs = (append ? promptExpandedContext ?? '' : '') + drained.map((d) => d.expandedContext ?? '').join('');
1719
+ promptExpandedContext = refs || undefined;
1720
+ promptClientMessageId = undefined;
1721
+ promptPickedSkills = [...(append ? promptPickedSkills ?? [] : []), ...drained.flatMap((d) => d.pickedSkills ?? [])];
1722
+ primaryTurn.holdSteer = drained.some((d) => d.interrupt);
1723
+ };
1724
+ // DD7 — project-trust gate. Resolve ONCE per turn (stable across drain
1725
+ // iterations) from USER/GLOBAL scope only — trust.json + the global
1726
+ // settings.json's defaultProjectTrust — BEFORE any project-local surface is
1727
+ // read below. When the repo is untrusted, `includeProject` suppresses its
1728
+ // CLAUDE.md, project skills, and project settings.json from the model turn
1729
+ // (the cloned-repo prompt-injection vector). The turn STILL PROCEEDS; an
1730
+ // 'ask' repo additionally raises a one-time operator prompt (deduped per cwd,
1731
+ // so cluster peers sharing the cwd prompt once). Decision + suppressed list
1732
+ // land in events.jsonl for the four-question test's visibility leg.
1733
+ const trustGate = !projectContextEnabled
1734
+ ? { includeProject: false, needsPrompt: false, status: 'never', resources: [] }
1735
+ : await (managedTrustSource
1736
+ ? projectTrust.gateManagedWorktreeResources(cwd, managedTrustSource)
1737
+ : projectTrust.gateProjectResources(cwd)).catch((err) => {
1738
+ // Fail SAFE: on any gate error, suppress project resources rather than
1739
+ // leaking an unvetted repo's instructions into the turn.
1740
+ console.error(`[arco] [${workflowId.slice(0, 8)}] project-trust gate failed; suppressing project resources:`, err);
1741
+ return { includeProject: false, needsPrompt: false, status: 'ask', resources: [] };
1742
+ });
1743
+ const includeProject = trustGate.includeProject;
1744
+ const trustDecisionCwd = managedTrustSource ?? cwd;
1745
+ // Log the suppression for the four-question test's visibility leg — but stay
1746
+ // quiet for an explicit 'never' (the operator deliberately chose to suppress;
1747
+ // a per-turn notice would just nag). 'ask' / fail-safe always log.
1748
+ if (!includeProject && trustGate.resources.length > 0 && trustGate.status !== 'never') {
1649
1749
  broadcastWorkflow(workflowId, {
1650
1750
  type: 'system_notice',
1651
1751
  workflowId,
1652
- content: `[PINNED SKILLS] ${resolved.skills.length} active (${built.bytes} bytes); skipped: ${skipped.join(', ')}.`,
1752
+ content: `[PROJECT TRUST] This repo is not trusted (${trustGate.status}); suppressed from this turn: ` +
1753
+ `${trustGate.resources.join(', ')}. Trust it to fold these in (next turn).`,
1653
1754
  });
1654
1755
  }
1655
- }
1656
- // Phase 6 — resolve the Codex transport once per primary-turn invocation.
1657
- // Reading the cascade up here means the value is stable across the
1658
- // drain-loop iterations below; an HMR-driven settings.json change between
1659
- // turns won't re-toggle the transport mid-loop, which would otherwise
1660
- // leak a long-lived `codex app-server` worker after switching back to
1661
- // exec mode. The dispatcher's exec-default fall-through covers other
1662
- // providers; reviewers/handoffs leave codexTransport unset.
1663
- // Phase 6e — per-tab override (`wf.config.codexTransport`) takes precedence
1664
- // over the cascade. The CONFIG-tab toggle writes to that field via
1665
- // update_primary_config so the operator's choice doesn't depend on a
1666
- // hand-edited settings.json.
1667
- const cascade = await readSettings(cwd, { includeProject }).catch(() => null);
1668
- const tabTransport = wf.config.codexTransport;
1669
- const codexTransport = tabTransport === 'appserver' || tabTransport === 'exec'
1670
- ? tabTransport
1671
- : cascade?.codex?.transport === 'appserver' ? 'appserver' : 'exec';
1672
- // Phase 7a — Claude transport, same precedence as Codex above.
1673
- const tabClaudeTransport = wf.config.claudeTransport;
1674
- // docs/PROVIDERS.md - sticky ultracode mode forces the CLI transport (the
1675
- // harness WorkflowTool lives only in the `claude` binary; Native's raw SDK
1676
- // can't host it). The operator's base transport is remembered separately in
1677
- // wf.config.ultracodeBaseTransport so turning ultracode OFF restores it.
1678
- const ultracode = wf.primary.provider === 'claude' && wf.config.ultracode === true;
1679
- const claudeTransport = ultracode
1680
- ? 'cli'
1681
- : tabClaudeTransport === 'native' || tabClaudeTransport === 'cli'
1682
- ? tabClaudeTransport
1683
- : cascade?.claude?.transport === 'native' ? 'native' : 'cli';
1684
- const providerAccount = wf.primary.provider === 'codex'
1685
- ? await resolveProviderAccount('codex', wf.config.providerAccountRef, cwd).catch(() => null)
1686
- : null;
1687
- if (providerAccount?.profile.id && wf.config.providerAccountRef !== providerAccount.profile.id) {
1688
- wf.config.providerAccountRef = providerAccount.profile.id;
1689
- }
1690
- // Anthropic server-side compaction (`compact_20260112`). Defaults OFF for
1691
- // Native tabs (NATIVE_COMPACTION_PLAN §1) — seeded into config at tab
1692
- // creation, so by here it's a concrete boolean; an absent value also reads
1693
- // as off. CLI Claude handles compaction inside the CLI process so the flag
1694
- // is moot there.
1695
- const claudeNativeCompact = claudeTransport === 'native'
1696
- ? wf.config.claudeNativeCompact === true
1697
- : false;
1698
- const claudeNativeForceInterleavedThinkingBeta = claudeTransport === 'native'
1699
- ? wf.config.claudeNativeForceInterleavedThinkingBeta === true
1700
- : false;
1701
- // Adaptive-thinking display for the Native worker. Absent ⇒ 'omitted'
1702
- // (Claude-Code parity — no thinking streamed back); 'summarized' streams
1703
- // summarized thinking into the Activity tab.
1704
- const claudeNativeThinkingDisplay = claudeTransport === 'native'
1705
- ? wf.config.claudeNativeThinkingDisplay
1706
- : undefined;
1707
- // docs/PROVIDERS.md - Native tool-result filter mode. Only honored
1708
- // on Native (the filter pipeline runs inside `claude-native/dispatchTool`;
1709
- // CLI/Codex don't surface raw tool stdout to us). Default off until measured
1710
- // per the §13.3 / §2.4 doc-discipline rule (no aggressive defaults).
1711
- const efficiencyToolFilter = claudeTransport === 'native'
1712
- ? (wf.config.efficiencyToolFilter ?? 'off')
1713
- : 'off';
1714
- // docs/PROVIDERS.md - fact-force first-edit gate mode. It is
1715
- // opt-in: new tabs and rehydrated tabs without the field stay 'off'. CLI
1716
- // parity is deferred (master §3.3 F4), so hard-zero non-Native transports.
1717
- const efficiencyFactForce = claudeTransport === 'native'
1718
- ? (wf.config.efficiencyFactForce ?? 'off')
1719
- : 'off';
1720
- // Config-protection write-gate. Default 'on' (safety gate); the operator
1721
- // opts out per-tab. Native-only (the gate lives in the Native worker), so
1722
- // we hard-zero non-Native transports to 'off' to avoid a meaningless flag.
1723
- const efficiencyConfigProtection = claudeTransport === 'native'
1724
- ? (wf.config.efficiencyConfigProtection ?? 'on')
1725
- : 'off';
1726
- const efficiencySandbox = claudeTransport === 'native' && !isolatedMember
1727
- ? (wf.config.efficiencySandbox ?? 'off')
1728
- : 'off';
1729
- // docs/PROVIDERS.md - operator-armed durable review gate. Native-only (the gate
1730
- // lives in the in-process worker's dispatchTool). Default 'off' so it stays
1731
- // operator-opted-in and inert until armed.
1732
- const reviewSafeMode = claudeTransport === 'native'
1733
- ? (wf.config.reviewSafeMode ?? 'off')
1734
- : 'off';
1735
- // docs/PROVIDERS.md - operator-armed terseness picker. Honored by
1736
- const outputStyleSupported = (wf.primary.provider === 'claude' && claudeTransport === 'native') ||
1737
- (wf.primary.provider === 'codex' && codexTransport === 'appserver');
1738
- const outputStyle = primitive === 'docs' || primitive === 'git'
1739
- ? 'normal'
1740
- : outputStyleSupported
1741
- ? (wf.config.outputStyle ?? 'normal')
1742
- : 'normal';
1743
- // docs/GOTCHAS.md - operator-set persistent north-star. Read straight
1744
- // from wf.config, inherited on EVERY path including in-tab DOCS / GIT (the one
1745
- // deliberate divergence from outputStyle's forced 'normal' for those two — a
1746
- // DOCS/GIT prompt benefits from the goal context). Absent / blank ⇒ no block
1747
- // on any transport; honored wherever clusterPlan is folded.
1748
- const goal = isolatedMember ? undefined : wf.config.goal;
1749
- // docs/PROVIDERS.md - per-tab Ollama param preset blob. Resolved
1750
- // ONLY for Ollama tabs (the provider's request builder is the sole consumer;
1751
- // every other provider ignores the field). Read straight from wf.config so
1752
- // it is byte-stable across this workflow's turns — the prefix-cache
1753
- // invariant. The operator-edit path (updatePrimaryConfig) is the only place
1754
- // it changes between turns, and that's logged as a cache-invalidation event.
1755
- const ollamaParams = wf.primary.provider === 'ollama'
1756
- ? wf.config.ollamaParams
1757
- : undefined;
1758
- let activeTurnObservation;
1759
- try {
1760
- while (true) {
1761
- const pickedSkillsBlock = await resolvePickedSkillsBlock(promptPickedSkills);
1762
- console.log(`[arco] [${workflowId.slice(0, 8)}] user_message received; starting primary turn (${wf.primary.provider}:${wf.primary.model}, resume=${wf.primarySessionId?.slice(0, 8) || 'none'})`);
1763
- // Peer mailbox: don't auto-drain pre-turn. Just count what's pending and
1764
- // surface a short notice so the worker knows it has peer mail and reads
1765
- // it via peer_read. Keeps peer messages as a normal tool-flow primitive
1766
- // instead of getting silently shoved into the system prompt where the
1767
- // model conflates "system context" with "current peer mail."
1768
- // peer_message_received events now fire on peer_read call (where they
1769
- // belong) rather than pre-turn.
1770
- //
1771
- // Phrase the notice as an instruction to read peer mail so the model
1772
- // invokes the tool rather than echoing a tool-call example.
1773
- // the notice text now varies by the cluster's efficiency
1774
- // level (clusterEfficiency.buildPeerMailboxNotice). At balanced/lean the
1775
- // doctrine tells members not to re-review unless signalled, so the notice
1776
- // must NOT also shout "re-engage on every inbound" — that contradiction
1777
- // is exactly the over-review loop this feature targets. The level lookup
1778
- // is a synchronous in-memory read, so resolving the clusterId here
1779
- // (ahead of the turn-start resolution below) is cheap. 'thorough' yields
1780
- // the byte-identical historical notice.
1781
- let peerMessagesPrologue;
1782
- if (firstIteration) {
1783
- const pendingDepth = await clusterMailbox.depthFor(workflowId).catch(() => 0);
1784
- if (pendingDepth > 0) {
1785
- const noticeClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
1786
- const noticeLevel = noticeClusterId
1787
- ? clusterStore.getEfficiencyLevel(noticeClusterId)
1788
- : 'thorough';
1789
- const noticeAccess = noticeClusterId
1790
- ? clusterStore.getMemberAccessMode(noticeClusterId, workflowId)
1791
- : 'standard';
1792
- peerMessagesPrologue = noticeAccess === 'standard'
1793
- ? clusterEfficiency.buildPeerMailboxNotice(noticeLevel, pendingDepth, noticeClusterId ? clusterStore.getMemberRole(noticeClusterId, workflowId) : undefined)
1794
- : `You have ${pendingDepth} pending peer message${pendingDepth === 1 ? '' : 's'}. Read them with peer_read; no other cluster context is available.`;
1756
+ if (trustGate.needsPrompt && projectTrust.markPromptPending(trustDecisionCwd)) {
1757
+ broadcastWorkflow(workflowId, {
1758
+ type: 'project_trust_prompt',
1759
+ workflowId,
1760
+ cwd: trustDecisionCwd,
1761
+ resources: trustGate.resources,
1762
+ });
1763
+ }
1764
+ // DD8 — resolve picks for the prompt that owns them, including queued
1765
+ // interrupt instructions. Picking is an explicit operator action, so it
1766
+ // applies regardless
1767
+ // of the DD7 trust gate above — picking IS the operator's vouch. A missing /
1768
+ // unreadable skill is skipped with a notice rather than failing the turn.
1769
+ async function resolvePickedSkillsBlock(picks) {
1770
+ if (!projectContextEnabled || !picks?.length)
1771
+ return '';
1772
+ const resolved = [];
1773
+ const missing = [];
1774
+ for (const pick of picks) {
1775
+ try {
1776
+ if (pick.scope === 'builtin') {
1777
+ // Built-in skills ship with Arco. The Architecture review also gets
1778
+ // the facts Arco gathers now and the project's recorded decisions.
1779
+ const builtin = readBuiltinSkill(pick.slug);
1780
+ if (!builtin) {
1781
+ missing.push(`builtin:${pick.slug}`);
1782
+ continue;
1783
+ }
1784
+ const trust = await projectTrust.resolveTrustStatus(managedTrustSource ?? cwd).catch(() => 'ask');
1785
+ const catalog = await listSkills(cwd, { includeProject: trust === 'always' });
1786
+ const summary = catalog.builtin.find((s) => s.slug === builtin.slug);
1787
+ if (!summary || summary.off || summary.replaced) {
1788
+ missing.push(`builtin:${pick.slug}`);
1789
+ continue;
1790
+ }
1791
+ const extra = builtin.slug === ARCHITECTURE_REVIEW_SLUG
1792
+ ? `\n\nArtifacts folder for this conversation: ${artifactsDir(cwd, workflowId)}\n\n${await architectureReviewFacts(cwd, wf?.planId ?? clusterStore.getPlanId(clusterStore.getClusterIdForWorkflow(workflowId) ?? ''))}`
1793
+ : `\n\nThe available skill files are listed in the skill manifest.`;
1794
+ resolved.push({ name: builtin.name, scope: 'builtin', body: builtin.body + extra });
1795
+ continue;
1796
+ }
1797
+ const full = await readSkillBody(pick.scope, pick.slug, cwd);
1798
+ if (full)
1799
+ resolved.push({ name: full.name, scope: full.scope, body: full.body });
1800
+ else
1801
+ missing.push(`${pick.scope}:${pick.slug}`);
1795
1802
  }
1796
- }
1797
- // First turn echoes the operator's fresh prompt into events.jsonl.
1798
- // Drain turns don't re-echo — each queued interjection was already
1799
- // echoed at enqueue-time, so the transcript renders the individual
1800
- // interjections rather than the joined follow-up prompt.
1801
- if (firstIteration) {
1802
- // An idle drain's items were echoed individually at enqueue time.
1803
- if (!fromQueue)
1804
- send(ws, {
1805
- type: 'user_message_echo',
1806
- workflowId,
1807
- content: prompt,
1808
- attachments: promptAttachments,
1809
- clientMessageId: promptClientMessageId,
1810
- timestamp: Date.now(),
1811
- ...(trackOllama ? { ollamaReplayInput: true } : {}),
1812
- });
1813
- if (!fromQueue && trackOllama)
1814
- activeOllamaInputSeqs = [currentWorkflowSeq(cwd, workflowId)];
1815
- if (chatMode && !incognito) {
1816
- // Keep the global Past Chats list useful without rescanning a growing
1817
- // events.jsonl for every creator render.
1818
- const preview = prompt.replace(/\s+/g, ' ').trim().slice(0, 80);
1819
- await updateMeta(cwd, workflowId, (meta) => {
1820
- meta.lastActiveAt = Date.now();
1821
- meta.lastUserPreview = preview;
1822
- }).catch((err) => {
1823
- console.warn(`[arco] [${workflowId.slice(0, 8)}] Chat activity meta write failed:`, err);
1824
- });
1803
+ catch {
1804
+ missing.push(`${pick.scope}:${pick.slug}`);
1825
1805
  }
1826
1806
  }
1827
- // Lazy-create the bg-jobs tracker on first turn — most tabs never
1828
- // spawn long-running children, so the /proc poller only starts when
1829
- // a Bash(run_in_background) hint or a fresh descendant actually
1830
- // appears. Tracker is persistent across turns (and across handoffs)
1831
- // so a download started in turn N stays visible in turn N+3.
1832
- if (!chatMode && !wf.bgTracker) {
1833
- wf.bgTracker = new PrimaryBackgroundTracker({
1807
+ const built = buildPickedSkillsBlock(resolved);
1808
+ const names = resolved.map((s) => s.name).join(', ');
1809
+ broadcastWorkflow(workflowId, {
1810
+ type: 'system_notice',
1811
+ workflowId,
1812
+ content: `[SKILLS] Inlined ${resolved.length} operator-picked skill${resolved.length === 1 ? '' : 's'} ` +
1813
+ `(${built.bytes} bytes) into this turn${names ? `: ${names}` : ''}.` +
1814
+ (missing.length > 0 ? ` Skipped (not found): ${missing.join(', ')}.` : ''),
1815
+ });
1816
+ return built.text;
1817
+ }
1818
+ // Standing SKILLS pins are re-resolved once per primary-turn invocation.
1819
+ // This keeps edits live, survives Native compaction / Handoff / restart, and
1820
+ // avoids silently snapshotting stale bodies into meta.json. Like a one-shot
1821
+ // pick, a project pin is an explicit operator vouch and bypasses discovery's
1822
+ // project-trust suppression. Missing files fail safe and stay visible.
1823
+ let pinnedSkillsBlock = '';
1824
+ if (projectContextEnabled && wf.config.pinnedSkills?.length) {
1825
+ const resolved = await resolvePinnedSkills(wf.config.pinnedSkills, cwd);
1826
+ const built = buildPinnedSkillsBlock(resolved.skills);
1827
+ pinnedSkillsBlock = built.text;
1828
+ const skipped = [...resolved.missing, ...resolved.truncated];
1829
+ if (skipped.length > 0) {
1830
+ broadcastWorkflow(workflowId, {
1831
+ type: 'system_notice',
1834
1832
  workflowId,
1835
- broadcast: (msg) => broadcastTransient(workflowId, msg),
1833
+ content: `[PINNED SKILLS] ${resolved.skills.length} active (${built.bytes} bytes); skipped: ${skipped.join(', ')}.`,
1836
1834
  });
1837
1835
  }
1838
- // Plan header injection. When a plan is attached, prepend a brief
1839
- // "active plan" reminder to the prompt before forwarding to the
1840
- // provider — the operator's echo'd transcript stays clean. If the
1841
- // plan body was edited since the last turn that injected it, also
1842
- // include the full body once so the agent picks up the change. The
1843
- // operator's transcript is unaffected (echo already sent above).
1844
- const planPrefix = projectContextEnabled ? await buildPlanPrefix(cwd, wf, workflowId) : '';
1845
- const promptWithRefs = promptExpandedContext ? prompt + promptExpandedContext : prompt;
1846
- // DD8 — inline the picks owned by this prompt, after explicit refs.
1847
- // Model-facing only; each queued prompt carries its own picks.
1848
- const promptWithSkills = pickedSkillsBlock
1849
- ? `${promptWithRefs}\n\n${pickedSkillsBlock}`
1850
- : promptWithRefs;
1851
- let promptWithPlan = planPrefix ? planPrefix + promptWithSkills : promptWithSkills;
1852
- if (firstIteration && primitive === 'plan-review' && wf.primary.provider === 'cursor') {
1853
- const prior = renderTranscript(await replayWorkflowEvents(cwd, workflowId, 0)).slice(-48_000);
1854
- if (prior.trim())
1855
- promptWithPlan = `Recent conversation (may be truncated):\n${prior}\n\n${promptWithPlan}`;
1856
- }
1857
- // Ollama has no native session resume — every spawn is a fresh HTTP
1858
- // request. To give the model memory across turns we replay the
1859
- // workflow's events.jsonl into the same USER:/AGENT: transcript shape
1860
- // the fresh-summarizer Handoff produces, then hand it to the provider
1861
- // as appendSystemPrompt. The provider parses it back into structured
1862
- // /api/chat messages so the prefix bytes stay stable across turns
1863
- // and Ollama's prefix cache hits.
1864
- //
1865
- // The system prompt counters two observed Qwen-MoE behaviors against
1866
- // a code chat: (1) verbose tabular formatting on every reply, (2)
1867
- // hallucinating about files when no tools are wired (§5.4 still
1868
- // pending). Static text — no timestamps or random ids — so the prefix
1869
- // cache hits cleanly across turns.
1870
- let ollamaReplay;
1871
- let primaryAppendSystemPrompt;
1872
- let primarySystemPrompt;
1873
- // The current user echo was just recorded above. Stateless providers
1874
- // receive only the completed turns before it; the current prompt rides
1875
- // the normal provider input exactly once.
1876
- const priorIncognitoEvents = incognito
1877
- ? (() => {
1878
- const events = wf.incognitoEvents ?? [];
1879
- return events[events.length - 1]?.type === 'user_message_echo'
1880
- ? events.slice(0, -1)
1881
- : [...events];
1882
- })()
1883
- : null;
1884
- // Phase 1 — Arco-managed skills. Scan project + global skill
1885
- // directories on every turn (cheap — small dir count, single SKILL.md
1886
- // read each), build the XML manifest, and route it to wherever the
1887
- // provider's system prompt actually lives. Manifest holds only name +
1888
- // description; the agent reads the full SKILL.md via its Read tool.
1889
- // Re-scanning per turn means edits / deletes via the UI take effect on
1890
- // the next turn without restarting anything.
1891
- let primarySkillsManifest = '';
1892
- if (projectContextEnabled)
1893
- try {
1894
- const catalog = await listSkills(cwd, { includeProject });
1895
- // A pinned body is already present in full; omit its progressive-
1896
- // disclosure metadata to avoid duplicate/conflicting instructions.
1897
- const pinnedKeys = new Set((wf.config.pinnedSkills ?? []).map((s) => `${s.scope}:${s.slug}`));
1898
- primarySkillsManifest = buildSkillsManifest({
1899
- project: catalog.project.filter((s) => !pinnedKeys.has(`project:${s.slug}`)),
1900
- global: catalog.global.filter((s) => !pinnedKeys.has(`global:${s.slug}`)),
1901
- });
1902
- }
1903
- catch (err) {
1904
- console.error(`[arco] [${workflowId.slice(0, 8)}] skills scan failed:`, err);
1836
+ }
1837
+ // Phase 6 — resolve the Codex transport once per primary-turn invocation.
1838
+ // Reading the cascade up here means the value is stable across the
1839
+ // drain-loop iterations below; an HMR-driven settings.json change between
1840
+ // turns won't re-toggle the transport mid-loop, which would otherwise
1841
+ // leak a long-lived `codex app-server` worker after switching back to
1842
+ // exec mode. The dispatcher's exec-default fall-through covers other
1843
+ // providers; reviewers/handoffs leave codexTransport unset.
1844
+ // Phase 6e — per-tab override (`wf.config.codexTransport`) takes precedence
1845
+ // over the cascade. The CONFIG-tab toggle writes to that field via
1846
+ // update_primary_config so the operator's choice doesn't depend on a
1847
+ // hand-edited settings.json.
1848
+ const cascade = await readSettings(cwd, { includeProject }).catch(() => null);
1849
+ // turnSettings.ts — which value wins for each per-turn setting (tab
1850
+ // choice, settings files, default; Native-only switches off elsewhere).
1851
+ const { codexTransport, ultracode, claudeTransport, claudeNativeCompact, claudeNativeForceInterleavedThinkingBeta, claudeNativeThinkingDisplay, nativeSubagents, efficiencyToolFilter, efficiencyFactForce, efficiencyConfigProtection, efficiencySandbox, reviewSafeMode, outputStyle, goal, ollamaParams, } = resolveTurnSettings({ provider: wf.primary.provider, config: wf.config, cascade, isolatedMember, primitive });
1852
+ // In-turn compaction follows the tab's or cluster's auto-compaction policy
1853
+ // (the plan-review step, a Chat-style request, leaves it off below).
1854
+ const inTurnClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
1855
+ const claudeNativeInTurnCompactPercent = wf.primary.provider === 'claude'
1856
+ ? resolveNativeInTurnCompactPercent({
1857
+ native: claudeTransport === 'native',
1858
+ chat: isChatWorkflow(wf.config),
1859
+ claudeNativeCompact,
1860
+ worker: wf.config.autoCompaction ?? undefined,
1861
+ cluster: inTurnClusterId ? clusterStore.getAutoCompaction(inTurnClusterId) : undefined,
1862
+ })
1863
+ : undefined;
1864
+ const providerAccount = wf.primary.provider === 'codex'
1865
+ ? await resolveProviderAccount('codex', wf.config.providerAccountRef, cwd).catch(() => null)
1866
+ : null;
1867
+ if (providerAccount?.profile.id && wf.config.providerAccountRef !== providerAccount.profile.id) {
1868
+ wf.config.providerAccountRef = providerAccount.profile.id;
1869
+ }
1870
+ let activeTurnObservation;
1871
+ try {
1872
+ while (true) {
1873
+ primaryTurn.clusterDispatch = undefined;
1874
+ const pickedSkillsBlock = await resolvePickedSkillsBlock(promptPickedSkills);
1875
+ console.log(`[arco] [${workflowId.slice(0, 8)}] user_message received; starting primary turn (${wf.primary.provider}:${wf.primary.model}, resume=${wf.primarySessionId?.slice(0, 8) || 'none'})`);
1876
+ // Peer mailbox: don't auto-drain pre-turn. Just count what's pending and
1877
+ // surface a short notice so the worker knows it has peer mail and reads
1878
+ // it via peer_read. Keeps peer messages as a normal tool-flow primitive
1879
+ // instead of getting silently shoved into the system prompt where the
1880
+ // model conflates "system context" with "current peer mail."
1881
+ // peer_message_received events now fire on peer_read call (where they
1882
+ // belong) rather than pre-turn.
1883
+ //
1884
+ // Phrase the notice as an instruction to read peer mail so the model
1885
+ // invokes the tool rather than echoing a tool-call example.
1886
+ // the notice text now varies by the cluster's efficiency
1887
+ // level (clusterEfficiency.buildPeerMailboxNotice). At balanced/lean the
1888
+ // doctrine tells members not to re-review unless signalled, so the notice
1889
+ // must NOT also shout "re-engage on every inbound" — that contradiction
1890
+ // is exactly the over-review loop this feature targets. The level lookup
1891
+ // is a synchronous in-memory read, so resolving the clusterId here
1892
+ // (ahead of the turn-start resolution below) is cheap. 'thorough' yields
1893
+ // the byte-identical historical notice.
1894
+ let peerMessagesPrologue;
1895
+ if (firstIteration) {
1896
+ const pendingDepth = await clusterMailbox.depthFor(workflowId).catch(() => 0);
1897
+ if (pendingDepth > 0) {
1898
+ const noticeClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
1899
+ const noticeLevel = noticeClusterId
1900
+ ? clusterStore.getEfficiencyLevel(noticeClusterId)
1901
+ : 'thorough';
1902
+ const noticeAccess = noticeClusterId
1903
+ ? clusterStore.getMemberAccessMode(noticeClusterId, workflowId)
1904
+ : 'standard';
1905
+ peerMessagesPrologue = noticeAccess === 'standard'
1906
+ ? clusterEfficiency.buildPeerMailboxNotice(noticeLevel, pendingDepth, noticeClusterId ? clusterStore.getMemberRole(noticeClusterId, workflowId) : undefined)
1907
+ : `You have ${pendingDepth} pending peer message${pendingDepth === 1 ? '' : 's'}. Read them with peer_read; no other cluster context is available.`;
1908
+ }
1905
1909
  }
1906
- if (wf.primary.provider === 'ollama') {
1907
- primarySystemPrompt = chatMode ? chatSystemPrompt(chatWeb) : OLLAMA_PRIMARY_SYSTEM_PROMPT;
1908
- try {
1909
- const events = priorIncognitoEvents ?? (wf.config.voiceOperator
1910
- ? await computerReplayEvents(cwd, workflowId, wf.config.computerContext?.lastResetAt, wf.config.computerContext?.lastResetSeq)
1911
- : await replayWorkflowEvents(cwd, workflowId, 0));
1912
- // preserveThinking: Qwen-family models (3.6, 3-VL) implement
1913
- // Thinking Preservation — prior turn reasoning fed back as
1914
- // context improves multi-turn coherence. Cheap (just routes
1915
- // primary_thinking events into a <think> block on each AGENT
1916
- // entry); UI/handoff paths still call renderTranscript without
1917
- // the flag and stay reasoning-clean.
1918
- // Hidden reasoning is useful continuity for project Agent work, but
1919
- // Chat capabilities can change between turns via the WEB toggle. A
1920
- // saved offline turn can contain the old system restriction verbatim;
1921
- // replaying that reasoning after web is armed makes local models obey
1922
- // the stale state instead of the current system block + tools[].
1923
- const clusterForReplay = clusterStore.getClusterIdForWorkflow(workflowId);
1924
- const savedOllamaPolicy = cascade?.ollama?.compaction?.enabled !== undefined || cascade?.ollama?.compaction?.threshold !== undefined;
1925
- const policy = trackOllama ? resolveProviderAutoCompaction(wf.config.autoCompaction, clusterForReplay ? clusterStore.getAutoCompaction(clusterForReplay) : undefined, 'ollama', '', false, savedOllamaPolicy) : undefined;
1926
- let replayEvents = events;
1927
- if (policy) {
1928
- const policyKey = JSON.stringify(policy);
1929
- ollamaReplay = { events, activeInputSeqs: [...activeOllamaInputSeqs], policy, stillOwner: () => {
1930
- const cluster = clusterStore.getClusterIdForWorkflow(workflowId);
1931
- const current = resolveProviderAutoCompaction(wf.config.autoCompaction, cluster ? clusterStore.getAutoCompaction(cluster) : undefined, 'ollama', '', false, savedOllamaPolicy);
1932
- return workflows.get(workflowId) === wf && ownsBusy(wf, busyToken) && wf.primary.provider === 'ollama' && JSON.stringify(current) === policyKey;
1933
- } };
1934
- replayEvents = projectOllamaHistory(events, workflowId, activeOllamaInputSeqs).events;
1910
+ // First turn echoes the operator's fresh prompt into events.jsonl.
1911
+ // Drain turns don't re-echo — each queued interjection was already
1912
+ // echoed at enqueue-time, so the transcript renders the individual
1913
+ // interjections rather than the joined follow-up prompt.
1914
+ if (firstIteration) {
1915
+ // An idle drain's items were echoed individually at enqueue time.
1916
+ if (!fromQueue)
1917
+ send(ws, {
1918
+ type: 'user_message_echo',
1919
+ workflowId,
1920
+ ...(opts?.automaticKind ? { automaticKind: opts.automaticKind } : {}),
1921
+ content: prompt,
1922
+ attachments: promptAttachments,
1923
+ clientMessageId: promptClientMessageId,
1924
+ deliveryTracked: true,
1925
+ timestamp: Date.now(),
1926
+ ...(trackOllama ? { ollamaReplayInput: true } : {}),
1927
+ });
1928
+ if (!fromQueue)
1929
+ activeInputClientIds = promptClientMessageId ? [promptClientMessageId] : [];
1930
+ if (!fromQueue && trackOllama)
1931
+ activeOllamaInputSeqs = [currentWorkflowSeq(cwd, workflowId)];
1932
+ if (chatMode && !incognito) {
1933
+ // Keep the global Past Chats list useful without rescanning a growing
1934
+ // events.jsonl for every creator render.
1935
+ const preview = prompt.replace(/\s+/g, ' ').trim().slice(0, 80);
1936
+ await updateMeta(cwd, workflowId, (meta) => {
1937
+ meta.lastActiveAt = Date.now();
1938
+ meta.lastUserPreview = preview;
1939
+ }).catch((err) => {
1940
+ console.warn(`[arco] [${workflowId.slice(0, 8)}] Chat activity meta write failed:`, err);
1941
+ });
1935
1942
  }
1936
- const rendered = (wf.config.voiceOperator ? renderComputerHistory(replayEvents) : renderTranscript(replayEvents, { preserveThinking: !chatMode })).trim();
1937
- if (rendered)
1938
- primaryAppendSystemPrompt = rendered;
1939
1943
  }
1940
- catch (err) {
1941
- console.error(`[arco] [${workflowId.slice(0, 8)}] ollama transcript build failed:`, err);
1944
+ // Lazy-create the bg-jobs tracker on first turn — most tabs never
1945
+ // spawn long-running children, so the /proc poller only starts when
1946
+ // a Bash(run_in_background) hint or a fresh descendant actually
1947
+ // appears. Tracker is persistent across turns (and across handoffs)
1948
+ // so a download started in turn N stays visible in turn N+3.
1949
+ if (!chatMode && !wf.bgTracker) {
1950
+ wf.bgTracker = new PrimaryBackgroundTracker({
1951
+ workflowId,
1952
+ broadcast: (msg) => broadcastTransient(workflowId, msg),
1953
+ });
1942
1954
  }
1943
- }
1944
- else if (wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek') || (chatMode && wf.primary.provider === 'cursor')) {
1945
- // M13 — LM Studio reuses llama.cpp's transcript-rebuild path verbatim:
1946
- // both are OpenAI-compat local runtimes with no native session, so the
1947
- // deterministic prior-turn summary + reasoning-clean rendered
1948
- // transcript apply identically. (LM Studio is remote, but the
1949
- // context-loss-across-turns problem is the same.)
1950
- primarySystemPrompt = chatMode ? chatSystemPrompt(chatWeb) : LLAMACPP_PRIMARY_SYSTEM_PROMPT;
1951
- // llama.cpp: same prefix-cache benefits as ollama but with an
1952
- // additional structured prior-turn summary prepended. Local thinking
1953
- // models lose track across turns because renderTranscript drops all
1954
- // tool history (only USER:/AGENT: text survives) — the model on
1955
- // turn N has no idea which files it read or wrote on turn N-1.
1956
- // summarizePriorTurns walks events.jsonl and produces a deterministic
1957
- // per-turn breakdown (tools used, files touched, bash run, final
1958
- // reply text). It's stuffed into a faux AGENT block at the head of
1959
- // the transcript so the parser routes it into one assistant message.
1955
+ // Plan header injection. When a plan is attached, prepend a brief
1956
+ // "active plan" reminder to the prompt before forwarding to the
1957
+ // provider — the operator's echo'd transcript stays clean. If the
1958
+ // plan body was edited since the last turn that injected it, also
1959
+ // include the full body once so the agent picks up the change. The
1960
+ // operator's transcript is unaffected (echo already sent above).
1961
+ const planPrefix = projectContextEnabled ? await buildPlanPrefix(cwd, wf, workflowId) : '';
1962
+ const promptWithRefs = promptExpandedContext ? prompt + promptExpandedContext : prompt;
1963
+ // DD8 — inline the picks owned by this prompt, after explicit refs.
1964
+ // Model-facing only; each queued prompt carries its own picks.
1965
+ const promptWithSkills = pickedSkillsBlock
1966
+ ? `${promptWithRefs}\n\n${pickedSkillsBlock}`
1967
+ : promptWithRefs;
1968
+ let promptWithPlan = planPrefix ? planPrefix + promptWithSkills : promptWithSkills;
1969
+ if (firstIteration && primitive === 'plan-review' && wf.primary.provider === 'cursor') {
1970
+ const prior = renderTranscript(await replayWorkflowEvents(cwd, workflowId, 0)).slice(-48_000);
1971
+ if (prior.trim())
1972
+ promptWithPlan = `Recent conversation (may be truncated):\n${prior}\n\n${promptWithPlan}`;
1973
+ }
1974
+ // Ollama has no native session resume — every spawn is a fresh HTTP
1975
+ // request. To give the model memory across turns we replay the
1976
+ // workflow's events.jsonl into the same USER:/AGENT: transcript shape
1977
+ // the fresh-summarizer Handoff produces, then hand it to the provider
1978
+ // as appendSystemPrompt. The provider parses it back into structured
1979
+ // /api/chat messages so the prefix bytes stay stable across turns
1980
+ // and Ollama's prefix cache hits.
1960
1981
  //
1961
- // We deliberately do NOT preserveThinking here: re-feeding Qwen3.6
1962
- // its own reasoning across turns has the opposite of the ollama
1963
- // benefit because llama-server already exposes reasoning_content
1964
- // separately and the extra <think> blocks just inflate the prompt
1965
- // and trigger more verbose monologue on the next turn.
1966
- try {
1967
- const events = priorIncognitoEvents ?? (wf.config.voiceOperator
1968
- ? await computerReplayEvents(cwd, workflowId, wf.config.computerContext?.lastResetAt, wf.config.computerContext?.lastResetSeq)
1969
- : await replayWorkflowEvents(cwd, workflowId, 0));
1970
- const summary = chatMode ? '' : summarizePriorTurns(events);
1971
- const rendered = (wf.config.voiceOperator ? renderComputerHistory(events) : renderTranscript(events, { preserveThinking: false })).trim();
1972
- const parts = [];
1973
- if (summary) {
1974
- parts.push(`USER: [Workflow context]`);
1975
- parts.push(`AGENT: ${summary}`);
1982
+ // The system prompt counters two observed Qwen-MoE behaviors against
1983
+ // a code chat: (1) verbose tabular formatting on every reply, (2)
1984
+ // hallucinating about files when no tools are wired (§5.4 still
1985
+ // pending). Static text — no timestamps or random ids — so the prefix
1986
+ // cache hits cleanly across turns.
1987
+ let ollamaReplay;
1988
+ const retainLocalFiles = ['ollama', 'llamacpp', 'lmstudio', 'strata', 'deepseek'].includes(wf.primary.provider);
1989
+ let priorFiles = retainLocalFiles || chatMode ? [] : undefined;
1990
+ let primaryAppendSystemPrompt;
1991
+ let primarySystemPrompt;
1992
+ // The current user echo was just recorded above. Stateless providers
1993
+ // receive only the completed turns before it; the current prompt rides
1994
+ // the normal provider input exactly once.
1995
+ const priorIncognitoEvents = incognito
1996
+ ? (() => {
1997
+ const events = wf.incognitoEvents ?? [];
1998
+ return events[events.length - 1]?.type === 'user_message_echo'
1999
+ ? events.slice(0, -1)
2000
+ : [...events];
2001
+ })()
2002
+ : null;
2003
+ // Phase 1 — Arco-managed skills. Scan project + global skill
2004
+ // directories on every turn (cheap — small dir count, single SKILL.md
2005
+ // read each), build the XML manifest, and route it to wherever the
2006
+ // provider's system prompt actually lives. Manifest holds only name +
2007
+ // description; the agent reads the full SKILL.md via its Read tool.
2008
+ // Re-scanning per turn means edits / deletes via the UI take effect on
2009
+ // the next turn without restarting anything.
2010
+ let primarySkillsManifest = '';
2011
+ if (projectContextEnabled)
2012
+ try {
2013
+ const catalog = await listSkills(cwd, { includeProject });
2014
+ // A pinned body is already present in full; omit its progressive-
2015
+ // disclosure metadata to avoid duplicate/conflicting instructions.
2016
+ const pinnedKeys = new Set((wf.config.pinnedSkills ?? []).map((s) => `${s.scope}:${s.slug}`));
2017
+ primarySkillsManifest = buildSkillsManifest({
2018
+ project: catalog.project.filter((s) => !pinnedKeys.has(`project:${s.slug}`)),
2019
+ global: catalog.global.filter((s) => !pinnedKeys.has(`global:${s.slug}`)),
2020
+ builtin: catalog.builtin,
2021
+ });
2022
+ }
2023
+ catch (err) {
2024
+ console.error(`[arco] [${workflowId.slice(0, 8)}] skills scan failed:`, err);
2025
+ }
2026
+ if (wf.primary.provider === 'ollama') {
2027
+ primarySystemPrompt = chatMode ? chatSystemPrompt(chatWeb) : OLLAMA_PRIMARY_SYSTEM_PROMPT;
2028
+ try {
2029
+ const events = priorIncognitoEvents ?? (wf.config.voiceOperator
2030
+ ? await computerReplayEvents(cwd, workflowId, wf.config.computerContext?.lastResetAt, wf.config.computerContext?.lastResetSeq)
2031
+ : await replayWorkflowEvents(cwd, workflowId, 0));
2032
+ // preserveThinking: Qwen-family models (3.6, 3-VL) implement
2033
+ // Thinking Preservation — prior turn reasoning fed back as
2034
+ // context improves multi-turn coherence. Cheap (just routes
2035
+ // primary_thinking events into a <think> block on each AGENT
2036
+ // entry); UI/handoff paths still call renderTranscript without
2037
+ // the flag and stay reasoning-clean.
2038
+ // Hidden reasoning is useful continuity for project Agent work, but
2039
+ // Chat capabilities can change between turns via the WEB toggle. A
2040
+ // saved offline turn can contain the old system restriction verbatim;
2041
+ // replaying that reasoning after web is armed makes local models obey
2042
+ // the stale state instead of the current system block + tools[].
2043
+ const clusterForReplay = clusterStore.getClusterIdForWorkflow(workflowId);
2044
+ const savedOllamaPolicy = cascade?.ollama?.compaction?.enabled !== undefined || cascade?.ollama?.compaction?.threshold !== undefined;
2045
+ const policy = trackOllama ? resolveProviderAutoCompaction(wf.config.autoCompaction, clusterForReplay ? clusterStore.getAutoCompaction(clusterForReplay) : undefined, 'ollama', '', false, savedOllamaPolicy) : undefined;
2046
+ let replayEvents = events;
2047
+ if (policy) {
2048
+ const policyKey = JSON.stringify(policy);
2049
+ ollamaReplay = { events, activeInputSeqs: [...activeOllamaInputSeqs], policy, stillOwner: () => {
2050
+ const cluster = clusterStore.getClusterIdForWorkflow(workflowId);
2051
+ const current = resolveProviderAutoCompaction(wf.config.autoCompaction, cluster ? clusterStore.getAutoCompaction(cluster) : undefined, 'ollama', '', false, savedOllamaPolicy);
2052
+ return workflows.get(workflowId) === wf && ownsBusy(wf, busyToken) && wf.primary.provider === 'ollama' && JSON.stringify(current) === policyKey;
2053
+ } };
2054
+ replayEvents = projectOllamaHistory(events, workflowId, activeOllamaInputSeqs, true).events;
2055
+ }
2056
+ priorFiles = projectLocalFileReferences(events, cwd, chatMode);
2057
+ const rendered = (wf.config.voiceOperator ? renderComputerHistory(replayEvents) : renderTranscript(replayEvents, { preserveThinking: !chatMode, separateFileContext: !chatMode, attachmentOnly: chatMode })).trim();
2058
+ if (rendered)
2059
+ primaryAppendSystemPrompt = rendered;
2060
+ }
2061
+ catch (err) {
2062
+ console.error(`[arco] [${workflowId.slice(0, 8)}] ollama transcript build failed:`, err);
1976
2063
  }
1977
- if (rendered)
1978
- parts.push(rendered);
1979
- const combined = parts.join('\n\n').trim();
1980
- if (combined)
1981
- primaryAppendSystemPrompt = combined;
1982
- }
1983
- catch (err) {
1984
- console.error(`[arco] [${workflowId.slice(0, 8)}] ${wf.primary.provider} transcript build failed:`, err);
1985
2064
  }
1986
- }
1987
- else if (incognito
1988
- && ((wf.primary.provider === 'claude' && claudeTransport !== 'native')
1989
- || (wf.primary.provider === 'codex' && codexTransport !== 'appserver'))) {
1990
- // Incognito CLI turns deliberately have no resumable provider session.
1991
- // Replay the memory-only completed transcript into each one-shot call.
1992
- const rendered = renderTranscript(priorIncognitoEvents ?? []).trim();
1993
- if (rendered)
1994
- primaryAppendSystemPrompt = `Conversation so far:\n\n${rendered}`;
1995
- }
1996
- // Local HTTP transports receive stable tool instructions through the
1997
- // provider system-prompt field; Claude and Codex transports fold them
1998
- // into their string-form prompt or native request blocks.
1999
- const usesSystemPromptForSkills = wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek');
2000
- const primarySkillsContext = [pinnedSkillsBlock, primarySkillsManifest].filter(Boolean).join('\n\n');
2001
- let finalSystemPrompt = usesSystemPromptForSkills && primarySkillsContext
2002
- ? (primarySystemPrompt ? `${primarySkillsContext}\n\n${primarySystemPrompt}` : primarySkillsContext)
2003
- : primarySystemPrompt;
2004
- const finalAppendBase = chatMode ? primaryAppendSystemPrompt : withPreviewNudge(primaryAppendSystemPrompt);
2005
- const baseWithSkills = !usesSystemPromptForSkills && primarySkillsContext
2006
- ? `${primarySkillsContext}\n\n${finalAppendBase}`
2007
- : finalAppendBase;
2008
- // Phase 7a — fold discovered CLAUDE.md files into appendSystemPrompt
2009
- // for Claude tabs (CLI + Native both benefit). Walks up from cwd
2010
- // collecting CLAUDE.md, plus ~/.claude/CLAUDE.md.
2011
- let finalAppend = baseWithSkills;
2012
- // docs/VOICE.md - the Computer voice operator chat has its own
2013
- // base instructions and real (arco-voice) tools; the generic Chat
2014
- // preamble ("do not use backend tools… continue in an Agent tab") made
2015
- // Luna refuse them (2026-10-17 smoke:voice-luna regression).
2016
- if (chatMode && wf.config.voiceOperator === true) {
2017
- if (usesSystemPromptForSkills)
2018
- finalSystemPrompt = VOICE_OPERATOR_PROMPT;
2019
- else if (wf.primary.provider !== 'codex')
2020
- finalAppend = [VOICE_OPERATOR_PROMPT, finalAppend].filter(Boolean).join('\n\n');
2021
- }
2022
- if (chatMode && wf.config.voiceOperator !== true) {
2023
- const chatPrompt = chatSystemPrompt(chatWeb);
2024
- if (usesSystemPromptForSkills) {
2025
- finalSystemPrompt = chatPrompt;
2065
+ else if (wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek') || (chatMode && wf.primary.provider === 'cursor')) {
2066
+ // M13 — LM Studio reuses llama.cpp's transcript-rebuild path verbatim:
2067
+ // both are OpenAI-compat local runtimes with no native session, so the
2068
+ // deterministic prior-turn summary + reasoning-clean rendered
2069
+ // transcript apply identically. (LM Studio is remote, but the
2070
+ // context-loss-across-turns problem is the same.)
2071
+ primarySystemPrompt = chatMode ? chatSystemPrompt(chatWeb) : LLAMACPP_PRIMARY_SYSTEM_PROMPT;
2072
+ // llama.cpp: same prefix-cache benefits as ollama but with an
2073
+ // additional structured prior-turn summary prepended. Local thinking
2074
+ // models lose track across turns because renderTranscript drops all
2075
+ // tool history (only USER:/AGENT: text survives) — the model on
2076
+ // turn N has no idea which files it read or wrote on turn N-1.
2077
+ // summarizePriorTurns walks events.jsonl and produces a deterministic
2078
+ // per-turn breakdown (tools used, files touched, bash run, final
2079
+ // reply text). It's stuffed into a faux AGENT block at the head of
2080
+ // the transcript so the parser routes it into one assistant message.
2081
+ //
2082
+ // We deliberately do NOT preserveThinking here: re-feeding Qwen3.6
2083
+ // its own reasoning across turns has the opposite of the ollama
2084
+ // benefit because llama-server already exposes reasoning_content
2085
+ // separately and the extra <think> blocks just inflate the prompt
2086
+ // and trigger more verbose monologue on the next turn.
2087
+ try {
2088
+ const events = priorIncognitoEvents ?? (wf.config.voiceOperator
2089
+ ? await computerReplayEvents(cwd, workflowId, wf.config.computerContext?.lastResetAt, wf.config.computerContext?.lastResetSeq)
2090
+ : await replayWorkflowEvents(cwd, workflowId, 0));
2091
+ if (retainLocalFiles || chatMode)
2092
+ priorFiles = projectLocalFileReferences(events, cwd, chatMode);
2093
+ const summary = chatMode ? '' : summarizePriorTurns(events);
2094
+ const rendered = (wf.config.voiceOperator ? renderComputerHistory(events) : renderTranscript(events, { preserveThinking: false, separateFileContext: !chatMode && (wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio'), attachmentOnly: chatMode })).trim();
2095
+ const parts = [];
2096
+ if (summary) {
2097
+ parts.push(`USER: [Workflow context]`);
2098
+ parts.push(`AGENT: ${summary}`);
2099
+ }
2100
+ if (rendered)
2101
+ parts.push(rendered);
2102
+ const combined = parts.join('\n\n').trim();
2103
+ if (combined)
2104
+ primaryAppendSystemPrompt = combined;
2105
+ }
2106
+ catch (err) {
2107
+ console.error(`[arco] [${workflowId.slice(0, 8)}] ${wf.primary.provider} transcript build failed:`, err);
2108
+ }
2026
2109
  }
2027
- else {
2028
- finalAppend = finalAppend ? `${chatPrompt}\n\n${finalAppend}` : chatPrompt;
2110
+ else if (incognito
2111
+ && ((wf.primary.provider === 'claude' && claudeTransport !== 'native')
2112
+ || (wf.primary.provider === 'codex' && codexTransport !== 'appserver'))) {
2113
+ // Incognito CLI turns deliberately have no resumable provider session.
2114
+ // Replay the memory-only completed transcript into each one-shot call.
2115
+ const rendered = renderTranscript(priorIncognitoEvents ?? []).trim();
2116
+ if (rendered)
2117
+ primaryAppendSystemPrompt = `Conversation so far:\n\n${rendered}`;
2029
2118
  }
2030
- }
2031
- if (projectContextEnabled && (wf.primary.provider === 'claude') && cwd) {
2032
- try {
2033
- const claudeMd = await discoverClaudeMdFiles(cwd, { includeProject });
2034
- if (claudeMd) {
2035
- finalAppend = baseWithSkills
2036
- ? `${claudeMd}\n\n${baseWithSkills}`
2037
- : claudeMd;
2119
+ if (chatMode && (incognito || !wf.primarySessionId) && (wf.primary.provider === 'codex' || (wf.primary.provider === 'claude' && claudeTransport !== 'native'))) {
2120
+ try {
2121
+ const events = priorIncognitoEvents ?? await replayWorkflowEvents(cwd, workflowId, 0);
2122
+ priorFiles = projectLocalFileReferences(events, cwd, true);
2123
+ }
2124
+ catch (err) {
2125
+ console.error(`[arco] [${workflowId.slice(0, 8)}] chat attachment replay failed:`, err);
2038
2126
  }
2039
2127
  }
2040
- catch (err) {
2041
- console.warn(`[arco] [${workflowId.slice(0, 8)}] CLAUDE.md discovery failed:`, err);
2128
+ // Local HTTP transports receive stable tool instructions through the
2129
+ // provider system-prompt field; Claude and Codex transports fold them
2130
+ // into their string-form prompt or native request blocks.
2131
+ let claudeMd = null;
2132
+ if (projectContextEnabled && (wf.primary.provider === 'claude') && cwd) {
2133
+ try {
2134
+ claudeMd = (await discoverClaudeMdFiles(cwd, { includeProject })) || null;
2135
+ }
2136
+ catch (err) {
2137
+ console.warn(`[arco] [${workflowId.slice(0, 8)}] CLAUDE.md discovery failed:`, err);
2138
+ }
2042
2139
  }
2043
- }
2044
- // docs/ARCHITECTURE.md - fold the operator-curated knowledge
2045
- // base into appendSystemPrompt as a BOUNDED block. Provider-agnostic
2046
- // (every primary provider that consumes appendSystemPrompt benefits),
2047
- // and only the always-include articles are injected. buildKnowledgeBlock
2048
- // hard-caps the combined body at KNOWLEDGE_INJECT_BUDGET and appends an
2049
- // explicit truncation notice when the set overflows — the KB can NEVER
2050
- // silently bloat the turn. Emitted byte counts land in events.jsonl
2051
- // (system_notice) for the four-question test's context visibility. FENCE:
2052
- // this READS operator-curated articles; nothing here writes the KB.
2053
- if (projectContextEnabled && cwd) {
2054
- try {
2055
- const kb = await buildKnowledgeBlock(cwd);
2056
- if (kb.text) {
2057
- finalAppend = finalAppend ? `${kb.text}\n\n${finalAppend}` : kb.text;
2058
- if (firstIteration) {
2059
- const truncNote = kb.truncated ? ` (truncated — exceeds injection budget)` : '';
2060
- send(ws, {
2061
- type: 'system_notice',
2062
- workflowId,
2063
- content: `Knowledge base: ${kb.included}/${kb.total} always-include article${kb.total === 1 ? '' : 's'} folded into context (${kb.bytes} bytes)${truncNote}.`,
2064
- });
2140
+ // docs/ARCHITECTURE.md - the operator-curated knowledge base, as a
2141
+ // BOUNDED block. Provider-agnostic, only the always-include articles.
2142
+ // buildKnowledgeBlock hard-caps the combined body at
2143
+ // KNOWLEDGE_INJECT_BUDGET and appends a truncation notice when the set
2144
+ // overflows — the KB can NEVER silently bloat the turn. Emitted byte
2145
+ // counts land in events.jsonl (system_notice) for the four-question
2146
+ // test's context visibility. FENCE: this READS operator-curated
2147
+ // articles; nothing here writes the KB.
2148
+ let knowledge = null;
2149
+ if (projectContextEnabled && cwd) {
2150
+ try {
2151
+ const kb = await buildKnowledgeBlock(cwd);
2152
+ if (kb.text) {
2153
+ knowledge = kb.text;
2154
+ if (firstIteration) {
2155
+ const truncNote = kb.truncated ? ` (truncated — exceeds injection budget)` : '';
2156
+ send(ws, {
2157
+ type: 'system_notice',
2158
+ workflowId,
2159
+ content: `Knowledge base: ${kb.included}/${kb.total} always-include article${kb.total === 1 ? '' : 's'} folded into context (${kb.bytes} bytes)${truncNote}.`,
2160
+ });
2161
+ }
2065
2162
  }
2066
2163
  }
2164
+ catch (err) {
2165
+ console.warn(`[arco] [${workflowId.slice(0, 8)}] knowledge-base injection failed:`, err);
2166
+ }
2067
2167
  }
2068
- catch (err) {
2069
- console.warn(`[arco] [${workflowId.slice(0, 8)}] knowledge-base injection failed:`, err);
2070
- }
2071
- }
2072
- // Operator-initiated plan-mode entry. Resolved per turn from the
2073
- // pending flag the `enter_plan_mode_request` handler set. Only Claude
2074
- // Native honours arming; on any other resolved transport the flag is
2075
- // silently cleared so a stale arm doesn't survive a provider switch.
2076
- // docs/PROVIDERS.md - per-turn text for Claude Native
2077
- // rides WorkerConfig.turnNotice (appended to the user message, kept
2078
- // forever) instead of appendSystemPrompt, which the Native worker now
2079
- // freezes; a firstIteration-gated fold there flipped the system prompt
2080
- // between consecutive requests of an auto-continued turn.
2081
- const nativeClaudeTurn = wf.primary.provider === 'claude' && claudeTransport === 'native';
2082
- const turnNoticeParts = [];
2083
- let armPlanMode = false;
2084
- if (wf.pendingPlanModeEntry) {
2085
- if (nativeClaudeTurn && firstIteration) {
2086
- armPlanMode = true;
2087
- turnNoticeParts.push('Operator has armed plan mode for this turn. Write/Edit tools are disabled until you call ExitPlanMode. Begin by calling EnterPlanMode with a plan body for what the operator just asked.');
2088
- }
2089
- wf.pendingPlanModeEntry = false;
2090
- }
2091
- // docs/PROTOCOL_CLUSTER.md - fold the drained mailbox prologue
2092
- // into the front of appendSystemPrompt so a CLI / Codex worker renders
2093
- // it as system-level context before any operator-supplied
2094
- // appendSystemPrompt content. Only first-iteration (drain ran above only
2095
- // on firstIteration); follow-up drains skip. Native takes it as a
2096
- // turnNotice instead (see above).
2097
- if (peerMessagesPrologue) {
2098
- if (nativeClaudeTurn)
2099
- turnNoticeParts.push(peerMessagesPrologue);
2100
- else
2101
- finalAppend = finalAppend ? `${peerMessagesPrologue}\n\n${finalAppend}` : peerMessagesPrologue;
2102
- }
2103
- // docs/PROTOCOL_CLUSTER.md - resolve the workflow's clusterId
2104
- // (if any) at turn start. Threaded into the worker's WorkerConfig so
2105
- // peer tools register and dispatch only when the membership is live.
2106
- // Per plan §6.2 reversibility: once the cluster is deleted via REST,
2107
- // the next turn's lookup returns undefined and the tools disappear
2108
- // from the worker's tool list.
2109
- const turnClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
2110
- // Phase 2.6 — resolve the cluster's shared plan body + this member's
2111
- // role hint at turn start. Both ride into WorkerConfig so the Native
2112
- // worker's buildSystemBlocks() can inject them as forced system blocks
2113
- // (after FORCED_FIRST_BLOCK, before operator prompts). Editing the
2114
- // plan mid-turn never tears the running turn down — only the NEXT
2115
- // turn's resolution picks up the new body.
2116
- let turnClusterPlan;
2117
- let turnClusterRole;
2118
- // per-cluster efficiency doctrine + level. The doctrine
2119
- // (canned restraint text for the level + optional operator addendum)
2120
- // injects alongside plan/role; the level itself also drives the
2121
- // peer-mailbox notice variant below. Resolved at turn start so an
2122
- // operator level-change lands on the NEXT turn (in-flight turns are
2123
- // untouched). Legacy omitted styles remain Thorough; guards resolve
2124
- // independently and are included even for mailbox-only members.
2125
- let turnClusterEfficiencyDoctrine = turnClusterId ? buildMessageGuardPolicy(clusterStore.getMessageGuard(turnClusterId)) : undefined;
2126
- let turnClusterEfficiencyLevel = 'thorough';
2127
- let turnClusterTaskBoardAttached = false;
2128
- // per-cluster progress-tracking doctrine. Built from the
2129
- // cluster's mode (plan/board/both, default both) gated on whether a plan
2130
- // body and/or a task board actually exist for this turn. Injected
2131
- // alongside the efficiency doctrine. Resolved at turn start so an operator
2132
- // mode-change lands on the NEXT turn (in-flight turns untouched). Undefined
2133
- // when there is nothing to keep current (e.g. mode 'plan' but no plan).
2134
- let turnClusterProgressDoctrine;
2135
- if (turnClusterId && clusterAccessMode === 'standard') {
2136
- const planRec = await clusterPlanBridge.readClusterPlan(turnClusterId).catch(() => null);
2137
- turnClusterPlan = planRec?.body;
2138
- // Plan reference docs ride as one trailing heading line — a heading so
2139
- // the outline fallback (clusterPlanOutline keeps every heading) can't
2140
- // drop it, and slugs only so it stays small. Members read a ref with
2141
- // plan_ref_read or plain file tools.
2142
- const refsCwd = wf.config.workingDirectory;
2143
- if (planRec && turnClusterPlan && refsCwd) {
2144
- const refs = await listPlanRefs(refsCwd, planRec.planId).catch(() => []);
2145
- if (refs.length > 0) {
2146
- turnClusterPlan = `${turnClusterPlan.trimEnd()}\n\n#### Plan reference docs (planId ${planRec.planId}) — ${refsDoctrine(planRec.planId, refs.map((r) => r.slug), 24)}\n`;
2168
+ // turnPrompt.ts — skills, the Chat or Computer preamble, CLAUDE.md and
2169
+ // the knowledge base, in the order the model sees them.
2170
+ let { systemPrompt: finalSystemPrompt, appendSystemPrompt: finalAppend } = composeBasePrompts({
2171
+ provider: wf.primary.provider,
2172
+ chatMode,
2173
+ computerChat: wf.config.voiceOperator === true,
2174
+ chatWeb,
2175
+ systemPrompt: primarySystemPrompt,
2176
+ appendSystemPrompt: primaryAppendSystemPrompt,
2177
+ pinnedSkills: pinnedSkillsBlock,
2178
+ skillsManifest: primarySkillsManifest,
2179
+ claudeMd,
2180
+ knowledge,
2181
+ });
2182
+ // Operator-initiated plan-mode entry. Resolved per turn from the
2183
+ // pending flag the `enter_plan_mode_request` handler set. Only Claude
2184
+ // Native honours arming; on any other resolved transport the flag is
2185
+ // silently cleared so a stale arm doesn't survive a provider switch.
2186
+ // docs/PROVIDERS.md - per-turn text for Claude Native
2187
+ // rides WorkerConfig.turnNotice (appended to the user message, kept
2188
+ // forever) instead of appendSystemPrompt, which the Native worker now
2189
+ // freezes; a firstIteration-gated fold there flipped the system prompt
2190
+ // between consecutive requests of an auto-continued turn.
2191
+ const nativeClaudeTurn = wf.primary.provider === 'claude' && claudeTransport === 'native';
2192
+ const turnNoticeParts = [];
2193
+ let armPlanMode = false;
2194
+ if (wf.pendingPlanModeEntry) {
2195
+ if (nativeClaudeTurn && firstIteration) {
2196
+ armPlanMode = true;
2197
+ turnNoticeParts.push('Operator has armed plan mode for this turn. Write/Edit tools are disabled until you call ExitPlanMode. Begin by calling EnterPlanMode with a plan body for what the operator just asked.');
2147
2198
  }
2199
+ wf.pendingPlanModeEntry = false;
2148
2200
  }
2149
- turnClusterRole = clusterStore.getMemberRole(turnClusterId, workflowId);
2150
- turnClusterTaskBoardAttached = clusterStore.isTaskBoardAttached(turnClusterId);
2151
- turnClusterEfficiencyLevel = clusterStore.getEfficiencyLevel(turnClusterId);
2152
- turnClusterEfficiencyDoctrine = clusterEfficiency.buildDoctrine(turnClusterEfficiencyLevel, clusterStore.getEfficiencyAddendum(turnClusterId), turnClusterRole, clusterStore.getMessageGuard(turnClusterId));
2153
- turnClusterProgressDoctrine = joinClusterDoctrines(buildClusterDirectorDoctrine(turnClusterRole), buildProgressDoctrine(clusterStore.getProgressTracking(turnClusterId), !!turnClusterPlan && turnClusterPlan.trim().length > 0, turnClusterTaskBoardAttached));
2154
- }
2155
- if (turnClusterId && (wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp')) {
2156
- if (clusterAccessMode === 'standard') {
2157
- finalSystemPrompt = buildLocalClusterSystemPrompt({
2158
- base: finalSystemPrompt,
2159
- clusterPlan: turnClusterPlan,
2160
- clusterRole: turnClusterRole,
2161
- clusterEfficiencyDoctrine: turnClusterEfficiencyDoctrine,
2162
- clusterProgressDoctrine: turnClusterProgressDoctrine,
2163
- });
2201
+ // docs/PROTOCOL_CLUSTER.md - fold the drained mailbox prologue
2202
+ // into the front of appendSystemPrompt so a CLI / Codex worker renders
2203
+ // it as system-level context before any operator-supplied
2204
+ // appendSystemPrompt content. Only first-iteration (drain ran above only
2205
+ // on firstIteration); follow-up drains skip. Native takes it as a
2206
+ // turnNotice instead (see above).
2207
+ if (peerMessagesPrologue) {
2208
+ if (nativeClaudeTurn)
2209
+ turnNoticeParts.push(peerMessagesPrologue);
2210
+ else
2211
+ finalAppend = finalAppend ? `${peerMessagesPrologue}\n\n${finalAppend}` : peerMessagesPrologue;
2164
2212
  }
2165
- else {
2166
- finalSystemPrompt = finalSystemPrompt
2167
- ? `${BLIND_CLUSTER_DOCTRINE}\n\n${turnClusterEfficiencyDoctrine}\n\n${finalSystemPrompt}`
2168
- : `${BLIND_CLUSTER_DOCTRINE}\n\n${turnClusterEfficiencyDoctrine}`;
2213
+ // docs/PROTOCOL_CLUSTER.md - resolve the workflow's clusterId
2214
+ // (if any) at turn start. Threaded into the worker's WorkerConfig so
2215
+ // peer tools register and dispatch only when the membership is live.
2216
+ // Per plan §6.2 reversibility: once the cluster is deleted via REST,
2217
+ // the next turn's lookup returns undefined and the tools disappear
2218
+ // from the worker's tool list.
2219
+ const turnClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
2220
+ primaryTurn.clusterDispatch = { clusterId: turnClusterId };
2221
+ // Phase 2.6 — resolve the cluster's shared plan body + this member's
2222
+ // role hint at turn start. Both ride into WorkerConfig so the Native
2223
+ // worker's buildSystemBlocks() can inject them as forced system blocks
2224
+ // (after FORCED_FIRST_BLOCK, before operator prompts). Editing the
2225
+ // plan mid-turn never tears the running turn down — only the NEXT
2226
+ // turn's resolution picks up the new body.
2227
+ let turnClusterPlan;
2228
+ let turnClusterRole;
2229
+ // per-cluster efficiency doctrine + level. The doctrine
2230
+ // (canned restraint text for the level + optional operator addendum)
2231
+ // injects alongside plan/role; the level itself also drives the
2232
+ // peer-mailbox notice variant below. Resolved at turn start so an
2233
+ // operator level-change lands on the NEXT turn (in-flight turns are
2234
+ // untouched). Legacy omitted styles remain Thorough; guards resolve
2235
+ // independently and are included even for mailbox-only members.
2236
+ let turnClusterEfficiencyDoctrine = turnClusterId ? buildMessageGuardPolicy(clusterStore.getMessageGuard(turnClusterId)) : undefined;
2237
+ let turnClusterEfficiencyLevel = 'thorough';
2238
+ let turnClusterTaskBoardAttached = false;
2239
+ // per-cluster progress-tracking doctrine. Built from the
2240
+ // cluster's mode (plan/board/both, default both) gated on whether a plan
2241
+ // body and/or a task board actually exist for this turn. Injected
2242
+ // alongside the efficiency doctrine. Resolved at turn start so an operator
2243
+ // mode-change lands on the NEXT turn (in-flight turns untouched). Undefined
2244
+ // when there is nothing to keep current (e.g. mode 'plan' but no plan).
2245
+ let turnClusterProgressDoctrine;
2246
+ if (turnClusterId && clusterAccessMode === 'standard') {
2247
+ const planRec = await clusterPlanBridge.readClusterPlan(turnClusterId).catch(() => null);
2248
+ turnClusterPlan = planRec?.body;
2249
+ // Plan reference docs ride as one trailing heading line — a heading so
2250
+ // the outline fallback (clusterPlanOutline keeps every heading) can't
2251
+ // drop it, and slugs only so it stays small. Members read a ref with
2252
+ // plan_ref_read or plain file tools.
2253
+ const refsCwd = wf.config.workingDirectory;
2254
+ if (planRec && turnClusterPlan && refsCwd) {
2255
+ const refs = await listPlanRefs(refsCwd, planRec.planId).catch(() => []);
2256
+ if (refs.length > 0) {
2257
+ turnClusterPlan = `${turnClusterPlan.trimEnd()}\n\n#### Plan reference docs (planId ${planRec.planId}) — ${refsDoctrine(planRec.planId, refs.map((r) => r.slug), 24)}\n`;
2258
+ }
2259
+ }
2260
+ turnClusterRole = clusterStore.getMemberRole(turnClusterId, workflowId);
2261
+ turnClusterTaskBoardAttached = clusterStore.isTaskBoardAttached(turnClusterId);
2262
+ turnClusterEfficiencyLevel = clusterStore.getEfficiencyLevel(turnClusterId);
2263
+ turnClusterEfficiencyDoctrine = clusterEfficiency.buildDoctrine(turnClusterEfficiencyLevel, clusterStore.getEfficiencyAddendum(turnClusterId), turnClusterRole, clusterStore.getMessageGuard(turnClusterId));
2264
+ turnClusterProgressDoctrine = joinClusterDoctrines(buildClusterDirectorDoctrine(turnClusterRole), buildProgressDoctrine(clusterStore.getProgressTracking(turnClusterId), !!turnClusterPlan && turnClusterPlan.trim().length > 0, turnClusterTaskBoardAttached));
2169
2265
  }
2170
- }
2171
- // docs/PROTOCOL_CLUSTER.md - non-Native cluster member
2172
- // wiring. Native dispatches peer_* in-process via peerTools (clusterId
2173
- // on WorkerConfig is sufficient, and buildSystemBlocks injects plan +
2174
- // role as forced system blocks). CLI Claude / Codex `exec` / Codex
2175
- // `appserver` all reach the model via a string-form prompt, so the
2176
- // plan + role have to fold into `finalAppend` (which becomes
2177
- // `--append-system-prompt` for Claude CLI and the byte-stable prefix
2178
- // for both Codex transports). Order (peer prologue → plan → role)
2179
- // matches Native's buildSystemBlocks ordering.
2180
- //
2181
- // For Claude CLI: also write the per-workflow mcp-config.json so the
2182
- // claude CLI's `--mcp-config <path>` spawns the per-turn MCP stdio
2183
- // child. For Codex: nothing to write — the codex provider builds
2184
- // `-c mcp_servers.arco-cluster.*` TOML overrides at spawn time
2185
- // from `WorkerConfig.clusterId` (Phase 4 §13 decision: Codex CLI has
2186
- // no `--mcp-config <path>` flag, but `-c` overrides leave the
2187
- // operator's `~/.codex/config.toml` untouched and avoid TOML merge).
2188
- //
2189
- // CLI transports retain the 16 KB cap: argv paths E2BIG above roughly
2190
- // 128 KB and the tmpfile fallback handles arbitrary sizes, while the
2191
- // explicit bound surfaces unreasonable growth early. Codex app-server
2192
- // uses 48 KB because it rides JSON-RPC stdin and needs room for the
2193
- // maximum 32 KB plan plus small blocks. The PLAN is the only block that
2194
- // shrinks to fit
2195
- // (composeClusterAppend) — the small blocks are load-bearing and
2196
- // survive verbatim.
2197
- let turnClusterMcpConfigPath;
2198
- const needsStringFormCluster = turnClusterId !== undefined &&
2199
- ((wf.primary.provider === 'claude' && claudeTransport === 'cli') ||
2200
- wf.primary.provider === 'codex' || wf.primary.provider === 'cursor');
2201
- if (needsStringFormCluster) {
2202
- // Small load-bearing blocks first — composeClusterAppend reserves
2203
- // their bytes (plus whatever already folded into finalAppend, i.e.
2204
- // the peer-mailbox notice) and truncates the PLAN to the remaining
2205
- // budget. This prevents a large plan from evicting the notice, role
2206
- // and code-mode guidance. See clusterStringFold.ts.
2207
- const tailBlocks = [];
2208
- if (clusterAccessMode !== 'standard') {
2209
- tailBlocks.push(clusterAccessMode === 'isolated'
2210
- ? 'ISOLATED cluster member: the project and cluster coordination state are intentionally hidden. Use only peer_send and peer_read for cluster communication.'
2211
- : BLIND_CLUSTER_DOCTRINE);
2266
+ if (turnClusterId && (wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek')) {
2267
+ if (clusterAccessMode === 'standard') {
2268
+ finalSystemPrompt = buildLocalClusterSystemPrompt({
2269
+ base: finalSystemPrompt,
2270
+ clusterPlan: turnClusterPlan,
2271
+ clusterRole: turnClusterRole,
2272
+ clusterEfficiencyDoctrine: turnClusterEfficiencyDoctrine,
2273
+ clusterProgressDoctrine: turnClusterProgressDoctrine,
2274
+ });
2275
+ }
2276
+ else {
2277
+ finalSystemPrompt = finalSystemPrompt
2278
+ ? `${BLIND_CLUSTER_DOCTRINE}\n\n${turnClusterEfficiencyDoctrine}\n\n${finalSystemPrompt}`
2279
+ : `${BLIND_CLUSTER_DOCTRINE}\n\n${turnClusterEfficiencyDoctrine}`;
2280
+ }
2212
2281
  }
2213
- if (turnClusterRole && turnClusterRole.length > 0) {
2214
- tailBlocks.push(`Your role in this cluster: ${turnClusterRole}`);
2282
+ // docs/PROTOCOL_CLUSTER.md - non-Native cluster member
2283
+ // wiring. Native dispatches peer_* in-process via peerTools (clusterId
2284
+ // on WorkerConfig is sufficient, and buildSystemBlocks injects plan +
2285
+ // role as forced system blocks). CLI Claude / Codex `exec` / Codex
2286
+ // `appserver` all reach the model via a string-form prompt, so the
2287
+ // plan + role have to fold into `finalAppend` (which becomes
2288
+ // `--append-system-prompt` for Claude CLI and the byte-stable prefix
2289
+ // for both Codex transports). Order (peer prologue → plan → role)
2290
+ // matches Native's buildSystemBlocks ordering.
2291
+ //
2292
+ // For Claude CLI: also write the per-workflow mcp-config.json so the
2293
+ // claude CLI's `--mcp-config <path>` spawns the per-turn MCP stdio
2294
+ // child. For Codex: nothing to write — the codex provider builds
2295
+ // `-c mcp_servers.arco-cluster.*` TOML overrides at spawn time
2296
+ // from `WorkerConfig.clusterId` (Phase 4 §13 decision: Codex CLI has
2297
+ // no `--mcp-config <path>` flag, but `-c` overrides leave the
2298
+ // operator's `~/.codex/config.toml` untouched and avoid TOML merge).
2299
+ //
2300
+ // CLI transports retain the 16 KB cap: argv paths E2BIG above roughly
2301
+ // 128 KB and the tmpfile fallback handles arbitrary sizes, while the
2302
+ // explicit bound surfaces unreasonable growth early. Codex app-server
2303
+ // uses 48 KB because it rides JSON-RPC stdin and needs room for the
2304
+ // maximum 32 KB plan plus small blocks. The PLAN is the only block that
2305
+ // shrinks to fit
2306
+ // (composeClusterAppend) — the small blocks are load-bearing and
2307
+ // survive verbatim.
2308
+ let turnClusterMcpConfigPath;
2309
+ const needsStringFormCluster = turnClusterId !== undefined &&
2310
+ ((wf.primary.provider === 'claude' && claudeTransport === 'cli') ||
2311
+ wf.primary.provider === 'codex' || wf.primary.provider === 'cursor');
2312
+ if (needsStringFormCluster) {
2313
+ // Small load-bearing blocks first — composeClusterAppend reserves
2314
+ // their bytes (plus whatever already folded into finalAppend, i.e.
2315
+ // the peer-mailbox notice) and truncates the PLAN to the remaining
2316
+ // budget. This prevents a large plan from evicting the notice, role
2317
+ // and code-mode guidance. See clusterStringFold.ts.
2318
+ const tailBlocks = [];
2319
+ if (clusterAccessMode !== 'standard') {
2320
+ tailBlocks.push(clusterAccessMode === 'isolated'
2321
+ ? 'ISOLATED cluster member: the project and cluster coordination state are intentionally hidden. Use only peer_send and peer_read for cluster communication.'
2322
+ : BLIND_CLUSTER_DOCTRINE);
2323
+ }
2324
+ if (turnClusterRole && turnClusterRole.length > 0) {
2325
+ tailBlocks.push(`Your role in this cluster: ${turnClusterRole}`);
2326
+ }
2327
+ // docs/CODEX_GPT56_CLUSTER_INCOMPAT.md — code-mode models run
2328
+ // OpenAI's own multi-agent "code mode" harness, which renames the
2329
+ // arco-cluster MCP tools into the exec code cell's `tools`
2330
+ // namespace (`tools.mcp__arco_cluster__peer_send`) and gives the
2331
+ // harness's native send_message top billing. Without this addendum
2332
+ // a code-mode member cannot find the peer substrate. Detection is
2333
+ // catalog-driven (codex's own models_cache.json `tool_mode` /
2334
+ // `multi_agent_version` — the exact fields that gate the harness);
2335
+ // fail-open on unknown because the addendum is phrased
2336
+ // conditionally and reads as inapplicable to plain
2337
+ if (wf.primary.provider === 'codex'
2338
+ && codexModelUsesCodeMode(wf.primary.model, providerAccount?.codexHome) !== false) {
2339
+ tailBlocks.push(codexCodeModeClusterAddendum());
2340
+ }
2341
+ if (turnClusterEfficiencyDoctrine && turnClusterEfficiencyDoctrine.length > 0) {
2342
+ tailBlocks.push(turnClusterEfficiencyDoctrine);
2343
+ }
2344
+ if (turnClusterProgressDoctrine && turnClusterProgressDoctrine.length > 0) {
2345
+ tailBlocks.push(turnClusterProgressDoctrine);
2346
+ }
2347
+ const planBlock = turnClusterPlan && turnClusterPlan.length > 0
2348
+ ? `--- Shared cluster plan ---\n${turnClusterPlan}`
2349
+ : undefined;
2350
+ // Outline fallback: when the full plan overflows the budget, fold a
2351
+ // deterministic outline (headings + every checkbox line verbatim +
2352
+ // labelled standing-directive sections) instead of a head-slice — the
2353
+ // actionable skeleton survives whole and omitted prose is one
2354
+ // cluster_plan_read call away.
2355
+ const planFallback = turnClusterPlan && turnClusterPlan.length > 0
2356
+ ? `--- Shared cluster plan (OUTLINE — prose omitted; call cluster_plan_read for the full plan) ---\n${planOutline(turnClusterPlan)}`
2357
+ : undefined;
2358
+ const clusterAppendCap = wf.primary.provider === 'codex' && codexTransport === 'appserver'
2359
+ ? CODEX_APP_SERVER_CLUSTER_MAX
2360
+ : APPEND_CLUSTER_MAX;
2361
+ const { combined, planTruncatedFrom, usedFallback } = composeClusterAppend(planBlock, tailBlocks, finalAppend?.length ?? 0, clusterAppendCap, planFallback);
2362
+ if (planTruncatedFrom !== undefined) {
2363
+ console.log(`[arco] [${workflowId.slice(0, 8)}] cluster plan over string-form fold budget ` +
2364
+ `(${planTruncatedFrom} bytes → ${usedFallback ? 'outline fallback' : 'head-truncated'}; ` +
2365
+ `${clusterAppendCap} total cap; notice/role/addendum/doctrines preserved)`);
2366
+ }
2367
+ if (combined) {
2368
+ finalAppend = finalAppend ? `${combined}\n\n${finalAppend}` : combined;
2369
+ }
2215
2370
  }
2216
- // docs/CODEX_GPT56_CLUSTER_INCOMPAT.md — code-mode models run
2217
- // OpenAI's own multi-agent "code mode" harness, which renames the
2218
- // arco-cluster MCP tools into the exec code cell's `tools`
2219
- // namespace (`tools.mcp__arco_cluster__peer_send`) and gives the
2220
- // harness's native send_message top billing. Without this addendum
2221
- // a code-mode member cannot find the peer substrate. Detection is
2222
- // catalog-driven (codex's own models_cache.json `tool_mode` /
2223
- // `multi_agent_version` — the exact fields that gate the harness);
2224
- // fail-open on unknown because the addendum is phrased
2225
- // conditionally and reads as inapplicable to plain
2226
- if (wf.primary.provider === 'codex'
2227
- && codexModelUsesCodeMode(wf.primary.model, providerAccount?.codexHome) !== false) {
2228
- tailBlocks.push(codexCodeModeClusterAddendum());
2371
+ const genesisSeed = wf.config.genesisSeed;
2372
+ // Separator-agnostic scratch-dir check (POSIX primary; tolerate Windows).
2373
+ const inGenesisScratch = !!genesisSeed && /[\\/]\.arco[\\/]genesis[\\/]/.test(cwd);
2374
+ // M3 Creative mode runs the same staged framing inside an EXISTING workflow
2375
+ // (real cwd) — gated on the operator-armed seed.creative flag instead of the
2376
+ // scratch-dir path. buildGenesisSystemBlock folds in seed.projectContext for
2377
+ // this case so the model stays anchored to what is really on disk.
2378
+ const inGenesisCreative = !!genesisSeed && genesisSeed.creative === true;
2379
+ if ((inGenesisScratch || inGenesisCreative || genesisSeed?.planOnly) && genesisSeed) {
2380
+ if (wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek')) {
2381
+ finalSystemPrompt = buildGenesisSystemBlock(genesisSeed, { base: finalSystemPrompt });
2382
+ }
2383
+ else {
2384
+ const genesisBlock = buildGenesisSystemBlock(genesisSeed);
2385
+ finalAppend = finalAppend ? `${genesisBlock}\n\n${finalAppend}` : genesisBlock;
2386
+ }
2229
2387
  }
2230
- if (turnClusterEfficiencyDoctrine && turnClusterEfficiencyDoctrine.length > 0) {
2231
- tailBlocks.push(turnClusterEfficiencyDoctrine);
2388
+ if (genesisSeed?.github?.create && genesisSeed.github.visibility === 'public') {
2389
+ if (wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek')) {
2390
+ finalSystemPrompt = finalSystemPrompt
2391
+ ? `${PUBLIC_REPO_SAFETY_SYSTEM_BLOCK}\n\n${finalSystemPrompt}`
2392
+ : PUBLIC_REPO_SAFETY_SYSTEM_BLOCK;
2393
+ }
2394
+ else {
2395
+ finalAppend = finalAppend
2396
+ ? `${PUBLIC_REPO_SAFETY_SYSTEM_BLOCK}\n\n${finalAppend}`
2397
+ : PUBLIC_REPO_SAFETY_SYSTEM_BLOCK;
2398
+ }
2232
2399
  }
2233
- if (turnClusterProgressDoctrine && turnClusterProgressDoctrine.length > 0) {
2234
- tailBlocks.push(turnClusterProgressDoctrine);
2400
+ // docs/GOTCHAS.md - the north-star is NOT folded here. Native
2401
+ // injects it as its own cached system block (buildSystemBlocks reads
2402
+ // config.goal); every other transport folds goalBlock(config.goal) inside
2403
+ // its own provider (mirroring outputStyleAddendum). Doing it per-provider
2404
+ // rather than into finalAppend here is load-bearing: reviewers spawn via
2405
+ // manager.spawn and handoff seeds via runPrimaryTurn — both bypass this
2406
+ // operator-turn assembly but still carry config.goal, so the provider fold
2407
+ // is the one place that covers operator turns AND primitive seeds without
2408
+ // double-injecting.
2409
+ // docs/ARCHITECTURE.md - resolve the operator-enabled-and-allowed
2410
+ // registry MCP servers for this workflow from the global registry + the
2411
+ // workflow's per-tab allowlist (meta.mcpAllow). Produces BOTH the merged
2412
+ // server entries (for the mcp-config write / Codex `-c` overrides) AND
2413
+ // the dangerous-and-unticked `--disallowedTools` set for CLI Claude.
2414
+ // This is the ONLY model-exposed expansion besides cluster /
2415
+ // codebase-memory — no hidden, model-selected servers.
2416
+ let turnRegistryServers = [];
2417
+ let turnMcpDisallowedTools = [];
2418
+ if (projectContextEnabled)
2419
+ try {
2420
+ const metaForMcp = await readMeta(cwd, workflowId);
2421
+ const wiring = await resolveRegistryWiring(metaForMcp?.mcpAllow ?? []);
2422
+ turnRegistryServers = wiring.registryServers;
2423
+ turnMcpDisallowedTools = wiring.disallowedTools;
2424
+ }
2425
+ catch (err) {
2426
+ console.error(`[arco] [${workflowId.slice(0, 8)}] mcp registry resolve failed:`, err);
2427
+ }
2428
+ // docs/PROVIDERS.md - write `.arco/<wfid>/mcp-config.json`
2429
+ // for CLI Claude turns when cluster membership, the operator-attached
2430
+ // codebase-memory entry, OR §E1 registry servers apply. All coexist; the
2431
+ // writer merges deterministically and unlinks when none apply. Codex
2432
+ // transports don't use --mcp-config — they layer the same registrations
2433
+ // on via `-c mcp_servers.*` TOML overrides built in the codex provider.
2434
+ if (projectContextEnabled && wf.primary.provider === 'claude' && claudeTransport === 'cli') {
2435
+ const cbm = wf.config.codebaseMemory;
2436
+ const wantsCodebaseMemory = projectContextEnabled && cbm?.attached === true;
2437
+ // The workflow-scoped `arco` plan entry applies to EVERY workflow, so
2438
+ // the config is now written unconditionally (cwd is the only
2439
+ // precondition) rather than only when a cluster / codebase-memory /
2440
+ // registry entry applies.
2441
+ {
2442
+ try {
2443
+ turnClusterMcpConfigPath = await mcpConfigWriter.writeFor(cwd, workflowId, {
2444
+ planToolsCwd: cwd,
2445
+ handoffHistoryToken: !wf.primary.tools || wf.primary.tools.includes('handoff_history')
2446
+ ? await mintHandoffHistoryCapability(workflowId) : undefined,
2447
+ clusterId: turnClusterId,
2448
+ taskBoardAttached: turnClusterTaskBoardAttached,
2449
+ accessMode: clusterAccessMode,
2450
+ port: PORT,
2451
+ codebaseMemoryIndexPath: wantsCodebaseMemory
2452
+ ? (cbm?.indexPath || cwd)
2453
+ : undefined,
2454
+ registryServers: turnRegistryServers,
2455
+ });
2456
+ }
2457
+ catch (err) {
2458
+ console.error(`[arco] [${workflowId.slice(0, 8)}] mcp-config write failed:`, err);
2459
+ }
2460
+ }
2235
2461
  }
2236
- const planBlock = turnClusterPlan && turnClusterPlan.length > 0
2237
- ? `--- Shared cluster plan ---\n${turnClusterPlan}`
2238
- : undefined;
2239
- // Outline fallback: when the full plan overflows the budget, fold a
2240
- // deterministic outline (headings + every checkbox line verbatim +
2241
- // labelled standing-directive sections) instead of a head-slice — the
2242
- // actionable skeleton survives whole and omitted prose is one
2243
- // cluster_plan_read call away.
2244
- const planFallback = turnClusterPlan && turnClusterPlan.length > 0
2245
- ? `--- Shared cluster plan (OUTLINE — prose omitted; call cluster_plan_read for the full plan) ---\n${planOutline(turnClusterPlan)}`
2246
- : undefined;
2247
- const clusterAppendCap = wf.primary.provider === 'codex' && codexTransport === 'appserver'
2248
- ? CODEX_APP_SERVER_CLUSTER_MAX
2249
- : APPEND_CLUSTER_MAX;
2250
- const { combined, planTruncatedFrom, usedFallback } = composeClusterAppend(planBlock, tailBlocks, finalAppend?.length ?? 0, clusterAppendCap, planFallback);
2251
- if (planTruncatedFrom !== undefined) {
2252
- console.log(`[arco] [${workflowId.slice(0, 8)}] cluster plan over string-form fold budget ` +
2253
- `(${planTruncatedFrom} bytes → ${usedFallback ? 'outline fallback' : 'head-truncated'}; ` +
2254
- `${clusterAppendCap} total cap; notice/role/addendum/doctrines preserved)`);
2462
+ // Workbench Expansion A2 — shadow-git checkpoint. Snapshot the working
2463
+ // tree BEFORE the turn that may mutate files so the operator can
2464
+ // undo-the-agent independent of their real git history. Skipped when
2465
+ // plan mode is armed (the turn is read-only until ExitPlanMode, so
2466
+ // there's nothing to checkpoint). Wait at most two seconds; a slow or
2467
+ // failed capture is omitted and the turn proceeds without a summary.
2468
+ //
2469
+ // Hooked HERE rather than in seedWorker.ts (the plan's guess): runtime
2470
+ // verification showed runPrimaryTurn is shared by reviewers, handoff
2471
+ // seeds, exportContext, and Task children — none of which should snapshot
2472
+ // the operator's tree. The operator-turn loop in turnEngine.handleUserMessage
2473
+ // is the only dispatch path that runs an operator-driven, file-mutating
2474
+ // turn, so the checkpoint belongs at this call site. The ref suffix uses
2475
+ // the workflow's current event seq (the turn it guards), carried as
2476
+ // `checkpointSeq`; the checkpoint_created event gets its own next seq.
2477
+ // Upload-time image downscaling runs in the background; a send right
2478
+ // after a paste can beat it. Wait (bounded) here so the sync providers
2479
+ // (Claude CLI / Native, Codex exec) read the model copy too — they call
2480
+ // the sync modelImagePath() and can't wait themselves.
2481
+ if (promptAttachments && promptAttachments.length > 0)
2482
+ await awaitModelImages(promptAttachments);
2483
+ // STOP landed during the pre-spawn awaits above (killAll had nothing to
2484
+ // kill yet). Spawning now would run a turn nobody owns.
2485
+ if (!ownsBusy(wf, busyToken))
2486
+ break;
2487
+ if (wf.queue.steering.some((q) => q.interrupt)) {
2488
+ firstIteration = false;
2489
+ loadQueuedPrompt(primaryTurn.holdSteer);
2490
+ continue;
2255
2491
  }
2256
- if (combined) {
2257
- finalAppend = finalAppend ? `${combined}\n\n${finalAppend}` : combined;
2492
+ let checkpointSkipNoticeSent = false;
2493
+ const onCheckpointSkipped = (content) => {
2494
+ if (checkpointSkipNoticeSent || workflows.get(workflowId) !== wf)
2495
+ return;
2496
+ checkpointSkipNoticeSent = true;
2497
+ broadcastWorkflow(workflowId, { type: 'system_notice', workflowId, content });
2498
+ };
2499
+ let checkpoint = null;
2500
+ let checkpointGuardSeq;
2501
+ if (!(firstIteration && primitive === 'plan-review') && shouldCaptureTurn({ chatMode, planMode: armPlanMode, isolated: isolatedMember, provider: wf.primary.provider, tools: wf.primary.tools })) {
2502
+ checkpointGuardSeq = currentWorkflowSeq(cwd, workflowId);
2503
+ activeTurnObservation = observeCheckoutWriters(workflowWritePaths(wf), wf.manager);
2504
+ checkpoint = await timelyCheckpoint((deps.captureCheckpoint ?? createCheckpoint)({ cwd, workflowId, seq: checkpointGuardSeq, onSkipped: onCheckpointSkipped }));
2505
+ if (!checkpoint || !ownsBusy(wf, busyToken)) {
2506
+ activeTurnObservation.stop();
2507
+ activeTurnObservation = undefined;
2508
+ checkpoint = null;
2509
+ }
2258
2510
  }
2259
- }
2260
- const genesisSeed = wf.config.genesisSeed;
2261
- // Separator-agnostic scratch-dir check (POSIX primary; tolerate Windows).
2262
- const inGenesisScratch = !!genesisSeed && /[\\/]\.arco[\\/]genesis[\\/]/.test(cwd);
2263
- // M3 Creative mode runs the same staged framing inside an EXISTING workflow
2264
- // (real cwd) — gated on the operator-armed seed.creative flag instead of the
2265
- // scratch-dir path. buildGenesisSystemBlock folds in seed.projectContext for
2266
- // this case so the model stays anchored to what is really on disk.
2267
- const inGenesisCreative = !!genesisSeed && genesisSeed.creative === true;
2268
- if ((inGenesisScratch || inGenesisCreative) && genesisSeed) {
2269
- if (wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek')) {
2270
- finalSystemPrompt = buildGenesisSystemBlock(genesisSeed, { base: finalSystemPrompt });
2511
+ // STOP or an interrupt during capture must never launch the stale prompt.
2512
+ if (!ownsBusy(wf, busyToken))
2513
+ break;
2514
+ if (wf.queue.steering.some((q) => q.interrupt)) {
2515
+ activeTurnObservation?.stop();
2516
+ activeTurnObservation = undefined;
2517
+ firstIteration = false;
2518
+ loadQueuedPrompt(primaryTurn.holdSteer);
2519
+ continue;
2271
2520
  }
2272
- else {
2273
- const genesisBlock = buildGenesisSystemBlock(genesisSeed);
2274
- finalAppend = finalAppend ? `${genesisBlock}\n\n${finalAppend}` : genesisBlock;
2521
+ if (checkpoint && checkpointGuardSeq !== undefined) {
2522
+ broadcastWorkflow(workflowId, {
2523
+ type: 'checkpoint_created', workflowId, checkpointSeq: checkpointGuardSeq,
2524
+ ref: checkpoint.ref, label: checkpoint.label, ts: checkpoint.ts, fileCount: checkpoint.fileCount,
2525
+ ...(checkpoint.skippedLargeFiles ? { skippedLargeFiles: checkpoint.skippedLargeFiles } : {}),
2526
+ ...(checkpoint.limitation ? { limitation: checkpoint.limitation } : {}),
2527
+ });
2275
2528
  }
2276
- }
2277
- if (genesisSeed?.github?.create && genesisSeed.github.visibility === 'public') {
2278
- if (wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek')) {
2279
- finalSystemPrompt = finalSystemPrompt
2280
- ? `${PUBLIC_REPO_SAFETY_SYSTEM_BLOCK}\n\n${finalSystemPrompt}`
2281
- : PUBLIC_REPO_SAFETY_SYSTEM_BLOCK;
2529
+ const policyTurnProvider = wf.primary.provider;
2530
+ const ollamaExecutionId = trackOllama ? randomUUID() : undefined;
2531
+ const executionInputSeqs = [...activeOllamaInputSeqs];
2532
+ const executionInputClientIds = [...activeInputClientIds];
2533
+ let dispatchedWorkerId;
2534
+ const dispatchCurrent = () => workflows.get(workflowId) === wf && ownsBusy(wf, busyToken) && (dispatchedWorkerId === undefined || primaryTurn.workerId === dispatchedWorkerId);
2535
+ const turn = runPrimaryTurn({
2536
+ workflowId,
2537
+ cwd,
2538
+ manager: wf.manager,
2539
+ broadcast: (msg) => {
2540
+ // A Task child's final status still belongs to the card after STOP.
2541
+ if (!dispatchCurrent() && !deliverAfterTurnRevoked(msg))
2542
+ return;
2543
+ const delivery = msg.type === 'primary_turn_started' && executionInputClientIds.length
2544
+ ? { ...msg, inputClientMessageIds: executionInputClientIds } : msg;
2545
+ send(ws, ollamaExecutionId ? stampOllamaExecution(delivery, ollamaExecutionId, executionInputSeqs) : delivery);
2546
+ },
2547
+ bgTracker: chatMode ? undefined : wf.bgTracker,
2548
+ notePotentialDevServerStart: chatMode ? undefined : (cmd, toolUseId) => { if (dispatchCurrent())
2549
+ deps.previewAutoDetect.notePotentialDevServerStart(workflowId, cmd, toolUseId); },
2550
+ noteAgentText: chatMode ? undefined : (text) => { if (dispatchCurrent())
2551
+ deps.previewAutoDetect.noteAgentText(workflowId, text); },
2552
+ }, {
2553
+ primary: wf.primary,
2554
+ prompt: promptWithPlan,
2555
+ resumeSessionId: incognito ? undefined : wf.primarySessionId,
2556
+ attachments: promptAttachments,
2557
+ disableRssGuard: wf.disableRssGuard,
2558
+ appendSystemPrompt: finalAppend,
2559
+ systemPrompt: finalSystemPrompt,
2560
+ interactionMode: chatMode || (firstIteration && primitive === 'plan-review') ? 'chat' : 'agent',
2561
+ disableProviderHooks: firstIteration && primitive === 'plan-review',
2562
+ chatWebAccess: firstIteration && primitive === 'plan-review' ? false : chatWeb,
2563
+ voiceOperator: chatMode && wf.config.voiceOperator === true,
2564
+ incognito,
2565
+ drainSteer: () => {
2566
+ if (!dispatchCurrent())
2567
+ return [];
2568
+ return drainSteerForWorker(workflowId, ws, policyTurnProvider);
2569
+ },
2570
+ requeueSteer: (items, bucket) => {
2571
+ if (workflows.get(workflowId) === wf && (busyRevocations.get(wf) ?? 0) === interruptEpoch)
2572
+ requeueSteerForWorker(workflowId, ws, items, bucket);
2573
+ },
2574
+ onSteerDelivered: (items) => {
2575
+ const clientMessageIds = items.flatMap((item) => item.clientMessageId ? [item.clientMessageId] : []);
2576
+ if (clientMessageIds.length && policyTurnProvider === 'codex')
2577
+ broadcastWorkflow(workflowId, { type: 'turn_messages_delivered', workflowId, clientMessageIds, ...(items[0]?.deliveryId ? { deliveryId: items[0].deliveryId } : {}) });
2578
+ },
2579
+ codexTransport,
2580
+ codexContextPolicy: wf.config.codexContextPolicy,
2581
+ providerAccountRef: providerAccount?.profile.id,
2582
+ codexHome: providerAccount?.codexHome,
2583
+ claudeTransport,
2584
+ ultracode,
2585
+ claudeNativeCompact,
2586
+ claudeNativeTaskDisabled: wf.config.claudeNativeTaskDisabled,
2587
+ ...(claudeNativeInTurnCompactPercent !== undefined && !(firstIteration && primitive === 'plan-review') ? { claudeNativeInTurnCompactPercent } : {}),
2588
+ claudeNativeForceInterleavedThinkingBeta,
2589
+ claudeNativeThinkingDisplay, nativeSubagents,
2590
+ claudeNativePlanModeArmed: armPlanMode,
2591
+ turnNotice: turnNoticeParts.length > 0 ? turnNoticeParts.join('\n\n') : undefined,
2592
+ efficiencyToolFilter,
2593
+ efficiencyFactForce,
2594
+ efficiencyConfigProtection,
2595
+ efficiencySandbox,
2596
+ reviewSafeMode,
2597
+ outputStyle: firstIteration && primitive === 'plan-review' ? 'normal' : outputStyle,
2598
+ goal,
2599
+ // §4.1 — session-local posture filter (runtime-only WorkflowState
2600
+ // field). Operator-turn only; primitives (reviewers / handoff seeds /
2601
+ // Task children) leave it unset ⇒ full, like outputStyle's 'normal'.
2602
+ toolPosture: wf.toolPosture,
2603
+ clusterId: turnClusterId,
2604
+ clusterAccessMode,
2605
+ executionCwd: isolatedMember && turnClusterId
2606
+ ? clusterStore.isolatedWorkspaceFor(turnClusterId, workflowId)
2607
+ : undefined,
2608
+ persistenceCwd: isolatedMember ? cwd : undefined,
2609
+ clusterTaskBoardAttached: turnClusterTaskBoardAttached,
2610
+ clusterPlan: turnClusterPlan,
2611
+ clusterRole: turnClusterRole,
2612
+ clusterEfficiencyDoctrine: turnClusterEfficiencyDoctrine,
2613
+ clusterProgressDoctrine: turnClusterProgressDoctrine,
2614
+ clusterMcpConfigPath: turnClusterMcpConfigPath,
2615
+ codebaseMemoryAttached: projectContextEnabled && wf.config.codebaseMemory?.attached === true,
2616
+ codebaseMemoryIndexPath: projectContextEnabled && wf.config.codebaseMemory?.attached === true
2617
+ ? (wf.config.codebaseMemory.indexPath || cwd)
2618
+ : undefined,
2619
+ // §E1 — registry servers feed Codex `-c` overrides; CLI Claude got
2620
+ // them via the mcp-config write above. mcpDisallowedTools feed CLI
2621
+ // Claude's --disallowedTools (dangerous-tool denylist enforcement).
2622
+ mcpRegistryServers: turnRegistryServers,
2623
+ mcpDisallowedTools: turnMcpDisallowedTools,
2624
+ ollamaParams,
2625
+ ollamaReplay,
2626
+ priorFiles,
2627
+ fileContextCwd: retainLocalFiles ? cwd : undefined,
2628
+ fileContextInputIds: retainLocalFiles ? [...activeInputClientIds] : undefined,
2629
+ // Per-tab Claude Native web budget (Anthropic server-tool max_uses).
2630
+ // Native-only; the worker falls back to the server default when unset.
2631
+ webSearchMaxUses: wf.config.webSearchMaxUses,
2632
+ });
2633
+ dispatchedWorkerId = turn.workerId;
2634
+ activeTurnObservation?.setPrimaryWorker(turn.workerId);
2635
+ primaryTurn.workerId = turn.workerId;
2636
+ // Claude pre-mints its session id; pin it into meta.json immediately so a
2637
+ // crash between now and turn-completion still leaves meta pointing at the
2638
+ // right CLI session. Only relevant on the first iteration — later
2639
+ // flushes resume the already-pinned session. Native transport runs
2640
+ // in-process and never writes a CLI rollout, so seedWorker's pre-minted
2641
+ // UUID is meaningless here — recording it would phantom-pollute meta and
2642
+ // break original-worker handoff (which would try `claude --resume <id>`
2643
+ // against a non-existent rollout).
2644
+ if (!incognito && firstIteration && !wf.primarySessionId && turn.initialSessionId
2645
+ && wf.primary.provider === 'claude' && claudeTransport !== 'native') {
2646
+ wf.primarySessionId = turn.initialSessionId;
2647
+ reconcileLatestCliSession(cwd, workflowId, 'claude', turn.initialSessionId).catch((err) => {
2648
+ console.error(`[arco] [${workflowId.slice(0, 8)}] meta reconcile (claude mint) failed:`, err);
2649
+ });
2282
2650
  }
2283
- else {
2284
- finalAppend = finalAppend
2285
- ? `${PUBLIC_REPO_SAFETY_SYSTEM_BLOCK}\n\n${finalAppend}`
2286
- : PUBLIC_REPO_SAFETY_SYSTEM_BLOCK;
2651
+ // Codex emits thread_id at init. Capture on first fire, persist to meta.
2652
+ turn.onSessionDiscovered((sid) => {
2653
+ if (incognito || !dispatchCurrent() || wf.primary.provider !== policyTurnProvider)
2654
+ return;
2655
+ if (!wf.primarySessionId)
2656
+ wf.primarySessionId = sid;
2657
+ reconcileLatestCliSession(cwd, workflowId, policyTurnProvider, sid, providerAccount?.profile.id).catch((err) => {
2658
+ console.error(`[arco] [${workflowId.slice(0, 8)}] meta reconcile (${wf.primary.provider}) failed:`, err);
2659
+ });
2660
+ });
2661
+ // docs/PROVIDERS.md - surface the background fleet. Under ultracode the
2662
+ // CLI's WorkflowTool runs subagents whose transcripts never touch the
2663
+ // parent stream, so the Activity tab would look dead. Poll those files and
2664
+ // emit live `ultracode_fleet_progress` snapshots, scoped strictly to this
2665
+ // turn (started here, stopped in finally). Gated on a known session id —
2666
+ // the watcher needs it to locate `<sessionId>/subagents/workflows/`.
2667
+ let fleetWatcher = null;
2668
+ if (ultracode && wf.primarySessionId) {
2669
+ fleetWatcher = startUltracodeFleetWatcher({
2670
+ workflowId,
2671
+ cwd,
2672
+ sessionId: wf.primarySessionId,
2673
+ emit: (msg) => broadcastTransient(workflowId, msg),
2674
+ });
2287
2675
  }
2288
- }
2289
- // docs/GOTCHAS.md - the north-star is NOT folded here. Native
2290
- // injects it as its own cached system block (buildSystemBlocks reads
2291
- // config.goal); every other transport folds goalBlock(config.goal) inside
2292
- // its own provider (mirroring outputStyleAddendum). Doing it per-provider
2293
- // rather than into finalAppend here is load-bearing: reviewers spawn via
2294
- // manager.spawn and handoff seeds via runPrimaryTurn — both bypass this
2295
- // operator-turn assembly but still carry config.goal, so the provider fold
2296
- // is the one place that covers operator turns AND primitive seeds without
2297
- // double-injecting.
2298
- // docs/ARCHITECTURE.md - resolve the operator-enabled-and-allowed
2299
- // registry MCP servers for this workflow from the global registry + the
2300
- // workflow's per-tab allowlist (meta.mcpAllow). Produces BOTH the merged
2301
- // server entries (for the mcp-config write / Codex `-c` overrides) AND
2302
- // the dangerous-and-unticked `--disallowedTools` set for CLI Claude.
2303
- // This is the ONLY model-exposed expansion besides cluster /
2304
- // codebase-memory — no hidden, model-selected servers.
2305
- let turnRegistryServers = [];
2306
- let turnMcpDisallowedTools = [];
2307
- if (projectContextEnabled)
2676
+ policyReading = undefined;
2677
+ let outcome;
2678
+ let carryInterruptedPrompt = false;
2308
2679
  try {
2309
- const metaForMcp = await readMeta(cwd, workflowId);
2310
- const wiring = await resolveRegistryWiring(metaForMcp?.mcpAllow ?? []);
2311
- turnRegistryServers = wiring.registryServers;
2312
- turnMcpDisallowedTools = wiring.disallowedTools;
2680
+ outcome = await turn.settled;
2681
+ // A second correction may cancel Native during auth/hooks, before
2682
+ // its first correction entered history. Carry that unsent input.
2683
+ carryInterruptedPrompt = await primaryTurn.interruption === false && primaryTurn.holdSteer;
2313
2684
  }
2314
2685
  catch (err) {
2315
- console.error(`[arco] [${workflowId.slice(0, 8)}] mcp registry resolve failed:`, err);
2686
+ if (!primaryTurn.interruption)
2687
+ throw err;
2688
+ preserveQueue = true;
2689
+ lastTurnErrored = true;
2690
+ broadcastWorkflow(workflowId, { type: 'system_notice', workflowId,
2691
+ content: `[INTERRUPT & SEND] Cancellation failed; queued messages were preserved without starting another turn. ${err instanceof Error ? err.message : String(err)}` });
2692
+ break;
2316
2693
  }
2317
- // docs/PROVIDERS.md - write `.arco/<wfid>/mcp-config.json`
2318
- // for CLI Claude turns when cluster membership, the operator-attached
2319
- // codebase-memory entry, OR §E1 registry servers apply. All coexist; the
2320
- // writer merges deterministically and unlinks when none apply. Codex
2321
- // transports don't use --mcp-config — they layer the same registrations
2322
- // on via `-c mcp_servers.*` TOML overrides built in the codex provider.
2323
- if (projectContextEnabled && wf.primary.provider === 'claude' && claudeTransport === 'cli') {
2324
- const cbm = wf.config.codebaseMemory;
2325
- const wantsCodebaseMemory = projectContextEnabled && cbm?.attached === true;
2326
- // The workflow-scoped `arco` plan entry applies to EVERY workflow, so
2327
- // the config is now written unconditionally (cwd is the only
2328
- // precondition) rather than only when a cluster / codebase-memory /
2329
- // registry entry applies.
2330
- {
2331
- try {
2332
- turnClusterMcpConfigPath = await mcpConfigWriter.writeFor(cwd, workflowId, {
2333
- planToolsCwd: cwd,
2334
- clusterId: turnClusterId,
2335
- taskBoardAttached: turnClusterTaskBoardAttached,
2336
- accessMode: clusterAccessMode,
2337
- port: PORT,
2338
- codebaseMemoryIndexPath: wantsCodebaseMemory
2339
- ? (cbm?.indexPath || cwd)
2340
- : undefined,
2341
- registryServers: turnRegistryServers,
2342
- });
2343
- }
2344
- catch (err) {
2345
- console.error(`[arco] [${workflowId.slice(0, 8)}] mcp-config write failed:`, err);
2346
- }
2694
+ finally {
2695
+ fleetWatcher?.stop();
2696
+ primaryTurn.workerId = undefined;
2697
+ primaryTurn.interruption = undefined;
2347
2698
  }
2348
- }
2349
- // Workbench Expansion A2 — shadow-git checkpoint. Snapshot the working
2350
- // tree BEFORE the turn that may mutate files so the operator can
2351
- // undo-the-agent independent of their real git history. Skipped when
2352
- // plan mode is armed (the turn is read-only until ExitPlanMode, so
2353
- // there's nothing to checkpoint). Wait at most two seconds; a slow or
2354
- // failed capture is omitted and the turn proceeds without a summary.
2355
- //
2356
- // Hooked HERE rather than in seedWorker.ts (the plan's guess): runtime
2357
- // verification showed runPrimaryTurn is shared by reviewers, handoff
2358
- // seeds, exportContext, and Task children — none of which should snapshot
2359
- // the operator's tree. The operator-turn loop in turnEngine.handleUserMessage
2360
- // is the only dispatch path that runs an operator-driven, file-mutating
2361
- // turn, so the checkpoint belongs at this call site. The ref suffix uses
2362
- // the workflow's current event seq (the turn it guards); the
2363
- // checkpoint_created broadcast is itself stamped a fresh events.jsonl seq.
2364
- // Upload-time image downscaling runs in the background; a send right
2365
- // after a paste can beat it. Wait (bounded) here so the sync providers
2366
- // (Claude CLI / Native, Codex exec) read the model copy too — they call
2367
- // the sync modelImagePath() and can't wait themselves.
2368
- if (promptAttachments && promptAttachments.length > 0)
2369
- await awaitModelImages(promptAttachments);
2370
- // STOP landed during the pre-spawn awaits above (killAll had nothing to
2371
- // kill yet). Spawning now would run a turn nobody owns.
2372
- if (!ownsBusy(wf, busyToken))
2373
- break;
2374
- if (wf.queue.steering.some((q) => q.interrupt)) {
2375
- firstIteration = false;
2376
- loadQueuedPrompt(primaryTurn.holdSteer);
2377
- continue;
2378
- }
2379
- let checkpoint = null;
2380
- let checkpointGuardSeq;
2381
- if (!(firstIteration && primitive === 'plan-review') && shouldCaptureTurn({ chatMode, planMode: armPlanMode, isolated: isolatedMember, provider: wf.primary.provider, tools: wf.primary.tools })) {
2382
- checkpointGuardSeq = currentWorkflowSeq(cwd, workflowId);
2383
- activeTurnObservation = observeCheckoutWriters(workflowWritePaths(wf), wf.manager);
2384
- checkpoint = await timelyCheckpoint((deps.captureCheckpoint ?? createCheckpoint)({ cwd, workflowId, seq: checkpointGuardSeq }));
2385
- if (!checkpoint || !ownsBusy(wf, busyToken)) {
2386
- activeTurnObservation.stop();
2387
- activeTurnObservation = undefined;
2388
- checkpoint = null;
2699
+ if (checkpoint && checkpointGuardSeq !== undefined && activeTurnObservation && ownsBusy(wf, busyToken)) {
2700
+ // Hold this workflow's busy claim until the end snapshot is captured;
2701
+ // otherwise a queued follow-up could alter the tree before the range ends.
2702
+ const endSeq = currentWorkflowSeq(cwd, workflowId);
2703
+ if (endSeq > checkpointGuardSeq) {
2704
+ const end = await (deps.captureCheckpoint ?? createCheckpoint)({ cwd, workflowId, seq: endSeq, onSkipped: onCheckpointSkipped });
2705
+ if (end && ownsBusy(wf, busyToken)) {
2706
+ const otherWriters = activeTurnObservation.hasOverlap();
2707
+ activeTurnObservation.stop();
2708
+ activeTurnObservation = undefined;
2709
+ const summary = await summarizeTurnChanges(cwd, checkpoint.ref, end.ref);
2710
+ if (summary && summary.fileCount > 0 && ownsBusy(wf, busyToken)) {
2711
+ broadcastWorkflow(workflowId, {
2712
+ type: 'turn_changes', workflowId, checkpointSeq: checkpointGuardSeq,
2713
+ fromRef: checkpoint.ref, toRef: end.ref, ...summary,
2714
+ otherWriters,
2715
+ ...((checkpoint.skippedLargeFiles || end.skippedLargeFiles) ? { skippedLargeFiles: Math.max(checkpoint.skippedLargeFiles ?? 0, end.skippedLargeFiles ?? 0) } : {}),
2716
+ timestamp: Date.now(),
2717
+ });
2718
+ }
2719
+ }
2720
+ }
2389
2721
  }
2390
- }
2391
- // STOP or an interrupt during capture must never launch the stale prompt.
2392
- if (!ownsBusy(wf, busyToken))
2393
- break;
2394
- if (wf.queue.steering.some((q) => q.interrupt)) {
2395
2722
  activeTurnObservation?.stop();
2396
2723
  activeTurnObservation = undefined;
2724
+ console.log(`[arco] [${workflowId.slice(0, 8)}] turn settled${outcome.error ? ' with error: ' + outcome.error : ''}`);
2725
+ lastTurnErrored = !!outcome.error;
2726
+ watchHadError ||= lastTurnErrored;
2727
+ if (firstIteration && opts?.backgroundEvent)
2728
+ opts.onBackgroundSettled?.(outcome.error ?? undefined);
2729
+ clearComputerBackgroundClaim(workflowId, busyToken);
2397
2730
  firstIteration = false;
2398
- loadQueuedPrompt(primaryTurn.holdSteer);
2399
- continue;
2400
- }
2401
- if (checkpoint && checkpointGuardSeq !== undefined) {
2402
- broadcastWorkflow(workflowId, {
2403
- type: 'checkpoint_created', workflowId, seq: checkpointGuardSeq,
2404
- ref: checkpoint.ref, label: checkpoint.label, ts: checkpoint.ts, fileCount: checkpoint.fileCount,
2405
- ...(checkpoint.skippedLargeFiles ? { skippedLargeFiles: checkpoint.skippedLargeFiles } : {}),
2406
- });
2407
- }
2408
- const policyTurnProvider = wf.primary.provider;
2409
- const ollamaExecutionId = trackOllama ? randomUUID() : undefined;
2410
- const executionInputSeqs = [...activeOllamaInputSeqs];
2411
- const turn = runPrimaryTurn({
2412
- workflowId,
2413
- cwd,
2414
- manager: wf.manager,
2415
- broadcast: (msg) => send(ws, ollamaExecutionId ? stampOllamaExecution(msg, ollamaExecutionId, executionInputSeqs) : msg),
2416
- bgTracker: chatMode ? undefined : wf.bgTracker,
2417
- notePotentialDevServerStart: chatMode ? undefined : (cmd, toolUseId) => deps.previewAutoDetect.notePotentialDevServerStart(workflowId, cmd, toolUseId),
2418
- noteAgentText: chatMode ? undefined : (text) => deps.previewAutoDetect.noteAgentText(workflowId, text),
2419
- }, {
2420
- primary: wf.primary,
2421
- prompt: promptWithPlan,
2422
- resumeSessionId: incognito ? undefined : wf.primarySessionId,
2423
- attachments: promptAttachments,
2424
- disableRssGuard: wf.disableRssGuard,
2425
- appendSystemPrompt: finalAppend,
2426
- systemPrompt: finalSystemPrompt,
2427
- interactionMode: chatMode || (firstIteration && primitive === 'plan-review') ? 'chat' : 'agent',
2428
- disableProviderHooks: firstIteration && primitive === 'plan-review',
2429
- chatWebAccess: firstIteration && primitive === 'plan-review' ? false : chatWeb,
2430
- voiceOperator: chatMode && wf.config.voiceOperator === true,
2431
- incognito,
2432
- drainSteer: () => drainSteerForWorker(workflowId, ws),
2433
- requeueSteer: (items, bucket) => requeueSteerForWorker(workflowId, ws, items, bucket),
2434
- onSteerDelivered: (items) => {
2435
- const clientMessageIds = items.flatMap((item) => item.clientMessageId ? [item.clientMessageId] : []);
2436
- if (clientMessageIds.length)
2437
- broadcastTransient(workflowId, { type: 'turn_messages_delivered', workflowId, clientMessageIds });
2438
- },
2439
- codexTransport,
2440
- codexContextPolicy: wf.config.codexContextPolicy,
2441
- providerAccountRef: providerAccount?.profile.id,
2442
- codexHome: providerAccount?.codexHome,
2443
- claudeTransport,
2444
- ultracode,
2445
- claudeNativeCompact,
2446
- claudeNativeForceInterleavedThinkingBeta,
2447
- claudeNativeThinkingDisplay,
2448
- claudeNativePlanModeArmed: armPlanMode,
2449
- turnNotice: turnNoticeParts.length > 0 ? turnNoticeParts.join('\n\n') : undefined,
2450
- efficiencyToolFilter,
2451
- efficiencyFactForce,
2452
- efficiencyConfigProtection,
2453
- efficiencySandbox,
2454
- reviewSafeMode,
2455
- outputStyle: firstIteration && primitive === 'plan-review' ? 'normal' : outputStyle,
2456
- goal,
2457
- // §4.1 — session-local posture filter (runtime-only WorkflowState
2458
- // field). Operator-turn only; primitives (reviewers / handoff seeds /
2459
- // Task children) leave it unset ⇒ full, like outputStyle's 'normal'.
2460
- toolPosture: wf.toolPosture,
2461
- clusterId: turnClusterId,
2462
- clusterAccessMode,
2463
- executionCwd: isolatedMember && turnClusterId
2464
- ? clusterStore.isolatedWorkspaceFor(turnClusterId, workflowId)
2465
- : undefined,
2466
- persistenceCwd: isolatedMember ? cwd : undefined,
2467
- clusterTaskBoardAttached: turnClusterTaskBoardAttached,
2468
- clusterPlan: turnClusterPlan,
2469
- clusterRole: turnClusterRole,
2470
- clusterEfficiencyDoctrine: turnClusterEfficiencyDoctrine,
2471
- clusterProgressDoctrine: turnClusterProgressDoctrine,
2472
- clusterMcpConfigPath: turnClusterMcpConfigPath,
2473
- codebaseMemoryAttached: projectContextEnabled && wf.config.codebaseMemory?.attached === true,
2474
- codebaseMemoryIndexPath: projectContextEnabled && wf.config.codebaseMemory?.attached === true
2475
- ? (wf.config.codebaseMemory.indexPath || cwd)
2476
- : undefined,
2477
- // §E1 — registry servers feed Codex `-c` overrides; CLI Claude got
2478
- // them via the mcp-config write above. mcpDisallowedTools feed CLI
2479
- // Claude's --disallowedTools (dangerous-tool denylist enforcement).
2480
- mcpRegistryServers: turnRegistryServers,
2481
- mcpDisallowedTools: turnMcpDisallowedTools,
2482
- ollamaParams,
2483
- ollamaReplay,
2484
- // Per-tab Claude Native web budget (Anthropic server-tool max_uses).
2485
- // Native-only; the worker falls back to the server default when unset.
2486
- webSearchMaxUses: wf.config.webSearchMaxUses,
2487
- });
2488
- activeTurnObservation?.setPrimaryWorker(turn.workerId);
2489
- primaryTurn.workerId = turn.workerId;
2490
- // Claude pre-mints its session id; pin it into meta.json immediately so a
2491
- // crash between now and turn-completion still leaves meta pointing at the
2492
- // right CLI session. Only relevant on the first iteration — later
2493
- // flushes resume the already-pinned session. Native transport runs
2494
- // in-process and never writes a CLI rollout, so seedWorker's pre-minted
2495
- // UUID is meaningless here — recording it would phantom-pollute meta and
2496
- // break original-worker handoff (which would try `claude --resume <id>`
2497
- // against a non-existent rollout).
2498
- if (!incognito && firstIteration && !wf.primarySessionId && turn.initialSessionId
2499
- && wf.primary.provider === 'claude' && claudeTransport !== 'native') {
2500
- wf.primarySessionId = turn.initialSessionId;
2501
- reconcileLatestCliSession(cwd, workflowId, 'claude', turn.initialSessionId).catch((err) => {
2502
- console.error(`[arco] [${workflowId.slice(0, 8)}] meta reconcile (claude mint) failed:`, err);
2503
- });
2504
- }
2505
- // Codex emits thread_id at init. Capture on first fire, persist to meta.
2506
- turn.onSessionDiscovered((sid) => {
2507
- if (incognito)
2508
- return;
2509
- if (!wf.primarySessionId)
2510
- wf.primarySessionId = sid;
2511
- reconcileLatestCliSession(cwd, workflowId, wf.primary.provider, sid, providerAccount?.profile.id).catch((err) => {
2512
- console.error(`[arco] [${workflowId.slice(0, 8)}] meta reconcile (${wf.primary.provider}) failed:`, err);
2513
- });
2514
- });
2515
- // docs/PROVIDERS.md - surface the background fleet. Under ultracode the
2516
- // CLI's WorkflowTool runs subagents whose transcripts never touch the
2517
- // parent stream, so the Activity tab would look dead. Poll those files and
2518
- // emit live `ultracode_fleet_progress` snapshots, scoped strictly to this
2519
- // turn (started here, stopped in finally). Gated on a known session id —
2520
- // the watcher needs it to locate `<sessionId>/subagents/workflows/`.
2521
- let fleetWatcher = null;
2522
- if (ultracode && wf.primarySessionId) {
2523
- fleetWatcher = startUltracodeFleetWatcher({
2524
- workflowId,
2525
- cwd,
2526
- sessionId: wf.primarySessionId,
2527
- emit: (msg) => broadcastTransient(workflowId, msg),
2528
- });
2529
- }
2530
- policyReading = undefined;
2531
- let outcome;
2532
- let carryInterruptedPrompt = false;
2533
- try {
2534
- outcome = await turn.settled;
2535
- // A second correction may cancel Native during auth/hooks, before
2536
- // its first correction entered history. Carry that unsent input.
2537
- carryInterruptedPrompt = await primaryTurn.interruption === false && primaryTurn.holdSteer;
2538
- }
2539
- catch (err) {
2540
- if (!primaryTurn.interruption)
2541
- throw err;
2542
- preserveQueue = true;
2543
- lastTurnErrored = true;
2544
- broadcastWorkflow(workflowId, { type: 'system_notice', workflowId,
2545
- content: `[INTERRUPT & SEND] Cancellation failed; queued messages were preserved without starting another turn. ${err instanceof Error ? err.message : String(err)}` });
2546
- break;
2547
- }
2548
- finally {
2549
- fleetWatcher?.stop();
2550
- primaryTurn.workerId = undefined;
2551
- primaryTurn.interruption = undefined;
2552
- }
2553
- if (checkpoint && checkpointGuardSeq !== undefined && activeTurnObservation && ownsBusy(wf, busyToken)) {
2554
- // Hold this workflow's busy claim until the end snapshot is captured;
2555
- // otherwise a queued follow-up could alter the tree before the range ends.
2556
- const endSeq = currentWorkflowSeq(cwd, workflowId);
2557
- if (endSeq > checkpointGuardSeq) {
2558
- const end = await (deps.captureCheckpoint ?? createCheckpoint)({ cwd, workflowId, seq: endSeq });
2559
- if (end && ownsBusy(wf, busyToken)) {
2560
- const otherWriters = activeTurnObservation.hasOverlap();
2561
- activeTurnObservation.stop();
2562
- activeTurnObservation = undefined;
2563
- const summary = await summarizeTurnChanges(cwd, checkpoint.ref, end.ref);
2564
- if (summary && summary.fileCount > 0 && ownsBusy(wf, busyToken)) {
2565
- broadcastWorkflow(workflowId, {
2566
- type: 'turn_changes', workflowId, checkpointSeq: checkpointGuardSeq,
2567
- fromRef: checkpoint.ref, toRef: end.ref, ...summary,
2568
- otherWriters,
2569
- ...((checkpoint.skippedLargeFiles || end.skippedLargeFiles) ? { skippedLargeFiles: Math.max(checkpoint.skippedLargeFiles ?? 0, end.skippedLargeFiles ?? 0) } : {}),
2570
- timestamp: Date.now(),
2571
- });
2572
- }
2731
+ if (wf.config.voiceOperator && outcome.error?.startsWith(COMPUTER_TIMEOUT)) {
2732
+ // The transport may have executed earlier actions. Never replay this
2733
+ // request or drain dependent queued instructions after a timeout.
2734
+ const queued = wf.queue.steering.length + wf.queue.followUp.length;
2735
+ for (const item of [...wf.queue.steering, ...wf.queue.followUp])
2736
+ if (item.clientMessageId)
2737
+ broadcastWorkflow(workflowId, { type: 'queued_message_cancelled', workflowId, clientMessageId: item.clientMessageId });
2738
+ if (queued)
2739
+ broadcastWorkflow(workflowId, { type: 'system_notice', workflowId,
2740
+ content: `[COMPUTER] Cancelled ${queued} queued request(s) after the timeout; resubmit them when ready. Earlier actions may already have happened.` });
2741
+ if (incognito)
2742
+ wf.config.computerContext = { ...(wf.config.computerContext ?? { keepContext: false, resets: 0 }), pendingFresh: true, pendingFreshReason: 'recovery' };
2743
+ break;
2744
+ }
2745
+ if (wf.primary.provider === 'claude' && wf.primarySessionId && claudeTransport !== 'native') {
2746
+ const sid = wf.primarySessionId;
2747
+ estimateContextFill(cwd, sid, wf.primary.model, wf.calibration).then((est) => {
2748
+ if (!est)
2749
+ return;
2750
+ broadcastTransient(workflowId, {
2751
+ type: 'context_usage',
2752
+ workflowId,
2753
+ ...est,
2754
+ claudeSessionId: sid,
2755
+ });
2756
+ // Keep the shared context signal fresh (fire-and-forget, so it may
2757
+ // settle one turn late; nothing here acts on a single reading).
2758
+ wf.lastContextPercent = est.percentOfWindow;
2759
+ }).catch(() => { });
2760
+ }
2761
+ else if (wf.primary.provider === 'claude' && claudeTransport === 'native' && typeof outcome.lastPromptTokens === 'number') {
2762
+ // Native Claude has no session JSONL to read. The worker's settled
2763
+ // outcome carries the last round's prompt size — convert to a fresh
2764
+ // ground-truth context_usage and fan out via broadcastTransient
2765
+ // (consistent with the CLI path: primary_complete already persists
2766
+ // lastPromptTokens, so context_usage stays derived/transient).
2767
+ const est = wf.config.voiceOperator && outcome.modelContextWindow
2768
+ ? promptContextEstimate(outcome.lastPromptTokens, outcome.modelContextWindow, Date.now())
2769
+ : nativeContextEstimate(wf.primary.model, outcome.lastPromptTokens, Date.now());
2770
+ if (est) {
2771
+ wf.lastContextPercent = est.percentOfWindow;
2772
+ broadcastTransient(workflowId, {
2773
+ type: 'context_usage',
2774
+ workflowId,
2775
+ ...est,
2776
+ });
2777
+ }
2778
+ // §2.3 — emit the deterministic budget meter alongside the CTX bar's
2779
+ // context_usage. Uses the same ground-truth lastPromptTokens but against
2780
+ // the EFFECTIVE window (real window − reserved output budget) — the
2781
+ // usable-input-pressure signal the §2.1 auto-fold trigger reads. Window +
2782
+ // reserved come straight from the model's own params (KNOWN_CTX +
2783
+ // chooseMaxTokens), so this stays deterministic and LLM-free.
2784
+ const win = lookupCtx(wf.primary.model);
2785
+ if (typeof win === 'number' && win > 0) {
2786
+ const reserved = chooseMaxTokens(wf.primary.model, wf.primary.effort ?? 'high');
2787
+ const budget = computeContextBudget(outcome.lastPromptTokens, win, reserved);
2788
+ wf.lastContextBudgetPct = budget.pct;
2789
+ const thresholds = {
2790
+ ...(typeof wf.autoFold?.foldAt === 'number' ? { foldAt: wf.autoFold.foldAt } : {}),
2791
+ };
2792
+ broadcastTransient(workflowId, {
2793
+ type: 'context_budget',
2794
+ workflowId,
2795
+ usedTokens: budget.usedTokens,
2796
+ windowSize: budget.windowSize,
2797
+ reservedOutput: budget.reservedOutput,
2798
+ effectiveWindow: budget.effectiveWindow,
2799
+ pct: budget.pct,
2800
+ thresholds,
2801
+ crossed: crossedThresholds(budget.pct, thresholds),
2802
+ });
2573
2803
  }
2574
2804
  }
2575
- }
2576
- activeTurnObservation?.stop();
2577
- activeTurnObservation = undefined;
2578
- console.log(`[arco] [${workflowId.slice(0, 8)}] turn settled${outcome.error ? ' with error: ' + outcome.error : ''}`);
2579
- lastTurnErrored = !!outcome.error;
2580
- watchHadError ||= lastTurnErrored;
2581
- if (firstIteration && opts?.backgroundEvent)
2582
- opts.onBackgroundSettled?.(outcome.error ?? undefined);
2583
- clearComputerBackgroundClaim(workflowId, busyToken);
2584
- firstIteration = false;
2585
- if (wf.config.voiceOperator && outcome.error?.startsWith(COMPUTER_TIMEOUT)) {
2586
- // The transport may have executed earlier actions. Never replay this
2587
- // request or drain dependent queued instructions after a timeout.
2588
- const queued = wf.queue.steering.length + wf.queue.followUp.length;
2589
- for (const item of [...wf.queue.steering, ...wf.queue.followUp])
2590
- if (item.clientMessageId)
2591
- broadcastWorkflow(workflowId, { type: 'queued_message_cancelled', workflowId, clientMessageId: item.clientMessageId });
2592
- if (queued)
2593
- broadcastWorkflow(workflowId, { type: 'system_notice', workflowId,
2594
- content: `[COMPUTER] Cancelled ${queued} queued request(s) after the timeout; resubmit them when ready. Earlier actions may already have happened.` });
2595
- if (incognito)
2596
- wf.config.computerContext = { ...(wf.config.computerContext ?? { keepContext: false, resets: 0 }), pendingFresh: true, pendingFreshReason: 'recovery' };
2597
- break;
2598
- }
2599
- if (wf.primary.provider === 'claude' && wf.primarySessionId && claudeTransport !== 'native') {
2600
- const sid = wf.primarySessionId;
2601
- estimateContextFill(cwd, sid, wf.primary.model, wf.calibration).then((est) => {
2602
- if (!est)
2603
- return;
2604
- broadcastTransient(workflowId, {
2605
- type: 'context_usage',
2606
- workflowId,
2607
- ...est,
2608
- claudeSessionId: sid,
2609
- });
2610
- // Keep the shared auto-handoff signal fresh (fire-and-forget, so it
2611
- // may settle just after maybeAutoHandoff runs — warnAt/autoAt margin
2612
- // absorbs the one-turn lag).
2613
- wf.lastContextPercent = est.percentOfWindow;
2614
- }).catch(() => { });
2615
- }
2616
- else if (wf.primary.provider === 'claude' && claudeTransport === 'native' && typeof outcome.lastPromptTokens === 'number') {
2617
- // Native Claude has no session JSONL to read. The worker's settled
2618
- // outcome carries the last round's prompt size — convert to a fresh
2619
- // ground-truth context_usage and fan out via broadcastTransient
2620
- // (consistent with the CLI path: primary_complete already persists
2621
- // lastPromptTokens, so context_usage stays derived/transient).
2622
- const est = wf.config.voiceOperator && outcome.modelContextWindow
2623
- ? promptContextEstimate(outcome.lastPromptTokens, outcome.modelContextWindow, Date.now())
2624
- : nativeContextEstimate(wf.primary.model, outcome.lastPromptTokens, Date.now());
2625
- if (est) {
2626
- wf.lastContextPercent = est.percentOfWindow;
2627
- broadcastTransient(workflowId, {
2628
- type: 'context_usage',
2629
- workflowId,
2630
- ...est,
2631
- });
2805
+ else if (wf.primary.provider === 'ollama' && typeof outcome.lastPromptTokens === 'number') {
2806
+ // M6 — Ollama has no session JSONL. The worker's settled outcome carries
2807
+ // the LAST turn's prompt_eval_count (ground truth: the exact prompt the
2808
+ // daemon saw on its final call) plus the per-backend probed num_ctx the
2809
+ // request actually used (M3/M4: the window is per-host, so the
2810
+ // denominator must be the host that produced this answer, not a static
2811
+ // map). Build the same-shaped context_usage the CTX bar already renders
2812
+ // for every other provider; fall back to Ollama's 2048 default only when
2813
+ // nothing was probed. Transient (broadcastTransient): primary_complete
2814
+ // already persisted lastPromptTokens + modelContextWindow, so this stays
2815
+ // derived. M8 reads context_usage.percentOfWindow as its compaction gate.
2816
+ const est = ollamaContextUsage(outcome.lastPromptTokens, outcome.modelContextWindow, Date.now());
2817
+ if (est) {
2818
+ wf.lastContextPercent = est.percentOfWindow;
2819
+ broadcastTransient(workflowId, {
2820
+ type: 'context_usage',
2821
+ workflowId,
2822
+ ...est,
2823
+ });
2824
+ }
2632
2825
  }
2633
- // §2.3 — emit the deterministic budget meter alongside the CTX bar's
2634
- // context_usage. Uses the same ground-truth lastPromptTokens but against
2635
- // the EFFECTIVE window (real window − reserved output budget) — the
2636
- // usable-input-pressure signal the §2.1 auto-fold trigger reads. Window +
2637
- // reserved come straight from the model's own params (KNOWN_CTX +
2638
- // chooseMaxTokens), so this stays deterministic and LLM-free.
2639
- const win = lookupCtx(wf.primary.model);
2640
- if (typeof win === 'number' && win > 0) {
2641
- const reserved = chooseMaxTokens(wf.primary.model, wf.primary.effort ?? 'high');
2642
- const budget = computeContextBudget(outcome.lastPromptTokens, win, reserved);
2643
- wf.lastContextBudgetPct = budget.pct;
2644
- const thresholds = {
2645
- warnAt: wf.autoHandoff.warnAt,
2646
- autoAt: wf.autoHandoff.autoAt,
2647
- ...(typeof wf.autoFold?.foldAt === 'number' ? { foldAt: wf.autoFold.foldAt } : {}),
2648
- };
2649
- broadcastTransient(workflowId, {
2650
- type: 'context_budget',
2651
- workflowId,
2652
- usedTokens: budget.usedTokens,
2653
- windowSize: budget.windowSize,
2654
- reservedOutput: budget.reservedOutput,
2655
- effectiveWindow: budget.effectiveWindow,
2656
- pct: budget.pct,
2657
- thresholds,
2658
- crossed: crossedThresholds(budget.pct, thresholds),
2659
- });
2826
+ else if ((wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek') && typeof outcome.lastPromptTokens === 'number' && outcome.modelContextWindow) {
2827
+ // Use Strata's discovered window and the final call's actual prompt;
2828
+ // never count summed tool-loop input as context occupancy.
2829
+ const est = promptContextEstimate(outcome.lastPromptTokens, outcome.modelContextWindow, Date.now());
2830
+ if (est) {
2831
+ wf.lastContextPercent = est.percentOfWindow;
2832
+ broadcastTransient(workflowId, { type: 'context_usage', workflowId, ...est });
2833
+ }
2660
2834
  }
2661
- }
2662
- else if (wf.primary.provider === 'ollama' && typeof outcome.lastPromptTokens === 'number') {
2663
- // M6 — Ollama has no session JSONL. The worker's settled outcome carries
2664
- // the LAST turn's prompt_eval_count (ground truth: the exact prompt the
2665
- // daemon saw on its final call) plus the per-backend probed num_ctx the
2666
- // request actually used (M3/M4: the window is per-host, so the
2667
- // denominator must be the host that produced this answer, not a static
2668
- // map). Build the same-shaped context_usage the CTX bar already renders
2669
- // for every other provider; fall back to Ollama's 2048 default only when
2670
- // nothing was probed. Transient (broadcastTransient): primary_complete
2671
- // already persisted lastPromptTokens + modelContextWindow, so this stays
2672
- // derived. M8 reads context_usage.percentOfWindow as its compaction gate.
2673
- const est = ollamaContextUsage(outcome.lastPromptTokens, outcome.modelContextWindow, Date.now());
2674
- if (est) {
2675
- wf.lastContextPercent = est.percentOfWindow;
2676
- broadcastTransient(workflowId, {
2677
- type: 'context_usage',
2678
- workflowId,
2679
- ...est,
2680
- });
2835
+ else if (incognito && wf.config.voiceOperator && wf.primary.provider === 'codex'
2836
+ && typeof outcome.lastPromptTokens === 'number' && outcome.modelContextWindow) {
2837
+ const est = promptContextEstimate(outcome.lastPromptTokens, outcome.modelContextWindow, Date.now());
2838
+ if (est) {
2839
+ wf.lastContextPercent = est.percentOfWindow;
2840
+ broadcastTransient(workflowId, { type: 'context_usage', workflowId, ...est });
2841
+ }
2681
2842
  }
2682
- }
2683
- else if ((wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek') && typeof outcome.lastPromptTokens === 'number' && outcome.modelContextWindow) {
2684
- // Use Strata's discovered window and the final call's actual prompt;
2685
- // never count summed tool-loop input as context occupancy.
2686
- const est = promptContextEstimate(outcome.lastPromptTokens, outcome.modelContextWindow, Date.now());
2687
- if (est) {
2688
- wf.lastContextPercent = est.percentOfWindow;
2689
- broadcastTransient(workflowId, { type: 'context_usage', workflowId, ...est });
2843
+ // This policy uses only this settled turn's own measurement, never the
2844
+ // rollout fallback or a previous turn's display snapshot.
2845
+ if (wf.primary.provider === policyTurnProvider) {
2846
+ const percent = freshAutoCompactionPercent(policyTurnProvider, policyTurnProvider === 'claude' ? claudeTransport : codexTransport, outcome);
2847
+ if (percent !== undefined)
2848
+ policyReading = { percent, sessionId: wf.primarySessionId, provider: policyTurnProvider, transport: policyTurnProvider === 'claude' ? claudeTransport : codexTransport };
2690
2849
  }
2691
- }
2692
- else if (incognito && wf.config.voiceOperator && wf.primary.provider === 'codex'
2693
- && typeof outcome.lastPromptTokens === 'number' && outcome.modelContextWindow) {
2694
- const est = promptContextEstimate(outcome.lastPromptTokens, outcome.modelContextWindow, Date.now());
2695
- if (est) {
2696
- wf.lastContextPercent = est.percentOfWindow;
2697
- broadcastTransient(workflowId, { type: 'context_usage', workflowId, ...est });
2850
+ // Codex app-server equivalent — provider turn usage can be the SUM across all
2851
+ // internal LLM calls within this operator turn. That's right for billing
2852
+ // but wrong for context-window-fill display; the live context is the LAST
2853
+ // call's prompt. Await this best-effort rollout read before threshold
2854
+ // checks so auto-handoff never fires from the previous turn's percentage.
2855
+ if ((wf.primary.provider === 'codex') && wf.primarySessionId) {
2856
+ await refreshCodexTokenSnapshot(workflowId, wf, providerAccount?.codexHome);
2698
2857
  }
2858
+ // Drain the whole queue at once as a single merged follow-up turn.
2859
+ // Operators typically stack queued messages as a cumulative thought
2860
+ // ("oh and also…", "I forgot to mention…") and want one integrated
2861
+ // reply, not N sequential turns each answering a partial thought.
2862
+ // Messages join with `\n\n` (blank line between, reads as paragraphs
2863
+ // of one prompt), attachments concat across all drained items.
2864
+ // `cancel` clears the queue, so STOP during the merge drops the
2865
+ // whole batch before it fires.
2866
+ //
2867
+ // Phase 4 — order is steering first, then follow-up. Steer is "do this
2868
+ // now / change direction"; follow-up is "after the current task lands."
2869
+ // Interrupt entries get their own next turn; remaining steers and
2870
+ // follow-ups stay queued until that correction has completed.
2871
+ // Cancelled (and possibly superseded by a resend) while settling: the
2872
+ // queue belongs to whoever holds busy now — don't drain it.
2873
+ if (!ownsBusy(wf, busyToken))
2874
+ break;
2875
+ if (wf.queue.steering.length === 0 && wf.queue.followUp.length === 0)
2876
+ break;
2877
+ loadQueuedPrompt(carryInterruptedPrompt);
2699
2878
  }
2700
- // This policy uses only this settled turn's own measurement, never the
2701
- // rollout fallback or a previous turn's display snapshot.
2702
- if (wf.primary.provider === policyTurnProvider) {
2703
- const percent = freshAutoCompactionPercent(policyTurnProvider, policyTurnProvider === 'claude' ? claudeTransport : codexTransport, outcome);
2704
- if (percent !== undefined)
2705
- policyReading = { percent, sessionId: wf.primarySessionId, provider: policyTurnProvider, transport: policyTurnProvider === 'claude' ? claudeTransport : codexTransport };
2706
- }
2707
- // Codex app-server equivalent — provider turn usage can be the SUM across all
2708
- // internal LLM calls within this operator turn. That's right for billing
2709
- // but wrong for context-window-fill display; the live context is the LAST
2710
- // call's prompt. Await this best-effort rollout read before threshold
2711
- // checks so auto-handoff never fires from the previous turn's percentage.
2712
- if ((wf.primary.provider === 'codex') && wf.primarySessionId) {
2713
- await refreshCodexTokenSnapshot(workflowId, wf, providerAccount?.codexHome);
2714
- }
2715
- // Drain the whole queue at once as a single merged follow-up turn.
2716
- // Operators typically stack queued messages as a cumulative thought
2717
- // ("oh and also…", "I forgot to mention…") and want one integrated
2718
- // reply, not N sequential turns each answering a partial thought.
2719
- // Messages join with `\n\n` (blank line between, reads as paragraphs
2720
- // of one prompt), attachments concat across all drained items.
2721
- // `cancel` clears the queue, so STOP during the merge drops the
2722
- // whole batch before it fires.
2723
- //
2724
- // Phase 4 — order is steering first, then follow-up. Steer is "do this
2725
- // now / change direction"; follow-up is "after the current task lands."
2726
- // Interrupt entries get their own next turn; remaining steers and
2727
- // follow-ups stay queued until that correction has completed.
2728
- // Cancelled (and possibly superseded by a resend) while settling: the
2729
- // queue belongs to whoever holds busy now — don't drain it.
2730
- if (!ownsBusy(wf, busyToken))
2731
- break;
2732
- if (wf.queue.steering.length === 0 && wf.queue.followUp.length === 0)
2733
- break;
2734
- loadQueuedPrompt(carryInterruptedPrompt);
2879
+ watchLoopFinished = true;
2735
2880
  }
2736
- watchLoopFinished = true;
2737
- }
2738
- finally {
2739
- activeTurnObservation?.stop();
2740
- if (wf.primaryTurn === primaryTurn)
2741
- wf.primaryTurn = undefined;
2742
- // Only the owning claim may release busy / touch the queue. A loop whose
2743
- // claim STOP revoked exits quietly — STOP + quick resend used to let turn
2744
- // 1's finally clear turn 2's busy flag (and drain/clear turn 2's queue).
2745
- staleLoop = !releaseBusy(wf, busyToken, watchLoopFinished && !watchHadError ? 'finished' : 'failed');
2746
- if (!staleLoop) {
2747
- // The provider's `primary_turn_ended` broadcast already fired before
2748
- // this finally runs (it's queued from the settled.then() microtask in
2749
- // seedWorker which awaits the same promise the turn loop does — the
2750
- // provider's .then attaches first, so it runs first). At that moment
2751
- // wf.busy was still `true`, so the cluster_state push triggered by
2752
- // CLUSTER_STATE_TRIGGERS read `busy` and reported the member as still
2753
- // busy. Re-notify here so the cluster tab dot + per-card status
2754
- // actually drop when the worker becomes idle. Without this the
2755
- // cluster-level indicators stay lit until the next unrelated event.
2756
- void notifyClusterStateForWorkflow(workflowId);
2757
- // Defensive: the drain loop above already empties both arrays on each
2758
- // iteration. This catches the case where the loop exited via throw —
2759
- // we don't want the next turn to inherit half-drained state.
2760
- if (!preserveQueue && (wf.queue.steering.length > 0 || wf.queue.followUp.length > 0)) {
2761
- wf.queue.steering.length = 0;
2762
- wf.queue.followUp.length = 0;
2763
- broadcastQueueUpdate(workflowId);
2881
+ finally {
2882
+ activeTurnObservation?.stop();
2883
+ if (wf.primaryTurn === primaryTurn)
2884
+ wf.primaryTurn = undefined;
2885
+ // Only the owning claim may release busy / touch the queue. A loop whose
2886
+ // claim STOP revoked exits quietly — STOP + quick resend used to let turn
2887
+ // 1's finally clear turn 2's busy flag (and drain/clear turn 2's queue).
2888
+ staleLoop = !releaseBusy(wf, busyToken, watchLoopFinished && !watchHadError ? 'finished' : 'failed');
2889
+ if (!staleLoop) {
2890
+ // The provider's `primary_turn_ended` broadcast already fired before
2891
+ // this finally runs (it's queued from the settled.then() microtask in
2892
+ // seedWorker which awaits the same promise the turn loop does — the
2893
+ // provider's .then attaches first, so it runs first). At that moment
2894
+ // wf.busy was still `true`, so the cluster_state push triggered by
2895
+ // CLUSTER_STATE_TRIGGERS read `busy` and reported the member as still
2896
+ // busy. Re-notify here so the cluster tab dot + per-card status
2897
+ // actually drop when the worker becomes idle. Without this the
2898
+ // cluster-level indicators stay lit until the next unrelated event.
2899
+ void notifyClusterStateForWorkflow(workflowId);
2900
+ // Defensive: the drain loop above already empties both arrays on each
2901
+ // iteration. This catches the case where the loop exited via throw —
2902
+ // we don't want the next turn to inherit half-drained state.
2903
+ if (!preserveQueue && (wf.queue.steering.length > 0 || wf.queue.followUp.length > 0)) {
2904
+ wf.queue.steering.length = 0;
2905
+ wf.queue.followUp.length = 0;
2906
+ broadcastQueueUpdate(workflowId);
2907
+ }
2764
2908
  }
2765
2909
  }
2766
- }
2767
- // Stale loop: STOP already disarmed the goal run and owns the teardown; the
2768
- // post-settle armed actions belong to whoever holds the tab now.
2769
- if (staleLoop) {
2770
- // A requested Computer reset still needs a boundary after STOP's
2771
- // interrupt actually settles. A newer busy owner keeps it deferred.
2772
- if (wf.config.voiceOperator) {
2773
- await maybeFreshComputerContext(workflowId, false);
2774
- await drainQueueIfIdle(workflowId);
2775
- await announceComputerSettled(workflowId);
2776
- }
2777
- return;
2778
- }
2779
- if (preserveQueue)
2780
- return;
2781
- // Computer rotates only after the complete tool/queue turn has settled.
2782
- await maybeFreshComputerContext(workflowId, !lastTurnErrored);
2783
- await announceComputerSettled(workflowId);
2784
- // Phase 2 calibration — run after the full drain queue empties (idle moment).
2785
- // Updates per-session ratio/overhead from ground-truth /context output.
2786
- await maybeCalibrate(workflowId, wf, cwd);
2787
- // §2.1 — auto-fold runs FIRST (foldAt sits below the handoff thresholds): the
2788
- // cheap deterministic in-place Fold is tried before recommending a handoff. A
2789
- // successful fold reseeds the session, so skip the (now-stale) handoff check
2790
- // this round — the next turn's meter re-evaluates against the reduced context.
2791
- const clusterIdForPolicy = clusterStore.getClusterIdForWorkflow(workflowId);
2792
- const explicitPolicy = resolveProviderAutoCompaction(wf.config.autoCompaction, clusterIdForPolicy ? clusterStore.getAutoCompaction(clusterIdForPolicy) : undefined, wf.primary.provider, claudeTransport, wf.config.claudeNativeCompact === true, cascade?.ollama?.compaction?.enabled !== undefined || cascade?.ollama?.compaction?.threshold !== undefined);
2793
- if (explicitPolicy) {
2794
- const action = await runExplicitContextActions(workflowId, wf, cwd, explicitPolicy, policyReading, busyToken, ws, session);
2795
- if (action === 'stale')
2796
- return;
2797
- if (action === 'compact-attempted') {
2798
- await drainQueueIfIdle(workflowId);
2910
+ // Stale loop: STOP already disarmed the goal run and owns the teardown; the
2911
+ // post-settle armed actions belong to whoever holds the tab now.
2912
+ if (staleLoop) {
2913
+ // A requested Computer reset still needs a boundary after STOP's
2914
+ // interrupt actually settles. A newer busy owner keeps it deferred.
2915
+ if (wf.config.voiceOperator) {
2916
+ await maybeFreshComputerContext(workflowId, false);
2917
+ await drainQueueIfIdle(workflowId);
2918
+ await announceComputerSettled(workflowId);
2919
+ }
2799
2920
  return;
2800
2921
  }
2922
+ if (preserveQueue)
2923
+ return;
2924
+ // afterTurn.ts — the post-settle steps in their fixed order.
2925
+ await runAfterTurn({
2926
+ // Computer rotates only after the complete tool/queue turn has settled.
2927
+ computer: async () => {
2928
+ await maybeFreshComputerContext(workflowId, !lastTurnErrored);
2929
+ await announceComputerSettled(workflowId);
2930
+ },
2931
+ // Phase 2 calibration: per-session ratio/overhead from ground-truth /context output.
2932
+ calibrate: () => maybeCalibrate(workflowId, wf, cwd),
2933
+ // A due auto-handoff (N compactions this conversation) runs first and
2934
+ // replaces any fold or compaction of this boundary; otherwise the cheap
2935
+ // deterministic Fold, then the auto-compaction policy.
2936
+ context: async () => {
2937
+ const clusterIdForPolicy = clusterStore.getClusterIdForWorkflow(workflowId);
2938
+ const explicitPolicy = resolveProviderAutoCompaction(wf.config.autoCompaction, clusterIdForPolicy ? clusterStore.getAutoCompaction(clusterIdForPolicy) : undefined, wf.primary.provider, claudeTransport, wf.config.claudeNativeCompact === true, cascade?.ollama?.compaction?.enabled !== undefined || cascade?.ollama?.compaction?.threshold !== undefined);
2939
+ if (explicitPolicy) {
2940
+ const action = await runExplicitContextActions(workflowId, wf, cwd, explicitPolicy, policyReading, busyToken, ws, session);
2941
+ if (action === 'stale')
2942
+ return 'stop';
2943
+ if (action === 'compact-attempted') {
2944
+ await drainQueueIfIdle(workflowId);
2945
+ return 'stop';
2946
+ }
2947
+ }
2948
+ else {
2949
+ // Work without an explicit policy: a due auto-handoff first, else
2950
+ // the cheap fold. Provider-owned compaction remains with the provider.
2951
+ if (!(await maybeAutoHandoff(workflowId, wf, cwd)))
2952
+ await maybeAutoFold(workflowId, wf, cwd);
2953
+ }
2954
+ return 'continue';
2955
+ },
2956
+ // Messages typed while auto-fold / auto-handoff held the tab are still
2957
+ // queued; that turn runs its own post-settle chain (goal run included).
2958
+ drainQueue: () => drainQueueIfIdle(workflowId),
2959
+ // docs/GOTCHAS.md - north-star auto-continue, last on purpose: fold,
2960
+ // handoff and compaction all reshape the context this tick would run against.
2961
+ goalRun: () => maybeGoalRun(workflowId, wf, ws, session, lastTurnErrored),
2962
+ });
2801
2963
  }
2802
- else {
2803
- // Preserve existing behavior for work without the new policy.
2804
- const folded = await maybeAutoFold(workflowId, wf, cwd);
2805
- if (!folded)
2806
- await maybeAutoHandoff(workflowId, wf, cwd);
2807
- // Provider-owned compaction remains with the provider.
2964
+ finally {
2965
+ const remaining = (incomingMessages.get(wf) ?? 1) - 1;
2966
+ if (remaining)
2967
+ incomingMessages.set(wf, remaining);
2968
+ else
2969
+ incomingMessages.delete(wf);
2808
2970
  }
2809
- // Messages typed while auto-fold / auto-handoff held the tab are still
2810
- // queued. Flush them first; that turn runs its own post-settle chain (goal
2811
- // run included), so this settle is done.
2812
- if (await drainQueueIfIdle(workflowId))
2813
- return;
2814
- // docs/GOTCHAS.md - north-star auto-continue. Last of the post-settle armed
2815
- // actions on purpose: fold / handoff / compaction all reshape the context
2816
- // this tick would run against, so they get to act first.
2817
- await maybeGoalRun(workflowId, wf, ws, session, lastTurnErrored);
2818
2971
  }
2819
2972
  // docs/GOTCHAS.md - one tick of an armed goal run. Every branch either
2820
2973
  // dispatches exactly one visible turn or stops the run with an operator-