arco-workbench 0.1.5 → 0.1.6

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.
Files changed (154) hide show
  1. package/CONTRIBUTING.md +9 -0
  2. package/README.md +11 -4
  3. package/client/dist/assets/{PhosphorBackdrop-D6cbmLNY.js → PhosphorBackdrop-BR-TgB5x.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-2dyerOi4.js → ThemedBackgroundShaderImpl-DgcFj6JN.js} +1 -1
  5. package/client/dist/assets/{XtermView-AIwo7O3D.js → XtermView-CflVBQgC.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-DXAuxS8D.js → galleryEditor-BB-emfmi.js} +1 -1
  7. package/client/dist/assets/{index-8j6p-pmQ.js → index-B_EqHDz3.js} +242 -240
  8. package/client/dist/index.html +1 -1
  9. package/client/src/alerts/desktopAlerts.ts +13 -0
  10. package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +28 -5
  11. package/client/src/components/ClusterRightPanel/MemberRow.tsx +1 -1
  12. package/client/src/components/ClusterTaskBoardTab.tsx +54 -3
  13. package/client/src/components/ContextMeter.tsx +7 -0
  14. package/client/src/components/Home/HomeView.tsx +1 -1
  15. package/client/src/components/NeedsYouBadge.tsx +31 -16
  16. package/client/src/components/OperatorQuestionNotice.tsx +10 -1
  17. package/client/src/components/ProvidersPopover.tsx +23 -12
  18. package/client/src/components/TabBar.tsx +11 -8
  19. package/client/src/components/TabStatusChip.tsx +8 -7
  20. package/client/src/components/clusterNeedsYou.ts +27 -8
  21. package/client/src/help/content/cluster.tsx +34 -22
  22. package/client/src/help/content/composer.tsx +8 -1
  23. package/client/src/help/content/header.tsx +22 -13
  24. package/client/src/help/content/misc.tsx +8 -0
  25. package/client/src/help/content/tabbar.tsx +2 -1
  26. package/client/src/help/manualSections/clusters.tsx +61 -18
  27. package/client/src/help/manualSections/gettingStarted.tsx +10 -0
  28. package/client/src/help/manualSections/maintenance.tsx +38 -8
  29. package/client/src/help/manualSections/providers.tsx +10 -3
  30. package/client/src/help/manualSections/reference.tsx +1 -1
  31. package/client/src/help/manualSections/workflows.tsx +13 -0
  32. package/client/src/help/manualSections/workspace.tsx +7 -1
  33. package/client/src/questions/waitingQuestion.ts +3 -2
  34. package/client/src/stores/appStore.ts +1 -1
  35. package/client/src/stores/appStore.types.ts +1 -0
  36. package/client/src/stores/notificationStore.ts +2 -0
  37. package/client/src/utils/activityPresentation.ts +1 -1
  38. package/client/src/utils/tabStatus.ts +8 -0
  39. package/client/src/voice/commands.ts +4 -3
  40. package/client/src/voice/executor.ts +3 -3
  41. package/client/src/ws/handleServerMessage.ts +22 -2
  42. package/client/src/ws/operatorQuestions.ts +2 -0
  43. package/docs/CLIENT.md +3 -3
  44. package/docs/FEATURES.md +1 -1
  45. package/docs/GETTING_STARTED.md +11 -5
  46. package/docs/GLOSSARY.md +6 -2
  47. package/docs/GOTCHAS.md +17 -5
  48. package/docs/OPERATIONS.md +184 -5
  49. package/docs/PERSISTENCE.md +4 -0
  50. package/docs/PRIMITIVES.md +1 -1
  51. package/docs/PROTOCOL.md +1 -1
  52. package/docs/PROTOCOL_CLUSTER.md +9 -5
  53. package/docs/PROVIDERS.md +10 -5
  54. package/docs/SETTINGS.md +4 -2
  55. package/docs/TASK_LEDGER.md +6 -0
  56. package/docs/VOICE.md +2 -0
  57. package/native/win32-arm64/manifest.json +1 -1
  58. package/node_modules/@arco/shared/dist/clusterRolePresets.d.ts +1 -1
  59. package/node_modules/@arco/shared/dist/clusterRolePresets.js +10 -0
  60. package/node_modules/@arco/shared/dist/protocol/autoPickup.js +9 -1
  61. package/node_modules/@arco/shared/dist/protocol/clientMessages.d.ts +2 -2
  62. package/node_modules/@arco/shared/dist/protocol/models.d.ts +6 -0
  63. package/node_modules/@arco/shared/dist/protocol/notifications.d.ts +4 -0
  64. package/node_modules/@arco/shared/dist/protocol/operatorQuestions.d.ts +12 -0
  65. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +9 -3
  66. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
  67. package/node_modules/@arco/shared/package.json +1 -1
  68. package/package.json +2 -2
  69. package/scripts/packaging/arco.mjs +1 -0
  70. package/server/dist/attention.d.ts +1 -1
  71. package/server/dist/attention.js +6 -4
  72. package/server/dist/capabilities.d.ts +9 -8
  73. package/server/dist/capabilities.js +71 -102
  74. package/server/dist/cliUpdateDecision.d.ts +34 -0
  75. package/server/dist/cliUpdateDecision.js +152 -0
  76. package/server/dist/clusterDirector.js +1 -0
  77. package/server/dist/clusterPeerOps.js +2 -2
  78. package/server/dist/defaults/models.md +1 -1
  79. package/server/dist/fileAccessPolicy.js +7 -5
  80. package/server/dist/http/workflowDataRoutes.js +1 -1
  81. package/server/dist/index.js +5 -1
  82. package/server/dist/primitives/seedWorker.d.ts +1 -0
  83. package/server/dist/primitives/seedWorker.js +2 -1
  84. package/server/dist/providerConversation.d.ts +9 -0
  85. package/server/dist/providerConversation.js +80 -0
  86. package/server/dist/providers/claude-native/retainedContext.d.ts +4 -0
  87. package/server/dist/providers/claude-native/retainedContext.js +20 -0
  88. package/server/dist/providers/claude-native/worker.d.ts +1 -0
  89. package/server/dist/providers/claude-native/worker.js +34 -6
  90. package/server/dist/providers/codex-appserver/operatorQuestions.d.ts +5 -0
  91. package/server/dist/providers/codex-appserver/operatorQuestions.js +30 -0
  92. package/server/dist/providers/codex-appserver/worker.js +9 -4
  93. package/server/dist/providers/ollama.js +2 -3
  94. package/server/dist/server/broadcast.d.ts +1 -1
  95. package/server/dist/smartPickupAdapters.d.ts +1 -0
  96. package/server/dist/smartPickupAdapters.js +18 -5
  97. package/server/dist/smartPickupObserver.js +45 -8
  98. package/server/dist/workers/WorkerManager.d.ts +1 -0
  99. package/server/dist/workers/WorkerManager.js +1 -0
  100. package/server/dist/workers/limits.js +6 -2
  101. package/server/dist/workflowMeta.d.ts +11 -1
  102. package/server/dist/workflowMeta.js +132 -6
  103. package/server/dist/workflows/types.d.ts +1 -0
  104. package/server/dist/ws/compactHandlers.d.ts +1 -1
  105. package/server/dist/ws/compactHandlers.js +11 -4
  106. package/server/dist/ws/handoffHandlers.js +16 -6
  107. package/server/dist/ws/operatorQuestionHandlers.d.ts +2 -1
  108. package/server/dist/ws/operatorQuestionHandlers.js +9 -1
  109. package/server/dist/ws/turnEngine.d.ts +2 -4
  110. package/server/dist/ws/turnEngine.js +88 -129
  111. package/server/package.json +1 -1
  112. package/server/src/attention.ts +5 -4
  113. package/server/src/capabilities.ts +70 -111
  114. package/server/src/cliUpdateDecision.ts +159 -0
  115. package/server/src/clusterDirector.ts +1 -0
  116. package/server/src/clusterPeerOps.ts +2 -2
  117. package/server/src/defaults/models.md +1 -1
  118. package/server/src/fileAccessPolicy.ts +7 -5
  119. package/server/src/http/workflowDataRoutes.ts +1 -1
  120. package/server/src/index.ts +5 -1
  121. package/server/src/primitives/seedWorker.ts +3 -1
  122. package/server/src/providerConversation.ts +71 -0
  123. package/server/src/providers/claude-native/retainedContext.ts +22 -0
  124. package/server/src/providers/claude-native/worker.ts +33 -5
  125. package/server/src/providers/codex-appserver/operatorQuestions.ts +24 -0
  126. package/server/src/providers/codex-appserver/worker.ts +8 -4
  127. package/server/src/providers/ollama.ts +2 -3
  128. package/server/src/smartPickupAdapters.ts +19 -5
  129. package/server/src/smartPickupObserver.ts +31 -6
  130. package/server/src/workers/WorkerManager.ts +2 -0
  131. package/server/src/workers/limits.ts +7 -2
  132. package/server/src/workflowMeta.ts +139 -5
  133. package/server/src/workflows/types.ts +1 -0
  134. package/server/src/ws/compactHandlers.ts +9 -3
  135. package/server/src/ws/handoffHandlers.ts +13 -6
  136. package/server/src/ws/operatorQuestionHandlers.ts +10 -2
  137. package/server/src/ws/turnEngine.ts +80 -135
  138. package/shared/dist/clusterRolePresets.d.ts +1 -1
  139. package/shared/dist/clusterRolePresets.js +10 -0
  140. package/shared/dist/protocol/autoPickup.js +9 -1
  141. package/shared/dist/protocol/clientMessages.d.ts +2 -2
  142. package/shared/dist/protocol/models.d.ts +6 -0
  143. package/shared/dist/protocol/notifications.d.ts +4 -0
  144. package/shared/dist/protocol/operatorQuestions.d.ts +12 -0
  145. package/shared/dist/protocol/serverMessages.d.ts +9 -3
  146. package/shared/dist/protocol/workflows.d.ts +1 -0
  147. package/shared/src/clusterRolePresets.ts +11 -1
  148. package/shared/src/protocol/autoPickup.ts +9 -1
  149. package/shared/src/protocol/clientMessages.ts +2 -1
  150. package/shared/src/protocol/models.ts +5 -2
  151. package/shared/src/protocol/notifications.ts +5 -0
  152. package/shared/src/protocol/operatorQuestions.ts +13 -0
  153. package/shared/src/protocol/serverMessages.ts +12 -2
  154. package/shared/src/protocol/workflows.ts +4 -0
@@ -12,6 +12,7 @@ export function buildClusterDirectorDoctrine(role) {
12
12
  'You are the operator-assigned Director of THIS Arco cluster: you coordinate, read the diff, and land. Peers implement, build, and test.',
13
13
  'At the start of each turn, inspect pending peer mail. If the injected shared plan is marked OUTLINE, call cluster_plan_read before deciding what to do.',
14
14
  'Reconcile relevant tasks, new peer evidence, repository state and applicable project instructions before reporting status. Read the broader plan or history when relevant or stale. Check an operator problem against the affected priorities and open items before asking them anything.',
15
+ 'When this cluster has an Advisor, consult it before a design decision or when the evidence is thin; the decision remains yours.',
15
16
  'Delegate implementation, builds, and test runs only through peer_send and track them on the board. Do not write or edit product code or tests yourself.',
16
17
  'Stay available to the operator. Hand long-running work to peers: the project\'s checks to the tester (or a builder when there is no tester), CI watching to the change\'s author. Use their reports of what was done, run and not covered; do not run builds, test suites or CI waits yourself.',
17
18
  'Never wait inside a turn: no sleep or polling longer than 60 seconds at a time. When the next step depends on a peer or on CI, say what is pending and end the turn; reports arrive as mail.',
@@ -43,7 +43,7 @@ import * as clusterPlanStore from './clusterPlanStore.js';
43
43
  import * as clusterPlanBridge from './clusterPlanBridge.js';
44
44
  import * as taskLedger from './project/taskLedger.js';
45
45
  import { appendLedgerComment, persistLedgerKernelMutation, persistLedgerMutation } from './ws/taskLedgerHandlers.js';
46
- import { isClusterDirector } from '@arco/shared';
46
+ import { isClusterDirector, presetForText } from '@arco/shared';
47
47
  // peer_send dedupe — guards against the orphan-tool-use retry pattern:
48
48
  // a previous turn aborted mid-tool, leaving the model with no memory of
49
49
  // having sent (pruneOrphanToolUse drops the orphan assistant block); on
@@ -145,7 +145,7 @@ export async function peerSend(ctx, args, opts) {
145
145
  resolved = rolePrefix[0].wfid;
146
146
  }
147
147
  else if (rolePrefix.length === 0) {
148
- const roleWord = withRole.filter((r) => r.roleLc.split(/[^a-z0-9]+/).some((part) => part === ref));
148
+ const roleWord = withRole.filter((r) => (presetForText(r.role)?.label.toLowerCase() ?? r.roleLc).split(/[^a-z0-9]+/).some((part) => part === ref));
149
149
  if (roleWord.length === 1)
150
150
  resolved = roleWord[0].wfid;
151
151
  }
@@ -36,7 +36,7 @@ The operator can set a per-workflow Claude effort floor via `minClaudeWorkerEffo
36
36
 
37
37
  ## Artifact references
38
38
 
39
- When a worker writes a report file (the server-appended footer points it at the workflow artifacts directory), reference the file in chat as `[artifact:<name>]` — e.g. `[artifact:audit-spawns.md]`. Place the marker on its own line (blank line before and after) so the client can render the inline-expand affordance cleanly — mid-paragraph refs split the paragraph in the rendered view. Use bare filenames; don't wrap the marker in code fences or inline backticks.
39
+ When a worker writes a conversation report in the workflow artifacts directory, reference the file in chat as `[artifact:<name>]` - e.g. `[artifact:audit-spawns.md]`. Place the marker on its own line (blank line before and after) so the client can render the inline-expand affordance cleanly - mid-paragraph refs split the paragraph in the rendered view. Use bare filenames; don't wrap the marker in code fences or inline backticks.
40
40
 
41
41
  **Open-ended asks are not opus signals.** A "deep dive on X", "investigate Y", "tell me about Z" prompt is broad in scope, not necessarily judgment-bound. Sonnet at `max` or GPT-5.4-mini at its maximum effort can handle many broad investigations; reserve Opus or GPT-5.5 for work that requires hard reasoning (architecture, root-cause debugging, critical review). Prompt breadth does not imply judgment depth.
42
42
 
@@ -72,12 +72,14 @@ export function assertSpellingSafe(target, pathApi = path) {
72
72
  for (let i = 0; i < parts.length; i++) {
73
73
  if (parts[i] !== '.arco')
74
74
  continue;
75
- if (!runtimePathAllowed(parts.slice(i + 1)))
75
+ const runtimeUploads = isPathWithin(pathApi.join(homedir(), '.arco'), target, pathApi) || isPathWithin(runtimeHome(), target, pathApi);
76
+ if (!runtimePathAllowed(parts.slice(i + 1), runtimeUploads))
76
77
  throw new FileAccessError();
77
78
  }
78
79
  }
79
- function runtimePathAllowed(parts) {
80
- return parts[0] === 'plans' || parts[0] === 'media-scratch'
80
+ function runtimePathAllowed(parts, allowUploads = false) {
81
+ return (allowUploads && parts[0] === 'uploads' && parts.length <= 2)
82
+ || parts[0] === 'plans' || parts[0] === 'media-scratch'
81
83
  || (parts[0] === 'workflows' && /^[a-z0-9_-]+$/.test(parts[1] || '') && ['artifacts', 'handoffs'].includes(parts[2]))
82
84
  || (['chats', 'genesis'].includes(parts[0]) && /^[a-z0-9_-]+$/.test(parts[1] || ''));
83
85
  }
@@ -94,7 +96,7 @@ export function assertSafePath(target) {
94
96
  catch { /* not created */ }
95
97
  }
96
98
  for (const root of runtimeRoots) {
97
- if (isPathWithin(root, target) && !runtimePathAllowed(path.relative(root, target).split(path.sep).map((p) => p.toLowerCase())))
99
+ if (isPathWithin(root, target) && !runtimePathAllowed(path.relative(root, target).split(path.sep).map((p) => p.toLowerCase()), true))
98
100
  throw new FileAccessError();
99
101
  }
100
102
  for (const { root, temporaryRoot } of protectedRoots()) {
@@ -175,7 +177,7 @@ export async function createReadAccessContext() {
175
177
  const assert = (target) => {
176
178
  assertSpellingSafe(target);
177
179
  for (const root of runtimeRoots) {
178
- if (isPathWithin(root, target) && !runtimePathAllowed(path.relative(root, target).split(path.sep).map(p => p.toLowerCase())))
180
+ if (isPathWithin(root, target) && !runtimePathAllowed(path.relative(root, target).split(path.sep).map(p => p.toLowerCase()), true))
179
181
  throw new FileAccessError();
180
182
  }
181
183
  protectedPaths.forEach(({ root, temporaryRoot }, index) => {
@@ -503,7 +503,7 @@ export async function tryHandleWorkflowDataRoutes(req, res, deps) {
503
503
  }
504
504
  return true;
505
505
  }
506
- // Per-workflow artifact reader. Workers write report-shaped outputs into
506
+ // Per-workflow artifact reader. Workers write conversation reports into
507
507
  // `<cwd>/.arco/workflows/<wfid>/artifacts/`; the client fetches them on
508
508
  // demand when chat contains `[artifact:<name>]`. Name is strictly sanitized.
509
509
  if (req.url?.startsWith('/api/workflows/artifact') && req.method === 'GET') {
@@ -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';
@@ -783,6 +783,10 @@ wss.on('connection', (ws) => {
783
783
  resolveVoiceTool(msg);
784
784
  break;
785
785
  }
786
+ case 'operator_question_dismiss': {
787
+ handleOperatorQuestionDismiss(ws, session, msg);
788
+ break;
789
+ }
786
790
  case 'operator_question_reply': {
787
791
  void handleOperatorQuestionReply(ws, session, msg).catch(() => {
788
792
  if (ws.readyState === WebSocket.OPEN)
@@ -49,6 +49,7 @@ export declare function runPrimaryTurn(ctx: TurnContext, args: {
49
49
  voiceOperator?: boolean;
50
50
  incognito?: boolean;
51
51
  drainSteer?: () => SteerItem[];
52
+ peekSteer?: () => readonly SteerItem[];
52
53
  requeueSteer?: (items: SteerItem[], bucket: 'steer' | 'follow-up') => void;
53
54
  onSteerDelivered?: (items: SteerItem[]) => void;
54
55
  codexTransport?: 'exec' | 'appserver';
@@ -129,7 +129,7 @@ function emitWorkerStuck(ctx, toolName, verdict) {
129
129
  }
130
130
  }
131
131
  export function runPrimaryTurn(ctx, args) {
132
- 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;
132
+ 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;
133
133
  const workerId = `primary-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
134
134
  // Claude: pre-mint on first turn so meta.json can pin it before the CLI
135
135
  // even starts. Codex mints its own; we'll learn it via the init event.
@@ -168,6 +168,7 @@ export function runPrimaryTurn(ctx, args) {
168
168
  ...(interactionMode === 'chat' ? { sandbox: 'read-only' } : {}),
169
169
  disableRssGuard,
170
170
  drainSteer,
171
+ peekSteer,
171
172
  requeueSteer,
172
173
  onSteerDelivered,
173
174
  codexTransport,
@@ -0,0 +1,9 @@
1
+ import type { ProviderName } from '@arco/shared';
2
+ import type { WorkflowState } from './workflows/types.js';
3
+ export declare function hasConversationHistory(cwd: string, workflowId: string, afterSeq?: number): Promise<boolean>;
4
+ export declare function reportConversationSaveFailure(workflowId: string, err: unknown): void;
5
+ export declare function ensureWorkflowMetadata(cwd: string, workflowId: string, wf: WorkflowState): Promise<void>;
6
+ export declare function providerConversationState(cwd: string, workflowId: string, wf: WorkflowState): Promise<WorkflowState['providerConversation']>;
7
+ export declare function saveProviderSession(cwd: string, workflowId: string, wf: WorkflowState, provider: ProviderName, sessionId: string, providerAccountRef?: string): Promise<void>;
8
+ export declare function announceReplacementConversation(workflowId: string, wf: WorkflowState): void;
9
+ export declare function markConversationReading(cwd: string, workflowId: string, wf: WorkflowState): Promise<void>;
@@ -0,0 +1,80 @@
1
+ import { resolveClaudeTransport } from './claudeTransport.js';
2
+ import { readMeta, persistInitialMeta, reconcileLatestCliSession, workflowMetaSeed, updateMeta } from './workflowMeta.js';
3
+ import { scanEventsOfTypes } from './workflowStore.js';
4
+ import { broadcastWorkflow, broadcastTransient } from './server/broadcast.js';
5
+ export async function hasConversationHistory(cwd, workflowId, afterSeq = 0) {
6
+ let found = false;
7
+ await scanEventsOfTypes(cwd, workflowId, ['primary_complete', 'primary_text'], event => { if ((('seq' in event && typeof event.seq === 'number') ? event.seq : 0) > afterSeq)
8
+ found = true; });
9
+ return found;
10
+ }
11
+ export function reportConversationSaveFailure(workflowId, err) {
12
+ console.error(`[arco] [${workflowId.slice(0, 8)}] conversation metadata save failed:`, err);
13
+ broadcastWorkflow(workflowId, { type: 'system_notice', workflowId,
14
+ content: 'Could not save the provider conversation metadata. A restart may lose its resume id. Check that the project folder is writable.' });
15
+ }
16
+ export async function ensureWorkflowMetadata(cwd, workflowId, wf) {
17
+ if (wf.config.incognito)
18
+ return;
19
+ try {
20
+ await persistInitialMeta(cwd, workflowId, wf.config, wf.primary, { sessionId: wf.primarySessionId, pendingReading: wf.providerConversation === 'awaiting-reading' });
21
+ const meta = await readMeta(cwd, workflowId);
22
+ if (meta?.providerConversationPendingReading)
23
+ wf.providerConversation = 'awaiting-reading';
24
+ }
25
+ catch (err) {
26
+ reportConversationSaveFailure(workflowId, err);
27
+ }
28
+ }
29
+ export async function providerConversationState(cwd, workflowId, wf) {
30
+ if (wf.config.incognito)
31
+ return undefined;
32
+ const provider = wf.primary.provider;
33
+ const external = provider === 'codex' || provider === 'cursor'
34
+ || (provider === 'claude' && await resolveClaudeTransport(wf, cwd) === 'cli');
35
+ if (!external)
36
+ return undefined;
37
+ if (!wf.primarySessionId) {
38
+ const boundary = wf.config.voiceOperator ? wf.config.computerContext?.lastResetSeq ?? 0 : 0;
39
+ return await hasConversationHistory(cwd, workflowId, boundary) ? 'unavailable' : undefined;
40
+ }
41
+ return wf.providerConversation === 'awaiting-reading' ? wf.providerConversation : undefined;
42
+ }
43
+ export async function saveProviderSession(cwd, workflowId, wf, provider, sessionId, providerAccountRef) {
44
+ if (wf.config.incognito)
45
+ return;
46
+ const seed = workflowMetaSeed(cwd, workflowId, wf.config, wf.primary);
47
+ seed.providerConversationPendingReading = wf.providerConversation === 'awaiting-reading';
48
+ try {
49
+ await reconcileLatestCliSession(cwd, workflowId, provider, sessionId, providerAccountRef, seed);
50
+ }
51
+ catch (err) {
52
+ reportConversationSaveFailure(workflowId, err);
53
+ }
54
+ }
55
+ // Only session discovery proves that the provider actually started the new
56
+ // conversation. Reconnecting or a failed pre-dispatch attempt is not a start.
57
+ export function announceReplacementConversation(workflowId, wf) {
58
+ if (wf.providerConversation !== 'unavailable')
59
+ return;
60
+ const provider = wf.primary.provider === 'codex' ? 'Codex' : wf.primary.provider === 'cursor' ? 'Cursor' : 'Claude CLI';
61
+ wf.providerConversation = 'awaiting-reading';
62
+ broadcastWorkflow(workflowId, { type: 'provider_conversation_state', workflowId, state: 'awaiting-reading' });
63
+ broadcastWorkflow(workflowId, { type: 'system_notice', workflowId,
64
+ content: `A new ${provider} conversation started because no saved thread id is available. Earlier messages remain in this tab.` });
65
+ }
66
+ export async function markConversationReading(cwd, workflowId, wf) {
67
+ if (wf.providerConversation !== 'awaiting-reading')
68
+ return;
69
+ wf.providerConversation = undefined;
70
+ broadcastTransient(workflowId, { type: 'provider_conversation_state', workflowId, state: 'ready' });
71
+ try {
72
+ const saved = await updateMeta(cwd, workflowId, meta => { delete meta.providerConversationPendingReading; });
73
+ if (!saved)
74
+ throw new Error('Workflow metadata disappeared before the context reading was saved.');
75
+ }
76
+ catch (err) {
77
+ reportConversationSaveFailure(workflowId, err);
78
+ }
79
+ }
80
+ //# sourceMappingURL=providerConversation.js.map
@@ -1,5 +1,9 @@
1
1
  export type ServerToolResultType = 'web_search_tool_result' | 'web_fetch_tool_result' | 'tool_search_tool_result' | 'code_execution_tool_result' | 'bash_code_execution_tool_result' | 'text_editor_code_execution_tool_result' | 'container_upload';
2
2
  export declare function isServerToolResultType(type: string): type is ServerToolResultType;
3
+ export declare function pendingServerTools(messages: readonly {
4
+ role?: string;
5
+ content?: unknown;
6
+ }[], startMessageIndex: number): string[];
3
7
  export declare function isClaudeServerToolDef(tool: unknown): boolean;
4
8
  export declare function pruneServerToolEvidenceAfterTurn(messages: Array<{
5
9
  role?: string;
@@ -10,6 +10,26 @@ const SERVER_TOOL_RESULT_TYPES = new Set([
10
10
  export function isServerToolResultType(type) {
11
11
  return SERVER_TOOL_RESULT_TYPES.has(type);
12
12
  }
13
+ // A mixed client/server response can defer its server results to a later
14
+ // assistant message. Until those IDs are answered, the continuation must
15
+ // contain only client tool_result blocks, without a steer or history splice.
16
+ export function pendingServerTools(messages, startMessageIndex) {
17
+ const pending = new Map();
18
+ for (let i = Math.max(0, startMessageIndex); i < messages.length; i++) {
19
+ const message = messages[i];
20
+ if (message.role !== 'assistant' || !Array.isArray(message.content))
21
+ continue;
22
+ for (const block of message.content) {
23
+ if (block.type === 'server_tool_use' && typeof block.id === 'string') {
24
+ pending.set(block.id, typeof block.name === 'string' ? block.name : 'server tool');
25
+ }
26
+ else if (typeof block.type === 'string' && isServerToolResultType(block.type) && typeof block.tool_use_id === 'string') {
27
+ pending.delete(block.tool_use_id);
28
+ }
29
+ }
30
+ }
31
+ return [...new Set(pending.values())];
32
+ }
13
33
  export function isClaudeServerToolDef(tool) {
14
34
  const type = tool.type;
15
35
  return typeof type === 'string' && (type.startsWith('web_search_') ||
@@ -59,6 +59,7 @@ export declare class ClaudeNativeWorker extends EventEmitter {
59
59
  private authRecovery;
60
60
  private clientTokenObtainedAt;
61
61
  private messages;
62
+ private heldSteerNotices;
62
63
  private hooks;
63
64
  private hooksLoaded;
64
65
  notifyDelays: {
@@ -58,7 +58,7 @@ import { getSandboxToolDefinitions, isSandboxTool, executeSandboxTool } from './
58
58
  import { buildMessagesFromReplayEvents, replayMessagesWithResumePolicy, compactSummarySeed } from './resumeSummary.js';
59
59
  import { readMeta, setResolvedModelId } from '../../workflowMeta.js';
60
60
  import { lspManager } from '../../lsp/client.js';
61
- import { isClaudeServerToolDef, isServerToolResultType, pruneServerToolEvidenceAfterTurn, stripDanglingServerToolResults } from './retainedContext.js';
61
+ import { isClaudeServerToolDef, isServerToolResultType, pendingServerTools, pruneServerToolEvidenceAfterTurn, stripDanglingServerToolResults } from './retainedContext.js';
62
62
  import { gzipSync } from 'node:zlib';
63
63
  import { executeNativeToolResult, getNativeToolDefinitions, } from './tools.js';
64
64
  // Phase P0 — leaf helpers extracted to keep this file under the 2000-line cap.
@@ -185,6 +185,7 @@ export class ClaudeNativeWorker extends EventEmitter {
185
185
  authRecovery = { transport: 'native', binding: nativeCredentialBinding() };
186
186
  clientTokenObtainedAt = null;
187
187
  messages = [];
188
+ heldSteerNotices = new WeakSet();
188
189
  hooks = { byEvent: {} };
189
190
  // Set once discoverTrustedHooks has run (ensureStarted, or a FOLD before any turn).
190
191
  hooksLoaded = false;
@@ -2822,6 +2823,21 @@ export class ClaudeNativeWorker extends EventEmitter {
2822
2823
  this.toolAbort = null;
2823
2824
  return;
2824
2825
  }
2826
+ // Client results alone do not close a mixed server/client turn. Match
2827
+ // server results across assistant messages before adding ordinary user
2828
+ // input or replacing history; either would end an unresolved turn.
2829
+ const pendingServer = pendingServerTools(this.messages, turnMessageStart);
2830
+ if (pendingServer.length > 0) {
2831
+ const work = pendingServer.every((name) => name === 'web_search') ? 'web search finishes'
2832
+ : pendingServer.every((name) => name === 'web_fetch') ? 'web fetch finishes' : 'server tools finish';
2833
+ for (const item of this.config.peekSteer?.() ?? []) {
2834
+ if (this.heldSteerNotices.has(item))
2835
+ continue;
2836
+ this.heldSteerNotices.add(item);
2837
+ this.emit('system_notice', `Message held until ${work}.`);
2838
+ }
2839
+ continue;
2840
+ }
2825
2841
  // In-turn auto-compaction at a clean boundary: every tool_use of this
2826
2842
  // round has its result and the next request has not been sent. Runs
2827
2843
  // before the steer drain so a steer lands after the compacted history.
@@ -4152,7 +4168,15 @@ export class ClaudeNativeWorker extends EventEmitter {
4152
4168
  this.emit('error', 'request_too_large');
4153
4169
  return 'fatal';
4154
4170
  }
4155
- if (status === 429 || status === 529 || errType === 'rate_limit_error' || errType === 'overloaded_error' || status === 500 || errType === 'api_error') {
4171
+ const gatewayError = status === 502 || status === 503 || status === 504 || (status >= 520 && status <= 524);
4172
+ // The SDK wraps failures before headers in APIConnectionError (including
4173
+ // APIConnectionTimeoutError). A dropped response body can instead expose
4174
+ // the fetch socket error directly; do not retry arbitrary statusless errors.
4175
+ const connectionCode = e.cause?.code ?? e.code ?? '';
4176
+ const connectionError = status === 0 && (err instanceof Anthropic.APIConnectionError
4177
+ || /^(?:ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|UND_ERR_(?:SOCKET|CONNECT_TIMEOUT|HEADERS_TIMEOUT|BODY_TIMEOUT))$/.test(connectionCode));
4178
+ const transportError = gatewayError || connectionError;
4179
+ if (transportError || status === 429 || status === 529 || errType === 'rate_limit_error' || errType === 'overloaded_error' || status === 500 || errType === 'api_error') {
4156
4180
  // H10 — honor Anthropic's own retry timing when it sends one. `retry-after`
4157
4181
  // (seconds or HTTP-date) wins; else the soonest `anthropic-ratelimit-*-reset`.
4158
4182
  // Falls back to the fixed 15/30/60s ladder when no usable header is present
@@ -4165,15 +4189,19 @@ export class ClaudeNativeWorker extends EventEmitter {
4165
4189
  const via = timing.source
4166
4190
  ? ` (per ${timing.source}${timing.capped ? ', capped' : ''})`
4167
4191
  : '';
4168
- const label = kind === 'genuine'
4169
- ? `rate limit (${errType || `HTTP ${status}`})`
4170
- : `overload (${errType || `HTTP ${status}`})`;
4192
+ const label = gatewayError ? `gateway error (HTTP ${status})`
4193
+ : connectionError ? (err instanceof Anthropic.APIConnectionTimeoutError ? 'connection timeout' : 'connection error')
4194
+ : kind === 'genuine'
4195
+ ? `rate limit (${errType || `HTTP ${status}`})`
4196
+ : `overload (${errType || `HTTP ${status}`})`;
4171
4197
  // Same attempt-budget guard as the auth / thinking branches: a 'retry'
4172
4198
  // on the last attempt is discarded by streamOneRound, which returns null
4173
4199
  // WITHOUT emitting — runTurn reads null as "error already emitted", so a
4174
4200
  // third consecutive 429/529/500 left the tab busy forever.
4175
4201
  if (attempt >= MAX_RETRY_ATTEMPTS - 1) {
4176
- this.emit('system_notice', `Anthropic ${label}: still failing after ${MAX_RETRY_ATTEMPTS} attempts — giving up on this turn. ${msg.slice(0, 300)}`);
4202
+ this.emit('system_notice', transportError
4203
+ ? `Anthropic could not be reached${gatewayError ? ` (HTTP ${status})` : ` (${label})`} after ${MAX_RETRY_ATTEMPTS} attempts. The conversation is intact; send a message to continue.`
4204
+ : `Anthropic ${label}: still failing after ${MAX_RETRY_ATTEMPTS} attempts — giving up on this turn. ${msg.slice(0, 300)}`);
4177
4205
  this.emit('error', `claude-native: ${label} after ${MAX_RETRY_ATTEMPTS} attempts`);
4178
4206
  return 'fatal';
4179
4207
  }
@@ -17,6 +17,10 @@ export declare function replyToOperatorQuestion(workflowId: string, requestId: s
17
17
  ok: boolean;
18
18
  error?: string;
19
19
  }>;
20
+ export declare function dismissOperatorQuestion(workflowId: string, requestId: string): {
21
+ ok: boolean;
22
+ error?: string;
23
+ };
20
24
  export declare class CodexOperatorQuestions {
21
25
  private workflowId;
22
26
  private provider;
@@ -31,6 +35,7 @@ export declare class CodexOperatorQuestions {
31
35
  }): void;
32
36
  private add;
33
37
  finish(entry: Pending, state: OperatorQuestionState): void;
38
+ settleTurn(threadId: string, turnId: string): void;
34
39
  resolvedRpc(rpcId: JsonRpcId): void;
35
40
  cancel(reason: string, rpcOnly?: boolean): void;
36
41
  }
@@ -70,6 +70,28 @@ export async function replyToOperatorQuestion(workflowId, requestId, value, send
70
70
  entry.sending = false;
71
71
  }
72
72
  }
73
+ export function dismissOperatorQuestion(workflowId, requestId) {
74
+ const entry = pending.get(requestId);
75
+ if (!entry || entry.workflowId !== workflowId)
76
+ return { ok: false, error: 'This question is no longer pending.' };
77
+ if (entry.sending)
78
+ return { ok: false, error: 'An answer is already being delivered.' };
79
+ entry.sending = true;
80
+ try {
81
+ if (entry.respond && entry.respond({ answers: {} }) === false)
82
+ throw new Error('Codex connection closed.');
83
+ if (pending.get(requestId) !== entry)
84
+ return { ok: false, error: 'This question is no longer pending.' };
85
+ entry.owner.finish(entry, { ...entry.state, status: 'cancelled', reason: 'Dismissed by the operator.' });
86
+ return { ok: true };
87
+ }
88
+ catch {
89
+ return { ok: false, error: 'The dismissal could not be delivered. The question is still pending.' };
90
+ }
91
+ finally {
92
+ entry.sending = false;
93
+ }
94
+ }
73
95
  export class CodexOperatorQuestions {
74
96
  workflowId;
75
97
  provider;
@@ -124,6 +146,14 @@ export class CodexOperatorQuestions {
124
146
  this.ids.delete(entry.state.requestId);
125
147
  entry.publish(state);
126
148
  }
149
+ settleTurn(threadId, turnId) {
150
+ for (const id of [...this.ids]) {
151
+ const p = pending.get(id);
152
+ if (p && p.rpcId === undefined && p.state.threadId === threadId && p.state.turnId === turnId) {
153
+ this.finish(p, { ...p.state, status: 'cancelled', reason: "The agent's turn ended before an answer was received." });
154
+ }
155
+ }
156
+ }
127
157
  resolvedRpc(rpcId) {
128
158
  for (const id of [...this.ids]) {
129
159
  const p = pending.get(id);
@@ -758,15 +758,17 @@ export class CodexAppServerWorker extends EventEmitter {
758
758
  //
759
759
  // Re-queue semantics on errors mirror the §9 mapping:
760
760
  // - activeTurnNotSteerable {turnKind: review|compact} → re-enqueue to
761
- // the steer bucket; the next operator turn picks it up
761
+ // the steer bucket; the queue engine delivers it at the next safe
762
+ // turn boundary, or starts a queued turn if the tab is already idle
762
763
  // - mismatched turnId / turn already ended → re-enqueue as follow-up
763
764
  // - any other transport error → re-enqueue to follow-up + system_notice
764
765
  async dispatchSteer(items) {
765
766
  const config = this.config;
766
767
  const turn = this.current;
767
768
  if (!this.rpc || !this.threadId || !this.current.turnId) {
768
- // No live turn — push everything back into follow-up so the operator
769
- // sees their messages reappear after the next user_message arrives.
769
+ // No live turn — push everything back into follow-up so the queue
770
+ // engine starts it when idle, with the normal delivery receipt. A
771
+ // later operator message must not be needed to unpark this batch.
770
772
  this.requeueSteer(items, 'follow-up', 'turn ended before steer dispatched', config);
771
773
  return;
772
774
  }
@@ -806,7 +808,8 @@ export class CodexAppServerWorker extends EventEmitter {
806
808
  }
807
809
  else {
808
810
  // Anything else — mismatched expectedTurnId, transport blip, etc.
809
- // Treat as follow-up; the operator's next turn will see the item.
811
+ // Treat as follow-up; the queue engine delivers it after the active
812
+ // turn, or starts the returned batch itself when already idle.
810
813
  const reason = err instanceof Error ? err.message : String(err);
811
814
  this.requeueSteer(items, 'follow-up', `steer rpc failed: ${reason}`, config);
812
815
  // Surface non-`activeTurnNotSteerable` failures so the operator sees
@@ -1483,6 +1486,8 @@ export class CodexAppServerWorker extends EventEmitter {
1483
1486
  // (subsequent calls during the same turn are no-ops; the turn id is the
1484
1487
  // gate).
1485
1488
  settleTurn(data) {
1489
+ if (this.threadId && this.current.turnId)
1490
+ this.operatorQuestions.settleTurn(this.threadId, this.current.turnId);
1486
1491
  this.operatorQuestions.cancel('The turn ended before an answer was received.', true);
1487
1492
  if (!this.current.turnId && !this.current.startedAt) {
1488
1493
  // No turn was actually in flight (e.g., kill() before turn/start).
@@ -23,7 +23,7 @@ import { resolveCompactionConfig, shouldAutoCompact, shouldWarnContext, splitFor
23
23
  import { consumeOllamaForceCompact } from './ollamaForceCompact.js';
24
24
  import { runUtilitySummaryJob, resolveUtilityConfig } from './ollamaUtility.js';
25
25
  import { loadEffectivePrompt as loadCompactionFraming } from '../handoffPrompts.js';
26
- import { ollamaThinkParam, parseOllamaThinking } from '@arco/shared';
26
+ import { isClusterDirector, ollamaThinkParam, parseOllamaThinking } from '@arco/shared';
27
27
  import { readSettings } from '../settings.js';
28
28
  import { resolveConfigValue } from '../configValue.js';
29
29
  import { resolveBackends, singleBackend, selectBackend, reportFailure, classifyOllamaError, backoffMs, resolveViaTailscale, isBackendCooled, OLLAMA_CONNECT_TIMEOUT_MS, OLLAMA_STREAM_START_TIMEOUT_MS, CONNECT_TIMEOUT_MARKER, } from './ollamaResilience.js';
@@ -212,8 +212,7 @@ function shouldRequireClusterPeerReport(config, observedToolNames) {
212
212
  return false;
213
213
  if (observedToolNames.has('peer_send'))
214
214
  return false;
215
- const role = (config.clusterRole ?? '').toLowerCase();
216
- if (/\b(coordinator|director)\b/.test(role))
215
+ if (isClusterDirector(config.clusterRole))
217
216
  return false;
218
217
  return true;
219
218
  }
@@ -17,7 +17,7 @@ export declare function releasePlansWatcher(cwd: string): void;
17
17
  export declare function fsWatchEnsureDir(dir: string): void;
18
18
  export declare function flushPlansWatcher(cwd: string, state: PlansWatcher): Promise<void>;
19
19
  export declare function broadcastWorkflow(workflowId: string, message: ServerMessage): void;
20
- export declare const CLUSTER_STATE_TRIGGERS: Set<"error" | "provider_fell_back" | "checkpoint_created" | "turn_changes" | "checkpoint_reverted" | "operator_question" | "operator_question_reply_result" | "mcp_registry_snapshot" | "mcp_probe_result" | "mcp_allow_snapshot" | "mcp_malware_warning" | "genesis_seed_updated" | "genesis_assist_started" | "genesis_assist_proposed" | "workflow_cwd_bound" | "genesis_scaffolded" | "genesis_creative_armed" | "genesis_plan_saved" | "computer_context_updated" | "voice_tool_call" | "computer_activity_changed" | "output_saved" | "peer_message_sent" | "peer_message_received" | "peer_send_rejected" | "cluster_snapshot_list" | "cluster_snapshot_saved" | "cluster_snapshot_conflict" | "cluster_snapshot_error" | "workflow_rename_result" | "workflow_renamed" | "cluster_state" | "cluster_not_found" | "cluster_creation_finished" | "cluster_created" | "cluster_deleted" | "cluster_member_added" | "cluster_member_removed" | "cluster_member_replaced" | "cluster_plan_changed" | "codebase_memory_state" | "cluster_broadcast_dispatched" | "cluster_dispatch_result" | "cluster_swarm_created" | "cluster_member_nudged" | "cluster_auto_turn_fired" | "hub_link_status" | "bakeoff_list_result" | "bakeoff_state" | "bakeoff_error" | "bakeoff_attempts_removed" | "review_started" | "review_artifact_ready" | "research_started" | "research_progress" | "research_complete" | "compare_started" | "compare_leg_delta" | "compare_leg_complete" | "compare_complete" | "compare_vote_recorded" | "diagnostics" | "doc_edit_started" | "doc_edit_proposed" | "md_tuneup_candidates" | "md_tuneup_started" | "md_tuneup_proposed" | "md_tuneup_applied" | "md_tuneup_undone" | "knowledge_distill_started" | "knowledge_distill_proposed" | "recall_summary_ready" | "workbench_notice" | "notification_mutes" | "attention_event" | "handoff_started" | "handoff_artifact_ready" | "handoff_complete" | "handoff_lock_snapshot" | "spawn_from_here_complete" | "live_changes_snapshot" | "storage_warning" | "git_op_result" | "media_stems_result" | "media_op_result" | "terminal_opened" | "terminal_sessions" | "terminal_killed" | "shutdown" | "terminal_command_logged" | "task_ledger_snapshot" | "task_ledger_event" | "cluster_orchestration_assist_started" | "cluster_orchestration_proposal_started" | "cluster_orchestration_proposals_snapshot" | "cluster_orchestration_proposal_proposed" | "cluster_orchestration_proposal_rejected" | "cluster_orchestration_proposal_applied" | "preview_capture_started" | "preview_capture_ready" | "plan_attached" | "plan_detached" | "plan_set" | "plan_exited" | "plan_candidate_ready" | "connected" | "workspace_snapshot" | "workspace_changed" | "workflow_config_synced" | "workflow_created" | "user_message_echo" | "primary_text" | "primary_complete" | "hook_rewrote_input" | "tool_gate_triggered" | "tool_posture_set" | "goal_set" | "goal_run_state" | "pinned_skills_set" | "project_trust_prompt" | "project_trust_set" | "worker_stuck" | "tool_loop_warning" | "file_mutation_queued" | "model_resolved" | "primary_refusal" | "primary_tool_counter" | "sandbox_chunk_added" | "sandbox_db_cleared" | "ctx_action" | "native_compacting" | "native_compacted" | "context_folded" | "tool_filtered" | "tool_evicted" | "primary_turn_token_usage" | "primary_model" | "primary_thinking" | "primary_tool_use" | "primary_activity" | "primary_turn_started" | "primary_turn_ended" | "worker_model" | "worker_spawned" | "worker_text" | "worker_thinking" | "worker_tool_use" | "worker_complete" | "worker_activity" | "worker_error" | "file_uploaded" | "file_context" | "worker_file_context" | "primary_artifact" | "quota_status" | "turn_cancelled" | "conversation_changed" | "workflow_state_snapshot" | "workflow_session_metadata" | "replay_batch" | "capabilities_updated" | "capabilities_changed" | "settings_updated" | "session_entry" | "queued_message_edit_result" | "queued_message_cancelled" | "queued_messages_drained" | "system_notice" | "claude_native_question_settled" | "session_history_status" | "codex_token_snapshot" | "gate_required" | "gate_resolved" | "gate_standing" | "preview_set" | "preview_cleared" | "preview_history" | "context_usage" | "ultracode_fleet_progress" | "context_budget" | "operator_label" | "queue_update" | "todos_updated" | "task_started" | "task_status" | "branch_summary" | "leaf_move" | "app_update_available" | "turn_messages_delivered">;
20
+ export declare const CLUSTER_STATE_TRIGGERS: Set<"error" | "provider_fell_back" | "checkpoint_created" | "turn_changes" | "checkpoint_reverted" | "operator_question" | "operator_question_reply_result" | "operator_question_dismiss_result" | "mcp_registry_snapshot" | "mcp_probe_result" | "mcp_allow_snapshot" | "mcp_malware_warning" | "genesis_seed_updated" | "genesis_assist_started" | "genesis_assist_proposed" | "workflow_cwd_bound" | "genesis_scaffolded" | "genesis_creative_armed" | "genesis_plan_saved" | "computer_context_updated" | "voice_tool_call" | "computer_activity_changed" | "output_saved" | "peer_message_sent" | "peer_message_received" | "peer_send_rejected" | "cluster_snapshot_list" | "cluster_snapshot_saved" | "cluster_snapshot_conflict" | "cluster_snapshot_error" | "workflow_rename_result" | "workflow_renamed" | "cluster_state" | "cluster_not_found" | "cluster_creation_finished" | "cluster_created" | "cluster_deleted" | "cluster_member_added" | "cluster_member_removed" | "cluster_member_replaced" | "cluster_plan_changed" | "codebase_memory_state" | "cluster_broadcast_dispatched" | "cluster_dispatch_result" | "cluster_swarm_created" | "cluster_member_nudged" | "cluster_auto_turn_fired" | "hub_link_status" | "bakeoff_list_result" | "bakeoff_state" | "bakeoff_error" | "bakeoff_attempts_removed" | "review_started" | "review_artifact_ready" | "research_started" | "research_progress" | "research_complete" | "compare_started" | "compare_leg_delta" | "compare_leg_complete" | "compare_complete" | "compare_vote_recorded" | "diagnostics" | "doc_edit_started" | "doc_edit_proposed" | "md_tuneup_candidates" | "md_tuneup_started" | "md_tuneup_proposed" | "md_tuneup_applied" | "md_tuneup_undone" | "knowledge_distill_started" | "knowledge_distill_proposed" | "recall_summary_ready" | "workbench_notice" | "notification_mutes" | "attention_event" | "attention_question_closed" | "handoff_started" | "handoff_artifact_ready" | "handoff_complete" | "handoff_lock_snapshot" | "spawn_from_here_complete" | "live_changes_snapshot" | "storage_warning" | "git_op_result" | "media_stems_result" | "media_op_result" | "terminal_opened" | "terminal_sessions" | "terminal_killed" | "shutdown" | "terminal_command_logged" | "task_ledger_snapshot" | "task_ledger_event" | "cluster_orchestration_assist_started" | "cluster_orchestration_proposal_started" | "cluster_orchestration_proposals_snapshot" | "cluster_orchestration_proposal_proposed" | "cluster_orchestration_proposal_rejected" | "cluster_orchestration_proposal_applied" | "preview_capture_started" | "preview_capture_ready" | "plan_attached" | "plan_detached" | "plan_set" | "plan_exited" | "plan_candidate_ready" | "connected" | "workspace_snapshot" | "workspace_changed" | "workflow_config_synced" | "workflow_created" | "user_message_echo" | "primary_text" | "primary_complete" | "hook_rewrote_input" | "tool_gate_triggered" | "tool_posture_set" | "goal_set" | "goal_run_state" | "pinned_skills_set" | "project_trust_prompt" | "project_trust_set" | "worker_stuck" | "tool_loop_warning" | "file_mutation_queued" | "model_resolved" | "primary_refusal" | "primary_tool_counter" | "sandbox_chunk_added" | "sandbox_db_cleared" | "ctx_action" | "native_compacting" | "native_compacted" | "context_folded" | "tool_filtered" | "tool_evicted" | "primary_turn_token_usage" | "primary_model" | "primary_thinking" | "primary_tool_use" | "primary_activity" | "primary_turn_started" | "primary_turn_ended" | "worker_model" | "worker_spawned" | "worker_text" | "worker_thinking" | "worker_tool_use" | "worker_complete" | "worker_activity" | "worker_error" | "file_uploaded" | "file_context" | "worker_file_context" | "primary_artifact" | "quota_status" | "turn_cancelled" | "conversation_changed" | "provider_conversation_state" | "workflow_state_snapshot" | "workflow_session_metadata" | "replay_batch" | "capabilities_updated" | "capabilities_changed" | "settings_updated" | "session_entry" | "queued_message_edit_result" | "queued_message_cancelled" | "queued_messages_drained" | "system_notice" | "claude_native_question_settled" | "session_history_status" | "codex_token_snapshot" | "gate_required" | "gate_resolved" | "gate_standing" | "preview_set" | "preview_cleared" | "preview_history" | "context_usage" | "ultracode_fleet_progress" | "context_budget" | "operator_label" | "queue_update" | "todos_updated" | "task_started" | "task_status" | "branch_summary" | "leaf_move" | "app_update_available" | "turn_messages_delivered">;
21
21
  export declare function broadcastCluster(clusterId: string, message: ServerMessage): void;
22
22
  export declare function sendWorkflowLive(workflowId: string, message: ServerMessage, sent?: Set<WebSocket>): void;
23
23
  export declare function buildClusterStatePayload(clusterId: string): Promise<{
@@ -11,6 +11,7 @@ export interface EvaluatorRequest {
11
11
  trace?: (line: string) => void;
12
12
  }
13
13
  export declare const EVALUATOR_STARTUP_TIMEOUT_MS = 30000;
14
+ export declare const EVALUATOR_REASONING_HEADROOM = 8192;
14
15
  export declare function isStartupFailure(reason: string): boolean;
15
16
  export interface EvaluatorAdapter {
16
17
  provider: SmartPickupEvaluatorProvider;
@@ -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, and callers treat a rejection as "no decision" (never a wake).
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.
@@ -48,8 +49,16 @@ import { localModelsUnloading } from './providers/localModelControl.js';
48
49
  // initialize about 0.25 s, session/new about 2 s); the allowance covers a cold
49
50
  // agent start (update, sign-in refresh) without touching the answer limit.
50
51
  export const EVALUATOR_STARTUP_TIMEOUT_MS = 30_000;
52
+ // Match the existing short Claude request's bounded reasoning allowance.
53
+ // The selected answer limit still caps visible text; this is total generation
54
+ // headroom for evaluator requests, not a larger permitted evaluator answer.
55
+ export const EVALUATOR_REASONING_HEADROOM = 8192;
56
+ function totalOutputLimit(req) {
57
+ return req.maxOutputTokens + (req.freeText ? 0 : EVALUATOR_REASONING_HEADROOM);
58
+ }
51
59
  // A failure before the agent session was ready (reason prefix startup_). The
52
- // observer retries such a failure once for the same mail.
60
+ // observer preserves one retry of such a failure for the same mail, with a
61
+ // fresh reservation. A second startup failure can use guarded fallback.
53
62
  export function isStartupFailure(reason) {
54
63
  return reason.startsWith('startup_');
55
64
  }
@@ -100,7 +109,8 @@ export function ollamaAdapter(opts = {}) {
100
109
  model: req.model,
101
110
  stream: false,
102
111
  ...(req.freeText ? {} : { format: ANSWER_SCHEMA }),
103
- options: { num_predict: req.maxOutputTokens, temperature: 0 },
112
+ ...(req.freeText ? {} : { think: false }),
113
+ options: { num_predict: totalOutputLimit(req), temperature: 0 },
104
114
  messages: [{ role: 'system', content: req.instructions }, { role: 'user', content: req.prompt }],
105
115
  }),
106
116
  });
@@ -154,6 +164,7 @@ export function claudeAdapter(opts = {}) {
154
164
  const resp = await client.messages.create({
155
165
  model,
156
166
  ...shortTextRequestParams(model, req.maxOutputTokens),
167
+ ...(req.freeText ? {} : { max_tokens: totalOutputLimit(req) }),
157
168
  system: [{ type: 'text', text: CLAUDE_IDENTITY }, { type: 'text', text: req.instructions }],
158
169
  messages: [{ role: 'user', content: req.prompt }],
159
170
  }, { signal });
@@ -168,6 +179,8 @@ export function claudeAdapter(opts = {}) {
168
179
  };
169
180
  if (!Array.isArray(blocks))
170
181
  return refuse('unreadable_answer');
182
+ if (resp.stop_reason === 'refusal')
183
+ return refuse('provider_refused');
171
184
  if (resp.stop_reason === 'tool_use' || types.includes('tool_use') || types.includes('other'))
172
185
  return refuse('non_text_answer');
173
186
  if (blocks.some((b) => b && typeof b === 'object' && 'type' in b && b.type === 'text' && (!('text' in b) || typeof b.text !== 'string')))
@@ -555,12 +568,12 @@ export function openAiCompatibleAdapter(provider, opts) {
555
568
  signal.throwIfAborted();
556
569
  const response = await fetchImpl(`${base}/chat/completions`, {
557
570
  method: 'POST', headers: { 'Content-Type': 'application/json' }, signal,
558
- body: JSON.stringify({ model: req.model, stream: false, max_tokens: req.maxOutputTokens, temperature: 0,
571
+ body: JSON.stringify({ model: req.model, stream: false, max_tokens: totalOutputLimit(req), temperature: 0,
559
572
  messages: [{ role: 'system', content: req.instructions }, { role: 'user', content: req.prompt }] }),
560
573
  });
561
574
  if (!response.ok)
562
575
  throw new EvaluatorRefused(response.status === 401 || response.status === 403 ? 'not_signed_in' : `provider_http_${response.status}`);
563
- const result = await boundedLocalResponse(response, outputCharCap(req.maxOutputTokens) * 4 + 16_384);
576
+ const result = await boundedLocalResponse(response, outputCharCap(totalOutputLimit(req)) * 4 + 16_384);
564
577
  const choice = result && Array.isArray(result.choices) ? result.choices[0] : undefined;
565
578
  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'))
566
579
  throw new EvaluatorRefused('tool_attempted');