synabun 2.4.3 → 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 (153) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +61 -32
  4. package/mcp-server/dist/http.d.ts.map +1 -1
  5. package/mcp-server/dist/http.js +8 -1
  6. package/mcp-server/dist/http.js.map +1 -1
  7. package/mcp-server/dist/services/identity.d.ts +2 -0
  8. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  9. package/mcp-server/dist/services/identity.js +4 -0
  10. package/mcp-server/dist/services/identity.js.map +1 -1
  11. package/mcp-server/dist/services/memory-client.d.ts +5 -0
  12. package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
  13. package/mcp-server/dist/services/memory-client.js +21 -2
  14. package/mcp-server/dist/services/memory-client.js.map +1 -1
  15. package/mcp-server/dist/services/memory-writer.d.ts +3 -0
  16. package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
  17. package/mcp-server/dist/services/memory-writer.js +7 -1
  18. package/mcp-server/dist/services/memory-writer.js.map +1 -1
  19. package/mcp-server/dist/services/neural-interface.d.ts +11 -1
  20. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  21. package/mcp-server/dist/services/neural-interface.js +67 -17
  22. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  23. package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
  24. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  25. package/mcp-server/dist/services/typesafe-config.js +260 -8
  26. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  27. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  28. package/mcp-server/dist/tools/agents.d.ts +3 -1
  29. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  30. package/mcp-server/dist/tools/agents.js +11 -6
  31. package/mcp-server/dist/tools/agents.js.map +1 -1
  32. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  33. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-observe.js +113 -27
  35. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  37. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  38. package/mcp-server/dist/tools/browser-readers.js +17 -0
  39. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  40. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  41. package/mcp-server/dist/tools/remember.js +6 -2
  42. package/mcp-server/dist/tools/remember.js.map +1 -1
  43. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  44. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  45. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  46. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  47. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  48. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  49. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  50. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  51. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  52. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  53. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  54. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  55. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  56. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  57. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  58. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  59. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  60. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  61. package/mcp-server/package-lock.json +2 -2
  62. package/mcp-server/package.json +1 -1
  63. package/mcp-server/src/http.ts +8 -1
  64. package/mcp-server/src/services/identity.ts +5 -0
  65. package/mcp-server/src/services/memory-client.ts +32 -12
  66. package/mcp-server/src/services/memory-writer.ts +5 -2
  67. package/mcp-server/src/services/neural-interface.ts +65 -18
  68. package/mcp-server/src/services/typesafe-config.ts +268 -7
  69. package/mcp-server/src/tools/agents.ts +12 -6
  70. package/mcp-server/src/tools/browser-observe.ts +117 -28
  71. package/mcp-server/src/tools/browser-readers.ts +19 -0
  72. package/mcp-server/src/tools/remember.ts +6 -1
  73. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  74. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  75. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  76. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  77. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  78. package/neural-interface/i18n/en.json +139 -0
  79. package/neural-interface/i18n/pt-BR.json +139 -0
  80. package/neural-interface/lib/assistant-api.js +90 -0
  81. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  82. package/neural-interface/lib/assistant-dispatch.js +276 -42
  83. package/neural-interface/lib/assistant-memory.js +3 -1
  84. package/neural-interface/lib/assistant-persona.js +6 -0
  85. package/neural-interface/lib/assistant-router.js +18 -8
  86. package/neural-interface/lib/assistant-runtime.js +87 -1
  87. package/neural-interface/lib/assistant-task-prompt.js +15 -2
  88. package/neural-interface/lib/browser-connection-state.js +20 -0
  89. package/neural-interface/lib/browser-extension-adapter.js +221 -15
  90. package/neural-interface/lib/browser-extension-bridge.js +40 -7
  91. package/neural-interface/lib/browser-extension-folder.js +50 -11
  92. package/neural-interface/lib/browser-extension-package.js +6 -5
  93. package/neural-interface/lib/browser-extension-pin.json +15 -13
  94. package/neural-interface/lib/browser-extension-protocol.js +111 -13
  95. package/neural-interface/lib/browser-extension-setup.js +7 -5
  96. package/neural-interface/lib/browser-extension-update.js +104 -0
  97. package/neural-interface/lib/browser-extraction.js +38 -14
  98. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  99. package/neural-interface/lib/claude-history.js +12 -1
  100. package/neural-interface/lib/confined-fs.js +25 -0
  101. package/neural-interface/lib/coordination/operations.js +2 -0
  102. package/neural-interface/lib/db.js +39 -16
  103. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  104. package/neural-interface/lib/git-bash/manager.js +28 -3
  105. package/neural-interface/lib/git-status-runner.js +31 -3
  106. package/neural-interface/lib/loop-inventory.js +162 -0
  107. package/neural-interface/lib/loop-stall.js +74 -4
  108. package/neural-interface/lib/memory-session-capture.js +157 -66
  109. package/neural-interface/lib/native-loop-providers.js +73 -13
  110. package/neural-interface/lib/native-loop-runtime.js +3 -0
  111. package/neural-interface/lib/opencode-protocol.js +4 -2
  112. package/neural-interface/lib/peer-identity.js +62 -16
  113. package/neural-interface/lib/session-cache-builder.js +66 -18
  114. package/neural-interface/lib/session-capture-gate.js +42 -0
  115. package/neural-interface/lib/session-indexer.js +28 -20
  116. package/neural-interface/lib/teams/scheduler.js +3 -2
  117. package/neural-interface/lib/ui-blob-api.js +14 -5
  118. package/neural-interface/lib/ui-blob-store.js +302 -39
  119. package/neural-interface/package-lock.json +2 -2
  120. package/neural-interface/package.json +1 -1
  121. package/neural-interface/public/extension-setup.html +1 -0
  122. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  123. package/neural-interface/public/shared/assistant/asst-api.js +42 -0
  124. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  125. package/neural-interface/public/shared/assistant/asst-panel.js +285 -10
  126. package/neural-interface/public/shared/assistant/asst-render.js +205 -4
  127. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  128. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  129. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  130. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  131. package/neural-interface/public/shared/assistant/asst-styles.js +20 -0
  132. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  133. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  134. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  135. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  136. package/neural-interface/public/shared/browser-extension-updates.js +88 -0
  137. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  138. package/neural-interface/public/shared/extension-setup/es-page.js +18 -11
  139. package/neural-interface/public/shared/extension-update-view.js +34 -0
  140. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +8 -4
  141. package/neural-interface/public/shared/settings/settings-browser-extension.js +10 -4
  142. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  143. package/neural-interface/public/shared/styles.css +4 -0
  144. package/neural-interface/public/shared/ui-claude-panel.js +110 -1
  145. package/neural-interface/public/shared/ui-notifications.js +23 -4
  146. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  147. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  148. package/neural-interface/public/shared/worker-end.js +18 -0
  149. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  150. package/neural-interface/scripts/rebuild-pty.js +10 -0
  151. package/neural-interface/server.js +483 -280
  152. package/npm-shrinkwrap.json +2 -2
  153. package/package.json +1 -1
@@ -5,7 +5,7 @@ import { compareVersions } from './browser-extension-folder.js';
5
5
  import { dirname } from 'node:path';
6
6
  import { lookup } from 'node:dns/promises';
7
7
  import { WebSocketServer } from 'ws';
8
- import { anyOrigin, channel, command, COMMAND_WAIT, commandWait as operationWait, CONTROL, controlSurface, equalMac, ERROR_TEXT, fail, handle, HISTORY, inventory, localHost, LONG_OPS_SINCE, longOp, mac, MAX_MESSAGE, nonce, object, pairingKey, parse, payload, portOf, publicOrigin, safeError, string } from './browser-extension-protocol.js';
8
+ import { anyOrigin, channel, command, COMMAND_WAIT, commandWait as operationWait, CONTROL, controlSurface, equalMac, ERROR_TEXT, fail, handle, HISTORY, inventory, localHost, LONG_OPS_SINCE, longOp, mac, MAX_MESSAGE, nonce, object, pairingKey, parse, payload, portOf, publicOrigin, READS_SINCE, requiredVersion, safeError, SELF_RELOAD_SINCE, string, cleanDetail, errorDetail } from './browser-extension-protocol.js';
9
9
  import { EXTENSION_ID } from './browser-extension-pin.js';
10
10
 
11
11
  // The wire contract is the app's own copy of the extension's protocol.js (kept byte-identical by
@@ -62,7 +62,7 @@ export function createBridgeStore(path) {
62
62
  // SynaBun's own addresses stay out of reach in both modes: `forbiddenOrigins` (its public aliases, any port),
63
63
  // `blockedPorts` (its ports; the bridge's own is always added) on this computer, which is localhost, a loopback address
64
64
  // or one of `selfHosts` (its names and interface addresses) or a name that resolves to one (`lookupAddresses`).
65
- export function createExtensionBridge({ port = 3345, log = () => {}, onInventory = () => {}, resolvePublic = publicDestination, now = Date.now, forbiddenOrigins = () => [], revokedTabsKept = 1024,
65
+ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory = () => {}, onConnected = () => {}, updateStatus = () => null, runsActive = () => false, resolvePublic = publicDestination, now = Date.now, forbiddenOrigins = () => [], revokedTabsKept = 1024,
66
66
  commandWait = COMMAND_WAIT, clock = () => performance.now(), fullControl = true, store = null, blockedPorts = () => [], selfHosts = () => [],
67
67
  lookupAddresses = host => lookup(host, { all: true }) } = {}) {
68
68
  if (!Number.isSafeInteger(commandWait) || commandWait < 1 || commandWait > COMMAND_WAIT) fail('INVALID_MESSAGE');
@@ -126,7 +126,12 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
126
126
  }
127
127
  const pending = new Map();
128
128
  const sockets = new Set();
129
- const note = (op, tab, code) => { try { log({ command: op, tab: typeof tab === 'string' && /^[a-f0-9]{32}$/.test(tab) ? tab : null, code: code === 'OK' || Object.hasOwn(ERROR_TEXT, code) ? code : 'OPERATION_FAILED' }); } catch {} };
129
+ // 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
+ };
130
135
  const coded = code => () => Object.assign(new Error(code), { code });
131
136
  const notConnected = coded('NOT_CONNECTED'), cancelled = coded('CANCELLED');
132
137
  // Rejects pending requests at once. `keepControl` spares the owner's own revocations, which must still reach the extension.
@@ -152,11 +157,24 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
152
157
  to.pushedMode = key;
153
158
  void request('mode', null, 'owner', { fullControl: mode.fullControl, version: mode.version }).catch(() => { if (to.pushedMode === key) to.pushedMode = null; });
154
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
+ }
155
172
  function update(value, from = null) {
156
173
  const { versions, fullControl: fullControlNow, modeVersion, ...next } = inventory(value);
157
174
  if (from && modeVersion !== undefined) peerMode(from, fullControlNow, modeVersion);
158
175
  if (from && !from.ready) {
159
176
  from.ready = true;
177
+ onConnected(from.version); publishUpdate();
160
178
  // Only an extension that knows `reset` (it reports a mode) is sent one; an older one keeps what it holds.
161
179
  if (resetDue && modeVersion !== undefined) { resetDue = false; void request('reset', null, 'owner').catch(() => { resetDue = true; }); }
162
180
  }
@@ -239,7 +257,13 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
239
257
  };
240
258
  const timer = setTimeout(() => ws.close(), 10000); timer.unref?.();
241
259
  let lastSeen = Date.now();
242
- const heartbeat = setInterval(() => { if (Date.now() - lastSeen > 65000) ws.close(); else if (wire) void send({ type: 'ping' }).catch(() => ws.close()); }, 20000); heartbeat.unref?.();
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?.();
243
267
  ws.send(JSON.stringify({ type: 'challenge', session }));
244
268
  ws.on('message', raw => {
245
269
  chain = chain.then(async () => {
@@ -302,10 +326,17 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
302
326
  }
303
327
  function authorize(op, tab, owner, args = {}) {
304
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
+ }
305
333
  if (op === 'upload' && compareVersions(peer.version, '1.3.0') < 0) fail('UPLOAD_RELOAD_REQUIRED');
306
334
  // An extension from before the long operations ends the connection on a command it does not know (its payload()
307
335
  // throws while it authenticates the message): it is never sent one. The owner reloads the extension instead.
308
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');
309
340
  }
310
341
  function authorizeAccess(op, tab, owner, args) {
311
342
  if (!enabled || !peer || peer.ws.readyState !== 1) fail('EXTENSION_NOT_CONNECTED');
@@ -375,11 +406,11 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
375
406
  if (stale()) fail('CANCELLED');
376
407
  authorize(op, tab, owner, args);
377
408
  }
378
- 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;
379
410
  } catch (error) { note(op, tab, safeError(error).code); throw error; }
380
411
  }
381
412
  return {
382
- request, authorize,
413
+ request, authorize, publishUpdate,
383
414
  // Whether an agent may be shown or given this page in full control (the session listing): never a browser page
384
415
  // or SynaBun's own.
385
416
  openable: url => { try { openable(url); return true; } catch { return false; } },
@@ -438,7 +469,9 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
438
469
  setupPairing: () => ({ active: !!pair?.setup && pair.until >= now() && pairingAttempts <= 5, attempted: pair?.setup ? pair.attempted === true : false }),
439
470
  // Diagnostics: how many revocation records the bridge keeps (counts only).
440
471
  records: () => ({ revokedTabs: revokedTabs.size, revokedSites: revokedSites.size, siteVersions: siteVersions.size }),
441
- status: () => ({ connected: !!peer && enabled && peer.ready === true, paired: !!credential, port: server?.address()?.port || port, extensionId: EXTENSION_ID,
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,
442
475
  fullControl: mode.fullControl, pairedAt: credential ? pairedAt : 0, extensionVersion: peer?.ready ? peer.version : null, ...structuredClone(state) }),
443
476
  disconnect,
444
477
  resume: () => { enabled = true; persist(); },
@@ -417,20 +417,47 @@ function writeTree(dir, files) {
417
417
  if (files.some(f => f.rel.startsWith('icons/'))) syncDir(join(dir, 'icons'));
418
418
  syncDir(dir);
419
419
  }
420
+ // Recognize an ordinary upgrade for the reload prompt only. Installation always verifies against the NEW pin.
421
+ // If the old manifest, contents or recorded installation disagree, keep the manual repair confirmation.
422
+ function previousInstall(paths, marker, previous, pin) {
423
+ if (!previous?.version || previous.version !== marker?.version || compareVersions(previous.version, pin.version) >= 0) return null;
424
+ const names = list(paths.folder);
425
+ if (!names || names.length > EXTENSION_MAX_FILES) return null;
426
+ const pathsInOrder = names.filter(name => name !== 'icons').sort();
427
+ if (names.includes('icons')) {
428
+ const icons = join(paths.folder, 'icons');
429
+ let info;
430
+ try { info = lstatOrNull(icons); } catch { return null; }
431
+ if (!info?.isDirectory() || !ownedSafely(info, paths.system)) return null;
432
+ const children = list(icons);
433
+ if (!children || children.length + pathsInOrder.length > EXTENSION_MAX_FILES) return null;
434
+ pathsInOrder.push(...children.sort().map(name => `icons/${name}`));
435
+ }
436
+ const digest = createHash('sha256');
437
+ for (const rel of pathsInOrder) {
438
+ if (!extensionFileAllowed(rel)) return null;
439
+ const bytes = readRegular(join(paths.folder, rel));
440
+ if (!bytes || (rel === 'manifest.json' && manifestOf(bytes)?.key !== pin.key)) return null;
441
+ digest.update(rel).update('\0').update(bytes).update('\0');
442
+ }
443
+ return digest.digest('hex') === marker.digest ? previous.version : null;
444
+ }
420
445
  // The Reload the marker asks for after a replacement (`reload`), until the setup page sees the extension running again
421
- // (confirmExtensionReload), or for a repair until the owner confirms the Reload (confirmExtensionRepairReload).
446
+ // (confirmExtensionReload), the new version authenticates (confirmExtensionVersion), or the owner confirms a repair.
422
447
  // `repair`: the folder held files that were not the pinned extension (changed, added or
423
- // deleted, another version) and they were replaced: the browser may still run them, at any version. `fromPort`: the
448
+ // deleted, or an unrecognized version) and they were replaced: the browser may still run them, at any version. `fromPort`: the
424
449
  // same extension on another port, whose old manifest the browser keeps until a Reload. A Reload asked for before and
425
450
  // not yet seen is kept (a repair stays a repair). A first install (no folder) asks for none.
426
- function reloadAfter(pending, previous, port) {
451
+ function reloadAfter(pending, previous, port, fromVersion) {
427
452
  const kept = pending && typeof pending === 'object' && !Array.isArray(pending) ? pending : null;
453
+ if (fromVersion && !kept?.repair) return { reload: { fromVersion } };
428
454
  const repair = previous?.state === 'other' || kept?.repair === true;
429
455
  const fromPort = previous?.state === 'pinned' && previous.port !== port ? previous.port : Number.isInteger(kept?.fromPort) ? kept.fromPort : null;
430
456
  if (!repair && fromPort === null && !kept) return {};
431
- return { reload: { ...(fromPort !== null ? { fromPort } : {}), ...(repair ? { repair: true } : {}) } };
457
+ return { reload: { ...(fromPort !== null ? { fromPort } : {}), ...(repair ? { repair: true } : {}),
458
+ ...(!repair && kept?.fromVersion ? { fromVersion: kept.fromVersion } : {}) } };
432
459
  }
433
- const reloadReasonOf = reload => (!reload ? null : reload.repair === true ? 'repair' : 'port');
460
+ const reloadReasonOf = reload => (!reload ? null : reload.repair === true ? 'repair' : reload.fromVersion ? 'version' : 'port');
434
461
  // The verified files into the browser's path for `port`, as one transaction. `previous`: what inspectTree said of the
435
462
  // folder that is there. Returns the marker written.
436
463
  function place(paths, { files, port, pin, now, io, previous }) {
@@ -442,8 +469,10 @@ function place(paths, { files, port, pin, now, io, previous }) {
442
469
  io.step('staged');
443
470
  const live = identity(paths.folder);
444
471
  const mode = live ? 'renames' : 'place';
472
+ const oldMarker = readJson(paths.marker);
473
+ const fromVersion = previous?.state === 'other' ? previousInstall(paths, oldMarker, previous, pin) : null;
445
474
  const marker = { v: 1, version: pin.version, digest: folderDigest(wanted), appPort: port, preparedAt: now(), package: pin.sha256,
446
- ...reloadAfter(readJson(paths.marker)?.reload, previous, port) };
475
+ ...reloadAfter(oldMarker?.reload, previous, port, fromVersion) };
447
476
  const j = { v: 1, mode, staging: basename(staging), retired: mode === 'renames' ? `unpacked.${hex()}.old` : null, next: identity(staging), previous: live,
448
477
  previousVerified: previous?.state === 'pinned', marker };
449
478
  try { writeDurably(paths.journal, Buffer.from(JSON.stringify(j)), io); } catch (error) { unstage(error); }
@@ -582,7 +611,7 @@ export function cachedExtensionPackage({ home, pin = EXTENSION_PIN }) {
582
611
  export function extensionWorkDir(home) { return installRoot(home, { create: true }).root; }
583
612
 
584
613
  // The marker's pending Reload removed under the lock, when `clears(reload, marker)` says so. Returns whether it was.
585
- function clearReload(home, io, clears) {
614
+ function clearReload(home, io, clears, remaining = () => null) {
586
615
  let paths;
587
616
  try { paths = installRoot(home); } catch { return false; }
588
617
  if (!paths) return false;
@@ -590,7 +619,9 @@ function clearReload(home, io, clears) {
590
619
  return withLock(paths, () => {
591
620
  const marker = readJson(paths.marker);
592
621
  if (!marker?.reload || !clears(marker.reload, marker)) return false;
593
- const { reload: _done, ...rest } = marker;
622
+ const { reload, ...rest } = marker;
623
+ const pending = remaining(reload);
624
+ if (pending) rest.reload = pending;
594
625
  writeDurably(paths.marker, Buffer.from(JSON.stringify(rest)), io);
595
626
  return true;
596
627
  });
@@ -607,7 +638,14 @@ function clearReload(home, io, clears) {
607
638
  * (reconcileMarker carries it).
608
639
  */
609
640
  export function confirmExtensionReload({ home, appPort, io: given = {} }) {
610
- return clearReload(home, ioOf(given), (reload, marker) => reload.repair !== true && marker.appPort === Number(appPort));
641
+ return clearReload(home, ioOf(given), (reload, marker) => !reload.fromVersion && reload.repair !== true && marker.appPort === Number(appPort));
642
+ }
643
+
644
+ // A newly authenticated browser reported the installed version. This clears only an ordinary version upgrade.
645
+ export function confirmExtensionVersion({ home, version, io: given = {} }) {
646
+ // A same-version port change after this upgrade still needs the content script on the new port.
647
+ return clearReload(home, ioOf(given), (reload, marker) => !!reload.fromVersion && !reload.repair && marker.version === version,
648
+ reload => Number.isInteger(reload.fromPort) ? { fromPort: reload.fromPort } : null);
611
649
  }
612
650
 
613
651
  /**
@@ -622,7 +660,8 @@ export function confirmExtensionRepairReload({ home, io: given = {} }) {
622
660
 
623
661
  /**
624
662
  * What the folder's marker says, without writing or verifying: { folder, version, prepared, present, appPort,
625
- * preparedAt, package, reloadPending, reloadReason }. `reloadReason`: 'repair' (files that were not the pinned
663
+ * preparedAt, package, reloadPending, reloadReason, fromVersion? }. `reloadReason`: 'version' for an upgrade from an
664
+ * intact recorded installation, 'repair' (files that were not the pinned
626
665
  * extension were replaced) or 'port' (only the setup port changed), while a Reload is pending; else null. For display
627
666
  * only: whether the folder is the pinned extension is inspectExtensionFolder's answer, never this one.
628
667
  */
@@ -632,5 +671,5 @@ export function extensionFolderState(home) {
632
671
  try { const info = lstatSync(folder); present = info.isDirectory() && !info.isSymbolicLink() && lstatSync(join(folder, 'manifest.json')).isFile(); } catch { present = false; }
633
672
  return { folder, version: typeof marker?.version === 'string' ? marker.version : null, prepared: !!marker, present, appPort: marker?.appPort ?? null,
634
673
  preparedAt: marker?.preparedAt ?? null, package: typeof marker?.package === 'string' ? marker.package : null, reloadPending: !!marker?.reload,
635
- reloadReason: reloadReasonOf(marker?.reload), root };
674
+ reloadReason: reloadReasonOf(marker?.reload), ...(marker?.reload?.fromVersion ? { fromVersion: marker.reload.fromVersion } : {}), root };
636
675
  }
@@ -25,7 +25,7 @@
25
25
  import { readFileSync, rmSync } from 'node:fs';
26
26
  import { join } from 'node:path';
27
27
  import { downloadFile } from './cli-install.js';
28
- import { cachedExtensionPackage, confirmExtensionReload, confirmExtensionRepairReload, downloadWorkName, extensionFolderState, extensionWorkDir, inspectExtensionFolder, prepareExtensionFolder, retargetExtensionFolder, verifiedPackageFiles } from './browser-extension-folder.js';
28
+ import { cachedExtensionPackage, confirmExtensionReload, confirmExtensionRepairReload, confirmExtensionVersion, downloadWorkName, extensionFolderState, extensionWorkDir, inspectExtensionFolder, prepareExtensionFolder, retargetExtensionFolder, verifiedPackageFiles } from './browser-extension-folder.js';
29
29
  import { EXTENSION_PACKAGE_HOST, EXTENSION_PIN, pinProblems } from './browser-extension-pin.js';
30
30
 
31
31
  /** What a failed download or check is called (the setup's error codes; lib/browser-extension-setup.js has the words). */
@@ -97,21 +97,21 @@ export function createExtensionPackage({ home, appPort, pin = EXTENSION_PIN, fet
97
97
  * version, or a file changed, added or deleted), 'unsafe' (its root is a link, another user's or writable by others:
98
98
  * nothing is done there), or null (the pinned extension; at most its port is set, with no download).
99
99
  */
100
- function needs() {
101
- const state = look().state;
100
+ function needs(state = look().state) {
102
101
  return state === 'missing' ? 'install' : state === 'other' ? 'update' : state === 'unsafe' ? 'unsafe' : null;
103
102
  }
104
103
  function status() {
105
- const state = extensionFolderState(home), need = needs(), shown = state.present ? state : null;
104
+ const inspected = look(), state = extensionFolderState(home), need = needs(inspected.state), shown = state.present ? state : null;
106
105
  const failed = need === 'unsafe' ? { code: 'EXTENSION_FOLDER_UNSAFE', reason: 'check', at: null } : !job && last && !last.ok && need ? last : null;
107
106
  return {
108
- pinnedVersion: pin.version, folderVersion: shown ? shown.version : null, folder: shown ? shown.folder : null, needs: need,
107
+ pinnedVersion: pin.version, folderVersion: shown ? inspected.version : null, folder: shown ? shown.folder : null, needs: need,
109
108
  phase: job ? 'downloading' : failed ? 'failed' : 'idle',
110
109
  ...(job ? { received: job.received, total: job.total, reason: job.reason } : {}),
111
110
  ...(!job && failed ? { code: failed.code, reason: failed.reason, at: failed.at } : {}),
112
111
  // A Reload the folder's marker asks for (a port change, or a repair: lib/browser-extension-folder.js), until the
113
112
  // setup page sees the extension running again (confirmReload), or for a repair until the owner confirms it in
114
113
  // Settings (confirmRepairReload).
114
+ ...(state.fromVersion ? { fromVersion: state.fromVersion } : {}),
115
115
  ...(state.reloadPending ? { reloadPending: true, reloadReason: state.reloadReason } : {}),
116
116
  };
117
117
  }
@@ -193,6 +193,7 @@ export function createExtensionPackage({ home, appPort, pin = EXTENSION_PIN, fet
193
193
  */
194
194
  retarget: settle,
195
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 }),
196
197
  confirmReload: () => confirmExtensionReload({ home, appPort: port() }),
197
198
  /** The owner confirmed in Settings that they reloaded the extension after a repair: that Reload is done. */
198
199
  confirmRepairReload: () => confirmExtensionRepairReload({ home }),
@@ -2,13 +2,13 @@
2
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
3
  "name": "SynaBun Browser Bridge",
4
4
  "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsDPDDuBTQq9nQgulmTSvzujxyOMZ7A7ttMSXtbIwup/X3kOlbkqoJEqQRGGJeb7+cNBSiiDBA5lhS0oYc9YeFcwNCucNMvGawDGblbQzDWEmn9dDK1krFVXWqNHVPIrEWlzCD2swXmIE2FCjMd5zw6dSRmmxu7VgE6bzvuOgB/W/oeOAyCsEDhDRDLBkjmb+yCsuexiXRWoempPsvAVhxhE8zEQJ1e8ChlFMtpOXSobU+YDgKYfcFy9Fbmk/o6M6B9y5zSlzs/HYIu7xvcCwjZI457idVMRxxAT6J/kXytmfKe/zbi5IO5/i0x9SCA1HRvt8K3nJqoH03h4TOvFwOwIDAQAB",
5
- "version": "1.4.0",
6
- "url": "https://synabun.ai/Public/downloads/browser-extension/synabun-browser-bridge-1.4.0.zip",
7
- "sha256": "6c6fdd942c9b11173758701678571d3c60f1b56aa8712e3f754d6c7b8a7a96bb",
8
- "size": 206907,
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
9
  "files": {
10
- "content.js": "5420e3bf96c4aea5c7d5f529264eedd49bae9431da3f52abb96de536a4f48944",
11
- "engine.js": "653f06e353e99b7c417e61c1415925673455ffce075105ba794ae740e6a2c816",
10
+ "content.js": "86db13f9688e4501e1d031491e841862382142c6bf04782f8862e1b35fb797c6",
11
+ "engine.js": "acd421f91f0f6fb40c2af3a09ab954c6e962e0932b641639380c094cdb736cec",
12
12
  "icons/icon-128.png": "0749c9c8b40090232e0a234443c634117275598630ec06f4834d20bcad2b6841",
13
13
  "icons/icon-16.png": "e91f674029855c7ea4bc6ca045087fe867ddba706209707060379c4832c15422",
14
14
  "icons/icon-32.png": "5cc0916b2557a8d13c479a7e3a0170584be4c2f58cf770899c1be1aea106fe53",
@@ -19,14 +19,16 @@
19
19
  "icons/status-on-16.png": "c9cbb6e4211f918b2179a796908cf9ebcf7cb5723d9aaa38a93486c2e3b0cd3e",
20
20
  "icons/status-on-32.png": "b67d8fb865e02754ca0d1f1f2e0ead08655340a4ad93511e52ff65db4d487ed7",
21
21
  "icons/status-on-48.png": "c9f306fb5dcbd6a919e5169e3c87c618116bad54858b434b02245dcd1a40b269",
22
- "manifest.json": "d027d047542b2affa0c2528ee1863de29767f4b2d9abdc79085022455b301735",
23
- "popup-strings.js": "683063d9896a306b3abf5d19283ba38a8f0ed88a0c32db1f028262fa1d075107",
24
- "popup-view.js": "c7c9bd582a893d11ca088544e64dd5661c75406920ef5f2b0609a44a58f183c4",
22
+ "manifest.json": "2903c7ac8a25ff0ad73a784e963f3c3420aa291e89ccf29d86ce03250d339cc8",
23
+ "popup-strings.js": "b9d6a147a15dae32b2513437f5de39ec77e8a1ca899086c0092ba31d30dea3d4",
24
+ "popup-view.js": "c5834c2ff19c2cd86fe6954c7a20f154f8804173a022d16910d893bf52491322",
25
25
  "popup.css": "d6a6c5442942bede66f315accef476c591ad71ea4ac09b51d689a622753208f1",
26
- "popup.html": "b04a333f7c7db956fe30dfc760e2bb528984dcf874d5a8e5849776209b8529ec",
27
- "popup.js": "62a83c93aa9657e16dbd81eb6e853cc772794b22042fca051ea8744c55602670",
28
- "protocol.js": "7b29203855da05a6122565273b77094e2abfd91d2e820ac90797d6317bb8bea4",
29
- "service-worker.js": "b8871ebe8b62b1e8d44c6b38757175cd8d519534ed04360597c8cc19cc956b88",
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",
30
32
  "setup-content.js": "9cb56f6f046af294328c03a080cefc58052ee405366eff5f3d70bb1ea02dbabe",
31
33
  "tokens.css": "a27f691794d844cb81b98b45e12863b102e06e9f0a3c722ba96b69b84d3c5a3f"
32
34
  }
@@ -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
  }
@@ -36,7 +36,7 @@ const fail = (code, message = code) => { throw Object.assign(new Error(message),
36
36
  * wants (the pinned version, or a newer one a later release left there) and the browser runs something else. While
37
37
  * the folder itself is older than the pin a Reload changes nothing: that is `updateNeeded`, which SynaBun settles by
38
38
  * downloading the pinned package. `reloadPending`: the folder's marker asks for a Reload until the setup page saw the
39
- * extension running again; `reloadReason` says why. 'port': the setup port changed while the version stayed, and the
39
+ * extension running again; `reloadReason` says why. 'version': a verified upgrade awaits the new peer. 'port': the setup port changed while the version stayed, and the
40
40
  * browser still runs the old manifest (asked only while the extension is connected). 'repair': files that were not
41
41
  * the pinned extension were replaced, and the browser may still run them at the same version, connected or not (the
42
42
  * changed code may not connect at all): asked until the owner confirms the Reload in Settings, and said in its own
@@ -45,7 +45,7 @@ const fail = (code, message = code) => { throw Object.assign(new Error(message),
45
45
  export function extensionVersions({ connected, extensionVersion, folderVersion, pinnedVersion, reloadPending = false, reloadReason = null }) {
46
46
  const current = !!folderVersion && (!pinnedVersion || compareVersions(folderVersion, pinnedVersion) >= 0);
47
47
  const repaired = current && reloadPending === true && reloadReason === 'repair';
48
- const reloadNeeded = repaired || !!(connected && current && (extensionVersion !== folderVersion || reloadPending === true));
48
+ const reloadNeeded = repaired || (current && reloadPending === true && reloadReason === 'version') || !!(connected && current && (extensionVersion !== folderVersion || reloadPending === true));
49
49
  return {
50
50
  reloadNeeded,
51
51
  updateNeeded: !!(folderVersion && pinnedVersion && compareVersions(folderVersion, pinnedVersion) < 0),
@@ -64,7 +64,7 @@ export function extensionVersions({ connected, extensionVersion, folderVersion,
64
64
  * never clears a repair's Reload).
65
65
  */
66
66
  export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin, platform = process.platform, now = Date.now,
67
- windowMs = SETUP_WINDOW_MS, ticketMs = TICKET_MS, maxTickets = MAX_TICKETS, folderVersion = () => null, packageStatus = () => ({}), confirmReload = () => false } = {}) {
67
+ windowMs = SETUP_WINDOW_MS, ticketMs = TICKET_MS, maxTickets = MAX_TICKETS, folderVersion = () => null, packageStatus = () => ({}), confirmReload = () => false, updateStatus } = {}) {
68
68
  let setup = null;
69
69
  // The latest start, from its first step: a cancel or a later start ends it before it prepares or opens anything.
70
70
  let attempt = null;
@@ -97,10 +97,12 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
97
97
  }
98
98
  function view() {
99
99
  const current = state(), bridgeStatus = bridge.status();
100
- const version = folderVersion(), pkg = packageStatus() || {};
100
+ const pkg = packageStatus() || {};
101
+ const version = Object.hasOwn(pkg, 'folderVersion') ? pkg.folderVersion : folderVersion();
101
102
  const pinnedVersion = typeof pkg.pinnedVersion === 'string' ? pkg.pinnedVersion : null;
102
103
  return {
103
104
  state: current,
105
+ ...(updateStatus ? { update: updateStatus(bridgeStatus, pkg) } : {}),
104
106
  ...(setup ? { setupId: setup.id, browser: describe(setup.browser), defaultBrowser: describe(setup.defaultBrowser), installedBrowsers: setup.installed.map(describe),
105
107
  folder: setup.folder, extensionsUrl: setup.browser?.extensionsUrl || null, opened: setup.opened, revealed: setup.revealed, expiresAt: setup.until } : {}),
106
108
  ...(setup?.error ? { code: setup.error.code } : {}),
@@ -173,7 +175,7 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
173
175
  await present();
174
176
  return view();
175
177
  },
176
- status: view,
178
+ status: view, state,
177
179
  /**
178
180
  * The setup page saw the extension's content script on this server's port (POST …/setup/seen): the browser runs
179
181
  * the folder's manifest for this port, so the Reload a port change asked for is done. A repair's Reload is not: the