arco-workbench 0.1.5 → 0.1.7
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 +9 -0
- package/README.md +17 -5
- package/client/dist/assets/{PhosphorBackdrop-D6cbmLNY.js → PhosphorBackdrop-DVQdBrTw.js} +1 -1
- package/client/dist/assets/{ThemedBackgroundShaderImpl-2dyerOi4.js → ThemedBackgroundShaderImpl-BfSs2tB4.js} +1 -1
- package/client/dist/assets/{XtermView-AIwo7O3D.js → XtermView-DaMjC8Ny.js} +1 -1
- package/client/dist/assets/{galleryEditor-DXAuxS8D.js → galleryEditor-BCQnXj7R.js} +1 -1
- package/client/dist/assets/{index-8j6p-pmQ.js → index-COfbHCYv.js} +245 -243
- package/client/dist/index.html +1 -1
- package/client/src/alerts/desktopAlerts.ts +13 -0
- package/client/src/buildCheck.ts +3 -1
- package/client/src/components/AppUpdateNotice.tsx +2 -1
- package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +46 -11
- package/client/src/components/ClusterRightPanel/MemberRow.tsx +1 -1
- package/client/src/components/ClusterRightPanel/index.tsx +2 -1
- package/client/src/components/ClusterTaskBoardTab.tsx +54 -3
- package/client/src/components/ContextMeter.tsx +7 -0
- package/client/src/components/HeaderVersionBox.tsx +7 -4
- package/client/src/components/Home/HomeView.tsx +1 -1
- package/client/src/components/NeedsYouBadge.tsx +31 -16
- package/client/src/components/OperatorQuestionNotice.tsx +10 -1
- package/client/src/components/ProvidersPopover.tsx +23 -12
- package/client/src/components/TabBar.tsx +11 -8
- package/client/src/components/TabStatusChip.tsx +8 -7
- package/client/src/components/UpdateAction.tsx +18 -4
- package/client/src/components/UpdateResultNotice.tsx +3 -1
- package/client/src/components/clusterNeedsYou.ts +27 -8
- package/client/src/help/content/cluster.tsx +50 -27
- package/client/src/help/content/composer.tsx +8 -1
- package/client/src/help/content/header.tsx +25 -14
- 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 +1 -1
- package/client/src/help/content/tabbar.tsx +2 -1
- package/client/src/help/manualSections/clusters.tsx +78 -19
- package/client/src/help/manualSections/configuration.tsx +20 -4
- package/client/src/help/manualSections/gettingStarted.tsx +10 -0
- package/client/src/help/manualSections/maintenance.tsx +50 -8
- package/client/src/help/manualSections/plans.tsx +5 -1
- package/client/src/help/manualSections/providers.tsx +10 -3
- package/client/src/help/manualSections/reference.tsx +1 -1
- package/client/src/help/manualSections/workflows.tsx +20 -0
- package/client/src/help/manualSections/workspace.tsx +7 -1
- package/client/src/questions/waitingQuestion.ts +3 -2
- package/client/src/stores/appStore.ts +1 -1
- package/client/src/stores/appStore.types.ts +1 -0
- package/client/src/stores/appUpdateStore.ts +29 -8
- package/client/src/stores/notificationStore.ts +2 -0
- package/client/src/utils/activityPresentation.ts +1 -1
- package/client/src/utils/tabStatus.ts +8 -0
- package/client/src/utils/wsSession.ts +2 -1
- package/client/src/voice/commands.ts +4 -3
- package/client/src/voice/executor.ts +3 -3
- package/client/src/ws/handleServerMessage.ts +22 -2
- package/client/src/ws/operatorQuestions.ts +2 -0
- package/docs/CLIENT.md +3 -3
- package/docs/FEATURES.md +1 -1
- package/docs/GETTING_STARTED.md +16 -6
- package/docs/GLOSSARY.md +6 -2
- package/docs/GOTCHAS.md +17 -5
- package/docs/OPERATIONS.md +207 -5
- package/docs/PERSISTENCE.md +22 -1
- package/docs/PRIMITIVES.md +1 -1
- package/docs/PROTOCOL.md +1 -1
- package/docs/PROTOCOL_CLUSTER.md +18 -7
- package/docs/PROVIDERS.md +10 -5
- package/docs/SETTINGS.md +4 -2
- package/docs/TASK_LEDGER.md +6 -0
- package/docs/VOICE.md +2 -0
- package/native/darwin-arm64/manifest.json +1 -1
- package/native/win32-arm64/manifest.json +1 -1
- package/node_modules/@arco/shared/dist/clusterRolePresets.d.ts +1 -1
- package/node_modules/@arco/shared/dist/clusterRolePresets.js +10 -0
- package/node_modules/@arco/shared/dist/protocol/autoPickup.d.ts +3 -0
- package/node_modules/@arco/shared/dist/protocol/autoPickup.js +9 -1
- package/node_modules/@arco/shared/dist/protocol/clientMessages.d.ts +2 -2
- package/node_modules/@arco/shared/dist/protocol/models.d.ts +6 -0
- package/node_modules/@arco/shared/dist/protocol/notifications.d.ts +4 -0
- package/node_modules/@arco/shared/dist/protocol/operatorQuestions.d.ts +12 -0
- package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +9 -3
- package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
- package/node_modules/@arco/shared/package.json +1 -1
- package/package.json +2 -2
- package/scripts/packaging/arco.mjs +1 -0
- package/scripts/packaging/native-repair.mjs +46 -8
- package/scripts/packaging/update.mjs +5 -1
- package/server/dist/attention.d.ts +1 -1
- package/server/dist/attention.js +6 -4
- package/server/dist/capabilities.d.ts +9 -8
- package/server/dist/capabilities.js +71 -102
- package/server/dist/cliUpdateDecision.d.ts +34 -0
- package/server/dist/cliUpdateDecision.js +152 -0
- 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 -0
- package/server/dist/clusterPeerOps.js +2 -2
- package/server/dist/clusterStore.d.ts +3 -0
- package/server/dist/clusterStore.js +22 -0
- package/server/dist/defaults/models.md +1 -1
- package/server/dist/fileAccessPolicy.js +7 -5
- package/server/dist/http/workflowDataRoutes.js +1 -1
- package/server/dist/index.js +5 -1
- package/server/dist/primitives/seedWorker.d.ts +1 -0
- package/server/dist/primitives/seedWorker.js +2 -1
- package/server/dist/providerConversation.d.ts +9 -0
- package/server/dist/providerConversation.js +80 -0
- package/server/dist/providers/claude-native/retainedContext.d.ts +4 -0
- package/server/dist/providers/claude-native/retainedContext.js +20 -0
- package/server/dist/providers/claude-native/worker.d.ts +1 -0
- package/server/dist/providers/claude-native/worker.js +34 -6
- package/server/dist/providers/codex-appserver/operatorQuestions.d.ts +5 -0
- package/server/dist/providers/codex-appserver/operatorQuestions.js +30 -0
- package/server/dist/providers/codex-appserver/worker.js +9 -4
- package/server/dist/providers/ollama.js +2 -3
- package/server/dist/server/broadcast.d.ts +1 -1
- package/server/dist/smartPickup.d.ts +2 -1
- package/server/dist/smartPickup.js +28 -1
- package/server/dist/smartPickupAdapters.d.ts +1 -0
- package/server/dist/smartPickupAdapters.js +18 -5
- package/server/dist/smartPickupLedger.js +6 -4
- package/server/dist/smartPickupObserver.d.ts +1 -0
- package/server/dist/smartPickupObserver.js +69 -23
- package/server/dist/workers/WorkerManager.d.ts +1 -0
- package/server/dist/workers/WorkerManager.js +1 -0
- package/server/dist/workers/limits.js +6 -2
- package/server/dist/workflowMeta.d.ts +11 -1
- package/server/dist/workflowMeta.js +132 -6
- package/server/dist/workflows/types.d.ts +1 -0
- package/server/dist/ws/clusterHandlers.d.ts +1 -0
- package/server/dist/ws/clusterHandlers.js +2 -1
- package/server/dist/ws/compactHandlers.d.ts +1 -1
- package/server/dist/ws/compactHandlers.js +11 -4
- package/server/dist/ws/handoffHandlers.js +16 -6
- package/server/dist/ws/operatorQuestionHandlers.d.ts +2 -1
- package/server/dist/ws/operatorQuestionHandlers.js +9 -1
- package/server/dist/ws/turnEngine.d.ts +2 -4
- package/server/dist/ws/turnEngine.js +88 -129
- package/server/package.json +1 -1
- package/server/src/attention.ts +5 -4
- package/server/src/capabilities.ts +70 -111
- package/server/src/cliUpdateDecision.ts +159 -0
- package/server/src/clusterAutoTurn.ts +26 -21
- package/server/src/clusterBusyReminder.ts +1 -1
- package/server/src/clusterDirector.ts +1 -0
- package/server/src/clusterPeerOps.ts +2 -2
- package/server/src/clusterStore.ts +26 -1
- package/server/src/defaults/models.md +1 -1
- package/server/src/fileAccessPolicy.ts +7 -5
- package/server/src/http/workflowDataRoutes.ts +1 -1
- package/server/src/index.ts +5 -1
- package/server/src/primitives/seedWorker.ts +3 -1
- package/server/src/providerConversation.ts +71 -0
- package/server/src/providers/claude-native/retainedContext.ts +22 -0
- package/server/src/providers/claude-native/worker.ts +33 -5
- package/server/src/providers/codex-appserver/operatorQuestions.ts +24 -0
- package/server/src/providers/codex-appserver/worker.ts +8 -4
- package/server/src/providers/ollama.ts +2 -3
- package/server/src/smartPickup.ts +27 -3
- package/server/src/smartPickupAdapters.ts +19 -5
- package/server/src/smartPickupLedger.ts +6 -4
- package/server/src/smartPickupObserver.ts +51 -17
- package/server/src/workers/WorkerManager.ts +2 -0
- package/server/src/workers/limits.ts +7 -2
- package/server/src/workflowMeta.ts +139 -5
- package/server/src/workflows/types.ts +1 -0
- package/server/src/ws/clusterHandlers.ts +3 -2
- package/server/src/ws/compactHandlers.ts +9 -3
- package/server/src/ws/handoffHandlers.ts +13 -6
- package/server/src/ws/operatorQuestionHandlers.ts +10 -2
- package/server/src/ws/turnEngine.ts +80 -135
- package/shared/dist/clusterRolePresets.d.ts +1 -1
- package/shared/dist/clusterRolePresets.js +10 -0
- package/shared/dist/protocol/autoPickup.d.ts +3 -0
- package/shared/dist/protocol/autoPickup.js +9 -1
- package/shared/dist/protocol/clientMessages.d.ts +2 -2
- package/shared/dist/protocol/models.d.ts +6 -0
- package/shared/dist/protocol/notifications.d.ts +4 -0
- package/shared/dist/protocol/operatorQuestions.d.ts +12 -0
- package/shared/dist/protocol/serverMessages.d.ts +9 -3
- package/shared/dist/protocol/workflows.d.ts +1 -0
- package/shared/src/clusterRolePresets.ts +11 -1
- package/shared/src/protocol/autoPickup.ts +14 -1
- package/shared/src/protocol/clientMessages.ts +2 -1
- package/shared/src/protocol/models.ts +5 -2
- package/shared/src/protocol/notifications.ts +5 -0
- package/shared/src/protocol/operatorQuestions.ts +13 -0
- package/shared/src/protocol/serverMessages.ts +12 -2
- package/shared/src/protocol/workflows.ts +4 -0
|
@@ -70,12 +70,14 @@ export function assertSpellingSafe(target: string, pathApi = path): void {
|
|
|
70
70
|
// transcripts, settings, account homes, cluster vaults or logs browseable.
|
|
71
71
|
for (let i = 0; i < parts.length; i++) {
|
|
72
72
|
if (parts[i] !== '.arco') continue;
|
|
73
|
-
|
|
73
|
+
const runtimeUploads = isPathWithin(pathApi.join(homedir(), '.arco'), target, pathApi) || isPathWithin(runtimeHome(), target, pathApi);
|
|
74
|
+
if (!runtimePathAllowed(parts.slice(i + 1), runtimeUploads)) throw new FileAccessError();
|
|
74
75
|
}
|
|
75
76
|
}
|
|
76
77
|
|
|
77
|
-
function runtimePathAllowed(parts: string[]): boolean {
|
|
78
|
-
return parts[0] === '
|
|
78
|
+
function runtimePathAllowed(parts: string[], allowUploads = false): boolean {
|
|
79
|
+
return (allowUploads && parts[0] === 'uploads' && parts.length <= 2)
|
|
80
|
+
|| parts[0] === 'plans' || parts[0] === 'media-scratch'
|
|
79
81
|
|| (parts[0] === 'workflows' && /^[a-z0-9_-]+$/.test(parts[1] || '') && ['artifacts', 'handoffs'].includes(parts[2]))
|
|
80
82
|
|| (['chats', 'genesis'].includes(parts[0]) && /^[a-z0-9_-]+$/.test(parts[1] || ''));
|
|
81
83
|
}
|
|
@@ -90,7 +92,7 @@ export function assertSafePath(target: string): void {
|
|
|
90
92
|
try { runtimeRoots.push(realpathSync(runtime)); } catch { /* not created */ }
|
|
91
93
|
}
|
|
92
94
|
for (const root of runtimeRoots) {
|
|
93
|
-
if (isPathWithin(root, target) && !runtimePathAllowed(path.relative(root, target).split(path.sep).map((p) => p.toLowerCase()))) throw new FileAccessError();
|
|
95
|
+
if (isPathWithin(root, target) && !runtimePathAllowed(path.relative(root, target).split(path.sep).map((p) => p.toLowerCase()), true)) throw new FileAccessError();
|
|
94
96
|
}
|
|
95
97
|
for (const { root, temporaryRoot } of protectedRoots()) {
|
|
96
98
|
// Default AppData and LOCALAPPDATA exempt only local temporary storage.
|
|
@@ -170,7 +172,7 @@ export async function createReadAccessContext(): Promise<ReadAccessContext> {
|
|
|
170
172
|
const assert = (target: string) => {
|
|
171
173
|
assertSpellingSafe(target);
|
|
172
174
|
for (const root of runtimeRoots) {
|
|
173
|
-
if (isPathWithin(root, target) && !runtimePathAllowed(path.relative(root, target).split(path.sep).map(p => p.toLowerCase()))) throw new FileAccessError();
|
|
175
|
+
if (isPathWithin(root, target) && !runtimePathAllowed(path.relative(root, target).split(path.sep).map(p => p.toLowerCase()), true)) throw new FileAccessError();
|
|
174
176
|
}
|
|
175
177
|
protectedPaths.forEach(({ root, temporaryRoot }, index) => {
|
|
176
178
|
if (isProtectedRoot(root, target, temporaryRoot)) throw new FileAccessError();
|
|
@@ -529,7 +529,7 @@ export async function tryHandleWorkflowDataRoutes(
|
|
|
529
529
|
return true;
|
|
530
530
|
}
|
|
531
531
|
|
|
532
|
-
// Per-workflow artifact reader. Workers write
|
|
532
|
+
// Per-workflow artifact reader. Workers write conversation reports into
|
|
533
533
|
// `<cwd>/.arco/workflows/<wfid>/artifacts/`; the client fetches them on
|
|
534
534
|
// demand when chat contains `[artifact:<name>]`. Name is strictly sanitized.
|
|
535
535
|
if (req.url?.startsWith('/api/workflows/artifact') && req.method === 'GET') {
|
package/server/src/index.ts
CHANGED
|
@@ -19,7 +19,7 @@ import { setDeepSeekActivityCheck } from './providers/deepseekProfiles.js';
|
|
|
19
19
|
import { setStrataSwitchActivityCheck } from './providers/strataProfiles.js';
|
|
20
20
|
import { setOperatorQuestionPublisher } from './providers/codex-appserver/operatorQuestions.js';
|
|
21
21
|
import { resolveVoiceTool, setVoiceToolPublisher } from './voice/operatorTools.js';
|
|
22
|
-
import { handleOperatorQuestionReply } from './ws/operatorQuestionHandlers.js';
|
|
22
|
+
import { handleOperatorQuestionReply, handleOperatorQuestionDismiss } from './ws/operatorQuestionHandlers.js';
|
|
23
23
|
// Side-effect import, kept FIRST: forces this process onto IPv4 before any
|
|
24
24
|
// module can open a socket. See server/src/net/forceIpv4.ts.
|
|
25
25
|
import { loadWorkspace, onWorkspaceChange, syncWorkspace } from './workspace.js';
|
|
@@ -975,6 +975,10 @@ wss.on('connection', (ws: WebSocket) => {
|
|
|
975
975
|
if (wf && wf.observers.has(ws)) resolveVoiceTool(msg);
|
|
976
976
|
break;
|
|
977
977
|
}
|
|
978
|
+
case 'operator_question_dismiss': {
|
|
979
|
+
handleOperatorQuestionDismiss(ws, session, msg);
|
|
980
|
+
break;
|
|
981
|
+
}
|
|
978
982
|
case 'operator_question_reply': {
|
|
979
983
|
void handleOperatorQuestionReply(ws, session, msg).catch(() => {
|
|
980
984
|
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'operator_question_reply_result', workflowId: msg.workflowId, requestId: msg.requestId, ok: false, error: 'The answer could not be delivered.' }));
|
|
@@ -224,6 +224,7 @@ export function runPrimaryTurn(
|
|
|
224
224
|
// tool-result append and the next API round-trip. Other providers
|
|
225
225
|
// ignore it; the post-turn drain still picks up anything not consumed.
|
|
226
226
|
drainSteer?: () => SteerItem[];
|
|
227
|
+
peekSteer?: () => readonly SteerItem[];
|
|
227
228
|
// Phase 6b — paired with drainSteer for the Codex app-server worker.
|
|
228
229
|
// Symmetrical contract — same scoping (primary-turn only), same
|
|
229
230
|
// in-process callback shape. Called when a `turn/steer` round-trip
|
|
@@ -358,7 +359,7 @@ export function runPrimaryTurn(
|
|
|
358
359
|
webSearchMaxUses?: number;
|
|
359
360
|
},
|
|
360
361
|
): TurnHandle {
|
|
361
|
-
const { primary, prompt, resumeSessionId, attachments, disableRssGuard, appendSystemPrompt, systemPrompt, interactionMode, disableProviderHooks, chatWebAccess, voiceOperator, incognito, drainSteer, requeueSteer, onSteerDelivered, codexTransport, codexContextPolicy, providerAccountRef, codexHome, claudeTransport, ultracode, claudeNativeTaskDisabled, claudeNativeSubagent, claudeNativeCompact, claudeNativeInTurnCompactPercent, claudeNativeForceInterleavedThinkingBeta, claudeNativeThinkingDisplay, nativeSubagents, claudeNativePlanModeArmed, turnNotice, efficiencyToolFilter, efficiencyFactForce, efficiencyConfigProtection, efficiencySandbox, reviewSafeMode, outputStyle, goal, toolPosture, clusterId, clusterAccessMode, executionCwd, persistenceCwd, clusterTaskBoardAttached, clusterPlan, clusterRole, clusterEfficiencyDoctrine, clusterProgressDoctrine, clusterMcpConfigPath, codebaseMemoryAttached, codebaseMemoryIndexPath, mcpRegistryServers, mcpDisallowedTools, ollamaParams, webSearchMaxUses } = args;
|
|
362
|
+
const { primary, prompt, resumeSessionId, attachments, disableRssGuard, appendSystemPrompt, systemPrompt, interactionMode, disableProviderHooks, chatWebAccess, voiceOperator, incognito, drainSteer, peekSteer, requeueSteer, onSteerDelivered, codexTransport, codexContextPolicy, providerAccountRef, codexHome, claudeTransport, ultracode, claudeNativeTaskDisabled, claudeNativeSubagent, claudeNativeCompact, claudeNativeInTurnCompactPercent, claudeNativeForceInterleavedThinkingBeta, claudeNativeThinkingDisplay, nativeSubagents, claudeNativePlanModeArmed, turnNotice, efficiencyToolFilter, efficiencyFactForce, efficiencyConfigProtection, efficiencySandbox, reviewSafeMode, outputStyle, goal, toolPosture, clusterId, clusterAccessMode, executionCwd, persistenceCwd, clusterTaskBoardAttached, clusterPlan, clusterRole, clusterEfficiencyDoctrine, clusterProgressDoctrine, clusterMcpConfigPath, codebaseMemoryAttached, codebaseMemoryIndexPath, mcpRegistryServers, mcpDisallowedTools, ollamaParams, webSearchMaxUses } = args;
|
|
362
363
|
|
|
363
364
|
const workerId = `primary-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
|
364
365
|
|
|
@@ -401,6 +402,7 @@ export function runPrimaryTurn(
|
|
|
401
402
|
...(interactionMode === 'chat' ? { sandbox: 'read-only' as const } : {}),
|
|
402
403
|
disableRssGuard,
|
|
403
404
|
drainSteer,
|
|
405
|
+
peekSteer,
|
|
404
406
|
requeueSteer,
|
|
405
407
|
onSteerDelivered,
|
|
406
408
|
codexTransport,
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { ProviderName } from '@arco/shared';
|
|
2
|
+
import type { WorkflowState } from './workflows/types.js';
|
|
3
|
+
import { resolveClaudeTransport } from './claudeTransport.js';
|
|
4
|
+
import { readMeta, persistInitialMeta, reconcileLatestCliSession, workflowMetaSeed, updateMeta } from './workflowMeta.js';
|
|
5
|
+
import { scanEventsOfTypes } from './workflowStore.js';
|
|
6
|
+
import { broadcastWorkflow, broadcastTransient } from './server/broadcast.js';
|
|
7
|
+
|
|
8
|
+
export async function hasConversationHistory(cwd: string, workflowId: string, afterSeq = 0): Promise<boolean> {
|
|
9
|
+
let found = false;
|
|
10
|
+
await scanEventsOfTypes(cwd, workflowId, ['primary_complete', 'primary_text'], event => { if ((('seq' in event && typeof event.seq === 'number') ? event.seq : 0) > afterSeq) found = true; });
|
|
11
|
+
return found;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function reportConversationSaveFailure(workflowId: string, err: unknown): void {
|
|
15
|
+
console.error(`[arco] [${workflowId.slice(0, 8)}] conversation metadata save failed:`, err);
|
|
16
|
+
broadcastWorkflow(workflowId, { type: 'system_notice', workflowId,
|
|
17
|
+
content: 'Could not save the provider conversation metadata. A restart may lose its resume id. Check that the project folder is writable.' });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function ensureWorkflowMetadata(cwd: string, workflowId: string, wf: WorkflowState): Promise<void> {
|
|
21
|
+
if (wf.config.incognito) return;
|
|
22
|
+
try {
|
|
23
|
+
await persistInitialMeta(cwd, workflowId, wf.config, wf.primary, { sessionId: wf.primarySessionId, pendingReading: wf.providerConversation === 'awaiting-reading' });
|
|
24
|
+
const meta = await readMeta(cwd, workflowId);
|
|
25
|
+
if (meta?.providerConversationPendingReading) wf.providerConversation = 'awaiting-reading';
|
|
26
|
+
} catch (err) { reportConversationSaveFailure(workflowId, err); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function providerConversationState(cwd: string, workflowId: string, wf: WorkflowState): Promise<WorkflowState['providerConversation']> {
|
|
30
|
+
if (wf.config.incognito) return undefined;
|
|
31
|
+
const provider = wf.primary.provider;
|
|
32
|
+
const external = provider === 'codex' || provider === 'cursor'
|
|
33
|
+
|| (provider === 'claude' && await resolveClaudeTransport(wf, cwd) === 'cli');
|
|
34
|
+
if (!external) return undefined;
|
|
35
|
+
if (!wf.primarySessionId) {
|
|
36
|
+
const boundary = wf.config.voiceOperator ? wf.config.computerContext?.lastResetSeq ?? 0 : 0;
|
|
37
|
+
return await hasConversationHistory(cwd, workflowId, boundary) ? 'unavailable' : undefined;
|
|
38
|
+
}
|
|
39
|
+
return wf.providerConversation === 'awaiting-reading' ? wf.providerConversation : undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function saveProviderSession(cwd: string, workflowId: string, wf: WorkflowState, provider: ProviderName, sessionId: string, providerAccountRef?: string): Promise<void> {
|
|
43
|
+
if (wf.config.incognito) return;
|
|
44
|
+
const seed = workflowMetaSeed(cwd, workflowId, wf.config, wf.primary);
|
|
45
|
+
seed.providerConversationPendingReading = wf.providerConversation === 'awaiting-reading';
|
|
46
|
+
try {
|
|
47
|
+
await reconcileLatestCliSession(cwd, workflowId, provider, sessionId, providerAccountRef, seed);
|
|
48
|
+
} catch (err) { reportConversationSaveFailure(workflowId, err); }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Only session discovery proves that the provider actually started the new
|
|
52
|
+
// conversation. Reconnecting or a failed pre-dispatch attempt is not a start.
|
|
53
|
+
export function announceReplacementConversation(workflowId: string, wf: WorkflowState): void {
|
|
54
|
+
if (wf.providerConversation !== 'unavailable') return;
|
|
55
|
+
const provider = wf.primary.provider === 'codex' ? 'Codex' : wf.primary.provider === 'cursor' ? 'Cursor' : 'Claude CLI';
|
|
56
|
+
wf.providerConversation = 'awaiting-reading';
|
|
57
|
+
broadcastWorkflow(workflowId, { type: 'provider_conversation_state', workflowId, state: 'awaiting-reading' });
|
|
58
|
+
broadcastWorkflow(workflowId, { type: 'system_notice', workflowId,
|
|
59
|
+
content: `A new ${provider} conversation started because no saved thread id is available. Earlier messages remain in this tab.` });
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function markConversationReading(cwd: string, workflowId: string, wf: WorkflowState): Promise<void> {
|
|
63
|
+
if (wf.providerConversation !== 'awaiting-reading') return;
|
|
64
|
+
wf.providerConversation = undefined;
|
|
65
|
+
broadcastTransient(workflowId, { type: 'provider_conversation_state', workflowId, state: 'ready' });
|
|
66
|
+
try {
|
|
67
|
+
const saved = await updateMeta(cwd, workflowId, meta => { delete meta.providerConversationPendingReading; });
|
|
68
|
+
if (!saved) throw new Error('Workflow metadata disappeared before the context reading was saved.');
|
|
69
|
+
}
|
|
70
|
+
catch (err) { reportConversationSaveFailure(workflowId, err); }
|
|
71
|
+
}
|
|
@@ -21,6 +21,28 @@ export function isServerToolResultType(type: string): type is ServerToolResultTy
|
|
|
21
21
|
return SERVER_TOOL_RESULT_TYPES.has(type);
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
// A mixed client/server response can defer its server results to a later
|
|
25
|
+
// assistant message. Until those IDs are answered, the continuation must
|
|
26
|
+
// contain only client tool_result blocks, without a steer or history splice.
|
|
27
|
+
export function pendingServerTools(
|
|
28
|
+
messages: readonly { role?: string; content?: unknown }[],
|
|
29
|
+
startMessageIndex: number,
|
|
30
|
+
): string[] {
|
|
31
|
+
const pending = new Map<string, string>();
|
|
32
|
+
for (let i = Math.max(0, startMessageIndex); i < messages.length; i++) {
|
|
33
|
+
const message = messages[i];
|
|
34
|
+
if (message.role !== 'assistant' || !Array.isArray(message.content)) continue;
|
|
35
|
+
for (const block of message.content as Array<Record<string, unknown>>) {
|
|
36
|
+
if (block.type === 'server_tool_use' && typeof block.id === 'string') {
|
|
37
|
+
pending.set(block.id, typeof block.name === 'string' ? block.name : 'server tool');
|
|
38
|
+
} else if (typeof block.type === 'string' && isServerToolResultType(block.type) && typeof block.tool_use_id === 'string') {
|
|
39
|
+
pending.delete(block.tool_use_id);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return [...new Set(pending.values())];
|
|
44
|
+
}
|
|
45
|
+
|
|
24
46
|
export function isClaudeServerToolDef(tool: unknown): boolean {
|
|
25
47
|
const type = (tool as { type?: unknown }).type;
|
|
26
48
|
return typeof type === 'string' && (
|
|
@@ -61,7 +61,7 @@ import { getSandboxToolDefinitions, isSandboxTool, executeSandboxTool } from './
|
|
|
61
61
|
import { buildMessagesFromReplayEvents, replayMessagesWithResumePolicy, compactSummarySeed, type ClaudeResumeMessage } from './resumeSummary.js';
|
|
62
62
|
import { readMeta, setResolvedModelId } from '../../workflowMeta.js';
|
|
63
63
|
import { lspManager } from '../../lsp/client.js';
|
|
64
|
-
import { isClaudeServerToolDef, isServerToolResultType, pruneServerToolEvidenceAfterTurn, stripDanglingServerToolResults } from './retainedContext.js';
|
|
64
|
+
import { isClaudeServerToolDef, isServerToolResultType, pendingServerTools, pruneServerToolEvidenceAfterTurn, stripDanglingServerToolResults } from './retainedContext.js';
|
|
65
65
|
import { gzipSync } from 'node:zlib';
|
|
66
66
|
import {
|
|
67
67
|
executeNativeToolResult,
|
|
@@ -378,6 +378,7 @@ export class ClaudeNativeWorker extends EventEmitter {
|
|
|
378
378
|
private authRecovery: AuthRecoveryContext = { transport: 'native', binding: nativeCredentialBinding() };
|
|
379
379
|
private clientTokenObtainedAt: number | null = null;
|
|
380
380
|
private messages: MessageParam[] = [];
|
|
381
|
+
private heldSteerNotices = new WeakSet<object>();
|
|
381
382
|
private hooks: HookConfig = { byEvent: {} };
|
|
382
383
|
// Set once discoverTrustedHooks has run (ensureStarted, or a FOLD before any turn).
|
|
383
384
|
private hooksLoaded = false;
|
|
@@ -3005,6 +3006,21 @@ export class ClaudeNativeWorker extends EventEmitter {
|
|
|
3005
3006
|
return;
|
|
3006
3007
|
}
|
|
3007
3008
|
|
|
3009
|
+
// Client results alone do not close a mixed server/client turn. Match
|
|
3010
|
+
// server results across assistant messages before adding ordinary user
|
|
3011
|
+
// input or replacing history; either would end an unresolved turn.
|
|
3012
|
+
const pendingServer = pendingServerTools(this.messages, turnMessageStart);
|
|
3013
|
+
if (pendingServer.length > 0) {
|
|
3014
|
+
const work = pendingServer.every((name) => name === 'web_search') ? 'web search finishes'
|
|
3015
|
+
: pendingServer.every((name) => name === 'web_fetch') ? 'web fetch finishes' : 'server tools finish';
|
|
3016
|
+
for (const item of this.config.peekSteer?.() ?? []) {
|
|
3017
|
+
if (this.heldSteerNotices.has(item)) continue;
|
|
3018
|
+
this.heldSteerNotices.add(item);
|
|
3019
|
+
this.emit('system_notice', `Message held until ${work}.`);
|
|
3020
|
+
}
|
|
3021
|
+
continue;
|
|
3022
|
+
}
|
|
3023
|
+
|
|
3008
3024
|
// In-turn auto-compaction at a clean boundary: every tool_use of this
|
|
3009
3025
|
// round has its result and the next request has not been sent. Runs
|
|
3010
3026
|
// before the steer drain so a steer lands after the compacted history.
|
|
@@ -4263,7 +4279,7 @@ export class ClaudeNativeWorker extends EventEmitter {
|
|
|
4263
4279
|
// SDK's own `.type` property), NOT on `e.error.type` (which is the outer
|
|
4264
4280
|
// body wrapper field "error"). Read `e.type` first so overloaded/rate-limit
|
|
4265
4281
|
// mid-stream errors are correctly classified for retry.
|
|
4266
|
-
const e = err as { status?: number; message?: string; error?: { type?: string; message?: string; error?: { type?: string; message?: string } }; type?: string; name?: string };
|
|
4282
|
+
const e = err as { status?: number; message?: string; error?: { type?: string; message?: string; error?: { type?: string; message?: string } }; type?: string; name?: string; code?: string; cause?: { code?: string } };
|
|
4267
4283
|
const name = e.name ?? '';
|
|
4268
4284
|
// Inner message is at e.error.error.message (full body → error → message)
|
|
4269
4285
|
// for streaming errors; fall back through outer body message and SDK message.
|
|
@@ -4317,7 +4333,15 @@ export class ClaudeNativeWorker extends EventEmitter {
|
|
|
4317
4333
|
this.emit('error', 'request_too_large');
|
|
4318
4334
|
return 'fatal';
|
|
4319
4335
|
}
|
|
4320
|
-
|
|
4336
|
+
const gatewayError = status === 502 || status === 503 || status === 504 || (status >= 520 && status <= 524);
|
|
4337
|
+
// The SDK wraps failures before headers in APIConnectionError (including
|
|
4338
|
+
// APIConnectionTimeoutError). A dropped response body can instead expose
|
|
4339
|
+
// the fetch socket error directly; do not retry arbitrary statusless errors.
|
|
4340
|
+
const connectionCode = e.cause?.code ?? e.code ?? '';
|
|
4341
|
+
const connectionError = status === 0 && (err instanceof Anthropic.APIConnectionError
|
|
4342
|
+
|| /^(?:ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|UND_ERR_(?:SOCKET|CONNECT_TIMEOUT|HEADERS_TIMEOUT|BODY_TIMEOUT))$/.test(connectionCode));
|
|
4343
|
+
const transportError = gatewayError || connectionError;
|
|
4344
|
+
if (transportError || status === 429 || status === 529 || errType === 'rate_limit_error' || errType === 'overloaded_error' || status === 500 || errType === 'api_error') {
|
|
4321
4345
|
// H10 — honor Anthropic's own retry timing when it sends one. `retry-after`
|
|
4322
4346
|
// (seconds or HTTP-date) wins; else the soonest `anthropic-ratelimit-*-reset`.
|
|
4323
4347
|
// Falls back to the fixed 15/30/60s ladder when no usable header is present
|
|
@@ -4330,7 +4354,9 @@ export class ClaudeNativeWorker extends EventEmitter {
|
|
|
4330
4354
|
const via = timing.source
|
|
4331
4355
|
? ` (per ${timing.source}${timing.capped ? ', capped' : ''})`
|
|
4332
4356
|
: '';
|
|
4333
|
-
const label =
|
|
4357
|
+
const label = gatewayError ? `gateway error (HTTP ${status})`
|
|
4358
|
+
: connectionError ? (err instanceof Anthropic.APIConnectionTimeoutError ? 'connection timeout' : 'connection error')
|
|
4359
|
+
: kind === 'genuine'
|
|
4334
4360
|
? `rate limit (${errType || `HTTP ${status}`})`
|
|
4335
4361
|
: `overload (${errType || `HTTP ${status}`})`;
|
|
4336
4362
|
// Same attempt-budget guard as the auth / thinking branches: a 'retry'
|
|
@@ -4338,7 +4364,9 @@ export class ClaudeNativeWorker extends EventEmitter {
|
|
|
4338
4364
|
// WITHOUT emitting — runTurn reads null as "error already emitted", so a
|
|
4339
4365
|
// third consecutive 429/529/500 left the tab busy forever.
|
|
4340
4366
|
if (attempt >= MAX_RETRY_ATTEMPTS - 1) {
|
|
4341
|
-
this.emit('system_notice',
|
|
4367
|
+
this.emit('system_notice', transportError
|
|
4368
|
+
? `Anthropic could not be reached${gatewayError ? ` (HTTP ${status})` : ` (${label})`} after ${MAX_RETRY_ATTEMPTS} attempts. The conversation is intact; send a message to continue.`
|
|
4369
|
+
: `Anthropic ${label}: still failing after ${MAX_RETRY_ATTEMPTS} attempts — giving up on this turn. ${msg.slice(0, 300)}`);
|
|
4342
4370
|
this.emit('error', `claude-native: ${label} after ${MAX_RETRY_ATTEMPTS} attempts`);
|
|
4343
4371
|
return 'fatal';
|
|
4344
4372
|
}
|
|
@@ -72,6 +72,21 @@ export async function replyToOperatorQuestion(workflowId: string, requestId: str
|
|
|
72
72
|
} finally { entry.sending = false; }
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
export function dismissOperatorQuestion(workflowId: string, requestId: string): { ok: boolean; error?: string } {
|
|
76
|
+
const entry = pending.get(requestId);
|
|
77
|
+
if (!entry || entry.workflowId !== workflowId) return { ok: false, error: 'This question is no longer pending.' };
|
|
78
|
+
if (entry.sending) return { ok: false, error: 'An answer is already being delivered.' };
|
|
79
|
+
entry.sending = true;
|
|
80
|
+
try {
|
|
81
|
+
if (entry.respond && entry.respond({ answers: {} }) === false) throw new Error('Codex connection closed.');
|
|
82
|
+
if (pending.get(requestId) !== entry) return { ok: false, error: 'This question is no longer pending.' };
|
|
83
|
+
entry.owner.finish(entry, { ...entry.state, status: 'cancelled', reason: 'Dismissed by the operator.' });
|
|
84
|
+
return { ok: true };
|
|
85
|
+
} catch {
|
|
86
|
+
return { ok: false, error: 'The dismissal could not be delivered. The question is still pending.' };
|
|
87
|
+
} finally { entry.sending = false; }
|
|
88
|
+
}
|
|
89
|
+
|
|
75
90
|
export class CodexOperatorQuestions {
|
|
76
91
|
private ids = new Set<string>();
|
|
77
92
|
private asyncItems = new Set<string>();
|
|
@@ -112,6 +127,15 @@ export class CodexOperatorQuestions {
|
|
|
112
127
|
pending.delete(entry.state.requestId); this.ids.delete(entry.state.requestId); entry.publish(state);
|
|
113
128
|
}
|
|
114
129
|
|
|
130
|
+
settleTurn(threadId: string, turnId: string): void {
|
|
131
|
+
for (const id of [...this.ids]) {
|
|
132
|
+
const p = pending.get(id);
|
|
133
|
+
if (p && p.rpcId === undefined && p.state.threadId === threadId && p.state.turnId === turnId) {
|
|
134
|
+
this.finish(p, { ...p.state, status: 'cancelled', reason: "The agent's turn ended before an answer was received." });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
115
139
|
resolvedRpc(rpcId: JsonRpcId): void {
|
|
116
140
|
for (const id of [...this.ids]) {
|
|
117
141
|
const p = pending.get(id);
|
|
@@ -917,15 +917,17 @@ export class CodexAppServerWorker extends EventEmitter {
|
|
|
917
917
|
//
|
|
918
918
|
// Re-queue semantics on errors mirror the §9 mapping:
|
|
919
919
|
// - activeTurnNotSteerable {turnKind: review|compact} → re-enqueue to
|
|
920
|
-
// the steer bucket; the
|
|
920
|
+
// the steer bucket; the queue engine delivers it at the next safe
|
|
921
|
+
// turn boundary, or starts a queued turn if the tab is already idle
|
|
921
922
|
// - mismatched turnId / turn already ended → re-enqueue as follow-up
|
|
922
923
|
// - any other transport error → re-enqueue to follow-up + system_notice
|
|
923
924
|
private async dispatchSteer(items: SteerItem[]): Promise<void> {
|
|
924
925
|
const config = this.config;
|
|
925
926
|
const turn = this.current;
|
|
926
927
|
if (!this.rpc || !this.threadId || !this.current.turnId) {
|
|
927
|
-
// No live turn — push everything back into follow-up so the
|
|
928
|
-
//
|
|
928
|
+
// No live turn — push everything back into follow-up so the queue
|
|
929
|
+
// engine starts it when idle, with the normal delivery receipt. A
|
|
930
|
+
// later operator message must not be needed to unpark this batch.
|
|
929
931
|
this.requeueSteer(items, 'follow-up', 'turn ended before steer dispatched', config);
|
|
930
932
|
return;
|
|
931
933
|
}
|
|
@@ -960,7 +962,8 @@ export class CodexAppServerWorker extends EventEmitter {
|
|
|
960
962
|
this.requeueSteer(items, 'steer', `turn not steerable (kind=${kind})`, config);
|
|
961
963
|
} else {
|
|
962
964
|
// Anything else — mismatched expectedTurnId, transport blip, etc.
|
|
963
|
-
// Treat as follow-up; the
|
|
965
|
+
// Treat as follow-up; the queue engine delivers it after the active
|
|
966
|
+
// turn, or starts the returned batch itself when already idle.
|
|
964
967
|
const reason = err instanceof Error ? err.message : String(err);
|
|
965
968
|
this.requeueSteer(items, 'follow-up', `steer rpc failed: ${reason}`, config);
|
|
966
969
|
// Surface non-`activeTurnNotSteerable` failures so the operator sees
|
|
@@ -1628,6 +1631,7 @@ export class CodexAppServerWorker extends EventEmitter {
|
|
|
1628
1631
|
// (subsequent calls during the same turn are no-ops; the turn id is the
|
|
1629
1632
|
// gate).
|
|
1630
1633
|
private settleTurn(data: { error?: string; result?: TurnSettleData }): void {
|
|
1634
|
+
if (this.threadId && this.current.turnId) this.operatorQuestions.settleTurn(this.threadId, this.current.turnId);
|
|
1631
1635
|
this.operatorQuestions.cancel('The turn ended before an answer was received.', true);
|
|
1632
1636
|
if (!this.current.turnId && !this.current.startedAt) {
|
|
1633
1637
|
// No turn was actually in flight (e.g., kill() before turn/start).
|
|
@@ -56,7 +56,7 @@ import type {
|
|
|
56
56
|
OllamaPsModel,
|
|
57
57
|
OllamaThinkingInfo,
|
|
58
58
|
} from '@arco/shared';
|
|
59
|
-
import { ollamaThinkParam, parseOllamaThinking } from '@arco/shared';
|
|
59
|
+
import { isClusterDirector, ollamaThinkParam, parseOllamaThinking } from '@arco/shared';
|
|
60
60
|
import { readSettings } from '../settings.js';
|
|
61
61
|
import { resolveConfigValue } from '../configValue.js';
|
|
62
62
|
import type { Provider, ProviderProcess } from './types.js';
|
|
@@ -357,8 +357,7 @@ function shouldRequireClusterPeerReport(
|
|
|
357
357
|
if (!config.clusterId || !config.workflowId) return false;
|
|
358
358
|
if (observedToolNames.has('peer_send')) return false;
|
|
359
359
|
|
|
360
|
-
|
|
361
|
-
if (/\b(coordinator|director)\b/.test(role)) return false;
|
|
360
|
+
if (isClusterDirector(config.clusterRole)) return false;
|
|
362
361
|
|
|
363
362
|
return true;
|
|
364
363
|
}
|
|
@@ -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
|
}
|
|
@@ -2,7 +2,8 @@ import { nativeOAuthBaseUrl } from './providers/claude-native/apiEndpoint.js';
|
|
|
2
2
|
// Smart AUTO-PICKUP evaluator adapters. Each makes one bounded request with
|
|
3
3
|
// no tools and nothing Arco keeps or resumes afterwards: a time limit, an
|
|
4
4
|
// abort signal and an output cap. Any error, tool attempt or oversized answer
|
|
5
|
-
// rejects
|
|
5
|
+
// rejects. Smart: Automatic may then attempt ordinary pickup through its
|
|
6
|
+
// deterministic wake gate; Observe-only records the failure without waking.
|
|
6
7
|
//
|
|
7
8
|
// Capability per provider:
|
|
8
9
|
// ollama - /api/chat, stream off, JSON-schema format, no tools field.
|
|
@@ -69,8 +70,18 @@ export interface EvaluatorRequest {
|
|
|
69
70
|
// agent start (update, sign-in refresh) without touching the answer limit.
|
|
70
71
|
export const EVALUATOR_STARTUP_TIMEOUT_MS = 30_000;
|
|
71
72
|
|
|
73
|
+
// Match the existing short Claude request's bounded reasoning allowance.
|
|
74
|
+
// The selected answer limit still caps visible text; this is total generation
|
|
75
|
+
// headroom for evaluator requests, not a larger permitted evaluator answer.
|
|
76
|
+
export const EVALUATOR_REASONING_HEADROOM = 8192;
|
|
77
|
+
|
|
78
|
+
function totalOutputLimit(req: EvaluatorRequest): number {
|
|
79
|
+
return req.maxOutputTokens + (req.freeText ? 0 : EVALUATOR_REASONING_HEADROOM);
|
|
80
|
+
}
|
|
81
|
+
|
|
72
82
|
// A failure before the agent session was ready (reason prefix startup_). The
|
|
73
|
-
// observer
|
|
83
|
+
// observer preserves one retry of such a failure for the same mail, with a
|
|
84
|
+
// fresh reservation. A second startup failure can use guarded fallback.
|
|
74
85
|
export function isStartupFailure(reason: string): boolean {
|
|
75
86
|
return reason.startsWith('startup_');
|
|
76
87
|
}
|
|
@@ -132,7 +143,8 @@ export function ollamaAdapter(opts: { base?: () => Promise<string>; fetchImpl?:
|
|
|
132
143
|
model: req.model,
|
|
133
144
|
stream: false,
|
|
134
145
|
...(req.freeText ? {} : { format: ANSWER_SCHEMA }),
|
|
135
|
-
|
|
146
|
+
...(req.freeText ? {} : { think: false }),
|
|
147
|
+
options: { num_predict: totalOutputLimit(req), temperature: 0 },
|
|
136
148
|
messages: [{ role: 'system', content: req.instructions }, { role: 'user', content: req.prompt }],
|
|
137
149
|
}),
|
|
138
150
|
});
|
|
@@ -179,6 +191,7 @@ export function claudeAdapter(opts: { fetchImpl?: typeof fetch; tokens?: () => P
|
|
|
179
191
|
const resp = await client.messages.create({
|
|
180
192
|
model,
|
|
181
193
|
...shortTextRequestParams(model, req.maxOutputTokens),
|
|
194
|
+
...(req.freeText ? {} : { max_tokens: totalOutputLimit(req) }),
|
|
182
195
|
system: [{ type: 'text', text: CLAUDE_IDENTITY }, { type: 'text', text: req.instructions }],
|
|
183
196
|
messages: [{ role: 'user', content: req.prompt }],
|
|
184
197
|
}, { signal });
|
|
@@ -192,6 +205,7 @@ export function claudeAdapter(opts: { fetchImpl?: typeof fetch; tokens?: () => P
|
|
|
192
205
|
throw new EvaluatorRefused(reason);
|
|
193
206
|
};
|
|
194
207
|
if (!Array.isArray(blocks)) return refuse('unreadable_answer');
|
|
208
|
+
if (resp.stop_reason === 'refusal') return refuse('provider_refused');
|
|
195
209
|
if (resp.stop_reason === 'tool_use' || types.includes('tool_use') || types.includes('other')) return refuse('non_text_answer');
|
|
196
210
|
if (blocks.some((b: unknown) => b && typeof b === 'object' && 'type' in b && b.type === 'text' && (!('text' in b) || typeof b.text !== 'string'))) return refuse('unreadable_answer');
|
|
197
211
|
const text = blocks.filter((b: { type?: string }) => b?.type === 'text').map((b: { text: string }) => b.text).join('');
|
|
@@ -500,11 +514,11 @@ export function openAiCompatibleAdapter(provider: SmartPickupEvaluatorProvider,
|
|
|
500
514
|
signal.throwIfAborted();
|
|
501
515
|
const response = await fetchImpl(`${base}/chat/completions`, {
|
|
502
516
|
method: 'POST', headers: { 'Content-Type': 'application/json' }, signal,
|
|
503
|
-
body: JSON.stringify({ model: req.model, stream: false, max_tokens: req
|
|
517
|
+
body: JSON.stringify({ model: req.model, stream: false, max_tokens: totalOutputLimit(req), temperature: 0,
|
|
504
518
|
messages: [{ role: 'system', content: req.instructions }, { role: 'user', content: req.prompt }] }),
|
|
505
519
|
});
|
|
506
520
|
if (!response.ok) throw new EvaluatorRefused(response.status === 401 || response.status === 403 ? 'not_signed_in' : `provider_http_${response.status}`);
|
|
507
|
-
const result = await boundedLocalResponse(response, outputCharCap(req
|
|
521
|
+
const result = await boundedLocalResponse(response, outputCharCap(totalOutputLimit(req)) * 4 + 16_384) as { choices?: Array<{ message?: { content?: unknown; tool_calls?: unknown; function_call?: unknown }; finish_reason?: string }> };
|
|
508
522
|
const choice = result && Array.isArray(result.choices) ? result.choices[0] : undefined;
|
|
509
523
|
if ((choice?.message?.tool_calls != null && (!Array.isArray(choice.message.tool_calls) || choice.message.tool_calls.length > 0)) || choice?.message?.function_call || (choice?.finish_reason === 'tool_calls' || choice?.finish_reason === 'function_call')) throw new EvaluatorRefused('tool_attempted');
|
|
510
524
|
if (!choice?.message || !('content' in choice.message)) throw new EvaluatorRefused('unreadable_answer');
|
|
@@ -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));
|