arco-workbench 0.1.7 → 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.
- package/CONTRIBUTING.md +52 -12
- package/README.md +14 -12
- package/client/dist/assets/{PhosphorBackdrop-DVQdBrTw.js → PhosphorBackdrop-D7jdAV_G.js} +1 -1
- package/client/dist/assets/{ThemedBackgroundShaderImpl-BfSs2tB4.js → ThemedBackgroundShaderImpl-DrDm60h8.js} +1 -1
- package/client/dist/assets/{XtermView-DaMjC8Ny.js → XtermView-BGFujb1e.js} +1 -1
- package/client/dist/assets/{galleryEditor-BCQnXj7R.js → galleryEditor-D951A2sE.js} +1 -1
- package/client/dist/assets/{index-COfbHCYv.js → index-CsVy3eZm.js} +246 -246
- package/client/dist/index.html +1 -1
- package/client/src/components/ClusterRightPanel/ReplaceMemberDialog.tsx +65 -15
- package/client/src/components/ClusterRightPanel/SkillsControl.tsx +107 -0
- package/client/src/components/ClusterRightPanel/index.tsx +4 -0
- package/client/src/components/ClusterTaskBoardTab.tsx +9 -22
- package/client/src/components/NeedsYouBadge.tsx +3 -3
- package/client/src/components/ProviderReleasesModal.tsx +8 -4
- package/client/src/components/ProvidersPopover.tsx +28 -23
- package/client/src/components/SettingsPanel.tsx +2 -2
- package/client/src/components/SkillsSettings.tsx +5 -0
- package/client/src/components/TabBar.tsx +91 -9
- package/client/src/components/TerminalInput.tsx +12 -10
- package/client/src/components/TranscriptSendDialog.tsx +12 -8
- package/client/src/components/TranscriptWorkerDialog.tsx +119 -0
- package/client/src/components/clusterNeedsYou.ts +11 -18
- package/client/src/help/content/cluster.tsx +38 -17
- package/client/src/help/content/composer.tsx +22 -0
- package/client/src/help/content/header.tsx +16 -0
- package/client/src/help/content/misc.tsx +8 -0
- package/client/src/help/content/settings.tsx +18 -4
- package/client/src/help/content/tabbar.tsx +5 -0
- package/client/src/help/manualSections/actions.tsx +31 -0
- package/client/src/help/manualSections/clusters.tsx +41 -20
- package/client/src/help/manualSections/configuration.tsx +18 -0
- package/client/src/help/manualSections/maintenance.tsx +18 -0
- package/client/src/help/manualSections/providers.tsx +32 -8
- package/client/src/help/manualSections/troubleshooting.tsx +2 -1
- package/client/src/help/manualSections/workflows.tsx +12 -0
- package/client/src/help/manualSections/workspace.tsx +6 -0
- package/client/src/utils/transcriptWorkerRequest.ts +24 -0
- package/client/src/ws/handleServerMessage.ts +8 -2
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CLIENT.md +9 -8
- package/docs/FEATURES.md +8 -5
- package/docs/GETTING_STARTED.md +4 -3
- package/docs/GOTCHAS.md +2 -1
- package/docs/OPERATIONS.md +14 -4
- package/docs/PERSISTENCE.md +7 -2
- package/docs/PRIMITIVES.md +42 -0
- package/docs/PROTOCOL_CLUSTER.md +42 -3
- package/docs/PROTOCOL_PRIMITIVES.md +39 -0
- package/docs/PROVIDERS.md +50 -13
- package/docs/SETTINGS.md +27 -3
- package/docs/TASK_LEDGER.md +7 -15
- package/native/darwin-arm64/manifest.json +1 -1
- package/node_modules/@arco/shared/dist/clusterCoordination.d.ts +2 -0
- package/node_modules/@arco/shared/dist/clusterCoordination.js +5 -1
- package/node_modules/@arco/shared/dist/protocol/clientMessages.d.ts +3 -2
- package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +13 -1
- package/node_modules/@arco/shared/dist/protocol/index.d.ts +1 -0
- package/node_modules/@arco/shared/dist/protocol/index.js +1 -0
- package/node_modules/@arco/shared/dist/protocol/models.d.ts +4 -3
- package/node_modules/@arco/shared/dist/protocol/models.js +26 -2
- package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +2 -1
- package/node_modules/@arco/shared/dist/protocol/tasks.d.ts +4 -0
- package/node_modules/@arco/shared/dist/protocol/transcriptWorker.d.ts +47 -0
- package/node_modules/@arco/shared/dist/protocol/transcriptWorker.js +2 -0
- package/node_modules/@arco/shared/dist/runtimeVersions.d.ts +1 -0
- package/node_modules/@arco/shared/dist/runtimeVersions.js +14 -0
- package/node_modules/@arco/shared/package.json +1 -1
- package/package.json +2 -2
- package/scripts/packaging/arco.mjs +1 -1
- package/scripts/packaging/native-repair.mjs +32 -4
- package/server/dist/atomicFile.js +1 -2
- package/server/dist/capabilities.d.ts +5 -2
- package/server/dist/capabilities.js +59 -9
- package/server/dist/cliUpdateDecision.d.ts +1 -1
- package/server/dist/cliUpdateDecision.js +5 -3
- package/server/dist/clusterDirector.js +1 -1
- package/server/dist/clusterPeerOps.js +10 -7
- package/server/dist/clusterProgress.js +1 -1
- package/server/dist/clusterSkills.d.ts +13 -0
- package/server/dist/clusterSkills.js +81 -0
- package/server/dist/clusterSnapshots.js +2 -0
- package/server/dist/clusterStore.d.ts +7 -2
- package/server/dist/clusterStore.js +42 -1
- package/server/dist/diagnostics/codeSkew.js +1 -0
- package/server/dist/eventLog.d.ts +7 -0
- package/server/dist/eventLog.js +70 -13
- package/server/dist/historyLimits.d.ts +1 -0
- package/server/dist/historyLimits.js +3 -0
- package/server/dist/http/router.js +1 -1
- package/server/dist/index.js +24 -1
- package/server/dist/jsonlLines.d.ts +4 -0
- package/server/dist/jsonlLines.js +53 -0
- package/server/dist/management/identity.js +1 -0
- package/server/dist/mcp/clusterMcpTools.js +4 -4
- package/server/dist/project/taskLedger.d.ts +4 -0
- package/server/dist/project/taskLedger.js +7 -4
- package/server/dist/providerConversation.d.ts +1 -0
- package/server/dist/providerConversation.js +17 -0
- package/server/dist/providers/claude-native/resumeSummary.d.ts +9 -0
- package/server/dist/providers/claude-native/resumeSummary.js +102 -49
- package/server/dist/providers/claude-native/worker.js +8 -4
- package/server/dist/providers/claude.js +2 -1
- package/server/dist/providers/clusterTaskToolDefinitions.js +4 -4
- package/server/dist/providers/codex-appserver/catalog.js +16 -1
- package/server/dist/providers/codex.js +2 -1
- package/server/dist/providers/codexCodeMode.d.ts +1 -1
- package/server/dist/providers/codexCodeMode.js +4 -3
- package/server/dist/providers/cursor/print.js +2 -1
- package/server/dist/providers/cursor/worker.js +2 -1
- package/server/dist/providers/llamacpp.js +17 -8
- package/server/dist/providers/ollamaRecovery.js +6 -6
- package/server/dist/providers/ollamaResilience.js +3 -3
- package/server/dist/providers/ollamaTokens.js +1 -1
- package/server/dist/quota.d.ts +0 -18
- package/server/dist/quota.js +0 -44
- package/server/dist/replacementHistory.d.ts +19 -0
- package/server/dist/replacementHistory.js +49 -0
- package/server/dist/server/broadcast.d.ts +2 -1
- package/server/dist/server/broadcast.js +1 -0
- package/server/dist/server/prompts.d.ts +1 -0
- package/server/dist/server/prompts.js +6 -1
- package/server/dist/sessionJsonl.d.ts +1 -1
- package/server/dist/sessionJsonl.js +115 -40
- package/server/dist/smartPickupAdapters.js +15 -2
- package/server/dist/transcriptWorker.d.ts +34 -0
- package/server/dist/transcriptWorker.js +201 -0
- package/server/dist/workflowStore.d.ts +1 -0
- package/server/dist/workflowStore.js +31 -0
- package/server/dist/ws/clusterHandlers.d.ts +1 -0
- package/server/dist/ws/clusterHandlers.js +62 -26
- package/server/dist/ws/handoffHandlers.js +5 -2
- package/server/dist/ws/transcriptWorkerHandlers.d.ts +25 -0
- package/server/dist/ws/transcriptWorkerHandlers.js +139 -0
- package/server/dist/ws/turnEngine.js +23 -9
- package/server/dist/ws/updatePrimaryConfig.js +27 -8
- package/server/dist/ws/workflowHandlers.d.ts +4 -1
- package/server/dist/ws/workflowHandlers.js +3 -1
- package/server/package.json +1 -1
- package/server/src/atomicFile.ts +1 -2
- package/server/src/capabilities.ts +58 -17
- package/server/src/cliUpdateDecision.ts +5 -4
- package/server/src/clusterDirector.ts +1 -1
- package/server/src/clusterPeerOps.ts +11 -8
- package/server/src/clusterProgress.ts +1 -1
- package/server/src/clusterSkills.ts +79 -0
- package/server/src/clusterSnapshots.ts +1 -0
- package/server/src/clusterStore.ts +38 -0
- package/server/src/diagnostics/codeSkew.ts +1 -0
- package/server/src/eventLog.ts +73 -13
- package/server/src/historyLimits.ts +2 -0
- package/server/src/http/router.ts +1 -1
- package/server/src/index.ts +23 -0
- package/server/src/jsonlLines.ts +52 -0
- package/server/src/management/identity.ts +1 -0
- package/server/src/mcp/clusterMcpTools.ts +4 -4
- package/server/src/project/taskLedger.ts +7 -5
- package/server/src/providerConversation.ts +15 -0
- package/server/src/providers/claude-native/resumeSummary.ts +98 -50
- package/server/src/providers/claude-native/worker.ts +8 -4
- package/server/src/providers/claude.ts +2 -1
- package/server/src/providers/clusterTaskToolDefinitions.ts +4 -4
- package/server/src/providers/codex-appserver/catalog.ts +14 -1
- package/server/src/providers/codex.ts +2 -1
- package/server/src/providers/codexCodeMode.ts +4 -4
- package/server/src/providers/cursor/print.ts +2 -1
- package/server/src/providers/cursor/worker.ts +2 -1
- package/server/src/providers/llamacpp.ts +18 -7
- package/server/src/providers/llamacppRecovery.ts +2 -0
- package/server/src/providers/ollamaRecovery.ts +6 -6
- package/server/src/providers/ollamaResilience.ts +3 -3
- package/server/src/providers/ollamaTokens.ts +1 -1
- package/server/src/providers/ollamaToolSubset.ts +3 -3
- package/server/src/quota.ts +0 -50
- package/server/src/replacementHistory.ts +44 -0
- package/server/src/server/broadcast.ts +2 -0
- package/server/src/server/prompts.ts +8 -1
- package/server/src/sessionJsonl.ts +92 -32
- package/server/src/smartPickupAdapters.ts +17 -3
- package/server/src/transcriptWorker.ts +182 -0
- package/server/src/workflowStore.ts +21 -0
- package/server/src/ws/clusterHandlers.ts +43 -25
- package/server/src/ws/handoffHandlers.ts +5 -1
- package/server/src/ws/transcriptWorkerHandlers.ts +126 -0
- package/server/src/ws/turnEngine.ts +20 -8
- package/server/src/ws/updatePrimaryConfig.ts +25 -6
- package/server/src/ws/workflowHandlers.ts +3 -1
- package/shared/dist/clusterCoordination.d.ts +2 -0
- package/shared/dist/clusterCoordination.js +5 -1
- package/shared/dist/protocol/clientMessages.d.ts +3 -2
- package/shared/dist/protocol/clusters.d.ts +13 -1
- package/shared/dist/protocol/index.d.ts +1 -0
- package/shared/dist/protocol/index.js +1 -0
- package/shared/dist/protocol/models.d.ts +4 -3
- package/shared/dist/protocol/models.js +26 -2
- package/shared/dist/protocol/serverMessages.d.ts +2 -1
- package/shared/dist/protocol/tasks.d.ts +4 -0
- package/shared/dist/protocol/transcriptWorker.d.ts +47 -0
- package/shared/dist/protocol/transcriptWorker.js +2 -0
- package/shared/dist/runtimeVersions.d.ts +1 -0
- package/shared/dist/runtimeVersions.js +14 -0
- package/shared/src/clusterCoordination.ts +7 -1
- package/shared/src/protocol/clientMessages.ts +5 -0
- package/shared/src/protocol/clusters.ts +16 -1
- package/shared/src/protocol/index.ts +1 -0
- package/shared/src/protocol/models.ts +31 -5
- package/shared/src/protocol/serverMessages.ts +2 -0
- package/shared/src/protocol/settings.ts +2 -3
- package/shared/src/protocol/tasks.ts +4 -7
- package/shared/src/protocol/transcriptWorker.ts +49 -0
- package/shared/src/runtimeVersions.ts +14 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { basename, extname } from 'node:path';
|
|
3
|
+
import { getHeadSeq, streamWorkflowEvents } from './workflowStore.js';
|
|
4
|
+
import { readMeta } from './workflowMeta.js';
|
|
5
|
+
import { walkBranchSeqs } from './providers/claude-native/resumeSummary.js';
|
|
6
|
+
import { TRANSCRIPT_JSON_HEADER } from './providers/renderedTranscript.js';
|
|
7
|
+
export const TRANSCRIPT_WORKER_MAX_BYTES = 32 * 1024;
|
|
8
|
+
export const TRANSCRIPT_WORKER_PREFACE_BYTES = 4 * 1024;
|
|
9
|
+
// The retention estimate tolerates split surrogate pairs. The final encoded
|
|
10
|
+
// seed is measured exactly after joining deltas; nothing is clipped to fit.
|
|
11
|
+
const textBytes = (text) => Buffer.byteLength(text, 'utf8');
|
|
12
|
+
const newTurn = (limit, count) => ({ limit, count, parts: [], bytes: 0, oversized: false, tools: new Map(), keys: [], legacy: [] });
|
|
13
|
+
const countBytes = (turn, delta) => { turn.bytes += delta; turn.count?.(delta); };
|
|
14
|
+
function add(turn, role, text, kind, merge = false) {
|
|
15
|
+
if (turn.oversized)
|
|
16
|
+
return;
|
|
17
|
+
let part = merge ? turn.text : undefined;
|
|
18
|
+
if (!part) {
|
|
19
|
+
part = { role, text: [], kind };
|
|
20
|
+
countBytes(turn, Buffer.byteLength(`${role}: ""\n`));
|
|
21
|
+
turn.parts.push(part);
|
|
22
|
+
}
|
|
23
|
+
part.text.push(text);
|
|
24
|
+
countBytes(turn, textBytes(text));
|
|
25
|
+
turn.text = merge ? part : undefined;
|
|
26
|
+
// Retain a bounded candidate ring, not every delta in a very large turn.
|
|
27
|
+
// Oversized selected turns are refused as a seed, never silently clipped.
|
|
28
|
+
if (turn.bytes > 2 * turn.limit) {
|
|
29
|
+
turn.oversized = true;
|
|
30
|
+
turn.parts = [];
|
|
31
|
+
turn.tools.clear();
|
|
32
|
+
turn.legacy = [];
|
|
33
|
+
turn.text = undefined;
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
return part;
|
|
37
|
+
}
|
|
38
|
+
export async function buildTranscriptWorkerSlice(cwd, workflowId, options) {
|
|
39
|
+
return buildTranscriptSlice(cwd, workflowId, options);
|
|
40
|
+
}
|
|
41
|
+
// Both new-worker copying and member replacement use this one turn/receipt
|
|
42
|
+
// reader. Replacement may fit a whole-turn suffix; new-worker copying keeps
|
|
43
|
+
// its original refusal instead of silently reducing the requested count.
|
|
44
|
+
export async function buildTranscriptSlice(cwd, workflowId, options, policy) {
|
|
45
|
+
const maxBytes = policy?.maxBytes ?? TRANSCRIPT_WORKER_MAX_BYTES;
|
|
46
|
+
const fit = policy?.fitWholeTurns === true;
|
|
47
|
+
if (!Number.isInteger(options.turns) || options.turns < 1 || (!policy?.allTurns && options.turns > 50))
|
|
48
|
+
throw new Error('Choose from 1 to 50 turns.');
|
|
49
|
+
if (typeof options.preface !== 'string' || Buffer.byteLength(options.preface, 'utf8') > TRANSCRIPT_WORKER_PREFACE_BYTES)
|
|
50
|
+
throw new Error('The preface must be at most 4 KiB.');
|
|
51
|
+
if (typeof options.includePartial !== 'boolean')
|
|
52
|
+
throw new Error('Choose whether to include the current partial turn.');
|
|
53
|
+
const cutoffSeq = options.cutoffSeq ?? await getHeadSeq(cwd, workflowId);
|
|
54
|
+
const meta = await readMeta(cwd, workflowId).catch(() => null);
|
|
55
|
+
let branch;
|
|
56
|
+
if (typeof meta?.leafSeq === 'number') {
|
|
57
|
+
// A rewind needs ancestry, but not the old text/tool payloads. Reuse the
|
|
58
|
+
// established branch walk over lightweight links, then stream the slice.
|
|
59
|
+
const links = [];
|
|
60
|
+
for await (const message of streamWorkflowEvents(cwd, workflowId)) {
|
|
61
|
+
const event = message;
|
|
62
|
+
if ((event.seq ?? 0) > cutoffSeq)
|
|
63
|
+
break;
|
|
64
|
+
links.push({ type: event.type, seq: event.seq, parentEventSeq: event.parentEventSeq, targetSeq: event.targetSeq });
|
|
65
|
+
}
|
|
66
|
+
const walked = walkBranchSeqs(links, links.at(-1)?.seq ?? meta.leafSeq);
|
|
67
|
+
if (walked.truncated)
|
|
68
|
+
throw new Error('The source branch has missing ancestry. Its selected turns cannot be copied exactly.');
|
|
69
|
+
branch = walked.inScope;
|
|
70
|
+
}
|
|
71
|
+
const turns = [];
|
|
72
|
+
let retainedBytes = 0;
|
|
73
|
+
const dropOldest = () => {
|
|
74
|
+
const dropped = turns.shift();
|
|
75
|
+
retainedBytes -= dropped.bytes;
|
|
76
|
+
dropped.count = undefined;
|
|
77
|
+
for (const key of dropped.keys)
|
|
78
|
+
toolOwners.set(key, null);
|
|
79
|
+
};
|
|
80
|
+
const toolOwners = new Map();
|
|
81
|
+
let total = 0;
|
|
82
|
+
let structuralSeq = 0;
|
|
83
|
+
for await (const message of streamWorkflowEvents(cwd, workflowId)) {
|
|
84
|
+
const event = message;
|
|
85
|
+
try {
|
|
86
|
+
const seq = event.seq ?? 0;
|
|
87
|
+
if (event.type === 'leaf_move' || event.type === 'conversation_changed')
|
|
88
|
+
structuralSeq = seq;
|
|
89
|
+
if (seq > cutoffSeq || (branch && !branch.has(seq)))
|
|
90
|
+
continue;
|
|
91
|
+
if (event.type === 'user_message_echo') {
|
|
92
|
+
total++;
|
|
93
|
+
const turn = newTurn(maxBytes, delta => retainedBytes += delta);
|
|
94
|
+
turns.push(turn);
|
|
95
|
+
if (turns.length > options.turns + 1)
|
|
96
|
+
dropOldest();
|
|
97
|
+
add(turn, 'USER', event.content ?? '', 'text');
|
|
98
|
+
for (const file of event.attachments ?? []) {
|
|
99
|
+
add(turn, 'USER', `[Attachment: ${basename(file)}; type: ${extname(file) || 'file'}; source: ${file}; receipt only, not copied]`, 'receipt');
|
|
100
|
+
}
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
let turn = turns.at(-1);
|
|
104
|
+
if (!turn)
|
|
105
|
+
continue;
|
|
106
|
+
if (event.type === 'primary_tool_use') {
|
|
107
|
+
const stableKey = event.toolUseId ?? event.itemId;
|
|
108
|
+
if (stableKey) {
|
|
109
|
+
if (toolOwners.has(stableKey)) {
|
|
110
|
+
const owner = toolOwners.get(stableKey);
|
|
111
|
+
if (!owner)
|
|
112
|
+
continue;
|
|
113
|
+
turn = owner;
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
toolOwners.set(stableKey, turn);
|
|
117
|
+
turn.keys.push(stableKey);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (turn.oversized)
|
|
122
|
+
continue;
|
|
123
|
+
if (event.type === 'primary_text' && typeof event.text === 'string')
|
|
124
|
+
add(turn, 'AGENT', event.text, 'text', true);
|
|
125
|
+
else if (event.type === 'primary_complete' || event.type === 'primary_turn_ended')
|
|
126
|
+
turn.text = undefined;
|
|
127
|
+
else if (event.type === 'primary_tool_use') {
|
|
128
|
+
turn.text = undefined;
|
|
129
|
+
const fullName = (event.tool ?? 'tool').replace(/\s+/g, ' ');
|
|
130
|
+
const name = fullName.length > 120 ? fullName.slice(0, 117) + '...' : fullName;
|
|
131
|
+
const status = ['started', 'in_progress', 'completed', 'failed'].includes(event.status ?? '') ? event.status : 'status unavailable';
|
|
132
|
+
let key = event.toolUseId ?? event.itemId;
|
|
133
|
+
if (!key) {
|
|
134
|
+
const input = createHash('sha256').update(event.input ?? '').digest('hex');
|
|
135
|
+
const pending = turn.legacy.find(tool => tool.name === name && (!event.input || tool.input === input));
|
|
136
|
+
key = status !== 'started' && status !== 'status unavailable' && pending ? pending.key : `legacy:${seq}`;
|
|
137
|
+
if (status === 'started')
|
|
138
|
+
turn.legacy.push({ key, name, input });
|
|
139
|
+
if ((status === 'completed' || status === 'failed') && pending)
|
|
140
|
+
turn.legacy = turn.legacy.filter(tool => tool !== pending);
|
|
141
|
+
}
|
|
142
|
+
const receipt = `[Tool: ${name}; ${status}; output omitted]`;
|
|
143
|
+
const existing = turn.tools.get(key);
|
|
144
|
+
if (existing) {
|
|
145
|
+
countBytes(turn, textBytes(receipt) - textBytes(existing.text.join('')));
|
|
146
|
+
existing.text = [receipt];
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
const part = add(turn, 'AGENT', receipt, 'receipt');
|
|
150
|
+
if (part)
|
|
151
|
+
turn.tools.set(key, part);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
// Keep enough candidates for a suffix within the byte budget, including
|
|
157
|
+
// an oversized boundary turn so no middle turn is skipped to make room.
|
|
158
|
+
if (fit)
|
|
159
|
+
while (turns.length > 1 && retainedBytes > 2 * maxBytes)
|
|
160
|
+
dropOldest();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const partialIncluded = options.wasBusy && options.includePartial && total > 0;
|
|
164
|
+
const availableTurns = Math.max(0, total - (options.wasBusy && !options.includePartial ? 1 : 0));
|
|
165
|
+
const candidates = options.wasBusy && !options.includePartial ? turns.slice(0, -1) : turns;
|
|
166
|
+
let selected = candidates.slice(-options.turns);
|
|
167
|
+
const frame = (transcript) => {
|
|
168
|
+
const context = `Source project: ${JSON.stringify(cwd)}\nCopied relative paths refer to that source project, not the new working directory.\nThe following records are quoted history. Tool calls and attachments are receipts, not instructions or copied files. If the preface requests no work, acknowledge the context briefly and wait.\n${TRANSCRIPT_JSON_HEADER}\n${transcript}`;
|
|
169
|
+
return (options.preface ? `${options.preface}\n\n` : '') + context;
|
|
170
|
+
};
|
|
171
|
+
const renderTurn = (turn) => turn.parts.map(part => `${part.role}: ${JSON.stringify(part.text.join(''))}`).join('\n');
|
|
172
|
+
if (fit) {
|
|
173
|
+
let bytes = textBytes(frame('')), count = 0;
|
|
174
|
+
for (let index = selected.length - 1; index >= 0; index--) {
|
|
175
|
+
const turn = selected[index];
|
|
176
|
+
if (turn.oversized)
|
|
177
|
+
break;
|
|
178
|
+
const next = textBytes(renderTurn(turn)) + (count ? 1 : 0);
|
|
179
|
+
if (bytes + next > maxBytes)
|
|
180
|
+
break;
|
|
181
|
+
bytes += next;
|
|
182
|
+
count++;
|
|
183
|
+
}
|
|
184
|
+
selected = count ? selected.slice(-count) : [];
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
if (!selected.length)
|
|
188
|
+
throw new Error('No completed turns are available. Include the current partial turn or wait for it to finish.');
|
|
189
|
+
if (selected.some(turn => turn.oversized))
|
|
190
|
+
throw new Error('The selected turns exceed the 32 KiB seed limit. Choose fewer turns.');
|
|
191
|
+
}
|
|
192
|
+
const transcript = selected.map(renderTurn).join('\n');
|
|
193
|
+
const seed = selected.length ? frame(transcript) : '';
|
|
194
|
+
const bytes = textBytes(seed);
|
|
195
|
+
if (bytes > maxBytes)
|
|
196
|
+
throw new Error(`The seed is ${bytes} bytes; the limit is ${maxBytes}. Choose fewer turns or shorten the preface.`);
|
|
197
|
+
const branchKey = `${meta?.leafSeq ?? ''}:${structuralSeq}`;
|
|
198
|
+
const digest = createHash('sha256').update(JSON.stringify({ seed, availableTurns, cutoffSeq, branchKey })).digest('hex');
|
|
199
|
+
return { seed, bytes, availableTurns, selectedTurns: selected.length, partialIncluded, cutoffSeq, digest, branchKey };
|
|
200
|
+
}
|
|
201
|
+
//# sourceMappingURL=transcriptWorker.js.map
|
|
@@ -14,6 +14,7 @@ export declare function replayEventsWithTs(cwd: string, wfid: string, fromSeq: n
|
|
|
14
14
|
ts: number;
|
|
15
15
|
message: ServerMessage;
|
|
16
16
|
}>>;
|
|
17
|
+
export declare function streamWorkflowEvents(cwd: string, wfid: string): AsyncGenerator<ServerMessage>;
|
|
17
18
|
export declare function replayEvents(cwd: string, wfid: string, fromSeq: number): Promise<ServerMessage[]>;
|
|
18
19
|
export declare function replayTailEvents(cwd: string, wfid: string, maxBytes: number): Promise<{
|
|
19
20
|
events: ServerMessage[];
|
|
@@ -597,6 +597,37 @@ function withEventTs(entry) {
|
|
|
597
597
|
const { ts, ...rest } = entry;
|
|
598
598
|
return typeof ts === 'number' ? { ...rest, eventTs: ts } : rest;
|
|
599
599
|
}
|
|
600
|
+
// Streaming consumers can retain their selected slice instead of materializing
|
|
601
|
+
// the whole history. Sequence repair, sealed copies and pending flushes are the
|
|
602
|
+
// same as the existing replay APIs.
|
|
603
|
+
export async function* streamWorkflowEvents(cwd, wfid) {
|
|
604
|
+
if (!cwd)
|
|
605
|
+
return;
|
|
606
|
+
validateWfid(wfid);
|
|
607
|
+
const buf = buffers.get(bufferKey(cwd, wfid));
|
|
608
|
+
if (buf) {
|
|
609
|
+
if (buf.flushTimer) {
|
|
610
|
+
clearTimeout(buf.flushTimer);
|
|
611
|
+
buf.flushTimer = null;
|
|
612
|
+
}
|
|
613
|
+
await flushBuffer(buf);
|
|
614
|
+
}
|
|
615
|
+
for await (const { line, step } of effectiveLines(workflowDir(cwd, wfid))) {
|
|
616
|
+
if (!step)
|
|
617
|
+
continue;
|
|
618
|
+
let entry;
|
|
619
|
+
try {
|
|
620
|
+
entry = JSON.parse(line);
|
|
621
|
+
}
|
|
622
|
+
catch {
|
|
623
|
+
continue;
|
|
624
|
+
}
|
|
625
|
+
if (typeof entry.seq !== 'number')
|
|
626
|
+
continue;
|
|
627
|
+
applyStep(entry, step);
|
|
628
|
+
yield withEventTs(entry);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
600
631
|
// Replay all events with seq > fromSeq, in seq order. Caller streams each
|
|
601
632
|
// returned ServerMessage to the newly-connected WS (stamped seq included on
|
|
602
633
|
// the wire object). Flushes pending first so the replay is head-current.
|
|
@@ -60,6 +60,7 @@ export declare function handleClusterMemberFocusSet(ws: WebSocket, clusterId: st
|
|
|
60
60
|
export declare function handleClusterIdleNudgerToggle(ws: WebSocket, clusterId: string, enabled: boolean): Promise<void>;
|
|
61
61
|
export declare function handleClusterAutoCompactionSet(ws: WebSocket, clusterId: string, policy: import('@arco/shared').AutoCompactionPolicy | null): Promise<void>;
|
|
62
62
|
export declare function handleClusterEfficiencySet(ws: WebSocket, clusterId: string, level: ClusterEfficiencyLevel, addendum?: string, messageGuard?: import('@arco/shared').ClusterMessageGuard): Promise<void>;
|
|
63
|
+
export declare function handleClusterSkillsSet(ws: WebSocket, clusterId: string, pins: unknown): Promise<void>;
|
|
63
64
|
export declare function handleClusterRemoteSet(ws: WebSocket, clusterId: string, enabled: boolean): Promise<void>;
|
|
64
65
|
export declare function handleClusterGatesSet(ws: WebSocket, clusterId: string, enabled: boolean): Promise<void>;
|
|
65
66
|
export declare function handleClusterMemberReorder(ws: WebSocket, clusterId: string, memberIds: string[]): Promise<void>;
|
|
@@ -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 { isClusterMemberProvider, isClusterMemberAccessMode, isClusterEfficiencyLevel, isClusterTaskBoardMode, isClusterProgressMode, } from '@arco/shared';
|
|
11
14
|
import { WebSocket } from 'ws';
|
|
12
15
|
import * as clusterAutoTurn from '../clusterAutoTurn.js';
|
|
@@ -18,7 +21,6 @@ import * as clusterRehydrate from '../clusterRehydrate.js';
|
|
|
18
21
|
import * as clusterStore from '../clusterStore.js';
|
|
19
22
|
import { refreshHubReporting } from '../management/initHubLink.js';
|
|
20
23
|
import { replayEvents } from '../workflowStore.js';
|
|
21
|
-
import { renderTranscript, summarizePriorTurns } from '../primitives/exportContext.js';
|
|
22
24
|
import * as taskDispatcher from '../taskDispatcher.js';
|
|
23
25
|
import * as taskLedger from '../project/taskLedger.js';
|
|
24
26
|
import * as orchestrationProposals from '../project/orchestrationProposals.js';
|
|
@@ -1813,6 +1815,13 @@ export async function handleClusterAddFreshWorkers(ws, session, msg) {
|
|
|
1813
1815
|
model: msg.model, effort: msg.effort, accountRef: msg.providerAccountRef, isolated: accessMode === 'isolated', resolveCodexAccount,
|
|
1814
1816
|
tuning: msg,
|
|
1815
1817
|
});
|
|
1818
|
+
try {
|
|
1819
|
+
await assertSkillUnion(cluster, newRole || undefined, childConfig.pinnedSkills ?? [], childName);
|
|
1820
|
+
}
|
|
1821
|
+
catch (err) {
|
|
1822
|
+
send(ws, { type: 'error', message: `cluster_add_fresh_workers rejected: ${err instanceof Error ? err.message : String(err)}` });
|
|
1823
|
+
return;
|
|
1824
|
+
}
|
|
1816
1825
|
try {
|
|
1817
1826
|
const id = await deps.createBlankNativeWorkflow(ws, session, childConfig, MEMBER_PENDING);
|
|
1818
1827
|
newIds.push(id);
|
|
@@ -1864,7 +1873,6 @@ export async function handleClusterAddFreshWorkers(ws, session, msg) {
|
|
|
1864
1873
|
}
|
|
1865
1874
|
console.log(`[arco] cluster ${msg.clusterId.slice(0, 8)} grew by ${newIds.length} fresh workers`);
|
|
1866
1875
|
}
|
|
1867
|
-
const REPLACEMENT_HISTORY_MAX_BYTES = 512 * 1024;
|
|
1868
1876
|
// The name and role a REPLACE request carries, as a refusal code or null.
|
|
1869
1877
|
function replaceIdentityRefusal(cluster, msg) {
|
|
1870
1878
|
if (msg.name !== undefined && (typeof msg.name !== 'string' || msg.name.trim().length > 64))
|
|
@@ -1898,7 +1906,12 @@ export async function handleClusterMemberReplace(ws, session, msg) {
|
|
|
1898
1906
|
send(ws, { type: 'error', message: 'cluster_member_replace rejected: invalid_access_mode' });
|
|
1899
1907
|
return;
|
|
1900
1908
|
}
|
|
1901
|
-
|
|
1909
|
+
const historyMode = msg.historyMode ?? (msg.includeHistory ? 'full' : 'none');
|
|
1910
|
+
if (!['none', 'recent', 'full'].includes(historyMode)) {
|
|
1911
|
+
send(ws, { type: 'error', message: 'cluster_member_replace rejected: invalid_history_mode' });
|
|
1912
|
+
return;
|
|
1913
|
+
}
|
|
1914
|
+
if (accessMode === 'isolated' && (historyMode !== 'none' || msg.transferActiveTasks)) {
|
|
1902
1915
|
send(ws, { type: 'error', message: 'cluster_member_replace rejected: isolated_requires_fresh_context_and_no_tasks' });
|
|
1903
1916
|
return;
|
|
1904
1917
|
}
|
|
@@ -1938,22 +1951,24 @@ export async function handleClusterMemberReplace(ws, session, msg) {
|
|
|
1938
1951
|
return;
|
|
1939
1952
|
}
|
|
1940
1953
|
}
|
|
1941
|
-
let historySeed = '';
|
|
1942
|
-
if (
|
|
1943
|
-
const
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1954
|
+
let historySeed = '', historyNotice;
|
|
1955
|
+
if (historyMode !== 'none') {
|
|
1956
|
+
const turns = msg.historyTurns ?? 10;
|
|
1957
|
+
try {
|
|
1958
|
+
if (!Number.isInteger(turns) || turns < 1 || turns > 50)
|
|
1959
|
+
throw new Error('Choose from 1 to 50 recent turns.');
|
|
1960
|
+
const preview = msg.historyToken
|
|
1961
|
+
? await takeReplacementHistoryPreview(ws, msg.clusterId, msg.workflowId, historyMode, turns, msg.historyToken)
|
|
1962
|
+
: msg.historyMode !== undefined
|
|
1963
|
+
? (() => { throw new Error('Preview the history before replacing this member.'); })()
|
|
1964
|
+
: await buildReplacementHistory(cluster.cwd, msg.workflowId, 'full', { turns, includePartial: false, preface: '', wasBusy: false });
|
|
1965
|
+
historySeed = preview.seed;
|
|
1966
|
+
historyNotice = replacementHistoryNotice(preview);
|
|
1967
|
+
if (source.busy)
|
|
1968
|
+
throw new Error('The member started working. Wait for it to finish and refresh the preview.');
|
|
1969
|
+
}
|
|
1970
|
+
catch (err) {
|
|
1971
|
+
send(ws, { type: 'error', message: `cluster_member_replace rejected: ${err instanceof Error ? err.message : String(err)}` });
|
|
1957
1972
|
return;
|
|
1958
1973
|
}
|
|
1959
1974
|
}
|
|
@@ -1962,16 +1977,22 @@ export async function handleClusterMemberReplace(ws, session, msg) {
|
|
|
1962
1977
|
model: msg.model, effort: msg.effort, accountRef: msg.providerAccountRef, isolated: accessMode === 'isolated', resolveCodexAccount,
|
|
1963
1978
|
tuning: msg,
|
|
1964
1979
|
});
|
|
1980
|
+
try {
|
|
1981
|
+
await assertSkillUnion(cluster, msg.role ?? clusterStore.getMemberRole(msg.clusterId, msg.workflowId), childConfig.pinnedSkills ?? [], childConfig.name ?? 'Replacement');
|
|
1982
|
+
}
|
|
1983
|
+
catch (err) {
|
|
1984
|
+
send(ws, { type: 'error', message: `cluster_member_replace rejected: ${err instanceof Error ? err.message : String(err)}` });
|
|
1985
|
+
return;
|
|
1986
|
+
}
|
|
1965
1987
|
let newWorkflowId;
|
|
1966
1988
|
try {
|
|
1967
1989
|
newWorkflowId = await deps.createBlankNativeWorkflow(ws, session, childConfig, MEMBER_PENDING);
|
|
1968
|
-
const replaced = await clusterStore.replaceMember(msg.clusterId, msg.workflowId, newWorkflowId, accessMode);
|
|
1990
|
+
const replaced = await clusterStore.replaceMember(msg.clusterId, msg.workflowId, newWorkflowId, accessMode, msg.role);
|
|
1969
1991
|
if (!replaced)
|
|
1970
1992
|
throw new Error('atomic_replace_failed');
|
|
1971
1993
|
// The slot's role, tier and focus moved with the replacement; the
|
|
1972
|
-
// request's own values win.
|
|
1973
|
-
|
|
1974
|
-
await clusterStore.setMemberRole(msg.clusterId, newWorkflowId, msg.role);
|
|
1994
|
+
// request's own values win. Role and skill limits were applied atomically
|
|
1995
|
+
// with replacement; the tier/focus values were checked above.
|
|
1975
1996
|
if (msg.tier !== undefined)
|
|
1976
1997
|
await clusterStore.setMemberTier(msg.clusterId, newWorkflowId, msg.tier);
|
|
1977
1998
|
if (msg.focus !== undefined)
|
|
@@ -2024,7 +2045,7 @@ export async function handleClusterMemberReplace(ws, session, msg) {
|
|
|
2024
2045
|
oldWorkflowId: msg.workflowId,
|
|
2025
2046
|
newWorkflowId,
|
|
2026
2047
|
accessMode,
|
|
2027
|
-
historyIncluded: !!
|
|
2048
|
+
historyIncluded: !!historySeed,
|
|
2028
2049
|
transferredTaskCount,
|
|
2029
2050
|
member: {
|
|
2030
2051
|
workflowId: newWorkflowId,
|
|
@@ -2045,6 +2066,8 @@ export async function handleClusterMemberReplace(ws, session, msg) {
|
|
|
2045
2066
|
const payload = await buildClusterStatePayload(msg.clusterId);
|
|
2046
2067
|
if (payload)
|
|
2047
2068
|
broadcastCluster(msg.clusterId, { type: 'cluster_state', clusterId: msg.clusterId, state: payload });
|
|
2069
|
+
if (historyNotice)
|
|
2070
|
+
broadcastWorkflow(newWorkflowId, { type: 'system_notice', workflowId: newWorkflowId, content: historyNotice });
|
|
2048
2071
|
if (historySeed) {
|
|
2049
2072
|
await deps.handleUserMessage(ws, session, newWorkflowId, historySeed, undefined, undefined, false, undefined, undefined);
|
|
2050
2073
|
}
|
|
@@ -2174,8 +2197,8 @@ export async function handleClusterMemberRoleSet(ws, clusterId, workflowId, role
|
|
|
2174
2197
|
updated = await clusterStore.setMemberRole(clusterId, workflowId, role);
|
|
2175
2198
|
}
|
|
2176
2199
|
catch (err) {
|
|
2177
|
-
if (err instanceof clusterStore.ClusterValidationError
|
|
2178
|
-
send(ws, { type: 'error', message: `cluster_member_role_set rejected:
|
|
2200
|
+
if (err instanceof clusterStore.ClusterValidationError) {
|
|
2201
|
+
send(ws, { type: 'error', message: `cluster_member_role_set rejected: ${err.code}: ${err.message}` });
|
|
2179
2202
|
return;
|
|
2180
2203
|
}
|
|
2181
2204
|
throw err;
|
|
@@ -2292,6 +2315,19 @@ export async function handleClusterEfficiencySet(ws, clusterId, level, addendum,
|
|
|
2292
2315
|
}
|
|
2293
2316
|
console.log(`[arco] cluster ${clusterId.slice(0, 8)} efficiency → ${level}${addendum !== undefined ? ' (addendum updated)' : ''}`);
|
|
2294
2317
|
}
|
|
2318
|
+
export async function handleClusterSkillsSet(ws, clusterId, pins) {
|
|
2319
|
+
try {
|
|
2320
|
+
const updated = await clusterStore.setSkillPins(clusterId, pins);
|
|
2321
|
+
if (!updated)
|
|
2322
|
+
throw new Error('Unknown cluster.');
|
|
2323
|
+
const payload = await buildClusterStatePayload(clusterId);
|
|
2324
|
+
if (payload)
|
|
2325
|
+
broadcastCluster(clusterId, { type: 'cluster_state', clusterId, state: payload });
|
|
2326
|
+
}
|
|
2327
|
+
catch (err) {
|
|
2328
|
+
send(ws, { type: 'error', message: `Cluster skills: ${err instanceof Error ? err.message : String(err)}` });
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2295
2331
|
// R3 (docs/REMOTE_MANAGEMENT.md) - operator flipped the cluster-level
|
|
2296
2332
|
// ◉ REMOTE chip. Persist, rebroadcast cluster_state, and re-push the hub
|
|
2297
2333
|
// snapshot immediately so the phone console reflects the flip without waiting
|
|
@@ -33,7 +33,7 @@ import { disposeProviderResources } from '../providers/index.js';
|
|
|
33
33
|
import { INCOGNITO_CHAT_PROVIDERS, incognitoChatCwd, isChatWorkflow } from '../chatMode.js';
|
|
34
34
|
import { registerPrivateLogToken } from '../server/logger.js';
|
|
35
35
|
import { acquirePlansWatcher, broadcastCluster, broadcastHandoffLockSnapshot, broadcastTransient, broadcastWorkflow, recordContextUsage, buildClusterStatePayload, send, } from '../server/broadcast.js';
|
|
36
|
-
import { buildLocalClusterSystemPrompt, LLAMACPP_PRIMARY_SYSTEM_PROMPT, OLLAMA_PRIMARY_SYSTEM_PROMPT, withPreviewNudge, } from '../server/prompts.js';
|
|
36
|
+
import { buildLocalClusterSystemPrompt, withLocalTurnWaitInstructions, LLAMACPP_PRIMARY_SYSTEM_PROMPT, OLLAMA_PRIMARY_SYSTEM_PROMPT, withPreviewNudge, } from '../server/prompts.js';
|
|
37
37
|
import { cwdHandoffChain, workflowCwds, workflows, } from '../server/state.js';
|
|
38
38
|
import { acquireProjectSettingsWatcher, readSettings, } from '../settings.js';
|
|
39
39
|
import { appendHistoryEntry, readMeta, workflowConfigFromMeta, writeMeta, } from '../workflowMeta.js';
|
|
@@ -517,11 +517,14 @@ export async function handleHandoffRequest(ws, session, msg) {
|
|
|
517
517
|
prewarmClusterProgressDoctrine = joinClusterDoctrines(buildClusterDirectorDoctrine(prewarmClusterRole), buildProgressDoctrine(clusterStore.getProgressTracking(prewarmClusterId), !!prewarmClusterPlan?.trim(), prewarmClusterTaskBoardAttached));
|
|
518
518
|
}
|
|
519
519
|
const prewarmIsLocal = wf.primary.provider === 'ollama' || wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek');
|
|
520
|
-
const
|
|
520
|
+
const prewarmLocalBaseline = wf.primary.provider === 'ollama'
|
|
521
521
|
? OLLAMA_PRIMARY_SYSTEM_PROMPT
|
|
522
522
|
: (wf.primary.provider === 'llamacpp' || wf.primary.provider === 'lmstudio' || (wf.primary.provider === 'strata' || wf.primary.provider === 'deepseek'))
|
|
523
523
|
? LLAMACPP_PRIMARY_SYSTEM_PROMPT
|
|
524
524
|
: undefined;
|
|
525
|
+
const prewarmLocalBase = prewarmIsLocal
|
|
526
|
+
? withLocalTurnWaitInstructions(prewarmLocalBaseline, prewarmClusterRole)
|
|
527
|
+
: undefined;
|
|
525
528
|
const prewarmSystemPrompt = prewarmIsLocal && prewarmClusterId
|
|
526
529
|
? buildLocalClusterSystemPrompt({
|
|
527
530
|
base: prewarmLocalBase,
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type WebSocket from 'ws';
|
|
2
|
+
import type { TranscriptWorkerCreateMessage, TranscriptWorkerPreviewMessage, WorkflowConfig } from '@arco/shared';
|
|
3
|
+
import type { Session } from '../workflows/types.js';
|
|
4
|
+
interface Dependencies {
|
|
5
|
+
create(ws: WebSocket, session: Session, config: WorkflowConfig): Promise<string>;
|
|
6
|
+
seed(ws: WebSocket, session: Session, workflowId: string, content: string): void;
|
|
7
|
+
}
|
|
8
|
+
export declare function initTranscriptWorkerHandlers(value: Dependencies): void;
|
|
9
|
+
export declare function handleTranscriptWorkerPreview(ws: WebSocket, message: TranscriptWorkerPreviewMessage): Promise<void>;
|
|
10
|
+
export declare function handleTranscriptWorkerCreate(ws: WebSocket, session: Session, message: TranscriptWorkerCreateMessage): Promise<void>;
|
|
11
|
+
export declare function takeReplacementHistoryPreview(ws: WebSocket, clusterId: string, workflowId: string, mode: 'recent' | 'full', turns: number, token: string): Promise<{
|
|
12
|
+
seed: string;
|
|
13
|
+
bytes: number;
|
|
14
|
+
selectedTurns: number;
|
|
15
|
+
digest: string;
|
|
16
|
+
historyMode: import("../replacementHistory.js").ReplacementHistoryMode;
|
|
17
|
+
requestedTurns: number;
|
|
18
|
+
truncated: boolean;
|
|
19
|
+
historyFallback: boolean;
|
|
20
|
+
availableTurns: number;
|
|
21
|
+
partialIncluded: boolean;
|
|
22
|
+
cutoffSeq: number;
|
|
23
|
+
branchKey: string;
|
|
24
|
+
}>;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,139 @@
|
|
|
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 { send } from '../server/broadcast.js';
|
|
6
|
+
import { workflows } from '../server/state.js';
|
|
7
|
+
import { safeDirectory } from '../fileAccessPolicy.js';
|
|
8
|
+
import { readSettings } from '../settings.js';
|
|
9
|
+
import { isKnownProvider } from '../providers/index.js';
|
|
10
|
+
import { configuredAccounts } from '../providerAccounts.js';
|
|
11
|
+
import { buildTranscriptWorkerSlice } from '../transcriptWorker.js';
|
|
12
|
+
import { TERMINAL_CODEX_ACCOUNT } from '@arco/shared';
|
|
13
|
+
let deps;
|
|
14
|
+
export function initTranscriptWorkerHandlers(value) { deps = value; }
|
|
15
|
+
const snapshots = new Map();
|
|
16
|
+
function prune() {
|
|
17
|
+
for (const [token, entry] of snapshots)
|
|
18
|
+
if (entry.expires < Date.now() && !entry.creating)
|
|
19
|
+
snapshots.delete(token);
|
|
20
|
+
while (snapshots.size >= 32) {
|
|
21
|
+
const oldest = [...snapshots].find(([, entry]) => !entry.creating);
|
|
22
|
+
if (!oldest)
|
|
23
|
+
throw new Error('Transcript previews are busy. Try again when a request finishes.');
|
|
24
|
+
snapshots.delete(oldest[0]);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function sourceFor(workflowId) {
|
|
28
|
+
const source = workflows.get(workflowId);
|
|
29
|
+
if (!source || source.config.kind === 'chat' || source.config.kind === 'cluster' || source.config.incognito || !source.config.workingDirectory)
|
|
30
|
+
throw new Error('Choose an available Agent conversation as the source.');
|
|
31
|
+
return source;
|
|
32
|
+
}
|
|
33
|
+
export async function handleTranscriptWorkerPreview(ws, message) {
|
|
34
|
+
try {
|
|
35
|
+
prune();
|
|
36
|
+
const source = sourceFor(message.workflowId);
|
|
37
|
+
const options = { turns: message.turns, includePartial: message.includePartial, preface: message.preface, wasBusy: source.busy };
|
|
38
|
+
let cwd = source.config.workingDirectory;
|
|
39
|
+
if (message.replacement) {
|
|
40
|
+
const cluster = await clusterStore.readCluster(message.replacement.clusterId);
|
|
41
|
+
if (!cluster?.members.includes(message.workflowId))
|
|
42
|
+
throw new Error('Choose an available cluster member.');
|
|
43
|
+
if (source.busy)
|
|
44
|
+
throw new Error('Wait for the member to finish before replacing it.');
|
|
45
|
+
if (!['recent', 'full'].includes(message.replacement.mode))
|
|
46
|
+
throw new Error('Choose a valid history mode.');
|
|
47
|
+
cwd = cluster.cwd;
|
|
48
|
+
options.includePartial = false;
|
|
49
|
+
options.preface = '';
|
|
50
|
+
options.wasBusy = false;
|
|
51
|
+
}
|
|
52
|
+
const slice = message.replacement
|
|
53
|
+
? await buildReplacementHistory(cwd, message.workflowId, message.replacement.mode, options)
|
|
54
|
+
: await buildTranscriptWorkerSlice(cwd, message.workflowId, options);
|
|
55
|
+
const token = randomUUID();
|
|
56
|
+
snapshots.set(token, { replacement: message.replacement, owner: ws, source: message.workflowId, cwd, options: { ...options, cutoffSeq: slice.cutoffSeq }, slice, expires: Date.now() + 10 * 60_000 });
|
|
57
|
+
const { digest: _digest, branchKey: _branch, ...preview } = slice;
|
|
58
|
+
send(ws, { type: 'transcript_worker_result', requestId: message.requestId, preview: { ...preview, token } });
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
send(ws, { type: 'transcript_worker_result', requestId: message.requestId, error: error instanceof Error ? error.message : String(error) });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
async function destinationConfig(message) {
|
|
65
|
+
const target = message.destination;
|
|
66
|
+
if (!target || typeof target.workingDirectory !== 'string' || !isAbsolute(target.workingDirectory))
|
|
67
|
+
throw new Error('Choose an existing absolute working directory for the new worker.');
|
|
68
|
+
let workingDirectory;
|
|
69
|
+
try {
|
|
70
|
+
workingDirectory = safeDirectory(target.workingDirectory);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
throw new Error('The destination folder is unavailable or protected. Choose another existing folder.');
|
|
74
|
+
}
|
|
75
|
+
if (!isKnownProvider(target.provider) || typeof target.model !== 'string' || !target.model.trim())
|
|
76
|
+
throw new Error('Choose a supported provider and model.');
|
|
77
|
+
if (!['none', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'].includes(target.effort))
|
|
78
|
+
throw new Error('Choose a valid effort.');
|
|
79
|
+
if (target.skipPermissions !== undefined && typeof target.skipPermissions !== 'boolean')
|
|
80
|
+
throw new Error('Choose the new worker permission setting.');
|
|
81
|
+
const settings = await readSettings(workingDirectory);
|
|
82
|
+
if (settings.enabledProviders?.[target.provider] === false)
|
|
83
|
+
throw new Error('That provider is turned off. Enable it or choose another provider.');
|
|
84
|
+
if (target.providerAccountRef && !(target.provider === 'codex' && target.providerAccountRef === TERMINAL_CODEX_ACCOUNT)) {
|
|
85
|
+
if (target.provider !== 'codex' || !(await configuredAccounts('codex', workingDirectory)).some(account => account.id === target.providerAccountRef))
|
|
86
|
+
throw new Error('Choose an available account for the new worker.');
|
|
87
|
+
}
|
|
88
|
+
return { kind: 'workflow', name: typeof target.name === 'string' && target.name.trim() ? target.name.trim().slice(0, 120) : 'Transcript worker', workingDirectory,
|
|
89
|
+
primaryProvider: target.provider, primaryModel: target.model.trim(), primaryEffort: target.effort,
|
|
90
|
+
...(target.provider === 'codex' && target.providerAccountRef ? { providerAccountRef: target.providerAccountRef } : {}), skipPermissions: target.skipPermissions === true };
|
|
91
|
+
}
|
|
92
|
+
export async function handleTranscriptWorkerCreate(ws, session, message) {
|
|
93
|
+
try {
|
|
94
|
+
const entry = snapshots.get(message.token);
|
|
95
|
+
if (!entry || entry.owner !== ws || entry.replacement || entry.expires < Date.now())
|
|
96
|
+
throw new Error('The preview expired or disconnected. Refresh the preview before sending.');
|
|
97
|
+
if (!entry.created && !entry.creating) {
|
|
98
|
+
entry.creating = (async () => {
|
|
99
|
+
const source = sourceFor(entry.source);
|
|
100
|
+
if (source.config.workingDirectory !== entry.cwd)
|
|
101
|
+
throw new Error('The source folder changed. Refresh the preview.');
|
|
102
|
+
const current = await buildTranscriptWorkerSlice(entry.cwd, entry.source, entry.options);
|
|
103
|
+
if (current.digest !== entry.slice.digest)
|
|
104
|
+
throw new Error('The source history changed or was rewound. Refresh the preview.');
|
|
105
|
+
const config = await destinationConfig(message);
|
|
106
|
+
const id = await deps.create(ws, session, config);
|
|
107
|
+
entry.created = id;
|
|
108
|
+
deps.seed(ws, session, id, entry.slice.seed);
|
|
109
|
+
return id;
|
|
110
|
+
})();
|
|
111
|
+
}
|
|
112
|
+
const id = entry.created ?? await entry.creating;
|
|
113
|
+
entry.creating = undefined;
|
|
114
|
+
send(ws, { type: 'transcript_worker_result', requestId: message.requestId, newWorkflowId: id });
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
const entry = snapshots.get(message.token);
|
|
118
|
+
if (entry && !entry.created)
|
|
119
|
+
entry.creating = undefined;
|
|
120
|
+
send(ws, { type: 'transcript_worker_result', requestId: message.requestId, error: error instanceof Error ? error.message : String(error) });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// REPLACE consumes the same socket-bound, fixed-cutoff preview as NEW WORKER.
|
|
124
|
+
// Claim after checking again so a repeated submit cannot allocate two members.
|
|
125
|
+
export async function takeReplacementHistoryPreview(ws, clusterId, workflowId, mode, turns, token) {
|
|
126
|
+
const entry = snapshots.get(token);
|
|
127
|
+
if (!entry || entry.owner !== ws || entry.expires < Date.now() || entry.source !== workflowId
|
|
128
|
+
|| entry.replacement?.clusterId !== clusterId || entry.replacement.mode !== mode || entry.options.turns !== turns) {
|
|
129
|
+
throw new Error('The history preview expired or changed. Refresh it before replacing.');
|
|
130
|
+
}
|
|
131
|
+
const current = await buildReplacementHistory(entry.cwd, workflowId, mode, entry.options);
|
|
132
|
+
if (current.digest !== entry.slice.digest)
|
|
133
|
+
throw new Error('The source history changed or was rewound. Refresh the preview.');
|
|
134
|
+
if (entry.claimed)
|
|
135
|
+
throw new Error('This history preview was already used. Refresh it before replacing again.');
|
|
136
|
+
entry.claimed = true;
|
|
137
|
+
return current;
|
|
138
|
+
}
|
|
139
|
+
//# sourceMappingURL=transcriptWorkerHandlers.js.map
|