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
@@ -273,10 +273,11 @@ export class NativeLoopRuntime {
273
273
  _loadLedger() {
274
274
  const rows = readJson(this.ledgerPath, []);
275
275
  if (!Array.isArray(rows)) return;
276
+ let options;
276
277
  for (const row of rows) {
277
278
  if (!row?.runId) continue;
278
279
  let stored;
279
- try { stored = readStoredToolListRecord(row, this.toolListOptions()); }
280
+ try { stored = readStoredToolListRecord(row, options ??= this.toolListOptions()); }
280
281
  catch (error) {
281
282
  // A historical run may name a custom preset the owner has since deleted. Refuse that
282
283
  // run, preserve the original selection for diagnosis, and keep the rest of the server up.
@@ -405,12 +406,13 @@ export class NativeLoopRuntime {
405
406
 
406
407
  _emit(type, record, extra = {}) {
407
408
  record.version = (Number(record.version) || 0) + 1;
408
- record.updatedAt = iso(this.now());
409
+ const leaseChange = type === 'sidepanel:run-claimed' || extra.reason === 'claim-released';
410
+ if (!leaseChange) record.updatedAt = iso(this.now());
409
411
  // Force-flush on terminal transitions (a crash between throttled flushes
410
412
  // would otherwise leave the run listed as running after a restart), and on
411
413
  // a suspension (the next start resumes the run from this ledger).
412
414
  const terminal = ['completed', 'failed', 'stopped', 'interrupted', 'suspended'].includes(record.status);
413
- this._persistLedger({ force: terminal });
415
+ this._persistLedger({ force: terminal && !leaseChange });
414
416
  const descriptor = cleanDescriptor(record);
415
417
  const message = { type, run: descriptor, ...extra };
416
418
  try { this.onEvent(message); } catch {}
@@ -1042,10 +1044,7 @@ export class NativeLoopRuntime {
1042
1044
  record.claimedBy = claimant;
1043
1045
  record.claimedAt = iso(this.now());
1044
1046
  if (changedOwner) this._emit('sidepanel:run-claimed', record);
1045
- else {
1046
- record.updatedAt = iso(this.now());
1047
- this._persistLedger();
1048
- }
1047
+ else this._persistLedger();
1049
1048
  return { ok: true, run: cleanDescriptor(record) };
1050
1049
  }
1051
1050
 
@@ -11,8 +11,8 @@ import { moreLoginProcessesRunning } from './process-identity.js';
11
11
  /** Strictly parse the observed MoreLogin /api/env/detail response; never retain cookies or other profile data. */
12
12
  export function portProtectionOf(detail) {
13
13
  const value = detail?.advancedSetting?.port_scan_protection;
14
- if (!value || ![0, 1].includes(value.switcher) || typeof value.value !== 'string') return null;
15
- const words = value.value.trim() ? value.value.split(',').map(s => s.trim()) : [];
14
+ if (!value || ![0, 1].includes(value.switcher) || (value.value !== null && typeof value.value !== 'string')) return null;
15
+ const words = value.value?.trim() ? value.value.split(',').map(s => s.trim()) : [];
16
16
  if (words.some(s => !/^\d{1,5}$/.test(s) || +s < 1 || +s > 65535)) return null;
17
17
  return { enabled: value.switcher === 1, ports: [...new Set(words.map(Number))] };
18
18
  }
@@ -26,7 +26,7 @@ export function moreLoginFailureDetail(error) {
26
26
  return 'API request failed';
27
27
  }
28
28
  function profileError(code, message, envId) {
29
- return Object.assign(new Error(message), { code, offenders: envId ? [{ envId, reason: code }] : [] });
29
+ return Object.assign(new Error(message), { code, sharedPreflight: true, offenders: envId ? [{ envId, reason: code }] : [] });
30
30
  }
31
31
  export async function reconcilePreflightProfiles(profiles, list, { requested = [], allowUnavailable = false,
32
32
  browserProcesses = moreLoginProcessesRunning, log = () => {} } = {}) {
@@ -48,9 +48,14 @@ export async function reconcilePreflightProfiles(profiles, list, { requested = [
48
48
  throw profileError('MORELOGIN_LIST_UNREADABLE', `MoreLogin profile listing failed: ${moreLoginFailureDetail(error)}. OpenCode build verification has not started.`);
49
49
  }
50
50
  if (!Array.isArray(live) || live.moreloginError || live.some(p => !p?.id)) throw profileError('MORELOGIN_LIST_UNREADABLE', 'MoreLogin profile listing is malformed or incomplete.');
51
- const ids = new Set(live.map(p => String(p.id)));
52
- for (const id of requested) if (!ids.has(String(id))) throw profileError('MORELOGIN_PROFILE_MISSING', `Explicitly requested MoreLogin profile ${id} is missing.`, String(id));
53
- return profiles.filter(p => { if (ids.has(p.envId)) return true; log(`Skipping stale MoreLogin profile ${p.envId}: absent from the complete live listing.`); return false; });
51
+ const byId = new Map(live.map(p => [String(p.id), p]));
52
+ for (const id of requested) if (!byId.has(String(id))) throw profileError('MORELOGIN_PROFILE_MISSING', `Explicitly requested MoreLogin profile ${id} is missing.`, String(id));
53
+ return profiles.flatMap(profile => {
54
+ const row = byId.get(profile.envId);
55
+ if (row) return [!profile.name && row.name ? { ...profile, name: row.name } : profile];
56
+ log(`Skipping stale MoreLogin profile ${profile.envId}: absent from the complete live listing.`);
57
+ return [];
58
+ });
54
59
  }
55
60
 
56
61
  export async function preflightExcludedPorts(profiles, readDetail) {
@@ -60,7 +65,7 @@ export async function preflightExcludedPorts(profiles, readDetail) {
60
65
  let policy, detail = 'malformed port protection policy';
61
66
  try { policy = portProtectionOf(await readDetail(profile.envId)); } catch (error) { detail = moreLoginFailureDetail(error); }
62
67
  if (!policy) throw profileError('MORELOGIN_POLICY_UNREADABLE', `MoreLogin profile ${name}: port protection could not be read from /api/env/detail (${detail}). Check the MoreLogin local API and try again; OpenCode build verification has not started.`, profile.envId);
63
- if (!policy.enabled) throw new Error(`MoreLogin profile ${name}: Port scan protection is off. Edit profile → Advanced settings → Port scan protection: Enable, then retry OpenCode build verification.`);
68
+ if (!policy.enabled) throw profileError('MORELOGIN_POLICY_DISABLED', `MoreLogin profile ${name}: Port scan protection is off. Edit profile → Advanced settings → Port scan protection: Enable, then retry OpenCode build verification.`, profile.envId);
64
69
  for (const port of policy.ports) ports.add(port);
65
70
  }
66
71
  return ports;
@@ -38,7 +38,7 @@
38
38
  // app's pages and every other read still load). A failure that may pass (a timeout, a busy system) is tried once
39
39
  // more at once and is kept on its connection for a moment only (NEGATIVE_TTL_MS), so an open tab recovers by
40
40
  // itself; a client that left is never kept. The server probes netstat and ps once at start (probe()), keeps the
41
- // state for GET /api/health (`ownerAuthority`: ok / degraded / unsupported / off), says the change in one loud log
41
+ // state for GET /api/health (`ownerAuthority`: pending / ok / degraded / unsupported / off), says the change in one loud log
42
42
  // line, and the page shows a banner while it is degraded (public/shared/ui-owner-authority.js).
43
43
  // Only a machine elsewhere on the network ('remote', below) still keeps the rules from before without a lookup: what to
44
44
  // do about a LAN client is a separate decision (TODO(peer-identity-remote): decide the LAN policy).
@@ -707,15 +707,14 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
707
707
  const say = (line) => { try { log(line); } catch { /* a logger's own failure */ } };
708
708
 
709
709
  // ── The state of the owner's authority (GET /api/health `ownerAuthority`, the page's banner) ──
710
- // off / unsupported never change. On macOS it is ok until the start probe or a lookup fails (degraded, with the
711
- // reason), and ok again after a whole lookup works (one that read the process table, not just this server's own
712
- // call, which needs netstat only). Each change is said once, loudly; a lookup that keeps failing is not said again.
710
+ // On macOS readiness is pending until the start probe or a whole lookup settles.
711
+ // This describes the verifier. Each request still needs its own peer verdict.
713
712
  const iso = (ms) => { try { return new Date(ms).toISOString(); } catch { return null; } };
714
713
  let authority = disabled
715
714
  ? { state: 'off', reason: 'SYNABUN_PEER_IDENTITY=off', retryable: false, since: iso(now()) }
716
715
  : !supported
717
716
  ? { state: 'unsupported', reason: unsupportedReason, retryable: false, since: iso(now()) }
718
- : { state: 'ok', reason: null, retryable: false, since: iso(now()) };
717
+ : { state: 'pending', reason: null, retryable: false, since: iso(now()) };
719
718
  let probed = null; // the start probe's promise
720
719
  function degrade(reason, { retryable = false, source = 'lookup' } = {}) {
721
720
  if (!supported) return;
@@ -736,7 +735,7 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
736
735
  if (!supported || authority.state === 'ok') return;
737
736
  const was = authority.reason;
738
737
  authority = { state: 'ok', reason: null, retryable: false, since: iso(now()) };
739
- say(`[peer-identity] owner authority restored (${source}): local programs are identified again${was ? ` (it was: ${was})` : ''}`);
738
+ if (was) say(`[peer-identity] owner authority restored (${source}): local programs are identified again (it was: ${was})`);
740
739
  }
741
740
  /** What a lookup said about the lookup itself: a whole answer restores, a failure degrades (one about a single
742
741
  * connection — it has no address any more — says nothing about the tools). */
@@ -745,7 +744,7 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
745
744
  if (verdict.status === 'unknown' && verdict.kind === 'failed') { if (!verdict.connection) degrade(verdict.reason, { retryable: verdict.retryable === true }); }
746
745
  else if (verdict.status === 'ok' && !verdict.self) restore();
747
746
  }
748
- /** The state for GET /api/health: { state: 'ok'|'degraded'|'unsupported'|'off', reason, retryable, since }. */
747
+ /** The state for GET /api/health: { state: 'pending'|'ok'|'degraded'|'unsupported'|'off', reason, retryable, since }. */
749
748
  function authorityState() {
750
749
  return { state: authority.state, reason: authority.reason, retryable: authority.retryable === true, since: authority.since };
751
750
  }
@@ -769,13 +768,19 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
769
768
  if (!parents.size) failures.push('ps listed no processes');
770
769
  else if (!parents.has(selfPid)) failures.push('ps did not list this server');
771
770
  } catch (error) { failures.push(`ps: ${failureText(error)}`); retryable = retryable || isTransientLookupError(error); }
771
+ // A request can finish its full lookup while this boot-time sample is in flight.
772
+ // Its observed outcome takes precedence over the preflight in either direction.
773
+ if (authority.state !== 'pending') return authorityState();
772
774
  if (failures.length) degrade(failures.join('; '), { retryable, source: 'start probe' });
773
775
  else {
774
776
  say('[peer-identity] start probe: netstat and ps answer; the owner\'s authority is checked against the calling process');
775
777
  restore('start probe');
776
778
  }
777
779
  return authorityState();
778
- })().catch((error) => { degrade(`the probe failed (${error?.message || error})`, { source: 'start probe' }); return authorityState(); });
780
+ })().catch((error) => {
781
+ if (authority.state === 'pending') degrade(`the probe failed (${error?.message || error})`, { source: 'start probe' });
782
+ return authorityState();
783
+ });
779
784
  return probed;
780
785
  }
781
786
  const isThisMachine = (addr) => {
@@ -32,6 +32,26 @@ const MAX_MSG_CHARS = 8 * 1024;
32
32
  const MAX_CLAUDE_FILE = 50 * 1024 * 1024;
33
33
  const MAX_CODEX_FILE = 50 * 1024 * 1024;
34
34
 
35
+ // The synchronous API is also used by explicit rebuilds. At startup, let
36
+ // socket callbacks and timers run between sessions once a slice is spent.
37
+ function finishScan(scan) {
38
+ let result = scan.next();
39
+ while (!result.done) result = scan.next();
40
+ return result.value;
41
+ }
42
+
43
+ async function finishBackgroundScan(scan) {
44
+ let sliceStart = performance.now();
45
+ for (;;) {
46
+ const result = scan.next();
47
+ if (result.done) return result.value;
48
+ if (performance.now() - sliceStart >= 12) {
49
+ await new Promise(resolve => setImmediate(resolve));
50
+ sliceStart = performance.now();
51
+ }
52
+ }
53
+ }
54
+
35
55
  const TAG_RE = /<\/?(?:ide_opened_file|ide_selection|system-reminder|antml:[a-z_]+)[^>]*>[^\n]*/gi;
36
56
  const GENERIC_TAG_RE = /<\/?[a-z_-]+[^>]*>/gi;
37
57
  const BLOCK_TAG_RE = /<(system-reminder|ide_opened_file|ide_selection)>[\s\S]*?<\/\1>/gi;
@@ -140,7 +160,12 @@ function parseClaudeSession(filePath) {
140
160
  };
141
161
  }
142
162
 
143
- export function rebuildClaudeCache({ project, onProgress } = {}) {
163
+ export function rebuildClaudeCache(options = {}) {
164
+ const scan = scanClaudeCache(options);
165
+ return options.background ? finishBackgroundScan(scan) : finishScan(scan);
166
+ }
167
+
168
+ function* scanClaudeCache({ project, onProgress }) {
144
169
  const emit = onProgress || (() => {});
145
170
  const homeDir = process.env.USERPROFILE || process.env.HOME;
146
171
  const projectsDir = join(homeDir, '.claude', 'projects');
@@ -166,6 +191,7 @@ export function rebuildClaudeCache({ project, onProgress } = {}) {
166
191
  try { files = readdirSync(projDir.path).filter(f => f.endsWith('.jsonl')); } catch { continue; }
167
192
 
168
193
  for (const file of files) {
194
+ yield;
169
195
  total++;
170
196
  const filePath = join(projDir.path, file);
171
197
  let stat;
@@ -289,7 +315,12 @@ function parseCodexSession(filePath) {
289
315
  };
290
316
  }
291
317
 
292
- export function rebuildCodexCache({ project, projects, accounts, onProgress } = {}) {
318
+ export function rebuildCodexCache(options = {}) {
319
+ const scan = scanCodexCache(options);
320
+ return options.background ? finishBackgroundScan(scan) : finishScan(scan);
321
+ }
322
+
323
+ function* scanCodexCache({ project, projects, accounts, onProgress }) {
293
324
  const emit = onProgress || (() => {});
294
325
  const homeDir = process.env.USERPROFILE || process.env.HOME;
295
326
  const configuredAccounts = Array.isArray(accounts) && accounts.length
@@ -312,6 +343,7 @@ export function rebuildCodexCache({ project, projects, accounts, onProgress } =
312
343
 
313
344
  const liveSessionIds = new Set();
314
345
  for (const session of catalog) {
346
+ yield;
315
347
  const filePath = session.rolloutPath;
316
348
  if (!filePath) continue;
317
349
  total++;
@@ -384,7 +416,12 @@ export function rebuildCodexCache({ project, projects, accounts, onProgress } =
384
416
 
385
417
  // OpenCode 2 keeps its sessions in session_v2 and their text in session_message rows
386
418
  // (lib/opencode-db-schema.js); a file without those tables has nothing to index.
387
- export function rebuildOpencodeCache({ getOpencodeDb, onProgress } = {}) {
419
+ export function rebuildOpencodeCache(options = {}) {
420
+ const scan = scanOpencodeCache(options);
421
+ return options.background ? finishBackgroundScan(scan) : finishScan(scan);
422
+ }
423
+
424
+ function* scanOpencodeCache({ getOpencodeDb, onProgress }) {
388
425
  const emit = onProgress || (() => {});
389
426
  if (typeof getOpencodeDb !== 'function') return { sessions: 0, updated: 0 };
390
427
 
@@ -423,6 +460,7 @@ export function rebuildOpencodeCache({ getOpencodeDb, onProgress } = {}) {
423
460
  } catch { partStmt = null; }
424
461
 
425
462
  for (const row of sessions) {
463
+ yield;
426
464
  const sessionId = row.id;
427
465
  const modifiedIso = row.time_updated ? new Date(row.time_updated).toISOString() : null;
428
466
  // Unchanged since the last pass (same update time and message count): skip it,
@@ -512,7 +512,7 @@ export function createTeamScheduler({
512
512
  }
513
513
  if (routed.route?.workflowId && routed.route.workflowId !== `team:${checked.plan.teamId}`) return refuse('TEAM_ROUTE_SPLIT_MISMATCH', 'This route already belongs to another team.', { status: 409 });
514
514
  const defaults = dispatchDefaults(input);
515
- if (!routed.route && !defaults.provider && checked.plan.slices.some((slice) => !slice.agentRef)) {
515
+ if (!routed.route && !defaults.provider && checked.plan.slices.some((slice) => !slice.agentRef || slice.agentRef === 'none')) {
516
516
  return refuse('TEAM_PROVIDER_REQUIRED', 'Name the provider the team\'s workers run on (or give every slice an agent_ref).', { status: 400 });
517
517
  }
518
518
  if (records.has(checked.plan.teamId)) return refuse('TEAM_EXISTS', `A team named "${checked.plan.teamId}" exists already: a team id is used once.`, { status: 409 });
@@ -557,7 +557,7 @@ export function createTeamScheduler({
557
557
  // model, effort and account are for the slices that name none. (An approved route binds every slice all the same:
558
558
  // the router writes its target over the spec after the agent was applied.)
559
559
  const { provider: _provider, model: _model, effort: _effort, accountId: _accountId, ...shared } = record.dispatch || {};
560
- const defaults = slice.agentRef ? shared : (record.dispatch || {});
560
+ const defaults = slice.agentRef && slice.agentRef !== 'none' ? shared : (record.dispatch || {});
561
561
  const spec = {
562
562
  ...defaults,
563
563
  task: lead ? `${lead}\n\nYOUR SLICE'S TASK (as first given):\n${slice.task}` : slice.task,
@@ -365,7 +365,7 @@ export function validateTeamPlan(input, { density = null, maxSlices = null } = {
365
365
  const rawRef = pick(raw, 'agentRef');
366
366
  if (rawRef !== undefined && rawRef !== null && rawRef !== '') {
367
367
  if (typeof rawRef !== 'string') add(`${at}.agentRef`, 'invalid_type', 'agentRef must be text.');
368
- else if (!parseAgentRef(rawRef)) add(`${at}.agentRef`, 'invalid_format', `"${rawRef.slice(0, 80)}" is not an agent ref ("<id>", "<id>@<revision>", "global:<id>", "project:<id>").`);
368
+ else if (rawRef.trim() !== 'none' && !parseAgentRef(rawRef)) add(`${at}.agentRef`, 'invalid_format', `"${rawRef.slice(0, 80)}" is not an agent ref ("<id>", "<id>@<revision>", "global:<id>", "project:<id>").`);
369
369
  }
370
370
  const rawOwned = pick(raw, 'ownedPaths');
371
371
  if ((!plan.readOnly || rawOwned != null) && (!Array.isArray(rawOwned) || rawOwned.some((item) => typeof item !== 'string'))) add(`${at}.ownedPaths`, 'invalid_type', 'ownedPaths must be a list of patterns.');
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "neural-memory-interface",
3
- "version": "2.4.0",
3
+ "version": "2.4.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "neural-memory-interface",
9
- "version": "2.4.0",
9
+ "version": "2.4.1",
10
10
  "hasInstallScript": true,
11
11
  "license": "Apache-2.0",
12
12
  "dependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neural-memory-interface",
3
- "version": "2.4.0",
3
+ "version": "2.4.1",
4
4
  "private": true,
5
5
  "description": "Private local SynaBun interface for memory visualization and multi-agent workflows",
6
6
  "license": "Apache-2.0",
@@ -96,6 +96,57 @@
96
96
  </script>
97
97
  </head>
98
98
  <body>
99
+ <div id="startup-status" role="status" style="position:fixed;inset:0;z-index:99999;display:grid;place-content:center;text-align:center;background:#050505;color:var(--t-primary,#ccc);font-family:Inter,system-ui,sans-serif">
100
+ <strong>SynaBun</strong><span>Connecting…</span>
101
+ <a href="" hidden style="color:inherit">Retry connection</a>
102
+ </div>
103
+ <script>
104
+ // The module graph may never arrive. Keep the initial page usable before its overlay takes over.
105
+ (() => {
106
+ const status = document.getElementById('startup-status');
107
+ let sawOffline = false;
108
+ let entryFailed = false;
109
+ // A module graph that failed to load stays failed in this document, even if
110
+ // the server has already recovered by the time the first probe runs.
111
+ addEventListener('error', event => {
112
+ if (event.target?.getAttribute?.('src') === '/variant/3d/main.js') entryFailed = true;
113
+ }, true);
114
+ // Both module graphs share one automatic retry for this navigation.
115
+ function retryHealthyStartup() {
116
+ if (!history.state?.startupRetried) {
117
+ try {
118
+ history.replaceState({ ...history.state, startupRetried: true }, '');
119
+ location.reload();
120
+ return;
121
+ } catch { /* Manual retry is still available. */ }
122
+ }
123
+ entryFailed = true;
124
+ status.querySelector('span').textContent = 'Interface failed to load';
125
+ status.querySelector('a').hidden = false;
126
+ if (!status.isConnected) document.body.append(status);
127
+ }
128
+ addEventListener('synabun:startup-module-failed', retryHealthyStartup, { once: true });
129
+ async function checkStartup() {
130
+ if (!status.isConnected) return;
131
+ status.querySelector('a').hidden = false;
132
+ let healthy = false;
133
+ try {
134
+ const response = await fetch('/api/health', { cache: 'no-store', signal: AbortSignal.timeout(3000) });
135
+ const health = response.ok && await response.json();
136
+ healthy = health?.ok === true && !health.restarting;
137
+ } catch {}
138
+ if (!status.isConnected) return;
139
+ if (healthy && (entryFailed || sawOffline)) {
140
+ retryHealthyStartup();
141
+ return;
142
+ }
143
+ if (!healthy) sawOffline = true;
144
+ status.querySelector('span').textContent = healthy ? 'Loading interface…' : 'Server offline';
145
+ setTimeout(checkStartup, 3000);
146
+ }
147
+ setTimeout(checkStartup, 12000);
148
+ })();
149
+ </script>
99
150
 
100
151
  <!-- html2canvas for card screenshot MCP tool (vendored: public/vendor/html2canvas/) -->
101
152
  <script src="/vendor/html2canvas/html2canvas-1.4.1.min.js" defer></script>
@@ -444,7 +444,7 @@
444
444
  }
445
445
  </style>
446
446
  </head>
447
- <body>
447
+ <body data-synabun-offline>
448
448
 
449
449
  <!-- Ambient particles -->
450
450
  <div class="particles" id="particles"></div>
@@ -571,8 +571,9 @@
571
571
 
572
572
  async function serverAnswers() {
573
573
  try {
574
- const res = await fetch('/', { method: 'HEAD', cache: 'no-store' });
575
- return res.ok;
574
+ const res = await fetch('/api/health', { cache: 'no-store', signal: AbortSignal.timeout(3000) });
575
+ const health = res.ok && await res.json();
576
+ return health?.ok === true && !health.restarting;
576
577
  } catch {
577
578
  return false;
578
579
  }
@@ -498,8 +498,8 @@ function openMenu(ctx, ed, opener, head) {
498
498
  ctx.caps.has('export') ? { id: 'export', label: t('agentsStudio.action.export') } : null,
499
499
  canExportNative(ctx, ed.agent) ? { id: 'native-export', label: t('agentsStudio.nativeExport.action') } : null,
500
500
  draft?.status === 'draft' ? { id: 'discard', label: t('agentsStudio.action.discardDraft'), danger: true } : null,
501
- ctx.owner && (draft || s.status === 'approved') ? { id: 'withdraw', label: t('agentsStudio.action.withdrawMenu'), danger: true } : null,
502
- ctx.owner ? { id: 'delete', label: t('agentsStudio.action.delete'), danger: true } : null,
501
+ ctx.owner && ed.agent?.source !== 'builtin' && (draft || s.status === 'approved') ? { id: 'withdraw', label: t('agentsStudio.action.withdrawMenu'), danger: true } : null,
502
+ ctx.owner && ed.agent?.source !== 'builtin' ? { id: 'delete', label: t('agentsStudio.action.delete'), danger: true } : null,
503
503
  ].filter(Boolean);
504
504
  const el = document.createElement('div');
505
505
  el.className = 'sx-menu ax-menu';
@@ -202,7 +202,7 @@ function refreshChoices(host, ctx, ed) {
202
202
  if (busy) {
203
203
  if (!input || !made.entries) continue;
204
204
  setDropdownItems(input, made.entries);
205
- if (made.summary) { const label = el.querySelector('.cc-dropdown-value'); if (label) { label.textContent = made.summary; label.title = made.summary; } }
205
+ if (made.summary) { const label = el.querySelector('.cc-dropdown-value'); if (label) label.textContent = made.summary; }
206
206
  continue;
207
207
  }
208
208
  const holder = document.createElement('template');
@@ -49,7 +49,7 @@ export function statusLabel(t, status) {
49
49
  /** The labels of where an agent stands: its status with the revision, and a working revision on top of it. */
50
50
  export function standingLabels(t, agent) {
51
51
  const s = standingOf(agent);
52
- return html`${statusLabel(t, s.status)}${s.revision ? html`<span class="ax-rev">${t('agentsStudio.revisionShort', { n: s.revision })}</span>` : ''}${s.pending ? html`<span class="sx-label ax-status ax-status--${s.pending}">${t(`agentsStudio.pending.${s.pending}`, { n: s.draftRevision ?? '' })}</span>` : ''}${s.damaged ? html`<span class="sx-label ax-status ax-status--damaged" title="${t('agentsStudio.damagedHelp')}">${t('agentsStudio.damaged')}</span>` : ''}`;
52
+ return html`${agent.source === 'builtin' ? html`<span class="sx-chip ax-chip" title="${t('agentsStudio.builtinHelp')}">${t('agentsStudio.builtin')}</span>` : ''}${statusLabel(t, s.status)}${s.revision ? html`<span class="ax-rev">${t('agentsStudio.revisionShort', { n: s.revision })}</span>` : ''}${s.pending ? html`<span class="sx-label ax-status ax-status--${s.pending}">${t(`agentsStudio.pending.${s.pending}`, { n: s.draftRevision ?? '' })}</span>` : ''}${s.damaged ? html`<span class="sx-label ax-status ax-status--damaged" title="${t('agentsStudio.damagedHelp')}">${t('agentsStudio.damaged')}</span>` : ''}`;
53
53
  }
54
54
 
55
55
  export function scopeTag(t, scope, projects = []) {
@@ -78,7 +78,7 @@ export function field({ id, label, control, help = '', count = null, field: name
78
78
 
79
79
  /** The app's dropdown as markup for `html` (the hidden input has `id`; its change event bubbles). */
80
80
  export function dropdown(id, entries, { labelledBy = '', label = '', multiple = false, summary = '', disabled = false, field: name = '', classes = '' } = {}) {
81
- return raw(dropdownHTML(id, entries, { labelledBy, label, multiple, summary, disabled, classes: `sx-dd ${classes}`.trim(), inputAttrs: name ? `data-form-field="${name}"` : '' }));
81
+ return raw(dropdownHTML(id, entries, { labelledBy, label, multiple, summary, disabled, fitTrigger: !!name, classes: `sx-dd ${classes}`.trim(), inputAttrs: name ? `data-form-field="${name}"` : '' }));
82
82
  }
83
83
 
84
84
  /** The problems of one field, as the lines under it. */
@@ -47,7 +47,8 @@ function jsonBody(data) {
47
47
  // ─── Health ──────────────────────────────
48
48
 
49
49
  export async function fetchHealth() {
50
- const res = await fetch('/api/health', { signal: AbortSignal.timeout(3000) });
50
+ const res = await fetch('/api/health', { cache: 'no-store', signal: AbortSignal.timeout(3000) });
51
+ if (!res.ok) throw new Error('Health check failed: ' + res.status);
51
52
  return res.json();
52
53
  }
53
54
 
@@ -254,6 +254,7 @@ export function updateRunCard(card, run, opts = {}) {
254
254
  const usage = runTokens?.total > 0 || run.usageObserved ? formatRunTokens(runTokens, run.usageFidelity || run.tokens?.fidelity, t) : null;
255
255
  if (usage) bits.push(`<span class="asst-usage-run-tokens" aria-label="${esc(usage.label)}">${esc(usage.text)}</span>`);
256
256
  if (run.currentIteration > 1) bits.push(`<span>${esc(t('assistant.run.turn', 'turn {n}', { n: run.currentIteration }))}</span>`);
257
+ if (run.agentRef) bits.push(`<span>${esc(run.agentRef)}</span>`);
257
258
  if (run.route && typeof run.route === 'object') {
258
259
  const r = run.route;
259
260
  const routeBits = [r.taskClassLabel || r.taskClass || t('assistant.routes.task', 'task')];
@@ -145,6 +145,7 @@ function normalizeRouteOption(o) {
145
145
  vision: src.vision === true,
146
146
  price: priceOf(src.price),
147
147
  contextWindow: num(src.contextWindow),
148
+ ...(src.agentRef ? { agentRef: str(src.agentRef) } : {}),
148
149
  reason: str(src.reason),
149
150
  warning: str(src.warning) || null,
150
151
  budget: str(src.budget) || null,
@@ -571,6 +572,7 @@ export function routeLineParts(route, phase = 'decided', { brainLabel = '', t =
571
572
  default: decided = r.remembered ? tr('assistant.routes.remembered', 'your saved choice') : '';
572
573
  }
573
574
  const meta = [];
575
+ if (kind === 'dispatch' && r.agentRef) meta.push(r.agentRef);
574
576
  if (r.plannedSplit?.workers) meta.push(tf(t)('assistant.routes.splitWorkers', '{count} workers planned', { count: r.plannedSplit.workers }));
575
577
  const accountLabel = routeDisplayAccount(target, t);
576
578
  if (accountLabel) meta.push(accountLabel);
@@ -958,7 +960,7 @@ export function renderRouteCard(container, input, hooks = {}) {
958
960
  row.setAttribute('aria-disabled', o.disabled ? 'true' : 'false');
959
961
  row.tabIndex = -1;
960
962
  const kindWord = o.kind && o.kind !== 'direct' ? routeKindWord(o.kind, hooks.t) : '';
961
- const sub = [kindWord, routeDisplayAccount(o, hooks.t), o.effort && o.effort !== 'off' && !o.titleEffort ? routeEffortWord(o.effort) : '', o.price ? priceText(o.price) : '', o.vision ? tr('assistant.brain.vision', 'vision') : '', o.reason].filter(Boolean).join(' · ');
963
+ const sub = [kindWord, o.agentRef, routeDisplayAccount(o, hooks.t), o.effort && o.effort !== 'off' && !o.titleEffort ? routeEffortWord(o.effort) : '', o.price ? priceText(o.price) : '', o.vision ? tr('assistant.brain.vision', 'vision') : '', o.reason].filter(Boolean).join(' · ');
962
964
  row.innerHTML = `
963
965
  <span class="asst-route-num" aria-hidden="true">${esc(o.number)}</span>
964
966
  <span class="asst-route-opt-icon asst-icon" aria-hidden="true"${o.provider ? ` style="color:${esc(providerColor(o.provider))}"` : ''}>${providerIconHtml(o.provider, hooks)}</span>
@@ -124,21 +124,21 @@ const multipleText = (options, values) => options.filter(o => values.includes(St
124
124
 
125
125
  // ── Markup ──
126
126
 
127
- function optionHTML(id, option, index, chosen) {
127
+ function optionHTML(id, option, index, chosen, fitTrigger) {
128
128
  const label = String(option.label ?? '');
129
129
  const active = Array.isArray(chosen) ? (chosen.includes(String(option.value ?? '')) || (option.automatic && option.selected)) : index === chosen;
130
130
  return `<div class="cc-dropdown-item${active ? ' active' : ''}" id="${esc(id)}-opt-${index}" role="option" aria-selected="${active}"`
131
- + `${option.disabled ? ' aria-disabled="true"' : ''} data-value="${esc(option.value ?? '')}" data-index="${index}"${option.exclusive ? ' data-exclusive="true"' : ''}${option.scope ? ` data-scope="${esc(option.scope)}"` : ''}${option.automatic ? ' data-automatic="true"' : ''} data-label="${esc(label)}" title="${esc(option.caption || label)}">${Array.isArray(chosen) ? '<span class="cc-dropdown-check" aria-hidden="true"></span>' : ''}<span>${esc(label)}${option.caption ? `<small class="cc-dropdown-caption">${esc(option.caption)}</small>` : ''}</span></div>`;
131
+ + `${option.disabled ? ' aria-disabled="true"' : ''} data-value="${esc(option.value ?? '')}" data-index="${index}"${option.exclusive ? ' data-exclusive="true"' : ''}${option.scope ? ` data-scope="${esc(option.scope)}"` : ''}${option.automatic ? ' data-automatic="true"' : ''} data-label="${esc(label)}"${fitTrigger ? '' : ` title="${esc(option.caption || label)}"`}>${Array.isArray(chosen) ? '<span class="cc-dropdown-check" aria-hidden="true"></span>' : ''}<span>${esc(label)}${option.caption ? `<small class="cc-dropdown-caption">${esc(option.caption)}</small>` : ''}</span></div>`;
132
132
  }
133
133
 
134
134
  /** The menu's options (and headings) for `entries`, the `chosen` index marked. */
135
- export function menuHTML(id, entries, chosen = chosenIndex(flatOptions(entries))) {
135
+ export function menuHTML(id, entries, chosen = chosenIndex(flatOptions(entries)), fitTrigger = false) {
136
136
  let index = 0;
137
137
  let group = 0;
138
138
  return (entries || []).filter(Boolean).map((entry) => {
139
- if (!Array.isArray(entry.options)) return optionHTML(id, entry, index++, chosen);
139
+ if (!Array.isArray(entry.options)) return optionHTML(id, entry, index++, chosen, fitTrigger);
140
140
  const headId = `${id}-grp-${group++}`;
141
- const options = entry.options.filter(Boolean).map(option => optionHTML(id, option, index++, chosen)).join('');
141
+ const options = entry.options.filter(Boolean).map(option => optionHTML(id, option, index++, chosen, fitTrigger)).join('');
142
142
  return `<div class="cc-dropdown-optgroup" role="group" aria-labelledby="${esc(headId)}"><div class="cc-dropdown-group" id="${esc(headId)}" role="presentation">${esc(entry.group ?? '')}</div>${options}</div>`;
143
143
  }).join('');
144
144
  }
@@ -148,17 +148,17 @@ export function menuHTML(id, entries, chosen = chosenIndex(flatOptions(entries))
148
148
  * Name it with `labelledBy` (the id of its visible label) or `label`. `classes` and `attrs` go on
149
149
  * the `.cc-dropdown`.
150
150
  */
151
- export function dropdownHTML(id, entries, { classes = '', labelledBy = '', label = '', attrs = '', inputAttrs = '', disabled = false, multiple = false, summary = '' } = {}) {
151
+ export function dropdownHTML(id, entries, { classes = '', labelledBy = '', label = '', attrs = '', inputAttrs = '', disabled = false, multiple = false, summary = '', fitTrigger = false } = {}) {
152
152
  const options = flatOptions(entries);
153
153
  const chosen = multiple ? multipleValues(options) : chosenIndex(options);
154
154
  const current = chosen >= 0 ? options[chosen] : null;
155
155
  const name = labelledBy ? ` aria-labelledby="${esc(labelledBy)}"` : label ? ` aria-label="${esc(label)}"` : '';
156
156
  const text = multiple ? (summary || multipleText(options, chosen)) : String(current?.label ?? '');
157
157
  return `<input type="hidden" id="${esc(id)}" value="${esc(multiple ? chosen.join(',') : current?.value ?? '')}"${disabled ? ' disabled' : ''}${inputAttrs ? ` ${inputAttrs}` : ''}>`
158
- + `<div class="cc-dropdown${classes ? ` ${classes}` : ''}${disabled ? ' disabled' : ''}" data-for="${esc(id)}"${multiple ? ' data-multiple="true"' : ''}${attrs ? ` ${attrs}` : ''}>`
158
+ + `<div class="cc-dropdown${classes ? ` ${classes}` : ''}${disabled ? ' disabled' : ''}" data-for="${esc(id)}"${fitTrigger ? ' data-fit-trigger="true"' : ''}${multiple ? ' data-multiple="true"' : ''}${attrs ? ` ${attrs}` : ''}>`
159
159
  + `<button type="button" class="cc-dropdown-trigger" id="${esc(id)}-trigger" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-controls="${esc(id)}-menu"${name}${disabled ? ' disabled' : ''}>`
160
- + `<span class="cc-dropdown-value" title="${esc(text)}">${esc(text)}</span>${ARROW}</button>`
161
- + `<div class="cc-dropdown-menu" id="${esc(id)}-menu" role="listbox"${multiple ? ' aria-multiselectable="true"' : ''}${name} tabindex="-1">${menuHTML(id, entries, chosen)}</div>`
160
+ + `<span class="cc-dropdown-value"${fitTrigger ? '' : ` title="${esc(text)}"`}>${esc(text)}</span>${ARROW}</button>`
161
+ + `<div class="cc-dropdown-menu" id="${esc(id)}-menu" role="listbox"${multiple ? ' aria-multiselectable="true"' : ''}${name} tabindex="-1">${menuHTML(id, entries, chosen, fitTrigger)}</div>`
162
162
  + '</div>';
163
163
  }
164
164
 
@@ -218,7 +218,7 @@ function showChosen(dd, index) {
218
218
  if (input) input.value = item ? item.dataset.value ?? '' : '';
219
219
  if (label) {
220
220
  label.textContent = item ? item.textContent : '';
221
- label.title = label.textContent;
221
+ if (dd.dataset.fitTrigger !== 'true') label.title = label.textContent;
222
222
  }
223
223
  }
224
224
 
@@ -233,7 +233,7 @@ function showMultiple(dd, values) {
233
233
  if (input) input.value = values.join(',');
234
234
  if (label) {
235
235
  label.textContent = multipleText(optionsOf(items), values);
236
- label.title = label.textContent;
236
+ if (dd.dataset.fitTrigger !== 'true') label.title = label.textContent;
237
237
  }
238
238
  }
239
239
 
@@ -285,6 +285,10 @@ function place(dd) {
285
285
  const roomWidth = Math.max(0, room.right - room.left);
286
286
  style.maxWidth = `${roomWidth}px`;
287
287
  style.minWidth = `${Math.min(t.width, roomWidth)}px`;
288
+ if (dd.dataset.fitTrigger === 'true') {
289
+ style.width = style.minWidth;
290
+ style.maxHeight = 'var(--cc-menu-max-height)';
291
+ }
288
292
  const height = menu.offsetHeight;
289
293
  const below = room.bottom - t.bottom - GAP;
290
294
  const above = t.top - GAP - room.top;
@@ -333,7 +337,7 @@ function close(dd, { focus = false, cancel = false } = {}) {
333
337
  if (cancel && changed) {
334
338
  if (menu && dd._ccBeforeMenu != null) menu.innerHTML = dd._ccBeforeMenu;
335
339
  showMultiple(dd, dd._ccBefore === '' ? [''] : dd._ccBefore.split(','));
336
- if (label) { label.textContent = dd._ccBeforeLabel; label.title = label.textContent; }
340
+ if (label) { label.textContent = dd._ccBeforeLabel; if (dd.dataset.fitTrigger !== 'true') label.title = label.textContent; }
337
341
  }
338
342
  dd.classList.remove('open', 'drop-up');
339
343
  trigger?.setAttribute('aria-expanded', 'false');
@@ -382,7 +386,7 @@ export function setDropdownItems(input, entries) {
382
386
  const options = flatOptions(entries);
383
387
  const multiple = dd.dataset.multiple === 'true';
384
388
  const chosen = multiple ? multipleValues(options) : chosenIndex(options);
385
- menu.innerHTML = menuHTML(input.id, entries, chosen);
389
+ menu.innerHTML = menuHTML(input.id, entries, chosen, dd.dataset.fitTrigger === 'true');
386
390
  if (multiple) showMultiple(dd, chosen); else showChosen(dd, chosen);
387
391
  if (!wasOpen) return;
388
392
  place(dd);
@@ -458,11 +462,13 @@ export function wireDropdowns(root, { signal } = {}) {
458
462
 
459
463
  // The focus stays on the trigger while a choice is clicked.
460
464
  on(root, 'mousedown', (e) => { if (e.target.closest?.('.cc-dropdown-menu')) e.preventDefault(); });
461
- on(root, 'mouseover', (e) => {
465
+ // Scrolling an item under a stationary pointer generates mouseover. Only an actual move
466
+ // should replace the keyboard highlight after End/PageDown scrolled the listbox.
467
+ on(root, 'pointermove', (e) => {
462
468
  const item = e.target.closest?.('.cc-dropdown-item');
463
469
  if (!item || item.getAttribute('aria-disabled') === 'true') return;
464
470
  const dd = item.closest('.cc-dropdown');
465
- if (isOpen(dd)) highlight(dd, itemsOf(dd).indexOf(item));
471
+ if (isOpen(dd) && !item.classList.contains('highlight')) highlight(dd, itemsOf(dd).indexOf(item));
466
472
  });
467
473
 
468
474
  on(root, 'keydown', (e) => {
@@ -915,4 +915,5 @@ export function injectSharedHTML() {
915
915
  // out once without it.
916
916
  document.documentElement.classList.add(FRAMED_CLASS);
917
917
  document.body.insertAdjacentHTML('afterbegin', getSharedHTML());
918
+ document.getElementById('startup-status')?.remove();
918
919
  }