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
@@ -46,6 +46,10 @@ const SYSTEM_ENTRY = 'synabun-system';
46
46
  const PAGE_LIMIT = 200;
47
47
  const MAX_PAGES = 50;
48
48
  const WAIT_TIMEOUT_MS = 30 * 60 * 1000;
49
+ /** How many checks of a turn that is not held waitForTurn makes before it gives up (an error, never success). */
50
+ const WAIT_ROUNDS_MAX = 1000;
51
+ /** How often a held turn is looked at again. */
52
+ const HELD_POLL_MS = 500;
49
53
 
50
54
  const str = (v) => (typeof v === 'string' ? v : v == null ? '' : String(v));
51
55
  const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
@@ -65,7 +69,11 @@ export function vcsModeToV2(mode) {
65
69
  * `baseUrl` of the serve and the launch's `password`. `version` is the serve's
66
70
  * (sessions carry it), `fetchImpl` a fetch (tests pass a fixture's).
67
71
  */
68
- export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThis.fetch, version = '' } = {}) {
72
+ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThis.fetch, version = '', timing = {} } = {}) {
73
+ // `timing`: tests shorten the waits (heldPollMs, waitRoundsMax, waitPauseMs, heldSettleMs, heldRecheckMs, heldConfirmMs).
74
+ const HELD_POLL = Number(timing.heldPollMs) > 0 ? Number(timing.heldPollMs) : HELD_POLL_MS;
75
+ const ROUNDS_MAX = Number(timing.waitRoundsMax) > 0 ? Number(timing.waitRoundsMax) : WAIT_ROUNDS_MAX;
76
+ const WAIT_PAUSE = Number(timing.waitPauseMs) > 0 ? Number(timing.waitPauseMs) : 200;
69
77
  if (!baseUrl) throw new Error('createOpencode2Client: baseUrl required');
70
78
  const root = String(baseUrl).replace(/\/+$/, '');
71
79
  const auth = password ? basicAuthHeader(password) : null;
@@ -254,6 +262,8 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
254
262
  async function sendPrompt(params = {}, options = {}) {
255
263
  const { sessionID, model, variant, agent, system, noReply } = params;
256
264
  if (!sessionID) return { result: { data: undefined, error: { message: 'sessionID required' }, response: { status: 400, ok: false } } };
265
+ // The user's turn: a wake-up a Stop left pending must not interrupt it.
266
+ if (noReply !== true) forgetStoppedWake(sessionID);
257
267
  const failed = await prepare(sessionID, { model, variant, agent, system });
258
268
  if (failed) return { result: failed };
259
269
  const { body, synthetic } = promptBody(params);
@@ -286,10 +296,19 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
286
296
  */
287
297
  async function waitForTurn(sessionID, { since, signal, directory, quietEnds = false } = {}) {
288
298
  const base = `/api/session/${encodeURIComponent(sessionID)}`;
289
- for (let round = 0; round < 1000; round++) {
299
+ // `round` counts the checks of a turn that is not held: time held for a command the model waits for (a long
300
+ // test run) is bounded by `signal` alone, never by this budget (review B4: 1,000 held polls of 500 ms ran it
301
+ // out after 8 min 20 s, and running out read as the end of the turn).
302
+ for (let round = 0; round < ROUNDS_MAX;) {
290
303
  const waited = await call('POST', `/api/experimental/session/${encodeURIComponent(sessionID)}/wait`, { signal });
291
304
  if (waited.error) return waited;
292
305
  if (!since) return null;
306
+ // At rest for OpenCode, but a command the model waits for still runs: the turn is not over (a held turn).
307
+ if (translator.held(sessionID)) {
308
+ await pause(HELD_POLL, signal);
309
+ continue;
310
+ }
311
+ round += 1;
293
312
  const info = await call('GET', base, { signal });
294
313
  if (info.error) return info;
295
314
  if (Number(info.data?.data?.time?.idle) >= since) return null;
@@ -301,9 +320,10 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
301
320
  const pending = Array.isArray(queued.data?.data) && queued.data.data.length > 0;
302
321
  if (!queued.error && !active.error && !pending && !obj(active.data?.data)[sessionID]) return null;
303
322
  }
304
- await new Promise((resolveWait) => setTimeout(resolveWait, 200));
323
+ await pause(WAIT_PAUSE, signal);
305
324
  }
306
- return null;
325
+ // Out of checks with the turn still not over: said as a failure, never taken for its end.
326
+ return { data: undefined, error: { name: 'TurnWaitExhausted', message: 'OpenCode did not say the turn was over: SynaBun stopped waiting for it.' }, response: { status: 504, ok: false } };
307
327
  }
308
328
 
309
329
  /**
@@ -345,6 +365,7 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
345
365
  * the command's prompt carries.
346
366
  */
347
367
  async function runCommand({ sessionID, command, arguments: args, agent, model, variant, parts, directory } = {}, options = {}) {
368
+ forgetStoppedWake(sessionID);
348
369
  const failed = await prepare(sessionID, { model, variant, agent });
349
370
  if (failed) return failed;
350
371
  const { body: attached } = promptBody({ parts });
@@ -360,6 +381,17 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
360
381
  return replyOf(sessionID, { directory, before, latest: false });
361
382
  }
362
383
 
384
+ /** A wait `signal` ends early (its rejection is the caller's, as a call's would be). */
385
+ function pause(ms, signal) {
386
+ return new Promise((resolveWait, rejectWait) => {
387
+ if (signal?.aborted) { rejectWait(signal.reason ?? new Error('aborted')); return; }
388
+ const done = () => { signal?.removeEventListener?.('abort', stop); resolveWait(); };
389
+ const timer = setTimeout(done, ms);
390
+ const stop = () => { clearTimeout(timer); rejectWait(signal.reason ?? new Error('aborted')); };
391
+ signal?.addEventListener?.('abort', stop, { once: true });
392
+ });
393
+ }
394
+
363
395
  // ── Events ──
364
396
 
365
397
  /** `global.event()`: OpenCode 2's /api/event, translated, as `{ stream }` of `{ directory, payload }`. */
@@ -375,11 +407,33 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
375
407
  }
376
408
  const reader = res.body.getReader();
377
409
  const decoder = new TextDecoder();
410
+ // What this client says by itself (the end of a held turn: releaseHeld) reaches the reader between two events
411
+ // of OpenCode's, never out of a read that is under way.
412
+ const queue = [];
413
+ let wake = null;
414
+ const push = (events) => {
415
+ queue.push(...events);
416
+ const resume = wake;
417
+ wake = null;
418
+ resume?.();
419
+ };
420
+ streams.add(push);
421
+ // A stream (re)opened: what OpenCode said while none was open is unknown, so no wake-up a Stop left pending can
422
+ // be told from the user's next start any more (review S2).
423
+ stoppedWakes.clear();
378
424
  async function* stream() {
379
425
  let buffer = '';
426
+ let pending = null;
380
427
  try {
381
428
  while (true) {
382
- const { value, done } = await reader.read();
429
+ while (queue.length) yield queue.shift();
430
+ if (!pending) pending = reader.read();
431
+ const woken = new Promise((resolveWake) => { wake = resolveWake; });
432
+ const result = await Promise.race([pending, woken.then(() => null)]);
433
+ wake = null;
434
+ if (!result) continue;
435
+ pending = null;
436
+ const { value, done } = result;
383
437
  if (done) break;
384
438
  buffer += decoder.decode(value, { stream: true });
385
439
  let cut;
@@ -390,16 +444,281 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
390
444
  if (!data) continue;
391
445
  let event;
392
446
  try { event = JSON.parse(data); } catch { continue; }
447
+ if (event && typeof event.type === 'string') stopWoken(event);
393
448
  for (const translated of translator.translate(event)) yield translated;
449
+ if (event?.type === 'shell.exited' || event?.type === 'shell.deleted') watchHeld(HELD_SETTLE_MS);
450
+ else if (event?.type === 'session.execution.succeeded') watchHeld();
394
451
  }
395
452
  }
396
453
  } finally {
454
+ streams.delete(push);
397
455
  try { reader.releaseLock(); } catch { /* already released */ }
398
456
  }
399
457
  }
400
458
  return { stream: stream() };
401
459
  }
402
460
 
461
+ // ── Commands that run on after their tool call (lib/opencode2-translate.js: a held turn) ──
462
+
463
+ const streams = new Set();
464
+ const inject = (events) => { if (events.length) for (const push of streams) push(events); };
465
+
466
+ /**
467
+ * Is OpenCode done with the held turn of `sessionID`: no execution, none of the commands the turn waits for still
468
+ * running, and no notification of one queued for the model? null when it cannot be asked. Only the waited
469
+ * commands count (review S1): a server the model sent to the background itself runs on for good and holds
470
+ * nothing; and between a command's end and the start OpenCode makes for it, its notification sits in the inbox.
471
+ */
472
+ async function sessionSettled(sessionID) {
473
+ const directory = translator.sessionDirectory(sessionID);
474
+ const waited = new Set(translator.heldShellIds(sessionID));
475
+ const [active, jobs, inbox] = await Promise.all([
476
+ call('GET', '/api/session/active', { query: located(directory) }),
477
+ call('GET', '/api/experimental/job', { query: located(directory, { sessionID }) }),
478
+ call('GET', `/api/session/${encodeURIComponent(sessionID)}/inbox`, { query: located(directory) }),
479
+ ]).catch(() => [null, null, null]);
480
+ if (!active || active.error || !jobs || jobs.error || !inbox || inbox.error) return null;
481
+ if (obj(active.data?.data)[sessionID]) return false;
482
+ const queued = Array.isArray(inbox.data?.data) ? inbox.data.data : [];
483
+ if (queued.length) return false;
484
+ const jobId = (job) => str(job?.shellID || job?.jobID || job?.id);
485
+ return !(Array.isArray(jobs.data?.data) ? jobs.data.data : []).some((job) => job?.status === 'running' && waited.has(jobId(job)));
486
+ }
487
+
488
+ /**
489
+ * A held turn ends when its command exits and OpenCode starts the session again. Should that start never come
490
+ * (OpenCode itself says the session is at rest and holds no command of it), the turn is over: said here.
491
+ */
492
+ async function releaseStale(sessionID) {
493
+ if (disposed || !translator.held(sessionID)) return false;
494
+ if (await sessionSettled(sessionID) !== true) return false;
495
+ // Between a command's end and the start OpenCode makes for it the session is at rest for a moment: asked twice.
496
+ await new Promise((resolveWait) => { const timer = setTimeout(resolveWait, HELD_CONFIRM_MS); timer.unref?.(); });
497
+ if (disposed || !translator.held(sessionID) || await sessionSettled(sessionID) !== true || !translator.held(sessionID) || disposed) return false;
498
+ inject(translator.release(sessionID));
499
+ return true;
500
+ }
501
+ // While a turn is held, OpenCode is asked now and then whether it still backs it (an event the stream lost must
502
+ // not leave a session busy for good), and sooner after a command's end that should have started the session.
503
+ const HELD_SETTLE_MS = Number(timing.heldSettleMs) > 0 ? Number(timing.heldSettleMs) : 4000;
504
+ const HELD_RECHECK_MS = Number(timing.heldRecheckMs) > 0 ? Number(timing.heldRecheckMs) : 30000;
505
+ const HELD_CONFIRM_MS = Number(timing.heldConfirmMs) > 0 ? Number(timing.heldConfirmMs) : 1500;
506
+ let heldWatch = null;
507
+ let heldWatchAt = 0;
508
+ // A client that was let go (its serve stopped, its wrapper stopped) asks OpenCode nothing more (review S1).
509
+ let disposed = false;
510
+ function dispose() {
511
+ disposed = true;
512
+ if (heldWatch) clearTimeout(heldWatch);
513
+ heldWatch = null;
514
+ stoppedWakes.clear();
515
+ stoppedShells.clear();
516
+ for (const id of [...abandonedShells.keys()]) dropAbandoned(id);
517
+ userQueued.clear();
518
+ }
519
+ function watchHeld(ms = HELD_RECHECK_MS) {
520
+ if (disposed || !translator.heldSessions().length) return;
521
+ const at = Date.now() + ms;
522
+ if (heldWatch) {
523
+ if (at >= heldWatchAt) return;
524
+ clearTimeout(heldWatch);
525
+ }
526
+ heldWatchAt = at;
527
+ heldWatch = setTimeout(async () => {
528
+ heldWatch = null;
529
+ if (disposed) return;
530
+ for (const sessionID of translator.heldSessions()) await releaseStale(sessionID).catch(() => false);
531
+ watchHeld();
532
+ }, ms);
533
+ heldWatch.unref?.();
534
+ }
535
+
536
+ /**
537
+ * Stop a session. OpenCode's interrupt ends an execution and leaves the commands in the background running
538
+ * (checked on 2.3.2: `{ interrupted: false }` on a session at rest, the command goes on), so those are ended
539
+ * here, one by one, and a turn held for them is ended as a stopped one. OpenCode then tells the model that its
540
+ * command is gone and starts the session for that, a moment or seconds later: that execution is the stopped
541
+ * turn's too, and is interrupted when its start arrives on the event stream (`stopWoken`).
542
+ */
543
+ async function abortSession(sessionID, { force = false } = {}) {
544
+ const base = `/api/session/${encodeURIComponent(sessionID)}`;
545
+ // An execution still at work with a command in the background: the commands are ended first, and the execution
546
+ // is interrupted only once they are. Interrupted first, its end would reach the panels as the end of the turn
547
+ // even when a removal then fails (the turn must stay on while its command runs). A held turn has no execution
548
+ // to interrupt: as before, the interrupt goes first.
549
+ const deleteFirst = !force && stopNeedsKill(sessionID) && !translator.held(sessionID);
550
+ let first = deleteFirst ? null : await call('POST', `${base}/interrupt`);
551
+ const running = translator.backgroundShells(sessionID);
552
+ if (!running.length) {
553
+ if (!first) first = await call('POST', `${base}/interrupt`);
554
+ return map(first, (body) => body?.interrupted !== false);
555
+ }
556
+ const directory = translator.sessionDirectory(sessionID);
557
+ const until = Date.now() + STOPPED_SHELL_MS;
558
+ for (const shell of running) if (!abandonedShells.has(shell.id)) stoppedShells.set(shell.id, { until, sessionID });
559
+ // Each removal is checked: a command whose end is not confirmed (an HTTP error, a network failure) still runs,
560
+ // so it is never marked killed, the turn stays held for it, and the caller is told which (review B3). A 404 is
561
+ // a command OpenCode no longer holds: ended.
562
+ const removals = await Promise.all(running.map((shell) => removeShell(shell.id, directory)));
563
+ const why = new Map(running.map((shell, i) => [shell.id, removals[i]]));
564
+ // A command an earlier "Stop anyway" gave up on holds no turn: its removal is tried again here, but it never
565
+ // fails the Stop of a later turn.
566
+ const left = running.filter((shell, i) => removals[i] !== true && !abandonedShells.has(shell.id));
567
+ for (const shell of left) stoppedShells.delete(shell.id);
568
+ if (left.length && force) {
569
+ // "Stop anyway" (offered after a second failed Stop): the turn ends here while the command may still run on
570
+ // the machine. It holds nothing from now on, its removal is tried again in the background, and the start
571
+ // OpenCode makes for its notification (when it ends, or when a removal works) is interrupted like a Stop's.
572
+ for (const shell of left) abandonShell(shell.id, sessionID, directory);
573
+ const ids = left.map((shell) => shell.id);
574
+ inject([...translator.unhold(ids), ...translator.release(sessionID, { aborted: true, running: ids })]);
575
+ return { data: { stopped: true, abandoned: left.map((shell) => ({ id: shell.id, command: shell.command, reason: why.get(shell.id) })) }, error: undefined, response: { status: 200, ok: true } };
576
+ }
577
+ if (left.length) {
578
+ const names = left.map((shell) => shell.command || shell.id);
579
+ const reasons = [...new Set(left.map((shell) => why.get(shell.id)))].join('; ');
580
+ return {
581
+ data: undefined,
582
+ error: { name: 'ShellStopFailed', message: `Stop could not end ${left.length === 1 ? 'a command' : `${left.length} commands`} still running in the background: ${names.join(', ')} (${reasons}). Press Stop again.`, data: { shells: left.map((shell) => ({ id: shell.id, command: shell.command, reason: why.get(shell.id) })) } },
583
+ response: { status: 502, ok: false },
584
+ };
585
+ }
586
+ if (!first) first = await call('POST', `${base}/interrupt`);
587
+ inject(translator.release(sessionID, { aborted: true }));
588
+ return first.error ? first : { ...first, data: true };
589
+ }
590
+
591
+ // The commands a Stop removed, until OpenCode has told the model (shellID → { until, sessionID }), and the
592
+ // notification OpenCode queued for each (sessionID → { inboxID, until }): the execution that starts while that
593
+ // notification is still undelivered, with nothing of the user's queued after it, is the stopped turn's and is
594
+ // interrupted. Anything else ends the entry (review S2): the notification delivered, a prompt of the user's (queued
595
+ // in OpenCode or sent through this client), a lapse, a new event stream (what it missed is unknown).
596
+ const STOPPED_SHELL_MS = 60_000;
597
+ const STOPPED_WAKE_MS = 30_000;
598
+ const stoppedShells = new Map();
599
+ const stoppedWakes = new Map();
600
+ // The commands a "Stop anyway" gave up on (shellID → { sessionID, until, timer, attempt }): they may run for
601
+ // hours, so they wait for their notification until they end (then STOPPED_SHELL_MS more), at most ABANDONED_MS.
602
+ // Unlike a Stop's, a prompt of the user's does not forget them: the turn they belonged to is over either way.
603
+ const ABANDONED_MS = 24 * 60 * 60_000;
604
+ const KILL_RETRY_MS = Array.isArray(timing.killRetryMs) && timing.killRetryMs.length ? timing.killRetryMs.map(Number) : [2_000, 5_000, 15_000, 30_000, 60_000];
605
+ const abandonedShells = new Map();
606
+ // Prompts of the user's queued in OpenCode and not delivered yet (sessionID → inbox ids, '' for one sent through
607
+ // this client): a notification queued after one of them wakes nothing of its own (the next start is the user's).
608
+ const userQueued = new Map();
609
+ const noteUserQueued = (sessionID, inboxID) => userQueued.set(sessionID, new Set([...(userQueued.get(sessionID) || []), inboxID]));
610
+ /** Would a Stop of `sessionID` have commands to end (one it could fail to end)? Those a "Stop anyway" left do not count. */
611
+ function stopNeedsKill(sessionID) {
612
+ return translator.backgroundShells(str(sessionID)).some((shell) => !abandonedShells.has(shell.id));
613
+ }
614
+ /**
615
+ * A removal of a command: true once OpenCode says it is gone (a 404 too); otherwise why that is not confirmed (a
616
+ * short line: OpenCode's own message and status, or the network error), for the panel to say.
617
+ */
618
+ async function removeShell(shellID, directory) {
619
+ try {
620
+ const r = await call('DELETE', `/api/shell/${encodeURIComponent(shellID)}`, { query: located(directory) });
621
+ const status = Number(r.response?.status);
622
+ if (!r.error || status === 404) return true;
623
+ const said = str(r.error?.message || r.error?._tag || r.error?.name).trim().slice(0, 200);
624
+ return [said, status ? `HTTP ${status}` : ''].filter(Boolean).join(', ') || 'OpenCode did not confirm the end';
625
+ } catch (error) { return str(error?.cause?.code || error?.message || error).slice(0, 200) || 'OpenCode could not be reached'; }
626
+ }
627
+ /** Give up on ending `shellID` now; keep trying in the background until it ends or OpenCode removes it. */
628
+ function abandonShell(shellID, sessionID, directory) {
629
+ const entry = { sessionID, until: Date.now() + ABANDONED_MS, timer: null, attempt: 0 };
630
+ abandonedShells.set(shellID, entry);
631
+ const retry = () => {
632
+ if (disposed || abandonedShells.get(shellID) !== entry) return;
633
+ const delay = KILL_RETRY_MS[Math.min(entry.attempt, KILL_RETRY_MS.length - 1)];
634
+ entry.attempt += 1;
635
+ entry.timer = setTimeout(async () => {
636
+ entry.timer = null;
637
+ if (disposed || abandonedShells.get(shellID) !== entry) return;
638
+ // Ended by itself meanwhile: nothing to remove (its notification is still awaited).
639
+ if (translator.shell(shellID)?.status !== 'running') return;
640
+ if (Date.now() > entry.until) { abandonedShells.delete(shellID); return; }
641
+ if ((await removeShell(shellID, directory)) !== true) retry();
642
+ }, delay);
643
+ entry.timer.unref?.();
644
+ };
645
+ retry();
646
+ }
647
+ function dropAbandoned(shellID) {
648
+ const entry = abandonedShells.get(shellID);
649
+ if (!entry) return;
650
+ if (entry.timer) clearTimeout(entry.timer);
651
+ abandonedShells.delete(shellID);
652
+ }
653
+ /** A turn of the user's begins on `sessionID`: no wake-up of a Stop before it may interrupt it. */
654
+ function forgetStoppedWake(sessionID) {
655
+ const id = str(sessionID);
656
+ stoppedWakes.delete(id);
657
+ for (const [shellID, entry] of stoppedShells) if (entry.sessionID === id) stoppedShells.delete(shellID);
658
+ if (abandonedShells.size) noteUserQueued(id, '');
659
+ }
660
+ /** Called with every event of OpenCode's, as it arrives. */
661
+ function stopWoken(event) {
662
+ if (!stoppedShells.size && !stoppedWakes.size && !abandonedShells.size) return;
663
+ const data = obj(event?.data);
664
+ const sessionID = str(data.sessionID);
665
+ const now = Date.now();
666
+ for (const [id, entry] of stoppedShells) if (now > entry.until) stoppedShells.delete(id);
667
+ for (const [id, wake] of stoppedWakes) if (now > wake.until) stoppedWakes.delete(id);
668
+ for (const [id, entry] of abandonedShells) if (now > entry.until) dropAbandoned(id);
669
+ if ((event.type === 'shell.exited' || event.type === 'shell.deleted') && abandonedShells.has(str(data.id))) {
670
+ // Its end: the notification follows soon, or never (a serve that tells nothing).
671
+ const entry = abandonedShells.get(str(data.id));
672
+ if (entry.timer) { clearTimeout(entry.timer); entry.timer = null; }
673
+ entry.until = Math.min(entry.until, now + STOPPED_SHELL_MS);
674
+ return;
675
+ }
676
+ if (event.type === 'session.inbox.enqueued') {
677
+ const item = obj(data.item);
678
+ const shellID = item.type === 'synthetic' ? str(obj(obj(item.payload).metadata).shellID) : '';
679
+ if (shellID && abandonedShells.has(shellID)) {
680
+ dropAbandoned(shellID);
681
+ // A prompt of the user's waits in OpenCode before it: the start is theirs, and takes the notification along.
682
+ if (userQueued.get(sessionID)?.size) return;
683
+ stoppedWakes.set(sessionID, { inboxID: str(data.inboxID), until: now + STOPPED_WAKE_MS });
684
+ return;
685
+ }
686
+ const entry = shellID ? stoppedShells.get(shellID) : undefined;
687
+ if (entry === undefined) {
688
+ // Something else queued after the notification (the user's prompt): the next start may be theirs.
689
+ if (item.type !== 'synthetic') {
690
+ stoppedWakes.delete(sessionID);
691
+ if (abandonedShells.size) noteUserQueued(sessionID, str(data.inboxID));
692
+ }
693
+ return;
694
+ }
695
+ stoppedShells.delete(shellID);
696
+ stoppedWakes.set(sessionID, { inboxID: str(data.inboxID), until: now + STOPPED_WAKE_MS });
697
+ } else if (event.type === 'session.execution.started') {
698
+ userQueued.delete(sessionID);
699
+ if (!stoppedWakes.delete(sessionID)) return;
700
+ call('POST', `/api/session/${encodeURIComponent(sessionID)}/interrupt`).catch(() => {});
701
+ } else if (event.type === 'session.inbox.delivered') {
702
+ // Delivered without a start this client saw: the wake-up went by; nothing later is it.
703
+ if (stoppedWakes.get(sessionID)?.inboxID === str(data.inboxID)) stoppedWakes.delete(sessionID);
704
+ userQueued.get(sessionID)?.delete(str(data.inboxID));
705
+ } else if (event.type === 'session.deleted') {
706
+ forgetStoppedWake(sessionID);
707
+ }
708
+ }
709
+
710
+ /** A page of a command's output (stdout and stderr as written, in order), from the byte `cursor`. */
711
+ async function shellOutput({ shellID, directory, cursor = 0, limit } = {}) {
712
+ const id = str(shellID);
713
+ if (!id) return { data: undefined, error: { message: 'shellID required' }, response: { status: 400, ok: false } };
714
+ const where = directory || translator.sessionDirectory(translator.shell(id)?.sessionID);
715
+ const read = await call('GET', `/api/shell/${encodeURIComponent(id)}/output`, { query: located(where, { cursor: Math.max(0, Number(cursor) || 0), ...(Number(limit) > 0 ? { limit: Math.floor(Number(limit)) } : {}) }) });
716
+ return map(read, (body) => {
717
+ const page = obj(body?.data);
718
+ return { output: str(page.output), cursor: Number(page.cursor) || 0, size: Number(page.size) || 0, truncated: page.truncated === true };
719
+ });
720
+ }
721
+
403
722
  // ── Asks ──
404
723
 
405
724
  async function permissionSessionOf(requestID, directory) {
@@ -568,7 +887,8 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
568
887
  if (!removed.error) sessionState.delete(sessionID);
569
888
  return ok(removed, true);
570
889
  },
571
- abort: async ({ sessionID } = {}) => map(await call('POST', `/api/session/${encodeURIComponent(sessionID)}/interrupt`), (body) => body?.interrupted !== false),
890
+ // `force`: "Stop anyway", the turn ends even when a command in the background could not be ended.
891
+ abort: ({ sessionID, force } = {}) => abortSession(str(sessionID), { force: force === true }),
572
892
  messages: ({ sessionID, directory, limit } = {}) => messagesV1(sessionID, { directory, limit }),
573
893
  message: async ({ sessionID, messageID, directory } = {}) => {
574
894
  const read = await call('GET', `/api/session/${encodeURIComponent(sessionID)}/message/${encodeURIComponent(messageID)}`);
@@ -576,11 +896,16 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
576
896
  },
577
897
  prompt: (p, o) => prompt(p, o),
578
898
  promptAsync: (p, o) => promptAsync(p, o),
899
+ // A session held for a command in the background (OpenCode lists it as at rest) is busy here too: a reader
900
+ // that asks instead of listening (a reloaded panel) is told what the events said. A hold OpenCode no longer
901
+ // backs is ended first.
579
902
  status: async ({ directory } = {}) => {
903
+ for (const sessionID of translator.heldSessions()) await releaseStale(sessionID).catch(() => false);
580
904
  const active = await call('GET', '/api/session/active', { query: located(directory) });
581
905
  return map(active, (body) => {
582
906
  const out = {};
583
907
  for (const [id, status] of Object.entries(obj(body?.data))) out[id] = status?.type === 'running' ? { type: 'busy' } : { type: 'idle' };
908
+ for (const id of translator.heldSessions()) if (out[id]?.type !== 'busy') out[id] = { type: 'busy', background: true };
584
909
  return out;
585
910
  });
586
911
  },
@@ -605,6 +930,7 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
605
930
  init: async ({ sessionID } = {}) => ok(await call('POST', `/api/session/${encodeURIComponent(sessionID)}/command`, { body: { name: 'init', text: '' } }), true),
606
931
  command: (p, o) => runCommand(p, o),
607
932
  shell: async ({ sessionID, command, agent, model } = {}) => {
933
+ forgetStoppedWake(sessionID);
608
934
  const failed = await prepare(sessionID, { model, agent });
609
935
  if (failed) return failed;
610
936
  return ok(await call('POST', `/api/session/${encodeURIComponent(sessionID)}/shell`, { body: { command: String(command || '') } }), { info: null, parts: [] });
@@ -612,6 +938,10 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
612
938
  };
613
939
 
614
940
  const client = {
941
+ /** Let this client go: no more checks of held turns are scheduled, none that is due runs. */
942
+ dispose,
943
+ /** Would a Stop of the session have a command in the background to end (and so could it fail)? */
944
+ stopNeedsKill,
615
945
  global: {
616
946
  event: globalEvent,
617
947
  health: async () => map(await call('GET', '/api/info'), (body) => ({ healthy: true, version: str(body?.version) })),
@@ -785,6 +1115,11 @@ export function createOpencode2Client({ baseUrl, password, fetchImpl = globalThi
785
1115
  return map(info, () => ({ home: '', state: '', config: '', worktree: str(directory), directory: str(directory) }));
786
1116
  },
787
1117
  },
1118
+ // The shell commands of tool calls: which a session has (as its event stream told), and a command's output.
1119
+ shell: {
1120
+ list: async ({ sessionID } = {}) => ({ data: translator.shells(sessionID), error: undefined, response: { status: 200, ok: true } }),
1121
+ output: (params) => shellOutput(params),
1122
+ },
788
1123
  // A stateless one-shot (editor autocomplete, titles): OpenCode 2's generator.
789
1124
  generate: async ({ prompt: text, model, directory, signal } = {}) => {
790
1125
  const ref = modelRefToV2(model);