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.
- package/CONTRIBUTING.md +52 -12
- package/README.md +20 -13
- package/client/dist/assets/{PhosphorBackdrop-BR-TgB5x.js → PhosphorBackdrop-D7jdAV_G.js} +1 -1
- package/client/dist/assets/{ThemedBackgroundShaderImpl-DgcFj6JN.js → ThemedBackgroundShaderImpl-DrDm60h8.js} +1 -1
- package/client/dist/assets/{XtermView-CflVBQgC.js → XtermView-BGFujb1e.js} +1 -1
- package/client/dist/assets/{galleryEditor-BB-emfmi.js → galleryEditor-D951A2sE.js} +1 -1
- package/client/dist/assets/{index-B_EqHDz3.js → index-CsVy3eZm.js} +248 -248
- package/client/dist/index.html +1 -1
- package/client/src/buildCheck.ts +3 -1
- package/client/src/components/AppUpdateNotice.tsx +2 -1
- package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +24 -12
- 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 +6 -1
- package/client/src/components/ClusterTaskBoardTab.tsx +9 -22
- package/client/src/components/HeaderVersionBox.tsx +7 -4
- 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/UpdateAction.tsx +18 -4
- package/client/src/components/UpdateResultNotice.tsx +3 -1
- package/client/src/components/clusterNeedsYou.ts +11 -18
- package/client/src/help/content/cluster.tsx +54 -22
- package/client/src/help/content/composer.tsx +22 -0
- package/client/src/help/content/header.tsx +19 -1
- package/client/src/help/content/misc.tsx +8 -0
- package/client/src/help/content/rightPanel.tsx +1 -1
- package/client/src/help/content/settings.tsx +19 -5
- 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 +58 -21
- package/client/src/help/manualSections/configuration.tsx +38 -4
- package/client/src/help/manualSections/maintenance.tsx +30 -0
- package/client/src/help/manualSections/plans.tsx +5 -1
- 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 +19 -0
- package/client/src/help/manualSections/workspace.tsx +6 -0
- package/client/src/stores/appUpdateStore.ts +29 -8
- package/client/src/utils/transcriptWorkerRequest.ts +24 -0
- package/client/src/utils/wsSession.ts +2 -1
- 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 +9 -4
- package/docs/GOTCHAS.md +2 -1
- package/docs/OPERATIONS.md +37 -4
- package/docs/PERSISTENCE.md +25 -3
- package/docs/PRIMITIVES.md +42 -0
- package/docs/PROTOCOL_CLUSTER.md +51 -5
- 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/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/autoPickup.d.ts +3 -0
- 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 +78 -12
- package/scripts/packaging/update.mjs +5 -1
- 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/clusterAutoTurn.d.ts +4 -0
- package/server/dist/clusterAutoTurn.js +29 -25
- package/server/dist/clusterBusyReminder.js +1 -1
- 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 +10 -2
- package/server/dist/clusterStore.js +64 -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/smartPickup.d.ts +2 -1
- package/server/dist/smartPickup.js +28 -1
- package/server/dist/smartPickupAdapters.js +15 -2
- package/server/dist/smartPickupLedger.js +6 -4
- package/server/dist/smartPickupObserver.d.ts +1 -0
- package/server/dist/smartPickupObserver.js +24 -15
- 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 +2 -0
- package/server/dist/ws/clusterHandlers.js +64 -27
- 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/clusterAutoTurn.ts +26 -21
- package/server/src/clusterBusyReminder.ts +1 -1
- 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 +64 -1
- 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/smartPickup.ts +27 -3
- package/server/src/smartPickupAdapters.ts +17 -3
- package/server/src/smartPickupLedger.ts +6 -4
- package/server/src/smartPickupObserver.ts +20 -11
- package/server/src/transcriptWorker.ts +182 -0
- package/server/src/workflowStore.ts +21 -0
- package/server/src/ws/clusterHandlers.ts +46 -27
- 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/autoPickup.d.ts +3 -0
- 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/autoPickup.ts +5 -0
- 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,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
|
-
|
|
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 (
|
|
2005
|
-
const
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
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.
|
|
2041
|
-
|
|
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: !!
|
|
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
|
|
2260
|
-
send(ws, { type: 'error', message: `cluster_member_role_set rejected:
|
|
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
|
|
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 {
|
|
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
|
-
|
|
1843
|
-
|
|
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((
|
|
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({
|