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
@@ -1,22 +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 { fileURLToPath } from 'node:url';
6
- 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';
7
7
  import sharp from 'sharp';
8
8
  import { parseScreenshotOptions, screenshotPathRefusal, defaultScreenshotPath, writeScreenshotFile } from './browser-screenshot.js';
9
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';
10
12
 
11
- export const EXTENSION_FOLDER = fileURLToPath(new URL('../../browser-extension/', import.meta.url));
12
- // 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.
13
15
  export function uploadMimeType(name) {
16
+ const named = uploadType(name);
17
+ if (named !== 'application/octet-stream') return named;
14
18
  const ext = extname(name).toLowerCase();
15
- if (['.heic', '.heif', '.avif'].includes(ext)) return 'image/' + ext.slice(1);
16
- return express.static.mime.lookup(ext);
19
+ return (ext && express.static.mime.lookup(ext)) || named;
17
20
  }
18
21
  const aliases = { 'screenshot-base64': 'screenshot' };
19
- 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.';
20
39
  const argumentKeys = ['url', 'ref', 'selector', 'nthMatch', 'value', 'text', 'key', 'direction', 'distance', 'maxChars', 'offset', 'timeout', 'state'];
21
40
  const unsupported = reason => Object.assign(new Error(reason), { code: 'UNSUPPORTED_IN_EXTENSION_MODE' });
22
41
  // A whole number of milliseconds from a request body, 1 to `most`; undefined when none (or nothing usable) was given.
@@ -50,7 +69,10 @@ const HISTORY_DESTINATION = 'The page this history step reached is not on an app
50
69
  // `refusal({ session, req, tabId, script })` answers the X publish gate's refusal (or null), `run({ session, req, execute })`
51
70
  // spaces a social write (`pace` in the body) and answers { result } or { paced } with it. Without one, nothing is gated
52
71
  // (tests of the adapter alone).
53
- 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)) }) {
54
76
  const salt = randomBytes(32).toString('hex');
55
77
  const agent = owner => createHash('sha256').update(`${salt}:${owner}`).digest('hex');
56
78
  let sessionId = null, chain = Promise.resolve();
@@ -102,7 +124,8 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
102
124
  const status = bridge.status();
103
125
  const shared = target || (status.fullControl ? null : status.tabs.find(t => t.owner === null && !t.created));
104
126
  const result = await bridge.request(shared ? 'claim' : 'create', shared?.handle || null, opaque);
105
- 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) });
106
129
  const tab = result.tab;
107
130
  const now = bridge.status(), reading = now.tabs.find(t => t.handle === tab && t.owner === opaque);
108
131
  if (!reading) fail('TAB_NOT_APPROVED');
@@ -204,13 +227,166 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
204
227
  if (outcome.paced?.pending) return { ok: true, paced: outcome.paced };
205
228
  return { ok: true, result: outcome.result === undefined ? null : outcome.result, ...(cut || {}), ...(outcome.paced ? { paced: outcome.paced } : {}) };
206
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
+ }
207
379
  async function operation(s, owner, tab, action, body = {}, req = null) {
208
380
  if (!bridge.status().connected) fail('EXTENSION_NOT_CONNECTED');
209
381
  if (!s || !tab || !s.tabs.has(tab)) fail('TAB_CLOSED');
210
382
  if (!ownsTab(s, owner, tab)) fail('NOT_OWNED');
211
383
  const op = aliases[action] || action;
212
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);
213
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);
214
390
  let shot;
215
391
  if (op === 'screenshot') {
216
392
  shot = parseScreenshotOptions(body);
@@ -218,9 +394,9 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
218
394
  if (shot.path && screenshotPathRefusal(shot.path, { dataHome })) fail('SCREENSHOT_PATH_REFUSED');
219
395
  }
220
396
  if (op === 'wait' && body.loadState) {
221
- // A load-state wait (extension 1.4.0 and later): 'load' and 'networkidle', for the tab, not for an element (as in
222
- // the Playwright route, a selector sent with it is not used). The extension has no DOMContentLoaded signal.
223
- 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".
224
400
  if (!LOAD_STATES.includes(body.loadState)) return { ok: false, error: 'Invalid loadState. Use: load, domcontentloaded, networkidle' };
225
401
  const timeout = milliseconds(body.timeout, NETWORK_IDLE_TIMEOUT_MAX);
226
402
  return worded(finish(s, tab, await bridge.request('wait', tab, agent(owner), { loadState: body.loadState, ...(timeout ? { timeout } : {}) })));
@@ -234,6 +410,15 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
234
410
  }
235
411
  const args = {};
236
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
+ }
237
422
  let upload;
238
423
  if (op === 'upload') {
239
424
  bridge.authorize(op, tab, agent(owner), args);
@@ -274,8 +459,23 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
274
459
  }
275
460
  return result;
276
461
  }
277
- function denied(res, error) {
462
+ async function describeError(error) {
278
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);
279
479
  if (body.code === 'UNSUPPORTED_IN_EXTENSION_MODE') body.error = `${body.code}: ${error.message}`;
280
480
  else if (body.code === 'SITE_NOT_APPROVED' && typeof error.reason === 'string') body.error = `${body.code}: ${error.reason}`;
281
481
  return res.status(body.code === 'TAB_CLOSED' ? 410 : body.code === 'EXTENSION_NOT_CONNECTED' || body.code === 'NOT_CONNECTED' ? 503 : 403).json(body);
@@ -302,11 +502,11 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
302
502
  let nav, failure = null;
303
503
  try { nav = await operation(created, owner, acq.browserTabId, 'navigate', { url: req.body.url }); } catch (error) { failure = error; }
304
504
  if (failure || !nav?.ok) {
305
- 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 } : {}) };
306
506
  let released = false;
307
507
  if (!acq.reused) { try { await release(acq.browserSessionId, owner, acq.browserTabId); released = true; } catch {} }
308
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.';
309
- 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 {}
310
510
  return res.status(body.code === 'EXTENSION_NOT_CONNECTED' || body.code === 'NOT_CONNECTED' ? 503 : 403)
311
511
  .json({ ...body, error: `${body.error} ${closing}`, tabReleased: released, ...(acq.reused || !released ? { sessionId: acq.browserSessionId, tabId: acq.browserTabId } : {}) });
312
512
  }
@@ -334,7 +534,11 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
334
534
  const result = await operation(s, owner, tab, match[2], body, req);
335
535
  // 409: the publish gate's refusal, as the Playwright routes answer it.
336
536
  return res.status(result.ok ? 200 : result.code === 'TAB_CLOSED' ? 410 : result.quoteGuard ? 409 : 400).json(result);
337
- } 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
+ }
338
542
  }
339
- return { acquire, release, destroy, sync, operation, middleware, agent, session, ownerTabs, ownsTab };
543
+ return { acquire, describeError, release, destroy, sync, operation, middleware, agent, session, ownerTabs, ownsTab };
340
544
  }
@@ -0,0 +1,149 @@
1
+ // The extension package: which files an extension folder may hold, and the one zip form SynaBun writes and reads.
2
+ //
3
+ // One allowlist for everything (extensionFileAllowed): the manifest, scripts, pages, styles at the top and the PNGs
4
+ // in `icons/`. The folder the owner loads, a folder read as a source (Dev's build, tests) and a downloaded package
5
+ // are all held to it.
6
+ //
7
+ // The package is a zip SynaBun builds itself (scripts/extension/build-browser-extension.mjs, Dev only) in one fixed
8
+ // form, so two builds of the same files are the same bytes on any machine and any Node: entries sorted by name, every
9
+ // one STORED (no deflate, whose output depends on the zlib at hand), one fixed time, one fixed mode, no folder
10
+ // entries, no extra fields, no comments. readExtensionZip accepts only that form, which is also what makes a hostile
11
+ // file harmless: nothing is inflated (no zip bomb), a name outside the allowlist, a link, a second entry of a name, a
12
+ // gap or bytes after the directory are each a refusal, and every entry's CRC is checked. It returns bytes in memory and
13
+ // writes nothing; the caller has verified the file's size and SHA-256 before it calls (lib/browser-extension-package.js).
14
+ import { lstatSync, readdirSync, readFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { crc32 } from 'node:zlib';
17
+
18
+ const FILE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(js|json|html|css|png)$/;
19
+ const ICON = /^[A-Za-z0-9][A-Za-z0-9._-]*\.png$/;
20
+ /** The most entries a package may hold, and the most bytes one of them may be. */
21
+ export const EXTENSION_MAX_FILES = 64;
22
+ export const EXTENSION_MAX_FILE_BYTES = 4 * 1024 * 1024;
23
+
24
+ const fail = (message) => { throw Object.assign(new Error(message), { code: 'EXTENSION_ARCHIVE_INVALID' }); };
25
+
26
+ /** Whether `rel` (forward slashes, relative to the extension folder) is a file an extension folder may hold. */
27
+ export function extensionFileAllowed(rel) {
28
+ if (typeof rel !== 'string') return false;
29
+ const parts = rel.split('/');
30
+ if (parts.length === 1) return FILE.test(parts[0]);
31
+ return parts.length === 2 && parts[0] === 'icons' && ICON.test(parts[1]);
32
+ }
33
+
34
+ /**
35
+ * A folder's extension files, by path relative to it: regular files of the allowlist (a link is never followed), the
36
+ * top level and `icons/`, sorted by name. Returns [{ rel, bytes }].
37
+ */
38
+ export function readExtensionSource(source) {
39
+ const files = [];
40
+ for (const [dir, prefix] of [[source, ''], [join(source, 'icons'), 'icons/']]) {
41
+ let names = [];
42
+ try { names = readdirSync(dir); } catch { continue; }
43
+ for (const name of names) {
44
+ const rel = prefix + name;
45
+ if (!extensionFileAllowed(rel)) continue;
46
+ const path = join(dir, name);
47
+ try { if (!lstatSync(path).isFile()) continue; } catch { continue; }
48
+ files.push({ rel, bytes: readFileSync(path) });
49
+ }
50
+ }
51
+ return files.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
52
+ }
53
+
54
+ // 1980-01-01 00:00:00, the first moment a zip can name; rw-r--r-- on a regular file, written by "Unix".
55
+ const DOS_TIME = 0, DOS_DATE = 0x0021, MADE_BY = 0x031e, NEEDED = 10, MODE = 0o100644;
56
+ const LOCAL = 0x04034b50, CENTRAL = 0x02014b50, END = 0x06054b50;
57
+
58
+ function checkFiles(files) {
59
+ if (!Array.isArray(files) || !files.length) fail('The extension has no files.');
60
+ if (files.length > EXTENSION_MAX_FILES) fail('The extension has too many files.');
61
+ const seen = new Set();
62
+ for (const file of files) {
63
+ if (!extensionFileAllowed(file?.rel)) fail('The extension holds a file that is not allowed.');
64
+ if (!Buffer.isBuffer(file.bytes) || file.bytes.length > EXTENSION_MAX_FILE_BYTES) fail('A file of the extension is too large.');
65
+ const key = file.rel.toLowerCase();
66
+ if (seen.has(key)) fail('The extension names a file twice.');
67
+ seen.add(key);
68
+ }
69
+ if (!seen.has('manifest.json')) fail('The extension has no manifest.');
70
+ }
71
+
72
+ /** The package of `files` ([{ rel, bytes }]) in SynaBun's one zip form. The same files give the same bytes. */
73
+ export function writeExtensionZip(files) {
74
+ checkFiles(files);
75
+ const sorted = [...files].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
76
+ const parts = [], directory = [];
77
+ let offset = 0;
78
+ for (const { rel, bytes } of sorted) {
79
+ const name = Buffer.from(rel, 'ascii'), crc = crc32(bytes);
80
+ const local = Buffer.alloc(30);
81
+ local.writeUInt32LE(LOCAL, 0); local.writeUInt16LE(NEEDED, 4); local.writeUInt16LE(0, 6); local.writeUInt16LE(0, 8);
82
+ local.writeUInt16LE(DOS_TIME, 10); local.writeUInt16LE(DOS_DATE, 12); local.writeUInt32LE(crc, 14);
83
+ local.writeUInt32LE(bytes.length, 18); local.writeUInt32LE(bytes.length, 22); local.writeUInt16LE(name.length, 26); local.writeUInt16LE(0, 28);
84
+ const central = Buffer.alloc(46);
85
+ central.writeUInt32LE(CENTRAL, 0); central.writeUInt16LE(MADE_BY, 4); central.writeUInt16LE(NEEDED, 6); central.writeUInt16LE(0, 8); central.writeUInt16LE(0, 10);
86
+ central.writeUInt16LE(DOS_TIME, 12); central.writeUInt16LE(DOS_DATE, 14); central.writeUInt32LE(crc, 16);
87
+ central.writeUInt32LE(bytes.length, 20); central.writeUInt32LE(bytes.length, 24); central.writeUInt16LE(name.length, 28);
88
+ central.writeUInt16LE(0, 30); central.writeUInt16LE(0, 32); central.writeUInt16LE(0, 34); central.writeUInt16LE(0, 36);
89
+ central.writeUInt32LE((MODE << 16) >>> 0, 38); central.writeUInt32LE(offset, 42);
90
+ parts.push(local, name, bytes); directory.push(central, name);
91
+ offset += 30 + name.length + bytes.length;
92
+ }
93
+ const directoryBytes = Buffer.concat(directory);
94
+ const end = Buffer.alloc(22);
95
+ end.writeUInt32LE(END, 0); end.writeUInt16LE(0, 4); end.writeUInt16LE(0, 6); end.writeUInt16LE(sorted.length, 8); end.writeUInt16LE(sorted.length, 10);
96
+ end.writeUInt32LE(directoryBytes.length, 12); end.writeUInt32LE(offset, 16); end.writeUInt16LE(0, 20);
97
+ return Buffer.concat([...parts, directoryBytes, end]);
98
+ }
99
+
100
+ /**
101
+ * The files of a package in SynaBun's one zip form: [{ rel, bytes }], sorted by name. Throws
102
+ * EXTENSION_ARCHIVE_INVALID for anything else (see the top of this file); never writes and never inflates.
103
+ */
104
+ export function readExtensionZip(zip) {
105
+ if (!Buffer.isBuffer(zip) || zip.length < 22) fail('The package is not a zip file.');
106
+ const endAt = zip.length - 22;
107
+ if (zip.readUInt32LE(endAt) !== END) fail('The package does not end as SynaBun writes it.');
108
+ const count = zip.readUInt16LE(endAt + 10), directorySize = zip.readUInt32LE(endAt + 12), directoryAt = zip.readUInt32LE(endAt + 16);
109
+ if (zip.readUInt16LE(endAt + 4) || zip.readUInt16LE(endAt + 6) || zip.readUInt16LE(endAt + 8) !== count || zip.readUInt16LE(endAt + 20)) fail('The package is not a plain single zip file.');
110
+ if (!count || count > EXTENSION_MAX_FILES) fail('The package holds no files, or too many.');
111
+ if (directoryAt + directorySize !== endAt) fail('The package has bytes its directory does not account for.');
112
+ const files = [], seen = new Set();
113
+ let at = directoryAt, dataAt = 0, previous = '';
114
+ for (let i = 0; i < count; i++) {
115
+ if (at + 46 > endAt || zip.readUInt32LE(at) !== CENTRAL) fail('The package directory is damaged.');
116
+ const flags = zip.readUInt16LE(at + 8), method = zip.readUInt16LE(at + 10), crc = zip.readUInt32LE(at + 16);
117
+ const packed = zip.readUInt32LE(at + 20), size = zip.readUInt32LE(at + 24), nameLength = zip.readUInt16LE(at + 28);
118
+ const attributes = zip.readUInt32LE(at + 38), localAt = zip.readUInt32LE(at + 42);
119
+ if (flags !== 0 || method !== 0 || packed !== size) fail('The package holds an entry that is compressed, encrypted or streamed.');
120
+ if (zip.readUInt16LE(at + 30) || zip.readUInt16LE(at + 32) || zip.readUInt16LE(at + 34)) fail('The package holds an entry with extra data.');
121
+ // Every other field is the one value SynaBun's writer puts there: the version needed, the time, the date, the
122
+ // internal attributes (and, below, the same in the entry's own header).
123
+ if (zip.readUInt16LE(at + 6) !== NEEDED || zip.readUInt16LE(at + 12) !== DOS_TIME || zip.readUInt16LE(at + 14) !== DOS_DATE || zip.readUInt16LE(at + 36) !== 0) fail('The package holds an entry that SynaBun did not write.');
124
+ if (size > EXTENSION_MAX_FILE_BYTES) fail('The package holds a file that is too large.');
125
+ if (at + 46 + nameLength > endAt) fail('The package directory is damaged.');
126
+ const nameBytes = zip.subarray(at + 46, at + 46 + nameLength), rel = nameBytes.toString('latin1');
127
+ // A regular file and nothing else: a link, a folder, a device are told by the Unix mode a zip keeps for its maker.
128
+ if (zip.readUInt16LE(at + 4) !== MADE_BY || (attributes >>> 16) !== MODE) fail('The package holds an entry that is not a plain file.');
129
+ if (!extensionFileAllowed(rel)) fail('The package holds a file that is not part of the extension.');
130
+ const key = rel.toLowerCase();
131
+ if (seen.has(key)) fail('The package names a file twice.');
132
+ if (previous && !(previous < rel)) fail('The package is not in SynaBun\'s order.');
133
+ seen.add(key); previous = rel;
134
+ // The entry itself: where the last one ended, with a header that says what the directory says.
135
+ if (localAt !== dataAt || localAt + 30 + nameLength + size > directoryAt) fail('The package has a gap or an overlap between its files.');
136
+ if (zip.readUInt32LE(localAt) !== LOCAL || zip.readUInt16LE(localAt + 4) !== NEEDED || zip.readUInt16LE(localAt + 6) !== 0 || zip.readUInt16LE(localAt + 8) !== 0
137
+ || zip.readUInt16LE(localAt + 10) !== DOS_TIME || zip.readUInt16LE(localAt + 12) !== DOS_DATE || zip.readUInt32LE(localAt + 14) !== crc
138
+ || zip.readUInt32LE(localAt + 18) !== size || zip.readUInt32LE(localAt + 22) !== size || zip.readUInt16LE(localAt + 26) !== nameLength || zip.readUInt16LE(localAt + 28) !== 0
139
+ || !zip.subarray(localAt + 30, localAt + 30 + nameLength).equals(nameBytes)) fail('The package has an entry whose header does not match its directory.');
140
+ const bytes = Buffer.from(zip.subarray(localAt + 30 + nameLength, localAt + 30 + nameLength + size));
141
+ if (crc32(bytes) !== crc) fail('The package holds a damaged file.');
142
+ files.push({ rel, bytes });
143
+ dataAt = localAt + 30 + nameLength + size;
144
+ at += 46 + nameLength;
145
+ }
146
+ if (at !== endAt || dataAt !== directoryAt) fail('The package has bytes its directory does not account for.');
147
+ if (!seen.has('manifest.json')) fail('The package has no manifest.');
148
+ return files;
149
+ }
@@ -1,14 +1,17 @@
1
1
  import { createServer } from 'node:http';
2
- import { createHash, randomBytes } from 'node:crypto';
2
+ import { randomBytes } from 'node:crypto';
3
3
  import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
4
  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
+ import { EXTENSION_ID } from './browser-extension-pin.js';
9
10
 
10
- const manifest = JSON.parse(readFileSync(new URL('../../browser-extension/manifest.json', import.meta.url), 'utf8'));
11
- export const EXTENSION_ID = createHash('sha256').update(Buffer.from(manifest.key, 'base64')).digest('hex').slice(0, 32).replace(/[0-9a-f]/g, c => String.fromCharCode(97 + parseInt(c, 16)));
11
+ // The wire contract is the app's own copy of the extension's protocol.js (kept byte-identical by
12
+ // scripts/extension/check-browser-extension-pin.mjs), and the extension's identity is the app's pin: the server
13
+ // starts, restores a pairing and checks an Origin with no extension folder anywhere.
14
+ export { EXTENSION_ID };
12
15
  const empty = () => ({ tabs: [], sites: [], allowNewTabs: false, uploads: false, downloads: false });
13
16
  export async function publicDestination(url, resolver = lookup) {
14
17
  const origin = publicOrigin(url);
@@ -59,7 +62,7 @@ export function createBridgeStore(path) {
59
62
  // SynaBun's own addresses stay out of reach in both modes: `forbiddenOrigins` (its public aliases, any port),
60
63
  // `blockedPorts` (its ports; the bridge's own is always added) on this computer, which is localhost, a loopback address
61
64
  // or one of `selfHosts` (its names and interface addresses) or a name that resolves to one (`lookupAddresses`).
62
- 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,
63
66
  commandWait = COMMAND_WAIT, clock = () => performance.now(), fullControl = true, store = null, blockedPorts = () => [], selfHosts = () => [],
64
67
  lookupAddresses = host => lookup(host, { all: true }) } = {}) {
65
68
  if (!Number.isSafeInteger(commandWait) || commandWait < 1 || commandWait > COMMAND_WAIT) fail('INVALID_MESSAGE');
@@ -123,7 +126,12 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
123
126
  }
124
127
  const pending = new Map();
125
128
  const sockets = new Set();
126
- 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
+ // One log line per command: its op, the tab's opaque handle, the outcome's code and, when the browser refused it,
130
+ // what the browser said (`detail`, a chrome.* error message: cleanDetail; never a page's content or a credential).
131
+ const note = (op, tab, code, detail) => {
132
+ const said = cleanDetail(detail);
133
+ 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 {}
134
+ };
127
135
  const coded = code => () => Object.assign(new Error(code), { code });
128
136
  const notConnected = coded('NOT_CONNECTED'), cancelled = coded('CANCELLED');
129
137
  // Rejects pending requests at once. `keepControl` spares the owner's own revocations, which must still reach the extension.
@@ -149,11 +157,24 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
149
157
  to.pushedMode = key;
150
158
  void request('mode', null, 'owner', { fullControl: mode.fullControl, version: mode.version }).catch(() => { if (to.pushedMode === key) to.pushedMode = null; });
151
159
  }
160
+ // Read-only hint for the popup. Older peers reject unknown payloads. Never send a reload from here.
161
+ function publishUpdate() {
162
+ const to = peer;
163
+ if (!to?.ready || compareVersions(to.version, SELF_RELOAD_SINCE) < 0) return;
164
+ const status = updateStatus(to.version);
165
+ if (!status) return;
166
+ const message = { type: 'updateStatus', version: status.version, runsActive: runsActive() };
167
+ const key = JSON.stringify(message);
168
+ if (key === to.updateKey) return;
169
+ to.updateKey = key;
170
+ void to.send(payload(message)).catch(() => { if (to.updateKey === key) to.updateKey = null; });
171
+ }
152
172
  function update(value, from = null) {
153
173
  const { versions, fullControl: fullControlNow, modeVersion, ...next } = inventory(value);
154
174
  if (from && modeVersion !== undefined) peerMode(from, fullControlNow, modeVersion);
155
175
  if (from && !from.ready) {
156
176
  from.ready = true;
177
+ onConnected(from.version); publishUpdate();
157
178
  // Only an extension that knows `reset` (it reports a mode) is sent one; an older one keeps what it holds.
158
179
  if (resetDue && modeVersion !== undefined) { resetDue = false; void request('reset', null, 'owner').catch(() => { resetDue = true; }); }
159
180
  }
@@ -236,7 +257,13 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
236
257
  };
237
258
  const timer = setTimeout(() => ws.close(), 10000); timer.unref?.();
238
259
  let lastSeen = Date.now();
239
- const heartbeat = setInterval(() => { if (Date.now() - lastSeen > 65000) ws.close(); else if (wire) void send({ type: 'ping' }).catch(() => ws.close()); }, 20000); heartbeat.unref?.();
260
+ const heartbeat = setInterval(() => {
261
+ if (Date.now() - lastSeen > 65000) { ws.close(); return; }
262
+ if (!wire) return;
263
+ if (peer?.ws === ws) publishUpdate();
264
+ void send({ type: 'ping' }).catch(() => ws.close());
265
+ }, 20000);
266
+ heartbeat.unref?.();
240
267
  ws.send(JSON.stringify({ type: 'challenge', session }));
241
268
  ws.on('message', raw => {
242
269
  chain = chain.then(async () => {
@@ -299,10 +326,17 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
299
326
  }
300
327
  function authorize(op, tab, owner, args = {}) {
301
328
  authorizeAccess(op, tab, owner, args);
329
+ if (op === 'selfReload') {
330
+ if (compareVersions(peer.version, SELF_RELOAD_SINCE) < 0) fail('EXTENSION_RELOAD_REQUIRED');
331
+ if (!args.allowBusy && (state.tabs.some(tab => tab.owner) || runsActive())) fail('RELOAD_BUSY');
332
+ }
302
333
  if (op === 'upload' && compareVersions(peer.version, '1.3.0') < 0) fail('UPLOAD_RELOAD_REQUIRED');
303
334
  // An extension from before the long operations ends the connection on a command it does not know (its payload()
304
335
  // throws while it authenticates the message): it is never sent one. The owner reloads the extension instead.
305
336
  if (longOp(op, args) && compareVersions(peer.version, LONG_OPS_SINCE) < 0) fail('EXTENSION_RELOAD_REQUIRED');
337
+ // The fixed readers, a snapshot's `offset` and the domcontentloaded wait (1.5.0) likewise.
338
+ const needs = requiredVersion(op, args);
339
+ if (needs && compareVersions(peer.version, needs) < 0) fail('EXTENSION_RELOAD_REQUIRED');
306
340
  }
307
341
  function authorizeAccess(op, tab, owner, args) {
308
342
  if (!enabled || !peer || peer.ws.readyState !== 1) fail('EXTENSION_NOT_CONNECTED');
@@ -372,11 +406,11 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
372
406
  if (stale()) fail('CANCELLED');
373
407
  authorize(op, tab, owner, args);
374
408
  }
375
- note(op, tab || result.tab, result.code || 'OK'); return result;
409
+ note(op, tab || result.tab, result.code || 'OK', result.ok === false ? errorDetail(result) : ''); return result;
376
410
  } catch (error) { note(op, tab, safeError(error).code); throw error; }
377
411
  }
378
412
  return {
379
- request, authorize,
413
+ request, authorize, publishUpdate,
380
414
  // Whether an agent may be shown or given this page in full control (the session listing): never a browser page
381
415
  // or SynaBun's own.
382
416
  openable: url => { try { openable(url); return true; } catch { return false; } },
@@ -435,7 +469,9 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
435
469
  setupPairing: () => ({ active: !!pair?.setup && pair.until >= now() && pairingAttempts <= 5, attempted: pair?.setup ? pair.attempted === true : false }),
436
470
  // Diagnostics: how many revocation records the bridge keeps (counts only).
437
471
  records: () => ({ revokedTabs: revokedTabs.size, revokedSites: revokedSites.size, siteVersions: siteVersions.size }),
438
- status: () => ({ connected: !!peer && enabled && peer.ready === true, paired: !!credential, port: server?.address()?.port || port, extensionId: EXTENSION_ID,
472
+ // `paused`: the owner's Disconnect in Settings → Browser holds (kept across a restart until Reconnect / Resume);
473
+ // the extension's own popup cannot reconnect then (AUTH_FAILED).
474
+ status: () => ({ connected: peer?.ws.readyState === 1 && enabled && peer.ready === true, paired: !!credential, paused: !enabled, port: server?.address()?.port || port, extensionId: EXTENSION_ID,
439
475
  fullControl: mode.fullControl, pairedAt: credential ? pairedAt : 0, extensionVersion: peer?.ready ? peer.version : null, ...structuredClone(state) }),
440
476
  disconnect,
441
477
  resume: () => { enabled = true; persist(); },