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
@@ -28,6 +28,8 @@
28
28
  // (c) `additionalSpeedTiers` (e.g. 'priority'), (d) personality support.
29
29
 
30
30
  import { spawn } from 'node:child_process';
31
+ import { statSync } from 'node:fs';
32
+ import { join } from 'node:path';
31
33
  import { JsonRpcClient } from './jsonRpc.js';
32
34
  import type { InitializeResponse } from './bindings/InitializeResponse.js';
33
35
  import type { ModelListResponse } from './bindings/v2/ModelListResponse.js';
@@ -49,6 +51,16 @@ const ARCO_CLIENT_VERSION = '0.1.0';
49
51
  // reads of the same home share one entry.
50
52
  const caches = new Map<string, CodexCatalogSnapshot>();
51
53
  const inFlightByKey = new Map<string, Promise<CodexCatalogSnapshot>>();
54
+ const modelCacheStamps = new Map<string, string | null>();
55
+
56
+ // Codex refreshes this file independently, including from its own model picker.
57
+ // A new local catalog must not wait for Arco's one-hour snapshot to expire.
58
+ function modelCacheStamp(home: string): string | null {
59
+ try {
60
+ const file = statSync(join(home, 'models_cache.json'));
61
+ return `${file.mtimeMs}:${file.ctimeMs}:${file.size}:${file.ino}`;
62
+ } catch { return null; }
63
+ }
52
64
 
53
65
  function cacheKey(codexHome?: string): string {
54
66
  return resolveCodexHome(codexHome);
@@ -97,13 +109,14 @@ export async function getCodexCatalog(force = false, codexHome?: string): Promis
97
109
  const key = cacheKey(codexHome);
98
110
  const now = Date.now();
99
111
  const cache = caches.get(key) ?? null;
100
- if (!force && cache && now - cache.fetchedAt < REFRESH_INTERVAL_MS) return cache;
112
+ if (!force && cache && now - cache.fetchedAt < REFRESH_INTERVAL_MS && modelCacheStamps.get(key) === modelCacheStamp(key)) return cache;
101
113
  const existing = inFlightByKey.get(key);
102
114
  if (existing) return existing;
103
115
  const p = (async () => {
104
116
  try {
105
117
  const fresh = await fetchCodexCatalog(codexHome);
106
118
  caches.set(key, fresh);
119
+ modelCacheStamps.set(key, modelCacheStamp(key));
107
120
  return fresh;
108
121
  } catch (err) {
109
122
  if (cache) {
@@ -0,0 +1,58 @@
1
+ // docs/PROVIDERS.md - a Codex app-server turn that ends while a command the
2
+ // agent started is still running is not over for Arco. These limits bound the
3
+ // wait and the text that carries each result back to the agent.
4
+ import type { HeldCommandResult } from './lateCommands.js';
5
+
6
+ export const HELD_WAIT_LIMIT_MS = 30 * 60_000;
7
+ export const HELD_CONTINUATION_LIMIT = 20;
8
+ export const HELD_OUTPUT_CHARS = 4_000;
9
+ // Results in one message; any further results in the same batch keep their
10
+ // exit code but not their output.
11
+ export const HELD_RESULTS_WITH_OUTPUT = 8;
12
+ // Ends this close together go to the agent in one continuation.
13
+ export const HELD_BATCH_MS = 2_000;
14
+
15
+ export function formatDuration(ms: number): string {
16
+ const seconds = Math.max(0, Math.round(ms / 1000));
17
+ if (seconds < 60) return `${seconds}s`;
18
+ const minutes = Math.floor(seconds / 60);
19
+ if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
20
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
21
+ }
22
+
23
+ export function shortCommand(command: string, max = 160): string {
24
+ const flat = command.replace(/\s+/g, ' ').trim();
25
+ return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
26
+ }
27
+
28
+ function outcome(result: HeldCommandResult): string {
29
+ return typeof result.exitCode === 'number' ? `exit ${result.exitCode}` : result.failed ? 'failed' : 'ended';
30
+ }
31
+
32
+ /** The operator-visible line for one delivered result. */
33
+ export function heldResultNotice(result: HeldCommandResult, continues: boolean): string {
34
+ return `Command ended: \`${shortCommand(result.command)}\` - ${outcome(result)} after ${formatDuration(result.endedAt - result.startedAt)}.${continues ? ' Codex continues.' : ''}`;
35
+ }
36
+
37
+ /** The text Codex receives: each result once, output tail capped. */
38
+ export function heldResultsMessage(results: HeldCommandResult[], stillRunning: Array<{ command: string }>): string {
39
+ const parts = ['[Arco] A command you started has ended since your last reply. This is its result, observed by Arco; it is not from the operator.'];
40
+ results.forEach((result, index) => {
41
+ const lines = [
42
+ `Command: ${result.command}`,
43
+ ...(result.cwd ? [`Working directory: ${result.cwd}`] : []),
44
+ `Result: ${outcome(result)} after ${formatDuration(result.endedAt - result.startedAt)}`,
45
+ ];
46
+ if (index < HELD_RESULTS_WITH_OUTPUT) {
47
+ const output = result.output ?? '';
48
+ const tail = output.length > HELD_OUTPUT_CHARS ? output.slice(-HELD_OUTPUT_CHARS) : output;
49
+ lines.push(output.length > HELD_OUTPUT_CHARS
50
+ ? `Output (last ${HELD_OUTPUT_CHARS} of ${output.length} characters):\n${tail}`
51
+ : `Output:\n${tail || '(none)'}`);
52
+ } else lines.push('Output: not included; too many results in one message.');
53
+ parts.push(lines.join('\n'));
54
+ });
55
+ if (stillRunning.length) parts.push(`Still running: ${stillRunning.map(item => shortCommand(item.command)).join('; ')}. Arco tells you when ${stillRunning.length === 1 ? 'it ends' : 'they end'}.`);
56
+ parts.push('Continue the work.');
57
+ return parts.join('\n\n');
58
+ }
@@ -12,12 +12,17 @@ import { providerSessionScope } from '../sessionScope.js';
12
12
  // to tear down the long-lived child when the operator closes the tab.
13
13
 
14
14
  import { EventEmitter } from 'events';
15
- import type { WorkerConfig, WorkerStatus } from '@arco/shared';
15
+ import type { PrimaryToolUseMessage, WorkerConfig, WorkerStatus } from '@arco/shared';
16
16
  import type { Provider, ProviderProcess } from '../types.js';
17
17
  import { CodexAppServerWorker, computeMcpSignature, bootstrapSurfaceKey, type ToolUseEvent, type PrimaryArtifactEvent, type TurnSettleData } from './worker.js';
18
18
  import { codexContextWindowOverride } from '../codexContextWindow.js';
19
19
  import { allowVoiceTools, blockVoiceTools, observeVoiceTools } from '../../voice/operatorTools.js';
20
20
  import { ComputerTurnWatchdog } from '../../voice/turnWatchdog.js';
21
+ import type { SteerItem } from '@arco/shared';
22
+ import {
23
+ HELD_BATCH_MS, HELD_CONTINUATION_LIMIT, HELD_WAIT_LIMIT_MS,
24
+ formatDuration, heldResultNotice, heldResultsMessage, shortCommand,
25
+ } from './heldCommands.js';
21
26
 
22
27
  const workersByWorkflow = new Map<string, CodexAppServerWorker>();
23
28
  const compactReservations = new Map<string, CodexAppServerWorker>();
@@ -70,7 +75,7 @@ function resetFailureCount(workflowId: string): void {
70
75
 
71
76
  // One operator turn against the long-lived worker. ProviderProcess shape
72
77
  // preserved so WorkerManager / seedWorker can stay unchanged.
73
- class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
78
+ export class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
74
79
  readonly id: string;
75
80
  private _status: WorkerStatus = 'spawning';
76
81
  private _output = '';
@@ -86,6 +91,24 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
86
91
  private watchdog?: ComputerTurnWatchdog;
87
92
  private stopToolObserver?: () => void;
88
93
  private timeoutReason?: string;
94
+ // docs/PROVIDERS.md - the Arco turn stays open while a command the agent
95
+ // started is still running after its Codex turn completed. Each Codex turn
96
+ // inside it adds its cost; the result is reported once, at the end.
97
+ private readonly startedAt = Date.now();
98
+ private costUsd = 0;
99
+ private lastResult?: TurnSettleData;
100
+ private continuations = 0;
101
+ private waitedMs = 0;
102
+ private waitStartedAt = 0;
103
+ private waitTimer?: NodeJS.Timeout;
104
+ private inputTimer?: NodeJS.Timeout;
105
+ private batchTimer?: NodeJS.Timeout;
106
+ private resultSteer?: Promise<void>;
107
+ // STOP: nothing continues, and no later result restarts the turn.
108
+ private stopped = false;
109
+ // Interrupt & send: the wait ends, but the commands stay held so the
110
+ // operator's next turn receives their results.
111
+ private interrupting = false;
89
112
 
90
113
  constructor(
91
114
  id: string,
@@ -168,11 +191,17 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
168
191
  }
169
192
 
170
193
  async interrupt(): Promise<void> {
171
- if (!this.settled) await this.worker.cancelCurrentTurn();
194
+ if (this.settled) return;
195
+ this.interrupting = true;
196
+ this.stopWaitClock();
197
+ await this.worker.cancelCurrentTurn();
172
198
  }
173
199
 
174
200
  kill(): void {
175
201
  if (this.settled) return;
202
+ this.stopped = true;
203
+ this.stopWaitClock();
204
+ this.worker.abandonHeldCommands();
176
205
  // Async; the wrapper's `error` event fires when `turn_settled` lands.
177
206
  void this.worker.cancelCurrentTurn().catch((err: unknown) => {
178
207
  if (this.settled) return;
@@ -221,26 +250,26 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
221
250
  this.fail('turn settled with no result');
222
251
  return;
223
252
  }
224
- this.settled = true;
225
- this._status = 'completed';
226
- this.unwire();
227
253
  // Successful turn — the spawn-failure circuit breaker resets so any
228
254
  // earlier intermittent crashes stop counting toward the 3-strike cap.
229
255
  resetFailureCount(this.workflowId);
230
- this.emit('result', {
231
- text: this._output.length >= r.text.length ? this._output : r.text,
232
- costUsd: r.costUsd,
233
- durationMs: r.durationMs,
234
- ...(r.usage ? { usage: r.usage } : {}),
235
- ...(typeof r.modelContextWindow === 'number' ? { modelContextWindow: r.modelContextWindow } : {}),
236
- ...(typeof r.freshContextWindow === 'number' ? { freshContextWindow: r.freshContextWindow } : {}),
237
- ...(typeof r.lastPromptTokens === 'number' ? { lastPromptTokens: r.lastPromptTokens } : {}),
238
- // docs/PROVIDERS.md - Codex doesn't expose tool_result bytes
239
- // through the app-server JSON-RPC surface. Sentinel: -1 = unknown.
240
- thinkingBytes: 0,
241
- toolResultBytes: -1,
242
- toolResultBytesRaw: -1,
243
- });
256
+ this.costUsd += r.costUsd ?? 0;
257
+ this.lastResult = r;
258
+ void this.afterCodexTurn();
259
+ };
260
+ const onHeldCommands = () => {
261
+ if (this.settled || this.stopped) return;
262
+ if (this.waitStartedAt) {
263
+ // Ends that arrive close together go to the agent in one turn.
264
+ if (!this.batchTimer) this.batchTimer = setTimeout(() => { this.batchTimer = undefined; this.reviewWait(); }, HELD_BATCH_MS);
265
+ return;
266
+ }
267
+ // A result that arrives while the final answer is being written waits
268
+ // for the turn to complete and continues it, so it is never lost.
269
+ if (this.worker.hasHeldResults() && !this.resultSteer && !this.lastResult && this.worker.acceptsResultSteer) {
270
+ // A Codex turn is running: the result goes into it, never a second turn.
271
+ this.resultSteer = this.steerResults().finally(() => { this.resultSteer = undefined; });
272
+ }
244
273
  };
245
274
  const onFatal = (reason: string) => {
246
275
  if (this.settled) return;
@@ -258,6 +287,7 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
258
287
  this.worker.on('system_notice', onSystemNotice);
259
288
  this.worker.on('turn_settled', onSettled);
260
289
  this.worker.on('fatal', onFatal);
290
+ this.worker.on('held_commands', onHeldCommands);
261
291
 
262
292
  this.wired.push(
263
293
  { event: 'init', fn: onInit as (...args: unknown[]) => void },
@@ -268,6 +298,7 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
268
298
  { event: 'system_notice', fn: onSystemNotice as (...args: unknown[]) => void },
269
299
  { event: 'turn_settled', fn: onSettled as (...args: unknown[]) => void },
270
300
  { event: 'fatal', fn: onFatal as (...args: unknown[]) => void },
301
+ { event: 'held_commands', fn: onHeldCommands as (...args: unknown[]) => void },
271
302
  );
272
303
 
273
304
  // Phase 6a unused but harmless — silences "WorkerConfig.appendSystemPrompt
@@ -277,6 +308,7 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
277
308
  }
278
309
 
279
310
  private unwire(): void {
311
+ this.stopWaitClock();
280
312
  this.watchdog?.stop(); this.watchdog = undefined;
281
313
  this.stopToolObserver?.(); this.stopToolObserver = undefined;
282
314
  for (const { event, fn } of this.wired) {
@@ -290,8 +322,157 @@ class CodexAppServerTurn extends EventEmitter implements ProviderProcess {
290
322
  this.settled = true;
291
323
  this._status = 'failed';
292
324
  this.unwire();
325
+ // After Interrupt & send the operator's message runs next and takes the
326
+ // results; any other failure leaves nobody to deliver them to.
327
+ if (!this.interrupting) this.worker.abandonHeldCommands();
293
328
  this.emit('error', reason);
294
329
  }
330
+
331
+ // ── Waiting on commands the agent started ───────────────────────────
332
+
333
+ private async afterCodexTurn(): Promise<void> {
334
+ // A result steer still in flight either landed in the turn that just
335
+ // ended or comes back to the queue of results; wait to know which.
336
+ if (this.resultSteer) await this.resultSteer;
337
+ if (this.settled) return;
338
+ const running = this.worker.heldCommands;
339
+ const ready = this.worker.hasHeldResults();
340
+ if (this.stopped || (!ready && running.length === 0)) return this.finish();
341
+ if (this.continuations >= HELD_CONTINUATION_LIMIT) {
342
+ return this.giveUp(`Arco stopped continuing Codex after ${HELD_CONTINUATION_LIMIT} command results in this turn.`);
343
+ }
344
+ if (ready && (running.length === 0 || this.worker.hasFailedHeldResult())) return this.continueWith([]);
345
+ this.startWait();
346
+ }
347
+
348
+ private startWait(): void {
349
+ const remaining = HELD_WAIT_LIMIT_MS - this.waitedMs;
350
+ if (remaining <= 0) return this.giveUp(`Arco stopped waiting after ${formatDuration(HELD_WAIT_LIMIT_MS)} in this turn.`);
351
+ this.waitStartedAt = Date.now();
352
+ this.worker.showHeldUntil(this.waitStartedAt + remaining);
353
+ this.waitTimer = setTimeout(() => {
354
+ this.stopWaitClock();
355
+ this.giveUp(`Arco stopped waiting after ${formatDuration(HELD_WAIT_LIMIT_MS)} in this turn.`);
356
+ }, remaining);
357
+ this.waitTimer.unref?.();
358
+ this.inputTimer = setInterval(() => this.checkInput(), 500);
359
+ this.inputTimer.unref?.();
360
+ }
361
+
362
+ private stopWaitClock(): void {
363
+ if (this.waitStartedAt) {
364
+ this.waitedMs += Date.now() - this.waitStartedAt;
365
+ this.worker.releaseHeldWait();
366
+ }
367
+ this.waitStartedAt = 0;
368
+ clearTimeout(this.waitTimer); this.waitTimer = undefined;
369
+ clearInterval(this.inputTimer); this.inputTimer = undefined;
370
+ clearTimeout(this.batchTimer); this.batchTimer = undefined;
371
+ }
372
+
373
+ private reviewWait(): void {
374
+ if (this.settled || !this.waitStartedAt) return;
375
+ const running = this.worker.heldCommands;
376
+ const ready = this.worker.hasHeldResults();
377
+ if (ready && (running.length === 0 || this.worker.hasFailedHeldResult())) {
378
+ this.stopWaitClock();
379
+ this.continueWith([]);
380
+ } else if (!ready && running.length === 0) {
381
+ // Codex lost the commands (connection or thread closed); the lost
382
+ // line has already been shown.
383
+ this.stopWaitClock();
384
+ this.finish();
385
+ }
386
+ }
387
+
388
+ // Direct operator input or an explicit nudge ends the wait. A steer goes
389
+ // to the agent at once; a follow-up waits for the turn to end, so the
390
+ // turn ends here and the follow-up turn takes over the held commands.
391
+ private checkInput(): void {
392
+ if (this.settled || !this.waitStartedAt) return;
393
+ const pending = this.config.pendingInput?.();
394
+ if (!pending) return;
395
+ const peeked = this.config.peekSteer?.() ?? [];
396
+ if (pending === 'follow-up' || peeked.some(item => item.attachments?.length)) {
397
+ this.stopWaitClock();
398
+ this.emit('system_notice', `Stopped waiting for ${this.runningLabel()}: your message is next. Arco still passes the result on when it ends.`);
399
+ return this.finish();
400
+ }
401
+ const items = this.config.drainSteer?.() ?? [];
402
+ if (!items.length) return;
403
+ this.stopWaitClock();
404
+ this.continueWith(items);
405
+ }
406
+
407
+ private continueWith(items: SteerItem[]): void {
408
+ this.continuations += 1;
409
+ const results = this.worker.takeHeldResults();
410
+ const running = this.worker.heldCommands;
411
+ for (const result of results) this.emit('system_notice', heldResultNotice(result, true));
412
+ const message = [
413
+ ...(results.length ? [heldResultsMessage(results, running)] : []),
414
+ ...items.map(item => item.content),
415
+ ...(!results.length && running.length ? [`[Arco] Still running: ${running.map(item => shortCommand(item.command)).join('; ')}. Arco tells you when it ends.`] : []),
416
+ ].join('\n\n');
417
+ this._output += this._output ? '\n\n' : '';
418
+ this.lastResult = undefined;
419
+ this.worker.beginTurn(message, undefined, { continuation: true })
420
+ .then(() => {
421
+ if (items.length) this.config.onSteerDelivered?.(items);
422
+ if (this.settled) void this.worker.cancelCurrentTurn().catch(() => {});
423
+ })
424
+ .catch((err: unknown) => {
425
+ if (this.settled) return;
426
+ this.worker.restoreHeldResults(results);
427
+ if (items.length) this.config.requeueSteer?.(items, 'follow-up');
428
+ this.fail(err instanceof Error ? err.message : String(err));
429
+ });
430
+ }
431
+
432
+ private async steerResults(): Promise<void> {
433
+ const results = this.worker.takeHeldResults();
434
+ if (!results.length) return;
435
+ const delivered = await this.worker.steerText(heldResultsMessage(results, this.worker.heldCommands));
436
+ if (!delivered) { this.worker.restoreHeldResults(results); return; }
437
+ for (const result of results) this.emit('system_notice', heldResultNotice(result, false));
438
+ }
439
+
440
+ private runningLabel(): string {
441
+ const running = this.worker.heldCommands;
442
+ return running.length ? running.map(item => `\`${shortCommand(item.command)}\``).join(', ') : 'the command';
443
+ }
444
+
445
+ private giveUp(line: string): void {
446
+ const running = this.worker.heldCommands;
447
+ this.worker.abandonHeldCommands();
448
+ this.emit('system_notice', running.length
449
+ ? `${line} Still running: ${running.map(item => `\`${shortCommand(item.command)}\``).join(', ')}. Its row records how it ends.`
450
+ : line);
451
+ this.finish();
452
+ }
453
+
454
+ private finish(): void {
455
+ if (this.settled) return;
456
+ const r = this.lastResult;
457
+ if (!r) { this.fail('turn settled with no result'); return; }
458
+ this.settled = true;
459
+ this._status = 'completed';
460
+ this.unwire();
461
+ this.emit('result', {
462
+ text: this._output.length >= r.text.length ? this._output : r.text,
463
+ costUsd: this.costUsd,
464
+ durationMs: Math.max(r.durationMs ?? 0, Date.now() - this.startedAt),
465
+ ...(r.usage ? { usage: r.usage } : {}),
466
+ ...(typeof r.modelContextWindow === 'number' ? { modelContextWindow: r.modelContextWindow } : {}),
467
+ ...(typeof r.freshContextWindow === 'number' ? { freshContextWindow: r.freshContextWindow } : {}),
468
+ ...(typeof r.lastPromptTokens === 'number' ? { lastPromptTokens: r.lastPromptTokens } : {}),
469
+ // docs/PROVIDERS.md - Codex doesn't expose tool_result bytes
470
+ // through the app-server JSON-RPC surface. Sentinel: -1 = unknown.
471
+ thinkingBytes: 0,
472
+ toolResultBytes: -1,
473
+ toolResultBytesRaw: -1,
474
+ });
475
+ }
295
476
  }
296
477
 
297
478
  // Long-lived worker accessor. Creates lazily on first turn for a given
@@ -335,6 +516,23 @@ function acquireWorker(
335
516
  }
336
517
  const fresh = new CodexAppServerWorker(workflowId, config, resumeSessionId);
337
518
  workersByWorkflow.set(workflowId, fresh);
519
+ fresh.on('late_command', (event: ToolUseEvent, lateCommand: PrimaryToolUseMessage['lateCommand']) => {
520
+ void import('../../server/broadcast.js').then(({ broadcastWorkflow }) => {
521
+ const { name: tool, ...entry } = event;
522
+ broadcastWorkflow(workflowId, {
523
+ ...entry, type: 'primary_tool_use', workflowId, tool, lateCommand,
524
+ ...(lateCommand?.state === 'finished' ? {} : { status: 'in_progress' }),
525
+ });
526
+ if (lateCommand?.state === 'lost') {
527
+ let command = 'A command';
528
+ try { command = JSON.parse(event.input).command || command; } catch { /* use the fallback */ }
529
+ broadcastWorkflow(workflowId, {
530
+ type: 'system_notice', workflowId,
531
+ content: `Codex lost the result for ${command.slice(0, 240)} when its connection closed.`,
532
+ });
533
+ }
534
+ }).catch(error => console.warn('[arco] could not record a late Codex command result', error));
535
+ });
338
536
  fresh.on('fatal', (reason: string) => {
339
537
  // Drop the cache entry so the next operator turn re-spawns. Don't
340
538
  // dispose() — the entry is already torn down by `onChildDeath`.
@@ -350,6 +548,10 @@ function acquireWorker(
350
548
  return fresh;
351
549
  }
352
550
 
551
+ export function runningCodexLateCommands(workflowId: string) {
552
+ return workersByWorkflow.get(workflowId)?.runningLateCommands ?? [];
553
+ }
554
+
353
555
  // Operator-triggered native compaction against the long-lived per-workflow
354
556
  // thread (the app-server equivalent of `/compact` in Codex CLI). Out-of-band
355
557
  // vs. the per-turn CodexAppServerTurn wrapper — it talks straight to the
@@ -0,0 +1,225 @@
1
+ import type { CodexLateCommand, PrimaryToolUseMessage } from '@arco/shared';
2
+ import type { ToolUseEvent } from './worker.js';
3
+
4
+ const DISPLAY_MS = 5 * 60_000;
5
+ const MAX_COMMANDS = 64;
6
+
7
+ // A program meant to keep running (a server or a watcher) must never hold a
8
+ // turn open. Programs the shell put in the background (`&`, `nohup`) end the
9
+ // shell at once, so Codex completes their item inside the turn; only a known
10
+ // long-running program started in the foreground needs this pattern. Kept
11
+ // narrower than the preview detector's pattern: `vite build` or `deno run
12
+ // script.ts` end on their own and must still be waited on.
13
+ const LONG_RUNNING_RE = new RegExp([
14
+ String.raw`\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve|watch)\b`,
15
+ String.raw`\b(?:vite|next|astro|nuxt|remix|gatsby|docusaurus)\s+(?:dev|develop|start|serve|preview)\b`,
16
+ String.raw`\bvite\s*(?:$|['"]|--(?:host|port)\b)`,
17
+ String.raw`\bpython3?\s+-m\s+http\.server\b`,
18
+ String.raw`\buvicorn\b`, String.raw`\bflask\s+run\b`, String.raw`\brails\s+s(?:erver)?\b`, String.raw`\bphp\s+-S\b`,
19
+ String.raw`(?:^|\s)--watch\b`, String.raw`\bwatch\s+-n\b`, String.raw`\btail\s+(?:-\w+\s+)*-\w*[fF]\b`,
20
+ String.raw`\bsleep\s+infinity\b`,
21
+ String.raw`\bdocker[\s-]compose\s+(?:\S+\s+)*up\b(?![^|;&]*\s(?:-d|--detach)\b)`,
22
+ ].join('|'));
23
+
24
+ export function isLongRunningProgram(command: string): boolean {
25
+ return LONG_RUNNING_RE.test(command);
26
+ }
27
+
28
+ export interface HeldCommandResult {
29
+ itemId: string;
30
+ command: string;
31
+ cwd?: string;
32
+ startedAt: number;
33
+ endedAt: number;
34
+ exitCode?: number;
35
+ output?: string;
36
+ failed: boolean;
37
+ }
38
+
39
+ interface Command {
40
+ turnId: string;
41
+ startedAt: number;
42
+ event: ToolUseEvent;
43
+ waitingUntil?: number;
44
+ timer?: NodeJS.Timeout;
45
+ // The agent waits on this command: its result is delivered to the agent
46
+ // once, by the wrapper of the Arco turn that holds it.
47
+ held?: boolean;
48
+ // The Arco turn is open right now only because of this command.
49
+ waiting?: boolean;
50
+ }
51
+
52
+ export function commandText(event: Pick<ToolUseEvent, 'input'>): { command: string; cwd?: string } {
53
+ try {
54
+ const parsed = JSON.parse(event.input) as { command?: unknown; cwd?: unknown };
55
+ return {
56
+ command: typeof parsed.command === 'string' ? parsed.command : 'a shell command',
57
+ ...(typeof parsed.cwd === 'string' ? { cwd: parsed.cwd } : {}),
58
+ };
59
+ } catch { return { command: 'a shell command' }; }
60
+ }
61
+
62
+ export class CodexLateCommands {
63
+ private readonly commands = new Map<string, Command>();
64
+ // Ended held commands whose result has not yet been delivered to the agent.
65
+ private readonly results: HeldCommandResult[] = [];
66
+
67
+ constructor(
68
+ private readonly publish: (event: ToolUseEvent, state: NonNullable<PrimaryToolUseMessage['lateCommand']>) => void,
69
+ private readonly onHeldChange: () => void = () => {},
70
+ ) {}
71
+
72
+ start(turnId: string, event: ToolUseEvent): void {
73
+ if (!event.itemId || this.commands.has(event.itemId)) return;
74
+ if (this.commands.size >= MAX_COMMANDS) {
75
+ const oldest = this.commands.keys().next().value;
76
+ if (oldest) {
77
+ const previous = this.commands.get(oldest)!;
78
+ if (previous.waitingUntil) this.notify(previous, 'untracked');
79
+ clearTimeout(previous.timer);
80
+ this.commands.delete(oldest);
81
+ if (previous.held) this.onHeldChange();
82
+ }
83
+ }
84
+ this.commands.set(event.itemId, { turnId, event, startedAt: Date.now() });
85
+ }
86
+
87
+ /** True once the long-lived publisher owns this completion. */
88
+ complete(turnId: string, event: ToolUseEvent): boolean {
89
+ const id = event.itemId;
90
+ const command = id ? this.commands.get(id) : undefined;
91
+ if (!id || !command || command.turnId !== turnId) return false;
92
+ this.commands.delete(id);
93
+ clearTimeout(command.timer);
94
+ if (!command.waitingUntil) return false;
95
+ this.notify(command, 'finished', event);
96
+ if (command.held) {
97
+ this.results.push(this.result(command, event));
98
+ this.onHeldChange();
99
+ }
100
+ return true;
101
+ }
102
+
103
+ /**
104
+ * A command that ended inside its own turn after the agent's final answer
105
+ * had started: the model never saw the result, so it is kept for delivery
106
+ * once that turn has completed. The completion is still shown in the turn.
107
+ * False when the command is unknown, belongs to another turn or has
108
+ * already outlived its turn.
109
+ */
110
+ completeUnseen(turnId: string, event: ToolUseEvent): boolean {
111
+ const id = event.itemId;
112
+ const command = id ? this.commands.get(id) : undefined;
113
+ if (!id || !command || command.turnId !== turnId || command.waitingUntil) return false;
114
+ this.commands.delete(id);
115
+ clearTimeout(command.timer);
116
+ if (!isLongRunningProgram(commandText(command.event).command)) {
117
+ this.results.push(this.result(command, event));
118
+ this.onHeldChange();
119
+ }
120
+ return true;
121
+ }
122
+
123
+ settle(turnId: string): void {
124
+ let held = false;
125
+ for (const command of this.commands.values()) {
126
+ if (command.turnId !== turnId || command.waitingUntil) continue;
127
+ command.waitingUntil = Date.now() + DISPLAY_MS;
128
+ command.held = !isLongRunningProgram(commandText(command.event).command);
129
+ held ||= command.held;
130
+ this.notify(command, 'running');
131
+ command.timer = setTimeout(() => this.notify(command, 'untracked'), DISPLAY_MS);
132
+ command.timer.unref();
133
+ }
134
+ if (held) this.onHeldChange();
135
+ }
136
+
137
+ /** Commands the agent still waits on, oldest first. */
138
+ running(): Array<{ itemId: string; command: string; startedAt: number }> {
139
+ return [...this.commands.values()].flatMap(command => command.held && command.event.itemId
140
+ ? [{ itemId: command.event.itemId, command: commandText(command.event).command, startedAt: command.startedAt }] : []);
141
+ }
142
+
143
+ hasResults(): boolean { return this.results.length > 0; }
144
+
145
+ hasFailedResult(): boolean { return this.results.some(result => result.failed); }
146
+
147
+ /** Ended results; each is handed out exactly once. */
148
+ takeResults(): HeldCommandResult[] { return this.results.splice(0); }
149
+
150
+ /** Put back results whose delivery failed, ahead of any newer ones. */
151
+ restoreResults(results: HeldCommandResult[]): void {
152
+ if (results.length) this.results.unshift(...results);
153
+ }
154
+
155
+ /** The Arco turn now waits on the held commands, at most until `until`. */
156
+ hold(until: number): void {
157
+ for (const command of this.commands.values()) {
158
+ if (!command.held || !command.waitingUntil) continue;
159
+ command.waiting = true;
160
+ if (command.waitingUntil < until) {
161
+ command.waitingUntil = until;
162
+ clearTimeout(command.timer);
163
+ command.timer = setTimeout(() => this.notify(command, 'untracked'), Math.max(0, until - Date.now()));
164
+ command.timer.unref();
165
+ }
166
+ this.notify(command, 'running');
167
+ }
168
+ }
169
+
170
+ /** The turn no longer waits (it continued, ended or was stopped). */
171
+ release(): void {
172
+ for (const command of this.commands.values()) {
173
+ if (!command.waiting) continue;
174
+ command.waiting = false;
175
+ this.notify(command, 'running');
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Nobody waits on these commands any more (STOP, the wait limit, a failed
181
+ * turn). They keep running and their rows still record how they end, but
182
+ * no result reaches the agent.
183
+ */
184
+ abandon(): void {
185
+ this.release();
186
+ this.results.length = 0;
187
+ for (const command of this.commands.values()) command.held = false;
188
+ }
189
+
190
+ snapshot(): CodexLateCommand[] {
191
+ const now = Date.now();
192
+ return [...this.commands.values()].flatMap(({ event, startedAt, waitingUntil, waiting }) =>
193
+ event.itemId && waitingUntil && waitingUntil > now
194
+ ? [{ itemId: event.itemId, input: event.input, startedAt, waitingUntil, ...(waiting ? { waiting } : {}) }] : []);
195
+ }
196
+
197
+ disconnect(): void {
198
+ const held = this.results.length > 0 || [...this.commands.values()].some(command => command.held);
199
+ for (const command of this.commands.values()) {
200
+ clearTimeout(command.timer);
201
+ this.notify(command, 'lost');
202
+ }
203
+ this.commands.clear();
204
+ this.results.length = 0;
205
+ if (held) this.onHeldChange();
206
+ }
207
+
208
+ private result(command: Command, event: ToolUseEvent): HeldCommandResult {
209
+ const { command: text, cwd } = commandText(command.event);
210
+ return {
211
+ itemId: command.event.itemId!, command: text, ...(cwd ? { cwd } : {}),
212
+ startedAt: command.startedAt, endedAt: Date.now(),
213
+ ...(typeof event.exitCode === 'number' ? { exitCode: event.exitCode } : {}),
214
+ ...(typeof event.output === 'string' ? { output: event.output } : {}),
215
+ failed: event.status === 'failed' || (typeof event.exitCode === 'number' && event.exitCode !== 0),
216
+ };
217
+ }
218
+
219
+ private notify(command: Command, state: NonNullable<PrimaryToolUseMessage['lateCommand']>['state'], result?: ToolUseEvent): void {
220
+ this.publish(result ?? command.event, {
221
+ state, startedAt: command.startedAt, waitingUntil: command.waitingUntil ?? Date.now(),
222
+ ...(command.waiting && state === 'running' ? { waiting: true } : {}),
223
+ });
224
+ }
225
+ }