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
@@ -171,6 +171,9 @@ export function createAssistantApi({
171
171
  // The page secret (lib/page-session.js): a request without an agent pin is the owner's page only when it carries
172
172
  // this boot's cookie; a local process that merely sends no headers is nobody (never 'ui').
173
173
  pageSession = null,
174
+ // The Background tasks view of a Claude brain: lib/claude-bg-tasks.js over the brain's own transcript
175
+ // ({ list(identity), output(identity, q) } built in server.js). None: those routes answer 404.
176
+ backgroundTasks = null,
174
177
  // Whether a pin counts (lib/terminal-tokens.js verdict, server.js): (pin, req) → { accepted, code, error, httpStatus }.
175
178
  // A pin SynaBun gave a proof to (a run's terminal token, a brain's launch credential) counts only with it: a request
176
179
  // that names a worker's run, or a brain's id, without it is refused (403 TERMINAL_TOKEN_REQUIRED / _INVALID) instead
@@ -1046,6 +1049,43 @@ export function createAssistantApi({
1046
1049
  res.json(await dispatcher.sendTurn(req.params.runId, body.text ?? body.message, { origin, queue: body.queue !== false }));
1047
1050
  } catch (error) { sendError(res, error); }
1048
1051
  });
1052
+ // Steer: the user changed work in flight. With runId, that run's current turn is interrupted and the steer follows
1053
+ // (dispatcher.steerRun; the run must be this session's); without, the session's own brain is steered (the page only:
1054
+ // a brain never steers itself). → { ok, target: { kind, runId? }, interruptedTurn }.
1055
+ router.post('/steer', orchestrationGuard, async (req, res) => {
1056
+ try {
1057
+ const body = req.body || {};
1058
+ const caller = req.assistantCaller;
1059
+ const text = typeof body.text === 'string' ? body.text.trim() : '';
1060
+ if (!text) return res.status(400).json({ ok: false, code: 'MESSAGE_REQUIRED', error: 'text is required' });
1061
+ const runId = typeof (body.runId ?? body.run_id) === 'string' ? String(body.runId ?? body.run_id).trim() : '';
1062
+ // A brain's session is the one its credential proves, whatever the body says.
1063
+ const sessionId = caller.credentialed ? (caller.assistantSessionId || null) : (body.assistantSessionId || body.assistant_session_id || null);
1064
+ if (runId) {
1065
+ const run = dispatcher.get(runId);
1066
+ if (!run) return res.status(404).json({ ok: false, code: 'RUN_NOT_FOUND', error: `Unknown run ${runId}` });
1067
+ if (!sessionId && caller.kind !== 'ui') return res.status(404).json({ ok: false, code: 'SESSION_NOT_FOUND', error: 'The caller has no assistant session.' });
1068
+ if (sessionId && String(run.assistantSessionId || '') !== String(sessionId)) {
1069
+ return res.status(404).json({ ok: false, code: 'RUN_NOT_FOUND', error: `Run ${runId} does not belong to assistant session ${sessionId}` });
1070
+ }
1071
+ if (planRefusal(req, res, sessionId, 'steer a worker')) return;
1072
+ if (planState(req, sessionId) === 'plan' && planSendRefusal(res, run)) return;
1073
+ const from = caller.kind === 'ui' ? 'user' : 'assistant';
1074
+ try { await dispatcher.coverFollowUp?.(runId); } catch { /* steerRun decides */ }
1075
+ const steered = await dispatcher.steerRun(runId, text, { from, assistantSessionId: sessionId });
1076
+ return res.json({ ok: true, target: steered.target, interruptedTurn: steered.interruptedTurn, followUpId: steered.followUpId, run: steered.run });
1077
+ }
1078
+ if (caller.kind !== 'ui') return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Only the user\'s page steers the Assistant itself; a brain steers a worker with runId.' });
1079
+ if (!sessionId) return res.status(400).json({ ok: false, code: 'SESSION_REQUIRED', error: 'assistantSessionId is required' });
1080
+ if (typeof runtime?.steerBrain !== 'function') return res.status(503).json({ ok: false, code: 'STEER_UNAVAILABLE', error: 'This server cannot steer the Assistant yet; restart it.' });
1081
+ const out = await runtime.steerBrain(String(sessionId), { text, origin: 'ui' });
1082
+ if (!out?.ok) {
1083
+ const status = out?.code === 'SESSION_NOT_FOUND' ? 404 : out?.code === 'MESSAGE_REQUIRED' ? 400 : 409;
1084
+ return res.status(status).json({ ok: false, code: out?.code || 'STEER_FAILED', error: out?.message || 'The steer did not reach the Assistant.', interruptedTurn: !!out?.interruptedTurn });
1085
+ }
1086
+ res.json({ ok: true, target: { kind: 'brain' }, interruptedTurn: !!out.interruptedTurn });
1087
+ } catch (error) { sendError(res, error); }
1088
+ });
1049
1089
  router.post('/runs/:runId/permission', orchestrationGuard, (req, res) => {
1050
1090
  try {
1051
1091
  const body = req.body || {};
@@ -1169,6 +1209,89 @@ export function createAssistantApi({
1169
1209
  res.json({ ok: true, usage: runtime.usageView?.(id, task) ?? usage?.taskView(id, task) ?? null, budget: sessionBudgetView(id) });
1170
1210
  } catch (error) { sendError(res, error); }
1171
1211
  });
1212
+ // The shell commands of a session's OpenCode brain (which tool call each belongs to, whether it runs, how it
1213
+ // ended) and a page of what one printed: what the panel's terminal blocks show. The owner's page alone reads
1214
+ // them (this boot's page secret, no agent header): what a command printed is display data, so no brain and no
1215
+ // worker gets it here, and with it nothing of it reaches a model's context. The session in the path is the one
1216
+ // whose own brain is asked, and that brain reads only a command it ran itself (runtime.shellOutput).
1217
+ function shellReader(req, res) {
1218
+ const agent = ['x-synabun-terminal', 'x-synabun-assistant', 'x-synabun-role', 'x-synabun-brain-token', 'x-synabun-desktop-grant'].some((name) => req.get(name));
1219
+ if (agent || isGuestRequest(req) || callerContext(req).kind !== 'ui') { uiOnly(req, res, 'A command\'s output is shown in the user\'s own Assistant panel only.'); return false; }
1220
+ // The automation browser verifies as the owner while the owner's setting lets it act as owner; it still never
1221
+ // reads what a command printed (review S4): a page an agent drives would hand it to that agent's model.
1222
+ let fromAutomationBrowser = false;
1223
+ try { fromAutomationBrowser = typeof pageSession?.isAutomationBrowser === 'function' && pageSession.isAutomationBrowser(req) === true; } catch { fromAutomationBrowser = true; }
1224
+ if (fromAutomationBrowser) { res.status(403).json({ ok: false, code: 'WORKER_BROWSER', error: 'A command\'s output is shown in the owner\'s own browser or the app, never in SynaBun\'s automation browser.' }); return false; }
1225
+ return true;
1226
+ }
1227
+ router.get('/sessions/:id/shells', noStore, (req, res) => {
1228
+ if (!requireRuntime(res) || !shellReader(req, res)) return;
1229
+ const shells = typeof runtime.shellList === 'function' ? runtime.shellList(req.params.id) : null;
1230
+ if (!shells) return res.status(404).json({ ok: false, code: 'SESSION_NOT_FOUND', error: `Unknown assistant session ${req.params.id}` });
1231
+ res.json({ ok: true, shells });
1232
+ });
1233
+ router.get('/sessions/:id/shells/:shellId/output', noStore, async (req, res) => {
1234
+ if (!requireRuntime(res) || !shellReader(req, res)) return;
1235
+ if (typeof runtime.shellOutput !== 'function') return res.status(404).json({ ok: false, code: 'SHELL_OUTPUT_GONE', error: 'The output of that command is no longer available.' });
1236
+ const shellId = String(req.params.shellId || '');
1237
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(shellId)) return res.status(400).json({ ok: false, code: 'SHELL_ID_INVALID', error: 'That is not a command of this conversation.' });
1238
+ const number = (value) => (typeof value === 'string' && /^\d{1,15}$/.test(value) ? Number(value) : undefined);
1239
+ try {
1240
+ const page = await runtime.shellOutput(req.params.id, { shellId, cursor: number(req.query.cursor), tail: number(req.query.tail), limit: number(req.query.limit) });
1241
+ if (!page || page.ok === false) return res.status(Number(page?.status) >= 400 ? Number(page.status) : 502).json({ ok: false, code: page?.code || 'SHELL_OUTPUT_FAILED', error: page?.error || 'The output could not be read.' });
1242
+ res.json({ ok: true, ...page.data });
1243
+ } catch (error) { sendError(res, error); }
1244
+ });
1245
+ // The background shells and watches of a session's Claude brain (the panel's Background tasks view), a page of
1246
+ // what one printed, and the owner's Stop. The same reader as a command's output (shellReader): the owner's page
1247
+ // alone, never a brain, a worker or the automation browser. The brain named in the path is the one asked, and its
1248
+ // transcript is the only one read (lib/claude-bg-tasks.js: only the file it reported for a task it ran).
1249
+ const bgTaskId = (value) => (/^[A-Za-z0-9_-]{1,128}$/.test(String(value || '')) ? String(value) : '');
1250
+ function bgSource(req, res) {
1251
+ if (!requireRuntime(res) || !shellReader(req, res)) return null;
1252
+ const source = typeof runtime.backgroundTaskSource === 'function' ? runtime.backgroundTaskSource(req.params.id) : null;
1253
+ if (source === null && typeof runtime.getSession === 'function' && !runtime.getSession(req.params.id, { transcript: false })) {
1254
+ res.status(404).json({ ok: false, code: 'SESSION_NOT_FOUND', error: `Unknown assistant session ${req.params.id}` });
1255
+ return null;
1256
+ }
1257
+ if (!source || !backgroundTasks) { res.json({ ok: true, tasks: [], live: null, supported: false }); return null; }
1258
+ return source;
1259
+ }
1260
+ router.get('/sessions/:id/background-tasks', noStore, (req, res) => {
1261
+ const source = bgSource(req, res);
1262
+ if (!source) return;
1263
+ try {
1264
+ const listed = backgroundTasks.list(source);
1265
+ res.json({ ok: true, supported: true, tasks: listed?.tasks || [], live: Array.isArray(source.live) ? source.live : null });
1266
+ } catch (error) {
1267
+ if (Number(error?.status) === 404) return res.json({ ok: true, supported: true, tasks: [], live: Array.isArray(source.live) ? source.live : null });
1268
+ sendError(res, error);
1269
+ }
1270
+ });
1271
+ router.get('/sessions/:id/background-tasks/:taskId/output', noStore, async (req, res) => {
1272
+ const taskId = bgTaskId(req.params.taskId);
1273
+ if (!taskId) { if (requireRuntime(res) && shellReader(req, res)) res.status(400).json({ ok: false, code: 'TASK_ID_INVALID', error: 'That is not a background task of this conversation.' }); return; }
1274
+ const source = bgSource(req, res);
1275
+ if (!source) return;
1276
+ const number = (value) => (typeof value === 'string' && /^\d{1,15}$/.test(value) ? Number(value) : undefined);
1277
+ try {
1278
+ const running = Array.isArray(source.live) ? source.live.some((t) => t.task_id === taskId) : null;
1279
+ const page = await backgroundTasks.output(source, { taskId, cursor: number(req.query.cursor), tail: number(req.query.tail), limit: number(req.query.limit), running });
1280
+ if (!page || page.ok === false) return res.status(Number(page?.status) >= 400 ? Number(page.status) : 502).json({ ok: false, code: page?.code || 'OUTPUT_FAILED', error: page?.error || 'The output could not be read.' });
1281
+ res.json({ ok: true, ...page.data });
1282
+ } catch (error) { sendError(res, error); }
1283
+ });
1284
+ router.post('/sessions/:id/background-tasks/:taskId/stop', noStore, async (req, res) => {
1285
+ if (!requireRuntime(res) || !shellReader(req, res)) return;
1286
+ const taskId = bgTaskId(req.params.taskId);
1287
+ if (!taskId) return res.status(400).json({ ok: false, code: 'TASK_ID_INVALID', error: 'That is not a background task of this conversation.' });
1288
+ if (typeof runtime.stopBackgroundTask !== 'function') return res.status(404).json({ ok: false, code: 'NOT_SUPPORTED', error: 'Stopping a background task needs the SynaBun server restart.' });
1289
+ try {
1290
+ const out = await runtime.stopBackgroundTask(req.params.id, taskId);
1291
+ if (!out || out.ok === false) return res.status(Number(out?.status) >= 400 ? Number(out.status) : 409).json({ ok: false, code: out?.code || 'STOP_FAILED', error: out?.error || 'The task could not be stopped.' });
1292
+ res.json({ ok: true, taskId });
1293
+ } catch (error) { sendError(res, error); }
1294
+ });
1172
1295
  router.get('/sessions/:id', (req, res) => {
1173
1296
  if (!requireRuntime(res)) return;
1174
1297
  const session = runtime.getSession(req.params.id, { transcript: req.query.transcript !== '0', limit: clampInt(req.query.limit, 1, 2000, 400) });
@@ -215,6 +215,16 @@ export function createClaudeBrain({ session, sink, deps = {}, persona = '', hook
215
215
  // Background agents or scheduled wakeups still running after their turn
216
216
  // ended. Not "busy" (the mailbox may deliver), but disposing would kill them.
217
217
  hasPendingWork() { return !!inner._hasPendingWork?.(); },
218
+ // The live background set the CLI reports (background_tasks_changed), for the panel's Background tasks view;
219
+ // null while no process runs (the set is per process).
220
+ backgroundTasks() { return inner.q && inner._bgTasks instanceof Map ? [...inner._bgTasks.values()].map(t => ({ ...t })) : null; },
221
+ // The owner's Stop of one of them, through the SDK's own stop (never a kill of a process by hand).
222
+ async stopTask(taskId) {
223
+ const q = inner.q;
224
+ if (!q || typeof q.stopTask !== 'function') return { ok: false, error: q ? 'Not supported by this Claude Code version' : 'Nothing of this conversation runs now: the task has already ended.' };
225
+ await q.stopTask(String(taskId));
226
+ return { ok: true };
227
+ },
218
228
  identity() {
219
229
  return {
220
230
  providerSessionId: inner.sessionId || providerSessionId, providerThreadId: null, accountId: brain.accountId || 'default',
@@ -13,9 +13,10 @@ import { dirname, resolve } from 'node:path';
13
13
  import { fileURLToPath, pathToFileURL } from 'node:url';
14
14
  import { normalizeOpenCodeModel } from '../native-loop-providers.js';
15
15
  import { agentOf, mcpServersOf, opencodeConfigFilePath, readOpencodeConfigDocument, setAgent, setMcpServer, withPlugin, withoutPlugin } from '../opencode-config.js';
16
- import { createOpenCodeEnvelopeTranslator, opencodeControlResponse } from '../assistant-envelope.js';
16
+ import { createOpenCodeEnvelopeTranslator, opencodeControlResponse, opencodeShellView } from '../assistant-envelope.js';
17
17
  import { opencodePlanPermission, opencodeReadOnlyPermission, planDenyMessage, readOnlyDenyMessage } from '../assistant-plan-permissions.js';
18
18
  import { planModeInstructions } from '../assistant-persona.js';
19
+ import { readShellOutputPage, SHELL_OUTPUT_GONE_TEXT } from '../opencode-shell-read.js';
19
20
  import { waitForSynabunTools, synabunConfigured, synabunToolsTimeoutText, OPENCODE_MCP_READY_TIMEOUT_MS, OPENCODE_MCP_SETTLE_MS, OPENCODE_MCP_LIST_GRACE_MS } from '../opencode-mcp-ready.js';
20
21
  export { synabunMcpState } from '../opencode-mcp-ready.js';
21
22
 
@@ -154,6 +155,9 @@ export function patchOpenCodeAssistantConfig(xdgRoot, { persona = '', role = 'as
154
155
  }
155
156
 
156
157
 
158
+ /** How many shell commands of its tool calls a brain remembers (a command still running is never forgotten for a newer one). */
159
+ export const OPENCODE_BRAIN_SHELLS_MAX = 200;
160
+
157
161
  /** The assistant's OpenCode approval mode: 'auto' (auto-accept) or 'default'. */
158
162
  export function opencodeApprovalMode(mode) {
159
163
  return mode === 'auto' || mode === 'acceptEdits' || mode === 'bypassPermissions' ? 'auto' : 'default';
@@ -208,12 +212,18 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
208
212
  let startPromise = null;
209
213
  let synabunExpected = false;
210
214
  let stops = 0;
215
+ // After a "Stop anyway" (a command may still run): what OpenCode does for that command's end (a start the client
216
+ // interrupts, its error) is no turn of the runtime's, and reaches nobody until the next turn of the user's.
217
+ let muted = false;
211
218
  let waitingAbort = null;
212
219
  let interruptPrompt = null;
213
220
  let exited = false;
214
221
  const serveExitMessage = 'The isolated OpenCode server stopped during this turn. Send the message again to resume.';
215
222
  const serveExitError = () => Object.assign(new Error(serveExitMessage), { code: 'OPENCODE_SERVE_EXITED' });
216
223
  const serveExited = () => exited || entry?.proc?.exitCode != null || entry?.proc?.signalCode != null;
224
+ const stopMayFail = () => {
225
+ try { return !!(client && sessionId && client.getClient?.()?.stopNeedsKill?.(sessionId) === true); } catch { return false; }
226
+ };
217
227
  function onServeExit() {
218
228
  if (disposed) return;
219
229
  exited = true;
@@ -248,8 +258,31 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
248
258
  if (typeof plan === 'boolean') planMode = plan;
249
259
  }
250
260
 
261
+ // The shell commands of this brain's tool calls, as its event stream told them (shellId → the panel's view of
262
+ // it, assistant-envelope.js opencodeShellView): what a panel is sent when it attaches, and the only commands
263
+ // whose output this brain reads for it. Display data: nothing of it goes to the model, the transcript or a meter.
264
+ const shells = new Map();
265
+ function noteShell(shell) {
266
+ if (!shell?.id) return;
267
+ shells.delete(shell.id);
268
+ shells.set(shell.id, shell);
269
+ if (shells.size <= OPENCODE_BRAIN_SHELLS_MAX) return;
270
+ for (const [id, known] of shells) {
271
+ if (shells.size <= OPENCODE_BRAIN_SHELLS_MAX) break;
272
+ if (known.status !== 'running') shells.delete(id);
273
+ }
274
+ }
275
+
251
276
  const emit = (packet) => {
252
277
  if (disposed) return;
278
+ if (packet.type === 'assistant:shell') { noteShell(packet.shell); sink.send(packet); return; }
279
+ if (muted) {
280
+ // What OpenCode does for an abandoned command's end is no turn of anyone's: its model output goes nowhere. A
281
+ // permission request or a question of it would wait where nobody sees it, so it is refused at once, and every
282
+ // panel of the session says so (review 29cd51fe, finding 3).
283
+ if (packet.type === 'control_request' && client) refuseMuted(packet);
284
+ return;
285
+ }
253
286
  const decision = packet.type === 'control_request' && client ? opencodeAutoDecision(packet, { approvalMode: remoteReadOnly ? 'default' : approvalMode, planMode: planning(), readOnly: remoteReadOnly }) : null;
254
287
  if (decision) {
255
288
  const body = opencodeControlResponse(packet, { behavior: decision });
@@ -268,6 +301,18 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
268
301
  };
269
302
  sink.send({ type: 'engine', engine: 'opencode', brain: 'opencode' });
270
303
 
304
+ /** A request asked after a "Stop anyway", before the user's next turn: refused, never left pending, and said. */
305
+ function refuseMuted(packet) {
306
+ const body = opencodeControlResponse(packet, { behavior: 'deny' });
307
+ const tool = packet.request?.tool_name || (body.kind === 'question' ? 'a question' : 'a permission');
308
+ sink.send({ type: 'stderr', text: `Declined ${tool}: OpenCode asked it after Stop anyway, while no turn of yours was running. Send a message to go on.` });
309
+ if (!body.requestID) return;
310
+ const call = body.kind === 'question'
311
+ ? client.question.reject({ requestID: body.requestID, directory: cwd })
312
+ : client.permission.reply({ requestID: body.requestID, reply: 'reject', directory: cwd, message: 'The user stopped this turn.' });
313
+ Promise.resolve(call).catch((error) => { if (!serveExited()) sink.send({ type: 'error', message: `OpenCode decline failed: ${error?.message || error}` }); });
314
+ }
315
+
271
316
  function bindTranslator() {
272
317
  translator = createOpenCodeEnvelopeTranslator({
273
318
  sessionId, emit, brain: { cwd, model: brain.model || null }, planTurn: () => turnPlanned,
@@ -279,6 +324,21 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
279
324
  unsubscribe = source?.onEvent?.((envelope) => {
280
325
  if (!disposed && !serveExited()) translator.handle(envelope?.eventType || '', envelope?.event || {});
281
326
  }) || null;
327
+ recallShells();
328
+ }
329
+
330
+ // A brain that comes back to a serve already running (a resumed conversation) learns the commands that serve
331
+ // still knows for its session; what the stream says from now on is newer, so a command already noted stays.
332
+ async function recallShells() {
333
+ const asked = sessionId;
334
+ if (!asked || typeof client?.extra?.shell?.list !== 'function') return;
335
+ let listed = null;
336
+ try { listed = await client.extra.shell.list({ sessionID: asked }); } catch { return; }
337
+ if (disposed || asked !== sessionId) return;
338
+ for (const item of Array.isArray(listed?.data) ? listed.data : []) {
339
+ const shell = opencodeShellView(item);
340
+ if (shell?.callID && !shells.has(shell.id)) emit({ type: 'assistant:shell', shell });
341
+ }
282
342
  }
283
343
 
284
344
  /** The serve's MCP servers as an `mcp_status` event (the runtime reads whether SynaBun, and so agent_route, is reachable). */
@@ -331,12 +391,14 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
331
391
  needsRestart: serveExited,
332
392
  start,
333
393
  async sendUserTurn({ text, images = [], model = null, effort = null, permissionMode: mode = null, planMode: plan = null } = {}) {
394
+ muted = false;
334
395
  const stop = stops;
335
396
  await start();
336
397
  if (disposed || stops !== stop) return false;
337
398
  if (serveExited()) throw serveExitError();
338
399
  applyModes(mode, plan);
339
400
  turnActive = true;
401
+ translator?.noteTurnStart?.();
340
402
  // The runtime passes the effective model/effort on every turn (the record
341
403
  // may have changed since this brain started; routed turns override it).
342
404
  const parts = [{ type: 'text', text }, ...opencodeImageParts(images)];
@@ -390,12 +452,31 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
390
452
  throw serveExited() ? serveExitError() : error;
391
453
  } finally { interruptPrompt = null; }
392
454
  },
393
- async abort() {
394
- stops += 1;
395
- waitingAbort?.abort();
396
- if (serveExited()) return;
397
- try { if (client && sessionId) await client.session.abort({ sessionID: sessionId, directory: cwd }); } catch {}
455
+ /** Could a Stop fail now (a command in the background to end, lib/opencode2-client.js stopNeedsKill)? */
456
+ stopMayFail: () => stopMayFail(),
457
+ /**
458
+ * Stop the turn. A Stop that has a command to end tears nothing down before OpenCode confirmed its end: when it
459
+ * could not (lib/opencode2-client.js abortSession, review B3) the turn goes on, held for the command, and the
460
+ * error (code SHELL_STOP_FAILED, `shells`) says which and why. `force` ("Stop anyway"): the turn ends whatever
461
+ * the command does; → `{ abandoned }`, the commands that may still run.
462
+ */
463
+ async abort({ force = false } = {}) {
464
+ const mayFail = !force && stopMayFail();
465
+ if (!mayFail) { stops += 1; waitingAbort?.abort(); }
466
+ if (serveExited()) return { abandoned: [] };
467
+ let answer = null;
468
+ try { if (client && sessionId) answer = await client.session.abort({ sessionID: sessionId, directory: cwd, ...(force ? { force: true } : {}) }); } catch (error) {
469
+ if (error?.cause?.name === 'ShellStopFailed' && !serveExited()) {
470
+ error.code = 'SHELL_STOP_FAILED';
471
+ error.shells = Array.isArray(error.data?.shells) ? error.data.shells : [];
472
+ throw error;
473
+ }
474
+ }
475
+ if (mayFail) { stops += 1; waitingAbort?.abort(); }
476
+ const abandoned = Array.isArray(answer?.data?.abandoned) ? answer.data.abandoned : [];
398
477
  if (!serveExited()) emit({ type: 'aborted' });
478
+ if (force) muted = true;
479
+ return { abandoned };
399
480
  },
400
481
  async setPermissionMode(mode, { planMode: plan = null } = {}) { applyModes(mode, plan); sink.send({ type: 'mode_changed', mode: approvalMode, planMode }); },
401
482
  respondControl(requestId, response) {
@@ -413,9 +494,31 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
413
494
  async compact() {
414
495
  await start();
415
496
  turnPlanned = false;
497
+ // A compact is the user's own request: what it says is theirs again, even right after a Stop anyway.
498
+ muted = false;
416
499
  await client.session.compact({ sessionID: sessionId, directory: cwd });
417
500
  },
418
501
  async mcpStatus() { await reportMcpStatus(); },
502
+ /** The shell commands of this brain's tool calls, oldest first (what a panel that attaches is shown). */
503
+ shells: () => [...shells.values()],
504
+ /**
505
+ * A page of what one of those commands printed (stdout and stderr as written, in order), for the panel that
506
+ * shows it: from the byte `cursor`, or the last `tail` bytes. Only a command this brain ran is read, on its
507
+ * own serve. → { status, data: { output, cursor, size, from } } or { ok: false, status, error }. Never throws.
508
+ */
509
+ async shellOutput({ shellId, cursor, tail, limit } = {}) {
510
+ const id = typeof shellId === 'string' ? shellId : '';
511
+ if (!id || !shells.has(id)) return { ok: false, status: 404, error: 'That command is not one of this conversation.' };
512
+ const api = client?.extra?.shell;
513
+ if (disposed || serveExited() || typeof api?.output !== 'function') return { ok: false, status: 404, error: SHELL_OUTPUT_GONE_TEXT };
514
+ try {
515
+ return await readShellOutputPage(api, { shellID: id, directory: cwd, cursor, tail, limit });
516
+ } catch (error) {
517
+ const status = Number(error?.status);
518
+ // OpenCode keeps a finished command's output for a while only (404); any other failure may pass.
519
+ return { ok: false, status: status >= 400 && status < 600 ? status : 502, error: status === 404 ? SHELL_OUTPUT_GONE_TEXT : (error?.message || 'The output could not be read.') };
520
+ }
521
+ },
419
522
  async reconcileUsage(meter) {
420
523
  if (!client || !sessionId || !meter || serveExited()) return false;
421
524
  let failed = false;
@@ -441,7 +544,18 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
441
544
  return !failed;
442
545
  },
443
546
  // The session resumed is the conversation now: the usage meter's root follows it.
444
- async resume(id) { if (!id) return; sessionId = id; deps.onOpenCodeRoot?.(id); if (client) bindTranslator(); },
547
+ async resume(id) {
548
+ if (!id) return;
549
+ // Another provider conversation (/resume): the commands of the one before are not this one's, neither to
550
+ // list nor to read (review S3). The panels hear the new list; the commands its serve knows follow.
551
+ if (id !== sessionId && shells.size) {
552
+ shells.clear();
553
+ if (!disposed) sink.send({ type: 'assistant:shells' });
554
+ }
555
+ sessionId = id;
556
+ deps.onOpenCodeRoot?.(id);
557
+ if (client) bindTranslator();
558
+ },
445
559
  async listSessions() { await start(); const rows = await client.session.list({ directory: cwd }).catch(() => null); return Array.isArray(rows?.data) ? rows.data : []; },
446
560
  isBusy() { return turnActive || pendingControls.size > 0; },
447
561
  identity() { return { providerSessionId: sessionId, providerThreadId: null, accountId: null, model: brain.model || null, effort: null, cwd, costUsd, busy: turnActive, termId }; },