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
@@ -134,6 +134,7 @@ import * as fsp from 'fs/promises';
134
134
  import { createInterface as createReadlineInterface } from 'readline';
135
135
  import { jsonlLines } from './lib/jsonl-lines.js';
136
136
  import { createHistoryCache } from './lib/claude-history-cache.js';
137
+ import { createClaudeBgTasks, claudeOutputRoots } from './lib/claude-bg-tasks.js';
137
138
  import { createRolloutReader } from './lib/codex-rollout-reader.js';
138
139
  import { randomBytes, randomUUID, createHash, pbkdf2Sync, createDecipheriv } from 'crypto';
139
140
  import { exec, execFile, execSync, spawn, spawnSync } from 'child_process';
@@ -317,8 +318,9 @@ import {
317
318
  import * as moreLogin from './lib/browser-profiles.js';
318
319
  import { createStyleGuideStore } from './lib/style-guide/store.js';
319
320
  import { registerStyleGuideRoutes } from './lib/style-guide/api.js';
320
- import { initBlobStore, blobGetNamespace, blobGet, blobPut, blobDelete, blobClearNamespace, blobPrune, closeBlobStore } from './lib/ui-blob-store.js';
321
+ import { initBlobStore, blobGetNamespace, blobGetNamespaceJsonAsync, blobGet, blobPut, blobDelete, blobClearNamespace, blobPrune, closeBlobStore } from './lib/ui-blob-store.js';
321
322
  import { createUiBlobRouter } from './lib/ui-blob-api.js';
323
+ import { createLoopInventoryScanner } from './lib/loop-inventory.js';
322
324
  import { memoCache, asyncPool } from './lib/memo-cache.js';
323
325
  import {
324
326
  buildAntigravityMcpEntry,
@@ -703,9 +705,11 @@ import { ownerRouteGuard } from './lib/http-guards.js';
703
705
  import { createBridgeStore, createExtensionBridge } from './lib/browser-extension-bridge.js';
704
706
  import { createExtensionAdapter } from './lib/browser-extension-adapter.js';
705
707
  import { detectBrowsers } from './lib/browser-default.js';
706
- import { extensionFolderState } from './lib/browser-extension-folder.js';
708
+ import { compareVersions } from './lib/browser-extension-folder.js';
707
709
  import { createExtensionPackage } from './lib/browser-extension-package.js';
710
+ import { createExtensionUpdate, ownerReloadHandler } from './lib/browser-extension-update.js';
708
711
  import { createExtensionSetup, extensionVersions, setupError as extensionSetupError } from './lib/browser-extension-setup.js';
712
+ import { stoppedProfileAdvice } from './lib/browser-connection-state.js';
709
713
  import { safeError as extensionSafeError } from './lib/browser-extension-protocol.js';
710
714
  import { setUntrustedFileHeaders } from './lib/untrusted-file-headers.js';
711
715
  import { BUNDLED_LOGO_FILES, UPLOADED_IMAGE_PATH } from './lib/request-gate.js';
@@ -3809,8 +3813,12 @@ function claudeChildEnv(env = process.env) {
3809
3813
  try { return gitBash.childEnv(ordered); } catch { return ordered; }
3810
3814
  }
3811
3815
  // SynaBun's own git features (the terminal's branch and checkout, the File Explorer's and the code editor's git,
3812
- // the git routes) run the copy's git.exe on a PC without git: its path for spawnGit, its folder for every read.
3813
- setGitFallbackFolder(() => { const git = gitBash.gitExecutable(); return git ? dirname(git) : null; });
3816
+ // the git routes) resolve git through one resolver (bundled → managed → system) for both startup and the runner.
3817
+ setGitFallbackFolder(() => {
3818
+ const git = gitBash.managedGitExecutable?.() || gitBash.gitExecutable({ includeSystem: true });
3819
+ return git ? dirname(git) : null;
3820
+ });
3821
+ gitStatusRunner.setBinaryResolver(() => resolveGitPathInBackground());
3814
3822
  // The user's own `claude`, started in another terminal: ~/.claude/settings.json names SynaBun's copy while it is
3815
3823
  // the one in use and loses that value when it is not; a value of the user's own is never touched. Windows only.
3816
3824
  function syncGitBashSettings(resolution = gitBash.resolution()) {
@@ -4000,9 +4008,10 @@ async function detectOpencode({ force = false } = {}) {
4000
4008
  // OpenCode 2). Every start path throws it or answers with it: isolated serves, loops and schedules, workers.
4001
4009
  async function opencodeStartRefusal() {
4002
4010
  const detected = await detectOpencode();
4003
- if (detected.major == null || detected.supported) return null;
4004
- const refusal = new Error(detected.reason);
4005
- refusal.code = 'OPENCODE_UNSUPPORTED';
4011
+ if (detected.supported) return null;
4012
+ if (detected.major == null && (detected.path || detected.commandLine)) return null;
4013
+ const refusal = new Error(detected.reason || 'OpenCode is not installed.');
4014
+ refusal.code = detected.major == null ? 'OPENCODE_NOT_INSTALLED' : 'OPENCODE_UNSUPPORTED';
4006
4015
  return refusal;
4007
4016
  }
4008
4017
 
@@ -9922,7 +9931,7 @@ function handleOpencodeV2Ws(ws) {
9922
9931
  // `_ocpLastCheck` keeps the whole answer (what answered, and why it is not usable).
9923
9932
  let _ocpLastCheck = null;
9924
9933
  async function checkOpencodeHealth() {
9925
- const check = await checkOpencodeServer({ port: _ocpPort, password: _ocpPassword, timeoutMs: 3000 });
9934
+ const check = await checkOpencodeServer({ port: _ocpPort, password: _ocpPassword, timeoutMs: 3000, signal: arguments[0]?.signal || null });
9926
9935
  _ocpLastCheck = check;
9927
9936
  if (check.ok) _ocpVersion = check.version || null;
9928
9937
  return check.ok;
@@ -10044,11 +10053,12 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10044
10053
  if (_ocpSharedEnd) await _ocpSharedEnd;
10045
10054
 
10046
10055
  // 0. Which OpenCode is installed. One SynaBun does not drive (OpenCode 1, an OpenCode 2 older than the
10047
- // minimum) is refused here, with a sentence the panel and Settings show, instead of failing call by call later.
10056
+ // minimum) or a missing CLI is refused here, with a sentence the panel and Settings show, instead of
10057
+ // spawning a shell that exits immediately and waiting 15 s for health.
10048
10058
  const detected = await detectOpencode();
10049
- if (detected.major != null && !detected.supported) {
10059
+ if (!detected.supported && (detected.major != null || (!detected.path && !detected.commandLine))) {
10050
10060
  _ocpStarting = false;
10051
- reportOpencodeProblem(detected.reason);
10061
+ reportOpencodeProblem(detected.reason || 'OpenCode is not installed.');
10052
10062
  return false;
10053
10063
  }
10054
10064
  _ocpProblem = null;
@@ -10090,6 +10100,17 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10090
10100
  outcome = await oneOpencodeStartAtATime(async () => {
10091
10101
  let proc = null;
10092
10102
  let tracked = null;
10103
+ let procExited = false;
10104
+ let procExitCode = null;
10105
+ let procExitSignal = null;
10106
+ let procError = null;
10107
+ const exitWaiters = new Set();
10108
+ const exitAbort = new AbortController();
10109
+ const wakeExitWaiters = () => {
10110
+ if (!exitAbort.signal.aborted) exitAbort.abort();
10111
+ for (const fn of exitWaiters) fn();
10112
+ exitWaiters.clear();
10113
+ };
10093
10114
  try {
10094
10115
  // A token of this spawn in its environment: what tells its processes from any other (lib/opencode-serve-records.js).
10095
10116
  const token = opencodeServeRecords.newToken();
@@ -10120,7 +10141,21 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10120
10141
  proc.stdout?.on('end', () => outLog.flush());
10121
10142
  proc.stderr?.on('end', () => errLog.flush());
10122
10143
  proc.on('close', () => { outLog.flush(); errLog.flush(); });
10123
- proc.on('exit', (code) => {
10144
+ const childExited = () => proc.exitCode != null || proc.signalCode != null;
10145
+ proc.on('error', (err) => {
10146
+ // Match trackOpencodeServe's rule: a spawn that failed (no pid) may never exit,
10147
+ // whereas an error on a live child (e.g. failed kill) leaves the process running.
10148
+ if (!proc.pid || childExited()) {
10149
+ procExited = true;
10150
+ procError = err;
10151
+ wakeExitWaiters();
10152
+ }
10153
+ });
10154
+ proc.on('exit', (code, signal) => {
10155
+ procExited = true;
10156
+ procExitCode = code;
10157
+ procExitSignal = signal;
10158
+ wakeExitWaiters();
10124
10159
  console.log(`[opencode] Process exited with code ${code}`);
10125
10160
  // A serve stopped or replaced meanwhile says nothing about the one running now. (Its record goes with
10126
10161
  // its process either way: trackOpencodeServe.)
@@ -10140,9 +10175,19 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10140
10175
  }
10141
10176
  return 'not-spawned';
10142
10177
  }
10178
+ const isGone = () => procExited || proc.exitCode != null || proc.signalCode != null;
10179
+ const waitStep = (ms) => new Promise((done) => {
10180
+ if (isGone()) { done(); return; }
10181
+ const onEnd = () => { clearTimeout(t); done(); };
10182
+ const t = setTimeout(() => { exitWaiters.delete(onEnd); done(); }, ms);
10183
+ exitWaiters.add(onEnd);
10184
+ });
10185
+ let exitedEarly = false;
10143
10186
  for (let i = 0; i < 30; i++) {
10144
- await new Promise(r => setTimeout(r, 500));
10145
- if (await checkOpencodeHealth()) {
10187
+ await waitStep(500);
10188
+ if (isGone()) { exitedEarly = true; break; }
10189
+ if (await checkOpencodeHealth({ signal: exitAbort.signal })) {
10190
+ if (isGone()) { exitedEarly = true; break; }
10146
10191
  // Only SynaBun's own process counts (the spawned one, or one it started): another server that took the
10147
10192
  // port meanwhile answers for itself.
10148
10193
  if (await tracked.answering({ password: _ocpPassword }) !== 'foreign') return 'ready';
@@ -10151,9 +10196,17 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10151
10196
  await endOpencodeChild(proc);
10152
10197
  return 'collision';
10153
10198
  }
10199
+ if (isGone()) { exitedEarly = true; break; }
10154
10200
  // Something answers, but not as SynaBun expects (a version it does not drive, a web page): no use waiting.
10155
10201
  if (_ocpLastCheck && ['unsupported', 'html', 'locked'].includes(_ocpLastCheck.state) && i >= 3) break;
10156
10202
  }
10203
+ if (exitedEarly) {
10204
+ if (_ocpProc === proc) _ocpProc = null;
10205
+ const detail = procError
10206
+ ? (procError.code || procError.message || 'spawn error')
10207
+ : (procExitCode != null ? `code ${procExitCode}` : (procExitSignal || 'exited'));
10208
+ return `exited:${detail}`;
10209
+ }
10157
10210
  stopOpencodeServer();
10158
10211
  await endOpencodeChild(proc);
10159
10212
  return 'unhealthy';
@@ -10178,11 +10231,14 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
10178
10231
  return true;
10179
10232
  }
10180
10233
 
10234
+ const exitedDetail = typeof outcome === 'string' && outcome.startsWith('exited:') ? outcome.slice('exited:'.length) : null;
10181
10235
  const why = outcome === 'collision'
10182
10236
  ? `Another server took port ${_ocpPort} while SynaBun's OpenCode serve was starting, on every port it tried; it is left running.`
10183
- : _ocpLastCheck && _ocpLastCheck.state !== 'down'
10184
- ? opencodeProblemText({ check: _ocpLastCheck, port: _ocpPort })
10185
- : 'OpenCode did not start within 15 seconds.';
10237
+ : exitedDetail != null
10238
+ ? `OpenCode exited before becoming healthy (${exitedDetail}).`
10239
+ : _ocpLastCheck && _ocpLastCheck.state !== 'down'
10240
+ ? opencodeProblemText({ check: _ocpLastCheck, port: _ocpPort })
10241
+ : 'OpenCode did not start within 15 seconds.';
10186
10242
  console.error(`[opencode] Server did not become healthy: ${why}`);
10187
10243
  _ocpStarting = false;
10188
10244
  reportOpencodeProblem(why);
@@ -12338,7 +12394,7 @@ const editorOwnerGuard = ownerRouteGuard({ isGuestRequest, port: PORT, allowedOr
12338
12394
  // whatever order they arrive; the editor's namespace asks the owner's guard on every route.
12339
12395
  app.use(createUiBlobRouter({
12340
12396
  namespaces: BLOB_NS_ALLOWLIST,
12341
- store: { getNamespace: blobGetNamespace, get: blobGet, put: blobPut, delete: blobDelete, prune: blobPrune },
12397
+ store: { getNamespace: blobGetNamespace, getNamespaceJsonAsync: blobGetNamespaceJsonAsync, get: blobGet, put: blobPut, delete: blobDelete, prune: blobPrune },
12342
12398
  ownerNamespace: EDITOR_BACKUP_NAMESPACE,
12343
12399
  ownerGuard: editorOwnerGuard,
12344
12400
  }));
@@ -14869,60 +14925,10 @@ app.get('/api/loop/active', (req, res) => {
14869
14925
  // Unlike /api/loop/active, this returns ALL loop files (active + inactive)
14870
14926
  // classified by state so the UI can show stale/finished/orphaned entries
14871
14927
  // alongside running ones. Does NOT delete anything (read-only).
14872
- app.get('/api/loop/list', (_req, res) => {
14928
+ app.get('/api/loop/list', async (_req, res) => {
14873
14929
  try {
14874
- if (!existsSync(LOOP_DIR)) return res.json({ loops: [], staleCount: 0 });
14875
- const files = readdirSync(LOOP_DIR).filter(f => f.endsWith('.json') && f !== '.gitkeep' && !f.startsWith('pending-') && f !== 'active-pointer.json');
14876
- const now = Date.now();
14877
- const loops = [];
14878
- let staleCount = 0;
14879
- for (const f of files) {
14880
- try {
14881
- const filePath = resolve(LOOP_DIR, f);
14882
- const data = JSON.parse(readFileSync(filePath, 'utf-8'));
14883
- const startedAtMs = data.startedAt ? new Date(data.startedAt).getTime() : 0;
14884
- const lastIterAtMs = data.lastIterationAt ? new Date(data.lastIterationAt).getTime() : startedAtMs;
14885
- const elapsedMs = startedAtMs ? now - startedAtMs : 0;
14886
- const stalledMs = lastIterAtMs ? now - lastIterAtMs : 0;
14887
- const terminalAlive = isLoopRuntimeAlive(data);
14888
- const iterDone = (data.currentIteration || 0) >= (data.totalIterations || 0) && (data.totalIterations || 0) > 0;
14889
- let state;
14890
- if (data.active === false) {
14891
- state = 'stale-inactive';
14892
- staleCount++;
14893
- } else if (data.terminalSessionId && !terminalAlive) {
14894
- state = data.runtimeType === 'native' ? 'orphaned-native' : 'orphaned-pty';
14895
- } else if (iterDone) {
14896
- state = 'finished';
14897
- } else {
14898
- state = 'active';
14899
- }
14900
- loops.push({
14901
- sessionId: f.replace('.json', ''),
14902
- terminalSessionId: data.terminalSessionId || null,
14903
- terminalAlive,
14904
- runId: data.runId || null,
14905
- profile: data.profile || null,
14906
- runtimeType: data.runtimeType || 'pty',
14907
- surface: data.surface || 'terminal',
14908
- task: typeof data.task === 'string' ? data.task.slice(0, 200) : '',
14909
- currentIteration: data.currentIteration || 0,
14910
- totalIterations: data.totalIterations || 0,
14911
- startedAt: data.startedAt || null,
14912
- lastIterationAt: data.lastIterationAt || null,
14913
- elapsedMinutes: Math.round(elapsedMs / 60000),
14914
- stalledMinutes: Math.round(stalledMs / 60000),
14915
- stalledMs,
14916
- state,
14917
- browserSessionId: data.browserSessionId || null,
14918
- browserTabId: data.browserTabId || null,
14919
- usesBrowser: !!data.usesBrowser,
14920
- });
14921
- } catch { /* skip corrupt */ }
14922
- }
14923
- // Newest first
14924
- loops.sort((a, b) => (b.startedAt || '').localeCompare(a.startedAt || ''));
14925
- res.json({ loops, staleCount });
14930
+ const inventory = await scanLoopInventory({ includeExtraFields: true });
14931
+ res.json(inventory);
14926
14932
  } catch (err) {
14927
14933
  res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
14928
14934
  }
@@ -15596,7 +15602,19 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15596
15602
  const fresh = req.body?.reason === 'create';
15597
15603
  // A create that takes over one of the owner's tabs in the everyday browser (extension mode only).
15598
15604
  const takeOverTab = fresh && typeof req.body?.takeOverTab === 'string' && loadBrowserConfig().connectMode === 'extension' ? req.body.takeOverTab : null;
15599
- if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(who.id) && !fresh) {
15605
+ let requestedBrowserSessionId = null;
15606
+ const initial = req.body?.reason === 'initial';
15607
+ if (initial) {
15608
+ const worker = who.status === 'verified' && named && _assistantDispatcher?.optionalBrowserRoute?.(named);
15609
+ if (!worker) return res.status(403).json({ code: 'NOT_OWNED', error: 'Only the active worker can open its first browser tab.' });
15610
+ requestedBrowserSessionId = worker.requestedBrowserSessionId || null;
15611
+ if (worker.sessionId) {
15612
+ const current = liveAutomationRoute(named);
15613
+ if (!current) return res.status(410).json(extensionSafeError({ code: 'TAB_CLOSED' }));
15614
+ return res.json({ ok: true, sessionId: current.browserSessionId, tabId: current.browserTabId, current: true });
15615
+ }
15616
+ }
15617
+ if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(who.id) && !fresh && !initial) {
15600
15618
  return res.status(410).json(extensionSafeError({ code: 'TAB_CLOSED' }));
15601
15619
  }
15602
15620
  const lost = req.body?.lost && typeof req.body.lost === 'object' ? req.body.lost : null;
@@ -15607,7 +15625,7 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15607
15625
  }
15608
15626
  }
15609
15627
  const start = async () => {
15610
- const acq = await acquireLoopBrowserAndTab({ terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser', takeOverTab });
15628
+ const acq = await acquireLoopBrowserAndTab({ requestedBrowserSessionId, terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser', takeOverTab });
15611
15629
  // Its profile was closed outside SynaBun under it and is not started again for it: the loop ends when its turn
15612
15630
  // ends, never asking again iteration after iteration.
15613
15631
  if (acq.code === 'MORELOGIN_CLOSED_OUTSIDE') finishBlockedLoop(owner, acq);
@@ -23899,6 +23917,86 @@ app.get('/api/claude-code/sessions/:sessionId/messages', async (req, res) => {
23899
23917
  }
23900
23918
  });
23901
23919
 
23920
+ // --- Background tasks of a session (the panels' Background tasks view, lib/claude-bg-tasks.js) ---
23921
+ // The session's background shells and watches, rebuilt from its own transcript, and a page of what one printed.
23922
+ // The owner's page alone reads them (this boot's page secret, no agent header, no guest, one of this server's
23923
+ // Hosts): what a command printed is display data, never a model's. A task's output is read only from the file the
23924
+ // session reported for it, inside Claude Code's own task folders of that session.
23925
+ const claudeBgTasks = createClaudeBgTasks({ roots: (found) => claudeOutputRoots({ configDirs: [found.configDir] }) });
23926
+ function bgTasksOwnerPage(req, res, next) {
23927
+ if (AGENT_HEADERS.some((name) => req.headers[name] !== undefined) || req.headers['x-synabun-brain-token'] !== undefined) {
23928
+ return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'A background task\'s output is shown in the owner\'s own panel only.' });
23929
+ }
23930
+ let owner = false;
23931
+ try { owner = _pageSession.verify(req) === true; } catch { owner = false; }
23932
+ if (!owner) return res.status(403).json({ ok: false, code: 'PAGE_SECRET_REQUIRED', error: 'A background task\'s output is shown in SynaBun\'s own page only. Reload the page and try again.' });
23933
+ next();
23934
+ }
23935
+ // The transcript a Claude panel tab names (its project and account), found as GET …/messages finds it.
23936
+ function claudeBgTranscript(req, res) {
23937
+ const homeDir = process.env.USERPROFILE || process.env.HOME;
23938
+ let accountHome = null;
23939
+ const wantedAccount = typeof req.query.account === 'string' ? req.query.account : '';
23940
+ if (wantedAccount && wantedAccount !== 'default') {
23941
+ try { accountHome = _panelClaudeAccounts().homeFor(wantedAccount); } catch { accountHome = null; }
23942
+ if (!accountHome) { res.status(404).json({ ok: false, code: 'account_unavailable', error: 'That Claude account is no longer set up in SynaBun.' }); return null; }
23943
+ }
23944
+ const configDir = accountHome || join(homeDir, '.claude');
23945
+ const project = typeof req.query.project === 'string' ? req.query.project : '';
23946
+ const found = findSessionTranscript({ sessionId: req.params.sessionId, project, projects: loadHookProjects(), projectsDir: join(configDir, 'projects'), pathToKey: pathToClaudeKey });
23947
+ if (!found) { res.status(404).json({ ok: false, code: 'TRANSCRIPT_NOT_FOUND', error: 'No transcript of that session was found.', tasks: [] }); return null; }
23948
+ return { ...found, configDir };
23949
+ }
23950
+ const bgNumber = (value) => (typeof value === 'string' && /^\d{1,15}$/.test(value) ? Number(value) : undefined);
23951
+ // An Assistant Claude brain's transcript: its conversation id under its account, in the folder it runs in
23952
+ // (runtime.backgroundTaskSource). Nothing a request says is a path here.
23953
+ function assistantBgTranscript(source) {
23954
+ if (!source?.providerSessionId) return null;
23955
+ const homeDir = process.env.USERPROFILE || process.env.HOME;
23956
+ let configDir = join(homeDir, '.claude');
23957
+ if (source.accountId && source.accountId !== 'default') {
23958
+ let home = null;
23959
+ try { home = _panelClaudeAccounts().homeFor(source.accountId); } catch { home = null; }
23960
+ if (!home) return null;
23961
+ configDir = home;
23962
+ }
23963
+ const cwd = source.cwd || PACKAGE_ROOT;
23964
+ let found = null;
23965
+ try { found = findSessionTranscript({ sessionId: source.providerSessionId, project: cwd, projects: [{ path: cwd }], projectsDir: join(configDir, 'projects'), pathToKey: pathToClaudeKey }); } catch { found = null; }
23966
+ return found ? { ...found, configDir } : null;
23967
+ }
23968
+ const assistantBackgroundTasks = {
23969
+ list: (source) => { const found = assistantBgTranscript(source); return found ? claudeBgTasks.list(found) : { tasks: [] }; },
23970
+ output: async (source, q) => {
23971
+ const found = assistantBgTranscript(source);
23972
+ if (!found) return { ok: false, status: 404, code: 'TRANSCRIPT_NOT_FOUND', error: 'No transcript of this conversation was found.' };
23973
+ return claudeBgTasks.output(found, { ...q, sessionId: source.providerSessionId });
23974
+ },
23975
+ };
23976
+ app.get('/api/claude-code/sessions/:sessionId/background-tasks', editorOwnerGuard, bgTasksOwnerPage, (req, res) => {
23977
+ try {
23978
+ res.set('Cache-Control', 'no-store');
23979
+ const found = claudeBgTranscript(req, res);
23980
+ if (!found) return;
23981
+ res.json({ ok: true, ...claudeBgTasks.list(found) });
23982
+ } catch (err) {
23983
+ res.status(err instanceof PathConfineError ? err.status : 500).json({ ok: false, error: err.message, tasks: [] });
23984
+ }
23985
+ });
23986
+ app.get('/api/claude-code/sessions/:sessionId/background-tasks/:taskId/output', editorOwnerGuard, bgTasksOwnerPage, async (req, res) => {
23987
+ try {
23988
+ res.set('Cache-Control', 'no-store');
23989
+ const found = claudeBgTranscript(req, res);
23990
+ if (!found) return;
23991
+ const running = req.query.running === '1' ? true : (req.query.running === '0' ? false : null);
23992
+ const page = await claudeBgTasks.output(found, { sessionId: req.params.sessionId, taskId: String(req.params.taskId || ''), cursor: bgNumber(req.query.cursor), tail: bgNumber(req.query.tail), limit: bgNumber(req.query.limit), running });
23993
+ if (!page || page.ok === false) return res.status(Number(page?.status) >= 400 ? Number(page.status) : 502).json({ ok: false, code: page?.code || 'OUTPUT_FAILED', error: page?.error || 'The output could not be read.' });
23994
+ res.json({ ok: true, ...page.data });
23995
+ } catch (err) {
23996
+ res.status(err instanceof PathConfineError ? err.status : 500).json({ ok: false, error: err.message });
23997
+ }
23998
+ });
23999
+
23902
24000
  // --- Session Indexing ---
23903
24001
 
23904
24002
  let _indexingJob = null; // { jobId, cancelled, promise }
@@ -30622,6 +30720,8 @@ function noteMoreLoginContextClose(session, sessionId, context = session?.contex
30622
30720
  automationBrowserOwnerAccess: _automationBrowserOwnerAccess,
30623
30721
  // A request without an agent pin is the owner's page only with this boot's page secret (lib/page-session.js).
30624
30722
  pageSession: _pageSession,
30723
+ // The Background tasks view of a Claude brain: its own transcript (lib/claude-bg-tasks.js).
30724
+ backgroundTasks: assistantBackgroundTasks,
30625
30725
  // A pin counts only with its proof (lib/terminal-tokens.js): a worker's run id, a brain's id.
30626
30726
  terminalVerdict: (pin, req) => _terminalTokens.verdict(pin, presentedTerminalProof(req)),
30627
30727
  }));
@@ -31308,7 +31408,7 @@ function syncRegistryFromTerminals() {
31308
31408
 
31309
31409
  // ── Leak Detection ──
31310
31410
 
31311
- function scanForLeaks() {
31411
+ async function scanForLeaks({ loopInventory = null, cleanupSnapshots = null } = {}) {
31312
31412
  const leaks = [];
31313
31413
  const now = Date.now();
31314
31414
  const activeSessionIds = new Set(sessionRegistry.keys());
@@ -31316,42 +31416,37 @@ function scanForLeaks() {
31316
31416
  if (s.claudeSessionId) activeSessionIds.add(s.claudeSessionId);
31317
31417
  }
31318
31418
 
31319
- // 1. Orphaned pending-remember files
31419
+ // 1. Orphaned pending-remember files (async off-main-thread FS I/O)
31320
31420
  try {
31321
- if (existsSync(PENDING_REMEMBER_DIR)) {
31322
- const files = readdirSync(PENDING_REMEMBER_DIR).filter(f => f.endsWith('.json') && !f.startsWith('test-'));
31323
- for (const f of files) {
31324
- const filePath = join(PENDING_REMEMBER_DIR, f);
31325
- try {
31326
- const fstat = statSync(filePath);
31327
- const ageMs = now - fstat.mtimeMs;
31328
- if (ageMs < 5 * 60 * 1000) continue;
31329
- const sid = f.replace('.json', '');
31330
- if (!activeSessionIds.has(sid)) {
31331
- leaks.push({ type: 'orphaned-state', severity: ageMs > 30 * 60 * 1000 ? 'warning' : 'info', description: `Orphaned pending-remember flag (${Math.round(ageMs / 60000)}m old)`, file: filePath, sessionId: sid, ageMs });
31332
- }
31333
- } catch { /* skip */ }
31334
- }
31421
+ const files = (await fsp.readdir(PENDING_REMEMBER_DIR)).filter(f => f.endsWith('.json') && !f.startsWith('test-'));
31422
+ for (const f of files) {
31423
+ const filePath = join(PENDING_REMEMBER_DIR, f);
31424
+ try {
31425
+ const fstat = await fsp.stat(filePath);
31426
+ const ageMs = now - fstat.mtimeMs;
31427
+ if (ageMs < 5 * 60 * 1000) continue;
31428
+ const sid = f.replace('.json', '');
31429
+ if (!activeSessionIds.has(sid)) {
31430
+ cleanupSnapshots?.set(filePath, fstat);
31431
+ leaks.push({ type: 'orphaned-state', severity: ageMs > 30 * 60 * 1000 ? 'warning' : 'info', description: `Orphaned pending-remember flag (${Math.round(ageMs / 60000)}m old)`, file: filePath, sessionId: sid, ageMs });
31432
+ }
31433
+ } catch { /* skip */ }
31335
31434
  }
31336
- } catch { /* ok */ }
31435
+ } catch { /* missing or unreadable directory */ }
31337
31436
 
31338
- // 2. Orphaned loop files
31437
+ // 2. Orphaned loop files — share the async stat-cached loop inventory instead of re-reading loop files
31339
31438
  try {
31340
- if (existsSync(LOOP_DIR_MONITOR)) {
31341
- const files = readdirSync(LOOP_DIR_MONITOR).filter(f => f.endsWith('.json') && !f.startsWith('pending-'));
31342
- for (const f of files) {
31343
- const filePath = join(LOOP_DIR_MONITOR, f);
31344
- try {
31345
- const data = JSON.parse(readFileSync(filePath, 'utf-8'));
31346
- if (data.stopped || data.finishedAt) continue;
31347
- const fstat = statSync(filePath);
31348
- const ageMs = now - fstat.mtimeMs;
31349
- if (ageMs < 2 * 60 * 1000) continue;
31350
- const sid = f.replace('.json', '');
31351
- if (!activeSessionIds.has(sid) && data.active) {
31352
- leaks.push({ type: 'orphaned-loop', severity: 'warning', description: `Active loop with no session (${data.template || 'custom'}, ${Math.round(ageMs / 60000)}m stale)`, file: filePath, sessionId: sid, ageMs, loopData: { template: data.template, currentIteration: data.currentIteration, maxIterations: data.maxIterations } });
31353
- }
31354
- } catch { /* skip */ }
31439
+ const inv = loopInventory?.rawEntries
31440
+ ? loopInventory
31441
+ : await scanLoopInventory({ includeRaw: true }).catch(() => ({ rawEntries: [] }));
31442
+ for (const entry of inv.rawEntries || []) {
31443
+ const { data, filePath, sessionId: sid, mtimeMs } = entry;
31444
+ if (!data || data.stopped || data.finishedAt) continue;
31445
+ const ageMs = now - mtimeMs;
31446
+ if (ageMs < 2 * 60 * 1000) continue;
31447
+ if (!activeSessionIds.has(sid) && data.active) {
31448
+ cleanupSnapshots?.set(filePath, entry.stat);
31449
+ leaks.push({ type: 'orphaned-loop', severity: 'warning', description: `Active loop with no session (${data.template || 'custom'}, ${Math.round(ageMs / 60000)}m stale)`, file: filePath, sessionId: sid, ageMs, loopData: { template: data.template, currentIteration: data.currentIteration, maxIterations: data.maxIterations } });
31355
31450
  }
31356
31451
  }
31357
31452
  } catch { /* ok */ }
@@ -31374,105 +31469,73 @@ function scanForLeaks() {
31374
31469
  }
31375
31470
  }
31376
31471
 
31377
- // 4. Stale precompact flags
31472
+ // 4. Stale precompact flags (async off-main-thread FS I/O)
31378
31473
  const precompactDir = resolve(DATA_HOME, 'data', 'precompact');
31379
31474
  try {
31380
- if (existsSync(precompactDir)) {
31381
- const files = readdirSync(precompactDir).filter(f => f.endsWith('.json'));
31382
- for (const f of files) {
31383
- const filePath = join(precompactDir, f);
31384
- try {
31385
- const fstat = statSync(filePath);
31386
- const ageMs = now - fstat.mtimeMs;
31387
- if (ageMs > 10 * 60 * 1000) {
31388
- leaks.push({ type: 'stale-precompact', severity: 'info', description: `Stale precompact cache (${Math.round(ageMs / 60000)}m old)`, file: filePath, sessionId: f.replace('.json', ''), ageMs });
31389
- }
31390
- } catch { /* skip */ }
31391
- }
31475
+ const files = (await fsp.readdir(precompactDir)).filter(f => f.endsWith('.json'));
31476
+ for (const f of files) {
31477
+ const filePath = join(precompactDir, f);
31478
+ try {
31479
+ const fstat = await fsp.stat(filePath);
31480
+ const ageMs = now - fstat.mtimeMs;
31481
+ if (ageMs > 10 * 60 * 1000) {
31482
+ cleanupSnapshots?.set(filePath, fstat);
31483
+ leaks.push({ type: 'stale-precompact', severity: 'info', description: `Stale precompact cache (${Math.round(ageMs / 60000)}m old)`, file: filePath, sessionId: f.replace('.json', ''), ageMs });
31484
+ }
31485
+ } catch { /* skip */ }
31392
31486
  }
31393
- } catch { /* ok */ }
31487
+ } catch { /* missing or unreadable directory */ }
31394
31488
 
31395
31489
  return leaks;
31396
31490
  }
31397
31491
 
31398
- let _lastLeakHash = '';
31399
- setInterval(() => {
31400
- markActivity('timer:session-leaks');
31401
- syncRegistryFromTerminals();
31402
- const leaks = scanForLeaks();
31403
- // Strip ageMs AND description (which embeds age as "Xm old") to prevent
31404
- // broadcasts every ~60s when the minute counter ticks in descriptions
31405
- const hash = JSON.stringify(leaks.map(l => { const { ageMs, description, ...stable } = l; return stable; }));
31406
- if (hash !== _lastLeakHash) {
31407
- _lastLeakHash = hash;
31408
- if (leaks.length > 0) broadcastSessionEvent({ type: 'session:leaks', leaks });
31409
- }
31410
- }, LEAK_SCAN_INTERVAL_MS);
31411
-
31412
- // Inline scan of LOOP_DIR matching the GET /api/loop/list shape. Used by both
31413
- // the WS init payload and the periodic broadcast so the Session Monitor stays
31414
- // in sync with the Loops tab without a separate fetch.
31415
- function scanLoopInventory() {
31416
- const result = { loops: [], staleCount: 0 };
31417
- try {
31418
- if (!existsSync(LOOP_DIR)) return result;
31419
- const files = readdirSync(LOOP_DIR).filter(f => f.endsWith('.json') && f !== '.gitkeep' && !f.startsWith('pending-') && f !== 'active-pointer.json');
31420
- const now = Date.now();
31421
- for (const f of files) {
31422
- try {
31423
- const filePath = resolve(LOOP_DIR, f);
31424
- const data = JSON.parse(readFileSync(filePath, 'utf-8'));
31425
- const startedAtMs = data.startedAt ? new Date(data.startedAt).getTime() : 0;
31426
- const lastIterAtMs = data.lastIterationAt ? new Date(data.lastIterationAt).getTime() : startedAtMs;
31427
- const elapsedMs = startedAtMs ? now - startedAtMs : 0;
31428
- const stalledMs = lastIterAtMs ? now - lastIterAtMs : 0;
31429
- const terminalAlive = isLoopRuntimeAlive(data);
31430
- const iterDone = (data.currentIteration || 0) >= (data.totalIterations || 0) && (data.totalIterations || 0) > 0;
31431
- let state;
31432
- if (data.active === false) { state = 'stale-inactive'; result.staleCount++; }
31433
- else if (data.terminalSessionId && !terminalAlive) state = data.runtimeType === 'native' ? 'orphaned-native' : 'orphaned-pty';
31434
- else if (iterDone) state = 'finished';
31435
- else state = 'active';
31436
- result.loops.push({
31437
- sessionId: f.replace('.json', ''),
31438
- terminalSessionId: data.terminalSessionId || null,
31439
- terminalAlive,
31440
- task: typeof data.task === 'string' ? data.task.slice(0, 200) : '',
31441
- currentIteration: data.currentIteration || 0,
31442
- totalIterations: data.totalIterations || 0,
31443
- startedAt: data.startedAt || null,
31444
- lastIterationAt: data.lastIterationAt || null,
31445
- elapsedMinutes: Math.round(elapsedMs / 60000),
31446
- stalledMinutes: Math.round(stalledMs / 60000),
31447
- stalledMs,
31448
- state,
31449
- browserSessionId: data.browserSessionId || null,
31450
- browserTabId: data.browserTabId || null,
31451
- usesBrowser: !!data.usesBrowser,
31452
- });
31453
- } catch { /* skip corrupt */ }
31454
- }
31455
- result.loops.sort((a, b) => (b.startedAt || '').localeCompare(a.startedAt || ''));
31456
- } catch { /* ok */ }
31457
- return result;
31492
+ // Async, stat-identity-cached scan of LOOP_DIR matching the GET /api/loop/list shape.
31493
+ // Used by the route, leak detection, WS init payload and periodic broadcast so the
31494
+ // Session Monitor stays in sync with the Loops tab without blocking the event loop.
31495
+ const _loopInventoryScanner = createLoopInventoryScanner({
31496
+ loopDir: () => LOOP_DIR,
31497
+ isLoopRuntimeAlive,
31498
+ });
31499
+ function scanLoopInventory(options) {
31500
+ return _loopInventoryScanner.scan(options);
31458
31501
  }
31459
31502
 
31503
+ let _lastLeakHash = '';
31460
31504
  let _lastLoopHash = '';
31505
+ let _loopInventoryInFlight = false;
31461
31506
  setInterval(() => {
31462
- markActivity('timer:loop-inventory');
31463
- const inventory = scanLoopInventory();
31464
- // Hash on stable fields only (drop minute counters that tick every poll)
31465
- const hash = JSON.stringify({
31466
- staleCount: inventory.staleCount,
31467
- loops: inventory.loops.map(l => ({
31468
- sessionId: l.sessionId, state: l.state, terminalAlive: l.terminalAlive,
31469
- currentIteration: l.currentIteration, totalIterations: l.totalIterations,
31470
- })),
31507
+ if (_loopInventoryInFlight) return;
31508
+ _loopInventoryInFlight = true;
31509
+ const endActivity = beginActivity('timer:loop-inventory');
31510
+ syncRegistryFromTerminals();
31511
+ (async () => {
31512
+ const inventory = await scanLoopInventory({ includeRaw: true }).catch(() => null);
31513
+ if (inventory) {
31514
+ // Hash on stable fields only (drop minute counters that tick every poll)
31515
+ const loopHash = JSON.stringify({
31516
+ staleCount: inventory.staleCount,
31517
+ loops: inventory.loops.map(l => ({
31518
+ sessionId: l.sessionId, state: l.state, terminalAlive: l.terminalAlive,
31519
+ currentIteration: l.currentIteration, totalIterations: l.totalIterations,
31520
+ })),
31521
+ });
31522
+ if (loopHash !== _lastLoopHash) {
31523
+ _lastLoopHash = loopHash;
31524
+ broadcastSessionEvent({ type: 'session:loops', loops: inventory.loops, staleCount: inventory.staleCount });
31525
+ }
31526
+ }
31527
+ const leaks = await scanForLeaks({ loopInventory: inventory });
31528
+ // Strip ageMs AND description (which embeds age as "Xm old") to prevent
31529
+ // broadcasts every ~60s when the minute counter ticks in descriptions
31530
+ const leakHash = JSON.stringify(leaks.map(l => { const { ageMs, description, ...stable } = l; return stable; }));
31531
+ if (leakHash !== _lastLeakHash) {
31532
+ _lastLeakHash = leakHash;
31533
+ if (leaks.length > 0) broadcastSessionEvent({ type: 'session:leaks', leaks });
31534
+ }
31535
+ })().catch(() => {}).finally(() => {
31536
+ _loopInventoryInFlight = false;
31537
+ endActivity();
31471
31538
  });
31472
- if (hash !== _lastLoopHash) {
31473
- _lastLoopHash = hash;
31474
- broadcastSessionEvent({ type: 'session:loops', loops: inventory.loops, staleCount: inventory.staleCount });
31475
- }
31476
31539
  }, LEAK_SCAN_INTERVAL_MS);
31477
31540
 
31478
31541
  // ── Session Monitor API ──
@@ -31534,19 +31597,33 @@ app.get('/api/sessions/:id/state', (req, res) => {
31534
31597
  res.json({ session: entry, ownedFiles });
31535
31598
  });
31536
31599
 
31537
- app.get('/api/sessions/leaks', (req, res) => {
31600
+ app.get('/api/sessions/leaks', async (req, res) => {
31538
31601
  syncRegistryFromTerminals();
31539
- res.json({ leaks: scanForLeaks(), scannedAt: Date.now() });
31602
+ res.json({ leaks: await scanForLeaks(), scannedAt: Date.now() });
31540
31603
  });
31541
31604
 
31542
- app.post('/api/sessions/cleanup', express.json(), (req, res) => {
31605
+ async function cleanInactiveFlag(leak, snapshot) {
31606
+ if (!snapshot) return false;
31607
+ const current = await fsp.stat(leak.file);
31608
+ if (current.dev !== snapshot.dev || current.ino !== snapshot.ino || current.size !== snapshot.size
31609
+ || current.mtimeMs !== snapshot.mtimeMs || current.ctimeMs !== snapshot.ctimeMs) return false;
31610
+ if (sessionRegistry.has(leak.sessionId)) return false;
31611
+ for (const session of terminalSessions.values()) {
31612
+ if (session.claudeSessionId === leak.sessionId) return false;
31613
+ }
31614
+ await fsp.unlink(leak.file);
31615
+ return true;
31616
+ }
31617
+
31618
+ app.post('/api/sessions/cleanup', express.json(), async (req, res) => {
31543
31619
  const { types } = req.body || {};
31544
31620
  const allowedTypes = new Set(types || ['orphaned-state', 'stale-precompact']);
31545
- const leaks = scanForLeaks();
31621
+ const snapshots = new Map();
31622
+ const leaks = await scanForLeaks({ cleanupSnapshots: snapshots });
31546
31623
  let cleaned = 0;
31547
31624
  for (const leak of leaks) {
31548
31625
  if (!allowedTypes.has(leak.type) || !leak.file) continue;
31549
- try { unlinkSync(leak.file); cleaned++; } catch { /* skip */ }
31626
+ try { if (await cleanInactiveFlag(leak, snapshots.get(leak.file))) cleaned++; } catch { /* skip */ }
31550
31627
  }
31551
31628
  res.json({ ok: true, cleaned, total: leaks.length });
31552
31629
  });
@@ -31554,9 +31631,9 @@ app.post('/api/sessions/cleanup', express.json(), (req, res) => {
31554
31631
  // GET /api/sessions/pending-remember-prompt — build the prompt that processes
31555
31632
  // orphaned pending-remember flags. The client routes this prompt to the
31556
31633
  // chosen provider sidepanel (Claude Code / Codex / OpenCode) — no agent spawn.
31557
- app.get('/api/sessions/pending-remember-prompt', (req, res) => {
31634
+ app.get('/api/sessions/pending-remember-prompt', async (req, res) => {
31558
31635
  try {
31559
- const leaks = scanForLeaks().filter(l =>
31636
+ const leaks = (await scanForLeaks()).filter(l =>
31560
31637
  l.type === 'orphaned-state' && l.file && l.file.includes('pending-remember') && l.sessionId
31561
31638
  );
31562
31639
  if (leaks.length === 0) return res.json({ ok: true, count: 0, prompt: '', message: 'No pending-remember flags to process.' });
@@ -31608,16 +31685,35 @@ app.get('/api/sessions/pending-remember-prompt', (req, res) => {
31608
31685
  // ── Session Monitor WebSocket ──
31609
31686
 
31610
31687
  function handleSessionMonitorWebSocket(ws) {
31611
- sessionMonitorClients.add(ws);
31612
- syncRegistryFromTerminals();
31613
- const sessions = [...sessionRegistry.values()].map(s => ({
31614
- ...s,
31615
- isAlive: s.terminalSessionId ? terminalSessions.has(s.terminalSessionId) : (Date.now() - s.lastActivity < 5 * 60 * 1000),
31616
- }));
31617
- const loopInv = scanLoopInventory();
31618
- ws.send(JSON.stringify({ type: 'session:init', sessions, leaks: scanForLeaks(), loops: loopInv.loops, staleCount: loopInv.staleCount }));
31619
- ws.on('close', () => sessionMonitorClients.delete(ws));
31620
- ws.on('error', () => sessionMonitorClients.delete(ws));
31688
+ let closed = false;
31689
+ const cleanup = () => {
31690
+ closed = true;
31691
+ sessionMonitorClients.delete(ws);
31692
+ };
31693
+ ws.on('close', cleanup);
31694
+ ws.on('error', cleanup);
31695
+ (async () => {
31696
+ syncRegistryFromTerminals();
31697
+ const loopInv = await scanLoopInventory({ includeRaw: true }).catch(() => ({ loops: [], staleCount: 0, rawEntries: [] }));
31698
+ const leaks = await scanForLeaks({ loopInventory: loopInv }).catch(() => []);
31699
+ if (closed || ws.readyState !== 1) return;
31700
+ // Snapshot active sessions AFTER awaiting the async scans and subscribe in the same
31701
+ // synchronous turn so session:init is always delivered first and never overwrites
31702
+ // sessions registered while the inventory was being scanned.
31703
+ syncRegistryFromTerminals();
31704
+ const sessions = [...sessionRegistry.values()].map(s => ({
31705
+ ...s,
31706
+ isAlive: s.terminalSessionId ? terminalSessions.has(s.terminalSessionId) : (Date.now() - s.lastActivity < 5 * 60 * 1000),
31707
+ }));
31708
+ ws.send(JSON.stringify({
31709
+ type: 'session:init',
31710
+ sessions,
31711
+ leaks,
31712
+ loops: loopInv.loops,
31713
+ staleCount: loopInv.staleCount,
31714
+ }));
31715
+ sessionMonitorClients.add(ws);
31716
+ })().catch(() => {});
31621
31717
  }
31622
31718
 
31623
31719
  const providerPanelTerminalAuth = createProviderPanelTerminalAuth({
@@ -31785,13 +31881,21 @@ let _gitExePath = null; // Cached absolute path — preferring .exe on Windows
31785
31881
  let _gitResolved = false;
31786
31882
  let _gitResolving = null; // the lookup resolveGitPathInBackground() runs, while it runs
31787
31883
 
31788
- // Resolve git's absolute path at first use. On Windows, `where git` lists all matches;
31789
- // prefer .exe so spawnSync works without cmd.exe quoting issues. On Unix, use `command -v`.
31790
- // A Windows PC without git: the git.exe of SynaBun's copy of Git for Windows (lib/git-bash/), asked each time,
31791
- // since a copy that is still being fetched at the first call arrives later.
31884
+ // Resolve git's absolute path for server Git operations in one unified order:
31885
+ // bundled → managed (downloaded) → system (PATH, then standard Windows install roots).
31886
+ // Never dumps raw OEM codepage stderr on Windows.
31792
31887
  function resolveGitPath() {
31793
- if (_gitResolved) return _gitExePath || gitBash.gitExecutable();
31888
+ const managed = gitBash.managedGitExecutable?.() || null;
31889
+ if (managed) {
31890
+ if (!_gitResolved) {
31891
+ _gitResolved = true;
31892
+ console.log(`[git] resolved: ${managed}`);
31893
+ }
31894
+ return managed;
31895
+ }
31896
+ if (_gitResolved) return _gitExePath || gitBash.gitExecutable({ includeSystem: true });
31794
31897
  _gitResolved = true;
31898
+ let resolveErr = null;
31795
31899
  try {
31796
31900
  const cmd = IS_WINDOWS ? 'where git' : 'command -v git';
31797
31901
  const out = execSync(cmd, { encoding: 'utf8', timeout: 3000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
@@ -31801,13 +31905,29 @@ function resolveGitPath() {
31801
31905
  } else {
31802
31906
  _gitExePath = lines[0] || null;
31803
31907
  }
31804
- if (_gitExePath) console.log(`[git] resolved: ${_gitExePath}`);
31805
- else console.warn('[git] resolver returned no paths');
31806
31908
  } catch (err) {
31807
- console.warn('[git] resolution failed:', err?.message || String(err));
31909
+ resolveErr = err;
31808
31910
  _gitExePath = null;
31809
31911
  }
31810
- return _gitExePath || gitBash.gitExecutable();
31912
+ if (_gitExePath) {
31913
+ console.log(`[git] resolved: ${_gitExePath}`);
31914
+ } else {
31915
+ const fallback = gitBash.gitExecutable() || gitBash.gitExecutable({ includeSystem: true });
31916
+ if (fallback) {
31917
+ _gitExePath = fallback;
31918
+ console.log(`[git] resolved: ${fallback}`);
31919
+ } else {
31920
+ const detail = resolveErr?.killed
31921
+ ? 'timed out'
31922
+ : typeof resolveErr?.code === 'string'
31923
+ ? resolveErr.code
31924
+ : typeof resolveErr?.code === 'number' || typeof resolveErr?.status === 'number'
31925
+ ? `not found on PATH (exit ${resolveErr.code ?? resolveErr.status})`
31926
+ : 'resolver returned no paths';
31927
+ console.warn(`[git] resolution failed: ${detail}`);
31928
+ }
31929
+ }
31930
+ return _gitExePath || gitBash.gitExecutable({ includeSystem: true });
31811
31931
  }
31812
31932
 
31813
31933
  // Cross-platform git invocation. Uses resolved absolute path when possible (spawnable
@@ -31823,22 +31943,40 @@ async function spawnGitRead(args, opts = {}) {
31823
31943
  }
31824
31944
 
31825
31945
  function logGitFailure(where, err) {
31826
- const msg = err?.stderr?.toString?.() || err?.message || String(err);
31946
+ const redact = typeof redactSecrets === 'function' ? redactSecrets : (s) => s;
31947
+ const rawStderr = redact(Buffer.isBuffer(err?.stderr)
31948
+ ? err.stderr.toString('utf8')
31949
+ : (typeof err?.stderr === 'string' ? err.stderr : ''));
31950
+ const stderrLine = rawStderr.trim().split(/\r?\n/)[0]?.trim() || '';
31951
+ const errMessage = typeof err?.message === 'string' ? redact(err.message).trim().split(/\r?\n/)[0]?.trim() : '';
31952
+ const code = err?.code != null && err.code !== ''
31953
+ ? String(err.code)
31954
+ : (err?.status != null ? `exit ${err.status}` : '');
31955
+ const fallback = typeof err === 'string' ? redact(err).trim().split(/\r?\n/)[0]?.trim() : '';
31956
+ const msg = stderrLine || errMessage || (code ? `git failed (${code})` : '') || fallback;
31827
31957
  if (!msg || /not a git repository/i.test(msg)) return;
31828
- if (/ENOENT/i.test(msg) || /is not recognized/i.test(msg) || /command not found/i.test(msg)) {
31958
+ if (code === 'ENOENT' || /ENOENT/i.test(msg) || /is not recognized/i.test(msg) || /command not found/i.test(msg)) {
31829
31959
  if (_gitMissingLogged) return;
31830
31960
  _gitMissingLogged = true;
31831
31961
  console.warn(`[git] '${where}' failed: git executable not found on PATH. Install Git and ensure it's on the Node process PATH.`);
31832
31962
  return;
31833
31963
  }
31834
- console.warn(`[git] '${where}' failed:`, msg.trim().split('\n')[0]);
31964
+ const detail = (code && !msg.includes(code)) ? `${msg} (${code})` : msg;
31965
+ console.warn(`[git] '${where}' failed:`, detail);
31835
31966
  }
31836
31967
 
31837
- // resolveGitPath()'s lookup without blocking: `where git` (Windows) or `command -v git`, run once in the
31838
- // background at start-up, so the first git call of a request finds the answer kept instead of running the
31839
- // lookup itself (a synchronous spawn through cmd.exe holds every request on a Windows PC without git).
31968
+ // Unified non-blocking server Git resolver (bundled → managed → system). Shared by
31969
+ // startup probing, spawnGit/spawnGitRead, and gitStatusRunner (status, reads, stage/commit).
31840
31970
  function resolveGitPathInBackground() {
31841
- if (_gitResolved) return Promise.resolve(_gitExePath || gitBash.gitExecutable());
31971
+ const managed = gitBash.managedGitExecutable?.() || null;
31972
+ if (managed) {
31973
+ if (!_gitResolved) {
31974
+ _gitResolved = true;
31975
+ console.log(`[git] resolved: ${managed}`);
31976
+ }
31977
+ return Promise.resolve(managed);
31978
+ }
31979
+ if (_gitResolved) return Promise.resolve(_gitExePath || gitBash.gitExecutable({ includeSystem: true }));
31842
31980
  if (_gitResolving) return _gitResolving;
31843
31981
  _gitResolving = new Promise((done) => {
31844
31982
  const [command, args] = IS_WINDOWS ? ['where', ['git']] : ['/bin/sh', ['-c', 'command -v git']];
@@ -31847,10 +31985,26 @@ function resolveGitPathInBackground() {
31847
31985
  _gitResolved = true;
31848
31986
  const lines = error ? [] : String(stdout || '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
31849
31987
  _gitExePath = (IS_WINDOWS ? lines.find((line) => /\.exe$/i.test(line)) : null) || lines[0] || null;
31850
- if (_gitExePath) console.log(`[git] resolved: ${_gitExePath}`);
31851
- else console.warn('[git] resolution failed:', error?.message || 'resolver returned no paths');
31988
+ if (_gitExePath) {
31989
+ console.log(`[git] resolved: ${_gitExePath}`);
31990
+ } else {
31991
+ const fallback = gitBash.gitExecutable() || gitBash.gitExecutable({ includeSystem: true });
31992
+ if (fallback) {
31993
+ _gitExePath = fallback;
31994
+ console.log(`[git] resolved: ${fallback}`);
31995
+ } else {
31996
+ const detail = error?.killed
31997
+ ? 'timed out'
31998
+ : typeof error?.code === 'string'
31999
+ ? error.code
32000
+ : typeof error?.code === 'number'
32001
+ ? `not found on PATH (exit ${error.code})`
32002
+ : 'resolver returned no paths';
32003
+ console.warn(`[git] resolution failed: ${detail}`);
32004
+ }
32005
+ }
31852
32006
  }
31853
- done(_gitExePath || gitBash.gitExecutable());
32007
+ done(gitBash.managedGitExecutable?.() || _gitExePath || gitBash.gitExecutable({ includeSystem: true }));
31854
32008
  });
31855
32009
  }).finally(() => { _gitResolving = null; });
31856
32010
  return _gitResolving;
@@ -31862,8 +32016,8 @@ setImmediate(async () => {
31862
32016
  try {
31863
32017
  const gitPath = await resolveGitPathInBackground();
31864
32018
  const result = await gitStatusRunner.run(['--version'], { binary: gitPath || 'git', timeoutMs: 3000 });
31865
- if (result.ok) console.log(`[git] ${String(result.stdout).trim()} — OK`);
31866
- else console.warn(`[git] startup probe FAILED: ${String(result.stderr).trim() || result.code}. File explorer git UI will be hidden.`);
32019
+ if (result.ok) console.log(`[git] ${redactSecrets(String(result.stdout)).trim()} — OK`);
32020
+ else console.warn(`[git] startup probe FAILED: ${redactSecrets(String(result.stderr)).trim() || result.code}. File explorer git UI will be hidden.`);
31867
32021
  } catch { /* availability is reported on the first read */ }
31868
32022
  });
31869
32023
 
@@ -31981,7 +32135,7 @@ app.get('/api/terminal/branches', async (req, res) => {
31981
32135
 
31982
32136
  const inside = await spawnGitRead(['rev-parse', '--is-inside-work-tree'], { cwd: dir, timeout: 3000 });
31983
32137
  if (inside.status !== 0) {
31984
- logGitFailure('branches: rev-parse', inside.error || { stderr: inside.stderr });
32138
+ logGitFailure('branches: rev-parse', inside.error || inside);
31985
32139
  return res.json({ branches: [], current: null });
31986
32140
  }
31987
32141
 
@@ -31990,7 +32144,7 @@ app.get('/api/terminal/branches', async (req, res) => {
31990
32144
  let current = '';
31991
32145
  const showCurrent = await spawnGitRead(['branch', '--show-current'], { cwd: dir, timeout: 3000 });
31992
32146
  if (showCurrent.status === 0) current = showCurrent.stdout.toString().trim();
31993
- else logGitFailure('branches: show-current', showCurrent.error || { stderr: showCurrent.stderr });
32147
+ else logGitFailure('branches: show-current', showCurrent.error || showCurrent);
31994
32148
  if (!current) {
31995
32149
  const abbrev = await spawnGitRead(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: dir, timeout: 3000 });
31996
32150
  if (abbrev.status === 0) {
@@ -32002,7 +32156,7 @@ app.get('/api/terminal/branches', async (req, res) => {
32002
32156
  // All local branches — plain `git branch` parsed manually; avoids --format=%(refname:short)
32003
32157
  // which can get mangled by cmd.exe variable expansion on Windows even with proper quoting.
32004
32158
  const branchResult = await spawnGitRead(['branch'], { cwd: dir });
32005
- if (branchResult.status !== 0) logGitFailure('branch list', branchResult.error || { stderr: branchResult.stderr });
32159
+ if (branchResult.status !== 0) logGitFailure('branch list', branchResult.error || branchResult);
32006
32160
  const raw = branchResult.status === 0 ? branchResult.stdout.toString() : '';
32007
32161
  // Plain `git branch` output: each line is " branch" or "* branch" (current). Strip
32008
32162
  // marker + whitespace. Skip detached-HEAD lines like "* (HEAD detached at abc1234)".
@@ -32037,8 +32191,8 @@ app.post('/api/terminal/trust-workspace', async (req, res) => {
32037
32191
  const gitPath = normalizeGitPath(abs);
32038
32192
  const r = await spawnGit(['config', '--global', '--add', 'safe.directory', gitPath]);
32039
32193
  if (r.status !== 0) {
32040
- const stderr = r.stderr?.toString?.()?.trim() || r.error?.message || 'git config failed';
32041
- logGitFailure('config --add safe.directory', r.error || { stderr: r.stderr });
32194
+ const stderr = r.stderr?.toString?.()?.trim() || r.error?.message || (r.code ? `git config failed (${r.code})` : 'git config failed');
32195
+ logGitFailure('config --add safe.directory', r.error || r);
32042
32196
  return res.status(500).json({ ok: false, error: stderr });
32043
32197
  }
32044
32198
 
@@ -32059,7 +32213,7 @@ app.post('/api/terminal/checkout', async (req, res) => {
32059
32213
 
32060
32214
  const inside = await spawnGitRead(['rev-parse', '--is-inside-work-tree'], { cwd: dir, timeout: 3000 });
32061
32215
  if (inside.status !== 0) {
32062
- logGitFailure('checkout: rev-parse', inside.error || { stderr: inside.stderr });
32216
+ logGitFailure('checkout: rev-parse', inside.error || inside);
32063
32217
  return res.status(400).json({ error: 'Not a git repository' });
32064
32218
  }
32065
32219
 
@@ -32070,7 +32224,7 @@ app.post('/api/terminal/checkout', async (req, res) => {
32070
32224
  const result = await spawnGit(['checkout', branch], { cwd: dir, timeout: 10000 });
32071
32225
  gitStatusRunner.invalidate(dir);
32072
32226
  if (result.status !== 0) {
32073
- const stderr = result.stderr?.toString?.()?.trim() || result.error?.message || 'Checkout failed';
32227
+ const stderr = result.stderr?.toString?.()?.trim() || result.error?.message || (result.code ? `Checkout failed (${result.code})` : 'Checkout failed');
32074
32228
  return res.status(500).json({ error: stderr });
32075
32229
  }
32076
32230
 
@@ -32078,7 +32232,7 @@ app.post('/api/terminal/checkout', async (req, res) => {
32078
32232
  let current = '';
32079
32233
  const showCurrent = await spawnGitRead(['branch', '--show-current'], { cwd: dir, timeout: 3000 });
32080
32234
  if (showCurrent.status === 0) current = showCurrent.stdout.toString().trim();
32081
- else logGitFailure('checkout: show-current', showCurrent.error || { stderr: showCurrent.stderr });
32235
+ else logGitFailure('checkout: show-current', showCurrent.error || showCurrent);
32082
32236
  const output = result.stderr?.toString?.()?.trim() || `Switched to branch '${current}'`;
32083
32237
  res.json({ ok: true, branch: current, output });
32084
32238
  });
@@ -33243,7 +33397,17 @@ function extensionSelfHosts() {
33243
33397
  try { for (const list of Object.values(os.networkInterfaces())) for (const entry of list || []) if (entry?.address) hosts.add(entry.address.split('%')[0]); } catch {}
33244
33398
  return [...hosts];
33245
33399
  }
33400
+ function extensionRunsActive() {
33401
+ const { assistant, loop } = systemActivitySources();
33402
+ return !collectActivity({ assistant, loop }).idle;
33403
+ }
33246
33404
  const extensionBridge = createExtensionBridge({
33405
+ runsActive: extensionRunsActive,
33406
+ onConnected: version => extensionUpdate.connected(version),
33407
+ updateStatus: version => {
33408
+ const disk = extensionPackage.status();
33409
+ return { version: !disk.needs && disk.folderVersion && compareVersions(version, disk.folderVersion) < 0 ? disk.folderVersion : null };
33410
+ },
33247
33411
  forbiddenOrigins: publicWebOrigins,
33248
33412
  blockedPorts: extensionBlockedPorts,
33249
33413
  selfHosts: extensionSelfHosts,
@@ -33272,7 +33436,10 @@ const extensionEvaluateGate = {
33272
33436
  };
33273
33437
  const extensionAdapter = createExtensionAdapter({
33274
33438
  bridge: extensionBridge, sessions: browserSessions, uploadRoot: extensionUploadRoot, dataHome: DATA_HOME,
33439
+ // The bridge handshake identifies the connection. Local profile settings belong to mirror/attach.
33275
33440
  caller: browserCaller, ownerPage: browserOwnerPageOnly, evaluateGate: extensionEvaluateGate,
33441
+ // browser_content markdown in extension mode: the Playwright route's own converter (nhm, below), called per request.
33442
+ htmlToMarkdown: html => nhm.translate(html),
33276
33443
  selected: req => loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(browserCaller(req).id),
33277
33444
  });
33278
33445
  // The extension folder the owner loads (DATA_HOME/browser-extension/unpacked). Its files are the one package this
@@ -33293,6 +33460,7 @@ try { const prepared = extensionPackage.retarget(); if (prepared.changed) consol
33293
33460
  catch (error) { console.warn(`[extension-bridge] extension folder not checked (${error?.code || 'error'}${error?.code === 'EXTENSION_FOLDER_UNSAFE' && error.reason ? `: ${error.reason}` : ''})`); }
33294
33461
  // The one-button setup (Settings → Browser → "Connect your browser"; docs/browser-extension-bridge.md → One-button
33295
33462
  // setup). Programs are started with execFile/spawn and argument arrays, never a shell; reads time out.
33463
+ const extensionUpdate = createExtensionUpdate({ bridge: extensionBridge, pkg: extensionPackage, runsActive: extensionRunsActive });
33296
33464
  const extensionSetup = createExtensionSetup({
33297
33465
  bridge: extensionBridge,
33298
33466
  detect: () => detectBrowsers({
@@ -33304,12 +33472,12 @@ const extensionSetup = createExtensionSetup({
33304
33472
  prepare: ({ signal } = {}) => extensionPackage.ensure({ reason: 'setup', signal }),
33305
33473
  packageStatus: () => extensionPackage.status(),
33306
33474
  confirmReload: () => extensionPackage.confirmReload(),
33475
+ updateStatus: (peer, disk) => extensionUpdate.status(peer, disk),
33307
33476
  exec: (cmd, args) => new Promise((resolveExec, rejectExec) => {
33308
33477
  const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true, shell: false });
33309
33478
  child.once('error', rejectExec); child.once('spawn', () => { child.unref(); resolveExec(); });
33310
33479
  }),
33311
33480
  appOrigin: () => `http://127.0.0.1:${Number(PORT) || 3344}`,
33312
- folderVersion: () => { const state = extensionFolderState(DATA_HOME); return state.present ? state.version : null; },
33313
33481
  });
33314
33482
  {
33315
33483
  const restored = extensionBridge.restore();
@@ -33634,14 +33802,44 @@ function sessionServesMoreLoginEnv(session, envId) {
33634
33802
  return !!session && session._profileMode === 'morelogin' && String(session._mlEnvId || '') === String(envId);
33635
33803
  }
33636
33804
 
33637
- /** Whether `session` is a browser run `ownerKey` may work in: its pinned profile's, else the default browser's. */
33805
+ /**
33806
+ * Whether `session` is a browser run `ownerKey` may work in: its pinned profile's, else the default browser's.
33807
+ * No session serves. An unpinned run gets a MoreLogin session only while MoreLogin is the default browser (and then
33808
+ * only the default profile's), and a local session (clean, managed, direct, mirror, attach) only when it is the one
33809
+ * Settings → Browser selects, by the rule findReusableBrowserSession reuses by. Before review round 3 any MoreLogin
33810
+ * or local session served a run under a mirror / attach / clean default, so a requested session id reached another
33811
+ * profile in strategy 0 of acquireSharedBrowserTab (which also destroys a requested session that fails its check).
33812
+ */
33638
33813
  function sessionServesRun(session, cfg, ownerKey) {
33814
+ if (!session) return false;
33639
33815
  const pin = runMoreLoginPin(ownerKey);
33640
33816
  // A pin that may not be used (an agent's, its profile off the owner's list) serves in no session at all: not its
33641
33817
  // profile's, and never the default browser's.
33642
33818
  if (pin) return !pinUseRefusal(pin, cfg) && sessionServesMoreLoginEnv(session, pin.envId);
33643
- if (cfg.connectMode === 'extension' || session?._profileMode === 'extension') return cfg.connectMode === 'extension' && session?._profileMode === 'extension';
33644
- return cfg.connectMode !== 'morelogin' || sessionServesMoreLoginDefault(session, cfg);
33819
+ if (cfg.connectMode === 'extension' || session._profileMode === 'extension') return cfg.connectMode === 'extension' && session._profileMode === 'extension';
33820
+ if (cfg.connectMode === 'morelogin' || session._profileMode === 'morelogin') return cfg.connectMode === 'morelogin' && sessionServesMoreLoginDefault(session, cfg);
33821
+ return sessionServesLocalBrowser(session, cfg);
33822
+ }
33823
+
33824
+ /**
33825
+ * Whether a local session (not MoreLogin, not the extension) is the browser Settings → Browser selects: attach when
33826
+ * attach is active and a launch otherwise, on the selected profile folder, or a clean session when none is selected.
33827
+ * findReusableBrowserSession reuses by this rule, and sessionServesRun holds a requested or recorded session to it.
33828
+ */
33829
+ function sessionServesLocalBrowser(session, cfg) {
33830
+ if (!session || session._profileMode === 'morelogin' || session._profileMode === 'extension') return false;
33831
+ if (isAttachConfigActive(cfg) !== (session._profileMode === 'cdp')) return false;
33832
+ let selectedPath = cfg.userDataDir || '';
33833
+ if (selectedPath && !selectedPath.startsWith('/') && !(/^[A-Z]:/i.test(selectedPath))) {
33834
+ selectedPath = resolve(DATA_HOME, selectedPath);
33835
+ }
33836
+ const normalize = (p) => (p || '').replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
33837
+ const selectedNorm = normalize(selectedPath);
33838
+ if (!selectedNorm) return session._profileMode === 'clean';
33839
+ const sessionSelected = normalize(session._selectedProfilePath);
33840
+ const sessionRoot = normalize(session._launchUserDataDir);
33841
+ const sessionActiveProfile = normalize(resolve(session._launchUserDataDir || '', session._launchProfileDirectory || 'Default'));
33842
+ return selectedNorm === sessionSelected || selectedNorm === sessionRoot || selectedNorm === sessionActiveProfile;
33645
33843
  }
33646
33844
 
33647
33845
  function describeBrowserSessionForLog(session) {
@@ -33654,17 +33852,7 @@ function describeBrowserSessionForLog(session) {
33654
33852
  async function findReusableBrowserSession(opts = {}) {
33655
33853
  const { excludeAgentOwned = true, excludeLoopOwned = true, moreloginEnvId = null } = opts;
33656
33854
  const cfg = loadBrowserConfig();
33657
- // Don't reuse across connect modes: an attach (cdp) session and a mirror session
33658
- // are not interchangeable. Protects in-flight loops when the mode is switched.
33659
- // Use the same applicability test as session creation to avoid infinite re-spawn.
33660
- const wantAttach = isAttachConfigActive(cfg);
33661
33855
  const wantMoreLogin = cfg.connectMode === 'morelogin';
33662
- let selectedPath = cfg.userDataDir || '';
33663
- if (selectedPath && !selectedPath.startsWith('/') && !(/^[A-Z]:/i.test(selectedPath))) {
33664
- selectedPath = resolve(DATA_HOME, selectedPath);
33665
- }
33666
- const normalize = (p) => (p || '').replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
33667
- const selectedNorm = normalize(selectedPath);
33668
33856
  for (const [id, session] of browserSessions) {
33669
33857
  if (session._profileMode === 'extension' || cfg.connectMode === 'extension' && !moreloginEnvId) {
33670
33858
  if (session._profileMode === 'extension' && cfg.connectMode === 'extension' && extensionBridge.status().connected && !moreloginEnvId) return { id, session };
@@ -33689,19 +33877,11 @@ async function findReusableBrowserSession(opts = {}) {
33689
33877
  if (!sessionServesMoreLoginEnv(session, moreloginEnvId)) continue;
33690
33878
  } else if (wantMoreLogin || session._profileMode === 'morelogin') {
33691
33879
  if (!wantMoreLogin || !sessionServesMoreLoginDefault(session, cfg)) continue;
33692
- } else {
33693
- if (wantAttach && session._profileMode !== 'cdp') continue;
33694
- if (!wantAttach && session._profileMode === 'cdp') continue;
33695
- if (selectedNorm) {
33696
- const sessionSelected = normalize(session._selectedProfilePath);
33697
- const sessionRoot = normalize(session._launchUserDataDir);
33698
- const sessionActiveProfile = normalize(resolve(session._launchUserDataDir || '', session._launchProfileDirectory || 'Default'));
33699
- if (selectedNorm !== sessionSelected && selectedNorm !== sessionRoot && selectedNorm !== sessionActiveProfile) {
33700
- continue;
33701
- }
33702
- } else if (session._profileMode !== 'clean') {
33703
- continue;
33704
- }
33880
+ } else if (!sessionServesLocalBrowser(session, cfg)) {
33881
+ // Don't reuse across connect modes or profile folders: an attach (cdp) session and a mirror session are not
33882
+ // interchangeable. Protects in-flight loops when the mode is switched. The same applicability test as session
33883
+ // creation (isAttachConfigActive) avoids an infinite re-spawn.
33884
+ continue;
33705
33885
  }
33706
33886
  try {
33707
33887
  // Do not probe only the mutable `session.page` alias here. A renderer can
@@ -33807,7 +33987,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33807
33987
  if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(ownerKey)) {
33808
33988
  // takeOverTab: one of the owner's open tabs in the everyday browser (full control), named by browser_session create.
33809
33989
  try { return await extensionAdapter.acquire(ownerKey, ownerType, { adopt: takeOverTab || undefined }); }
33810
- catch (error) { return extensionSafeError(error); }
33990
+ catch (error) { return extensionAdapter.describeError(error); }
33811
33991
  }
33812
33992
  const lockKey = loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig());
33813
33993
  const acquired = await withLoopBrowserLock(lockKey, async () => {
@@ -33878,6 +34058,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33878
34058
  // createBrowserSession is strict: with MoreLogin as the default it either attaches
33879
34059
  // to MoreLogin (auto-launching the app) or throws — never a Chrome fallback.
33880
34060
  let createError = null;
34061
+ let createdHere = false;
33881
34062
  if (!browserSessionId) {
33882
34063
  try {
33883
34064
  // The start guard: a profile closed outside SynaBun is not started again by this acquisition (an attach to the
@@ -33889,6 +34070,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33889
34070
  ? { url: 'about:blank', connectMode: 'morelogin', moreloginEnvId: pin.envId, _mlPinned: true, moreloginStartGuard, moreloginAfterOutsideClose }
33890
34071
  : { url: 'about:blank', moreloginStartGuard, moreloginAfterOutsideClose });
33891
34072
  browserSessionId = result.sessionId;
34073
+ createdHere = true;
33892
34074
  loopLog(ownerKey, logTag, 'strategy 2: created shared browser session', {
33893
34075
  browserSessionId, profileMode: result.profileMode, profileSource: result.profileSource,
33894
34076
  });
@@ -33908,9 +34090,14 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33908
34090
  // The run's own profile (its pin, else the MoreLogin default) failed to start or connect in this run: from now on
33909
34091
  // it may not move to another profile (POST /api/morelogin/use answers 409 PROFILE_FAILED_NO_SWITCH) until that
33910
34092
  // profile connects again for it (below), the owner moves it, or it ends (lib/morelogin-profile-failures.js).
34093
+ let profileAdvice = '';
33911
34094
  if (createError) {
33912
34095
  const own = pin || (moreLoginDefault && moreLoginDefaultEnvId(policyCfg) ? { envId: String(moreLoginDefaultEnvId(policyCfg)), name: null } : null);
33913
34096
  noteRunProfileFailure(ownerKey, own, createError);
34097
+ if (own && !createError.code) {
34098
+ profileAdvice = await stoppedProfileAdvice(own.envId, own.name || _moreLoginEnvNames.get(own.envId),
34099
+ id => moreLogin.profileStatus(id, { savedCfg: policyCfg, timeout: 1500 }));
34100
+ }
33914
34101
  }
33915
34102
  // The profile was closed outside SynaBun: the sentence says it all (which profile, when, that SynaBun does not
33916
34103
  // reopen it, how to go on); no "could not start" around it.
@@ -33930,9 +34117,9 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33930
34117
  ? `this needs the user, not a retry: ${createError.planLimit ? 'wait for MoreLogin\'s daily reset, upgrade the MoreLogin plan, or keep the profile open so runs need no new start' : 'fix what MoreLogin names in the MoreLogin app'}.`
33931
34118
  : createError?.code === 'MORELOGIN_PROFILE_WINDOWLESS'
33932
34119
  ? 'this needs the user, not a retry: open the profile\'s window again in MoreLogin (or close it fully there and start it again).'
33933
- : 'check that MoreLogin is open and that the profile still exists, or pick another profile where this run is set up.'}`
34120
+ : profileAdvice || 'check that MoreLogin is open and that the profile still exists, or pick another profile where this run is set up.'}`
33934
34121
  : createError
33935
- ? `Could not start the shared browser session: ${createError.error}`
34122
+ ? `Could not start the shared browser session: ${createError.error}${profileAdvice ? `${/[.!?]$/.test(String(createError.error || '').trim()) ? '' : '.'} ${profileAdvice}` : ''}`
33936
34123
  : 'Could not start the shared browser session. Open Browser Settings and verify the selected profile can launch.',
33937
34124
  ...(createError?.code ? { code: createError.code, offenders: createError.offenders } : {}),
33938
34125
  ...(createError?.needsUser ? { needsUser: true } : {}),
@@ -33948,7 +34135,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33948
34135
  browserSessionId, ...describeBrowserSessionForLog(chosenSession), wantMoreLoginEnvId: pin.envId,
33949
34136
  });
33950
34137
  return {
33951
- error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode${chosenSession._mlEnvId ? `, MoreLogin env ${chosenSession._mlEnvId}` : ''}): this run is set to ${describeMoreLoginPin(pin)} and never falls back to another profile or browser.`,
34138
+ error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode${chosenSession._mlEnvId ? `, MoreLogin env ${chosenSession._mlEnvId}` : ''}): this run is set to ${describeMoreLoginPin(pin)} and never falls back to another profile or browser. Open the profile configured for this run.`,
33952
34139
  };
33953
34140
  }
33954
34141
  if (!pin && moreLoginDefault && chosenSession && !sessionServesMoreLoginDefault(chosenSession, policyCfg)) {
@@ -33956,7 +34143,18 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
33956
34143
  browserSessionId, ...describeBrowserSessionForLog(chosenSession),
33957
34144
  });
33958
34145
  return {
33959
- error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode): MoreLogin env ${moreLoginDefaultEnvId(policyCfg) || '(default)'} is the default browser, and automations never fall back to another browser.`,
34146
+ error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode): MoreLogin env ${moreLoginDefaultEnvId(policyCfg) || '(default)'} is the default browser, and automations never fall back to another browser. Open the configured AI browser profile.`,
34147
+ };
34148
+ }
34149
+ // A reused or requested session for a run on SynaBun's own browser (mirror, attach, clean) is the one its settings
34150
+ // select, and never a MoreLogin profile or another local profile (sessionServesRun; review round 3, X1). The
34151
+ // session this acquisition just created is that browser by construction.
34152
+ if (!pin && !moreLoginDefault && chosenSession && !createdHere && !sessionServesRun(chosenSession, policyCfg, ownerKey)) {
34153
+ loopLog(ownerKey, logTag, 'ABORT: acquired session is not the default browser', {
34154
+ browserSessionId, ...describeBrowserSessionForLog(chosenSession),
34155
+ });
34156
+ return {
34157
+ error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode${chosenSession._mlEnvId ? `, MoreLogin env ${chosenSession._mlEnvId}` : ''}): it is not the browser selected in Settings → Browser, and automations never fall back to another browser or profile.`,
33960
34158
  };
33961
34159
  }
33962
34160
 
@@ -37550,7 +37748,7 @@ app.use('/api/browser/sessions/:id', (req, res, next) => {
37550
37748
  }
37551
37749
  const envId = moreLoginDefaultEnvId(cfg);
37552
37750
  res.status(409).json({
37553
- error: `Session ${req.params.id} is not the default browser (${session._profileMode || 'unknown'} mode${session._mlEnvId ? `, MoreLogin env ${session._mlEnvId}` : ''}; the default is MoreLogin${envId ? ` env ${envId}` : ''}), so SynaBun's browser tools do not act on it. Leave sessionId out: browser_navigate opens the page in the default browser.`,
37751
+ error: `Session ${req.params.id} is not the default browser (${session._profileMode || 'unknown'} mode${session._mlEnvId ? `, MoreLogin env ${session._mlEnvId}` : ''}; the default is ${cfg.connectMode === 'morelogin' ? `MoreLogin${envId ? ` env ${envId}` : ''}` : cfg.connectMode === 'extension' ? 'the SynaBun browser extension' : 'the browser selected in Settings → Browser'}), so SynaBun's browser tools do not act on it. Leave sessionId out: browser_navigate opens the page in the default browser.`,
37554
37752
  code: 'NOT_DEFAULT_BROWSER',
37555
37753
  });
37556
37754
  };
@@ -37572,15 +37770,18 @@ app.use('/api/browser/extension', extensionOwnerGuard, (req, res, next) => {
37572
37770
  res.setHeader('Cache-Control', 'no-store'); next();
37573
37771
  });
37574
37772
  app.get('/api/browser/extension', (_req, res) => {
37575
- const folderState = extensionFolderState(DATA_HOME), status = extensionBridge.status();
37773
+ const status = extensionBridge.status();
37576
37774
  // `folder`: the folder the owner loads, once it is there (null until "Connect your browser" downloaded the extension).
37577
37775
  // `package`: the pinned package and its download (pinnedVersion, needs, phase, received, total, code).
37578
37776
  const pkg = extensionPackage.status();
37579
- res.json({ ...status, folder: folderState.present ? folderState.folder : null, uploadFolder: extensionUploadRoot,
37580
- folderVersion: folderState.present ? folderState.version : null, pinnedVersion: pkg.pinnedVersion, package: pkg,
37581
- ...extensionVersions({ connected: status.connected, extensionVersion: status.extensionVersion, folderVersion: folderState.present ? folderState.version : null, pinnedVersion: pkg.pinnedVersion, reloadPending: pkg.reloadPending === true, reloadReason: pkg.reloadReason ?? null }),
37582
- setup: extensionSetup.status().state });
37583
- });
37777
+ res.json({ ...status, folder: pkg.folder, uploadFolder: extensionUploadRoot,
37778
+ folderVersion: pkg.folderVersion, pinnedVersion: pkg.pinnedVersion, package: pkg,
37779
+ ...extensionVersions({ connected: status.connected, extensionVersion: status.extensionVersion, folderVersion: pkg.folderVersion, pinnedVersion: pkg.pinnedVersion, reloadPending: pkg.reloadPending === true, reloadReason: pkg.reloadReason ?? null }),
37780
+ update: extensionUpdate.status(status, pkg), setup: extensionSetup.state() });
37781
+ });
37782
+ // A summary without paths, tab inventories or pairing data for the owner's proactive notices.
37783
+ app.get('/api/browser/extension/update/status', (_req, res) => res.json(extensionUpdate.status()));
37784
+ app.post('/api/browser/extension/reload', ownerReloadHandler({ update: extensionUpdate, isAutomationBrowser: req => _pageSession.isAutomationBrowser(req) }));
37584
37785
  // The one-button setup. Owner only: these sit under the guard above (ownerRouteGuard, the page secret, no automation
37585
37786
  // caller), like pairing and the mode. The token (ticket) goes to SynaBun's own setup page only, never into a log or URL.
37586
37787
  const sendSetup = (res, run) => Promise.resolve().then(run).then(value => res.json({ ok: true, ...value }),
@@ -37617,7 +37818,7 @@ app.post('/api/browser/extension/:action', async (req, res) => {
37617
37818
  // The owner's mode: full control (any site and tab of the paired browser) or only what the owner shares.
37618
37819
  else if (action === 'mode') await extensionBridge.setMode(req.body?.fullControl);
37619
37820
  // The owner's retry of an update that did not download (Settings): only for a folder that is already there.
37620
- else if (action === 'update') { if (extensionPackage.needs() === 'update') extensionPackage.ensure({ reason: 'update' }).catch(() => {}); }
37821
+ else if (action === 'update') { if (extensionPackage.needs() === 'update') extensionPackage.ensure({ reason: 'update' }).then(() => extensionBridge.publishUpdate(), () => {}); }
37621
37822
  else return res.status(400).json({ code: 'INVALID_MESSAGE', error: 'Unknown extension action.' });
37622
37823
  return res.json({ ok: true, ...extensionBridge.status() });
37623
37824
  } catch (error) { return res.status(400).json(extensionSafeError(error)); }
@@ -37689,6 +37890,7 @@ app.get('/api/browser/sessions', (req, res) => {
37689
37890
  // A run's own route as the server last recorded it (a recovery or a browser_session create moved it): the MCP
37690
37891
  // follows it even after its process restarted and forgot (mcp-server neural-interface.ts resolveSessionUncached).
37691
37892
  const yourRoute = caller ? liveAutomationRoute(caller, { cfg: policyCfg }) : null;
37893
+ const workerBrowser = who.status === 'verified' && _assistantDispatcher?.optionalBrowserRoute?.(caller);
37692
37894
  res.json({
37693
37895
  sessions,
37694
37896
  defaultBrowser: callerPin
@@ -37696,6 +37898,7 @@ app.get('/api/browser/sessions', (req, res) => {
37696
37898
  : moreLoginDefault
37697
37899
  ? { connectMode: 'morelogin', moreloginEnvId: moreLoginDefaultEnvId(policyCfg) }
37698
37900
  : { connectMode: policyCfg.connectMode || null },
37901
+ ...(workerBrowser ? { workerBrowser } : {}),
37699
37902
  ...(yourRoute ? { yourRoute: { sessionId: yourRoute.browserSessionId, tabId: yourRoute.browserTabId } } : {}),
37700
37903
  // The MoreLogin profile this caller works in when it is not the default (its launch's, or its own choice: POST
37701
37904
  // /api/morelogin/use). The MCP reads it to move a run whose pinned tab is in a browser it left.
@@ -40180,7 +40383,7 @@ const httpServer = app.listen(PORT, async () => {
40180
40383
  // fetched and verified in the background (lib/browser-extension-package.js). Nothing is downloaded for somebody who
40181
40384
  // never set the extension up, and a failure keeps the folder that is there.
40182
40385
  setTimeout(() => {
40183
- try { markActivity('startup:extension-package'); extensionPackage.refreshInBackground(); }
40386
+ try { markActivity('startup:extension-package'); extensionPackage.refreshInBackground()?.then(() => extensionBridge.publishUpdate(), () => {}); }
40184
40387
  catch (error) { console.warn(`[extension-bridge] extension update not started (${error?.code || 'error'})`); }
40185
40388
  }, 4000).unref?.();
40186
40389