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
@@ -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.
@@ -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 retries such a failure once for the same mail.
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
- options: { num_predict: req.maxOutputTokens, temperature: 0 },
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.maxOutputTokens, temperature: 0,
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.maxOutputTokens) * 4 + 16_384) as { choices?: Array<{ message?: { content?: unknown; tool_calls?: unknown; function_call?: unknown }; finish_reason?: string }> };
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,6 +11,7 @@
11
11
  // the session or mode changed while it was running.
12
12
  import {
13
13
  isSmartPickupMode,
14
+ isAutoPickupAcknowledgement,
14
15
  presetForText,
15
16
  sanitizeSmartPickupLimits,
16
17
  type SmartPickupAction,
@@ -181,7 +182,10 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
181
182
  if (prior && prior.sessionId === arm.sessionId && prior.fingerprint === snapshot.fingerprint) {
182
183
  // An admitted-in-principle wake that was blocked by a passing condition
183
184
  // (busy, cooldown) is retried without asking the evaluator again.
184
- if (prior.wakeOwed && arm.mode === 'smart-auto') return gateAndRecord({ ...base, action: 'wake', reason: 'retry', outcome: 'pending' }, arm);
185
+ if (prior.wakeOwed && arm.mode === 'smart-auto') {
186
+ const fallback = prior.action === null;
187
+ return gateAndRecord({ ...base, action: fallback ? null : 'wake', reason: fallback ? prior.reason! : 'retry', outcome: 'pending' }, arm);
188
+ }
185
189
  // A defer lapses after deferMs so unchanged mail is looked at again; an
186
190
  // evaluation refused by a passing limit is attempted again.
187
191
  const deferLapsed = prior.action === 'defer' && prior.deferUntil !== undefined && deps.now() >= prior.deferUntil;
@@ -236,21 +240,30 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
236
240
  }
237
241
  if (failure !== null) {
238
242
  const d = { ...base, action: null, reason: `evaluator_error:${failure}`.slice(0, 64), outcome: 'none' };
239
- // A failure before the evaluator session was ready (a cold agent start)
240
- // says nothing about this mail: evaluate the same mail once more, with a
241
- // new reservation counted against the limits. Any other failure, or a
242
- // second start-up failure, stands until the mail changes.
243
+ // Preserve the established one retry for a failure before the evaluator
244
+ // session was ready: the model has not seen this mail yet. The retry
245
+ // spends its own reservation. A second startup failure or any other
246
+ // failure then takes the guarded fallback path without another request.
243
247
  const sameMail = prior?.fingerprint === snapshot.fingerprint && prior.sessionId === arm.sessionId;
244
248
  if (isStartupFailure(failure) && !(sameMail && prior?.startupRetried)) {
245
249
  await record(d, { retryEvaluation: true, startupRetried: true });
246
250
  return d;
247
251
  }
252
+ if (failure === 'cancelled') {
253
+ d.outcome = 'discarded';
254
+ await record(d);
255
+ return d;
256
+ }
257
+ if (still.mode === 'smart-auto') return gateAndRecord(d, still);
258
+ d.outcome = 'fallback_observed';
248
259
  await record(d);
249
260
  return d;
250
261
  }
251
262
  const parsed = parseEvaluatorAnswer(raw);
252
263
  if (!parsed.ok) {
253
264
  const d = { ...base, action: null, reason: `invalid_answer:${parsed.problem}`, outcome: 'none' };
265
+ if (still.mode === 'smart-auto') return gateAndRecord(d, still);
266
+ d.outcome = 'fallback_observed';
254
267
  await record(d);
255
268
  return d;
256
269
  }
@@ -268,7 +281,10 @@ const TRANSIENT = new Set(['busy', 'cooldown', 'rate_capped', 'limit_wakes_membe
268
281
 
269
282
  async function gateAndRecord(proposal: ObservedDecision, arm: { sessionId: string; mode: 'smart-observe' | 'smart-auto' }): Promise<ObservedDecision> {
270
283
  const result = await gateWake(proposal, arm);
271
- const d = { ...proposal, outcome: result.outcome, ...(result.reason ? { reason: proposal.reason === 'retry' ? result.reason : `${proposal.reason}:${result.reason}` } : {}) };
284
+ const fallback = proposal.action === null;
285
+ const d = fallback
286
+ ? { ...proposal, outcome: `fallback_${result.outcome}${result.reason ? `:${result.reason}` : ''}` }
287
+ : { ...proposal, outcome: result.outcome, ...(result.reason ? { reason: proposal.reason === 'retry' ? result.reason : `${proposal.reason}:${result.reason}` } : {}) };
272
288
  const owed = result.outcome !== 'woke' && result.reason !== undefined && TRANSIENT.has(result.reason);
273
289
  await record(d, owed ? { wakeOwed: true } : {});
274
290
  return d;
@@ -302,6 +318,15 @@ async function gateWake(p: ObservedDecision, arm: { sessionId: string }): Promis
302
318
  let ids: string[];
303
319
  try { ids = await clusterMailbox.pendingIdsStrict(clusterId, wfid); } catch { refusal = 'unverifiable'; return false; }
304
320
  if (mailFingerprint(ids) !== p.fingerprint) { refusal = 'mail_changed'; return false; }
321
+ if (p.action === null) {
322
+ // Ordinary pickup ignores bare acknowledgements. Re-read the same
323
+ // exact mailbox under its lock; unreadable or empty mail cannot
324
+ // authorise fallback, and attachments retain their normal exception.
325
+ let pending: Awaited<ReturnType<typeof clusterMailbox.peek>>;
326
+ try { pending = await clusterMailbox.peek(wfid); } catch { refusal = 'unverifiable'; return false; }
327
+ if (ids.length === 0 || pending.length !== ids.length || pending.some((m) => !ids.includes(m.msgId))) { refusal = 'unverifiable'; return false; }
328
+ if (pending.every((m) => !m.artifacts?.length && isAutoPickupAcknowledgement(m.content))) { refusal = 'ack_only'; return false; }
329
+ }
305
330
  if (await smartPickupHoldActive(clusterId, wfid, ids, deps.now()).catch(() => true)) { refusal = 'stop_hold'; return false; }
306
331
  if (sharedGuardProblem(clusterId, wfid, depth, deps.now())) { refusal = 'rate_capped'; return false; }
307
332
  if (!claim()) { refusal = 'busy'; return false; }
@@ -150,6 +150,7 @@ export class WorkerManager {
150
150
  // and the next API round-trip to drain any pending mid-turn steer
151
151
  // queue entries. See WorkerConfig.drainSteer.
152
152
  drainSteer?: WorkerConfig['drainSteer'];
153
+ peekSteer?: WorkerConfig['peekSteer'];
153
154
  // Phase 6b — paired with drainSteer for the Codex app-server worker.
154
155
  // Called when `turn/steer` round-trip fails and the drained items
155
156
  // need to land back in a queue. Bucket determines whether items
@@ -289,6 +290,7 @@ export class WorkerManager {
289
290
  voiceOperator: options?.voiceOperator,
290
291
  incognito: options?.incognito,
291
292
  drainSteer: options?.drainSteer,
293
+ peekSteer: options?.peekSteer,
292
294
  requeueSteer: options?.requeueSteer,
293
295
  onSteerDelivered: options?.onSteerDelivered,
294
296
  // Phase 6 — workflowId is required for per-workflow-lifetime providers
@@ -23,7 +23,7 @@ function formatCapMb(bytes: number): string {
23
23
  export const OUTPUT_TRUNCATION_NOTICE =
24
24
  `\n\n[OUTPUT TRUNCATED — Arco enforced ${formatCapMb(MAX_WORKER_OUTPUT_BYTES)} worker-output cap. ` +
25
25
  'For reports larger than this, instruct the worker to write the full ' +
26
- 'output to a markdown file in the workflow artifacts directory and return only a brief summary + path.]';
26
+ 'output to a markdown file in the workflow artifacts directory and return only a brief summary + path, unless the operator wants it kept in the project.]';
27
27
 
28
28
  function parseRssEnv(): number {
29
29
  const raw = process.env.ARCO_RSS_KILL_BYTES;
@@ -68,6 +68,11 @@ export function buildWorkerSafetyFooter(cwd?: string, wfid?: string): string {
68
68
  ? `- For report-shaped outputs (deep dives, inventories, audits, multi-section findings), write a markdown file into \`${dir}/\` (this directory already exists) and return a brief summary that names the file in backticks (for example \`audit-spawns.md\`) so it is clickable in chat. Do NOT write report files at the project root — Arco tracks artifacts per-workflow and surfaces them inline in chat. For ordinary prose responses — even detailed ones — return the full text inline; the operator reads it in chat.`
69
69
  : `- For report-shaped outputs (deep dives, inventories, audits, multi-section findings), write a markdown file in the cwd and return a brief summary + absolute path. For ordinary prose responses — even detailed ones — return the full text inline; the operator reads it in chat.`;
70
70
 
71
+ const projectStateLine = `Never commit, force-add or add an ignore exception for \`.arco/\`, which is local state, except a skill shared through SHARE WITH REPOSITORY.`;
72
+ const projectFilesLine = dir
73
+ ? `\n- Put files the operator wants kept in the project (documentation, a README or notes to commit) in the project tree, for example \`docs/\`, not in artifacts. ${projectStateLine}`
74
+ : `\n- ${projectStateLine}`;
75
+
71
76
  const scratchLine = dir
72
77
  ? `\n- Put large intermediate files (builds, disk images, downloads, datasets) in \`${path.join(path.dirname(dir), 'scratch')}/\` (create it if missing), not in artifacts. Keep only finished deliverables in artifacts. The operator empties scratch with EMPTY SCRATCH; nothing there is deleted automatically.`
73
78
  : '';
@@ -79,7 +84,7 @@ export function buildWorkerSafetyFooter(cwd?: string, wfid?: string): string {
79
84
  - No \`find /\` / \`du -sh /\` without \`-maxdepth\` and exclusions for \`/proc /sys /dev /run\`. Skip \`~/.cache\`, \`node_modules\`, \`.git/objects\`, \`/var/cache\`, \`/snap\`.
80
85
  - No reads of \`/proc/kcore\`, \`/proc/*/mem\`, \`/dev/{kmem,mem,zero,urandom}\` past first KB. No unbounded \`journalctl\` or \`while true\` loops.
81
86
  - No \`cat\` of files >10MB; use \`head -c 100K\` instead. \`xargs\` always with explicit limits.
82
- ${bigOutputLine}${scratchLine}
87
+ ${bigOutputLine}${projectFilesLine}${scratchLine}
83
88
  - Arco will hard-kill your process tree at 32GB RSS or ${formatCapMb(MAX_WORKER_OUTPUT_BYTES)} returned output. These are the floor, not the budget.
84
89
  `;
85
90
  }
@@ -1,6 +1,7 @@
1
+ import type { PrimaryConfig } from './primitives/seedWorker.js';
1
2
  import { beginConversationWrite } from './conversationActivity.js';
2
3
  import { ensureProjectStateIgnore } from './projectStateIgnore.js';
3
- import { normalizeAutoHandoff, normalizeOutputStyle, retiredProviderReason, resolveAutoCompactionPolicy } from '@arco/shared';
4
+ import { isAutoCompactionPolicy, storedOutputStyle, normalizeAutoHandoff, normalizeOutputStyle, retiredProviderReason, resolveAutoCompactionPolicy } from '@arco/shared';
4
5
  // Slot 9 — per-workflow identity + session ledger (meta.json).
5
6
  //
6
7
  // Lives at <cwd>/.arco/workflows/<wfid>/meta.json alongside Slot 5's
@@ -80,6 +81,8 @@ export interface WorkflowMeta {
80
81
  // Append-only ledger of every CLI session bound to this workflow. Newest
81
82
  // entry last.
82
83
  cliSessions: WorkflowCliSession[];
84
+ // A replacement external conversation has not supplied its own context reading.
85
+ providerConversationPendingReading?: boolean;
83
86
  // Phase 6 Lite — session rotations archived by Handoff land here. Not the
84
87
  // same as `cliSessions[]`: a session can appear in both (it was live at
85
88
  // some point, then later archived). The history entry carries the handoff
@@ -470,8 +473,8 @@ export async function updateMeta(
470
473
  }
471
474
 
472
475
  // Ensure a meta.json exists — write one from `seed` if missing. Used by the
473
- // rehydrate path so pre-Slot-9 workflows (no meta.json on disk) get one
474
- // lazily the next time their client reconnects.
476
+ // creation, reconnect and turn paths. Existing metadata is preserved, including
477
+ // updates that land while the caller is constructing its authoritative seed.
475
478
  export async function ensureMeta(cwd: string, seed: WorkflowMeta): Promise<WorkflowMeta> {
476
479
  if (!cwd) return seed;
477
480
  validateWfid(seed.workflowId);
@@ -519,16 +522,21 @@ export async function appendCliSession(
519
522
  // with Arco's placeholder id. Update that provider's latest entry in place
520
523
  // rather than appending a second row; when the ids already match, only refresh
521
524
  // lastActiveAt. This keeps resume lookup aligned with the live CLI session
522
- // after initial binding or session rotation.
525
+ // after initial binding or session rotation. An authoritative seed repairs a
526
+ // missing file inside the same lock; generic updateMeta remains update-only.
523
527
  export async function reconcileLatestCliSession(
524
528
  cwd: string,
525
529
  wfid: string,
526
530
  provider: ProviderName,
527
531
  liveSessionId: string,
528
532
  providerAccountRef?: string,
533
+ seed?: WorkflowMeta,
529
534
  ): Promise<void> {
530
535
  if (!cwd || !liveSessionId) return;
531
- await updateMeta(cwd, wfid, (meta) => {
536
+ validateWfid(wfid);
537
+ await withFileLock(metaPath(cwd, wfid), async () => {
538
+ const meta = await readMeta(cwd, wfid) ?? seed;
539
+ if (!meta) throw new Error('Workflow metadata is missing; the provider conversation was not saved.');
532
540
  // Find the latest entry for this provider (not strictly the last overall —
533
541
  // a cross-provider workflow might have interleaved entries).
534
542
  let latestIdx = -1;
@@ -544,6 +552,11 @@ export async function reconcileLatestCliSession(
544
552
  meta.cliSessions[latestIdx].providerAccountRef = providerAccountRef;
545
553
  }
546
554
  meta.lastActiveAt = now;
555
+ if (seed) {
556
+ if (seed.providerConversationPendingReading) meta.providerConversationPendingReading = true;
557
+ else delete meta.providerConversationPendingReading;
558
+ }
559
+ await writeMeta(cwd, meta);
547
560
  });
548
561
  }
549
562
 
@@ -683,3 +696,124 @@ export async function listWorkflowMetas(cwd: string): Promise<WorkflowMetaSummar
683
696
  out.sort((a, b) => b.lastActiveAt - a.lastActiveAt);
684
697
  return out;
685
698
  }
699
+
700
+ export function workflowMetaSeed(
701
+ cwd: string, workflowId: string, config: WorkflowConfig,
702
+ primary: Pick<PrimaryConfig, 'provider' | 'model' | 'effort'>,
703
+ opts?: { parentWorkflowId?: string },
704
+ ): WorkflowMeta {
705
+ const now = Date.now();
706
+ return {
707
+ workflowId,
708
+ name: config.name,
709
+ cwd,
710
+ ...(config.kind === 'chat' ? { kind: 'chat' as const } : {}),
711
+ ...(config.kind === 'chat' && config.voiceOperator === true ? { voiceOperator: true } : {}),
712
+ createdAt: now,
713
+ lastActiveAt: now,
714
+ primaryProvider: primary.provider,
715
+ primaryModel: primary.model,
716
+ primaryEffort: primary.effort,
717
+ ...(config.providerAccountRef ? { providerAccountRef: config.providerAccountRef } : {}),
718
+ cliSessions: [],
719
+ operator: 'local',
720
+ lastEventSeq: null,
721
+ lastTranscriptSeq: null,
722
+ compactedAt: null,
723
+ ...(config.pinnedSkills?.length
724
+ ? { pinnedSkills: config.pinnedSkills.map((s) => ({ scope: s.scope, slug: s.slug })) }
725
+ : {}),
726
+ ...(opts?.parentWorkflowId ? { parentWorkflowId: opts.parentWorkflowId } : {}),
727
+ // docs/PROVIDERS.md / docs/PROVIDERS.md - when the New-tab
728
+ // picker (or Spawn-from-here parent inheritance) provided a non-default
729
+ // value, persist it to disk on the very first meta write so a server
730
+ // restart before the operator's first turn doesn't lose the pick.
731
+ // Sanitized one more time at write-site against unknown values reaching
732
+ // disk via a hand-edited cascade default.
733
+ ...(config.efficiencyToolFilter === 'off' || config.efficiencyToolFilter === 'conservative' || config.efficiencyToolFilter === 'aggressive'
734
+ ? { efficiencyToolFilter: config.efficiencyToolFilter }
735
+ : {}),
736
+ // docs/PROVIDERS.md - persist the stamped new-tab default or
737
+ // an explicit operator choice on the first meta write.
738
+ ...(config.efficiencyFactForce === 'on' || config.efficiencyFactForce === 'off'
739
+ ? { efficiencyFactForce: config.efficiencyFactForce }
740
+ : {}),
741
+ // Persist an explicit config-protection choice to disk on first meta-write
742
+ // so an operator opt-out survives a restart. Absent ⇒ gate ON by default.
743
+ ...(config.efficiencyConfigProtection === 'on' || config.efficiencyConfigProtection === 'off'
744
+ ? { efficiencyConfigProtection: config.efficiencyConfigProtection }
745
+ : {}),
746
+ ...(typeof config.claudeNativeCompact === 'boolean'
747
+ ? {
748
+ claudeNativeCompact: config.claudeNativeCompact,
749
+ ...(config.claudeNativeCompact === true ? { claudeNativeCompactUserSetAt: now } : {}),
750
+ }
751
+ : {}),
752
+ ...(typeof config.claudeNativeForceInterleavedThinkingBeta === 'boolean'
753
+ ? { claudeNativeForceInterleavedThinkingBeta: config.claudeNativeForceInterleavedThinkingBeta }
754
+ : {}),
755
+ nativeSubagents: config.nativeSubagents,
756
+ claudeNativeTaskDisabled: config.claudeNativeTaskDisabled,
757
+ ...(config.claudeNativeThinkingDisplay === 'omitted' || config.claudeNativeThinkingDisplay === 'summarized' || config.claudeNativeThinkingDisplay === 'updates'
758
+ ? { claudeNativeThinkingDisplay: config.claudeNativeThinkingDisplay }
759
+ : {}),
760
+ ...(config.codexTransport === 'exec' || config.codexTransport === 'appserver'
761
+ ? { codexTransport: config.codexTransport }
762
+ : {}),
763
+ ...(config.codexContextPolicy === 'max' || config.codexContextPolicy === 'standard'
764
+ ? { codexContextPolicy: config.codexContextPolicy }
765
+ : {}),
766
+ ...(config.claudeTransport === 'cli' || config.claudeTransport === 'native'
767
+ ? { claudeTransport: config.claudeTransport }
768
+ : {}),
769
+ // Persist the seeded auto-handoff default on the first meta-write so a
770
+ // server restart before the operator's first turn keeps the global
771
+ // default (handleCreateWorkflow bakes it into config for new tabs). The
772
+ // savedMeta restore in handleCreateWorkflow reads this back.
773
+ ...(isAutoCompactionPolicy(config.autoCompaction) ? { autoCompaction: { ...config.autoCompaction } } : {}),
774
+ ...(config.autoHandoff ? { autoHandoff: { ...config.autoHandoff } } : {}),
775
+ // docs/PROVIDERS.md - persist the sandbox toggle on the
776
+ // first meta-write when the cascade default supplied a non-undefined
777
+ // value. Default is 'off'; only the explicit on/off pair lands here so
778
+ // a stale cascade doesn't accidentally turn the sandbox on for tabs
779
+ // that were never asked.
780
+ ...(config.efficiencySandbox === 'on' || config.efficiencySandbox === 'off'
781
+ ? { efficiencySandbox: config.efficiencySandbox }
782
+ : {}),
783
+ // docs/PROVIDERS.md - persist the review-gate toggle on the first meta-write
784
+ // when the cascade default supplied an explicit value, so an operator opt-in
785
+ // survives a restart before the first turn. Default 'off'.
786
+ ...(config.reviewSafeMode === 'on' || config.reviewSafeMode === 'off'
787
+ ? { reviewSafeMode: config.reviewSafeMode }
788
+ : {}),
789
+ // Only a style other than the default is written; unset means
790
+ // DEFAULT_OUTPUT_STYLE. Legacy `lite` / `caveman` from a stale client are
791
+ // written as `plain` / `terse` (plain being the default, it stays unset).
792
+ ...(storedOutputStyle(config.outputStyle) ? { outputStyle: storedOutputStyle(config.outputStyle) } : {}),
793
+ // docs/GOTCHAS.md - persist a north-star seeded before the first turn
794
+ // (e.g. a Spawn-from-here that inherited the parent's) so it survives a
795
+ // restart even if the operator never re-sets it. Blank ⇒ omitted.
796
+ ...(config.goal && config.goal.trim() ? { goal: config.goal } : {}),
797
+ // docs/PROVIDERS.md - persist sticky ultracode on the first meta-write so a
798
+ // tab left in ultracode survives a restart (the rehydrate read in
799
+ // workflowHandlers.ts expects saved.ultracode). Without this the flag lives
800
+ // only in-memory and the tab silently drops out of ultracode on restart.
801
+ ...(config.ultracode === true ? { ultracode: true } : {}),
802
+ ...(typeof config.webSearchMaxUses === 'number' ? { webSearchMaxUses: config.webSearchMaxUses } : {}),
803
+ ...(config.managedWorktreeSourceCwd
804
+ ? { managedWorktreeSourceCwd: config.managedWorktreeSourceCwd }
805
+ : {}),
806
+ };
807
+ }
808
+
809
+ export async function persistInitialMeta(
810
+ cwd: string, workflowId: string, config: WorkflowConfig,
811
+ primary: Pick<PrimaryConfig, 'provider' | 'model' | 'effort'>,
812
+ opts?: { parentWorkflowId?: string; sessionId?: string; pendingReading?: boolean },
813
+ ): Promise<void> {
814
+ if (config.incognito) return;
815
+ const seed = workflowMetaSeed(cwd, workflowId, config, primary, opts);
816
+ if (opts?.pendingReading) seed.providerConversationPendingReading = true;
817
+ if (opts?.sessionId) seed.cliSessions.push({ provider: primary.provider, sessionId: opts.sessionId, createdAt: Date.now(), providerAccountRef: config.providerAccountRef });
818
+ await ensureMeta(cwd, seed);
819
+ }
@@ -38,6 +38,7 @@ export interface WorkflowState {
38
38
  manager: WorkerManager;
39
39
  primary: PrimaryConfig;
40
40
  primarySessionId?: string;
41
+ providerConversation?: 'unavailable' | 'awaiting-reading';
41
42
  // Owned by the user-message loop; interrupt only its worker, never reviewers
42
43
  // or compaction. Keep the claim until cancellation has actually settled.
43
44
  primaryTurn?: { token: number; workerId?: string; holdSteer: boolean; clusterDispatch?: { clusterId?: string }; interruption?: Promise<boolean | void> };
@@ -1,3 +1,4 @@
1
+ import { hasConversationHistory } from '../providerConversation.js';
1
2
  import { supportsManualCompact } from '../manualCompactCapability.js';
2
3
  // `compact_workflow` handler — operator-triggered native compaction. One WS
3
4
  // message, provider-routed:
@@ -30,6 +31,7 @@ import {
30
31
  releaseBusy,
31
32
  refreshCodexTokenSnapshot,
32
33
  resetCodexContextAfterCompact,
34
+ resetAutoCompactionCycle,
33
35
  } from './turnEngine.js';
34
36
  import { send, broadcastWorkflow, broadcastTransient, notifyClusterStateForWorkflow } from '../server/broadcast.js';
35
37
  import { workflows, workflowCwds } from '../server/state.js';
@@ -43,7 +45,7 @@ import { readSettings } from '../settings.js';
43
45
  import * as clusterStore from '../clusterStore.js';
44
46
 
45
47
  export async function handleCompactWorkflow(ws: WebSocket, session: Session, msg: CompactWorkflowMessage,
46
- claimGuard?: (claim: () => number) => Promise<number | false>, autoDetail?: string): Promise<void> {
48
+ claimGuard?: (claim: () => number) => Promise<number | false>, autoDetail?: string, onSuccess?: () => void): Promise<void> {
47
49
  const workflowId = msg.workflowId;
48
50
  const wf = workflows.get(workflowId);
49
51
  if (!wf) {
@@ -153,7 +155,7 @@ export async function handleCompactWorkflow(ws: WebSocket, session: Session, msg
153
155
  if (codexTransport !== 'appserver') {
154
156
  result = { ok: false, error: 'Compact needs the Codex app-server transport (CONFIG → TRANSPORT). On Codex exec, use Handoff.' };
155
157
  } else if (!wf.primarySessionId) {
156
- result = { ok: false, error: 'no saved Codex thread for this workflow — run a turn first' };
158
+ result = { ok: false, error: await hasConversationHistory(cwd!, workflowId) ? 'The previous Codex conversation cannot be resumed because its saved thread id is unavailable. The next message starts a new conversation; earlier messages remain in this tab.' : 'no saved Codex thread for this workflow — run a turn first' };
157
159
  } else {
158
160
  const account = await resolveProviderAccount('codex', wf.config.providerAccountRef, cwd).catch(() => null);
159
161
  const turnClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
@@ -183,7 +185,7 @@ export async function handleCompactWorkflow(ws: WebSocket, session: Session, msg
183
185
  } else if (provider === 'cursor') {
184
186
  compactedVia = 'cursor-acp';
185
187
  if (!wf.primarySessionId) {
186
- result = { ok: false, error: 'no saved Cursor session for this workflow — run a turn first' };
188
+ result = { ok: false, error: await hasConversationHistory(cwd!, workflowId) ? 'The previous Cursor conversation cannot be resumed because its saved session id is unavailable. The next message starts a new conversation; earlier messages remain in this tab.' : 'no saved Cursor session for this workflow — run a turn first' };
187
189
  } else {
188
190
  const turnClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
189
191
  result = await compactCursorAcpThread(workflowId, {
@@ -240,6 +242,10 @@ export async function handleCompactWorkflow(ws: WebSocket, session: Session, msg
240
242
  // busy now) — report the outcome but leave busy + the queue alone.
241
243
  const owned = releaseBusy(wf, busyToken, 'interrupted', false);
242
244
 
245
+ if (result.ok && owned) {
246
+ if (autoDetail) onSuccess?.();
247
+ else resetAutoCompactionCycle(wf);
248
+ }
243
249
  if (result.ok && owned && autoDetail) {
244
250
  if (provider === 'codex') resetCodexContextAfterCompact(workflowId, wf);
245
251
  else wf.lastContextPercent = 0;
@@ -1,3 +1,4 @@
1
+ import { ensureWorkflowMetadata, providerConversationState, saveProviderSession } from '../providerConversation.js';
1
2
  import { isClaudeNativeTaskActive } from '../providers/claude-native/index.js';
2
3
  import { appendHandoffNotice } from '../handoffHistoryTool.js';
3
4
  import { unsettledTaskStatuses } from './taskLifecycle.js';
@@ -78,7 +79,6 @@ import {
78
79
  appendHistoryEntry,
79
80
  readMeta,
80
81
  workflowConfigFromMeta,
81
- reconcileLatestCliSession,
82
82
  writeMeta,
83
83
  } from '../workflowMeta.js';
84
84
  import {
@@ -492,6 +492,7 @@ export async function handleHandoffRequest(
492
492
  // Clear the pinned session id so the next primary turn mints fresh.
493
493
  if (!handoffOwned()) return;
494
494
  wf.primarySessionId = undefined;
495
+ wf.providerConversation = undefined;
495
496
 
496
497
  // Retire every cached transport before the new seed, so Codex app-server
497
498
  // and Cursor ACP bootstrap their MCP children with the new history grant.
@@ -680,7 +681,7 @@ export async function handleHandoffRequest(
680
681
  // extras filter excludes non-streaming assistants when sessionChat is
681
682
  // non-empty from the pre-handoff session). No-op for non-Claude.
682
683
  startSessionWatcher(msg.workflowId, wf, cwd, ws);
683
- reconcileLatestCliSession(cwd, msg.workflowId, 'claude', primaryTurn.initialSessionId).catch((err) => {
684
+ saveProviderSession(cwd, msg.workflowId, wf, 'claude', primaryTurn.initialSessionId).catch((err) => {
684
685
  console.error(`[arco] handoff ${handle.handoffId} meta reconcile failed:`, err);
685
686
  });
686
687
  }
@@ -694,7 +695,7 @@ export async function handleHandoffRequest(
694
695
  startSessionWatcher(msg.workflowId, wf, cwd, ws);
695
696
  }
696
697
 
697
- reconcileLatestCliSession(cwd, msg.workflowId, wf.primary.provider, sid, handoffAccount?.profile.id).catch((err) => {
698
+ saveProviderSession(cwd, msg.workflowId, wf, wf.primary.provider, sid, handoffAccount?.profile.id).catch((err) => {
698
699
  console.error(`[arco] handoff ${handle.handoffId} meta reconcile (${wf.primary.provider}) failed:`, err);
699
700
  });
700
701
  });
@@ -1323,7 +1324,7 @@ export async function handleSpawnFromHere(
1323
1324
  // the usual watcher-start call never runs. Start it here once the new
1324
1325
  // session's id is known — same reasoning as the handoff fix above.
1325
1326
  startSessionWatcher(newWorkflowId, spawnedWf, newCwd, ws);
1326
- reconcileLatestCliSession(newCwd, newWorkflowId, 'claude', primaryTurn.initialSessionId).catch((err) => {
1327
+ saveProviderSession(newCwd, newWorkflowId, spawnedWf, 'claude', primaryTurn.initialSessionId).catch((err) => {
1327
1328
  console.error(`[arco] spawn meta reconcile failed:`, err);
1328
1329
  });
1329
1330
  }
@@ -1334,7 +1335,8 @@ export async function handleSpawnFromHere(
1334
1335
  wf.primarySessionId = sid;
1335
1336
  startSessionWatcher(newWorkflowId, wf, newCwd, ws);
1336
1337
  }
1337
- reconcileLatestCliSession(newCwd, newWorkflowId, newPrimary.provider, sid, spawnAccount?.profile.id).catch((err) => {
1338
+ if (!wf) return;
1339
+ saveProviderSession(newCwd, newWorkflowId, wf, newPrimary.provider, sid, spawnAccount?.profile.id).catch((err) => {
1338
1340
  console.error(`[arco] spawn meta reconcile (${newPrimary.provider}) failed:`, err);
1339
1341
  });
1340
1342
  });
@@ -1480,6 +1482,7 @@ export async function handleRehydrateWorkflows(
1480
1482
  // Read meta.json to restore primarySessionId so the next user_message
1481
1483
  // continues the prior CLI session instead of starting a fresh one.
1482
1484
  try {
1485
+ await ensureWorkflowMetadata(cwd, entry.workflowId, wf);
1483
1486
  const meta = await readMeta(cwd, entry.workflowId);
1484
1487
  if (meta) {
1485
1488
  const latestForProvider = [...meta.cliSessions].reverse().find((s) => s.provider === wf.primary.provider);
@@ -1752,6 +1755,7 @@ export async function rehydrateOneWorkflow(
1752
1755
  opts: { tail?: boolean } = {},
1753
1756
  ): Promise<void> {
1754
1757
  const cwd = wf.config.incognito ? '' : wf.config.workingDirectory;
1758
+ if (cwd) await ensureWorkflowMetadata(cwd, workflowId, wf);
1755
1759
  let latestNativeLastPromptTokens: number | undefined;
1756
1760
  const captureReplayTokens = (events: ServerMessage[]): void => {
1757
1761
  for (const event of events) {
@@ -1882,9 +1886,12 @@ export async function rehydrateOneWorkflow(
1882
1886
  : null;
1883
1887
  const codexSnapshotWindow = codexSnapshot?.modelContextWindow;
1884
1888
  const computerState = isComputer(wf) ? await computerContextState(workflowId, wf) : undefined;
1889
+ const conversationState = cwd ? await providerConversationState(cwd, workflowId, wf) : undefined;
1890
+ wf.providerConversation = conversationState;
1885
1891
  const msg: ServerMessage = {
1886
1892
  type: 'workflow_state_snapshot',
1887
1893
  workflowId,
1894
+ ...(conversationState ? { providerConversation: conversationState } : {}),
1888
1895
  workers: {},
1889
1896
  busy: wf.busy,
1890
1897
  ...(wf.busy && Number.isFinite(wf.turnStartedAt) ? { turnStartedAt: wf.turnStartedAt } : {}),
@@ -1925,7 +1932,7 @@ export async function rehydrateOneWorkflow(
1925
1932
 
1926
1933
  // Phase 2 — emit a context estimate immediately so the client has a fill
1927
1934
  // reading as soon as the snapshot arrives (not only after the next turn).
1928
- if (cwd && wf.primary.provider === 'claude' && typeof latestNativeLastPromptTokens === 'number' && latestNativeLastPromptTokens > 0) {
1935
+ if (cwd && !conversationState && wf.primary.provider === 'claude' && typeof latestNativeLastPromptTokens === 'number' && latestNativeLastPromptTokens > 0) {
1929
1936
  const estimate = nativeContextEstimate(wf.primary.model, latestNativeLastPromptTokens);
1930
1937
  if (estimate && ws.readyState === WebSocket.OPEN) {
1931
1938
  const usage = { type: 'context_usage' as const, workflowId, ...estimate };
@@ -1,8 +1,8 @@
1
1
  import { WebSocket } from 'ws';
2
- import type { OperatorQuestionReplyMessage } from '@arco/shared';
2
+ import type { OperatorQuestionReplyMessage, OperatorQuestionDismissMessage } from '@arco/shared';
3
3
  import type { Session } from '../workflows/types.js';
4
4
  import { workflows } from '../server/state.js';
5
- import { replyToOperatorQuestion } from '../providers/codex-appserver/operatorQuestions.js';
5
+ import { replyToOperatorQuestion, dismissOperatorQuestion } from '../providers/codex-appserver/operatorQuestions.js';
6
6
  import { handleUserMessage } from './turnEngine.js';
7
7
  import { broadcastWorkflow } from '../server/broadcast.js';
8
8
 
@@ -25,3 +25,11 @@ export async function handleOperatorQuestionReply(ws: WebSocket, session: Sessio
25
25
  // publisher; failed/stale reply attempts do not become transcript events.
26
26
  if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'operator_question_reply_result', workflowId: msg.workflowId, requestId: msg.requestId, ...result }));
27
27
  }
28
+
29
+ export function handleOperatorQuestionDismiss(ws: WebSocket, session: Session, msg: OperatorQuestionDismissMessage): void {
30
+ const wf = workflows.get(msg.workflowId);
31
+ const result = !wf || !wf.observers.has(ws) || !session.workflowIds.has(msg.workflowId)
32
+ ? { ok: false, error: 'Subscribe to this workflow before dismissing.' }
33
+ : dismissOperatorQuestion(msg.workflowId, msg.requestId);
34
+ if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'operator_question_dismiss_result', workflowId: msg.workflowId, requestId: msg.requestId, ...result }));
35
+ }