synabun 2.4.2 → 2.4.3

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 (103) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +23 -3
  4. package/lib/release-npm-ci.mjs +23 -1
  5. package/mcp-server/dist/services/neural-interface.js +1 -1
  6. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  7. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
  8. package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
  9. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
  10. package/mcp-server/package-lock.json +5 -5
  11. package/mcp-server/package.json +1 -1
  12. package/mcp-server/src/services/neural-interface.ts +1 -1
  13. package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
  14. package/neural-interface/i18n/en.json +50 -1
  15. package/neural-interface/i18n/pt-BR.json +57 -8
  16. package/neural-interface/lib/assistant-api.js +33 -0
  17. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  18. package/neural-interface/lib/assistant-dispatch.js +26 -2
  19. package/neural-interface/lib/assistant-envelope.js +40 -0
  20. package/neural-interface/lib/assistant-runtime.js +95 -10
  21. package/neural-interface/lib/browser-extension-adapter.js +1 -3
  22. package/neural-interface/lib/browser-extension-archive.js +149 -0
  23. package/neural-interface/lib/browser-extension-bridge.js +7 -4
  24. package/neural-interface/lib/browser-extension-folder.js +596 -76
  25. package/neural-interface/lib/browser-extension-package.js +200 -0
  26. package/neural-interface/lib/browser-extension-pin.js +84 -0
  27. package/neural-interface/lib/browser-extension-pin.json +33 -0
  28. package/neural-interface/lib/browser-extension-setup.js +105 -18
  29. package/neural-interface/lib/cli-install.js +23 -3
  30. package/neural-interface/lib/cli-update-planner.js +67 -4
  31. package/neural-interface/lib/native-loop-providers.js +10 -1
  32. package/neural-interface/lib/native-loop-runtime.js +20 -2
  33. package/neural-interface/lib/opencode-shell-read.js +107 -0
  34. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  35. package/neural-interface/lib/opencode-turn-release.js +173 -0
  36. package/neural-interface/lib/opencode-v2-client.js +4 -1
  37. package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
  38. package/neural-interface/lib/opencode2-client.js +341 -6
  39. package/neural-interface/lib/opencode2-translate.js +161 -4
  40. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  41. package/neural-interface/lib/whatsapp/bridge.js +52 -6
  42. package/neural-interface/package-lock.json +5 -5
  43. package/neural-interface/package.json +1 -1
  44. package/neural-interface/public/extension-setup.html +5 -2
  45. package/neural-interface/public/shared/agy/agy-panel.js +38 -10
  46. package/neural-interface/public/shared/assistant/asst-api.js +25 -0
  47. package/neural-interface/public/shared/assistant/asst-panel.js +69 -1
  48. package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
  49. package/neural-interface/public/shared/assistant/asst-render.js +138 -6
  50. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  51. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  52. package/neural-interface/public/shared/assistant/asst-styles.js +1 -0
  53. package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
  54. package/neural-interface/public/shared/extension-setup/es-page.js +10 -4
  55. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  56. package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
  57. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  58. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  59. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
  60. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  61. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
  62. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
  63. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
  64. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  65. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +346 -0
  66. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  67. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  68. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
  69. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  70. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  71. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  72. package/neural-interface/public/shared/settings/settings-browser-extension.js +54 -12
  73. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  74. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  75. package/neural-interface/public/shared/tray-auto-close.js +36 -6
  76. package/neural-interface/public/shared/ui-claude-panel.js +20 -0
  77. package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
  78. package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
  79. package/neural-interface/server.js +249 -35
  80. package/npm-shrinkwrap.json +5 -5
  81. package/package.json +1 -2
  82. package/browser-extension/content.js +0 -231
  83. package/browser-extension/engine.js +0 -658
  84. package/browser-extension/icons/icon-128.png +0 -0
  85. package/browser-extension/icons/icon-16.png +0 -0
  86. package/browser-extension/icons/icon-32.png +0 -0
  87. package/browser-extension/icons/icon-48.png +0 -0
  88. package/browser-extension/icons/status-off-16.png +0 -0
  89. package/browser-extension/icons/status-off-32.png +0 -0
  90. package/browser-extension/icons/status-off-48.png +0 -0
  91. package/browser-extension/icons/status-on-16.png +0 -0
  92. package/browser-extension/icons/status-on-32.png +0 -0
  93. package/browser-extension/icons/status-on-48.png +0 -0
  94. package/browser-extension/manifest.json +0 -58
  95. package/browser-extension/popup-strings.js +0 -250
  96. package/browser-extension/popup-view.js +0 -151
  97. package/browser-extension/popup.css +0 -166
  98. package/browser-extension/popup.html +0 -108
  99. package/browser-extension/popup.js +0 -359
  100. package/browser-extension/service-worker.js +0 -283
  101. package/browser-extension/setup-content.js +0 -36
  102. package/browser-extension/tokens.css +0 -326
  103. /package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +0 -0
@@ -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.
@@ -3970,7 +3971,13 @@ export function createAssistantDispatcher({
3970
3971
  if (entry.state === 'resuming') await endOldProcess(entry);
3971
3972
  }
3972
3973
  const runtime = safeRuntime();
3973
- const stopped = runtime ? await runtime.stop(runId, reason, { stopProvenance: provenance }) : false;
3974
+ // The runtime marks the run stopped before its adapter's abort answers, and a finalize started by that mark
3975
+ // waits for this stop to settle (finalizeRun): what the abort gave up on (abandonedCommands) is then on the run.
3976
+ let stopSettled = () => {};
3977
+ runtimeStops.set(runId, new Promise((resolveStop) => { stopSettled = resolveStop; }));
3978
+ let stopped = false;
3979
+ try { stopped = runtime ? await runtime.stop(runId, reason, { stopProvenance: provenance }) : false; }
3980
+ finally { runtimeStops.delete(runId); stopSettled(); }
3974
3981
  if (!stopped) {
3975
3982
  // Another stop can win while it is disposing the adapter. Keep its action and caller.
3976
3983
  const winner = runtime?.get?.(runId);
@@ -3994,6 +4001,8 @@ export function createAssistantDispatcher({
3994
4001
  // Native runtime notifications do not await subscribers. Keep terminal events
3995
4002
  // admitted through their outbox cancellation before closing the shared store.
3996
4003
  const finalizations = new Map();
4004
+ // runId → a promise settled when this dispatcher's runtime.stop of the run returned (stop).
4005
+ const runtimeStops = new Map();
3997
4006
  function finalize(entry, runtimeRun) {
3998
4007
  if (finalizations.has(entry.runId)) return finalizations.get(entry.runId);
3999
4008
  if (TERMINAL_STATES.has(entry.state)) return Promise.resolve();
@@ -4016,6 +4025,15 @@ export function createAssistantDispatcher({
4016
4025
  }
4017
4026
  async function finalizeRun(entry, runtimeRun) {
4018
4027
  if (TERMINAL_STATES.has(entry.state)) return;
4028
+ // A stop of ours still under way (stop): its abort's answer is on the run once it settled (bounded by the
4029
+ // adapter's own wait for OpenCode).
4030
+ const stopping = runtimeStops.get(entry.runId);
4031
+ if (stopping) {
4032
+ await stopping;
4033
+ if (TERMINAL_STATES.has(entry.state)) return;
4034
+ const latest = safeRuntime()?.get?.(entry.runId);
4035
+ if (Array.isArray(latest?.abandonedCommands) && latest.abandonedCommands.length) runtimeRun = { ...(runtimeRun || {}), abandonedCommands: latest.abandonedCommands };
4036
+ }
4019
4037
  const liveState = live.get(entry.runId);
4020
4038
  // Follow-ups still queued for it (behind a turn, or for its resume after a restart) go with it: its notes say so.
4021
4039
  const cancelled = cancelFollowUps(entry.runId);
@@ -4055,6 +4073,12 @@ export function createAssistantDispatcher({
4055
4073
  const unsent = await cancelled;
4056
4074
  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
4075
  if (undelivered) entry.notes.push(undelivered);
4076
+ // A command its stop could not end (OpenCode, lib/native-loop-runtime.js _abortAdapter) may still be running: the
4077
+ // result says so, by program name only (a command line can hold a token), and the brain hears it with the stop.
4078
+ const abandoned = Array.isArray(runtimeRun?.abandonedCommands) && runtimeRun.abandonedCommands.length ? abandonedPrograms(runtimeRun.abandonedCommands) : [];
4079
+ const abandonedNote = abandoned.length ? describeAbandoned(abandoned.map((command) => ({ command }))) : null;
4080
+ if (abandonedNote) { entry.abandonedCommands = abandoned; entry.notes.push(abandonedNote); }
4081
+ const endText = [abandonedNote, undelivered].filter(Boolean).join('\n');
4058
4082
  if (entry.state === 'failed' && !budgetStopReason(entry.completionReason) && judge?.workerOutcome && !isEvalRun(entry)) {
4059
4083
  // State, queue and desktop move on now; the 'failed' event waits for its cause.
4060
4084
  const failed = emitFailed(entry, liveState?.evidence || null);
@@ -4063,7 +4087,7 @@ export function createAssistantDispatcher({
4063
4087
  }
4064
4088
  if (entry.state === 'failed' || entry.lastResult?.status === 'blocked') { noteLimit(entry); entry.escalation = computeEscalation(entry, terminal.state); }
4065
4089
  // 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);
4090
+ await emit(entry, terminal.state, endText ? { text: endText } : {}, completion);
4067
4091
  // A memory already stored for the run (by the worker or the brain) is the run's memory.
4068
4092
  // An evaluation run (lib/skills/evals.js) is a measurement, not work to remember: it stores no memory.
4069
4093
  if (memory?.rememberDispatch && !isEvalRun(entry) && !syncMemory(entry, { announce: true }) && (entry.state === 'completed' || (entry.state === 'stopped' && entry.lastResult))) {
@@ -442,6 +442,28 @@ export function opencodeControlResponse(pending, response = {}) {
442
442
  return { kind: 'permission', requestID: native.requestID, reply: allow ? (response.always ? 'always' : 'once') : 'reject' };
443
443
  }
444
444
 
445
+ /**
446
+ * A shell command of an OpenCode tool call as the Assistant panel shows it: which call it belongs to (`callID` is
447
+ * the tool_use id of that call in the envelope), whether it runs, how it ended. Never what it printed: that is
448
+ * read apart, in pages, by the panel that shows it. null for anything without an id.
449
+ */
450
+ export function opencodeShellView(shell) {
451
+ if (!shell || typeof shell !== 'object' || typeof shell.id !== 'string' || !shell.id) return null;
452
+ const time = shell.time && typeof shell.time === 'object' ? shell.time : {};
453
+ const started = Number(time.started) || 0;
454
+ const ended = Number(time.ended) || 0;
455
+ return {
456
+ id: shell.id,
457
+ callID: typeof shell.callID === 'string' ? shell.callID : '',
458
+ command: clip(typeof shell.command === 'string' ? shell.command : '', 4000),
459
+ status: typeof shell.status === 'string' && shell.status ? shell.status : 'running',
460
+ background: shell.background === true,
461
+ waited: shell.waited === true,
462
+ ...(typeof shell.exit === 'number' ? { exit: shell.exit } : {}),
463
+ time: ended ? { started, ended } : { started },
464
+ };
465
+ }
466
+
445
467
  /**
446
468
  * Stateful translator for one OpenCode brain session: SSE events → envelope.
447
469
  * Only events for `sessionId` are considered.
@@ -543,10 +565,22 @@ export function createOpenCodeEnvelopeTranslator({ sessionId, emit, onTurnEnd =
543
565
  }
544
566
  return {
545
567
  state,
568
+ /** A turn of the brain's own starts: a stop told before it is over. */
569
+ noteTurnStart() { state.stopTold = false; },
546
570
  handle(eventType, ev = {}) {
547
571
  // Metering only (child sessions too, before the filter): a throw here must not drop the event.
548
572
  if (/^(?:message|session)[.:](?:updated|created)$/i.test(eventType)) { try { onUsageEvent(eventType, ev); } catch {} }
549
573
  if (!belongs(ev)) return false;
574
+ // A tool call's shell command started, went on after its call ("in the background") or ended
575
+ // (lib/opencode2-translate.js). It is what the panel shows next to the call, never an event of the
576
+ // conversation: a packet of its own, which the runtime sends to the open panels and keeps nowhere.
577
+ if (/^shell[.:]updated$/i.test(eventType)) {
578
+ // Named by its session or not at all: a command is never taken for this conversation's by default.
579
+ if (ev.sessionID !== sessionId) return false;
580
+ const shell = opencodeShellView(ev.shell);
581
+ if (shell) emit({ type: 'assistant:shell', shell });
582
+ return !!shell;
583
+ }
550
584
  if (!state.announcedInit) { state.announcedInit = true; event(synthesizeInit({ brain: 'opencode', sessionId, cwd: brain.cwd || null, model: brain.model || null })); }
551
585
  if (/^message[.:]updated$/i.test(eventType)) {
552
586
  const info = ev.info || ev.message?.info || {};
@@ -585,6 +619,12 @@ export function createOpenCodeEnvelopeTranslator({ sessionId, emit, onTurnEnd =
585
619
  }
586
620
  if (/^session[.:]error$/i.test(eventType)) {
587
621
  const message = ev.error?.message || ev.error?.data?.message || (typeof ev.error === 'string' ? ev.error : 'OpenCode session error');
622
+ // A Stop while a command ran in the background ends the turn at once; OpenCode then starts the session to
623
+ // report the removed command, and that execution is interrupted too. It is the same Stop: nothing more is
624
+ // said, and the idle that follows it ends nothing (the next turn's own start clears this).
625
+ const stopped = ev.error?.name === 'MessageAbortedError';
626
+ if (stopped && state.stopTold) { state.errored = true; return true; }
627
+ state.stopTold = stopped;
588
628
  flushHeld();
589
629
  if (state.started) event(messageStop());
590
630
  state.errored = true;
@@ -45,6 +45,7 @@ import { browserPolicyRoots } from './browser-policy-roots.js';
45
45
  import { stripFollowups } from '../public/shared/assistant/asst-followups.js';
46
46
  import { readJsonStrict } from './rulesets/fs-safe.js';
47
47
  import { redactTerminalSecrets } from './terminal-token-redaction.js';
48
+ import { readSafeShellOutputPage } from './opencode-shell-read.js';
48
49
 
49
50
  export const BRAIN_PROVIDERS = new Set(['claude-code', 'codex', 'opencode', 'antigravity']);
50
51
  // Every tab is called SynaBun; the session title (the history list) comes from
@@ -1203,6 +1204,52 @@ export function createAssistantRuntime({
1203
1204
  const raw = JSON.stringify({ type: 'assistant:limit', sessionId: live.record.id, limit: live.limit });
1204
1205
  for (const ws of sockets) { if (ws.readyState === 1) { try { ws.send(raw); } catch {} } }
1205
1206
  }
1207
+ /**
1208
+ * The shell commands of the brain's tool calls (an OpenCode brain: assistant-brains/opencode.js `shells`) are a
1209
+ * view as well: which command belongs to which call, whether it runs, how it ended. A change goes to the open
1210
+ * sockets, the whole list to a socket when it attaches and to all of them when the brain is gone (an empty one).
1211
+ * Never buffered, replayed, journaled or shown to the packet observers, and what a command printed is in none
1212
+ * of it: a panel reads that in pages (shellOutput), so nothing of it reaches the model, the transcript, a memory
1213
+ * or a meter.
1214
+ */
1215
+ function brainShells(live) {
1216
+ try { const list = live.brain?.shells?.(); return Array.isArray(list) ? list : []; } catch { return []; }
1217
+ }
1218
+ function sendShell(live, shell) {
1219
+ if (!shell?.id) return;
1220
+ const raw = JSON.stringify({ type: 'assistant:shell', sessionId: live.record.id, shell });
1221
+ for (const ws of live.sockets) { if (ws.readyState === 1) { try { ws.send(raw); } catch {} } }
1222
+ }
1223
+ function sendShells(live, sockets = live.sockets) {
1224
+ const raw = JSON.stringify({ type: 'assistant:shells', sessionId: live.record.id, shells: redactTerminalSecrets(brainShells(live)) });
1225
+ for (const ws of sockets) { if (ws.readyState === 1) { try { ws.send(raw); } catch {} } }
1226
+ }
1227
+ /** The session's shell commands as its brain knows them now; null for an unknown session. */
1228
+ function shellList(sessionId) {
1229
+ const live = sessions.get(String(sessionId || ''));
1230
+ return live ? redactTerminalSecrets(brainShells(live)) : null;
1231
+ }
1232
+ /**
1233
+ * A page of what one of the session's commands printed, for the owner's panel (GET
1234
+ * /api/assistant/sessions/:id/shells/:shellId/output). The session's own brain reads it, and only for a command
1235
+ * it ran: another conversation's command is not readable through this one. What comes back is scrubbed of
1236
+ * SynaBun's run secrets like everything a brain says. → { status, data } or { ok: false, status, error }.
1237
+ */
1238
+ async function shellOutput(sessionId, { shellId, cursor, tail, limit } = {}) {
1239
+ const live = sessions.get(String(sessionId || ''));
1240
+ if (!live) return { ok: false, status: 404, code: 'SESSION_NOT_FOUND', error: `Unknown assistant session ${sessionId}` };
1241
+ const brain = live.brain;
1242
+ if (typeof brain?.shellOutput !== 'function') return { ok: false, status: 404, code: 'SHELL_OUTPUT_GONE', error: 'The output of that command is no longer available.' };
1243
+ // Scrubbed on the whole window around the page (opencode-shell-read.js readSafeShellOutputPage): matched on the
1244
+ // complete read plus what lies on both sides first, cut after, so a secret at a page boundary, or one followed by
1245
+ // what looks like the start of another, never leaves in pieces. Every read the brain does is a raw page.
1246
+ const running = brainShells(live).some((shell) => shell.id === shellId && shell.status === 'running');
1247
+ const page = await readSafeShellOutputPage((q) => brain.shellOutput({ shellId, cursor: q.cursor, limit: q.limit }), { cursor, tail, limit, running });
1248
+ if (!page || page.ok === false || !(Number(page.status) < 400)) {
1249
+ return { ok: false, status: Number(page?.status) >= 400 ? Number(page.status) : 502, code: Number(page?.status) === 404 ? 'SHELL_OUTPUT_GONE' : 'SHELL_OUTPUT_FAILED', error: page?.error || 'The output could not be read.' };
1250
+ }
1251
+ return { status: 200, data: page.data };
1252
+ }
1206
1253
  /** `next`: a limitNotice() value. True when the session's notice changed (and the sockets heard). */
1207
1254
  function setLimit(live, next, { remember = true } = {}) {
1208
1255
  if (next === undefined) return false;
@@ -1411,6 +1458,10 @@ export function createAssistantRuntime({
1411
1458
  // launch credential or a worker's terminal token an agent printed (lib/terminal-token-redaction.js).
1412
1459
  packet = redactTerminalSecrets(packet);
1413
1460
  const id = live.record.id;
1461
+ // A shell command of the brain's tool call changed (OpenCode): a view for the panels that are open, nothing else.
1462
+ if (packet.type === 'assistant:shell') { sendShell(live, packet.shell); return; }
1463
+ // The brain's list was replaced (another provider conversation): every open panel gets the list it has now.
1464
+ if (packet.type === 'assistant:shells') { sendShells(live); return; }
1414
1465
  if (packet.type === 'event') {
1415
1466
  const event = packet.event || {};
1416
1467
  // The usage limit comes with every response: the session keeps its state and says so when
@@ -1524,6 +1575,8 @@ export function createAssistantRuntime({
1524
1575
  else settleClaudeEstimate(live, 'interrupted');
1525
1576
  }
1526
1577
  live.running = false;
1578
+ // A new turn counts its own failed Stops (stopTurn: "Stop anyway" from the second one on).
1579
+ live.stopFailures = 0;
1527
1580
  // A remote session's computer use ends with its turn (the approval and the live grant); a
1528
1581
  // prompt the CLI still holds starts its own turn, unapproved.
1529
1582
  endComputerTurn(live, packet.type === 'aborted' ? 'stopped' : 'turn_ended');
@@ -2322,6 +2375,8 @@ export function createAssistantRuntime({
2322
2375
  live.pendingControls.clear();
2323
2376
  clearControlTimers(live);
2324
2377
  try { await brain.dispose?.(); } catch (error) { log('assistant:brain-dispose-error', error?.message || String(error)); }
2378
+ // Its commands ended with its serve: the open panels stop following them (the next brain has none yet).
2379
+ if (!live.brain) sendShells(live);
2325
2380
  // The next brain reports its own routing reach, and its own OpenCode serve says hello again.
2326
2381
  live.gatePluginAt = null;
2327
2382
  live.gate?.setUnavailable(null);
@@ -3460,17 +3515,42 @@ export function createAssistantRuntime({
3460
3515
  * included), and closes the plan card (late answers are refused), which
3461
3516
  * releases its hold: the mailbox goes on. The in-turn route cards close.
3462
3517
  */
3463
- async function stopTurn(id, { origin = 'api' } = {}) {
3518
+ async function stopTurn(id, { origin = 'api', force: forced = false, forceAfterFailures = 0 } = {}) {
3464
3519
  const live = sessions.get(String(id || ''));
3465
3520
  if (!live) return { ok: false, code: 'SESSION_NOT_FOUND', message: `Unknown assistant session ${id}` };
3466
- newGeneration(live, 'stopped');
3467
- // A remote session: computer use stops with the turn, before the brain is even asked to (its
3468
- // approval, its open request, the live grant; an action in progress is aborted).
3469
- endComputerTurn(live, 'stopped');
3470
- try { router?.cancelForSession?.(live.record.id, 'aborted', { origins: BRAIN_CARD_ORIGINS }); } catch {}
3471
- if (origin !== 'ui') log('assistant:stop', `${live.record.id}: turn stopped from ${origin}`);
3472
- try { await live.brain?.abort?.(); } catch (error) { return { ok: false, code: 'STOP_FAILED', message: error?.message || String(error) }; }
3473
- return { ok: true };
3521
+ // `forceAfterFailures` (WhatsApp's /stop, which has no "Stop anyway" button): this Stop is a Stop anyway once
3522
+ // that many Stops of THIS turn failed (live.stopFailures is reset when a turn ends), never because of an earlier turn.
3523
+ const force = forced === true || (Number(forceAfterFailures) > 0 && (live.stopFailures || 0) >= Number(forceAfterFailures));
3524
+ // A Stop the brain may fail (an OpenCode command in the background to end) tears the turn down only once it
3525
+ // worked: a failed one leaves the turn, its queue and its cards as they were (the command still runs).
3526
+ const mayFail = !force && live.brain?.stopMayFail?.() === true;
3527
+ const tearDown = () => {
3528
+ newGeneration(live, 'stopped');
3529
+ // A remote session: computer use stops with the turn, before the brain is even asked to (its
3530
+ // approval, its open request, the live grant; an action in progress is aborted).
3531
+ endComputerTurn(live, 'stopped');
3532
+ try { router?.cancelForSession?.(live.record.id, 'aborted', { origins: BRAIN_CARD_ORIGINS }); } catch {}
3533
+ };
3534
+ if (!mayFail) tearDown();
3535
+ if (origin !== 'ui') log('assistant:stop', `${live.record.id}: turn stopped from ${origin}${force ? ' (stop anyway)' : ''}`);
3536
+ let stopped = null;
3537
+ try { stopped = await live.brain?.abort?.(force ? { force: true } : undefined); } catch (error) {
3538
+ const message = error?.message || String(error);
3539
+ if (error?.code !== 'SHELL_STOP_FAILED') return { ok: false, code: 'STOP_FAILED', message };
3540
+ // The turn goes on: every panel of the session hears which command still runs and why, and from the second
3541
+ // failure of this turn on it offers "Stop anyway" (abort with `force`).
3542
+ const failures = (live.stopFailures || 0) + 1;
3543
+ live.stopFailures = failures;
3544
+ const shells = Array.isArray(error.shells) ? error.shells.map((shell) => ({ id: String(shell?.id || ''), command: String(shell?.command || ''), reason: String(shell?.reason || '') })) : [];
3545
+ const packet = { type: 'stop_failed', code: 'SHELL_STOP_FAILED', message, shells, failures, canForce: failures >= 2 };
3546
+ sendToSockets(live, packet);
3547
+ return { ok: false, code: 'STOP_FAILED', message, shells, failures, canForce: failures >= 2 };
3548
+ }
3549
+ if (mayFail) tearDown();
3550
+ live.stopFailures = 0;
3551
+ const abandoned = Array.isArray(stopped?.abandoned) ? stopped.abandoned.map((shell) => ({ id: String(shell?.id || ''), command: String(shell?.command || '') })) : [];
3552
+ if (abandoned.length) sendToSockets(live, { type: 'stop_abandoned', shells: abandoned });
3553
+ return { ok: true, ...(abandoned.length ? { abandoned } : {}) };
3474
3554
  }
3475
3555
  function controlResolved(live, requestId, origin) {
3476
3556
  sendToSockets(live, { type: 'control_resolved', request_id: requestId, origin: String(origin || 'ui') });
@@ -3655,6 +3735,8 @@ export function createAssistantRuntime({
3655
3735
  try { const budgetNow = sessionMoney(live.record.id); if (budgetNow) ws.send(JSON.stringify({ type: 'assistant:budget', sessionId: live.record.id, reason: 'attached', budget: budgetNow })); } catch {}
3656
3736
  // The limit notice as it is now (null clears one this panel still shows from before).
3657
3737
  sendLimit(live, [ws]);
3738
+ // The shell commands of the brain's tool calls as they are now (an empty list ends what this panel still follows).
3739
+ sendShells(live, [ws]);
3658
3740
  const replay = live.buffer.splice(0, live.buffer.length);
3659
3741
  try { ws.send(JSON.stringify({ type: 'reattach_result', ok: true, sessionId: live.record.id, running: live.running, replayed: replay.length })); } catch {}
3660
3742
  for (const packet of replay) { try { ws.send(JSON.stringify(packet)); } catch {} }
@@ -3707,7 +3789,8 @@ export function createAssistantRuntime({
3707
3789
  return;
3708
3790
  }
3709
3791
  case 'abort':
3710
- await stopTurn(live.record.id, { origin: 'ui' });
3792
+ // `force`: the panel's "Stop anyway", offered after a second Stop that could not end a command.
3793
+ await stopTurn(live.record.id, { origin: 'ui', force: msg.force === true });
3711
3794
  return;
3712
3795
  case 'set_route_mode':
3713
3796
  applyRouteMode(live, msg.mode);
@@ -4440,6 +4523,8 @@ export function createAssistantRuntime({
4440
4523
  clarifySession, clarifyEvent, clarifyGate, clarifySinks,
4441
4524
  getComputerUse, getComputerTurn, supersedeComputerApproval, abortTurn, notifySession,
4442
4525
  brainSpend, brainSpendByProvider, budgetSession, onBudgetChanged, onBudgetSplit, sendBudget, currentTask, usageView,
4526
+ // The shell commands of a session's OpenCode brain and a page of what one printed (the panel's terminal blocks).
4527
+ shellList, shellOutput,
4443
4528
  // Programmatic surface (the WhatsApp bridge) and remote sessions.
4444
4529
  observe, submit, stopTurn, answerControl, answerDispatchControl, pendingControls, isBusy, sessionPolicy, sessionChannel,
4445
4530
  // whatsapp_send_file's caller identity (POST /api/assistant/whatsapp/send-file).
@@ -2,13 +2,11 @@ import { createHash, randomBytes } from 'node:crypto';
2
2
  import { basename, extname, isAbsolute, resolve } from 'node:path';
3
3
  import express from 'express';
4
4
  import { readConfinedFileWithMetadata } from './confined-fs.js';
5
- import { fileURLToPath } from 'node:url';
6
- import { EVALUATE_SCRIPT_MAX, EVALUATE_TIMEOUT_MAX, EVALUATE_WORLDS, fail, handle, HISTORY, LOAD_STATES, MAX_FILE, NETWORK_IDLE_TIMEOUT_MAX, safeError } from '../../browser-extension/protocol.js';
5
+ import { EVALUATE_SCRIPT_MAX, EVALUATE_TIMEOUT_MAX, EVALUATE_WORLDS, fail, handle, HISTORY, LOAD_STATES, MAX_FILE, NETWORK_IDLE_TIMEOUT_MAX, safeError } from './browser-extension-protocol.js';
7
6
  import sharp from 'sharp';
8
7
  import { parseScreenshotOptions, screenshotPathRefusal, defaultScreenshotPath, writeScreenshotFile } from './browser-screenshot.js';
9
8
  import { ownerOnlyCreateFields } from './browser-automation-routes.js';
10
9
 
11
- export const EXTENSION_FOLDER = fileURLToPath(new URL('../../browser-extension/', import.meta.url));
12
10
  // Use the server's static-file MIME table. Its bundled table predates these image formats.
13
11
  export function uploadMimeType(name) {
14
12
  const ext = extname(name).toLowerCase();
@@ -0,0 +1,149 @@
1
+ // The extension package: which files an extension folder may hold, and the one zip form SynaBun writes and reads.
2
+ //
3
+ // One allowlist for everything (extensionFileAllowed): the manifest, scripts, pages, styles at the top and the PNGs
4
+ // in `icons/`. The folder the owner loads, a folder read as a source (Dev's build, tests) and a downloaded package
5
+ // are all held to it.
6
+ //
7
+ // The package is a zip SynaBun builds itself (scripts/extension/build-browser-extension.mjs, Dev only) in one fixed
8
+ // form, so two builds of the same files are the same bytes on any machine and any Node: entries sorted by name, every
9
+ // one STORED (no deflate, whose output depends on the zlib at hand), one fixed time, one fixed mode, no folder
10
+ // entries, no extra fields, no comments. readExtensionZip accepts only that form, which is also what makes a hostile
11
+ // file harmless: nothing is inflated (no zip bomb), a name outside the allowlist, a link, a second entry of a name, a
12
+ // gap or bytes after the directory are each a refusal, and every entry's CRC is checked. It returns bytes in memory and
13
+ // writes nothing; the caller has verified the file's size and SHA-256 before it calls (lib/browser-extension-package.js).
14
+ import { lstatSync, readdirSync, readFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { crc32 } from 'node:zlib';
17
+
18
+ const FILE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(js|json|html|css|png)$/;
19
+ const ICON = /^[A-Za-z0-9][A-Za-z0-9._-]*\.png$/;
20
+ /** The most entries a package may hold, and the most bytes one of them may be. */
21
+ export const EXTENSION_MAX_FILES = 64;
22
+ export const EXTENSION_MAX_FILE_BYTES = 4 * 1024 * 1024;
23
+
24
+ const fail = (message) => { throw Object.assign(new Error(message), { code: 'EXTENSION_ARCHIVE_INVALID' }); };
25
+
26
+ /** Whether `rel` (forward slashes, relative to the extension folder) is a file an extension folder may hold. */
27
+ export function extensionFileAllowed(rel) {
28
+ if (typeof rel !== 'string') return false;
29
+ const parts = rel.split('/');
30
+ if (parts.length === 1) return FILE.test(parts[0]);
31
+ return parts.length === 2 && parts[0] === 'icons' && ICON.test(parts[1]);
32
+ }
33
+
34
+ /**
35
+ * A folder's extension files, by path relative to it: regular files of the allowlist (a link is never followed), the
36
+ * top level and `icons/`, sorted by name. Returns [{ rel, bytes }].
37
+ */
38
+ export function readExtensionSource(source) {
39
+ const files = [];
40
+ for (const [dir, prefix] of [[source, ''], [join(source, 'icons'), 'icons/']]) {
41
+ let names = [];
42
+ try { names = readdirSync(dir); } catch { continue; }
43
+ for (const name of names) {
44
+ const rel = prefix + name;
45
+ if (!extensionFileAllowed(rel)) continue;
46
+ const path = join(dir, name);
47
+ try { if (!lstatSync(path).isFile()) continue; } catch { continue; }
48
+ files.push({ rel, bytes: readFileSync(path) });
49
+ }
50
+ }
51
+ return files.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
52
+ }
53
+
54
+ // 1980-01-01 00:00:00, the first moment a zip can name; rw-r--r-- on a regular file, written by "Unix".
55
+ const DOS_TIME = 0, DOS_DATE = 0x0021, MADE_BY = 0x031e, NEEDED = 10, MODE = 0o100644;
56
+ const LOCAL = 0x04034b50, CENTRAL = 0x02014b50, END = 0x06054b50;
57
+
58
+ function checkFiles(files) {
59
+ if (!Array.isArray(files) || !files.length) fail('The extension has no files.');
60
+ if (files.length > EXTENSION_MAX_FILES) fail('The extension has too many files.');
61
+ const seen = new Set();
62
+ for (const file of files) {
63
+ if (!extensionFileAllowed(file?.rel)) fail('The extension holds a file that is not allowed.');
64
+ if (!Buffer.isBuffer(file.bytes) || file.bytes.length > EXTENSION_MAX_FILE_BYTES) fail('A file of the extension is too large.');
65
+ const key = file.rel.toLowerCase();
66
+ if (seen.has(key)) fail('The extension names a file twice.');
67
+ seen.add(key);
68
+ }
69
+ if (!seen.has('manifest.json')) fail('The extension has no manifest.');
70
+ }
71
+
72
+ /** The package of `files` ([{ rel, bytes }]) in SynaBun's one zip form. The same files give the same bytes. */
73
+ export function writeExtensionZip(files) {
74
+ checkFiles(files);
75
+ const sorted = [...files].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
76
+ const parts = [], directory = [];
77
+ let offset = 0;
78
+ for (const { rel, bytes } of sorted) {
79
+ const name = Buffer.from(rel, 'ascii'), crc = crc32(bytes);
80
+ const local = Buffer.alloc(30);
81
+ local.writeUInt32LE(LOCAL, 0); local.writeUInt16LE(NEEDED, 4); local.writeUInt16LE(0, 6); local.writeUInt16LE(0, 8);
82
+ local.writeUInt16LE(DOS_TIME, 10); local.writeUInt16LE(DOS_DATE, 12); local.writeUInt32LE(crc, 14);
83
+ local.writeUInt32LE(bytes.length, 18); local.writeUInt32LE(bytes.length, 22); local.writeUInt16LE(name.length, 26); local.writeUInt16LE(0, 28);
84
+ const central = Buffer.alloc(46);
85
+ central.writeUInt32LE(CENTRAL, 0); central.writeUInt16LE(MADE_BY, 4); central.writeUInt16LE(NEEDED, 6); central.writeUInt16LE(0, 8); central.writeUInt16LE(0, 10);
86
+ central.writeUInt16LE(DOS_TIME, 12); central.writeUInt16LE(DOS_DATE, 14); central.writeUInt32LE(crc, 16);
87
+ central.writeUInt32LE(bytes.length, 20); central.writeUInt32LE(bytes.length, 24); central.writeUInt16LE(name.length, 28);
88
+ central.writeUInt16LE(0, 30); central.writeUInt16LE(0, 32); central.writeUInt16LE(0, 34); central.writeUInt16LE(0, 36);
89
+ central.writeUInt32LE((MODE << 16) >>> 0, 38); central.writeUInt32LE(offset, 42);
90
+ parts.push(local, name, bytes); directory.push(central, name);
91
+ offset += 30 + name.length + bytes.length;
92
+ }
93
+ const directoryBytes = Buffer.concat(directory);
94
+ const end = Buffer.alloc(22);
95
+ end.writeUInt32LE(END, 0); end.writeUInt16LE(0, 4); end.writeUInt16LE(0, 6); end.writeUInt16LE(sorted.length, 8); end.writeUInt16LE(sorted.length, 10);
96
+ end.writeUInt32LE(directoryBytes.length, 12); end.writeUInt32LE(offset, 16); end.writeUInt16LE(0, 20);
97
+ return Buffer.concat([...parts, directoryBytes, end]);
98
+ }
99
+
100
+ /**
101
+ * The files of a package in SynaBun's one zip form: [{ rel, bytes }], sorted by name. Throws
102
+ * EXTENSION_ARCHIVE_INVALID for anything else (see the top of this file); never writes and never inflates.
103
+ */
104
+ export function readExtensionZip(zip) {
105
+ if (!Buffer.isBuffer(zip) || zip.length < 22) fail('The package is not a zip file.');
106
+ const endAt = zip.length - 22;
107
+ if (zip.readUInt32LE(endAt) !== END) fail('The package does not end as SynaBun writes it.');
108
+ const count = zip.readUInt16LE(endAt + 10), directorySize = zip.readUInt32LE(endAt + 12), directoryAt = zip.readUInt32LE(endAt + 16);
109
+ if (zip.readUInt16LE(endAt + 4) || zip.readUInt16LE(endAt + 6) || zip.readUInt16LE(endAt + 8) !== count || zip.readUInt16LE(endAt + 20)) fail('The package is not a plain single zip file.');
110
+ if (!count || count > EXTENSION_MAX_FILES) fail('The package holds no files, or too many.');
111
+ if (directoryAt + directorySize !== endAt) fail('The package has bytes its directory does not account for.');
112
+ const files = [], seen = new Set();
113
+ let at = directoryAt, dataAt = 0, previous = '';
114
+ for (let i = 0; i < count; i++) {
115
+ if (at + 46 > endAt || zip.readUInt32LE(at) !== CENTRAL) fail('The package directory is damaged.');
116
+ const flags = zip.readUInt16LE(at + 8), method = zip.readUInt16LE(at + 10), crc = zip.readUInt32LE(at + 16);
117
+ const packed = zip.readUInt32LE(at + 20), size = zip.readUInt32LE(at + 24), nameLength = zip.readUInt16LE(at + 28);
118
+ const attributes = zip.readUInt32LE(at + 38), localAt = zip.readUInt32LE(at + 42);
119
+ if (flags !== 0 || method !== 0 || packed !== size) fail('The package holds an entry that is compressed, encrypted or streamed.');
120
+ if (zip.readUInt16LE(at + 30) || zip.readUInt16LE(at + 32) || zip.readUInt16LE(at + 34)) fail('The package holds an entry with extra data.');
121
+ // Every other field is the one value SynaBun's writer puts there: the version needed, the time, the date, the
122
+ // internal attributes (and, below, the same in the entry's own header).
123
+ if (zip.readUInt16LE(at + 6) !== NEEDED || zip.readUInt16LE(at + 12) !== DOS_TIME || zip.readUInt16LE(at + 14) !== DOS_DATE || zip.readUInt16LE(at + 36) !== 0) fail('The package holds an entry that SynaBun did not write.');
124
+ if (size > EXTENSION_MAX_FILE_BYTES) fail('The package holds a file that is too large.');
125
+ if (at + 46 + nameLength > endAt) fail('The package directory is damaged.');
126
+ const nameBytes = zip.subarray(at + 46, at + 46 + nameLength), rel = nameBytes.toString('latin1');
127
+ // A regular file and nothing else: a link, a folder, a device are told by the Unix mode a zip keeps for its maker.
128
+ if (zip.readUInt16LE(at + 4) !== MADE_BY || (attributes >>> 16) !== MODE) fail('The package holds an entry that is not a plain file.');
129
+ if (!extensionFileAllowed(rel)) fail('The package holds a file that is not part of the extension.');
130
+ const key = rel.toLowerCase();
131
+ if (seen.has(key)) fail('The package names a file twice.');
132
+ if (previous && !(previous < rel)) fail('The package is not in SynaBun\'s order.');
133
+ seen.add(key); previous = rel;
134
+ // The entry itself: where the last one ended, with a header that says what the directory says.
135
+ if (localAt !== dataAt || localAt + 30 + nameLength + size > directoryAt) fail('The package has a gap or an overlap between its files.');
136
+ if (zip.readUInt32LE(localAt) !== LOCAL || zip.readUInt16LE(localAt + 4) !== NEEDED || zip.readUInt16LE(localAt + 6) !== 0 || zip.readUInt16LE(localAt + 8) !== 0
137
+ || zip.readUInt16LE(localAt + 10) !== DOS_TIME || zip.readUInt16LE(localAt + 12) !== DOS_DATE || zip.readUInt32LE(localAt + 14) !== crc
138
+ || zip.readUInt32LE(localAt + 18) !== size || zip.readUInt32LE(localAt + 22) !== size || zip.readUInt16LE(localAt + 26) !== nameLength || zip.readUInt16LE(localAt + 28) !== 0
139
+ || !zip.subarray(localAt + 30, localAt + 30 + nameLength).equals(nameBytes)) fail('The package has an entry whose header does not match its directory.');
140
+ const bytes = Buffer.from(zip.subarray(localAt + 30 + nameLength, localAt + 30 + nameLength + size));
141
+ if (crc32(bytes) !== crc) fail('The package holds a damaged file.');
142
+ files.push({ rel, bytes });
143
+ dataAt = localAt + 30 + nameLength + size;
144
+ at += 46 + nameLength;
145
+ }
146
+ if (at !== endAt || dataAt !== directoryAt) fail('The package has bytes its directory does not account for.');
147
+ if (!seen.has('manifest.json')) fail('The package has no manifest.');
148
+ return files;
149
+ }
@@ -1,14 +1,17 @@
1
1
  import { createServer } from 'node:http';
2
- import { createHash, randomBytes } from 'node:crypto';
2
+ import { randomBytes } from 'node:crypto';
3
3
  import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
4
  import { compareVersions } from './browser-extension-folder.js';
5
5
  import { dirname } from 'node:path';
6
6
  import { lookup } from 'node:dns/promises';
7
7
  import { WebSocketServer } from 'ws';
8
- import { anyOrigin, channel, command, COMMAND_WAIT, commandWait as operationWait, CONTROL, controlSurface, equalMac, ERROR_TEXT, fail, handle, HISTORY, inventory, localHost, LONG_OPS_SINCE, longOp, mac, MAX_MESSAGE, nonce, object, pairingKey, parse, payload, portOf, publicOrigin, safeError, string } from '../../browser-extension/protocol.js';
8
+ import { anyOrigin, channel, command, COMMAND_WAIT, commandWait as operationWait, CONTROL, controlSurface, equalMac, ERROR_TEXT, fail, handle, HISTORY, inventory, localHost, LONG_OPS_SINCE, longOp, mac, MAX_MESSAGE, nonce, object, pairingKey, parse, payload, portOf, publicOrigin, safeError, string } from './browser-extension-protocol.js';
9
+ import { EXTENSION_ID } from './browser-extension-pin.js';
9
10
 
10
- const manifest = JSON.parse(readFileSync(new URL('../../browser-extension/manifest.json', import.meta.url), 'utf8'));
11
- export const EXTENSION_ID = createHash('sha256').update(Buffer.from(manifest.key, 'base64')).digest('hex').slice(0, 32).replace(/[0-9a-f]/g, c => String.fromCharCode(97 + parseInt(c, 16)));
11
+ // The wire contract is the app's own copy of the extension's protocol.js (kept byte-identical by
12
+ // scripts/extension/check-browser-extension-pin.mjs), and the extension's identity is the app's pin: the server
13
+ // starts, restores a pairing and checks an Origin with no extension folder anywhere.
14
+ export { EXTENSION_ID };
12
15
  const empty = () => ({ tabs: [], sites: [], allowNewTabs: false, uploads: false, downloads: false });
13
16
  export async function publicDestination(url, resolver = lookup) {
14
17
  const origin = publicOrigin(url);