synabun 2.4.0 → 2.4.1

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 (72) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +25 -5
  4. package/browser-extension/engine.js +44 -13
  5. package/browser-extension/manifest.json +2 -2
  6. package/browser-extension/popup-strings.js +10 -4
  7. package/browser-extension/popup-view.js +1 -1
  8. package/browser-extension/popup.css +1 -0
  9. package/browser-extension/popup.html +4 -1
  10. package/browser-extension/popup.js +22 -10
  11. package/browser-extension/protocol.js +11 -5
  12. package/browser-extension/service-worker.js +8 -0
  13. package/docs/browser-extension-bridge.md +2 -2
  14. package/lib/data-home-files.js +45 -0
  15. package/lib/data-home-migration.js +34 -58
  16. package/mcp-server/dist/services/neural-interface.d.ts +1 -0
  17. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  18. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  19. package/mcp-server/dist/tools/agents.d.ts +3 -2
  20. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  21. package/mcp-server/dist/tools/agents.js +9 -7
  22. package/mcp-server/dist/tools/agents.js.map +1 -1
  23. package/mcp-server/package-lock.json +2 -2
  24. package/mcp-server/package.json +1 -1
  25. package/mcp-server/src/services/neural-interface.ts +1 -0
  26. package/mcp-server/src/tools/agents.ts +8 -6
  27. package/neural-interface/i18n/en.json +3 -1
  28. package/neural-interface/i18n/pt-BR.json +3 -1
  29. package/neural-interface/lib/agents/builtins.json +207 -0
  30. package/neural-interface/lib/agents/registry.js +60 -15
  31. package/neural-interface/lib/agents/resolve.js +69 -10
  32. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  33. package/neural-interface/lib/assistant-dispatch.js +127 -24
  34. package/neural-interface/lib/assistant-persona.js +1 -1
  35. package/neural-interface/lib/assistant-router.js +50 -7
  36. package/neural-interface/lib/assistant-runtime.js +9 -1
  37. package/neural-interface/lib/backup-service.js +64 -105
  38. package/neural-interface/lib/browser-extension-adapter.js +24 -15
  39. package/neural-interface/lib/browser-extension-bridge.js +27 -4
  40. package/neural-interface/lib/native-loop-runtime.js +6 -7
  41. package/neural-interface/lib/opencode-build-preflight.js +12 -7
  42. package/neural-interface/lib/peer-identity.js +13 -8
  43. package/neural-interface/lib/session-cache-builder.js +41 -3
  44. package/neural-interface/lib/teams/scheduler.js +2 -2
  45. package/neural-interface/lib/teams/schema.js +1 -1
  46. package/neural-interface/package-lock.json +2 -2
  47. package/neural-interface/package.json +1 -1
  48. package/neural-interface/public/index.html +51 -0
  49. package/neural-interface/public/offline.html +4 -3
  50. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
  51. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
  52. package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
  53. package/neural-interface/public/shared/api.js +2 -1
  54. package/neural-interface/public/shared/assistant/asst-render.js +1 -0
  55. package/neural-interface/public/shared/assistant/asst-route.js +3 -1
  56. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  57. package/neural-interface/public/shared/html-shell.js +1 -0
  58. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  59. package/neural-interface/public/shared/page-session.js +1 -1
  60. package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
  61. package/neural-interface/public/shared/start-bridge.js +2 -2
  62. package/neural-interface/public/shared/styles.css +13 -1
  63. package/neural-interface/public/shared/ui-loading.js +72 -19
  64. package/neural-interface/public/shared/ui-native-loop-router.js +49 -20
  65. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  66. package/neural-interface/public/shared/ui-settings.js +10 -2
  67. package/neural-interface/public/shared/ui-sync.js +1 -0
  68. package/neural-interface/public/sw.js +4 -3
  69. package/neural-interface/public/variant/3d/main.js +13 -4
  70. package/neural-interface/server.js +34 -25
  71. package/npm-shrinkwrap.json +2 -2
  72. package/package.json +2 -1
@@ -32,6 +32,7 @@
32
32
  // Catalog, config and runtime I/O are injected. The split planner checks git before worktree approval.
33
33
 
34
34
  import { routeTaskIdentity } from '../public/shared/assistant/route-identity.js';
35
+ import { agentPinOf, agentRefOf, routedAgent } from './agents/resolve.js';
35
36
  import { planRouteSplit } from './agents/split.js';
36
37
  import { normalizeAgentDensity } from './agents/density.js';
37
38
  import { randomBytes } from 'node:crypto';
@@ -215,8 +216,9 @@ export function normalizeRouteRequest(body = {}, { brain = {} } = {}) {
215
216
  let coercedProvider = null;
216
217
  for (const raw of Array.isArray(body.proposals) ? body.proposals.slice(0, 3) : []) {
217
218
  if (!raw || typeof raw !== 'object') continue;
219
+ const requested = agentRefOf(raw);
218
220
  let kind = raw.kind === 'direct' ? 'direct' : 'dispatch';
219
- let provider = CATALOG_PROVIDERS.includes(raw.provider) ? raw.provider : null;
221
+ let provider = CATALOG_PROVIDERS.includes(raw.provider) ? raw.provider : requested === 'none' ? brain.provider : null;
220
222
  let model = raw.model ? String(raw.model).trim().slice(0, 200) : null;
221
223
  if (kind === 'direct') {
222
224
  if (provider && provider !== brain.provider) {
@@ -232,6 +234,7 @@ export function normalizeRouteRequest(body = {}, { brain = {} } = {}) {
232
234
  }
233
235
  proposals.push({
234
236
  kind, provider, model,
237
+ ...(requested ? { agentRequest: requested } : {}),
235
238
  effort: raw.effort ? String(raw.effort).trim().slice(0, 40) : null,
236
239
  ...(raw.accountId || raw.account_id ? { accountId: String(raw.accountId || raw.account_id).slice(0, 64) } : {}),
237
240
  reason: raw.reason ? clip(raw.reason, 240) : null,
@@ -1070,6 +1073,7 @@ export function escalationFor({ run, catalog = null, routing = {}, depth = 0 })
1070
1073
  export function createAssistantRouter({
1071
1074
  catalog,
1072
1075
  configStore = null,
1076
+ agents = null,
1073
1077
  getSession = () => null,
1074
1078
  sinks = {},
1075
1079
  now = Date.now,
@@ -1092,6 +1096,32 @@ export function createAssistantRouter({
1092
1096
  const lastClosed = new Map(); // routeId → { routeId, settled } of recently closed cards
1093
1097
  const call = (name, ...args) => { try { return sinks[name]?.(...args); } catch (error) { log('router:sink-error', `${name}: ${error?.message || error}`); return undefined; } };
1094
1098
 
1099
+ // Resolve each distinct proposed role once. A different model (saved preference, budget or
1100
+ // custom card choice) can still run the proposed role. Direct choices never use a worker.
1101
+ function workerRoles(request, cwd, pin = null) {
1102
+ const roles = new Map();
1103
+ return request.proposals.map(proposal => {
1104
+ const ref = proposal.agentRequest;
1105
+ if (pin) return { agentRef: pin.ref, agentRevision: pin.revision, agentRequest: pin.ref };
1106
+ if (!roles.has(ref)) {
1107
+ const role = agents ? routedAgent(agents, request.taskClass, cwd, ref) : {};
1108
+ roles.set(ref, role.meta || (role.note ? { agentCorrection: role.note } : {}));
1109
+ }
1110
+ return roles.get(ref);
1111
+ });
1112
+ }
1113
+ function workerRole(request, target, optionId) {
1114
+ if (target?.kind !== 'dispatch' || !request.roles) return {};
1115
+ const suggestion = /^s([1-3])$/.exec(optionId || '');
1116
+ const index = suggestion ? Number(suggestion[1]) - 1 : 0;
1117
+ return request.roles[index] || request.roles[0] || {};
1118
+ }
1119
+ function agentFields(record) {
1120
+ if (!record) return {};
1121
+ const { agentRef, agentRevision, agentRequest, agentCorrection } = record;
1122
+ return { ...(agentRef ? { agentRef, agentRevision } : {}), ...(agentRequest ? { agentRequest } : {}),
1123
+ ...(agentCorrection ? { agentCorrection } : {}) };
1124
+ }
1095
1125
  function routing() { try { return configStore?.routing?.() || effectiveRouting({}); } catch { return effectiveRouting({}); } }
1096
1126
  function modeFor(sessionId) {
1097
1127
  const session = getSession(sessionId);
@@ -1219,6 +1249,7 @@ export function createAssistantRouter({
1219
1249
  function routeView(source, { catalog: cat = null, brain = {}, brainInfo = null } = {}) {
1220
1250
  const target = source.target ? describeTarget(source.target, { catalog: cat, brain, brainInfo }) : null;
1221
1251
  return {
1252
+ ...agentFields(source),
1222
1253
  routeId: source.routeId, runIds: [...(source.runIds || [])], taskClass: source.taskClass, taskClassLabel: TASK_CLASS_META[source.taskClass]?.label || source.taskClass,
1223
1254
  plannedSplit: source.plannedSplit || null, sessionId: source.sessionId || null, taskId: source.taskId || null, taskKey: source.taskKey || '',
1224
1255
  summary: source.summary || '', confidence: source.confidence ?? null, reason: source.reason || null,
@@ -1453,10 +1484,11 @@ export function createAssistantRouter({
1453
1484
  : `Call agent_dispatch with route_id="${routeId}" for one worker. Explain: ${plannedSplit.reason}`
1454
1485
  : null;
1455
1486
  return {
1487
+ ...agentFields(record),
1456
1488
  ok: true, status, routeId, mode, source: source || record?.decidedBy || (status === 'expired' ? 'timeout' : status === 'cancelled' ? 'system' : null), reasonCode: record?.reasonCode || (status === 'expired' ? 'expired' : status === 'cancelled' ? 'cancelled' : null), target: described, remembered, continuation,
1457
1489
  taskClass: record?.taskClass || null, sessionId: sessionId || record?.sessionId || null, taskId: record?.taskId || null, taskKey: record?.taskKey || '',
1458
1490
  agentDensity: plannedSplit?.density || normalizeAgentDensity(getSession(sessionId || record?.sessionId)?.agentDensity), expectedWorkers: plannedSplit?.workers || 1, plannedSplit, workflowId: record?.workflowId || null,
1459
- corrections, runIds, expiresAt: card?.expiresAt ? new Date(card.expiresAt).toISOString() : null,
1491
+ corrections: record?.agentCorrection ? [...corrections, record.agentCorrection] : corrections, runIds, expiresAt: card?.expiresAt ? new Date(card.expiresAt).toISOString() : null,
1460
1492
  ...(shares ? { budget: shares } : {}),
1461
1493
  next: `${waitLead}${lead}${status === 'approved' ? kindLead : ''}${splitNext || nextText(record?.reasonCode === 'moved_on' ? 'moved_on' : status, described, { routeId, label: status === 'declined' ? record?.reasonCode : described?.label })}`,
1462
1494
  };
@@ -1516,6 +1548,7 @@ export function createAssistantRouter({
1516
1548
  const first = request.proposals[0];
1517
1549
  const fallback = origin === 'dispatch' && option.badge !== 'remembered' && option.provider === first?.provider ? first.accountId : null;
1518
1550
  Object.assign(option, accountTarget(option, brain, cat, { check: false, fallback }));
1551
+ Object.assign(option, workerRole(request, option, option.id));
1519
1552
  if (option.accountError) { option.disabled = true; option.disabledReason = option.accountError.message; }
1520
1553
  // A "here" whose account cannot take it (this conversation's is out of usage) runs on a worker
1521
1554
  // on another account: the card names it as a worker and says why, never "Do it here".
@@ -1531,6 +1564,7 @@ export function createAssistantRouter({
1531
1564
  const expiresAt = now() + r.cardTimeoutMinutes * 60_000;
1532
1565
  const pref = r.preferences?.[request.taskClass];
1533
1566
  const card = {
1567
+ ...agentFields(options.find(o => o.id === (defaults.dispatch || defaultOptionId))),
1534
1568
  routeId, requestId, sessionId, origin, status: 'pending', mode, workflowId,
1535
1569
  plannedSplit: request.plannedSplit || null, taskId: request.taskId, taskKey: request.taskKey || '',
1536
1570
  taskClass: request.taskClass, summary: request.summary, confidence: request.confidence, needsVision: request.needsVision,
@@ -1731,6 +1765,7 @@ export function createAssistantRouter({
1731
1765
  if (existing) return existing;
1732
1766
  request.plannedSplit = await planRouteSplit(body, session, request.taskClass);
1733
1767
  request.projectPath = request.plannedSplit?.projectPath || null;
1768
+ request.roles = workerRoles(request, body.cwd || body.project);
1734
1769
  if (request.plannedSplit) {
1735
1770
  request.dispatchOnly = true;
1736
1771
  request.proposals = request.proposals.map(p => ({ ...p, kind: 'dispatch' }));
@@ -1759,6 +1794,7 @@ export function createAssistantRouter({
1759
1794
  const route = {
1760
1795
  taskId: request.taskId, taskKey: request.taskKey || '', plannedSplit: request.plannedSplit || null, workflowId: null,
1761
1796
  routeId, status: 'approved', sessionId, taskClass: request.taskClass, summary: request.summary, confidence: request.confidence,
1797
+ ...workerRole(request, target),
1762
1798
  target, decidedBy, remembered: evaluation.source === 'remembered', corrections: [...accountCorrections(target, evaluation.corrections), ...(waits ? [waits] : [])], mode,
1763
1799
  reason: request.proposals[0]?.reason || null, runIds: [], expiresAt: now() + DECIDED_TTL_MS,
1764
1800
  };
@@ -1841,6 +1877,7 @@ export function createAssistantRouter({
1841
1877
  }
1842
1878
  const { optionId, remember } = parsed;
1843
1879
  const target = checkedTarget(parsed.target, brain, cat, null, null, card.mode === 'always-ask');
1880
+ const pickedRole = workerRole(card.request, target, optionId);
1844
1881
  const corrections = accountCorrections(target, parsed.corrections || []);
1845
1882
  // The session budget must be able to pay for the pick: a provider with no share left divides the
1846
1883
  // unspent budget again first; still none, and the card stays open with the reason.
@@ -1861,7 +1898,7 @@ export function createAssistantRouter({
1861
1898
  // or reported started: the card stays open with the reason. A "here" pick starts none.
1862
1899
  if (!keptHere) {
1863
1900
  for (const runId of card.runIds) {
1864
- const refusal = call('checkHeld', runId, target);
1901
+ const refusal = call('checkHeld', runId, target, pickedRole);
1865
1902
  if (refusal) throw routeError(refusal.code || 'ROUTE_INVALID', refusal.message || 'The held run cannot start on that model.', Number(refusal.status) || 400);
1866
1903
  }
1867
1904
  }
@@ -1902,6 +1939,7 @@ export function createAssistantRouter({
1902
1939
  const route = {
1903
1940
  taskId: card.taskId, taskKey: card.taskKey || '', plannedSplit: card.plannedSplit || null, workflowId: null,
1904
1941
  routeId, status: 'approved', sessionId: card.sessionId, taskClass: card.taskClass, summary: card.summary, confidence: card.confidence,
1942
+ ...pickedRole,
1905
1943
  target, decidedBy: 'user', remembered, optionId, corrections, mode: card.mode, runIds: heldRuns,
1906
1944
  reason: card.options.find((o) => o.id === optionId)?.reason || null, alternatives: card.alternatives, expiresAt: now() + DECIDED_TTL_MS,
1907
1945
  };
@@ -1910,7 +1948,7 @@ export function createAssistantRouter({
1910
1948
  // A remote session: the held run this card was for is its one dispatch.
1911
1949
  if (heldRuns.length && session.remote === true) route.consumed = true;
1912
1950
  for (const runId of droppedRuns) call('declineHeld', runId, 'route_here');
1913
- for (const runId of heldRuns) call('startHeld', runId, target, { routeId, decidedBy: 'user', remembered, optionId });
1951
+ for (const runId of heldRuns) call('startHeld', runId, target, { routeId, decidedBy: 'user', remembered, optionId, agentRequest: route.agentRequest });
1914
1952
  const view = routeView(route, { catalog: cat, brain, brainInfo });
1915
1953
  call('routeEvent', card.sessionId, 'decided', view);
1916
1954
  const inTurnWaiter = card.waiters.size > 0;
@@ -2023,6 +2061,8 @@ export function createAssistantRouter({
2023
2061
  expireOtherTasks(sessionId, session.latestTaskId || request.taskId);
2024
2062
  const prior = existingTaskResult(request, sessionId, { cat, brain, brainInfo });
2025
2063
  if (prior && prior.routeId !== routeId) return resolveDispatch({ sessionId, spec: { ...spec, routeId: prior.routeId }, origin, team });
2064
+ request.proposals[0].agentRequest = agentRefOf(spec);
2065
+ request.roles = workerRoles(request, spec.cwd || spec.project, agentPinOf(spec));
2026
2066
  if (!spec.provider) request.proposals[0].provider = brain.provider || 'claude-code';
2027
2067
  const evaluation = await evaluateWithBudget(sessionId, { mode, routing: r, request, brain, brainInfo, catalog: cat });
2028
2068
  if (evaluation.unavailable === 'budget_exhausted') {
@@ -2035,8 +2075,9 @@ export function createAssistantRouter({
2035
2075
  if (raced) return resolveDispatch({ sessionId, spec: { ...spec, routeId: raced.routeId }, origin, team });
2036
2076
  const t = checkedTarget(evaluation.auto, brain, cat);
2037
2077
  noteBudgetTask(sessionId, request, t);
2038
- const applied = { ...spec, provider: t.provider, model: t.model || null, effort: t.effort || spec.effort || null, ...(t.accountId ? { accountId: t.accountId, codexAccountId: null, claudeAccountId: null } : {}) };
2078
+ const applied = { ...spec, provider: t.provider, model: t.model || null, effort: t.effort ?? null, accountId: t.accountId || null, codexAccountId: null, claudeAccountId: null };
2039
2079
  const route = {
2080
+ ...workerRole(request, { ...t, kind: 'dispatch' }),
2040
2081
  routeId: `route-${randomId()}`, status: 'auto', decidedBy: evaluation.source === 'remembered' ? 'remembered' : evaluation.source === 'budget' ? 'budget' : 'brain', mode,
2041
2082
  taskClass: request.taskClass, confidence: request.confidence, target: t, corrections: accountCorrections(t, evaluation.corrections),
2042
2083
  remembered: evaluation.source === 'remembered',
@@ -2061,6 +2102,7 @@ export function createAssistantRouter({
2061
2102
 
2062
2103
  function routeMeta(route, cat, brain, brainInfo) {
2063
2104
  return {
2105
+ ...agentFields(route),
2064
2106
  routeId: route.routeId, status: route.status === 'approved' ? 'approved' : route.status, decidedBy: route.decidedBy || null, mode: route.mode || null,
2065
2107
  plannedSplit: route.plannedSplit || null, taskId: route.taskId || null, taskKey: route.taskKey || '', sessionId: route.sessionId || null,
2066
2108
  taskClass: route.taskClass || null, taskClassLabel: TASK_CLASS_META[route.taskClass]?.label || null, confidence: route.confidence ?? null,
@@ -2070,6 +2112,7 @@ export function createAssistantRouter({
2070
2112
  }
2071
2113
  function pendingMeta(card) {
2072
2114
  return {
2115
+ ...agentFields(card),
2073
2116
  routeId: card.routeId, taskId: card.taskId || null, taskKey: card.taskKey || '', sessionId: card.sessionId || null, status: 'pending', decidedBy: null, mode: card.mode, taskClass: card.taskClass,
2074
2117
  taskClassLabel: TASK_CLASS_META[card.taskClass]?.label || null, confidence: card.confidence ?? null,
2075
2118
  target: null, corrections: [], remembered: false, decidedAt: null,
@@ -2167,9 +2210,9 @@ export function createAssistantRouter({
2167
2210
  }
2168
2211
  function status(routeId) {
2169
2212
  const card = cards.get(routeId);
2170
- if (card) return { routeId, status: card.status, sessionId: card.sessionId, taskId: card.taskId || null, taskKey: card.taskKey || '', runIds: [...card.runIds], taskClass: card.taskClass, expiresAt: new Date(card.expiresAt).toISOString(), request: card.packet.request };
2213
+ if (card) return { ...agentFields(card), routeId, status: card.status, sessionId: card.sessionId, taskId: card.taskId || null, taskKey: card.taskKey || '', runIds: [...card.runIds], taskClass: card.taskClass, expiresAt: new Date(card.expiresAt).toISOString(), request: card.packet.request };
2171
2214
  const route = decided.get(routeId);
2172
- if (route) return { routeId, status: route.status, sessionId: route.sessionId, taskId: route.taskId || null, taskKey: route.taskKey || '', runIds: route.runIds || [], taskClass: route.taskClass, target: route.target, decidedBy: route.decidedBy, plannedSplit: route.plannedSplit || null, workflowId: route.workflowId || null };
2215
+ if (route) return { ...agentFields(route), routeId, status: route.status, sessionId: route.sessionId, taskId: route.taskId || null, taskKey: route.taskKey || '', runIds: route.runIds || [], taskClass: route.taskClass, target: route.target, decidedBy: route.decidedBy, plannedSplit: route.plannedSplit || null, workflowId: route.workflowId || null };
2173
2216
  return null;
2174
2217
  }
2175
2218
 
@@ -931,6 +931,7 @@ export function createAssistantRuntime({
931
931
  */
932
932
  function brainNeedsRestart(live) {
933
933
  if (!live?.brain) return false;
934
+ if (live.brain.needsRestart?.()) return true;
934
935
  // Its persona was built with (or without) a user-context layer that was switched since.
935
936
  if (userContext && live.brainUserContext !== null) {
936
937
  let key = null;
@@ -2504,7 +2505,7 @@ export function createAssistantRuntime({
2504
2505
  await disposeBrain(live, 'budget');
2505
2506
  if (cancelled()) return dropTurn(live, request);
2506
2507
  }
2507
- // A Claude brain built for another remote level restarts (resuming its conversation).
2508
+ // A dead OpenCode serve or stale brain policy needs a fresh brain with the same conversation.
2508
2509
  if (live.brain && !live.running && brainNeedsRestart(live)) {
2509
2510
  await disposeBrain(live, 'policy');
2510
2511
  if (cancelled()) return dropTurn(live, request);
@@ -2751,6 +2752,13 @@ export function createAssistantRuntime({
2751
2752
  try { router?.continuationStarted?.(work.routeId); } catch (error) { log('assistant:route-continuation', error?.message || String(error)); }
2752
2753
  }
2753
2754
  } catch (error) {
2755
+ if (error?.code === 'OPENCODE_SERVE_EXITED') {
2756
+ const message = error.message;
2757
+ // The exit listener normally closed the turn. If the serve died before
2758
+ // the brain entered the turn, close it here with the same single packet.
2759
+ if (live.running) onBrainPacket(live, { type: 'error', message });
2760
+ return { ok: false, code: 'TURN_FAILED', message };
2761
+ }
2754
2762
  live.running = false;
2755
2763
  live.turnRun = previousRun;
2756
2764
  endComputerTurn(live, 'turn_failed');
@@ -5,7 +5,6 @@ import {
5
5
  constants as FS_CONSTANTS,
6
6
  createReadStream,
7
7
  existsSync,
8
- lstatSync,
9
8
  mkdtempSync,
10
9
  mkdirSync,
11
10
  openSync,
@@ -28,6 +27,7 @@ import { Worker } from 'node:worker_threads';
28
27
  import archiver from 'archiver';
29
28
  import { openZipArchive, readZipEntry, verifyBackupChecksums } from './backup-zip-reader.js';
30
29
  import { writeZipArchive } from './backup-zip-writer.js';
30
+ import { hashFileSync, walkDataHomeTree } from '../../lib/data-home-files.js';
31
31
  import { LOCK_FILE_NAME } from './rulesets/lock.js';
32
32
 
33
33
  export const BACKUP_MANIFEST_VERSION = 3;
@@ -304,33 +304,26 @@ export function assertBackupDestinationMounted(folderPath, options) {
304
304
  if (missing) throw new BackupDestinationUnavailableError({ ...missing, folderPath });
305
305
  }
306
306
 
307
- function collectFiles(root, archiveRoot, { filter = () => true } = {}) {
308
- const files = [];
309
- function walk(current) {
310
- if (!existsSync(current)) return;
311
- let stat;
312
- try { stat = lstatSync(current); }
313
- catch (error) {
314
- if (error?.code === 'ENOENT') return;
315
- throw error;
316
- }
317
- if (stat.isSymbolicLink()) return;
318
- if (stat.isFile()) {
319
- const rel = relative(root, current).replace(/\\/g, '/');
320
- if (filter(rel, current)) files.push({ diskPath: current, archivePath: `${archiveRoot}/${rel}` });
321
- return;
322
- }
323
- if (!stat.isDirectory()) return;
324
- let entries;
325
- try { entries = readdirSync(current).sort(); }
326
- catch (error) {
327
- if (error?.code === 'ENOENT') return;
328
- throw error;
307
+ // De-duplicate as files are discovered. Later additional entries take precedence,
308
+ // as before, without constructing an argument list or a second subtree listing.
309
+ function collectBackupFiles(dataHome, filters, additionalEntries) {
310
+ const entries = new Map();
311
+ const add = (diskPath, archivePath) => entries.set(archivePath.replace(/\\/g, '/'), { diskPath, archivePath });
312
+ const envPath = resolve(dataHome, '.env');
313
+ if (existsSync(envPath)) add(envPath, 'env.bak');
314
+
315
+ function collect(root, archiveRoot, filter) {
316
+ for (const { path, stat } of walkDataHomeTree(root)) {
317
+ if (!stat.isFile()) continue;
318
+ const rel = relative(root, path).replace(/\\/g, '/');
319
+ if (!filter || filter(rel)) add(path, rel ? `${archiveRoot}/${rel}` : archiveRoot);
329
320
  }
330
- for (const entry of entries) walk(join(current, entry));
331
321
  }
332
- walk(root);
333
- return files;
322
+ for (const dir of BACKUP_DATA_DIRS) collect(resolve(dataHome, dir), dir, filters[dir]);
323
+ for (const entry of additionalEntries) {
324
+ if (entry?.diskPath && entry?.archivePath) collect(entry.diskPath, entry.archivePath);
325
+ }
326
+ return Array.from(entries.values());
334
327
  }
335
328
 
336
329
  function backupFileSize(file) {
@@ -366,13 +359,15 @@ export function assertBackupWorkingSpace({
366
359
  getAvailableBytes = backupAvailableBytes,
367
360
  } = {}) {
368
361
  const primaryDatabaseBytes = databasePath && existsSync(databasePath) ? statSync(databasePath).size : 0;
369
- const inputBytes = files.reduce((sum, file) => sum + backupFileSize(file), primaryDatabaseBytes);
370
- const stagedMutableBytes = files
371
- .filter(isMutableBackupInput)
372
- .reduce((sum, file) => sum + backupFileSize(file), 0);
373
- const sqliteSnapshotBytes = files
374
- .filter(isSqliteBackupInput)
375
- .reduce((sum, file) => sum + backupFileSize(file), primaryDatabaseBytes);
362
+ let inputBytes = primaryDatabaseBytes;
363
+ let stagedMutableBytes = 0;
364
+ let sqliteSnapshotBytes = primaryDatabaseBytes;
365
+ for (const file of files) {
366
+ const size = backupFileSize(file);
367
+ inputBytes += size;
368
+ if (isSqliteBackupInput(file)) sqliteSnapshotBytes += size;
369
+ else if (isMutableBackupInput(file)) stagedMutableBytes += size;
370
+ }
376
371
  const archiveBytes = Math.max(Number(expectedArchiveBytes) || 0, inputBytes);
377
372
  const requiredBytes = Math.max(0, Number(freeSpaceReserveBytes) || 0)
378
373
  + stagedMutableBytes
@@ -446,39 +441,38 @@ function snapshotMutableBackupFiles(files, folderPath) {
446
441
  }
447
442
  }
448
443
 
449
- function normalizeAdditionalEntries(entries = []) {
450
- const result = [];
451
- for (const entry of entries) {
452
- if (!entry?.diskPath || !entry?.archivePath || !existsSync(entry.diskPath)) continue;
453
- let stat;
454
- try { stat = lstatSync(entry.diskPath); }
455
- catch (error) {
456
- if (error?.code === 'ENOENT') continue;
457
- throw error;
458
- }
459
- if (stat.isSymbolicLink()) continue;
460
- if (stat.isDirectory()) result.push(...collectFiles(entry.diskPath, entry.archivePath));
461
- else if (stat.isFile()) result.push({ diskPath: entry.diskPath, archivePath: entry.archivePath });
462
- }
463
- return result;
464
- }
465
-
466
444
  async function writeArchive({ tempPath, files, manifest, level = 6 }) {
467
445
  const { createWriteStream } = await import('node:fs');
468
446
  await new Promise((resolveWrite, reject) => {
469
447
  const output = createWriteStream(tempPath, { flags: 'wx' });
470
448
  const archive = archiver('zip', { zlib: { level } });
471
- output.on('close', resolveWrite);
472
- output.on('error', reject);
473
- archive.on('warning', error => error.code === 'ENOENT' ? null : reject(error));
474
- archive.on('error', reject);
475
- archive.pipe(output);
476
- for (const file of files) {
449
+ const remaining = files.values();
450
+ let failure;
451
+ function fail(error) {
452
+ if (failure) return;
453
+ failure = error;
454
+ archive.abort();
455
+ output.destroy();
456
+ }
457
+ // Archiver queues a stat and a lazy stream for each file handed to it.
458
+ // Feed one member after the preceding entry has finished.
459
+ function appendNext() {
460
+ const next = remaining.next();
461
+ if (next.done) {
462
+ archive.finalize().catch(fail);
463
+ return;
464
+ }
465
+ const file = next.value;
477
466
  const store = INCOMPRESSIBLE_EXTENSIONS.has(extname(file.archivePath).toLowerCase());
478
467
  archive.file(file.diskPath, { name: `${BACKUP_PREFIX}/${file.archivePath}`, store });
479
468
  }
469
+ output.on('close', () => failure ? reject(failure) : resolveWrite());
470
+ output.on('error', fail);
471
+ archive.on('warning', error => error.code === 'ENOENT' ? appendNext() : fail(error));
472
+ archive.on('error', fail);
473
+ archive.on('entry', appendNext);
474
+ archive.pipe(output);
480
475
  archive.append(JSON.stringify(manifest, null, 2), { name: `${BACKUP_PREFIX}/manifest.json` });
481
- archive.finalize().catch(reject);
482
476
  });
483
477
  }
484
478
 
@@ -547,9 +541,6 @@ export async function createVerifiedBackup({
547
541
  let sqliteSnapshot = null;
548
542
  let stageDir = null;
549
543
  try {
550
- const files = [];
551
- const envPath = resolve(dataHome, '.env');
552
- if (existsSync(envPath)) files.push({ diskPath: envPath, archivePath: 'env.bak' });
553
544
  // BACKUP_DATA_DIRS is the list other modules read (backupRoots): every folder copied here is on it.
554
545
  const dataDirFilters = {
555
546
  data: rel => !shouldSkipDataPath(rel),
@@ -558,27 +549,19 @@ export async function createVerifiedBackup({
558
549
  && !/^memory\.db(?:-wal|-shm)?$/i.test(rel)
559
550
  && !/\.db-(?:wal|shm)$/i.test(rel),
560
551
  };
561
- for (const dir of BACKUP_DATA_DIRS) files.push(...collectFiles(resolve(dataHome, dir), dir, { filter: dataDirFilters[dir] }));
562
- files.push(...normalizeAdditionalEntries(additionalEntries));
563
-
564
- // De-duplicate before estimating work space so explicit additional entries
565
- // cannot inflate the preflight or create ambiguous ZIP members.
566
- const deduped = [...new Map(files.map(file => [
567
- file.archivePath.replace(/\\/g, '/'),
568
- file,
569
- ])).values()];
552
+ const deduped = collectBackupFiles(dataHome, dataDirFilters, additionalEntries);
570
553
 
571
554
  // Keep the upgrade path bounded: state is archived, generated media is not.
572
555
  const leanSnapshot = UPGRADE_BACKUP_KINDS.has(kind);
573
556
  const selection = leanSnapshot
574
557
  ? selectUpgradeSnapshotFiles(deduped, { softLimitBytes: upgradeSoftLimitBytes })
575
558
  : { files: deduped, excluded: null };
576
- const sourceFiles = selection.files;
559
+ const files = selection.files;
577
560
  const excluded = selection.excluded;
578
561
 
579
562
  const workingSpace = assertBackupWorkingSpace({
580
563
  folderPath,
581
- files: sourceFiles,
564
+ files,
582
565
  databasePath,
583
566
  expectedArchiveBytes,
584
567
  freeSpaceReserveBytes,
@@ -586,7 +569,7 @@ export async function createVerifiedBackup({
586
569
  });
587
570
  report({
588
571
  phase: 'collect',
589
- files: sourceFiles.length,
572
+ files: files.length,
590
573
  bytes: workingSpace.archiveBytes,
591
574
  skippedFiles: excluded?.files ?? 0,
592
575
  skippedBytes: excluded?.bytes ?? 0,
@@ -594,9 +577,12 @@ export async function createVerifiedBackup({
594
577
  });
595
578
 
596
579
  sqliteSnapshot = createConsistentSqliteSnapshot(databasePath, sqliteTemp);
597
- files.length = 0;
598
- files.push(...sourceFiles);
599
- if (sqliteSnapshot) files.push({ diskPath: sqliteSnapshot.path, archivePath: 'database/memory.db' });
580
+ if (sqliteSnapshot) {
581
+ const primary = { diskPath: sqliteSnapshot.path, archivePath: 'database/memory.db' };
582
+ const duplicate = files.findIndex(file => file.archivePath.replace(/\\/g, '/') === primary.archivePath);
583
+ if (duplicate === -1) files.push(primary);
584
+ else files[duplicate] = primary;
585
+ }
600
586
 
601
587
  // UI blob/state databases also use WAL. Snapshot every additional SQLite
602
588
  // file rather than pairing an arbitrary main file with a moving WAL.
@@ -610,10 +596,7 @@ export async function createVerifiedBackup({
610
596
  files[index] = { ...file, diskPath: temp };
611
597
  }
612
598
 
613
- // De-duplicate archive paths so explicit additional entries cannot create
614
- // ambiguous ZIP members.
615
- const unique = new Map(files.map(file => [file.archivePath.replace(/\\/g, '/'), file]));
616
- const stableInputs = snapshotMutableBackupFiles([...unique.values()], folderPath);
599
+ const stableInputs = snapshotMutableBackupFiles(files, folderPath);
617
600
  stageDir = stableInputs.stageDir;
618
601
  const finalFiles = stableInputs.files.sort((a, b) => a.archivePath.localeCompare(b.archivePath));
619
602
  report({ phase: 'checksum', files: finalFiles.length });
@@ -736,25 +719,6 @@ export function isSqliteDatabaseFile(path) {
736
719
  }
737
720
  }
738
721
 
739
- /** SHA-256 (hex) of a file, read in one pass on this thread (WAL files: small, and read while a lock is held). */
740
- function hashFileNow(path) {
741
- const digest = createHash('sha256');
742
- const fd = openSync(path, 'r');
743
- try {
744
- const buffer = Buffer.allocUnsafe(4 * 1024 * 1024);
745
- let position = 0;
746
- for (;;) {
747
- const read = readSync(fd, buffer, 0, buffer.length, position);
748
- if (!read) break;
749
- digest.update(buffer.subarray(0, read));
750
- position += read;
751
- }
752
- } finally {
753
- closeSync(fd);
754
- }
755
- return digest.digest('hex');
756
- }
757
-
758
722
  /**
759
723
  * What tells a later reader, in any process, whether the SQLite database at `path` was written since: its file
760
724
  * (device, inode, size, modification and change times, and its first 100 bytes, where a rollback-journal database
@@ -768,7 +732,7 @@ export function sqliteFingerprint(path) {
768
732
  const walPath = `${path}-wal`;
769
733
  try {
770
734
  const walSize = statSync(walPath).size;
771
- if (walSize > 0) wal = { size: walSize, sha256: hashFileNow(walPath) };
735
+ if (walSize > 0) wal = { size: walSize, sha256: hashFileSync(walPath) };
772
736
  } catch (error) {
773
737
  if (error?.code !== 'ENOENT') throw error;
774
738
  }
@@ -970,9 +934,6 @@ export function isUpgradeRuntimeFile(dir, relativePath) {
970
934
  * and shared-memory files belong to it (never archived on their own).
971
935
  */
972
936
  function collectUpgradeInputs({ dataHome, additionalEntries = [], softLimitBytes = UPGRADE_SNAPSHOT_SOFT_LIMIT_BYTES }) {
973
- const files = [];
974
- const envPath = resolve(dataHome, '.env');
975
- if (existsSync(envPath)) files.push({ diskPath: envPath, archivePath: 'env.bak' });
976
937
  const dataDirFilters = {
977
938
  data: rel => !shouldSkipDataPath(rel) && !isUpgradeRuntimeFile('data', rel),
978
939
  'mcp-data': rel => !shouldSkipDataPath(rel)
@@ -980,9 +941,7 @@ function collectUpgradeInputs({ dataHome, additionalEntries = [], softLimitBytes
980
941
  && !isDatabaseCopyArtifact(rel)
981
942
  && !/^memory\.db(?:-wal|-shm|-journal)?$/i.test(rel),
982
943
  };
983
- for (const dir of BACKUP_DATA_DIRS) files.push(...collectFiles(resolve(dataHome, dir), dir, { filter: dataDirFilters[dir] }));
984
- files.push(...normalizeAdditionalEntries(additionalEntries));
985
- const deduped = [...new Map(files.map(file => [file.archivePath.replace(/\\/g, '/'), file])).values()];
944
+ const deduped = collectBackupFiles(dataHome, dataDirFilters, additionalEntries);
986
945
  const { files: kept, excluded } = selectUpgradeSnapshotFiles(deduped, { softLimitBytes });
987
946
  const marked = kept.map(file => ({ ...file, sqlite: isSqliteDatabaseFile(file.diskPath) }));
988
947
  const databases = new Set(marked.filter(file => file.sqlite).map(file => file.archivePath.toLowerCase()));
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { basename, resolve } from 'node:path';
2
+ import { basename, isAbsolute, resolve } from 'node:path';
3
3
  import { readConfinedFile } from './confined-fs.js';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { fail, handle, HISTORY, MAX_FILE, safeError } from '../../browser-extension/protocol.js';
@@ -122,18 +122,24 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
122
122
  for (const owner of [...s._tabOwners.keys()]) await release(id, owner);
123
123
  sessions.delete(id); if (sessionId === id) sessionId = null;
124
124
  }
125
- async function files(paths) {
126
- if (!Array.isArray(paths) || !paths.length || paths.length > 4) fail('INVALID_MESSAGE');
127
- const result = []; let size = 0;
128
- for (const path of paths) {
129
- if (typeof path !== 'string') fail('INVALID_MESSAGE');
130
- let bytes;
131
- try { bytes = readConfinedFile(uploadRoot, resolve(path), { maxBytes: MAX_FILE - size }); }
132
- catch (error) { fail(error.status === 413 ? 'MESSAGE_TOO_LARGE' : 'PERMISSION_REQUIRED'); }
133
- size += bytes.length;
134
- result.push({ name: basename(path), base64: bytes.toString('base64') });
135
- }
136
- return result;
125
+ function uploadFiles(paths) {
126
+ if (!Array.isArray(paths) || !paths.length || paths.length > 4 ||
127
+ paths.some(path => typeof path !== 'string' || !isAbsolute(path))) fail('INVALID_MESSAGE');
128
+ let remaining = MAX_FILE;
129
+ return {
130
+ names: paths.map(path => basename(path)),
131
+ read(index) {
132
+ try {
133
+ const bytes = readConfinedFile(uploadRoot, resolve(paths[index]), { maxBytes: remaining });
134
+ remaining -= bytes.length;
135
+ return bytes;
136
+ } catch (error) {
137
+ if (error.status === 404) fail('UPLOAD_FILE_MISSING');
138
+ if (error.status === 413) fail('UPLOAD_TOO_LARGE');
139
+ fail('UPLOAD_FILE_REFUSED');
140
+ }
141
+ },
142
+ };
137
143
  }
138
144
  async function operation(s, owner, tab, action, body = {}) {
139
145
  if (!bridge.status().connected) fail('EXTENSION_NOT_CONNECTED');
@@ -157,10 +163,13 @@ export function createExtensionAdapter({ bridge, sessions, uploadRoot, caller, o
157
163
  }
158
164
  const args = {};
159
165
  for (const k of argumentKeys) if (body[k] !== undefined && body[k] !== null) args[k] = ['nthMatch', 'distance', 'maxChars', 'offset', 'timeout'].includes(k) ? Number(body[k]) : body[k];
166
+ let upload;
160
167
  if (op === 'upload') {
161
- bridge.authorize(op, tab, agent(owner), args); args.files = await files(body.filePaths);
168
+ bridge.authorize(op, tab, agent(owner), args);
169
+ upload = uploadFiles(body.filePaths);
170
+ args.files = upload.names;
162
171
  }
163
- const result = finish(s, tab, await bridge.request(op, tab, agent(owner), args));
172
+ const result = finish(s, tab, await bridge.request(op, tab, agent(owner), args, upload));
164
173
  if (op === 'wait' && result.ok) result.state = body.state || 'visible';
165
174
  if (op === 'screenshot' && result.ok) {
166
175
  const raw = Buffer.from(result.base64, 'base64'), meta = await sharp(raw).metadata();
@@ -1,6 +1,7 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { createHash, randomBytes } from 'node:crypto';
3
3
  import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { compareVersions } from './browser-extension-folder.js';
4
5
  import { dirname } from 'node:path';
5
6
  import { lookup } from 'node:dns/promises';
6
7
  import { WebSocketServer } from 'ws';
@@ -174,7 +175,25 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
174
175
  async function start() {
175
176
  if (listening) return listening;
176
177
  listening = new Promise((resolve, reject) => {
177
- server = createServer((_req, res) => { res.writeHead(404); res.end(); });
178
+ // An upload command id doubles as a short-lived capability. Only the paired extension
179
+ // receives it. Each file can be read once, in order, while its command is authorized.
180
+ server = createServer((req, res) => {
181
+ const match = /^Bearer ([a-f0-9]{32})$/.exec(req.headers.authorization || '');
182
+ const p = match && pending.get(match[1]);
183
+ if (!p?.upload || req.method !== 'POST' || req.url !== '/upload/' + p.nextFile ||
184
+ p.nextFile >= p.args.files.length || req.headers.origin !== `chrome-extension://${EXTENSION_ID}` ||
185
+ req.headers.host !== `127.0.0.1:${server.address()?.port}` ||
186
+ p.issued !== revocations || clock() >= p.expires) {
187
+ res.writeHead(404).end(); return;
188
+ }
189
+ try {
190
+ authorize('upload', p.tab, p.owner, p.args);
191
+ const bytes = p.upload.read(p.nextFile++);
192
+ res.writeHead(200, { 'Cache-Control': 'no-store', 'Content-Type': 'application/octet-stream', 'Content-Length': bytes.length }).end(bytes);
193
+ } catch (error) {
194
+ res.writeHead(400, { 'Cache-Control': 'no-store' }).end(safeError(error).code);
195
+ }
196
+ });
178
197
  wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, perMessageDeflate: false });
179
198
  server.on('upgrade', (req, socket, head) => {
180
199
  if (req.socket.remoteAddress !== '127.0.0.1' || req.headers.origin !== `chrome-extension://${EXTENSION_ID}` || req.url !== '/bridge'
@@ -274,6 +293,10 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
274
293
  });
275
294
  }
276
295
  function authorize(op, tab, owner, args = {}) {
296
+ authorizeAccess(op, tab, owner, args);
297
+ if (op === 'upload' && compareVersions(peer.version, '1.3.0') < 0) fail('UPLOAD_RELOAD_REQUIRED');
298
+ }
299
+ function authorizeAccess(op, tab, owner, args) {
277
300
  if (!enabled || !peer || peer.ws.readyState !== 1) fail('EXTENSION_NOT_CONNECTED');
278
301
  // The peer must hold the credential that is current now, admitted in the current generation: a replaced credential
279
302
  // is refused even before it would have expired.
@@ -296,9 +319,9 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
296
319
  if (t.url !== 'about:blank' && !state.sites.includes(publicOrigin(t.url))) fail('SITE_NOT_APPROVED');
297
320
  if (t.url === 'about:blank' && op !== 'navigate' && !HISTORY.includes(op)) fail('SITE_NOT_APPROVED');
298
321
  if (args.url && !state.sites.includes(publicOrigin(args.url))) fail('SITE_NOT_APPROVED');
299
- if (op === 'upload' && !state.uploads || op === 'download' && !state.downloads) fail('PERMISSION_REQUIRED');
322
+ if (op === 'download' && !state.downloads) fail('PERMISSION_REQUIRED');
300
323
  }
301
- async function request(op, tab, owner, args = {}) {
324
+ async function request(op, tab, owner, args = {}, upload) {
302
325
  // The revocation generation this command was issued in; an owner revocation that begins later cancels it.
303
326
  const issued = revocations, stale = () => !CONTROL.includes(op) && issued !== revocations;
304
327
  if (pending.size >= 32) fail('TIMEOUT');
@@ -325,7 +348,7 @@ export function createExtensionBridge({ port = 3345, log = () => {}, onInventory
325
348
  pending.delete(msg.id); reject(Object.assign(new Error('TIMEOUT'), { code: 'TIMEOUT' }));
326
349
  if (peer === via && via.ws.readyState === 1) void via.send({ type: 'cancel', id: msg.id }).catch(() => {});
327
350
  }, commandWait);
328
- pending.set(msg.id, { resolve, reject, timer, op, tab, owner, args, issued, expires: clock() + commandWait });
351
+ pending.set(msg.id, { resolve, reject, timer, op, tab, owner, args, upload, nextFile: 0, issued, expires: clock() + commandWait });
329
352
  via.send(msg).catch(error => { clearTimeout(timer); pending.delete(msg.id); reject(['CANCELLED', 'TIMEOUT'].includes(error?.code) ? coded(error.code)() : notConnected()); });
330
353
  });
331
354
  if (HISTORY.includes(op) && result.ok) {