synabun 2.4.2 → 2.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +23 -3
  4. package/lib/release-npm-ci.mjs +23 -1
  5. package/mcp-server/dist/services/neural-interface.js +1 -1
  6. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  7. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
  8. package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
  9. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
  10. package/mcp-server/package-lock.json +5 -5
  11. package/mcp-server/package.json +1 -1
  12. package/mcp-server/src/services/neural-interface.ts +1 -1
  13. package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
  14. package/neural-interface/i18n/en.json +50 -1
  15. package/neural-interface/i18n/pt-BR.json +57 -8
  16. package/neural-interface/lib/assistant-api.js +33 -0
  17. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  18. package/neural-interface/lib/assistant-dispatch.js +26 -2
  19. package/neural-interface/lib/assistant-envelope.js +40 -0
  20. package/neural-interface/lib/assistant-runtime.js +95 -10
  21. package/neural-interface/lib/browser-extension-adapter.js +1 -3
  22. package/neural-interface/lib/browser-extension-archive.js +149 -0
  23. package/neural-interface/lib/browser-extension-bridge.js +7 -4
  24. package/neural-interface/lib/browser-extension-folder.js +596 -76
  25. package/neural-interface/lib/browser-extension-package.js +200 -0
  26. package/neural-interface/lib/browser-extension-pin.js +84 -0
  27. package/neural-interface/lib/browser-extension-pin.json +33 -0
  28. package/neural-interface/lib/browser-extension-setup.js +105 -18
  29. package/neural-interface/lib/cli-install.js +23 -3
  30. package/neural-interface/lib/cli-update-planner.js +67 -4
  31. package/neural-interface/lib/native-loop-providers.js +10 -1
  32. package/neural-interface/lib/native-loop-runtime.js +20 -2
  33. package/neural-interface/lib/opencode-shell-read.js +107 -0
  34. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  35. package/neural-interface/lib/opencode-turn-release.js +173 -0
  36. package/neural-interface/lib/opencode-v2-client.js +4 -1
  37. package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
  38. package/neural-interface/lib/opencode2-client.js +341 -6
  39. package/neural-interface/lib/opencode2-translate.js +161 -4
  40. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  41. package/neural-interface/lib/whatsapp/bridge.js +52 -6
  42. package/neural-interface/package-lock.json +5 -5
  43. package/neural-interface/package.json +1 -1
  44. package/neural-interface/public/extension-setup.html +5 -2
  45. package/neural-interface/public/shared/agy/agy-panel.js +38 -10
  46. package/neural-interface/public/shared/assistant/asst-api.js +25 -0
  47. package/neural-interface/public/shared/assistant/asst-panel.js +69 -1
  48. package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
  49. package/neural-interface/public/shared/assistant/asst-render.js +138 -6
  50. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  51. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  52. package/neural-interface/public/shared/assistant/asst-styles.js +1 -0
  53. package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
  54. package/neural-interface/public/shared/extension-setup/es-page.js +10 -4
  55. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  56. package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
  57. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  58. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  59. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
  60. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  61. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
  62. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
  63. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
  64. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  65. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +346 -0
  66. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  67. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  68. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
  69. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  70. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  71. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  72. package/neural-interface/public/shared/settings/settings-browser-extension.js +54 -12
  73. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  74. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  75. package/neural-interface/public/shared/tray-auto-close.js +36 -6
  76. package/neural-interface/public/shared/ui-claude-panel.js +20 -0
  77. package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
  78. package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
  79. package/neural-interface/server.js +249 -35
  80. package/npm-shrinkwrap.json +5 -5
  81. package/package.json +1 -2
  82. package/browser-extension/content.js +0 -231
  83. package/browser-extension/engine.js +0 -658
  84. package/browser-extension/icons/icon-128.png +0 -0
  85. package/browser-extension/icons/icon-16.png +0 -0
  86. package/browser-extension/icons/icon-32.png +0 -0
  87. package/browser-extension/icons/icon-48.png +0 -0
  88. package/browser-extension/icons/status-off-16.png +0 -0
  89. package/browser-extension/icons/status-off-32.png +0 -0
  90. package/browser-extension/icons/status-off-48.png +0 -0
  91. package/browser-extension/icons/status-on-16.png +0 -0
  92. package/browser-extension/icons/status-on-32.png +0 -0
  93. package/browser-extension/icons/status-on-48.png +0 -0
  94. package/browser-extension/manifest.json +0 -58
  95. package/browser-extension/popup-strings.js +0 -250
  96. package/browser-extension/popup-view.js +0 -151
  97. package/browser-extension/popup.css +0 -166
  98. package/browser-extension/popup.html +0 -108
  99. package/browser-extension/popup.js +0 -359
  100. package/browser-extension/service-worker.js +0 -283
  101. package/browser-extension/setup-content.js +0 -36
  102. package/browser-extension/tokens.css +0 -326
  103. /package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +0 -0
@@ -633,17 +633,51 @@ export function createEventTranslator({ version = '', directory: defaultDirector
633
633
  const inbox = new Map(); // inboxID → { sessionID, item }
634
634
  const permissions = new Map(); // requestID → sessionID
635
635
  const forms = new Map(); // formID → form
636
+ // The shell commands of tool calls (OpenCode 2 runs each as a "shell" with an
637
+ // id of its own): shellID → { id, sessionID, messageID, callID, command,
638
+ // started, ended, status, exit, linked, background, waited }. A command that
639
+ // outlives its tool call runs on "in the background": OpenCode ends the tool
640
+ // call (and, once the model has nothing else to do, the turn) while the
641
+ // command still runs, and starts the session again by itself when it exits.
642
+ const shells = new Map();
643
+ const detached = new Set(); // `${messageID}:${callID}` of calls the model itself sent to the background
636
644
  const MAX_MESSAGES = 400;
637
645
  const MAX_INBOX = 200;
646
+ const MAX_SHELLS = 200;
647
+ let released = 0;
638
648
 
639
649
  const sessionState = (sessionID) => {
640
650
  let state = sessions.get(sessionID);
641
651
  if (!state) {
642
- state = { info: null, directory: '', lastUser: '', compacting: 0 };
652
+ state = { info: null, directory: '', lastUser: '', compacting: 0, executing: false, held: false };
643
653
  sessions.set(sessionID, state);
644
654
  }
645
655
  return state;
646
656
  };
657
+
658
+ const shellView = (shell) => ({
659
+ id: shell.id,
660
+ sessionID: shell.sessionID,
661
+ messageID: shell.messageID,
662
+ callID: shell.callID,
663
+ command: shell.command,
664
+ status: shell.status,
665
+ background: shell.background,
666
+ waited: shell.waited,
667
+ time: shell.ended ? { started: shell.started, ended: shell.ended } : { started: shell.started },
668
+ ...(shell.exit != null ? { exit: shell.exit } : {}),
669
+ });
670
+ /** The commands of `sessionID` still running after their tool call ended; `waited`: only those the model did not send there itself. */
671
+ const backgroundShells = (sessionID, { waited = false } = {}) => [...shells.values()]
672
+ .filter((shell) => shell.sessionID === sessionID && shell.linked && shell.status === 'running' && shell.background && (!waited || shell.waited));
673
+ const trimShells = () => {
674
+ if (shells.size <= MAX_SHELLS) return;
675
+ // A command that ended goes first; one still running is never forgotten for a newer one.
676
+ for (const [id, shell] of shells) {
677
+ if (shells.size <= MAX_SHELLS) break;
678
+ if (shell.status !== 'running') shells.delete(id);
679
+ }
680
+ };
647
681
  const directoryOf = (event, sessionID) => str(event?.location?.directory)
648
682
  || (sessionID ? sessions.get(sessionID)?.directory : '')
649
683
  || defaultDirectory;
@@ -735,8 +769,23 @@ export function createEventTranslator({ version = '', directory: defaultDirector
735
769
  const { created, ...rest } = part;
736
770
  return rest;
737
771
  };
738
- const turnEnd = (error = null) => {
772
+ const updateShell = (shell) => {
773
+ if (shell.linked && shell.sessionID) emit('shell.updated', { sessionID: shell.sessionID, shell: shellView(shell) });
774
+ };
775
+ // An execution that ended is the end of the turn, except one that succeeded
776
+ // while a command the model waits for still runs in the background: OpenCode
777
+ // starts the session again by itself when that command exits, so the session
778
+ // is still at work and nobody is told it went idle (`held`). A command the
779
+ // model sent to the background itself (a server it started) holds nothing.
780
+ const turnEnd = (error = null, { hold = false } = {}) => {
781
+ const state = sessionState(sessionID);
782
+ state.executing = false;
783
+ state.held = hold && backgroundShells(sessionID, { waited: true }).length > 0;
739
784
  if (error) emit('session.error', { sessionID, error });
785
+ if (state.held) {
786
+ emit('session.status', { sessionID, status: { type: 'busy', background: true } });
787
+ return;
788
+ }
740
789
  emit('session.status', { sessionID, status: { type: 'idle' } });
741
790
  emit('session.idle', { sessionID });
742
791
  };
@@ -802,6 +851,7 @@ export function createEventTranslator({ version = '', directory: defaultDirector
802
851
  case 'session.deleted': {
803
852
  const info = sessionInfo(sessionID);
804
853
  sessions.delete(sessionID);
854
+ for (const [id, shell] of shells) if (shell.sessionID === sessionID) shells.delete(id);
805
855
  emit('session.deleted', { sessionID, info });
806
856
  break;
807
857
  }
@@ -841,14 +891,18 @@ export function createEventTranslator({ version = '', directory: defaultDirector
841
891
  }
842
892
 
843
893
  // ── A turn ──
844
- case 'session.execution.started':
894
+ case 'session.execution.started': {
895
+ const state = sessionState(sessionID);
896
+ state.executing = true;
897
+ state.held = false;
845
898
  emit('session.status', { sessionID, status: { type: 'busy' } });
846
899
  break;
900
+ }
847
901
  case 'session.retry.scheduled':
848
902
  emit('session.status', { sessionID, status: { type: 'retry', attempt: num(data.attempt), message: str(data.error?.message) || 'Retrying', next: num(data.at) } });
849
903
  break;
850
904
  case 'session.execution.succeeded':
851
- turnEnd(null);
905
+ turnEnd(null, { hold: true });
852
906
  break;
853
907
  case 'session.execution.failed':
854
908
  turnEnd(errorToV1(data.error));
@@ -948,6 +1002,10 @@ export function createEventTranslator({ version = '', directory: defaultDirector
948
1002
  case 'session.tool.called': {
949
1003
  const part = toolOf(data);
950
1004
  part.state = { status: 'running', input: obj(data.input), time: { start: at } };
1005
+ if (obj(data.input).background === true) {
1006
+ detached.add(`${part.messageID}:${part.callID}`);
1007
+ trim(detached, MAX_SHELLS);
1008
+ }
951
1009
  updatePart(publicTool(part));
952
1010
  break;
953
1011
  }
@@ -956,6 +1014,21 @@ export function createEventTranslator({ version = '', directory: defaultDirector
956
1014
  const start = num(part.state.time?.start, at);
957
1015
  part.state = { ...part.state, status: 'running', metadata: { ...obj(part.state.metadata), ...obj(data.metadata) }, time: { start } };
958
1016
  updatePart(publicTool(part));
1017
+ // The shell tool says which command it started: from here on its output
1018
+ // can be read while it runs (GET /api/shell/:id/output).
1019
+ const shellID = str(obj(data.metadata).shellID);
1020
+ if (shellID) {
1021
+ let shell = shells.get(shellID);
1022
+ if (!shell) {
1023
+ shell = { id: shellID, sessionID, messageID: '', callID: '', command: '', started: at, ended: 0, status: 'running', exit: null, linked: false, background: false, waited: false };
1024
+ shells.set(shellID, shell);
1025
+ trimShells();
1026
+ }
1027
+ if (!shell.linked) {
1028
+ Object.assign(shell, { linked: true, sessionID, messageID: part.messageID, callID: part.callID, command: shell.command || str(obj(part.state.input).command) });
1029
+ updateShell(shell);
1030
+ }
1031
+ }
959
1032
  break;
960
1033
  }
961
1034
  case 'session.tool.success':
@@ -965,8 +1038,40 @@ export function createEventTranslator({ version = '', directory: defaultDirector
965
1038
  const state = event.type === 'session.tool.success'
966
1039
  ? { status: 'completed', input: obj(part.state.input), content: data.content, metadata: data.metadata }
967
1040
  : { status: 'error', input: obj(part.state.input), error: data.error, metadata: data.metadata };
1041
+ const shellID = str(obj(data.metadata).shellID) || str(obj(part.state.metadata).shellID);
968
1042
  part.state = toolStateToV1(state, { name: part.tool, times: { ran: start, completed: at }, base: { sessionID, messageID: part.messageID, callID: part.callID } });
1043
+ // The call's command, for a reader of the part (a transcript read later has it only for a command that went
1044
+ // to the background: OpenCode keeps no shell id on one that finished inside its call).
1045
+ if (shellID && !part.state.metadata?.shellID) part.state = { ...part.state, metadata: { ...obj(part.state.metadata), shellID } };
969
1046
  updatePart(publicTool(part));
1047
+ const shell = shellID ? shells.get(shellID) : null;
1048
+ // "Succeeded" with a command still running: the call is over, the command is not.
1049
+ if (shell && shell.status === 'running' && event.type === 'session.tool.success' && obj(data.metadata).status === 'running') {
1050
+ shell.background = true;
1051
+ shell.waited = !detached.has(`${part.messageID}:${part.callID}`);
1052
+ updateShell(shell);
1053
+ }
1054
+ detached.delete(`${part.messageID}:${part.callID}`);
1055
+ break;
1056
+ }
1057
+
1058
+ // ── Shell commands ──
1059
+ case 'shell.created': {
1060
+ const info = obj(data.info);
1061
+ const id = str(info.id);
1062
+ if (!id || shells.has(id)) break;
1063
+ shells.set(id, { id, sessionID: str(obj(info.metadata).sessionID), messageID: '', callID: '', command: str(info.command), started: num(obj(info.time).started, at), ended: 0, status: 'running', exit: null, linked: false, background: false, waited: false });
1064
+ trimShells();
1065
+ break;
1066
+ }
1067
+ case 'shell.exited':
1068
+ case 'shell.deleted': {
1069
+ const shell = shells.get(str(data.id));
1070
+ if (!shell || shell.status !== 'running') break;
1071
+ shell.status = event.type === 'shell.deleted' ? 'killed' : (str(data.status) || 'exited');
1072
+ shell.ended = at;
1073
+ if (typeof data.exit === 'number') shell.exit = data.exit;
1074
+ updateShell(shell);
970
1075
  break;
971
1076
  }
972
1077
 
@@ -1051,6 +1156,58 @@ export function createEventTranslator({ version = '', directory: defaultDirector
1051
1156
  noteForm: (form) => { if (form?.id) { forms.set(str(form.id), form); trim(forms, MAX_INBOX); } },
1052
1157
  notePermission: (requestID, sessionID) => { if (requestID && sessionID) { permissions.set(str(requestID), str(sessionID)); trim(permissions, MAX_INBOX); } },
1053
1158
  sessionDirectory: (sessionID) => sessions.get(str(sessionID))?.directory || '',
1159
+ /** The shell commands of a session's tool calls this stream has seen, oldest first (`{ id, status, command, callID, background, … }`). */
1160
+ shells: (sessionID) => [...shells.values()].filter((shell) => shell.linked && shell.sessionID === str(sessionID)).map(shellView),
1161
+ /** One of them by its id, or null. */
1162
+ shell: (shellID) => { const shell = shells.get(str(shellID)); return shell?.linked ? shellView(shell) : null; },
1163
+ /** The commands of a session that run on after their tool call ended. */
1164
+ backgroundShells: (sessionID, options) => backgroundShells(str(sessionID), options).map(shellView),
1165
+ /** The ids of the commands a held turn of `sessionID` waits for (still running, not sent to the background by the model). */
1166
+ heldShellIds: (sessionID) => backgroundShells(str(sessionID), { waited: true }).map((shell) => shell.id),
1167
+ /** A session whose execution ended while a command the model waits for still runs: reported busy, not idle. */
1168
+ held: (sessionID) => sessions.get(str(sessionID))?.held === true,
1169
+ heldSessions: () => [...sessions].filter(([, state]) => state.held).map(([id]) => id),
1170
+ /**
1171
+ * Commands a "Stop anyway" gave up on: still listed as running (they may be), but no turn of their session waits
1172
+ * for them from now on. → the events that say so.
1173
+ */
1174
+ unhold(shellIDs = []) {
1175
+ const out = [];
1176
+ for (const id of shellIDs) {
1177
+ const shell = shells.get(str(id));
1178
+ if (!shell || !shell.waited) continue;
1179
+ shell.waited = false;
1180
+ const directory = sessions.get(shell.sessionID)?.directory || defaultDirectory;
1181
+ out.push({ directory, payload: { id: `synabun-release-${++released}`, type: 'shell.updated', properties: { sessionID: shell.sessionID, shell: shellView(shell) } } });
1182
+ }
1183
+ return out;
1184
+ },
1185
+ /**
1186
+ * End a held turn OpenCode will not end by itself (its commands were stopped, or the session never started
1187
+ * again): the events of that end, none when the session is not held. `aborted`: as a stopped turn.
1188
+ * `running`: the ids of commands a "Stop anyway" could not end. They stay listed as running (they may well be),
1189
+ * and are left as they are (`unhold` says they hold nothing).
1190
+ */
1191
+ release(sessionID, { aborted = false, running = [] } = {}) {
1192
+ const id = str(sessionID);
1193
+ const state = sessions.get(id);
1194
+ if (!state?.held) return [];
1195
+ state.held = false;
1196
+ const directory = state.directory || defaultDirectory;
1197
+ const event = (type, properties) => ({ directory, payload: { id: `synabun-release-${++released}`, type, properties } });
1198
+ const left = new Set((Array.isArray(running) ? running : []).map(str));
1199
+ // A command still listed as running is not: OpenCode holds none of this session any more.
1200
+ const ended = backgroundShells(id).filter((shell) => !left.has(shell.id)).map((shell) => {
1201
+ Object.assign(shell, { status: aborted ? 'killed' : 'exited', ended: Date.now() });
1202
+ return event('shell.updated', { sessionID: id, shell: shellView(shell) });
1203
+ });
1204
+ return [
1205
+ ...ended,
1206
+ ...(aborted ? [event('session.error', { sessionID: id, error: { name: 'MessageAbortedError', data: { message: 'The turn was stopped (user).' } } })] : []),
1207
+ event('session.status', { sessionID: id, status: { type: 'idle' } }),
1208
+ event('session.idle', { sessionID: id }),
1209
+ ];
1210
+ },
1054
1211
  };
1055
1212
  }
1056
1213
 
@@ -179,6 +179,89 @@ export function containsTokenText(text) {
179
179
  return typeof text === 'string' && text.length >= 40 && secretIntervals(text, knownForms).length > 0;
180
180
  }
181
181
 
182
+ /**
183
+ * For a text read in pages by position (a command's output file, where no stream is kept between two reads): how many
184
+ * characters at the end of `text` could still become a token or a known form once the next page follows (a token's
185
+ * beginning, the beginning of a known form). 0 when the page can go out whole. A reader holds that end back and
186
+ * starts its next page there, so no page boundary ever cuts a secret in two that each half would pass unmasked.
187
+ */
188
+ export function partialSecretTail(text) {
189
+ if (typeof text !== 'string' || !text) return 0;
190
+ let start = text.length;
191
+ const tail = PARTIAL_TAIL_RE.exec(text);
192
+ if (tail) start = Math.min(start, tail.index);
193
+ for (const form of knownForms) {
194
+ const from = Math.max(0, text.length - (form.length - 1));
195
+ for (let i = from; i < start; i++) {
196
+ if (text.charCodeAt(i) !== form.charCodeAt(0) || !form.startsWith(text.slice(i))) continue;
197
+ start = i;
198
+ break;
199
+ }
200
+ }
201
+ return text.length - start;
202
+ }
203
+
204
+ /** How many characters before a page a reader passes to scrubPageText: more than the longest form of a secret. */
205
+ export const PAGE_CONTEXT_CHARS = 128;
206
+
207
+ /**
208
+ * One page of a text read by position, scrubbed. `before`: the characters right before the page, so a secret the
209
+ * page starts in the middle of is still recognised and its rest masked (a reader that opens on the end of a long
210
+ * output starts wherever that falls). `final`: nothing follows this page, so a marked beginning at its end (a token
211
+ * the output was cut in) is masked too. Only the page comes back.
212
+ */
213
+ export function scrubPageText(text, { before = '', final = false } = {}) {
214
+ if (typeof text !== 'string' || !text) return '';
215
+ const context = typeof before === 'string' ? before.slice(-PAGE_CONTEXT_CHARS) : '';
216
+ const whole = context + text;
217
+ const found = secretIntervals(whole, knownForms);
218
+ if (final) {
219
+ const tail = PARTIAL_TAIL_RE.exec(whole);
220
+ if (tail && MARKED_PARTIAL_RE.test(tail[0])) found.push([tail.index, whole.length]);
221
+ }
222
+ const intervals = mergeIntervals(found);
223
+ return intervals.length ? render(whole, context.length, whole.length, intervals) : text;
224
+ }
225
+
226
+ /**
227
+ * One page of a text read by position, with what lies on both sides of it, scrubbed so that the pages a reader joins
228
+ * never hold a secret whole: the masked stretches are found on the complete window (`before` + `text` + `after`)
229
+ * first, and only then is the page cut, so a secret that ends at the page's end is masked whole whatever follows it,
230
+ * and a secret that crosses the page's end is either masked here through its end or left for the next page (which
231
+ * starts with it), never split into two halves that each pass. `before`: the characters right before the page;
232
+ * `after`: the characters right after it (as many as were read; at least PAGE_CONTEXT_CHARS unless the text ends
233
+ * there); `final`: nothing will ever follow `after` (a marked beginning at the very end is masked); otherwise an end
234
+ * of the window that could still become a secret, when it reaches back into the page, is held for the next page.
235
+ * → `{ text, consumed, held }`: the scrubbed page, how many characters of `text` + `after` it covers (the next page
236
+ * starts there), and whether its end was held back because it could still become a secret.
237
+ */
238
+ export function scrubOutputWindow(text, { before = '', after = '', final = false } = {}) {
239
+ const page = typeof text === 'string' ? text : '';
240
+ const context = typeof before === 'string' ? before.slice(-PAGE_CONTEXT_CHARS) : '';
241
+ const ahead = typeof after === 'string' ? after : '';
242
+ const whole = context + page + ahead;
243
+ const start = context.length;
244
+ let end = start + page.length;
245
+ if (!page) return { text: '', consumed: 0, held: false };
246
+ const found = secretIntervals(whole, knownForms);
247
+ let held = false;
248
+ if (final) {
249
+ const tail = PARTIAL_TAIL_RE.exec(whole);
250
+ if (tail && MARKED_PARTIAL_RE.test(tail[0])) found.push([tail.index, whole.length]);
251
+ } else {
252
+ const keep = partialSecretTail(whole);
253
+ if (keep > 0 && whole.length - keep < end) { end = Math.max(start, whole.length - keep); held = true; }
254
+ }
255
+ const intervals = mergeIntervals(found);
256
+ for (const [a, b] of intervals) {
257
+ if (a >= end || b <= end) continue;
258
+ // A secret across the cut: the page ends before it, or (when the page starts inside it) runs through its end.
259
+ if (a > start) { end = a; } else { end = b; held = false; }
260
+ }
261
+ const out = intervals.length ? render(whole, start, end, intervals) : whole.slice(start, end);
262
+ return { text: out, consumed: end - start, held };
263
+ }
264
+
182
265
  /**
183
266
  * `value` with every token-shaped string replaced, at any depth of plain objects and arrays (the events, results and
184
267
  * messages SynaBun passes on). Copy on write: what holds no token is returned as it is (the same reference), and so is
@@ -57,6 +57,7 @@
57
57
  // composition are injected (Packages A and C); nothing here knows a phone number.
58
58
 
59
59
  import { assistantEventKey } from '../../public/shared/assistant/asst-state.js';
60
+ import { abandonedPrograms } from '../../public/shared/shell-stop-view.js';
60
61
  import { stripFollowups } from '../../public/shared/assistant/asst-followups.js';
61
62
  import { brainCapsLevel, defaultRemotePolicyRegistry, effectiveLevel, remoteBrainNotice } from '../remote-policy.js';
62
63
  import { brainSignature, resolveBrainChoice } from './brain.js';
@@ -136,7 +137,39 @@ const ROUTE_DONE_PHASES = new Set(['decided', 'auto', 'expired', 'declined', 'ca
136
137
  const WORKER_MOVED_ON_NOTE = 'The user did not approve this on WhatsApp (they moved on to something else). Do not retry it: continue without it, or report it as blocked.';
137
138
  const CLARIFY_DONE_PHASES = new Set(['answered', 'declined', 'chat', 'cancelled', 'expired']);
138
139
  // Computer control was stopped at the Mac (Esc, the corner, the Stop button): one line to the phone.
139
- export const MAC_STOP_TEXT = 'Computer control was stopped on your Mac: I am no longer controlling it.';
140
+ /**
141
+ * Why a Stop could not end a command, as the phone is told it: one generic reason from what the client recorded
142
+ * (lib/opencode2-client.js removeShell: OpenCode's own message with its HTTP status, or a network error). OpenCode's
143
+ * words never leave the machine: they can quote the command line.
144
+ */
145
+ export function phoneStopReason(shells) {
146
+ const said = (Array.isArray(shells) ? shells : []).map((shell) => String(shell?.reason || '')).join(' ');
147
+ if (/\bHTTP 5\d\d\b/.test(said)) return 'OpenCode answered with an error';
148
+ if (/\bHTTP 4\d\d\b/.test(said)) return 'OpenCode refused';
149
+ if (/ECONN|ETIMEDOUT|EHOSTUNREACH|ENOTFOUND|EPIPE|socket|fetch failed|could not be reached|timed? ?out/i.test(said)) return 'OpenCode could not be reached';
150
+ return 'OpenCode did not confirm the end';
151
+ }
152
+
153
+ const programList = (names) => (Array.isArray(names) ? names : []).slice(0, 5).map((name) => (name === 'command' ? 'a command' : `\`${name}\``)).join(', ');
154
+
155
+ /**
156
+ * The reply to /stop: what was cancelled (the session's runs and the queue) in every case, then what the turn's Stop
157
+ * did. `turnStop`: `{ failed: [program], reason }` (the turn goes on: the next /stop of that turn stops anyway) or
158
+ * `{ abandoned: [program] }` (it stopped anyway; the command may still run). Programs by name only.
159
+ */
160
+ export function phoneStopReply(cancelled, turnStop = null) {
161
+ const n = Math.max(0, Number(cancelled) || 0);
162
+ const tasks = `${n} task${n === 1 ? '' : 's'}`;
163
+ if (turnStop?.failed) {
164
+ const what = programList(turnStop.failed) || 'a command';
165
+ const one = turnStop.failed.length <= 1;
166
+ return `${n ? `Cancelled ${tasks}, but could not` : 'Could not'} end ${what} on your computer (${turnStop.reason || 'OpenCode did not confirm the end'}). ${one ? 'It is' : 'They are'} still running, so the current reply goes on. Send /stop again to stop anyway: ${one ? 'it' : 'they'} may keep running on the computer, and SynaBun will keep trying to end ${one ? 'it' : 'them'}.`;
167
+ }
168
+ const left = turnStop?.abandoned?.length ? ` ${programList(turnStop.abandoned)} may still be running on your computer: SynaBun keeps trying to end ${turnStop.abandoned.length === 1 ? 'it' : 'them'} in the background.` : '';
169
+ return `Stopped. Cancelled ${tasks}.${left}`;
170
+ }
171
+
172
+ export const MAC_STOP_TEXT ='Computer control was stopped on your Mac: I am no longer controlling it.';
140
173
  const usd = (value) => `$${(Number(value) || 0).toFixed(2)}`;
141
174
  const hhmm = (ms) => new Date(ms).toTimeString().slice(0, 5);
142
175
  const monthDay = (ms) => new Date(ms).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
@@ -1071,9 +1104,8 @@ export function createWhatsAppBridge({
1071
1104
  // what waited behind it) is not acted on, as /stop clears what already waits in line.
1072
1105
  state.stoppedAt = Math.max(state.stoppedAt, tsMs(message.ts, now()));
1073
1106
  state.stopLateNoted = false;
1074
- const { stoppedRuns, clearedQueue } = await stopEverything({ reason: 'phone' });
1075
- const n = stoppedRuns + clearedQueue;
1076
- await say(`Stopped. Cancelled ${n} task${n === 1 ? '' : 's'}.`, { maxChunks: 1 });
1107
+ const { stoppedRuns, clearedQueue, turnStop } = await stopEverything({ reason: 'phone' });
1108
+ await say(phoneStopReply(stoppedRuns + clearedQueue, turnStop), { maxChunks: 1 });
1077
1109
  return;
1078
1110
  }
1079
1111
  case 'new':
@@ -1124,7 +1156,21 @@ export function createWhatsAppBridge({
1124
1156
  let stoppedRuns = 0;
1125
1157
  const turn = id ? state.turns.get(id) : null;
1126
1158
  if (turn) turn.stoppedByPhone = reason === 'phone';
1127
- if (rt && id) { try { await rt.stopTurn?.(id, { origin: 'whatsapp' }); } catch {} }
1159
+ // A Stop that could not end a command in the background (OpenCode): the turn goes on, and the phone is told. The
1160
+ // phone has no "Stop anyway" button, so the next /stop of the same turn is one (forceAfterFailures: 1, counted by
1161
+ // the runtime per turn); a stop of the service's never leaves a turn behind. What the phone hears of it is the
1162
+ // program's name and a generic reason only (phoneStopReply): never a command line or OpenCode's own words.
1163
+ let turnStop = null;
1164
+ if (rt && id) {
1165
+ try {
1166
+ const r = await rt.stopTurn?.(id, { origin: 'whatsapp', ...(reason !== 'phone' ? { force: true } : { forceAfterFailures: 1 }) });
1167
+ if (r && r.ok === false && Array.isArray(r.shells)) turnStop = { failed: abandonedPrograms(r.shells), reason: phoneStopReason(r.shells) };
1168
+ else if (r?.abandoned?.length) turnStop = { abandoned: abandonedPrograms(r.abandoned) };
1169
+ // A stop of the service's (no phone to tell): the Assistant panels of the session hear it from the runtime
1170
+ // (stop_abandoned), and the log keeps it.
1171
+ if (reason !== 'phone' && turnStop?.abandoned) log('whatsapp:bridge', `session ${id}: stopped anyway; ${turnStop.abandoned.join(', ')} may still be running (SynaBun keeps trying to end it)`);
1172
+ } catch {}
1173
+ }
1128
1174
  const d = dispatcher();
1129
1175
  if (d?.list && d?.stop && id) {
1130
1176
  let runs = [];
@@ -1147,7 +1193,7 @@ export function createWhatsAppBridge({
1147
1193
  const cleared = state.queue.splice(0, state.queue.length);
1148
1194
  for (const job of cleared) react(job.sourceIds, 'stopped');
1149
1195
  persistBridgeState();
1150
- return { stoppedRuns, clearedQueue: cleared.length };
1196
+ return { stoppedRuns, clearedQueue: cleared.length, turnStop };
1151
1197
  }
1152
1198
  function pause(by = 'desktop') {
1153
1199
  state.paused = true;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "neural-memory-interface",
3
- "version": "2.4.2",
3
+ "version": "2.4.3",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "neural-memory-interface",
9
- "version": "2.4.2",
9
+ "version": "2.4.3",
10
10
  "hasInstallScript": true,
11
11
  "license": "Apache-2.0",
12
12
  "dependencies": {
@@ -2966,9 +2966,9 @@
2966
2966
  "license": "MIT"
2967
2967
  },
2968
2968
  "node_modules/body-parser": {
2969
- "version": "1.20.8",
2970
- "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.8.tgz",
2971
- "integrity": "sha512-JNcyFQ64OiijEkPzUBTCe+hyPXUD/3LEldGQ6iF5LR1w00mx9o7xtDWHXBY2iItjdCFGoilOLNQbH943ut7pHA==",
2969
+ "version": "1.20.9",
2970
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz",
2971
+ "integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==",
2972
2972
  "license": "MIT",
2973
2973
  "dependencies": {
2974
2974
  "bytes": "~3.1.2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neural-memory-interface",
3
- "version": "2.4.2",
3
+ "version": "2.4.3",
4
4
  "private": true,
5
5
  "description": "Private local SynaBun interface for memory visualization and multi-agent workflows",
6
6
  "license": "Apache-2.0",
@@ -14,8 +14,9 @@
14
14
  status, then automatic pairing. Every string comes from i18n browserExtension.setup.* (es-page.js); es-view.js
15
15
  decides. Stable hooks: #es-setup[data-state], #es-title, #es-lead, #es-live[data-tone], #es-browser,
16
16
  #es-steps > li[data-step][data-done], #es-extensions-url + #es-copy-url, #es-folder + #es-copy-folder + #es-reveal,
17
- #es-alternatives, #es-reload, #es-restart, #es-copied. The ticket element is the only thing the extension's content
18
- script reads; it is filled only while the extension is on this page and the server waits for it. -->
17
+ #es-alternatives, #es-reload, #es-restart, #es-copied, #es-progress (the bytes of the extension's download, while
18
+ the state is "downloading"). The ticket element is the only thing the extension's content script reads; it is
19
+ filled only while the extension is on this page and the server waits for it. -->
19
20
  <main id="es-setup" class="es-setup" data-state="idle" data-layout="result" aria-busy="true">
20
21
  <div class="es-top">
21
22
  <p class="es-brand"><img src="/icon-192.png" alt="" width="32" height="32"><span>SynaBun</span></p>
@@ -75,6 +76,7 @@
75
76
  <h2 class="es-status-title" id="es-status-title"></h2>
76
77
  <p id="es-live" class="es-live" role="status" aria-live="polite" data-tone=""></p>
77
78
  <p id="es-help" class="es-note" hidden></p>
79
+ <p id="es-progress" class="es-note es-progress" hidden></p>
78
80
  <section id="es-alternatives" class="es-alternatives" hidden aria-labelledby="es-alternatives-title">
79
81
  <h3 id="es-alternatives-title" class="es-subtitle"></h3>
80
82
  <div id="es-alternatives-list" class="es-row"></div>
@@ -95,6 +97,7 @@
95
97
  <details class="es-surface es-info es-help" id="es-trouble">
96
98
  <summary id="es-trouble-title"></summary>
97
99
  <p id="es-trouble-help" class="es-note"></p>
100
+ <p id="es-moved-help" class="es-note"></p>
98
101
  <p id="es-policy-help" class="es-note"></p>
99
102
  </details>
100
103
  </div>
@@ -58,6 +58,7 @@ import { runAwaitsAnswer, runTurnLive } from '../sidepanel-session-status.js';
58
58
  import { wireFileLinks } from '../ui-file-links.js';
59
59
  import { notify, NOTIF_TYPE } from '../ui-notifications.js';
60
60
  import { forgetGreeting, mountGreeting } from '../greeting/greeting-card.js';
61
+ import { composerHoldsDraft, markAutoCloseKeep } from '../tray-auto-close.js';
61
62
 
62
63
  export const PANEL_OWNER = 'antigravity-sidepanel';
63
64
  const ICON = ICONS.mark;
@@ -557,10 +558,12 @@ function blockedNow() {
557
558
  return '';
558
559
  }
559
560
 
560
- async function send({ text: given = null, staged: givenStaged = null, fromQueue = false } = {}) {
561
- const tab = activeTab();
561
+ // `tab` is the tab the message is for: the one on screen, or (from drainQueue only) a tab in the background
562
+ // whose turn ended with its queue to go on, whose composer is not the one on screen and is never touched.
563
+ async function send({ text: given = null, staged: givenStaged = null, fromQueue = false, tab = activeTab() } = {}) {
562
564
  if (!tab || tab.automationActive) return;
563
- const input = $('.agy-input');
565
+ const onScreen = tab === activeTab();
566
+ const input = onScreen ? $('.agy-input') : null;
564
567
  const text = given ?? (input?.value || '');
565
568
  const rt = runtimeOf(tab);
566
569
  const staged = givenStaged ?? rt.staged;
@@ -645,7 +648,7 @@ async function send({ text: given = null, staged: givenStaged = null, fromQueue
645
648
  rt.notice = null;
646
649
  tab.running = true;
647
650
  tab.startedAt = Date.now();
648
- hideHints();
651
+ if (onScreen) hideHints();
649
652
  saveTabs();
650
653
  renderTabs();
651
654
  renderAttachments();
@@ -667,13 +670,20 @@ async function send({ text: given = null, staged: givenStaged = null, fromQueue
667
670
  }
668
671
  }
669
672
 
673
+ /**
674
+ * Send the next prompt queued in `tab`, the tab it was typed in, as the Claude Code and Codex panels do: a tab in
675
+ * the background whose turn ends goes on with its own queue, one prompt per turn in the order they were queued
676
+ * (the next one goes at that prompt's turn:end). A paused queue waits; so does one that cannot be sent now (a
677
+ * send under way, a running automation, a missing or broken agy): the prompt stays first in its queue.
678
+ */
670
679
  function drainQueue(tab) {
671
680
  const rt = runtimeOf(tab);
672
- if (!rt.queue.length || rt.queuePaused || tab.running) { renderQueue(); return; }
681
+ if (!rt.queue.length || rt.queuePaused || tab.running || rt.sending || tab.automationActive) { renderQueue(tab); return; }
682
+ if (blockedNow()) { if (tab === activeTab()) nudgeSetup(); renderQueue(tab); return; }
673
683
  const next = rt.queue.shift();
674
- renderQueue();
675
- if (tab === activeTab()) send({ text: next.text, staged: next.staged, fromQueue: true });
676
- else rt.queue.unshift(next);
684
+ // send() takes the prompt before its first await (rt.sending), so the mark below still says 'queue'.
685
+ send({ tab, text: next.text, staged: next.staged, fromQueue: true });
686
+ renderQueue(tab);
677
687
  }
678
688
 
679
689
  async function stop() {
@@ -1261,9 +1271,13 @@ function renderAttachments() {
1261
1271
  box.innerHTML = staged.map((file, idx) => `<span class="agy-chip" title="${esc(file.path || file.name)}">${file.mimeType?.startsWith('image/') && file.dataUrl ? `<img src="${esc(file.dataUrl)}" alt="">` : ''}<span>${esc(file.name)}</span><button type="button" data-unstage="${idx}" aria-label="${esc(T('attachmentRemove', { name: file.name }))}">&times;</button></span>`).join('');
1262
1272
  }
1263
1273
 
1264
- function renderQueue() {
1274
+ function renderQueue(tab = activeTab()) {
1275
+ // The tray's auto-close keeps a tab while its queue holds prompts (autoCloseKeepOf): said at every change,
1276
+ // for a tab in the background too; only the tab on screen has its queue drawn.
1277
+ if (tab?.pillEl) markAutoCloseKeep(tab.pillEl, autoCloseKeepOf(tab));
1278
+ if (tab !== activeTab()) return;
1265
1279
  const box = $('.agy-queue');
1266
- const rt = runtimeOf(activeTab());
1280
+ const rt = runtimeOf(tab);
1267
1281
  if (!box) return;
1268
1282
  const queue = rt?.queue || [];
1269
1283
  box.hidden = !queue.length;
@@ -1581,6 +1595,18 @@ function chooseHint(idx) {
1581
1595
  renderComposer();
1582
1596
  }
1583
1597
 
1598
+ // What the tray's auto-close must leave open (tray-auto-close.js), or '': a tab with prompts in its queue that
1599
+ // were never sent ('queue': paused or not, and while one taken off it is still on its way, `sending`), else a tab
1600
+ // holding an unsent draft, its text (in the composer while the tab is the one on screen) and its staged
1601
+ // attachments. The user's X closes it as before. renderQueue repaints the mark at every change of a queue.
1602
+ function autoCloseKeepOf(tab) {
1603
+ if (!tab) return '';
1604
+ const rt = _runtime.get(tab.id);
1605
+ if (rt?.queue.length || rt?.sending) return 'queue';
1606
+ const input = tab === activeTab() ? $('.agy-input') : null;
1607
+ return composerHoldsDraft(input ? input.value : tab.draft, rt?.staged) ? 'draft' : '';
1608
+ }
1609
+
1584
1610
  // ── Tray pills (shown for tabs with something in them while the panel is closed, or not the active tab) ──
1585
1611
  function renderPills() {
1586
1612
  const tray = document.getElementById('term-minimized-tray');
@@ -1591,6 +1617,7 @@ function renderPills() {
1591
1617
  pill.className = 'term-minimized-pill agy-session-pill';
1592
1618
  pill.dataset.tabId = tab.id;
1593
1619
  pill.getAutomationRunId = () => tab.automationRunId;
1620
+ pill.keepFromAutoClose = () => autoCloseKeepOf(tab);
1594
1621
  pill.tabIndex = 0;
1595
1622
  pill.innerHTML = `<span class="term-minimized-pill-icon agy-mark">${ICON}</span><span class="term-minimized-pill-label"></span><button class="term-minimized-pill-close" data-tooltip="${esc(T('closeTab'))}" data-tooltip-pos="top">&times;</button>`;
1596
1623
  const openIt = () => {
@@ -1622,6 +1649,7 @@ function renderPills() {
1622
1649
  const needsYou = !!(tab.needsYou || tab.automationAwaits);
1623
1650
  tab.pillEl.classList.toggle('agy-pill-attention', needsYou);
1624
1651
  tab.pillEl.classList.toggle('agy-pill-running', !needsYou && !!tab.running);
1652
+ markAutoCloseKeep(tab.pillEl, autoCloseKeepOf(tab));
1625
1653
  const meaningful = !!(tab.sessionId || tab.running || tab.draft || tab.automationRunId || tab.needsYou);
1626
1654
  tab.pillEl.style.display = meaningful && (!_visible || tab !== activeTab()) ? '' : 'none';
1627
1655
  }
@@ -40,6 +40,31 @@ function jsonBody(data, method = 'POST') {
40
40
 
41
41
  const enc = encodeURIComponent;
42
42
 
43
+ // ── A shell command's output (OpenCode brain) ─
44
+
45
+ /**
46
+ * One page of what a command of this conversation printed. Never throws and raises no guest toast: a page that
47
+ * cannot be read is the terminal block's to say. → { status, data: { output, cursor, size, from } } or { ok: false, status, error }.
48
+ */
49
+ export async function readAssistantShellOutput(sessionId, { shellId, cursor, tail, limit } = {}) {
50
+ const query = new URLSearchParams();
51
+ if (Number.isSafeInteger(cursor) && cursor >= 0) query.set('cursor', String(cursor));
52
+ if (Number.isSafeInteger(tail) && tail > 0) query.set('tail', String(tail));
53
+ if (Number.isSafeInteger(limit) && limit > 0) query.set('limit', String(limit));
54
+ const search = query.toString();
55
+ let res;
56
+ try {
57
+ res = await fetch(`/api/assistant/sessions/${enc(sessionId)}/shells/${enc(shellId)}/output${search ? `?${search}` : ''}`, { credentials: 'same-origin' });
58
+ } catch (error) {
59
+ return { ok: false, error: error?.message || 'The output could not be read.' };
60
+ }
61
+ let body = null;
62
+ try { body = await res.json(); } catch { /* not JSON */ }
63
+ if (!res.ok || !body?.ok) return { ok: false, status: res.status, error: body?.error || `HTTP ${res.status}` };
64
+ const { ok: _ok, ...data } = body;
65
+ return { status: res.status, data };
66
+ }
67
+
43
68
  // ── Catalog ──────────────────────────────────
44
69
 
45
70
  export function fetchAssistantCatalog({ force = false } = {}) {