arco-workbench 0.1.7 → 0.1.9

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 (301) hide show
  1. package/CONTRIBUTING.md +63 -12
  2. package/README.md +21 -17
  3. package/client/dist/assets/{PhosphorBackdrop-DVQdBrTw.js → PhosphorBackdrop-DRu16-Is.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-BfSs2tB4.js → ThemedBackgroundShaderImpl-BLdwwQ4D.js} +1 -1
  5. package/client/dist/assets/{XtermView-DaMjC8Ny.js → XtermView-Xk7_9JaH.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-BCQnXj7R.js → galleryEditor-CI8ClzBa.js} +1 -1
  7. package/client/dist/assets/{index-DD9kFGsF.css → index-BEFgrUJJ.css} +1 -1
  8. package/client/dist/assets/{index-COfbHCYv.js → index-C7WzZfsr.js} +257 -255
  9. package/client/dist/index.html +2 -2
  10. package/client/src/App.tsx +2 -0
  11. package/client/src/components/ChatMessage.tsx +33 -8
  12. package/client/src/components/ChatModeView.tsx +2 -0
  13. package/client/src/components/ClusterRightPanel/ReplaceMemberDialog.tsx +65 -15
  14. package/client/src/components/ClusterRightPanel/SkillsControl.tsx +124 -0
  15. package/client/src/components/ClusterRightPanel/index.tsx +4 -0
  16. package/client/src/components/ClusterTaskBoardTab.tsx +9 -22
  17. package/client/src/components/CodexLateCommand.tsx +34 -0
  18. package/client/src/components/DialogShell.tsx +2 -0
  19. package/client/src/components/MemberCard.tsx +4 -1
  20. package/client/src/components/MemberPane.tsx +3 -1
  21. package/client/src/components/NeedsYouBadge.tsx +3 -3
  22. package/client/src/components/PhoneUpload.tsx +288 -0
  23. package/client/src/components/PrimaryStatus.tsx +14 -6
  24. package/client/src/components/ProviderReleasesModal.tsx +8 -4
  25. package/client/src/components/ProvidersPopover.tsx +28 -23
  26. package/client/src/components/RuntimeStateBanner.tsx +5 -0
  27. package/client/src/components/SettingsPanel.tsx +2 -2
  28. package/client/src/components/SkillEditorDialog.tsx +2 -2
  29. package/client/src/components/SkillsSettings.tsx +21 -4
  30. package/client/src/components/TabBar.tsx +91 -9
  31. package/client/src/components/TerminalInput.tsx +15 -11
  32. package/client/src/components/TranscriptSendDialog.tsx +12 -8
  33. package/client/src/components/TranscriptWorkerDialog.tsx +119 -0
  34. package/client/src/components/WorkflowView.tsx +2 -0
  35. package/client/src/components/clusterNeedsYou.ts +11 -18
  36. package/client/src/explorer/ArtifactsLens.tsx +37 -28
  37. package/client/src/explorer/ExplorerApp.tsx +5 -4
  38. package/client/src/explorer/types.ts +8 -3
  39. package/client/src/help/content/cluster.tsx +48 -17
  40. package/client/src/help/content/composer.tsx +40 -1
  41. package/client/src/help/content/header.tsx +18 -1
  42. package/client/src/help/content/misc.tsx +9 -1
  43. package/client/src/help/content/settings.tsx +18 -4
  44. package/client/src/help/content/tabbar.tsx +5 -0
  45. package/client/src/help/manualSections/actions.tsx +31 -0
  46. package/client/src/help/manualSections/clusters.tsx +44 -20
  47. package/client/src/help/manualSections/configuration.tsx +20 -0
  48. package/client/src/help/manualSections/gettingStarted.tsx +4 -4
  49. package/client/src/help/manualSections/maintenance.tsx +25 -6
  50. package/client/src/help/manualSections/powerFeatures.tsx +3 -2
  51. package/client/src/help/manualSections/providers.tsx +32 -8
  52. package/client/src/help/manualSections/troubleshooting.tsx +2 -1
  53. package/client/src/help/manualSections/workflows.tsx +12 -0
  54. package/client/src/help/manualSections/workspace.tsx +36 -0
  55. package/client/src/stores/appStore.ts +7 -0
  56. package/client/src/stores/appStore.types.ts +4 -0
  57. package/client/src/styles/global.css +109 -0
  58. package/client/src/utils/phoneTheme.ts +38 -0
  59. package/client/src/utils/phoneUploadApi.ts +10 -0
  60. package/client/src/utils/transcriptWorkerRequest.ts +24 -0
  61. package/client/src/ws/handleServerMessage.ts +31 -8
  62. package/docs/ARCHITECTURE.md +1 -1
  63. package/docs/CLIENT.md +16 -9
  64. package/docs/FEATURES.md +13 -7
  65. package/docs/GETTING_STARTED.md +12 -6
  66. package/docs/GOTCHAS.md +2 -1
  67. package/docs/INDEX.md +1 -1
  68. package/docs/OPERATIONS.md +213 -52
  69. package/docs/PERSISTENCE.md +7 -2
  70. package/docs/PRIMITIVES.md +42 -0
  71. package/docs/PROTOCOL_CLUSTER.md +51 -4
  72. package/docs/PROTOCOL_PRIMITIVES.md +39 -0
  73. package/docs/PROVIDERS.md +84 -13
  74. package/docs/SETTINGS.md +29 -3
  75. package/docs/TASK_LEDGER.md +7 -15
  76. package/native/linux-x64/manifest.json +1 -1
  77. package/native/win32-x64/manifest.json +1 -1
  78. package/node_modules/@arco/shared/dist/clusterCoordination.d.ts +2 -0
  79. package/node_modules/@arco/shared/dist/clusterCoordination.js +5 -1
  80. package/node_modules/@arco/shared/dist/protocol/chat.d.ts +1 -0
  81. package/node_modules/@arco/shared/dist/protocol/clientMessages.d.ts +3 -2
  82. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +15 -1
  83. package/node_modules/@arco/shared/dist/protocol/index.d.ts +1 -0
  84. package/node_modules/@arco/shared/dist/protocol/index.js +1 -0
  85. package/node_modules/@arco/shared/dist/protocol/models.d.ts +4 -3
  86. package/node_modules/@arco/shared/dist/protocol/models.js +26 -2
  87. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +13 -1
  88. package/node_modules/@arco/shared/dist/protocol/tasks.d.ts +4 -0
  89. package/node_modules/@arco/shared/dist/protocol/transcriptWorker.d.ts +47 -0
  90. package/node_modules/@arco/shared/dist/protocol/transcriptWorker.js +2 -0
  91. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
  92. package/node_modules/@arco/shared/dist/runtimeVersions.d.ts +1 -0
  93. package/node_modules/@arco/shared/dist/runtimeVersions.js +14 -0
  94. package/node_modules/@arco/shared/package.json +1 -1
  95. package/package.json +2 -2
  96. package/scripts/packaging/arco.mjs +1 -1
  97. package/scripts/packaging/native-repair.mjs +32 -4
  98. package/server/dist/atomicFile.js +1 -2
  99. package/server/dist/capabilities.d.ts +5 -2
  100. package/server/dist/capabilities.js +59 -9
  101. package/server/dist/cliUpdateDecision.d.ts +1 -1
  102. package/server/dist/cliUpdateDecision.js +5 -3
  103. package/server/dist/clusterDirector.js +2 -1
  104. package/server/dist/clusterPeerOps.js +14 -8
  105. package/server/dist/clusterProgress.js +1 -1
  106. package/server/dist/clusterRehydrate.js +2 -0
  107. package/server/dist/clusterSkills.d.ts +13 -0
  108. package/server/dist/clusterSkills.js +81 -0
  109. package/server/dist/clusterSnapshots.js +2 -0
  110. package/server/dist/clusterStore.d.ts +7 -2
  111. package/server/dist/clusterStore.js +42 -1
  112. package/server/dist/diagnostics/codeSkew.js +1 -0
  113. package/server/dist/eventLog.d.ts +7 -0
  114. package/server/dist/eventLog.js +70 -13
  115. package/server/dist/explorerDocs.d.ts +10 -6
  116. package/server/dist/explorerDocs.js +75 -34
  117. package/server/dist/historyLimits.d.ts +1 -0
  118. package/server/dist/historyLimits.js +3 -0
  119. package/server/dist/http/attachmentUpload.d.ts +13 -0
  120. package/server/dist/http/attachmentUpload.js +38 -0
  121. package/server/dist/http/browserWorktrees.d.ts +23 -0
  122. package/server/dist/http/browserWorktrees.js +120 -0
  123. package/server/dist/http/phoneUploadDrafts.d.ts +13 -0
  124. package/server/dist/http/phoneUploadDrafts.js +125 -0
  125. package/server/dist/http/phoneUploadListener.d.ts +17 -0
  126. package/server/dist/http/phoneUploadListener.js +81 -0
  127. package/server/dist/http/phoneUploadNetwork.d.ts +9 -0
  128. package/server/dist/http/phoneUploadNetwork.js +106 -0
  129. package/server/dist/http/phoneUploadPage.d.ts +2 -0
  130. package/server/dist/http/phoneUploadPage.js +136 -0
  131. package/server/dist/http/phoneUploadRouteHistory.d.ts +4 -0
  132. package/server/dist/http/phoneUploadRouteHistory.js +72 -0
  133. package/server/dist/http/phoneUploadRoutes.d.ts +4 -0
  134. package/server/dist/http/phoneUploadRoutes.js +419 -0
  135. package/server/dist/http/phoneUploadTheme.d.ts +17 -0
  136. package/server/dist/http/phoneUploadTheme.js +96 -0
  137. package/server/dist/http/projectBinding.d.ts +1 -0
  138. package/server/dist/http/projectBinding.js +3 -2
  139. package/server/dist/http/readConfinement.js +5 -1
  140. package/server/dist/http/router.js +14 -25
  141. package/server/dist/http/writeConfinement.js +19 -2
  142. package/server/dist/index.js +24 -1
  143. package/server/dist/jsonlLines.d.ts +4 -0
  144. package/server/dist/jsonlLines.js +53 -0
  145. package/server/dist/management/identity.js +1 -0
  146. package/server/dist/mcp/clusterMcpTools.js +4 -4
  147. package/server/dist/primitives/seedWorker.d.ts +1 -0
  148. package/server/dist/primitives/seedWorker.js +2 -1
  149. package/server/dist/project/taskLedger.d.ts +4 -0
  150. package/server/dist/project/taskLedger.js +7 -4
  151. package/server/dist/providerConversation.d.ts +1 -0
  152. package/server/dist/providerConversation.js +17 -0
  153. package/server/dist/providers/claude-native/resumeSummary.d.ts +9 -0
  154. package/server/dist/providers/claude-native/resumeSummary.js +102 -49
  155. package/server/dist/providers/claude-native/worker.js +8 -4
  156. package/server/dist/providers/claude.js +2 -1
  157. package/server/dist/providers/clusterTaskToolDefinitions.js +4 -4
  158. package/server/dist/providers/codex-appserver/catalog.js +16 -1
  159. package/server/dist/providers/codex-appserver/heldCommands.d.ts +14 -0
  160. package/server/dist/providers/codex-appserver/heldCommands.js +54 -0
  161. package/server/dist/providers/codex-appserver/index.d.ts +52 -2
  162. package/server/dist/providers/codex-appserver/index.js +239 -21
  163. package/server/dist/providers/codex-appserver/lateCommands.d.ts +62 -0
  164. package/server/dist/providers/codex-appserver/lateCommands.js +195 -0
  165. package/server/dist/providers/codex-appserver/worker.d.ts +23 -1
  166. package/server/dist/providers/codex-appserver/worker.js +89 -20
  167. package/server/dist/providers/codex.js +2 -1
  168. package/server/dist/providers/codexCodeMode.d.ts +2 -1
  169. package/server/dist/providers/codexCodeMode.js +8 -3
  170. package/server/dist/providers/cursor/print.js +2 -1
  171. package/server/dist/providers/cursor/worker.js +2 -1
  172. package/server/dist/providers/llamacpp.js +17 -8
  173. package/server/dist/providers/ollamaRecovery.js +6 -6
  174. package/server/dist/providers/ollamaResilience.js +3 -3
  175. package/server/dist/providers/ollamaTokens.js +1 -1
  176. package/server/dist/quota.d.ts +0 -18
  177. package/server/dist/quota.js +0 -44
  178. package/server/dist/replacementHistory.d.ts +19 -0
  179. package/server/dist/replacementHistory.js +49 -0
  180. package/server/dist/server/broadcast.d.ts +2 -1
  181. package/server/dist/server/broadcast.js +1 -0
  182. package/server/dist/server/prompts.d.ts +1 -0
  183. package/server/dist/server/prompts.js +6 -1
  184. package/server/dist/sessionJsonl.d.ts +1 -1
  185. package/server/dist/sessionJsonl.js +115 -40
  186. package/server/dist/smartPickupAdapters.js +15 -2
  187. package/server/dist/transcriptWorker.d.ts +34 -0
  188. package/server/dist/transcriptWorker.js +201 -0
  189. package/server/dist/workers/WorkerManager.d.ts +1 -0
  190. package/server/dist/workers/WorkerManager.js +1 -0
  191. package/server/dist/workers/processKill.d.ts +9 -1
  192. package/server/dist/workers/processKill.js +26 -10
  193. package/server/dist/workflowStore.d.ts +1 -0
  194. package/server/dist/workflowStore.js +31 -0
  195. package/server/dist/ws/clusterHandlers.d.ts +1 -0
  196. package/server/dist/ws/clusterHandlers.js +62 -26
  197. package/server/dist/ws/handoffHandlers.js +7 -2
  198. package/server/dist/ws/transcriptWorkerHandlers.d.ts +25 -0
  199. package/server/dist/ws/transcriptWorkerHandlers.js +139 -0
  200. package/server/dist/ws/turnEngine.js +40 -9
  201. package/server/dist/ws/updatePrimaryConfig.js +27 -8
  202. package/server/dist/ws/workflowHandlers.d.ts +4 -1
  203. package/server/dist/ws/workflowHandlers.js +3 -1
  204. package/server/package.json +1 -1
  205. package/server/src/atomicFile.ts +1 -2
  206. package/server/src/capabilities.ts +58 -17
  207. package/server/src/cliUpdateDecision.ts +5 -4
  208. package/server/src/clusterDirector.ts +2 -1
  209. package/server/src/clusterPeerOps.ts +15 -9
  210. package/server/src/clusterProgress.ts +1 -1
  211. package/server/src/clusterRehydrate.ts +2 -0
  212. package/server/src/clusterSkills.ts +79 -0
  213. package/server/src/clusterSnapshots.ts +1 -0
  214. package/server/src/clusterStore.ts +38 -0
  215. package/server/src/diagnostics/codeSkew.ts +1 -0
  216. package/server/src/eventLog.ts +73 -13
  217. package/server/src/explorerDocs.ts +75 -34
  218. package/server/src/historyLimits.ts +2 -0
  219. package/server/src/http/attachmentUpload.ts +49 -0
  220. package/server/src/http/browserWorktrees.ts +124 -0
  221. package/server/src/http/phoneUploadDrafts.ts +118 -0
  222. package/server/src/http/phoneUploadListener.ts +96 -0
  223. package/server/src/http/phoneUploadNetwork.ts +117 -0
  224. package/server/src/http/phoneUploadPage.ts +137 -0
  225. package/server/src/http/phoneUploadRouteHistory.ts +73 -0
  226. package/server/src/http/phoneUploadRoutes.ts +398 -0
  227. package/server/src/http/phoneUploadTheme.ts +97 -0
  228. package/server/src/http/projectBinding.ts +3 -2
  229. package/server/src/http/readConfinement.ts +5 -1
  230. package/server/src/http/router.ts +12 -26
  231. package/server/src/http/writeConfinement.ts +13 -2
  232. package/server/src/index.ts +23 -0
  233. package/server/src/jsonlLines.ts +52 -0
  234. package/server/src/management/identity.ts +1 -0
  235. package/server/src/mcp/clusterMcpTools.ts +4 -4
  236. package/server/src/primitives/seedWorker.ts +3 -1
  237. package/server/src/project/taskLedger.ts +7 -5
  238. package/server/src/providerConversation.ts +15 -0
  239. package/server/src/providers/claude-native/resumeSummary.ts +98 -50
  240. package/server/src/providers/claude-native/worker.ts +8 -4
  241. package/server/src/providers/claude.ts +2 -1
  242. package/server/src/providers/clusterTaskToolDefinitions.ts +4 -4
  243. package/server/src/providers/codex-appserver/catalog.ts +14 -1
  244. package/server/src/providers/codex-appserver/heldCommands.ts +58 -0
  245. package/server/src/providers/codex-appserver/index.ts +222 -20
  246. package/server/src/providers/codex-appserver/lateCommands.ts +225 -0
  247. package/server/src/providers/codex-appserver/worker.ts +85 -21
  248. package/server/src/providers/codex.ts +2 -1
  249. package/server/src/providers/codexCodeMode.ts +9 -4
  250. package/server/src/providers/cursor/print.ts +2 -1
  251. package/server/src/providers/cursor/worker.ts +2 -1
  252. package/server/src/providers/llamacpp.ts +18 -7
  253. package/server/src/providers/llamacppRecovery.ts +2 -0
  254. package/server/src/providers/ollamaRecovery.ts +6 -6
  255. package/server/src/providers/ollamaResilience.ts +3 -3
  256. package/server/src/providers/ollamaTokens.ts +1 -1
  257. package/server/src/providers/ollamaToolSubset.ts +3 -3
  258. package/server/src/quota.ts +0 -50
  259. package/server/src/replacementHistory.ts +44 -0
  260. package/server/src/server/broadcast.ts +2 -0
  261. package/server/src/server/prompts.ts +8 -1
  262. package/server/src/sessionJsonl.ts +92 -32
  263. package/server/src/smartPickupAdapters.ts +17 -3
  264. package/server/src/transcriptWorker.ts +182 -0
  265. package/server/src/workers/WorkerManager.ts +2 -0
  266. package/server/src/workers/processKill.ts +35 -7
  267. package/server/src/workflowStore.ts +21 -0
  268. package/server/src/ws/clusterHandlers.ts +43 -25
  269. package/server/src/ws/handoffHandlers.ts +7 -1
  270. package/server/src/ws/transcriptWorkerHandlers.ts +126 -0
  271. package/server/src/ws/turnEngine.ts +35 -8
  272. package/server/src/ws/updatePrimaryConfig.ts +25 -6
  273. package/server/src/ws/workflowHandlers.ts +3 -1
  274. package/shared/dist/clusterCoordination.d.ts +2 -0
  275. package/shared/dist/clusterCoordination.js +5 -1
  276. package/shared/dist/protocol/chat.d.ts +1 -0
  277. package/shared/dist/protocol/clientMessages.d.ts +3 -2
  278. package/shared/dist/protocol/clusters.d.ts +15 -1
  279. package/shared/dist/protocol/index.d.ts +1 -0
  280. package/shared/dist/protocol/index.js +1 -0
  281. package/shared/dist/protocol/models.d.ts +4 -3
  282. package/shared/dist/protocol/models.js +26 -2
  283. package/shared/dist/protocol/serverMessages.d.ts +13 -1
  284. package/shared/dist/protocol/tasks.d.ts +4 -0
  285. package/shared/dist/protocol/transcriptWorker.d.ts +47 -0
  286. package/shared/dist/protocol/transcriptWorker.js +2 -0
  287. package/shared/dist/protocol/workflows.d.ts +1 -0
  288. package/shared/dist/runtimeVersions.d.ts +1 -0
  289. package/shared/dist/runtimeVersions.js +14 -0
  290. package/shared/src/clusterCoordination.ts +7 -1
  291. package/shared/src/protocol/chat.ts +1 -0
  292. package/shared/src/protocol/clientMessages.ts +5 -0
  293. package/shared/src/protocol/clusters.ts +20 -6
  294. package/shared/src/protocol/index.ts +1 -0
  295. package/shared/src/protocol/models.ts +31 -5
  296. package/shared/src/protocol/serverMessages.ts +13 -0
  297. package/shared/src/protocol/settings.ts +2 -3
  298. package/shared/src/protocol/tasks.ts +4 -7
  299. package/shared/src/protocol/transcriptWorker.ts +49 -0
  300. package/shared/src/protocol/workflows.ts +4 -0
  301. package/shared/src/runtimeVersions.ts +14 -0
@@ -1,3 +1,4 @@
1
+ import { CodexLateCommands } from './lateCommands.js';
1
2
  import { historyBinding } from '../handoffHistoryBinding.js';
2
3
  import { codexWebSearchMode } from '../codexWebSearch.js';
3
4
  import { codexImageToolConfig } from '../codexImageTool.js';
@@ -208,6 +209,7 @@ function emptyTurnState() {
208
209
  transientNoticeKey: null,
209
210
  transientNoticeCount: 0,
210
211
  lastAgentMsgItemId: null,
212
+ finalAnswerStarted: false,
211
213
  artifacts: new Set(),
212
214
  settling: false,
213
215
  };
@@ -513,7 +515,7 @@ export class CodexAppServerWorker extends EventEmitter {
513
515
  // element. Empty prompt + image-only payload is a valid request shape now
514
516
  // that images are first-class — no more "Please inspect the attached
515
517
  // image(s)." synthetic fallback.
516
- async beginTurn(prompt, appendSystemPrompt) {
518
+ async beginTurn(prompt, appendSystemPrompt, options = {}) {
517
519
  if (this.disposed)
518
520
  throw new Error('codex app-server worker disposed');
519
521
  if (!this.rpc || !this.threadId) {
@@ -526,7 +528,8 @@ export class CodexAppServerWorker extends EventEmitter {
526
528
  throw new Error('codex app-server worker has a compaction in flight');
527
529
  }
528
530
  const preparationGeneration = this.preparationGeneration;
529
- const prepared = await prepareProviderAttachments(this.config.attachments, true, undefined, false, this.config.interactionMode === 'chat' && !this.config.voiceOperator);
531
+ // A continuation carries command results, never the operator's files again.
532
+ const prepared = await prepareProviderAttachments(options.continuation ? undefined : this.config.attachments, true, undefined, false, this.config.interactionMode === 'chat' && !this.config.voiceOperator);
530
533
  if (preparationGeneration !== this.preparationGeneration)
531
534
  throw new Error('Worker killed');
532
535
  const modelImages = await persistProviderImages(prepared.images);
@@ -903,6 +906,71 @@ export class CodexAppServerWorker extends EventEmitter {
903
906
  };
904
907
  }
905
908
  // ── Notification handling ────────────────────────────────────────────
909
+ lateCommands = new CodexLateCommands((event, state) => {
910
+ this.emit('late_command', event, state);
911
+ }, () => this.emit('held_commands'));
912
+ get runningLateCommands() { return this.lateCommands.snapshot(); }
913
+ // Commands the agent waits on after its Codex turn ended. The per-turn
914
+ // wrapper holds the Arco turn open for them and delivers each result once.
915
+ get heldCommands() { return this.lateCommands.running(); }
916
+ hasHeldResults() { return this.lateCommands.hasResults(); }
917
+ hasFailedHeldResult() { return this.lateCommands.hasFailedResult(); }
918
+ takeHeldResults() { return this.lateCommands.takeResults(); }
919
+ restoreHeldResults(results) { this.lateCommands.restoreResults(results); }
920
+ showHeldUntil(until) { this.lateCommands.hold(until); }
921
+ releaseHeldWait() { this.lateCommands.release(); }
922
+ // Arco's text may join the running turn only before its final answer starts.
923
+ get acceptsResultSteer() { return !!this.current.turnId && !this.current.finalAnswerStarted; }
924
+ abandonHeldCommands() { this.lateCommands.abandon(); }
925
+ /** Add Arco's text to the running turn. False when no turn takes it. */
926
+ async steerText(text) {
927
+ const turn = this.current;
928
+ if (!this.rpc || !this.threadId || !turn.turnId)
929
+ return false;
930
+ try {
931
+ await this.rpc.request('turn/steer', {
932
+ threadId: this.threadId, input: buildSteerInput([{ content: text }]),
933
+ responsesapiClientMetadata: null, expectedTurnId: turn.turnId,
934
+ });
935
+ return true;
936
+ }
937
+ catch (err) {
938
+ console.warn(`[appserver:${this.workflowId.slice(0, 8)}] command result steer failed: ${err instanceof Error ? err.message : String(err)}`);
939
+ return false;
940
+ }
941
+ }
942
+ commandToolUse(item, completed) {
943
+ return {
944
+ name: 'Bash',
945
+ input: JSON.stringify({ command: item.command, cwd: item.cwd }),
946
+ status: completed ? (item.exitCode === 0 ? 'completed' : 'failed') : 'started',
947
+ provider: appServerProvider(this.config), itemType: 'command_execution', itemId: item.id,
948
+ ...(completed && item.aggregatedOutput != null ? { output: item.aggregatedOutput } : {}),
949
+ ...(completed && item.exitCode != null ? { exitCode: item.exitCode } : {}),
950
+ };
951
+ }
952
+ handleCommandItem(p, completed) {
953
+ if (p.item.type !== 'commandExecution')
954
+ return false;
955
+ if (p.threadId !== this.threadId || appServerProvider(this.config) !== 'codex')
956
+ return false;
957
+ const active = this.current.startedAt && (!this.current.turnId || p.turnId === this.current.turnId);
958
+ const event = this.commandToolUse(p.item, completed);
959
+ if (completed) {
960
+ // One completion per command: one that ended after the agent's final
961
+ // answer began is kept for after this turn; one from a turn that has
962
+ // already completed belongs to the long-lived publisher.
963
+ if (active && this.current.finalAnswerStarted)
964
+ this.lateCommands.completeUnseen(p.turnId, event);
965
+ else if (this.lateCommands.complete(p.turnId, event))
966
+ return true;
967
+ }
968
+ else if (active)
969
+ this.lateCommands.start(p.turnId, event);
970
+ if (active)
971
+ this.emit('tool_use', event);
972
+ return true;
973
+ }
906
974
  onNotification(n) {
907
975
  switch (n.method) {
908
976
  case 'serverRequest/resolved': {
@@ -911,6 +979,13 @@ export class CodexAppServerWorker extends EventEmitter {
911
979
  this.operatorQuestions.resolvedRpc(p.requestId);
912
980
  return;
913
981
  }
982
+ case 'thread/closed': {
983
+ // Codex unloaded the thread and stopped its terminals: no held
984
+ // command will report an end any more.
985
+ if (n.params.threadId === this.threadId)
986
+ this.lateCommands.disconnect();
987
+ return;
988
+ }
914
989
  case 'thread/started': {
915
990
  const p = n.params;
916
991
  this.threadId = p.thread.id;
@@ -987,12 +1062,17 @@ export class CodexAppServerWorker extends EventEmitter {
987
1062
  }
988
1063
  case 'item/started': {
989
1064
  const p = n.params;
990
- this.emitToolUseFromItem(p.item, 'started');
1065
+ if (p.item.type === 'agentMessage' && p.item.phase === 'final_answer' && p.threadId === this.threadId
1066
+ && this.current.startedAt && (!this.current.turnId || p.turnId === this.current.turnId))
1067
+ this.current.finalAnswerStarted = true;
1068
+ if (!this.handleCommandItem(p, false))
1069
+ this.emitToolUseFromItem(p.item, 'started');
991
1070
  return;
992
1071
  }
993
1072
  case 'item/completed': {
994
1073
  const p = n.params;
995
- this.emitToolUseFromItem(p.item, 'completed');
1074
+ if (!this.handleCommandItem(p, true))
1075
+ this.emitToolUseFromItem(p.item, 'completed');
996
1076
  const asyncItem = p.item;
997
1077
  if (asyncItem.type === 'agentMessage' && asyncItem.delivery === 'async' && p.threadId === this.threadId && this.current.startedAt && (!this.current.turnId || p.turnId === this.current.turnId)) {
998
1078
  try {
@@ -1114,23 +1194,9 @@ export class CodexAppServerWorker extends EventEmitter {
1114
1194
  // unchanged on appserver tabs.
1115
1195
  const provider = appServerProvider(this.config);
1116
1196
  switch (item.type) {
1117
- case 'commandExecution': {
1118
- const completed = status === 'completed';
1119
- const finalStatus = completed ? (item.exitCode === 0 ? 'completed' : 'failed') : 'started';
1120
- this.emit('tool_use', {
1121
- name: 'Bash',
1122
- input: JSON.stringify({ command: item.command, cwd: item.cwd }),
1123
- status: finalStatus,
1124
- provider,
1125
- itemType: 'command_execution',
1126
- itemId: item.id,
1127
- ...(completed && item.aggregatedOutput !== null
1128
- ? { output: item.aggregatedOutput }
1129
- : {}),
1130
- ...(completed && item.exitCode !== null ? { exitCode: item.exitCode } : {}),
1131
- });
1197
+ case 'commandExecution':
1198
+ this.emit('tool_use', this.commandToolUse(item, status === 'completed'));
1132
1199
  return;
1133
- }
1134
1200
  case 'fileChange': {
1135
1201
  const completed = status === 'completed';
1136
1202
  const finalStatus = completed ? (item.status === 'completed' ? 'completed' : 'failed') : 'started';
@@ -1496,6 +1562,8 @@ export class CodexAppServerWorker extends EventEmitter {
1496
1562
  this.emit('turn_settled', data);
1497
1563
  return;
1498
1564
  }
1565
+ if (this.current.turnId)
1566
+ this.lateCommands.settle(this.current.turnId);
1499
1567
  this.current = emptyTurnState();
1500
1568
  if (data.error && data.error !== 'Worker killed') {
1501
1569
  // Also run the stderr fallback throttle sniffer in case the protocol
@@ -1519,6 +1587,7 @@ export class CodexAppServerWorker extends EventEmitter {
1519
1587
  this.emit('fatal', reason);
1520
1588
  }
1521
1589
  teardownProcess() {
1590
+ this.lateCommands.disconnect();
1522
1591
  this.operatorQuestions.cancel('The Codex connection closed.');
1523
1592
  if (this.rpc) {
1524
1593
  try {
@@ -1,3 +1,4 @@
1
+ import { codexTurnWaitInstructions } from './codexCodeMode.js';
1
2
  import { prepareProviderHistory, historyBinding } from './handoffHistoryBinding.js';
2
3
  import { prepareLocalFileContext, combineChatAttachments } from './localFileMedia.js';
3
4
  import { codexChatOverrides, requireCodexChatCapabilities } from './codexChatBoundary.js';
@@ -106,7 +107,7 @@ class CodexWorkerProcess extends EventEmitter {
106
107
  // prefix cache like the rest of the framing. Covers operator turns AND
107
108
  // primitive seeds (both carry config.goal). Absent / blank ⇒ no change.
108
109
  // The output-style addendum closes the prefix, as on app-server.
109
- const prefixParts = [goalBlock(this.config.goal), this.config.appendSystemPrompt, cliFileReadGuidance(this.config), outputStyleAddendum(this.config.outputStyle)]
110
+ const prefixParts = [codexTurnWaitInstructions(this.config.clusterRole), goalBlock(this.config.goal), this.config.appendSystemPrompt, cliFileReadGuidance(this.config), outputStyleAddendum(this.config.outputStyle)]
110
111
  .filter((s) => typeof s === 'string' && s.length > 0);
111
112
  const prefixSp = prefixParts.length > 0 ? prefixParts.join('\n\n') : undefined;
112
113
  const fullPrompt = prefixSp
@@ -1,5 +1,6 @@
1
1
  import type { WorkerConfig } from '@arco/shared';
2
2
  export declare function codexModelUsesCodeMode(modelId: string, codexHome?: string): boolean | null;
3
3
  export declare function codexCodeModeClusterAddendum(): string;
4
- export declare const CODEX_TURN_DISCIPLINE = "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.";
4
+ export declare const CODEX_TURN_DISCIPLINE: string;
5
+ export declare function codexTurnWaitInstructions(role: string | undefined): string;
5
6
  export declare function codexClusterDeveloperInstructions(config: WorkerConfig): string | null;
@@ -11,6 +11,7 @@
11
11
  import * as fs from 'node:fs';
12
12
  import { resolveCodexHome } from './codexHome.js';
13
13
  import * as path from 'node:path';
14
+ import { AGENT_TURN_WAIT, buildTurnWaitInstructions, isClusterDirector } from '@arco/shared';
14
15
  import { buildClusterDirectorDoctrine } from '../clusterDirector.js';
15
16
  // Keyed by resolved models_cache.json path; revalidated by mtime so a codex
16
17
  // catalog refresh (hourly, or on CLI upgrade) is picked up next turn.
@@ -80,17 +81,21 @@ export function codexCodeModeClusterAddendum() {
80
81
  ].join('\n');
81
82
  }
82
83
  // Standing turn discipline for every Codex workflow (cluster and single).
83
- export const CODEX_TURN_DISCIPLINE = '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.';
84
+ const CODEX_COMMAND_WAIT = 'A command reply with a session ID and no exit code means it is still running. Poll that session until it exits before reporting, and do not end the turn saying you are waiting for it. Start a program meant to keep running, such as a server or a watcher, in the background with & or nohup, so Arco does not wait for it.';
85
+ export const CODEX_TURN_DISCIPLINE = AGENT_TURN_WAIT + ' ' + CODEX_COMMAND_WAIT;
86
+ export function codexTurnWaitInstructions(role) {
87
+ return isClusterDirector(role) ? buildTurnWaitInstructions(role) : CODEX_TURN_DISCIPLINE;
88
+ }
84
89
  // app-server can place Arco's durable cluster identity at developer level
85
90
  // when a thread starts/resumes. Per-turn plan content still rides in user
86
91
  // input because it is mutable; the stable role and tool contract do not need
87
92
  // to compete with Codex's own `/root` developer framing there.
88
93
  // Non-cluster threads still receive CODEX_TURN_DISCIPLINE so single workflows
89
- // stay available to the operator the same way.
94
+ // wait for the result their report depends on and check for messages between waits.
90
95
  export function codexClusterDeveloperInstructions(config) {
91
96
  if (config.provider !== 'codex')
92
97
  return null;
93
- const blocks = [CODEX_TURN_DISCIPLINE];
98
+ const blocks = [codexTurnWaitInstructions(config.clusterRole)];
94
99
  if (config.clusterId) {
95
100
  blocks.push('--- Arco cluster identity ---', config.clusterRole ? `Your operator-assigned role in the Arco cluster is: ${config.clusterRole.trim()}` : '', buildClusterDirectorDoctrine(config.clusterRole) ?? '');
96
101
  if (codexModelUsesCodeMode(config.model, config.codexHome) !== false) {
@@ -1,3 +1,4 @@
1
+ import { buildTurnWaitInstructions } from '@arco/shared';
1
2
  import { prepareProviderHistory, historyBinding } from '../handoffHistoryBinding.js';
2
3
  import { prepareLocalFileContext, combineChatAttachments } from '../localFileMedia.js';
3
4
  import { createChatSandbox, CHAT_FLAGS, CHAT_GUIDANCE } from './chatSandbox.js';
@@ -114,7 +115,7 @@ class CursorPrintProcess extends EventEmitter {
114
115
  // ACP worker's beginTurn. goalBlock is null-when-empty so the default primitive
115
116
  // path is byte-identical to a bare prompt.
116
117
  // The output-style addendum closes the prefix (null for normal).
117
- const prefixParts = [chat ? CHAT_GUIDANCE : undefined, goalBlock(this.config.goal), this.config.appendSystemPrompt, this.filePlugin ? FILE_READ_GUIDANCE : undefined, outputStyleAddendum(this.config.outputStyle)]
118
+ const prefixParts = [buildTurnWaitInstructions(this.config.clusterRole), chat ? CHAT_GUIDANCE : undefined, goalBlock(this.config.goal), this.config.appendSystemPrompt, this.filePlugin ? FILE_READ_GUIDANCE : undefined, outputStyleAddendum(this.config.outputStyle)]
118
119
  .filter((s) => typeof s === 'string' && s.trim().length > 0);
119
120
  const prefix = prefixParts.length > 0 ? prefixParts.join('\n\n') : undefined;
120
121
  const body = [prompt, prepared?.text, chat ? undefined : withAttachmentRefs('', imagePaths)].filter(Boolean).join('\n\n');
@@ -1,3 +1,4 @@
1
+ import { buildTurnWaitInstructions } from '@arco/shared';
1
2
  import { historyBinding } from '../handoffHistoryBinding.js';
2
3
  import { readFileContent } from '../../fileContent.js';
3
4
  import { prepareProviderAttachments, FILE_READ_GUIDANCE } from '../providerFileContent.js';
@@ -320,7 +321,7 @@ export class CursorAcpWorker extends EventEmitter {
320
321
  // above appendSystemPrompt, both above the `---` prompt separator. goalBlock is
321
322
  // null-when-empty so the default path is byte-identical to pre-Phase-4.
322
323
  // The output-style addendum closes the prefix (null for normal).
323
- const prefixParts = [goalBlock(this.config.goal), appendSystemPrompt, this.clusterMcpDescriptor && this.config.cwd ? FILE_READ_GUIDANCE : undefined, outputStyleAddendum(this.config.outputStyle)]
324
+ const prefixParts = [buildTurnWaitInstructions(this.config.clusterRole), goalBlock(this.config.goal), appendSystemPrompt, this.clusterMcpDescriptor && this.config.cwd ? FILE_READ_GUIDANCE : undefined, outputStyleAddendum(this.config.outputStyle)]
324
325
  .filter((s) => typeof s === 'string' && s.trim().length > 0);
325
326
  const prefix = prefixParts.length > 0 ? prefixParts.join('\n\n') : undefined;
326
327
  // Operator attachments: images ride as ACP `image` content blocks when the
@@ -341,7 +341,7 @@ class LlamacppWorkerProcess extends EventEmitter {
341
341
  };
342
342
  let res;
343
343
  try {
344
- res = await requestWithDeadline(this.abortController.signal, recovery.enabled ? Math.min(recovery.stallTimeoutMs, recovery.turnBudgetMs) : 120_000, (signal) => fetch(`${baseUrl}/v1/chat/completions`, {
344
+ res = await requestWithDeadline(this.abortController.signal, Math.min(recovery.stallTimeoutMs, recovery.turnBudgetMs), (signal) => fetch(`${baseUrl}/v1/chat/completions`, {
345
345
  method: 'POST',
346
346
  headers: { 'Content-Type': 'application/json' },
347
347
  body: JSON.stringify(body),
@@ -390,22 +390,23 @@ class LlamacppWorkerProcess extends EventEmitter {
390
390
  const charsToTokens = (chars) => Math.ceil(chars / 4);
391
391
  // Recovery-bounded stream read. Wraps reader.read() in a stall timeout
392
392
  // and a per-iteration runaway check. Aborts the upstream call cleanly
393
- // when either trips so the run loop can recover.
393
+ // when either trips so the run loop can recover. The time limits also
394
+ // apply with recovery off; that setting controls retries, not the bound.
394
395
  const readWithGuards = async () => {
395
- if (!recovery.enabled)
396
- return reader.read();
396
+ const remainingMs = recovery.turnBudgetMs - (Date.now() - turnStart);
397
+ const wallClockFirst = remainingMs <= recovery.stallTimeoutMs;
397
398
  let stallTimer = null;
398
399
  try {
399
400
  return await Promise.race([
400
401
  reader.read(),
401
402
  new Promise((resolve) => {
402
403
  stallTimer = setTimeout(() => {
403
- interruption = 'stall';
404
+ interruption = wallClockFirst ? 'wall_clock' : 'stall';
404
405
  // Cancel the underlying body reader so the next read() resolves
405
406
  // with done:true; resolve our race so the outer loop exits.
406
407
  reader.cancel().catch(() => { });
407
408
  resolve({ done: true });
408
- }, recovery.stallTimeoutMs);
409
+ }, Math.max(0, Math.min(recovery.stallTimeoutMs, remainingMs)));
409
410
  }),
410
411
  ]);
411
412
  }
@@ -430,7 +431,7 @@ class LlamacppWorkerProcess extends EventEmitter {
430
431
  // Catches the "tool_calls + reasoning + content pumping endlessly"
431
432
  // mode that the runaway detector misses (model looks productive by
432
433
  // every per-signal metric but isn't converging).
433
- if (recovery.enabled && Date.now() - turnStart > recovery.turnBudgetMs) {
434
+ if (Date.now() - turnStart >= recovery.turnBudgetMs) {
434
435
  interruption = 'wall_clock';
435
436
  reader.cancel().catch(() => { });
436
437
  break;
@@ -449,7 +450,7 @@ class LlamacppWorkerProcess extends EventEmitter {
449
450
  break;
450
451
  }
451
452
  const { value, done } = await readWithGuards();
452
- if (interruption === 'stall')
453
+ if (interruption)
453
454
  break;
454
455
  if (done) {
455
456
  streamEnded = true;
@@ -777,6 +778,14 @@ class LlamacppWorkerProcess extends EventEmitter {
777
778
  const turnResult = await this.streamOneTurn(baseUrl, def.alias, messages, tools, recovery);
778
779
  if (turnResult === null)
779
780
  return;
781
+ if (!recovery.enabled && turnResult.interruption) {
782
+ await this.eraseLlamaSlot(baseUrl);
783
+ const reason = turnResult.interruption === 'stall'
784
+ ? `no stream data for ${recovery.stallTimeoutMs}ms`
785
+ : `reply exceeded the ${recovery.turnBudgetMs}ms time limit`;
786
+ this.fail(`llama.cpp stopped: ${reason}. Automatic recovery is off; no retry was made.`);
787
+ return;
788
+ }
780
789
  // Don't update lastInputTokens on interrupted streams — the usage
781
790
  // event only fires on normal completion, so an interrupted call
782
791
  // leaves the field at 0 and would falsely "reset" the CTX bar.
@@ -1,8 +1,8 @@
1
1
  // Ollama auto-compaction (Master-plan M8 / Hardening §6 Phase 4).
2
2
  //
3
3
  // This is a PORT of `llamacppRecovery.ts`'s auto-compaction to the Ollama
4
- // provider, sharpened with the two tool-message invariants odysseus learned the
5
- // hard way (sanitize orphaned tool turns, truncate oversized tool-call args).
4
+ // provider, with two tool-message invariants ported from Odysseus
5
+ // (sanitize orphaned tool turns, truncate oversized tool-call args).
6
6
  // Read `llamacppRecovery.ts` first — this module mirrors its operator-facing
7
7
  // POSTURE exactly: opt-in by choosing the provider (default-on for the provider,
8
8
  // env-gated off), bounded by a deterministic context-fill threshold, every
@@ -13,8 +13,8 @@
13
13
  // ── WHY THE TRANSFORM DIFFERS FROM llamacppRecovery.performCompaction ─────────
14
14
  // The reference asks the PRIMARY model to summarize its whole stack and reseeds
15
15
  // `[system, seed]`. M8's spec (Hardening §6) is sharper, matching odysseus:
16
- // - keep the leading system block intact (odysseus dropped it with a naïve
17
- // split — load-bearing);
16
+ // - keep the leading system block intact (a naive midpoint split can drop
17
+ // the system prompt - load-bearing);
18
18
  // - keep the current turn + last-10 messages VERBATIM (the recent tail the
19
19
  // model needs to continue coherently — a summary of the last few turns
20
20
  // loses the exact state the model is mid-edit on);
@@ -318,8 +318,8 @@ export function compactionSeedMessage(summary, foldedCount) {
318
318
  // pairing + arg-size safety).
319
319
  export function splitForCompaction(messages, keepLastMessages) {
320
320
  // Leading system block: all consecutive system messages at the front. Preserve
321
- // them verbatim — odysseus's bug was dropping the system prompt with a naïve
322
- // midpoint split. Offset the split past it.
321
+ // them verbatim - a naive midpoint split can drop the system prompt.
322
+ // Offset the split past it.
323
323
  let sysEnd = 0;
324
324
  while (sysEnd < messages.length && messages[sysEnd].role === 'system')
325
325
  sysEnd++;
@@ -28,9 +28,9 @@
28
28
  import { execFile } from 'child_process';
29
29
  // ── Cooldown TTLs (Hardening §4: SHORT 5–15s, not minutes) ────────────────
30
30
  //
31
- // A blipped Tailscale host must rejoin selection fast — odysseus's hard-won
32
- // lesson: "a SINGLE transient blip used to trip a full 60s lockout — the user
33
- // saw a 503 and thought the model died when it was fine a second later." We
31
+ // A blipped Tailscale host must rejoin selection fast. A single transient
32
+ // failure must not impose a full 60s lockout after the backend has recovered,
33
+ // leaving requests blocked even though the host is healthy again. We
34
34
  // cool reactively on the failure itself (no per-minute %-failure math — at low
35
35
  // local request volume a single failure IS the whole signal, per Excellence
36
36
  // §"Deliberately rejected") and recover lazily once the TTL lapses.
@@ -17,7 +17,7 @@ import { imageBase64TokenCost } from '../imageTokens.js';
17
17
  // so it can compact BEFORE the request overflows the window, not after a
18
18
  // 400. This module is that estimate.
19
19
  //
20
- // THE LOAD-BEARING GOTCHA (odysseus 6973c54, Hardening §5): a naïve estimate
20
+ // THE LOAD-BEARING GOTCHA (Hardening §5): a naïve estimate
21
21
  // that only counts visible `content` text undershoots by 20-30% on tool-heavy
22
22
  // transcripts, because a tool-CALL assistant turn carries `content:""` with
23
23
  // the entire payload in `tool_calls[].function.arguments`, and a tool-RESULT
@@ -26,22 +26,4 @@ export declare function wireSnapshot(): Record<ProviderName, {
26
26
  throttled: boolean;
27
27
  resetsAt?: number;
28
28
  }>;
29
- /**
30
- * Legacy PROVIDER STATUS formatter, currently without live callers. Returns empty string when every
31
- * provider is available — no need to clutter the prompt when routing is
32
- * unconstrained. See §6.4 for the format.
33
- */
34
- export declare function buildQuotaInjection(): string;
35
- /**
36
- * §5.4 cross-family reviewer fallback. Maps a primary model to a cross-family
37
- * reviewer used when the preferred reviewer's provider is throttled. Returns
38
- * null for models that intentionally skip review (ollama / heretic).
39
- *
40
- * Legacy helper, currently without live callers. Kept for a separate cleanup.
41
- */
42
- export interface ReviewerFallback {
43
- model: string;
44
- provider: ProviderName;
45
- }
46
- export declare function crossFamilyFallback(primaryModel: string): ReviewerFallback | null;
47
29
  export {};
@@ -119,48 +119,4 @@ export function wireSnapshot() {
119
119
  }
120
120
  return out;
121
121
  }
122
- /**
123
- * Legacy PROVIDER STATUS formatter, currently without live callers. Returns empty string when every
124
- * provider is available — no need to clutter the prompt when routing is
125
- * unconstrained. See §6.4 for the format.
126
- */
127
- export function buildQuotaInjection() {
128
- const snap = snapshot();
129
- const anyThrottled = PROVIDERS.some((p) => snap[p].throttled);
130
- if (!anyThrottled)
131
- return '';
132
- const lines = ['## PROVIDER STATUS'];
133
- for (const p of PROVIDERS) {
134
- const s = snap[p];
135
- if (s.throttled) {
136
- const suffix = s.resetsAt
137
- ? ` until ${new Date(s.resetsAt).toISOString()}`
138
- : ' (no reset time known)';
139
- lines.push(`- ${p}: THROTTLED${suffix}`);
140
- }
141
- else {
142
- lines.push(`- ${p}: available`);
143
- }
144
- }
145
- lines.push('');
146
- lines.push('Dispatch AWAY from throttled providers. If a capable worker from an available provider can cover the task, pick that one. Throttled-provider spawns will fail — the cost of retrying is wasted tokens and a stuck workflow.');
147
- return lines.join('\n');
148
- }
149
- export function crossFamilyFallback(primaryModel) {
150
- // Codex → Claude
151
- if (primaryModel === 'gpt-5.4-mini')
152
- return { model: 'opus', provider: 'claude' };
153
- if (primaryModel === 'gpt-5.3-codex')
154
- return { model: 'opus', provider: 'claude' };
155
- if (primaryModel === 'gpt-5.2-codex')
156
- return { model: 'opus', provider: 'claude' };
157
- if (primaryModel === 'gpt-5.5')
158
- return { model: 'opus', provider: 'claude' };
159
- if (primaryModel === 'gpt-5.4')
160
- return { model: 'opus', provider: 'claude' };
161
- if (primaryModel === 'gpt-5.1-codex-max')
162
- return { model: 'opus', provider: 'claude' };
163
- // Heretic (ollama) — review intentionally skipped.
164
- return null;
165
- }
166
122
  //# sourceMappingURL=quota.js.map
@@ -0,0 +1,19 @@
1
+ import { type TranscriptSliceOptions } from './transcriptWorker.js';
2
+ export declare const REPLACEMENT_FULL_BYTES: number;
3
+ export declare const REPLACEMENT_RECENT_BYTES: number;
4
+ export type ReplacementHistoryMode = 'recent' | 'full';
5
+ export declare function buildReplacementHistory(cwd: string, workflowId: string, mode: ReplacementHistoryMode, options: TranscriptSliceOptions): Promise<{
6
+ seed: string;
7
+ bytes: number;
8
+ selectedTurns: number;
9
+ digest: string;
10
+ historyMode: ReplacementHistoryMode;
11
+ requestedTurns: number;
12
+ truncated: boolean;
13
+ historyFallback: boolean;
14
+ availableTurns: number;
15
+ partialIncluded: boolean;
16
+ cutoffSeq: number;
17
+ branchKey: string;
18
+ }>;
19
+ export declare function replacementHistoryNotice(preview: Awaited<ReturnType<typeof buildReplacementHistory>>): string | undefined;
@@ -0,0 +1,49 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { buildTranscriptSlice } from './transcriptWorker.js';
3
+ import { replayEvents } from './workflowStore.js';
4
+ import { renderTranscript, summarizePriorTurns } from './primitives/exportContext.js';
5
+ import { RECENT_HISTORY_MAX_BYTES } from './historyLimits.js';
6
+ export const REPLACEMENT_FULL_BYTES = 512 * 1024;
7
+ export const REPLACEMENT_RECENT_BYTES = RECENT_HISTORY_MAX_BYTES;
8
+ export async function buildReplacementHistory(cwd, workflowId, mode, options) {
9
+ if (mode !== 'recent' && mode !== 'full')
10
+ throw new Error('Choose NO HISTORY, RECENT HISTORY or FULL HISTORY.');
11
+ const slice = await buildTranscriptSlice(cwd, workflowId, { ...options, turns: mode === 'full' ? Number.MAX_SAFE_INTEGER : options.turns }, {
12
+ maxBytes: mode === 'full' ? REPLACEMENT_FULL_BYTES : REPLACEMENT_RECENT_BYTES,
13
+ fitWholeTurns: true, allTurns: mode === 'full',
14
+ });
15
+ let seed = slice.seed, selectedTurns = slice.selectedTurns, historyFallback = false;
16
+ if (mode === 'full') {
17
+ // Preserve the existing full-history transcript and action digest while
18
+ // they fit. Only the oversized fallback uses the shared recent-turn form.
19
+ const events = (await replayEvents(cwd, workflowId, 0)).filter(event => !('seq' in event) || typeof event.seq !== 'number' || event.seq <= slice.cutoffSeq);
20
+ const transcript = renderTranscript(events).trim(), actions = summarizePriorTurns(events).trim();
21
+ const full = [
22
+ '[REPLACEMENT CONTEXT — copied by explicit operator request; this is a new provider session]',
23
+ transcript,
24
+ actions ? `\n[Prior-turn action digest]\n${actions}` : '',
25
+ '\nAcknowledge this imported context briefly, then wait for the operator.',
26
+ ].filter(Boolean).join('\n\n');
27
+ if (Buffer.byteLength(full, 'utf8') <= REPLACEMENT_FULL_BYTES) {
28
+ seed = full;
29
+ selectedTurns = slice.availableTurns;
30
+ }
31
+ else
32
+ historyFallback = true;
33
+ }
34
+ const bytes = Buffer.byteLength(seed, 'utf8');
35
+ const digest = createHash('sha256').update(JSON.stringify({ source: slice.digest, seed, mode, turns: options.turns })).digest('hex');
36
+ return { ...slice, seed, bytes, selectedTurns, digest, historyMode: mode,
37
+ requestedTurns: mode === 'full' ? slice.availableTurns : options.turns,
38
+ truncated: selectedTurns < slice.availableTurns, historyFallback };
39
+ }
40
+ export function replacementHistoryNotice(preview) {
41
+ if (!preview.truncated && !preview.historyFallback)
42
+ return;
43
+ if (!preview.selectedTurns)
44
+ return 'No whole recent turn fit the replacement history limit. No earlier history was copied; it remains in the previous member conversation.';
45
+ if (preview.truncated)
46
+ return `Only the most recent ${preview.selectedTurns} of ${preview.availableTurns} turns were copied from the previous member. Earlier turns were not copied; they remain in its conversation.`;
47
+ return `The full history exceeded 512 KiB. All ${preview.selectedTurns} turns were copied as text and tool/file receipts; the full action digest was not copied.`;
48
+ }
49
+ //# sourceMappingURL=replacementHistory.js.map
@@ -17,10 +17,11 @@ export declare function releasePlansWatcher(cwd: string): void;
17
17
  export declare function fsWatchEnsureDir(dir: string): void;
18
18
  export declare function flushPlansWatcher(cwd: string, state: PlansWatcher): Promise<void>;
19
19
  export declare function broadcastWorkflow(workflowId: string, message: ServerMessage): void;
20
- export declare const CLUSTER_STATE_TRIGGERS: Set<"error" | "provider_fell_back" | "checkpoint_created" | "turn_changes" | "checkpoint_reverted" | "operator_question" | "operator_question_reply_result" | "operator_question_dismiss_result" | "mcp_registry_snapshot" | "mcp_probe_result" | "mcp_allow_snapshot" | "mcp_malware_warning" | "genesis_seed_updated" | "genesis_assist_started" | "genesis_assist_proposed" | "workflow_cwd_bound" | "genesis_scaffolded" | "genesis_creative_armed" | "genesis_plan_saved" | "computer_context_updated" | "voice_tool_call" | "computer_activity_changed" | "output_saved" | "peer_message_sent" | "peer_message_received" | "peer_send_rejected" | "cluster_snapshot_list" | "cluster_snapshot_saved" | "cluster_snapshot_conflict" | "cluster_snapshot_error" | "workflow_rename_result" | "workflow_renamed" | "cluster_state" | "cluster_not_found" | "cluster_creation_finished" | "cluster_created" | "cluster_deleted" | "cluster_member_added" | "cluster_member_removed" | "cluster_member_replaced" | "cluster_plan_changed" | "codebase_memory_state" | "cluster_broadcast_dispatched" | "cluster_dispatch_result" | "cluster_swarm_created" | "cluster_member_nudged" | "cluster_auto_turn_fired" | "hub_link_status" | "bakeoff_list_result" | "bakeoff_state" | "bakeoff_error" | "bakeoff_attempts_removed" | "review_started" | "review_artifact_ready" | "research_started" | "research_progress" | "research_complete" | "compare_started" | "compare_leg_delta" | "compare_leg_complete" | "compare_complete" | "compare_vote_recorded" | "diagnostics" | "doc_edit_started" | "doc_edit_proposed" | "md_tuneup_candidates" | "md_tuneup_started" | "md_tuneup_proposed" | "md_tuneup_applied" | "md_tuneup_undone" | "knowledge_distill_started" | "knowledge_distill_proposed" | "recall_summary_ready" | "workbench_notice" | "notification_mutes" | "attention_event" | "attention_question_closed" | "handoff_started" | "handoff_artifact_ready" | "handoff_complete" | "handoff_lock_snapshot" | "spawn_from_here_complete" | "live_changes_snapshot" | "storage_warning" | "git_op_result" | "media_stems_result" | "media_op_result" | "terminal_opened" | "terminal_sessions" | "terminal_killed" | "shutdown" | "terminal_command_logged" | "task_ledger_snapshot" | "task_ledger_event" | "cluster_orchestration_assist_started" | "cluster_orchestration_proposal_started" | "cluster_orchestration_proposals_snapshot" | "cluster_orchestration_proposal_proposed" | "cluster_orchestration_proposal_rejected" | "cluster_orchestration_proposal_applied" | "preview_capture_started" | "preview_capture_ready" | "plan_attached" | "plan_detached" | "plan_set" | "plan_exited" | "plan_candidate_ready" | "connected" | "workspace_snapshot" | "workspace_changed" | "workflow_config_synced" | "workflow_created" | "user_message_echo" | "primary_text" | "primary_complete" | "hook_rewrote_input" | "tool_gate_triggered" | "tool_posture_set" | "goal_set" | "goal_run_state" | "pinned_skills_set" | "project_trust_prompt" | "project_trust_set" | "worker_stuck" | "tool_loop_warning" | "file_mutation_queued" | "model_resolved" | "primary_refusal" | "primary_tool_counter" | "sandbox_chunk_added" | "sandbox_db_cleared" | "ctx_action" | "native_compacting" | "native_compacted" | "context_folded" | "tool_filtered" | "tool_evicted" | "primary_turn_token_usage" | "primary_model" | "primary_thinking" | "primary_tool_use" | "primary_activity" | "primary_turn_started" | "primary_turn_ended" | "worker_model" | "worker_spawned" | "worker_text" | "worker_thinking" | "worker_tool_use" | "worker_complete" | "worker_activity" | "worker_error" | "file_uploaded" | "file_context" | "worker_file_context" | "primary_artifact" | "quota_status" | "turn_cancelled" | "conversation_changed" | "provider_conversation_state" | "workflow_state_snapshot" | "workflow_session_metadata" | "replay_batch" | "capabilities_updated" | "capabilities_changed" | "settings_updated" | "session_entry" | "queued_message_edit_result" | "queued_message_cancelled" | "queued_messages_drained" | "system_notice" | "claude_native_question_settled" | "session_history_status" | "codex_token_snapshot" | "gate_required" | "gate_resolved" | "gate_standing" | "preview_set" | "preview_cleared" | "preview_history" | "context_usage" | "ultracode_fleet_progress" | "context_budget" | "operator_label" | "queue_update" | "todos_updated" | "task_started" | "task_status" | "branch_summary" | "leaf_move" | "app_update_available" | "turn_messages_delivered">;
20
+ export declare const CLUSTER_STATE_TRIGGERS: Set<"error" | "provider_fell_back" | "checkpoint_created" | "turn_changes" | "checkpoint_reverted" | "operator_question" | "operator_question_reply_result" | "operator_question_dismiss_result" | "mcp_registry_snapshot" | "mcp_probe_result" | "mcp_allow_snapshot" | "mcp_malware_warning" | "genesis_seed_updated" | "genesis_assist_started" | "genesis_assist_proposed" | "workflow_cwd_bound" | "genesis_scaffolded" | "genesis_creative_armed" | "genesis_plan_saved" | "computer_context_updated" | "voice_tool_call" | "computer_activity_changed" | "output_saved" | "transcript_worker_result" | "peer_message_sent" | "peer_message_received" | "peer_send_rejected" | "cluster_snapshot_list" | "cluster_snapshot_saved" | "cluster_snapshot_conflict" | "cluster_snapshot_error" | "workflow_rename_result" | "workflow_renamed" | "cluster_state" | "cluster_not_found" | "cluster_creation_finished" | "cluster_created" | "cluster_deleted" | "cluster_member_added" | "cluster_member_removed" | "cluster_member_replaced" | "cluster_plan_changed" | "codebase_memory_state" | "cluster_broadcast_dispatched" | "cluster_dispatch_result" | "cluster_swarm_created" | "cluster_member_nudged" | "cluster_auto_turn_fired" | "hub_link_status" | "bakeoff_list_result" | "bakeoff_state" | "bakeoff_error" | "bakeoff_attempts_removed" | "review_started" | "review_artifact_ready" | "research_started" | "research_progress" | "research_complete" | "compare_started" | "compare_leg_delta" | "compare_leg_complete" | "compare_complete" | "compare_vote_recorded" | "diagnostics" | "doc_edit_started" | "doc_edit_proposed" | "md_tuneup_candidates" | "md_tuneup_started" | "md_tuneup_proposed" | "md_tuneup_applied" | "md_tuneup_undone" | "knowledge_distill_started" | "knowledge_distill_proposed" | "recall_summary_ready" | "workbench_notice" | "notification_mutes" | "attention_event" | "attention_question_closed" | "handoff_started" | "handoff_artifact_ready" | "handoff_complete" | "handoff_lock_snapshot" | "spawn_from_here_complete" | "live_changes_snapshot" | "storage_warning" | "git_op_result" | "media_stems_result" | "media_op_result" | "terminal_opened" | "terminal_sessions" | "terminal_killed" | "shutdown" | "terminal_command_logged" | "task_ledger_snapshot" | "task_ledger_event" | "cluster_orchestration_assist_started" | "cluster_orchestration_proposal_started" | "cluster_orchestration_proposals_snapshot" | "cluster_orchestration_proposal_proposed" | "cluster_orchestration_proposal_rejected" | "cluster_orchestration_proposal_applied" | "preview_capture_started" | "preview_capture_ready" | "plan_attached" | "plan_detached" | "plan_set" | "plan_exited" | "plan_candidate_ready" | "connected" | "workspace_snapshot" | "workspace_changed" | "workflow_config_synced" | "workflow_created" | "user_message_echo" | "primary_text" | "primary_complete" | "hook_rewrote_input" | "tool_gate_triggered" | "tool_posture_set" | "goal_set" | "goal_run_state" | "pinned_skills_set" | "project_trust_prompt" | "project_trust_set" | "worker_stuck" | "tool_loop_warning" | "file_mutation_queued" | "model_resolved" | "primary_refusal" | "primary_tool_counter" | "sandbox_chunk_added" | "sandbox_db_cleared" | "ctx_action" | "native_compacting" | "native_compacted" | "context_folded" | "tool_filtered" | "tool_evicted" | "primary_turn_token_usage" | "primary_model" | "primary_thinking" | "primary_tool_use" | "primary_activity" | "primary_turn_started" | "primary_turn_ended" | "worker_model" | "worker_spawned" | "worker_text" | "worker_thinking" | "worker_tool_use" | "worker_complete" | "worker_activity" | "worker_error" | "file_uploaded" | "file_context" | "worker_file_context" | "primary_artifact" | "quota_status" | "turn_cancelled" | "conversation_changed" | "provider_conversation_state" | "workflow_state_snapshot" | "workflow_session_metadata" | "replay_batch" | "capabilities_updated" | "capabilities_changed" | "settings_updated" | "session_entry" | "queued_message_edit_result" | "queued_message_cancelled" | "queued_messages_drained" | "system_notice" | "claude_native_question_settled" | "session_history_status" | "codex_token_snapshot" | "gate_required" | "gate_resolved" | "gate_standing" | "preview_set" | "preview_cleared" | "preview_history" | "context_usage" | "ultracode_fleet_progress" | "context_budget" | "operator_label" | "queue_update" | "todos_updated" | "task_started" | "task_status" | "branch_summary" | "leaf_move" | "app_update_available" | "turn_messages_delivered">;
21
21
  export declare function broadcastCluster(clusterId: string, message: ServerMessage): void;
22
22
  export declare function sendWorkflowLive(workflowId: string, message: ServerMessage, sent?: Set<WebSocket>): void;
23
23
  export declare function buildClusterStatePayload(clusterId: string): Promise<{
24
+ skillPins?: import('@arco/shared').ClusterSkillPin[];
24
25
  clusterId: string;
25
26
  cwd: string;
26
27
  members: Array<{
@@ -723,6 +723,7 @@ export async function buildClusterStatePayload(clusterId) {
723
723
  }
724
724
  return {
725
725
  clusterId,
726
+ ...(state.skillPins?.length ? { skillPins: state.skillPins } : {}),
726
727
  cwd: state.cwd,
727
728
  members,
728
729
  mailboxDepth,
@@ -1,5 +1,6 @@
1
1
  export declare const PREVIEW_NUDGE: string;
2
2
  export declare function withPreviewNudge(existing: string | undefined): string;
3
+ export declare function withLocalTurnWaitInstructions(base: string | undefined, role?: string): string;
3
4
  export declare function buildLocalClusterSystemPrompt(opts: {
4
5
  base?: string;
5
6
  clusterPlan?: string;
@@ -1,3 +1,4 @@
1
+ import { buildTurnWaitInstructions } from '@arco/shared';
1
2
  // Tells the agent the operator can see a live iframe of any dev server it
2
3
  // runs. Static text — appended verbatim to every primary turn so the prefix
3
4
  // cache keeps hitting (Claude / Codex caches; Ollama prefix cache). The
@@ -13,6 +14,11 @@ export const PREVIEW_NUDGE = [
13
14
  export function withPreviewNudge(existing) {
14
15
  return existing && existing.length > 0 ? `${PREVIEW_NUDGE}\n\n${existing}` : PREVIEW_NUDGE;
15
16
  }
17
+ // Local baselines are role-neutral. Add the wait rule once, after the turn's
18
+ // membership is resolved, before wrapping any cluster coordination around it.
19
+ export function withLocalTurnWaitInstructions(base, role) {
20
+ return [buildTurnWaitInstructions(role), base].filter(Boolean).join('\n\n');
21
+ }
16
22
  export function buildLocalClusterSystemPrompt(opts) {
17
23
  const localBlocks = [];
18
24
  localBlocks.push([
@@ -59,7 +65,6 @@ export const OLLAMA_PRIMARY_SYSTEM_PROMPT = [
59
65
  'When the operator asks about the project, start by exploring (Glob the top-level files, Read the README or CLAUDE.md, Grep for relevant terms) before answering. When they ask about something specific, go straight to the file.',
60
66
  'Be concise. Default to plain prose. Only use headers, tables, or executive-summary formatting when the operator explicitly asks for that format.',
61
67
  'Honor the safety reminders appended to each user message: cap unknown-size shell output, no `find /` without `-maxdepth`, no unbounded scans.',
62
- '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.',
63
68
  ].join(' ');
64
69
  // llama.cpp-specific system prompt. Same baseline as Ollama plus extra
65
70
  // directives tuned for Qwen3.6's specific failure modes observed in real