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
@@ -0,0 +1,201 @@
1
+ // Where the extension's files come from: the one package this app release pins (lib/browser-extension-pin.js),
2
+ // downloaded from synabun.ai (docs/browser-extension-bridge.md → Where the extension comes from). The extension has
3
+ // broad permissions in the owner's browser, so a download is hostile until it is proven to be that exact file:
4
+ //
5
+ // transfer HTTPS only, the one host only (a redirect anywhere else, or to plain http, is not followed), the body
6
+ // as sent (no Content-Encoding: the pinned size bounds the bytes on the wire), nothing larger than the
7
+ // pinned size, a wait for the first byte and between bytes (stallMs) and for the whole transfer
8
+ // (totalMs). It is the hardened transfer of lib/cli-install.js (downloadFile), which aborts the request
9
+ // of every answer it refuses.
10
+ // verify the size and the SHA-256 must be the pin's, checked over the bytes that are then read, before anything
11
+ // looks inside the file; then SynaBun's one zip form, the pinned version and key, and exactly the files
12
+ // the pin lists (lib/browser-extension-folder.js verifiedPackageFiles).
13
+ // place lib/browser-extension-folder.js prepareExtensionFolder: under the data home's lock, a staged folder,
14
+ // then two renames (the live folder aside, the new one into its place), recorded so that a stopped
15
+ // process is finished or taken back at the next start.
16
+ //
17
+ // The folder is held to the pin, never to its marker (inspectExtensionFolder): a folder that is not exactly the
18
+ // pinned extension for this port is repaired, from the verified package this data home keeps when it has one (no
19
+ // network), else by downloading it again. The port is set from the folder's own files only once they verified.
20
+ //
21
+ // When it downloads (createExtensionPackage): with no folder yet, only when the owner starts "Connect your browser"
22
+ // (`ensure`); with a folder that is not the pinned extension, by itself after start-up (`refreshInBackground`), keeping
23
+ // the old folder on any failure. One transfer at a time. Nothing is logged with a path, and the download's working
24
+ // file lives beside the folder, never in it.
25
+ import { readFileSync, rmSync } from 'node:fs';
26
+ import { join } from 'node:path';
27
+ import { downloadFile } from './cli-install.js';
28
+ import { cachedExtensionPackage, confirmExtensionReload, confirmExtensionRepairReload, confirmExtensionVersion, downloadWorkName, extensionFolderState, extensionWorkDir, inspectExtensionFolder, prepareExtensionFolder, retargetExtensionFolder, verifiedPackageFiles } from './browser-extension-folder.js';
29
+ import { EXTENSION_PACKAGE_HOST, EXTENSION_PIN, pinProblems } from './browser-extension-pin.js';
30
+
31
+ /** What a failed download or check is called (the setup's error codes; lib/browser-extension-setup.js has the words). */
32
+ export const PACKAGE_ERROR_CODES = Object.freeze(['EXTENSION_DOWNLOAD_OFFLINE', 'EXTENSION_DOWNLOAD_UNAVAILABLE', 'EXTENSION_VERIFY_FAILED', 'EXTENSION_FOLDER_FAILED', 'EXTENSION_FOLDER_UNSAFE', 'EXTENSION_DOWNLOAD_CANCELLED']);
33
+ export const PACKAGE_STALL_MS = 20_000;
34
+ export const PACKAGE_TOTAL_MS = 120_000;
35
+
36
+ const packageError = (code, message, detail) => Object.assign(new Error(message), { code, ...(detail ? { detail } : {}) });
37
+ // The transfer's own failure kinds (lib/cli-install.js CLI_INSTALL_ERROR_CODES) as the setup's codes.
38
+ const TRANSFER_CODES = Object.freeze({
39
+ offline: 'EXTENSION_DOWNLOAD_OFFLINE', timeout: 'EXTENSION_DOWNLOAD_OFFLINE', interrupted: 'EXTENSION_DOWNLOAD_OFFLINE',
40
+ http: 'EXTENSION_DOWNLOAD_UNAVAILABLE', checksum: 'EXTENSION_VERIFY_FAILED', disk: 'EXTENSION_FOLDER_FAILED', cancelled: 'EXTENSION_DOWNLOAD_CANCELLED',
41
+ });
42
+
43
+ /** Only the pinned host, on the default HTTPS port, with no credentials in the address. */
44
+ export function allowedPackageHost(url) {
45
+ return url.protocol === 'https:' && url.hostname === EXTENSION_PACKAGE_HOST && (url.port === '' || url.port === '443') && !url.username && !url.password;
46
+ }
47
+
48
+ // The pinned package's bytes and verified files: { zip, files }. `workDir` holds the transfer's working file, removed
49
+ // whatever happens. Throws one of PACKAGE_ERROR_CODES; never writes anything else.
50
+ async function downloadPackage({ pin = EXTENSION_PIN, workDir, fetchImpl = fetch, signal, onProgress = () => {}, stallMs = PACKAGE_STALL_MS, totalMs = PACKAGE_TOTAL_MS }) {
51
+ if (pinProblems(pin).length) throw packageError('EXTENSION_VERIFY_FAILED', 'This SynaBun has no valid extension pin.');
52
+ const file = join(workDir, downloadWorkName());
53
+ const stop = new AbortController();
54
+ let timedOut = false;
55
+ const timer = setTimeout(() => { timedOut = true; stop.abort(); }, totalMs); timer.unref?.();
56
+ const onAbort = () => stop.abort();
57
+ if (signal?.aborted) onAbort(); else signal?.addEventListener('abort', onAbort, { once: true });
58
+ try {
59
+ let zip;
60
+ try {
61
+ await downloadFile({ url: pin.url, allow: allowedPackageHost, destination: file, maxBytes: pin.size, expectedSize: pin.size, sha256: pin.sha256, fetchImpl, signal: stop.signal, onProgress, stallMs,
62
+ accept: 'application/zip, application/octet-stream', identityOnly: true });
63
+ } catch (error) {
64
+ if (timedOut) throw packageError('EXTENSION_DOWNLOAD_OFFLINE', 'The download took too long.', 'timeout');
65
+ throw packageError(TRANSFER_CODES[error?.code] || 'EXTENSION_FOLDER_FAILED', error?.message || 'The download failed.', error?.code === 'http' ? error.detail : error?.code);
66
+ }
67
+ try { zip = readFileSync(file); } catch { throw packageError('EXTENSION_FOLDER_FAILED', 'The download could not be read back.'); }
68
+ // The bytes that are read are the bytes that were checked: size and SHA-256 once more, over what is in memory.
69
+ let files;
70
+ try { files = verifiedPackageFiles(zip, pin); } catch (error) { throw packageError('EXTENSION_VERIFY_FAILED', error?.message || 'The package cannot be read.'); }
71
+ return { zip, files };
72
+ } finally {
73
+ clearTimeout(timer);
74
+ signal?.removeEventListener('abort', onAbort);
75
+ rmSync(file, { force: true });
76
+ }
77
+ }
78
+
79
+ /**
80
+ * The verified files of the pinned package: [{ rel, bytes }]. `workDir` holds the transfer's working file, which is
81
+ * removed whatever happens. Throws one of PACKAGE_ERROR_CODES; never writes anything else.
82
+ */
83
+ export async function fetchExtensionPackage(options) { return (await downloadPackage(options)).files; }
84
+
85
+ /**
86
+ * The owner's extension folder and the package it comes from. `home`: the data home; `appPort`: () => this server's
87
+ * port; `pin`: the release's pin. Returns { status, needs, ensure, refreshInBackground, retarget, confirmReload, confirmRepairReload }.
88
+ */
89
+ export function createExtensionPackage({ home, appPort, pin = EXTENSION_PIN, fetchImpl = fetch, now = Date.now, log = () => {}, stallMs = PACKAGE_STALL_MS, totalMs = PACKAGE_TOTAL_MS, io }) {
90
+ const port = () => Number(typeof appPort === 'function' ? appPort() : appPort);
91
+ let job = null; // the transfer under way: { promise, reason, received, total, stop }
92
+ let last = null; // how the last one ended: { ok, code, reason, at }
93
+
94
+ const look = () => inspectExtensionFolder({ home, appPort: port(), pin });
95
+ /**
96
+ * What the folder needs: 'install' (no folder), 'update' (a folder that is not exactly the pinned extension: another
97
+ * version, or a file changed, added or deleted), 'unsafe' (its root is a link, another user's or writable by others:
98
+ * nothing is done there), or null (the pinned extension; at most its port is set, with no download).
99
+ */
100
+ function needs(state = look().state) {
101
+ return state === 'missing' ? 'install' : state === 'other' ? 'update' : state === 'unsafe' ? 'unsafe' : null;
102
+ }
103
+ function status() {
104
+ const inspected = look(), state = extensionFolderState(home), need = needs(inspected.state), shown = state.present ? state : null;
105
+ const failed = need === 'unsafe' ? { code: 'EXTENSION_FOLDER_UNSAFE', reason: 'check', at: null } : !job && last && !last.ok && need ? last : null;
106
+ return {
107
+ pinnedVersion: pin.version, folderVersion: shown ? inspected.version : null, folder: shown ? shown.folder : null, needs: need,
108
+ phase: job ? 'downloading' : failed ? 'failed' : 'idle',
109
+ ...(job ? { received: job.received, total: job.total, reason: job.reason } : {}),
110
+ ...(!job && failed ? { code: failed.code, reason: failed.reason, at: failed.at } : {}),
111
+ // A Reload the folder's marker asks for (a port change, or a repair: lib/browser-extension-folder.js), until the
112
+ // setup page sees the extension running again (confirmReload), or for a repair until the owner confirms it in
113
+ // Settings (confirmRepairReload).
114
+ ...(state.fromVersion ? { fromVersion: state.fromVersion } : {}),
115
+ ...(state.reloadPending ? { reloadPending: true, reloadReason: state.reloadReason } : {}),
116
+ };
117
+ }
118
+ const settle = () => retargetExtensionFolder({ home, appPort: port(), pin, now, io });
119
+ async function run(reason, stop) {
120
+ const workDir = extensionWorkDir(home);
121
+ // A folder this data home can repair or place by itself: the verified package it keeps, with no network.
122
+ const kept = cachedExtensionPackage({ home, pin });
123
+ if (kept) return prepareExtensionFolder({ files: kept, home, appPort: port(), pin, now, io });
124
+ const { zip, files } = await downloadPackage({ pin, workDir, fetchImpl, signal: stop.signal, stallMs, totalMs,
125
+ onProgress: ({ received, total }) => { if (job) { job.received = received; job.total = total || pin.size; } } });
126
+ // A setup the owner cancelled while the last bytes arrived installs nothing.
127
+ if (stop.signal.aborted) throw packageError('EXTENSION_DOWNLOAD_CANCELLED', 'The download was stopped.');
128
+ return prepareExtensionFolder({ files, zip, home, appPort: port(), pin, now, io });
129
+ }
130
+ /**
131
+ * The folder, ready to load: when it is the pinned extension, as it is (its setup port set and verified, no network);
132
+ * else after the pinned package was verified and placed. Resolves what prepareExtensionFolder returns; rejects with
133
+ * one of PACKAGE_ERROR_CODES, leaving the folder that was there in place. `signal` stops the transfer.
134
+ */
135
+ function ensure({ reason = 'setup', signal } = {}) {
136
+ // A transfer that was told to stop is over for whoever asks now (a setup started again): it gets its own, after it.
137
+ if (job?.stop.signal.aborted) {
138
+ const ending = job.promise;
139
+ return ending.then(() => {}, () => {}).then(() => ensure({ reason, signal }));
140
+ }
141
+ if (!job) {
142
+ const need = needs();
143
+ // Its message says why (no path): a link, another user's, others can write it, or a Linux group not proven private.
144
+ if (need === 'unsafe') { const why = look().reason; return Promise.reject(packageError('EXTENSION_FOLDER_UNSAFE', `The extension folder in the data folder is not safe to use${why ? `: ${why}` : ''}.`)); }
145
+ if (!need) {
146
+ // The pinned extension: its port set and the result verified (lib/browser-extension-folder.js), or a failure.
147
+ try {
148
+ const done = settle();
149
+ if (done.state !== 'current') throw packageError('EXTENSION_FOLDER_FAILED', 'The extension folder is not the pinned extension.');
150
+ return Promise.resolve({ folder: done.folder, version: done.version, changed: done.changed, previousVersion: done.version, appPort: port(), stale: false });
151
+ } catch (error) {
152
+ log({ event: 'package', outcome: 'failed', reason: 'port', code: error?.code || 'EXTENSION_FOLDER_FAILED' });
153
+ return Promise.reject(packageError(PACKAGE_ERROR_CODES.includes(error?.code) ? error.code : 'EXTENSION_FOLDER_FAILED', error?.message || 'The extension folder could not be set.'));
154
+ }
155
+ }
156
+ const stop = new AbortController();
157
+ const mine = { reason, received: 0, total: pin.size, stop, promise: null };
158
+ mine.promise = run(reason, stop).then(
159
+ result => { last = { ok: true, reason, at: now() }; log({ event: 'package', outcome: 'installed', reason, version: result.version, changed: result.changed }); return result; },
160
+ error => {
161
+ const code = PACKAGE_ERROR_CODES.includes(error?.code) ? error.code : 'EXTENSION_FOLDER_FAILED';
162
+ // The owner stopped it: nothing failed, and there is nothing to report. A folder that is still not the pinned
163
+ // extension is the exception: its update did not happen, nothing is running, and Settings has to offer Try again.
164
+ const cancelled = code === 'EXTENSION_DOWNLOAD_CANCELLED';
165
+ last = cancelled && needs() !== 'update' ? null : { ok: false, code, reason, at: now() };
166
+ log({ event: 'package', outcome: cancelled ? 'cancelled' : 'failed', reason, code, ...(typeof error?.detail === 'string' ? { detail: error.detail.slice(0, 40) } : {}) });
167
+ throw packageError(code, error?.message || code);
168
+ },
169
+ ).finally(() => { if (job === mine) job = null; });
170
+ job = mine;
171
+ }
172
+ const current = job;
173
+ // A setup stops only a transfer made for a setup: one that joined the background update leaves it running.
174
+ if (signal && current.reason === 'setup') {
175
+ const onAbort = () => current.stop.abort();
176
+ if (signal.aborted) onAbort(); else { signal.addEventListener('abort', onAbort, { once: true }); current.promise.then(() => {}, () => {}).finally(() => signal.removeEventListener('abort', onAbort)); }
177
+ }
178
+ return current.promise;
179
+ }
180
+ return {
181
+ pin, needs, status, ensure,
182
+ /** After start-up: bring a folder that is not the pinned extension up to date. Never downloads for a folder that is not there. */
183
+ refreshInBackground() {
184
+ if (job || needs() !== 'update') return null;
185
+ const promise = ensure({ reason: 'update' });
186
+ promise.catch(() => {});
187
+ return promise;
188
+ },
189
+ /**
190
+ * At start-up (no network): a stopped replacement settled, leftovers removed, the pinned extension's setup port set
191
+ * to this server's, and a changed folder repaired from the verified package this data home keeps. Throws
192
+ * EXTENSION_FOLDER_FAILED / EXTENSION_FOLDER_UNSAFE.
193
+ */
194
+ retarget: settle,
195
+ /** The setup page saw the extension on this port: a Reload a port change asked for is done (never a repair's). */
196
+ confirmVersion: version => confirmExtensionVersion({ home, version }),
197
+ confirmReload: () => confirmExtensionReload({ home, appPort: port() }),
198
+ /** The owner confirmed in Settings that they reloaded the extension after a repair: that Reload is done. */
199
+ confirmRepairReload: () => confirmExtensionRepairReload({ home }),
200
+ };
201
+ }
@@ -0,0 +1,84 @@
1
+ // Which SynaBun Browser Bridge this app release works with, and who the extension is.
2
+ //
3
+ // The extension is not inside the app (no npm file, no installer payload). The app knows it by two things kept here,
4
+ // in app-owned code, so the server starts and pairs with no extension folder and no network:
5
+ //
6
+ // identity the extension's public key (the manifest's `key`). The extension ID is derived from it (EXTENSION_ID)
7
+ // and is what the bridge accepts as an Origin. It never changes, so a paired browser stays paired.
8
+ // release one exact package per app release: its version, its address on synabun.ai, its size and SHA-256
9
+ // (browser-extension-pin.json). The wire contract rejects unknown fields, so app and extension move in
10
+ // lock-step: a download is installed only when it is exactly that file (lib/browser-extension-package.js).
11
+ // files the SHA-256 of every file of that package (the manifest's with its setup content script set to one
12
+ // fixed port, TEMPLATE_PORT of lib/browser-extension-folder.js). The folder the browser loads is current
13
+ // only when it holds exactly these files, byte for byte, and nothing else (inspectExtensionFolder).
14
+ //
15
+ // The pin file is written by scripts/extension/check-browser-extension-pin.mjs (Dev only) and checked by it before a
16
+ // release. Nothing here reads the network or the data home.
17
+ import { createHash } from 'node:crypto';
18
+ import { readFileSync } from 'node:fs';
19
+ import { EXTENSION_MAX_FILES, extensionFileAllowed } from './browser-extension-archive.js';
20
+
21
+ /**
22
+ * The one host an extension package may come from, and the folder its versioned, immutable files live in. The website
23
+ * serves its `Public/` tree under that same name (its build copies a .zip there byte for byte, and its image copies
24
+ * no other top-level folder), so the file `Public/downloads/browser-extension/<name>` of the website is this address.
25
+ */
26
+ export const EXTENSION_PACKAGE_HOST = 'synabun.ai';
27
+ export const EXTENSION_PACKAGE_PATH = '/Public/downloads/browser-extension/';
28
+ /** No package is ever larger than this, whatever a pin says (the real one is about 0.2 MB). */
29
+ export const EXTENSION_PACKAGE_MAX_BYTES = 8 * 1024 * 1024;
30
+
31
+ /** The file name of a version's package. */
32
+ export function extensionPackageName(version) { return `synabun-browser-bridge-${version}.zip`; }
33
+ /** The address of a version's package: https, the one host, a versioned path that is never reused. */
34
+ export function extensionPackageUrl(version) { return `https://${EXTENSION_PACKAGE_HOST}${EXTENSION_PACKAGE_PATH}${extensionPackageName(version)}`; }
35
+ /** The extension ID a browser gives the extension with this public key (base64 DER): SHA-256, 16 bytes, as a-p. */
36
+ export function extensionIdOf(key) {
37
+ return createHash('sha256').update(Buffer.from(String(key), 'base64')).digest('hex').slice(0, 32).replace(/[0-9a-f]/g, c => String.fromCharCode(97 + parseInt(c, 16)));
38
+ }
39
+ /**
40
+ * The extension's ID since it was first published. It is derived from the key, and a browser keeps an extension's
41
+ * pairing under its ID: a pin whose key gives another ID would be another extension, and every owner would pair again.
42
+ * scripts/extension/check-browser-extension-pin.mjs refuses to write or pass such a pin.
43
+ */
44
+ export const HISTORICAL_EXTENSION_ID = 'hnoncohimcacnnlngchbkgpflpoefnil';
45
+ /** What is wrong with a pin's file list (an empty list: nothing). */
46
+ export function inventoryProblems(files) {
47
+ if (!files || typeof files !== 'object' || Array.isArray(files)) return ['files is not an object'];
48
+ const names = Object.keys(files), problems = [], seen = new Set();
49
+ if (!names.length || names.length > EXTENSION_MAX_FILES) problems.push(`files lists no file, or more than ${EXTENSION_MAX_FILES}`);
50
+ if (!names.includes('manifest.json')) problems.push('files has no manifest.json');
51
+ for (const name of names) {
52
+ if (!extensionFileAllowed(name)) problems.push(`files names ${JSON.stringify(name.slice(0, 80))}, which no extension folder may hold`);
53
+ else if (seen.has(name.toLowerCase())) problems.push(`files names ${name} twice`);
54
+ seen.add(name.toLowerCase());
55
+ if (typeof files[name] !== 'string' || !/^[a-f0-9]{64}$/.test(files[name])) problems.push(`files.${name} is not 64 lowercase hex characters`);
56
+ }
57
+ return problems;
58
+ }
59
+ /** What is wrong with a pin (an empty list: nothing). */
60
+ export function pinProblems(pin) {
61
+ const problems = [];
62
+ if (!pin || typeof pin !== 'object') return ['the pin is not an object'];
63
+ if (typeof pin.name !== 'string' || !pin.name) problems.push('name is missing');
64
+ if (typeof pin.key !== 'string' || !/^[A-Za-z0-9+/]{300,}={0,2}$/.test(pin.key)) problems.push('key is not a base64 public key');
65
+ if (typeof pin.version !== 'string' || !/^\d+(\.\d+){1,3}$/.test(pin.version)) problems.push('version is not a dotted version');
66
+ if (typeof pin.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(pin.sha256)) problems.push('sha256 is not 64 lowercase hex characters');
67
+ if (!Number.isInteger(pin.size) || pin.size < 1 || pin.size > EXTENSION_PACKAGE_MAX_BYTES) problems.push(`size is not a whole number of bytes up to ${EXTENSION_PACKAGE_MAX_BYTES}`);
68
+ if (typeof pin.version === 'string' && pin.url !== extensionPackageUrl(pin.version)) problems.push(`url is not ${extensionPackageUrl(pin.version)}`);
69
+ problems.push(...inventoryProblems(pin.files));
70
+ return problems;
71
+ }
72
+ /** Reads and checks a pin file. Throws with every problem named. */
73
+ export function readExtensionPin(path) {
74
+ const { $comment: _comment, ...pin } = JSON.parse(readFileSync(path, 'utf8'));
75
+ const problems = pinProblems(pin);
76
+ if (problems.length) throw Object.assign(new Error(`The browser extension pin is not valid: ${problems.join('; ')}.`), { code: 'EXTENSION_PIN_INVALID' });
77
+ return Object.freeze({ ...pin, files: Object.freeze({ ...pin.files }) });
78
+ }
79
+
80
+ export const EXTENSION_PIN_PATH = new URL('./browser-extension-pin.json', import.meta.url);
81
+ /** This release's pin: { name, key, version, url, sha256, size, files }. */
82
+ export const EXTENSION_PIN = readExtensionPin(EXTENSION_PIN_PATH);
83
+ /** The extension's ID in every Chromium browser, from every folder it is loaded from. */
84
+ export const EXTENSION_ID = extensionIdOf(EXTENSION_PIN.key);
@@ -0,0 +1,35 @@
1
+ {
2
+ "$comment": "The one SynaBun Browser Bridge this app release works with (docs/browser-extension-bridge.md -> Where the extension comes from). The app downloads exactly this file when the owner presses \"Connect your browser\" and installs it only when its size and SHA-256 are these. files is the SHA-256 of every file in it (the manifest with its setup content script set to port 1): the folder the browser loads counts as this extension only when it holds exactly these files. version, url, sha256, size and files are written by `node scripts/extension/check-browser-extension-pin.mjs --write` from the zip built out of browser-extension/ (Dev only); never edit them by hand. key is the extension's public key (its manifest's `key`): the extension ID is derived from it and never changes.",
3
+ "name": "SynaBun Browser Bridge",
4
+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsDPDDuBTQq9nQgulmTSvzujxyOMZ7A7ttMSXtbIwup/X3kOlbkqoJEqQRGGJeb7+cNBSiiDBA5lhS0oYc9YeFcwNCucNMvGawDGblbQzDWEmn9dDK1krFVXWqNHVPIrEWlzCD2swXmIE2FCjMd5zw6dSRmmxu7VgE6bzvuOgB/W/oeOAyCsEDhDRDLBkjmb+yCsuexiXRWoempPsvAVhxhE8zEQJ1e8ChlFMtpOXSobU+YDgKYfcFy9Fbmk/o6M6B9y5zSlzs/HYIu7xvcCwjZI457idVMRxxAT6J/kXytmfKe/zbi5IO5/i0x9SCA1HRvt8K3nJqoH03h4TOvFwOwIDAQAB",
5
+ "version": "1.5.0",
6
+ "url": "https://synabun.ai/Public/downloads/browser-extension/synabun-browser-bridge-1.5.0.zip",
7
+ "sha256": "f34e0166183223ac80fe4243fe03cecb67c43c74aa1ff1f9b55217c8801e0fa7",
8
+ "size": 313679,
9
+ "files": {
10
+ "content.js": "86db13f9688e4501e1d031491e841862382142c6bf04782f8862e1b35fb797c6",
11
+ "engine.js": "acd421f91f0f6fb40c2af3a09ab954c6e962e0932b641639380c094cdb736cec",
12
+ "icons/icon-128.png": "0749c9c8b40090232e0a234443c634117275598630ec06f4834d20bcad2b6841",
13
+ "icons/icon-16.png": "e91f674029855c7ea4bc6ca045087fe867ddba706209707060379c4832c15422",
14
+ "icons/icon-32.png": "5cc0916b2557a8d13c479a7e3a0170584be4c2f58cf770899c1be1aea106fe53",
15
+ "icons/icon-48.png": "6076ff8376ddf79356adc53672524b893f35a007c1666c9b3873c15803a386d8",
16
+ "icons/status-off-16.png": "b860b60a99a5f89bb024fd8411c6645ca071fabc4eee807dad7d7e1a0eec6a26",
17
+ "icons/status-off-32.png": "9ecc6608dd8da21b3d35497aa94480bb4c8b542398d6d8b35b35d3912e72c7c1",
18
+ "icons/status-off-48.png": "9b1395d665df287e299b20b5ba7a0503eb880cd0797fa07c600572491e126c9a",
19
+ "icons/status-on-16.png": "c9cbb6e4211f918b2179a796908cf9ebcf7cb5723d9aaa38a93486c2e3b0cd3e",
20
+ "icons/status-on-32.png": "b67d8fb865e02754ca0d1f1f2e0ead08655340a4ad93511e52ff65db4d487ed7",
21
+ "icons/status-on-48.png": "c9f306fb5dcbd6a919e5169e3c87c618116bad54858b434b02245dcd1a40b269",
22
+ "manifest.json": "2903c7ac8a25ff0ad73a784e963f3c3420aa291e89ccf29d86ce03250d339cc8",
23
+ "popup-strings.js": "b9d6a147a15dae32b2513437f5de39ec77e8a1ca899086c0092ba31d30dea3d4",
24
+ "popup-view.js": "c5834c2ff19c2cd86fe6954c7a20f154f8804173a022d16910d893bf52491322",
25
+ "popup.css": "d6a6c5442942bede66f315accef476c591ad71ea4ac09b51d689a622753208f1",
26
+ "popup.html": "a2dc445a70a8f3430cc4219ab506c7f942bf36c1bd4f6bc85a07e3d1f619cc24",
27
+ "popup.js": "4d60c643c2adc7d0ee0654e9fe2c5b621259531899a52f64d3b855c98ab82f97",
28
+ "protocol.js": "b2d10bcb8461e7d8197080c2293cc0ea60d034d232bd9ab6d45d98ba883fc972",
29
+ "readers-generated.js": "43c4a56f2a195f67712fea55eb12e3d5390082190d5d0b41e41751590f649619",
30
+ "readers.js": "19b7ed04289a2341cdca1035b7fc11bf95d35a31ff48da14097832eb2295e199",
31
+ "service-worker.js": "10adeb063685092f234ebc3b9fa82dc500e837d94d308dc04805d61b8bc81ae9",
32
+ "setup-content.js": "9cb56f6f046af294328c03a080cefc58052ee405366eff5f3d70bb1ea02dbabe",
33
+ "tokens.css": "a27f691794d844cb81b98b45e12863b102e06e9f0a3c722ba96b69b84d3c5a3f"
34
+ }
35
+ }
@@ -34,9 +34,10 @@ export const EVALUATE_RESULT_MAX = 1000000;
34
34
  // 'MAIN' is the page's own JavaScript world (its globals are visible); 'USER_SCRIPT' is Chrome's separate world for
35
35
  // user scripts (the DOM, none of the page's globals, exempt from the page's CSP).
36
36
  export const EVALUATE_WORLDS = ['MAIN', 'USER_SCRIPT'];
37
- // wait with loadState: 'load' (the tab finished loading) or 'networkidle' (also no request of the tab in flight for
38
- // NETWORK_IDLE_QUIET ms, as Playwright counts it), within args.timeout (default, most).
39
- export const LOAD_STATES = ['load', 'networkidle'];
37
+ // wait with loadState: 'load' (the tab finished loading), 'networkidle' (also no request of the tab in flight for
38
+ // NETWORK_IDLE_QUIET ms, as Playwright counts it) or, from READS_SINCE, 'domcontentloaded' (the document was parsed:
39
+ // its readyState is no longer 'loading'), within args.timeout (default, most).
40
+ export const LOAD_STATES = ['load', 'networkidle', 'domcontentloaded'];
40
41
  export const NETWORK_IDLE_QUIET = 500;
41
42
  export const NETWORK_IDLE_TIMEOUT = 15000;
42
43
  export const NETWORK_IDLE_TIMEOUT_MAX = 60000;
@@ -163,15 +164,84 @@ export function inventory(value) {
163
164
  }
164
165
  return value;
165
166
  }
166
- export const COMMANDS = ['create', 'claim', 'release', 'navigate', 'back', 'forward', 'reload', 'snapshot', 'click', 'hover', 'fill', 'type', 'press', 'select', 'scroll', 'wait', 'content', 'screenshot', 'upload', 'download', 'evaluate', 'revokeTab', 'revokeSite', 'disconnect', 'revoke', 'mode', 'reset'];
167
+ export const COMMANDS = ['create', 'claim', 'release', 'navigate', 'back', 'forward', 'reload', 'snapshot', 'click', 'hover', 'fill', 'type', 'press', 'select', 'scroll', 'wait', 'content', 'screenshot', 'upload', 'download', 'evaluate', 'read', 'revokeTab', 'revokeSite', 'disconnect', 'revoke', 'mode', 'reset', 'selfReload'];
167
168
  // The first extension version that knows `evaluate` and `wait` with `loadState`. An older one ends the connection on a
168
169
  // command it does not know, so the server never sends it one (it answers EXTENSION_RELOAD_REQUIRED itself).
169
170
  export const LONG_OPS_SINCE = '1.4.0';
171
+ // The first extension version that reloads itself on the owner's one click (Settings → Update now).
172
+ export const SELF_RELOAD_SINCE = '1.5.0';
173
+ // ── Readers (1.5.0): fixed, read-only page functions shipped in the extension ──
174
+ // `read` runs one of READER_IDS in the agent's tab through chrome.scripting.executeScript({ func }) in the isolated
175
+ // world: no page JavaScript, no "Allow User Scripts", no debugger. A reader is named by its id and nothing else; its
176
+ // arguments are plain data (a CSS selector for the page readers, a scroll step for the paged extractors), never code.
177
+ // The functions are browser-extension/readers.js and readers-generated.js (generated from the extractors the MCP
178
+ // server sends the Playwright backend: scripts/extension/build-browser-readers.mjs). An id not on this list is
179
+ // INVALID_MESSAGE on both sides. `snapshot` with `offset` and `wait` with loadState 'domcontentloaded' came with it.
180
+ export const READS_SINCE = '1.5.0';
181
+ export const READER_IDS = Object.freeze([
182
+ // The page itself: its text (innerText), its main content as cleaned HTML (the server turns it into Markdown), its address.
183
+ 'page.text', 'page.html', 'page.url',
184
+ // Paged extractors: one read of what the page shows, and a scroll of the feed between reads.
185
+ 'x.tweets', 'fb.posts', 'fb.groups', 'tiktok.feed', 'tiktok.search', 'tiktok.studio', 'wa.chats', 'wa.messages',
186
+ 'ig.feed', 'ig.reels', 'ig.search', 'li.feed', 'li.notifications', 'li.search_people', 'li.jobs',
187
+ // One-shot readers.
188
+ 'tiktok.profile', 'tiktok.account', 'ig.profile', 'ig.post', 'li.profile', 'li.post', 'li.messages', 'li.network', 'fb.composer_state',
189
+ 'youtube.channel_id', 'youtube.channel_ready', 'youtube.channel_name', 'youtube.videos',
190
+ ]);
191
+ // The readers that take a scroll step (their feed scrolls between reads); every other one only reads.
192
+ export const PAGED_READERS = Object.freeze(['x.tweets', 'fb.posts', 'fb.groups', 'tiktok.feed', 'tiktok.search', 'tiktok.studio', 'wa.chats', 'wa.messages',
193
+ 'ig.feed', 'ig.reels', 'ig.search', 'li.feed', 'li.notifications', 'li.search_people', 'li.jobs']);
194
+ export const READ_STEPS = ['read', 'scroll'];
195
+ // The most text a page reader answers with (characters): the server pages it (maxChars / offset) as it does a
196
+ // Playwright page's.
197
+ export const READ_TEXT_MAX = 1000000;
198
+ // The extension version an operation needs (null: any paired one). The server answers EXTENSION_RELOAD_REQUIRED itself
199
+ // for an older peer, which would otherwise end the connection on the command or argument it does not know.
200
+ export function requiredVersion(op, args = {}) {
201
+ if (op === 'read' || op === 'wait' && args?.loadState === 'domcontentloaded' || op === 'snapshot' && args?.offset !== undefined) return READS_SINCE;
202
+ if (longOp(op, args)) return LONG_OPS_SINCE;
203
+ return null;
204
+ }
205
+ // ── Uploads: the type of a file, from its name ──
206
+ // A file input and the site behind it read a File's `type` (TikTok Studio refuses a video whose type is not a video
207
+ // one). The extension gives every file it assigns the type this fixed table names for its extension, whatever the
208
+ // transport said; an extension the table does not know is application/octet-stream.
209
+ export const UPLOAD_TYPES = Object.freeze({
210
+ mp4: 'video/mp4', m4v: 'video/x-m4v', mov: 'video/quicktime', webm: 'video/webm', mkv: 'video/x-matroska', avi: 'video/x-msvideo',
211
+ mpeg: 'video/mpeg', mpg: 'video/mpeg', '3gp': 'video/3gpp',
212
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', heic: 'image/heic',
213
+ heif: 'image/heif', bmp: 'image/bmp', svg: 'image/svg+xml', ico: 'image/x-icon', tif: 'image/tiff', tiff: 'image/tiff',
214
+ mp3: 'audio/mpeg', m4a: 'audio/mp4', aac: 'audio/aac', wav: 'audio/wav', ogg: 'audio/ogg', oga: 'audio/ogg', opus: 'audio/opus', flac: 'audio/flac',
215
+ pdf: 'application/pdf', txt: 'text/plain', md: 'text/markdown', csv: 'text/csv', tsv: 'text/tab-separated-values', html: 'text/html', htm: 'text/html',
216
+ json: 'application/json', xml: 'application/xml', zip: 'application/zip', srt: 'application/x-subrip', vtt: 'text/vtt',
217
+ doc: 'application/msword', docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
218
+ xls: 'application/vnd.ms-excel', xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
219
+ ppt: 'application/vnd.ms-powerpoint', pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
220
+ });
221
+ // The extension of a file name as Node's path.extname reads it: after the last dot of the last path segment, never a
222
+ // leading dot ('.mp4' has none).
223
+ export function uploadType(name) {
224
+ const base = String(name || '').split(/[\\/]/).pop(), dot = base.lastIndexOf('.');
225
+ const ext = dot > 0 ? base.slice(dot + 1).toLowerCase() : '';
226
+ return Object.hasOwn(UPLOAD_TYPES, ext) ? UPLOAD_TYPES[ext] : 'application/octet-stream';
227
+ }
228
+ // What the browser itself said when it refused an operation (a Chrome API's error message), carried inside the
229
+ // answer's `error` text after the code's own sentence: `… The browser said: "No current window".` Never a page's
230
+ // content: only messages of chrome.* calls are put there, on one line, cut to DETAIL_MAX characters.
231
+ export const DETAIL_MAX = 300;
232
+ export function cleanDetail(value) {
233
+ const text = String(value?.message ?? value ?? '').replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/"/g, "'").trim();
234
+ return text.slice(0, DETAIL_MAX);
235
+ }
236
+ export function errorDetail(result) {
237
+ const match = /The browser said: "([^"]*)"\.$/.exec(typeof result?.error === 'string' ? result.error : '');
238
+ return match ? match[1] : '';
239
+ }
170
240
  export const HISTORY = ['back', 'forward'];
171
241
  // The owner's control messages: revocations, the mode (full control or restricted) and `reset` (a restarted server
172
242
  // hands back every tab agents of its previous process held). They overtake queued commands on both sides, are never
173
243
  // cancelled themselves, and carry the owner's name only: nothing an agent sends can be one.
174
- export const CONTROL = ['revokeTab', 'revokeSite', 'disconnect', 'revoke', 'mode', 'reset'];
244
+ export const CONTROL = ['revokeTab', 'revokeSite', 'disconnect', 'revoke', 'mode', 'reset', 'selfReload'];
175
245
  export function command(value) {
176
246
  object(value, ['type', 'id', 'op', 'tab', 'owner', 'args', 'blockedHosts', 'blockedPorts', 'selfHosts', 'deadline']);
177
247
  if (value.type !== 'command' || !COMMANDS.includes(value.op)) fail('UNSUPPORTED_IN_EXTENSION_MODE');
@@ -185,8 +255,14 @@ export function command(value) {
185
255
  if (value[key] !== undefined && (!Array.isArray(value[key]) || value[key].length > 200 || value[key].some(h => typeof h !== 'string' || h.length > 253 || !/^[a-zA-Z0-9.:%-]+$/.test(h)))) fail('INVALID_MESSAGE');
186
256
  }
187
257
  if (value.blockedPorts !== undefined && (!Array.isArray(value.blockedPorts) || value.blockedPorts.length > 32 || value.blockedPorts.some(p => !Number.isSafeInteger(p) || p < 1 || p > 65535))) fail('INVALID_MESSAGE');
258
+ if (value.op === 'selfReload') {
259
+ if (value.owner !== 'owner' || value.tab !== null) fail('NOT_OWNED');
260
+ object(value.args, ['allowBusy']);
261
+ if (typeof value.args.allowBusy !== 'boolean' || value.deadline > COMMAND_WAIT) fail('INVALID_MESSAGE');
262
+ return value;
263
+ }
188
264
  const a = value.args; object(a, ['url', 'ref', 'selector', 'nthMatch', 'value', 'text', 'key', 'direction', 'distance', 'maxChars', 'offset', 'timeout', 'state', 'files', 'site', 'fullControl', 'version',
189
- 'expression', 'body', 'params', 'world', 'frame', 'loadState']);
265
+ 'expression', 'body', 'params', 'world', 'frame', 'loadState', 'reader', 'step']);
190
266
  if (value.deadline > commandWait(value.op, a)) fail('INVALID_MESSAGE');
191
267
  for (const [k, v] of Object.entries(a)) {
192
268
  if (k === 'fullControl') { if (typeof v !== 'boolean') fail('INVALID_MESSAGE'); }
@@ -195,6 +271,9 @@ export function command(value) {
195
271
  else if (k === 'frame') { if (!Number.isSafeInteger(v) || v < 0 || v > 2147483647) fail('INVALID_MESSAGE'); }
196
272
  else if (k === 'expression' || k === 'body') string(v, EVALUATE_SCRIPT_MAX);
197
273
  else if (k === 'params') string(v, EVALUATE_PARAMS_MAX);
274
+ // A reader is one id of a closed list, never anything that names or carries code.
275
+ else if (k === 'reader') { if (typeof v !== 'string' || !READER_IDS.includes(v)) fail('INVALID_MESSAGE'); }
276
+ else if (k === 'step') { if (!READ_STEPS.includes(v)) fail('INVALID_MESSAGE'); }
198
277
  else if (['nthMatch', 'distance', 'maxChars', 'offset', 'timeout'].includes(k)) {
199
278
  if (!Number.isSafeInteger(v) || v < 0 || v > 1000000) fail('INVALID_MESSAGE');
200
279
  } else if (k === 'files') {
@@ -230,20 +309,33 @@ export function command(value) {
230
309
  if (!Array.isArray(list)) fail('INVALID_MESSAGE');
231
310
  }
232
311
  } else if (evaluate.some(k => a[k] !== undefined)) fail('INVALID_MESSAGE');
312
+ // read: a reader of the agent's tab (`reader`), a page reader's scope (`selector`), a paged extractor's scroll
313
+ // (`step` 'scroll' with `distance` and `direction`), and nothing else.
314
+ if (value.op === 'read') {
315
+ if (value.tab === null || typeof a.reader !== 'string') fail('INVALID_MESSAGE');
316
+ if (Object.keys(a).some(k => !['reader', 'step', 'selector', 'distance', 'direction'].includes(k))) fail('INVALID_MESSAGE');
317
+ if (a.step === 'scroll' ? a.selector !== undefined || !PAGED_READERS.includes(a.reader) : a.distance !== undefined || a.direction !== undefined) fail('INVALID_MESSAGE');
318
+ if (a.selector !== undefined && !['page.text', 'page.html'].includes(a.reader)) fail('INVALID_MESSAGE');
319
+ } else if (a.reader !== undefined || a.step !== undefined) fail('INVALID_MESSAGE');
233
320
  // A load-state wait names the state and, at most, its timeout: it waits for the tab, not for an element.
234
321
  if (a.loadState !== undefined && (value.op !== 'wait' || value.tab === null || !LOAD_STATES.includes(a.loadState)
235
322
  || Object.keys(a).some(k => k !== 'loadState' && k !== 'timeout'))) fail('INVALID_MESSAGE');
236
323
  return value;
237
324
  }
238
325
  export function payload(value) {
239
- if (value?.type === 'state') { object(value, ['type', 'inventory']); inventory(value.inventory); }
326
+ if (value?.type === 'updateStatus') {
327
+ object(value, ['type', 'version', 'runsActive']);
328
+ if (typeof value.runsActive !== 'boolean' || (value.version !== null && !/^\d{1,5}(\.\d{1,5}){0,3}$/.test(string(value.version, 23)))) fail('INVALID_MESSAGE');
329
+ } else if (value?.type === 'state') { object(value, ['type', 'inventory']); inventory(value.inventory); }
240
330
  else if (value?.type === 'result') {
241
331
  object(value, ['type', 'id', 'result', 'inventory']); handle(value.id); inventory(value.inventory);
242
332
  // evaluate adds `value` (the JSON text of the script's result), `truncated` with `valueLength` (the result was
243
333
  // longer than its cap: `value` is then the beginning of that JSON text, not valid JSON) and, with code PAGE_ERROR,
244
334
  // `errorMessage` and `errorStack` (what the page's script threw). A load-state wait adds `loadState`.
335
+ // read (1.5.0) adds `loading` (a paged extractor's feed showed a loading marker); a snapshot asked with an `offset`
336
+ // adds `snapshotTotal` (characters of the whole snapshot) and `snapshotNext` (the offset of what did not fit).
245
337
  object(value.result, ['ok', 'code', 'error', 'url', 'title', 'snapshotText', 'mode', 'snapshotId', 'content', 'text', 'base64', 'mimeType', 'tab', 'downloadId', 'files',
246
- 'value', 'truncated', 'valueLength', 'errorMessage', 'errorStack', 'loadState']);
338
+ 'value', 'truncated', 'valueLength', 'errorMessage', 'errorStack', 'loadState', 'loading', 'snapshotTotal', 'snapshotNext']);
247
339
  if (typeof value.result.ok !== 'boolean') fail('INVALID_MESSAGE');
248
340
  for (const [k, v] of Object.entries(value.result)) {
249
341
  if (k === 'ok') continue;
@@ -258,8 +350,8 @@ export function payload(value) {
258
350
  }
259
351
  if (total > MAX_FILE) fail('INVALID_MESSAGE');
260
352
  } else if (k === 'downloadId') { if (!Number.isSafeInteger(v)) fail('INVALID_MESSAGE'); }
261
- else if (k === 'valueLength') { if (!Number.isSafeInteger(v) || v < 0) fail('INVALID_MESSAGE'); }
262
- else if (k === 'truncated') { if (typeof v !== 'boolean') fail('INVALID_MESSAGE'); }
353
+ else if (['valueLength', 'snapshotTotal', 'snapshotNext'].includes(k)) { if (!Number.isSafeInteger(v) || v < 0) fail('INVALID_MESSAGE'); }
354
+ else if (k === 'truncated' || k === 'loading') { if (typeof v !== 'boolean') fail('INVALID_MESSAGE'); }
263
355
  else string(v, k === 'base64' ? MAX_MESSAGE - 4096 : ['content', 'text', 'snapshotText', 'value'].includes(k) ? EVALUATE_RESULT_MAX : 8192);
264
356
  }
265
357
  } else if (value?.type === 'ping' || value?.type === 'pong' || value?.type === 'unpair') object(value, ['type']);
@@ -269,6 +361,7 @@ export function payload(value) {
269
361
  return value;
270
362
  }
271
363
  export const ERROR_TEXT = Object.freeze({
364
+ RELOAD_BUSY: 'Automation is active. Wait for it to finish or confirm the reload.',
272
365
  EXTENSION_NOT_CONNECTED: 'The browser extension is not connected. Open its popup and reconnect (after a SynaBun restart it reconnects by itself).',
273
366
  NOT_CONNECTED: 'The extension disconnected. Reconnect from its popup.',
274
367
  AUTH_FAILED: 'Authentication failed. Revoke pairing and pair again on both sides.',
@@ -284,7 +377,7 @@ export const ERROR_TEXT = Object.freeze({
284
377
  NO_HISTORY_ENTRY: 'There is no page to go back or forward to in this tab. Nothing was done.',
285
378
  STALE_REF: 'This element reference is stale. Take a fresh snapshot; no action was performed.',
286
379
  UNSUPPORTED_IN_EXTENSION_MODE: 'This operation is unavailable with the extension backend. See docs/browser-extension-bridge.md.',
287
- ACTIVE_TAB_REQUIRED: 'Screenshots capture the visible part of the active tab only, and the tab was not (or stopped being) the active one while capturing. Retry; in restricted mode, activate the tab first.',
380
+ ACTIVE_TAB_REQUIRED: 'The extension captures screenshots with chrome.tabs.captureVisibleTab, which draws only the tab a window is showing (no debugger is attached, so a tab in the background cannot be drawn), and the tab was not, or stopped being, the one shown while capturing. In full control the extension brings the agent’s own tab to the front of its window for the capture: retry. In restricted mode it never does: the owner activates the tab, or switches the extension to full control. To read the page instead, use browser_snapshot or browser_content.',
288
381
  TAB_LIMIT: 'This bridge already controls 200 tabs. Close an agent tab before opening another.',
289
382
  TAB_BUSY: 'Chrome is editing tabs (for example during a drag). Retry navigation after the tab strip settles.',
290
383
  NAVIGATION_FAILED: 'Chrome refused tabs.update for this navigation. Check the browser site-access policy and destination, then retry.',
@@ -309,9 +402,14 @@ export const ERROR_TEXT = Object.freeze({
309
402
  PAGE_ERROR: 'The page’s script threw, or did not compile (evaluate takes one expression: wrap statements in a function, (() => { …; return value; })()). errorMessage and errorStack say what the page reported; the bridge itself did not fail.',
310
403
  BLANK_PAGE: 'The tab shows the blank start page, where no script can run. Navigate it to an http(s) page first.',
311
404
  FRAME_NOT_FOUND: 'The tab has no frame with this id that a script can run in (frame 0 is the top document). Nothing was run.',
312
- NETWORK_IDLE_UNAVAILABLE: 'The extension cannot watch this browser’s network requests (its webRequest permission is not in effect). The owner reloads SynaBun Browser Bridge on the browser’s extensions page; until then wait for a selector or a fixed time instead.',
405
+ READER_FAILED: 'The extension’s reader found nothing it could read on this page (the page changed under it, or is not the page this reader is for). Nothing was changed on the page; observe the tab, then retry.',
406
+ INVALID_SELECTOR: 'The selector is not a valid CSS selector. Nothing was read.',
407
+ SCROLL_TARGET_MISSING: 'The feed this extractor scrolls is not on the page (scroll container not found). Items read so far are kept.',
408
+ NETWORK_IDLE_UNAVAILABLE:'The extension cannot watch this browser’s network requests (its webRequest permission is not in effect). The owner reloads SynaBun Browser Bridge on the browser’s extensions page; until then wait for a selector or a fixed time instead.',
313
409
  });
410
+ // `error.detail`: what the browser said (cleanDetail), appended to the code's own sentence (errorDetail reads it back).
314
411
  export function safeError(error) {
315
412
  const code = Object.hasOwn(ERROR_TEXT, error?.code) ? error.code : 'OPERATION_FAILED';
316
- return { ok: false, code, error: `${code}: ${ERROR_TEXT[code]}` };
413
+ const detail = cleanDetail(error?.detail);
414
+ return { ok: false, code, error: `${code}: ${ERROR_TEXT[code]}${detail ? ` The browser said: "${detail}".` : ''}` };
317
415
  }