arco-workbench 0.1.6 → 0.1.8

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 (236) hide show
  1. package/CONTRIBUTING.md +52 -12
  2. package/README.md +20 -13
  3. package/client/dist/assets/{PhosphorBackdrop-BR-TgB5x.js → PhosphorBackdrop-D7jdAV_G.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-DgcFj6JN.js → ThemedBackgroundShaderImpl-DrDm60h8.js} +1 -1
  5. package/client/dist/assets/{XtermView-CflVBQgC.js → XtermView-BGFujb1e.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-BB-emfmi.js → galleryEditor-D951A2sE.js} +1 -1
  7. package/client/dist/assets/{index-B_EqHDz3.js → index-CsVy3eZm.js} +248 -248
  8. package/client/dist/index.html +1 -1
  9. package/client/src/buildCheck.ts +3 -1
  10. package/client/src/components/AppUpdateNotice.tsx +2 -1
  11. package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +24 -12
  12. package/client/src/components/ClusterRightPanel/ReplaceMemberDialog.tsx +65 -15
  13. package/client/src/components/ClusterRightPanel/SkillsControl.tsx +107 -0
  14. package/client/src/components/ClusterRightPanel/index.tsx +6 -1
  15. package/client/src/components/ClusterTaskBoardTab.tsx +9 -22
  16. package/client/src/components/HeaderVersionBox.tsx +7 -4
  17. package/client/src/components/NeedsYouBadge.tsx +3 -3
  18. package/client/src/components/ProviderReleasesModal.tsx +8 -4
  19. package/client/src/components/ProvidersPopover.tsx +28 -23
  20. package/client/src/components/SettingsPanel.tsx +2 -2
  21. package/client/src/components/SkillsSettings.tsx +5 -0
  22. package/client/src/components/TabBar.tsx +91 -9
  23. package/client/src/components/TerminalInput.tsx +12 -10
  24. package/client/src/components/TranscriptSendDialog.tsx +12 -8
  25. package/client/src/components/TranscriptWorkerDialog.tsx +119 -0
  26. package/client/src/components/UpdateAction.tsx +18 -4
  27. package/client/src/components/UpdateResultNotice.tsx +3 -1
  28. package/client/src/components/clusterNeedsYou.ts +11 -18
  29. package/client/src/help/content/cluster.tsx +54 -22
  30. package/client/src/help/content/composer.tsx +22 -0
  31. package/client/src/help/content/header.tsx +19 -1
  32. package/client/src/help/content/misc.tsx +8 -0
  33. package/client/src/help/content/rightPanel.tsx +1 -1
  34. package/client/src/help/content/settings.tsx +19 -5
  35. package/client/src/help/content/tabbar.tsx +5 -0
  36. package/client/src/help/manualSections/actions.tsx +31 -0
  37. package/client/src/help/manualSections/clusters.tsx +58 -21
  38. package/client/src/help/manualSections/configuration.tsx +38 -4
  39. package/client/src/help/manualSections/maintenance.tsx +30 -0
  40. package/client/src/help/manualSections/plans.tsx +5 -1
  41. package/client/src/help/manualSections/providers.tsx +32 -8
  42. package/client/src/help/manualSections/troubleshooting.tsx +2 -1
  43. package/client/src/help/manualSections/workflows.tsx +19 -0
  44. package/client/src/help/manualSections/workspace.tsx +6 -0
  45. package/client/src/stores/appUpdateStore.ts +29 -8
  46. package/client/src/utils/transcriptWorkerRequest.ts +24 -0
  47. package/client/src/utils/wsSession.ts +2 -1
  48. package/client/src/ws/handleServerMessage.ts +8 -2
  49. package/docs/ARCHITECTURE.md +1 -1
  50. package/docs/CLIENT.md +9 -8
  51. package/docs/FEATURES.md +8 -5
  52. package/docs/GETTING_STARTED.md +9 -4
  53. package/docs/GOTCHAS.md +2 -1
  54. package/docs/OPERATIONS.md +37 -4
  55. package/docs/PERSISTENCE.md +25 -3
  56. package/docs/PRIMITIVES.md +42 -0
  57. package/docs/PROTOCOL_CLUSTER.md +51 -5
  58. package/docs/PROTOCOL_PRIMITIVES.md +39 -0
  59. package/docs/PROVIDERS.md +50 -13
  60. package/docs/SETTINGS.md +27 -3
  61. package/docs/TASK_LEDGER.md +7 -15
  62. package/node_modules/@arco/shared/dist/clusterCoordination.d.ts +2 -0
  63. package/node_modules/@arco/shared/dist/clusterCoordination.js +5 -1
  64. package/node_modules/@arco/shared/dist/protocol/autoPickup.d.ts +3 -0
  65. package/node_modules/@arco/shared/dist/protocol/clientMessages.d.ts +3 -2
  66. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +13 -1
  67. package/node_modules/@arco/shared/dist/protocol/index.d.ts +1 -0
  68. package/node_modules/@arco/shared/dist/protocol/index.js +1 -0
  69. package/node_modules/@arco/shared/dist/protocol/models.d.ts +4 -3
  70. package/node_modules/@arco/shared/dist/protocol/models.js +26 -2
  71. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +2 -1
  72. package/node_modules/@arco/shared/dist/protocol/tasks.d.ts +4 -0
  73. package/node_modules/@arco/shared/dist/protocol/transcriptWorker.d.ts +47 -0
  74. package/node_modules/@arco/shared/dist/protocol/transcriptWorker.js +2 -0
  75. package/node_modules/@arco/shared/dist/runtimeVersions.d.ts +1 -0
  76. package/node_modules/@arco/shared/dist/runtimeVersions.js +14 -0
  77. package/node_modules/@arco/shared/package.json +1 -1
  78. package/package.json +2 -2
  79. package/scripts/packaging/arco.mjs +1 -1
  80. package/scripts/packaging/native-repair.mjs +78 -12
  81. package/scripts/packaging/update.mjs +5 -1
  82. package/server/dist/atomicFile.js +1 -2
  83. package/server/dist/capabilities.d.ts +5 -2
  84. package/server/dist/capabilities.js +59 -9
  85. package/server/dist/cliUpdateDecision.d.ts +1 -1
  86. package/server/dist/cliUpdateDecision.js +5 -3
  87. package/server/dist/clusterAutoTurn.d.ts +4 -0
  88. package/server/dist/clusterAutoTurn.js +29 -25
  89. package/server/dist/clusterBusyReminder.js +1 -1
  90. package/server/dist/clusterDirector.js +1 -1
  91. package/server/dist/clusterPeerOps.js +10 -7
  92. package/server/dist/clusterProgress.js +1 -1
  93. package/server/dist/clusterSkills.d.ts +13 -0
  94. package/server/dist/clusterSkills.js +81 -0
  95. package/server/dist/clusterSnapshots.js +2 -0
  96. package/server/dist/clusterStore.d.ts +10 -2
  97. package/server/dist/clusterStore.js +64 -1
  98. package/server/dist/diagnostics/codeSkew.js +1 -0
  99. package/server/dist/eventLog.d.ts +7 -0
  100. package/server/dist/eventLog.js +70 -13
  101. package/server/dist/historyLimits.d.ts +1 -0
  102. package/server/dist/historyLimits.js +3 -0
  103. package/server/dist/http/router.js +1 -1
  104. package/server/dist/index.js +24 -1
  105. package/server/dist/jsonlLines.d.ts +4 -0
  106. package/server/dist/jsonlLines.js +53 -0
  107. package/server/dist/management/identity.js +1 -0
  108. package/server/dist/mcp/clusterMcpTools.js +4 -4
  109. package/server/dist/project/taskLedger.d.ts +4 -0
  110. package/server/dist/project/taskLedger.js +7 -4
  111. package/server/dist/providerConversation.d.ts +1 -0
  112. package/server/dist/providerConversation.js +17 -0
  113. package/server/dist/providers/claude-native/resumeSummary.d.ts +9 -0
  114. package/server/dist/providers/claude-native/resumeSummary.js +102 -49
  115. package/server/dist/providers/claude-native/worker.js +8 -4
  116. package/server/dist/providers/claude.js +2 -1
  117. package/server/dist/providers/clusterTaskToolDefinitions.js +4 -4
  118. package/server/dist/providers/codex-appserver/catalog.js +16 -1
  119. package/server/dist/providers/codex.js +2 -1
  120. package/server/dist/providers/codexCodeMode.d.ts +1 -1
  121. package/server/dist/providers/codexCodeMode.js +4 -3
  122. package/server/dist/providers/cursor/print.js +2 -1
  123. package/server/dist/providers/cursor/worker.js +2 -1
  124. package/server/dist/providers/llamacpp.js +17 -8
  125. package/server/dist/providers/ollamaRecovery.js +6 -6
  126. package/server/dist/providers/ollamaResilience.js +3 -3
  127. package/server/dist/providers/ollamaTokens.js +1 -1
  128. package/server/dist/quota.d.ts +0 -18
  129. package/server/dist/quota.js +0 -44
  130. package/server/dist/replacementHistory.d.ts +19 -0
  131. package/server/dist/replacementHistory.js +49 -0
  132. package/server/dist/server/broadcast.d.ts +2 -1
  133. package/server/dist/server/broadcast.js +1 -0
  134. package/server/dist/server/prompts.d.ts +1 -0
  135. package/server/dist/server/prompts.js +6 -1
  136. package/server/dist/sessionJsonl.d.ts +1 -1
  137. package/server/dist/sessionJsonl.js +115 -40
  138. package/server/dist/smartPickup.d.ts +2 -1
  139. package/server/dist/smartPickup.js +28 -1
  140. package/server/dist/smartPickupAdapters.js +15 -2
  141. package/server/dist/smartPickupLedger.js +6 -4
  142. package/server/dist/smartPickupObserver.d.ts +1 -0
  143. package/server/dist/smartPickupObserver.js +24 -15
  144. package/server/dist/transcriptWorker.d.ts +34 -0
  145. package/server/dist/transcriptWorker.js +201 -0
  146. package/server/dist/workflowStore.d.ts +1 -0
  147. package/server/dist/workflowStore.js +31 -0
  148. package/server/dist/ws/clusterHandlers.d.ts +2 -0
  149. package/server/dist/ws/clusterHandlers.js +64 -27
  150. package/server/dist/ws/handoffHandlers.js +5 -2
  151. package/server/dist/ws/transcriptWorkerHandlers.d.ts +25 -0
  152. package/server/dist/ws/transcriptWorkerHandlers.js +139 -0
  153. package/server/dist/ws/turnEngine.js +23 -9
  154. package/server/dist/ws/updatePrimaryConfig.js +27 -8
  155. package/server/dist/ws/workflowHandlers.d.ts +4 -1
  156. package/server/dist/ws/workflowHandlers.js +3 -1
  157. package/server/package.json +1 -1
  158. package/server/src/atomicFile.ts +1 -2
  159. package/server/src/capabilities.ts +58 -17
  160. package/server/src/cliUpdateDecision.ts +5 -4
  161. package/server/src/clusterAutoTurn.ts +26 -21
  162. package/server/src/clusterBusyReminder.ts +1 -1
  163. package/server/src/clusterDirector.ts +1 -1
  164. package/server/src/clusterPeerOps.ts +11 -8
  165. package/server/src/clusterProgress.ts +1 -1
  166. package/server/src/clusterSkills.ts +79 -0
  167. package/server/src/clusterSnapshots.ts +1 -0
  168. package/server/src/clusterStore.ts +64 -1
  169. package/server/src/diagnostics/codeSkew.ts +1 -0
  170. package/server/src/eventLog.ts +73 -13
  171. package/server/src/historyLimits.ts +2 -0
  172. package/server/src/http/router.ts +1 -1
  173. package/server/src/index.ts +23 -0
  174. package/server/src/jsonlLines.ts +52 -0
  175. package/server/src/management/identity.ts +1 -0
  176. package/server/src/mcp/clusterMcpTools.ts +4 -4
  177. package/server/src/project/taskLedger.ts +7 -5
  178. package/server/src/providerConversation.ts +15 -0
  179. package/server/src/providers/claude-native/resumeSummary.ts +98 -50
  180. package/server/src/providers/claude-native/worker.ts +8 -4
  181. package/server/src/providers/claude.ts +2 -1
  182. package/server/src/providers/clusterTaskToolDefinitions.ts +4 -4
  183. package/server/src/providers/codex-appserver/catalog.ts +14 -1
  184. package/server/src/providers/codex.ts +2 -1
  185. package/server/src/providers/codexCodeMode.ts +4 -4
  186. package/server/src/providers/cursor/print.ts +2 -1
  187. package/server/src/providers/cursor/worker.ts +2 -1
  188. package/server/src/providers/llamacpp.ts +18 -7
  189. package/server/src/providers/llamacppRecovery.ts +2 -0
  190. package/server/src/providers/ollamaRecovery.ts +6 -6
  191. package/server/src/providers/ollamaResilience.ts +3 -3
  192. package/server/src/providers/ollamaTokens.ts +1 -1
  193. package/server/src/providers/ollamaToolSubset.ts +3 -3
  194. package/server/src/quota.ts +0 -50
  195. package/server/src/replacementHistory.ts +44 -0
  196. package/server/src/server/broadcast.ts +2 -0
  197. package/server/src/server/prompts.ts +8 -1
  198. package/server/src/sessionJsonl.ts +92 -32
  199. package/server/src/smartPickup.ts +27 -3
  200. package/server/src/smartPickupAdapters.ts +17 -3
  201. package/server/src/smartPickupLedger.ts +6 -4
  202. package/server/src/smartPickupObserver.ts +20 -11
  203. package/server/src/transcriptWorker.ts +182 -0
  204. package/server/src/workflowStore.ts +21 -0
  205. package/server/src/ws/clusterHandlers.ts +46 -27
  206. package/server/src/ws/handoffHandlers.ts +5 -1
  207. package/server/src/ws/transcriptWorkerHandlers.ts +126 -0
  208. package/server/src/ws/turnEngine.ts +20 -8
  209. package/server/src/ws/updatePrimaryConfig.ts +25 -6
  210. package/server/src/ws/workflowHandlers.ts +3 -1
  211. package/shared/dist/clusterCoordination.d.ts +2 -0
  212. package/shared/dist/clusterCoordination.js +5 -1
  213. package/shared/dist/protocol/autoPickup.d.ts +3 -0
  214. package/shared/dist/protocol/clientMessages.d.ts +3 -2
  215. package/shared/dist/protocol/clusters.d.ts +13 -1
  216. package/shared/dist/protocol/index.d.ts +1 -0
  217. package/shared/dist/protocol/index.js +1 -0
  218. package/shared/dist/protocol/models.d.ts +4 -3
  219. package/shared/dist/protocol/models.js +26 -2
  220. package/shared/dist/protocol/serverMessages.d.ts +2 -1
  221. package/shared/dist/protocol/tasks.d.ts +4 -0
  222. package/shared/dist/protocol/transcriptWorker.d.ts +47 -0
  223. package/shared/dist/protocol/transcriptWorker.js +2 -0
  224. package/shared/dist/runtimeVersions.d.ts +1 -0
  225. package/shared/dist/runtimeVersions.js +14 -0
  226. package/shared/src/clusterCoordination.ts +7 -1
  227. package/shared/src/protocol/autoPickup.ts +5 -0
  228. package/shared/src/protocol/clientMessages.ts +5 -0
  229. package/shared/src/protocol/clusters.ts +16 -1
  230. package/shared/src/protocol/index.ts +1 -0
  231. package/shared/src/protocol/models.ts +31 -5
  232. package/shared/src/protocol/serverMessages.ts +2 -0
  233. package/shared/src/protocol/settings.ts +2 -3
  234. package/shared/src/protocol/tasks.ts +4 -7
  235. package/shared/src/protocol/transcriptWorker.ts +49 -0
  236. package/shared/src/runtimeVersions.ts +14 -0
@@ -1850,7 +1850,7 @@ export async function handleHttpRequest(req, res, deps) {
1850
1850
  res.end(JSON.stringify({ error: retired }));
1851
1851
  return;
1852
1852
  }
1853
- const provider = providerParam === 'codex'
1853
+ const provider = providerParam === 'codex' || providerParam === 'cursor'
1854
1854
  ? providerParam
1855
1855
  : 'claude';
1856
1856
  const result = await runCliUpdate(deps.getCapabilities(), provider);
@@ -1,4 +1,5 @@
1
1
  import { releaseProjectSettingsWatcher } from './settings.js';
2
+ import { initTranscriptWorkerHandlers, handleTranscriptWorkerPreview, handleTranscriptWorkerCreate } from './ws/transcriptWorkerHandlers.js';
2
3
  import { NativeTaskAdmission, assertNativeTaskAllowed } from './providers/claude-native/taskAdmission.js';
3
4
  import { resolveNativeSubagents, CLAUDE_MODELS } from '@arco/shared';
4
5
  import { getCatalog as getNativeTaskCatalog } from './providers/claude-native/catalog.js';
@@ -70,7 +71,7 @@ import { startMemoryMonitor, logMemorySample } from './memoryMonitor.js';
70
71
  import { listeningPortsForPidFamily } from './workers/procListening.js';
71
72
  import { updateMeta, } from './workflowMeta.js';
72
73
  import { flushAll as flushAllWorkflowEvents, initWorkflowStore } from './workflowStore.js';
73
- import { detachClusterObservers, handleClusterAddFreshWorkers, handleClusterAutoTurnToggle, handleClusterAutoPickupSet, handleClusterBroadcast, handleClusterCreate, handleClusterCreateFromScratch, handleClusterCreateWithFreshWorkers, handleClusterDelete, handleClusterDispatchSettingsUpdate, handleClusterDispatchOnce, handleClusterDispatchToggle, handleClusterSwarmCreate, handleClusterOrchestrationAssistRequest, handleClusterOrchestrationProposalApply, handleClusterOrchestrationProposalList, handleClusterOrchestrationProposalReject, handleClusterIdleNudgerToggle, handleClusterEfficiencySet, handleClusterAutoCompactionSet, handleClusterRemoteSet, handleClusterGatesSet, handleClusterMemberReorder, handleClusterProgressSet, handleClusterTaskBoardAttachSet, handleClusterTaskBoardModeSet, handleClusterMemberAdd, handleClusterMemberFocusSet, handleClusterMemberRemove, handleClusterMemberReplace, handleClusterMemberRoleSet, handleClusterMemberTierSet, handleClusterPlanAttach, handleClusterPlanClear, handleClusterPlanSet, handleClusterRename, handleClusterSnapshotSave, handleClusterSnapshotList, handleClusterSnapshotRestore, handleClusterSnapshotDelete, handleClusterSubscribe, handleOperatorPeerSend, dispatchTaskTurnSynthetic, broadcastTaskDispatchResult, initClusterHandlers, } from './ws/clusterHandlers.js';
74
+ import { detachClusterObservers, handleClusterAddFreshWorkers, handleClusterAutoTurnToggle, handleClusterAutoPickupSet, handleClusterBroadcast, handleClusterCreate, handleClusterCreateFromScratch, handleClusterCreateWithFreshWorkers, handleClusterDelete, handleClusterDispatchSettingsUpdate, handleClusterDispatchOnce, handleClusterDispatchToggle, handleClusterSwarmCreate, handleClusterOrchestrationAssistRequest, handleClusterOrchestrationProposalApply, handleClusterOrchestrationProposalList, handleClusterOrchestrationProposalReject, handleClusterIdleNudgerToggle, handleClusterEfficiencySet, handleClusterSkillsSet, handleClusterAutoCompactionSet, handleClusterRemoteSet, handleClusterGatesSet, handleClusterMemberReorder, handleClusterProgressSet, handleClusterTaskBoardAttachSet, handleClusterTaskBoardModeSet, handleClusterMemberAdd, handleClusterMemberFocusSet, handleClusterMemberRemove, handleClusterMemberReplace, handleClusterMemberRoleSet, handleClusterMemberTierSet, handleClusterPlanAttach, handleClusterPlanClear, handleClusterPlanSet, handleClusterRename, handleClusterSnapshotSave, handleClusterSnapshotList, handleClusterSnapshotRestore, handleClusterSnapshotDelete, handleClusterSubscribe, handleOperatorPeerSend, dispatchTaskTurnSynthetic, broadcastTaskDispatchResult, initClusterHandlers, } from './ws/clusterHandlers.js';
74
75
  import { deriveAutoHandoff, derivePrimaryConfig, handleUserMessage, enqueueBusyReminder, initTurnEngine, maybeAutoCompactPolicy, claimBusy, releaseBusy, persistInitialMeta, writeCalibrationToMeta, broadcastQueueUpdate, drainQueueIfIdle } from './ws/turnEngine.js';
75
76
  import { handleBakeoffCleanup, handleBakeoffList, handleBakeoffPromote, handleBakeoffStart, initBakeoffHandlers, } from './ws/bakeoffHandlers.js';
76
77
  import { createBlankNativeWorkflow, handleAttachCodebaseMemory, handleCancel, handleCancelQueuedMessage, handleCancelResearch, handleCancelReview, handleClearPreviewPort, handleCreateLabelRequest, handleCreateWorkflow, handleDetachCodebaseMemory, handleDocEditRequest, handleMdTuneupRequest, handleMdTuneupAccept, handleMdTuneupUndo, handleMdTuneupCandidatesRequest, handleHandoffCancel, handleHandoffLockClear, handleLoadEarlierMessages, handleRemoveWorkflow, handleRenameWorkflow, handleRevertToCheckpoint, handleRevertToPointRequest, handleResearchRequest, handleRecallSummaryRequest, handleReviewRequest, handleSetPreviewPort, handleUpdatePrimaryConfig, initWorkflowHandlers, } from './ws/workflowHandlers.js';
@@ -424,6 +425,19 @@ const previewAutoDetect = new PreviewAutoDetect({
424
425
  });
425
426
  initTurnEngine({ previewAutoDetect, handleCreateWorkflow, handleHandoffRequest, handleCompactWorkflow });
426
427
  initWorkflowHandlers({ previewAutoDetect, handleRehydrateWorkflows });
428
+ initTranscriptWorkerHandlers({
429
+ create: async (ws, session, config) => {
430
+ let id;
431
+ await handleCreateWorkflow(ws, session, config, { backgroundCreated: true, onCreated: created => { id = created; } });
432
+ if (!id)
433
+ throw new Error('The new worker could not be created. Review its settings and try again.');
434
+ return id;
435
+ },
436
+ seed: (ws, session, workflowId, content) => {
437
+ void handleUserMessage(ws, session, workflowId, content, crypto.randomUUID(), undefined, false, undefined, undefined)
438
+ .catch(() => send(ws, { type: 'error', workflowId, message: 'Could not start the new worker. Open its tab to review the request and retry.' }));
439
+ },
440
+ });
427
441
  setStrataSwitchActivityCheck(() => [...workflows.values()].some((wf) => (wf.busy && ['ollama', 'llamacpp', 'lmstudio', 'deepseek'].includes(wf.primary.provider)) ||
428
442
  Object.values(wf.manager.snapshotWorkers()).some((w) => ['ollama', 'llamacpp', 'lmstudio', 'deepseek'].includes(w.provider ?? '') && (w.status === 'running' || w.status === 'spawning'))));
429
443
  setDeepSeekActivityCheck((includeDeepSeek) => [...workflows.values()].some((wf) => (wf.busy && ['ollama', 'llamacpp', 'lmstudio', 'strata', ...(includeDeepSeek ? ['deepseek'] : [])].includes(wf.primary.provider)) ||
@@ -532,6 +546,12 @@ wss.on('connection', (ws) => {
532
546
  return;
533
547
  }
534
548
  switch (msg.type) {
549
+ case 'transcript_worker_preview':
550
+ void handleTranscriptWorkerPreview(ws, msg);
551
+ break;
552
+ case 'transcript_worker_create':
553
+ void handleTranscriptWorkerCreate(ws, session, msg);
554
+ break;
535
555
  case 'create_workflow':
536
556
  (msg.config.incognito ? withoutOperationalLogging : (fn) => fn())(() => handleCreateWorkflow(ws, session, msg.config).catch((err) => {
537
557
  console.error('[arco] create_workflow handler failed:', err);
@@ -1121,6 +1141,9 @@ wss.on('connection', (ws) => {
1121
1141
  console.error('[arco] cluster_efficiency_set handler failed:', err);
1122
1142
  });
1123
1143
  break;
1144
+ case 'cluster_skills_set':
1145
+ void handleClusterSkillsSet(ws, msg.clusterId, msg.pins);
1146
+ break;
1124
1147
  case 'cluster_remote_set':
1125
1148
  handleClusterRemoteSet(ws, msg.clusterId, msg.enabled).catch((err) => {
1126
1149
  console.error('[arco] cluster_remote_set handler failed:', err);
@@ -0,0 +1,4 @@
1
+ export declare function jsonlLines(input: AsyncIterable<Buffer>, source: string, options?: {
2
+ finalLine?: boolean;
3
+ carriageReturns?: boolean;
4
+ }): AsyncGenerator<string>;
@@ -0,0 +1,53 @@
1
+ import { basename } from 'node:path';
2
+ const LARGE_RECORD_BYTES = 16 * 1024 * 1024;
3
+ const warnedSources = new Set();
4
+ // Retain only the current record's bytes. Decode once at its boundary so a
5
+ // split UTF-8 character is never replaced and a long record does not build a
6
+ // chain of decoded string fragments. Large records stay readable as before.
7
+ export async function* jsonlLines(input, source, options = {}) {
8
+ let parts = [];
9
+ let bytes = 0;
10
+ let afterCr = false;
11
+ const add = (part) => {
12
+ if (!part.length)
13
+ return;
14
+ parts.push(part);
15
+ bytes += part.length;
16
+ if (bytes > LARGE_RECORD_BYTES && !warnedSources.has(source)) {
17
+ warnedSources.add(source);
18
+ console.warn(`[arco] A record in ${basename(source)} exceeds 16 MiB; reading it in full.`);
19
+ }
20
+ };
21
+ const take = () => {
22
+ const line = parts.length === 1 ? parts[0].toString('utf8') : Buffer.concat(parts, bytes).toString('utf8');
23
+ parts = [];
24
+ bytes = 0;
25
+ return line;
26
+ };
27
+ for await (const chunk of input) {
28
+ let start = 0;
29
+ const hasCr = options.carriageReturns !== false && chunk.includes(0x0d);
30
+ while (start < chunk.length) {
31
+ if (afterCr) {
32
+ afterCr = false;
33
+ if (chunk[start] === 0x0a) {
34
+ start++;
35
+ continue;
36
+ }
37
+ }
38
+ const lf = chunk.indexOf(0x0a, start);
39
+ const cr = hasCr ? chunk.indexOf(0x0d, start) : -1;
40
+ const end = lf < 0 ? cr : cr < 0 ? lf : Math.min(lf, cr);
41
+ if (end < 0)
42
+ break;
43
+ add(chunk.subarray(start, end));
44
+ yield take();
45
+ afterCr = chunk[end] === 0x0d;
46
+ start = end + 1;
47
+ }
48
+ add(chunk.subarray(start));
49
+ }
50
+ if (bytes && options.finalLine !== false)
51
+ yield take();
52
+ }
53
+ //# sourceMappingURL=jsonlLines.js.map
@@ -58,6 +58,7 @@ function shortGitRevision(repoRoot) {
58
58
  return execFileSync('git', ['rev-parse', '--short', 'HEAD'], {
59
59
  cwd: repoRoot,
60
60
  encoding: 'utf8',
61
+ stdio: 'pipe',
61
62
  }).trim();
62
63
  }
63
64
  catch {
@@ -376,7 +376,7 @@ export function registerClusterTools(server, ctx) {
376
376
  }
377
377
  });
378
378
  registerTool('cluster_task_create', {
379
- description: 'Create a non-terminal task on the shared cluster board. New tasks start as todo; done/archived remain operator-only. Use title plus optional body/notes, assignee, priority, parentIds, links, reviewRequired, goalMode, and goalMaxTurns. parentIds must refer to existing tasks. When the task implements a plan item, start the title with that item\'s id or text (e.g. \'P6.9 Live tab drag follow on X11\'): cluster_task_show then resolves the item\'s reference docs (its own ref links, its sub-bullets, its phase intro) for whoever works it. Add any extra ref:slug links the task needs to notes.',
379
+ description: 'Create a non-terminal task on the shared cluster board. New tasks start as todo; terminal statuses cannot be set when creating a task. Use title plus optional body/notes, assignee, priority, parentIds, links, reviewRequired, goalMode, and goalMaxTurns. parentIds must refer to existing tasks. When the task implements a plan item, start the title with that item\'s id or text (e.g. \'P6.9 Live tab drag follow on X11\'): cluster_task_show then resolves the item\'s reference docs (its own ref links, its sub-bullets, its phase intro) for whoever works it. Add any extra ref:slug links the task needs to notes.',
380
380
  inputSchema: {
381
381
  title: z.string().min(1).describe('Task title. Required and non-empty.'),
382
382
  body: z.string().optional().describe('Initial task body. Alias for notes when notes is absent.'),
@@ -459,7 +459,7 @@ export function registerClusterTools(server, ctx) {
459
459
  }
460
460
  });
461
461
  registerTool('cluster_task_update', {
462
- description: "Update a task on the shared cluster board. Change its `status` (triage / todo / ready / in_progress / blocked / review), replace `notes`, and/or record a `signoff` verdict. IMPORTANT: `done` and `archived` are OPERATOR-ONLY — those statuses are REJECTED here (operator_gated). When you finish work, move the task to review or report completion via peer_send to the director; the operator marks done from the LEDGER tab.\n\nSIGN-OFF (director): when you review a peer's completed task, set `signoff` to your verdict — `met`, `not_met`, or `partial` — with a one-line `summary`. ADVISORY only: it does NOT mark the task done; it surfaces a recommendation on the board so the operator can accept at a glance. Only the reviewing member (the director) should set this.",
462
+ description: "Update a task on the shared cluster board. Workers move completed work to review. Only the director signs off: set signoff to met, partial, or not_met with a plain one-line summary for the operator, without commit hashes. A director's met sign-off closes the task unless Board auto-done is off in Settings; partial and not_met leave the task status unchanged unless you set a status. Tell the operator in chat what to try. Direct status changes to done or archived remain operator-only.",
463
463
  inputSchema: {
464
464
  id: z.string().min(1).describe('Task id from cluster_task_list.'),
465
465
  status: z.enum(['triage', 'todo', 'ready', 'in_progress', 'blocked', 'review']).optional().describe("New status. 'done' and 'archived' are rejected — operator-only."),
@@ -468,7 +468,7 @@ export function registerClusterTools(server, ctx) {
468
468
  signoff: z.object({
469
469
  state: z.enum(['met', 'not_met', 'partial']).describe('Your verdict: met / not_met / partial.'),
470
470
  summary: z.string().optional().describe('One-line reason shown on the board card.'),
471
- }).optional().describe('Advisory director verdict on whether the task met its target. Does NOT mark it done.'),
471
+ }).optional().describe('Director verdict: met closes the task unless Board auto-done is off.'),
472
472
  },
473
473
  }, async (args) => {
474
474
  try {
@@ -570,7 +570,7 @@ export function registerClusterTools(server, ctx) {
570
570
  }
571
571
  });
572
572
  registerTool('cluster_task_complete', {
573
- description: "Submit a completion report for a task. Moves the task to review and appends a durable COMPLETION REPORT comment. It does NOT mark done; done remains operator-only.",
573
+ description: "Submit a completion report for a task. Moves the task to review and appends a durable COMPLETION REPORT comment. It does not mark done; the director reviews the report.",
574
574
  inputSchema: {
575
575
  id: z.string().min(1).describe('Task id from cluster_task_list.'),
576
576
  summary: z.string().min(1).describe('What changed, tests run, files touched, and follow-ups.'),
@@ -76,6 +76,10 @@ export declare function applyUpdate(tasks: LedgerTask[], id: string, patch: {
76
76
  release?: string;
77
77
  worktree?: TaskWorktree | null;
78
78
  signoff?: TaskSignoff | null;
79
+ directorClosure?: {
80
+ byWorkflowId: string;
81
+ at: number;
82
+ };
79
83
  updatedBy?: string;
80
84
  }): {
81
85
  tasks: LedgerTask[];
@@ -14,10 +14,9 @@ import { ensureProjectStateIgnore } from '../projectStateIgnore.js';
14
14
  // need — is documented in docs/TASK_LEDGER.md, not assumed). The working set is
15
15
  // small + single-writer, so query() is load-all + filter-in-JS.
16
16
  //
17
- // LOAD-BEARING INVARIANT (§D1 acceptance): there is NO code path that sets
18
- // status: 'done' except an explicit operator-originated update (applyUpdate
19
- // below). create() never accepts a status; rebuildFromEvents only replays
20
- // recorded operator events; there is no auto-done / no inference anywhere.
17
+ // Direct terminal-status updates are operator-controlled. A director's met
18
+ // sign-off may close a task when Board auto-done is enabled; replay uses the
19
+ // recorded result and never infers a new status.
21
20
  import { promises as fs, existsSync } from 'fs';
22
21
  import path from 'path';
23
22
  import { randomUUID } from 'crypto';
@@ -711,6 +710,10 @@ patch) {
711
710
  else
712
711
  delete next.signoff;
713
712
  }
713
+ if (patch.directorClosure)
714
+ next.directorClosure = patch.directorClosure;
715
+ else if (patch.status && patch.status !== 'done')
716
+ delete next.directorClosure;
714
717
  const out = [...tasks];
715
718
  out[i] = next;
716
719
  return { tasks: out, updated: next };
@@ -1,5 +1,6 @@
1
1
  import type { ProviderName } from '@arco/shared';
2
2
  import type { WorkflowState } from './workflows/types.js';
3
+ export declare function reportHistoryLoadFailure(workflowId: string, owner: object, provider: 'native' | 'cli', emit?: (content: string) => void, nativeLimitBytes?: number): void;
3
4
  export declare function hasConversationHistory(cwd: string, workflowId: string, afterSeq?: number): Promise<boolean>;
4
5
  export declare function reportConversationSaveFailure(workflowId: string, err: unknown): void;
5
6
  export declare function ensureWorkflowMetadata(cwd: string, workflowId: string, wf: WorkflowState): Promise<void>;
@@ -2,6 +2,23 @@ import { resolveClaudeTransport } from './claudeTransport.js';
2
2
  import { readMeta, persistInitialMeta, reconcileLatestCliSession, workflowMetaSeed, updateMeta } from './workflowMeta.js';
3
3
  import { scanEventsOfTypes } from './workflowStore.js';
4
4
  import { broadcastWorkflow, broadcastTransient } from './server/broadcast.js';
5
+ const historyLoadNotices = new WeakMap();
6
+ export function reportHistoryLoadFailure(workflowId, owner, provider, emit, nativeLimitBytes) {
7
+ const shown = historyLoadNotices.get(owner) ?? new Set();
8
+ if (shown.has(provider))
9
+ return;
10
+ shown.add(provider);
11
+ historyLoadNotices.set(owner, shown);
12
+ const content = provider === 'native'
13
+ ? nativeLimitBytes !== undefined
14
+ ? `Earlier context could not be rebuilt within the ${nativeLimitBytes / (1024 * 1024)} MiB reconstruction limit, so the agent continues without it. Earlier messages remain in this tab.`
15
+ : 'Earlier context could not be rebuilt for this conversation, so the agent continues without it. Earlier messages remain in this tab.'
16
+ : 'Earlier Claude CLI session history could not be loaded in this tab. The saved conversation is intact; new session messages will appear when the file can be read.';
17
+ if (emit)
18
+ emit(content);
19
+ else
20
+ broadcastWorkflow(workflowId, { type: 'system_notice', workflowId, content });
21
+ }
5
22
  export async function hasConversationHistory(cwd, workflowId, afterSeq = 0) {
6
23
  let found = false;
7
24
  await scanEventsOfTypes(cwd, workflowId, ['primary_complete', 'primary_text'], event => { if ((('seq' in event && typeof event.seq === 'number') ? event.seq : 0) > afterSeq)
@@ -1,4 +1,11 @@
1
1
  import { type ServerCompactionBlock } from './serverFold.js';
2
+ export declare const NATIVE_RECONSTRUCTION_MAX_BYTES: number;
3
+ export declare class NativeReconstructionLimitError extends Error {
4
+ readonly rangeBytes: number;
5
+ readonly code = "NATIVE_RECONSTRUCTION_LIMIT";
6
+ readonly limitBytes: number;
7
+ constructor(rangeBytes: number);
8
+ }
2
9
  export declare const RESUME_EXACT_REPLAY_BYTES: number;
3
10
  export declare const RESUME_RECENT_TAIL_BYTES: number;
4
11
  export type ClaudeResumeMessage = {
@@ -57,10 +64,12 @@ export type ResumeReplayResult = {
57
64
  summaryThroughSeq?: number;
58
65
  summaryBytes?: number;
59
66
  tailEvents?: number;
67
+ summaryNotice?: string;
60
68
  reconstructed?: boolean;
61
69
  };
62
70
  type SummaryBuild = {
63
71
  summary: string;
72
+ summaryNotice?: string;
64
73
  throughSeq: number | null;
65
74
  lastHandoffSeq: number | null;
66
75
  };
@@ -6,14 +6,30 @@ import { promises as fs } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { atomicWriteFile } from '../../atomicFile.js';
9
- import { listSegments, readLogText, readLogLines } from '../../eventLog.js';
9
+ import { openLogByteSource, readLogLines } from '../../eventLog.js';
10
+ import { jsonlLines } from '../../jsonlLines.js';
10
11
  import { serverFoldSeed } from './serverFold.js';
11
12
  import { isShellToolName } from '@arco/shared';
13
+ import { RECENT_HISTORY_MAX_BYTES } from '../../historyLimits.js';
12
14
  const isFileRead = (name) => !!name && /^(?:Read|(?:.*__)?(?:read_file|fetch_file))$/i.test(name);
13
15
  const SUMMARY_CACHE_VERSION = 4;
14
16
  const SUMMARY_CACHE_KIND = 'claude-native-resume-summary';
15
17
  const DEFAULT_REPLAY_BYTES = 1 * 1024 * 1024;
16
18
  const TAIL_LINE_BACKTRACK_BYTES = 1 * 1024 * 1024;
19
+ // The retained event arrays still amplify source bytes during reconstruction.
20
+ // Refuse an uncached parse beyond the measured default-heap margin; a valid
21
+ // summary cache needs only its small tail and does not parse the old prefix.
22
+ export const NATIVE_RECONSTRUCTION_MAX_BYTES = 1024 * 1024 * 1024;
23
+ export class NativeReconstructionLimitError extends Error {
24
+ rangeBytes;
25
+ code = 'NATIVE_RECONSTRUCTION_LIMIT';
26
+ limitBytes = NATIVE_RECONSTRUCTION_MAX_BYTES;
27
+ constructor(rangeBytes) {
28
+ super(`Claude Native reconstruction requires ${rangeBytes} bytes, above the ${NATIVE_RECONSTRUCTION_MAX_BYTES}-byte limit.`);
29
+ this.rangeBytes = rangeBytes;
30
+ this.name = 'NativeReconstructionLimitError';
31
+ }
32
+ }
17
33
  function readPositiveIntEnv(name, fallback) {
18
34
  const raw = process.env[name];
19
35
  if (!raw)
@@ -26,39 +42,27 @@ export const RESUME_RECENT_TAIL_BYTES = readPositiveIntEnv('ARCO_CLAUDE_NATIVE_R
26
42
  function workflowDir(cwd, workflowId) {
27
43
  return join(cwd, '.arco', 'workflows', workflowId);
28
44
  }
29
- function eventsPath(cwd, workflowId) {
30
- return join(workflowDir(cwd, workflowId), 'events.jsonl');
31
- }
32
45
  function summaryCachePath(cwd, workflowId) {
33
46
  return join(workflowDir(cwd, workflowId), 'resume-summary.json');
34
47
  }
35
48
  async function openLogSource(cwd, workflowId) {
36
- const dir = workflowDir(cwd, workflowId);
37
- if ((await listSegments(dir)).length > 0) {
38
- const text = Buffer.from(await readLogText(dir), 'utf8');
39
- return { size: text.length, read: async (start, length) => text.subarray(start, start + length).toString('utf8') };
40
- }
41
- const path = eventsPath(cwd, workflowId);
42
- try {
43
- const size = (await fs.stat(path)).size;
44
- return { size, read: (start, length) => readByteRange(path, start, length) };
45
- }
46
- catch (err) {
47
- if (err.code === 'ENOENT')
48
- return null;
49
- throw err;
50
- }
49
+ return openLogByteSource(workflowDir(cwd, workflowId));
51
50
  }
52
- async function readByteRange(path, start, length) {
53
- const fh = await fs.open(path, 'r');
54
- try {
55
- const buf = Buffer.alloc(length);
56
- await fh.read(buf, 0, buf.length, start);
57
- return buf.toString('utf8');
58
- }
59
- finally {
60
- await fh.close();
51
+ async function readSourceEvents(source, length, dropLastPartial = false) {
52
+ if (length > NATIVE_RECONSTRUCTION_MAX_BYTES)
53
+ throw new NativeReconstructionLimitError(length);
54
+ const events = [];
55
+ for await (const line of jsonlLines(source.chunks(0, length), 'conversation replay', {
56
+ finalLine: !dropLastPartial, carriageReturns: false,
57
+ })) {
58
+ if (!line)
59
+ continue;
60
+ try {
61
+ events.push(JSON.parse(line));
62
+ }
63
+ catch { /* Match parseJsonl: corrupt or partial records remain untouched. */ }
61
64
  }
65
+ return events;
62
66
  }
63
67
  async function findTailReplayStart(source, desiredStart) {
64
68
  if (desiredStart <= 0)
@@ -445,22 +449,27 @@ export function summarizeClaudeNativePriorTurns(events, laterEvents = [], attach
445
449
  }
446
450
  if (turns.length === 0 && !compactSummary)
447
451
  return { summary: '', throughSeq, lastHandoffSeq };
448
- const lines = [];
449
- if (compactSummary) {
450
- lines.push('## Earlier context (operator-compacted)');
451
- lines.push('');
452
- lines.push(compactSummary.trim());
453
- if (compactTail) {
452
+ const renderPrefix = (summary = compactSummary, tail = compactTail) => {
453
+ const lines = [];
454
+ if (compactSummary) {
455
+ lines.push('## Earlier context (operator-compacted)');
454
456
  lines.push('');
455
- lines.push('### Recent verbatim turns kept at that compaction');
456
- lines.push(compactTail);
457
+ lines.push(summary?.trim() ?? '');
458
+ if (tail) {
459
+ lines.push('');
460
+ lines.push('### Recent verbatim turns kept at that compaction');
461
+ lines.push(tail);
462
+ }
463
+ if (turns.length > 0)
464
+ lines.push('');
457
465
  }
458
466
  if (turns.length > 0)
459
- lines.push('');
460
- }
461
- if (turns.length > 0)
462
- lines.push('## Prior turns in this workflow (auto-summary)');
463
- turns.forEach((t, i) => {
467
+ lines.push('## Prior turns in this workflow (auto-summary)');
468
+ return lines.join('\n');
469
+ };
470
+ let prefix = renderPrefix();
471
+ const notes = turns.map((t, i) => {
472
+ const lines = [];
464
473
  const head = t.userText.length > 120 ? t.userText.slice(0, 120) + '...' : t.userText;
465
474
  lines.push('');
466
475
  lines.push(`### Turn ${i + 1}: ${head}`);
@@ -489,8 +498,44 @@ export function summarizeClaudeNativePriorTurns(events, laterEvents = [], attach
489
498
  const reply = t.finalReply.trim().replace(/\s+/g, ' ').slice(0, 240);
490
499
  lines.push(`- Assistant reply: "${reply}${t.finalReply.length > 240 ? '...' : ''}"`);
491
500
  }
501
+ return lines.join('\n');
492
502
  });
493
- return { summary: lines.join('\n'), throughSeq, lastHandoffSeq };
503
+ const noteBytes = notes.map(note => Buffer.byteLength(note, 'utf8') + 1);
504
+ let retainedBytes = noteBytes.reduce((sum, bytes) => sum + bytes, 0);
505
+ if (Buffer.byteLength(prefix, 'utf8') + retainedBytes <= RECENT_HISTORY_MAX_BYTES) {
506
+ return { summary: [prefix, ...notes].join('\n'), throughSeq, lastHandoffSeq };
507
+ }
508
+ let omitted = 0;
509
+ let shortened = false;
510
+ const notice = () => `Earlier context: ${omitted} oldest turn note${omitted === 1 ? '' : 's'} ${omitted === 1 ? 'was' : 'were'} left out${shortened ? ' and compacted context was shortened' : ''} to stay within 128 KiB.`;
511
+ const prefixBytes = Buffer.byteLength(prefix, 'utf8');
512
+ while (omitted < notes.length && prefixBytes + 1 + Buffer.byteLength(notice(), 'utf8') + retainedBytes > RECENT_HISTORY_MAX_BYTES) {
513
+ retainedBytes -= noteBytes[omitted++];
514
+ }
515
+ if (prefixBytes + 1 + Buffer.byteLength(notice(), 'utf8') > RECENT_HISTORY_MAX_BYTES) {
516
+ // The compacted context itself can be larger than the budget. Preserve its
517
+ // kept-tail digest first, then as much summary text as fits, without cutting
518
+ // a UTF-8 character. The same notice discloses this exceptional shortening.
519
+ shortened = true;
520
+ const budget = RECENT_HISTORY_MAX_BYTES - Buffer.byteLength(notice(), 'utf8') - 1;
521
+ const clip = (text, bytes) => {
522
+ const encoded = Buffer.from(text, 'utf8');
523
+ let end = Math.min(encoded.length, Math.max(0, bytes));
524
+ while (end > 0 && (encoded[end] & 0xc0) === 0x80)
525
+ end--;
526
+ return encoded.subarray(0, end).toString('utf8');
527
+ };
528
+ const tailPrefix = renderPrefix('', compactTail);
529
+ if (Buffer.byteLength(tailPrefix, 'utf8') <= budget) {
530
+ prefix = renderPrefix(clip(compactSummary?.trim() ?? '', budget - Buffer.byteLength(tailPrefix, 'utf8')), compactTail);
531
+ }
532
+ else {
533
+ const overhead = Buffer.byteLength(renderPrefix('', 'x'), 'utf8') - 1;
534
+ prefix = renderPrefix('', clip(compactTail ?? '', budget - overhead));
535
+ }
536
+ }
537
+ const summaryNotice = notice();
538
+ return { summary: [prefix, summaryNotice, ...notes.slice(omitted)].join('\n'), summaryNotice, throughSeq, lastHandoffSeq };
494
539
  }
495
540
  async function readSummaryCache(path, workflowId, sourceSize, tailStartByte) {
496
541
  try {
@@ -501,7 +546,8 @@ async function readSummaryCache(path, workflowId, sourceSize, tailStartByte) {
501
546
  parsed.workflowId === workflowId &&
502
547
  parsed.sourceSize === sourceSize &&
503
548
  parsed.tailStartByte === tailStartByte &&
504
- typeof parsed.summary === 'string' && Array.isArray(parsed.inputHistory)
549
+ typeof parsed.summary === 'string' && Buffer.byteLength(parsed.summary, 'utf8') <= RECENT_HISTORY_MAX_BYTES && Array.isArray(parsed.inputHistory)
550
+ && (parsed.summaryNotice === undefined || typeof parsed.summaryNotice === 'string')
505
551
  && parsed.inputHistory.every(event => (event?.type === 'user_message_echo' && typeof event.content === 'string') || (event?.type === 'queued_messages_drained' && typeof event.deliveryId === 'string'))) {
506
552
  return parsed;
507
553
  }
@@ -527,6 +573,14 @@ export async function replayMessagesWithResumePolicy(cwd, workflowId, maxSeq, op
527
573
  const source = await openLogSource(cwd, workflowId);
528
574
  if (!source)
529
575
  return { messages: [], mode: 'empty', eventBytes: 0 };
576
+ try {
577
+ return await replayFromSource(cwd, workflowId, source, maxSeq, opts);
578
+ }
579
+ finally {
580
+ await source.close();
581
+ }
582
+ }
583
+ async function replayFromSource(cwd, workflowId, source, maxSeq, opts) {
530
584
  const stat = { size: source.size };
531
585
  const exactReplayBytes = opts.exactReplayBytes ?? RESUME_EXACT_REPLAY_BYTES;
532
586
  const recentTailBytes = opts.recentTailBytes ?? RESUME_RECENT_TAIL_BYTES;
@@ -544,8 +598,7 @@ export async function replayMessagesWithResumePolicy(cwd, workflowId, maxSeq, op
544
598
  // This is what lets post-rewind turns be included WITHOUT advancing leafSeq
545
599
  // on every turn.
546
600
  if (typeof opts.leafSeq === 'number') {
547
- const raw = await source.read(0, stat.size);
548
- const events = parseJsonl(raw);
601
+ const events = await readSourceEvents(source, stat.size);
549
602
  let tailSeq;
550
603
  for (const e of events) {
551
604
  if (typeof e.seq === 'number' && (tailSeq === undefined || e.seq > tailSeq))
@@ -561,8 +614,7 @@ export async function replayMessagesWithResumePolicy(cwd, workflowId, maxSeq, op
561
614
  };
562
615
  }
563
616
  if (stat.size <= exactReplayBytes) {
564
- const raw = await source.read(0, stat.size);
565
- const events = parseJsonl(raw);
617
+ const events = await readSourceEvents(source, stat.size);
566
618
  return {
567
619
  messages: buildMessagesFromReplayEvents(events, [], maxSeq, undefined, [], opts.attachmentMarkers),
568
620
  mode: 'exact',
@@ -596,8 +648,7 @@ export async function replayMessagesWithResumePolicy(cwd, workflowId, maxSeq, op
596
648
  const cachePath = summaryCachePath(cwd, workflowId);
597
649
  let cache = opts.attachmentMarkers ? null : await readSummaryCache(cachePath, workflowId, stat.size, tailStartByte);
598
650
  if (!cache) {
599
- const olderRaw = tailStartByte > 0 ? await source.read(0, tailStartByte) : '';
600
- const olderEvents = parseJsonl(olderRaw, { dropLastPartial: !tailStart.completeLine });
651
+ const olderEvents = await readSourceEvents(source, tailStartByte, !tailStart.completeLine);
601
652
  const built = summarizeClaudeNativePriorTurns(olderEvents, tailEvents, !!opts.attachmentMarkers);
602
653
  if (opts.attachmentMarkers) {
603
654
  const lastOlderSeq = olderEvents.reduce((max, event) => Math.max(max, event.seq ?? 0), 0);
@@ -621,6 +672,7 @@ export async function replayMessagesWithResumePolicy(cwd, workflowId, maxSeq, op
621
672
  throughSeq: built.throughSeq,
622
673
  lastHandoffSeq: built.lastHandoffSeq,
623
674
  summary: built.summary,
675
+ summaryNotice: built.summaryNotice,
624
676
  inputHistory: referencedInputRecords(tailEvents, olderEvents),
625
677
  updatedAt: new Date().toISOString(),
626
678
  };
@@ -635,6 +687,7 @@ export async function replayMessagesWithResumePolicy(cwd, workflowId, maxSeq, op
635
687
  summaryThroughSeq: cache.throughSeq ?? undefined,
636
688
  summaryBytes: cache.summary.length,
637
689
  tailEvents: tailEvents.length,
690
+ ...(cache.summaryNotice ? { summaryNotice: cache.summaryNotice } : {}),
638
691
  };
639
692
  }
640
693
  //# sourceMappingURL=resumeSummary.js.map
@@ -1,7 +1,7 @@
1
1
  import { setMaxListeners } from 'node:events';
2
2
  import { assertNativeTaskAllowed } from './taskAdmission.js';
3
3
  import { readSettings } from '../../settings.js';
4
- import { resolveNativeSubagents } from '@arco/shared';
4
+ import { buildTurnWaitInstructions, resolveNativeSubagents } from '@arco/shared';
5
5
  import { availableHandoffSources, executeHandoffHistory, HANDOFF_HISTORY_TOOL, HANDOFF_HISTORY_CONTEXT } from '../../handoffHistoryTool.js';
6
6
  import { mediaRetirementNotice } from './mediaRetirementNotice.js';
7
7
  import { nativeMediaLimits } from './mediaLimits.js';
@@ -15,6 +15,7 @@ import { nativeOAuthBaseUrl } from './apiEndpoint.js';
15
15
  import { createHash } from 'node:crypto';
16
16
  import { ensureProjectStateIgnore } from '../../projectStateIgnore.js';
17
17
  import { replayEventsWithTs } from '../../workflowStore.js';
18
+ import { reportHistoryLoadFailure } from '../../providerConversation.js';
18
19
  import { computerToolDefinitions, executeComputerTool } from '../../voice/toolDefinitions.js';
19
20
  // Phase 7a — long-lived per-workflow Claude Native worker.
20
21
  //
@@ -55,7 +56,7 @@ import { getPeerToolDefinitions, isPeerTool, executePeerTool } from './peerTools
55
56
  import { registryToolDefs, parseRegistryToolName, isRegistryToolAllowed, isRegistryToolReadOnly } from './registryTools.js';
56
57
  import { connectServer } from '../../mcp/client.js';
57
58
  import { getSandboxToolDefinitions, isSandboxTool, executeSandboxTool } from './sandboxTools.js';
58
- import { buildMessagesFromReplayEvents, replayMessagesWithResumePolicy, compactSummarySeed } from './resumeSummary.js';
59
+ import { buildMessagesFromReplayEvents, replayMessagesWithResumePolicy, compactSummarySeed, NativeReconstructionLimitError } from './resumeSummary.js';
59
60
  import { readMeta, setResolvedModelId } from '../../workflowMeta.js';
60
61
  import { lspManager } from '../../lsp/client.js';
61
62
  import { isClaudeServerToolDef, isServerToolResultType, pendingServerTools, pruneServerToolEvidenceAfterTurn, stripDanglingServerToolResults } from './retainedContext.js';
@@ -1266,10 +1267,12 @@ export class ClaudeNativeWorker extends EventEmitter {
1266
1267
  .filter((e) => meta?.computerContext?.lastResetSeq !== undefined
1267
1268
  ? (('seq' in e.message && typeof e.message.seq === 'number') ? e.message.seq : 0) > meta.computerContext.lastResetSeq
1268
1269
  : e.ts > (meta?.computerContext?.lastResetAt ?? 0)).map((e) => e.message)),
1269
- mode: 'exact', reconstructed: false, summaryThroughSeq: undefined, tailEvents: undefined }
1270
+ mode: 'exact', reconstructed: false, summaryThroughSeq: undefined, tailEvents: undefined, summaryNotice: undefined }
1270
1271
  : await replayMessagesWithResumePolicy(cwd, this.workflowId, undefined, { leafSeq: meta?.leafSeq, attachmentMarkers });
1271
1272
  this.messages = attachmentMarkers ? await restoreChatAttachments(replay.messages, attachmentMarkers) : replay.messages;
1272
1273
  this.resetPrefixFreeze('replay');
1274
+ if (replay.summaryNotice)
1275
+ this.emit('system_notice', replay.summaryNotice);
1273
1276
  if (replay.reconstructed) {
1274
1277
  // docs/PERSISTENCE.md - the rewound branch's ancestry
1275
1278
  // had rotated off the size-capped log, so this is a RECONSTRUCTED
@@ -1287,6 +1290,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1287
1290
  }
1288
1291
  catch (err) {
1289
1292
  console.warn(`[claude-native:${this.workflowId.slice(0, 8)}] replay failed:`, err);
1293
+ reportHistoryLoadFailure(this.workflowId, this, 'native', content => this.emit('system_notice', content), err instanceof NativeReconstructionLimitError ? err.limitBytes : undefined);
1290
1294
  }
1291
1295
  }
1292
1296
  this.replayed = true;
@@ -1861,7 +1865,7 @@ export class ClaudeNativeWorker extends EventEmitter {
1861
1865
  'Continue working until the request is complete or you are genuinely blocked on operator input. ' +
1862
1866
  "Never end your turn with a status update, a plan, or a promise of future work ('Continuing now', 'I'll do X next') — " +
1863
1867
  'if your final paragraph describes work you have not done, do that work now instead of ending the turn. ' +
1864
- 'Finishing the request does not mean waiting for it: do not sleep or poll for more than 60 seconds at a time for builds, test suites or CI; report what is running and end the turn. ' +
1868
+ buildTurnWaitInstructions(this.config.clusterRole) + ' ' +
1865
1869
  'If a delegated Task child fails or returns an error or nonsense (e.g. a login error), say so explicitly in your reply and adapt openly — never silently work around a failed delegation. ' +
1866
1870
  // Fable 5.1 / 5.2 can rewrite whole files where a targeted edit would do
1867
1871
  // (docs/PROVIDERS.md); Anthropic's documented one-liner.
@@ -1,3 +1,4 @@
1
+ import { buildTurnWaitInstructions } from '@arco/shared';
1
2
  import { prepareProviderHistory } from './handoffHistoryBinding.js';
2
3
  import { prepareLocalFileContext, combineChatAttachments } from './localFileMedia.js';
3
4
  import { cliFileReadGuidance, prepareProviderAttachments } from './providerFileContent.js';
@@ -37,7 +38,7 @@ const APPEND_SP_TMPDIR = joinPath(tmpdir(), 'arco-prompts');
37
38
  // last (the order Claude Native uses). Each part is stable for the tab, so the
38
39
  // appended system prompt stays byte-identical from turn to turn.
39
40
  function effectiveAppendSystemPrompt(config) {
40
- const parts = [goalBlock(config.goal), config.appendSystemPrompt, cliFileReadGuidance(config), outputStyleAddendum(config.outputStyle)]
41
+ const parts = [buildTurnWaitInstructions(config.clusterRole), goalBlock(config.goal), config.appendSystemPrompt, cliFileReadGuidance(config), outputStyleAddendum(config.outputStyle)]
41
42
  .filter((s) => typeof s === 'string' && s.length > 0);
42
43
  return parts.length > 0 ? parts.join('\n\n') : undefined;
43
44
  }