arco-workbench 0.1.4 → 0.1.6

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