synabun 2.4.2 → 2.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +83 -34
  4. package/lib/release-npm-ci.mjs +23 -1
  5. package/mcp-server/dist/http.d.ts.map +1 -1
  6. package/mcp-server/dist/http.js +8 -1
  7. package/mcp-server/dist/http.js.map +1 -1
  8. package/mcp-server/dist/services/identity.d.ts +2 -0
  9. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  10. package/mcp-server/dist/services/identity.js +4 -0
  11. package/mcp-server/dist/services/identity.js.map +1 -1
  12. package/mcp-server/dist/services/memory-client.d.ts +5 -0
  13. package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
  14. package/mcp-server/dist/services/memory-client.js +21 -2
  15. package/mcp-server/dist/services/memory-client.js.map +1 -1
  16. package/mcp-server/dist/services/memory-writer.d.ts +3 -0
  17. package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
  18. package/mcp-server/dist/services/memory-writer.js +7 -1
  19. package/mcp-server/dist/services/memory-writer.js.map +1 -1
  20. package/mcp-server/dist/services/neural-interface.d.ts +11 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -18
  23. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  24. package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
  25. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  26. package/mcp-server/dist/services/typesafe-config.js +260 -8
  27. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  28. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  29. package/mcp-server/dist/tools/agents.d.ts +3 -1
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +11 -6
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
  35. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  37. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  38. package/mcp-server/dist/tools/browser-observe.js +113 -27
  39. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  40. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  41. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  42. package/mcp-server/dist/tools/browser-readers.js +17 -0
  43. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  44. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  45. package/mcp-server/dist/tools/remember.js +6 -2
  46. package/mcp-server/dist/tools/remember.js.map +1 -1
  47. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  48. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  49. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  50. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  51. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  52. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  53. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  54. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  55. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  56. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  57. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  58. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  59. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  60. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  61. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  62. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  64. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  65. package/mcp-server/package-lock.json +5 -5
  66. package/mcp-server/package.json +1 -1
  67. package/mcp-server/src/http.ts +8 -1
  68. package/mcp-server/src/services/identity.ts +5 -0
  69. package/mcp-server/src/services/memory-client.ts +32 -12
  70. package/mcp-server/src/services/memory-writer.ts +5 -2
  71. package/mcp-server/src/services/neural-interface.ts +66 -19
  72. package/mcp-server/src/services/typesafe-config.ts +268 -7
  73. package/mcp-server/src/tools/agents.ts +12 -6
  74. package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
  75. package/mcp-server/src/tools/browser-observe.ts +117 -28
  76. package/mcp-server/src/tools/browser-readers.ts +19 -0
  77. package/mcp-server/src/tools/remember.ts +6 -1
  78. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  79. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  80. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  81. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  82. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  83. package/neural-interface/i18n/en.json +189 -1
  84. package/neural-interface/i18n/pt-BR.json +196 -8
  85. package/neural-interface/lib/assistant-api.js +123 -0
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  88. package/neural-interface/lib/assistant-dispatch.js +302 -44
  89. package/neural-interface/lib/assistant-envelope.js +40 -0
  90. package/neural-interface/lib/assistant-memory.js +3 -1
  91. package/neural-interface/lib/assistant-persona.js +6 -0
  92. package/neural-interface/lib/assistant-router.js +18 -8
  93. package/neural-interface/lib/assistant-runtime.js +182 -11
  94. package/neural-interface/lib/assistant-task-prompt.js +15 -2
  95. package/neural-interface/lib/browser-connection-state.js +20 -0
  96. package/neural-interface/lib/browser-extension-adapter.js +221 -17
  97. package/neural-interface/lib/browser-extension-archive.js +149 -0
  98. package/neural-interface/lib/browser-extension-bridge.js +46 -10
  99. package/neural-interface/lib/browser-extension-folder.js +635 -76
  100. package/neural-interface/lib/browser-extension-package.js +201 -0
  101. package/neural-interface/lib/browser-extension-pin.js +84 -0
  102. package/neural-interface/lib/browser-extension-pin.json +35 -0
  103. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +111 -13
  104. package/neural-interface/lib/browser-extension-setup.js +108 -19
  105. package/neural-interface/lib/browser-extension-update.js +104 -0
  106. package/neural-interface/lib/browser-extraction.js +38 -14
  107. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  108. package/neural-interface/lib/claude-history.js +12 -1
  109. package/neural-interface/lib/cli-install.js +23 -3
  110. package/neural-interface/lib/cli-update-planner.js +67 -4
  111. package/neural-interface/lib/confined-fs.js +25 -0
  112. package/neural-interface/lib/coordination/operations.js +2 -0
  113. package/neural-interface/lib/db.js +39 -16
  114. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  115. package/neural-interface/lib/git-bash/manager.js +28 -3
  116. package/neural-interface/lib/git-status-runner.js +31 -3
  117. package/neural-interface/lib/loop-inventory.js +162 -0
  118. package/neural-interface/lib/loop-stall.js +74 -4
  119. package/neural-interface/lib/memory-session-capture.js +157 -66
  120. package/neural-interface/lib/native-loop-providers.js +82 -13
  121. package/neural-interface/lib/native-loop-runtime.js +23 -2
  122. package/neural-interface/lib/opencode-protocol.js +4 -2
  123. package/neural-interface/lib/opencode-shell-read.js +107 -0
  124. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  125. package/neural-interface/lib/opencode-turn-release.js +173 -0
  126. package/neural-interface/lib/opencode-v2-client.js +4 -1
  127. package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
  128. package/neural-interface/lib/opencode2-client.js +341 -6
  129. package/neural-interface/lib/opencode2-translate.js +161 -4
  130. package/neural-interface/lib/peer-identity.js +62 -16
  131. package/neural-interface/lib/session-cache-builder.js +66 -18
  132. package/neural-interface/lib/session-capture-gate.js +42 -0
  133. package/neural-interface/lib/session-indexer.js +28 -20
  134. package/neural-interface/lib/teams/scheduler.js +3 -2
  135. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  136. package/neural-interface/lib/ui-blob-api.js +14 -5
  137. package/neural-interface/lib/ui-blob-store.js +302 -39
  138. package/neural-interface/lib/whatsapp/bridge.js +52 -6
  139. package/neural-interface/package-lock.json +5 -5
  140. package/neural-interface/package.json +1 -1
  141. package/neural-interface/public/extension-setup.html +6 -2
  142. package/neural-interface/public/shared/agy/agy-panel.js +38 -10
  143. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  144. package/neural-interface/public/shared/assistant/asst-api.js +67 -0
  145. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  146. package/neural-interface/public/shared/assistant/asst-panel.js +354 -11
  147. package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
  148. package/neural-interface/public/shared/assistant/asst-render.js +343 -10
  149. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  150. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  151. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  152. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  153. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  154. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  155. package/neural-interface/public/shared/assistant/asst-styles.js +21 -0
  156. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  157. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  158. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  159. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  160. package/neural-interface/public/shared/browser-extension-updates.js +88 -0
  161. package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
  162. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  163. package/neural-interface/public/shared/extension-setup/es-page.js +25 -12
  164. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  165. package/neural-interface/public/shared/extension-update-view.js +34 -0
  166. package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
  167. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  168. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  169. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
  170. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  171. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
  172. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
  173. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
  174. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  175. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +350 -0
  176. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  177. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  178. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
  179. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  180. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  181. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  182. package/neural-interface/public/shared/settings/settings-browser-extension.js +61 -13
  183. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  184. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  185. package/neural-interface/public/shared/styles.css +4 -0
  186. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  187. package/neural-interface/public/shared/tray-auto-close.js +36 -6
  188. package/neural-interface/public/shared/ui-claude-panel.js +130 -1
  189. package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
  190. package/neural-interface/public/shared/ui-notifications.js +23 -4
  191. package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
  192. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  193. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  194. package/neural-interface/public/shared/worker-end.js +18 -0
  195. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  196. package/neural-interface/scripts/rebuild-pty.js +10 -0
  197. package/neural-interface/server.js +725 -308
  198. package/npm-shrinkwrap.json +5 -5
  199. package/package.json +1 -2
  200. package/browser-extension/content.js +0 -231
  201. package/browser-extension/engine.js +0 -658
  202. package/browser-extension/icons/icon-128.png +0 -0
  203. package/browser-extension/icons/icon-16.png +0 -0
  204. package/browser-extension/icons/icon-32.png +0 -0
  205. package/browser-extension/icons/icon-48.png +0 -0
  206. package/browser-extension/icons/status-off-16.png +0 -0
  207. package/browser-extension/icons/status-off-32.png +0 -0
  208. package/browser-extension/icons/status-off-48.png +0 -0
  209. package/browser-extension/icons/status-on-16.png +0 -0
  210. package/browser-extension/icons/status-on-32.png +0 -0
  211. package/browser-extension/icons/status-on-48.png +0 -0
  212. package/browser-extension/manifest.json +0 -58
  213. package/browser-extension/popup-strings.js +0 -250
  214. package/browser-extension/popup-view.js +0 -151
  215. package/browser-extension/popup.css +0 -166
  216. package/browser-extension/popup.html +0 -108
  217. package/browser-extension/popup.js +0 -359
  218. package/browser-extension/service-worker.js +0 -283
  219. package/browser-extension/setup-content.js +0 -36
  220. package/browser-extension/tokens.css +0 -326
@@ -228,12 +228,14 @@ async function readJson(res) {
228
228
  * 'error' something answered, but not OpenCode 2's API
229
229
  * Never throws.
230
230
  */
231
- export async function checkOpencodeServer({ port, password = null, fetchImpl = globalThis.fetch, timeoutMs = 2000, host = '127.0.0.1' } = {}) {
231
+ export async function checkOpencodeServer({ port, password = null, fetchImpl = globalThis.fetch, timeoutMs = 2000, host = '127.0.0.1', signal = null } = {}) {
232
232
  let res;
233
233
  try {
234
+ const timeout = AbortSignal.timeout(timeoutMs);
235
+ const reqSignal = signal ? AbortSignal.any([timeout, signal]) : timeout;
234
236
  res = await fetchImpl(`http://${host}:${port}/api/info`, {
235
237
  headers: { accept: 'application/json', ...(password ? { authorization: basicAuthHeader(password) } : {}) },
236
- signal: AbortSignal.timeout(timeoutMs),
238
+ signal: reqSignal,
237
239
  });
238
240
  } catch (error) {
239
241
  return { ok: false, version: null, state: 'down', error: String(error?.message || error) };
@@ -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 },