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
@@ -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
@@ -53,11 +53,19 @@ export function createUiBlobRouter({ namespaces, store, ownerNamespace = null, o
53
53
  return ns;
54
54
  }
55
55
 
56
- router.get('/api/ui-blobs/:ns', (req, res) => {
56
+ router.get('/api/ui-blobs/:ns', async (req, res) => {
57
57
  const ns = namespaceOf(req, res);
58
58
  if (!ns) return;
59
- try { res.json(store.getNamespace(ns)); }
60
- catch (err) { res.status(500).json({ error: err.message }); }
59
+ try {
60
+ if (typeof store.getNamespaceJsonAsync === 'function') {
61
+ const json = await store.getNamespaceJsonAsync(ns);
62
+ res.type('application/json').send(json);
63
+ } else if (typeof store.getNamespaceAsync === 'function') {
64
+ res.json(await store.getNamespaceAsync(ns));
65
+ } else {
66
+ res.json(store.getNamespace(ns));
67
+ }
68
+ } catch (err) { res.status(500).json({ error: err.message }); }
61
69
  });
62
70
 
63
71
  router.get('/api/ui-blobs/:ns/:id', (req, res) => {
@@ -83,8 +91,9 @@ export function createUiBlobRouter({ namespaces, store, ownerNamespace = null, o
83
91
  order.applied(ns, req.params.id, revision);
84
92
  const maxEntries = parseInt(req.query.maxEntries, 10) || 0;
85
93
  const maxChars = parseInt(req.query.maxChars, 10) || 0;
86
- let evicted = [];
87
- if (maxEntries || maxChars) evicted = store.prune(ns, { maxEntries, maxTotalChars: maxChars });
94
+ const evicted = maxEntries > 0 || maxChars > 0
95
+ ? store.prune(ns, { maxEntries, maxTotalChars: maxChars })
96
+ : [];
88
97
  res.json({ ok: true, evicted });
89
98
  } catch (err) { res.status(500).json({ error: err.message }); }
90
99
  }
@@ -12,13 +12,101 @@
12
12
  // HTML churn would bloat its WAL and backups for no benefit.
13
13
 
14
14
  import { DatabaseSync } from 'node:sqlite';
15
+ import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
16
+ import { setTimeout, clearTimeout } from 'node:timers';
15
17
  import { dirname } from 'path';
16
18
  import { existsSync, mkdirSync } from 'fs';
17
19
 
20
+ const MAX_TRIM_ROWS = 128;
21
+ const DELETE_BATCH = 32;
22
+ const DEFAULT_BACKFILL_BATCH = 16;
23
+ const NAMESPACE_READ_PAGE = 25;
24
+ const WORKER_IDLE_MS = 5000;
25
+
18
26
  let db = null;
19
27
  let dbPath = null;
28
+ let backfillTimer = null;
29
+ let recountThrough = 0;
30
+ let readerState = null;
31
+ let readerJobSeq = 0;
32
+
33
+ function terminateReaderWorker(reason = 'ui-blob-store closed') {
34
+ const current = readerState;
35
+ if (!current) return;
36
+ readerState = null;
37
+ if (current.idleTimer) { clearTimeout(current.idleTimer); current.idleTimer = null; }
38
+ if (current.jobs.size) {
39
+ const err = new Error(reason);
40
+ for (const job of current.jobs.values()) job.reject(err);
41
+ current.jobs.clear();
42
+ }
43
+ try { void current.worker.terminate(); } catch {}
44
+ }
45
+
46
+ function ensureSchema(d) {
47
+ d.exec(`
48
+ CREATE TABLE IF NOT EXISTS ui_blobs (
49
+ ns TEXT NOT NULL, id TEXT NOT NULL, value TEXT NOT NULL,
50
+ value_chars INTEGER, updated_at INTEGER NOT NULL, PRIMARY KEY (ns, id)
51
+ );
52
+ CREATE TABLE IF NOT EXISTS ui_blob_meta (k TEXT PRIMARY KEY, v INTEGER NOT NULL);
53
+ `);
54
+ if (!d.prepare('PRAGMA table_info(ui_blobs)').all().some(col => col.name === 'value_chars')) {
55
+ d.exec('ALTER TABLE ui_blobs ADD COLUMN value_chars INTEGER');
56
+ }
57
+ d.exec(`
58
+ DROP TRIGGER IF EXISTS trg_ui_blobs_ai_chars;
59
+ DROP TRIGGER IF EXISTS trg_ui_blobs_au_chars;
60
+ DROP TRIGGER IF EXISTS trg_ui_blobs_au_rev;
61
+ DROP INDEX IF EXISTS idx_ui_blobs_ns_updated;
62
+ DROP INDEX IF EXISTS idx_ui_blobs_null_chars;
63
+ CREATE INDEX IF NOT EXISTS idx_ui_blobs_trim ON ui_blobs(ns, updated_at DESC, id DESC, value_chars);
64
+ INSERT OR IGNORE INTO ui_blob_meta (k, v)
65
+ SELECT 'recount_through', COALESCE(MAX(rowid), 0) FROM ui_blobs;
66
+ `);
67
+ return d.prepare("SELECT v FROM ui_blob_meta WHERE k = 'recount_through'").get().v;
68
+ }
69
+
70
+ // Recount pre-upgrade rows (both NULL and old UTF-16 counts). The rowid keyset and
71
+ // its checkpoint commit together. New writes already use SQLite LENGTH().
72
+ export function backfillBlobValueCharsBatch(limit = DEFAULT_BACKFILL_BATCH) {
73
+ if (!db || !recountThrough) return 0;
74
+ const batch = Math.max(1, Math.min(DEFAULT_BACKFILL_BATCH, Math.trunc(limit) || DEFAULT_BACKFILL_BATCH));
75
+ const rows = db.prepare('SELECT rowid FROM ui_blobs WHERE rowid <= ? ORDER BY rowid DESC LIMIT ?')
76
+ .all(recountThrough, batch);
77
+ const next = rows.length === batch ? Math.max(0, rows.at(-1).rowid - 1) : 0;
78
+ db.exec('BEGIN');
79
+ try {
80
+ if (rows.length) {
81
+ db.prepare('UPDATE ui_blobs SET value_chars = LENGTH(value) WHERE rowid BETWEEN ? AND ?')
82
+ .run(rows.at(-1).rowid, rows[0].rowid);
83
+ }
84
+ db.prepare("UPDATE ui_blob_meta SET v = ? WHERE k = 'recount_through'").run(next);
85
+ db.exec('COMMIT');
86
+ recountThrough = next;
87
+ return rows.length;
88
+ } catch (err) {
89
+ db.exec('ROLLBACK');
90
+ throw err;
91
+ }
92
+ }
93
+
94
+ function scheduleBackfill() {
95
+ if (!recountThrough) return;
96
+ backfillTimer = setTimeout(() => {
97
+ try {
98
+ backfillBlobValueCharsBatch();
99
+ } catch (err) {
100
+ console.warn('[ui-blobs] Character recount paused until next open:', err.message);
101
+ return;
102
+ }
103
+ scheduleBackfill();
104
+ }, 25);
105
+ backfillTimer.unref();
106
+ }
20
107
 
21
108
  export function initBlobStore(path) {
109
+ if (db && dbPath !== path) closeBlobStore();
22
110
  dbPath = path;
23
111
  return getBlobDb();
24
112
  }
@@ -26,19 +114,24 @@ export function initBlobStore(path) {
26
114
  function getBlobDb() {
27
115
  if (!db) {
28
116
  if (!dbPath) throw new Error('ui-blob-store: initBlobStore(path) not called');
29
- const dir = dirname(dbPath);
30
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
31
- db = new DatabaseSync(dbPath);
32
- db.exec('PRAGMA journal_mode = WAL');
33
- db.exec('PRAGMA busy_timeout = 5000');
34
- db.exec(`
35
- CREATE TABLE IF NOT EXISTS ui_blobs (
36
- ns TEXT NOT NULL,
37
- id TEXT NOT NULL,
38
- value TEXT NOT NULL,
39
- updated_at INTEGER NOT NULL,
40
- PRIMARY KEY (ns, id)
41
- );`);
117
+ if (dbPath !== ':memory:') {
118
+ const dir = dirname(dbPath);
119
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
120
+ }
121
+ const opened = new DatabaseSync(dbPath);
122
+ try {
123
+ if (dbPath !== ':memory:') opened.exec('PRAGMA journal_mode = WAL');
124
+ opened.exec('PRAGMA busy_timeout = 5000');
125
+ opened.exec('BEGIN');
126
+ recountThrough = ensureSchema(opened);
127
+ opened.exec('COMMIT');
128
+ } catch (err) {
129
+ try { opened.close(); } catch {}
130
+ throw err;
131
+ }
132
+ // Publish the connection only after PRAGMAs and ensureSchema() succeed.
133
+ db = opened;
134
+ scheduleBackfill();
42
135
  }
43
136
  return db;
44
137
  }
@@ -53,6 +146,106 @@ export function blobGetNamespace(ns) {
53
146
  return out;
54
147
  }
55
148
 
149
+ function buildNamespaceJsonSync(d, ns, pageSize = NAMESPACE_READ_PAGE) {
150
+ const firstStmt = d.prepare('SELECT id, value FROM ui_blobs WHERE ns = ? ORDER BY id ASC LIMIT ?');
151
+ const nextStmt = d.prepare('SELECT id, value FROM ui_blobs WHERE ns = ? AND id > ? ORDER BY id ASC LIMIT ?');
152
+ let lastId = null;
153
+ const parts = ['{'];
154
+ let first = true;
155
+ for (;;) {
156
+ const rows = lastId === null ? firstStmt.all(ns, pageSize) : nextStmt.all(ns, lastId, pageSize);
157
+ if (!rows.length) break;
158
+ for (const row of rows) {
159
+ lastId = row.id;
160
+ try {
161
+ const parsed = JSON.parse(row.value);
162
+ const encoded = JSON.stringify(parsed);
163
+ if (encoded === undefined) continue;
164
+ parts.push(`${first ? '' : ','}${JSON.stringify(row.id)}:${encoded}`);
165
+ first = false;
166
+ } catch { /* skip corrupt row */ }
167
+ }
168
+ if (rows.length < pageSize) break;
169
+ }
170
+ parts.push('}');
171
+ return parts.join('');
172
+ }
173
+
174
+ function getOrCreateReaderWorker(targetPath) {
175
+ if (readerState && readerState.path !== targetPath) {
176
+ terminateReaderWorker('ui-blob-store path changed');
177
+ }
178
+ if (!readerState) {
179
+ const worker = new Worker(new URL(import.meta.url), {
180
+ workerData: { uiBlobReader: true },
181
+ execArgv: process.execArgv.filter((arg) => arg === '--experimental-sqlite'),
182
+ });
183
+ const state = { worker, path: targetPath, jobs: new Map(), idleTimer: null };
184
+ readerState = state;
185
+ worker.on('message', (msg) => {
186
+ const job = state.jobs.get(msg.id);
187
+ if (!job) return;
188
+ state.jobs.delete(msg.id);
189
+ if (state.jobs.size === 0 && readerState === state) {
190
+ worker.unref();
191
+ if (state.idleTimer) clearTimeout(state.idleTimer);
192
+ state.idleTimer = setTimeout(() => {
193
+ state.idleTimer = null;
194
+ if (readerState === state && state.jobs.size === 0) {
195
+ terminateReaderWorker('idle');
196
+ }
197
+ }, WORKER_IDLE_MS);
198
+ state.idleTimer.unref?.();
199
+ }
200
+ if (msg.error) job.reject(new Error(msg.error));
201
+ else job.resolve(Buffer.from(msg.bytes.buffer, msg.bytes.byteOffset, msg.bytes.byteLength));
202
+ });
203
+ const onWorkerEnd = (err) => {
204
+ if (state.idleTimer) { clearTimeout(state.idleTimer); state.idleTimer = null; }
205
+ if (readerState === state) readerState = null;
206
+ if (state.jobs.size) {
207
+ const error = err || new Error('ui-blob reader worker exited before replying');
208
+ for (const job of state.jobs.values()) job.reject(error);
209
+ state.jobs.clear();
210
+ }
211
+ };
212
+ worker.once('error', onWorkerEnd);
213
+ worker.once('exit', () => onWorkerEnd());
214
+ }
215
+ return readerState;
216
+ }
217
+
218
+ /**
219
+ * Read and serialize an entire namespace as a UTF-8 JSON Buffer off the event loop
220
+ * (in a short-lived worker thread for file-backed DBs).
221
+ * Preserves the exact `{ [id]: value }` response contract for GET /api/ui-blobs/:ns.
222
+ */
223
+ export async function blobGetNamespaceJsonAsync(ns) {
224
+ const d = getBlobDb();
225
+ if (!dbPath || dbPath === ':memory:') {
226
+ return Buffer.from(buildNamespaceJsonSync(d, ns));
227
+ }
228
+ const targetPath = dbPath;
229
+ const state = getOrCreateReaderWorker(targetPath);
230
+ if (state.idleTimer) { clearTimeout(state.idleTimer); state.idleTimer = null; }
231
+ state.worker.ref();
232
+ const id = ++readerJobSeq;
233
+ return new Promise((resolve, reject) => {
234
+ state.jobs.set(id, { resolve, reject });
235
+ try {
236
+ state.worker.postMessage({ id, dbPath: targetPath, ns });
237
+ } catch (err) {
238
+ state.jobs.delete(id);
239
+ reject(err);
240
+ }
241
+ });
242
+ }
243
+
244
+ export async function blobGetNamespaceAsync(ns) {
245
+ const buf = await blobGetNamespaceJsonAsync(ns);
246
+ return JSON.parse(buf.toString('utf8'));
247
+ }
248
+
56
249
  export function blobGet(ns, id) {
57
250
  const d = getBlobDb();
58
251
  const row = d.prepare('SELECT value FROM ui_blobs WHERE ns = ? AND id = ?').get(ns, id);
@@ -62,15 +255,20 @@ export function blobGet(ns, id) {
62
255
 
63
256
  export function blobPut(ns, id, value) {
64
257
  const d = getBlobDb();
258
+ const serialized = JSON.stringify(value);
259
+ // Keep the last write newest through millisecond ties and backwards clock steps.
65
260
  d.prepare(`
66
- INSERT INTO ui_blobs (ns, id, value, updated_at) VALUES (?, ?, ?, ?)
67
- ON CONFLICT(ns, id) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
68
- `).run(ns, id, JSON.stringify(value), Date.now());
261
+ INSERT INTO ui_blobs (ns, id, value, value_chars, updated_at)
262
+ VALUES (?, ?, ?, LENGTH(?), MAX(?, COALESCE((
263
+ SELECT updated_at + 1 FROM ui_blobs WHERE ns = ? ORDER BY updated_at DESC LIMIT 1
264
+ ), 0)))
265
+ ON CONFLICT(ns, id) DO UPDATE SET
266
+ value = excluded.value, value_chars = excluded.value_chars, updated_at = excluded.updated_at
267
+ `).run(ns, id, serialized, serialized, Date.now(), ns);
69
268
  }
70
269
 
71
270
  export function blobDelete(ns, id) {
72
- const d = getBlobDb();
73
- d.prepare('DELETE FROM ui_blobs WHERE ns = ? AND id = ?').run(ns, id);
271
+ getBlobDb().prepare('DELETE FROM ui_blobs WHERE ns = ? AND id = ?').run(ns, id);
74
272
  }
75
273
 
76
274
  // ── Which of a page's requests for one entry is the newer ──
@@ -142,33 +340,98 @@ export function createBlobOrder({ now = Date.now, ttlMs = BLOB_ORDER_TTL_MS, max
142
340
  }
143
341
 
144
342
  export function blobClearNamespace(ns) {
145
- const d = getBlobDb();
146
- const result = d.prepare('DELETE FROM ui_blobs WHERE ns = ?').run(ns);
147
- return Number(result?.changes || 0);
343
+ return getBlobDb().prepare('DELETE FROM ui_blobs WHERE ns = ?').run(ns).changes;
148
344
  }
149
345
 
150
- // Evict oldest entries beyond maxEntries and/or beyond maxTotalChars of
151
- // cumulative value length (newest kept). Returns the evicted ids.
346
+ // Keep the newest entry even if it alone exceeds the character budget.
152
347
  export function blobPrune(ns, { maxEntries = 0, maxTotalChars = 0 } = {}) {
348
+ if (!(maxEntries > 0 || maxTotalChars > 0)) return [];
153
349
  const d = getBlobDb();
154
- const rows = d.prepare(
155
- 'SELECT id, LENGTH(value) AS len FROM ui_blobs WHERE ns = ? ORDER BY updated_at DESC'
156
- ).all(ns);
157
- const evicted = [];
158
- let totalChars = 0;
159
- rows.forEach((row, i) => {
160
- totalChars += row.len;
161
- const overCount = maxEntries > 0 && i >= maxEntries;
162
- const overChars = maxTotalChars > 0 && totalChars > maxTotalChars && i > 0;
163
- if (overCount || overChars) evicted.push(row.id);
164
- });
165
- if (evicted.length) {
166
- const del = d.prepare('DELETE FROM ui_blobs WHERE ns = ? AND id = ?');
167
- for (const id of evicted) del.run(ns, id);
350
+ let cutoff;
351
+ if (maxTotalChars > 0) {
352
+ // Only an uncounted legacy value needs a table lookup. Normal writes trim
353
+ // straight from the covering index and stop as soon as either cap is reached.
354
+ const rows = d.prepare(`
355
+ SELECT id, updated_at, CASE WHEN rowid <= ? OR value_chars IS NULL
356
+ THEN (SELECT LENGTH(legacy.value) FROM ui_blobs AS legacy WHERE legacy.rowid = b.rowid)
357
+ ELSE value_chars END AS chars
358
+ FROM ui_blobs AS b WHERE ns = ? ORDER BY updated_at DESC, id DESC LIMIT ?
359
+ `).iterate(recountThrough, ns, MAX_TRIM_ROWS);
360
+ let total = 0;
361
+ let count = 0;
362
+ for (const row of rows) {
363
+ total += row.chars;
364
+ if (count && total > maxTotalChars) break;
365
+ cutoff = row;
366
+ count++;
367
+ if (total >= maxTotalChars || count === maxEntries) break;
368
+ if (count === MAX_TRIM_ROWS) {
369
+ console.debug('[ui-blobs] Character trim reached the row budget for', ns);
370
+ // No character cutoff proven in this scan. A separate count cap still applies.
371
+ cutoff = null;
372
+ }
373
+ }
374
+ }
375
+ if (!cutoff && maxEntries > 0) {
376
+ cutoff = d.prepare(`
377
+ SELECT updated_at, id FROM ui_blobs WHERE ns = ?
378
+ ORDER BY updated_at DESC, id DESC LIMIT 1 OFFSET ?
379
+ `).get(ns, Math.min(Number.MAX_SAFE_INTEGER, maxEntries) - 1);
380
+ }
381
+ if (!cutoff) return [];
382
+ const victims = d.prepare(`
383
+ SELECT id FROM ui_blobs WHERE ns = ? AND (updated_at, id) < (?, ?)
384
+ ORDER BY updated_at, id LIMIT ?
385
+ `).all(ns, cutoff.updated_at, cutoff.id, MAX_TRIM_ROWS + 1);
386
+ if (victims.length > MAX_TRIM_ROWS) {
387
+ victims.pop();
388
+ console.debug('[ui-blobs] Remaining evictions deferred to next write for', ns);
168
389
  }
169
- return evicted;
390
+ const ids = victims.map(row => row.id);
391
+ if (ids.length) {
392
+ d.exec('BEGIN');
393
+ try {
394
+ for (let i = 0; i < ids.length; i += DELETE_BATCH) {
395
+ const batch = ids.slice(i, i + DELETE_BATCH);
396
+ const params = batch.map(() => '?').join(',');
397
+ d.prepare(`DELETE FROM ui_blobs WHERE ns = ? AND id IN (${params})`).run(ns, ...batch);
398
+ }
399
+ d.exec('COMMIT');
400
+ } catch (err) {
401
+ d.exec('ROLLBACK');
402
+ throw err;
403
+ }
404
+ }
405
+ return ids;
170
406
  }
171
407
 
172
408
  export function closeBlobStore() {
173
- if (db) { try { db.close(); } catch {} db = null; }
409
+ clearTimeout(backfillTimer);
410
+ backfillTimer = null;
411
+ recountThrough = 0;
412
+ terminateReaderWorker('ui-blob-store closed');
413
+ if (db) { db.close(); db = null; }
414
+ }
415
+
416
+ // ── Worker thread entrypoint for off-event-loop namespace reads ──
417
+ if (!isMainThread && workerData?.uiBlobReader && parentPort) {
418
+ const encoder = new TextEncoder();
419
+ parentPort.on('message', ({ id, dbPath: targetPath, ns }) => {
420
+ let reader = null;
421
+ try {
422
+ reader = new DatabaseSync(targetPath);
423
+ reader.exec('PRAGMA query_only = ON');
424
+ reader.exec('PRAGMA busy_timeout = 5000; BEGIN');
425
+ const json = buildNamespaceJsonSync(reader, ns, NAMESPACE_READ_PAGE);
426
+ reader.exec('COMMIT');
427
+ // Close before replying so an idle worker never pins the DB file (critical on Windows).
428
+ reader.close();
429
+ reader = null;
430
+ const bytes = encoder.encode(json);
431
+ parentPort.postMessage({ id, bytes }, [bytes.buffer]);
432
+ } catch (err) {
433
+ if (reader) { try { reader.close(); } catch {} }
434
+ parentPort.postMessage({ id, error: err?.message || String(err) });
435
+ }
436
+ });
174
437
  }
@@ -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.4",
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.4",
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.4",
4
4
  "private": true,
5
5
  "description": "Private local SynaBun interface for memory visualization and multi-agent workflows",
6
6
  "license": "Apache-2.0",