synabun 2.4.2 → 2.4.4

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 (220) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +83 -34
  4. package/lib/release-npm-ci.mjs +23 -1
  5. package/mcp-server/dist/http.d.ts.map +1 -1
  6. package/mcp-server/dist/http.js +8 -1
  7. package/mcp-server/dist/http.js.map +1 -1
  8. package/mcp-server/dist/services/identity.d.ts +2 -0
  9. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  10. package/mcp-server/dist/services/identity.js +4 -0
  11. package/mcp-server/dist/services/identity.js.map +1 -1
  12. package/mcp-server/dist/services/memory-client.d.ts +5 -0
  13. package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
  14. package/mcp-server/dist/services/memory-client.js +21 -2
  15. package/mcp-server/dist/services/memory-client.js.map +1 -1
  16. package/mcp-server/dist/services/memory-writer.d.ts +3 -0
  17. package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
  18. package/mcp-server/dist/services/memory-writer.js +7 -1
  19. package/mcp-server/dist/services/memory-writer.js.map +1 -1
  20. package/mcp-server/dist/services/neural-interface.d.ts +11 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -18
  23. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  24. package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
  25. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  26. package/mcp-server/dist/services/typesafe-config.js +260 -8
  27. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  28. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  29. package/mcp-server/dist/tools/agents.d.ts +3 -1
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +11 -6
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
  35. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  37. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  38. package/mcp-server/dist/tools/browser-observe.js +113 -27
  39. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  40. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  41. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  42. package/mcp-server/dist/tools/browser-readers.js +17 -0
  43. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  44. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  45. package/mcp-server/dist/tools/remember.js +6 -2
  46. package/mcp-server/dist/tools/remember.js.map +1 -1
  47. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  48. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  49. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  50. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  51. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  52. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  53. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  54. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  55. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  56. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  57. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  58. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  59. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  60. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  61. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  62. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  64. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  65. package/mcp-server/package-lock.json +5 -5
  66. package/mcp-server/package.json +1 -1
  67. package/mcp-server/src/http.ts +8 -1
  68. package/mcp-server/src/services/identity.ts +5 -0
  69. package/mcp-server/src/services/memory-client.ts +32 -12
  70. package/mcp-server/src/services/memory-writer.ts +5 -2
  71. package/mcp-server/src/services/neural-interface.ts +66 -19
  72. package/mcp-server/src/services/typesafe-config.ts +268 -7
  73. package/mcp-server/src/tools/agents.ts +12 -6
  74. package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
  75. package/mcp-server/src/tools/browser-observe.ts +117 -28
  76. package/mcp-server/src/tools/browser-readers.ts +19 -0
  77. package/mcp-server/src/tools/remember.ts +6 -1
  78. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  79. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  80. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  81. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  82. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  83. package/neural-interface/i18n/en.json +189 -1
  84. package/neural-interface/i18n/pt-BR.json +196 -8
  85. package/neural-interface/lib/assistant-api.js +123 -0
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  88. package/neural-interface/lib/assistant-dispatch.js +302 -44
  89. package/neural-interface/lib/assistant-envelope.js +40 -0
  90. package/neural-interface/lib/assistant-memory.js +3 -1
  91. package/neural-interface/lib/assistant-persona.js +6 -0
  92. package/neural-interface/lib/assistant-router.js +18 -8
  93. package/neural-interface/lib/assistant-runtime.js +182 -11
  94. package/neural-interface/lib/assistant-task-prompt.js +15 -2
  95. package/neural-interface/lib/browser-connection-state.js +20 -0
  96. package/neural-interface/lib/browser-extension-adapter.js +221 -17
  97. package/neural-interface/lib/browser-extension-archive.js +149 -0
  98. package/neural-interface/lib/browser-extension-bridge.js +46 -10
  99. package/neural-interface/lib/browser-extension-folder.js +635 -76
  100. package/neural-interface/lib/browser-extension-package.js +201 -0
  101. package/neural-interface/lib/browser-extension-pin.js +84 -0
  102. package/neural-interface/lib/browser-extension-pin.json +35 -0
  103. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +111 -13
  104. package/neural-interface/lib/browser-extension-setup.js +108 -19
  105. package/neural-interface/lib/browser-extension-update.js +104 -0
  106. package/neural-interface/lib/browser-extraction.js +38 -14
  107. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  108. package/neural-interface/lib/claude-history.js +12 -1
  109. package/neural-interface/lib/cli-install.js +23 -3
  110. package/neural-interface/lib/cli-update-planner.js +67 -4
  111. package/neural-interface/lib/confined-fs.js +25 -0
  112. package/neural-interface/lib/coordination/operations.js +2 -0
  113. package/neural-interface/lib/db.js +39 -16
  114. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  115. package/neural-interface/lib/git-bash/manager.js +28 -3
  116. package/neural-interface/lib/git-status-runner.js +31 -3
  117. package/neural-interface/lib/loop-inventory.js +162 -0
  118. package/neural-interface/lib/loop-stall.js +74 -4
  119. package/neural-interface/lib/memory-session-capture.js +157 -66
  120. package/neural-interface/lib/native-loop-providers.js +82 -13
  121. package/neural-interface/lib/native-loop-runtime.js +23 -2
  122. package/neural-interface/lib/opencode-protocol.js +4 -2
  123. package/neural-interface/lib/opencode-shell-read.js +107 -0
  124. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  125. package/neural-interface/lib/opencode-turn-release.js +173 -0
  126. package/neural-interface/lib/opencode-v2-client.js +4 -1
  127. package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
  128. package/neural-interface/lib/opencode2-client.js +341 -6
  129. package/neural-interface/lib/opencode2-translate.js +161 -4
  130. package/neural-interface/lib/peer-identity.js +62 -16
  131. package/neural-interface/lib/session-cache-builder.js +66 -18
  132. package/neural-interface/lib/session-capture-gate.js +42 -0
  133. package/neural-interface/lib/session-indexer.js +28 -20
  134. package/neural-interface/lib/teams/scheduler.js +3 -2
  135. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  136. package/neural-interface/lib/ui-blob-api.js +14 -5
  137. package/neural-interface/lib/ui-blob-store.js +302 -39
  138. package/neural-interface/lib/whatsapp/bridge.js +52 -6
  139. package/neural-interface/package-lock.json +5 -5
  140. package/neural-interface/package.json +1 -1
  141. package/neural-interface/public/extension-setup.html +6 -2
  142. package/neural-interface/public/shared/agy/agy-panel.js +38 -10
  143. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  144. package/neural-interface/public/shared/assistant/asst-api.js +67 -0
  145. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  146. package/neural-interface/public/shared/assistant/asst-panel.js +354 -11
  147. package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
  148. package/neural-interface/public/shared/assistant/asst-render.js +343 -10
  149. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  150. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  151. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  152. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  153. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  154. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  155. package/neural-interface/public/shared/assistant/asst-styles.js +21 -0
  156. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  157. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  158. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  159. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  160. package/neural-interface/public/shared/browser-extension-updates.js +88 -0
  161. package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
  162. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  163. package/neural-interface/public/shared/extension-setup/es-page.js +25 -12
  164. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  165. package/neural-interface/public/shared/extension-update-view.js +34 -0
  166. package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
  167. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  168. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  169. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
  170. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  171. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
  172. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
  173. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
  174. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  175. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +350 -0
  176. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  177. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  178. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
  179. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  180. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  181. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  182. package/neural-interface/public/shared/settings/settings-browser-extension.js +61 -13
  183. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  184. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  185. package/neural-interface/public/shared/styles.css +4 -0
  186. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  187. package/neural-interface/public/shared/tray-auto-close.js +36 -6
  188. package/neural-interface/public/shared/ui-claude-panel.js +130 -1
  189. package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
  190. package/neural-interface/public/shared/ui-notifications.js +23 -4
  191. package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
  192. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  193. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  194. package/neural-interface/public/shared/worker-end.js +18 -0
  195. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  196. package/neural-interface/scripts/rebuild-pty.js +10 -0
  197. package/neural-interface/server.js +725 -308
  198. package/npm-shrinkwrap.json +5 -5
  199. package/package.json +1 -2
  200. package/browser-extension/content.js +0 -231
  201. package/browser-extension/engine.js +0 -658
  202. package/browser-extension/icons/icon-128.png +0 -0
  203. package/browser-extension/icons/icon-16.png +0 -0
  204. package/browser-extension/icons/icon-32.png +0 -0
  205. package/browser-extension/icons/icon-48.png +0 -0
  206. package/browser-extension/icons/status-off-16.png +0 -0
  207. package/browser-extension/icons/status-off-32.png +0 -0
  208. package/browser-extension/icons/status-off-48.png +0 -0
  209. package/browser-extension/icons/status-on-16.png +0 -0
  210. package/browser-extension/icons/status-on-32.png +0 -0
  211. package/browser-extension/icons/status-on-48.png +0 -0
  212. package/browser-extension/manifest.json +0 -58
  213. package/browser-extension/popup-strings.js +0 -250
  214. package/browser-extension/popup-view.js +0 -151
  215. package/browser-extension/popup.css +0 -166
  216. package/browser-extension/popup.html +0 -108
  217. package/browser-extension/popup.js +0 -359
  218. package/browser-extension/service-worker.js +0 -283
  219. package/browser-extension/setup-content.js +0 -36
  220. package/browser-extension/tokens.css +0 -326
@@ -55,6 +55,7 @@ import { claudeTokensCostUsd } from './assistant-pricing.js';
55
55
  import { RemotePolicyError, clampDispatchSpec, getSessionPolicy, readRegisteredProjects } from './remote-policy.js';
56
56
  import { validateWorkerReply } from './worker-question.js';
57
57
  import { limitFromText } from '../public/shared/assistant/asst-limit.js';
58
+ import { abandonedPrograms, describeAbandoned } from '../public/shared/shell-stop-view.js';
58
59
  // agents-p1: a dispatch's agent_ref (lib/agents/resolve.js).
59
60
  import { agentCorrections, agentIntake, agentPinOf, agentRefOf, routedAgent, carryAgentRun, getAgentResolver, stampAgentRun } from './agents/resolve.js';
60
61
  // Agents P2 (durable agent messaging): run events, typed waits, the follow-up outbox and the transcript on disk.
@@ -537,6 +538,7 @@ export function createAssistantDispatcher({
537
538
  /** A known task class, else null. */
538
539
  const knownClass = (value) => (Object.prototype.hasOwnProperty.call(TASK_CLASS_META, String(value || '')) ? String(value) : null);
539
540
  const entries = new Map(); // runId → entry (persisted shape)
541
+ const pendingSingleClaims = new WeakMap(); // Only until this route's worker starts (including time in the queue).
540
542
  const live = new Map(); // runId → live state (in-memory only)
541
543
  const listeners = new Set();
542
544
  const queue = []; // runIds in FIFO order (state 'queued')
@@ -778,6 +780,10 @@ export function createAssistantDispatcher({
778
780
  turnCount: Array.isArray(entry.turns) ? entry.turns.length : 0,
779
781
  // The turn whose result this view carries: what a brain has read once it sees it.
780
782
  resultTurn: (Array.isArray(entry.turns) ? entry.turns.at(-1)?.n : null) ?? 0,
783
+ // A steer (steerRun) waits for its turn: true from the steer to the start of the turn that carries it.
784
+ steering: !!(live.get(entry.runId)?.steer || live.get(entry.runId)?.earlySteer),
785
+ // How the last turn ended when it did not end with a result: 'steered' (a steer cut it), else null.
786
+ turnEndReason: (Array.isArray(entry.turns) ? entry.turns.at(-1)?.endReason : null) || null,
781
787
  pending: Array.isArray(entry.pending) ? entry.pending : [],
782
788
  runtime: runtimeRun ? {
783
789
  status: runtimeRun.status, turnState: runtimeRun.turnState, stoppedReason: runtimeRun.stoppedReason,
@@ -1558,22 +1564,49 @@ export function createAssistantDispatcher({
1558
1564
 
1559
1565
  // agents-p4: `team` (lib/teams/brief.js teamBrief) and `runId` are the team scheduler's own (lib/teams/scheduler.js):
1560
1566
  // the slice a run works and the id its claims were taken under. No request body reaches these options.
1561
- async function dispatch(rawSpec = {}, { assistantSessionId = null, origin = 'assistant', brief: carried = null, notes: callerNotes = null, agentOf = null, team = null, runId: givenRunId = null } = {}) {
1562
- const sessionId = assistantSessionId ? String(assistantSessionId) : null;
1563
- const idempotencyKey = rawSpec.idempotencyKey || rawSpec.idempotency_key ? String(rawSpec.idempotencyKey || rawSpec.idempotency_key).slice(0, 200) : null;
1564
- if (idempotencyKey && sessionId) {
1565
- const hit = idempotency.get(`${sessionId}:${idempotencyKey}`);
1566
- if (hit && now() - hit.at < limits.idempotencyTtlMs && entries.has(hit.runId)) {
1567
- const prior = entries.get(hit.runId);
1568
- return { ok: true, replayed: true, queued: WAITING_STATES.has(prior.state), awaitingRoute: prior.state === 'awaiting_route', run: view(prior) };
1567
+ async function dispatch(rawSpec = {}, options = {}) {
1568
+ const sessionId = options.assistantSessionId ? String(options.assistantSessionId) : null;
1569
+ const key = String(rawSpec.idempotencyKey || rawSpec.idempotency_key || '').slice(0, 200);
1570
+ if (!key || !sessionId) return dispatchOnce(rawSpec, options, sessionId);
1571
+ const scope = `${sessionId}:${key}`;
1572
+ const hit = idempotency.get(scope);
1573
+ if (hit && (hit.pending || now() - hit.at < limits.idempotencyTtlMs)) {
1574
+ // Always wait for the first call to settle (review round 3, I3): its run is registered before fitBudget and the
1575
+ // queue rails, which may still refuse it and delete the entry, and its browser and ids are not known until
1576
+ // start. Replaying it mid-flight returned a run that no longer existed, or a stale 'queued' / 'starting' view.
1577
+ // dispatchOnce never re-enters dispatch with the same key, so this cannot wait on itself.
1578
+ if (hit.pending) {
1579
+ try { await hit.pending; } catch (error) { if (!entries.has(hit.runId)) throw error; }
1569
1580
  }
1581
+ const prior = entries.get(hit.runId);
1582
+ if (prior) return { ok: true, replayed: true, queued: WAITING_STATES.has(prior.state), awaitingRoute: prior.state === 'awaiting_route', run: view(prior) };
1570
1583
  }
1584
+ // Reserve before async profile/catalog intake. Once registered, even a failed run is replayable.
1585
+ const reservation = { runId: null, at: now() };
1586
+ idempotency.set(scope, reservation);
1587
+ try {
1588
+ reservation.pending = dispatchOnce(rawSpec, options, sessionId, key, reservation);
1589
+ return await reservation.pending;
1590
+ } finally {
1591
+ delete reservation.pending;
1592
+ // Only this call's own reservation: never one a later call put under the same key.
1593
+ if (!entries.has(reservation.runId) && idempotency.get(scope) === reservation) idempotency.delete(scope);
1594
+ }
1595
+ }
1596
+
1597
+ async function dispatchOnce(rawSpec, { origin = 'assistant', brief: carried = null, notes: callerNotes = null, agentOf = null, team = null, runId: givenRunId = null }, sessionId, idempotencyKey = null, reservation = null) {
1571
1598
  refreshLimits();
1572
1599
  refuseSessionOver(sessionId);
1573
1600
  // agents-p1: the agent the dispatch names (agent_ref) is applied before anything else reads the spec: what the
1574
1601
  // dispatch says itself wins, the definition fills the rest and never widens it (lib/agents/resolve.js). The very
1575
1602
  // same object comes back for a dispatch that names none.
1576
1603
  const original = rawSpec;
1604
+ const profile = original.moreloginProfile ?? original.morelogin_profile ?? original.moreloginEnvId ?? original.morelogin_env_id;
1605
+ const requestedBrowser = String(profile ?? '').trim() ? 'profile' : [true, 'true'].includes(original.usesBrowser) ? 'explicit' : null;
1606
+ // Escalations copy the effective flag. An older parent's record cannot distinguish its source.
1607
+ const browserSource = agentOf?.usesBrowser
1608
+ ? (agentOf.browserRequiredBy === undefined ? 'saved' : agentOf.browserRequiredBy)
1609
+ : requestedBrowser;
1577
1610
  const agentContext = { assistantSessionId: sessionId, origin, desktop, resolveExternalTools };
1578
1611
  rawSpec = agentIntake(agents, rawSpec, agentContext);
1579
1612
  // "true" (a string) is computer use too: normalizeSpec reads it so, and so must the gate.
@@ -1660,17 +1693,18 @@ export function createAssistantDispatcher({
1660
1693
  if (routed?.spec) refuseBrowserConflict(input);
1661
1694
  // agents-p4: a team's slices start on a route that is approved already; none waits on a card of its own.
1662
1695
  if (team && routed?.action === 'hold') throw new DispatchError('TEAM_ROUTE_REQUIRED', 'A team slice starts on an approved route: route the team\'s task with agent_route first and start the team with that route_id.', { status: 409, routeId: routed.routeId || null });
1696
+ const taskClass = routeClass || knownClass(input.taskClass);
1697
+ const browserRequiredBy = browserSource || (taskClass === 'design' ? 'design' : null);
1663
1698
  if (routed?.action === 'hold') {
1664
- return holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief, remoteNotes, agentNote, heldAgent });
1699
+ return holdForRoute(input, routed, { sessionId, origin, idempotencyKey, reservation, brief, remoteNotes, agentNote, heldAgent, browserRequiredBy });
1665
1700
  }
1666
1701
  // The run's class: its route's (the brain may omit task_class with a route_id), else the spec's.
1667
1702
  // Its capability backstop runs in normalizeSpec on the final target, however that was chosen.
1668
- const taskClass = routeClass || knownClass(input.taskClass);
1669
1703
  const spec = normalizeSpec(input, { catalogValue, taskClass, builtin });
1670
1704
  const queuedCount = [...entries.values()].filter((e) => e.state === 'queued' && e.assistantSessionId === sessionId).length;
1671
1705
  if (givenRunId && entries.has(String(givenRunId))) throw new DispatchError('RUN_EXISTS', `Run ${givenRunId} exists already.`, { status: 409 }); // agents-p4
1672
1706
  runId = givenRunId ? String(givenRunId) : randomId();
1673
- const entry = { ...baseEntry(runId, sessionId, origin), ...specFields(spec), notes: [...(spec.notes || []), ...remoteNotes] };
1707
+ const entry = { ...baseEntry(runId, sessionId, origin), ...specFields(spec), ...(spec.usesBrowser ? { browserRequiredBy } : {}), notes: [...(spec.notes || []), ...remoteNotes] };
1674
1708
  stampAgentRun(entry, input); // agents-p1: agentRef, agentRevision, agentPin (nothing for a dispatch without an agent)
1675
1709
  // agents-p4: a team slice's run names its team and slice from its first event on (the durable log files it under
1676
1710
  // the team), and keeps the slice's brief for its prompt. Its worker is confined by its worktree (worker-confinement.js).
@@ -1686,9 +1720,10 @@ export function createAssistantDispatcher({
1686
1720
  if (taskClass) entry.taskClass = taskClass;
1687
1721
  if (brief) { entry.brief = brief; entry.notes.push(`carries the user's brief ${brief.briefId || ''}`.trim()); }
1688
1722
  if (routed?.route) entry.route = routed.route;
1723
+ if (routed?.claimed && !team) pendingSingleClaims.set(entry, routed.claim);
1689
1724
  entries.set(runId, entry);
1690
1725
  // Before the budget check awaits (it may re-split): a retry with the same key replays this run.
1691
- if (spec.idempotencyKey && sessionId) idempotency.set(`${sessionId}:${spec.idempotencyKey}`, { runId, at: now() });
1726
+ if (reservation) Object.assign(reservation, { runId, at: now() });
1692
1727
  let budgetCorrections = [];
1693
1728
  try { budgetCorrections = await fitBudget(entry, { routed: !!routed?.route }); } catch (error) { entries.delete(runId); throw error; }
1694
1729
  entry.taskId = routed?.route?.taskId || taskAtDispatch(sessionId);
@@ -1700,7 +1735,7 @@ export function createAssistantDispatcher({
1700
1735
  ? { ...withCorrections, next: 'The user picked this route while the dispatch was on its way, so this run started on it. Do not dispatch it again when the route_decided event for this route arrives.' }
1701
1736
  : withCorrections;
1702
1737
  } catch (error) {
1703
- // A run that exists (it failed or stopped at start) used the route; a refusal before one did not.
1738
+ // A refusal before registration has no entry whose start could release the claim.
1704
1739
  if (routed?.claimed && !(runId && entries.has(runId))) router.releaseRoute?.(routed.route?.routeId, routed.claim);
1705
1740
  throw error;
1706
1741
  }
@@ -1755,6 +1790,7 @@ export function createAssistantDispatcher({
1755
1790
  }
1756
1791
 
1757
1792
  async function launchOrQueue(entry, spec, { queuedCount = 0, strict = false } = {}) {
1793
+ if (TERMINAL_STATES.has(entry.state)) return { ok: true, queued: false, run: view(entry) };
1758
1794
  const block = railBlock(spec, entry.assistantSessionId);
1759
1795
  if (block) {
1760
1796
  if (strict && !spec.queueIfBusy) {
@@ -1776,7 +1812,7 @@ export function createAssistantDispatcher({
1776
1812
  }
1777
1813
 
1778
1814
  /** Accept a dispatch the router is holding for the user's model choice. */
1779
- function holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief = null, remoteNotes = [], agentNote = null, heldAgent = null }) {
1815
+ function holdForRoute(input, routed, { sessionId, origin, idempotencyKey, reservation, brief = null, remoteNotes = [], agentNote = null, heldAgent = null, browserRequiredBy }) {
1780
1816
  const task = String(input.task || '').trim();
1781
1817
  if (!task) throw new DispatchError('TASK_REQUIRED', 'task is required');
1782
1818
  if (task.length > 20_000) throw new DispatchError('TASK_TOO_LONG', 'task must be at most 20000 characters');
@@ -1795,7 +1831,7 @@ export function createAssistantDispatcher({
1795
1831
  tags: Array.isArray(input.tags) ? input.tags.map((tag) => String(tag).trim()).filter(Boolean).slice(0, 10) : [],
1796
1832
  workflowId: input.workflowId ? String(input.workflowId) : null, parentRunId: input.parentRunId ? String(input.parentRunId) : null,
1797
1833
  usesBrowser: !!input.usesBrowser, usesComputer: input.usesComputer === true, capability: normalizeCapability(input.capability || 'full'),
1798
- idempotencyKey, rawSpec: { ...input }, route: routed.route,
1834
+ idempotencyKey, browserRequiredBy, rawSpec: { ...input }, route: routed.route,
1799
1835
  ...(heldAgent ? { heldAgent } : {}),
1800
1836
  notes: ['awaiting the user\'s model choice on the route card', ...remoteNotes],
1801
1837
  };
@@ -1819,7 +1855,7 @@ export function createAssistantDispatcher({
1819
1855
  throw new DispatchError('ROUTE_CANCELLED', closed?.message || 'This route is no longer valid: its card closed before the run could wait on it. Nothing was started; ask the user how to proceed.', { status: 409, routeId: routed.routeId });
1820
1856
  }
1821
1857
  entries.set(runId, entry);
1822
- if (idempotencyKey && sessionId) idempotency.set(`${sessionId}:${idempotencyKey}`, { runId, at: now() });
1858
+ if (reservation) Object.assign(reservation, { runId, at: now() });
1823
1859
  emit(entry, 'route_pending', { routeId: routed.routeId });
1824
1860
  return {
1825
1861
  ok: true, queued: true, awaitingRoute: true, routeId: routed.routeId, run: view(entry),
@@ -1877,15 +1913,21 @@ export function createAssistantDispatcher({
1877
1913
  }
1878
1914
 
1879
1915
  /** The user picked a target for a held run: validate, then start or queue it. */
1880
- async function resolveRoute(runId, { target, routeId = null, decidedBy = 'user', remembered = false, optionId = null, agentRequest } = {}) {
1916
+ async function resolveRoute(runId, { target, routeId = null, decidedBy = 'user', remembered = false, optionId = null, agentRequest, claim = null } = {}) {
1881
1917
  const entry = entries.get(runId);
1882
- if (!entry || entry.state !== 'awaiting_route' || !target?.provider) return { ok: false, code: 'NOT_HELD' };
1918
+ if (!entry || entry.state !== 'awaiting_route' || !target?.provider) {
1919
+ if (claim) router?.releaseRoute?.(routeId, claim);
1920
+ return { ok: false, code: 'NOT_HELD' };
1921
+ }
1922
+ if (claim) pendingSingleClaims.set(entry, claim);
1883
1923
  const catalogValue = await catalogSnapshot();
1884
1924
  let spec;
1885
1925
  const remoteNotes = [];
1886
1926
  try {
1927
+ if (entry.state !== 'awaiting_route') return { ok: false, code: 'NOT_HELD' };
1887
1928
  const pick = workerForRoutePick(entry, target, agentRequest);
1888
1929
  let input = pick.input.moreloginProfile || pick.input.morelogin_profile ? await withBrowserProfile(pick.input) : pick.input;
1930
+ if (entry.state !== 'awaiting_route') return { ok: false, code: 'NOT_HELD' };
1889
1931
  input = clampRemote(input, entry.assistantSessionId, remoteNotes);
1890
1932
  const pin = entry.heldAgent ? agentPinOf(input) : entry.agentPin;
1891
1933
  spec = normalizeSpec(input, { catalogValue, taskClass: entry.taskClass || null, builtin: pin?.source === 'builtin' || !!pin?.classDefault });
@@ -1897,6 +1939,8 @@ export function createAssistantDispatcher({
1897
1939
  }
1898
1940
  }
1899
1941
  catch (error) {
1942
+ if (entry.state !== 'awaiting_route') return { ok: false, code: 'NOT_HELD' };
1943
+ releaseStartupClaim(entry);
1900
1944
  entry.state = 'failed'; entry.completionReason = 'route_invalid'; entry.finishedAt = iso(now()); entry.turnState = 'terminal';
1901
1945
  entry.error = error?.message || String(error);
1902
1946
  entry.notes.push(`route target rejected: ${entry.error}`);
@@ -1906,6 +1950,7 @@ export function createAssistantDispatcher({
1906
1950
  return { ok: false, error };
1907
1951
  }
1908
1952
  Object.assign(entry, specFields(spec));
1953
+ if (!entry.usesBrowser) delete entry.browserRequiredBy;
1909
1954
  entry.notes.push(...(spec.notes || []), ...remoteNotes.filter((note) => !entry.notes.includes(note)), `route decided by ${decidedBy}: ${spec.provider}/${spec.model || 'default'}`);
1910
1955
  entry.route = {
1911
1956
  ...(entry.route || {}), routeId: routeId || entry.route?.routeId || null, status: 'approved', decidedBy, remembered, optionId,
@@ -2109,18 +2154,55 @@ export function createAssistantDispatcher({
2109
2154
  }).catch(() => { if (entry.judging) done(); });
2110
2155
  }
2111
2156
 
2157
+ // The native runtime accepts launch before its provider boots. Its started event commits
2158
+ // the claim by removing it from this map. Only a terminal exit before that point gives it back.
2159
+ function releaseStartupClaim(entry) {
2160
+ if (!pendingSingleClaims.has(entry)) return;
2161
+ const claim = pendingSingleClaims.get(entry);
2162
+ pendingSingleClaims.delete(entry);
2163
+ router?.releaseRoute?.(entry.route.routeId, claim);
2164
+ }
2165
+
2112
2166
  async function start(entry) {
2167
+ if (entry.state !== 'queued') return;
2168
+ entry.state = 'starting';
2169
+ entry.turnState = 'starting';
2170
+ try { return await startWorker(entry); }
2171
+ catch (error) {
2172
+ releaseStartupClaim(entry);
2173
+ if (!TERMINAL_STATES.has(entry.state)) {
2174
+ entry.state = 'failed'; entry.turnState = 'terminal'; entry.finishedAt = iso(now());
2175
+ entry.completionReason = 'startup_error'; entry.error = error?.message || String(error);
2176
+ emit(entry, 'failed');
2177
+ }
2178
+ if (!closing && queue.length) processQueue().catch(() => {});
2179
+ throw error;
2180
+ }
2181
+ }
2182
+
2183
+ async function startWorker(entry) {
2184
+ // Every failure exit gives the single route back FIRST (review round 3, I1c-a): before the run reads as failed and
2185
+ // before anything is awaited, so a retry that sees the failure is never refused by the route this run still held.
2113
2186
  try { requireConfinementProvider(entry); } catch (error) {
2187
+ releaseStartupClaim(entry);
2114
2188
  entry.state = 'failed'; entry.error = error.message; entry.completionReason = 'confinement_provider_mismatch';
2115
2189
  entry.finishedAt = iso(now()); entry.turnState = 'terminal';
2116
2190
  emit(entry, 'failed');
2117
2191
  throw error;
2118
2192
  }
2119
2193
  const runtime = safeRuntime();
2120
- if (!runtime) throw new DispatchError('RUNTIME_UNAVAILABLE', 'Native loop runtime is not available', { status: 503 });
2194
+ if (!runtime) {
2195
+ releaseStartupClaim(entry);
2196
+ entry.state = 'failed'; entry.turnState = 'terminal'; entry.completionReason = 'runtime_unavailable'; entry.finishedAt = iso(now());
2197
+ entry.error = 'Native loop runtime is not available';
2198
+ emit(entry, 'failed');
2199
+ throw new DispatchError('RUNTIME_UNAVAILABLE', entry.error, { status: 503 });
2200
+ }
2121
2201
  // A queued or held run starts under the budget as it is now (its provider's share included).
2122
2202
  refreshLimits();
2123
2203
  try { await fitBudget(entry, { routed: true }); } catch (error) {
2204
+ if (entry.state !== 'starting') throw error;
2205
+ releaseStartupClaim(entry);
2124
2206
  entry.state = 'stopped';
2125
2207
  entry.completionReason = error?.code === 'BUDGET_UNPRICED' ? 'budget_unpriced' : error?.code === 'BUDGET_SHARE_EXHAUSTED' ? 'budget_share' : 'session_budget_cap';
2126
2208
  entry.finishedAt = iso(now()); entry.turnState = 'terminal'; entry.pending = [];
@@ -2128,19 +2210,30 @@ export function createAssistantDispatcher({
2128
2210
  emit(entry, 'stopped');
2129
2211
  throw error;
2130
2212
  }
2213
+ if (entry.state !== 'starting') return;
2131
2214
  if (loopDir && !existsSync(loopDir)) mkdirSync(loopDir, { recursive: true });
2132
2215
  let browserSessionId = null;
2133
2216
  let browserTabId = null;
2134
- if (entry.usesBrowser && typeof acquireLoopBrowserAndTab === 'function') {
2135
- pinEntryBrowserProfile(entry);
2136
- const acq = await acquireLoopBrowserAndTab({ requestedBrowserSessionId: entry.requestedBrowserSessionId, terminalSessionId: entry.runId, logTag: 'assistant:browser' });
2217
+ pinEntryBrowserProfile(entry);
2218
+ // Older records have no source and keep their original browser requirement.
2219
+ if (entry.usesBrowser && entry.browserRequiredBy !== null && typeof acquireLoopBrowserAndTab === 'function') {
2220
+ let acq;
2221
+ try { acq = await acquireLoopBrowserAndTab({ requestedBrowserSessionId: entry.requestedBrowserSessionId, terminalSessionId: entry.runId, logTag: 'assistant:browser' }); }
2222
+ catch (error) { acq = { error: error?.message || String(error), code: error?.code }; }
2223
+ if (entry.state !== 'starting') {
2224
+ if (acq?.browserSessionId) await releaseSharedBrowserTab(acq.browserSessionId, entry.runId).catch(() => {});
2225
+ return;
2226
+ }
2137
2227
  if (acq?.error) {
2138
- entry.state = 'failed'; entry.completionReason = 'browser_unavailable'; entry.finishedAt = iso(now()); entry.notes.push(acq.error);
2228
+ const source = { profile: `morelogin_profile "${entry.moreloginEnvName || entry.moreloginEnvId}" on this dispatch`, design: 'the design task class', explicit: 'uses_browser:true on this dispatch' }[entry.browserRequiredBy] || 'the saved browser requirement for this worker';
2229
+ entry.error = `${acq.error} Browser required by ${source}.`;
2230
+ releaseStartupClaim(entry);
2231
+ entry.state = 'failed'; entry.turnState = 'terminal'; entry.completionReason = 'browser_unavailable'; entry.finishedAt = iso(now()); entry.notes.push(entry.error);
2139
2232
  // The native serve boundary's refusal keeps its own code and the serves it names, on the run and the error.
2140
2233
  const boundary = acq.code === 'NATIVE_SERVE_UNVERIFIED' ? { browserCode: acq.code, offenders: Array.isArray(acq.offenders) ? acq.offenders : [] } : null;
2141
2234
  if (boundary) entry.browserError = boundary;
2142
2235
  emit(entry, 'failed');
2143
- throw new DispatchError('PROVIDER_UNAVAILABLE', acq.error, { status: 500, ...(boundary || {}) });
2236
+ throw new DispatchError('PROVIDER_UNAVAILABLE', entry.error, { status: 500, ...(boundary || {}) });
2144
2237
  }
2145
2238
  browserSessionId = acq.browserSessionId || null;
2146
2239
  browserTabId = acq.browserTabId || null;
@@ -2166,8 +2259,6 @@ export function createAssistantDispatcher({
2166
2259
  // The project's Style Guide, read now like the rules: its summary and file paths go to the
2167
2260
  // prompt only (never the loop state file). null without a saved guide, or for a class it keeps out.
2168
2261
  const styleGuide = styleGuideFor(entry);
2169
- entry.state = 'starting';
2170
- entry.turnState = 'starting';
2171
2262
  entry.startedAt = state.startedAt;
2172
2263
  try {
2173
2264
  const descriptor = await runtime.launch({
@@ -2186,7 +2277,9 @@ export function createAssistantDispatcher({
2186
2277
  reconcileKeepAwake();
2187
2278
  return descriptor;
2188
2279
  } catch (error) {
2189
- entry.state = 'failed'; entry.completionReason = 'launch_error'; entry.finishedAt = iso(now());
2280
+ releaseStartupClaim(entry);
2281
+ entry.state = 'failed'; entry.turnState = 'terminal'; entry.completionReason = 'launch_error'; entry.finishedAt = iso(now());
2282
+ entry.error = error?.message || String(error);
2190
2283
  entry.notes.push(error?.message || String(error));
2191
2284
  if (browserSessionId) await releaseSharedBrowserTab(browserSessionId, entry.runId).catch(() => {});
2192
2285
  releaseDesktop(entry);
@@ -2493,7 +2586,27 @@ export function createAssistantDispatcher({
2493
2586
  // A queued follow-up is sent exactly here, as its prompt goes to the provider: a restart from now on continues
2494
2587
  // this turn (resumeInfo.inFlight) and never sends the text a second time.
2495
2588
  if (outboxId) { try { await coordination.followUps.markSent([outboxId]); } catch (error) { log(entry.runId, 'assistant:follow-up-error', error?.message || String(error)); } }
2496
- let raw = await inner.runTurn(prompt, { ...meta, turn: turnNumber, outputSchema: entry.outputSchema || undefined });
2589
+ // A steer may land here (steerRun): it clears for the turn it interrupts, never one of its own.
2590
+ if (liveState.steer && outboxId && liveState.steer.outboxId === outboxId) liveState.steer = null;
2591
+ // A steer that came while the run was still starting (no turn open yet) rides this turn's prompt: the task and
2592
+ // the change go together, in the first turn, and its outbox row is sent with it.
2593
+ if (liveState.earlySteer && outboxId && liveState.earlySteer.outboxId === outboxId) liveState.earlySteer = null;
2594
+ if (liveState.earlySteer && !liveState.steer) {
2595
+ const early = liveState.earlySteer;
2596
+ liveState.earlySteer = null;
2597
+ prompt = `${prompt}\n\n${buildFollowUpPrompt(early.text, state, { turn: turnNumber, maxTurns: entry.maxTurns, origin: 'steer', testDensity: changedTestDensity(entry) })}`;
2598
+ if (early.outboxId) { try { await coordination.followUps.markSent([early.outboxId]); } catch (error) { log(entry.runId, 'assistant:follow-up-error', error?.message || String(error)); } }
2599
+ }
2600
+ const turnInfo = { turnNumber, taskId, origin, label, startedAt, prompt };
2601
+ let raw;
2602
+ try { raw = await inner.runTurn(prompt, { ...meta, turn: turnNumber, outputSchema: entry.outputSchema || undefined }); }
2603
+ catch (error) {
2604
+ if (steeredAway(liveState)) return endSteeredTurn(entry, liveState, error, turnInfo);
2605
+ throw error;
2606
+ }
2607
+ // The provider finished the turn although a steer cut it (the interrupt came as it ended, or before the
2608
+ // provider had the prompt): the turn still ends as steered, and the steer's own turn follows.
2609
+ if (steeredAway(liveState)) return endSteeredTurn(entry, liveState, raw, turnInfo);
2497
2610
  if (entry.provider === 'codex') settleCodexTurn(entry, liveState, raw);
2498
2611
  else if (entry.provider === 'antigravity') settleAntigravityTurn(entry, liveState, raw);
2499
2612
  let text = typeof raw?.text === 'string' ? raw.text : '';
@@ -2539,6 +2652,8 @@ export function createAssistantDispatcher({
2539
2652
  // turn_completed or follow-up after it. The first provider turn was paid for: book it first.
2540
2653
  // Suspended for a server restart during it: the turn stays in flight for the resume.
2541
2654
  if (liveState.abortReason || liveState.suspending) { accumulateCost(entry, raw); throw error; }
2655
+ // Steered during the result-retry turn: the turn ends as steered (its first provider turn is booked here).
2656
+ if (steeredAway(liveState)) { accumulateCost(entry, raw); return endSteeredTurn(entry, liveState, error, turnInfo); }
2542
2657
  retryCost = accumulateCost(entry, error);
2543
2658
  if (entry.provider === 'codex') settleCodexTurn(entry, liveState, error);
2544
2659
  else if (entry.provider === 'antigravity') settleAntigravityTurn(entry, liveState, error);
@@ -2615,6 +2730,23 @@ export function createAssistantDispatcher({
2615
2730
  checkSession(entry.assistantSessionId, { source: entry });
2616
2731
  return parsed;
2617
2732
  };
2733
+ // A turn a steer interrupted (endSteeredTurn) is followed at once by the steer's own turn, in the same session;
2734
+ // a steer of that turn again cuts it too. Its outbox row is marked sent as its prompt goes (runInnerTurn).
2735
+ const runSteerable = async (prompt, meta, opts) => {
2736
+ let out = await runInnerTurn(prompt, meta, opts);
2737
+ while (out?.steered) {
2738
+ const steer = liveState.steer;
2739
+ if (!steer || liveState.abortReason || liveState.suspending || liveState.dead) return out;
2740
+ // The provider's own interrupt must be over before the next prompt goes (OpenCode's session abort).
2741
+ try { await steer.settled; } catch {}
2742
+ if (liveState.abortReason || liveState.suspending || liveState.dead) return out;
2743
+ liveState.steer = null;
2744
+ const steerPrompt = buildFollowUpPrompt(steer.text, state, { turn: liveState.turnCounter + 1, maxTurns: entry.maxTurns, origin: 'steer', testDensity: changedTestDensity(entry) });
2745
+ const followPrompt = out.notSent && out.prompt ? `${out.prompt}\n\n${steerPrompt}` : steerPrompt;
2746
+ out = await runInnerTurn(followPrompt, meta, { origin: 'steer', label: clip(steer.text, 80), followUp: steer.text, taskId: steer.taskId || entry.taskId || null, outboxId: steer.outboxId || null });
2747
+ }
2748
+ return out;
2749
+ };
2618
2750
  return {
2619
2751
  identity: () => (typeof inner.identity === 'function' ? inner.identity() : {}),
2620
2752
  isAlive: () => !liveState.dead && (typeof inner.isAlive === 'function' ? inner.isAlive() : true),
@@ -2627,7 +2759,7 @@ export function createAssistantDispatcher({
2627
2759
  liveState.resume = null;
2628
2760
  if (resume?.mode !== 'idle') {
2629
2761
  try {
2630
- await runInnerTurn(prompt, meta, resume?.mode === 'mid_turn'
2762
+ await runSteerable(prompt, meta, resume?.mode === 'mid_turn'
2631
2763
  ? { origin: 'resume', label: 'resumed after a server restart', taskId: resume.taskId || entry.taskId || null }
2632
2764
  : { origin: 'dispatch' });
2633
2765
  } catch (error) {
@@ -2690,7 +2822,7 @@ export function createAssistantDispatcher({
2690
2822
  }
2691
2823
  try {
2692
2824
  const followPrompt = buildFollowUpPrompt(next.text, state, { turn: liveState.turnCounter + 1, maxTurns: entry.maxTurns, origin: next.origin, testDensity: changedTestDensity(entry) });
2693
- await runInnerTurn(followPrompt, meta, { origin: next.origin, label: clip(next.text, 80), followUp: next.text, taskId: next.taskId || entry.taskId || null, outboxId: next.id || null });
2825
+ await runSteerable(followPrompt, meta, { origin: next.origin, label: clip(next.text, 80), followUp: next.text, taskId: next.taskId || entry.taskId || null, outboxId: next.id || null });
2694
2826
  } catch (error) {
2695
2827
  pauseWork(entry, liveState);
2696
2828
  return handleTurnError(error, liveState, entry, ctx);
@@ -2776,6 +2908,92 @@ export function createAssistantDispatcher({
2776
2908
  };
2777
2909
  }
2778
2910
 
2911
+ // ── steer (a change of the work mid-run) ───────────────────────────────────
2912
+ /** The turn's provider call ended because a steer interrupted it (and nothing stronger: a stop, a shutdown). */
2913
+ function steeredAway(liveState) {
2914
+ return !!liveState.steer?.interrupting && !liveState.abortReason && !liveState.suspending && !liveState.dead;
2915
+ }
2916
+ /**
2917
+ * The end of a turn a steer cut: what it spent is booked, its record says `endReason: 'steered'` with no result
2918
+ * (never a failure, never a completion: lastResult, the escalation and the worker-end card stay as they were), its
2919
+ * work time stops, and the turn loop goes on with the steer's own turn (runSteerable).
2920
+ */
2921
+ function endSteeredTurn(entry, liveState, error, { turnNumber, taskId, origin, label, startedAt, prompt }) {
2922
+ liveState.turnOpen = false;
2923
+ stopUsagePolling(liveState);
2924
+ const booked = accumulateCost(entry, error);
2925
+ if (entry.provider === 'codex') settleCodexTurn(entry, liveState, error);
2926
+ else if (entry.provider === 'opencode') bookOpenCodeTurn(entry, liveState, { reconciled: false });
2927
+ else if (entry.provider === 'antigravity') settleAntigravityTurn(entry, liveState, error);
2928
+ const turn = {
2929
+ n: turnNumber, taskId, origin, label, startedAt, endedAt: iso(now()), promptPreview: clip(prompt, 200), text: '',
2930
+ usage: liveState.turnUsage || error?.usage || null, tokens: withTotal(liveState.turnTokens || zeroTokens()),
2931
+ costUsd: Number(Math.max(0, (Number(booked) || 0) + (Number(liveState.turnMeteredUsd) || 0)).toFixed(8)),
2932
+ result: null, endReason: 'steered',
2933
+ };
2934
+ liveState.turnTokens = null;
2935
+ entry.turns = [...(entry.turns || []), turn].slice(-50);
2936
+ if (entry.resumeInfo) delete entry.resumeInfo.inFlight;
2937
+ entry.steeredTurns = (Number(entry.steeredTurns) || 0) + 1;
2938
+ pauseWork(entry, liveState);
2939
+ if (liveState.steer) liveState.steer.interrupting = false;
2940
+ entry.notes.push(`turn ${turnNumber} interrupted by a steer`);
2941
+ emit(entry, 'turn_steered', { turn: turnNumber });
2942
+ announceUnpriced(entry);
2943
+ checkSession(entry.assistantSessionId, { source: entry });
2944
+ // The provider never had the cut turn's prompt (it was still starting): the steer's turn carries it again.
2945
+ return { steered: true, turn: turnNumber, notSent: error?.notSent === true, prompt };
2946
+ }
2947
+ /**
2948
+ * Steer a run: the user changed what it is doing. A turn in flight is interrupted at the provider (the session stays
2949
+ * warm, its context kept, tool calls already done stay done), a pending permission or question is denied, and the
2950
+ * steer follows at once as the next turn ("STEER from the user (mid-run): …"). An idle run takes it as a follow-up
2951
+ * with the same wording; a run away for a restart gets it after its resume. The steer goes through the outbox like
2952
+ * every follow-up, so a restart in between still delivers it. → { ok, target, interruptedTurn, run }.
2953
+ */
2954
+ async function steerRun(runId, text, { from = 'assistant', assistantSessionId = null } = {}) {
2955
+ const entry = entries.get(String(runId || ''));
2956
+ if (!entry || (assistantSessionId && String(entry.assistantSessionId || '') !== String(assistantSessionId))) {
2957
+ throw new DispatchError('RUN_NOT_FOUND', `Unknown run ${runId}${entry ? ' in this assistant session' : ''}`, { status: 404 });
2958
+ }
2959
+ const message = String(text || '').trim();
2960
+ if (!message) throw new DispatchError('MESSAGE_REQUIRED', 'text is required');
2961
+ if (message.length > 20_000) throw new DispatchError('MESSAGE_TOO_LONG', 'text must be at most 20000 characters');
2962
+ if (TERMINAL_STATES.has(entry.state) || finalizations.has(entry.runId)) {
2963
+ throw new DispatchError('RUN_NOT_ACTIVE', `Run ${entry.runId} is ${TERMINAL_STATES.has(entry.state) ? entry.state : 'finishing'}: a run that ended cannot be steered; dispatch a new run with its result as context.`, { status: 409, resumable: false });
2964
+ }
2965
+ if (entry.state === 'queued') throw new DispatchError('RUN_NOT_STARTED', `Run ${entry.runId} is still queued`, { status: 409 });
2966
+ const origin = from === 'user' ? 'user' : 'assistant';
2967
+ const at = iso(now());
2968
+ const away = entry.state === 'suspended' || entry.state === 'resuming';
2969
+ const liveState = away ? null : live.get(entry.runId);
2970
+ if (!away && !liveState) throw new DispatchError('RUN_NOT_ACTIVE', `Run ${entry.runId} has no live worker`, { status: 409 });
2971
+ const item = { kind: 'follow-up', text: message, origin: 'steer', at, taskId: taskNow(entry.assistantSessionId) || entry.taskId || null };
2972
+ const queued = await queueFollowUp(entry, item);
2973
+ // Checked after the queueing: a turn that ended meanwhile leaves the steer to the turn loop, which takes it from
2974
+ // the outbox like any follow-up.
2975
+ const inFlight = !away && !!liveState.turnOpen && !liveState.waitResolve && !liveState.abortReason && !liveState.dead;
2976
+ if (inFlight) {
2977
+ let settle;
2978
+ const settled = new Promise((done) => { settle = done; });
2979
+ liveState.steer = { text: message, outboxId: queued.id || null, taskId: item.taskId, at, interrupting: true, settled };
2980
+ // A permission or a question the turn waits on is cancelled first (its tool call is refused).
2981
+ for (const requestId of [...liveState.pendingResolvers.keys()]) {
2982
+ finishPending(entry.runId, requestId, { behavior: 'deny', message: 'The user steered this run: this request was cancelled and the change follows.', resolvedBy: 'steer' }, { origin: 'steer' });
2983
+ }
2984
+ try { await liveState.inner?.abort?.('steered'); } catch (error) { log(entry.runId, 'assistant:steer-error', error?.message || String(error)); }
2985
+ settle();
2986
+ }
2987
+ else if (liveState?.waitResolve) liveState.waitResolve({ kind: 'follow-up' });
2988
+ else if (liveState && !liveState.abortReason && !liveState.dead) {
2989
+ // Still starting (no turn open, none awaited): the first turn takes it with the task (runInnerTurn).
2990
+ liveState.earlySteer = { text: message, outboxId: queued.id || null, taskId: item.taskId, at };
2991
+ }
2992
+ entry.notes.push(`steered by ${origin}${inFlight ? ' (turn interrupted)' : ''}`);
2993
+ await emit(entry, 'steered', { runId: entry.runId, text: clip(message, 500), at, interruptedTurn: inFlight, from: origin });
2994
+ if (origin === 'user') emit(entry, 'user_intervened', { text: clip(message, 200) });
2995
+ return { ok: true, target: { kind: 'run', runId: entry.runId }, interruptedTurn: inFlight, followUpId: queued.id || null, run: view(entry) };
2996
+ }
2779
2997
  function handleTurnError(error, liveState, entry, ctx) {
2780
2998
  // Suspended for a server shutdown (suspendForShutdown): the turn the shutdown cut off is resumed on the next start
2781
2999
  // (its in-flight mark stays), and what it spent was settled when it was suspended. Nothing ends here.
@@ -3707,8 +3925,8 @@ export function createAssistantDispatcher({
3707
3925
  // Its browser session went with the server: a new one (the resume prompt names it).
3708
3926
  let browserSessionId = null;
3709
3927
  let browserTabId = null;
3710
- if (entry.usesBrowser && typeof acquireLoopBrowserAndTab === 'function') {
3711
- pinEntryBrowserProfile(entry);
3928
+ pinEntryBrowserProfile(entry);
3929
+ if (entry.usesBrowser && entry.browserRequiredBy !== null && typeof acquireLoopBrowserAndTab === 'function') {
3712
3930
  const acq = await acquireResumeBrowser(entry);
3713
3931
  if (acq?.cancelled) return null;
3714
3932
  if (acq?.error) return await notResumed(entry, `no browser tab: ${acq.error}`);
@@ -3801,7 +4019,7 @@ export function createAssistantDispatcher({
3801
4019
  if (!/EXTENSION_NOT_CONNECTED/.test(String(acq?.error || ''))) return acq;
3802
4020
  if (entry.state !== 'resuming' || closing) return { cancelled: true };
3803
4021
  const left = resumeBrowserDeadline - now();
3804
- if (left <= 0) return { error: `the browser extension did not reconnect within ${Math.round(resumeBrowserWaitMs / 1000)} seconds of the restart` };
4022
+ if (left <= 0) return { ...acq, error: `the browser extension did not reconnect within ${Math.round(resumeBrowserWaitMs / 1000)} seconds of the restart. ${acq.error}` };
3805
4023
  await new Promise((done) => { const timer = setTimeout(done, Math.min(left, resumeBrowserPollMs)); timer.unref?.(); });
3806
4024
  if (entry.state !== 'resuming' || closing) return { cancelled: true };
3807
4025
  }
@@ -3942,7 +4160,9 @@ export function createAssistantDispatcher({
3942
4160
  const entry = requireEntry(runId);
3943
4161
  if (!TERMINAL_STATES.has(entry.state) && finalizations.has(runId)) await finalizations.get(runId);
3944
4162
  const provenance = stampStopProvenance(reason, stopProvenance, iso(now()));
3945
- if (WAITING_STATES.has(entry.state)) {
4163
+ const beforeLaunch = entry.state === 'starting' && !entry.startedAt;
4164
+ if (WAITING_STATES.has(entry.state) || beforeLaunch) {
4165
+ releaseStartupClaim(entry);
3946
4166
  const held = entry.state === 'awaiting_route';
3947
4167
  const index = queue.indexOf(runId);
3948
4168
  if (index !== -1) queue.splice(index, 1);
@@ -3952,6 +4172,7 @@ export function createAssistantDispatcher({
3952
4172
  delete entry.heldAgent;
3953
4173
  if (held) { try { router?.cancelForRun?.(runId, 'run_stopped'); } catch {} }
3954
4174
  emit(entry, 'stopped');
4175
+ if (beforeLaunch && !closing && queue.length) processQueue().catch(() => {});
3955
4176
  return { ok: true, run: view(entry) };
3956
4177
  }
3957
4178
  if (TERMINAL_STATES.has(entry.state)) return { ok: true, run: view(entry), alreadyTerminal: true };
@@ -3970,7 +4191,13 @@ export function createAssistantDispatcher({
3970
4191
  if (entry.state === 'resuming') await endOldProcess(entry);
3971
4192
  }
3972
4193
  const runtime = safeRuntime();
3973
- const stopped = runtime ? await runtime.stop(runId, reason, { stopProvenance: provenance }) : false;
4194
+ // The runtime marks the run stopped before its adapter's abort answers, and a finalize started by that mark
4195
+ // waits for this stop to settle (finalizeRun): what the abort gave up on (abandonedCommands) is then on the run.
4196
+ let stopSettled = () => {};
4197
+ runtimeStops.set(runId, new Promise((resolveStop) => { stopSettled = resolveStop; }));
4198
+ let stopped = false;
4199
+ try { stopped = runtime ? await runtime.stop(runId, reason, { stopProvenance: provenance }) : false; }
4200
+ finally { runtimeStops.delete(runId); stopSettled(); }
3974
4201
  if (!stopped) {
3975
4202
  // Another stop can win while it is disposing the adapter. Keep its action and caller.
3976
4203
  const winner = runtime?.get?.(runId);
@@ -3994,6 +4221,8 @@ export function createAssistantDispatcher({
3994
4221
  // Native runtime notifications do not await subscribers. Keep terminal events
3995
4222
  // admitted through their outbox cancellation before closing the shared store.
3996
4223
  const finalizations = new Map();
4224
+ // runId → a promise settled when this dispatcher's runtime.stop of the run returned (stop).
4225
+ const runtimeStops = new Map();
3997
4226
  function finalize(entry, runtimeRun) {
3998
4227
  if (finalizations.has(entry.runId)) return finalizations.get(entry.runId);
3999
4228
  if (TERMINAL_STATES.has(entry.state)) return Promise.resolve();
@@ -4016,6 +4245,15 @@ export function createAssistantDispatcher({
4016
4245
  }
4017
4246
  async function finalizeRun(entry, runtimeRun) {
4018
4247
  if (TERMINAL_STATES.has(entry.state)) return;
4248
+ // A stop of ours still under way (stop): its abort's answer is on the run once it settled (bounded by the
4249
+ // adapter's own wait for OpenCode).
4250
+ const stopping = runtimeStops.get(entry.runId);
4251
+ if (stopping) {
4252
+ await stopping;
4253
+ if (TERMINAL_STATES.has(entry.state)) return;
4254
+ const latest = safeRuntime()?.get?.(entry.runId);
4255
+ if (Array.isArray(latest?.abandonedCommands) && latest.abandonedCommands.length) runtimeRun = { ...(runtimeRun || {}), abandonedCommands: latest.abandonedCommands };
4256
+ }
4019
4257
  const liveState = live.get(entry.runId);
4020
4258
  // Follow-ups still queued for it (behind a turn, or for its resume after a restart) go with it: its notes say so.
4021
4259
  const cancelled = cancelFollowUps(entry.runId);
@@ -4032,6 +4270,7 @@ export function createAssistantDispatcher({
4032
4270
  // agent_wait reads this entry directly, and a registry flush can happen at any await.
4033
4271
  // Stage a successful completion until its log write returns. Failures can be visible while their cause is judged.
4034
4272
  const completion = terminal.state === 'completed' ? terminal : null;
4273
+ releaseStartupClaim(entry);
4035
4274
  if (!completion) Object.assign(entry, terminal);
4036
4275
  entry.completionReason = entry.completionReason || runtimeRun?.stoppedReason || (status === 'completed' ? 'complete' : status);
4037
4276
  if (runtimeRun?.stopProvenance) entry.stopProvenance = runtimeRun.stopProvenance;
@@ -4055,6 +4294,12 @@ export function createAssistantDispatcher({
4055
4294
  const unsent = await cancelled;
4056
4295
  const undelivered = unsent.length ? `${unsent.length} queued follow-up${unsent.length === 1 ? '' : 's'} not delivered: the run ended first (the first: "${clip(unsent[0].text, 160)}")` : null;
4057
4296
  if (undelivered) entry.notes.push(undelivered);
4297
+ // A command its stop could not end (OpenCode, lib/native-loop-runtime.js _abortAdapter) may still be running: the
4298
+ // result says so, by program name only (a command line can hold a token), and the brain hears it with the stop.
4299
+ const abandoned = Array.isArray(runtimeRun?.abandonedCommands) && runtimeRun.abandonedCommands.length ? abandonedPrograms(runtimeRun.abandonedCommands) : [];
4300
+ const abandonedNote = abandoned.length ? describeAbandoned(abandoned.map((command) => ({ command }))) : null;
4301
+ if (abandonedNote) { entry.abandonedCommands = abandoned; entry.notes.push(abandonedNote); }
4302
+ const endText = [abandonedNote, undelivered].filter(Boolean).join('\n');
4058
4303
  if (entry.state === 'failed' && !budgetStopReason(entry.completionReason) && judge?.workerOutcome && !isEvalRun(entry)) {
4059
4304
  // State, queue and desktop move on now; the 'failed' event waits for its cause.
4060
4305
  const failed = emitFailed(entry, liveState?.evidence || null);
@@ -4063,7 +4308,7 @@ export function createAssistantDispatcher({
4063
4308
  }
4064
4309
  if (entry.state === 'failed' || entry.lastResult?.status === 'blocked') { noteLimit(entry); entry.escalation = computeEscalation(entry, terminal.state); }
4065
4310
  // The end event says which follow-ups never reached the worker (a stop the brain hears of carries it to its mailbox).
4066
- await emit(entry, terminal.state, undelivered ? { text: undelivered } : {}, completion);
4311
+ await emit(entry, terminal.state, endText ? { text: endText } : {}, completion);
4067
4312
  // A memory already stored for the run (by the worker or the brain) is the run's memory.
4068
4313
  // An evaluation run (lib/skills/evals.js) is a measurement, not work to remember: it stores no memory.
4069
4314
  if (memory?.rememberDispatch && !isEvalRun(entry) && !syncMemory(entry, { announce: true }) && (entry.state === 'completed' || (entry.state === 'stopped' && entry.lastResult))) {
@@ -4184,10 +4429,13 @@ export function createAssistantDispatcher({
4184
4429
  if (run.providerThreadId) entry.providerThreadId = run.providerThreadId;
4185
4430
  if (run.antigravityHome) entry.antigravityHome = run.antigravityHome;
4186
4431
  if (newIdentity) persist({ force: true });
4187
- if (message.type === 'sidepanel:run-updated' && message.reason === 'started' && entry.state === 'starting') {
4188
- entry.state = 'running';
4189
- entry.turnState = 'running';
4190
- emit(entry, 'running');
4432
+ if (message.type === 'sidepanel:run-updated' && message.reason === 'started') {
4433
+ pendingSingleClaims.delete(entry);
4434
+ if (entry.state === 'starting') {
4435
+ entry.state = 'running';
4436
+ entry.turnState = 'running';
4437
+ emit(entry, 'running');
4438
+ }
4191
4439
  return;
4192
4440
  }
4193
4441
  if (['sidepanel:run-completed', 'sidepanel:run-failed', 'sidepanel:run-stopped'].includes(message.type) || TERMINAL_STATES.has(run.status)) {
@@ -4204,15 +4452,17 @@ export function createAssistantDispatcher({
4204
4452
  async function processQueue() {
4205
4453
  refreshLimits();
4206
4454
  for (const runId of [...queue]) {
4455
+ const index = queue.indexOf(runId);
4456
+ if (index === -1) continue; // another drain or stop already took it
4207
4457
  const entry = entries.get(runId);
4208
4458
  // A run a restart cut off and a lowered limit held back (resumeOnBoot) waits at the head of the queue.
4209
4459
  const resuming = entry?.state === 'resuming';
4210
- if (!entry || (entry.state !== 'queued' && !resuming)) { queue.splice(queue.indexOf(runId), 1); continue; }
4460
+ if (!entry || (entry.state !== 'queued' && !resuming)) { queue.splice(index, 1); continue; }
4211
4461
  const spec = { provider: entry.provider, accountId: entry.accountId, workflowId: entry.workflowId, usesComputer: !!entry.usesComputer };
4212
4462
  if (railBlock(spec, entry.assistantSessionId, resuming ? { except: runId } : {})) continue;
4213
- queue.splice(queue.indexOf(runId), 1);
4463
+ queue.splice(index, 1);
4214
4464
  if (resuming) { try { await resumeRun(entry); } catch (error) { await notResumed(entry, error?.message || String(error)); } continue; }
4215
- try { await start(entry); emit(entry, 'queue_started'); } catch (error) { entry.notes.push(`queue start failed: ${error?.message || error}`); }
4465
+ try { if (await start(entry)) emit(entry, 'queue_started'); } catch (error) { entry.notes.push(`queue start failed: ${error?.message || error}`); }
4216
4466
  }
4217
4467
  }
4218
4468
  function checkStalled() {
@@ -4410,6 +4660,7 @@ export function createAssistantDispatcher({
4410
4660
  if (entry.state === 'resuming') continue;
4411
4661
  if (ACTIVE_STATES.has(entry.state)) {
4412
4662
  pauseWork(entry);
4663
+ releaseStartupClaim(entry);
4413
4664
  entry.state = 'interrupted'; entry.completionReason = reason; entry.finishedAt = iso(now()); entry.turnState = 'terminal'; entry.pending = [];
4414
4665
  delete entry.rawSpec;
4415
4666
  delete entry.heldAgent;
@@ -4440,11 +4691,18 @@ export function createAssistantDispatcher({
4440
4691
  }
4441
4692
 
4442
4693
  return {
4443
- dispatch, sendTurn, complete, completeClosedTab, stop, killAll, get, peek, teamRuns, activeRouteRuns, hasRunAwaitingOwner, list, totals, wait, transcript, pendingPermissions,
4694
+ dispatch, sendTurn, steerRun, complete, completeClosedTab, stop, killAll, get, peek, teamRuns, activeRouteRuns, hasRunAwaitingOwner, list, totals, wait, transcript, pendingPermissions,
4444
4695
  respondPermission, subscribe, shutdown, limits, suspendForShutdown, drainFinalizations,
4445
4696
  sessionBudget, checkSession, refreshLimits, providerSpend, coverFollowUp, budget,
4446
4697
  resolveRoute, declineRoute, heldRouteRefusal, escalate,
4447
4698
  markDelivered, deliveryState, markEventsDelivered, noteBrowserRoute, noteBrowserProfile,
4699
+ // A worker launched without a tab still has its own route. Keep a closed tab's id so an
4700
+ // extension revocation cannot be mistaken for the first use of this browser.
4701
+ optionalBrowserRoute(runId) {
4702
+ const entry = entries.get(runId);
4703
+ if (!entry?.usesBrowser || entry.browserRequiredBy !== null || !entry.startedAt || !ACTIVE_STATES.has(entry.state)) return null;
4704
+ return { sessionId: entry.browserSessionId, tabId: entry.browserTabId, requestedBrowserSessionId: entry.requestedBrowserSessionId };
4705
+ },
4448
4706
  remove, removeFinished,
4449
4707
  mediaFile,
4450
4708
  scratchReleased(runId, isTask, finishedMs) {