synabun 2.2.1 → 2.2.2

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 (149) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +1 -1
  3. package/hooks/claude-code/pre-websearch.mjs +4 -1
  4. package/hooks/claude-code/prompt-submit.mjs +7 -0
  5. package/lib/release-scan.mjs +23 -10
  6. package/lib/virustotal.mjs +143 -39
  7. package/mcp-server/dist/http.d.ts +19 -0
  8. package/mcp-server/dist/http.d.ts.map +1 -1
  9. package/mcp-server/dist/http.js +55 -13
  10. package/mcp-server/dist/http.js.map +1 -1
  11. package/mcp-server/dist/index.d.ts.map +1 -1
  12. package/mcp-server/dist/index.js +14 -9
  13. package/mcp-server/dist/index.js.map +1 -1
  14. package/mcp-server/dist/services/browser-route-flow.d.ts +118 -0
  15. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -0
  16. package/mcp-server/dist/services/browser-route-flow.js +339 -0
  17. package/mcp-server/dist/services/browser-route-flow.js.map +1 -0
  18. package/mcp-server/dist/services/desktop-client.js +2 -2
  19. package/mcp-server/dist/services/desktop-client.js.map +1 -1
  20. package/mcp-server/dist/services/identity.d.ts +66 -3
  21. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  22. package/mcp-server/dist/services/identity.js +61 -4
  23. package/mcp-server/dist/services/identity.js.map +1 -1
  24. package/mcp-server/dist/services/neural-interface.d.ts +112 -1
  25. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  26. package/mcp-server/dist/services/neural-interface.js +555 -61
  27. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  28. package/mcp-server/dist/tools/bluesky.d.ts +20 -7
  29. package/mcp-server/dist/tools/bluesky.d.ts.map +1 -1
  30. package/mcp-server/dist/tools/bluesky.js +147 -45
  31. package/mcp-server/dist/tools/bluesky.js.map +1 -1
  32. package/mcp-server/dist/tools/browser-advanced.d.ts +11 -2
  33. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-advanced.js +131 -18
  35. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-cheatsheet.d.ts +2 -0
  37. package/mcp-server/dist/tools/browser-cheatsheet.d.ts.map +1 -1
  38. package/mcp-server/dist/tools/browser-cheatsheet.js +3 -0
  39. package/mcp-server/dist/tools/browser-cheatsheet.js.map +1 -1
  40. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  41. package/mcp-server/dist/tools/morelogin.js +4 -2
  42. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  43. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  44. package/mcp-server/dist/tools/youtube/helpers.d.ts +1 -0
  45. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  46. package/mcp-server/dist/tools/youtube/helpers.js +1 -1
  47. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  48. package/mcp-server/package-lock.json +2 -2
  49. package/mcp-server/package.json +1 -1
  50. package/mcp-server/src/http.ts +58 -12
  51. package/mcp-server/src/index.ts +15 -9
  52. package/mcp-server/src/services/browser-route-flow.ts +402 -0
  53. package/mcp-server/src/services/desktop-client.ts +2 -2
  54. package/mcp-server/src/services/identity.ts +80 -4
  55. package/mcp-server/src/services/neural-interface.ts +572 -70
  56. package/mcp-server/src/tools/bluesky.ts +164 -51
  57. package/mcp-server/src/tools/browser-advanced.ts +121 -17
  58. package/mcp-server/src/tools/browser-cheatsheet.ts +3 -0
  59. package/mcp-server/src/tools/morelogin.ts +4 -2
  60. package/mcp-server/src/tools/youtube/helpers.ts +2 -2
  61. package/neural-interface/i18n/en.json +24 -0
  62. package/neural-interface/i18n/pt-BR.json +24 -0
  63. package/neural-interface/lib/assistant-api.js +64 -23
  64. package/neural-interface/lib/assistant-catalog.js +20 -2
  65. package/neural-interface/lib/assistant-dispatch.js +27 -1
  66. package/neural-interface/lib/assistant-persona.js +1 -0
  67. package/neural-interface/lib/assistant-runtime.js +15 -1
  68. package/neural-interface/lib/assistant-tools.js +10 -1
  69. package/neural-interface/lib/browser-automation-routes.js +84 -0
  70. package/neural-interface/lib/browser-execution.js +16 -3
  71. package/neural-interface/lib/browser-owner.js +48 -0
  72. package/neural-interface/lib/browser-session-close.js +84 -0
  73. package/neural-interface/lib/browser-start-handoff.js +202 -0
  74. package/neural-interface/lib/browser-tool-policy.js +21 -4
  75. package/neural-interface/lib/browser-wedge-retire.js +64 -0
  76. package/neural-interface/lib/claude-agent-bridge.js +36 -1
  77. package/neural-interface/lib/claude-background-hold.js +239 -0
  78. package/neural-interface/lib/exec-loop-command.js +8 -0
  79. package/neural-interface/lib/http-guards.js +11 -6
  80. package/neural-interface/lib/loop-logger.js +6 -1
  81. package/neural-interface/lib/mcp-external-servers.js +37 -10
  82. package/neural-interface/lib/native-loop-providers.js +121 -10
  83. package/neural-interface/lib/native-loop-runtime.js +112 -11
  84. package/neural-interface/lib/owner-authority.js +113 -37
  85. package/neural-interface/lib/page-session.js +81 -23
  86. package/neural-interface/lib/peer-identity.js +263 -43
  87. package/neural-interface/lib/provider-panel-api-key-auth.js +7 -2
  88. package/neural-interface/lib/pty-host/core.js +36 -0
  89. package/neural-interface/lib/pty-host/protocol.js +2 -0
  90. package/neural-interface/lib/skills/api-v2.js +13 -2
  91. package/neural-interface/lib/skills/creation-api.js +3 -1
  92. package/neural-interface/lib/skills/evals-api.js +5 -1
  93. package/neural-interface/lib/social-write-pacing.js +151 -0
  94. package/neural-interface/lib/terminal-token-redaction.js +293 -0
  95. package/neural-interface/lib/terminal-tokens.js +359 -0
  96. package/neural-interface/lib/worker-mcp-channel.js +45 -10
  97. package/neural-interface/package-lock.json +2 -2
  98. package/neural-interface/package.json +1 -1
  99. package/neural-interface/public/shared/agy/agy-render.js +41 -1
  100. package/neural-interface/public/shared/agy/agy-styles.js +5 -0
  101. package/neural-interface/public/shared/api.js +1 -0
  102. package/neural-interface/public/shared/assistant/asst-computer.js +47 -2
  103. package/neural-interface/public/shared/assistant/asst-limit-wait.js +3 -1
  104. package/neural-interface/public/shared/assistant/asst-panel.js +7 -3
  105. package/neural-interface/public/shared/assistant/asst-render.js +10 -4
  106. package/neural-interface/public/shared/assistant/asst-styles.js +2 -1
  107. package/neural-interface/public/shared/cdx/cdx-render.js +73 -7
  108. package/neural-interface/public/shared/cdx/cdx-tabs.js +3 -3
  109. package/neural-interface/public/shared/cp/cp-agents.js +8 -0
  110. package/neural-interface/public/shared/cp/cp-permissions.js +6 -2
  111. package/neural-interface/public/shared/cp/cp-rehydrate.js +25 -1
  112. package/neural-interface/public/shared/cp/cp-tasks-model.js +33 -0
  113. package/neural-interface/public/shared/judgments-log-origins.js +29 -0
  114. package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
  115. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +13 -0
  116. package/neural-interface/public/shared/ocp-v2/ocp-v2-icons.js +3 -1
  117. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +4 -2
  118. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +6 -86
  119. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +5 -2
  120. package/neural-interface/public/shared/owner-access.js +134 -0
  121. package/neural-interface/public/shared/owner-authority-view.js +92 -0
  122. package/neural-interface/public/shared/page-session.js +143 -14
  123. package/neural-interface/public/shared/poll-backoff.js +59 -0
  124. package/neural-interface/public/shared/settings/settings-data.js +6 -1
  125. package/neural-interface/public/shared/settings/settings-kit.js +11 -3
  126. package/neural-interface/public/shared/settings/settings-shell.js +7 -0
  127. package/neural-interface/public/shared/shown-children.js +72 -0
  128. package/neural-interface/public/shared/static-bg-state.js +22 -0
  129. package/neural-interface/public/shared/styles.css +101 -7
  130. package/neural-interface/public/shared/synabun-tools.js +173 -0
  131. package/neural-interface/public/shared/tool-heartbeat.js +43 -0
  132. package/neural-interface/public/shared/tool-list-picker.js +3 -1
  133. package/neural-interface/public/shared/tool-list-view.js +23 -4
  134. package/neural-interface/public/shared/ui-automation-studio.js +8 -1
  135. package/neural-interface/public/shared/ui-claude-panel.js +159 -29
  136. package/neural-interface/public/shared/ui-judgments.js +37 -10
  137. package/neural-interface/public/shared/ui-navbar.js +6 -0
  138. package/neural-interface/public/shared/ui-owner-access.js +191 -0
  139. package/neural-interface/public/shared/ui-owner-authority.js +162 -0
  140. package/neural-interface/public/shared/ui-sessions.js +45 -16
  141. package/neural-interface/public/shared/ui-settings.js +86 -15
  142. package/neural-interface/public/shared/ui-terminal.js +15 -7
  143. package/neural-interface/public/shared/ui-tutorial-preview.js +4 -0
  144. package/neural-interface/public/shared/ui-update.js +3 -0
  145. package/neural-interface/public/shared/ui-whiteboard.js +4 -0
  146. package/neural-interface/public/shared/window-keys.js +38 -0
  147. package/neural-interface/server.js +1160 -205
  148. package/npm-shrinkwrap.json +2 -2
  149. package/package.json +1 -1
@@ -12416,8 +12416,30 @@
12416
12416
  "kindInterrupted": "interrupted"
12417
12417
  },
12418
12418
  "ownerAuthority": {
12419
+ "peerUnavailable": "SynaBun could not check which program sent this ({reason}), so it refused to act as the owner. Reload the page to try again. If it keeps happening, start SynaBun outside any sandbox, or turn this check off with SYNABUN_PEER_IDENTITY=off in ~/.synabun/.env and restart SynaBun.",
12419
12420
  "proxyRefused": "Your browser reaches SynaBun through {name} (pid {pid}), a proxy or relay, so SynaBun can't tell it is you and refused this. Let the browser connect directly: add localhost and 127.0.0.1 to the proxy's bypass list (macOS: System Settings › Network › your network › Details › Proxies › Bypass proxy settings for these Hosts & Domains; or the list in the proxy app or browser extension), or turn the proxy off for SynaBun, then reload."
12420
12421
  },
12422
+ "ownerAuthorityNotice": {
12423
+ "label": "Owner actions paused",
12424
+ "title": "SynaBun can't verify which program is calling it, so the owner's actions are paused.",
12425
+ "body": "Settings, files, terminals, the agent panels and dispatching are refused until the check works again. Pages and memories still load.",
12426
+ "reason": "Reason: {reason}",
12427
+ "hint": "If this persists, start SynaBun outside any sandbox, or add SYNABUN_PEER_IDENTITY=off to ~/.synabun/.env and restart SynaBun (this turns the check off).",
12428
+ "reload": "Reload to retry",
12429
+ "dismiss": "Dismiss"
12430
+ },
12431
+ "ownerAccess": {
12432
+ "label": "No owner access",
12433
+ "title": "This page doesn't have owner access.",
12434
+ "bodyAutomation": "It was opened from SynaBun's automation browser, which can read SynaBun's pages but not your settings, files or actions. Open SynaBun in your own browser or the desktop app.",
12435
+ "bodyOwner": "SynaBun refused this page your settings and actions. Reload the page; if it persists, open SynaBun in your own browser or the desktop app.",
12436
+ "reload": "Reload",
12437
+ "dismiss": "Dismiss",
12438
+ "panelTitle": "No access",
12439
+ "panelBody": "This page doesn't have owner access, so this can't be shown or changed here. Open SynaBun in your own browser or the desktop app.",
12440
+ "navStatus": "No access",
12441
+ "actionDisabled": "Needs owner access"
12442
+ },
12421
12443
  "toolList": {
12422
12444
  "label": "Tools and MCP servers",
12423
12445
  "defaultTools": "Default tools",
@@ -12447,6 +12469,8 @@
12447
12469
  "noServers": "No external servers",
12448
12470
  "blockedServer": "Blocked by Agents may use it",
12449
12471
  "unavailableServer": "Unavailable on this provider",
12472
+ "unknownServer": "Not checked: the provider's MCP configuration could not be read",
12473
+ "serversUnreadable": "Could not read the MCP configuration of {providers}; servers configured only there are not listed.",
12450
12474
  "configuredExternally": "Configured in provider"
12451
12475
  },
12452
12476
  "toolGroups": {
@@ -12416,8 +12416,30 @@
12416
12416
  "kindInterrupted": "interrompido"
12417
12417
  },
12418
12418
  "ownerAuthority": {
12419
+ "peerUnavailable": "O SynaBun não conseguiu verificar qual programa enviou isto ({reason}), então se recusou a agir como o dono. Recarregue a página para tentar de novo. Se continuar acontecendo, inicie o SynaBun fora de qualquer sandbox, ou desative esta verificação com SYNABUN_PEER_IDENTITY=off em ~/.synabun/.env e reinicie o SynaBun.",
12419
12420
  "proxyRefused": "Seu navegador chega ao SynaBun por meio de {name} (pid {pid}), um proxy ou relay, então o SynaBun não consegue confirmar que é você e recusou isto. Deixe o navegador se conectar diretamente: adicione localhost e 127.0.0.1 à lista de exceções do proxy (macOS: Ajustes do Sistema › Rede › sua rede › Detalhes › Proxies › Ignorar as configurações de proxy para estes Hosts e Domínios; ou a lista do app de proxy ou da extensão do navegador), ou desative o proxy para o SynaBun e recarregue a página."
12420
12421
  },
12422
+ "ownerAuthorityNotice": {
12423
+ "label": "Ações do dono pausadas",
12424
+ "title": "O SynaBun não consegue verificar qual programa o está chamando, então as ações do dono estão pausadas.",
12425
+ "body": "Ajustes, arquivos, terminais, os painéis de agentes e o envio de tarefas são recusados até a verificação voltar a funcionar. As páginas e as memórias continuam carregando.",
12426
+ "reason": "Motivo: {reason}",
12427
+ "hint": "Se continuar, inicie o SynaBun fora de qualquer sandbox, ou adicione SYNABUN_PEER_IDENTITY=off a ~/.synabun/.env e reinicie o SynaBun (isso desativa a verificação).",
12428
+ "reload": "Recarregar para tentar de novo",
12429
+ "dismiss": "Dispensar"
12430
+ },
12431
+ "ownerAccess": {
12432
+ "label": "Sem acesso de dono",
12433
+ "title": "Esta página não tem acesso de dono.",
12434
+ "bodyAutomation": "Ela foi aberta pelo navegador de automação do SynaBun, que lê as páginas do SynaBun mas não os seus ajustes, arquivos ou ações. Abra o SynaBun no seu próprio navegador ou no app para desktop.",
12435
+ "bodyOwner": "O SynaBun recusou a esta página os seus ajustes e ações. Recarregue a página; se continuar, abra o SynaBun no seu próprio navegador ou no app para desktop.",
12436
+ "reload": "Recarregar",
12437
+ "dismiss": "Dispensar",
12438
+ "panelTitle": "Sem acesso",
12439
+ "panelBody": "Esta página não tem acesso de dono, então isto não pode ser exibido nem alterado aqui. Abra o SynaBun no seu próprio navegador ou no app para desktop.",
12440
+ "navStatus": "Sem acesso",
12441
+ "actionDisabled": "Requer acesso de dono"
12442
+ },
12421
12443
  "toolList": {
12422
12444
  "label": "Ferramentas e servidores MCP",
12423
12445
  "defaultTools": "Ferramentas padrão",
@@ -12447,6 +12469,8 @@
12447
12469
  "noServers": "Nenhum servidor externo",
12448
12470
  "blockedServer": "Bloqueado em Agentes podem usar",
12449
12471
  "unavailableServer": "Indisponível neste provedor",
12472
+ "unknownServer": "Não verificado: a configuração MCP do provedor não pôde ser lida",
12473
+ "serversUnreadable": "Não foi possível ler a configuração MCP de {providers}; servidores configurados só ali não aparecem.",
12450
12474
  "configuredExternally": "Configurado no provedor"
12451
12475
  },
12452
12476
  "toolGroups": {
@@ -19,6 +19,8 @@ import { getSessionPolicy, requiresHumanApproval } from './remote-policy.js';
19
19
  import { clampPlanDispatch, PLAN_DISPATCH_NOTE, runCanChangeCode } from './assistant-plan-permissions.js';
20
20
  import { noStore, requireJson, requireLocal, requireLocalHost, sendGuardError } from './http-guards.js';
21
21
  import { setUntrustedFileHeaders } from './untrusted-file-headers.js';
22
+ import { PEER_VERDICT, peerAuthority } from './peer-identity.js';
23
+ import { sendPeerUnavailable } from './owner-authority.js';
22
24
 
23
25
  /** The header whatsapp_send_file's caller proves it is the WhatsApp conversation's own brain with (assistant-runtime.js BRAIN_CREDENTIAL_RE). */
24
26
  export const BRAIN_CREDENTIAL_HEADER = 'x-synabun-brain-token';
@@ -160,6 +162,11 @@ export function createAssistantApi({
160
162
  // The page secret (lib/page-session.js): a request without an agent pin is the owner's page only when it carries
161
163
  // this boot's cookie; a local process that merely sends no headers is nobody (never 'ui').
162
164
  pageSession = null,
165
+ // Whether a pin counts (lib/terminal-tokens.js verdict, server.js): (pin, req) → { accepted, code, error, httpStatus }.
166
+ // A pin SynaBun gave a proof to (a run's terminal token, a brain's launch credential) counts only with it: a request
167
+ // that names a worker's run, or a brain's id, without it is refused (403 TERMINAL_TOKEN_REQUIRED / _INVALID) instead
168
+ // of reading that run as its own worker. Without it (a test, an older host) every pin is taken as it is said.
169
+ terminalVerdict = null,
163
170
  } = {}) {
164
171
  if (!dispatcher) throw new Error('createAssistantApi requires a dispatcher');
165
172
  const router = Router();
@@ -182,10 +189,18 @@ export function createAssistantApi({
182
189
  const bodySession = req.body?.assistantSessionId || req.body?.assistant_session_id || req.query?.assistantSessionId || null;
183
190
  if (!pin) {
184
191
  // The page: this boot's page secret cookie (the browser sends it by itself). Without a page session wired
185
- // (a test, an older host) every pinless request is the page, as before.
192
+ // (a test, an older host) every pinless request is the page, as before. A request whose peer could not be
193
+ // identified (macOS, the lookup failed) never verifies: it is nobody here, and its refusals say 503
194
+ // PEER_UNAVAILABLE (uiOnly, refuseRunRead) rather than a 403 the page could not cure.
186
195
  if (pageSession && typeof pageSession.verify === 'function' && !pageSession.verify(req)) return { kind: 'unknown', assistantSessionId: bodySession ? String(bodySession) : null, pin: '', pageless: true };
187
196
  return { kind: 'ui', assistantSessionId: bodySession ? String(bodySession) : null };
188
197
  }
198
+ // The pin counts only with its proof: a forged one names nobody here, not even for attribution.
199
+ let verdict = null;
200
+ try { verdict = typeof terminalVerdict === 'function' ? terminalVerdict(pin, req) : null; } catch { verdict = { accepted: false, code: 'TERMINAL_TOKEN_INVALID', error: 'The run this request names could not be checked.', httpStatus: 403 }; }
201
+ if (verdict && verdict.accepted === false) {
202
+ return { kind: 'refused', forbidden: true, pin, refusal: { status: Number(verdict.httpStatus) || 403, code: String(verdict.code || 'TERMINAL_TOKEN_INVALID'), error: String(verdict.error || 'This request names a run it cannot prove it is.') } };
203
+ }
189
204
  if (dispatcher.get(pin)) return { kind: 'worker', forbidden: true, pin };
190
205
  // The session a request claims, for attribution once a credential has proven it a brain: a Claude brain's
191
206
  // pin resolves to its session; the OpenCode brain pins assistant-oc-<24> (never taken as an id) and names
@@ -229,6 +244,7 @@ export function createAssistantApi({
229
244
  }
230
245
  function orchestrationGuard(req, res, next) {
231
246
  const caller = callerContext(req);
247
+ if (caller.refusal) return refusePin(res, caller.refusal);
232
248
  if (caller.forbidden) return res.status(403).json({ ok: false, code: 'AGENTS_NOT_PERMITTED', error: 'Dispatched workers cannot orchestrate other agents.' });
233
249
  // The user's own page (this boot's page secret cookie): the only caller that orchestrates without being a brain.
234
250
  if (caller.kind === 'ui') { req.assistantCaller = caller; return next(); }
@@ -238,7 +254,7 @@ export function createAssistantApi({
238
254
  // `X-Synabun-Terminal: assistant-*` header, or a real live session id, used to pass here as the brain.
239
255
  const brain = brainCaller(req);
240
256
  if (brain) { req.assistantCaller = brain; return next(); }
241
- return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Orchestration is the user\'s (from SynaBun\'s own page) and the Assistant\'s brain\'s: this request is neither (no page secret, no brain launch credential a live session knows).' });
257
+ return uiOnly(req, res, 'Orchestration is the user\'s (from SynaBun\'s own page) and the Assistant\'s brain\'s: this request is neither (no page secret, no brain launch credential a live session knows).');
242
258
  }
243
259
  /**
244
260
  * The caller when it is an assistant brain, else null. The one proof is the per-launch credential
@@ -255,6 +271,8 @@ export function createAssistantApi({
255
271
  try { session = runtime?.sessionForBrainCredential?.(req.get('x-synabun-brain-token')) || null; } catch { session = null; }
256
272
  if (!session) return null;
257
273
  const caller = req.assistantCaller || callerContext(req);
274
+ // A pin the request cannot prove (another brain's, a worker's, an ended one) is refused, credential or not.
275
+ if (caller.refusal) return null;
258
276
  return { ...caller, kind: 'assistant', assistantSessionId: String(session), credentialed: true };
259
277
  }
260
278
  /**
@@ -278,9 +296,34 @@ export function createAssistantApi({
278
296
  if (caller.kind === 'worker' && caller.pin && String(caller.pin) === String(runId)) return true;
279
297
  return false;
280
298
  }
281
- function refuseRunRead(res) {
299
+ /**
300
+ * The request's peer could not be identified (lib/peer-identity.js, macOS: the lookup failed), so neither the page
301
+ * secret nor a brain credential could count: the peer verdict's own reading (peerAuthority), or the page session's
302
+ * (a request that carries the secret and was never identified). → { retryable, reason } or null.
303
+ */
304
+ function peerDown(req) {
305
+ const auth = peerAuthority(req?.[PEER_VERDICT]);
306
+ if (auth.decision === 'unavailable') return auth;
307
+ try { return typeof pageSession?.peerUnavailable === 'function' ? (pageSession.peerUnavailable(req) || null) : null; } catch { return null; }
308
+ }
309
+ /** "Only the owner's page": 403 UI_ONLY, or 503 PEER_UNAVAILABLE when the caller could not be identified (a reload,
310
+ * or the brain's retry, may cure that; a refusal would not). */
311
+ function uiOnly(req, res, error) {
312
+ const down = peerDown(req);
313
+ if (down) return sendPeerUnavailable(res, req, down);
314
+ return res.status(403).json({ ok: false, code: 'UI_ONLY', error });
315
+ }
316
+ function refuseRunRead(req, res) {
317
+ const down = peerDown(req);
318
+ if (down) return sendPeerUnavailable(res, req, down);
319
+ const refused = callerContext(req).refusal;
320
+ if (refused) return refusePin(res, refused);
282
321
  return res.status(403).json({ ok: false, code: 'RUN_FORBIDDEN', error: 'This run is readable by the owner (from SynaBun\'s own page), its own worker and the Assistant brain of its session only.' });
283
322
  }
323
+ /** A request that names a run or a brain it cannot prove it is: 403 TERMINAL_TOKEN_REQUIRED / _INVALID (never a token). */
324
+ function refusePin(res, refusal) {
325
+ return res.status(refusal.status || 403).json({ ok: false, code: refusal.code, error: refusal.error });
326
+ }
284
327
  /** A remote session whose workers only a person may answer (strict worker approvals below autonomous). */
285
328
  function humanApprovalRequired(assistantSessionId) {
286
329
  if (!assistantSessionId) return false;
@@ -514,7 +557,7 @@ export function createAssistantApi({
514
557
  router.put('/routing', async (req, res) => {
515
558
  if (!requireRouter(res)) return;
516
559
  if (!configStore?.patchRouting) return res.status(503).json({ ok: false, code: 'CONFIG_UNAVAILABLE', error: 'Routing settings are read-only' });
517
- if (callerContext(req).kind !== 'ui') return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Routing settings are changed from the assistant panel only.' });
560
+ if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'Routing settings are changed from the assistant panel only.');
518
561
  try {
519
562
  const body = req.body || {};
520
563
  const patch = body.routing && typeof body.routing === 'object' ? body.routing : body;
@@ -555,7 +598,7 @@ export function createAssistantApi({
555
598
  });
556
599
  router.delete('/routing/preferences/:key', (req, res) => {
557
600
  if (!requireRouter(res)) return;
558
- if (callerContext(req).kind !== 'ui') return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Routing settings are changed from the assistant panel only.' });
601
+ if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'Routing settings are changed from the assistant panel only.');
559
602
  try {
560
603
  configStore.patchRouting({ preferences: { [req.params.key]: null } }, { taskClasses: [...Object.keys(taskClasses || {}), 'vision'] });
561
604
  broadcastSync({ type: 'assistant:routing-changed', version: configStore.version() });
@@ -600,7 +643,7 @@ export function createAssistantApi({
600
643
  router.put('/user-context', (req, res) => {
601
644
  if (!userContextReady(res)) return;
602
645
  if (!configStore.patchUserContext) return res.status(503).json({ ok: false, code: 'CONFIG_UNAVAILABLE', error: 'User context settings are read-only' });
603
- if (callerContext(req).kind !== 'ui') return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'User context settings are changed from Settings only.' });
646
+ if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'User context settings are changed from Settings only.');
604
647
  try {
605
648
  const body = req.body || {};
606
649
  const { project: _project, ...patch } = body.settings && typeof body.settings === 'object' ? body.settings : body;
@@ -620,7 +663,7 @@ export function createAssistantApi({
620
663
  });
621
664
  router.put('/budget', (req, res) => {
622
665
  if (!configStore?.patchBudget) return res.status(503).json({ ok: false, code: 'CONFIG_UNAVAILABLE', error: 'Budget settings are read-only' });
623
- if (callerContext(req).kind !== 'ui') return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Budget settings are changed from the assistant panel only.' });
666
+ if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'Budget settings are changed from the assistant panel only.');
624
667
  try {
625
668
  const body = req.body || {};
626
669
  const patch = body.budget && typeof body.budget === 'object' && !Array.isArray(body.budget) ? body.budget : null;
@@ -738,7 +781,7 @@ export function createAssistantApi({
738
781
  }
739
782
  router.post('/clarify/:requestId/answer', (req, res) => {
740
783
  if (!requireClarifier(res)) return;
741
- if (callerContext(req).kind !== 'ui') return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Clarify cards are answered by the user.' });
784
+ if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'Clarify cards are answered by the user.');
742
785
  try { res.json(clarifier.answer(req.params.requestId, cardAnswer(req), { origin: 'rest' })); } catch (error) { sendError(res, error); }
743
786
  });
744
787
  router.get('/briefs/:briefId', (req, res) => {
@@ -760,7 +803,7 @@ export function createAssistantApi({
760
803
  });
761
804
  router.post('/routes/:routeId/answer', async (req, res) => {
762
805
  if (!requireRouter(res)) return;
763
- if (callerContext(req).kind !== 'ui') return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Route cards are answered by the user.' });
806
+ if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'Route cards are answered by the user.');
764
807
  try { res.json(await assistantRouter.answer(req.params.routeId, cardAnswer(req), { origin: 'rest' })); } catch (error) { sendError(res, error); }
765
808
  });
766
809
  router.get('/sessions/:id/routes', (req, res) => {
@@ -780,7 +823,7 @@ export function createAssistantApi({
780
823
  // Listing is owner-or-brain only: a worker reads its own run by id, never the roster of every run.
781
824
  const caller = callerContext(req);
782
825
  const brain = brainCaller(req);
783
- if (caller.kind !== 'ui' && !brain) return refuseRunRead(res);
826
+ if (caller.kind !== 'ui' && !brain) return refuseRunRead(req, res);
784
827
  try {
785
828
  const active = req.query.active === '1' || req.query.activeOnly === '1';
786
829
  // A brain sees only its OWN session's runs (its session id forced over whatever the query asks); the owner's
@@ -840,7 +883,7 @@ export function createAssistantApi({
840
883
  });
841
884
 
842
885
  router.get('/runs/:runId', (req, res) => {
843
- if (!runReadAllowed(req, req.params.runId)) return refuseRunRead(res);
886
+ if (!runReadAllowed(req, req.params.runId)) return refuseRunRead(req, res);
844
887
  const run = dispatcher.get(req.params.runId);
845
888
  if (!run) return res.status(404).json({ ok: false, code: 'RUN_NOT_FOUND', error: `Unknown run ${req.params.runId}` });
846
889
  const brain = brainCaller(req);
@@ -848,7 +891,7 @@ export function createAssistantApi({
848
891
  res.json({ ok: true, run: brain ? slimRunView(run) : run });
849
892
  });
850
893
  router.get('/runs/:runId/result', (req, res) => {
851
- if (!runReadAllowed(req, req.params.runId)) return refuseRunRead(res);
894
+ if (!runReadAllowed(req, req.params.runId)) return refuseRunRead(req, res);
852
895
  try {
853
896
  const out = dispatcher.transcript(req.params.runId, { format: 'result' });
854
897
  if (out?.result) {
@@ -859,7 +902,7 @@ export function createAssistantApi({
859
902
  } catch (error) { sendError(res, error); }
860
903
  });
861
904
  router.get('/runs/:runId/transcript', (req, res) => {
862
- if (!runReadAllowed(req, req.params.runId)) return refuseRunRead(res);
905
+ if (!runReadAllowed(req, req.params.runId)) return refuseRunRead(req, res);
863
906
  try {
864
907
  const format = req.query.format || 'tail';
865
908
  const out = dispatcher.transcript(req.params.runId, {
@@ -880,7 +923,7 @@ export function createAssistantApi({
880
923
  // path from the request; owner-only like everything here. sendFile answers
881
924
  // Range requests, so a video seeks.
882
925
  router.get('/runs/:runId/media/:n', async (req, res) => {
883
- if (!runReadAllowed(req, req.params.runId)) return refuseRunRead(res);
926
+ if (!runReadAllowed(req, req.params.runId)) return refuseRunRead(req, res);
884
927
  const notFound = () => res.status(404).json({ ok: false, code: 'MEDIA_NOT_FOUND', error: `No media ${req.params.n} for run ${req.params.runId}` });
885
928
  if (!/^\d{1,4}$/.test(String(req.params.n))) return notFound();
886
929
  let file = null;
@@ -975,7 +1018,7 @@ export function createAssistantApi({
975
1018
  router.delete('/runs/:runId', async (req, res) => {
976
1019
  const caller = callerContext(req);
977
1020
  const brain = brainCaller(req);
978
- if (caller.kind !== 'ui' && !brain) return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Finished runs are removed by the owner (from SynaBun\'s own page) or the Assistant brain of the run\'s session.' });
1021
+ if (caller.kind !== 'ui' && !brain) return uiOnly(req, res, 'Finished runs are removed by the owner (from SynaBun\'s own page) or the Assistant brain of the run\'s session.');
979
1022
  if (brain && caller.kind !== 'ui') {
980
1023
  // A brain removes only the runs of its own session: another session's run is left untouched.
981
1024
  const runSession = dispatcher.get(req.params.runId)?.assistantSessionId || null;
@@ -989,7 +1032,7 @@ export function createAssistantApi({
989
1032
  try { res.json(await dispatcher.remove(req.params.runId, { assistantSessionId })); } catch (error) { sendError(res, error); }
990
1033
  });
991
1034
  router.post('/runs/clear-finished', async (req, res) => {
992
- if (callerContext(req).kind !== 'ui') return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Finished runs are removed from the assistant panel only.' });
1035
+ if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'Finished runs are removed from the assistant panel only.');
993
1036
  const body = req.body || {};
994
1037
  const assistantSessionId = body.assistantSessionId || body.assistant_session_id || null;
995
1038
  const workflowId = body.workflowId || body.workflow_id || null;
@@ -1003,7 +1046,7 @@ export function createAssistantApi({
1003
1046
  // The user closed the sidepanel tab of a worker that finished its task: completed, never "stopped
1004
1047
  // by the user" (409 RUN_NOT_FINISHED for any other run, which the tab then stops as before).
1005
1048
  router.post('/runs/:runId/tab-closed', (req, res) => {
1006
- if (callerContext(req).kind !== 'ui') return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Only the sidepanel that closed the tab reports it.' });
1049
+ if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'Only the sidepanel that closed the tab reports it.');
1007
1050
  try { res.json(dispatcher.completeClosedTab(req.params.runId)); } catch (error) { sendError(res, error); }
1008
1051
  });
1009
1052
  router.post('/runs/:runId/focus', (req, res) => {
@@ -1338,9 +1381,8 @@ export function createAssistantApi({
1338
1381
  });
1339
1382
  router.put('/admin-sandbox', requireJson, (req, res) => {
1340
1383
  if (!adminSandbox) return res.status(503).json({ ok: false, code: 'ADMIN_SANDBOX_UNAVAILABLE', error: 'The Admin sandbox setting is not available on this server' });
1341
- if (callerContext(req).kind !== 'ui' || req.get('x-synabun-desktop-grant')) {
1342
- return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Only the user can change the Admin sandbox.' });
1343
- }
1384
+ if (req.get('x-synabun-desktop-grant')) return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Only the user can change the Admin sandbox.' });
1385
+ if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'Only the user can change the Admin sandbox.');
1344
1386
  const value = req.body?.adminSandbox;
1345
1387
  if (typeof value !== 'boolean') return res.status(400).json({ ok: false, code: 'INVALID_VALUE', error: 'adminSandbox must be true or false.' });
1346
1388
  try { res.json({ ok: true, ...adminSandbox.set(value) }); } catch (error) { sendError(res, error); }
@@ -1355,9 +1397,8 @@ export function createAssistantApi({
1355
1397
  });
1356
1398
  router.put('/worker-guard', requireJson, (req, res) => {
1357
1399
  if (!workerGuard) return res.status(503).json({ ok: false, code: 'WORKER_GUARD_UNAVAILABLE', error: 'The Protect workers setting is not available on this server' });
1358
- if (callerContext(req).kind !== 'ui' || req.get('x-synabun-desktop-grant') || req.get('x-synabun-role')) {
1359
- return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Only the user can change Protect workers.' });
1360
- }
1400
+ if (req.get('x-synabun-desktop-grant') || req.get('x-synabun-role')) return res.status(403).json({ ok: false, code: 'UI_ONLY', error: 'Only the user can change Protect workers.' });
1401
+ if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'Only the user can change Protect workers.');
1361
1402
  const value = req.body?.mode;
1362
1403
  if (typeof value !== 'string' || !workerGuard.view().modes.includes(value)) return res.status(400).json({ ok: false, code: 'INVALID_VALUE', error: `mode must be one of ${workerGuard.view().modes.join(', ')}.` });
1363
1404
  try { res.json({ ok: true, ...workerGuard.set(value) }); } catch (error) { sendError(res, error); }
@@ -1,4 +1,4 @@
1
- import { EXTERNAL_SERVER_LIMITATIONS } from './mcp-external-servers.js';
1
+ import { EXTERNAL_SERVER_LIMITATIONS, externalDiscoveryError } from './mcp-external-servers.js';
2
2
  import { toolCatalogView } from '../../mcp-server/dist/services/tool-catalog.js';
3
3
  // ═══════════════════════════════════════════
4
4
  // SynaBun — Assistant model catalog (providers · models · tier · price · vision)
@@ -681,6 +681,21 @@ export function createAssistantCatalog({
681
681
  let epoch = 0; // bumped by invalidate(): a build that began before it is not kept
682
682
  let lastListed = null; // provider → signature of the rows the last build listed
683
683
 
684
+ // External servers are read degraded here (the catalog only lists): a provider whose MCP configuration
685
+ // cannot be read is reported in `errors`, its rows say `unknown`, and every other provider's servers and
686
+ // every model stay listed. Dispatch and worker launch read their own strict inventories and refuse.
687
+ // getExternalServers answers { servers, errors } or plain rows (older form).
688
+ function externalServersReport(projectRows) {
689
+ try {
690
+ const answer = getExternalServers(projectRows);
691
+ if (Array.isArray(answer)) return { servers: answer, errors: [] };
692
+ return { servers: Array.isArray(answer?.servers) ? answer.servers : [], errors: Array.isArray(answer?.errors) ? answer.errors : [] };
693
+ } catch (error) {
694
+ log('catalog:external-servers-error', error?.code || error?.message || String(error));
695
+ return { servers: [], errors: [externalDiscoveryError(error?.provider || null, error)] };
696
+ }
697
+ }
698
+
684
699
  const pickArray = (value, keys = []) => {
685
700
  if (Array.isArray(value)) return value;
686
701
  for (const key of keys) if (Array.isArray(value?.[key])) return value[key];
@@ -783,8 +798,11 @@ export function createAssistantCatalog({
783
798
  const listedNow = Object.fromEntries(CATALOG_PROVIDERS.map((p) => [p, listedSignature(all[p])]));
784
799
  const changed = lastListed ? CATALOG_PROVIDERS.filter((p) => listedNow[p] !== lastListed[p]) : [];
785
800
  lastListed = listedNow;
801
+ const external = externalServersReport(pickArray(projects, ['projects']));
786
802
  return {
787
803
  generatedAt: new Date(now()).toISOString(),
804
+ // Providers whose MCP server list could not be checked: { provider, code, reason, errno? }, no paths.
805
+ externalServerErrors: external.errors,
788
806
  // Providers whose listed models differ from the build before (not part of the value's meaning: full() reports it).
789
807
  changedProviders: changed,
790
808
  models,
@@ -801,7 +819,7 @@ export function createAssistantCatalog({
801
819
  opencodeListed: listedCounts.opencode,
802
820
  opencodeHidden: hidden.opencode,
803
821
  projects: pickArray(projects, ['projects']),
804
- tools: { ...toolCatalogView(), servers: getExternalServers(pickArray(projects, ['projects'])), externalServerLimitations: EXTERNAL_SERVER_LIMITATIONS },
822
+ tools: { ...toolCatalogView(), servers: external.servers, externalServerErrors: external.errors, externalServerLimitations: EXTERNAL_SERVER_LIMITATIONS },
805
823
  accounts,
806
824
  // Efforts are per model (row.efforts); a provider's list is the union of its rows'.
807
825
  providers: [
@@ -766,6 +766,32 @@ export function createAssistantDispatcher({
766
766
  notifyWaiters(entry.runId, reason);
767
767
  }
768
768
 
769
+ // ── browser route (a run's browser moved while it works) ───────────────────
770
+ /**
771
+ * The worker's browser session or tab changed while the run lives: SynaBun recovered a lost one, or the worker
772
+ * opened a new one with browser_session create (server.js noteAutomationBrowserRoute). The run record names the
773
+ * route it uses now, so agent_status and the panel never show the dead one. Like markDelivered, persisted WITHOUT a
774
+ * version bump or a waiter wake-up (a route change is not news a waiting brain must stop for); the panel gets the
775
+ * view. Returns false for an unknown, ended or browser-less run.
776
+ */
777
+ function noteBrowserRoute(runId, { browserSessionId = null, browserTabId = null, reason = 'recovered' } = {}) {
778
+ const entry = entries.get(runId);
779
+ if (!entry || !entry.usesBrowser || !ACTIVE_STATES.has(entry.state) || !browserSessionId) return false;
780
+ const sessionId = String(browserSessionId);
781
+ const tabId = browserTabId ? String(browserTabId) : null;
782
+ if (entry.browserSessionId === sessionId && (entry.browserTabId || null) === tabId) return true;
783
+ const was = entry.browserSessionId ? `${entry.browserSessionId}${entry.browserTabId ? ` tab ${entry.browserTabId}` : ''}` : 'none';
784
+ entry.browserSessionId = sessionId;
785
+ entry.browserTabId = tabId;
786
+ if (!Array.isArray(entry.notes)) entry.notes = [];
787
+ entry.notes.push(`browser ${reason === 'created' ? 'replaced by the worker (browser_session create)' : 'recovered by SynaBun'}: session ${sessionId}${tabId ? ` tab ${tabId}` : ''} (was ${was})`);
788
+ persist();
789
+ const payload = { type: 'assistant:dispatch', reason: 'browser_route', run: view(entry) };
790
+ try { broadcastSync(payload); } catch {}
791
+ for (const listener of listeners) { try { listener(payload); } catch {} }
792
+ return true;
793
+ }
794
+
769
795
  // ── delivery (what the owning brain already read) ──────────────────────────
770
796
  /**
771
797
  * High-water mark of the run results a brain has read (agent_wait,
@@ -3970,7 +3996,7 @@ export function createAssistantDispatcher({
3970
3996
  respondPermission, subscribe, shutdown, limits, suspendForShutdown,
3971
3997
  sessionBudget, checkSession, refreshLimits, providerSpend, coverFollowUp, budget,
3972
3998
  resolveRoute, declineRoute, heldRouteRefusal, escalate,
3973
- markDelivered, deliveryState,
3999
+ markDelivered, deliveryState, noteBrowserRoute,
3974
4000
  remove, removeFinished,
3975
4001
  mediaFile,
3976
4002
  accountInUse: (provider, accountId) => activeEntries((e) => e.provider === provider && e.accountId === accountId).length > 0,
@@ -84,6 +84,7 @@ export function toolNames(toolPrefix = 'mcp__SynaBun__') {
84
84
  remember: `${p}remember`, recall: `${p}recall`, reflect: `${p}reflect`, choice: `${p}choice`, loop: `${p}loop`,
85
85
  computer: `${p}computer`, computerApps: `${p}computer_apps`, computerAx: `${p}computer_ax`, computerStatus: `${p}computer_status`,
86
86
  browserNavigate: `${p}browser_navigate`, browserSnapshot: `${p}browser_snapshot`, browserScreenshot: `${p}browser_screenshot`, browserConsole: `${p}browser_console`,
87
+ browserSession: `${p}browser_session`,
87
88
  whatsappSendFile: `${p}whatsapp_send_file`,
88
89
  skill: `${p}skill`,
89
90
  };
@@ -40,6 +40,7 @@ import { browserToolDenial } from './browser-tool-policy.js';
40
40
  import { browserPolicyRoots } from './browser-policy-roots.js';
41
41
  import { stripFollowups } from '../public/shared/assistant/asst-followups.js';
42
42
  import { readJsonStrict } from './rulesets/fs-safe.js';
43
+ import { redactTerminalSecrets } from './terminal-token-redaction.js';
43
44
 
44
45
  export const BRAIN_PROVIDERS = new Set(['claude-code', 'codex', 'opencode', 'antigravity']);
45
46
  // Every tab is called SynaBun; the session title (the history list) comes from
@@ -93,6 +94,8 @@ export const REMOTE_ASK_EXEMPT = new Set([
93
94
  */
94
95
  export const BRAIN_CREDENTIAL_RE = /^sbb_[A-Za-z0-9_-]{43}$/;
95
96
  export function mintBrainCredential() { return `sbb_${randomBytes(32).toString('base64url')}`; }
97
+ /** The brains whose SynaBun MCP names the session id as its pin (the Claude CLI's header, agy's environment). */
98
+ const BRAIN_PIN_PROVIDERS = new Set(['claude-code', 'antigravity']);
96
99
  // An OpenCode brain of a remote session reaches the web through these on its own
97
100
  // (no SynaBun browser, no approval): the gate plugin refuses them.
98
101
  const REMOTE_OPENCODE_WEB_TOOLS = new Set(['webfetch', 'websearch', 'codesearch']);
@@ -277,6 +280,10 @@ export function createAssistantRuntime({
277
280
  phoneAuthority = null,
278
281
  // The Admin sandbox setting (lib/agent-sandbox-setting.js): global, shown in every session view.
279
282
  adminSandbox = null,
283
+ // The server's terminal tokens (lib/terminal-tokens.js): a Claude Code or Antigravity brain names its session id in
284
+ // X-Synabun-Terminal, and that id is proven by the brain's launch credential (bind), never by a second secret;
285
+ // revoked when the brain goes. (Codex and OpenCode brains name a pin server.js binds where it starts their process.)
286
+ terminalTokens = null,
280
287
  } = {}) {
281
288
  if (!dataDir) throw new Error('createAssistantRuntime requires dataDir');
282
289
  const normalizeSessionBrain = (input, defaults, options) => normalizeBrain(input, defaults, { ...options, ...toolListOptions() });
@@ -1338,6 +1345,9 @@ export function createAssistantRuntime({
1338
1345
  }
1339
1346
  function onBrainPacket(live, packet) {
1340
1347
  if (!packet || typeof packet !== 'object') return;
1348
+ // What a brain says reaches sockets, the transcript and observers only scrubbed of SynaBun's run secrets: its own
1349
+ // launch credential or a worker's terminal token an agent printed (lib/terminal-token-redaction.js).
1350
+ packet = redactTerminalSecrets(packet);
1341
1351
  const id = live.record.id;
1342
1352
  if (packet.type === 'event') {
1343
1353
  const event = packet.event || {};
@@ -2100,6 +2110,9 @@ export function createAssistantRuntime({
2100
2110
  // (lib/skills/api-v2.js principalOf) take it; whatsapp_send_file takes it and then only the active WhatsApp
2101
2111
  // conversation's session (lib/whatsapp/service.js sendFile).
2102
2112
  live.brainCredential = mintBrainCredential();
2113
+ // The brain's own pin (its session id, for the brains that name it) is proven by this same credential: its MCP
2114
+ // presents it with X-Synabun-Terminal, and a process that only names the session gets nothing (lib/terminal-tokens.js).
2115
+ if (BRAIN_PIN_PROVIDERS.has(brain.provider)) { try { terminalTokens?.bind?.(live.record.id, live.brainCredential); } catch { /* the brain starts; its pin stays as it was */ } }
2103
2116
  const cliCap = brain.provider === 'claude-code' ? brainCliCap(live) : null;
2104
2117
  const deps = {
2105
2118
  ClaudeSession, sdkVersion, PACKAGE_ROOT, handleCodexSkinWebSocket, ensureIsolatedServe, stopIsolatedServe, setupOpencodeSidepanelConfig,
@@ -2196,8 +2209,9 @@ export function createAssistantRuntime({
2196
2209
  if (identity.providerThreadId) live.record.providerThreadId = identity.providerThreadId;
2197
2210
  } catch {}
2198
2211
  live.brain = null;
2199
- // Its credential dies with it: a file send presenting it is refused from here on.
2212
+ // Its credential dies with it: a file send presenting it is refused from here on, and so is its pin.
2200
2213
  live.brainCredential = null;
2214
+ if (BRAIN_PIN_PROVIDERS.has(live.brainProvider)) { try { terminalTokens?.revoke?.(live.record.id); } catch { /* the disposal goes on */ } }
2201
2215
  if (live.brainProvider === 'codex') pollCodex(live, { force: true });
2202
2216
  // No further turn will book them: a Claude brain's provisional tokens are booked as an estimate,
2203
2217
  // any other brain's go (Codex was just polled, OpenCode settled at its turn's end).
@@ -46,6 +46,15 @@ export function dispatchInput(body) {
46
46
  return { ...body };
47
47
  }
48
48
 
49
+ // A row only an unchecked provider might hold is not offered as available.
50
+ function serverRefText(row, unchecked) {
51
+ if (!unchecked.size) return row.ref;
52
+ const elsewhere = Object.entries(row.providers || {}).some(([provider, value]) => !unchecked.has(provider) && value === 'deliverable');
53
+ return elsewhere ? row.ref : `${row.ref} (not checked)`;
54
+ }
55
+
49
56
  export function workerToolsLine(catalog = toolCatalogView()) {
50
- return `SynaBun tools for workers: pass tools: [group ids] on agent_dispatch. Always there: ${catalog.alwaysOnTools.join(', ')}. With no tools a worker gets ${catalog.default.join(', ')}. Groups: ${catalog.groups.map(group => `${group.id} (${group.count})`).join(' · ')}. Host effect: ${Object.entries(catalog.effect).map(([host, effect]) => `${host}: ${effect}`).join(', ')}. Strict hosts load exactly those groups; Claude Code and Codex always reach every SynaBun tool on demand and the list only sets their focus. Never assume a Claude Code or Codex worker lacks a group you left out. Your MCP servers: name them as mcp:<name> in tools (or mcp:* for all allowed servers). Every unnamed external server is off for that worker on Claude Code, Codex, OpenCode and Antigravity. Available server refs: ${(catalog.servers || []).filter(row => row.selectable !== false).map(row => row.ref).join(', ') || 'none listed'}.`;
57
+ const unchecked = new Set((catalog.externalServerErrors || []).map(error => error.provider || 'unknown provider'));
58
+ const notChecked = unchecked.size ? ` MCP servers not checked for ${[...unchecked].join(', ')}: that provider's MCP configuration could not be read, so its servers are not listed as available and a dispatch to it naming an mcp: ref is refused until the configuration is fixed (its models are unaffected).` : '';
59
+ return `SynaBun tools for workers: pass tools: [group ids] on agent_dispatch. Always there: ${catalog.alwaysOnTools.join(', ')}. With no tools a worker gets ${catalog.default.join(', ')}. Groups: ${catalog.groups.map(group => `${group.id} (${group.count})`).join(' · ')}. Host effect: ${Object.entries(catalog.effect).map(([host, effect]) => `${host}: ${effect}`).join(', ')}. Strict hosts load exactly those groups; Claude Code and Codex always reach every SynaBun tool on demand and the list only sets their focus. Never assume a Claude Code or Codex worker lacks a group you left out. Your MCP servers: name them as mcp:<name> in tools (or mcp:* for all allowed servers). Every unnamed external server is off for that worker on Claude Code, Codex, OpenCode and Antigravity. Available server refs: ${(catalog.servers || []).filter(row => row.selectable !== false).map(row => serverRefText(row, unchecked)).join(', ') || 'none listed'}.${notChecked}`;
51
60
  }
@@ -0,0 +1,84 @@
1
+ // ── The browser routes an automation may call (DOM-free, no imports) ──
2
+ //
3
+ // SynaBun's browser API (/api/browser) serves two callers: the owner's page (the browser panel, Settings → Browser)
4
+ // and the automations that drive the browser through SynaBun's MCP tools (loops, dispatched workers, agents, the side
5
+ // panels, a CLI window). The MCP tools call a fixed set of routes (mcp-server/src/services/neural-interface.ts: the
6
+ // session list, create and close, acquire and release, and the page actions on a session); everything else under
7
+ // /api/browser is the owner's: the browser settings (PUT /config: attach to the user's real Chrome, pick a MoreLogin
8
+ // profile), the money guard's lift (paid-surfaces), the raw CDP endpoints (cdp, claude-connect), tab management
9
+ // outside a run's own tab (tabs: list, open, activate, close), the folder picker and the profile and browser
10
+ // detection. Until 2026-11-05 a run that proved its id reached all of them, and the worker-only MCP channel forwarded
11
+ // every /browser/* path with the run's token, so a sandboxed worker could switch the default browser to the user's
12
+ // real Chrome profile or lift the money guard (review 972afb74, finding 1).
13
+ //
14
+ // This list is the one answer to "may an automation call this": the worker channel forwards nothing else
15
+ // (lib/worker-mcp-channel.js), and server.js browserTerminalGate answers every other route the owner's page only (its
16
+ // page secret, or an invite guest the guest rules let in), whatever agent headers the request carries. A route a new
17
+ // MCP tool calls is added here, with its test (tests/browser-automation-routes.test.mjs checks the list against the
18
+ // paths the MCP server's source calls).
19
+
20
+ /** One path segment of a session or tab id SynaBun mints (hex today; base64url and uuid shapes allowed). */
21
+ const ID = '[A-Za-z0-9_-]{1,128}';
22
+ /** Page actions on a session the MCP tools post (navigate, click, …). */
23
+ const POST_ACTIONS = Object.freeze([
24
+ 'navigate', 'back', 'forward', 'reload', 'click', 'fill', 'type', 'hover', 'select', 'press', 'scroll', 'upload',
25
+ 'snapshot', 'evaluate', 'extract', 'x-compose-state', 'semantic-context', 'wait', 'bluesky/upload-blob',
26
+ ]);
27
+ /** Reads of a session the MCP tools get. */
28
+ const GET_READS = Object.freeze(['snapshot', 'content', 'markdown', 'screenshot-base64', 'console']);
29
+
30
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
31
+
32
+ /** [method, path pattern relative to /api/browser] for every route an automation may call. */
33
+ export const AUTOMATION_BROWSER_ROUTES = Object.freeze([
34
+ ['GET', '/sessions'],
35
+ ['POST', '/sessions'],
36
+ ['POST', '/acquire'],
37
+ ['POST', '/release'],
38
+ ['DELETE', '/sessions/:id'],
39
+ ...POST_ACTIONS.map((action) => ['POST', `/sessions/:id/${action}`]),
40
+ ...GET_READS.map((read) => ['GET', `/sessions/:id/${read}`]),
41
+ ].map((route) => Object.freeze(route)));
42
+
43
+ const MATCHERS = AUTOMATION_BROWSER_ROUTES.map(([method, path]) => ({
44
+ method,
45
+ re: new RegExp(`^${path.split('/').map((part) => (part === ':id' ? ID : escape(part))).join('/')}/?$`),
46
+ }));
47
+
48
+ /**
49
+ * Whether an automation may call `method` `path`. `path` is relative to /api/browser (`/sessions/abc/navigate`), as
50
+ * Express's req.path is under that mount; a query string is ignored. Anything that is not exactly one of the listed
51
+ * routes is the owner's: another method, another path, an encoded or dot segment, a doubled slash.
52
+ */
53
+ export function isAutomationBrowserRoute(method, path) {
54
+ const verb = String(method || '').toUpperCase() === 'HEAD' ? 'GET' : String(method || '').toUpperCase();
55
+ const bare = String(path || '').split('?')[0];
56
+ if (!bare.startsWith('/') || bare.includes('//')) return false;
57
+ return MATCHERS.some((m) => m.method === verb && m.re.test(bare));
58
+ }
59
+
60
+ /**
61
+ * The fields of a session create that pick which browser or profile it starts (POST /api/browser/sessions): the
62
+ * owner's choice (Settings → Browser), never an automation's. An automation's create opens the default browser.
63
+ */
64
+ export const OWNER_ONLY_CREATE_FIELDS = Object.freeze(['connectMode', 'moreloginEnvId']);
65
+
66
+ /**
67
+ * Every field that names a browser, a MoreLogin profile or a browser setting (PUT /api/browser/config's fields and
68
+ * the names an agent reaches for: profile, config, a profile folder, a CDP endpoint). The owner's choice, never an
69
+ * automation's: an automation's session create naming one is refused (403 OWNER_ONLY_FIELDS), and SynaBun's browser
70
+ * MCP tools refuse a call that names one instead of dropping it (mcp-server/src/services/browser-route-flow.ts
71
+ * OWNER_ONLY_FIELDS mirrors this list; tests/browser-automation-routes.test.mjs keeps the two equal). Until
72
+ * 2026-11-05 the tools' schemas dropped them silently, so `profile: "other"` looked accepted.
73
+ */
74
+ export const OWNER_ONLY_BROWSER_FIELDS = Object.freeze([
75
+ ...OWNER_ONLY_CREATE_FIELDS, 'attachSeed', 'openTabsInBackground',
76
+ 'config', 'profile', 'profileDir', 'profilePath', 'userDataDir', 'executablePath',
77
+ 'moreloginProfile', 'moreloginEnv', 'moreloginEnvironment', 'cdpUrl', 'wsEndpoint',
78
+ ]);
79
+
80
+ /** The owner-only fields a create body names (an empty list when none). */
81
+ export function ownerOnlyCreateFields(body) {
82
+ if (!body || typeof body !== 'object') return [];
83
+ return OWNER_ONLY_BROWSER_FIELDS.filter((field) => body[field] !== undefined && body[field] !== null && body[field] !== '');
84
+ }