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
|
@@ -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
|
};
|
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
} from '@arco/shared';
|
|
15
15
|
import * as ruleAutoTurn from './clusterAutoTurn.js';
|
|
16
16
|
import * as clusterStore from './clusterStore.js';
|
|
17
|
+
import { pickupSmartWaitingMail } from './smartPickupObserver.js';
|
|
17
18
|
import { evaluatorAdapter } from './smartPickupAdapters.js';
|
|
18
19
|
import {
|
|
19
20
|
recordSmartPickupDecision,
|
|
@@ -31,14 +32,14 @@ export const SMART_PICKUP_SWEEP_MS = (() => {
|
|
|
31
32
|
return Number.isInteger(raw) && raw >= 50 ? raw : 15_000;
|
|
32
33
|
})();
|
|
33
34
|
|
|
34
|
-
export type ArmProblem = 'unknown_cluster' | 'invalid_mode' | 'evaluator_required' | 'evaluator_provider_disabled' | 'evaluator_unavailable' | 'ledger_unreadable';
|
|
35
|
+
export type ArmProblem = 'unknown_cluster' | 'invalid_mode' | 'invalid_pause' | 'evaluator_required' | 'evaluator_provider_disabled' | 'evaluator_unavailable' | 'ledger_unreadable';
|
|
35
36
|
|
|
36
37
|
// Validate and apply an operator's AUTO-PICKUP choice. A Smart mode needs an
|
|
37
38
|
// evaluator whose provider is enabled and a readable budget ledger; arming
|
|
38
39
|
// always starts a fresh session. Every change is logged in the ledger.
|
|
39
40
|
export async function applyAutoPickup(
|
|
40
41
|
clusterId: string,
|
|
41
|
-
request: { mode: unknown; evaluator?: unknown; limits?: unknown; ruleLimits?: unknown; resumeRule?: boolean; remindBusy?: boolean },
|
|
42
|
+
request: { mode: unknown; paused?: unknown; evaluator?: unknown; limits?: unknown; ruleLimits?: unknown; resumeRule?: boolean; remindBusy?: boolean },
|
|
42
43
|
isProviderEnabled: (provider: SmartPickupEvaluator['provider']) => boolean,
|
|
43
44
|
now = Date.now(),
|
|
44
45
|
): Promise<{ ok: true; mode: AutoPickupMode } | { ok: false; problem: ArmProblem }> {
|
|
@@ -46,6 +47,27 @@ export async function applyAutoPickup(
|
|
|
46
47
|
if (mode !== 'off' && mode !== 'rule' && mode !== 'smart-observe' && mode !== 'smart-auto') return { ok: false, problem: 'invalid_mode' };
|
|
47
48
|
const state = clusterStore.getClusterCached(clusterId) ?? await clusterStore.readCluster(clusterId).catch(() => null);
|
|
48
49
|
if (!state) return { ok: false, problem: 'unknown_cluster' };
|
|
50
|
+
if (request.paused !== undefined) {
|
|
51
|
+
if (typeof request.paused !== 'boolean' || mode === 'off' || mode !== clusterStore.autoPickupModeOf(state)
|
|
52
|
+
|| request.resumeRule || request.evaluator !== undefined || request.limits !== undefined || request.ruleLimits !== undefined || request.remindBusy !== undefined) return { ok: false, problem: 'invalid_pause' };
|
|
53
|
+
const session = state.smartPickup?.session;
|
|
54
|
+
if (isSmartPickupMode(mode) && (!session || (state.autoPickupPausedAt ?? now) >= session.expiresAt)) {
|
|
55
|
+
await disarm(clusterId, session ? 'session_expired' : 'session_missing', now);
|
|
56
|
+
return { ok: true, mode: 'off' };
|
|
57
|
+
}
|
|
58
|
+
const updated = await clusterStore.setAutoPickup(clusterId, { mode, paused: request.paused, now });
|
|
59
|
+
if (!updated) return { ok: false, problem: 'invalid_pause' };
|
|
60
|
+
await recordSmartPickupDecision(clusterId, { at: now, action: null, reason: request.paused ? 'operator_paused' : 'operator_resumed', outcome: 'none' }).catch(() => undefined);
|
|
61
|
+
if (state.autoPickupPausedAt !== undefined && !request.paused) {
|
|
62
|
+
// Reply with the new control state promptly; evaluator requests may take
|
|
63
|
+
// time. Both scans use the same admission path as ordinary waiting mail.
|
|
64
|
+
setImmediate(() => {
|
|
65
|
+
void (mode === 'rule' ? ruleAutoTurn.pickupWaitingMail(clusterId) : pickupSmartWaitingMail(clusterId)).catch((error) => console.error('[arco] auto-pickup resume failed:', error));
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return { ok: true, mode };
|
|
69
|
+
}
|
|
70
|
+
if (request.resumeRule && state.autoPickupPausedAt !== undefined) return { ok: false, problem: 'invalid_pause' };
|
|
49
71
|
let evaluator: SmartPickupEvaluator | undefined;
|
|
50
72
|
if (isSmartPickupMode(mode)) {
|
|
51
73
|
evaluator = sanitizeSmartPickupEvaluator(request.evaluator) ?? undefined;
|
|
@@ -99,6 +121,8 @@ export async function autoPickupStateFor(state: clusterStore.ClusterState, now =
|
|
|
99
121
|
const smart = state.smartPickup ?? {};
|
|
100
122
|
const out: ClusterAutoPickupState = {
|
|
101
123
|
mode,
|
|
124
|
+
paused: state.autoPickupPausedAt !== undefined,
|
|
125
|
+
...(state.autoPickupPausedAt !== undefined ? { pausedAt: state.autoPickupPausedAt } : {}),
|
|
102
126
|
remindBusy: state.remindBusy === true,
|
|
103
127
|
limits: sanitizeSmartPickupLimits(smart.limits),
|
|
104
128
|
ruleLimits: sanitizeRulePickupLimits(state.rulePickupLimits),
|
|
@@ -134,7 +158,7 @@ export async function sweepSmartPickup(now = Date.now()): Promise<void> {
|
|
|
134
158
|
if (!state || !isSmartPickupMode(clusterStore.autoPickupModeOf(state))) continue;
|
|
135
159
|
const session = state.smartPickup?.session;
|
|
136
160
|
if (!session || !state.smartPickup?.evaluator) { await disarm(clusterId, 'session_missing', now); continue; }
|
|
137
|
-
if (now >= session.expiresAt) { await disarm(clusterId, 'session_expired', now); continue; }
|
|
161
|
+
if (state.autoPickupPausedAt === undefined && now >= session.expiresAt) { await disarm(clusterId, 'session_expired', now); continue; }
|
|
138
162
|
try { await smartPickupSnapshot(clusterId, session.id, now); }
|
|
139
163
|
catch { await disarm(clusterId, 'ledger_unreadable', now); }
|
|
140
164
|
}
|
|
@@ -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
|
};
|
|
@@ -11,7 +11,7 @@ import { join } from 'node:path';
|
|
|
11
11
|
import { randomUUID } from 'node:crypto';
|
|
12
12
|
import type { SmartPickupCounters, SmartPickupDecisionRecord, SmartPickupLimits } from '@arco/shared';
|
|
13
13
|
import { atomicWriteFile } from './atomicFile.js';
|
|
14
|
-
import { clusterDir } from './clusterStore.js';
|
|
14
|
+
import { clusterDir, getClusterCached } from './clusterStore.js';
|
|
15
15
|
|
|
16
16
|
export type SmartPickupReservationKind = 'evaluator' | 'wake';
|
|
17
17
|
|
|
@@ -36,8 +36,9 @@ interface LedgerFile {
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
const HOUR_MS = 60 * 60 * 1000;
|
|
39
|
-
//
|
|
40
|
-
// of at most 8 hours), so they are dropped on the next write.
|
|
39
|
+
// Older entries normally cannot affect a limit (hour windows and sessions
|
|
40
|
+
// of at most 8 hours), so they are dropped on the next write. Pauses can
|
|
41
|
+
// extend a session's wall-clock life: retain its entries until it ends.
|
|
41
42
|
const RETAIN_MS = 9 * HOUR_MS;
|
|
42
43
|
const DECISIONS_KEPT = 50;
|
|
43
44
|
|
|
@@ -75,7 +76,8 @@ async function read(clusterId: string): Promise<LedgerFile> {
|
|
|
75
76
|
}
|
|
76
77
|
|
|
77
78
|
async function write(clusterId: string, ledger: LedgerFile, now: number): Promise<void> {
|
|
78
|
-
|
|
79
|
+
const activeSession = getClusterCached(clusterId)?.smartPickup?.session?.id;
|
|
80
|
+
ledger.entries = ledger.entries.filter((e) => e.status === 'reserved' || e.sessionId === activeSession || now - e.at < RETAIN_MS);
|
|
79
81
|
ledger.decisions = ledger.decisions.slice(-DECISIONS_KEPT);
|
|
80
82
|
await fs.mkdir(clusterDir(clusterId), { recursive: true });
|
|
81
83
|
await atomicWriteFile(ledgerPath(clusterId), JSON.stringify(ledger, null, 2));
|
|
@@ -130,7 +130,7 @@ function armed(clusterId: string): { sessionId: string; mode: 'smart-observe' |
|
|
|
130
130
|
if (!state) return null;
|
|
131
131
|
const mode = clusterStore.autoPickupModeOf(state);
|
|
132
132
|
const session = state.smartPickup?.session;
|
|
133
|
-
if (!isSmartPickupMode(mode) || !session || !state.smartPickup?.evaluator) return null;
|
|
133
|
+
if (state.autoPickupPausedAt !== undefined || !isSmartPickupMode(mode) || !session || !state.smartPickup?.evaluator) return null;
|
|
134
134
|
if (deps.now() >= session.expiresAt) return null;
|
|
135
135
|
return { sessionId: session.id, mode };
|
|
136
136
|
}
|
|
@@ -139,9 +139,9 @@ function armed(clusterId: string): { sessionId: string; mode: 'smart-observe' |
|
|
|
139
139
|
// evaluation per recipient at a time; a trigger during a run schedules one
|
|
140
140
|
// more pass afterwards.
|
|
141
141
|
export function onSmartPickupMail(clusterId: string, workflowId: string, chainDepth = 0): Promise<void> {
|
|
142
|
-
if (!armed(clusterId)) return Promise.resolve();
|
|
143
142
|
const k = key(clusterId, workflowId);
|
|
144
143
|
if (chainDepth > (depthSeen.get(k) ?? 0)) depthSeen.set(k, chainDepth);
|
|
144
|
+
if (!armed(clusterId)) return Promise.resolve();
|
|
145
145
|
const current = running.get(k);
|
|
146
146
|
if (current) { rerun.add(k); return current; }
|
|
147
147
|
const run = (async () => {
|
|
@@ -205,6 +205,7 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
|
|
|
205
205
|
return d;
|
|
206
206
|
}
|
|
207
207
|
const evaluator = state.smartPickup!.evaluator!;
|
|
208
|
+
if (armed(clusterId)?.sessionId !== arm.sessionId) return null;
|
|
208
209
|
const slot = await reserveSmartPickup(clusterId, { kind: 'evaluator', memberId: workflowId, sessionId: arm.sessionId, limits, now: deps.now() }).catch(() => ({ ok: false as const, reason: 'ledger_unreadable' }));
|
|
209
210
|
if (!slot.ok) {
|
|
210
211
|
const d = { ...base, action: null, reason: slot.reason, outcome: 'skipped' };
|
|
@@ -219,6 +220,10 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
|
|
|
219
220
|
}
|
|
220
221
|
let raw: string | null = null;
|
|
221
222
|
let failure: string | null = null;
|
|
223
|
+
if (armed(clusterId)?.sessionId !== arm.sessionId) {
|
|
224
|
+
await settleSmartPickup(clusterId, slot.id, 'session_changed', deps.now()).catch(() => undefined);
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
222
227
|
try {
|
|
223
228
|
raw = await evaluatorAdapter(evaluator.provider).evaluate({
|
|
224
229
|
model: evaluator.model,
|
|
@@ -361,21 +366,25 @@ export async function sweepSmartPickupMail(): Promise<void> {
|
|
|
361
366
|
sweeping = true;
|
|
362
367
|
try {
|
|
363
368
|
for (const clusterId of clusterStore.listKnownClusterIds().sort()) {
|
|
364
|
-
|
|
365
|
-
const members = [...(clusterStore.getClusterCached(clusterId)?.members ?? [])].sort();
|
|
366
|
-
// One member at a time per cluster, in a stable order, so the
|
|
367
|
-
// in-flight limit is respected and no mailbox starves another.
|
|
368
|
-
for (const wfid of members) {
|
|
369
|
-
if (deps.isBusy(wfid)) continue;
|
|
370
|
-
const depth = await clusterMailbox.depthFor(wfid).catch(() => 0);
|
|
371
|
-
if (depth > 0) await onSmartPickupMail(clusterId, wfid).catch(() => undefined);
|
|
372
|
-
}
|
|
369
|
+
await pickupSmartWaitingMail(clusterId);
|
|
373
370
|
}
|
|
374
371
|
} finally {
|
|
375
372
|
sweeping = false;
|
|
376
373
|
}
|
|
377
374
|
}
|
|
378
375
|
|
|
376
|
+
export async function pickupSmartWaitingMail(clusterId: string): Promise<void> {
|
|
377
|
+
if (!armed(clusterId)) return;
|
|
378
|
+
const members = [...(clusterStore.getClusterCached(clusterId)?.members ?? [])].sort();
|
|
379
|
+
// One member at a time per cluster, in a stable order, so the
|
|
380
|
+
// in-flight limit is respected and no mailbox starves another.
|
|
381
|
+
for (const wfid of members) {
|
|
382
|
+
if (deps.isBusy(wfid)) continue;
|
|
383
|
+
const depth = await clusterMailbox.depthFor(wfid).catch(() => 0);
|
|
384
|
+
if (depth > 0) await onSmartPickupMail(clusterId, wfid).catch(() => undefined);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
379
388
|
let mailTimer: NodeJS.Timeout | null = null;
|
|
380
389
|
const MAIL_SWEEP_MS = (() => {
|
|
381
390
|
const raw = Number(process.env.ARCO_SMART_PICKUP_MAIL_SWEEP_MS);
|