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,3 +1,18 @@
1
+ import { setMaxListeners } from 'node:events';
2
+ import { assertNativeTaskAllowed } from './taskAdmission.js';
3
+ import { readSettings } from '../../settings.js';
4
+ import { resolveNativeSubagents, type NativeSubagentPolicy } from '@arco/shared';
5
+ import { availableHandoffSources, executeHandoffHistory, HANDOFF_HISTORY_TOOL, HANDOFF_HISTORY_CONTEXT } from '../../handoffHistoryTool.js';
6
+ import { mediaRetirementNotice } from './mediaRetirementNotice.js';
7
+ import { nativeMediaLimits } from './mediaLimits.js';
8
+ import { retainNewestMedia } from './mediaRetention.js';
9
+ import { PLAN_TOOL_NAMES, PLAN_TOOL_DEFINITIONS, executePlanTool } from '../../planTools.js';
10
+ import { fetchFileContent } from '../../fileFetch.js';
11
+ import { nativeAttachmentContent, nativeFileOutcome, restoreChatAttachments } from './fileContent.js';
12
+ import { admitImageResult, imageReceipts, type ImageReadResult, type ToolResultContent } from './imageRead.js';
13
+ import { shortTextRequestParams } from './modelParams.js';
14
+ import { nativeOAuthBaseUrl } from './apiEndpoint.js';
15
+ import { createHash } from 'node:crypto';
1
16
  import { ensureProjectStateIgnore } from '../../projectStateIgnore.js';
2
17
  import { replayEventsWithTs } from '../../workflowStore.js';
3
18
  import { computerToolDefinitions, executeComputerTool } from '../../voice/toolDefinitions.js';
@@ -13,7 +28,7 @@ import { computerToolDefinitions, executeComputerTool } from '../../voice/toolDe
13
28
 
14
29
  import { EventEmitter } from 'events';
15
30
  import { promises as fs, readFileSync } from 'node:fs';
16
- import { join, extname } from 'node:path';
31
+ import { basename, join, extname } from 'node:path';
17
32
  import Anthropic from '@anthropic-ai/sdk';
18
33
  import type { WorkerConfig, ServerMessage } from '@arco/shared';
19
34
  import { supportsClaudeAdaptiveThinking, isClaudeModelAlias, enforcesPreservedThinking, supportsMidConversationSystemMessages, supportsMidConversationToolChanges } from '@arco/shared';
@@ -21,9 +36,12 @@ import { loadTokens, nativeCredentialBinding } from './auth.js';
21
36
  import type { AuthRecoveryContext } from '@arco/shared';
22
37
  import { ensureLiveTokens, forceRefreshTokens, markClaudeAuthProblem, ClaudeNativeNoAuthError } from './oauth.js';
23
38
  import { resolveTrustStatus } from '../../projectTrust.js';
24
- import { discoverHooks, fireHooks, firstBlocking, parseHookOutput, type HookConfig } from './hooks.js';
25
- import { checkConfigProtection, checkFactForceFirstEdit, checkPartialReadFullWrite, checkHardlineCommand } from './pretoolGuards.js';
26
- import { evaluateGate, gateOutcome } from './gateReview.js';
39
+ import { isShellToolName } from '@arco/shared';
40
+ import { shellToolName } from '../../commandShell.js';
41
+ import { discoverHooks, evaluateHooks, fireHooks, hookToolInput, readHookStdout, type BackgroundHookDone, type HookConfig, type HookEvent, type HookFireResult, type HookVerdict } from './hooks.js';
42
+ import { checkPartialReadFullWrite } from './pretoolGuards.js';
43
+ import { firstBlockingGuard, postToolSteps, runPostToolSteps } from './toolChecks.js';
44
+ import { evaluateGate, gateOutcome, gateSignature, type GateProposal } from './gateReview.js';
27
45
  import { recordPendingGate, clearPendingGate, readGateStore, hasStandingApproval, addStandingApproval } from './gateStore.js';
28
46
  import { getCachedModelCapabilities, getCatalog, hasCatalogCache, resolveClaudeAliasFromCatalog } from './catalog.js';
29
47
  import { filterToolResult } from './filterToolResult.js';
@@ -43,10 +61,11 @@ import { getSandboxToolDefinitions, isSandboxTool, executeSandboxTool } from './
43
61
  import { buildMessagesFromReplayEvents, replayMessagesWithResumePolicy, compactSummarySeed, type ClaudeResumeMessage } from './resumeSummary.js';
44
62
  import { readMeta, setResolvedModelId } from '../../workflowMeta.js';
45
63
  import { lspManager } from '../../lsp/client.js';
46
- import { isClaudeServerToolDef, isServerToolResultType, pruneServerToolEvidenceAfterTurn, stripDanglingServerToolResults } from './retainedContext.js';
64
+ import { isClaudeServerToolDef, isServerToolResultType, pendingServerTools, pruneServerToolEvidenceAfterTurn, stripDanglingServerToolResults } from './retainedContext.js';
47
65
  import { gzipSync } from 'node:zlib';
48
66
  import {
49
- executeNativeTool,
67
+ executeNativeToolResult,
68
+ type NativeToolOutcome,
50
69
  getNativeToolDefinitions,
51
70
  MAX_TOOL_OUTPUT_BYTES,
52
71
  type NativeToolContext,
@@ -65,6 +84,7 @@ import {
65
84
  CLAUDE_CODE_SERVER_TOOLS,
66
85
  buildChatWebTools,
67
86
  buildClaudeServerTools,
87
+ webToolMaxUses,
68
88
  buildContextManagementEditsForRequest,
69
89
  shouldSendCompactBeta,
70
90
  summarizeCompactionIterations,
@@ -72,10 +92,7 @@ import {
72
92
  stripTrailingThinkingFromContent,
73
93
  orphanToolUseIds,
74
94
  fullListOrphanToolUseIds,
75
- buildUserMessageContent,
76
- describeSkippedImages,
77
95
  repairImageBlock,
78
- type SkippedImage,
79
96
  type ToolUseBlock,
80
97
  type AnyContentBlock,
81
98
  type ClaudeNativeToolDef,
@@ -92,7 +109,17 @@ import {
92
109
  projectKeptTail,
93
110
  projectKeptTailByTokens,
94
111
  sleepWithSignal,
112
+ splitSummaryParts,
113
+ estimateSummaryTokens,
114
+ inTurnCompactedHistory,
115
+ inTurnReplaySummary,
116
+ inTurnContinueText,
117
+ keptRequestText,
118
+ keptRequestFits,
119
+ KEPT_REQUEST_MAX_BYTES,
120
+ type KeptRequest,
95
121
  } from './workerHelpers.js';
122
+ import { billableRoundUsage, roundPromptTokens, type MeasurableRound, type RoundPromptMeasure } from './usageContext.js';
96
123
  import { buildFoldDigest } from './foldDigest.js';
97
124
  import { CLAUDE_CLI_USER_AGENT } from './wireFingerprint.js';
98
125
  // docs/PROVIDERS.md - frozen-prefix helpers (pure; unit-tested).
@@ -165,6 +192,15 @@ const FORCED_FIRST_BLOCK = "You are Claude Code, Anthropic's official CLI for Cl
165
192
  // message. Tuned to mirror Claude Code CLI's `/compact`: a dense continuation
166
193
  // brief, not chatty prose. Bounded output so the summary itself stays small.
167
194
  const COMPACT_SUMMARY_MAX_TOKENS = 8192;
195
+ // Room in a summary request for the system blocks, the summarizer prompt and
196
+ // the estimate's error margin.
197
+ const COMPACT_SUMMARY_REQUEST_OVERHEAD_TOKENS = 16_000;
198
+ // The user note after an in-turn compaction (see inTurnCompactedHistory).
199
+ const IN_TURN_COMPACT_NOTE = 'Note from Arco: the context was compacted automatically in the middle of this turn. The summary above replaces the earlier history. Continue the task you were doing; your latest tool calls and their results follow.';
200
+ // How long dispose waits for hook and shell processes to end. A shell gets
201
+ // SIGTERM and, 2 s later, SIGKILL; the Windows tree kill lists the tree first
202
+ // (up to 5 s) and then runs taskkill.
203
+ const PROCESS_EXIT_WAIT_MS = 15_000;
168
204
  // NATIVE_COMPACTION_PLAN Phase 2 — keep-last-N verbatim tail for compactInPlace.
169
205
  // After summarizing the older prefix, the last few user/assistant messages are
170
206
  // kept verbatim (projected to the clean resume shape) so the freshly-active
@@ -246,12 +282,19 @@ interface WorkerOpts {
246
282
  // the worker stays free of WorkflowState / WS knowledge.
247
283
  export interface TaskSpawnArgs {
248
284
  parentWorkflowId: string;
285
+ taskId?: string;
286
+ turnSignal?: AbortSignal;
287
+ signal?: AbortSignal;
288
+ policy?: NativeSubagentPolicy;
289
+ onQueued?: (model: string) => void;
290
+ onModel?: (model: string) => void;
249
291
  description: string;
250
292
  prompt: string;
251
293
  subagentType?: string;
252
294
  model?: string;
253
295
  }
254
296
  export interface TaskSpawnHandle {
297
+ model?: string;
255
298
  taskId: string;
256
299
  childWorkflowId: string;
257
300
  // Resolves with the child's final assistant text when the child settles.
@@ -299,12 +342,33 @@ interface PendingGate {
299
342
  reject: (err: Error) => void;
300
343
  }
301
344
 
345
+ // Claude Code ends the turn after Stop hooks keep the model working this many
346
+ // times in a row (the count resets when the model calls a tool).
347
+ function stopHookBlockCap(): number {
348
+ const n = Number(process.env.CLAUDE_CODE_STOP_HOOK_BLOCK_CAP);
349
+ return Number.isInteger(n) && n > 0 ? n : 8;
350
+ }
351
+
302
352
  export class ClaudeNativeWorker extends EventEmitter {
353
+ private handoffHistoryAvailable = false;
354
+
355
+ private async refreshHandoffHistory(): Promise<void> {
356
+ this.handoffHistoryAvailable = this.config.interactionMode !== 'chat'
357
+ && this.config.clusterAccessMode !== 'blind' && this.config.clusterAccessMode !== 'isolated'
358
+ && (await availableHandoffSources(this.workflowId).catch(() => [])).length > 0;
359
+ }
360
+
303
361
  readonly workflowId: string;
304
362
  private config: WorkerConfig;
305
363
  private client: Anthropic | null = null;
306
364
  private compactAbort?: AbortController;
365
+ private compactCancelEpoch = 0;
366
+ private compactOperationEpoch?: number;
307
367
  private compactInProgress = false;
368
+ // In-turn auto-compaction: `fired` is set when one runs and cleared once a
369
+ // request's prompt is below the threshold again, so a compaction that did not
370
+ // bring usage down is not repeated (one warning instead of a loop).
371
+ private inTurnCompact = { fired: false, warned: false };
308
372
  // The Anthropic SDK pins the OAuth token at construction time. When the
309
373
  // operator runs RE-LOGIN against a long-lived tab, new tokens land on
310
374
  // disk but the cached client still holds the stale token, so every
@@ -314,7 +378,29 @@ export class ClaudeNativeWorker extends EventEmitter {
314
378
  private authRecovery: AuthRecoveryContext = { transport: 'native', binding: nativeCredentialBinding() };
315
379
  private clientTokenObtainedAt: number | null = null;
316
380
  private messages: MessageParam[] = [];
381
+ private heldSteerNotices = new WeakSet<object>();
317
382
  private hooks: HookConfig = { byEvent: {} };
383
+ // Set once discoverTrustedHooks has run (ensureStarted, or a FOLD before any turn).
384
+ private hooksLoaded = false;
385
+ // Notification hooks: permission_prompt after a parked approval has waited,
386
+ // idle_prompt after a finished turn with nothing sent since (Claude Code's timings).
387
+ notifyDelays = { permissionMs: 6_000, idleMs: 60_000 };
388
+ private idleNotifyTimer: NodeJS.Timeout | null = null;
389
+ // Reasons already shown for hooks that did not run (one notice per reason).
390
+ private hooksNotRunReported = new Set<string>();
391
+ // Background hooks (async / asyncRewake) live as long as the worker.
392
+ private hookLifetime = new AbortController();
393
+ // Hook processes still running or being ended (hooks.ts RunOpts.running).
394
+ private runningHooks = new Set<Promise<void>>();
395
+ // Hook output for the model's next request: async hook context, and an
396
+ // asyncRewake report when it arrived during a turn (`wake`).
397
+ private pendingHookContext: Array<{ text: string; wake: boolean }> = [];
398
+ private turnRunning = false;
399
+ // A Task child's first turn ends with SubagentStop instead of Stop.
400
+ private subagentTurnPending = false;
401
+ // Set by a hook's continue:false; the turn ends after the current round.
402
+ private hookStopRequested: string | null = null;
403
+ private hookWakeHandler: ((text: string) => void) | null = null;
318
404
  private replayed = false;
319
405
  private todos: Todo[] = [];
320
406
  // H54 — cache-stable workspace facts block (detected verify/build/test cmds +
@@ -355,6 +441,7 @@ export class ClaudeNativeWorker extends EventEmitter {
355
441
 
356
442
  // Per-turn state.
357
443
  private inFlight: AbortController | null = null;
444
+ private tokenCountAbort: AbortController | null = null;
358
445
  // Text streamed by the CURRENT streamOneRound attempt. A mid-stream
359
446
  // overload retry re-generates the whole round, so this partial is retracted
360
447
  // (`text_discard`) — otherwise the adapter's _output persisted it followed
@@ -365,6 +452,8 @@ export class ClaudeNativeWorker extends EventEmitter {
365
452
  // first streamOneRound then made a fresh, un-aborted controller, so a turn
366
453
  // cancelled during startup still ran (spent tokens, could edit files).
367
454
  private cancelRequested = false;
455
+ private urlReadsThisTurn = 0;
456
+ private fetchUrlContent = fetchFileContent;
368
457
  private toolAbort: AbortController | null = null;
369
458
  private shells: ShellRegistry = {
370
459
  byId: new Map(),
@@ -414,6 +503,9 @@ export class ClaudeNativeWorker extends EventEmitter {
414
503
  // Phase 7b hooks. Wired by ClaudeNativeProvider after construction.
415
504
  private planBroadcast: PlanBroadcast | null = null;
416
505
  private taskHandler: TaskSpawnHandler | null = null;
506
+ private taskTurn = new AbortController();
507
+ private taskPolicy = resolveNativeSubagents();
508
+ private taskRequests = new Map<string, AbortController>();
417
509
  // docs/PROVIDERS.md - generic workflow-scoped event sink for
418
510
  // hook_rewrote_input / tool_gate_triggered / ctx_action. Wired by
419
511
  // ClaudeNativeProvider; no-op when absent (e.g. tests).
@@ -453,6 +545,11 @@ export class ClaudeNativeWorker extends EventEmitter {
453
545
  // Active Task children. Map entry dropped on dispose; on parent cancel,
454
546
  // each child's cancel() runs.
455
547
  private tasksByTaskId = new Map<string, TaskSpawnHandle>();
548
+ // Task children whose card has not received a final status yet. cancel()
549
+ // reports them synchronously: a status emitted later, when the child's
550
+ // promise rejects, would arrive after the operator's STOP has revoked the
551
+ // turn and never reach a browser.
552
+ private unsettledTasks = new Map<string, { toolUseId: string; startedAt: number }>();
456
553
  // docs/ARCHITECTURE.md (E1-Native) - open MCP sessions for this worker's
457
554
  // operator-allowed registry servers, keyed by `ResolvedMcpServer.key`
458
555
  // (`reg-<id8>`). Opened lazily and reconciled at turn start
@@ -461,12 +558,14 @@ export class ClaudeNativeWorker extends EventEmitter {
461
558
  // and MUST be closed on dispose — a leaked stdio child outlives the worker
462
559
  // otherwise (load-bearing, docs/GOTCHAS.md § Claude Native transport).
463
560
  private mcpSessions = new Map<string, McpSession>();
561
+ private mcpDefinitions = new Map<string, string>();
464
562
 
465
563
  constructor(opts: WorkerOpts) {
466
564
  super();
467
565
  this.workflowId = opts.workflowId;
468
566
  this.config = opts.config;
469
567
  this.taskDisabled = opts.taskDisabled === true;
568
+ this.subagentTurnPending = this.taskDisabled;
470
569
  }
471
570
 
472
571
  setTodosBroadcast(fn: (todos: Todo[]) => void): void {
@@ -481,6 +580,11 @@ export class ClaudeNativeWorker extends EventEmitter {
481
580
  this.taskHandler = fn;
482
581
  }
483
582
 
583
+ // Starts a turn for an asyncRewake hook that exits 2 while the tab is idle.
584
+ setHookWakeHandler(fn: (text: string) => void): void {
585
+ this.hookWakeHandler = fn;
586
+ }
587
+
484
588
  setWorkflowEventBroadcast(fn: (msg: ServerMessage) => void): void {
485
589
  this.workflowEventBroadcast = fn;
486
590
  }
@@ -519,7 +623,7 @@ export class ClaudeNativeWorker extends EventEmitter {
519
623
  // toolResultEviction module for the cross-turn tail eviction.
520
624
  private async maybeSpillTurnResults(
521
625
  contentBlocks: AnyContentBlock[],
522
- toolResults: Array<{ type: 'tool_result'; tool_use_id: string; content: string; is_error?: boolean }>,
626
+ toolResults: Array<{ type: 'tool_result'; tool_use_id: string; content: ToolResultContent; is_error?: boolean }>,
523
627
  ): Promise<void> {
524
628
  if (!toolEvictEnabled()) return;
525
629
  if (toolResults.length === 0) return;
@@ -545,10 +649,10 @@ export class ClaudeNativeWorker extends EventEmitter {
545
649
  for (const d of plan.spill) {
546
650
  const tr = byId.get(d.toolUseId);
547
651
  if (!tr) continue;
548
- const originalBytes = Buffer.byteLength(tr.content, 'utf8');
652
+ const originalBytes = Buffer.byteLength(typeof tr.content === 'string' ? tr.content : JSON.stringify(tr.content), 'utf8');
549
653
  let rawArtifactPath: string | undefined;
550
654
  try {
551
- rawArtifactPath = await this.persistRawArtifact(d.toolUseId, tr.content);
655
+ rawArtifactPath = await this.persistRawArtifact(d.toolUseId, typeof tr.content === 'string' ? tr.content : JSON.stringify(tr.content));
552
656
  } catch (err) {
553
657
  console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] tool-evict raw artifact write failed:`, err);
554
658
  }
@@ -574,6 +678,7 @@ export class ClaudeNativeWorker extends EventEmitter {
574
678
  input: unknown,
575
679
  status: 'started' | 'completed' | 'failed',
576
680
  output?: string,
681
+ mediaReceipt?: string,
577
682
  ): void {
578
683
  const payload: {
579
684
  id: string;
@@ -582,6 +687,7 @@ export class ClaudeNativeWorker extends EventEmitter {
582
687
  status: 'started' | 'completed' | 'failed';
583
688
  provider: 'claude';
584
689
  output?: string;
690
+ mediaReceipt?: string;
585
691
  outputHash?: string;
586
692
  } = {
587
693
  id: block.id,
@@ -598,6 +704,7 @@ export class ClaudeNativeWorker extends EventEmitter {
598
704
  // preview) so error-persistence detection compares the whole result.
599
705
  payload.outputHash = outputHash(output);
600
706
  }
707
+ if (mediaReceipt) payload.mediaReceipt = mediaReceipt;
601
708
  this.emit('tool_use', payload);
602
709
  }
603
710
 
@@ -710,6 +817,7 @@ export class ClaudeNativeWorker extends EventEmitter {
710
817
  // appendSystemPrompt rotates per turn (skills manifest, transcript)
711
818
  // and effort/model can be live-edited.
712
819
  this.config = next;
820
+ this.taskDisabled = this.taskDisabled || next.claudeNativeTaskDisabled === true;
713
821
  }
714
822
 
715
823
  // Pre-seed the conversation history before the first runTurn fires.
@@ -765,8 +873,9 @@ export class ClaudeNativeWorker extends EventEmitter {
765
873
  async compactInPlace(stillOwner?: () => boolean): Promise<{ ok: boolean; error?: string; foldedTurns?: number }> {
766
874
  if (this.compactInProgress) return { ok: false, error: 'a compaction is already running' };
767
875
  this.compactInProgress = true;
876
+ this.compactOperationEpoch = this.compactCancelEpoch;
768
877
  try { return await this.compactInPlaceLocked(stillOwner); }
769
- finally { this.compactInProgress = false; }
878
+ finally { this.compactInProgress = false; this.compactOperationEpoch = undefined; }
770
879
  }
771
880
 
772
881
  private async compactInPlaceLocked(stillOwner?: () => boolean): Promise<{ ok: boolean; error?: string; foldedTurns?: number }> {
@@ -820,12 +929,13 @@ export class ClaudeNativeWorker extends EventEmitter {
820
929
  });
821
930
  let summary: string;
822
931
  try {
823
- summary = await this.generateCompactSummary(prefix);
932
+ summary = await this.summarizeInParts(prefix);
824
933
  } catch (err) {
825
934
  return { ok: false, error: err instanceof Error ? err.message : String(err) };
826
935
  }
827
936
  if (!summary.trim()) return { ok: false, error: 'summary came back empty' };
828
937
  if (stillOwner && !stillOwner()) return { ok: false, error: 'compaction cancelled before history replacement' };
938
+ this.inTurnCompact = { fired: false, warned: false };
829
939
  if (pruned.droppedAssistantMessages > 0) {
830
940
  this.workflowEventBroadcast({ type: 'ctx_action', workflowId: this.workflowId, action: 'prune_orphan_tool_use', trigger: 'recovery', detail: `dropped ${pruned.droppedAssistantMessages} orphan assistant message(s) before compact; unpaired tool_use ids: ${pruned.droppedIds.join(', ')}` });
831
941
  }
@@ -845,7 +955,7 @@ export class ClaudeNativeWorker extends EventEmitter {
845
955
  workflowId: this.workflowId,
846
956
  summary,
847
957
  foldedTurns,
848
- ...(tailForSeed.length > 0 ? { keptTail: tailForSeed } : {}),
958
+ ...(tailForSeed.length > 0 ? { keptTail: imageReceipts(tailForSeed) } : {}),
849
959
  });
850
960
  this.workflowEventBroadcast({
851
961
  type: 'primary_tool_counter',
@@ -873,6 +983,7 @@ export class ClaudeNativeWorker extends EventEmitter {
873
983
  if (this.inFlight && !this.inFlight.signal.aborted) {
874
984
  return { ok: false, error: 'a turn is in flight — wait for it to finish' };
875
985
  }
986
+ await this.restoreSavedHistory();
876
987
  if (this.messages.length === 0) {
877
988
  return { ok: false, error: 'nothing to fold yet' };
878
989
  }
@@ -905,7 +1016,7 @@ export class ClaudeNativeWorker extends EventEmitter {
905
1016
  const rawPrefix = keptTail.length > 0 && keptTail.length < this.messages.length
906
1017
  ? this.messages.slice(0, this.messages.length - keptTail.length)
907
1018
  : this.messages;
908
- const tailForSeed = rawPrefix.length === this.messages.length ? [] : keptTail;
1019
+ const tailForSeed = keptTail;
909
1020
 
910
1021
  const digest = buildFoldDigest(
911
1022
  rawPrefix as Array<{ role: string; content: unknown }>,
@@ -945,7 +1056,7 @@ export class ClaudeNativeWorker extends EventEmitter {
945
1056
  originalBytes,
946
1057
  foldedBytes,
947
1058
  byteDelta,
948
- ...(tailForSeed.length > 0 ? { keptTail: tailForSeed } : {}),
1059
+ ...(tailForSeed.length > 0 ? { keptTail: imageReceipts(tailForSeed) } : {}),
949
1060
  });
950
1061
  this.workflowEventBroadcast({
951
1062
  type: 'primary_tool_counter',
@@ -1078,7 +1189,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1078
1189
  engine: 'server',
1079
1190
  summary: result.block.content,
1080
1191
  compactionBlock: result.block,
1081
- ...(kept.length > 0 ? { keptMessages: kept } : {}),
1192
+ ...(kept.length > 0 ? { keptMessages: imageReceipts(kept) } : {}),
1082
1193
  keptTurns: cut.keptTurns,
1083
1194
  foldedTurns,
1084
1195
  trigger: 'operator',
@@ -1101,7 +1212,198 @@ export class ClaudeNativeWorker extends EventEmitter {
1101
1212
  // streaming the text out (we don't surface it as a chat turn). The OAuth
1102
1213
  // endpoint requires the Claude Code identity, so FORCED_FIRST_BLOCK leads the
1103
1214
  // system exactly as on a normal round.
1104
- private async generateCompactSummary(toSummarize: MessageParam[] = this.messages): Promise<string> {
1215
+ // Headroom for the summary request: the projected prefix plus the summarizer
1216
+ // instructions and the summary itself must fit the model's window. When the
1217
+ // prefix is too large for one request it is summarized in parts, oldest
1218
+ // first, each part carrying the previous part's summary in front.
1219
+ private async summarizeInParts(prefix: MessageParam[]): Promise<string> {
1220
+ const epoch = this.compactOperationEpoch ?? this.compactCancelEpoch;
1221
+ const runPart = async (messages: MessageParam[]): Promise<string> => {
1222
+ this.assertCompactionActive(epoch);
1223
+ const summary = await this.generateCompactSummary(messages, epoch);
1224
+ this.assertCompactionActive(epoch);
1225
+ return summary;
1226
+ };
1227
+ const win = lookupCtx(this.capModel()) ?? 200_000;
1228
+ const budget = win - shortTextRequestParams(this.capModel(), COMPACT_SUMMARY_MAX_TOKENS).max_tokens - COMPACT_SUMMARY_REQUEST_OVERHEAD_TOKENS;
1229
+ const pending = [prefix as unknown as Parameters<typeof splitSummaryParts>[0]];
1230
+ let running = '';
1231
+ while (pending.length > 0) {
1232
+ const next = pending.shift()!;
1233
+ const intro = running
1234
+ ? `Summary of the earlier part of this conversation:\n\n${running}`
1235
+ : next[0]?.role === 'assistant' ? 'Summarize this continuation of the conversation.' : '';
1236
+ const room = budget - (intro ? estimateSummaryTokens(`${intro}\n\n`) : 0);
1237
+ if (room < 1) throw new Error('Carried summary exceeds the summary input budget');
1238
+ const chunks = splitSummaryParts(next, room);
1239
+ const part = chunks.shift();
1240
+ if (!part) continue;
1241
+ pending.unshift(...chunks);
1242
+ const messages = part.map((m) => ({ ...m })) as unknown as MessageParam[];
1243
+ if (intro) {
1244
+ const first = messages[0] as unknown as { role: string; content: string | Array<{ text: string }> };
1245
+ if (first.role === 'user') {
1246
+ const firstText = typeof first.content === 'string' ? first.content : first.content.map((b) => b.text).join('');
1247
+ first.content = `${intro}\n\n${firstText}`;
1248
+ } else {
1249
+ messages.unshift({ role: 'user', content: intro } as MessageParam);
1250
+ }
1251
+ }
1252
+ running = await runPart(messages);
1253
+ if (!running.trim()) return '';
1254
+ }
1255
+ return running;
1256
+ }
1257
+
1258
+ // Claude Native in-turn auto-compaction. Called by the turn loop at a clean
1259
+ // boundary: the round's tool results are appended and the next request has
1260
+ // not been sent. Compares that round's prompt size with the threshold and,
1261
+ // once per crossing, compacts the history before the in-progress round and
1262
+ // continues the same turn. Returns 'cancelled' when the operator cancelled
1263
+ // the turn during the summary.
1264
+ private async maybeCompactInTurn(round: MeasurableRound): Promise<'continue' | 'cancelled' | number> {
1265
+ const threshold = this.config.claudeNativeInTurnCompactPercent;
1266
+ if (typeof threshold !== 'number' || !(threshold > 0) || this.config.claudeNativeCompact === true || this.config.interactionMode === 'chat') return 'continue';
1267
+ const win = lookupCtx(this.capModel());
1268
+ if (!win) return 'continue';
1269
+ // The real prompt size, never the summed usage of a server-tool round:
1270
+ // the last pass from usage.iterations, the top-level usage for a
1271
+ // single-pass round, else count_tokens on the history as it stands (tool
1272
+ // results appended, next request not sent). Unmeasured means no decision.
1273
+ const measured = roundPromptTokens(round);
1274
+ let prompt = measured.tokens;
1275
+ if (prompt === undefined && measured.source === 'multi-pass') {
1276
+ prompt = await this.countCurrentContextTokens();
1277
+ console.log(`[claude-native:${this.workflowId.slice(0, 8)}] server-tool round without usage.iterations; context measured by count_tokens: ${prompt ?? 'unavailable'}`);
1278
+ if (this.cancelRequested) return 'cancelled';
1279
+ }
1280
+ if (prompt === undefined || !(prompt > 0)) return 'continue';
1281
+ const ratio = (prompt / win) * 100;
1282
+ const percent = Math.min(100, Math.round(ratio));
1283
+ if (ratio < threshold) {
1284
+ this.inTurnCompact = { fired: false, warned: false };
1285
+ return 'continue';
1286
+ }
1287
+ // The request that started the turn is kept word for word, never cut. A
1288
+ // request over the cap defers the compaction for this turn, said once.
1289
+ if (!keptRequestFits(this.turnOpeningRequest)) {
1290
+ if (!this.inTurnCompact.warned) {
1291
+ this.inTurnCompact.warned = true;
1292
+ this.emit('system_notice', `[AUTO-COMPACT] Context is at ${percent}%, but the request that started this turn (${Math.round((this.turnOpeningRequest?.bytes ?? 0) / 1024)} KB) is larger than the ${Math.round(KEPT_REQUEST_MAX_BYTES / 1024)} KB Arco keeps word for word through an automatic compaction, so Arco will not compact in this turn. Fold or Handoff this tab if the context fills up.`);
1293
+ }
1294
+ return 'continue';
1295
+ }
1296
+ if (this.inTurnCompact.fired) {
1297
+ if (!this.inTurnCompact.warned) {
1298
+ this.inTurnCompact.warned = true;
1299
+ this.emit('system_notice', `[AUTO-COMPACT] Context is still at ${percent}% after compacting automatically in this turn; Arco will not compact again until it falls below ${threshold}%. Fold or Handoff this tab if the context fills up.`);
1300
+ }
1301
+ return 'continue';
1302
+ }
1303
+ this.inTurnCompact = { fired: true, warned: false };
1304
+ if (this.compactInProgress) return 'continue';
1305
+ this.compactInProgress = true;
1306
+ this.compactOperationEpoch = this.compactCancelEpoch;
1307
+ try {
1308
+ const outcome = await this.compactInTurnLocked(percent, threshold);
1309
+ if (this.cancelRequested) return 'cancelled';
1310
+ if (!outcome.ok) {
1311
+ this.emit('system_notice', `[AUTO-COMPACT] Automatic compaction in this turn failed: ${outcome.error ?? 'unknown error'}. History left unchanged; the turn continues.`);
1312
+ return 'continue';
1313
+ }
1314
+ return outcome.noteIndex ?? 'continue';
1315
+ } finally {
1316
+ this.compactInProgress = false;
1317
+ this.compactOperationEpoch = undefined;
1318
+ }
1319
+ }
1320
+
1321
+ private async compactInTurnLocked(percent: number, threshold: number): Promise<{ ok: boolean; error?: string; noteIndex?: number }> {
1322
+ // The in-progress round: the last assistant message (its tool_use blocks
1323
+ // and their thinking) and the user message with the tool results. It is
1324
+ // kept raw; everything before it is summarized.
1325
+ let roundStart = -1;
1326
+ for (let i = this.messages.length - 1; i >= 0; i--) {
1327
+ if (this.messages[i].role === 'assistant') { roundStart = i; break; }
1328
+ }
1329
+ if (roundStart <= 0) return { ok: false, error: 'nothing before the current request to compact' };
1330
+ const originalMessages = this.messages;
1331
+ const inProgressRound = originalMessages.slice(roundStart);
1332
+ let foldedTurns: number;
1333
+ let prefix: MessageParam[];
1334
+ let tailForSeed: ReturnType<typeof projectKeptTail>;
1335
+ try {
1336
+ this.messages = structuredClone(originalMessages.slice(0, roundStart));
1337
+ demoteLeadingServerFoldBlock(this.messages, (t) => compactSummarySeed(t) as MessageParam[]);
1338
+ foldedTurns = this.messages.filter((m) => m.role === 'user').length;
1339
+ this.pruneOrphanToolUse();
1340
+ this.scrubEmptyTextContent();
1341
+ this.stripTrailingThinkingBlocks();
1342
+ const keptTail = projectKeptTail(this.messages, COMPACT_KEEP_LAST_MESSAGES);
1343
+ const rawPrefix = keptTail.length > 0 && keptTail.length < this.messages.length
1344
+ ? this.messages.slice(0, this.messages.length - keptTail.length) : this.messages;
1345
+ prefix = projectCompactSummaryMessages(rawPrefix) as MessageParam[];
1346
+ tailForSeed = rawPrefix.length === this.messages.length ? [] : keptTail;
1347
+ } finally {
1348
+ this.messages = originalMessages;
1349
+ }
1350
+ if (prefix.length === 0) return { ok: false, error: 'nothing before the current request to summarize' };
1351
+ // PreCompact hooks run as for every automatic compaction; a block skips it.
1352
+ const blocked = await this.preCompactBlock('auto');
1353
+ if (blocked) return { ok: false, error: `a PreCompact hook blocked the compaction. ${blocked}` };
1354
+ if (this.cancelRequested) return { ok: false, error: 'cancelled' };
1355
+ const reason = { trigger: 'auto-in-turn' as const, percent, thresholdPercent: threshold };
1356
+ this.emit('system_notice', `Compacting automatically (context ${percent}%)`);
1357
+ this.workflowEventBroadcast({ type: 'native_compacting', workflowId: this.workflowId, foldedTurns, ...reason });
1358
+ let summary: string;
1359
+ try {
1360
+ summary = await this.summarizeInParts(prefix);
1361
+ } catch (err) {
1362
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
1363
+ }
1364
+ if (this.cancelRequested) return { ok: false, error: 'cancelled' };
1365
+ if (!summary.trim()) return { ok: false, error: 'summary came back empty' };
1366
+ // The history may only have grown by nothing while the summary ran: the
1367
+ // loop is paused here, so the in-progress round is still the last one.
1368
+ if (this.messages !== originalMessages || this.messages.length !== roundStart + inProgressRound.length) {
1369
+ return { ok: false, error: 'history changed during the summary' };
1370
+ }
1371
+ const seed = compactSummarySeed(summary, tailForSeed);
1372
+ const keptRequest = this.turnOpeningRequest ?? undefined;
1373
+ this.messages = inTurnCompactedHistory(seed, IN_TURN_COMPACT_NOTE, inProgressRound, keptRequest);
1374
+ // Persisted only when the history gained it (replay composes the same text).
1375
+ const requestKept = keptRequest !== undefined && inTurnContinueText(IN_TURN_COMPACT_NOTE, keptRequest, tailForSeed) !== IN_TURN_COMPACT_NOTE;
1376
+ this.resetPrefixFreeze('compact');
1377
+ this.toolCallCountSinceCompact = 0;
1378
+ this.readSet.clear();
1379
+ this.partialReadSet.clear();
1380
+ const after = await this.countCurrentContextTokens();
1381
+ const win = lookupCtx(this.capModel());
1382
+ this.workflowEventBroadcast({
1383
+ type: 'native_compacted',
1384
+ workflowId: this.workflowId,
1385
+ summary: inTurnReplaySummary(summary, inProgressRound),
1386
+ foldedTurns,
1387
+ ...(tailForSeed.length > 0 ? { keptTail: imageReceipts(tailForSeed) } : {}),
1388
+ ...reason,
1389
+ inTurn: true,
1390
+ continueNote: IN_TURN_COMPACT_NOTE,
1391
+ ...(requestKept ? { keptRequest: keptRequest.text } : {}),
1392
+ ...(typeof after === 'number' && after > 0 ? { promptTokensAfter: after } : {}),
1393
+ ...(win ? { contextWindow: win } : {}),
1394
+ });
1395
+ this.workflowEventBroadcast({ type: 'primary_tool_counter', workflowId: this.workflowId, toolCallsSinceCompact: 0 });
1396
+ const afterPercent = typeof after === 'number' && after > 0 && win ? ` (context now ${Math.min(100, Math.round((after / win) * 100))}%)` : '';
1397
+ this.emit('system_notice', `Compacted, continuing${afterPercent}`);
1398
+ return { ok: true, noteIndex: this.messages.length - inProgressRound.length - 1 };
1399
+ }
1400
+
1401
+ private assertCompactionActive(epoch: number): void {
1402
+ if (epoch !== this.compactCancelEpoch) throw new Error('Compaction cancelled');
1403
+ }
1404
+
1405
+ private async generateCompactSummary(toSummarize: MessageParam[] = this.messages, epoch = this.compactOperationEpoch ?? this.compactCancelEpoch): Promise<string> {
1406
+ this.assertCompactionActive(epoch);
1105
1407
  // ARCO_TEST compact-probe: return a canned summary instead of calling the
1106
1408
  // Anthropic API, so the smoke can exercise the real compactInPlace keep-tail
1107
1409
  // + native_compacted emission without spend. Gated on both the probe flag
@@ -1123,7 +1425,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1123
1425
  try {
1124
1426
  const resp = await this.client!.messages.create({
1125
1427
  model: this.requestModel(),
1126
- max_tokens: COMPACT_SUMMARY_MAX_TOKENS,
1428
+ ...shortTextRequestParams(this.capModel(), COMPACT_SUMMARY_MAX_TOKENS),
1127
1429
  system: system as unknown as string,
1128
1430
  messages: messages as unknown as Parameters<Anthropic['messages']['create']>[0]['messages'],
1129
1431
  stream: true,
@@ -1141,50 +1443,9 @@ export class ClaudeNativeWorker extends EventEmitter {
1141
1443
  } finally { if (this.compactAbort === controller) this.compactAbort = undefined; }
1142
1444
  }
1143
1445
 
1144
- cancelCompaction(): void { this.compactAbort?.abort(); }
1446
+ cancelCompaction(): void { this.compactCancelEpoch++; this.compactAbort?.abort(); }
1145
1447
 
1146
- async ensureStarted(): Promise<void> {
1147
- // ARCO_TEST compact-probe: history is pre-seeded and the summary is
1148
- // canned, so skip the OAuth / client-rebuild path entirely.
1149
- if (this.compactProbeMode) return;
1150
- // Always probe live tokens — if the operator re-logged in since this
1151
- // worker built its client, ensureLiveTokens() returns the fresh set
1152
- // and the obtainedAt mismatch below forces a client rebuild. Cheap:
1153
- // ensureLiveTokens is a single disk read on the happy path.
1154
- const tokens = await ensureLiveTokens();
1155
- this.authRecovery = { transport: 'native', binding: nativeCredentialBinding(tokens) };
1156
- // An alias tab can't be dispatched until the alias resolves to a concrete
1157
- // id. Warm the catalog once per worker so the resolution is catalog-backed
1158
- // (newest family member) rather than the static CLAUDE_ALIAS_FALLBACK.
1159
- // Failure is non-fatal — the fallback still yields a real, dispatchable id.
1160
- if (!this.catalogWarmAttempted && isClaudeModelAlias(this.config.model) && !hasCatalogCache()) {
1161
- this.catalogWarmAttempted = true;
1162
- await getCatalog(false).catch((err) => {
1163
- console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] catalog warm for alias '${this.config.model}' failed; using static fallback:`, err instanceof Error ? err.message : err);
1164
- });
1165
- }
1166
- if (this.client && this.clientTokenObtainedAt === tokens.obtainedAt) return;
1167
- const isRebuild = this.client !== null;
1168
- if (isRebuild) {
1169
- console.log(`[claude-native:${this.workflowId.slice(0, 8)}] tokens rotated — rebuilding Anthropic client`);
1170
- }
1171
- this.client = new Anthropic({
1172
- authToken: tokens.accessToken,
1173
- defaultHeaders: this.buildDefaultHeaders(),
1174
- // H10 — our handleApiError ladder is the SINGLE retry path. The SDK's
1175
- // default maxRetries:2 would retry 429/529/500 INTERNALLY before throwing,
1176
- // then our 3-attempt ladder ran on top — compounding to ~6 attempts and
1177
- // minutes of stacked backoff per turn. 0 lets our header-aware ladder own
1178
- // the timing.
1179
- maxRetries: 0,
1180
- } as ConstructorParameters<typeof Anthropic>[0]);
1181
- this.clientTokenObtainedAt = tokens.obtainedAt;
1182
- // Token-rotation rebuilds reuse the existing hooks + replayed state
1183
- // and skip the worker-init emit. Hooks come from CLAUDE.md files,
1184
- // unrelated to auth; replay only ever runs once per worker; 'init'
1185
- // is for first-time wiring on the consumer side.
1186
- if (isRebuild) return;
1187
- this.hooks = await this.discoverTrustedHooks();
1448
+ private async restoreSavedHistory(): Promise<void> {
1188
1449
  if (!this.replayed) {
1189
1450
  const cwd = this.config.persistenceCwd ?? this.config.cwd;
1190
1451
  if (cwd) {
@@ -1201,14 +1462,15 @@ export class ClaudeNativeWorker extends EventEmitter {
1201
1462
  this.servedModel = meta.resolvedModelId;
1202
1463
  this.servedModelFor = this.config.model;
1203
1464
  }
1465
+ const attachmentMarkers = this.config.interactionMode === 'chat' && !this.config.voiceOperator ? new Map<string, string>() : undefined;
1204
1466
  const replay = this.config.voiceOperator
1205
1467
  ? { messages: buildMessagesFromReplayEvents((await replayEventsWithTs(cwd, this.workflowId, 0))
1206
1468
  .filter((e) => meta?.computerContext?.lastResetSeq !== undefined
1207
1469
  ? (('seq' in e.message && typeof e.message.seq === 'number') ? e.message.seq : 0) > meta.computerContext.lastResetSeq
1208
1470
  : e.ts > (meta?.computerContext?.lastResetAt ?? 0)).map((e) => e.message) as unknown as Parameters<typeof buildMessagesFromReplayEvents>[0]),
1209
1471
  mode: 'exact', reconstructed: false, summaryThroughSeq: undefined, tailEvents: undefined }
1210
- : await replayMessagesWithResumePolicy(cwd, this.workflowId, undefined, { leafSeq: meta?.leafSeq });
1211
- this.messages = replay.messages as MessageParam[];
1472
+ : await replayMessagesWithResumePolicy(cwd, this.workflowId, undefined, { leafSeq: meta?.leafSeq, attachmentMarkers });
1473
+ this.messages = attachmentMarkers ? await restoreChatAttachments(replay.messages as MessageParam[], attachmentMarkers) : replay.messages as MessageParam[];
1212
1474
  this.resetPrefixFreeze('replay');
1213
1475
  if (replay.reconstructed) {
1214
1476
  // docs/PERSISTENCE.md - the rewound branch's ancestry
@@ -1230,6 +1492,57 @@ export class ClaudeNativeWorker extends EventEmitter {
1230
1492
  }
1231
1493
  this.replayed = true;
1232
1494
  }
1495
+ }
1496
+
1497
+ async ensureStarted(): Promise<void> {
1498
+ // ARCO_TEST compact-probe: history is pre-seeded and the summary is
1499
+ // canned, so skip the OAuth / client-rebuild path entirely.
1500
+ if (this.compactProbeMode) return;
1501
+ // Always probe live tokens — if the operator re-logged in since this
1502
+ // worker built its client, ensureLiveTokens() returns the fresh set
1503
+ // and the obtainedAt mismatch below forces a client rebuild. Cheap:
1504
+ // ensureLiveTokens is a single disk read on the happy path.
1505
+ const tokens = await ensureLiveTokens();
1506
+ this.authRecovery = { transport: 'native', binding: nativeCredentialBinding(tokens) };
1507
+ // An alias tab can't be dispatched until the alias resolves to a concrete
1508
+ // id. Warm the catalog once per worker so the resolution is catalog-backed
1509
+ // (newest family member) rather than the static CLAUDE_ALIAS_FALLBACK.
1510
+ // Failure is non-fatal — the fallback still yields a real, dispatchable id.
1511
+ if (!this.catalogWarmAttempted && isClaudeModelAlias(this.config.model) && !hasCatalogCache()) {
1512
+ this.catalogWarmAttempted = true;
1513
+ await getCatalog(false).catch((err) => {
1514
+ console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] catalog warm for alias '${this.config.model}' failed; using static fallback:`, err instanceof Error ? err.message : err);
1515
+ });
1516
+ }
1517
+ const baseURL = await nativeOAuthBaseUrl();
1518
+ if (this.client && this.clientTokenObtainedAt === tokens.obtainedAt && this.client.baseURL === baseURL) return;
1519
+ const isRebuild = this.client !== null;
1520
+ if (isRebuild) {
1521
+ console.log(`[claude-native:${this.workflowId.slice(0, 8)}] credentials or endpoint changed - rebuilding Anthropic client`);
1522
+ }
1523
+ this.client = new Anthropic({
1524
+ authToken: tokens.accessToken,
1525
+ apiKey: null,
1526
+ baseURL,
1527
+ defaultHeaders: this.buildDefaultHeaders(),
1528
+ // H10 — our handleApiError ladder is the SINGLE retry path. The SDK's
1529
+ // default maxRetries:2 would retry 429/529/500 INTERNALLY before throwing,
1530
+ // then our 3-attempt ladder ran on top — compounding to ~6 attempts and
1531
+ // minutes of stacked backoff per turn. 0 lets our header-aware ladder own
1532
+ // the timing.
1533
+ maxRetries: 0,
1534
+ } as ConstructorParameters<typeof Anthropic>[0]);
1535
+ this.clientTokenObtainedAt = tokens.obtainedAt;
1536
+ // Token-rotation rebuilds reuse the existing hooks + replayed state
1537
+ // and skip the worker-init emit. Hooks come from CLAUDE.md files,
1538
+ // unrelated to auth; replay only ever runs once per worker; 'init'
1539
+ // is for first-time wiring on the consumer side.
1540
+ if (isRebuild) return;
1541
+ if (!this.hooksLoaded) {
1542
+ this.hooks = await this.discoverTrustedHooks();
1543
+ this.hooksLoaded = true;
1544
+ }
1545
+ await this.restoreSavedHistory();
1233
1546
  // H54 — probe workspace facts once per cwd (cache-stable). Best-effort: a
1234
1547
  // failure just means no facts block, never a broken turn.
1235
1548
  const factsCwd = this.config.cwd ?? process.cwd();
@@ -1511,9 +1824,10 @@ export class ClaudeNativeWorker extends EventEmitter {
1511
1824
 
1512
1825
  // Close + drop sessions no longer wanted (no leaked children).
1513
1826
  for (const [key, session] of this.mcpSessions) {
1514
- if (!wantedKeys.has(key)) {
1827
+ if (!wantedKeys.has(key) || session.isClosed()) {
1515
1828
  try { session.close(); } catch { /* already gone */ }
1516
1829
  this.mcpSessions.delete(key);
1830
+ this.mcpDefinitions.delete(key);
1517
1831
  }
1518
1832
  }
1519
1833
 
@@ -1521,7 +1835,16 @@ export class ClaudeNativeWorker extends EventEmitter {
1521
1835
  // ResolvedMcpServer carries the spawn fields (command/args/env) — the rest
1522
1836
  // (id/name/enabled/createdAt) are unused by the spawn path.
1523
1837
  for (const server of wanted) {
1524
- if (this.mcpSessions.has(server.key)) continue;
1838
+ const fingerprint = createHash('sha256').update(JSON.stringify([
1839
+ server.command, server.args, Object.entries(server.env ?? {}).sort(([a], [b]) => a.localeCompare(b)),
1840
+ ])).digest('hex');
1841
+ const current = this.mcpSessions.get(server.key);
1842
+ if (current && this.mcpDefinitions.get(server.key) === fingerprint) continue;
1843
+ if (current) {
1844
+ current.close();
1845
+ this.mcpSessions.delete(server.key);
1846
+ this.mcpDefinitions.delete(server.key);
1847
+ }
1525
1848
  const session = await connectServer({
1526
1849
  id: server.key,
1527
1850
  name: server.key,
@@ -1532,6 +1855,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1532
1855
  createdAt: 0,
1533
1856
  });
1534
1857
  this.mcpSessions.set(server.key, session);
1858
+ this.mcpDefinitions.set(server.key, fingerprint);
1535
1859
  }
1536
1860
  }
1537
1861
 
@@ -1542,11 +1866,12 @@ export class ClaudeNativeWorker extends EventEmitter {
1542
1866
  try { session.close(); } catch { /* already gone */ }
1543
1867
  }
1544
1868
  this.mcpSessions.clear();
1869
+ this.mcpDefinitions.clear();
1545
1870
  }
1546
1871
 
1547
1872
  private buildToolDefs(): ClaudeNativeToolDef[] {
1548
1873
  // Chat has no project toolset. When the operator arms web access the tab
1549
- // gets exactly web_search + web_fetch — no filesystem, no shell, no MCP,
1874
+ // gets web_search + web_fetch + read_url - no filesystem, no shell, no MCP,
1550
1875
  // no posture filter (there is nothing left for it to filter).
1551
1876
  if (this.config.interactionMode === 'chat') {
1552
1877
  if (this.config.voiceOperator) return computerToolDefinitions().map(({ function: f }) => ({ name: f.name, description: f.description, input_schema: f.parameters })) as ClaudeNativeToolDef[];
@@ -1556,6 +1881,8 @@ export class ClaudeNativeWorker extends EventEmitter {
1556
1881
  const isolated = this.config.clusterAccessMode === 'isolated';
1557
1882
  const base = getNativeToolDefinitions({ taskDisabled: this.taskDisabled || inCluster, isolated });
1558
1883
  const extras: ReturnType<typeof getNativeToolDefinitions> = [];
1884
+ if (!isolated && this.config.cwd && this.workflowId) extras.push(...PLAN_TOOL_DEFINITIONS);
1885
+ if (this.handoffHistoryAvailable && !isolated && this.config.clusterAccessMode !== 'blind') extras.push(HANDOFF_HISTORY_TOOL);
1559
1886
  if (inCluster) {
1560
1887
  extras.push(...getPeerToolDefinitions({
1561
1888
  taskBoardAttached: this.config.clusterTaskBoardAttached === true,
@@ -1580,7 +1907,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1580
1907
  if (!isolated && (this.config.efficiencySandbox ?? 'off') === 'on') extras.push(...getSandboxToolDefinitions());
1581
1908
  // docs/ARCHITECTURE.md - Deep Research threads its `maxRounds`
1582
1909
  // through as `webSearchMaxUses` so the web_search / web_fetch budget is a
1583
- // MECHANICAL hard ceiling, not just a prompt-stated cap. Unset ⇒ default 10.
1910
+ // MECHANICAL hard ceiling, not just a prompt-stated cap. Unset uses the default of 15.
1584
1911
  const serverTools = this.config.webSearchMaxUses !== undefined
1585
1912
  ? buildClaudeServerTools(this.config.webSearchMaxUses)
1586
1913
  : CLAUDE_CODE_SERVER_TOOLS;
@@ -1640,6 +1967,9 @@ export class ClaudeNativeWorker extends EventEmitter {
1640
1967
  blocks.push({ type: 'text', text: goalText });
1641
1968
  }
1642
1969
 
1970
+ if (this.handoffHistoryAvailable && this.buildToolDefs().some(tool => tool.name === 'handoff_history')) {
1971
+ blocks.push({ type: 'text', text: HANDOFF_HISTORY_CONTEXT });
1972
+ }
1643
1973
  let planIdx = -1;
1644
1974
  const planText = this.config.clusterPlan;
1645
1975
  if (planText && planText.trim().length > 0) {
@@ -1715,10 +2045,10 @@ export class ClaudeNativeWorker extends EventEmitter {
1715
2045
  blocks.push({
1716
2046
  type: 'text',
1717
2047
  text:
1718
- 'You have ctx_execute / ctx_search / ctx_fetch available alongside Read / Bash. Prefer them when:\n' +
2048
+ `You have ctx_execute / ctx_search / ctx_fetch available alongside Read / ${shellToolName()}. Prefer them when:\n` +
1719
2049
  ' - Reading large files where you only need a small section (pipe through head/grep/jq in the script and console.log only the slice).\n' +
1720
2050
  " - Running shell commands whose output is mostly noise — you can filter inside the script and only print what's relevant.\n" +
1721
- 'The full Read / Bash tools remain available — use them when the operator asked for full output, or when the section you need is small. ' +
2051
+ `The full Read / ${shellToolName()} tools remain available — use them when the operator asked for full output, or when the section you need is small. ` +
1722
2052
  'To stash content for later retrieval print lines as `[chunk] <text>` (or open `[chunk]` / close `[/chunk]` for multi-line); each becomes a searchable chunk. ' +
1723
2053
  'Retrieve via ctx_search (BM25) and ctx_fetch (exact id).',
1724
2054
  });
@@ -1726,7 +2056,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1726
2056
  if (!isolated) blocks.push({
1727
2057
  type: 'text',
1728
2058
  text:
1729
- 'You have two execution environments. Use Arco local tools (Read, Bash, Edit, Write, Grep, Glob) for the operator workspace and machine state. ' +
2059
+ `You have two execution environments. Use Arco local tools (Read, ${shellToolName()}, Edit, Write, Grep, Glob) for the operator workspace and machine state. ` +
1730
2060
  'The Anthropic code_execution server tool is a separate sandbox; use it only for web_search/web_fetch dynamic filtering or isolated computation that does not require local files/processes.',
1731
2061
  });
1732
2062
  // Place turn-completion guidance before operator instructions, which
@@ -1740,7 +2070,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1740
2070
  'if your final paragraph describes work you have not done, do that work now instead of ending the turn. ' +
1741
2071
  'Finishing the request does not mean waiting for it: do not sleep or poll for more than 60 seconds at a time for builds, test suites or CI; report what is running and end the turn. ' +
1742
2072
  'If a delegated Task child fails or returns an error or nonsense (e.g. a login error), say so explicitly in your reply and adapt openly — never silently work around a failed delegation. ' +
1743
- // Fable 5.1 rewrites whole files where a targeted edit would do
2073
+ // Fable 5.1 / 5.2 can rewrite whole files where a targeted edit would do
1744
2074
  // (docs/PROVIDERS.md); Anthropic's documented one-liner.
1745
2075
  'The number of tokens used to edit files is best minimized, all else being equal. Therefore, when it will not affect the end result, try to surgically edit a file rather than rewrite the entire thing.',
1746
2076
  });
@@ -1837,10 +2167,131 @@ export class ClaudeNativeWorker extends EventEmitter {
1837
2167
  return { byEvent: found.byEvent };
1838
2168
  }
1839
2169
 
2170
+ // The common hook input fields Claude Code sends, plus Arco's workflow_id.
2171
+ // transcript_path is this tab's event log (JSON lines in Arco's own format,
2172
+ // written in the background, so it can lag the current turn as Claude
2173
+ // Code's transcript can). During a Task child's turn the hooks also get
2174
+ // agent_id and agent_type, and transcript_path is the parent's log.
2175
+ private hookInput(extra: Record<string, unknown>): Record<string, unknown> {
2176
+ const sub = this.subagentTurnPending ? this.config.claudeNativeSubagent : undefined;
2177
+ return {
2178
+ session_id: sub?.parentWorkflowId ?? this.workflowId,
2179
+ transcript_path: this.transcriptPath(sub?.parentWorkflowId ?? this.workflowId),
2180
+ cwd: this.config.cwd ?? process.cwd(),
2181
+ permission_mode: this.planMode ? 'plan' : 'default',
2182
+ workflow_id: this.workflowId,
2183
+ ...(sub ? { agent_id: this.workflowId, agent_type: sub.agentType } : {}),
2184
+ ...extra,
2185
+ };
2186
+ }
2187
+
2188
+ private transcriptPath(workflowId: string): string {
2189
+ return join(this.config.persistenceCwd ?? this.config.cwd ?? process.cwd(), '.arco', 'workflows', workflowId, 'events.jsonl');
2190
+ }
2191
+
2192
+ // Notification hooks run in the background; their exit code, output and
2193
+ // stderr are ignored, as in Claude Code. Only a hook that could not start
2194
+ // is reported.
2195
+ private fireNotification(type: 'permission_prompt' | 'idle_prompt', message: string, title: string): void {
2196
+ if (!this.hooks.byEvent.Notification?.length) return;
2197
+ const cwd = this.config.cwd ?? process.cwd();
2198
+ void fireHooks(this.hooks, 'Notification', type, this.hookInput({ message, title, notification_type: type }), this.hookRunOpts(cwd, this.hookLifetime.signal))
2199
+ .then((results) => this.reportHooks('Notification', results, evaluateHooks('Notification', type, [])))
2200
+ .catch(() => { /* reported through the results */ });
2201
+ }
2202
+
2203
+ private clearIdleNotification(): void {
2204
+ if (this.idleNotifyTimer) clearTimeout(this.idleNotifyTimer);
2205
+ this.idleNotifyTimer = null;
2206
+ }
2207
+
2208
+ // PreCompact hooks before COMPACT and FOLD, manual or automatic, matched
2209
+ // against the trigger. Exit 2, decision "block" or a failure with onFailure
2210
+ // "block" skips the compaction; the reason comes back for the notice.
2211
+ async preCompactBlock(trigger: 'manual' | 'auto', customInstructions: string | null = null): Promise<string | null> {
2212
+ if (!this.hooksLoaded) {
2213
+ this.hooks = await this.discoverTrustedHooks();
2214
+ this.hooksLoaded = true;
2215
+ }
2216
+ if (!this.hooks.byEvent.PreCompact?.length) return null;
2217
+ const v = await this.runHooks('PreCompact', trigger, { trigger, custom_instructions: customInstructions }, this.config.cwd ?? process.cwd(), this.hookLifetime.signal);
2218
+ if (v.blocks.length === 0) return null;
2219
+ return v.blocks.map((b) => `[${b.command}]: ${b.reason}`).join('\n').slice(0, 2000);
2220
+ }
2221
+
2222
+ private hookRunOpts(cwd: string, abortSignal: AbortSignal): Parameters<typeof fireHooks>[4] {
2223
+ return {
2224
+ cwd,
2225
+ abortSignal,
2226
+ shells: this.shells,
2227
+ workflowId: this.workflowId,
2228
+ backgroundSignal: this.hookLifetime.signal,
2229
+ onBackground: (done) => this.onBackgroundHook(done),
2230
+ running: this.runningHooks,
2231
+ };
2232
+ }
2233
+
2234
+ // Runs the hooks for one event, shows the operator what Claude Code shows
2235
+ // (non-blocking errors, systemMessage, not-run reasons, the PowerShell
2236
+ // notice) and returns the verdict.
2237
+ private async runHooks(event: HookEvent, target: string, extra: Record<string, unknown>, cwd: string, abortSignal: AbortSignal): Promise<HookVerdict> {
2238
+ const results = await fireHooks(this.hooks, event, target, this.hookInput(extra), this.hookRunOpts(cwd, abortSignal));
2239
+ const verdict = evaluateHooks(event, target, results);
2240
+ this.reportHooks(event, results, verdict);
2241
+ return verdict;
2242
+ }
2243
+
2244
+ private reportHooks(event: string, results: HookFireResult[], verdict: HookVerdict): void {
2245
+ const blockedBy = new Set(verdict.blocks.filter((b) => b.via === 'failure').map((b) => b.command));
2246
+ for (const r of results) {
2247
+ if (r.shellNotice && !this.hooksNotRunReported.has(r.shellNotice)) {
2248
+ this.hooksNotRunReported.add(r.shellNotice);
2249
+ this.emit('system_notice', `[HOOKS] ${r.shellNotice}`);
2250
+ }
2251
+ if (!r.notRun || blockedBy.has(r.command ?? '') || this.hooksNotRunReported.has(r.notRun)) continue;
2252
+ this.hooksNotRunReported.add(r.notRun);
2253
+ this.emit('system_notice', `[HOOKS] A ${event} hook did not run, so the action went ahead. ${r.notRun}${r.command ? ` Hook: ${r.command.slice(0, 200)}` : ''}`);
2254
+ }
2255
+ for (const n of verdict.notices) this.emit('system_notice', `[HOOKS] ${n.slice(0, 1500)}`);
2256
+ // Claude Code discards systemMessage and continue on these events.
2257
+ if (event === 'PreCompact' || event === 'Notification') return;
2258
+ for (const m of verdict.systemMessages) this.emit('system_notice', `[HOOKS] ${m.slice(0, 2000)}`);
2259
+ if (verdict.stop) this.emit('system_notice', `[HOOKS] A ${event} hook stopped processing${verdict.stop.reason ? `: ${verdict.stop.reason.slice(0, 1000)}` : '.'}`);
2260
+ }
2261
+
2262
+ // async: its additionalContext and systemMessage reach the model with the
2263
+ // next request. asyncRewake: exit 2 wakes the model with stderr (or stdout).
2264
+ private onBackgroundHook({ event, target, hook, result }: BackgroundHookDone): void {
2265
+ const label = event === 'UserPromptSubmit' || event === 'Stop' ? event : `${event}:${target}`;
2266
+ if (hook.asyncRewake === true) {
2267
+ if (result.exitCode !== 2) return;
2268
+ const said = (result.stderr.trim() || result.stdout.trim()).slice(0, 4000);
2269
+ const text = `${label} hook [${hook.command}] reported (asyncRewake):\n${said || '(no output)'}`;
2270
+ if (this.turnRunning) this.pendingHookContext.push({ text, wake: true });
2271
+ else this.hookWakeHandler?.(text);
2272
+ return;
2273
+ }
2274
+ const json = readHookStdout(result.stdout).json;
2275
+ if (!json) return;
2276
+ const hso = json.hookSpecificOutput && typeof json.hookSpecificOutput === 'object' ? json.hookSpecificOutput as Record<string, unknown> : {};
2277
+ for (const value of [hso.additionalContext, json.systemMessage]) {
2278
+ if (typeof value === 'string' && value.trim()) this.pendingHookContext.push({ text: `${label} hook [${hook.command}] (async):\n${value.slice(0, 10_000)}`, wake: false });
2279
+ }
2280
+ }
2281
+
2282
+ // Hook text waiting for the model, as one block; empties the queue.
2283
+ private takeHookContext(): string | null {
2284
+ if (this.pendingHookContext.length === 0) return null;
2285
+ const text = this.pendingHookContext.map((c) => c.text).join('\n\n');
2286
+ this.pendingHookContext = [];
2287
+ return text;
2288
+ }
2289
+
1840
2290
  // Operator clicks CANCEL / RSS guard / tab close.
1841
2291
  cancel(): void {
1842
2292
  this.cancelCompaction();
1843
2293
  this.cancelRequested = true;
2294
+ try { this.tokenCountAbort?.abort(); } catch { /* already aborted */ }
1844
2295
  try { this.inFlight?.abort(); } catch { /* already aborted */ }
1845
2296
  try { this.toolAbort?.abort(); } catch { /* already aborted */ }
1846
2297
  // Reject any awaiting AskUserQuestion so the tool result returns the
@@ -1855,17 +2306,32 @@ export class ClaudeNativeWorker extends EventEmitter {
1855
2306
  try { g.reject(new Error('AbortError: turn cancelled')); } catch { /* ignore */ }
1856
2307
  }
1857
2308
  }
1858
- // Cascade cancel to any in-flight Task children.
1859
- for (const handle of this.tasksByTaskId.values()) {
1860
- try { handle.cancel(); } catch { /* already gone */ }
2309
+ this.cancelPendingTasks();
2310
+ }
2311
+
2312
+ private cancelPendingTasks(): void {
2313
+ // Settle before the parent error/result unwires lifecycle forwarding.
2314
+ const active = [...this.unsettledTasks.keys()];
2315
+ for (const [taskId, task] of this.unsettledTasks) {
2316
+ this.emit('task_status', { taskId, toolUseId: task.toolUseId, phase: 'cancelled', elapsedMs: Date.now() - task.startedAt, summary: 'Cancelled.' });
2317
+ }
2318
+ this.unsettledTasks.clear();
2319
+ this.taskTurn.abort();
2320
+ for (const request of this.taskRequests.values()) request.abort();
2321
+ for (const id of active) {
2322
+ try { this.tasksByTaskId.get(id)?.cancel(); } catch { /* already gone */ }
1861
2323
  }
1862
2324
  }
1863
2325
 
1864
2326
  async dispose(): Promise<void> {
1865
2327
  this.cancel();
1866
- // Kill any leftover background shells.
2328
+ this.clearIdleNotification();
2329
+ this.hookLifetime.abort();
2330
+ // Kill any leftover background shells, and wait below until they have ended.
2331
+ const shellsEnding: Promise<void>[] = [];
1867
2332
  for (const reg of this.shells.byId.values()) {
1868
2333
  try { reg.kill(); } catch { /* gone */ }
2334
+ if (reg.ended) shellsEnding.push(reg.ended);
1869
2335
  }
1870
2336
  this.shells.byId.clear();
1871
2337
  this.tasksByTaskId.clear();
@@ -1878,6 +2344,21 @@ export class ClaudeNativeWorker extends EventEmitter {
1878
2344
  this.client = null;
1879
2345
  this.messages = [];
1880
2346
  this.replayed = false;
2347
+ // Background hooks (async, asyncRewake, Notification) have no timeout and
2348
+ // run_in_background shells run until they finish, so dispose waits until
2349
+ // the kills above have ended every hook and shell process tree: a leftover
2350
+ // process would keep running and, on Windows, keep the project folder in
2351
+ // use. Capped so a stuck taskkill cannot hold dispose forever.
2352
+ const ending = [...this.runningHooks, ...shellsEnding];
2353
+ if (ending.length > 0) {
2354
+ let capTimer: NodeJS.Timeout | undefined;
2355
+ const capped = await Promise.race([
2356
+ Promise.all(ending).then(() => false),
2357
+ new Promise<boolean>((resolve) => { capTimer = setTimeout(() => resolve(true), PROCESS_EXIT_WAIT_MS); }),
2358
+ ]);
2359
+ if (capTimer) clearTimeout(capTimer);
2360
+ if (capped) console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] hook or shell processes still ending ${PROCESS_EXIT_WAIT_MS}ms after dispose`);
2361
+ }
1881
2362
  }
1882
2363
 
1883
2364
  // Defense-in-depth before every messages.create. Anthropic rejects with
@@ -1979,7 +2460,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1979
2460
  // Returns a replacement text block for an over-cap image, else null
1980
2461
  // (retyping happens in place).
1981
2462
  const repairImage = (b: Record<string, unknown>): AnyContentBlock | null => {
1982
- const r = repairImageBlock(b);
2463
+ const r = repairImageBlock(b, nativeMediaLimits(lookupCtx(this.capModel()), this.client?.baseURL));
1983
2464
  if (r.action === 'retyped') retypedImages++;
1984
2465
  if (r.action !== 'replace') return null;
1985
2466
  replacedOversizedImages++;
@@ -2092,13 +2573,99 @@ export class ClaudeNativeWorker extends EventEmitter {
2092
2573
 
2093
2574
  // An interrupt during auth/hooks must not silently lose a queued correction.
2094
2575
  turnInputAccepted = false;
2576
+ // The request that started the running turn (text plus attachment
2577
+ // references, byte-capped). An in-turn compaction keeps it word for word:
2578
+ // in a long turn the kept tail holds tool rounds, and a turn whose model
2579
+ // wrote no text between tool calls would otherwise keep the request only
2580
+ // inside the summary.
2581
+ private turnOpeningRequest: KeptRequest | null = null;
2582
+
2583
+ private retiredImagesThisTurn = 0;
2584
+ private retiredDocumentsThisTurn = 0;
2585
+
2586
+ private flushMediaRetirementNotice(): void {
2587
+ const notice = mediaRetirementNotice(this.retiredImagesThisTurn, this.retiredDocumentsThisTurn);
2588
+ this.retiredImagesThisTurn = 0;
2589
+ this.retiredDocumentsThisTurn = 0;
2590
+ if (notice) this.emit('system_notice', notice);
2591
+ }
2592
+
2593
+ override emit(event: string | symbol, ...args: unknown[]): boolean {
2594
+ // The adapter unwires on result/error, so deliver the aggregate first.
2595
+ if (event === 'result' || event === 'error') { this.cancelPendingTasks(); this.flushMediaRetirementNotice(); }
2596
+ return super.emit(event, ...args);
2597
+ }
2598
+
2599
+ private async admitMedia(pending: unknown, result: ImageReadResult, origin: 'tool' | 'attachment' = 'tool'): Promise<ImageReadResult> {
2600
+ const limits = nativeMediaLimits(lookupCtx(this.capModel()), this.client?.baseURL);
2601
+ // Attachment and tool preparation happen between API requests. Retirement
2602
+ // builds new objects; the previous request's history is never edited.
2603
+ let protectedRoundStart = this.messages.length;
2604
+ for (let index = this.messages.length - 1; index >= 0; index--) {
2605
+ const message = this.messages[index];
2606
+ if (message.role !== 'assistant') continue;
2607
+ if (Array.isArray(message.content) && message.content.some(block => block.type === 'tool_use')) protectedRoundStart = index;
2608
+ break;
2609
+ }
2610
+ const retained = await retainNewestMedia(this.messages, pending, result, limits, protectedRoundStart);
2611
+ if (retained.history !== this.messages) {
2612
+ this.messages = retained.history;
2613
+ this.resetPrefixFreeze('media-retention');
2614
+ }
2615
+ if (retained.pending !== pending && Array.isArray(pending) && Array.isArray(retained.pending)) pending.splice(0, pending.length, ...retained.pending);
2616
+ this.retiredImagesThisTurn += retained.imagesReplaced;
2617
+ this.retiredDocumentsThisTurn += retained.documentsReplaced;
2618
+ return admitImageResult(this.messages, pending, result, origin, limits);
2619
+ }
2095
2620
 
2096
2621
  async runTurn(prompt: string): Promise<void> {
2622
+ this.cancelPendingTasks();
2623
+ this.taskTurn = new AbortController();
2624
+ setMaxListeners(0, this.taskTurn.signal);
2625
+ this.retiredImagesThisTurn = 0;
2626
+ this.retiredDocumentsThisTurn = 0;
2627
+ this.turnRunning = true;
2628
+ this.hookStopRequested = null;
2629
+ this.clearIdleNotification();
2630
+ const subagentTurn = this.subagentTurnPending;
2631
+ try {
2632
+ await this.runTurnInner(prompt);
2633
+ } finally {
2634
+ this.cancelPendingTasks();
2635
+ this.flushMediaRetirementNotice();
2636
+ this.turnRunning = false;
2637
+ this.subagentTurnPending = false;
2638
+ // idle_prompt: the turn finished and nothing was sent for a while. Not
2639
+ // after a cancel, and not for a Task child's own turn.
2640
+ if (!subagentTurn && !this.cancelRequested && this.hooks.byEvent.Notification?.length) {
2641
+ this.idleNotifyTimer = setTimeout(() => {
2642
+ this.idleNotifyTimer = null;
2643
+ this.fireNotification('idle_prompt', 'Claude is waiting for your input', 'Claude Code');
2644
+ }, this.notifyDelays.idleMs);
2645
+ this.idleNotifyTimer.unref?.();
2646
+ }
2647
+ // An asyncRewake report that arrived during the turn and was not sent
2648
+ // with a later request wakes the model now.
2649
+ const wakes = this.pendingHookContext.filter((c) => c.wake);
2650
+ if (wakes.length > 0) {
2651
+ this.pendingHookContext = this.pendingHookContext.filter((c) => !c.wake);
2652
+ this.hookWakeHandler?.(wakes.map((w) => w.text).join('\n\n'));
2653
+ }
2654
+ }
2655
+ }
2656
+
2657
+ private async runTurnInner(prompt: string): Promise<void> {
2097
2658
  // Reset synchronously, before the first await: the adapter calls runTurn
2098
2659
  // from spawn() and any kill() can only land after this line.
2099
2660
  this.cancelRequested = false;
2661
+ this.urlReadsThisTurn = 0;
2100
2662
  this.turnInputAccepted = false;
2101
2663
  try {
2664
+ await this.refreshHandoffHistory();
2665
+ if (this.cancelledDuringStartup()) return;
2666
+ const taskDefaults = await readSettings(this.config.cwd).catch(() => undefined);
2667
+ if (this.cancelledDuringStartup()) return;
2668
+ this.taskPolicy = resolveNativeSubagents(taskDefaults?.nativeSubagents, this.config.nativeSubagents);
2102
2669
  await this.ensureStarted();
2103
2670
  } catch (err) {
2104
2671
  try { this.authRecovery = { transport: 'native', binding: nativeCredentialBinding(await loadTokens()) }; } catch { this.authRecovery = { transport: 'native' }; }
@@ -2157,17 +2724,16 @@ export class ClaudeNativeWorker extends EventEmitter {
2157
2724
  this.planMode = true;
2158
2725
  }
2159
2726
 
2160
- // UserPromptSubmit hook fires before the first messages.create.
2161
- const ups = await fireHooks(
2162
- this.hooks,
2163
- 'UserPromptSubmit',
2164
- 'UserPromptSubmit',
2165
- { prompt, workflow_id: this.workflowId, project_dir: this.config.cwd ?? '' },
2166
- { cwd: this.config.cwd ?? process.cwd(), abortSignal: this.makeAbortSignal('toolAbort'), shells: this.shells, workflowId: this.workflowId },
2167
- );
2168
- const blocked = firstBlocking(ups);
2169
- if (blocked) {
2170
- this.emit('system_notice', `UserPromptSubmit hook blocked turn (exit ${blocked.exitCode}): ${blocked.stderr.trim().slice(0, 500)}`);
2727
+ // UserPromptSubmit hooks run before the first messages.create. Exit 2 or
2728
+ // decision "block" (or continue:false) rejects the prompt and shows the
2729
+ // reason to the operator only; other non-zero exits are non-blocking
2730
+ // errors. additionalContext and plain stdout ride with the prompt.
2731
+ const ups = await this.runHooks('UserPromptSubmit', 'UserPromptSubmit',
2732
+ { prompt, project_dir: this.config.cwd ?? '' },
2733
+ this.config.cwd ?? process.cwd(), this.makeAbortSignal('toolAbort'));
2734
+ if (ups.blocks.length > 0 || ups.stop) {
2735
+ const why = ups.blocks.length > 0 ? ups.blocks.map((b) => b.reason).join('\n') : (ups.stop?.reason || 'a hook stopped processing');
2736
+ this.emit('system_notice', `UserPromptSubmit hook blocked the prompt: ${why.slice(0, 1500)}${ups.suppressOriginalPrompt ? '' : `\nOriginal prompt: ${prompt.slice(0, 2000)}`}`);
2171
2737
  this.emit('error', 'turn aborted by UserPromptSubmit hook');
2172
2738
  return;
2173
2739
  }
@@ -2214,11 +2780,19 @@ export class ClaudeNativeWorker extends EventEmitter {
2214
2780
  // bound to them, and the prefix diff re-appends whatever they carried.
2215
2781
  const poppedSystem = popTrailingSystemMessages(this.messages);
2216
2782
  if (poppedSystem > 0) console.log(`[claude-native:${this.workflowId.slice(0, 8)}] popped ${poppedSystem} trailing role:system message(s) before operator turn`);
2217
- const skippedImages: SkippedImage[] = [];
2218
- this.messages.push({ role: 'user', content: buildUserMessageContent(prompt, this.config.attachments, skippedImages) });
2783
+ const attached = await nativeAttachmentContent(prompt, this.config.attachments, this.messages, this.inFlight?.signal, (pending, result, origin) => this.admitMedia(pending, result, origin), this.config.interactionMode === 'chat' && !this.config.voiceOperator);
2784
+ for (const notice of attached.notices) this.emit('system_notice', notice);
2785
+ this.messages.push({ role: 'user', content: attached.content });
2219
2786
  this.turnInputAccepted = true;
2220
- const skippedNotice = describeSkippedImages(skippedImages);
2221
- if (skippedNotice) this.emit('system_notice', skippedNotice);
2787
+ this.turnOpeningRequest = keptRequestText(prompt, this.config.interactionMode === 'chat' && !this.config.voiceOperator ? this.config.attachments?.map(path => basename(path)) : this.config.attachments);
2788
+ this.inTurnCompact = { fired: false, warned: false };
2789
+ // UserPromptSubmit context and waiting async hook output ride with the
2790
+ // operator's message (never in `system`, so the cached prefix is kept).
2791
+ const promptHookText = [
2792
+ ...ups.context.map((c) => `UserPromptSubmit hook additional context:\n${c.slice(0, 10_000)}`),
2793
+ ...(() => { const t = this.takeHookContext(); return t ? [t] : []; })(),
2794
+ ].join('\n\n');
2795
+ if (promptHookText) appendTextToLastUserMessage(this.messages, promptHookText);
2222
2796
  // docs/PROVIDERS.md - per-turn operator notice (mailbox
2223
2797
  // depth, plan-mode arm). Lives on the user turn, never in `system`, and is
2224
2798
  // never removed: rebuilding it next turn would be a prefix edit.
@@ -2238,11 +2812,12 @@ export class ClaudeNativeWorker extends EventEmitter {
2238
2812
  // H9 — fresh loop counters for this turn (primary_turn_started boundary).
2239
2813
  this.toolLoopGuard.reset();
2240
2814
  let totalUsage: Record<string, number> | undefined;
2241
- // Track the LATEST round's usage separately. mergeUsage sums across
2242
- // rounds, which is right for billing/output but wrong for context-fill —
2243
- // the size of the prompt the model saw in context is the LAST round's
2244
- // (cache_read + cache_creation + input), not the sum across rounds.
2245
- let lastRoundUsage: Record<string, number> | undefined;
2815
+ // Track the LATEST round's prompt size separately. mergeUsage sums across
2816
+ // rounds, which is right for billing/output but wrong for context-fill:
2817
+ // the size of the prompt the model saw is the LAST round's, and for a
2818
+ // round that ran server tools it is the last PASS of that round, never
2819
+ // the round's summed usage (usageContext.ts).
2820
+ let lastRoundPrompt: RoundPromptMeasure | undefined;
2246
2821
  let stopReason: string | null = null;
2247
2822
  let finalText = '';
2248
2823
  // Opus-5 plan Phase 3 — carry the LAST round's stop_details so the
@@ -2252,9 +2827,10 @@ export class ClaudeNativeWorker extends EventEmitter {
2252
2827
  // docs/PROVIDERS.md - index where this turn's appended messages
2253
2828
  // start, so the end-of-turn telemetry walk only counts blocks added on
2254
2829
  // this turn (not the entire session).
2255
- const turnMessageStart = this.messages.length - 1;
2830
+ let turnMessageStart = this.messages.length - 1;
2256
2831
 
2257
2832
  let iterations = 0;
2833
+ let stopHookContinuations = 0;
2258
2834
  while (iterations++ < MAX_TOOL_TURNS) {
2259
2835
  const round = await this.streamOneRound();
2260
2836
  if (!round) {
@@ -2267,8 +2843,8 @@ export class ClaudeNativeWorker extends EventEmitter {
2267
2843
  stopReason = round.stopReason;
2268
2844
  finalText = round.text;
2269
2845
  stopDetails = round.stopDetails ?? null;
2270
- totalUsage = mergeUsage(totalUsage, round.usage);
2271
- if (round.usage) lastRoundUsage = round.usage;
2846
+ totalUsage = mergeUsage(totalUsage, billableRoundUsage(round.usage, round.usageIterations));
2847
+ if (round.usage) lastRoundPrompt = roundPromptTokens(round);
2272
2848
 
2273
2849
  // Re-emit init with the *echoed* model on the first round-trip so the
2274
2850
  // chat header upgrades from the requested ID to the canonical one
@@ -2322,11 +2898,22 @@ export class ClaudeNativeWorker extends EventEmitter {
2322
2898
  // Gating on stop_reason alone silently abandons the tools: the model
2323
2899
  // narrates intent, the tool calls show in Activity, but nothing runs
2324
2900
  // (`tools 0B`) and the orphaned client tool_use is pruned next turn.
2325
- if (!shouldContinueNativeToolLoop(round.contentBlocks, stopReason)) break;
2901
+ if (!shouldContinueNativeToolLoop(round.contentBlocks, stopReason)) {
2902
+ // Stop (SubagentStop for a Task child's turn) hooks: exit 2, decision
2903
+ // "block" or additionalContext keep the model working with the reason
2904
+ // as its next instruction, at most STOP_HOOK_BLOCK_CAP times in a row.
2905
+ const feedback = await this.runStopHooks(round.text, stopReason, stopHookContinuations);
2906
+ if (feedback === null) break;
2907
+ stopHookContinuations += 1;
2908
+ const extra = this.takeHookContext();
2909
+ this.messages.push({ role: 'user', content: [{ type: 'text', text: extra ? `${feedback}\n\n${extra}` : feedback }] as unknown as AnyContentBlock[] });
2910
+ continue;
2911
+ }
2912
+ if (round.contentBlocks.some((b) => b.type === 'tool_use')) stopHookContinuations = 0;
2326
2913
 
2327
2914
  // ── Tool-use round-trip ──
2328
2915
  this.toolAbort = new AbortController();
2329
- const toolResults: Array<{ type: 'tool_result'; tool_use_id: string; content: string; is_error?: boolean }> = [];
2916
+ const toolResults: Array<{ type: 'tool_result'; tool_use_id: string; content: ToolResultContent; is_error?: boolean }> = [];
2330
2917
  // Task children run in isolated child workflows with no shared
2331
2918
  // filesystem/process state, so concurrent dispatch is safe and
2332
2919
  // turns "write four docs in parallel" into actual parallelism.
@@ -2346,11 +2933,16 @@ export class ClaudeNativeWorker extends EventEmitter {
2346
2933
  // tool tripped; handled (graceful abort) once this round's results are in.
2347
2934
  let loopStopRequested = false;
2348
2935
  for (const block of otherBlocks) {
2349
- const result = await this.dispatchTool(block);
2936
+ // A hook returned continue:false: the rest of this round does not run.
2937
+ if (this.hookStopRequested !== null) {
2938
+ toolResults.push({ type: 'tool_result', tool_use_id: block.id, content: 'Not run: a hook stopped processing.', is_error: true });
2939
+ continue;
2940
+ }
2941
+ const result = await this.dispatchTool(block, toolResults);
2350
2942
  toolResults.push({
2351
2943
  type: 'tool_result',
2352
2944
  tool_use_id: block.id,
2353
- content: truncateOutput(result.text),
2945
+ content: result.content ?? truncateOutput(result.text),
2354
2946
  ...(result.isError ? { is_error: true } : {}),
2355
2947
  });
2356
2948
  if (this.checkToolLoop(block, result)) loopStopRequested = true;
@@ -2367,7 +2959,7 @@ export class ClaudeNativeWorker extends EventEmitter {
2367
2959
  toolResults.push({
2368
2960
  type: 'tool_result',
2369
2961
  tool_use_id: block.id,
2370
- content: truncateOutput(result.text),
2962
+ content: result.content ?? truncateOutput(result.text),
2371
2963
  ...(result.isError ? { is_error: true } : {}),
2372
2964
  });
2373
2965
  if (this.checkToolLoop(block, result)) loopStopRequested = true;
@@ -2390,7 +2982,16 @@ export class ClaudeNativeWorker extends EventEmitter {
2390
2982
  // operator arms ARCO_TOOL_EVICT — like clear_tool_uses it can spill a
2391
2983
  // result the model still needs. Cross-turn tail eviction lives in Fold.
2392
2984
  await this.maybeSpillTurnResults(round.contentBlocks, toolResults);
2393
- this.messages.push({ role: 'user', content: toolResults as unknown as AnyContentBlock[] });
2985
+ const hookText = this.takeHookContext();
2986
+ const content = hookText ? [...toolResults, { type: 'text', text: hookText }] : toolResults;
2987
+ this.messages.push({ role: 'user', content: content as unknown as AnyContentBlock[] });
2988
+ }
2989
+
2990
+ // A hook returned continue:false: end the turn now that every tool_use
2991
+ // of this round has its result.
2992
+ if (this.hookStopRequested !== null) {
2993
+ this.hookStopRequested = null;
2994
+ break;
2394
2995
  }
2395
2996
 
2396
2997
  // H9 — graceful hard-stop (armed only). The tool_results are appended above
@@ -2405,6 +3006,37 @@ export class ClaudeNativeWorker extends EventEmitter {
2405
3006
  return;
2406
3007
  }
2407
3008
 
3009
+ // Client results alone do not close a mixed server/client turn. Match
3010
+ // server results across assistant messages before adding ordinary user
3011
+ // input or replacing history; either would end an unresolved turn.
3012
+ const pendingServer = pendingServerTools(this.messages, turnMessageStart);
3013
+ if (pendingServer.length > 0) {
3014
+ const work = pendingServer.every((name) => name === 'web_search') ? 'web search finishes'
3015
+ : pendingServer.every((name) => name === 'web_fetch') ? 'web fetch finishes' : 'server tools finish';
3016
+ for (const item of this.config.peekSteer?.() ?? []) {
3017
+ if (this.heldSteerNotices.has(item)) continue;
3018
+ this.heldSteerNotices.add(item);
3019
+ this.emit('system_notice', `Message held until ${work}.`);
3020
+ }
3021
+ continue;
3022
+ }
3023
+
3024
+ // In-turn auto-compaction at a clean boundary: every tool_use of this
3025
+ // round has its result and the next request has not been sent. Runs
3026
+ // before the steer drain so a steer lands after the compacted history.
3027
+ if (toolResults.length > 0) {
3028
+ const compacted = await this.maybeCompactInTurn(round);
3029
+ if (compacted === 'cancelled') {
3030
+ this.emit('error', 'Worker killed');
3031
+ this.scrubServerToolEvidenceOnAbort(turnMessageStart);
3032
+ this.inFlight = null;
3033
+ this.toolAbort = null;
3034
+ return;
3035
+ }
3036
+ // The rebuilt history starts this turn's own messages at the note.
3037
+ if (typeof compacted === 'number') turnMessageStart = compacted;
3038
+ }
3039
+
2408
3040
  // Phase 5 hook — same placement as ollama.ts. Drained items become
2409
3041
  // role:'user' messages before the next round-trip. Steer attachments
2410
3042
  // get the same image-block treatment as the operator's first prompt.
@@ -2419,10 +3051,9 @@ export class ClaudeNativeWorker extends EventEmitter {
2419
3051
  if (toolResults.length === 0) continue;
2420
3052
  const steer = this.config.drainSteer?.() ?? [];
2421
3053
  for (const item of steer) {
2422
- const skippedSteer: SkippedImage[] = [];
2423
- this.messages.push({ role: 'user', content: buildUserMessageContent(item.content, item.attachments, skippedSteer) });
2424
- const steerNotice = describeSkippedImages(skippedSteer);
2425
- if (steerNotice) this.emit('system_notice', steerNotice);
3054
+ const attached = await nativeAttachmentContent(item.content, item.attachments, this.messages, this.inFlight?.signal, (pending, result, origin) => this.admitMedia(pending, result, origin), this.config.interactionMode === 'chat' && !this.config.voiceOperator);
3055
+ for (const notice of attached.notices) this.emit('system_notice', notice);
3056
+ this.messages.push({ role: 'user', content: attached.content });
2426
3057
  }
2427
3058
  }
2428
3059
 
@@ -2513,6 +3144,7 @@ export class ClaudeNativeWorker extends EventEmitter {
2513
3144
  for (const sub of c as Array<Record<string, unknown>>) {
2514
3145
  const txt = typeof sub.text === 'string' ? sub.text : '';
2515
3146
  toolResultBytes += Buffer.byteLength(txt, 'utf8');
3147
+ if ((sub.type === 'image' || sub.type === 'document') && isRecord(sub.source) && typeof sub.source.data === 'string') toolResultBytes += Buffer.byteLength(sub.source.data, 'utf8');
2516
3148
  }
2517
3149
  }
2518
3150
  } else if (typeof t === 'string' && isServerToolResultType(t)) {
@@ -2540,11 +3172,13 @@ export class ClaudeNativeWorker extends EventEmitter {
2540
3172
  }
2541
3173
  }
2542
3174
  const countedPromptTokens = await this.countCurrentContextTokens();
2543
- const usagePromptTokens = lastRoundUsage
2544
- ? (lastRoundUsage.cache_read_input_tokens ?? 0) +
2545
- (lastRoundUsage.cache_creation_input_tokens ?? 0) +
2546
- (lastRoundUsage.input_tokens ?? 0)
2547
- : undefined;
3175
+ // Fallback only for a single-pass round (or a round whose iterations name
3176
+ // the last pass). A server-tool round without iterations has no honest
3177
+ // usage figure: better no CTX reading this turn than an inflated one.
3178
+ const usagePromptTokens = lastRoundPrompt?.tokens;
3179
+ if (countedPromptTokens === undefined && lastRoundPrompt?.source === 'multi-pass') {
3180
+ console.log(`[claude-native:${this.workflowId.slice(0, 8)}] last round ran server tools and reported no usage.iterations; no context figure for this turn (count_tokens unavailable)`);
3181
+ }
2548
3182
  const lastPromptTokens = countedPromptTokens ?? usagePromptTokens;
2549
3183
 
2550
3184
  this.emit('result', {
@@ -2560,31 +3194,62 @@ export class ClaudeNativeWorker extends EventEmitter {
2560
3194
  serverToolResultBytes,
2561
3195
  });
2562
3196
 
2563
- // Stop hook (informational).
3197
+ // Stop hooks ran in the loop above, before the turn ended.
2564
3198
  // Clear the per-turn controller before returning to idle. `streamOneRound`
2565
3199
  // installs a fresh AbortController for every provider round; leaving the
2566
3200
  // final successful controller in place made later operator COMPACT clicks
2567
3201
  // look like a live turn even after `wf.busy` had cleared.
2568
3202
  this.inFlight = null;
2569
3203
  this.toolAbort = null;
2570
- void fireHooks(
2571
- this.hooks,
2572
- 'Stop',
2573
- 'Stop',
2574
- { workflow_id: this.workflowId, stop_reason: stopReason ?? 'unknown' },
2575
- { cwd: this.config.cwd ?? process.cwd(), abortSignal: this.makeAbortSignal('toolAbort'), shells: this.shells, workflowId: this.workflowId },
2576
- ).catch((err) => console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] Stop hook failed:`, err));
2577
- this.toolAbort = null;
3204
+ }
3205
+
3206
+ // Stop hooks when the model finished responding (SubagentStop on a Task
3207
+ // child's turn, matched against its agent type). Returns the feedback for
3208
+ // the model's next request when a hook keeps it working, else null. Not run
3209
+ // for a truncated, refused or cancelled response (Claude Code fires
3210
+ // StopFailure there, which Arco does not run).
3211
+ private async runStopHooks(lastText: string, stopReason: string | null, continuations: number): Promise<string | null> {
3212
+ if (stopReason === 'model_context_window_exceeded' || stopReason === 'refusal' || stopReason === 'max_tokens') return null;
3213
+ if (this.cancelRequested || this.inFlight?.signal.aborted) return null;
3214
+ const subagent = this.subagentTurnPending;
3215
+ const agentType = this.config.claudeNativeSubagent?.agentType ?? 'general-purpose';
3216
+ const event: HookEvent = subagent ? 'SubagentStop' : 'Stop';
3217
+ const extra: Record<string, unknown> = {
3218
+ stop_hook_active: continuations > 0,
3219
+ last_assistant_message: lastText,
3220
+ stop_reason: stopReason ?? 'unknown',
3221
+ ...(subagent ? { agent_id: this.workflowId, agent_type: agentType, agent_transcript_path: this.transcriptPath(this.workflowId) } : {}),
3222
+ };
3223
+ const v = await this.runHooks(event, subagent ? agentType : 'Stop', extra, this.config.cwd ?? process.cwd(), this.makeAbortSignal('toolAbort'));
3224
+ if (v.stop) return null;
3225
+ const parts = [...v.blocks.map((b) => `[${b.command}]: ${b.reason}`), ...v.context];
3226
+ if (parts.length === 0) return null;
3227
+ const cap = stopHookBlockCap();
3228
+ if (continuations >= cap) {
3229
+ this.emit('system_notice', `[HOOKS] ${event} hooks kept the model working ${cap} times in a row, so the turn ends here. CLAUDE_CODE_STOP_HOOK_BLOCK_CAP raises the limit.`);
3230
+ return null;
3231
+ }
3232
+ const text = parts.join('\n\n').slice(0, 20_000);
3233
+ this.emit('system_notice', `[HOOKS] ${event} hook feedback; the model keeps working:\n${text.slice(0, 1500)}`);
3234
+ return `${event} hook feedback:\n${text}`;
2578
3235
  }
2579
3236
 
2580
3237
  private async countCurrentContextTokens(): Promise<number | undefined> {
2581
- if (!this.client) return undefined;
3238
+ if (!this.client || this.cancelRequested) return undefined;
3239
+ const controller = new AbortController();
3240
+ this.tokenCountAbort = controller;
3241
+ const timer = setTimeout(() => controller.abort(), 5_000);
3242
+ let onAbort!: () => void;
3243
+ const cancelled = new Promise<never>((_resolve, reject) => {
3244
+ onAbort = () => reject(new Error('Token count cancelled or timed out'));
3245
+ controller.signal.addEventListener('abort', onAbort, { once: true });
3246
+ });
2582
3247
  try {
2583
3248
  const effort = this.config.effort ?? 'high';
2584
3249
  const thinkingParams = buildThinkingParams(this.capModel(), effort, this.config.claudeNativeThinkingDisplay ?? 'omitted');
2585
3250
  const betaHeader = this.buildBetaHeader();
2586
3251
  const prefix = this.peekPrefix();
2587
- const counted = await this.client.messages.countTokens({
3252
+ const counted = await Promise.race([cancelled, this.client.messages.countTokens({
2588
3253
  model: this.requestModel(),
2589
3254
  cache_control: { type: 'ephemeral' },
2590
3255
  system: prefix.system as unknown as string,
@@ -2595,12 +3260,19 @@ export class ClaudeNativeWorker extends EventEmitter {
2595
3260
  ...thinkingParams,
2596
3261
  } as Parameters<Anthropic['messages']['countTokens']>[0], {
2597
3262
  headers: { 'anthropic-beta': betaHeader },
2598
- });
3263
+ signal: controller.signal,
3264
+ timeout: 5_000,
3265
+ maxRetries: 0,
3266
+ })]);
2599
3267
  return counted.input_tokens;
2600
3268
  } catch (err) {
2601
3269
  const detail = err instanceof Error ? err.message : String(err);
2602
3270
  console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] count_tokens failed; falling back to response usage: ${detail.slice(0, 300)}`);
2603
3271
  return undefined;
3272
+ } finally {
3273
+ clearTimeout(timer);
3274
+ controller.signal.removeEventListener('abort', onAbort);
3275
+ if (this.tokenCountAbort === controller) this.tokenCountAbort = null;
2604
3276
  }
2605
3277
  }
2606
3278
 
@@ -2611,6 +3283,11 @@ export class ClaudeNativeWorker extends EventEmitter {
2611
3283
  text: string;
2612
3284
  contentBlocks: AnyContentBlock[];
2613
3285
  usage?: Record<string, number>;
3286
+ // Raw `usage.iterations` when the API sent it: one entry per sampling
3287
+ // pass. The last message pass is the real prompt size of a server-tool
3288
+ // round (usageContext.ts); a compaction pass is billed but absent from
3289
+ // the top-level fields.
3290
+ usageIterations?: unknown;
2614
3291
  echoedModel?: string;
2615
3292
  stopDetails?: StopDetails | null;
2616
3293
  }> {
@@ -2898,7 +3575,7 @@ export class ClaudeNativeWorker extends EventEmitter {
2898
3575
  const dense: AnyContentBlock[] = [];
2899
3576
  for (const b of blocks) if (b) dense.push(b);
2900
3577
  this.noticeServerCompaction(dense, usageIterations);
2901
- return { stopReason, text: allText, contentBlocks: dense, usage, echoedModel, stopDetails };
3578
+ return { stopReason, text: allText, contentBlocks: dense, usage, ...(usageIterations !== undefined ? { usageIterations } : {}), echoedModel, stopDetails };
2902
3579
  }
2903
3580
 
2904
3581
  // One cheap system_notice per compacting response so the operator can see
@@ -2916,15 +3593,31 @@ export class ClaudeNativeWorker extends EventEmitter {
2916
3593
  this.emit('system_notice', `Server compaction ${detail}; the summary replaces that history on later requests.`);
2917
3594
  }
2918
3595
 
2919
- private async dispatchTool(block: ToolUseBlock): Promise<{ text: string; isError: boolean }> {
3596
+ private async dispatchTool(block: ToolUseBlock, pendingResults: unknown = []): Promise<NativeToolOutcome> {
2920
3597
  if (this.config.interactionMode === 'chat' && this.config.voiceOperator) {
2921
3598
  const text = await executeComputerTool(this.workflowId, block.name, block.input);
2922
3599
  return { text, isError: text.startsWith('[error]') };
2923
3600
  }
2924
3601
  // A frozen tool prefix can outlive a switch into chat mode. Never execute
2925
3602
  // a local tool from that older prefix after the switch.
2926
- if (this.config.interactionMode === 'chat') return { text: '[error] tools are unavailable in chat mode', isError: true };
3603
+ if (block.name === 'read_url') {
3604
+ if (!this.buildToolDefs().some(tool => tool.name === 'read_url')) {
3605
+ return { text: '[error] URL reading is unavailable with the current web access or tool posture.', isError: true };
3606
+ }
3607
+ if (this.urlReadsThisTurn >= webToolMaxUses(this.config.webSearchMaxUses)) {
3608
+ return { text: '[error] URL reading reached its per-turn web lookup limit.', isError: true };
3609
+ }
3610
+ this.urlReadsThisTurn++;
3611
+ } else if (this.config.interactionMode === 'chat') return { text: '[error] tools are unavailable in chat mode', isError: true };
2927
3612
  const matcher = block.name;
3613
+ // One shell tool is offered (Bash, or PowerShell on Windows without Git
3614
+ // Bash). The other name is an unknown tool, as in Claude Code: refused
3615
+ // before any hook, so a "Bash" call cannot slip past "PowerShell" hooks.
3616
+ if (isShellToolName(block.name) && block.name !== shellToolName()) {
3617
+ const text = `[error] unknown tool "${block.name}". The shell tool here is ${shellToolName()}.`;
3618
+ this.emitToolActivity(block, (block.input ?? {}) as Record<string, unknown>, 'failed', text);
3619
+ return { text, isError: true };
3620
+ }
2928
3621
  const ctx: NativeToolContext = {
2929
3622
  cwd: this.config.cwd ?? process.cwd(),
2930
3623
  abortSignal: this.makeAbortSignal('toolAbort'),
@@ -2932,7 +3625,7 @@ export class ClaudeNativeWorker extends EventEmitter {
2932
3625
  readSet: this.readSet,
2933
3626
  partialReadSet: this.partialReadSet,
2934
3627
  planMode: this.planMode,
2935
- taskDisabled: this.taskDisabled,
3628
+ taskDisabled: this.taskDisabled || this.config.clusterId !== undefined || this.config.interactionMode === 'chat',
2936
3629
  onTodos: (todos) => {
2937
3630
  this.todos = todos;
2938
3631
  this.todosBroadcast(todos);
@@ -2974,40 +3667,43 @@ export class ClaudeNativeWorker extends EventEmitter {
2974
3667
  const initialInput = (block.input && typeof block.input === 'object' ? block.input : {}) as Record<string, unknown>;
2975
3668
  let input: Record<string, unknown> = initialInput;
2976
3669
 
2977
- // PreToolUse hook — non-zero blocks; stderr surfaces as the tool result.
2978
- const pre = await fireHooks(this.hooks, 'PreToolUse', matcher,
2979
- { tool_name: block.name, tool_input: input, workflow_id: this.workflowId },
2980
- { cwd: ctx.cwd, abortSignal: ctx.abortSignal, shells: this.shells, workflowId: this.workflowId },
2981
- );
2982
- const blocked = firstBlocking(pre);
2983
- if (blocked) {
2984
- const detail = blocked.stderr.trim() || `(hook exited ${blocked.exitCode}${blocked.timedOut ? ', timed out' : ''})`;
2985
- const text = `[blocked by PreToolUse hook] ${detail.slice(0, 1000)}`;
3670
+ // PreToolUse hooks, as in Claude Code: exit 2 or permissionDecision
3671
+ // "deny" refuses the call with the reason as the tool result; "ask" parks
3672
+ // it for the operator (below, after the guards); updatedInput replaces the
3673
+ // input; continue:false refuses it and ends the turn. Other non-zero exits
3674
+ // are non-blocking errors. "allow" skips no Arco check: the guards and the
3675
+ // operator's review gate still apply, like Claude Code's deny and ask rules.
3676
+ const pre = await this.runHooks('PreToolUse', matcher,
3677
+ { tool_name: block.name, tool_input: hookToolInput(input, ctx.cwd), tool_use_id: block.id },
3678
+ ctx.cwd, ctx.abortSignal);
3679
+ const preContext = pre.context.map((c) => `PreToolUse:${block.name} hook additional context: ${c.slice(0, 10_000)}`);
3680
+ if (pre.blocks.length > 0 || pre.permission === 'deny' || pre.stop) {
3681
+ const lines = pre.blocks.length > 0
3682
+ ? pre.blocks.map((b) => `PreToolUse:${block.name} hook error: [${b.command}]: ${b.reason.slice(0, 1000)}`)
3683
+ : pre.permission === 'deny'
3684
+ ? [`PreToolUse:${block.name} hook denied this tool call: ${(pre.permissionReason ?? '').slice(0, 1000)}`]
3685
+ : [`PreToolUse:${block.name} hook stopped processing${pre.stop?.reason ? `: ${pre.stop.reason.slice(0, 1000)}` : '.'}`];
3686
+ if (pre.stop) this.hookStopRequested = pre.stop.reason;
3687
+ const text = [...lines, ...preContext].join('\n\n');
2986
3688
  this.emitToolActivity(block, input, 'failed', text);
2987
3689
  return { text, isError: true };
2988
3690
  }
2989
3691
 
2990
- // docs/PROVIDERS.md - fold any PreToolUse hook's
2991
- // hookSpecificOutput.updatedInput into the dispatched input. Last-write-
2992
- // wins matches Claude Code's documented behavior. Each rewrite emits a
2993
- // hook_rewrote_input event so transcript review can attribute the
2994
- // mutation back to its origin (e.g. rtk vs. a bespoke project hook).
2995
- for (const r of pre) {
2996
- const parsed = parseHookOutput(r.stdout);
2997
- const next = parsed.hookSpecificOutput?.updatedInput;
2998
- if (!next) continue;
2999
- const rewritten = { ...input, ...next };
3692
+ // updatedInput replaces the whole input (Claude Code's contract). Each
3693
+ // rewrite emits a hook_rewrote_input event so transcript review can
3694
+ // attribute the change to its hook (e.g. rtk vs. a bespoke project hook).
3695
+ for (const rw of pre.rewrites) {
3000
3696
  this.workflowEventBroadcast({
3001
3697
  type: 'hook_rewrote_input',
3002
3698
  workflowId: this.workflowId,
3003
3699
  toolUseId: block.id,
3004
3700
  toolName: block.name,
3005
- hookCommand: r.command ?? '(unknown)',
3701
+ hookCommand: rw.command || '(unknown)',
3006
3702
  originalInput: JSON.stringify(input),
3007
- rewrittenInput: JSON.stringify(rewritten),
3703
+ rewrittenInput: JSON.stringify(rw.input),
3008
3704
  });
3009
- input = rewritten;
3010
3705
  }
3706
+ if (pre.updatedInput) input = pre.updatedInput;
3011
3707
 
3012
3708
  // docs/PROVIDERS.md - tool-call counter for the auto-
3013
3709
  // threshold opt-in. Counts every dispatched tool call (including
@@ -3023,76 +3719,32 @@ export class ClaudeNativeWorker extends EventEmitter {
3023
3719
  toolCallsSinceCompact: this.toolCallCountSinceCompact,
3024
3720
  });
3025
3721
 
3026
- // docs/PROVIDERS.md - pre-tool-use guards in a
3027
- // deterministic order. Cheap path-shape check first (config-protection
3028
- // never touches state), then the state-bearing fact-force gate. Both
3029
- // emit `tool_gate_triggered`; only the first blocking decision returns
3030
- // a synthetic tool_result. Documented in `docs/GOTCHAS.md § Efficiency`.
3031
- // Config-protection defaults ON (safety gate); the operator can relax it
3032
- // per-tab via `efficiencyConfigProtection: 'off'` when a legitimate config
3033
- // edit is needed. Absent field ⇒ gate ON, so opting out is always explicit.
3034
- // H17 — hardline command floor. ALWAYS ON (not operator-disablable) and
3035
- // checked FIRST: a self-restart/self-kill/rm -rf of the repo would take down
3036
- // this turn + every other tab, so it can never run from an agent turn.
3037
- const hardline = checkHardlineCommand(block.name, input, ctx.cwd);
3038
- if (hardline.blocked) {
3039
- this.workflowEventBroadcast({
3040
- type: 'tool_gate_triggered',
3041
- workflowId: this.workflowId,
3042
- toolUseId: block.id,
3043
- toolName: block.name,
3044
- gate: 'hardline-command-floor',
3045
- decision: 'blocked',
3046
- reason: hardline.reason,
3047
- });
3048
- this.emitToolActivity(block, input, 'failed', hardline.syntheticResult);
3049
- return { text: hardline.syntheticResult, isError: true };
3050
- }
3051
-
3052
- const guard = (this.config.efficiencyConfigProtection ?? 'on') === 'on'
3053
- ? checkConfigProtection(block.name, input, ctx.cwd)
3054
- : { blocked: false as const };
3055
- if (guard.blocked) {
3722
+ // docs/PROVIDERS.md - pre-tool-use guards in a deterministic order
3723
+ // (toolChecks.ts PRE_TOOL_GUARDS): the hardline command floor (always on,
3724
+ // first), config protection (on unless the tab opts out) and fact-force
3725
+ // (operator opt-in). Each blocking decision emits `tool_gate_triggered`;
3726
+ // only the first one returns a synthetic tool_result. Documented in
3727
+ // `docs/GOTCHAS.md § Efficiency`.
3728
+ const guardBlock = firstBlockingGuard({
3729
+ name: block.name,
3730
+ input,
3731
+ cwd: ctx.cwd,
3732
+ configProtection: (this.config.efficiencyConfigProtection ?? 'on') === 'on',
3733
+ factForce: (this.config.efficiencyFactForce ?? 'off') === 'on',
3734
+ filesEditedThisTurn: this.filesEditedThisTurn,
3735
+ });
3736
+ if (guardBlock) {
3056
3737
  this.workflowEventBroadcast({
3057
3738
  type: 'tool_gate_triggered',
3058
3739
  workflowId: this.workflowId,
3059
3740
  toolUseId: block.id,
3060
3741
  toolName: block.name,
3061
- gate: 'config-protection',
3742
+ gate: guardBlock.gate,
3062
3743
  decision: 'blocked',
3063
- reason: guard.reason,
3744
+ reason: guardBlock.reason,
3064
3745
  });
3065
- this.emitToolActivity(block, input, 'failed', guard.syntheticResult);
3066
- return { text: guard.syntheticResult, isError: true };
3067
- }
3068
- // Fact-force runs on Edit/Write/MultiEdit only and never on read tools
3069
- // (the model needs to inspect first). Operator opt-in is per-tab via
3070
- // `efficiencyFactForce: 'on'`. Default 'off' for all tabs: this synthetic
3071
- // failure/retry is an operator opt-in because it adds transcript context
3072
- // without verifying the facts (see docs/PROVIDERS.md).
3073
- if ((this.config.efficiencyFactForce ?? 'off') === 'on') {
3074
- const ff = checkFactForceFirstEdit(block.name, input, ctx.cwd, this.filesEditedThisTurn);
3075
- if (ff.resolvedPath !== null) {
3076
- // Record the path BEFORE returning the synthetic result so the
3077
- // model's subsequent re-issued Edit on the same path passes through
3078
- // silently. Path is added on both blocked and allowed branches: a
3079
- // first-blocked-then-re-issued sequence within one turn only
3080
- // engages the gate once.
3081
- this.filesEditedThisTurn.add(ff.resolvedPath);
3082
- }
3083
- if (ff.blocked) {
3084
- this.workflowEventBroadcast({
3085
- type: 'tool_gate_triggered',
3086
- workflowId: this.workflowId,
3087
- toolUseId: block.id,
3088
- toolName: block.name,
3089
- gate: 'fact-force-first-edit',
3090
- decision: 'blocked',
3091
- reason: ff.reason,
3092
- });
3093
- this.emitToolActivity(block, input, 'failed', ff.syntheticResult);
3094
- return { text: ff.syntheticResult, isError: true };
3095
- }
3746
+ this.emitToolActivity(block, input, 'failed', guardBlock.syntheticResult);
3747
+ return { text: guardBlock.syntheticResult, isError: true };
3096
3748
  }
3097
3749
 
3098
3750
  // DEBAG (docs/PROVIDERS.md) - operator-armed durable review
@@ -3108,7 +3760,16 @@ export class ClaudeNativeWorker extends EventEmitter {
3108
3760
  // writing it after reopens the lost-on-crash hole). Sequential tool dispatch
3109
3761
  // means the for-loop simply waits here (plan §4.4). Sub-phase 4: the sidecar
3110
3762
  // record lets rehydrateGatesOnce re-surface this gate after a restart.
3111
- const gate = evaluateGate((this.config.reviewSafeMode ?? 'off') === 'on', block.name, input, ctx.cwd);
3763
+ const reviewGate = evaluateGate((this.config.reviewSafeMode ?? 'off') === 'on', block.name, input, ctx.cwd);
3764
+ // A PreToolUse hook's "ask" parks the call through the same approval card.
3765
+ const gate: GateProposal | null = pre.permission === 'ask'
3766
+ ? {
3767
+ category: 'hook-ask',
3768
+ reason: `A PreToolUse hook asks for confirmation: ${pre.permissionReason ?? ''}${reviewGate ? ` (${reviewGate.reason})` : ''}`.slice(0, 1000),
3769
+ signature: gateSignature(block.name, input),
3770
+ proposedArgs: input,
3771
+ }
3772
+ : reviewGate;
3112
3773
  if (gate) {
3113
3774
  const liveArgsAtFire = gate.proposedArgs;
3114
3775
  const createdAt = Date.now();
@@ -3158,6 +3819,9 @@ export class ClaudeNativeWorker extends EventEmitter {
3158
3819
  createdAt,
3159
3820
  });
3160
3821
  let resolution: { decision: 'approve' | 'reject'; finalArgs?: Record<string, unknown>; remember?: boolean };
3822
+ // Notification hooks (permission_prompt) once the card has waited.
3823
+ const permissionTimer = setTimeout(() => this.fireNotification('permission_prompt', `Claude needs your permission to use ${block.name}`, 'Permission needed'), this.notifyDelays.permissionMs);
3824
+ permissionTimer.unref?.();
3161
3825
  try {
3162
3826
  resolution = await new Promise((resolve, reject) => {
3163
3827
  this.pendingGates.set(block.id, {
@@ -3181,6 +3845,8 @@ export class ClaudeNativeWorker extends EventEmitter {
3181
3845
  const m = err instanceof Error ? err.message : String(err);
3182
3846
  this.emitToolActivity(block, input, 'failed', `[review gate aborted] ${m}`);
3183
3847
  return { text: `[review gate aborted] ${m}`, isError: true };
3848
+ } finally {
3849
+ clearTimeout(permissionTimer);
3184
3850
  }
3185
3851
  await clearPendingGate(ctx.cwd, this.workflowId, block.id).catch(() => { /* ignore */ });
3186
3852
  const outcome = gateOutcome(resolution.decision, block.name, input, resolution.finalArgs);
@@ -3209,7 +3875,7 @@ export class ClaudeNativeWorker extends EventEmitter {
3209
3875
  signature: gate.signature,
3210
3876
  toolName: block.name,
3211
3877
  approvedAt: Date.now(),
3212
- sample: block.name === 'Bash' && typeof input.command === 'string' ? String(input.command).slice(0, 200) : undefined,
3878
+ sample: isShellToolName(block.name) && typeof input.command === 'string' ? String(input.command).slice(0, 200) : undefined,
3213
3879
  }).catch((e) => console.warn(`[arco] [${this.workflowId.slice(0, 8)}] standing-approval write failed:`, e));
3214
3880
  await this.broadcastStandingApprovals(ctx.cwd);
3215
3881
  }
@@ -3240,6 +3906,8 @@ export class ClaudeNativeWorker extends EventEmitter {
3240
3906
  }
3241
3907
 
3242
3908
  let resultText: string;
3909
+ let toolOutcome: NativeToolOutcome | undefined;
3910
+ let decodedPdfReceipt: string | undefined;
3243
3911
  let isError = false;
3244
3912
  // §E1 (E1-Native) — decoded once; the registry branch below uses it.
3245
3913
  const registryTool = parseRegistryToolName(block.name);
@@ -3249,7 +3917,42 @@ export class ClaudeNativeWorker extends EventEmitter {
3249
3917
  // worker will never have advertised the tool, so a model attempting to
3250
3918
  // call peer_send without a clusterId gets the standard "unknown tool"
3251
3919
  // path through executeNativeTool.
3252
- if (this.config.clusterId !== undefined && isPeerTool(block.name)) {
3920
+ if (block.name === 'read_url') {
3921
+ try {
3922
+ const result = await this.fetchUrlContent(typeof input.url === 'string' ? input.url : '', {
3923
+ signal: ctx.abortSignal,
3924
+ pages: typeof input.pages === 'string' ? input.pages : undefined,
3925
+ offset: typeof input.offset === 'number' ? input.offset : undefined,
3926
+ limit: typeof input.limit === 'number' ? input.limit : undefined,
3927
+ pdfMode: input.pdf_mode === 'visual' ? 'visual' : undefined,
3928
+ limits: { images: true, documents: input.pdf_mode === 'visual' },
3929
+ });
3930
+ toolOutcome = await this.admitMedia(pendingResults, nativeFileOutcome(result));
3931
+ resultText = toolOutcome.text;
3932
+ isError = toolOutcome.isError;
3933
+ } catch (err) {
3934
+ resultText = `[error] ${err instanceof Error ? err.message : String(err)}`;
3935
+ isError = true;
3936
+ }
3937
+ } else if (block.name === 'handoff_history') {
3938
+ try {
3939
+ if (!this.buildToolDefs().some(tool => tool.name === block.name)) throw new Error('History tool is unavailable.');
3940
+ resultText = JSON.stringify(await executeHandoffHistory(this.workflowId, input));
3941
+ } catch (error) {
3942
+ resultText = `[error] ${error instanceof Error ? error.message.slice(0, 2000) : 'History unavailable.'}`;
3943
+ isError = true;
3944
+ }
3945
+ } else if (PLAN_TOOL_NAMES.includes(block.name)) {
3946
+ if (!this.buildToolDefs().some(tool => tool.name === block.name)) {
3947
+ resultText = '[error] Plan tool is not available for this workflow.';
3948
+ } else {
3949
+ resultText = await executePlanTool(block.name, input, {
3950
+ cwd: this.config.cwd ?? '', workflowId: this.workflowId,
3951
+ arcoPort: parseInt(process.env.ARCO_PORT ?? '3001', 10),
3952
+ });
3953
+ }
3954
+ isError = resultText.startsWith('[error]');
3955
+ } else if (this.config.clusterId !== undefined && isPeerTool(block.name)) {
3253
3956
  try {
3254
3957
  resultText = await executePeerTool(block.name, input, {
3255
3958
  workflowId: this.workflowId,
@@ -3289,8 +3992,10 @@ export class ClaudeNativeWorker extends EventEmitter {
3289
3992
  } else {
3290
3993
  try {
3291
3994
  const r = await session.callTool(registryTool.tool, input);
3292
- resultText = r.text;
3293
- isError = r.isError;
3995
+ decodedPdfReceipt = r.pdfReceipt;
3996
+ toolOutcome = r.blocks ? await this.admitMedia(pendingResults, nativeFileOutcome({ text: r.text, blocks: r.blocks, kind: 'tool', truncated: false, isError: r.isError })) : undefined;
3997
+ resultText = toolOutcome?.text ?? r.text;
3998
+ isError = toolOutcome?.isError ?? r.isError;
3294
3999
  } catch (err) {
3295
4000
  resultText = `[error] ${err instanceof Error ? err.message : String(err)}`;
3296
4001
  isError = true;
@@ -3323,97 +4028,81 @@ export class ClaudeNativeWorker extends EventEmitter {
3323
4028
  }
3324
4029
  } else {
3325
4030
  try {
3326
- resultText = await executeNativeTool(block.name, input, ctx);
3327
- if (resultText.startsWith('[error] ')) isError = true;
4031
+ toolOutcome = await this.admitMedia(pendingResults, await executeNativeToolResult(block.name, input, ctx));
4032
+ resultText = toolOutcome.text;
4033
+ isError = toolOutcome.isError;
3328
4034
  } catch (err) {
3329
4035
  resultText = `[error] ${err instanceof Error ? err.message : String(err)}`;
3330
4036
  isError = true;
3331
4037
  }
3332
4038
  }
3333
4039
 
3334
- // docs/PROVIDERS.md - Native-side tool-result filter. Runs on
3335
- // the current turn's tool_result only (cache invariant: `messages[]`
3336
- // is never mutated retroactively). Filter runs BEFORE PostToolUse hook
3337
- // augmentation so operator-curated hook stderr / additionalContext
3338
- // stays untouched. When the filter actually shrinks output we gzip
3339
- // the raw bytes to artifacts/raw-tools/ so the operator can recover
3340
- // what the model didn't see — reversibility is non-negotiable.
3341
- const filterMode = this.config.efficiencyToolFilter ?? 'off';
3342
- if (filterMode !== 'off') {
3343
- const pack = resolveFilterPack(block.name, input, filterMode);
3344
- if (pack) {
3345
- // Synthesize an exit code from the [error] sentinel so the pack's
3346
- // branch_on_exit can flip head_cap → tail_cap. true exit codes
3347
- // aren't surfaced by executeNativeTool (returns string only); the
3348
- // model's view of "did this fail" is what matters here.
3349
- const synthExit = isError ? 1 : 0;
3350
- const fr = filterToolResult(block.name, resultText, synthExit, pack);
3351
- if (fr.filteredBytes !== fr.originalBytes) {
3352
- let rawArtifactPath: string | undefined;
3353
- try {
3354
- rawArtifactPath = await this.persistRawArtifact(block.id, resultText);
3355
- } catch (err) {
3356
- console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] raw-tools artifact write failed:`, err);
3357
- }
3358
- this.workflowEventBroadcast({
3359
- type: 'tool_filtered',
3360
- workflowId: this.workflowId,
3361
- toolUseId: block.id,
3362
- toolName: block.name,
3363
- filterName: fr.filterName,
3364
- originalBytes: fr.originalBytes,
3365
- filteredBytes: fr.filteredBytes,
3366
- ...(rawArtifactPath ? { rawArtifactPath } : {}),
3367
- });
3368
- resultText = fr.filtered;
3369
- } else {
3370
- // No-op — still emit so transcript review can confirm the filter
3371
- // ran and chose to pass through.
3372
- this.workflowEventBroadcast({
3373
- type: 'tool_filtered',
3374
- workflowId: this.workflowId,
3375
- toolUseId: block.id,
3376
- toolName: block.name,
3377
- filterName: fr.filterName,
3378
- originalBytes: fr.originalBytes,
3379
- filteredBytes: fr.filteredBytes,
3380
- });
3381
- }
3382
- }
3383
- }
3384
-
3385
- // H62 — append the partial-read warning to a SUCCESSFUL Write result so the
3386
- // model sees it (a failed write already told the model something's wrong).
3387
- if (partialWarn.warn && !isError) {
3388
- resultText += `\n\n${partialWarn.note}`;
3389
- }
4040
+ // After the tool, in order (toolChecks.ts postToolSteps): the output
4041
+ // filter, the partial-read note, then PostToolUse hooks.
4042
+ const done = await runPostToolSteps(postToolSteps({
4043
+ filter: (text, failed) => this.filterToolOutput(block, input, text, failed, toolOutcome?.exitCode),
4044
+ partialNote: partialWarn.warn ? partialWarn.note : null,
4045
+ postHooks: (text, failed) => this.runHooks(failed ? 'PostToolUseFailure' : 'PostToolUse', matcher,
4046
+ failed
4047
+ ? { tool_name: block.name, tool_input: hookToolInput(input, ctx.cwd), tool_use_id: block.id, error: text, is_interrupt: ctx.abortSignal.aborted || toolOutcome?.aborted === true, ...(toolOutcome?.exitCode !== undefined ? {exit_code:toolOutcome.exitCode,signal:toolOutcome.signal,timed_out:toolOutcome.timedOut} : {}) }
4048
+ : { tool_name: block.name, tool_input: hookToolInput(input, ctx.cwd), tool_use_id: block.id, tool_response: text },
4049
+ ctx.cwd, ctx.abortSignal),
4050
+ toolName: block.name,
4051
+ preContext,
4052
+ }), { text: resultText, isError });
4053
+ if (done.stop !== undefined) this.hookStopRequested = done.stop;
4054
+ const media = !done.isError ? toolOutcome?.content?.filter(b => b.type === 'image' || b.type === 'document') : undefined;
4055
+ const mediaReceipt = media?.length ? media.map(b => b.type === 'document' ? `document: ${b.title ?? 'tool document'} (${b.arcoPages ?? 'unknown'} pages)` : `image: ${b.source.media_type}`).join('; ') : decodedPdfReceipt;
4056
+ this.emitToolActivity(block, input, done.isError ? 'failed' : 'completed', done.text, mediaReceipt);
4057
+ return { text: done.text, isError: done.isError, ...(toolOutcome?.content && !done.isError ? { content: [{ type: 'text' as const, text: done.text }, ...toolOutcome.content.filter(b => b.type !== 'text')] } : {}) };
4058
+ }
3390
4059
 
3391
- // PostToolUse hook — informational; stderr appended to result.
3392
- const post = await fireHooks(this.hooks, 'PostToolUse', matcher,
3393
- { tool_name: block.name, tool_input: input, tool_response: resultText, workflow_id: this.workflowId },
3394
- { cwd: ctx.cwd, abortSignal: ctx.abortSignal, shells: this.shells, workflowId: this.workflowId },
3395
- );
3396
- for (const r of post) {
3397
- const stderr = r.stderr.trim();
3398
- if (stderr) resultText += `\n\n[PostToolUse hook stderr] ${stderr.slice(0, 500)}`;
3399
- // docs/PROVIDERS.md - additionalContext from PostToolUse
3400
- // hooks gets appended to the tool_result the model sees. `decision:
3401
- // "block"` triggers a model retry by surfacing the reason as an
3402
- // is_error tool_result; matches Claude Code semantics.
3403
- const parsed = parseHookOutput(r.stdout);
3404
- const extra = parsed.hookSpecificOutput?.additionalContext;
3405
- if (typeof extra === 'string' && extra.length > 0) {
3406
- resultText += `\n\n${extra}`;
3407
- }
3408
- if (parsed.decision === 'block') {
3409
- const reason = parsed.reason ?? 'PostToolUse hook requested retry';
3410
- const text = `[PostToolUse hook blocked] ${reason}`;
3411
- this.emitToolActivity(block, input, 'failed', text);
3412
- return { text, isError: true };
4060
+ // docs/PROVIDERS.md - Native-side tool-result filter. Runs on
4061
+ // the current turn's tool_result only (cache invariant: `messages[]`
4062
+ // is never mutated retroactively). Filter runs BEFORE PostToolUse hook
4063
+ // augmentation so operator-curated hook stderr / additionalContext
4064
+ // stays untouched. When the filter actually shrinks output we gzip
4065
+ // the raw bytes to artifacts/raw-tools/ so the operator can recover
4066
+ // what the model didn't see — reversibility is non-negotiable.
4067
+ private async filterToolOutput(block: ToolUseBlock, input: Record<string, unknown>, resultText: string, isError: boolean, exitCode?: number | null): Promise<string> {
4068
+ const filterMode = this.config.efficiencyToolFilter ?? 'off';
4069
+ if (filterMode === 'off') return resultText;
4070
+ const pack = resolveFilterPack(block.name, input, filterMode);
4071
+ if (!pack) return resultText;
4072
+ // Shell results carry their real status; other tools retain the existing
4073
+ // success/failure adapter for packs that only need that distinction.
4074
+ const fr = filterToolResult(block.name, resultText, exitCode ?? (isError ? 1 : 0), pack);
4075
+ if (fr.filteredBytes !== fr.originalBytes) {
4076
+ let rawArtifactPath: string | undefined;
4077
+ try {
4078
+ rawArtifactPath = await this.persistRawArtifact(block.id, resultText);
4079
+ } catch (err) {
4080
+ console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] raw-tools artifact write failed:`, err);
3413
4081
  }
4082
+ this.workflowEventBroadcast({
4083
+ type: 'tool_filtered',
4084
+ workflowId: this.workflowId,
4085
+ toolUseId: block.id,
4086
+ toolName: block.name,
4087
+ filterName: fr.filterName,
4088
+ originalBytes: fr.originalBytes,
4089
+ filteredBytes: fr.filteredBytes,
4090
+ ...(rawArtifactPath ? { rawArtifactPath } : {}),
4091
+ });
4092
+ return fr.filtered;
3414
4093
  }
3415
- this.emitToolActivity(block, input, isError ? 'failed' : 'completed', resultText);
3416
- return { text: resultText, isError };
4094
+ // No-op — still emit so transcript review can confirm the filter
4095
+ // ran and chose to pass through.
4096
+ this.workflowEventBroadcast({
4097
+ type: 'tool_filtered',
4098
+ workflowId: this.workflowId,
4099
+ toolUseId: block.id,
4100
+ toolName: block.name,
4101
+ filterName: fr.filterName,
4102
+ originalBytes: fr.originalBytes,
4103
+ filteredBytes: fr.filteredBytes,
4104
+ });
4105
+ return resultText;
3417
4106
  }
3418
4107
 
3419
4108
  // ── Phase 7b tool handlers ──
@@ -3453,16 +4142,56 @@ export class ClaudeNativeWorker extends EventEmitter {
3453
4142
  }
3454
4143
 
3455
4144
  private async handleSpawnTask(args: { description: string; prompt: string; subagentType?: string; model?: string; toolUseId: string }): Promise<string> {
4145
+ assertNativeTaskAllowed({ interactionMode: this.config.interactionMode, inCluster: this.config.clusterId !== undefined, taskDisabled: this.taskDisabled });
3456
4146
  if (!this.taskHandler) throw new Error('Task handler not registered');
3457
- const handle = await this.taskHandler({
3458
- parentWorkflowId: this.workflowId,
3459
- description: args.description,
3460
- prompt: args.prompt,
3461
- subagentType: args.subagentType,
3462
- model: args.model,
3463
- });
4147
+ const turn = this.taskTurn;
4148
+ const request = new AbortController();
4149
+ const requestId = `task-${crypto.randomUUID()}`;
4150
+ this.taskRequests.set(requestId, request);
4151
+ const operatorCancellation = () => `Task ${requestId}: the operator cancelled this sub-agent. Do not start a replacement unless the operator asks. Count this task as cancelled in your final reply.`;
4152
+ let queued = false;
4153
+ let chosenModel: string | undefined;
4154
+ let handle: TaskSpawnHandle;
4155
+ try {
4156
+ handle = await this.taskHandler({
4157
+ parentWorkflowId: this.workflowId,
4158
+ taskId: requestId, turnSignal: turn.signal, signal: request.signal,
4159
+ policy: this.taskPolicy,
4160
+ description: args.description, prompt: args.prompt, subagentType: args.subagentType, model: args.model,
4161
+ onQueued: (model) => {
4162
+ if (turn.signal.aborted || request.signal.aborted) throw new Error('AbortError: Task cancelled');
4163
+ chosenModel = model; queued = true;
4164
+ const startedAt = Date.now();
4165
+ this.unsettledTasks.set(requestId, { toolUseId: args.toolUseId, startedAt });
4166
+ this.emit('task_started', { taskId: requestId, toolUseId: args.toolUseId, description: args.description, startedAt, phase: 'queued', model });
4167
+ },
4168
+ onModel: (model) => {
4169
+ chosenModel = model;
4170
+ if (this.tasksByTaskId.has(requestId) && this.unsettledTasks.has(requestId)) {
4171
+ this.emit('task_status', { taskId: requestId, toolUseId: args.toolUseId, phase: 'running', elapsedMs: 0, model });
4172
+ }
4173
+ },
4174
+ });
4175
+ if (turn.signal.aborted || request.signal.aborted || this.taskTurn !== turn) {
4176
+ handle.finalText.catch(() => {});
4177
+ handle.cancel();
4178
+ throw new Error('AbortError: Task cancelled during initialization');
4179
+ }
4180
+ } catch (err) {
4181
+ if (queued && this.unsettledTasks.delete(requestId)) {
4182
+ const text = String(err);
4183
+ this.emit('task_status', { taskId: requestId, toolUseId: args.toolUseId, phase: /AbortError/.test(text) ? 'cancelled' : 'error', elapsedMs: 0, summary: text.slice(0, 200) });
4184
+ }
4185
+ this.taskRequests.delete(requestId);
4186
+ if (request.signal.aborted && !turn.signal.aborted) return operatorCancellation();
4187
+ throw err;
4188
+ }
4189
+ this.taskRequests.delete(requestId);
4190
+ this.taskRequests.set(handle.taskId, request);
4191
+ this.unsettledTasks.delete(requestId);
3464
4192
  this.tasksByTaskId.set(handle.taskId, handle);
3465
4193
  const startedAt = Date.now();
4194
+ this.unsettledTasks.set(handle.taskId, { toolUseId: args.toolUseId, startedAt });
3466
4195
  // Lifecycle broadcast — picked up by ClaudeNativeTurn → WorkerManager →
3467
4196
  // seedWorker.ts which adds workflowId and forwards as `task_started`.
3468
4197
  this.emit('task_started', {
@@ -3470,6 +4199,7 @@ export class ClaudeNativeWorker extends EventEmitter {
3470
4199
  childWorkflowId: handle.childWorkflowId,
3471
4200
  toolUseId: args.toolUseId,
3472
4201
  description: args.description,
4202
+ model: chosenModel ?? handle.model ?? args.model ?? this.config.model,
3473
4203
  startedAt,
3474
4204
  });
3475
4205
  let finalText: string;
@@ -3478,18 +4208,22 @@ export class ClaudeNativeWorker extends EventEmitter {
3478
4208
  } catch (err) {
3479
4209
  const msg = err instanceof Error ? err.message : String(err);
3480
4210
  const phase: 'cancelled' | 'error' = /AbortError/i.test(msg) ? 'cancelled' : 'error';
3481
- this.emit('task_status', {
3482
- taskId: handle.taskId,
3483
- toolUseId: args.toolUseId,
3484
- phase,
3485
- elapsedMs: Date.now() - startedAt,
3486
- summary: msg.slice(0, 200),
3487
- });
3488
- // SubagentStop hook fires regardless of success/failure (informational).
3489
- void this.fireSubagentStop({ taskId: handle.taskId, childWorkflowId: handle.childWorkflowId, status: 'error', error: msg })
3490
- .catch((e) => console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] SubagentStop hook failed:`, e));
4211
+ // Already reported by cancel().
4212
+ if (this.unsettledTasks.delete(handle.taskId)) {
4213
+ this.emit('task_status', {
4214
+ taskId: handle.taskId,
4215
+ toolUseId: args.toolUseId,
4216
+ phase,
4217
+ elapsedMs: Date.now() - startedAt,
4218
+ summary: phase === 'cancelled' ? 'Cancelled.' : msg.slice(0, 200),
4219
+ });
4220
+ }
4221
+ if (request.signal.aborted && !turn.signal.aborted) return operatorCancellation();
3491
4222
  return `[error] Task ${handle.taskId} failed: ${msg.slice(0, 500)}`;
4223
+ } finally {
4224
+ this.taskRequests.delete(handle.taskId);
3492
4225
  }
4226
+ if (!this.unsettledTasks.delete(handle.taskId)) return finalText;
3493
4227
  this.emit('task_status', {
3494
4228
  taskId: handle.taskId,
3495
4229
  toolUseId: args.toolUseId,
@@ -3497,9 +4231,23 @@ export class ClaudeNativeWorker extends EventEmitter {
3497
4231
  elapsedMs: Date.now() - startedAt,
3498
4232
  summary: finalText.slice(0, 200),
3499
4233
  });
3500
- void this.fireSubagentStop({ taskId: handle.taskId, childWorkflowId: handle.childWorkflowId, status: 'completed', finalTextLength: finalText.length })
3501
- .catch((e) => console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] SubagentStop hook failed:`, e));
3502
- return finalText;
4234
+ const overridden = this.taskPolicy.model && args.model
4235
+ && resolveClaudeAliasFromCatalog(this.taskPolicy.model) !== resolveClaudeAliasFromCatalog(args.model);
4236
+ return overridden
4237
+ ? `${finalText}\n\nSub-agent used ${chosenModel ?? handle.model ?? this.taskPolicy.model}: the operator's model setting overrides the requested ${args.model}.`
4238
+ : finalText;
4239
+ }
4240
+
4241
+ hasActiveTask(taskId: string): boolean {
4242
+ return this.taskRequests.has(taskId) || this.unsettledTasks.has(taskId);
4243
+ }
4244
+
4245
+ cancelTask(taskId: string): boolean {
4246
+ const request = this.taskRequests.get(taskId);
4247
+ const handle = this.tasksByTaskId.get(taskId);
4248
+ if (request) request.abort();
4249
+ if (handle) handle.cancel();
4250
+ return !!(request || handle);
3503
4251
  }
3504
4252
 
3505
4253
  private async handleReadTaskOutput(taskId: string): Promise<string> {
@@ -3514,16 +4262,6 @@ export class ClaudeNativeWorker extends EventEmitter {
3514
4262
  return `${head} task ${taskId} (child ${handle.childWorkflowId.slice(0, 8)})\n\n${tail || '(no output yet)'}`;
3515
4263
  }
3516
4264
 
3517
- private async fireSubagentStop(payload: Record<string, unknown>): Promise<void> {
3518
- await fireHooks(
3519
- this.hooks,
3520
- 'SubagentStop',
3521
- 'SubagentStop',
3522
- { workflow_id: this.workflowId, ...payload },
3523
- { cwd: this.config.cwd ?? process.cwd(), abortSignal: this.makeAbortSignal('toolAbort'), shells: this.shells, workflowId: this.workflowId },
3524
- );
3525
- }
3526
-
3527
4265
  private makeAbortSignal(which: 'inFlight' | 'toolAbort'): AbortSignal {
3528
4266
  if (which === 'inFlight') {
3529
4267
  this.inFlight ??= new AbortController();
@@ -3541,14 +4279,14 @@ export class ClaudeNativeWorker extends EventEmitter {
3541
4279
  // SDK's own `.type` property), NOT on `e.error.type` (which is the outer
3542
4280
  // body wrapper field "error"). Read `e.type` first so overloaded/rate-limit
3543
4281
  // mid-stream errors are correctly classified for retry.
3544
- const e = err as { status?: number; message?: string; error?: { type?: string; message?: string; error?: { type?: string; message?: string } }; type?: string; name?: string };
4282
+ const e = err as { status?: number; message?: string; error?: { type?: string; message?: string; error?: { type?: string; message?: string } }; type?: string; name?: string; code?: string; cause?: { code?: string } };
3545
4283
  const name = e.name ?? '';
3546
4284
  // Inner message is at e.error.error.message (full body → error → message)
3547
4285
  // for streaming errors; fall back through outer body message and SDK message.
3548
4286
  const msg = e.error?.error?.message || e.error?.message || e.message || String(err);
3549
4287
  const errType = e.type ?? e.error?.type ?? '';
3550
4288
 
3551
- if (name === 'AbortError' || name === 'APIUserAbortError') {
4289
+ if (this.cancelRequested || name === 'AbortError' || name === 'APIUserAbortError') {
3552
4290
  this.emit('error', 'Worker killed');
3553
4291
  return 'fatal';
3554
4292
  }
@@ -3595,7 +4333,15 @@ export class ClaudeNativeWorker extends EventEmitter {
3595
4333
  this.emit('error', 'request_too_large');
3596
4334
  return 'fatal';
3597
4335
  }
3598
- if (status === 429 || status === 529 || errType === 'rate_limit_error' || errType === 'overloaded_error' || status === 500 || errType === 'api_error') {
4336
+ const gatewayError = status === 502 || status === 503 || status === 504 || (status >= 520 && status <= 524);
4337
+ // The SDK wraps failures before headers in APIConnectionError (including
4338
+ // APIConnectionTimeoutError). A dropped response body can instead expose
4339
+ // the fetch socket error directly; do not retry arbitrary statusless errors.
4340
+ const connectionCode = e.cause?.code ?? e.code ?? '';
4341
+ const connectionError = status === 0 && (err instanceof Anthropic.APIConnectionError
4342
+ || /^(?:ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|UND_ERR_(?:SOCKET|CONNECT_TIMEOUT|HEADERS_TIMEOUT|BODY_TIMEOUT))$/.test(connectionCode));
4343
+ const transportError = gatewayError || connectionError;
4344
+ if (transportError || status === 429 || status === 529 || errType === 'rate_limit_error' || errType === 'overloaded_error' || status === 500 || errType === 'api_error') {
3599
4345
  // H10 — honor Anthropic's own retry timing when it sends one. `retry-after`
3600
4346
  // (seconds or HTTP-date) wins; else the soonest `anthropic-ratelimit-*-reset`.
3601
4347
  // Falls back to the fixed 15/30/60s ladder when no usable header is present
@@ -3608,7 +4354,9 @@ export class ClaudeNativeWorker extends EventEmitter {
3608
4354
  const via = timing.source
3609
4355
  ? ` (per ${timing.source}${timing.capped ? ', capped' : ''})`
3610
4356
  : '';
3611
- const label = kind === 'genuine'
4357
+ const label = gatewayError ? `gateway error (HTTP ${status})`
4358
+ : connectionError ? (err instanceof Anthropic.APIConnectionTimeoutError ? 'connection timeout' : 'connection error')
4359
+ : kind === 'genuine'
3612
4360
  ? `rate limit (${errType || `HTTP ${status}`})`
3613
4361
  : `overload (${errType || `HTTP ${status}`})`;
3614
4362
  // Same attempt-budget guard as the auth / thinking branches: a 'retry'
@@ -3616,7 +4364,9 @@ export class ClaudeNativeWorker extends EventEmitter {
3616
4364
  // WITHOUT emitting — runTurn reads null as "error already emitted", so a
3617
4365
  // third consecutive 429/529/500 left the tab busy forever.
3618
4366
  if (attempt >= MAX_RETRY_ATTEMPTS - 1) {
3619
- this.emit('system_notice', `Anthropic ${label}: still failing after ${MAX_RETRY_ATTEMPTS} attempts — giving up on this turn. ${msg.slice(0, 300)}`);
4367
+ this.emit('system_notice', transportError
4368
+ ? `Anthropic could not be reached${gatewayError ? ` (HTTP ${status})` : ` (${label})`} after ${MAX_RETRY_ATTEMPTS} attempts. The conversation is intact; send a message to continue.`
4369
+ : `Anthropic ${label}: still failing after ${MAX_RETRY_ATTEMPTS} attempts — giving up on this turn. ${msg.slice(0, 300)}`);
3620
4370
  this.emit('error', `claude-native: ${label} after ${MAX_RETRY_ATTEMPTS} attempts`);
3621
4371
  return 'fatal';
3622
4372
  }