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
|
@@ -17,7 +17,7 @@ import { imageBase64TokenCost } from '../imageTokens.js';
|
|
|
17
17
|
// so it can compact BEFORE the request overflows the window, not after a
|
|
18
18
|
// 400. This module is that estimate.
|
|
19
19
|
//
|
|
20
|
-
// THE LOAD-BEARING GOTCHA (
|
|
20
|
+
// THE LOAD-BEARING GOTCHA (Hardening §5): a naïve estimate
|
|
21
21
|
// that only counts visible `content` text undershoots by 20-30% on tool-heavy
|
|
22
22
|
// transcripts, because a tool-CALL assistant turn carries `content:""` with
|
|
23
23
|
// the entire payload in `tool_calls[].function.arguments`, and a tool-RESULT
|
|
@@ -5,14 +5,14 @@ import { PLAN_TOOL_NAMES } from '../planTools.js';
|
|
|
5
5
|
// ── Why subset at all ───────────────────────────────────────────────────────
|
|
6
6
|
// Arco advertises its ENTIRE tool registry on every /api/chat turn. On
|
|
7
7
|
// 7B–30B-class local models a large tool-schema payload degrades tool
|
|
8
|
-
// selection (wrong-tool / single-token-stop failures
|
|
8
|
+
// selection (wrong-tool / single-token-stop failures) AND
|
|
9
9
|
// burns input context (the schemas ride every request). We trim the advertised
|
|
10
10
|
// set to a relevant top-K so the schema stays small and selection stays sharp.
|
|
11
11
|
//
|
|
12
12
|
// ── Why a HEURISTIC (no embeddings) ─────────────────────────────────────────
|
|
13
13
|
// Arco's catalog is ~12 tools. Keyword/term-overlap ranking against the
|
|
14
|
-
// task context is more than enough; an embedding model + vector index
|
|
15
|
-
//
|
|
14
|
+
// task context is more than enough; an embedding model + vector index is
|
|
15
|
+
// rejected as overkill for a 12-item set
|
|
16
16
|
// (Hardening §1 "Out"). Deterministic, readable, inspectable — the M10
|
|
17
17
|
// guardrail.
|
|
18
18
|
//
|
package/server/src/quota.ts
CHANGED
|
@@ -137,53 +137,3 @@ export function wireSnapshot(): Record<ProviderName, { throttled: boolean; reset
|
|
|
137
137
|
}
|
|
138
138
|
return out;
|
|
139
139
|
}
|
|
140
|
-
|
|
141
|
-
/**
|
|
142
|
-
* Legacy PROVIDER STATUS formatter, currently without live callers. Returns empty string when every
|
|
143
|
-
* provider is available — no need to clutter the prompt when routing is
|
|
144
|
-
* unconstrained. See §6.4 for the format.
|
|
145
|
-
*/
|
|
146
|
-
export function buildQuotaInjection(): string {
|
|
147
|
-
const snap = snapshot();
|
|
148
|
-
const anyThrottled = PROVIDERS.some((p) => snap[p].throttled);
|
|
149
|
-
if (!anyThrottled) return '';
|
|
150
|
-
const lines: string[] = ['## PROVIDER STATUS'];
|
|
151
|
-
for (const p of PROVIDERS) {
|
|
152
|
-
const s = snap[p];
|
|
153
|
-
if (s.throttled) {
|
|
154
|
-
const suffix = s.resetsAt
|
|
155
|
-
? ` until ${new Date(s.resetsAt).toISOString()}`
|
|
156
|
-
: ' (no reset time known)';
|
|
157
|
-
lines.push(`- ${p}: THROTTLED${suffix}`);
|
|
158
|
-
} else {
|
|
159
|
-
lines.push(`- ${p}: available`);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
lines.push('');
|
|
163
|
-
lines.push('Dispatch AWAY from throttled providers. If a capable worker from an available provider can cover the task, pick that one. Throttled-provider spawns will fail — the cost of retrying is wasted tokens and a stuck workflow.');
|
|
164
|
-
return lines.join('\n');
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* §5.4 cross-family reviewer fallback. Maps a primary model to a cross-family
|
|
169
|
-
* reviewer used when the preferred reviewer's provider is throttled. Returns
|
|
170
|
-
* null for models that intentionally skip review (ollama / heretic).
|
|
171
|
-
*
|
|
172
|
-
* Legacy helper, currently without live callers. Kept for a separate cleanup.
|
|
173
|
-
*/
|
|
174
|
-
export interface ReviewerFallback {
|
|
175
|
-
model: string;
|
|
176
|
-
provider: ProviderName;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
export function crossFamilyFallback(primaryModel: string): ReviewerFallback | null {
|
|
180
|
-
// Codex → Claude
|
|
181
|
-
if (primaryModel === 'gpt-5.4-mini') return { model: 'opus', provider: 'claude' };
|
|
182
|
-
if (primaryModel === 'gpt-5.3-codex') return { model: 'opus', provider: 'claude' };
|
|
183
|
-
if (primaryModel === 'gpt-5.2-codex') return { model: 'opus', provider: 'claude' };
|
|
184
|
-
if (primaryModel === 'gpt-5.5') return { model: 'opus', provider: 'claude' };
|
|
185
|
-
if (primaryModel === 'gpt-5.4') return { model: 'opus', provider: 'claude' };
|
|
186
|
-
if (primaryModel === 'gpt-5.1-codex-max') return { model: 'opus', provider: 'claude' };
|
|
187
|
-
// Heretic (ollama) — review intentionally skipped.
|
|
188
|
-
return null;
|
|
189
|
-
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { buildTranscriptSlice, type TranscriptSliceOptions } from './transcriptWorker.js';
|
|
3
|
+
import { replayEvents } from './workflowStore.js';
|
|
4
|
+
import { renderTranscript, summarizePriorTurns } from './primitives/exportContext.js';
|
|
5
|
+
import { RECENT_HISTORY_MAX_BYTES } from './historyLimits.js';
|
|
6
|
+
|
|
7
|
+
export const REPLACEMENT_FULL_BYTES = 512 * 1024;
|
|
8
|
+
export const REPLACEMENT_RECENT_BYTES = RECENT_HISTORY_MAX_BYTES;
|
|
9
|
+
export type ReplacementHistoryMode = 'recent' | 'full';
|
|
10
|
+
|
|
11
|
+
export async function buildReplacementHistory(cwd: string, workflowId: string, mode: ReplacementHistoryMode, options: TranscriptSliceOptions) {
|
|
12
|
+
if (mode !== 'recent' && mode !== 'full') throw new Error('Choose NO HISTORY, RECENT HISTORY or FULL HISTORY.');
|
|
13
|
+
const slice = await buildTranscriptSlice(cwd, workflowId, { ...options, turns: mode === 'full' ? Number.MAX_SAFE_INTEGER : options.turns }, {
|
|
14
|
+
maxBytes: mode === 'full' ? REPLACEMENT_FULL_BYTES : REPLACEMENT_RECENT_BYTES,
|
|
15
|
+
fitWholeTurns: true, allTurns: mode === 'full',
|
|
16
|
+
});
|
|
17
|
+
let seed = slice.seed, selectedTurns = slice.selectedTurns, historyFallback = false;
|
|
18
|
+
if (mode === 'full') {
|
|
19
|
+
// Preserve the existing full-history transcript and action digest while
|
|
20
|
+
// they fit. Only the oversized fallback uses the shared recent-turn form.
|
|
21
|
+
const events = (await replayEvents(cwd, workflowId, 0)).filter(event => !('seq' in event) || typeof event.seq !== 'number' || event.seq <= slice.cutoffSeq);
|
|
22
|
+
const transcript = renderTranscript(events).trim(), actions = summarizePriorTurns(events).trim();
|
|
23
|
+
const full = [
|
|
24
|
+
'[REPLACEMENT CONTEXT — copied by explicit operator request; this is a new provider session]',
|
|
25
|
+
transcript,
|
|
26
|
+
actions ? `\n[Prior-turn action digest]\n${actions}` : '',
|
|
27
|
+
'\nAcknowledge this imported context briefly, then wait for the operator.',
|
|
28
|
+
].filter(Boolean).join('\n\n');
|
|
29
|
+
if (Buffer.byteLength(full, 'utf8') <= REPLACEMENT_FULL_BYTES) { seed = full; selectedTurns = slice.availableTurns; }
|
|
30
|
+
else historyFallback = true;
|
|
31
|
+
}
|
|
32
|
+
const bytes = Buffer.byteLength(seed, 'utf8');
|
|
33
|
+
const digest = createHash('sha256').update(JSON.stringify({ source: slice.digest, seed, mode, turns: options.turns })).digest('hex');
|
|
34
|
+
return { ...slice, seed, bytes, selectedTurns, digest, historyMode: mode,
|
|
35
|
+
requestedTurns: mode === 'full' ? slice.availableTurns : options.turns,
|
|
36
|
+
truncated: selectedTurns < slice.availableTurns, historyFallback };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function replacementHistoryNotice(preview: Awaited<ReturnType<typeof buildReplacementHistory>>): string | undefined {
|
|
40
|
+
if (!preview.truncated && !preview.historyFallback) return;
|
|
41
|
+
if (!preview.selectedTurns) return 'No whole recent turn fit the replacement history limit. No earlier history was copied; it remains in the previous member conversation.';
|
|
42
|
+
if (preview.truncated) return `Only the most recent ${preview.selectedTurns} of ${preview.availableTurns} turns were copied from the previous member. Earlier turns were not copied; they remain in its conversation.`;
|
|
43
|
+
return `The full history exceeded 512 KiB. All ${preview.selectedTurns} turns were copied as text and tool/file receipts; the full action digest was not copied.`;
|
|
44
|
+
}
|
|
@@ -631,6 +631,7 @@ export function sendWorkflowLive(workflowId: string, message: ServerMessage, sen
|
|
|
631
631
|
}
|
|
632
632
|
|
|
633
633
|
export async function buildClusterStatePayload(clusterId: string): Promise<{
|
|
634
|
+
skillPins?: import('@arco/shared').ClusterSkillPin[];
|
|
634
635
|
clusterId: string;
|
|
635
636
|
cwd: string;
|
|
636
637
|
members: Array<{
|
|
@@ -709,6 +710,7 @@ export async function buildClusterStatePayload(clusterId: string): Promise<{
|
|
|
709
710
|
}
|
|
710
711
|
return {
|
|
711
712
|
clusterId,
|
|
713
|
+
...(state.skillPins?.length ? { skillPins: state.skillPins } : {}),
|
|
712
714
|
cwd: state.cwd,
|
|
713
715
|
members,
|
|
714
716
|
mailboxDepth,
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { buildTurnWaitInstructions } from '@arco/shared';
|
|
2
|
+
|
|
1
3
|
// Tells the agent the operator can see a live iframe of any dev server it
|
|
2
4
|
// runs. Static text — appended verbatim to every primary turn so the prefix
|
|
3
5
|
// cache keeps hitting (Claude / Codex caches; Ollama prefix cache). The
|
|
@@ -15,6 +17,12 @@ export function withPreviewNudge(existing: string | undefined): string {
|
|
|
15
17
|
return existing && existing.length > 0 ? `${PREVIEW_NUDGE}\n\n${existing}` : PREVIEW_NUDGE;
|
|
16
18
|
}
|
|
17
19
|
|
|
20
|
+
// Local baselines are role-neutral. Add the wait rule once, after the turn's
|
|
21
|
+
// membership is resolved, before wrapping any cluster coordination around it.
|
|
22
|
+
export function withLocalTurnWaitInstructions(base: string | undefined, role?: string): string {
|
|
23
|
+
return [buildTurnWaitInstructions(role), base].filter(Boolean).join('\n\n');
|
|
24
|
+
}
|
|
25
|
+
|
|
18
26
|
export function buildLocalClusterSystemPrompt(opts: {
|
|
19
27
|
base?: string;
|
|
20
28
|
clusterPlan?: string;
|
|
@@ -70,7 +78,6 @@ export const OLLAMA_PRIMARY_SYSTEM_PROMPT = [
|
|
|
70
78
|
'When the operator asks about the project, start by exploring (Glob the top-level files, Read the README or CLAUDE.md, Grep for relevant terms) before answering. When they ask about something specific, go straight to the file.',
|
|
71
79
|
'Be concise. Default to plain prose. Only use headers, tables, or executive-summary formatting when the operator explicitly asks for that format.',
|
|
72
80
|
'Honor the safety reminders appended to each user message: cap unknown-size shell output, no `find /` without `-maxdepth`, no unbounded scans.',
|
|
73
|
-
'Finishing the request does not mean waiting for it: do not sleep or poll for more than 60 seconds at a time for builds, test suites or CI; report what is running and end the turn.',
|
|
74
81
|
].join(' ');
|
|
75
82
|
|
|
76
83
|
// llama.cpp-specific system prompt. Same baseline as Ollama plus extra
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { watch } from 'fs';
|
|
2
|
-
import {
|
|
3
|
-
import { join, resolve } from 'path';
|
|
1
|
+
import { watch, statSync } from 'fs';
|
|
2
|
+
import { open, type FileHandle } from 'fs/promises';
|
|
3
|
+
import { basename, dirname, join, resolve } from 'path';
|
|
4
4
|
import { homedir } from 'os';
|
|
5
|
+
import { jsonlLines } from './jsonlLines.js';
|
|
5
6
|
|
|
6
7
|
export interface SessionJsonlEntry {
|
|
7
8
|
type: string;
|
|
@@ -43,30 +44,58 @@ export function resolveSubagentsWorkflowsDir(cwd: string, sessionId: string): st
|
|
|
43
44
|
export async function loadSessionJsonl(
|
|
44
45
|
path: string,
|
|
45
46
|
): Promise<{ entries: SessionJsonlEntry[]; byteLength: number }> {
|
|
46
|
-
let
|
|
47
|
+
let fh: FileHandle;
|
|
47
48
|
try {
|
|
48
|
-
|
|
49
|
-
} catch {
|
|
50
|
-
return { entries: [], byteLength: 0 };
|
|
49
|
+
fh = await open(path, 'r');
|
|
50
|
+
} catch (err) {
|
|
51
|
+
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { entries: [], byteLength: 0 };
|
|
52
|
+
throw err;
|
|
51
53
|
}
|
|
52
54
|
const entries: SessionJsonlEntry[] = [];
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
55
|
+
let complete = 0;
|
|
56
|
+
try {
|
|
57
|
+
const size = (await fh.stat()).size;
|
|
58
|
+
async function* chunks(): AsyncGenerator<Buffer> {
|
|
59
|
+
for (let position = 0; position < size;) {
|
|
60
|
+
const buffer = Buffer.alloc(Math.min(64 * 1024, size - position));
|
|
61
|
+
const { bytesRead } = await fh.read(buffer, 0, buffer.length, position);
|
|
62
|
+
if (!bytesRead) break;
|
|
63
|
+
const chunk = buffer.subarray(0, bytesRead);
|
|
64
|
+
const newline = chunk.lastIndexOf(0x0a);
|
|
65
|
+
if (newline >= 0) complete = position + newline + 1;
|
|
66
|
+
position += bytesRead;
|
|
67
|
+
yield chunk;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for await (const line of jsonlLines(chunks(), path, { finalLine: false, carriageReturns: false })) {
|
|
71
|
+
if (!line.trim()) continue;
|
|
72
|
+
try {
|
|
73
|
+
const e = JSON.parse(line) as SessionJsonlEntry;
|
|
74
|
+
if (e && typeof e.type === 'string') entries.push(e);
|
|
75
|
+
} catch { /* skip malformed lines */ }
|
|
76
|
+
}
|
|
77
|
+
return { entries, byteLength: complete };
|
|
78
|
+
} finally { await fh.close(); }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function lastCompleteOffset(fh: FileHandle, size: number): Promise<number> {
|
|
82
|
+
for (let end = size; end > 0;) {
|
|
83
|
+
const start = Math.max(0, end - 64 * 1024), buffer = Buffer.alloc(end - start);
|
|
84
|
+
const { bytesRead } = await fh.read(buffer, 0, buffer.length, start);
|
|
85
|
+
const newline = buffer.subarray(0, bytesRead).lastIndexOf(0x0a);
|
|
86
|
+
if (newline >= 0) return start + newline + 1;
|
|
87
|
+
end = start;
|
|
60
88
|
}
|
|
61
|
-
return
|
|
89
|
+
return 0;
|
|
62
90
|
}
|
|
63
91
|
|
|
64
92
|
// Tail the session JSONL for new entries, emitting each one via `onEntry`.
|
|
65
93
|
// `initialOffset` should be the byteLength from loadSessionJsonl so we
|
|
66
|
-
// don't re-emit history.
|
|
94
|
+
// don't re-emit history. Null anchors at the first readable complete boundary
|
|
95
|
+
// after initial loading failed. Returns a dispose function.
|
|
67
96
|
export function watchSessionJsonl(
|
|
68
97
|
path: string,
|
|
69
|
-
initialOffset: number,
|
|
98
|
+
initialOffset: number | null,
|
|
70
99
|
onEntry: (entry: SessionJsonlEntry) => void,
|
|
71
100
|
): () => void {
|
|
72
101
|
let lastOffset = initialOffset;
|
|
@@ -76,6 +105,8 @@ export function watchSessionJsonl(
|
|
|
76
105
|
|
|
77
106
|
let reading = false;
|
|
78
107
|
let requested = false;
|
|
108
|
+
let identity: string | undefined;
|
|
109
|
+
try { const st = statSync(path); identity = `${st.dev}:${st.ino}`; } catch { /* not created yet */ }
|
|
79
110
|
const readNew = async () => {
|
|
80
111
|
if (!active) return;
|
|
81
112
|
requested = true;
|
|
@@ -85,20 +116,45 @@ export function watchSessionJsonl(
|
|
|
85
116
|
while (active && requested) {
|
|
86
117
|
requested = false;
|
|
87
118
|
try {
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
if (buf.length < lastOffset) lastOffset = 0;
|
|
91
|
-
const end = buf.lastIndexOf(10) + 1;
|
|
92
|
-
if (end <= lastOffset) continue;
|
|
93
|
-
const slice = buf.subarray(lastOffset, end).toString('utf-8');
|
|
94
|
-
lastOffset = end;
|
|
95
|
-
for (const line of slice.split('\n')) {
|
|
119
|
+
const fh = await open(path, 'r');
|
|
120
|
+
try {
|
|
96
121
|
if (!active) return;
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
122
|
+
const st = await fh.stat();
|
|
123
|
+
const nextIdentity = `${st.dev}:${st.ino}`;
|
|
124
|
+
// After an initial-load failure, anchor to the first readable
|
|
125
|
+
// complete boundary. Old terminal rows must not look like new
|
|
126
|
+
// concurrent-session writes; an unfinished last row stays pending.
|
|
127
|
+
if (lastOffset === null) {
|
|
128
|
+
lastOffset = await lastCompleteOffset(fh, st.size);
|
|
129
|
+
identity = nextIdentity;
|
|
130
|
+
}
|
|
131
|
+
if ((identity !== undefined && identity !== nextIdentity) || st.size < lastOffset) lastOffset = 0;
|
|
132
|
+
identity = nextIdentity;
|
|
133
|
+
const startOffset = lastOffset;
|
|
134
|
+
let completeOffset = startOffset;
|
|
135
|
+
// Read only the appended range. An unfinished record is left at
|
|
136
|
+
// lastOffset and completed by the next notification, as before.
|
|
137
|
+
async function* chunks(): AsyncGenerator<Buffer> {
|
|
138
|
+
for (let position = startOffset; active && position < st.size;) {
|
|
139
|
+
const buffer = Buffer.alloc(Math.min(64 * 1024, st.size - position));
|
|
140
|
+
const { bytesRead } = await fh.read(buffer, 0, buffer.length, position);
|
|
141
|
+
if (!bytesRead) break;
|
|
142
|
+
const chunk = buffer.subarray(0, bytesRead);
|
|
143
|
+
const newline = chunk.lastIndexOf(0x0a);
|
|
144
|
+
if (newline >= 0) completeOffset = position + newline + 1;
|
|
145
|
+
position += bytesRead;
|
|
146
|
+
yield chunk;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
for await (const line of jsonlLines(chunks(), path, { finalLine: false, carriageReturns: false })) {
|
|
150
|
+
if (!active) return;
|
|
151
|
+
if (!line.trim()) continue;
|
|
152
|
+
let e: SessionJsonlEntry;
|
|
153
|
+
try { e = JSON.parse(line); } catch { continue; }
|
|
154
|
+
if (e && typeof e.type === 'string') onEntry(e);
|
|
155
|
+
}
|
|
156
|
+
lastOffset = completeOffset;
|
|
157
|
+
} finally { await fh.close(); }
|
|
102
158
|
} catch { /* file unavailable; retry at the next notification */ }
|
|
103
159
|
}
|
|
104
160
|
} finally { reading = false; }
|
|
@@ -119,14 +175,18 @@ export function watchSessionJsonl(
|
|
|
119
175
|
const startWatcher = () => {
|
|
120
176
|
if (!active || watcher) return;
|
|
121
177
|
try {
|
|
122
|
-
|
|
178
|
+
// Watching the directory survives replacement of the session file;
|
|
179
|
+
// an inode-bound watcher would keep watching the removed file.
|
|
180
|
+
watcher = watch(dirname(path), { persistent: false }, (_event, name) => {
|
|
181
|
+
if (name === null || name === basename(path)) void readNew();
|
|
182
|
+
});
|
|
123
183
|
void readNew();
|
|
124
184
|
watcher.on('error', () => {
|
|
125
185
|
watcher = null;
|
|
126
186
|
scheduleRestart();
|
|
127
187
|
});
|
|
128
188
|
} catch {
|
|
129
|
-
//
|
|
189
|
+
// Session directory not yet created — retry after 2s (happens for brand-new sessions)
|
|
130
190
|
scheduleRestart();
|
|
131
191
|
}
|
|
132
192
|
};
|
|
@@ -19,7 +19,7 @@ import { nativeOAuthBaseUrl } from './providers/claude-native/apiEndpoint.js';
|
|
|
19
19
|
// agent message is kept. Any command, file change, tool or web
|
|
20
20
|
// item, or any approval or other server request, interrupts the
|
|
21
21
|
// turn, kills the process and gives no decision.
|
|
22
|
-
import { spawn } from 'node:child_process';
|
|
22
|
+
import { spawn, type ChildProcess } from 'node:child_process';
|
|
23
23
|
import { mkdtemp, realpath, rm } from 'node:fs/promises';
|
|
24
24
|
import { tmpdir } from 'node:os';
|
|
25
25
|
import { join } from 'node:path';
|
|
@@ -229,6 +229,20 @@ export function claudeAdapter(opts: { fetchImpl?: typeof fetch; tokens?: () => P
|
|
|
229
229
|
};
|
|
230
230
|
}
|
|
231
231
|
|
|
232
|
+
// A terminating child can still hold its cwd open on Windows. Allow up to
|
|
233
|
+
// 250 ms for exit, then at most 600 ms of removal retries. Cleanup must never
|
|
234
|
+
// change the evaluator's answer or refusal.
|
|
235
|
+
async function removeEvaluatorFolder(proc: ChildProcess, cwd: string): Promise<void> {
|
|
236
|
+
if (proc.pid && proc.exitCode === null && proc.signalCode === null) {
|
|
237
|
+
await new Promise<void>((resolve) => {
|
|
238
|
+
const done = () => { clearTimeout(timer); proc.off('close', done); resolve(); };
|
|
239
|
+
const timer = setTimeout(done, 250);
|
|
240
|
+
proc.once('close', done);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
await rm(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }).catch(() => undefined);
|
|
244
|
+
}
|
|
245
|
+
|
|
232
246
|
export function cursorAdapter(opts: { launch?: (model: string) => [string, string[]]; installed?: () => Promise<boolean>; catalog?: () => Promise<string[]> } = {}): EvaluatorAdapter {
|
|
233
247
|
// `cursor-agent acp` ignores `--model`; the model is selected over ACP after
|
|
234
248
|
// session/new and confirmed, and the evaluator refuses rather than answer
|
|
@@ -343,7 +357,7 @@ export function cursorAdapter(opts: { launch?: (model: string) => [string, strin
|
|
|
343
357
|
clearTimeout(timer);
|
|
344
358
|
req.signal?.removeEventListener('abort', onAbort);
|
|
345
359
|
stop();
|
|
346
|
-
await
|
|
360
|
+
await removeEvaluatorFolder(proc, cwd);
|
|
347
361
|
}
|
|
348
362
|
},
|
|
349
363
|
};
|
|
@@ -466,7 +480,7 @@ export function codexAdapter(opts: { launch?: () => [string, string[]]; usable?:
|
|
|
466
480
|
clearTimeout(timer);
|
|
467
481
|
req.signal?.removeEventListener('abort', onAbort);
|
|
468
482
|
stop();
|
|
469
|
-
await
|
|
483
|
+
await removeEvaluatorFolder(proc, cwd);
|
|
470
484
|
}
|
|
471
485
|
},
|
|
472
486
|
};
|
|
@@ -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.
|