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
@@ -82,6 +82,19 @@ export const OPENCODE_UPDATE_SOURCES = Object.freeze({
82
82
  brewToken: 'opencode-v2',
83
83
  });
84
84
 
85
+ /**
86
+ * OpenCode 2 in WinGet (checked 2026-11-23): the package id, and the arguments OpenCode's own updater asks WinGet
87
+ * with to find the version it can install (`winget search …`). WinGet is the yardstick of a WinGet install, not
88
+ * OpenCode's update API: a release reaches WinGet's repository days after it is published, and some never do (on
89
+ * 2026-11-23 the API said 2.4.1 while WinGet's newest was 2.3.2, after 2.2.7 with nothing between). `opencode
90
+ * upgrade --method winget` installs what WinGet has, so a badge measured against the API stays lit after an update
91
+ * that did all it could.
92
+ */
93
+ export const OPENCODE_WINGET_ID = 'Anomaly.OpenCode';
94
+ export const OPENCODE_WINGET_SEARCH_ARGS = Object.freeze([
95
+ 'search', '--id', OPENCODE_WINGET_ID, '--exact', '--source', 'winget', '--accept-source-agreements', '--disable-interactivity',
96
+ ]);
97
+
85
98
  const PLAIN_VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
86
99
  const plainVersion = (value) => {
87
100
  const text = typeof value === 'string' ? value.trim().replace(/^v(?=\d)/i, '') : '';
@@ -104,6 +117,24 @@ export function parseFormulaVersion(text) {
104
117
  return match ? plainVersion(match[1]) : null;
105
118
  }
106
119
 
120
+ /**
121
+ * The version `winget search --id <id> --exact` lists for a package, or null. Read as OpenCode's own updater reads
122
+ * it: on any line, the word after the package id (the table's columns are Name, Id, Version, Source; a progress
123
+ * spinner may share the first line, separated by carriage returns).
124
+ */
125
+ export function parseWingetSearchVersion(output, id = OPENCODE_WINGET_ID) {
126
+ const wanted = String(id || '').toLowerCase();
127
+ if (!wanted) return null;
128
+ for (const line of String(output ?? '').split(/\r?\n|\r/)) {
129
+ const words = line.trim().split(/\s+/);
130
+ const at = words.findIndex((word) => word.toLowerCase() === wanted);
131
+ if (at === -1) continue;
132
+ const version = plainVersion(words[at + 1]);
133
+ if (version) return version;
134
+ }
135
+ return null;
136
+ }
137
+
107
138
  /**
108
139
  * Where a tool's newest version is read from when it has no npm package:
109
140
  * `{ url, channel, read(text) }`, or null (an npm tool, a tool with no such
@@ -295,14 +326,32 @@ export function quoteCommandPath(file, platform = process.platform) {
295
326
  * upgrade` refreshes by itself only once in a while (HOMEBREW_AUTO_UPDATE_SECS,
296
327
  * a day by default) and would answer "already installed", leaving the badge
297
328
  * lit: the command refreshes first.
329
+ *
330
+ * `gitBash`: a Git Bash this PC has (lib/git-bash resolver: bash.exe), for OpenCode 2's own installer on Windows.
331
+ * `opencode upgrade --method curl` runs that installer, a bash script, with Git Bash, which it looks for through
332
+ * `git --exec-path`: a PC whose git is not on PATH (Git's "Git Bash only" setup, or SynaBun's own copy of Git) has
333
+ * one all the same, and is told where it is (OPENCODE_GIT_BASH_PATH, for that one command).
334
+ *
335
+ * `installedVersion`: the version found, when the caller knows it. An OpenCode in %USERPROFILE%\.opencode\bin that
336
+ * is not OpenCode 2 (the release archive an older SynaBun put there was OpenCode 1) gets no command, as before: its
337
+ * own upgrade is not the one meant here, and SynaBun's panel already says how to get OpenCode 2.
298
338
  */
299
- export function buildUpdateCommand(toolKey, installSource, { brewToken = null, binPath = null, platform = null, refreshBrew = false } = {}) {
339
+ export function buildUpdateCommand(toolKey, installSource, { brewToken = null, binPath = null, platform = null, refreshBrew = false, gitBash = null, installedVersion = null } = {}) {
340
+ if (toolKey === 'opencode' && installSource === 'standalone' && platform === 'win32' && installedVersion != null && !/^v?2\./.test(String(installedVersion).trim())) return null;
300
341
  const planned = planUpdateCommand(toolKey, installSource, { brewToken, platform });
301
342
  const command = planned && refreshBrew && isBrewSource(installSource) ? `brew update && ${planned}` : planned;
302
343
  const name = TOOL_COMMANDS[toolKey];
303
344
  if (!command || !binPath || !name) return command;
304
345
  if (command !== name && !command.startsWith(`${name} `)) return command;
305
- return `${quoteCommandPath(binPath, platform || process.platform)}${command.slice(name.length)}`;
346
+ const started = `${quoteCommandPath(binPath, platform || process.platform)}${command.slice(name.length)}`;
347
+ const bash = toolKey === 'opencode' && platform === 'win32' && installSource === 'standalone' ? cmdSetValue(gitBash) : null;
348
+ return bash ? `set "OPENCODE_GIT_BASH_PATH=${bash}" && ${started}` : started;
349
+ }
350
+
351
+ /** A value cmd.exe takes unchanged inside `set "NAME=value"`, or null (a quote, a variable or an escape in it). */
352
+ function cmdSetValue(value) {
353
+ const text = typeof value === 'string' ? value.trim() : '';
354
+ return text && !/["%!^\r\n]/.test(text) ? text : null;
306
355
  }
307
356
 
308
357
  function planUpdateCommand(toolKey, installSource, { brewToken = null, platform = null } = {}) {
@@ -326,8 +375,10 @@ function planUpdateCommand(toolKey, installSource, { brewToken = null, platform
326
375
 
327
376
  // OpenCode 2 updates itself through the channel it came from (brew is handled above).
328
377
  if (toolKey === 'opencode') {
329
- // Its installer script is bash: a copy in %USERPROFILE%\.opencode\bin on Windows is no OpenCode 2 install.
330
- if (installSource === 'standalone' && platform === 'win32') return null;
378
+ // %USERPROFILE%\.opencode\bin\opencode.exe is an install of OpenCode 2's own script on Windows too (the script
379
+ // runs in Git Bash and names the file opencode.exe), and OpenCode 2 updates it there with `--method curl`
380
+ // through Git Bash (read in the Windows builds of 2.2.7 and 2.4.1, 2026-11-23). It used to get no command here,
381
+ // so its badge could only say "update via the official installer".
331
382
  if (OPENCODE_METHODS[installSource]) return `opencode upgrade --method ${OPENCODE_METHODS[installSource]}`;
332
383
  if (['volta', 'scoop', 'choco'].includes(installSource)) return null; // not an OpenCode 2 channel: the caller shows a hint
333
384
  return selfUpdate;
@@ -408,6 +459,13 @@ export function parseBrewOutdated(raw) {
408
459
  * tool's formula as its tap publishes it (OpenCode's tap only): what Homebrew
409
460
  * installs once the tap is refreshed, so it counts when it is newer than the
410
461
  * install and `brew outdated` has not heard of it yet.
462
+ *
463
+ * `winget`: what WinGet was asked about a WinGet install (OpenCode 2 only):
464
+ * `{ version }`, the version WinGet lists, or null when it could not be
465
+ * asked. WinGet is then the yardstick, as Homebrew is for a Homebrew install:
466
+ * its version when that is newer than the install, else the install itself (no
467
+ * badge), and the install itself when WinGet could not be asked (fail closed:
468
+ * the update API's version is one WinGet may not have).
411
469
  */
412
470
  export function resolveLatest({
413
471
  installSource,
@@ -416,7 +474,12 @@ export function resolveLatest({
416
474
  npmLatest = null,
417
475
  brewUpstream = null,
418
476
  installed = null,
477
+ winget = undefined,
419
478
  } = {}) {
479
+ if (installSource === 'winget' && winget !== undefined) {
480
+ if (!installed) return null;
481
+ return winget?.version && semverNewer(installed, winget.version) ? winget.version : installed;
482
+ }
420
483
  if (!isBrewSource(installSource)) return npmLatest;
421
484
  if (!installed) return null;
422
485
  if (!brewOutdated) return installed;
@@ -1656,7 +1656,16 @@ export async function createOpenCodeNativeLoopAdapter(options = {}) {
1656
1656
  if (activeAbort) activeAbort.abort(asAbortError(reason));
1657
1657
  settleActiveTurn(asAbortError(reason));
1658
1658
  try {
1659
- await settleWithin(client.session.abort({ sessionID: sessionId, directory: cwd || undefined }));
1659
+ // A worker's or a loop's stop ends its run whatever OpenCode answers, so a command in the background it
1660
+ // cannot end is given up on with `force` (Stop anyway, lib/opencode2-client.js): still removed in the
1661
+ // background, and its end wakes no model turn in a session nobody owns any more.
1662
+ // What it gave up on goes back to the runtime (lib/native-loop-runtime.js stop), which keeps it on the run:
1663
+ // its result, its tab and the brain then say that the command may still be running (review 29cd51fe).
1664
+ const answer = await settleWithin(client.session.abort({ sessionID: sessionId, directory: cwd || undefined, force: true }));
1665
+ const abandoned = Array.isArray(answer?.data?.abandoned) ? answer.data.abandoned : [];
1666
+ if (abandoned.length) {
1667
+ return { stopped: true, abandoned: abandoned.map((shell) => ({ id: String(shell?.id || ''), command: String(shell?.command || '').slice(0, 200) })) };
1668
+ }
1660
1669
  } catch {}
1661
1670
  return true;
1662
1671
  },
@@ -68,6 +68,9 @@ function rawDescriptor(record) {
68
68
  claimedAt: record.claimedAt || null,
69
69
  error: record.error || null,
70
70
  ...(record.errorCode ? { errorCode: record.errorCode, offenders: record.offenders } : {}),
71
+ // The commands its stop could not end (an OpenCode command in the background): they may still be running, and the
72
+ // client keeps trying to end them (lib/opencode2-client.js abortSession force).
73
+ ...(Array.isArray(record.abandonedCommands) && record.abandonedCommands.length ? { abandonedCommands: record.abandonedCommands } : {}),
71
74
  version: Number(record.version) || 0,
72
75
  // Task-mode (assistant dispatch) fields. Absent/null for classic loops so
73
76
  // existing consumers (router, sidepanels, schedules) are unaffected.
@@ -932,6 +935,21 @@ export class NativeLoopRuntime {
932
935
  }
933
936
  }
934
937
 
938
+ /**
939
+ * The adapter's abort, for a run that is ending. An OpenCode adapter answers `{ abandoned: [{ id, command }] }` when
940
+ * a command in the background could not be ended (its stop forces, lib/native-loop-providers.js): the run keeps
941
+ * them (`abandonedCommands`, in its descriptor and its state file), so its result and its tab can say so.
942
+ */
943
+ async _abortAdapter(record, reason) {
944
+ let answer;
945
+ try { answer = await record.adapter?.abort?.(reason); } catch { return; }
946
+ const abandoned = Array.isArray(answer?.abandoned) ? answer.abandoned.filter((shell) => shell && (shell.command || shell.id)) : [];
947
+ if (!abandoned.length) return;
948
+ record.abandonedCommands = abandoned.slice(0, 20).map((shell) => ({ id: String(shell.id || ''), command: String(shell.command || '').slice(0, 200) }));
949
+ this.log(record.runId, 'native:stop-abandoned', 'its stop could not end a command in the background: it may still be running, and SynaBun keeps trying to end it', { count: abandoned.length });
950
+ this._writeTerminalState(record, { abandonedCommands: record.abandonedCommands });
951
+ }
952
+
935
953
  _releaseRuntimeRefs(record, { turnState = 'terminal' } = {}) {
936
954
  if (!record) return;
937
955
  record.adapter = null;
@@ -976,7 +994,7 @@ export class NativeLoopRuntime {
976
994
  try { record.startupAbortController?.abort(reason); } catch {}
977
995
  if (record._cancelStartup) { record._cancelStartup(reason); record._cancelStartup = null; }
978
996
  this._writeTerminalState(record, { active: false, pending: false, completedAt: record.completedAt, stoppedReason: reason, error: record.error, errorCode: record.errorCode, offenders: record.offenders });
979
- try { await record.adapter?.abort?.(reason); } catch {}
997
+ await this._abortAdapter(record, reason);
980
998
  try { await record.adapter?.dispose?.({ preserveSession: true }); } catch {}
981
999
  this._releaseRuntimeRefs(record);
982
1000
  this._emit(record.status === 'interrupted' ? 'sidepanel:run-stopped' : 'sidepanel:run-failed', record);
@@ -1020,7 +1038,7 @@ export class NativeLoopRuntime {
1020
1038
  try { record.startupAbortController?.abort(reason); } catch {}
1021
1039
  if (record._cancelStartup) { record._cancelStartup(reason); record._cancelStartup = null; }
1022
1040
  this._writeTerminalState(record, { active: false, pending: false, completedAt: record.completedAt, stoppedReason: reason });
1023
- try { await record.adapter?.abort?.(reason); } catch {}
1041
+ await this._abortAdapter(record, reason);
1024
1042
  try { await record.adapter?.dispose?.({ preserveSession: true, ...(terminate ? { terminate: true } : {}) }); } catch {}
1025
1043
  this._releaseRuntimeRefs(record);
1026
1044
  this._emit('sidepanel:run-stopped', record);
@@ -0,0 +1,107 @@
1
+ // ─────────────────────────────────────────────────────────────────────────────
2
+ // A page of what a shell command of OpenCode 2 printed
3
+ //
4
+ // OpenCode 2 keeps a command's combined stdout and stderr, in the order
5
+ // written, and answers pages of it by byte position while the command runs and
6
+ // after (GET /api/shell/:id/output, lib/opencode2-client.js `shell.output`).
7
+ // The OpenCode side panel (`shell:output`, lib/opencode-v2-ws-requests.js) and
8
+ // the Assistant's OpenCode brain (lib/assistant-brains/opencode.js) both read
9
+ // it through here, so a page means the same in both: at most
10
+ // SHELL_OUTPUT_PAGE_BYTES, from a byte `cursor`, or the last `tail` bytes.
11
+ // Who may read which command is the caller's to decide before it asks.
12
+ // ─────────────────────────────────────────────────────────────────────────────
13
+
14
+ import { PAGE_CONTEXT_CHARS, scrubOutputWindow } from './terminal-token-redaction.js';
15
+
16
+ /** The most one read returns. */
17
+ export const SHELL_OUTPUT_PAGE_BYTES = 256 * 1024;
18
+
19
+ /** The least a scrubbed page asks for: never so small that a secret could fill it. */
20
+ export const SHELL_OUTPUT_PAGE_MIN_BYTES = 4096;
21
+
22
+ /** How many bytes after a page are read to tell whether a secret crosses its end (more than the longest form). */
23
+ const LOOKAHEAD_BYTES = PAGE_CONTEXT_CHARS * 2;
24
+
25
+ /** What a reader is told when OpenCode no longer has the output. */
26
+ export const SHELL_OUTPUT_GONE_TEXT = 'The output of that command is no longer available.';
27
+
28
+ const wholeNumber = (value) => Math.max(0, Math.floor(Number(value) || 0));
29
+
30
+ /**
31
+ * `shell`: `{ output({ shellID, directory, cursor, limit }) → { status, data: { output, cursor, size } } }`
32
+ * (a client's `extra.shell`). `cursor`: the byte to read from; `tail`: instead, the last so many bytes (a
33
+ * reader that opens on a long output starts at its end). `errorText(body, fallback)` words a refusal.
34
+ * → `{ status, data: { output, cursor, size, truncated, from } }`, or `{ ok: false, status, error }`.
35
+ * A call that throws is the caller's to catch.
36
+ */
37
+ export async function readShellOutputPage(shell, { shellID, directory, cursor, tail, limit } = {}, { errorText = (_body, fallback) => fallback } = {}) {
38
+ const refused = (r) => ({ ok: false, status: r.status, error: errorText(r.data, SHELL_OUTPUT_GONE_TEXT) });
39
+ const size = Math.min(SHELL_OUTPUT_PAGE_BYTES, Math.max(1, Math.floor(Number(limit) || SHELL_OUTPUT_PAGE_BYTES)));
40
+ let from = wholeNumber(cursor);
41
+ const last = wholeNumber(tail);
42
+ if (last > 0) {
43
+ // The size first (one byte asked for), then the page that ends at it.
44
+ const probe = await shell.output({ shellID, directory, cursor: 0, limit: 1 });
45
+ if (probe.status >= 400) return refused(probe);
46
+ from = Math.max(0, (Number(probe.data?.size) || 0) - Math.min(last, size));
47
+ }
48
+ const r = await shell.output({ shellID, directory, cursor: from, limit: size });
49
+ if (r.status >= 400) return refused(r);
50
+ return { status: r.status, data: { ...r.data, from } };
51
+ }
52
+
53
+ /**
54
+ * A page as a reader may be given it: scrubbed of SynaBun's run secrets with what lies on both sides of it, so that
55
+ * the pages a reader joins never hold a secret whole (lib/terminal-token-redaction.js scrubOutputWindow). Both the
56
+ * OpenCode side panel (`shell:output`) and the Assistant panel (assistant-runtime.js shellOutput) read through here.
57
+ * `read({ cursor, limit })` → a raw page `{ status, data: { output, cursor, size } }` or a refusal. `running`: the
58
+ * command may still write (an end that could become a secret waits for the next page; once it ended it is masked).
59
+ * → `{ status, data: { output, cursor, size, from } }`, or the refusal of the read that failed (a failed look on
60
+ * either side is a failed page: unread, it could let part of a secret through).
61
+ */
62
+ export async function readSafeShellOutputPage(read, { cursor, tail, limit, running = false } = {}) {
63
+ const bad = (r) => !r || r.ok === false || !(Number(r.status) < 400);
64
+ const refusal = (r) => (r && r.ok === false ? r : { ok: false, status: Number(r?.status) >= 400 ? Number(r.status) : 502, error: r?.error || 'The output could not be read.' });
65
+ const size = Math.min(SHELL_OUTPUT_PAGE_BYTES, Math.max(SHELL_OUTPUT_PAGE_MIN_BYTES, Math.floor(Number(limit) || SHELL_OUTPUT_PAGE_BYTES)));
66
+ let from = wholeNumber(cursor);
67
+ const last = wholeNumber(tail);
68
+ if (last > 0) {
69
+ const probe = await read({ cursor: 0, limit: 1 });
70
+ if (bad(probe)) return refusal(probe);
71
+ from = Math.max(0, (Number(probe.data?.size) || 0) - Math.min(last, size));
72
+ }
73
+ const r = await read({ cursor: from, limit: size });
74
+ if (bad(r)) return refusal(r);
75
+ const data = r.data && typeof r.data === 'object' ? r.data : {};
76
+ const output = typeof data.output === 'string' ? data.output : '';
77
+ const next = Math.max(from, Number(data.cursor) || 0);
78
+ let total = Math.max(next, Number(data.size) || 0);
79
+ const extra = data.truncated === true ? { truncated: true } : {};
80
+ if (!output) return { status: r.status, data: { output: '', cursor: next, size: total, from, ...extra } };
81
+ let before = '';
82
+ if (from > 0) {
83
+ const start = Math.max(0, from - PAGE_CONTEXT_CHARS);
84
+ const context = await read({ cursor: start, limit: from - start });
85
+ if (bad(context)) return refusal(context);
86
+ before = typeof context.data?.output === 'string' ? context.data.output : '';
87
+ }
88
+ let after = '';
89
+ let aheadEnd = next;
90
+ if (next < total) {
91
+ const ahead = await read({ cursor: next, limit: LOOKAHEAD_BYTES });
92
+ if (bad(ahead)) return refusal(ahead);
93
+ after = typeof ahead.data?.output === 'string' ? ahead.data.output : '';
94
+ aheadEnd = Math.max(next, Number(ahead.data?.cursor) || next);
95
+ total = Math.max(total, Number(ahead.data?.size) || 0);
96
+ }
97
+ // The window reaches the end of what the command printed so far: nothing follows it once the command ended.
98
+ const reachesEnd = aheadEnd >= total;
99
+ const page = scrubOutputWindow(output, { before, after, final: reachesEnd && !running });
100
+ const at = page.consumed <= output.length
101
+ ? next - Buffer.byteLength(output.slice(page.consumed), 'utf8')
102
+ : next + Buffer.byteLength(after.slice(0, page.consumed - output.length), 'utf8');
103
+ const moved = Math.max(from, at);
104
+ // An end held back at the end of the output: nothing more to read for now, the reader asks again at its own pace.
105
+ if (page.held && reachesEnd) total = moved;
106
+ return { status: r.status, data: { output: page.text, cursor: moved, size: Math.max(moved, total), from, ...extra } };
107
+ }
@@ -0,0 +1,40 @@
1
+ // The Stops of an OpenCode side panel turn that could not end a command in the background (server.js
2
+ // handleOpencodeV2Ws, message:abort): from the second one of the same turn the panel offers "Stop anyway". One
3
+ // counter per socket, keyed by session, each entry naming the turn it counts for (the token of
4
+ // `_ocpActiveSessionTurns`). An entry goes when its turn ends or is replaced (`prune`, at every turn end and every
5
+ // failure), when its session is deleted (`clear`) and with the socket (`clearAll`), so a long-lived socket that
6
+ // works many sessions keeps at most one entry per session whose turn is still on.
7
+
8
+ /**
9
+ * `activeTurn(sessionId)`: the token of the turn running now in that session, or null / undefined when none.
10
+ */
11
+ export function createStopFailures({ activeTurn = () => null } = {}) {
12
+ const entries = new Map();
13
+ const current = (sid) => activeTurn(sid) ?? null;
14
+ /**
15
+ * Drop every entry whose turn is no longer the one running in its session, and every entry counted while no turn
16
+ * was known (a held turn whose token is gone): it could otherwise stay for good. `keep`: a session left alone.
17
+ */
18
+ function prune(keep = null) {
19
+ for (const [sid, entry] of entries) {
20
+ if (sid === keep) continue;
21
+ if (entry.turn === null || current(sid) !== entry.turn) entries.delete(sid);
22
+ }
23
+ }
24
+ return {
25
+ /** A Stop of `sid`'s turn failed: → how many have failed for that turn so far (1 for its first). */
26
+ fail(sid) {
27
+ prune(sid);
28
+ const turn = current(sid);
29
+ const prior = entries.get(sid);
30
+ const count = prior && prior.turn === turn ? prior.count + 1 : 1;
31
+ entries.set(sid, { turn, count });
32
+ return count;
33
+ },
34
+ /** The session's Stop worked, or the session is gone. */
35
+ clear(sid) { entries.delete(sid); },
36
+ prune: () => prune(),
37
+ clearAll() { entries.clear(); },
38
+ get size() { return entries.size; },
39
+ };
40
+ }
@@ -0,0 +1,173 @@
1
+ // What a serve of SynaBun's does right before it is stopped: the turns still running on it are interrupted, so that
2
+ // no session stays claimed in OpenCode's database.
3
+ //
4
+ // Why (measured on OpenCode 2.2.7 and 2.4.1, 2026-11-23): a session whose turn is in flight has `time_suspended` set
5
+ // in OpenCode's `session_v2` table. A serve that ends with the turn still running leaves that mark: on SIGKILL
6
+ // (`taskkill /F`, what Windows gets) and on SIGTERM alike. A serve started the way SynaBun starts one (`opencode
7
+ // serve`) never looks at the mark again, but OpenCode's own background service (the one a plain `opencode` in a
8
+ // terminal starts) resumes EVERY marked session at its boot, all at once, and each one calls its model again. A
9
+ // session a schedule ran weeks ago wakes up then. `POST /api/session/<id>/interrupt` on the serve that runs the turn
10
+ // clears the mark; on any other serve it changes nothing, so the only moment to do it is before the stop.
11
+ //
12
+ // The caller's stop is never held up for long: one read of the active sessions, one interrupt for each, and a short
13
+ // wait for the serve to say they ended, all inside `budgetMs`. A serve that does not answer is stopped as before.
14
+ import { basicAuthHeader } from './opencode-protocol.js';
15
+
16
+ /** How long a stop waits for its serve's turns to end, at most. */
17
+ export const TURN_RELEASE_BUDGET_MS = 2500;
18
+
19
+ const pause = (ms) => new Promise((done) => { const timer = setTimeout(done, ms); timer.unref?.(); });
20
+
21
+ async function request(fetchImpl, url, { method = 'GET', password, timeoutMs }) {
22
+ const res = await fetchImpl(url, {
23
+ method,
24
+ headers: { accept: 'application/json', ...(password ? { authorization: basicAuthHeader(password) } : {}) },
25
+ signal: AbortSignal.timeout(Math.max(1, Math.round(timeoutMs))),
26
+ });
27
+ let body = null;
28
+ try { body = await res.json(); } catch { /* no JSON body */ }
29
+ return { ok: res.ok, status: res.status, body };
30
+ }
31
+
32
+ /**
33
+ * The sessions a serve is running a turn for right now: `{ ok, ids, error }`. `ok` false when the serve did not
34
+ * answer its own API (stopped already, another server on the port, a refused password): nothing is known then.
35
+ */
36
+ export async function activeOpencodeSessions({ port, password = null, host = '127.0.0.1', fetchImpl = globalThis.fetch, timeoutMs = 1000 } = {}) {
37
+ if (!(Number(port) > 0)) return { ok: false, ids: [], error: 'no port' };
38
+ try {
39
+ const answer = await request(fetchImpl, `http://${host}:${port}/api/session/active`, { password, timeoutMs });
40
+ if (!answer.ok) return { ok: false, ids: [], error: `GET /api/session/active answered ${answer.status}` };
41
+ const data = answer.body?.data;
42
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return { ok: false, ids: [], error: 'GET /api/session/active answered no list' };
43
+ return { ok: true, ids: Object.keys(data), error: null };
44
+ } catch (error) {
45
+ return { ok: false, ids: [], error: String(error?.message || error) };
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Interrupt every turn a serve is running and wait, inside `budgetMs`, until it reports none of them.
51
+ * `{ ok, active, interrupted, remaining, ms, error }`: `active` the sessions that were running, `interrupted` the
52
+ * ones the serve took the interrupt for, `remaining` the ones still running when the budget ended (they stay
53
+ * claimed). Never throws.
54
+ */
55
+ export async function releaseOpencodeTurns({
56
+ port, password = null, host = '127.0.0.1', fetchImpl = globalThis.fetch,
57
+ budgetMs = TURN_RELEASE_BUDGET_MS, pollMs = 100, now = Date.now, sleep = pause,
58
+ } = {}) {
59
+ const started = now();
60
+ const left = () => budgetMs - (now() - started);
61
+ const done = (result) => ({ active: [], interrupted: [], remaining: [], error: null, ...result, ms: now() - started });
62
+ const first = await activeOpencodeSessions({ port, password, host, fetchImpl, timeoutMs: Math.min(1000, Math.max(1, budgetMs)) });
63
+ if (!first.ok) return done({ ok: false, error: first.error });
64
+ if (!first.ids.length) return done({ ok: true });
65
+ const interrupted = [];
66
+ await Promise.all(first.ids.map(async (id) => {
67
+ try {
68
+ const answer = await request(fetchImpl, `http://${host}:${port}/api/session/${encodeURIComponent(id)}/interrupt`, { method: 'POST', password, timeoutMs: Math.max(1, left()) });
69
+ if (answer.ok) interrupted.push(id);
70
+ } catch { /* it stays in `remaining` */ }
71
+ }));
72
+ let remaining = first.ids;
73
+ while (left() > 0) {
74
+ const look = await activeOpencodeSessions({ port, password, host, fetchImpl, timeoutMs: Math.max(1, Math.min(1000, left())) });
75
+ // A serve that stopped answering has ended: nothing more can be asked of it.
76
+ if (!look.ok) return done({ ok: false, active: first.ids, interrupted, remaining, error: look.error });
77
+ remaining = first.ids.filter((id) => look.ids.includes(id));
78
+ if (!remaining.length) break;
79
+ if (left() <= pollMs) break;
80
+ await sleep(pollMs);
81
+ }
82
+ return done({ ok: remaining.length === 0, active: first.ids, interrupted, remaining, error: remaining.length ? 'turns still running when the wait ended' : null });
83
+ }
84
+
85
+ /**
86
+ * How SynaBun ends its serves: `end()` releases a serve's turns and then runs its `kill`, exactly once.
87
+ *
88
+ * end({ port, password, alive, kill, label, immediate })
89
+ * → null when the serve was ended at once (nothing can be asked of it: no port or password, its process is
90
+ * gone, or `immediate`), else a promise of its end. `kill` always runs, also when the release failed.
91
+ * settled(timeoutMs) every end under way has finished (true), or the wait ran out (false): a shutdown waits here.
92
+ * killNow() the kills not run yet, now and synchronously: the process's exit handler, where nothing
93
+ * can be awaited, so that a serve whose release was still under way is not left running.
94
+ */
95
+ export function createServeEnds({ release = releaseOpencodeTurns, log = () => {} } = {}) {
96
+ const pending = new Set();
97
+ const kills = new Set();
98
+ return {
99
+ end({ port = null, password = null, alive = () => true, kill, label = 'serve', immediate = false } = {}) {
100
+ let ran = false;
101
+ const once = () => {
102
+ if (ran) return;
103
+ ran = true;
104
+ kills.delete(once);
105
+ try { kill?.(); } catch { /* its process is gone */ }
106
+ };
107
+ let running = false;
108
+ try { running = !!alive(); } catch { running = false; }
109
+ if (immediate || !(Number(port) > 0) || !password || !running) { once(); return null; }
110
+ kills.add(once);
111
+ const ended = (async () => {
112
+ try {
113
+ const released = await release({ port, password });
114
+ if (released?.active?.length) {
115
+ const kept = released.remaining?.length || 0;
116
+ log(`${label}: ${released.active.length - kept} of ${released.active.length} running turn(s) interrupted before the stop${kept ? `; ${kept} did not end in time and may be resumed by OpenCode's own background service` : ''}`);
117
+ }
118
+ } catch { /* the serve is ended either way */ } finally { once(); }
119
+ })().finally(() => pending.delete(ended));
120
+ pending.add(ended);
121
+ return ended;
122
+ },
123
+ killNow() { for (const kill of [...kills]) kill(); },
124
+ size: () => pending.size,
125
+ async settled(timeoutMs = TURN_RELEASE_BUDGET_MS + 1500) {
126
+ if (!pending.size) return true;
127
+ let timer = null;
128
+ const timeout = new Promise((done) => { timer = setTimeout(() => done(false), timeoutMs); timer.unref?.(); });
129
+ const all = Promise.allSettled([...pending]).then(() => true);
130
+ const result = await Promise.race([all, timeout]);
131
+ clearTimeout(timer);
132
+ return result;
133
+ },
134
+ };
135
+ }
136
+
137
+ // ── A serve older than the OpenCode on disk ────────────────────────────────────────────────────────────────────────
138
+ //
139
+ // An update of OpenCode replaces the file; a serve SynaBun started before keeps running the old program from memory
140
+ // (on Windows OpenCode's updater links the running file under another name first, so the installed path can be
141
+ // replaced while SynaBun's serve runs from it). Nothing told SynaBun: its shared serve, and the serve of every open
142
+ // session, stayed on the old version until SynaBun itself was restarted, and the panel kept showing that version.
143
+ // OpenCode treats the same situation in its own client as a reason to replace the server ("Restarting background
144
+ // server (version mismatch)").
145
+
146
+ /** A file's identity (lib/opencode-serve-probe.js binaryIdentity) as one string, or null. */
147
+ export function binaryFileKey(identity) {
148
+ if (!identity?.realpath) return null;
149
+ return [identity.realpath, identity.size, identity.mtimeMs, identity.ino, identity.dev].join('|');
150
+ }
151
+
152
+ /**
153
+ * Which of SynaBun's serves run a file that is no longer the OpenCode on disk.
154
+ *
155
+ * current the file key of the OpenCode SynaBun would start now; null (not readable, a command line in Settings):
156
+ * nothing is decided
157
+ * shared { key, managed, ready, starting }: SynaBun's shared serve. Only one SynaBun spawned (`managed`) and
158
+ * that answers (`ready`, not `starting`) is restarted.
159
+ * isolated [{ termId, key, busy }]: the serves of sessions, loops, workers and brains. One that runs a turn, is
160
+ * starting, or belongs to a live run (`busy`) is left for a later look.
161
+ *
162
+ * → { shared: 'keep' | 'restart', isolated: [termId], waiting: [termId] }
163
+ */
164
+ export function staleServePlan({ current = null, shared = null, isolated = [] } = {}) {
165
+ const plan = { shared: 'keep', isolated: [], waiting: [] };
166
+ if (!current) return plan;
167
+ if (shared?.managed && shared.ready && !shared.starting && shared.key && shared.key !== current) plan.shared = 'restart';
168
+ for (const serve of isolated) {
169
+ if (!serve?.termId || !serve.key || serve.key === current) continue;
170
+ (serve.busy ? plan.waiting : plan.isolated).push(serve.termId);
171
+ }
172
+ return plan;
173
+ }
@@ -88,6 +88,7 @@ export async function disconnect() {
88
88
  _stopRequested = true;
89
89
  if (_abort) { try { _abort.abort(); } catch {} }
90
90
  _abort = null;
91
+ try { _client?.dispose?.(); } catch {}
91
92
  _client = null;
92
93
  _port = null;
93
94
  _password = null;
@@ -211,6 +212,8 @@ export const EXTRA_CLIENT_METHODS = Object.freeze({
211
212
  mcp: ['add'],
212
213
  lsp: ['status'],
213
214
  formatter: ['status'],
215
+ // The shell commands of tool calls: a session's list and a command's output in pages.
216
+ shell: ['list', 'output'],
214
217
  });
215
218
 
216
219
  function extraGroups(getRaw) {
@@ -369,7 +372,7 @@ export function createClientInstance({ port, clientFactory = createOpencode2Clie
369
372
  if (!connected) throw new Error('OpenCode isolated event stream did not become ready');
370
373
  return true;
371
374
  },
372
- stop() { stopRequested = true; if (abort) { try { abort.abort(); } catch {} } abort = null; client = null; },
375
+ stop() { stopRequested = true; if (abort) { try { abort.abort(); } catch {} } abort = null; try { client?.dispose?.(); } catch {} client = null; },
373
376
  isConnected: () => connected,
374
377
  session: {
375
378
  list: (p = {}) => unwrap(req().session.list(clean(p))),
@@ -34,6 +34,7 @@
34
34
  import { OPENCODE_SESSION_TABLES } from './opencode-db-schema.js';
35
35
  import { opencodeMcpServerEntry } from './opencode-config.js';
36
36
  import { storedToolList } from './tool-lists.js';
37
+ import { readSafeShellOutputPage, readShellOutputPage, SHELL_OUTPUT_PAGE_BYTES } from './opencode-shell-read.js';
37
38
  import { statSync } from 'node:fs';
38
39
  import { LOCATION_MISSING_CODE, locationNotFoundMessage } from '../public/shared/ocp-v2/ocp-v2-location-logic.js';
39
40
 
@@ -253,6 +254,37 @@ async function sessionStatus(msg, deps) {
253
254
  return { status: r.status, data: { status: statusForSession(r.data, sessionIdOf(msg)) } };
254
255
  }
255
256
 
257
+ // ── The shell commands of a session's tool calls ────────────────────────────
258
+ // OpenCode 2 no longer sends a command's output with the tool call: it keeps it
259
+ // in a file, read in pages by byte position while the command runs and after.
260
+
261
+ /** The most a `shell:output` request reads at once. */
262
+ export { SHELL_OUTPUT_PAGE_BYTES };
263
+
264
+ /** The session's commands as its event stream told them (`{ id, status, command, callID, background, … }`). */
265
+ async function shellList(msg, deps) {
266
+ const r = await deps.bound(sessionKeyOf(msg)).extra.shell.list({ sessionID: sessionIdOf(msg) });
267
+ return { status: r.status, data: Array.isArray(r.data) ? r.data : [] };
268
+ }
269
+
270
+ /**
271
+ * A page of one command's output. Only a command of the session the request names is read (`shellId` is the
272
+ * page's word). `cursor`: the byte to read from; `tail`: instead, the last so many bytes (a panel that opens
273
+ * on a command with a long output starts at its end).
274
+ */
275
+ async function shellOutput(msg, deps) {
276
+ const shellId = typeof msg.shellId === 'string' ? msg.shellId : '';
277
+ if (!shellId) return failure(400, 'shellId required');
278
+ const extra = deps.bound(sessionKeyOf(msg)).extra;
279
+ const listed = await extra.shell.list({ sessionID: sessionIdOf(msg) });
280
+ const known = (Array.isArray(listed.data) ? listed.data : []).find((shell) => shell.id === shellId);
281
+ if (!known) return failure(404, 'That command is not one of this session.');
282
+ // Scrubbed on the whole window around the page, as the Assistant reads it (lib/opencode-shell-read.js
283
+ // readSafeShellOutputPage): each page scrubbed on its own would let a secret through that the panel joins.
284
+ const read = (q) => readShellOutputPage(extra.shell, { shellID: shellId, directory: directoryOf(msg), cursor: q.cursor, limit: q.limit }, { errorText: proxyErrorText });
285
+ return readSafeShellOutputPage(read, { cursor: msg.cursor, tail: msg.tail, limit: msg.limit, running: known.status === 'running' });
286
+ }
287
+
256
288
  // An MCP server as OpenCode 2 takes it (`mcp.servers.<name>`, lib/opencode-config.js), from what SynaBun
257
289
  // describes as { command, args, env } or { url, headers }: type local with the command as one array and its
258
290
  // `environment`, or type remote. Every word goes through as it is: an argument may be empty or carry spaces on
@@ -745,6 +777,8 @@ const HANDLERS = {
745
777
  },
746
778
  'session:compact': { session: true, run: compactSession },
747
779
  'session:status': { session: true, run: sessionStatus },
780
+ 'shell:list': { session: true, run: shellList },
781
+ 'shell:output': { session: true, run: shellOutput },
748
782
  'session:todo': { session: true, run: sessionTodo },
749
783
  'permission:reply': { run: permissionReply },
750
784
  'permission:list': { run: permissionList },