synabun 2.4.0 → 2.4.1

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 (72) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +25 -5
  4. package/browser-extension/engine.js +44 -13
  5. package/browser-extension/manifest.json +2 -2
  6. package/browser-extension/popup-strings.js +10 -4
  7. package/browser-extension/popup-view.js +1 -1
  8. package/browser-extension/popup.css +1 -0
  9. package/browser-extension/popup.html +4 -1
  10. package/browser-extension/popup.js +22 -10
  11. package/browser-extension/protocol.js +11 -5
  12. package/browser-extension/service-worker.js +8 -0
  13. package/docs/browser-extension-bridge.md +2 -2
  14. package/lib/data-home-files.js +45 -0
  15. package/lib/data-home-migration.js +34 -58
  16. package/mcp-server/dist/services/neural-interface.d.ts +1 -0
  17. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  18. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  19. package/mcp-server/dist/tools/agents.d.ts +3 -2
  20. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  21. package/mcp-server/dist/tools/agents.js +9 -7
  22. package/mcp-server/dist/tools/agents.js.map +1 -1
  23. package/mcp-server/package-lock.json +2 -2
  24. package/mcp-server/package.json +1 -1
  25. package/mcp-server/src/services/neural-interface.ts +1 -0
  26. package/mcp-server/src/tools/agents.ts +8 -6
  27. package/neural-interface/i18n/en.json +3 -1
  28. package/neural-interface/i18n/pt-BR.json +3 -1
  29. package/neural-interface/lib/agents/builtins.json +207 -0
  30. package/neural-interface/lib/agents/registry.js +60 -15
  31. package/neural-interface/lib/agents/resolve.js +69 -10
  32. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  33. package/neural-interface/lib/assistant-dispatch.js +127 -24
  34. package/neural-interface/lib/assistant-persona.js +1 -1
  35. package/neural-interface/lib/assistant-router.js +50 -7
  36. package/neural-interface/lib/assistant-runtime.js +9 -1
  37. package/neural-interface/lib/backup-service.js +64 -105
  38. package/neural-interface/lib/browser-extension-adapter.js +24 -15
  39. package/neural-interface/lib/browser-extension-bridge.js +27 -4
  40. package/neural-interface/lib/native-loop-runtime.js +6 -7
  41. package/neural-interface/lib/opencode-build-preflight.js +12 -7
  42. package/neural-interface/lib/peer-identity.js +13 -8
  43. package/neural-interface/lib/session-cache-builder.js +41 -3
  44. package/neural-interface/lib/teams/scheduler.js +2 -2
  45. package/neural-interface/lib/teams/schema.js +1 -1
  46. package/neural-interface/package-lock.json +2 -2
  47. package/neural-interface/package.json +1 -1
  48. package/neural-interface/public/index.html +51 -0
  49. package/neural-interface/public/offline.html +4 -3
  50. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
  51. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
  52. package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
  53. package/neural-interface/public/shared/api.js +2 -1
  54. package/neural-interface/public/shared/assistant/asst-render.js +1 -0
  55. package/neural-interface/public/shared/assistant/asst-route.js +3 -1
  56. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  57. package/neural-interface/public/shared/html-shell.js +1 -0
  58. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  59. package/neural-interface/public/shared/page-session.js +1 -1
  60. package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
  61. package/neural-interface/public/shared/start-bridge.js +2 -2
  62. package/neural-interface/public/shared/styles.css +13 -1
  63. package/neural-interface/public/shared/ui-loading.js +72 -19
  64. package/neural-interface/public/shared/ui-native-loop-router.js +49 -20
  65. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  66. package/neural-interface/public/shared/ui-settings.js +10 -2
  67. package/neural-interface/public/shared/ui-sync.js +1 -0
  68. package/neural-interface/public/sw.js +4 -3
  69. package/neural-interface/public/variant/3d/main.js +13 -4
  70. package/neural-interface/server.js +34 -25
  71. package/npm-shrinkwrap.json +2 -2
  72. package/package.json +2 -1
@@ -209,6 +209,22 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
209
209
  let synabunExpected = false;
210
210
  let stops = 0;
211
211
  let waitingAbort = null;
212
+ let interruptPrompt = null;
213
+ let exited = false;
214
+ const serveExitMessage = 'The isolated OpenCode server stopped during this turn. Send the message again to resume.';
215
+ const serveExitError = () => Object.assign(new Error(serveExitMessage), { code: 'OPENCODE_SERVE_EXITED' });
216
+ const serveExited = () => exited || entry?.proc?.exitCode != null || entry?.proc?.signalCode != null;
217
+ function onServeExit() {
218
+ if (disposed) return;
219
+ exited = true;
220
+ clearInterval(keepAliveTimer);
221
+ waitingAbort?.abort();
222
+ interruptPrompt?.();
223
+ if (!turnActive && !pendingControls.size) return;
224
+ turnActive = false;
225
+ pendingControls.clear();
226
+ emit({ type: 'error', message: serveExitMessage });
227
+ }
212
228
  const mcpWait = {
213
229
  readyTimeoutMs: deps.mcpReadyTimeoutMs, settleMs: deps.mcpSettleMs,
214
230
  listGraceMs: deps.mcpListGraceMs, pollMs: deps.mcpPollMs,
@@ -240,11 +256,14 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
240
256
  const tool = packet.request?.tool_name;
241
257
  if (decision === 'deny') sink.send({ type: 'stderr', text: `Plan mode: declined ${tool || 'permission'}${remoteReadOnly ? ' (read-only)' : ' (no code changes)'}` });
242
258
  Promise.resolve(client.permission.reply({ requestID: body.requestID, reply: body.reply, directory: cwd, ...(decision === 'deny' ? { message: remoteReadOnly ? readOnlyDenyMessage(tool) : planDenyMessage(tool, { host: 'opencode' }) } : {}) }))
243
- .catch((error) => sink.send({ type: 'error', message: `OpenCode auto-${decision === 'allow' ? 'accept' : 'decline'} failed: ${error?.message || error}` }));
259
+ .catch((error) => { if (!serveExited()) emit({ type: 'error', message: `OpenCode auto-${decision === 'allow' ? 'accept' : 'decline'} failed: ${error?.message || error}` }); });
244
260
  return;
245
261
  }
246
262
  if (packet.type === 'control_request') pendingControls.set(packet.request_id, packet);
247
- if (packet.type === 'done' || packet.type === 'aborted') turnActive = false;
263
+ if (packet.type === 'done' || packet.type === 'aborted') {
264
+ turnActive = false;
265
+ pendingControls.clear();
266
+ }
248
267
  sink.send(packet);
249
268
  };
250
269
  sink.send({ type: 'engine', engine: 'opencode', brain: 'opencode' });
@@ -257,7 +276,9 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
257
276
  });
258
277
  if (unsubscribe) { try { unsubscribe(); } catch {} }
259
278
  const source = client?.onEvent ? client : client?.event;
260
- unsubscribe = source?.onEvent?.((envelope) => translator.handle(envelope?.eventType || '', envelope?.event || {})) || null;
279
+ unsubscribe = source?.onEvent?.((envelope) => {
280
+ if (!disposed && !serveExited()) translator.handle(envelope?.eventType || '', envelope?.event || {});
281
+ }) || null;
261
282
  }
262
283
 
263
284
  /** The serve's MCP servers as an `mcp_status` event (the runtime reads whether SynaBun, and so agent_route, is reachable). */
@@ -285,6 +306,7 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
285
306
  // the assistant and plan agents): the brain's serve never reads it.
286
307
  entry = await deps.ensureIsolatedServe(termId, { xdgRoot, keepAlive: true, tools: brain.tools ?? OPENCODE_BRAIN_TOOLS, brainCredential: deps.brainCredential || null, extraEnv: { OPENCODE_CONFIG_DIR: null } });
287
308
  if (!entry?.client) throw new Error('OpenCode isolated serve failed to start');
309
+ entry.proc?.once?.('exit', onServeExit);
288
310
  client = entry.client;
289
311
  await client.waitUntilConnected?.(20_000);
290
312
  if (!sessionId) {
@@ -298,6 +320,7 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
298
320
  keepAliveTimer = setInterval(() => { if (entry) entry.lastUsed = Date.now(); }, 60_000);
299
321
  keepAliveTimer.unref?.();
300
322
  await reportMcpStatus();
323
+ if (serveExited()) throw new Error('The isolated OpenCode server stopped during startup');
301
324
  return true;
302
325
  })();
303
326
  return startPromise;
@@ -305,11 +328,13 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
305
328
 
306
329
  return {
307
330
  kind: 'opencode',
331
+ needsRestart: serveExited,
308
332
  start,
309
333
  async sendUserTurn({ text, images = [], model = null, effort = null, permissionMode: mode = null, planMode: plan = null } = {}) {
310
334
  const stop = stops;
311
335
  await start();
312
336
  if (disposed || stops !== stop) return false;
337
+ if (serveExited()) throw serveExitError();
313
338
  applyModes(mode, plan);
314
339
  turnActive = true;
315
340
  // The runtime passes the effective model/effort on every turn (the record
@@ -344,15 +369,37 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
344
369
  onTimeout: (ms) => sink.send({ type: 'event', event: { type: 'system', subtype: 'status', text: synabunToolsTimeoutText(ms, 'brain') } }),
345
370
  });
346
371
  } finally { if (waitingAbort === controller) waitingAbort = null; }
347
- if (!ready || disposed || stops !== stop) { turnActive = false; return false; }
348
- const response = await client.session.promptAsync(request);
349
- const status = Number(response?.status);
350
- if (Number.isFinite(status) && status >= 400) { turnActive = false; throw new Error(`OpenCode prompt failed (${status})`); }
351
- return true;
372
+ if (disposed || stops !== stop) return false;
373
+ if (serveExited()) throw serveExitError();
374
+ if (!ready) { turnActive = false; return false; }
375
+ // A process exit releases this send even if the client is still waiting for a response.
376
+ const interrupted = new Promise((resolve) => {
377
+ interruptPrompt = () => { controller.abort(); resolve(); };
378
+ });
379
+ try {
380
+ const response = await Promise.race([client.session.promptAsync({ ...request, signal: controller.signal }), interrupted]);
381
+ if (disposed || stops !== stop) return false;
382
+ if (serveExited()) throw serveExitError();
383
+ const status = Number(response?.status);
384
+ if (Number.isFinite(status) && status >= 400) throw new Error(`OpenCode prompt failed (${status})`);
385
+ return true;
386
+ } catch (error) {
387
+ if (disposed || stops !== stop) return false;
388
+ turnActive = false;
389
+ pendingControls.clear();
390
+ throw serveExited() ? serveExitError() : error;
391
+ } finally { interruptPrompt = null; }
392
+ },
393
+ async abort() {
394
+ stops += 1;
395
+ waitingAbort?.abort();
396
+ if (serveExited()) return;
397
+ try { if (client && sessionId) await client.session.abort({ sessionID: sessionId, directory: cwd }); } catch {}
398
+ if (!serveExited()) emit({ type: 'aborted' });
352
399
  },
353
- async abort() { stops += 1; waitingAbort?.abort(); if (client && sessionId) await client.session.abort({ sessionID: sessionId, directory: cwd }).catch(() => {}); emit({ type: 'aborted' }); },
354
400
  async setPermissionMode(mode, { planMode: plan = null } = {}) { applyModes(mode, plan); sink.send({ type: 'mode_changed', mode: approvalMode, planMode }); },
355
401
  respondControl(requestId, response) {
402
+ if (serveExited()) return;
356
403
  const pending = pendingControls.get(String(requestId));
357
404
  if (!pending || !client) { sink.send({ type: 'error', message: `No pending OpenCode request ${requestId}` }); return; }
358
405
  pendingControls.delete(String(requestId));
@@ -360,7 +407,7 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
360
407
  const call = body.kind === 'question'
361
408
  ? (body.reject ? client.question.reject({ requestID: body.requestID, directory: cwd }) : client.question.reply({ requestID: body.requestID, answers: body.answers, directory: cwd }))
362
409
  : client.permission.reply({ requestID: body.requestID, reply: body.reply, directory: cwd });
363
- Promise.resolve(call).catch((error) => sink.send({ type: 'error', message: `OpenCode reply failed: ${error?.message || error}` }));
410
+ Promise.resolve(call).catch((error) => { if (!serveExited()) emit({ type: 'error', message: `OpenCode reply failed: ${error?.message || error}` }); });
364
411
  },
365
412
  // OpenCode compacts the session on the model it runs on.
366
413
  async compact() {
@@ -370,7 +417,7 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
370
417
  },
371
418
  async mcpStatus() { await reportMcpStatus(); },
372
419
  async reconcileUsage(meter) {
373
- if (!client || !sessionId || !meter) return false;
420
+ if (!client || !sessionId || !meter || serveExited()) return false;
374
421
  let failed = false;
375
422
  await meter.reconcile({
376
423
  children: async (id) => {
@@ -402,7 +449,9 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
402
449
  async dispose() {
403
450
  if (disposed) return;
404
451
  disposed = true;
452
+ entry?.proc?.off?.('exit', onServeExit);
405
453
  waitingAbort?.abort();
454
+ interruptPrompt?.();
406
455
  if (keepAliveTimer) clearInterval(keepAliveTimer);
407
456
  if (unsubscribe) { try { unsubscribe(); } catch {} }
408
457
  try { deps.stopIsolatedServe(termId); } catch {}
@@ -55,7 +55,7 @@ import { RemotePolicyError, clampDispatchSpec, getSessionPolicy, readRegisteredP
55
55
  import { validateWorkerReply } from './worker-question.js';
56
56
  import { limitFromText } from '../public/shared/assistant/asst-limit.js';
57
57
  // agents-p1: a dispatch's agent_ref (lib/agents/resolve.js).
58
- import { agentCorrections, agentIntake, carryAgentRun, getAgentResolver, stampAgentRun } from './agents/resolve.js';
58
+ import { agentCorrections, agentIntake, agentPinOf, agentRefOf, routedAgent, carryAgentRun, getAgentResolver, stampAgentRun } from './agents/resolve.js';
59
59
  // Agents P2 (durable agent messaging): run events, typed waits, the follow-up outbox and the transcript on disk.
60
60
  import { createCoordinationService, sharedCoordinationService } from './coordination/service.js';
61
61
  import { createRunWaits } from './assistant-run-wait.js';
@@ -622,6 +622,7 @@ export function createAssistantDispatcher({
622
622
  entry.tools = []; entry.toolsRequested = [];
623
623
  entry.toolListError = { code: error.code, message: error.message, original: row.tools ?? row.mcpProfile };
624
624
  delete entry.mcpProfile; delete entry.rawSpec;
625
+ delete entry.heldAgent;
625
626
  entry.state = 'failed'; entry.completionReason = 'tools_invalid';
626
627
  }
627
628
  // A failure cause being judged when the server went down is never coming.
@@ -739,7 +740,7 @@ export function createAssistantDispatcher({
739
740
  // The brief goes to the worker's prompt; views name it only. The meters' state stays inside, and so does what a
740
741
  // resume after a restart needs (resumeInfo: the CLI's pid, the turn in progress); `resumes` counts them.
741
742
  // agents-p4: a team slice's brief (the TEAM block's content) goes to the worker's prompt; views carry `team` only.
742
- const { rawSpec: _rawSpec, brief: _brief, usageState: _usageState, resumeInfo: _resumeInfo, crashed: _crashed, refusedAtShutdown: _refusedAtShutdown, aliveAt: _aliveAt, teamBrief: _teamBrief, ...rest } = entry;
743
+ const { heldAgent: _heldAgent, rawSpec: _rawSpec, brief: _brief, usageState: _usageState, resumeInfo: _resumeInfo, crashed: _crashed, refusedAtShutdown: _refusedAtShutdown, aliveAt: _aliveAt, teamBrief: _teamBrief, ...rest } = entry;
743
744
  return {
744
745
  ...rest,
745
746
  tools: toolsView({ ...entry, tools: runtimeRun?.tools ?? entry.tools }),
@@ -921,7 +922,7 @@ export function createAssistantDispatcher({
921
922
  }
922
923
 
923
924
  /** `taskClass`: the run's class (its route's, else the spec's); image / video creation needs a model that makes the medium. */
924
- function normalizeSpec(spec = {}, { catalogValue = null, taskClass = null } = {}) {
925
+ function normalizeSpec(spec = {}, { catalogValue = null, taskClass = null, builtin = false } = {}) {
925
926
  const provider = String(spec.provider || '').trim().toLowerCase();
926
927
  if (!NATIVE_PROVIDERS.has(provider)) throw new DispatchError('INVALID_PROVIDER', `provider must be one of ${[...NATIVE_PROVIDERS].join(', ')}`);
927
928
  const task = String(spec.task || '').trim();
@@ -1032,6 +1033,15 @@ export function createAssistantDispatcher({
1032
1033
  }
1033
1034
  // Image / video creation (the router already routed it to a maker; this is the backstop).
1034
1035
  const medium = requiredOutput(taskClass);
1036
+ if (builtin && taskClass === 'computer') {
1037
+ if (!usesComputer) throw new DispatchError('COMPUTER_UNAVAILABLE', 'The bundled desktop operator needs a desktop grant.', { status: 409 });
1038
+ if (designFit(catalogValue, { kind: 'dispatch', provider, model }) !== 'ok') {
1039
+ throw new DispatchError('COMPUTER_NEEDS_VISION', 'The desktop operator needs an available model confirmed to see images.', { status: 409 });
1040
+ }
1041
+ }
1042
+ if (builtin && medium && !catalogValue) {
1043
+ throw new DispatchError('MODEL_CANNOT_GENERATE', `The model catalog is unavailable to confirm ${medium} generation.`, { status: 409 });
1044
+ }
1035
1045
  if (medium && catalogValue) {
1036
1046
  const row = model ? findModel(catalogValue, provider, model)?.row || null : defaultModelRow(catalogValue, provider);
1037
1047
  if (!rowMakes(row, medium)) {
@@ -1504,6 +1514,35 @@ export function createAssistantDispatcher({
1504
1514
  return true;
1505
1515
  }
1506
1516
 
1517
+ function applyRouteAgent(original, input, route, ctx, pinned = null) {
1518
+ // Scope follows the actual worker folder, including team worktrees. Re-read approval
1519
+ // at dispatch: the route may have been proposed before the project or revision was known.
1520
+ const selected = routedAgent(agents, route.taskClass, input.cwd || input.project || PACKAGE_ROOT, route.agentRequest, pinned);
1521
+ if (!selected.resolved) return { input, note: selected.note };
1522
+ const { provider, model, effort, accountId, codexAccountId, claudeAccountId } = input;
1523
+ const spec = selected.resolver.prepare({
1524
+ ...original, provider, model, effort, accountId, codexAccountId, claudeAccountId,
1525
+ taskClass: route.taskClass,
1526
+ }, selected.resolved, { ...ctx, routed: true, classDefault: route.agentRequest ? null : route.taskClass });
1527
+ // An explicit profile was already resolved before routing. A profile inherited from
1528
+ // the role still needs the dispatcher's normal identity check.
1529
+ if (input.moreloginEnvId) {
1530
+ delete spec.moreloginProfile;
1531
+ delete spec.morelogin_profile;
1532
+ Object.assign(spec, { moreloginEnvId: input.moreloginEnvId, moreloginEnvName: input.moreloginEnvName });
1533
+ }
1534
+ return { input: spec, resolved: selected.resolved };
1535
+ }
1536
+
1537
+ function appliedRoute(route, input, note) {
1538
+ const pin = agentPinOf(input);
1539
+ const { agentRef, agentRevision, agentRequest, agentCorrection, ...rest } = route;
1540
+ const requested = agentRefOf(input) || (pin && !pin.classDefault ? pin.requested : agentRequest);
1541
+ return { ...rest, ...(requested ? { agentRequest: requested } : {}),
1542
+ ...(pin ? { agentRef: pin.ref, agentRevision: pin.revision } : {}),
1543
+ corrections: [...(route.corrections || []).filter(c => c.reason !== 'class_agent_unavailable'), ...(note ? [note] : [])] };
1544
+ }
1545
+
1507
1546
  // agents-p4: `team` (lib/teams/brief.js teamBrief) and `runId` are the team scheduler's own (lib/teams/scheduler.js):
1508
1547
  // the slice a run works and the id its claims were taken under. No request body reaches these options.
1509
1548
  async function dispatch(rawSpec = {}, { assistantSessionId = null, origin = 'assistant', brief: carried = null, notes: callerNotes = null, agentOf = null, team = null, runId: givenRunId = null } = {}) {
@@ -1521,7 +1560,9 @@ export function createAssistantDispatcher({
1521
1560
  // agents-p1: the agent the dispatch names (agent_ref) is applied before anything else reads the spec: what the
1522
1561
  // dispatch says itself wins, the definition fills the rest and never widens it (lib/agents/resolve.js). The very
1523
1562
  // same object comes back for a dispatch that names none.
1524
- rawSpec = agentIntake(agents, rawSpec, { assistantSessionId: sessionId, origin, desktop, resolveExternalTools });
1563
+ const original = rawSpec;
1564
+ const agentContext = { assistantSessionId: sessionId, origin, desktop, resolveExternalTools };
1565
+ rawSpec = agentIntake(agents, rawSpec, agentContext);
1525
1566
  // "true" (a string) is computer use too: normalizeSpec reads it so, and so must the gate.
1526
1567
  rawSpec = { ...rawSpec, usesComputer: rawSpec.usesComputer === true || rawSpec.usesComputer === 'true' };
1527
1568
  // The MoreLogin profile it names for the worker's browser tab, as MoreLogin lists it (refused here when it cannot
@@ -1548,14 +1589,6 @@ export function createAssistantDispatcher({
1548
1589
  // Skills owns the runtime selection and its provider-specific workspace. Never bind Assistant routes.
1549
1590
  if (router && !isSkillsRun(rawSpec) && origin !== 'ui' && sessionId) {
1550
1591
  routed = await router.resolveDispatch({ sessionId, spec: rawSpec, origin, team });
1551
- // A hold names an open card, but an answer that was already in flight (it waited on the same
1552
- // catalog read) can decide that card before this continuation runs. Approved for this
1553
- // session: the dispatch is resolved again with that route_id, so the run starts on it as any
1554
- // dispatch with an approved route does (its validation, the remote clamps and claim, the
1555
- // rails). Declined, cancelled or expired: the attachment below fails and it is refused.
1556
- for (let i = 0; i < 2 && routed?.action === 'hold' && routeApprovedFor(routed.routeId, sessionId); i += 1) {
1557
- routed = { ...(await router.resolveDispatch({ sessionId, spec: { ...rawSpec, routeId: routed.routeId }, origin, team })), approvedMeanwhile: true };
1558
- }
1559
1592
  }
1560
1593
  // A remote session's approved route, claimed by resolveDispatch, is used up only by the run it
1561
1594
  // starts: a dispatch refused before its run exists gives the route back, so retrying the route_id
@@ -1564,7 +1597,26 @@ export function createAssistantDispatcher({
1564
1597
  try {
1565
1598
  // An approved route may have moved it to another provider: clamp for that one
1566
1599
  // (a route approved for design brings design's defaults).
1567
- let input = routed?.spec ? clampRemote(withClassDefaults(routed.spec, knownClass(routed.route?.taskClass)), sessionId, remoteNotes) : rawSpec;
1600
+ let input, agentNote, heldAgent;
1601
+ for (let attempt = 0; ; attempt++) {
1602
+ input = routed?.spec || rawSpec;
1603
+ const route = routed?.route;
1604
+ if (knownClass(route?.taskClass) && !agentPinOf(rawSpec) && !agentRefOf(original) && !agentOf) {
1605
+ const selected = applyRouteAgent(original, input, route, agentContext);
1606
+ input = selected.input.moreloginProfile ? await withBrowserProfile(selected.input) : selected.input;
1607
+ agentNote = selected.note;
1608
+ if (routed.action === 'hold') heldAgent = { input: original, resolved: selected.resolved };
1609
+ }
1610
+ // An in-flight approval may finish during routing or a role's asynchronous profile lookup.
1611
+ // Rebind both the model and the role on the approved route before attaching a waiting run.
1612
+ if (routed?.action !== 'hold' || attempt >= 2 || !routeApprovedFor(routed.routeId, sessionId)) break;
1613
+ routed = { ...(await router.resolveDispatch({ sessionId, spec: { ...rawSpec, routeId: routed.routeId }, origin, team })), approvedMeanwhile: true };
1614
+ }
1615
+ const dispatchRoute = routed?.route;
1616
+ const routeClass = knownClass(dispatchRoute?.taskClass);
1617
+ if (routed?.spec || dispatchRoute) input = clampRemote(withClassDefaults(input, routeClass), sessionId, remoteNotes);
1618
+ if (agentNote) remoteNotes.push(agentNote.text);
1619
+ if (dispatchRoute) routed.route = appliedRoute(dispatchRoute, input, agentNote);
1568
1620
  // UI / callers without an Assistant session bypass the router, but may
1569
1621
  // still ask for Auto. A routed concrete account is never picked again here.
1570
1622
  if (!routed?.route && accountUsage && ['codex', 'claude-code'].includes(input.provider)) {
@@ -1582,8 +1634,12 @@ export function createAssistantDispatcher({
1582
1634
  // A route approved for other work cannot carry image / video creation or design, nor the other way round:
1583
1635
  // the class decides the model's capability check, the worker's media block or rules and what is collected.
1584
1636
  const declaredClass = knownClass(rawSpec.taskClass);
1585
- const routeClass = knownClass(routed?.route?.taskClass);
1586
- if (declaredClass && routeClass && runContract(declaredClass) !== runContract(routeClass)) {
1637
+ const pin = agentPinOf(input) || agentOf?.agentPin;
1638
+ const builtin = pin?.source === 'builtin' || !!pin?.classDefault;
1639
+ const classMismatch = builtin && dispatchRoute
1640
+ ? (declaredClass || knownClass(input.taskClass)) !== routeClass
1641
+ : declaredClass && routeClass && runContract(declaredClass) !== runContract(routeClass);
1642
+ if (classMismatch) {
1587
1643
  throw new DispatchError('ROUTE_CLASS_MISMATCH', `Route ${routed.route.routeId || ''} was approved for ${routeClass} work, but this dispatch says task_class "${declaredClass}". Call agent_route with task_class "${declaredClass}" and dispatch with its route_id.`, { status: 409, routeId: routed.route.routeId || null, routeClass, taskClass: declaredClass });
1588
1644
  }
1589
1645
  // The route's spec (a route_id alone can make it a design dispatch, with design's defaults):
@@ -1591,11 +1647,13 @@ export function createAssistantDispatcher({
1591
1647
  if (routed?.spec) refuseBrowserConflict(input);
1592
1648
  // agents-p4: a team's slices start on a route that is approved already; none waits on a card of its own.
1593
1649
  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 });
1594
- if (routed?.action === 'hold') return holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief, remoteNotes });
1650
+ if (routed?.action === 'hold') {
1651
+ return holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief, remoteNotes, agentNote, heldAgent });
1652
+ }
1595
1653
  // The run's class: its route's (the brain may omit task_class with a route_id), else the spec's.
1596
1654
  // Its capability backstop runs in normalizeSpec on the final target, however that was chosen.
1597
1655
  const taskClass = routeClass || knownClass(input.taskClass);
1598
- const spec = normalizeSpec(input, { catalogValue, taskClass });
1656
+ const spec = normalizeSpec(input, { catalogValue, taskClass, builtin });
1599
1657
  const queuedCount = [...entries.values()].filter((e) => e.state === 'queued' && e.assistantSessionId === sessionId).length;
1600
1658
  if (givenRunId && entries.has(String(givenRunId))) throw new DispatchError('RUN_EXISTS', `Run ${givenRunId} exists already.`, { status: 409 }); // agents-p4
1601
1659
  runId = givenRunId ? String(givenRunId) : randomId();
@@ -1622,7 +1680,7 @@ export function createAssistantDispatcher({
1622
1680
  try { budgetCorrections = await fitBudget(entry, { routed: !!routed?.route }); } catch (error) { entries.delete(runId); throw error; }
1623
1681
  entry.taskId = routed?.route?.taskId || taskAtDispatch(sessionId);
1624
1682
  const launched = await launchOrQueue(entry, spec, { queuedCount, strict: true });
1625
- const corrections = [...budgetCorrections, ...agentCorrections(input)]; // agents-p1: what the agent's definition was held to
1683
+ const corrections = [...budgetCorrections, ...(agentNote ? [agentNote] : []), ...agentCorrections(input)]; // agents-p1: what the agent's definition was held to
1626
1684
  const withCorrections = corrections.length ? { ...launched, corrections } : launched;
1627
1685
  // The route's own "decided" event (it had no run attached) still tells the brain to dispatch.
1628
1686
  return routed?.approvedMeanwhile
@@ -1705,7 +1763,7 @@ export function createAssistantDispatcher({
1705
1763
  }
1706
1764
 
1707
1765
  /** Accept a dispatch the router is holding for the user's model choice. */
1708
- function holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief = null, remoteNotes = [] }) {
1766
+ function holdForRoute(input, routed, { sessionId, origin, idempotencyKey, brief = null, remoteNotes = [], agentNote = null, heldAgent = null }) {
1709
1767
  const task = String(input.task || '').trim();
1710
1768
  if (!task) throw new DispatchError('TASK_REQUIRED', 'task is required');
1711
1769
  if (task.length > 20_000) throw new DispatchError('TASK_TOO_LONG', 'task must be at most 20000 characters');
@@ -1725,6 +1783,7 @@ export function createAssistantDispatcher({
1725
1783
  workflowId: input.workflowId ? String(input.workflowId) : null, parentRunId: input.parentRunId ? String(input.parentRunId) : null,
1726
1784
  usesBrowser: !!input.usesBrowser, usesComputer: input.usesComputer === true, capability: normalizeCapability(input.capability || 'full'),
1727
1785
  idempotencyKey, rawSpec: { ...input }, route: routed.route,
1786
+ ...(heldAgent ? { heldAgent } : {}),
1728
1787
  notes: ['awaiting the user\'s model choice on the route card', ...remoteNotes],
1729
1788
  };
1730
1789
  stampAgentRun(entry, input); // agents-p1
@@ -1751,10 +1810,30 @@ export function createAssistantDispatcher({
1751
1810
  emit(entry, 'route_pending', { routeId: routed.routeId });
1752
1811
  return {
1753
1812
  ok: true, queued: true, awaitingRoute: true, routeId: routed.routeId, run: view(entry),
1813
+ ...(agentNote ? { corrections: [agentNote] } : {}),
1754
1814
  next: 'This run is waiting for the user to pick its model on the route card. Do not dispatch it again. It starts automatically after the pick; the decision arrives as a [SynaBun Mailbox] route_decided event. If the user picks "here" instead, this run never starts and that event asks you to do the task yourself.',
1755
1815
  };
1756
1816
  }
1757
1817
 
1818
+ function workerForRoutePick(entry, target, agentRequest) {
1819
+ const runtime = { provider: target.provider, model: target.model || null, effort: target.effort ?? null,
1820
+ accountId: target.accountId || null, codexAccountId: null, claudeAccountId: null };
1821
+ if (!entry.heldAgent) return { input: { ...entry.rawSpec, ...runtime } };
1822
+ // Keep the role pinned while the card is open. The final provider can deliver a different
1823
+ // set of external servers, and the owner can select a proposal with a different agent.
1824
+ const original = entry.heldAgent.input;
1825
+ const sameRole = agentRequest === entry.route?.agentRequest;
1826
+ const route = { ...entry.route, agentRequest };
1827
+ const input = { ...original, ...runtime };
1828
+ if (entry.rawSpec?.moreloginEnvId && (sameRole || original.moreloginProfile || original.morelogin_profile || original.moreloginEnvId || original.morelogin_env_id)) {
1829
+ input.moreloginEnvId = entry.rawSpec.moreloginEnvId;
1830
+ input.moreloginEnvName = entry.rawSpec.moreloginEnvName;
1831
+ }
1832
+ const selected = applyRouteAgent(original, input, route, { assistantSessionId: entry.assistantSessionId,
1833
+ origin: entry.origin, desktop, resolveExternalTools }, sameRole ? entry.heldAgent.resolved : null);
1834
+ return { input: withClassDefaults(selected.input, entry.taskClass), route, note: selected.note };
1835
+ }
1836
+
1758
1837
  /**
1759
1838
  * Why the held run `runId` could not start on `target`, else null: the router's checkHeld, asked
1760
1839
  * before it approves a route card's pick, so a pick resolveRoute would refuse is not approved,
@@ -1762,7 +1841,7 @@ export function createAssistantDispatcher({
1762
1841
  * catalog as it stands: MODEL_CANNOT_SEE, MODEL_UNAVAILABLE) and, for every run, browser
1763
1842
  * settings on that provider (BROWSER_SETTINGS_CONFLICT). Other refusals still come in resolveRoute.
1764
1843
  */
1765
- function heldRouteRefusal(runId, target) {
1844
+ function heldRouteRefusal(runId, target, { agentRequest } = {}) {
1766
1845
  const entry = entries.get(String(runId || ''));
1767
1846
  if (!entry || entry.state !== 'awaiting_route' || !target?.provider) return null;
1768
1847
  const provider = String(target.provider).trim().toLowerCase();
@@ -1771,25 +1850,45 @@ export function createAssistantDispatcher({
1771
1850
  try { catalogValue = catalog?.peek?.() || null; } catch { catalogValue = null; }
1772
1851
  const refusal = designRefusal(catalogValue, provider, model, entry.taskClass || null);
1773
1852
  if (refusal) return refusal;
1853
+ if (entry.heldAgent) {
1854
+ try {
1855
+ const pick = workerForRoutePick(entry, target, agentRequest);
1856
+ const input = clampRemote(pick.input, entry.assistantSessionId);
1857
+ const pin = agentPinOf(input);
1858
+ normalizeSpec(input, { catalogValue, taskClass: entry.taskClass, builtin: pin?.source === 'builtin' || !!pin?.classDefault });
1859
+ return null;
1860
+ } catch (error) { return error; }
1861
+ }
1774
1862
  const conflict = browserSettingsConflict({ ...(entry.rawSpec || {}), provider, model }, provider);
1775
1863
  return conflict ? new DispatchError('BROWSER_SETTINGS_CONFLICT', conflict, { status: 400 }) : null;
1776
1864
  }
1777
1865
 
1778
1866
  /** The user picked a target for a held run: validate, then start or queue it. */
1779
- async function resolveRoute(runId, { target, routeId = null, decidedBy = 'user', remembered = false, optionId = null } = {}) {
1867
+ async function resolveRoute(runId, { target, routeId = null, decidedBy = 'user', remembered = false, optionId = null, agentRequest } = {}) {
1780
1868
  const entry = entries.get(runId);
1781
1869
  if (!entry || entry.state !== 'awaiting_route' || !target?.provider) return { ok: false, code: 'NOT_HELD' };
1782
1870
  const catalogValue = await catalogSnapshot();
1783
- let input = { ...(entry.rawSpec || {}), provider: target.provider, model: target.model || null, effort: target.effort ?? null, accountId: target.accountId || null, codexAccountId: null, claudeAccountId: null };
1784
1871
  let spec;
1785
- // The picked provider may need another clamp (Codex under strict worker approvals), or the level fell meanwhile.
1786
1872
  const remoteNotes = [];
1787
- try { input = clampRemote(input, entry.assistantSessionId, remoteNotes); spec = normalizeSpec(input, { catalogValue, taskClass: entry.taskClass || null }); }
1873
+ try {
1874
+ const pick = workerForRoutePick(entry, target, agentRequest);
1875
+ let input = pick.input.moreloginProfile || pick.input.morelogin_profile ? await withBrowserProfile(pick.input) : pick.input;
1876
+ input = clampRemote(input, entry.assistantSessionId, remoteNotes);
1877
+ const pin = entry.heldAgent ? agentPinOf(input) : entry.agentPin;
1878
+ spec = normalizeSpec(input, { catalogValue, taskClass: entry.taskClass || null, builtin: pin?.source === 'builtin' || !!pin?.classDefault });
1879
+ if (pick.route) {
1880
+ if (entry.agentRef && !pin) Object.assign(entry, { agentRef: null, agentRevision: null, agentPin: null });
1881
+ stampAgentRun(entry, input);
1882
+ entry.route = appliedRoute(pick.route, input, pick.note);
1883
+ if (pick.note) remoteNotes.push(pick.note.text);
1884
+ }
1885
+ }
1788
1886
  catch (error) {
1789
1887
  entry.state = 'failed'; entry.completionReason = 'route_invalid'; entry.finishedAt = iso(now()); entry.turnState = 'terminal';
1790
1888
  entry.error = error?.message || String(error);
1791
1889
  entry.notes.push(`route target rejected: ${entry.error}`);
1792
1890
  delete entry.rawSpec;
1891
+ delete entry.heldAgent;
1793
1892
  emit(entry, 'failed');
1794
1893
  return { ok: false, error };
1795
1894
  }
@@ -1800,6 +1899,7 @@ export function createAssistantDispatcher({
1800
1899
  target: describeTarget(target, { catalog: catalogValue }), decidedAt: iso(now()),
1801
1900
  };
1802
1901
  delete entry.rawSpec;
1902
+ delete entry.heldAgent;
1803
1903
  entry.state = 'queued';
1804
1904
  emit(entry, 'route_decided', { routeId });
1805
1905
  try { return await launchOrQueue(entry, spec); }
@@ -1815,6 +1915,7 @@ export function createAssistantDispatcher({
1815
1915
  entry.route = { ...(entry.route || {}), status, decidedBy: reason === 'route_expired' ? 'timeout' : 'user', decidedAt: iso(now()) };
1816
1916
  if (reason === 'route_here') entry.notes.push('the user chose to do this task here, in the conversation: this worker was not started');
1817
1917
  delete entry.rawSpec;
1918
+ delete entry.heldAgent;
1818
1919
  emit(entry, 'stopped');
1819
1920
  return true;
1820
1921
  }
@@ -3747,6 +3848,7 @@ export function createAssistantDispatcher({
3747
3848
  if (index !== -1) queue.splice(index, 1);
3748
3849
  entry.state = 'stopped'; entry.completionReason = reason; entry.finishedAt = iso(now()); entry.turnState = 'terminal';
3749
3850
  delete entry.rawSpec;
3851
+ delete entry.heldAgent;
3750
3852
  if (held) { try { router?.cancelForRun?.(runId, 'run_stopped'); } catch {} }
3751
3853
  emit(entry, 'stopped');
3752
3854
  return { ok: true, run: view(entry) };
@@ -4156,6 +4258,7 @@ export function createAssistantDispatcher({
4156
4258
  pauseWork(entry);
4157
4259
  entry.state = 'interrupted'; entry.completionReason = reason; entry.finishedAt = iso(now()); entry.turnState = 'terminal'; entry.pending = [];
4158
4260
  delete entry.rawSpec;
4261
+ delete entry.heldAgent;
4159
4262
  // What the run's meter can still read is booked now; nothing provisional outlives the process.
4160
4263
  try { finishUsage(entry, live.get(entry.runId) || null); } catch {}
4161
4264
  releaseDesktop(entry);
@@ -207,7 +207,7 @@ export function followupsPersonaLines(askTool = 'AskUserQuestion') {
207
207
  * agent_route and agent_dispatch. One line of "Delegating to workers"; the tool descriptions carry the detail.
208
208
  */
209
209
  export function agentsPersonaLine(t = toolNames()) {
210
- return `11. Agents: ${t.catalog} lists the agents the owner approved (\`agents\`: ref, what each is for, what it runs on). To give a task to one, name it with agent_ref on the ${t.route} proposal (add cwd for a project's own agent), then on ${t.dispatch} with the approved route_id: its definition fills what you leave out and its instructions become the worker's role; what you pass yourself wins, and corrections say what the definition was held to. Only the owner approves an agent: on AGENT_NOT_APPROVED tell the user it waits for their approval. agent_ref is not \`agent\`, which is OpenCode's own agent (build | plan).`;
210
+ return `11. Agents: ${t.catalog} lists the agents the owner approved (\`agents\`). Routed workers inherit their task class agent. Set agent_ref on a ${t.route} proposal to choose another (cwd selects the project library). ${t.dispatch} inherits it with route_id; agent_ref overrides it and "none" opts out. The route sets provider, model, effort and account. The agent supplies instructions, tools and limits. On AGENT_NOT_APPROVED ask the owner to review it in Agents. OpenCode's own agent uses the separate agent field.`;
211
211
  }
212
212
 
213
213
  // ════ agents-p4 BEGIN: Agent density and teams ════