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
@@ -0,0 +1,182 @@
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
+
8
+ export const TRANSCRIPT_WORKER_MAX_BYTES = 32 * 1024;
9
+ export const TRANSCRIPT_WORKER_PREFACE_BYTES = 4 * 1024;
10
+ interface Event {
11
+ type: string; seq?: number; parentEventSeq?: number; targetSeq?: number;
12
+ content?: string; text?: string; attachments?: string[];
13
+ tool?: string; toolUseId?: string; itemId?: string; input?: string; status?: string;
14
+ }
15
+ interface Part { role: 'USER' | 'AGENT'; text: string[]; kind: 'text' | 'receipt' }
16
+ interface Turn { limit: number; count?: (delta: number) => void; parts: Part[]; bytes: number; oversized: boolean; text?: Part; tools: Map<string, Part>; keys: string[]; legacy: Array<{ key: string; name: string; input: string }> }
17
+ export interface TranscriptSliceOptions {
18
+ turns: number; includePartial: boolean; preface: string;
19
+ cutoffSeq?: number; wasBusy: boolean;
20
+ }
21
+ // The retention estimate tolerates split surrogate pairs. The final encoded
22
+ // seed is measured exactly after joining deltas; nothing is clipped to fit.
23
+ const textBytes = (text: string) => Buffer.byteLength(text, 'utf8');
24
+ const newTurn = (limit: number, count: (delta: number) => void): Turn => ({ limit, count, parts: [], bytes: 0, oversized: false, tools: new Map(), keys: [], legacy: [] });
25
+ const countBytes = (turn: Turn, delta: number): void => { turn.bytes += delta; turn.count?.(delta); };
26
+
27
+ function add(turn: Turn, role: Part['role'], text: string, kind: Part['kind'], merge = false): Part | undefined {
28
+ if (turn.oversized) return;
29
+ let part = merge ? turn.text : undefined;
30
+ if (!part) {
31
+ part = { role, text: [], kind };
32
+ countBytes(turn, Buffer.byteLength(`${role}: ""\n`));
33
+ turn.parts.push(part);
34
+ }
35
+ part.text.push(text);
36
+ countBytes(turn, textBytes(text));
37
+ turn.text = merge ? part : undefined;
38
+ // Retain a bounded candidate ring, not every delta in a very large turn.
39
+ // Oversized selected turns are refused as a seed, never silently clipped.
40
+ if (turn.bytes > 2 * turn.limit) {
41
+ turn.oversized = true; turn.parts = []; turn.tools.clear(); turn.legacy = []; turn.text = undefined;
42
+ return;
43
+ }
44
+ return part;
45
+ }
46
+
47
+ export async function buildTranscriptWorkerSlice(cwd: string, workflowId: string, options: TranscriptSliceOptions) {
48
+ return buildTranscriptSlice(cwd, workflowId, options);
49
+ }
50
+
51
+ export interface TranscriptSelectionPolicy {
52
+ maxBytes: number;
53
+ fitWholeTurns: boolean;
54
+ allTurns?: boolean;
55
+ }
56
+ // Both new-worker copying and member replacement use this one turn/receipt
57
+ // reader. Replacement may fit a whole-turn suffix; new-worker copying keeps
58
+ // its original refusal instead of silently reducing the requested count.
59
+ export async function buildTranscriptSlice(cwd: string, workflowId: string, options: TranscriptSliceOptions, policy?: TranscriptSelectionPolicy) {
60
+ const maxBytes = policy?.maxBytes ?? TRANSCRIPT_WORKER_MAX_BYTES;
61
+ const fit = policy?.fitWholeTurns === true;
62
+ if (!Number.isInteger(options.turns) || options.turns < 1 || (!policy?.allTurns && options.turns > 50)) throw new Error('Choose from 1 to 50 turns.');
63
+ if (typeof options.preface !== 'string' || Buffer.byteLength(options.preface, 'utf8') > TRANSCRIPT_WORKER_PREFACE_BYTES) throw new Error('The preface must be at most 4 KiB.');
64
+ if (typeof options.includePartial !== 'boolean') throw new Error('Choose whether to include the current partial turn.');
65
+ const cutoffSeq = options.cutoffSeq ?? await getHeadSeq(cwd, workflowId);
66
+ const meta = await readMeta(cwd, workflowId).catch(() => null);
67
+ let branch: Set<number> | undefined;
68
+ if (typeof meta?.leafSeq === 'number') {
69
+ // A rewind needs ancestry, but not the old text/tool payloads. Reuse the
70
+ // established branch walk over lightweight links, then stream the slice.
71
+ const links: Array<{ type: string; seq?: number; parentEventSeq?: number; targetSeq?: number }> = [];
72
+ for await (const message of streamWorkflowEvents(cwd, workflowId)) {
73
+ const event = message as unknown as Event;
74
+ if ((event.seq ?? 0) > cutoffSeq) break;
75
+ links.push({ type: event.type, seq: event.seq, parentEventSeq: event.parentEventSeq, targetSeq: event.targetSeq });
76
+ }
77
+ const walked = walkBranchSeqs(links, links.at(-1)?.seq ?? meta.leafSeq);
78
+ if (walked.truncated) throw new Error('The source branch has missing ancestry. Its selected turns cannot be copied exactly.');
79
+ branch = walked.inScope;
80
+ }
81
+ const turns: Turn[] = [];
82
+ let retainedBytes = 0;
83
+ const dropOldest = () => {
84
+ const dropped = turns.shift()!;
85
+ retainedBytes -= dropped.bytes;
86
+ dropped.count = undefined;
87
+ for (const key of dropped.keys) toolOwners.set(key, null);
88
+ };
89
+ const toolOwners = new Map<string, Turn | null>();
90
+ let total = 0;
91
+ let structuralSeq = 0;
92
+ for await (const message of streamWorkflowEvents(cwd, workflowId)) {
93
+ const event = message as unknown as Event;
94
+ try {
95
+ const seq = event.seq ?? 0;
96
+ if (event.type === 'leaf_move' || event.type === 'conversation_changed') structuralSeq = seq;
97
+ if (seq > cutoffSeq || (branch && !branch.has(seq))) continue;
98
+ if (event.type === 'user_message_echo') {
99
+ total++;
100
+ const turn = newTurn(maxBytes, delta => retainedBytes += delta); turns.push(turn);
101
+ if (turns.length > options.turns + 1) dropOldest();
102
+ add(turn, 'USER', event.content ?? '', 'text');
103
+ for (const file of event.attachments ?? []) {
104
+ add(turn, 'USER', `[Attachment: ${basename(file)}; type: ${extname(file) || 'file'}; source: ${file}; receipt only, not copied]`, 'receipt');
105
+ }
106
+ continue;
107
+ }
108
+ let turn = turns.at(-1);
109
+ if (!turn) continue;
110
+ if (event.type === 'primary_tool_use') {
111
+ const stableKey = event.toolUseId ?? event.itemId;
112
+ if (stableKey) {
113
+ if (toolOwners.has(stableKey)) {
114
+ const owner = toolOwners.get(stableKey);
115
+ if (!owner) continue;
116
+ turn = owner;
117
+ } else { toolOwners.set(stableKey, turn); turn.keys.push(stableKey); }
118
+ }
119
+ }
120
+ if (turn.oversized) continue;
121
+ if (event.type === 'primary_text' && typeof event.text === 'string') add(turn, 'AGENT', event.text, 'text', true);
122
+ else if (event.type === 'primary_complete' || event.type === 'primary_turn_ended') turn.text = undefined;
123
+ else if (event.type === 'primary_tool_use') {
124
+ turn.text = undefined;
125
+ const fullName = (event.tool ?? 'tool').replace(/\s+/g, ' ');
126
+ const name = fullName.length > 120 ? fullName.slice(0, 117) + '...' : fullName;
127
+ const status = ['started', 'in_progress', 'completed', 'failed'].includes(event.status ?? '') ? event.status! : 'status unavailable';
128
+ let key = event.toolUseId ?? event.itemId;
129
+ if (!key) {
130
+ const input = createHash('sha256').update(event.input ?? '').digest('hex');
131
+ const pending = turn.legacy.find(tool => tool.name === name && (!event.input || tool.input === input));
132
+ key = status !== 'started' && status !== 'status unavailable' && pending ? pending.key : `legacy:${seq}`;
133
+ if (status === 'started') turn.legacy.push({ key, name, input });
134
+ if ((status === 'completed' || status === 'failed') && pending) turn.legacy = turn.legacy.filter(tool => tool !== pending);
135
+ }
136
+ const receipt = `[Tool: ${name}; ${status}; output omitted]`;
137
+ const existing = turn.tools.get(key);
138
+ if (existing) {
139
+ countBytes(turn, textBytes(receipt) - textBytes(existing.text.join('')));
140
+ existing.text = [receipt];
141
+ } else {
142
+ const part = add(turn, 'AGENT', receipt, 'receipt');
143
+ if (part) turn.tools.set(key, part);
144
+ }
145
+ }
146
+ } finally {
147
+ // Keep enough candidates for a suffix within the byte budget, including
148
+ // an oversized boundary turn so no middle turn is skipped to make room.
149
+ if (fit) while (turns.length > 1 && retainedBytes > 2 * maxBytes) dropOldest();
150
+ }
151
+ }
152
+ const partialIncluded = options.wasBusy && options.includePartial && total > 0;
153
+ const availableTurns = Math.max(0, total - (options.wasBusy && !options.includePartial ? 1 : 0));
154
+ const candidates = options.wasBusy && !options.includePartial ? turns.slice(0, -1) : turns;
155
+ let selected = candidates.slice(-options.turns);
156
+ const frame = (transcript: string): string => {
157
+ 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}`;
158
+ return (options.preface ? `${options.preface}\n\n` : '') + context;
159
+ };
160
+ const renderTurn = (turn: Turn) => turn.parts.map(part => `${part.role}: ${JSON.stringify(part.text.join(''))}`).join('\n');
161
+ if (fit) {
162
+ let bytes = textBytes(frame('')), count = 0;
163
+ for (let index = selected.length - 1; index >= 0; index--) {
164
+ const turn = selected[index];
165
+ if (turn.oversized) break;
166
+ const next = textBytes(renderTurn(turn)) + (count ? 1 : 0);
167
+ if (bytes + next > maxBytes) break;
168
+ bytes += next; count++;
169
+ }
170
+ selected = count ? selected.slice(-count) : [];
171
+ } else {
172
+ if (!selected.length) throw new Error('No completed turns are available. Include the current partial turn or wait for it to finish.');
173
+ if (selected.some(turn => turn.oversized)) throw new Error('The selected turns exceed the 32 KiB seed limit. Choose fewer turns.');
174
+ }
175
+ const transcript = selected.map(renderTurn).join('\n');
176
+ const seed = selected.length ? frame(transcript) : '';
177
+ const bytes = textBytes(seed);
178
+ if (bytes > maxBytes) throw new Error(`The seed is ${bytes} bytes; the limit is ${maxBytes}. Choose fewer turns or shorten the preface.`);
179
+ const branchKey = `${meta?.leafSeq ?? ''}:${structuralSeq}`;
180
+ const digest = createHash('sha256').update(JSON.stringify({ seed, availableTurns, cutoffSeq, branchKey })).digest('hex');
181
+ return { seed, bytes, availableTurns, selectedTurns: selected.length, partialIncluded, cutoffSeq, digest, branchKey };
182
+ }
@@ -581,6 +581,27 @@ function withEventTs(entry: { ts?: unknown; [k: string]: unknown }): { [k: strin
581
581
  return typeof ts === 'number' ? { ...rest, eventTs: ts } : rest;
582
582
  }
583
583
 
584
+ // Streaming consumers can retain their selected slice instead of materializing
585
+ // the whole history. Sequence repair, sealed copies and pending flushes are the
586
+ // same as the existing replay APIs.
587
+ export async function* streamWorkflowEvents(cwd: string, wfid: string): AsyncGenerator<ServerMessage> {
588
+ if (!cwd) return;
589
+ validateWfid(wfid);
590
+ const buf = buffers.get(bufferKey(cwd, wfid));
591
+ if (buf) {
592
+ if (buf.flushTimer) { clearTimeout(buf.flushTimer); buf.flushTimer = null; }
593
+ await flushBuffer(buf);
594
+ }
595
+ for await (const { line, step } of effectiveLines(workflowDir(cwd, wfid))) {
596
+ if (!step) continue;
597
+ let entry: { seq?: number; ts?: number; [key: string]: unknown };
598
+ try { entry = JSON.parse(line); } catch { continue; }
599
+ if (typeof entry.seq !== 'number') continue;
600
+ applyStep(entry, step);
601
+ yield withEventTs(entry) as unknown as ServerMessage;
602
+ }
603
+ }
604
+
584
605
  // Replay all events with seq > fromSeq, in seq order. Caller streams each
585
606
  // returned ServerMessage to the newly-connected WS (stamped seq included on
586
607
  // the wire object). Flushes pending first so the replay is head-current.
@@ -1,3 +1,5 @@
1
+ import { buildReplacementHistory, replacementHistoryNotice } from '../replacementHistory.js';
2
+ import { takeReplacementHistoryPreview } from './transcriptWorkerHandlers.js';
1
3
  import { existingClusterMemberRefusal } from '../existingClusterMembers.js';
2
4
  import { isClusterCreationSettings, isClusterMessageGuard, clusterDirectorProblem, isClusterDirector, normalizeClusterRoleText, presetForText } from '@arco/shared';
3
5
  import { disabledClusterProvider, localCapacityRefusal, memberProvider } from '../localCapacity.js';
@@ -7,6 +9,7 @@ import { disabledClusterProvider, localCapacityRefusal, memberProvider } from '.
7
9
  // createBlankNativeWorkflow / assertAllMembersClaudeOrCodex) are injected once at
8
10
  // startup via initClusterHandlers to avoid a cycle with the entry point.
9
11
  import { isClusterOpen, workspaceAdoptFormerMembers, workspaceCloseCluster, workspaceOpenCluster } from '../workspace.js';
12
+ import { assertSkillUnion } from '../clusterSkills.js';
10
13
  import {
11
14
  isClusterMemberProvider,
12
15
  isClusterMemberAccessMode,
@@ -39,7 +42,6 @@ import * as clusterRehydrate from '../clusterRehydrate.js';
39
42
  import * as clusterStore from '../clusterStore.js';
40
43
  import { refreshHubReporting } from '../management/initHubLink.js';
41
44
  import { replayEvents } from '../workflowStore.js';
42
- import { renderTranscript, summarizePriorTurns } from '../primitives/exportContext.js';
43
45
  import * as taskDispatcher from '../taskDispatcher.js';
44
46
  import * as taskLedger from '../project/taskLedger.js';
45
47
  import * as orchestrationProposals from '../project/orchestrationProposals.js';
@@ -1881,6 +1883,8 @@ export async function handleClusterAddFreshWorkers(
1881
1883
  model: msg.model, effort: msg.effort, accountRef: msg.providerAccountRef, isolated: accessMode === 'isolated', resolveCodexAccount,
1882
1884
  tuning: msg,
1883
1885
  });
1886
+ try { await assertSkillUnion(cluster, newRole || undefined, childConfig.pinnedSkills ?? [], childName); }
1887
+ catch (err) { send(ws, { type: 'error', message: `cluster_add_fresh_workers rejected: ${err instanceof Error ? err.message : String(err)}` }); return; }
1884
1888
  try {
1885
1889
  const id = await deps.createBlankNativeWorkflow(ws, session, childConfig, MEMBER_PENDING);
1886
1890
  newIds.push(id);
@@ -1928,8 +1932,6 @@ export async function handleClusterAddFreshWorkers(
1928
1932
  console.log(`[arco] cluster ${msg.clusterId.slice(0, 8)} grew by ${newIds.length} fresh workers`);
1929
1933
  }
1930
1934
 
1931
- const REPLACEMENT_HISTORY_MAX_BYTES = 512 * 1024;
1932
-
1933
1935
  // The name and role a REPLACE request carries, as a refusal code or null.
1934
1936
  function replaceIdentityRefusal(cluster: clusterStore.ClusterState, msg: import('@arco/shared').ClusterMemberReplaceMessage): string | null {
1935
1937
  if (msg.name !== undefined && (typeof msg.name !== 'string' || msg.name.trim().length > 64)) return 'invalid_name';
@@ -1964,7 +1966,9 @@ export async function handleClusterMemberReplace(
1964
1966
  send(ws, { type: 'error', message: 'cluster_member_replace rejected: invalid_access_mode' });
1965
1967
  return;
1966
1968
  }
1967
- if (accessMode === 'isolated' && (msg.includeHistory || msg.transferActiveTasks)) {
1969
+ const historyMode = msg.historyMode ?? (msg.includeHistory ? 'full' : 'none');
1970
+ if (!['none', 'recent', 'full'].includes(historyMode)) { send(ws, { type: 'error', message: 'cluster_member_replace rejected: invalid_history_mode' }); return; }
1971
+ if (accessMode === 'isolated' && (historyMode !== 'none' || msg.transferActiveTasks)) {
1968
1972
  send(ws, { type: 'error', message: 'cluster_member_replace rejected: isolated_requires_fresh_context_and_no_tasks' });
1969
1973
  return;
1970
1974
  }
@@ -2000,22 +2004,21 @@ export async function handleClusterMemberReplace(
2000
2004
  }
2001
2005
  }
2002
2006
 
2003
- let historySeed = '';
2004
- if (msg.includeHistory) {
2005
- const events = await replayEvents(cluster.cwd, msg.workflowId, 0).catch(() => []);
2006
- const transcript = renderTranscript(events).trim();
2007
- const actions = summarizePriorTurns(events).trim();
2008
- historySeed = [
2009
- '[REPLACEMENT CONTEXT — copied by explicit operator request; this is a new provider session]',
2010
- transcript,
2011
- actions ? `\n[Prior-turn action digest]\n${actions}` : '',
2012
- '\nAcknowledge this imported context briefly, then wait for the operator.',
2013
- ].filter(Boolean).join('\n\n');
2014
- if (Buffer.byteLength(historySeed, 'utf8') > REPLACEMENT_HISTORY_MAX_BYTES) {
2015
- send(ws, {
2016
- type: 'error',
2017
- message: `cluster_member_replace rejected: history_too_large (>${REPLACEMENT_HISTORY_MAX_BYTES} bytes)`,
2018
- });
2007
+ let historySeed = '', historyNotice: string | undefined;
2008
+ if (historyMode !== 'none') {
2009
+ const turns = msg.historyTurns ?? 10;
2010
+ try {
2011
+ if (!Number.isInteger(turns) || turns < 1 || turns > 50) throw new Error('Choose from 1 to 50 recent turns.');
2012
+ const preview = msg.historyToken
2013
+ ? await takeReplacementHistoryPreview(ws, msg.clusterId, msg.workflowId, historyMode, turns, msg.historyToken)
2014
+ : msg.historyMode !== undefined
2015
+ ? (() => { throw new Error('Preview the history before replacing this member.'); })()
2016
+ : await buildReplacementHistory(cluster.cwd, msg.workflowId, 'full', { turns, includePartial: false, preface: '', wasBusy: false });
2017
+ historySeed = preview.seed;
2018
+ historyNotice = replacementHistoryNotice(preview);
2019
+ if (source.busy) throw new Error('The member started working. Wait for it to finish and refresh the preview.');
2020
+ } catch (err) {
2021
+ send(ws, { type: 'error', message: `cluster_member_replace rejected: ${err instanceof Error ? err.message : String(err)}` });
2019
2022
  return;
2020
2023
  }
2021
2024
  }
@@ -2025,6 +2028,8 @@ export async function handleClusterMemberReplace(
2025
2028
  model: msg.model, effort: msg.effort, accountRef: msg.providerAccountRef, isolated: accessMode === 'isolated', resolveCodexAccount,
2026
2029
  tuning: msg,
2027
2030
  });
2031
+ try { await assertSkillUnion(cluster, msg.role ?? clusterStore.getMemberRole(msg.clusterId, msg.workflowId), childConfig.pinnedSkills ?? [], childConfig.name ?? 'Replacement'); }
2032
+ catch (err) { send(ws, { type: 'error', message: `cluster_member_replace rejected: ${err instanceof Error ? err.message : String(err)}` }); return; }
2028
2033
 
2029
2034
  let newWorkflowId: string;
2030
2035
  try {
@@ -2034,11 +2039,12 @@ export async function handleClusterMemberReplace(
2034
2039
  msg.workflowId,
2035
2040
  newWorkflowId,
2036
2041
  accessMode,
2042
+ msg.role,
2037
2043
  );
2038
2044
  if (!replaced) throw new Error('atomic_replace_failed');
2039
2045
  // The slot's role, tier and focus moved with the replacement; the
2040
- // request's own values win. Checked above, so these cannot refuse.
2041
- if (msg.role !== undefined) await clusterStore.setMemberRole(msg.clusterId, newWorkflowId, msg.role);
2046
+ // request's own values win. Role and skill limits were applied atomically
2047
+ // with replacement; the tier/focus values were checked above.
2042
2048
  if (msg.tier !== undefined) await clusterStore.setMemberTier(msg.clusterId, newWorkflowId, msg.tier);
2043
2049
  if (msg.focus !== undefined) await clusterStore.setMemberFocus(msg.clusterId, newWorkflowId, msg.focus);
2044
2050
  } catch (err) {
@@ -2095,7 +2101,7 @@ export async function handleClusterMemberReplace(
2095
2101
  oldWorkflowId: msg.workflowId,
2096
2102
  newWorkflowId,
2097
2103
  accessMode,
2098
- historyIncluded: !!msg.includeHistory,
2104
+ historyIncluded: !!historySeed,
2099
2105
  transferredTaskCount,
2100
2106
  member: {
2101
2107
  workflowId: newWorkflowId,
@@ -2116,6 +2122,7 @@ export async function handleClusterMemberReplace(
2116
2122
  const payload = await buildClusterStatePayload(msg.clusterId);
2117
2123
  if (payload) broadcastCluster(msg.clusterId, { type: 'cluster_state', clusterId: msg.clusterId, state: payload });
2118
2124
 
2125
+ if (historyNotice) broadcastWorkflow(newWorkflowId, { type: 'system_notice', workflowId: newWorkflowId, content: historyNotice });
2119
2126
  if (historySeed) {
2120
2127
  await deps.handleUserMessage(
2121
2128
  ws,
@@ -2256,8 +2263,8 @@ export async function handleClusterMemberRoleSet(ws: WebSocket, clusterId: strin
2256
2263
  try {
2257
2264
  updated = await clusterStore.setMemberRole(clusterId, workflowId, role);
2258
2265
  } catch (err) {
2259
- if (err instanceof clusterStore.ClusterValidationError && err.code === 'multiple_directors') {
2260
- send(ws, { type: 'error', message: `cluster_member_role_set rejected: multiple_directors: ${err.message}` });
2266
+ if (err instanceof clusterStore.ClusterValidationError) {
2267
+ send(ws, { type: 'error', message: `cluster_member_role_set rejected: ${err.code}: ${err.message}` });
2261
2268
  return;
2262
2269
  }
2263
2270
  throw err;
@@ -2396,6 +2403,17 @@ export async function handleClusterEfficiencySet(
2396
2403
  console.log(`[arco] cluster ${clusterId.slice(0, 8)} efficiency → ${level}${addendum !== undefined ? ' (addendum updated)' : ''}`);
2397
2404
  }
2398
2405
 
2406
+ export async function handleClusterSkillsSet(ws: WebSocket, clusterId: string, pins: unknown): Promise<void> {
2407
+ try {
2408
+ const updated = await clusterStore.setSkillPins(clusterId, pins);
2409
+ if (!updated) throw new Error('Unknown cluster.');
2410
+ const payload = await buildClusterStatePayload(clusterId);
2411
+ if (payload) broadcastCluster(clusterId, { type: 'cluster_state', clusterId, state: payload });
2412
+ } catch (err) {
2413
+ send(ws, { type: 'error', message: `Cluster skills: ${err instanceof Error ? err.message : String(err)}` });
2414
+ }
2415
+ }
2416
+
2399
2417
  // R3 (docs/REMOTE_MANAGEMENT.md) - operator flipped the cluster-level
2400
2418
  // ◉ REMOTE chip. Persist, rebroadcast cluster_state, and re-push the hub
2401
2419
  // snapshot immediately so the phone console reflects the flip without waiting
@@ -2517,14 +2535,15 @@ export async function handleClusterAutoTurnToggle(
2517
2535
  // Operator chose an AUTO-PICKUP mode in the cluster dialog. Smart modes need
2518
2536
  // an evaluator from an enabled provider and start a new session; Off and
2519
2537
  // Rule-based end any Smart session. Pushes cluster_state on success.
2538
+ // A pause-only request keeps the current mode, session and budgets.
2520
2539
  export async function handleClusterAutoPickupSet(
2521
2540
  ws: WebSocket,
2522
- msg: { clusterId: string; mode: unknown; evaluator?: unknown; limits?: unknown; ruleLimits?: unknown; resumeRule?: boolean; remindBusy?: boolean },
2541
+ msg: { clusterId: string; mode: unknown; paused?: unknown; evaluator?: unknown; limits?: unknown; ruleLimits?: unknown; resumeRule?: boolean; remindBusy?: boolean },
2523
2542
  ): Promise<void> {
2524
2543
  const settings = await readSettings().catch(() => null);
2525
2544
  const result = await applyAutoPickup(
2526
2545
  msg.clusterId,
2527
- { mode: msg.mode, evaluator: msg.evaluator, limits: msg.limits, ruleLimits: msg.ruleLimits, resumeRule: msg.resumeRule },
2546
+ { mode: msg.mode, paused: msg.paused, evaluator: msg.evaluator, limits: msg.limits, ruleLimits: msg.ruleLimits, resumeRule: msg.resumeRule },
2528
2547
  (provider) => settings?.enabledProviders?.[provider] !== false,
2529
2548
  );
2530
2549
  if (!result.ok) {
@@ -62,6 +62,7 @@ import {
62
62
  } from '../server/broadcast.js';
63
63
  import {
64
64
  buildLocalClusterSystemPrompt,
65
+ withLocalTurnWaitInstructions,
65
66
  LLAMACPP_PRIMARY_SYSTEM_PROMPT,
66
67
  OLLAMA_PRIMARY_SYSTEM_PROMPT,
67
68
  withPreviewNudge,
@@ -598,11 +599,14 @@ export async function handleHandoffRequest(
598
599
  );
599
600
  }
600
601
  const prewarmIsLocal = wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek');
601
- const prewarmLocalBase = wf.primary.provider === 'ollama'
602
+ const prewarmLocalBaseline = wf.primary.provider === 'ollama'
602
603
  ? OLLAMA_PRIMARY_SYSTEM_PROMPT
603
604
  : (wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek'))
604
605
  ? LLAMACPP_PRIMARY_SYSTEM_PROMPT
605
606
  : undefined;
607
+ const prewarmLocalBase = prewarmIsLocal
608
+ ? withLocalTurnWaitInstructions(prewarmLocalBaseline, prewarmClusterRole)
609
+ : undefined;
606
610
  const prewarmSystemPrompt = prewarmIsLocal && prewarmClusterId
607
611
  ? buildLocalClusterSystemPrompt({
608
612
  base: prewarmLocalBase,
@@ -0,0 +1,126 @@
1
+ import * as clusterStore from '../clusterStore.js';
2
+ import { buildReplacementHistory } from '../replacementHistory.js';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { isAbsolute } from 'node:path';
5
+ import type WebSocket from 'ws';
6
+ import type { TranscriptWorkerCreateMessage, TranscriptWorkerPreviewMessage, WorkflowConfig } from '@arco/shared';
7
+ import type { Session } from '../workflows/types.js';
8
+ import { send } from '../server/broadcast.js';
9
+ import { workflows } from '../server/state.js';
10
+ import { safeDirectory } from '../fileAccessPolicy.js';
11
+ import { readSettings } from '../settings.js';
12
+ import { isKnownProvider } from '../providers/index.js';
13
+ import { configuredAccounts } from '../providerAccounts.js';
14
+ import { buildTranscriptWorkerSlice, type TranscriptSliceOptions } from '../transcriptWorker.js';
15
+ import { TERMINAL_CODEX_ACCOUNT } from '@arco/shared';
16
+
17
+ interface Dependencies {
18
+ create(ws: WebSocket, session: Session, config: WorkflowConfig): Promise<string>;
19
+ seed(ws: WebSocket, session: Session, workflowId: string, content: string): void;
20
+ }
21
+ let deps: Dependencies;
22
+ export function initTranscriptWorkerHandlers(value: Dependencies): void { deps = value; }
23
+ type Slice = Awaited<ReturnType<typeof buildTranscriptWorkerSlice>> | Awaited<ReturnType<typeof buildReplacementHistory>>;
24
+ interface Snapshot { replacement?: { clusterId: string; mode: 'recent' | 'full' }; claimed?: boolean; owner: WebSocket; source: string; cwd: string; options: TranscriptSliceOptions; slice: Slice; expires: number; created?: string; creating?: Promise<string> }
25
+ const snapshots = new Map<string, Snapshot>();
26
+ function prune(): void {
27
+ for (const [token, entry] of snapshots) if (entry.expires < Date.now() && !entry.creating) snapshots.delete(token);
28
+ while (snapshots.size >= 32) {
29
+ const oldest = [...snapshots].find(([, entry]) => !entry.creating);
30
+ if (!oldest) throw new Error('Transcript previews are busy. Try again when a request finishes.');
31
+ snapshots.delete(oldest[0]);
32
+ }
33
+ }
34
+ function sourceFor(workflowId: string) {
35
+ const source = workflows.get(workflowId);
36
+ if (!source || source.config.kind === 'chat' || source.config.kind === 'cluster' || source.config.incognito || !source.config.workingDirectory) throw new Error('Choose an available Agent conversation as the source.');
37
+ return source;
38
+ }
39
+
40
+ export async function handleTranscriptWorkerPreview(ws: WebSocket, message: TranscriptWorkerPreviewMessage): Promise<void> {
41
+ try {
42
+ prune();
43
+ const source = sourceFor(message.workflowId);
44
+ const options: TranscriptSliceOptions = { turns: message.turns, includePartial: message.includePartial, preface: message.preface, wasBusy: source.busy };
45
+ let cwd = source.config.workingDirectory;
46
+ if (message.replacement) {
47
+ const cluster = await clusterStore.readCluster(message.replacement.clusterId);
48
+ if (!cluster?.members.includes(message.workflowId)) throw new Error('Choose an available cluster member.');
49
+ if (source.busy) throw new Error('Wait for the member to finish before replacing it.');
50
+ if (!['recent', 'full'].includes(message.replacement.mode)) throw new Error('Choose a valid history mode.');
51
+ cwd = cluster.cwd;
52
+ options.includePartial = false; options.preface = ''; options.wasBusy = false;
53
+ }
54
+ const slice = message.replacement
55
+ ? await buildReplacementHistory(cwd, message.workflowId, message.replacement.mode, options)
56
+ : await buildTranscriptWorkerSlice(cwd, message.workflowId, options);
57
+ const token = randomUUID();
58
+ snapshots.set(token, { replacement: message.replacement, owner: ws, source: message.workflowId, cwd, options: { ...options, cutoffSeq: slice.cutoffSeq }, slice, expires: Date.now() + 10 * 60_000 });
59
+ const { digest: _digest, branchKey: _branch, ...preview } = slice;
60
+ send(ws, { type: 'transcript_worker_result', requestId: message.requestId, preview: { ...preview, token } });
61
+ } catch (error) {
62
+ send(ws, { type: 'transcript_worker_result', requestId: message.requestId, error: error instanceof Error ? error.message : String(error) });
63
+ }
64
+ }
65
+
66
+ async function destinationConfig(message: TranscriptWorkerCreateMessage): Promise<WorkflowConfig> {
67
+ const target = message.destination;
68
+ if (!target || typeof target.workingDirectory !== 'string' || !isAbsolute(target.workingDirectory)) throw new Error('Choose an existing absolute working directory for the new worker.');
69
+ let workingDirectory: string;
70
+ try { workingDirectory = safeDirectory(target.workingDirectory); }
71
+ catch { throw new Error('The destination folder is unavailable or protected. Choose another existing folder.'); }
72
+ if (!isKnownProvider(target.provider) || typeof target.model !== 'string' || !target.model.trim()) throw new Error('Choose a supported provider and model.');
73
+ if (!['none', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(target.effort)) throw new Error('Choose a valid effort.');
74
+ if (target.skipPermissions !== undefined && typeof target.skipPermissions !== 'boolean') throw new Error('Choose the new worker permission setting.');
75
+ const settings = await readSettings(workingDirectory);
76
+ if (settings.enabledProviders?.[target.provider] === false) throw new Error('That provider is turned off. Enable it or choose another provider.');
77
+ if (target.providerAccountRef && !(target.provider === 'codex' && target.providerAccountRef === TERMINAL_CODEX_ACCOUNT)) {
78
+ if (target.provider !== 'codex' || !(await configuredAccounts('codex', workingDirectory)).some(account => account.id === target.providerAccountRef)) throw new Error('Choose an available account for the new worker.');
79
+ }
80
+ return { kind: 'workflow', name: typeof target.name === 'string' && target.name.trim() ? target.name.trim().slice(0, 120) : 'Transcript worker', workingDirectory,
81
+ primaryProvider: target.provider, primaryModel: target.model.trim(), primaryEffort: target.effort,
82
+ ...(target.provider === 'codex' && target.providerAccountRef ? { providerAccountRef: target.providerAccountRef } : {}), skipPermissions: target.skipPermissions === true };
83
+ }
84
+
85
+ export async function handleTranscriptWorkerCreate(ws: WebSocket, session: Session, message: TranscriptWorkerCreateMessage): Promise<void> {
86
+ try {
87
+ const entry = snapshots.get(message.token);
88
+ if (!entry || entry.owner !== ws || entry.replacement || entry.expires < Date.now()) throw new Error('The preview expired or disconnected. Refresh the preview before sending.');
89
+ if (!entry.created && !entry.creating) {
90
+ entry.creating = (async () => {
91
+ const source = sourceFor(entry.source);
92
+ if (source.config.workingDirectory !== entry.cwd) throw new Error('The source folder changed. Refresh the preview.');
93
+ const current = await buildTranscriptWorkerSlice(entry.cwd, entry.source, entry.options);
94
+ if (current.digest !== entry.slice.digest) throw new Error('The source history changed or was rewound. Refresh the preview.');
95
+ const config = await destinationConfig(message);
96
+ const id = await deps.create(ws, session, config);
97
+ entry.created = id;
98
+ deps.seed(ws, session, id, entry.slice.seed);
99
+ return id;
100
+ })();
101
+ }
102
+ const id = entry.created ?? await entry.creating!;
103
+ entry.creating = undefined;
104
+ send(ws, { type: 'transcript_worker_result', requestId: message.requestId, newWorkflowId: id });
105
+ } catch (error) {
106
+ const entry = snapshots.get(message.token);
107
+ if (entry && !entry.created) entry.creating = undefined;
108
+ send(ws, { type: 'transcript_worker_result', requestId: message.requestId, error: error instanceof Error ? error.message : String(error) });
109
+ }
110
+ }
111
+
112
+
113
+ // REPLACE consumes the same socket-bound, fixed-cutoff preview as NEW WORKER.
114
+ // Claim after checking again so a repeated submit cannot allocate two members.
115
+ export async function takeReplacementHistoryPreview(ws: WebSocket, clusterId: string, workflowId: string, mode: 'recent' | 'full', turns: number, token: string) {
116
+ const entry = snapshots.get(token);
117
+ if (!entry || entry.owner !== ws || entry.expires < Date.now() || entry.source !== workflowId
118
+ || entry.replacement?.clusterId !== clusterId || entry.replacement.mode !== mode || entry.options.turns !== turns) {
119
+ throw new Error('The history preview expired or changed. Refresh it before replacing.');
120
+ }
121
+ const current = await buildReplacementHistory(entry.cwd, workflowId, mode, entry.options);
122
+ if (current.digest !== entry.slice.digest) throw new Error('The source history changed or was rewound. Refresh the preview.');
123
+ if (entry.claimed) throw new Error('This history preview was already used. Refresh it before replacing again.');
124
+ entry.claimed = true;
125
+ return current;
126
+ }
@@ -1,4 +1,5 @@
1
- import { ensureWorkflowMetadata, providerConversationState, saveProviderSession, announceReplacementConversation, markConversationReading } from '../providerConversation.js';
1
+ import { resolveWorkflowSkillPins } from '../clusterSkills.js';
2
+ import { ensureWorkflowMetadata, providerConversationState, saveProviderSession, announceReplacementConversation, markConversationReading, reportHistoryLoadFailure } from '../providerConversation.js';
2
3
  import { mintHandoffHistoryCapability } from '../http/handoffHistoryRoutes.js';
3
4
  import { deliverAfterTurnRevoked } from './taskLifecycle.js';
4
5
  import { resolveClaudeTransport } from '../claudeTransport.js';
@@ -82,6 +83,7 @@ SESSION_HISTORY_PAGE_SIZE
82
83
  } from '../server/constants.js';
83
84
  import {
84
85
  buildLocalClusterSystemPrompt,
86
+ withLocalTurnWaitInstructions,
85
87
  LLAMACPP_PRIMARY_SYSTEM_PROMPT,
86
88
  OLLAMA_PRIMARY_SYSTEM_PROMPT,
87
89
  withPreviewNudge
@@ -103,7 +105,6 @@ readSettings
103
105
  import {
104
106
  buildPickedSkillsBlock,
105
107
  buildPinnedSkillsBlock,
106
- resolvePinnedSkills,
107
108
  buildSkillsManifest,
108
109
  listSkills,
109
110
  readSkillBody,
@@ -310,9 +311,15 @@ export function startSessionWatcher(workflowId: string, wf: WorkflowState, cwd:
310
311
  const current = () => workflows.get(workflowId) === wf && wf.primarySessionId === sessionId
311
312
  && sessionWatcherEpochs.get(wf) === epoch && wf.primary.provider === 'claude';
312
313
  const path = resolveSessionJsonlPath(cwd, sessionId);
313
- resolveClaudeTransport(wf, cwd).then((transport) => {
314
+ resolveClaudeTransport(wf, cwd).then(async (transport) => {
314
315
  if (!current() || transport === 'native') return null;
315
- return loadSessionJsonl(path);
316
+ try { return await loadSessionJsonl(path); }
317
+ catch (err) {
318
+ console.error(`[arco] [${workflowId.slice(0, 8)}] session history load failed:`, err);
319
+ if (!current()) return null;
320
+ reportHistoryLoadFailure(workflowId, wf, 'cli');
321
+ return { entries: [] as SessionJsonlEntry[], byteLength: null };
322
+ }
316
323
  }).then((loaded) => {
317
324
  if (!loaded || !current()) return;
318
325
  const { entries, byteLength } = loaded;
@@ -381,7 +388,7 @@ export function startSessionWatcher(workflowId: string, wf: WorkflowState, cwd:
381
388
  } else {
382
389
  dispose(); // workflow gone — clean up immediately
383
390
  }
384
- console.log(`[arco] [${workflowId.slice(0, 8)}] session watcher started (${tail.length} emitted / ${earlier.length} deferred / ${entries.length} total, ${byteLength}B)`);
391
+ console.log(`[arco] [${workflowId.slice(0, 8)}] session watcher started (${tail.length} emitted / ${earlier.length} deferred / ${entries.length} total, ${byteLength === null ? 'offset pending' : `${byteLength}B`})`);
385
392
  }).catch((err) => {
386
393
  console.error(`[arco] [${workflowId.slice(0, 8)}] session watcher init failed:`, err);
387
394
  });
@@ -1839,8 +1846,9 @@ export async function handleUserMessage(
1839
1846
  // pick, a project pin is an explicit operator vouch and bypasses discovery's
1840
1847
  // project-trust suppression. Missing files fail safe and stay visible.
1841
1848
  let pinnedSkillsBlock = '';
1842
- if (projectContextEnabled && wf.config.pinnedSkills?.length) {
1843
- const resolved = await resolvePinnedSkills(wf.config.pinnedSkills, cwd);
1849
+ const effectivePins = projectContextEnabled ? await resolveWorkflowSkillPins(workflowId, cwd, wf.config.pinnedSkills ?? []) : undefined;
1850
+ if (effectivePins?.refs.length) {
1851
+ const { resolved } = effectivePins;
1844
1852
  const built = buildPinnedSkillsBlock(resolved.skills);
1845
1853
  pinnedSkillsBlock = built.text;
1846
1854
  const skipped = [...resolved.missing, ...resolved.truncated];
@@ -2045,7 +2053,7 @@ export async function handleUserMessage(
2045
2053
  const catalog = await listSkills(cwd, { includeProject });
2046
2054
  // A pinned body is already present in full; omit its progressive-
2047
2055
  // disclosure metadata to avoid duplicate/conflicting instructions.
2048
- const pinnedKeys = new Set((wf.config.pinnedSkills ?? []).map((s) => `${s.scope}:${s.slug}`));
2056
+ const pinnedKeys = new Set((effectivePins?.refs ?? []).map((s) => `${s.scope}:${s.slug}`));
2049
2057
  primarySkillsManifest = buildSkillsManifest({
2050
2058
  project: catalog.project.filter((s) => !pinnedKeys.has(`project:${s.slug}`)),
2051
2059
  global: catalog.global.filter((s) => !pinnedKeys.has(`global:${s.slug}`)),
@@ -2299,6 +2307,10 @@ export async function handleUserMessage(
2299
2307
  );
2300
2308
  }
2301
2309
 
2310
+ if (!chatMode && (wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek')) {
2311
+ finalSystemPrompt = withLocalTurnWaitInstructions(finalSystemPrompt, turnClusterRole);
2312
+ }
2313
+
2302
2314
  if (turnClusterId && (wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek')) {
2303
2315
  if (clusterAccessMode === 'standard') {
2304
2316
  finalSystemPrompt = buildLocalClusterSystemPrompt({