synabun 2.2.0 → 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 (166) hide show
  1. package/CHANGELOG.md +45 -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 +27 -0
  62. package/neural-interface/i18n/pt-BR.json +27 -0
  63. package/neural-interface/lib/assistant-api.js +64 -23
  64. package/neural-interface/lib/assistant-brains/codex.js +6 -1
  65. package/neural-interface/lib/assistant-catalog.js +20 -2
  66. package/neural-interface/lib/assistant-dispatch.js +31 -2
  67. package/neural-interface/lib/assistant-persona.js +1 -0
  68. package/neural-interface/lib/assistant-runtime.js +15 -1
  69. package/neural-interface/lib/assistant-tools.js +10 -1
  70. package/neural-interface/lib/browser-automation-routes.js +84 -0
  71. package/neural-interface/lib/browser-execution.js +16 -3
  72. package/neural-interface/lib/browser-owner.js +48 -0
  73. package/neural-interface/lib/browser-session-close.js +84 -0
  74. package/neural-interface/lib/browser-start-handoff.js +202 -0
  75. package/neural-interface/lib/browser-tool-policy.js +21 -4
  76. package/neural-interface/lib/browser-wedge-retire.js +64 -0
  77. package/neural-interface/lib/claude-agent-bridge.js +36 -1
  78. package/neural-interface/lib/claude-background-hold.js +239 -0
  79. package/neural-interface/lib/exec-loop-command.js +8 -0
  80. package/neural-interface/lib/http-guards.js +11 -6
  81. package/neural-interface/lib/loop-logger.js +6 -1
  82. package/neural-interface/lib/mcp-external-servers.js +64 -13
  83. package/neural-interface/lib/native-loop-providers.js +122 -10
  84. package/neural-interface/lib/native-loop-runtime.js +112 -11
  85. package/neural-interface/lib/opencode-native-boundary.js +155 -21
  86. package/neural-interface/lib/owner-authority.js +113 -37
  87. package/neural-interface/lib/page-session.js +81 -23
  88. package/neural-interface/lib/peer-identity.js +311 -47
  89. package/neural-interface/lib/provider-panel-api-key-auth.js +7 -2
  90. package/neural-interface/lib/pty-host/core.js +36 -0
  91. package/neural-interface/lib/pty-host/protocol.js +2 -0
  92. package/neural-interface/lib/skills/api-v2.js +13 -2
  93. package/neural-interface/lib/skills/creation-api.js +3 -1
  94. package/neural-interface/lib/skills/evals-api.js +5 -1
  95. package/neural-interface/lib/social-write-pacing.js +151 -0
  96. package/neural-interface/lib/terminal-token-redaction.js +293 -0
  97. package/neural-interface/lib/terminal-tokens.js +359 -0
  98. package/neural-interface/lib/worker-mcp-channel.js +45 -10
  99. package/neural-interface/package-lock.json +2 -2
  100. package/neural-interface/package.json +1 -1
  101. package/neural-interface/public/shared/agy/agy-render.js +41 -1
  102. package/neural-interface/public/shared/agy/agy-styles.js +5 -0
  103. package/neural-interface/public/shared/api.js +1 -0
  104. package/neural-interface/public/shared/assistant/asst-api.js +14 -2
  105. package/neural-interface/public/shared/assistant/asst-computer.js +73 -4
  106. package/neural-interface/public/shared/assistant/asst-limit-wait.js +3 -1
  107. package/neural-interface/public/shared/assistant/asst-motion-gate.js +80 -0
  108. package/neural-interface/public/shared/assistant/asst-panel.js +8 -4
  109. package/neural-interface/public/shared/assistant/asst-render.js +72 -11
  110. package/neural-interface/public/shared/assistant/asst-scene-styles.js +55 -23
  111. package/neural-interface/public/shared/assistant/asst-scenes.js +225 -79
  112. package/neural-interface/public/shared/assistant/asst-sidepanel-styles.js +4 -4
  113. package/neural-interface/public/shared/assistant/asst-style-cache.js +44 -0
  114. package/neural-interface/public/shared/assistant/asst-styles.js +26 -5
  115. package/neural-interface/public/shared/cdx/cdx-render.js +73 -7
  116. package/neural-interface/public/shared/cdx/cdx-tabs.js +3 -3
  117. package/neural-interface/public/shared/cp/cp-agents.js +8 -0
  118. package/neural-interface/public/shared/cp/cp-permissions.js +18 -2
  119. package/neural-interface/public/shared/cp/cp-rehydrate.js +25 -1
  120. package/neural-interface/public/shared/cp/cp-tasks-model.js +33 -0
  121. package/neural-interface/public/shared/judgments-log-origins.js +29 -0
  122. package/neural-interface/public/shared/loading-teardown.js +34 -0
  123. package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
  124. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +6 -1
  125. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +13 -0
  126. package/neural-interface/public/shared/ocp-v2/ocp-v2-icons.js +3 -1
  127. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +5 -2
  128. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +16 -86
  129. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +6 -0
  130. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +88 -72
  131. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +5 -2
  132. package/neural-interface/public/shared/owner-access.js +134 -0
  133. package/neural-interface/public/shared/owner-authority-view.js +92 -0
  134. package/neural-interface/public/shared/page-session.js +143 -14
  135. package/neural-interface/public/shared/poll-backoff.js +59 -0
  136. package/neural-interface/public/shared/settings/settings-data.js +6 -1
  137. package/neural-interface/public/shared/settings/settings-kit.js +11 -3
  138. package/neural-interface/public/shared/settings/settings-shell.js +7 -0
  139. package/neural-interface/public/shared/shown-children.js +72 -0
  140. package/neural-interface/public/shared/static-bg-state.js +22 -0
  141. package/neural-interface/public/shared/storage-retry.js +47 -0
  142. package/neural-interface/public/shared/storage.js +25 -4
  143. package/neural-interface/public/shared/styles.css +109 -8
  144. package/neural-interface/public/shared/synabun-mascot.js +27 -8
  145. package/neural-interface/public/shared/synabun-ticker.js +147 -12
  146. package/neural-interface/public/shared/synabun-tools.js +173 -0
  147. package/neural-interface/public/shared/tool-heartbeat.js +43 -0
  148. package/neural-interface/public/shared/tool-list-picker.js +3 -1
  149. package/neural-interface/public/shared/tool-list-view.js +23 -4
  150. package/neural-interface/public/shared/ui-automation-studio.js +8 -1
  151. package/neural-interface/public/shared/ui-claude-panel.js +238 -90
  152. package/neural-interface/public/shared/ui-judgments.js +37 -10
  153. package/neural-interface/public/shared/ui-loading.js +5 -4
  154. package/neural-interface/public/shared/ui-navbar.js +6 -0
  155. package/neural-interface/public/shared/ui-owner-access.js +191 -0
  156. package/neural-interface/public/shared/ui-owner-authority.js +162 -0
  157. package/neural-interface/public/shared/ui-sessions.js +45 -16
  158. package/neural-interface/public/shared/ui-settings.js +86 -15
  159. package/neural-interface/public/shared/ui-terminal.js +15 -7
  160. package/neural-interface/public/shared/ui-tutorial-preview.js +4 -0
  161. package/neural-interface/public/shared/ui-update.js +3 -0
  162. package/neural-interface/public/shared/ui-whiteboard.js +4 -0
  163. package/neural-interface/public/shared/window-keys.js +38 -0
  164. package/neural-interface/server.js +1240 -238
  165. package/npm-shrinkwrap.json +2 -2
  166. package/package.json +1 -1
@@ -6,12 +6,14 @@
6
6
 
7
7
  import { AsyncLocalStorage } from 'node:async_hooks';
8
8
  import { randomUUID } from 'node:crypto';
9
+ import { BrowserRouteLost, currentRouteFlow, noteRouteReplaced, type RouteLoss, type RouteRef } from './browser-route-flow.js';
9
10
 
10
11
  import {
11
12
  type CallerIdentity,
12
13
  getIdentity,
13
14
  effectivePins,
14
15
  terminalIdFor,
16
+ terminalHeaders,
15
17
  callerBrainCredential,
16
18
  callerRole,
17
19
  setReleaseHook,
@@ -23,7 +25,33 @@ const BASE_URL = process.env.NEURAL_INTERFACE_URL
23
25
  || `http://localhost:${process.env.NEURAL_PORT || '3344'}`;
24
26
  const DEFAULT_TIMEOUT = 10_000;
25
27
  const LONG_TIMEOUT = 30_000;
26
- const SESSION_CREATE_TIMEOUT = 70_000;
28
+ // A browser start (create, acquire, a run's recovery) is answered by the server within its request budget
29
+ // (neural-interface/lib/browser-execution.js BROWSER_REQUEST_MAX_MS, 120 s): the session, or BROWSER_STARTING while a
30
+ // cold MoreLogin start is still running (it can wait two minutes for the app), with the start kept for this caller's
31
+ // next request (lib/browser-start-handoff.js). This waits longer than that budget, so the answer read is the server's,
32
+ // never a timeout of its own that left the start running unseen (70 s before 2026-11-04).
33
+ const SESSION_CREATE_TIMEOUT = 150_000;
34
+
35
+ /**
36
+ * What an agent does when its browser session or tab is gone and no replacement was made for it: the rule of the
37
+ * browser policy (neural-interface/lib/browser-tool-policy.js browserSessionLossRule), in the answer itself.
38
+ */
39
+ export const LOST_ROUTE_HINT = 'Call browser_session with action "create" to open a new browser tab and continue there (pass its sessionId and tabId from then on, if you pass ids); only if that fails too, stop and report it. Never switch to another browser or tool.';
40
+
41
+ /** The server answered that the browser is still starting (lib/browser-start-handoff.js): nothing failed. */
42
+ export function isBrowserStarting(result: NiResponse | null | undefined): boolean {
43
+ return !!result && (result.starting === true || result.code === 'BROWSER_STARTING');
44
+ }
45
+
46
+ /**
47
+ * browser_navigate's own session (auto-create) while the browser is still starting: nothing failed, and the server keeps
48
+ * that start for this caller, so the next call gets it (never a second browser). Before 2026-11-04 this read
49
+ * "Failed to auto-create session: …" and agents gave up or reached for another browser.
50
+ */
51
+ export const AUTO_CREATE_STARTING = 'The browser is still starting (a cold MoreLogin start can take about two minutes); nothing failed. Call browser_navigate again in a moment: it opens the page in that browser as soon as it is ready and never starts a second one.';
52
+
53
+ /** A route, or why there is none (`starting`: the browser is still starting, not a failure). */
54
+ type RouteOrError = { sessionId: string; tabId?: string } | { error: string; starting?: boolean };
27
55
  // Existing engagement spacing can consume 90 seconds before the click begins.
28
56
  const CLICK_TIMEOUT = 120_000;
29
57
 
@@ -126,6 +154,11 @@ export interface NiResponse {
126
154
  error?: string;
127
155
  tabRecovered?: boolean;
128
156
  sessionInvalidated?: boolean;
157
+ /** The server closed this wedged tab (and kept its session, which other runs use): the next call gets a new tab. */
158
+ wedgedTabRetired?: boolean;
159
+ /** The session or tab the request named was gone, and request() sent it to this replacement route instead.
160
+ * A caller that holds a session id across several requests must use this route from now on. */
161
+ rerouted?: { sessionId: string; tabId: string | null };
129
162
  [key: string]: unknown;
130
163
  }
131
164
 
@@ -159,7 +192,9 @@ async function requestOnce(
159
192
  // Per-caller routing identity: the server maps this to the caller's owned
160
193
  // tab (_tabOwners) so tab-less browser calls never land on another
161
194
  // automation's tab. Derived per-request over HTTP, per-process for stdio.
162
- headers['X-Synabun-Terminal'] = terminalIdFor(getIdentity());
195
+ // A run's pin travels with its terminal token (X-Synabun-Terminal-Token),
196
+ // without which the browser routes refuse to act as that run.
197
+ Object.assign(headers, terminalHeaders(getIdentity()));
163
198
  // Assistant runtimes forward their role so /api/assistant/* can tell an
164
199
  // orchestrator apart from a worker run (workers must never dispatch).
165
200
  const role = callerRole();
@@ -225,25 +260,59 @@ async function requestOnce(
225
260
  }
226
261
  }
227
262
 
263
+ /** A browser request the server refused before starting anything, because its session or tab is gone. */
264
+ export function isMissingRoute(result: NiResponse | null | undefined): boolean {
265
+ return !!result && result.actionStarted === false
266
+ && (result.code === 'SESSION_NOT_FOUND' || result.code === 'TAB_NOT_FOUND');
267
+ }
268
+
269
+ /**
270
+ * `recover: false` — a missing session or tab is answered as it is, never sent on to a replacement route: for a
271
+ * caller that must prepare a page before it runs something there (a Bluesky script needs a bsky.app document, a
272
+ * replacement tab is about:blank) and recovers by itself (refreshSession).
273
+ */
228
274
  async function request(
229
275
  method: string,
230
276
  path: string,
231
277
  body?: Record<string, unknown>,
232
278
  timeout = DEFAULT_TIMEOUT,
279
+ opts: { recover?: boolean } = {},
233
280
  ): Promise<NiResponse> {
281
+ const match = /^\/api\/browser\/sessions\/([^/?]+)\/(.+)$/.exec(path);
282
+ // A tool call whose page was lost runs nothing more on a tab (browser-route-flow.ts): a later step would run on
283
+ // the blank replacement and answer for a page that is not there.
284
+ const flow = currentRouteFlow();
285
+ const guarded = !!flow && flow.policy !== 'follow' && !!match;
286
+ if (guarded && flow!.loss) throw new BrowserRouteLost(flow!.loss);
234
287
  const result = await requestOnce(method, path, body, timeout);
235
288
  const context = batchContext.getStore();
236
- const missingRoute = result.actionStarted === false
237
- && (result.code === 'SESSION_NOT_FOUND' || result.code === 'TAB_NOT_FOUND');
238
- const match = /^\/api\/browser\/sessions\/([^/?]+)\/(.+)$/.exec(path);
239
- if (isBrowserV2Enabled() && missingRoute && match) {
289
+ const missingRoute = isMissingRoute(result);
290
+ const routeOf = (): RouteLoss['from'] => {
291
+ const tabId = typeof body?.tabId === 'string' ? body.tabId : new URL(path, BASE_URL).searchParams.get('tabId');
292
+ return { sessionId: match![1], tabId: tabId || null };
293
+ };
294
+ const stepOf = () => match![2].split('?')[0];
295
+ if (guarded && !context && result.error
296
+ && (result.tabRecovered === true || result.wedgedTabRetired === true || result.sessionInvalidated === true)) {
297
+ // The step failed and the server reset the wedged page to about:blank under the same tab id, or closed the tab
298
+ // or the session: the page is gone. (A screenshot that worked can retire its tab too: it keeps its answer, and
299
+ // the next step finds the tab gone.)
300
+ flow!.loss = { reason: result.tabRecovered === true ? 'reset' : 'retired', step: stepOf(), from: routeOf() };
301
+ throw new BrowserRouteLost(flow!.loss);
302
+ }
303
+ if (isBrowserV2Enabled() && missingRoute && match && opts.recover !== false) {
240
304
  const id = getIdentity();
241
305
  const cached = resolvedRoutes.get(id);
242
306
  resolvedRoutes.delete(id);
243
307
  // Batches are pinned to their original tab and never recover midway.
244
308
  const pinnedSession = effectivePins(id).browserSessionId || id.state.ancestorPinnedSession;
309
+ // The run's pinned session, or the one its route moved to (a recovery, its own browser_session create), named by
310
+ // hand: both are the run's own route, recovered the same way.
245
311
  if (!context && cached?.route.sessionId === match[1]
246
- && (!cached.sessionId || cached.sessionId === pinnedSession)) {
312
+ && (!cached.sessionId || cached.sessionId === pinnedSession
313
+ || (!!pinnedSession && cached.sessionId === id.state.recoveredSessionId))) {
314
+ // The route that failed: the replacement's notice names it (announceReplacement).
315
+ id.state.lostRoute = routeOf();
247
316
  // Clear unpinned fast-mode state too: a force-refresh must not reuse it.
248
317
  if (id.state.interactiveSessionId === match[1]) {
249
318
  id.state.interactiveSessionId = null;
@@ -253,19 +322,48 @@ async function request(
253
322
  const refreshed = await resolutionRefresh.run(true, () => resolveSession(
254
323
  cached.sessionId, cached.autoCreate, cached.tabId, { platform: cached.platform === true },
255
324
  ));
325
+ if (!('error' in refreshed) && guarded) {
326
+ // The replacement tab is ready for the next call; this call stops here (or runs again from the start).
327
+ const from = routeOf();
328
+ const replaced = refreshed.sessionId !== from.sessionId || (refreshed.tabId || null) !== from.tabId;
329
+ flow!.loss = { reason: 'gone', step: stepOf(), from, ...(replaced && { to: { sessionId: refreshed.sessionId, tabId: refreshed.tabId || null } }) };
330
+ throw new BrowserRouteLost(flow!.loss);
331
+ }
256
332
  if (!('error' in refreshed)) {
257
333
  const nextPath = path.replace(`/sessions/${match[1]}/`, `/sessions/${refreshed.sessionId}/`);
258
334
  const nextBody = body ? { ...body, tabId: refreshed.tabId } : undefined;
259
335
  const url = new URL(nextPath, BASE_URL);
260
336
  if (refreshed.tabId) url.searchParams.set('tabId', refreshed.tabId);
261
337
  else url.searchParams.delete('tabId');
262
- return requestOnce(method, `${url.pathname}${url.search}`, nextBody, timeout);
338
+ const retried = await requestOnce(method, `${url.pathname}${url.search}`, nextBody, timeout);
339
+ // Say where it went: a tool that keeps the old session id for its next request would get "Session not
340
+ // found" there (bluesky.ts probed the replacement tab, then navigated the closed session, 2026-11-04).
341
+ const rerouted = { sessionId: refreshed.sessionId, tabId: refreshed.tabId || null };
342
+ if (flow) flow.rerouted = rerouted;
343
+ // The call ran on the replacement: its answer starts with a notice (once; resolution may have raised it).
344
+ announceReplacement(id, rerouted, routeOf());
345
+ return { ...retried, rerouted };
263
346
  }
264
347
  // Recovery failed: report why (e.g. "MoreLogin connect failed: …"), not the
265
348
  // bare "Session not found" that triggered it. Nothing was started.
266
- return { ...result, error: refreshed.error, recoveryFailed: true };
349
+ const starting = (refreshed as { starting?: boolean }).starting === true;
350
+ if (guarded) {
351
+ // Every later step of this tool would find the same dead route: the call stops here and says what happened
352
+ // (routeLossMessage: still starting, or create a tab of your own).
353
+ // The loss message says what to do; the hint the recovery's error carries would say it twice.
354
+ const why = refreshed.error.replace(`\n${LOST_ROUTE_HINT}`, '').trim();
355
+ flow!.loss = { reason: 'gone', step: stepOf(), from: routeOf(), recovery: { error: why, ...(starting && { starting: true }) } };
356
+ throw new BrowserRouteLost(flow!.loss);
357
+ }
358
+ return { ...result, error: refreshed.error, recoveryFailed: true, ...(starting && { starting: true }) };
267
359
  }
268
360
  }
361
+ if (guarded && !context && missingRoute && opts.recover !== false) {
362
+ // Gone, and not a route this caller resolved (a session id named by hand, v2 off): no replacement here; the
363
+ // call stops instead of polling a tab that does not exist until its own timeout.
364
+ flow!.loss = { reason: 'gone', step: stepOf(), from: routeOf() };
365
+ throw new BrowserRouteLost(flow!.loss);
366
+ }
269
367
  // The server refused a session that does not serve the default browser (the
270
368
  // settings changed under a cached route): forget it, so the next call resolves
271
369
  // the default browser. Not retried here: the page the call meant is in the other browser.
@@ -278,11 +376,17 @@ async function request(
278
376
  }
279
377
  if (id.state.affinitySessionId === match[1]) id.state.affinitySessionId = null;
280
378
  }
281
- if (context && result.error) context.errors.push(result);
282
- else if (context && typeof result.snapshotError === 'string') {
283
- context.errors.push({ error: result.snapshotError, code: 'SNAPSHOT_FAILED' });
379
+ // Gone, and nothing replaced it here (a batch, a session named by hand, v2 off): the answer says what to do, so the
380
+ // agent opens a new tab instead of giving up or reaching for another browser. A caller that recovers by itself
381
+ // (recover: false) gets the refusal as it is.
382
+ const answered = missingRoute && opts.recover !== false
383
+ ? { ...result, error: `${result.error || 'The browser session or tab is gone'}. ${LOST_ROUTE_HINT}` }
384
+ : result;
385
+ if (context && answered.error) context.errors.push(answered);
386
+ else if (context && typeof answered.snapshotError === 'string') {
387
+ context.errors.push({ error: answered.snapshotError, code: 'SNAPSHOT_FAILED' });
284
388
  }
285
- return result;
389
+ return answered;
286
390
  }
287
391
 
288
392
  /**
@@ -309,7 +413,7 @@ async function postRuntimeReport(path: string, body: Record<string, unknown>): P
309
413
  const controller = new AbortController();
310
414
  const timer = setTimeout(() => controller.abort(), RUNTIME_REPORT_TIMEOUT);
311
415
  try {
312
- const headers: Record<string, string> = { 'Content-Type': 'application/json', 'X-Synabun-Terminal': terminalIdFor(getIdentity()) };
416
+ const headers: Record<string, string> = { 'Content-Type': 'application/json', ...terminalHeaders(getIdentity()) };
313
417
  const role = callerRole();
314
418
  if (role) headers['X-Synabun-Role'] = role;
315
419
  const res = await fetch(`${BASE_URL}${path}`, { method: 'POST', headers, body: JSON.stringify(body), signal: controller.signal });
@@ -380,26 +484,157 @@ export async function reportRuntimeTools(
380
484
 
381
485
  // Join the ONE shared browser with a dedicated, owned tab (instead of launching a
382
486
  // second browser on a persistent profile, which fails with "profile is locked").
383
- async function acquireInteractive(id: CallerIdentity, url?: string): Promise<{ sessionId: string; tabId?: string } | { error: string }> {
487
+ async function acquireInteractive(id: CallerIdentity, url?: string): Promise<RouteOrError> {
488
+ // The tab is owned by the id this caller routes as (X-Synabun-Terminal): the server checks an explicit tab against
489
+ // that header, so a tab filed under the process's client id was refused to a run with a terminal pin and no browser
490
+ // pin (a native run without a browser, a brain's MCP child) as "another owner's".
384
491
  const resp = await request('POST', '/api/browser/acquire', {
385
- clientId: id.clientId,
492
+ clientId: terminalIdFor(id),
386
493
  url: url || 'about:blank',
387
494
  }, SESSION_CREATE_TIMEOUT);
495
+ // Still starting (a cold MoreLogin start): nothing failed, and the tab is kept for this caller's next request.
496
+ if (isBrowserStarting(resp)) return { error: String(resp.error || 'The browser is still starting. Call the browser tool again in a moment.'), starting: true };
388
497
  if (resp.error || !resp.sessionId) {
389
498
  return { error: `Failed to acquire a shared browser tab: ${resp.error || 'no session returned'}` };
390
499
  }
391
500
  id.state.interactiveSessionId = resp.sessionId as string;
392
501
  id.state.interactiveTabId = (resp.tabId as string) || null;
393
502
  id.state.affinitySessionId = id.state.interactiveSessionId;
503
+ // A tab of its own again, after the one it had went away: the call says so.
504
+ if (id.state.lostRoute) announceReplacement(id, { sessionId: id.state.interactiveSessionId, tabId: id.state.interactiveTabId });
394
505
  return { sessionId: id.state.interactiveSessionId, tabId: id.state.interactiveTabId || undefined };
395
506
  }
396
507
 
397
508
  function adoptCreatedSession(id: CallerIdentity, created: NiResponse, tabId?: string): { sessionId: string; tabId?: string } {
398
509
  const sessionId = created.sessionId as string;
399
510
  id.state.affinitySessionId = sessionId;
511
+ if (id.state.lostRoute) {
512
+ announceReplacement(id, { sessionId, tabId: tabId || (typeof created.tabId === 'string' ? created.tabId : null) });
513
+ }
400
514
  return { sessionId, tabId };
401
515
  }
402
516
 
517
+ /** Old tab ids this caller still names after they were replaced: kept small (the latest ones). */
518
+ const REPLACED_TABS_MAX = 16;
519
+
520
+ /**
521
+ * This call is served by a replacement route (`to`) for one that went away (`from`, else the caller's lostRoute):
522
+ * its answer starts with a notice that names both (browser-route-flow.ts noteRouteReplaced), once per replacement,
523
+ * and a later call that still names the old tab goes to the new one. A replacement that is the lost route itself (a
524
+ * recovery that handed the same tab back) is not one.
525
+ */
526
+ function announceReplacement(
527
+ id: CallerIdentity,
528
+ to: { sessionId: string; tabId?: string | null },
529
+ from?: RouteRef | null,
530
+ kind: 'lost' | 'moved' = 'lost',
531
+ ): void {
532
+ const lost = from || id.state.lostRoute;
533
+ id.state.lostRoute = null;
534
+ const next = { sessionId: to.sessionId, tabId: to.tabId || null };
535
+ if (lost && lost.sessionId === next.sessionId && (lost.tabId || null) === next.tabId) return;
536
+ // A tab that is still open (`moved`) was not lost: status reports the move (routeMoved), not a lost tab.
537
+ if (kind === 'lost' && lost?.tabId && next.tabId) {
538
+ id.state.replacedTabs.delete(lost.tabId);
539
+ id.state.replacedTabs.set(lost.tabId, next);
540
+ while (id.state.replacedTabs.size > REPLACED_TABS_MAX) id.state.replacedTabs.delete(id.state.replacedTabs.keys().next().value as string);
541
+ }
542
+ noteRouteReplaced({ kind, from: lost ? { sessionId: lost.sessionId, tabId: lost.tabId || null } : null, to: next });
543
+ }
544
+
545
+ /**
546
+ * The route this caller knew before a repin: the one it moved to earlier, else the one it last served a call on, else
547
+ * its launch pin. A route without a tab id is known by its session only.
548
+ */
549
+ function knownRoute(id: CallerIdentity): { sessionId: string; tabId: string | null } | null {
550
+ if (id.state.recoveredSessionId) return { sessionId: id.state.recoveredSessionId, tabId: id.state.recoveredTabId };
551
+ if (id.state.servedRoute) return id.state.servedRoute;
552
+ const pins = effectivePins(id);
553
+ const session = pins.browserSessionId || id.state.ancestorPinnedSession;
554
+ return session ? { sessionId: session, tabId: pins.browserTabId || id.state.ancestorPinnedTab || null } : null;
555
+ }
556
+
557
+ /**
558
+ * Whether `to` is a different route than `from`: another session, or another tab when both tab ids are known. A
559
+ * route it learns where it knew only the session (a pin without a tab) is the same route, not a move.
560
+ */
561
+ function isOtherRoute(from: { sessionId: string; tabId: string | null } | null, to: { sessionId: string; tabId: string | null }): boolean {
562
+ if (!from) return false;
563
+ return from.sessionId !== to.sessionId || (!!from.tabId && !!to.tabId && from.tabId !== to.tabId);
564
+ }
565
+
566
+ /** A pinned caller's route moves here (a recovery, its own browser_session create, a session of its own named by id). */
567
+ function repin(id: CallerIdentity, sessionId: string, tabId?: string | null): void {
568
+ const to = { sessionId, tabId: tabId || null };
569
+ const from = knownRoute(id);
570
+ // A move from a tab it knew (status says Replaced while it is current); adopting the route it was launched with, or
571
+ // the first one it learns, is not one.
572
+ if (from && isOtherRoute(from, to)) id.state.routeMoved = { from, to };
573
+ id.state.recoveredSessionId = sessionId;
574
+ id.state.recoveredTabId = tabId || null;
575
+ resolvedRoutes.delete(id);
576
+ }
577
+
578
+ /**
579
+ * The open tab this caller owns in `sessionId` (the server's tabOwners, under its routing id or its client id): the
580
+ * tab it named when that is one of its own and open, else its first open one (a tab it named that closed, or that is
581
+ * another owner's, is never returned). null for a session it has no open tab in, or one that is not the default browser.
582
+ */
583
+ function ownedTabIn(listing: NiResponse, sessionId: string, id: CallerIdentity, tabId?: string): string | null {
584
+ const session = ((listing.sessions || []) as BrowserSessionInfo[]).find(s => s.id === sessionId);
585
+ if (!session || !servesDefault(session)) return null;
586
+ const owners = session.tabOwners || {};
587
+ const mine = [owners[terminalIdFor(id)], owners[id.clientId]].filter((t): t is string => typeof t === 'string' && t.length > 0);
588
+ const open = (t: string) => !session.tabs || session.tabs.some(x => x.id === t);
589
+ if (tabId && mine.includes(tabId) && open(tabId)) return tabId;
590
+ return mine.find(open) || null;
591
+ }
592
+
593
+ /**
594
+ * A pinned run moved by itself to a tab it owns (ids of a session of its own, named by hand): the server records it
595
+ * as the run's route (POST /api/loop/recover-browser `adopt`), so a later MCP process of the run (a Codex turn, a
596
+ * restarted stdio child) follows it through yourRoute instead of the route the server knew before. Only a server
597
+ * that says it records it (`adoptRoute` in its session list): an older one would read the request as a recovery and
598
+ * open one more tab. Best-effort: the move holds in this process either way.
599
+ */
600
+ async function recordOwnRoute(id: CallerIdentity, listing: NiResponse, sessionId: string, tabId: string): Promise<void> {
601
+ if (listing.adoptRoute !== true) return;
602
+ const terminalSessionId = effectivePins(id).terminalSessionId || id.state.ancestorPinnedTerminal || undefined;
603
+ if (!terminalSessionId) return;
604
+ const recorded = await request('POST', '/api/loop/recover-browser', { terminalSessionId, adopt: { sessionId, tabId } });
605
+ if (recorded.error) console.error(`[MCP] the run's move to session ${sessionId} tab ${tabId} was not recorded: ${recorded.error}`);
606
+ }
607
+
608
+ /**
609
+ * A pinned run gets a new tab of its own in SynaBun's shared browser (POST /api/loop/recover-browser), started when
610
+ * none runs. `lost`: the route it found gone (the server hands back the run's current route when that one is still
611
+ * open, e.g. after another MCP process of the run recovered first). `reason: 'create'`: the run's own
612
+ * browser_session create, always a new tab. The server records the move on the run (state file, run record).
613
+ */
614
+ async function recoverRunBrowser(
615
+ id: CallerIdentity,
616
+ lost: { sessionId?: string; tabId?: string } | null,
617
+ reason?: 'create',
618
+ ): Promise<NiResponse> {
619
+ const pins = effectivePins(id);
620
+ const terminalSessionId = pins.terminalSessionId || id.state.ancestorPinnedTerminal || undefined;
621
+ const body: Record<string, unknown> = {};
622
+ if (terminalSessionId) body.terminalSessionId = terminalSessionId;
623
+ if (reason) body.reason = reason;
624
+ if (lost?.sessionId) body.lost = { sessionId: lost.sessionId, tabId: lost.tabId || null };
625
+ const recovered = await request('POST', '/api/loop/recover-browser', body, SESSION_CREATE_TIMEOUT);
626
+ if (!recovered.error && typeof recovered.sessionId === 'string' && !isBrowserStarting(recovered)) {
627
+ const tabId = typeof recovered.tabId === 'string' ? recovered.tabId : null;
628
+ repin(id, recovered.sessionId, tabId);
629
+ // A recovery (a new tab, or the route another process of the run moved to: `current`) serves this call; the
630
+ // run's own create is not a replacement it has to be told about.
631
+ if (reason === 'create') id.state.lostRoute = null;
632
+ else announceReplacement(id, { sessionId: recovered.sessionId, tabId },
633
+ id.state.lostRoute || (lost?.sessionId ? { sessionId: lost.sessionId, tabId: lost.tabId || null } : null));
634
+ }
635
+ return recovered;
636
+ }
637
+
403
638
  // Pages (localhost included) only run where the server says the default browser
404
639
  // is. Absent servesDefault (older server, or a managed / real-Chrome setup) keeps
405
640
  // the previous behavior.
@@ -420,11 +655,15 @@ function describeDefault(list: NiResponse): string {
420
655
  // Also registered as the identity-eviction hook (HTTP DELETE / idle TTL).
421
656
  function releaseTabFor(id: CallerIdentity): void {
422
657
  if (!id.state.interactiveSessionId) return;
658
+ // The id the tab was acquired under (acquireInteractive), as the caller it is: the server releases a caller's own
659
+ // tabs only, and a run's only with its terminal token (a stdio child's own; an HTTP identity evicted outside any
660
+ // request has none, and the run's end releases its tabs on the server anyway).
661
+ const owner = terminalIdFor(id);
423
662
  try {
424
663
  void fetch(`${BASE_URL}/api/browser/release`, {
425
664
  method: 'POST',
426
- headers: { 'Content-Type': 'application/json' },
427
- body: JSON.stringify({ clientId: id.clientId }),
665
+ headers: { 'Content-Type': 'application/json', ...terminalHeaders(id) },
666
+ body: JSON.stringify({ clientId: owner }),
428
667
  }).catch(() => {});
429
668
  } catch { /* best-effort */ }
430
669
  }
@@ -534,7 +773,7 @@ async function resolveSessionUncached(
534
773
  autoCreate?: { url?: string },
535
774
  tabId?: string,
536
775
  platform = false,
537
- ): Promise<{ sessionId: string; tabId?: string } | { error: string }> {
776
+ ): Promise<RouteOrError> {
538
777
  // Per-caller identity: pins come from launch headers (HTTP) or live env
539
778
  // (stdio); all caches below live on the identity, never module-level.
540
779
  const id = getIdentity();
@@ -546,8 +785,10 @@ async function resolveSessionUncached(
546
785
  // tool is refused, since the page it names is in the other browser. The
547
786
  // server refuses them too (NOT_DEFAULT_BROWSER).
548
787
  const wantsDefaultBrowser = platform || !!autoCreate;
788
+ let namedListing: NiResponse | null = null;
549
789
  if (sessionId && sessionId !== (pins.browserSessionId || id.state.ancestorPinnedSession)) {
550
790
  const listed = await request('GET', '/api/browser/sessions');
791
+ namedListing = listed;
551
792
  const named = ((listed.sessions || []) as BrowserSessionInfo[]).find(s => s.id === sessionId);
552
793
  if (named && !servesDefault(named)) {
553
794
  if (!wantsDefaultBrowser) {
@@ -568,7 +809,7 @@ async function resolveSessionUncached(
568
809
  await resolveFromAncestors(id);
569
810
  }
570
811
  const pinnedTab = pins.browserTabId || id.state.ancestorPinnedTab || undefined;
571
- const resolvedTabId = pinnedTab || tabId || undefined;
812
+ let resolvedTabId = pinnedTab || tabId || undefined;
572
813
  if (pinnedTab && tabId && tabId !== pinnedTab) {
573
814
  console.error(`[MCP] tabId override ignored: pinned=${pinnedTab} requested=${tabId}`);
574
815
  }
@@ -577,23 +818,76 @@ async function resolveSessionUncached(
577
818
  // this caller to a specific browser session (multi-session isolation).
578
819
  // If pinned session died, check recovery cache first, then auto-create.
579
820
  const pinnedSession = pins.browserSessionId || id.state.ancestorPinnedSession || undefined;
821
+ // A pinned run that names a session of its own by hand (the one its browser_session create returned, or one it
822
+ // recovered into in an earlier process): that session and its own open tab there, never the dead pinned tab paired
823
+ // with it. The run's route moves there, here and on the server (recordOwnRoute). A session that is not the run's
824
+ // (another run's, or one that is gone) is ignored like a tab the pin overrides: the run works in its own route.
825
+ // Before 2026-11-04 it was paired with the pinned tab, a pair that exists nowhere (the server refused it, and the
826
+ // call reported the run's tab lost).
827
+ if (pinnedSession && sessionId && sessionId !== pinnedSession && sessionId !== id.state.recoveredSessionId) {
828
+ const listed = namedListing || await request('GET', '/api/browser/sessions');
829
+ const owned = ownedTabIn(listed, sessionId, id, tabId);
830
+ if (owned) {
831
+ repin(id, sessionId, owned);
832
+ await recordOwnRoute(id, listed, sessionId, owned);
833
+ return { sessionId, tabId: owned };
834
+ }
835
+ console.error(`[MCP] session ${sessionId} is not one of this run's: ignored, the run's own route is used`);
836
+ sessionId = undefined;
837
+ tabId = undefined;
838
+ resolvedTabId = pinnedTab;
839
+ }
580
840
  // Loop prompts intentionally pass their injected sessionId/tabId on every
581
841
  // call. Treat an explicit session that matches the pin as pinned traffic too;
582
842
  // otherwise the old fast path skipped liveness checks and returned a stale
583
- // tab forever after a renderer/page closed.
584
- if (pinnedSession && (!sessionId || sessionId === pinnedSession)) {
843
+ // tab forever after a renderer/page closed. The session the run moved to (a
844
+ // recovery, its own browser_session create) is the run's pinned traffic now.
845
+ if (pinnedSession && (!sessionId || sessionId === pinnedSession || sessionId === id.state.recoveredSessionId)) {
585
846
  // Check recovery cache first — avoids re-creating on every call after recovery.
586
847
  // Return the RECOVERED tab, never the stale pinned tab (which 404s).
587
848
  if (id.state.recoveredSessionId) {
588
849
  const recheck = await request('GET', '/api/browser/sessions');
589
850
  const alive = ((recheck.sessions || []) as BrowserSessionInfo[]).find(s => s.id === id.state.recoveredSessionId);
590
- if (alive) return { sessionId: id.state.recoveredSessionId, tabId: id.state.recoveredTabId || undefined };
591
- id.state.recoveredSessionId = null; // recovered session also died — try fresh recovery
851
+ // The recovered TAB must still be there too: one closed while its session lives was returned forever
852
+ // ("Tab … not found in session" on every call, 2026-10-04).
853
+ const recoveredTab = id.state.recoveredTabId;
854
+ const tabAlive = !!alive && (!recoveredTab || !alive.tabs || alive.tabs.some(t => t.id === recoveredTab));
855
+ if (alive && tabAlive) return { sessionId: id.state.recoveredSessionId, tabId: recoveredTab || undefined };
856
+ id.state.recoveredSessionId = null; // recovered session or tab also died — try fresh recovery
592
857
  id.state.recoveredTabId = null;
593
858
  }
594
859
 
595
860
  const check = await request('GET', '/api/browser/sessions');
596
- const active = ((check.sessions || []) as BrowserSessionInfo[]).find(s => s.id === pinnedSession);
861
+ const listed = (check.sessions || []) as BrowserSessionInfo[];
862
+ // The route the server recorded for this run (yourRoute): where a recovery or the run's own browser_session
863
+ // create moved it, also when that happened in an earlier MCP process of the run (a Codex turn, a restarted
864
+ // stdio child) that this one never heard of. Used while its tab is open; the pin otherwise.
865
+ const yours = check.yourRoute as { sessionId?: unknown; tabId?: unknown } | undefined;
866
+ if (yours && typeof yours.sessionId === 'string' && typeof yours.tabId === 'string'
867
+ && (yours.sessionId !== pinnedSession || yours.tabId !== resolvedTabId)) {
868
+ const moved = listed.find(s => s.id === yours.sessionId);
869
+ if (moved && servesDefault(moved) && (!moved.tabs || moved.tabs.some(t => t.id === yours.tabId))) {
870
+ // A route this process already served calls on: a recorded route that differs from it is a move it is told
871
+ // about. The pin alone is not (the launch route, or a route that moved before this process started: status
872
+ // reports that one, from the pin, without a notice).
873
+ const served = id.state.servedRoute;
874
+ const servedElsewhere = !!served?.tabId && isOtherRoute(served, { sessionId: yours.sessionId, tabId: yours.tabId });
875
+ repin(id, yours.sessionId, yours.tabId);
876
+ // The server moved this run's route earlier (a recovery or a create in another MCP process of the run). A call
877
+ // that still names other ids, or that worked in another tab before, is told where it ran; one that names none
878
+ // in a process that never worked elsewhere just works there.
879
+ const namedTab = tabId || null;
880
+ if (id.state.lostRoute || servedElsewhere || (namedTab && namedTab !== yours.tabId) || (sessionId && sessionId !== yours.sessionId)) {
881
+ const pinnedListed = listed.find(s => s.id === pinnedSession);
882
+ const formerTab = namedTab || (servedElsewhere ? served!.tabId : null) || resolvedTabId || null;
883
+ const formerOpen = !!pinnedListed && !!formerTab && (!pinnedListed.tabs || pinnedListed.tabs.some(t => t.id === formerTab));
884
+ announceReplacement(id, { sessionId: yours.sessionId, tabId: yours.tabId },
885
+ id.state.lostRoute || { sessionId: sessionId || pinnedSession, tabId: formerTab }, formerOpen ? 'moved' : 'lost');
886
+ }
887
+ return { sessionId: yours.sessionId, tabId: yours.tabId };
888
+ }
889
+ }
890
+ const active = listed.find(s => s.id === pinnedSession);
597
891
  // A run's pinned browser must be the default one. Hard-fail rather than work
598
892
  // in the wrong browser.
599
893
  if (active && !servesDefault(active)) {
@@ -605,38 +899,40 @@ async function resolveSessionUncached(
605
899
  const tabAlive = !resolvedTabId || !tabList || tabList.some(t => t.id === resolvedTabId);
606
900
  if (tabAlive) return { sessionId: pinnedSession, tabId: resolvedTabId };
607
901
  console.error(`[MCP] Pinned tab ${resolvedTabId} not found in active session ${pinnedSession} — recovering`);
608
- const terminalSessionId = pins.terminalSessionId || undefined;
609
- const recovered = await request(
610
- 'POST',
611
- '/api/loop/recover-browser',
612
- terminalSessionId ? { terminalSessionId } : {},
613
- SESSION_CREATE_TIMEOUT
614
- );
902
+ const recovered = await recoverRunBrowser(id, { sessionId: pinnedSession, tabId: resolvedTabId });
903
+ if (isBrowserStarting(recovered)) return { error: String(recovered.error), starting: true };
615
904
  if (!recovered.error && recovered.sessionId) {
616
- id.state.recoveredSessionId = recovered.sessionId as string;
617
- id.state.recoveredTabId = (recovered.tabId as string) || null;
618
- return { sessionId: id.state.recoveredSessionId, tabId: id.state.recoveredTabId || undefined };
905
+ return { sessionId: recovered.sessionId as string, tabId: (recovered.tabId as string) || undefined };
619
906
  }
620
- return { sessionId: pinnedSession, tabId: resolvedTabId }; // fall through to old tab (will fail gracefully)
907
+ // Never hand back the dead tab: every call would answer "Tab … not found" and none would recover. An
908
+ // error is not cached, so the next call tries the recovery again.
909
+ return { error: `Browser tab ${resolvedTabId} of session ${pinnedSession} is gone and recovery failed: ${recovered.error || 'no tab returned'}\n${LOST_ROUTE_HINT}` };
621
910
  }
622
911
 
623
912
  // Pinned session is gone — rejoin the SHARED loop browser with a fresh owned
624
913
  // tab (not an isolated new browser), and adopt the NEW tabId. Forwarding the
625
914
  // stale pinned tab into a different session would 404 every subsequent call.
626
915
  console.error(`[MCP] Pinned browser session ${pinnedSession} is gone — recovering via shared loop browser`);
627
- const terminalSessionId = pins.terminalSessionId || undefined;
628
- const recovered = await request(
629
- 'POST',
630
- '/api/loop/recover-browser',
631
- terminalSessionId ? { terminalSessionId } : {},
632
- SESSION_CREATE_TIMEOUT
633
- );
916
+ const recovered = await recoverRunBrowser(id, { sessionId: pinnedSession, tabId: resolvedTabId });
917
+ if (isBrowserStarting(recovered)) return { error: String(recovered.error), starting: true };
634
918
  if (recovered.error || !recovered.sessionId) {
635
- return { error: `Pinned browser session ${pinnedSession} is no longer available and recovery failed: ${recovered.error || 'no session returned'}` };
919
+ return { error: `Pinned browser session ${pinnedSession} is no longer available and recovery failed: ${recovered.error || 'no session returned'}\n${LOST_ROUTE_HINT}` };
920
+ }
921
+ return { sessionId: recovered.sessionId as string, tabId: (recovered.tabId as string) || undefined };
922
+ }
923
+
924
+ // Ids of a tab of this caller's that went away. One SynaBun already replaced: the call goes to its replacement (the
925
+ // notice was given with the replacement). The one just lost (its own close, say): the call resolves its route as if
926
+ // it named none, which opens a tab of its own and says so, instead of failing on the old ids until it creates one.
927
+ if (tabId && !pinnedSession) {
928
+ const replaced = id.state.replacedTabs.get(tabId);
929
+ if (replaced) return { sessionId: replaced.sessionId, tabId: replaced.tabId || undefined };
930
+ const lost = id.state.lostRoute;
931
+ if (lost && lost.tabId === tabId && (!sessionId || lost.sessionId === sessionId)) {
932
+ sessionId = undefined;
933
+ tabId = undefined;
934
+ resolvedTabId = undefined;
636
935
  }
637
- id.state.recoveredSessionId = recovered.sessionId as string;
638
- id.state.recoveredTabId = (recovered.tabId as string) || null;
639
- return { sessionId: id.state.recoveredSessionId, tabId: id.state.recoveredTabId || undefined };
640
936
  }
641
937
 
642
938
  if (sessionId) {
@@ -658,6 +954,7 @@ async function resolveSessionUncached(
658
954
  const check = await request('GET', '/api/browser/sessions');
659
955
  const alive = ((check.sessions || []) as BrowserSessionInfo[]).find(s => s.id === id.state.interactiveSessionId);
660
956
  if (alive && servesDefault(alive)) return { sessionId: id.state.interactiveSessionId, tabId: resolvedTabId || id.state.interactiveTabId || undefined };
957
+ id.state.lostRoute = { sessionId: id.state.interactiveSessionId, tabId: id.state.interactiveTabId };
661
958
  id.state.interactiveSessionId = null;
662
959
  id.state.interactiveTabId = null; // session gone — fall through to re-acquire
663
960
  }
@@ -670,6 +967,8 @@ async function resolveSessionUncached(
670
967
  const created = await request('POST', '/api/browser/sessions', {
671
968
  url: autoCreate.url || 'about:blank',
672
969
  }, SESSION_CREATE_TIMEOUT);
970
+ // Still starting: not a failure (the server keeps the start for this caller's next call).
971
+ if (isBrowserStarting(created)) return { error: AUTO_CREATE_STARTING, starting: true };
673
972
  if (created.error) {
674
973
  if (/lock/i.test(created.error)) return acquireInteractive(id, autoCreate.url);
675
974
  return { error: `Failed to auto-create session: ${created.error}` };
@@ -702,11 +1001,13 @@ async function resolveSessionUncached(
702
1001
  // with a dedicated, owned tab. For a clean profile with no owners, keep the historical
703
1002
  // separate-browser behavior (no lock, no regression).
704
1003
  const lockRisk = allSessions.some(s => s.persistent || s.loopOwned || s.agentOwned || s.interactiveOwned);
705
- const autoCreateSession = async (): Promise<{ sessionId: string; tabId?: string } | { error: string }> => {
1004
+ const autoCreateSession = async (): Promise<RouteOrError> => {
706
1005
  if (lockRisk) return acquireInteractive(id, autoCreate?.url);
707
1006
  const created = await request('POST', '/api/browser/sessions', {
708
1007
  url: autoCreate?.url || 'about:blank',
709
1008
  }, SESSION_CREATE_TIMEOUT);
1009
+ // Still starting: not a failure (the server keeps the start for this caller's next call).
1010
+ if (isBrowserStarting(created)) return { error: AUTO_CREATE_STARTING, starting: true };
710
1011
  if (created.error) {
711
1012
  if (/lock/i.test(created.error)) return acquireInteractive(id, autoCreate?.url);
712
1013
  return { error: `Failed to auto-create session: ${created.error}` };
@@ -721,20 +1022,26 @@ async function resolveSessionUncached(
721
1022
  return autoCreateSession();
722
1023
  }
723
1024
 
724
- if (sessions.length === 1) {
725
- // No autoCreate — caller wants to interact with an existing page (click, snapshot, etc.).
726
- // Adopting is ONLY safe for a pristine, unowned session (e.g. a page the user opened
727
- // manually in the NI UI). If ANOTHER automation already owns a tab here (it plain-created
728
- // the session or acquired a tab — see _tabOwners), adopting makes us a tab-less freeloader
729
- // that FAILS CLOSED (404) the moment the session goes multi-tab — the sidepanel-vs-CLI
730
- // collision. In that case acquire our OWN dedicated tab in the shared browser instead.
1025
+ if (sessions.length > 0 && !resolvedTabId) {
1026
+ // No autoCreate — the caller wants to interact with a page (click, snapshot, etc.). The server hands an automation
1027
+ // only a tab it owns (server.js getTargetPage, since 2026-11-05): a page the user opened by hand in SynaBun's
1028
+ // browser panel, or another automation's tab, is never adopted. A tab of its own there (a session it created, which
1029
+ // this process forgot) is used; else acquire our OWN dedicated tab in the shared browser (it starts at about:blank:
1030
+ // navigate it where the work is).
731
1031
  const myTerminalId = terminalIdFor(id);
732
- const loneOwners = sessions[0].tabOwners || {};
733
- const ownedByOther = Object.keys(loneOwners).some(k => k !== id.clientId && k !== myTerminalId);
734
- if (ownedByOther) {
735
- return acquireInteractive(id, autoCreate?.url);
1032
+ for (const s of sessions) {
1033
+ const owners = s.tabOwners || {};
1034
+ const mine = owners[myTerminalId] || owners[id.clientId];
1035
+ if (mine && (s.tabs || []).some(t => t.id === mine)) {
1036
+ id.state.affinitySessionId = s.id;
1037
+ return { sessionId: s.id, tabId: mine };
1038
+ }
736
1039
  }
737
- id.state.affinitySessionId = sessions[0].id;
1040
+ return acquireInteractive(id, undefined);
1041
+ }
1042
+
1043
+ if (sessions.length === 1) {
1044
+ // An explicit tab with no session: the server checks that the tab is this caller's own.
738
1045
  return { sessionId: sessions[0].id, tabId: resolvedTabId };
739
1046
  }
740
1047
 
@@ -750,11 +1057,11 @@ async function resolveSessionUncached(
750
1057
  // navigate reuses this same owned tab via the X-Synabun-Terminal routing.
751
1058
  return acquireInteractive(id, undefined);
752
1059
  }
753
- return { error: 'No browser sessions open. Use browser_session to create one first, or use browser_navigate with a URL to auto-create.' };
1060
+ return { error: 'No browser sessions open. Call browser_session with action "create" to open one, or browser_navigate with a URL, which opens one by itself.' };
754
1061
  }
755
1062
 
756
1063
  // Multiple available sessions — require explicit ID
757
- const list = sessions.map(s => ` ${s.id} — ${s.title || s.url}`).join('\n');
1064
+ const list = sessions.map(s => ` ${s.id}${s.title || s.url ? ` — ${s.title || s.url}` : ''}`).join('\n');
758
1065
  return { error: `Multiple browser sessions open. Specify sessionId:\n${list}` };
759
1066
  }
760
1067
 
@@ -768,7 +1075,7 @@ export async function resolveSession(
768
1075
  autoCreate?: { url?: string },
769
1076
  tabId?: string,
770
1077
  opts: { platform?: boolean } = {},
771
- ): Promise<BrowserRoute | { error: string }> {
1078
+ ): Promise<BrowserRoute | { error: string; starting?: boolean }> {
772
1079
  const context = batchContext.getStore();
773
1080
  if (context) return context.route;
774
1081
  const startedAt = performance.now();
@@ -781,11 +1088,31 @@ export async function resolveSession(
781
1088
  return { ...cached.route };
782
1089
  }
783
1090
  const result = await resolveSessionUncached(sessionId, autoCreate, tabId, platform);
784
- if (!('error' in result)) resolvedRoutes.set(id, { key: routeKey(id, sessionId, tabId, platform || !!autoCreate), route: { ...result }, sessionId, tabId, autoCreate, platform });
1091
+ if (!('error' in result)) {
1092
+ resolvedRoutes.set(id, { key: routeKey(id, sessionId, tabId, platform || !!autoCreate), route: { ...result }, sessionId, tabId, autoCreate, platform });
1093
+ id.state.servedRoute = { sessionId: result.sessionId, tabId: result.tabId || null };
1094
+ }
785
1095
  browserMetric({ phase: 'session-resolution', cached: false, durationMs: performance.now() - startedAt });
786
1096
  return result;
787
1097
  }
788
1098
 
1099
+ /**
1100
+ * resolveSession without the route cache: for a caller whose request found its session or tab gone (isMissingRoute)
1101
+ * and that recovers by itself. A pinned run gets its session again or a replacement tab (POST /api/loop/recover-browser),
1102
+ * and the next resolveSession reuses what this found. Batches stay on their route and never recover midway.
1103
+ */
1104
+ export async function refreshSession(
1105
+ sessionId?: string,
1106
+ autoCreate?: { url?: string },
1107
+ tabId?: string,
1108
+ opts: { platform?: boolean } = {},
1109
+ ): Promise<BrowserRoute | { error: string; starting?: boolean }> {
1110
+ const context = batchContext.getStore();
1111
+ if (context) return context.route;
1112
+ resolvedRoutes.delete(getIdentity());
1113
+ return resolutionRefresh.run(true, () => resolveSession(sessionId, autoCreate, tabId, opts));
1114
+ }
1115
+
789
1116
  /** Batches require a concrete tab owned by this caller, verified once up front. */
790
1117
  export async function resolveBatchRoute(sessionId?: string, tabId?: string): Promise<BrowserRoute | { error: string }> {
791
1118
  const resolved = await resolveSession(sessionId, undefined, tabId);
@@ -820,14 +1147,180 @@ export async function listSessions(): Promise<NiResponse> {
820
1147
  return request('GET', '/api/browser/sessions');
821
1148
  }
822
1149
 
1150
+ export interface OwnBrowserTab { id: string; url: string; title: string }
1151
+ export interface OwnBrowserSession {
1152
+ id: string;
1153
+ /** This caller's own open tabs there (never another automation's or the owner's). */
1154
+ tabs: OwnBrowserTab[];
1155
+ /** How many other tabs the session has (other automations', the owner's). */
1156
+ otherTabs: number;
1157
+ servesDefault: boolean;
1158
+ profile: string;
1159
+ }
1160
+ export interface BrowserRouteStatus {
1161
+ error?: string;
1162
+ sessions: OwnBrowserSession[];
1163
+ /** The route this caller's next browser call uses, as far as it is known without opening anything. */
1164
+ current: { sessionId: string; tabId: string | null; open: boolean; url?: string; title?: string; source: 'current' | 'recovered' | 'recorded' | 'pinned' | 'own' } | null;
1165
+ /** Tabs of this caller's that were lost and replaced by `current`. */
1166
+ replacedTabs: string[];
1167
+ /** A route of this caller's that went away and that no replacement was opened for yet. */
1168
+ lost: { sessionId: string; tabId: string | null } | null;
1169
+ /** The run's route moved away from a tab it knew: the tab it was launched with (its pin), or one this process
1170
+ * worked in (a recovery or its own create). Never for the launch route itself or the first route a run learns. */
1171
+ movedFromPin: boolean;
1172
+ /** The tab it moved from, when known. */
1173
+ movedFrom?: { sessionId: string; tabId: string | null } | null;
1174
+ }
1175
+
1176
+ /**
1177
+ * What browser_session list / status show: the sessions this caller can see, each with the caller's own tabs only
1178
+ * (the server lists an automation nothing else, ownTabsOnly; an older server's other tabs are left out here by their
1179
+ * owner), and the route its next call uses. Reads only: never opens, recovers or moves a tab.
1180
+ */
1181
+ export async function browserRouteStatus(): Promise<BrowserRouteStatus> {
1182
+ const id = getIdentity();
1183
+ const pins = effectivePins(id);
1184
+ if (!pins.browserSessionId && !pins.browserTabId) await resolveFromAncestors(id);
1185
+ const listing = await request('GET', '/api/browser/sessions');
1186
+ const empty: BrowserRouteStatus = { sessions: [], current: null, replacedTabs: [], lost: id.state.lostRoute, movedFromPin: false };
1187
+ if (listing.error) return { ...empty, error: listing.error };
1188
+ const raw = (listing.sessions || []) as Array<BrowserSessionInfo & { otherTabs?: number }>;
1189
+ const keys = [terminalIdFor(id), id.clientId];
1190
+ const sessions: OwnBrowserSession[] = raw.map((s) => {
1191
+ const owners = s.tabOwners || {};
1192
+ const mine = new Set(keys.map(k => owners[k]).filter((t): t is string => typeof t === 'string' && t.length > 0));
1193
+ const all = s.tabs || [];
1194
+ const tabs = all.filter(t => mine.has(t.id)).map(t => ({ id: t.id, url: t.url || '', title: t.title || '' }));
1195
+ const otherTabs = typeof s.otherTabs === 'number' ? s.otherTabs : all.length - tabs.length;
1196
+ return { id: s.id, tabs, otherTabs, servesDefault: servesDefault(s), profile: describeSession(s) };
1197
+ });
1198
+ const openTab = (sessionId: string, tabId: string | null | undefined) => {
1199
+ const session = sessions.find(x => x.id === sessionId);
1200
+ if (!session) return null;
1201
+ if (!tabId) return session.tabs[0] || null;
1202
+ return session.tabs.find(t => t.id === tabId) || null;
1203
+ };
1204
+ const pinnedSession = pins.browserSessionId || id.state.ancestorPinnedSession || null;
1205
+ const pinnedTab = pins.browserTabId || id.state.ancestorPinnedTab || null;
1206
+ const yours = listing.yourRoute as { sessionId?: unknown; tabId?: unknown } | undefined;
1207
+ const cached = resolvedRoutes.get(id)?.route;
1208
+ type Source = NonNullable<BrowserRouteStatus['current']>['source'];
1209
+ const candidates: Array<{ sessionId: string; tabId: string | null; source: Source }> = [];
1210
+ if (cached) candidates.push({ sessionId: cached.sessionId, tabId: cached.tabId || null, source: 'current' });
1211
+ if (id.state.recoveredSessionId) candidates.push({ sessionId: id.state.recoveredSessionId, tabId: id.state.recoveredTabId, source: 'recovered' });
1212
+ if (yours && typeof yours.sessionId === 'string' && typeof yours.tabId === 'string') candidates.push({ sessionId: yours.sessionId, tabId: yours.tabId, source: 'recorded' });
1213
+ if (pinnedSession) candidates.push({ sessionId: pinnedSession, tabId: pinnedTab, source: 'pinned' });
1214
+ if (id.state.interactiveSessionId) candidates.push({ sessionId: id.state.interactiveSessionId, tabId: id.state.interactiveTabId, source: 'own' });
1215
+ if (id.state.affinitySessionId) candidates.push({ sessionId: id.state.affinitySessionId, tabId: null, source: 'own' });
1216
+ for (const s of sessions) if (s.tabs[0]) candidates.push({ sessionId: s.id, tabId: s.tabs[0].id, source: 'own' });
1217
+ let current: BrowserRouteStatus['current'] = null;
1218
+ for (const c of candidates) {
1219
+ const tab = openTab(c.sessionId, c.tabId);
1220
+ if (tab) { current = { sessionId: c.sessionId, tabId: tab.id, open: true, url: tab.url, title: tab.title, source: c.source }; break; }
1221
+ }
1222
+ // Nothing open: the route it had (pinned or last used), reported as gone.
1223
+ if (!current && candidates[0] && candidates[0].source !== 'own') current = { ...candidates[0], open: false };
1224
+ const replacedTabs = current?.open
1225
+ ? [...id.state.replacedTabs].filter(([, to]) => to.sessionId === current!.sessionId && to.tabId === current!.tabId).map(([from]) => from)
1226
+ : [];
1227
+ // Moved: the current route is not the launch pin, or it is where this process moved from a tab it knew. The route
1228
+ // the server recorded is not a move by itself: on a fresh run it is the launch route (live runs 188b4ed7, 2ed620e8
1229
+ // said "Replaced: yes" on their first call). A fresh process of a run that another process moved knows the move
1230
+ // from its launch pin only; with no tab pinned it cannot tell, and says no.
1231
+ const here = current?.open ? { sessionId: current.sessionId, tabId: current.tabId } : null;
1232
+ const fromPin = !!here && !!pinnedSession && isOtherRoute({ sessionId: pinnedSession, tabId: pinnedTab }, here);
1233
+ const moved = id.state.routeMoved;
1234
+ const fromHere = !!here && !!moved && moved.to.sessionId === here.sessionId && (!moved.to.tabId || moved.to.tabId === here.tabId);
1235
+ const movedFromPin = fromPin || fromHere;
1236
+ const movedFrom = fromHere ? moved!.from : fromPin ? { sessionId: pinnedSession!, tabId: pinnedTab } : null;
1237
+ return { sessions, current, replacedTabs, lost: id.state.lostRoute, movedFromPin, movedFrom };
1238
+ }
1239
+
1240
+ /**
1241
+ * browser_session create: a new browser tab of this caller's own, where it continues.
1242
+ * - A pinned run (a loop, a dispatched worker): a new tab in SynaBun's shared browser (started when none runs). The
1243
+ * run's route moves there (repinned): its next calls go to it with or without ids, and the server records it on the
1244
+ * run (state file, run record, agent_status).
1245
+ * - Any other caller: what browser_navigate's auto-create gives it. Its own tab in the shared browser when that runs
1246
+ * on a persistent profile or other automations hold it (a second browser on that profile fails, or ends the shared
1247
+ * one); else a new browser, which becomes its session.
1248
+ * A url other than about:blank is opened in the new tab. A start the server is still running answers
1249
+ * BROWSER_STARTING (isBrowserStarting): the next create gets that same start, never a second browser.
1250
+ */
823
1251
  export async function createSession(url?: string): Promise<NiResponse> {
824
- return request('POST', '/api/browser/sessions', {
825
- url: url || 'about:blank',
826
- }, SESSION_CREATE_TIMEOUT);
1252
+ const id = getIdentity();
1253
+ const pins = effectivePins(id);
1254
+ const target = url || 'about:blank';
1255
+ // The caller's own create is where it continues: nothing to announce about a tab it lost before.
1256
+ id.state.lostRoute = null;
1257
+ if (!pins.browserSessionId && !pins.browserTabId) await resolveFromAncestors(id);
1258
+ const pinned = pins.browserSessionId || id.state.ancestorPinnedSession;
1259
+ let created: NiResponse;
1260
+ let opened = false; // the new tab is already at `target`
1261
+ if (pinned) {
1262
+ created = await recoverRunBrowser(id, null, 'create');
1263
+ if (created.error || isBrowserStarting(created) || typeof created.sessionId !== 'string') return created;
1264
+ created = { ...created, repinned: true };
1265
+ } else {
1266
+ const listed = await request('GET', '/api/browser/sessions');
1267
+ if (listed.error) return listed;
1268
+ const all = (listed.sessions || []) as BrowserSessionInfo[];
1269
+ const lockRisk = all.some(s => s.persistent || s.loopOwned || s.agentOwned || s.interactiveOwned);
1270
+ let shared = lockRisk;
1271
+ created = {};
1272
+ if (!lockRisk) {
1273
+ created = await request('POST', '/api/browser/sessions', { url: target }, SESSION_CREATE_TIMEOUT);
1274
+ if (isBrowserStarting(created)) return created;
1275
+ if (created.error && /lock/i.test(created.error)) shared = true;
1276
+ else if (created.error || typeof created.sessionId !== 'string') return created;
1277
+ else {
1278
+ id.state.affinitySessionId = created.sessionId as string;
1279
+ resolvedRoutes.delete(id);
1280
+ // A start handed over from an earlier create may not be at this URL yet.
1281
+ opened = !created.handedOver;
1282
+ }
1283
+ }
1284
+ if (shared) {
1285
+ const acquired = await acquireInteractive(id, target);
1286
+ if ('error' in acquired) return { error: acquired.error, ...(acquired.starting && { starting: true, code: 'BROWSER_STARTING' }) };
1287
+ resolvedRoutes.delete(id);
1288
+ created = { ok: true, sessionId: acquired.sessionId, tabId: acquired.tabId || null, shared: true };
1289
+ }
1290
+ }
1291
+ const sessionId = created.sessionId as string;
1292
+ const tabId = typeof created.tabId === 'string' ? created.tabId : undefined;
1293
+ if (!opened && target !== 'about:blank') {
1294
+ const went = await navigate(sessionId, target, tabId, undefined, 'none');
1295
+ if (went.error) return { ...created, url: 'about:blank', navigateError: went.error };
1296
+ return { ...created, url: typeof went.url === 'string' ? went.url : target };
1297
+ }
1298
+ return { ...created, url: typeof created.url === 'string' ? created.url : target };
827
1299
  }
828
1300
 
1301
+ /**
1302
+ * Close a session. One that other automations still have tabs in is kept by the server, which closes only this
1303
+ * caller's own tab there (`sessionKept`). Either way this caller's cached route to it is forgotten: the next call
1304
+ * resolves again (a pinned run gets a tab back through its recovery).
1305
+ */
829
1306
  export async function closeSession(sessionId: string): Promise<NiResponse> {
830
- return request('DELETE', `/api/browser/sessions/${sessionId}`);
1307
+ const result = await request('DELETE', `/api/browser/sessions/${sessionId}`);
1308
+ if (!result.error) {
1309
+ const id = getIdentity();
1310
+ // The tab that went (the server's releasedTabId, else the one this caller routed to there): the next call that
1311
+ // opens a tab for this caller says it replaced this one.
1312
+ const cachedRoute = resolvedRoutes.get(id)?.route;
1313
+ const closedTab = typeof result.releasedTabId === 'string' ? result.releasedTabId
1314
+ : cachedRoute?.sessionId === sessionId ? cachedRoute.tabId || null
1315
+ : id.state.recoveredSessionId === sessionId ? id.state.recoveredTabId
1316
+ : id.state.interactiveSessionId === sessionId ? id.state.interactiveTabId : null;
1317
+ if (result.sessionKept !== true || closedTab) id.state.lostRoute = { sessionId, tabId: closedTab };
1318
+ if (resolvedRoutes.get(id)?.route.sessionId === sessionId) resolvedRoutes.delete(id);
1319
+ if (id.state.interactiveSessionId === sessionId) { id.state.interactiveSessionId = null; id.state.interactiveTabId = null; }
1320
+ if (id.state.affinitySessionId === sessionId) id.state.affinitySessionId = null;
1321
+ if (id.state.recoveredSessionId === sessionId) { id.state.recoveredSessionId = null; id.state.recoveredTabId = null; }
1322
+ }
1323
+ return result;
831
1324
  }
832
1325
 
833
1326
  // ── Navigation ──
@@ -1036,8 +1529,17 @@ export async function consoleMessages(
1036
1529
 
1037
1530
  // ── Advanced ──
1038
1531
 
1039
- export async function evaluate(sessionId: string, script: string, tabId?: string): Promise<NiResponse> {
1040
- return request('POST', `/api/browser/sessions/${sessionId}/evaluate`, { script, ...(tabId && { tabId }) }, LONG_TIMEOUT);
1532
+ /** A social write a page script makes (Bluesky): the platform whose gap the Neural Interface spaces it by, and the
1533
+ * longest this call may wait for it (neural-interface/lib/social-write-pacing.js). */
1534
+ export interface SocialWritePace {
1535
+ platform: 'bluesky';
1536
+ maxWaitMs: number;
1537
+ }
1538
+
1539
+ /** `recover: false`: a missing session or tab is reported, never retried on a replacement tab (see request()). */
1540
+ export async function evaluate(sessionId: string, script: string, tabId?: string, opts?: { pace?: SocialWritePace; recover?: boolean }): Promise<NiResponse> {
1541
+ const pace = opts?.pace ? { platform: opts.pace.platform, maxWaitMs: Math.max(0, Math.floor(opts.pace.maxWaitMs || 0)) } : null;
1542
+ return request('POST', `/api/browser/sessions/${sessionId}/evaluate`, { script, ...(tabId && { tabId }), ...(pace && { pace }) }, LONG_TIMEOUT + (pace?.maxWaitMs || 0), { recover: opts?.recover });
1041
1543
  }
1042
1544
 
1043
1545
  export interface BrowserExtractOptions {