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
@@ -15,4 +15,4 @@ export declare function loadSessionJsonl(path: string): Promise<{
15
15
  entries: SessionJsonlEntry[];
16
16
  byteLength: number;
17
17
  }>;
18
- export declare function watchSessionJsonl(path: string, initialOffset: number, onEntry: (entry: SessionJsonlEntry) => void): () => void;
18
+ export declare function watchSessionJsonl(path: string, initialOffset: number | null, onEntry: (entry: SessionJsonlEntry) => void): () => void;
@@ -1,7 +1,8 @@
1
- import { watch } from 'fs';
2
- import { readFile } from 'fs/promises';
3
- import { join, resolve } from 'path';
1
+ import { watch, statSync } from 'fs';
2
+ import { open } from 'fs/promises';
3
+ import { basename, dirname, join, resolve } from 'path';
4
4
  import { homedir } from 'os';
5
+ import { jsonlLines } from './jsonlLines.js';
5
6
  export function resolveSessionJsonlPath(cwd, sessionId) {
6
7
  // Claude's CLI encodes cwd by replacing any non-[A-Za-z0-9-] char with '-',
7
8
  // not just '/'. So `/home/operator/Projects/Sample_Project` becomes
@@ -21,30 +22,64 @@ export function resolveSubagentsWorkflowsDir(cwd, sessionId) {
21
22
  return join(homedir(), '.claude', 'projects', encoded, sessionId, 'subagents', 'workflows');
22
23
  }
23
24
  export async function loadSessionJsonl(path) {
24
- let buf;
25
+ let fh;
25
26
  try {
26
- buf = await readFile(path);
27
+ fh = await open(path, 'r');
27
28
  }
28
- catch {
29
- return { entries: [], byteLength: 0 };
29
+ catch (err) {
30
+ if (err.code === 'ENOENT')
31
+ return { entries: [], byteLength: 0 };
32
+ throw err;
30
33
  }
31
34
  const entries = [];
32
- const complete = buf.lastIndexOf(10) + 1;
33
- for (const line of buf.subarray(0, complete).toString('utf-8').split('\n')) {
34
- if (!line.trim())
35
- continue;
36
- try {
37
- const e = JSON.parse(line);
38
- if (e && typeof e.type === 'string')
39
- entries.push(e);
35
+ let complete = 0;
36
+ try {
37
+ const size = (await fh.stat()).size;
38
+ async function* chunks() {
39
+ for (let position = 0; position < size;) {
40
+ const buffer = Buffer.alloc(Math.min(64 * 1024, size - position));
41
+ const { bytesRead } = await fh.read(buffer, 0, buffer.length, position);
42
+ if (!bytesRead)
43
+ break;
44
+ const chunk = buffer.subarray(0, bytesRead);
45
+ const newline = chunk.lastIndexOf(0x0a);
46
+ if (newline >= 0)
47
+ complete = position + newline + 1;
48
+ position += bytesRead;
49
+ yield chunk;
50
+ }
40
51
  }
41
- catch { /* skip malformed lines */ }
52
+ for await (const line of jsonlLines(chunks(), path, { finalLine: false, carriageReturns: false })) {
53
+ if (!line.trim())
54
+ continue;
55
+ try {
56
+ const e = JSON.parse(line);
57
+ if (e && typeof e.type === 'string')
58
+ entries.push(e);
59
+ }
60
+ catch { /* skip malformed lines */ }
61
+ }
62
+ return { entries, byteLength: complete };
63
+ }
64
+ finally {
65
+ await fh.close();
42
66
  }
43
- return { entries, byteLength: complete };
67
+ }
68
+ async function lastCompleteOffset(fh, size) {
69
+ for (let end = size; end > 0;) {
70
+ const start = Math.max(0, end - 64 * 1024), buffer = Buffer.alloc(end - start);
71
+ const { bytesRead } = await fh.read(buffer, 0, buffer.length, start);
72
+ const newline = buffer.subarray(0, bytesRead).lastIndexOf(0x0a);
73
+ if (newline >= 0)
74
+ return start + newline + 1;
75
+ end = start;
76
+ }
77
+ return 0;
44
78
  }
45
79
  // Tail the session JSONL for new entries, emitting each one via `onEntry`.
46
80
  // `initialOffset` should be the byteLength from loadSessionJsonl so we
47
- // don't re-emit history. Returns a dispose function.
81
+ // don't re-emit history. Null anchors at the first readable complete boundary
82
+ // after initial loading failed. Returns a dispose function.
48
83
  export function watchSessionJsonl(path, initialOffset, onEntry) {
49
84
  let lastOffset = initialOffset;
50
85
  let active = true;
@@ -52,6 +87,12 @@ export function watchSessionJsonl(path, initialOffset, onEntry) {
52
87
  let restartTimer = null;
53
88
  let reading = false;
54
89
  let requested = false;
90
+ let identity;
91
+ try {
92
+ const st = statSync(path);
93
+ identity = `${st.dev}:${st.ino}`;
94
+ }
95
+ catch { /* not created yet */ }
55
96
  const readNew = async () => {
56
97
  if (!active)
57
98
  return;
@@ -63,30 +104,59 @@ export function watchSessionJsonl(path, initialOffset, onEntry) {
63
104
  while (active && requested) {
64
105
  requested = false;
65
106
  try {
66
- const buf = await readFile(path);
67
- if (!active)
68
- return;
69
- if (buf.length < lastOffset)
70
- lastOffset = 0;
71
- const end = buf.lastIndexOf(10) + 1;
72
- if (end <= lastOffset)
73
- continue;
74
- const slice = buf.subarray(lastOffset, end).toString('utf-8');
75
- lastOffset = end;
76
- for (const line of slice.split('\n')) {
107
+ const fh = await open(path, 'r');
108
+ try {
77
109
  if (!active)
78
110
  return;
79
- if (!line.trim())
80
- continue;
81
- let e;
82
- try {
83
- e = JSON.parse(line);
111
+ const st = await fh.stat();
112
+ const nextIdentity = `${st.dev}:${st.ino}`;
113
+ // After an initial-load failure, anchor to the first readable
114
+ // complete boundary. Old terminal rows must not look like new
115
+ // concurrent-session writes; an unfinished last row stays pending.
116
+ if (lastOffset === null) {
117
+ lastOffset = await lastCompleteOffset(fh, st.size);
118
+ identity = nextIdentity;
84
119
  }
85
- catch {
86
- continue;
120
+ if ((identity !== undefined && identity !== nextIdentity) || st.size < lastOffset)
121
+ lastOffset = 0;
122
+ identity = nextIdentity;
123
+ const startOffset = lastOffset;
124
+ let completeOffset = startOffset;
125
+ // Read only the appended range. An unfinished record is left at
126
+ // lastOffset and completed by the next notification, as before.
127
+ async function* chunks() {
128
+ for (let position = startOffset; active && position < st.size;) {
129
+ const buffer = Buffer.alloc(Math.min(64 * 1024, st.size - position));
130
+ const { bytesRead } = await fh.read(buffer, 0, buffer.length, position);
131
+ if (!bytesRead)
132
+ break;
133
+ const chunk = buffer.subarray(0, bytesRead);
134
+ const newline = chunk.lastIndexOf(0x0a);
135
+ if (newline >= 0)
136
+ completeOffset = position + newline + 1;
137
+ position += bytesRead;
138
+ yield chunk;
139
+ }
87
140
  }
88
- if (e && typeof e.type === 'string')
89
- onEntry(e);
141
+ for await (const line of jsonlLines(chunks(), path, { finalLine: false, carriageReturns: false })) {
142
+ if (!active)
143
+ return;
144
+ if (!line.trim())
145
+ continue;
146
+ let e;
147
+ try {
148
+ e = JSON.parse(line);
149
+ }
150
+ catch {
151
+ continue;
152
+ }
153
+ if (e && typeof e.type === 'string')
154
+ onEntry(e);
155
+ }
156
+ lastOffset = completeOffset;
157
+ }
158
+ finally {
159
+ await fh.close();
90
160
  }
91
161
  }
92
162
  catch { /* file unavailable; retry at the next notification */ }
@@ -112,7 +182,12 @@ export function watchSessionJsonl(path, initialOffset, onEntry) {
112
182
  if (!active || watcher)
113
183
  return;
114
184
  try {
115
- watcher = watch(path, { persistent: false }, () => { void readNew(); });
185
+ // Watching the directory survives replacement of the session file;
186
+ // an inode-bound watcher would keep watching the removed file.
187
+ watcher = watch(dirname(path), { persistent: false }, (_event, name) => {
188
+ if (name === null || name === basename(path))
189
+ void readNew();
190
+ });
116
191
  void readNew();
117
192
  watcher.on('error', () => {
118
193
  watcher = null;
@@ -120,7 +195,7 @@ export function watchSessionJsonl(path, initialOffset, onEntry) {
120
195
  });
121
196
  }
122
197
  catch {
123
- // File not yet created — retry after 2s (happens for brand-new sessions)
198
+ // Session directory not yet created — retry after 2s (happens for brand-new sessions)
124
199
  scheduleRestart();
125
200
  }
126
201
  };
@@ -215,6 +215,19 @@ export function claudeAdapter(opts = {}) {
215
215
  },
216
216
  };
217
217
  }
218
+ // A terminating child can still hold its cwd open on Windows. Allow up to
219
+ // 250 ms for exit, then at most 600 ms of removal retries. Cleanup must never
220
+ // change the evaluator's answer or refusal.
221
+ async function removeEvaluatorFolder(proc, cwd) {
222
+ if (proc.pid && proc.exitCode === null && proc.signalCode === null) {
223
+ await new Promise((resolve) => {
224
+ const done = () => { clearTimeout(timer); proc.off('close', done); resolve(); };
225
+ const timer = setTimeout(done, 250);
226
+ proc.once('close', done);
227
+ });
228
+ }
229
+ await rm(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch(() => undefined);
230
+ }
218
231
  export function cursorAdapter(opts = {}) {
219
232
  // `cursor-agent acp` ignores `--model`; the model is selected over ACP after
220
233
  // session/new and confirmed, and the evaluator refuses rather than answer
@@ -357,7 +370,7 @@ export function cursorAdapter(opts = {}) {
357
370
  clearTimeout(timer);
358
371
  req.signal?.removeEventListener('abort', onAbort);
359
372
  stop();
360
- await rm(cwd, { recursive: true, force: true }).catch(() => undefined);
373
+ await removeEvaluatorFolder(proc, cwd);
361
374
  }
362
375
  },
363
376
  };
@@ -504,7 +517,7 @@ export function codexAdapter(opts = {}) {
504
517
  clearTimeout(timer);
505
518
  req.signal?.removeEventListener('abort', onAbort);
506
519
  stop();
507
- await rm(cwd, { recursive: true, force: true }).catch(() => undefined);
520
+ await removeEvaluatorFolder(proc, cwd);
508
521
  }
509
522
  },
510
523
  };
@@ -0,0 +1,34 @@
1
+ export declare const TRANSCRIPT_WORKER_MAX_BYTES: number;
2
+ export declare const TRANSCRIPT_WORKER_PREFACE_BYTES: number;
3
+ export interface TranscriptSliceOptions {
4
+ turns: number;
5
+ includePartial: boolean;
6
+ preface: string;
7
+ cutoffSeq?: number;
8
+ wasBusy: boolean;
9
+ }
10
+ export declare function buildTranscriptWorkerSlice(cwd: string, workflowId: string, options: TranscriptSliceOptions): Promise<{
11
+ seed: string;
12
+ bytes: number;
13
+ availableTurns: number;
14
+ selectedTurns: number;
15
+ partialIncluded: boolean;
16
+ cutoffSeq: number;
17
+ digest: string;
18
+ branchKey: string;
19
+ }>;
20
+ export interface TranscriptSelectionPolicy {
21
+ maxBytes: number;
22
+ fitWholeTurns: boolean;
23
+ allTurns?: boolean;
24
+ }
25
+ export declare function buildTranscriptSlice(cwd: string, workflowId: string, options: TranscriptSliceOptions, policy?: TranscriptSelectionPolicy): Promise<{
26
+ seed: string;
27
+ bytes: number;
28
+ availableTurns: number;
29
+ selectedTurns: number;
30
+ partialIncluded: boolean;
31
+ cutoffSeq: number;
32
+ digest: string;
33
+ branchKey: string;
34
+ }>;
@@ -0,0 +1,201 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { basename, extname } from 'node:path';
3
+ import { getHeadSeq, streamWorkflowEvents } from './workflowStore.js';
4
+ import { readMeta } from './workflowMeta.js';
5
+ import { walkBranchSeqs } from './providers/claude-native/resumeSummary.js';
6
+ import { TRANSCRIPT_JSON_HEADER } from './providers/renderedTranscript.js';
7
+ export const TRANSCRIPT_WORKER_MAX_BYTES = 32 * 1024;
8
+ export const TRANSCRIPT_WORKER_PREFACE_BYTES = 4 * 1024;
9
+ // The retention estimate tolerates split surrogate pairs. The final encoded
10
+ // seed is measured exactly after joining deltas; nothing is clipped to fit.
11
+ const textBytes = (text) => Buffer.byteLength(text, 'utf8');
12
+ const newTurn = (limit, count) => ({ limit, count, parts: [], bytes: 0, oversized: false, tools: new Map(), keys: [], legacy: [] });
13
+ const countBytes = (turn, delta) => { turn.bytes += delta; turn.count?.(delta); };
14
+ function add(turn, role, text, kind, merge = false) {
15
+ if (turn.oversized)
16
+ return;
17
+ let part = merge ? turn.text : undefined;
18
+ if (!part) {
19
+ part = { role, text: [], kind };
20
+ countBytes(turn, Buffer.byteLength(`${role}: ""\n`));
21
+ turn.parts.push(part);
22
+ }
23
+ part.text.push(text);
24
+ countBytes(turn, textBytes(text));
25
+ turn.text = merge ? part : undefined;
26
+ // Retain a bounded candidate ring, not every delta in a very large turn.
27
+ // Oversized selected turns are refused as a seed, never silently clipped.
28
+ if (turn.bytes > 2 * turn.limit) {
29
+ turn.oversized = true;
30
+ turn.parts = [];
31
+ turn.tools.clear();
32
+ turn.legacy = [];
33
+ turn.text = undefined;
34
+ return;
35
+ }
36
+ return part;
37
+ }
38
+ export async function buildTranscriptWorkerSlice(cwd, workflowId, options) {
39
+ return buildTranscriptSlice(cwd, workflowId, options);
40
+ }
41
+ // Both new-worker copying and member replacement use this one turn/receipt
42
+ // reader. Replacement may fit a whole-turn suffix; new-worker copying keeps
43
+ // its original refusal instead of silently reducing the requested count.
44
+ export async function buildTranscriptSlice(cwd, workflowId, options, policy) {
45
+ const maxBytes = policy?.maxBytes ?? TRANSCRIPT_WORKER_MAX_BYTES;
46
+ const fit = policy?.fitWholeTurns === true;
47
+ if (!Number.isInteger(options.turns) || options.turns < 1 || (!policy?.allTurns && options.turns > 50))
48
+ throw new Error('Choose from 1 to 50 turns.');
49
+ if (typeof options.preface !== 'string' || Buffer.byteLength(options.preface, 'utf8') > TRANSCRIPT_WORKER_PREFACE_BYTES)
50
+ throw new Error('The preface must be at most 4 KiB.');
51
+ if (typeof options.includePartial !== 'boolean')
52
+ throw new Error('Choose whether to include the current partial turn.');
53
+ const cutoffSeq = options.cutoffSeq ?? await getHeadSeq(cwd, workflowId);
54
+ const meta = await readMeta(cwd, workflowId).catch(() => null);
55
+ let branch;
56
+ if (typeof meta?.leafSeq === 'number') {
57
+ // A rewind needs ancestry, but not the old text/tool payloads. Reuse the
58
+ // established branch walk over lightweight links, then stream the slice.
59
+ const links = [];
60
+ for await (const message of streamWorkflowEvents(cwd, workflowId)) {
61
+ const event = message;
62
+ if ((event.seq ?? 0) > cutoffSeq)
63
+ break;
64
+ links.push({ type: event.type, seq: event.seq, parentEventSeq: event.parentEventSeq, targetSeq: event.targetSeq });
65
+ }
66
+ const walked = walkBranchSeqs(links, links.at(-1)?.seq ?? meta.leafSeq);
67
+ if (walked.truncated)
68
+ throw new Error('The source branch has missing ancestry. Its selected turns cannot be copied exactly.');
69
+ branch = walked.inScope;
70
+ }
71
+ const turns = [];
72
+ let retainedBytes = 0;
73
+ const dropOldest = () => {
74
+ const dropped = turns.shift();
75
+ retainedBytes -= dropped.bytes;
76
+ dropped.count = undefined;
77
+ for (const key of dropped.keys)
78
+ toolOwners.set(key, null);
79
+ };
80
+ const toolOwners = new Map();
81
+ let total = 0;
82
+ let structuralSeq = 0;
83
+ for await (const message of streamWorkflowEvents(cwd, workflowId)) {
84
+ const event = message;
85
+ try {
86
+ const seq = event.seq ?? 0;
87
+ if (event.type === 'leaf_move' || event.type === 'conversation_changed')
88
+ structuralSeq = seq;
89
+ if (seq > cutoffSeq || (branch && !branch.has(seq)))
90
+ continue;
91
+ if (event.type === 'user_message_echo') {
92
+ total++;
93
+ const turn = newTurn(maxBytes, delta => retainedBytes += delta);
94
+ turns.push(turn);
95
+ if (turns.length > options.turns + 1)
96
+ dropOldest();
97
+ add(turn, 'USER', event.content ?? '', 'text');
98
+ for (const file of event.attachments ?? []) {
99
+ add(turn, 'USER', `[Attachment: ${basename(file)}; type: ${extname(file) || 'file'}; source: ${file}; receipt only, not copied]`, 'receipt');
100
+ }
101
+ continue;
102
+ }
103
+ let turn = turns.at(-1);
104
+ if (!turn)
105
+ continue;
106
+ if (event.type === 'primary_tool_use') {
107
+ const stableKey = event.toolUseId ?? event.itemId;
108
+ if (stableKey) {
109
+ if (toolOwners.has(stableKey)) {
110
+ const owner = toolOwners.get(stableKey);
111
+ if (!owner)
112
+ continue;
113
+ turn = owner;
114
+ }
115
+ else {
116
+ toolOwners.set(stableKey, turn);
117
+ turn.keys.push(stableKey);
118
+ }
119
+ }
120
+ }
121
+ if (turn.oversized)
122
+ continue;
123
+ if (event.type === 'primary_text' && typeof event.text === 'string')
124
+ add(turn, 'AGENT', event.text, 'text', true);
125
+ else if (event.type === 'primary_complete' || event.type === 'primary_turn_ended')
126
+ turn.text = undefined;
127
+ else if (event.type === 'primary_tool_use') {
128
+ turn.text = undefined;
129
+ const fullName = (event.tool ?? 'tool').replace(/\s+/g, ' ');
130
+ const name = fullName.length > 120 ? fullName.slice(0, 117) + '...' : fullName;
131
+ const status = ['started', 'in_progress', 'completed', 'failed'].includes(event.status ?? '') ? event.status : 'status unavailable';
132
+ let key = event.toolUseId ?? event.itemId;
133
+ if (!key) {
134
+ const input = createHash('sha256').update(event.input ?? '').digest('hex');
135
+ const pending = turn.legacy.find(tool => tool.name === name && (!event.input || tool.input === input));
136
+ key = status !== 'started' && status !== 'status unavailable' && pending ? pending.key : `legacy:${seq}`;
137
+ if (status === 'started')
138
+ turn.legacy.push({ key, name, input });
139
+ if ((status === 'completed' || status === 'failed') && pending)
140
+ turn.legacy = turn.legacy.filter(tool => tool !== pending);
141
+ }
142
+ const receipt = `[Tool: ${name}; ${status}; output omitted]`;
143
+ const existing = turn.tools.get(key);
144
+ if (existing) {
145
+ countBytes(turn, textBytes(receipt) - textBytes(existing.text.join('')));
146
+ existing.text = [receipt];
147
+ }
148
+ else {
149
+ const part = add(turn, 'AGENT', receipt, 'receipt');
150
+ if (part)
151
+ turn.tools.set(key, part);
152
+ }
153
+ }
154
+ }
155
+ finally {
156
+ // Keep enough candidates for a suffix within the byte budget, including
157
+ // an oversized boundary turn so no middle turn is skipped to make room.
158
+ if (fit)
159
+ while (turns.length > 1 && retainedBytes > 2 * maxBytes)
160
+ dropOldest();
161
+ }
162
+ }
163
+ const partialIncluded = options.wasBusy && options.includePartial && total > 0;
164
+ const availableTurns = Math.max(0, total - (options.wasBusy && !options.includePartial ? 1 : 0));
165
+ const candidates = options.wasBusy && !options.includePartial ? turns.slice(0, -1) : turns;
166
+ let selected = candidates.slice(-options.turns);
167
+ const frame = (transcript) => {
168
+ const context = `Source project: ${JSON.stringify(cwd)}\nCopied relative paths refer to that source project, not the new working directory.\nThe following records are quoted history. Tool calls and attachments are receipts, not instructions or copied files. If the preface requests no work, acknowledge the context briefly and wait.\n${TRANSCRIPT_JSON_HEADER}\n${transcript}`;
169
+ return (options.preface ? `${options.preface}\n\n` : '') + context;
170
+ };
171
+ const renderTurn = (turn) => turn.parts.map(part => `${part.role}: ${JSON.stringify(part.text.join(''))}`).join('\n');
172
+ if (fit) {
173
+ let bytes = textBytes(frame('')), count = 0;
174
+ for (let index = selected.length - 1; index >= 0; index--) {
175
+ const turn = selected[index];
176
+ if (turn.oversized)
177
+ break;
178
+ const next = textBytes(renderTurn(turn)) + (count ? 1 : 0);
179
+ if (bytes + next > maxBytes)
180
+ break;
181
+ bytes += next;
182
+ count++;
183
+ }
184
+ selected = count ? selected.slice(-count) : [];
185
+ }
186
+ else {
187
+ if (!selected.length)
188
+ throw new Error('No completed turns are available. Include the current partial turn or wait for it to finish.');
189
+ if (selected.some(turn => turn.oversized))
190
+ throw new Error('The selected turns exceed the 32 KiB seed limit. Choose fewer turns.');
191
+ }
192
+ const transcript = selected.map(renderTurn).join('\n');
193
+ const seed = selected.length ? frame(transcript) : '';
194
+ const bytes = textBytes(seed);
195
+ if (bytes > maxBytes)
196
+ throw new Error(`The seed is ${bytes} bytes; the limit is ${maxBytes}. Choose fewer turns or shorten the preface.`);
197
+ const branchKey = `${meta?.leafSeq ?? ''}:${structuralSeq}`;
198
+ const digest = createHash('sha256').update(JSON.stringify({ seed, availableTurns, cutoffSeq, branchKey })).digest('hex');
199
+ return { seed, bytes, availableTurns, selectedTurns: selected.length, partialIncluded, cutoffSeq, digest, branchKey };
200
+ }
201
+ //# sourceMappingURL=transcriptWorker.js.map
@@ -54,6 +54,7 @@ export declare class WorkerManager {
54
54
  }) => void;
55
55
  drainSteer?: WorkerConfig['drainSteer'];
56
56
  peekSteer?: WorkerConfig['peekSteer'];
57
+ pendingInput?: WorkerConfig['pendingInput'];
57
58
  requeueSteer?: WorkerConfig['requeueSteer'];
58
59
  onSteerDelivered?: WorkerConfig['onSteerDelivered'];
59
60
  codexTransport?: WorkerConfig['codexTransport'];
@@ -65,6 +65,7 @@ export class WorkerManager {
65
65
  incognito: options?.incognito,
66
66
  drainSteer: options?.drainSteer,
67
67
  peekSteer: options?.peekSteer,
68
+ pendingInput: options?.pendingInput,
68
69
  requeueSteer: options?.requeueSteer,
69
70
  onSteerDelivered: options?.onSteerDelivered,
70
71
  // Phase 6 — workflowId is required for per-workflow-lifetime providers
@@ -27,9 +27,17 @@ export declare function spawnShellChild(run: ShellChildRun, options: SpawnOption
27
27
  /** Tests: the tag spawnShellChild gave a child, if any. */
28
28
  export declare function _shellTreeTagForTest(child: ChildProcess): string | undefined;
29
29
  export declare const MSYS_TREE_SWEEP: string;
30
- export declare function msysTreeSweep(bash: string, tag: string, platform?: NodeJS.Platform): Promise<number[]>;
30
+ interface MsysSweepObservation {
31
+ code: number | null;
32
+ signal: NodeJS.Signals | null;
33
+ error?: string;
34
+ stdout: string;
35
+ stderr: string;
36
+ }
37
+ export declare function msysTreeSweep(bash: string, tag: string, platform?: NodeJS.Platform, observe?: (result: MsysSweepObservation) => void): Promise<number[]>;
31
38
  /** Spawn options for such a child: its own process group on Unix, no console window on Windows. */
32
39
  export declare function shellChildSpawnOptions(platform?: NodeJS.Platform): {
33
40
  detached: boolean;
34
41
  windowsHide: true;
35
42
  };
43
+ export {};
@@ -163,9 +163,15 @@ export function _shellTreeTagForTest(child) {
163
163
  // Prints, one per line, the Windows process id (or, outside Windows, the
164
164
  // process id) of every MSYS process whose environment holds the tag. Bash
165
165
  // built-ins only, so it starts nothing per process.
166
+ // Test observations on stderr contain process IDs and readability only.
166
167
  export const MSYS_TREE_SWEEP = [
167
168
  'tag=$1',
169
+ 'if [ -n "$2" ]; then exec 3>&2; fi',
168
170
  'for d in /proc/[0-9]*; do',
171
+ ' if [ -n "$2" ]; then',
172
+ ' readable=no; [ -r "$d/environ" ] && readable=yes',
173
+ ' printf \'entry %s readable=%s\\n\' "${d#/proc/}" "$readable" >&3',
174
+ ' fi',
169
175
  ' [ -r "$d/environ" ] || continue',
170
176
  ' hit=',
171
177
  ' while IFS= read -r -d \'\' e || [ -n "$e" ]; do',
@@ -174,6 +180,7 @@ export const MSYS_TREE_SWEEP = [
174
180
  ' [ -n "$hit" ] || continue',
175
181
  ' w=',
176
182
  ' [ -r "$d/winpid" ] && read -r w < "$d/winpid"',
183
+ ' if [ -n "$2" ]; then printf \'match %s pid=%s\\n\' "${d#/proc/}" "$w" >&3; fi',
177
184
  ' printf \'%s\\n\' "${w:-${d#/proc/}}"',
178
185
  'done 2>/dev/null',
179
186
  '',
@@ -184,36 +191,45 @@ const SWEEP_TIMEOUT_MS = 5_000;
184
191
  function listMsysTree(tree) {
185
192
  return msysTreeSweep(tree.bash, tree.tag, process.platform);
186
193
  }
187
- export function msysTreeSweep(bash, tag, platform = process.platform) {
194
+ export function msysTreeSweep(bash, tag, platform = process.platform, observe) {
188
195
  return new Promise((resolve) => {
189
196
  const env = { ...process.env };
190
197
  delete env[PROCESS_TREE_ENV];
191
198
  let out = '';
199
+ let stderr = '';
192
200
  let done = false;
193
- const finish = () => {
201
+ const finish = (code, signal, error) => {
194
202
  if (done)
195
203
  return;
196
204
  done = true;
197
205
  clearTimeout(timer);
206
+ observe?.({ code, signal, error, stdout: out, stderr });
198
207
  resolve(out.split(/\r?\n/).filter((l) => /^\d+$/.test(l.trim())).map((l) => Number(l.trim())));
199
208
  };
200
- const timer = setTimeout(() => { try {
201
- sweeper?.kill();
202
- }
203
- catch { /* gone */ } finish(); }, SWEEP_TIMEOUT_MS);
209
+ const timer = setTimeout(() => {
210
+ try {
211
+ sweeper?.kill();
212
+ }
213
+ catch { /* gone */ }
214
+ finish(null, null, 'sweep timed out');
215
+ }, SWEEP_TIMEOUT_MS);
204
216
  let sweeper;
205
217
  try {
206
- const plan = shellSpawnPlan({ file: bash, args: ['-c', MSYS_TREE_SWEEP, 'arco-sweep', tag], msys: true }, { env, stdio: ['ignore', 'pipe', 'ignore'] }, platform);
218
+ const args = ['-c', MSYS_TREE_SWEEP, 'arco-sweep', tag];
219
+ if (observe)
220
+ args.push('observe');
221
+ const plan = shellSpawnPlan({ file: bash, args, msys: true }, { env, stdio: ['ignore', 'pipe', observe ? 'pipe' : 'ignore'] }, platform);
207
222
  // The sweep itself must not carry a tag, or it would list itself.
208
223
  if (plan.options.env)
209
224
  delete plan.options.env[PROCESS_TREE_ENV];
210
225
  sweeper = spawn(plan.file, plan.args, plan.options);
211
226
  sweeper.stdout?.on('data', (b) => { out += b.toString('utf8'); });
212
- sweeper.on('error', finish);
227
+ sweeper.stderr?.on('data', (b) => { stderr += b.toString('utf8'); });
228
+ sweeper.on('error', (error) => finish(null, null, error.code ?? error.name));
213
229
  sweeper.on('close', finish);
214
230
  }
215
- catch {
216
- finish();
231
+ catch (error) {
232
+ finish(null, null, error.code ?? 'sweep spawn failed');
217
233
  }
218
234
  });
219
235
  }
@@ -14,6 +14,7 @@ export declare function replayEventsWithTs(cwd: string, wfid: string, fromSeq: n
14
14
  ts: number;
15
15
  message: ServerMessage;
16
16
  }>>;
17
+ export declare function streamWorkflowEvents(cwd: string, wfid: string): AsyncGenerator<ServerMessage>;
17
18
  export declare function replayEvents(cwd: string, wfid: string, fromSeq: number): Promise<ServerMessage[]>;
18
19
  export declare function replayTailEvents(cwd: string, wfid: string, maxBytes: number): Promise<{
19
20
  events: ServerMessage[];
@@ -597,6 +597,37 @@ function withEventTs(entry) {
597
597
  const { ts, ...rest } = entry;
598
598
  return typeof ts === 'number' ? { ...rest, eventTs: ts } : rest;
599
599
  }
600
+ // Streaming consumers can retain their selected slice instead of materializing
601
+ // the whole history. Sequence repair, sealed copies and pending flushes are the
602
+ // same as the existing replay APIs.
603
+ export async function* streamWorkflowEvents(cwd, wfid) {
604
+ if (!cwd)
605
+ return;
606
+ validateWfid(wfid);
607
+ const buf = buffers.get(bufferKey(cwd, wfid));
608
+ if (buf) {
609
+ if (buf.flushTimer) {
610
+ clearTimeout(buf.flushTimer);
611
+ buf.flushTimer = null;
612
+ }
613
+ await flushBuffer(buf);
614
+ }
615
+ for await (const { line, step } of effectiveLines(workflowDir(cwd, wfid))) {
616
+ if (!step)
617
+ continue;
618
+ let entry;
619
+ try {
620
+ entry = JSON.parse(line);
621
+ }
622
+ catch {
623
+ continue;
624
+ }
625
+ if (typeof entry.seq !== 'number')
626
+ continue;
627
+ applyStep(entry, step);
628
+ yield withEventTs(entry);
629
+ }
630
+ }
600
631
  // Replay all events with seq > fromSeq, in seq order. Caller streams each
601
632
  // returned ServerMessage to the newly-connected WS (stamped seq included on
602
633
  // the wire object). Flushes pending first so the replay is head-current.