synabun 2.4.3 → 2.4.5

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 (177) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +66 -36
  4. package/docs/whatsapp.md +3 -3
  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 +12 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -17
  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 +19 -4
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +85 -17
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  34. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  35. package/mcp-server/dist/tools/browser-observe.js +113 -27
  36. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  37. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  38. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  39. package/mcp-server/dist/tools/browser-readers.js +17 -0
  40. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  41. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  42. package/mcp-server/dist/tools/remember.js +6 -2
  43. package/mcp-server/dist/tools/remember.js.map +1 -1
  44. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  45. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  46. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  47. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  48. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  49. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  50. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  51. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  52. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  53. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  54. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  55. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  56. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  57. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  58. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  59. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  60. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  61. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  62. package/mcp-server/package-lock.json +2 -2
  63. package/mcp-server/package.json +1 -1
  64. package/mcp-server/src/http.ts +8 -1
  65. package/mcp-server/src/services/identity.ts +5 -0
  66. package/mcp-server/src/services/memory-client.ts +32 -12
  67. package/mcp-server/src/services/memory-writer.ts +5 -2
  68. package/mcp-server/src/services/neural-interface.ts +67 -19
  69. package/mcp-server/src/services/typesafe-config.ts +268 -7
  70. package/mcp-server/src/tools/agents.ts +79 -17
  71. package/mcp-server/src/tools/browser-observe.ts +117 -28
  72. package/mcp-server/src/tools/browser-readers.ts +19 -0
  73. package/mcp-server/src/tools/remember.ts +6 -1
  74. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  75. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  76. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  77. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  78. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  79. package/neural-interface/i18n/en.json +487 -8
  80. package/neural-interface/i18n/pt-BR.json +487 -8
  81. package/neural-interface/lib/agents-studio-api.js +7 -2
  82. package/neural-interface/lib/antigravity/home.js +43 -8
  83. package/neural-interface/lib/antigravity/tool-call.js +14 -0
  84. package/neural-interface/lib/assistant-api.js +90 -0
  85. package/neural-interface/lib/assistant-brains/antigravity.js +4 -2
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-dispatch.js +276 -42
  88. package/neural-interface/lib/assistant-memory.js +3 -1
  89. package/neural-interface/lib/assistant-persona.js +14 -3
  90. package/neural-interface/lib/assistant-route-gate.js +11 -2
  91. package/neural-interface/lib/assistant-router.js +18 -8
  92. package/neural-interface/lib/assistant-runtime.js +103 -6
  93. package/neural-interface/lib/assistant-spilled-output.js +53 -0
  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-default.js +22 -2
  97. package/neural-interface/lib/browser-extension-adapter.js +221 -15
  98. package/neural-interface/lib/browser-extension-bridge.js +89 -9
  99. package/neural-interface/lib/browser-extension-folder.js +50 -11
  100. package/neural-interface/lib/browser-extension-package.js +6 -5
  101. package/neural-interface/lib/browser-extension-pin.json +15 -13
  102. package/neural-interface/lib/browser-extension-protocol.js +141 -14
  103. package/neural-interface/lib/browser-extension-setup.js +210 -40
  104. package/neural-interface/lib/browser-extension-update.js +104 -0
  105. package/neural-interface/lib/browser-extraction.js +38 -14
  106. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  107. package/neural-interface/lib/claude-history.js +12 -1
  108. package/neural-interface/lib/confined-fs.js +25 -0
  109. package/neural-interface/lib/coordination/operations.js +2 -0
  110. package/neural-interface/lib/db.js +39 -16
  111. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  112. package/neural-interface/lib/git-bash/manager.js +28 -3
  113. package/neural-interface/lib/git-status-runner.js +31 -3
  114. package/neural-interface/lib/loop-inventory.js +162 -0
  115. package/neural-interface/lib/loop-stall.js +74 -4
  116. package/neural-interface/lib/memory-session-capture.js +157 -66
  117. package/neural-interface/lib/native-loop-providers.js +73 -13
  118. package/neural-interface/lib/native-loop-runtime.js +3 -0
  119. package/neural-interface/lib/opencode-protocol.js +4 -2
  120. package/neural-interface/lib/peer-identity.js +62 -16
  121. package/neural-interface/lib/remote-policy.js +24 -7
  122. package/neural-interface/lib/session-cache-builder.js +66 -18
  123. package/neural-interface/lib/session-capture-gate.js +42 -0
  124. package/neural-interface/lib/session-indexer.js +28 -20
  125. package/neural-interface/lib/teams/README.md +22 -1
  126. package/neural-interface/lib/teams/api.js +79 -6
  127. package/neural-interface/lib/teams/index.js +2 -0
  128. package/neural-interface/lib/teams/recovery.js +68 -0
  129. package/neural-interface/lib/teams/scheduler.js +352 -31
  130. package/neural-interface/lib/teams/worktrees.js +123 -30
  131. package/neural-interface/lib/ui-blob-api.js +14 -5
  132. package/neural-interface/lib/ui-blob-store.js +302 -39
  133. package/neural-interface/package-lock.json +2 -2
  134. package/neural-interface/package.json +1 -1
  135. package/neural-interface/public/extension-setup.html +7 -2
  136. package/neural-interface/public/shared/agents/studio/ax-api.js +16 -0
  137. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +318 -13
  138. package/neural-interface/public/shared/agents/studio/ax-teams.js +141 -9
  139. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  140. package/neural-interface/public/shared/assistant/asst-api.js +42 -0
  141. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  142. package/neural-interface/public/shared/assistant/asst-panel.js +285 -10
  143. package/neural-interface/public/shared/assistant/asst-render.js +205 -4
  144. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  145. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  146. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  147. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  148. package/neural-interface/public/shared/assistant/asst-styles.js +20 -0
  149. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  150. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  151. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  152. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  153. package/neural-interface/public/shared/browser-extension-updates.js +90 -0
  154. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  155. package/neural-interface/public/shared/extension-setup/es-page.js +41 -15
  156. package/neural-interface/public/shared/extension-setup/es-view.js +51 -11
  157. package/neural-interface/public/shared/extension-update-view.js +34 -0
  158. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +8 -4
  159. package/neural-interface/public/shared/settings/settings-ai-browser.js +23 -3
  160. package/neural-interface/public/shared/settings/settings-browser-extension.js +581 -197
  161. package/neural-interface/public/shared/settings/settings-extension-diagrams.js +116 -0
  162. package/neural-interface/public/shared/settings/settings-extension-guide.js +222 -0
  163. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  164. package/neural-interface/public/shared/settings/settings-ia.js +2 -2
  165. package/neural-interface/public/shared/settings/settings-shell.js +5 -0
  166. package/neural-interface/public/shared/styles.css +200 -13
  167. package/neural-interface/public/shared/ui-claude-panel.js +110 -1
  168. package/neural-interface/public/shared/ui-notifications.js +23 -4
  169. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  170. package/neural-interface/public/shared/ui-settings.js +48 -11
  171. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  172. package/neural-interface/public/shared/worker-end.js +18 -0
  173. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  174. package/neural-interface/scripts/rebuild-pty.js +10 -0
  175. package/neural-interface/server.js +503 -281
  176. package/npm-shrinkwrap.json +2 -2
  177. package/package.json +1 -1
@@ -1,20 +1,41 @@
1
+ import { connectionAdvice } from './browser-connection-state.js';
1
2
  import { createHash, randomBytes } from 'node:crypto';
2
3
  import { basename, extname, isAbsolute, resolve } from 'node:path';
3
4
  import express from 'express';
4
5
  import { readConfinedFileWithMetadata } from './confined-fs.js';
5
- import { EVALUATE_SCRIPT_MAX, EVALUATE_TIMEOUT_MAX, EVALUATE_WORLDS, fail, handle, HISTORY, LOAD_STATES, MAX_FILE, NETWORK_IDLE_TIMEOUT_MAX, safeError } from './browser-extension-protocol.js';
6
+ import { errorDetail, EVALUATE_SCRIPT_MAX, EVALUATE_TIMEOUT_MAX, EVALUATE_WORLDS, fail, handle, HISTORY, LOAD_STATES, MAX_FILE, NETWORK_IDLE_TIMEOUT_MAX, PAGED_READERS, READER_IDS, READS_SINCE, safeError, uploadType } from './browser-extension-protocol.js';
6
7
  import sharp from 'sharp';
7
8
  import { parseScreenshotOptions, screenshotPathRefusal, defaultScreenshotPath, writeScreenshotFile } from './browser-screenshot.js';
8
9
  import { ownerOnlyCreateFields } from './browser-automation-routes.js';
10
+ import { budgetExtractionItems, EXTRACTION_TIMEOUT_MS } from './browser-extraction.js';
11
+ import { compareVersions } from './browser-extension-folder.js';
9
12
 
10
- // Use the server's static-file MIME table. Its bundled table predates these image formats.
13
+ // The extension's fixed type table first (protocol.js UPLOAD_TYPES: the type the extension gives the File anyway),
14
+ // then the server's static-file MIME table for a name it does not know.
11
15
  export function uploadMimeType(name) {
16
+ const named = uploadType(name);
17
+ if (named !== 'application/octet-stream') return named;
12
18
  const ext = extname(name).toLowerCase();
13
- if (['.heic', '.heif', '.avif'].includes(ext)) return 'image/' + ext.slice(1);
14
- return express.static.mime.lookup(ext);
19
+ return (ext && express.static.mime.lookup(ext)) || named;
15
20
  }
16
21
  const aliases = { 'screenshot-base64': 'screenshot' };
17
- const supported = new Set(['navigate', 'back', 'forward', 'reload', 'snapshot', 'click', 'hover', 'fill', 'type', 'press', 'select', 'scroll', 'wait', 'content', 'screenshot', 'upload', 'evaluate']);
22
+ const supported = new Set(['navigate', 'back', 'forward', 'reload', 'snapshot', 'click', 'hover', 'fill', 'type', 'press', 'select', 'scroll', 'wait', 'content', 'markdown', 'extract', 'screenshot', 'upload', 'evaluate']);
23
+ // The Playwright routes' reading contract (server.js /content and /markdown), which the extension's readers answer to
24
+ // as well: the default page size of each, and the note a cut page ends with (the same words, the same next offset).
25
+ export const TEXT_PAGE_DEFAULT = 50000;
26
+ export const MARKDOWN_PAGE_DEFAULT = 80000;
27
+ export function pageOf(whole, query = {}, defaultMax, separator) {
28
+ const totalChars = whole.length;
29
+ const offset = Math.max(0, parseInt(query.offset, 10) || 0);
30
+ const maxChars = Math.max(1, parseInt(query.maxChars, 10) || defaultMax);
31
+ let text = whole;
32
+ if (offset > 0 || totalChars > offset + maxChars) {
33
+ const slice = whole.slice(offset, offset + maxChars), more = totalChars > offset + maxChars;
34
+ text = slice + (more ? `${separator}... (truncated — ${totalChars} chars total, pass offset=${offset + maxChars} to continue)` : '');
35
+ }
36
+ return { text, totalChars };
37
+ }
38
+ const SELECTOR_ONE = 'Content selector must match exactly one element.';
18
39
  const argumentKeys = ['url', 'ref', 'selector', 'nthMatch', 'value', 'text', 'key', 'direction', 'distance', 'maxChars', 'offset', 'timeout', 'state'];
19
40
  const unsupported = reason => Object.assign(new Error(reason), { code: 'UNSUPPORTED_IN_EXTENSION_MODE' });
20
41
  // A whole number of milliseconds from a request body, 1 to `most`; undefined when none (or nothing usable) was given.
@@ -48,7 +69,10 @@ const HISTORY_DESTINATION = 'The page this history step reached is not on an app
48
69
  // `refusal({ session, req, tabId, script })` answers the X publish gate's refusal (or null), `run({ session, req, execute })`
49
70
  // spaces a social write (`pace` in the body) and answers { result } or { paced } with it. Without one, nothing is gated
50
71
  // (tests of the adapter alone).
51
- export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, ownerPage, selected, dataHome, log = () => {}, evaluateGate = null }) {
72
+ // `htmlToMarkdown(html)` is the Playwright Markdown route's converter (server.js nhm.translate), so both backends turn a
73
+ // page into the same Markdown; `now` / `sleep` are the paged extraction's clock (tests pass their own).
74
+ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, ownerPage, selected, dataHome, log = () => {}, evaluateGate = null,
75
+ htmlToMarkdown = null, now = Date.now, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) {
52
76
  const salt = randomBytes(32).toString('hex');
53
77
  const agent = owner => createHash('sha256').update(`${salt}:${owner}`).digest('hex');
54
78
  let sessionId = null, chain = Promise.resolve();
@@ -100,7 +124,8 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
100
124
  const status = bridge.status();
101
125
  const shared = target || (status.fullControl ? null : status.tabs.find(t => t.owner === null && !t.created));
102
126
  const result = await bridge.request(shared ? 'claim' : 'create', shared?.handle || null, opaque);
103
- if (!result.ok) throw Object.assign(new Error(result.error), { code: result.code });
127
+ // What the browser said when it refused (protocol.js errorDetail) stays with the code, to the agent and the log.
128
+ if (!result.ok) throw Object.assign(new Error(result.error), { code: result.code, detail: errorDetail(result) });
104
129
  const tab = result.tab;
105
130
  const now = bridge.status(), reading = now.tabs.find(t => t.handle === tab && t.owner === opaque);
106
131
  if (!reading) fail('TAB_NOT_APPROVED');
@@ -202,13 +227,166 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
202
227
  if (outcome.paced?.pending) return { ok: true, paced: outcome.paced };
203
228
  return { ok: true, result: outcome.result === undefined ? null : outcome.result, ...(cut || {}), ...(outcome.paced ? { paced: outcome.paced } : {}) };
204
229
  }
230
+ // ── The extension's fixed readers (1.5.0): protocol.js READER_IDS, run by id, never a script ──
231
+ const readsReaders = () => compareVersions(bridge.status().extensionVersion, READS_SINCE) >= 0;
232
+ const coded = result => Object.assign(new Error(result?.code || 'OPERATION_FAILED'), { code: result?.code || 'OPERATION_FAILED', detail: errorDetail(result), answer: worded(result) });
233
+ async function read(s, owner, tab, args) {
234
+ const result = finish(s, tab, await bridge.request('read', tab, agent(owner), args));
235
+ if (!result.ok) throw coded(result);
236
+ return result;
237
+ }
238
+ // A reader's JSON answer (what an extractor returned), parsed; one cut for length is a refusal, never half an answer.
239
+ function valueOf(result) {
240
+ if (result.truncated) throw Object.assign(new Error('READER_FAILED'), { code: 'READER_FAILED', answer: { ok: false, code: 'READER_FAILED', error: `READER_FAILED: what the page shows is larger than one answer (${result.valueLength} characters of JSON). Read fewer items, or narrow the page first.` } });
241
+ try { return JSON.parse(result.value); } catch { fail('OPERATION_FAILED'); }
242
+ }
243
+ // browser_content format "text" (GET /content): the page's innerText, paged as the Playwright route pages it.
244
+ async function contentText(s, owner, tab, body) {
245
+ if (!readsReaders()) {
246
+ // An extension from before the readers: its own content command, as it always answered.
247
+ const args = {};
248
+ for (const k of ['selector', 'maxChars', 'offset']) if (body[k] !== undefined && body[k] !== null && body[k] !== '') args[k] = k === 'selector' ? String(body[k]) : Number(body[k]);
249
+ return finish(s, tab, await bridge.request('content', tab, agent(owner), args));
250
+ }
251
+ const selector = typeof body.selector === 'string' && body.selector ? body.selector : undefined;
252
+ let result;
253
+ try { result = await read(s, owner, tab, { reader: 'page.text', ...(selector ? { selector } : {}) }); }
254
+ catch (error) { if (['NO_MATCH', 'AMBIGUOUS_TARGET', 'INVALID_SELECTOR'].includes(error.code)) return { ok: false, code: error.code, error: SELECTOR_ONE }; throw error; }
255
+ const page = pageOf(result.text || '', body, TEXT_PAGE_DEFAULT, '\n');
256
+ return { ok: true, url: result.url, title: result.title ?? '', text: page.text, totalChars: page.totalChars, ...(selector ? { selector } : {}),
257
+ ...(result.truncated ? { sourceTruncated: true, sourceChars: result.valueLength } : {}) };
258
+ }
259
+ // browser_content format "markdown" (GET /markdown): the page's main content as HTML, read by the same page function
260
+ // the Playwright route runs (lib/browser-extraction.js contentHtmlOf, shipped as the reader 'page.html'), turned into
261
+ // Markdown by the same converter, paged the same way.
262
+ async function contentMarkdown(s, owner, tab, body) {
263
+ if (!readsReaders()) fail('EXTENSION_RELOAD_REQUIRED');
264
+ if (typeof htmlToMarkdown !== 'function') throw unsupported('Markdown is unavailable in this server build.');
265
+ const selector = typeof body.selector === 'string' && body.selector ? body.selector : undefined;
266
+ let result;
267
+ try { result = await read(s, owner, tab, { reader: 'page.html', ...(selector ? { selector } : {}) }); }
268
+ catch (error) { if (['NO_MATCH', 'AMBIGUOUS_TARGET', 'INVALID_SELECTOR'].includes(error.code)) return { ok: false, code: error.code, error: SELECTOR_ONE }; throw error; }
269
+ const html = result.text || '';
270
+ if (!html) return { ok: true, url: result.url, title: result.title ?? '', markdown: '', tokens: 0 };
271
+ const markdown = htmlToMarkdown(html);
272
+ const page = pageOf(markdown, body, MARKDOWN_PAGE_DEFAULT, '\n\n');
273
+ return { ok: true, url: result.url, title: result.title ?? '', markdown: page.text, tokens: Math.ceil(page.totalChars / 4), totalChars: page.totalChars, ...(selector ? { selector } : {}),
274
+ ...(result.truncated ? { sourceTruncated: true, sourceChars: result.valueLength } : {}) };
275
+ }
276
+ // The paged extraction (POST /extract), as lib/browser-extraction.js runBrowserExtraction runs it on a Playwright
277
+ // page: read, merge and dedupe, scroll, wait until the feed shows something new (or its loading marker ends), read
278
+ // again; the same options, limits, stop reasons and answer. Here the reads and the scroll are the extractor's fixed
279
+ // reader (`body.extractor`, one of protocol.js PAGED_READERS); the `script` and `scrollTarget` the request also
280
+ // carries are for the Playwright backend and are never sent anywhere.
281
+ async function extract(s, owner, tab, body, req) {
282
+ const id = body.extractor;
283
+ if (typeof id !== 'string' || !PAGED_READERS.includes(id)) {
284
+ return { ok: false, actionStarted: false, code: 'UNSUPPORTED_IN_EXTENSION_MODE',
285
+ error: `UNSUPPORTED_IN_EXTENSION_MODE: the extension backend runs only its own fixed extractors, named by id (${PAGED_READERS.join(', ')}); this request names ${typeof id === 'string' ? JSON.stringify(id.slice(0, 64)) : 'none'}. No script was run.` };
286
+ }
287
+ const opts = {};
288
+ for (const name of ['scrolls', 'minItems', 'maxItems', 'maxChars', 'timeoutMs', 'settleMs', 'scrollDistance']) {
289
+ if (body[name] === undefined || body[name] === null) continue;
290
+ const v = body[name];
291
+ if (!Number.isInteger(v) || v < (name === 'scrolls' ? 0 : name === 'maxChars' ? 2 : 1)) return { ok: false, actionStarted: false, error: `${name} must be a ${name === 'scrolls' ? 'nonnegative' : 'positive'} integer` };
292
+ opts[name] = v;
293
+ }
294
+ for (const name of ['fields', 'dedupeKeys']) {
295
+ if (body[name] === undefined) continue;
296
+ if (!Array.isArray(body[name]) || body[name].some(key => typeof key !== 'string' || !key)) return { ok: false, actionStarted: false, error: `${name} must be an array of nonempty strings` };
297
+ opts[name] = body[name];
298
+ }
299
+ opts.scrollDirection = body.scrollDirection === -1 ? -1 : 1;
300
+ opts.scrollIfEmpty = body.scrollIfEmpty === true;
301
+ if (!readsReaders()) fail('EXTENSION_RELOAD_REQUIRED');
302
+ bridge.authorize('read', tab, agent(owner), { reader: id });
303
+ const scrolls = Math.min(Math.max(Math.trunc(opts.scrolls ?? 0), 0), 10), maxItems = Math.max(1, Math.trunc(opts.maxItems || 50));
304
+ const dedupeKeys = opts.dedupeKeys || [], timeoutMs = Math.min(Math.max(opts.timeoutMs || EXTRACTION_TIMEOUT_MS, 1), 30000);
305
+ const deadline = Math.min(now() + timeoutMs, Number.isFinite(req?.browserRequest?.deadline) ? req.browserRequest.deadline : Infinity);
306
+ const signal = req?.browserRequest?.signal;
307
+ const keyOf = item => { for (const key of dedupeKeys) if (item[key] !== null && item[key] !== undefined && item[key] !== '') return `${key}:${item[key]}`; return JSON.stringify(item); };
308
+ const stop = (message, code) => Object.assign(new Error(message), { code, stopCode: code });
309
+ const active = () => {
310
+ if (signal?.aborted) throw stop('Extraction cancelled; collected items are preserved.', 'cancelled');
311
+ if (now() >= deadline) throw stop('Extraction deadline reached; collected items are preserved.', 'deadline');
312
+ };
313
+ const readOnce = async () => {
314
+ active();
315
+ const result = await read(s, owner, tab, { reader: id });
316
+ const items = valueOf(result);
317
+ if (!Array.isArray(items) || items.some(item => !item || typeof item !== 'object' || Array.isArray(item))) throw new Error('Extractor must return an array of objects.');
318
+ return { items, loading: result.loading === true };
319
+ };
320
+ const collected = new Map();
321
+ let raw = 0, scrollsUsed = 0, stopReason = 'scroll_limit', failureReason, dryRounds = 0, bonusRounds = 0;
322
+ const merge = items => { raw += items.length; const before = collected.size; for (const item of items) collected.set(keyOf(item), item); return collected.size - before; };
323
+ try {
324
+ let { items } = await readOnce();
325
+ for (let round = 0; ; round++) {
326
+ active();
327
+ const added = merge(items);
328
+ const budget = budgetExtractionItems([...collected.values()], opts);
329
+ if (budget.budgetReason) { stopReason = budget.budgetReason; break; }
330
+ if (collected.size >= maxItems) { stopReason = 'max_items'; break; }
331
+ if (opts.minItems && collected.size >= opts.minItems) { stopReason = 'min_items'; break; }
332
+ if (opts.scrollIfEmpty && round === 0 && collected.size === 0) bonusRounds = 1;
333
+ dryRounds = added ? 0 : dryRounds + 1;
334
+ if (dryRounds >= 2) { stopReason = 'end_of_feed'; break; }
335
+ if (round >= scrolls + bonusRounds) break;
336
+ active();
337
+ const distance = (opts.scrollDistance ?? 1200) * opts.scrollDirection;
338
+ const scrolled = await read(s, owner, tab, { reader: id, step: 'scroll', distance: Math.min(100000, Math.abs(distance)), direction: distance < 0 ? 'up' : 'down' });
339
+ let loadingBefore = scrolled.loading === true;
340
+ scrollsUsed++;
341
+ // Wait, within settleMs, for the feed to show an item not seen yet (or for its loading marker to end).
342
+ const until = Math.min(now() + Math.min(opts.settleMs ?? 3000, Math.max(1, deadline - now())), deadline);
343
+ let next = null;
344
+ for (;;) {
345
+ await sleep(Math.max(1, Math.min(150, until - now())));
346
+ const seen = await readOnce();
347
+ loadingBefore ||= seen.loading;
348
+ const fresh = seen.items.some(item => !collected.has(keyOf(item)));
349
+ if (!seen.loading && (fresh || loadingBefore)) { next = seen.items; break; }
350
+ if (now() >= until) {
351
+ if (seen.loading) throw stop('Feed is still loading after the readiness deadline; collected items are preserved.', 'readiness_timeout');
352
+ next = seen.items; break;
353
+ }
354
+ }
355
+ items = next;
356
+ }
357
+ } catch (error) {
358
+ if (error?.code === 'NOT_OWNED' || error?.code === 'TAB_CLOSED' && !collected.size) throw error;
359
+ stopReason = ['deadline', 'cancelled', 'readiness_timeout'].includes(error?.stopCode) ? error.stopCode : 'extraction_error';
360
+ failureReason = error?.answer?.error || (error?.code && !error.stopCode ? safeError(error).error : error?.message) || 'Extraction failed.';
361
+ }
362
+ const budget = budgetExtractionItems([...collected.values()], opts);
363
+ const outcome = { ...budget, raw, scrollsUsed, stopReason: budget.budgetReason || stopReason, partial: !!failureReason && collected.size > 0,
364
+ ...(failureReason ? { failureReason, ...(collected.size === 0 ? { error: failureReason } : {}) } : {}) };
365
+ return { ok: !outcome.error, url: s.tabs.get(tab)?.url || '', ...outcome };
366
+ }
367
+ // A read-only script the MCP tools tagged with the id of the extension's fixed reader that does the same
368
+ // (`body.extractor`; mcp-server/src/tools/browser-readers.ts): that reader runs, and the script never does. An id the
369
+ // extension does not have is refused (never "run the script instead"). Only an extension from before the readers
370
+ // gets the script, as browser_evaluate, exactly as before (Allow User Scripts and the publish gate apply).
371
+ async function evaluateReader(s, owner, tab, body) {
372
+ const id = body.extractor;
373
+ if (typeof id !== 'string' || !READER_IDS.includes(id) || PAGED_READERS.includes(id) || ['page.text', 'page.html'].includes(id)) {
374
+ return { ok: false, code: 'INVALID_MESSAGE', error: `INVALID_MESSAGE: ${typeof id === 'string' ? JSON.stringify(id.slice(0, 64)) : 'This value'} is not one of the extension's one-shot readers. Nothing was run.` };
375
+ }
376
+ try { return { ok: true, result: valueOf(await read(s, owner, tab, { reader: id })) }; }
377
+ catch (error) { if (error?.answer) return error.answer; throw error; }
378
+ }
205
379
  async function operation(s, owner, tab, action, body = {}, req = null) {
206
380
  if (!bridge.status().connected) fail('EXTENSION_NOT_CONNECTED');
207
381
  if (!s || !tab || !s.tabs.has(tab)) fail('TAB_CLOSED');
208
382
  if (!ownsTab(s, owner, tab)) fail('NOT_OWNED');
209
383
  const op = aliases[action] || action;
210
384
  if (!supported.has(op)) throw unsupported('This operation is not supported by the extension backend. No debugger is attached; page JavaScript runs through browser_evaluate only.');
385
+ if (op === 'evaluate' && body.extractor !== undefined && body.extractor !== null && readsReaders()) return evaluateReader(s, owner, tab, body);
211
386
  if (op === 'evaluate') return evaluate(s, owner, tab, body, req);
387
+ if (op === 'content') return contentText(s, owner, tab, body);
388
+ if (op === 'markdown') return contentMarkdown(s, owner, tab, body);
389
+ if (op === 'extract') return extract(s, owner, tab, body, req);
212
390
  let shot;
213
391
  if (op === 'screenshot') {
214
392
  shot = parseScreenshotOptions(body);
@@ -216,9 +394,9 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
216
394
  if (shot.path && screenshotPathRefusal(shot.path, { dataHome })) fail('SCREENSHOT_PATH_REFUSED');
217
395
  }
218
396
  if (op === 'wait' && body.loadState) {
219
- // A load-state wait (extension 1.4.0 and later): 'load' and 'networkidle', for the tab, not for an element (as in
220
- // the Playwright route, a selector sent with it is not used). The extension has no DOMContentLoaded signal.
221
- if (body.loadState === 'domcontentloaded') throw unsupported('Extension waits support loadState "load" and "networkidle" (and selectors and fixed delays), not "domcontentloaded".');
397
+ // A load-state wait (extension 1.4.0 and later): 'load' and 'networkidle', and from 1.5.0 'domcontentloaded' (the
398
+ // document's readyState, read by a fixed function), for the tab, not for an element (as in the Playwright route,
399
+ // a selector sent with it is not used). None of them needs "Allow User Scripts".
222
400
  if (!LOAD_STATES.includes(body.loadState)) return { ok: false, error: 'Invalid loadState. Use: load, domcontentloaded, networkidle' };
223
401
  const timeout = milliseconds(body.timeout, NETWORK_IDLE_TIMEOUT_MAX);
224
402
  return worded(finish(s, tab, await bridge.request('wait', tab, agent(owner), { loadState: body.loadState, ...(timeout ? { timeout } : {}) })));
@@ -232,6 +410,15 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
232
410
  }
233
411
  const args = {};
234
412
  for (const k of argumentKeys) if (body[k] !== undefined && body[k] !== null) args[k] = ['nthMatch', 'distance', 'maxChars', 'offset', 'timeout'].includes(k) ? Number(body[k]) : body[k];
413
+ if (op === 'snapshot') {
414
+ // An extension with the readers pages its snapshot (offset, default 0) and says how long it is; an older one
415
+ // never gets an offset (it would not know what to answer with).
416
+ if (readsReaders()) args.offset = Number.isSafeInteger(args.offset) && args.offset > 0 ? args.offset : 0; else delete args.offset;
417
+ const result = finish(s, tab, await bridge.request('snapshot', tab, agent(owner), args));
418
+ if (!result.ok || result.snapshotTotal === undefined) return result;
419
+ const { snapshotTotal, snapshotNext, ...rest } = result, more = snapshotNext < snapshotTotal;
420
+ return { ...rest, snapshotBudgetApplied: true, snapshotOffset: args.offset, snapshotTotalChars: snapshotTotal, ...(more ? { snapshotTruncated: true, snapshotNextOffset: snapshotNext } : {}) };
421
+ }
235
422
  let upload;
236
423
  if (op === 'upload') {
237
424
  bridge.authorize(op, tab, agent(owner), args);
@@ -272,8 +459,23 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
272
459
  }
273
460
  return result;
274
461
  }
275
- function denied(res, error) {
462
+ async function describeError(error) {
276
463
  const body = safeError(error);
464
+ if (body.code === 'EXTENSION_NOT_CONNECTED' || body.code === 'NOT_CONNECTED') {
465
+ // The handshake carries no paired browser/profile identity. Only the connection can be checked live. An unpaired
466
+ // or paused bridge is fixed in SynaBun, not from the extension's popup (which a paused bridge refuses): the advice
467
+ // says so (review round 3, I7b).
468
+ const status = bridge.status();
469
+ const advice = status.connected ? 'The extension has reconnected. Retry the browser tool.'
470
+ : status.paired === false ? 'The SynaBun browser extension is not paired. Pair it in SynaBun Settings → Browser (Start pairing), then retry the browser tool.'
471
+ : status.paused === true ? 'The browser extension bridge is paused: it was disconnected in SynaBun Settings → Browser. Resume it there (Reconnect), then retry the browser tool.'
472
+ : connectionAdvice();
473
+ body.error = `${body.code}: ${advice}`;
474
+ }
475
+ return body;
476
+ }
477
+ async function denied(res, error) {
478
+ const body = await describeError(error);
277
479
  if (body.code === 'UNSUPPORTED_IN_EXTENSION_MODE') body.error = `${body.code}: ${error.message}`;
278
480
  else if (body.code === 'SITE_NOT_APPROVED' && typeof error.reason === 'string') body.error = `${body.code}: ${error.reason}`;
279
481
  return res.status(body.code === 'TAB_CLOSED' ? 410 : body.code === 'EXTENSION_NOT_CONNECTED' || body.code === 'NOT_CONNECTED' ? 503 : 403).json(body);
@@ -300,11 +502,11 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
300
502
  let nav, failure = null;
301
503
  try { nav = await operation(created, owner, acq.browserTabId, 'navigate', { url: req.body.url }); } catch (error) { failure = error; }
302
504
  if (failure || !nav?.ok) {
303
- const body = failure ? safeError(failure) : { ...safeError(nav), ...(typeof nav?.error === 'string' ? { error: nav.error } : {}) };
505
+ const body = failure ? await describeError(failure) : { ...safeError(nav), ...(typeof nav?.error === 'string' ? { error: nav.error } : {}) };
304
506
  let released = false;
305
507
  if (!acq.reused) { try { await release(acq.browserSessionId, owner, acq.browserTabId); released = true; } catch {} }
306
508
  const closing = acq.reused ? 'Your tab stays as it was.' : released ? (adopt ? 'The taken-over tab went back to the owner, open; you hold no tab from this create.' : 'The tab this create opened was closed; nothing was left open.') : 'The tab this create opened could not be closed (the extension did not answer); it stays yours: close it with browser_session close.';
307
- try { log({ command: 'create', tab: null, code: body.code }); } catch {}
509
+ try { log({ command: 'create', tab: null, code: body.code, ...(errorDetail(body) ? { detail: errorDetail(body) } : {}) }); } catch {}
308
510
  return res.status(body.code === 'EXTENSION_NOT_CONNECTED' || body.code === 'NOT_CONNECTED' ? 503 : 403)
309
511
  .json({ ...body, error: `${body.error} ${closing}`, tabReleased: released, ...(acq.reused || !released ? { sessionId: acq.browserSessionId, tabId: acq.browserTabId } : {}) });
310
512
  }
@@ -332,7 +534,11 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
332
534
  const result = await operation(s, owner, tab, match[2], body, req);
333
535
  // 409: the publish gate's refusal, as the Playwright routes answer it.
334
536
  return res.status(result.ok ? 200 : result.code === 'TAB_CLOSED' ? 410 : result.quoteGuard ? 409 : 400).json(result);
335
- } catch (error) { try { log({ command: supported.has(match?.[2]) ? match[2] : 'session', tab: null, code: safeError(error).code }); } catch {} return denied(res, error); }
537
+ } catch (error) {
538
+ const command = supported.has(match?.[2]) ? match[2] : req.method === 'POST' && ['/sessions', '/acquire'].includes(req.path) ? 'create' : 'session', said = safeError(error);
539
+ try { log({ command, tab: null, code: said.code, ...(errorDetail(said) ? { detail: errorDetail(said) } : {}) }); } catch {}
540
+ return denied(res, error);
541
+ }
336
542
  }
337
- return { acquire, release, destroy, sync, operation, middleware, agent, session, ownerTabs, ownsTab };
543
+ return { acquire, describeError, release, destroy, sync, operation, middleware, agent, session, ownerTabs, ownsTab };
338
544
  }
@@ -5,7 +5,7 @@ import { compareVersions } from './browser-extension-folder.js';
5
5
  import { dirname } from 'node:path';
6
6
  import { lookup } from 'node:dns/promises';
7
7
  import { WebSocketServer } from 'ws';
8
- import { anyOrigin, channel, command, COMMAND_WAIT, commandWait as operationWait, CONTROL, controlSurface, equalMac, ERROR_TEXT, fail, handle, HISTORY, inventory, localHost, LONG_OPS_SINCE, longOp, mac, MAX_MESSAGE, nonce, object, pairingKey, parse, payload, portOf, publicOrigin, safeError, string } from './browser-extension-protocol.js';
8
+ import { anyOrigin, channel, command, COMMAND_WAIT, commandWait as operationWait, CONTROL, controlSurface, equalMac, ERROR_TEXT, fail, handle, HISTORY, inventory, localHost, LONG_OPS_SINCE, longOp, mac, MAX_MESSAGE, nonce, object, pairingKey, parse, payload, portOf, publicOrigin, READS_SINCE, requiredVersion, safeError, SELF_RELOAD_SINCE, string, cleanDetail, errorDetail } from './browser-extension-protocol.js';
9
9
  import { EXTENSION_ID } from './browser-extension-pin.js';
10
10
 
11
11
  // The wire contract is the app's own copy of the extension's protocol.js (kept byte-identical by
@@ -62,7 +62,7 @@ export function createBridgeStore(path) {
62
62
  // SynaBun's own addresses stay out of reach in both modes: `forbiddenOrigins` (its public aliases, any port),
63
63
  // `blockedPorts` (its ports; the bridge's own is always added) on this computer, which is localhost, a loopback address
64
64
  // or one of `selfHosts` (its names and interface addresses) or a name that resolves to one (`lookupAddresses`).
65
- export function createExtensionBridge({ port = 3345, log = () => {}, onInventory = () => {}, resolvePublic = publicDestination, now = Date.now, forbiddenOrigins = () => [], revokedTabsKept = 1024,
65
+ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory = () => {}, onConnected = () => {}, updateStatus = () => null, runsActive = () => false, resolvePublic = publicDestination, now = Date.now, forbiddenOrigins = () => [], revokedTabsKept = 1024,
66
66
  commandWait = COMMAND_WAIT, clock = () => performance.now(), fullControl = true, store = null, blockedPorts = () => [], selfHosts = () => [],
67
67
  lookupAddresses = host => lookup(host, { all: true }) } = {}) {
68
68
  if (!Number.isSafeInteger(commandWait) || commandWait < 1 || commandWait > COMMAND_WAIT) fail('INVALID_MESSAGE');
@@ -126,7 +126,15 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
126
126
  }
127
127
  const pending = new Map();
128
128
  const sockets = new Set();
129
- const note = (op, tab, code) => { try { log({ command: op, tab: typeof tab === 'string' && /^[a-f0-9]{32}$/.test(tab) ? tab : null, code: code === 'OK' || Object.hasOwn(ERROR_TEXT, code) ? code : 'OPERATION_FAILED' }); } catch {} };
129
+ // The probes waiting for a fresh capabilities report (probe()): each is called with the peer whose report arrived,
130
+ // or with ENDED when the owner ended the connection or the pairing.
131
+ const observers = new Set(), ENDED = Symbol('ended');
132
+ // One log line per command: its op, the tab's opaque handle, the outcome's code and, when the browser refused it,
133
+ // what the browser said (`detail`, a chrome.* error message: cleanDetail; never a page's content or a credential).
134
+ const note = (op, tab, code, detail) => {
135
+ const said = cleanDetail(detail);
136
+ try { log({ command: op, tab: typeof tab === 'string' && /^[a-f0-9]{32}$/.test(tab) ? tab : null, code: code === 'OK' || Object.hasOwn(ERROR_TEXT, code) ? code : 'OPERATION_FAILED', ...(said ? { detail: said } : {}) }); } catch {}
137
+ };
130
138
  const coded = code => () => Object.assign(new Error(code), { code });
131
139
  const notConnected = coded('NOT_CONNECTED'), cancelled = coded('CANCELLED');
132
140
  // Rejects pending requests at once. `keepControl` spares the owner's own revocations, which must still reach the extension.
@@ -152,11 +160,24 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
152
160
  to.pushedMode = key;
153
161
  void request('mode', null, 'owner', { fullControl: mode.fullControl, version: mode.version }).catch(() => { if (to.pushedMode === key) to.pushedMode = null; });
154
162
  }
163
+ // Read-only hint for the popup. Older peers reject unknown payloads. Never send a reload from here.
164
+ function publishUpdate() {
165
+ const to = peer;
166
+ if (!to?.ready || compareVersions(to.version, SELF_RELOAD_SINCE) < 0) return;
167
+ const status = updateStatus(to.version);
168
+ if (!status) return;
169
+ const message = { type: 'updateStatus', version: status.version, runsActive: runsActive() };
170
+ const key = JSON.stringify(message);
171
+ if (key === to.updateKey) return;
172
+ to.updateKey = key;
173
+ void to.send(payload(message)).catch(() => { if (to.updateKey === key) to.updateKey = null; });
174
+ }
155
175
  function update(value, from = null) {
156
176
  const { versions, fullControl: fullControlNow, modeVersion, ...next } = inventory(value);
157
177
  if (from && modeVersion !== undefined) peerMode(from, fullControlNow, modeVersion);
158
178
  if (from && !from.ready) {
159
179
  from.ready = true;
180
+ onConnected(from.version); publishUpdate();
160
181
  // Only an extension that knows `reset` (it reports a mode) is sent one; an older one keeps what it holds.
161
182
  if (resetDue && modeVersion !== undefined) { resetDue = false; void request('reset', null, 'owner').catch(() => { resetDue = true; }); }
162
183
  }
@@ -165,6 +186,14 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
165
186
  next.sites = next.sites.filter((site, i) => !revokedSites.has(site) || (versions ? versions[i] : siteVersions.get(site) || 0) > revokedSites.get(site));
166
187
  state = next; revision++; onInventory({ ...state, fullControl: mode.fullControl });
167
188
  }
189
+ // What the extension saw of this browser (protocol.js capabilityReport), kept on the peer that said it with the time
190
+ // it arrived: a disconnect, a reload or a new pairing (no peer, or a new one) leaves nothing of it behind. Taken from
191
+ // the current peer only, once its first inventory made it the connection agents use.
192
+ function observe(from, report) {
193
+ if (!from || from !== peer || !from.ready || from.generation !== authentication) return;
194
+ from.capabilities = { ...structuredClone(report), observedAt: now() };
195
+ for (const waiter of [...observers]) waiter(from);
196
+ }
168
197
  // An owner revocation begins: cancel everything issued before it, synchronously, before the extension is told.
169
198
  function revoking() { revocations++; settle(cancelled, true); }
170
199
  // Ends the connection and every handshake still under way; nothing admitted before acts after.
@@ -172,6 +201,7 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
172
201
  enabled = false; authentication++; revocations++;
173
202
  peer = null; for (const ws of sockets) ws.close();
174
203
  settle(notConnected);
204
+ for (const waiter of [...observers]) waiter(ENDED);
175
205
  }
176
206
  // The owner's Disconnect: kept across a restart (the bridge stays off until Resume).
177
207
  function disconnect() { cut(); persist(); }
@@ -239,7 +269,13 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
239
269
  };
240
270
  const timer = setTimeout(() => ws.close(), 10000); timer.unref?.();
241
271
  let lastSeen = Date.now();
242
- const heartbeat = setInterval(() => { if (Date.now() - lastSeen > 65000) ws.close(); else if (wire) void send({ type: 'ping' }).catch(() => ws.close()); }, 20000); heartbeat.unref?.();
272
+ const heartbeat = setInterval(() => {
273
+ if (Date.now() - lastSeen > 65000) { ws.close(); return; }
274
+ if (!wire) return;
275
+ if (peer?.ws === ws) publishUpdate();
276
+ void send({ type: 'ping' }).catch(() => ws.close());
277
+ }, 20000);
278
+ heartbeat.unref?.();
243
279
  ws.send(JSON.stringify({ type: 'challenge', session }));
244
280
  ws.on('message', raw => {
245
281
  chain = chain.then(async () => {
@@ -264,7 +300,7 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
264
300
  if (admitted !== authentication || !enabled || ws.readyState !== 1
265
301
  || (isPair ? pair !== pairWindow || pairWindow.until < now() : key !== credential || now() >= credentialUntil)) fail('AUTH_FAILED');
266
302
  const previous = peer;
267
- peer = { ws, send, session, key, generation: admitted, ready: false, pushedMode: null, version: hello.version || null }; previous?.ws.close();
303
+ peer = { ws, send, session, key, generation: admitted, ready: false, pushedMode: null, version: hello.version || null, capabilities: null }; previous?.ws.close();
268
304
  if (previous) settle(notConnected);
269
305
  // A new pairing starts from a cleared extension: nothing of a previous process to hand back.
270
306
  // A setup's token is gone with it (single use): `pair` is cleared in this same step. A setup pairing, like a
@@ -281,6 +317,8 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
281
317
  const message = payload(await wire.decode(raw.toString())); lastSeen = Date.now();
282
318
  if (message.type === 'pong') return;
283
319
  if (message.type === 'unpair') { revoke(); return; }
320
+ // A report from this socket's peer only (the decoding above awaited: the peer may have changed meanwhile).
321
+ if (message.type === 'capabilities') { if (peer?.ws === ws) observe(peer, message.capabilities); return; }
284
322
  if (message.type !== 'state' && message.type !== 'result') fail('INVALID_MESSAGE');
285
323
  update(message.inventory, peer);
286
324
  if (message.type === 'result') {
@@ -302,10 +340,17 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
302
340
  }
303
341
  function authorize(op, tab, owner, args = {}) {
304
342
  authorizeAccess(op, tab, owner, args);
343
+ if (op === 'selfReload') {
344
+ if (compareVersions(peer.version, SELF_RELOAD_SINCE) < 0) fail('EXTENSION_RELOAD_REQUIRED');
345
+ if (!args.allowBusy && (state.tabs.some(tab => tab.owner) || runsActive())) fail('RELOAD_BUSY');
346
+ }
305
347
  if (op === 'upload' && compareVersions(peer.version, '1.3.0') < 0) fail('UPLOAD_RELOAD_REQUIRED');
306
348
  // An extension from before the long operations ends the connection on a command it does not know (its payload()
307
349
  // throws while it authenticates the message): it is never sent one. The owner reloads the extension instead.
308
350
  if (longOp(op, args) && compareVersions(peer.version, LONG_OPS_SINCE) < 0) fail('EXTENSION_RELOAD_REQUIRED');
351
+ // The fixed readers, a snapshot's `offset` and the domcontentloaded wait (1.5.0) likewise.
352
+ const needs = requiredVersion(op, args);
353
+ if (needs && compareVersions(peer.version, needs) < 0) fail('EXTENSION_RELOAD_REQUIRED');
309
354
  }
310
355
  function authorizeAccess(op, tab, owner, args) {
311
356
  if (!enabled || !peer || peer.ws.readyState !== 1) fail('EXTENSION_NOT_CONNECTED');
@@ -375,11 +420,37 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
375
420
  if (stale()) fail('CANCELLED');
376
421
  authorize(op, tab, owner, args);
377
422
  }
378
- note(op, tab || result.tab, result.code || 'OK'); return result;
423
+ note(op, tab || result.tab, result.code || 'OK', result.ok === false ? errorDetail(result) : ''); return result;
379
424
  } catch (error) { note(op, tab, safeError(error).code); throw error; }
380
425
  }
426
+ // "Check again": a fresh capabilities report. Only an ordinary ping goes out (an extension from before 1.6.0 ends the
427
+ // connection on any type it does not know); 1.6.0 and later answer every ping with a pong and a new report. Waits for
428
+ // the first report that arrives after the ping was asked for, from this peer or from one that replaced it (a reload
429
+ // of the extension), up to `timeoutMs`. Resolves { ok: true, capabilities, legacy }: `capabilities` the fresh report
430
+ // (with its `observedAt`) or null, `legacy` true when none came and the extension connected now never sent one (it
431
+ // predates the reports); or { ok: false, code: 'NOT_CONNECTED' }. Never throws.
432
+ async function probe(options = {}) {
433
+ try {
434
+ const timeoutMs = options?.timeoutMs ?? 4000;
435
+ const wait = Number.isFinite(timeoutMs) ? Math.max(1, Math.min(60000, Math.floor(timeoutMs))) : 4000;
436
+ const asked = peer;
437
+ if (!enabled || !asked?.ready || asked.ws.readyState !== 1) return { ok: false, code: 'NOT_CONNECTED' };
438
+ const fresh = await new Promise(resolve => {
439
+ let timer = null;
440
+ const done = value => { clearTimeout(timer); observers.delete(done); resolve(value); };
441
+ observers.add(done);
442
+ timer = setTimeout(() => done(null), wait); timer.unref?.();
443
+ void asked.send({ type: 'ping' }).catch(() => {});
444
+ });
445
+ if (fresh && fresh !== ENDED && fresh.capabilities) return { ok: true, capabilities: structuredClone(fresh.capabilities), legacy: false };
446
+ const current = peer;
447
+ if (fresh === ENDED || !enabled || !current?.ready || current.ws.readyState !== 1) return { ok: false, code: 'NOT_CONNECTED' };
448
+ return { ok: true, capabilities: null, legacy: !current.capabilities };
449
+ } catch { return { ok: false, code: 'NOT_CONNECTED' }; }
450
+ }
381
451
  return {
382
- request, authorize,
452
+ probe,
453
+ request, authorize, publishUpdate,
383
454
  // Whether an agent may be shown or given this page in full control (the session listing): never a browser page
384
455
  // or SynaBun's own.
385
456
  openable: url => { try { openable(url); return true; } catch { return false; } },
@@ -438,8 +509,17 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
438
509
  setupPairing: () => ({ active: !!pair?.setup && pair.until >= now() && pairingAttempts <= 5, attempted: pair?.setup ? pair.attempted === true : false }),
439
510
  // Diagnostics: how many revocation records the bridge keeps (counts only).
440
511
  records: () => ({ revokedTabs: revokedTabs.size, revokedSites: revokedSites.size, siteVersions: siteVersions.size }),
441
- status: () => ({ connected: !!peer && enabled && peer.ready === true, paired: !!credential, port: server?.address()?.port || port, extensionId: EXTENSION_ID,
442
- fullControl: mode.fullControl, pairedAt: credential ? pairedAt : 0, extensionVersion: peer?.ready ? peer.version : null, ...structuredClone(state) }),
512
+ // `paused`: the owner's Disconnect in Settings → Browser holds (kept across a restart until Reconnect / Resume);
513
+ // the extension's own popup cannot reconnect then (AUTH_FAILED).
514
+ // `capabilities`: the connected extension's last report of what this browser allows (protocol.js capabilityReport,
515
+ // with `observedAt`, the time it arrived), or null: none connected, or one that sent none (before 1.6.0). Refreshed
516
+ // with every heartbeat ping, and at once by probe().
517
+ status: () => {
518
+ const connected = peer?.ws.readyState === 1 && enabled && peer.ready === true;
519
+ return { connected, paired: !!credential, paused: !enabled, port: server?.address()?.port || port, extensionId: EXTENSION_ID,
520
+ fullControl: mode.fullControl, pairedAt: credential ? pairedAt : 0, extensionVersion: peer?.ready ? peer.version : null,
521
+ capabilities: connected && peer.capabilities ? structuredClone(peer.capabilities) : null, ...structuredClone(state) };
522
+ },
443
523
  disconnect,
444
524
  resume: () => { enabled = true; persist(); },
445
525
  revoke,