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
@@ -5,12 +5,33 @@
5
5
  */
6
6
  import { AsyncLocalStorage } from 'node:async_hooks';
7
7
  import { randomUUID } from 'node:crypto';
8
- import { getIdentity, effectivePins, terminalIdFor, callerBrainCredential, callerRole, setReleaseHook, peekStdioIdentity, isHttpMode, } from './identity.js';
8
+ import { BrowserRouteLost, currentRouteFlow, noteRouteReplaced } from './browser-route-flow.js';
9
+ import { getIdentity, effectivePins, terminalIdFor, terminalHeaders, callerBrainCredential, callerRole, setReleaseHook, peekStdioIdentity, isHttpMode, } from './identity.js';
9
10
  const BASE_URL = process.env.NEURAL_INTERFACE_URL
10
11
  || `http://localhost:${process.env.NEURAL_PORT || '3344'}`;
11
12
  const DEFAULT_TIMEOUT = 10_000;
12
13
  const LONG_TIMEOUT = 30_000;
13
- const SESSION_CREATE_TIMEOUT = 70_000;
14
+ // A browser start (create, acquire, a run's recovery) is answered by the server within its request budget
15
+ // (neural-interface/lib/browser-execution.js BROWSER_REQUEST_MAX_MS, 120 s): the session, or BROWSER_STARTING while a
16
+ // cold MoreLogin start is still running (it can wait two minutes for the app), with the start kept for this caller's
17
+ // next request (lib/browser-start-handoff.js). This waits longer than that budget, so the answer read is the server's,
18
+ // never a timeout of its own that left the start running unseen (70 s before 2026-11-04).
19
+ const SESSION_CREATE_TIMEOUT = 150_000;
20
+ /**
21
+ * What an agent does when its browser session or tab is gone and no replacement was made for it: the rule of the
22
+ * browser policy (neural-interface/lib/browser-tool-policy.js browserSessionLossRule), in the answer itself.
23
+ */
24
+ 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.';
25
+ /** The server answered that the browser is still starting (lib/browser-start-handoff.js): nothing failed. */
26
+ export function isBrowserStarting(result) {
27
+ return !!result && (result.starting === true || result.code === 'BROWSER_STARTING');
28
+ }
29
+ /**
30
+ * browser_navigate's own session (auto-create) while the browser is still starting: nothing failed, and the server keeps
31
+ * that start for this caller, so the next call gets it (never a second browser). Before 2026-11-04 this read
32
+ * "Failed to auto-create session: …" and agents gave up or reached for another browser.
33
+ */
34
+ 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.';
14
35
  // Existing engagement spacing can consume 90 seconds before the click begins.
15
36
  const CLICK_TIMEOUT = 120_000;
16
37
  export function isBrowserV2Enabled() {
@@ -97,7 +118,9 @@ async function requestOnce(method, path, body, timeout = DEFAULT_TIMEOUT, extraH
97
118
  // Per-caller routing identity: the server maps this to the caller's owned
98
119
  // tab (_tabOwners) so tab-less browser calls never land on another
99
120
  // automation's tab. Derived per-request over HTTP, per-process for stdio.
100
- headers['X-Synabun-Terminal'] = terminalIdFor(getIdentity());
121
+ // A run's pin travels with its terminal token (X-Synabun-Terminal-Token),
122
+ // without which the browser routes refuse to act as that run.
123
+ Object.assign(headers, terminalHeaders(getIdentity()));
101
124
  // Assistant runtimes forward their role so /api/assistant/* can tell an
102
125
  // orchestrator apart from a worker run (workers must never dispatch).
103
126
  const role = callerRole();
@@ -170,20 +193,53 @@ async function requestOnce(method, path, body, timeout = DEFAULT_TIMEOUT, extraH
170
193
  }
171
194
  }
172
195
  }
173
- async function request(method, path, body, timeout = DEFAULT_TIMEOUT) {
174
- const result = await requestOnce(method, path, body, timeout);
175
- const context = batchContext.getStore();
176
- const missingRoute = result.actionStarted === false
196
+ /** A browser request the server refused before starting anything, because its session or tab is gone. */
197
+ export function isMissingRoute(result) {
198
+ return !!result && result.actionStarted === false
177
199
  && (result.code === 'SESSION_NOT_FOUND' || result.code === 'TAB_NOT_FOUND');
200
+ }
201
+ /**
202
+ * `recover: false` — a missing session or tab is answered as it is, never sent on to a replacement route: for a
203
+ * caller that must prepare a page before it runs something there (a Bluesky script needs a bsky.app document, a
204
+ * replacement tab is about:blank) and recovers by itself (refreshSession).
205
+ */
206
+ async function request(method, path, body, timeout = DEFAULT_TIMEOUT, opts = {}) {
178
207
  const match = /^\/api\/browser\/sessions\/([^/?]+)\/(.+)$/.exec(path);
179
- if (isBrowserV2Enabled() && missingRoute && match) {
208
+ // A tool call whose page was lost runs nothing more on a tab (browser-route-flow.ts): a later step would run on
209
+ // the blank replacement and answer for a page that is not there.
210
+ const flow = currentRouteFlow();
211
+ const guarded = !!flow && flow.policy !== 'follow' && !!match;
212
+ if (guarded && flow.loss)
213
+ throw new BrowserRouteLost(flow.loss);
214
+ const result = await requestOnce(method, path, body, timeout);
215
+ const context = batchContext.getStore();
216
+ const missingRoute = isMissingRoute(result);
217
+ const routeOf = () => {
218
+ const tabId = typeof body?.tabId === 'string' ? body.tabId : new URL(path, BASE_URL).searchParams.get('tabId');
219
+ return { sessionId: match[1], tabId: tabId || null };
220
+ };
221
+ const stepOf = () => match[2].split('?')[0];
222
+ if (guarded && !context && result.error
223
+ && (result.tabRecovered === true || result.wedgedTabRetired === true || result.sessionInvalidated === true)) {
224
+ // The step failed and the server reset the wedged page to about:blank under the same tab id, or closed the tab
225
+ // or the session: the page is gone. (A screenshot that worked can retire its tab too: it keeps its answer, and
226
+ // the next step finds the tab gone.)
227
+ flow.loss = { reason: result.tabRecovered === true ? 'reset' : 'retired', step: stepOf(), from: routeOf() };
228
+ throw new BrowserRouteLost(flow.loss);
229
+ }
230
+ if (isBrowserV2Enabled() && missingRoute && match && opts.recover !== false) {
180
231
  const id = getIdentity();
181
232
  const cached = resolvedRoutes.get(id);
182
233
  resolvedRoutes.delete(id);
183
234
  // Batches are pinned to their original tab and never recover midway.
184
235
  const pinnedSession = effectivePins(id).browserSessionId || id.state.ancestorPinnedSession;
236
+ // The run's pinned session, or the one its route moved to (a recovery, its own browser_session create), named by
237
+ // hand: both are the run's own route, recovered the same way.
185
238
  if (!context && cached?.route.sessionId === match[1]
186
- && (!cached.sessionId || cached.sessionId === pinnedSession)) {
239
+ && (!cached.sessionId || cached.sessionId === pinnedSession
240
+ || (!!pinnedSession && cached.sessionId === id.state.recoveredSessionId))) {
241
+ // The route that failed: the replacement's notice names it (announceReplacement).
242
+ id.state.lostRoute = routeOf();
187
243
  // Clear unpinned fast-mode state too: a force-refresh must not reuse it.
188
244
  if (id.state.interactiveSessionId === match[1]) {
189
245
  id.state.interactiveSessionId = null;
@@ -192,6 +248,13 @@ async function request(method, path, body, timeout = DEFAULT_TIMEOUT) {
192
248
  if (id.state.affinitySessionId === match[1])
193
249
  id.state.affinitySessionId = null;
194
250
  const refreshed = await resolutionRefresh.run(true, () => resolveSession(cached.sessionId, cached.autoCreate, cached.tabId, { platform: cached.platform === true }));
251
+ if (!('error' in refreshed) && guarded) {
252
+ // The replacement tab is ready for the next call; this call stops here (or runs again from the start).
253
+ const from = routeOf();
254
+ const replaced = refreshed.sessionId !== from.sessionId || (refreshed.tabId || null) !== from.tabId;
255
+ flow.loss = { reason: 'gone', step: stepOf(), from, ...(replaced && { to: { sessionId: refreshed.sessionId, tabId: refreshed.tabId || null } }) };
256
+ throw new BrowserRouteLost(flow.loss);
257
+ }
195
258
  if (!('error' in refreshed)) {
196
259
  const nextPath = path.replace(`/sessions/${match[1]}/`, `/sessions/${refreshed.sessionId}/`);
197
260
  const nextBody = body ? { ...body, tabId: refreshed.tabId } : undefined;
@@ -200,13 +263,36 @@ async function request(method, path, body, timeout = DEFAULT_TIMEOUT) {
200
263
  url.searchParams.set('tabId', refreshed.tabId);
201
264
  else
202
265
  url.searchParams.delete('tabId');
203
- return requestOnce(method, `${url.pathname}${url.search}`, nextBody, timeout);
266
+ const retried = await requestOnce(method, `${url.pathname}${url.search}`, nextBody, timeout);
267
+ // Say where it went: a tool that keeps the old session id for its next request would get "Session not
268
+ // found" there (bluesky.ts probed the replacement tab, then navigated the closed session, 2026-11-04).
269
+ const rerouted = { sessionId: refreshed.sessionId, tabId: refreshed.tabId || null };
270
+ if (flow)
271
+ flow.rerouted = rerouted;
272
+ // The call ran on the replacement: its answer starts with a notice (once; resolution may have raised it).
273
+ announceReplacement(id, rerouted, routeOf());
274
+ return { ...retried, rerouted };
204
275
  }
205
276
  // Recovery failed: report why (e.g. "MoreLogin connect failed: …"), not the
206
277
  // bare "Session not found" that triggered it. Nothing was started.
207
- return { ...result, error: refreshed.error, recoveryFailed: true };
278
+ const starting = refreshed.starting === true;
279
+ if (guarded) {
280
+ // Every later step of this tool would find the same dead route: the call stops here and says what happened
281
+ // (routeLossMessage: still starting, or create a tab of your own).
282
+ // The loss message says what to do; the hint the recovery's error carries would say it twice.
283
+ const why = refreshed.error.replace(`\n${LOST_ROUTE_HINT}`, '').trim();
284
+ flow.loss = { reason: 'gone', step: stepOf(), from: routeOf(), recovery: { error: why, ...(starting && { starting: true }) } };
285
+ throw new BrowserRouteLost(flow.loss);
286
+ }
287
+ return { ...result, error: refreshed.error, recoveryFailed: true, ...(starting && { starting: true }) };
208
288
  }
209
289
  }
290
+ if (guarded && !context && missingRoute && opts.recover !== false) {
291
+ // Gone, and not a route this caller resolved (a session id named by hand, v2 off): no replacement here; the
292
+ // call stops instead of polling a tab that does not exist until its own timeout.
293
+ flow.loss = { reason: 'gone', step: stepOf(), from: routeOf() };
294
+ throw new BrowserRouteLost(flow.loss);
295
+ }
210
296
  // The server refused a session that does not serve the default browser (the
211
297
  // settings changed under a cached route): forget it, so the next call resolves
212
298
  // the default browser. Not retried here: the page the call meant is in the other browser.
@@ -220,12 +306,18 @@ async function request(method, path, body, timeout = DEFAULT_TIMEOUT) {
220
306
  if (id.state.affinitySessionId === match[1])
221
307
  id.state.affinitySessionId = null;
222
308
  }
223
- if (context && result.error)
224
- context.errors.push(result);
225
- else if (context && typeof result.snapshotError === 'string') {
226
- context.errors.push({ error: result.snapshotError, code: 'SNAPSHOT_FAILED' });
309
+ // Gone, and nothing replaced it here (a batch, a session named by hand, v2 off): the answer says what to do, so the
310
+ // agent opens a new tab instead of giving up or reaching for another browser. A caller that recovers by itself
311
+ // (recover: false) gets the refusal as it is.
312
+ const answered = missingRoute && opts.recover !== false
313
+ ? { ...result, error: `${result.error || 'The browser session or tab is gone'}. ${LOST_ROUTE_HINT}` }
314
+ : result;
315
+ if (context && answered.error)
316
+ context.errors.push(answered);
317
+ else if (context && typeof answered.snapshotError === 'string') {
318
+ context.errors.push({ error: answered.snapshotError, code: 'SNAPSHOT_FAILED' });
227
319
  }
228
- return result;
320
+ return answered;
229
321
  }
230
322
  const RUNTIME_REPORT_TIMEOUT = 2_000;
231
323
  /** One report: its status and its JSON body, or null for a body that is not JSON (a route the server does not have). */
@@ -233,7 +325,7 @@ async function postRuntimeReport(path, body) {
233
325
  const controller = new AbortController();
234
326
  const timer = setTimeout(() => controller.abort(), RUNTIME_REPORT_TIMEOUT);
235
327
  try {
236
- const headers = { 'Content-Type': 'application/json', 'X-Synabun-Terminal': terminalIdFor(getIdentity()) };
328
+ const headers = { 'Content-Type': 'application/json', ...terminalHeaders(getIdentity()) };
237
329
  const role = callerRole();
238
330
  if (role)
239
331
  headers['X-Synabun-Role'] = role;
@@ -303,23 +395,154 @@ export async function reportRuntimeTools(groups, options) {
303
395
  // Join the ONE shared browser with a dedicated, owned tab (instead of launching a
304
396
  // second browser on a persistent profile, which fails with "profile is locked").
305
397
  async function acquireInteractive(id, url) {
398
+ // The tab is owned by the id this caller routes as (X-Synabun-Terminal): the server checks an explicit tab against
399
+ // that header, so a tab filed under the process's client id was refused to a run with a terminal pin and no browser
400
+ // pin (a native run without a browser, a brain's MCP child) as "another owner's".
306
401
  const resp = await request('POST', '/api/browser/acquire', {
307
- clientId: id.clientId,
402
+ clientId: terminalIdFor(id),
308
403
  url: url || 'about:blank',
309
404
  }, SESSION_CREATE_TIMEOUT);
405
+ // Still starting (a cold MoreLogin start): nothing failed, and the tab is kept for this caller's next request.
406
+ if (isBrowserStarting(resp))
407
+ return { error: String(resp.error || 'The browser is still starting. Call the browser tool again in a moment.'), starting: true };
310
408
  if (resp.error || !resp.sessionId) {
311
409
  return { error: `Failed to acquire a shared browser tab: ${resp.error || 'no session returned'}` };
312
410
  }
313
411
  id.state.interactiveSessionId = resp.sessionId;
314
412
  id.state.interactiveTabId = resp.tabId || null;
315
413
  id.state.affinitySessionId = id.state.interactiveSessionId;
414
+ // A tab of its own again, after the one it had went away: the call says so.
415
+ if (id.state.lostRoute)
416
+ announceReplacement(id, { sessionId: id.state.interactiveSessionId, tabId: id.state.interactiveTabId });
316
417
  return { sessionId: id.state.interactiveSessionId, tabId: id.state.interactiveTabId || undefined };
317
418
  }
318
419
  function adoptCreatedSession(id, created, tabId) {
319
420
  const sessionId = created.sessionId;
320
421
  id.state.affinitySessionId = sessionId;
422
+ if (id.state.lostRoute) {
423
+ announceReplacement(id, { sessionId, tabId: tabId || (typeof created.tabId === 'string' ? created.tabId : null) });
424
+ }
321
425
  return { sessionId, tabId };
322
426
  }
427
+ /** Old tab ids this caller still names after they were replaced: kept small (the latest ones). */
428
+ const REPLACED_TABS_MAX = 16;
429
+ /**
430
+ * This call is served by a replacement route (`to`) for one that went away (`from`, else the caller's lostRoute):
431
+ * its answer starts with a notice that names both (browser-route-flow.ts noteRouteReplaced), once per replacement,
432
+ * and a later call that still names the old tab goes to the new one. A replacement that is the lost route itself (a
433
+ * recovery that handed the same tab back) is not one.
434
+ */
435
+ function announceReplacement(id, to, from, kind = 'lost') {
436
+ const lost = from || id.state.lostRoute;
437
+ id.state.lostRoute = null;
438
+ const next = { sessionId: to.sessionId, tabId: to.tabId || null };
439
+ if (lost && lost.sessionId === next.sessionId && (lost.tabId || null) === next.tabId)
440
+ return;
441
+ // A tab that is still open (`moved`) was not lost: status reports the move (routeMoved), not a lost tab.
442
+ if (kind === 'lost' && lost?.tabId && next.tabId) {
443
+ id.state.replacedTabs.delete(lost.tabId);
444
+ id.state.replacedTabs.set(lost.tabId, next);
445
+ while (id.state.replacedTabs.size > REPLACED_TABS_MAX)
446
+ id.state.replacedTabs.delete(id.state.replacedTabs.keys().next().value);
447
+ }
448
+ noteRouteReplaced({ kind, from: lost ? { sessionId: lost.sessionId, tabId: lost.tabId || null } : null, to: next });
449
+ }
450
+ /**
451
+ * The route this caller knew before a repin: the one it moved to earlier, else the one it last served a call on, else
452
+ * its launch pin. A route without a tab id is known by its session only.
453
+ */
454
+ function knownRoute(id) {
455
+ if (id.state.recoveredSessionId)
456
+ return { sessionId: id.state.recoveredSessionId, tabId: id.state.recoveredTabId };
457
+ if (id.state.servedRoute)
458
+ return id.state.servedRoute;
459
+ const pins = effectivePins(id);
460
+ const session = pins.browserSessionId || id.state.ancestorPinnedSession;
461
+ return session ? { sessionId: session, tabId: pins.browserTabId || id.state.ancestorPinnedTab || null } : null;
462
+ }
463
+ /**
464
+ * Whether `to` is a different route than `from`: another session, or another tab when both tab ids are known. A
465
+ * route it learns where it knew only the session (a pin without a tab) is the same route, not a move.
466
+ */
467
+ function isOtherRoute(from, to) {
468
+ if (!from)
469
+ return false;
470
+ return from.sessionId !== to.sessionId || (!!from.tabId && !!to.tabId && from.tabId !== to.tabId);
471
+ }
472
+ /** A pinned caller's route moves here (a recovery, its own browser_session create, a session of its own named by id). */
473
+ function repin(id, sessionId, tabId) {
474
+ const to = { sessionId, tabId: tabId || null };
475
+ const from = knownRoute(id);
476
+ // A move from a tab it knew (status says Replaced while it is current); adopting the route it was launched with, or
477
+ // the first one it learns, is not one.
478
+ if (from && isOtherRoute(from, to))
479
+ id.state.routeMoved = { from, to };
480
+ id.state.recoveredSessionId = sessionId;
481
+ id.state.recoveredTabId = tabId || null;
482
+ resolvedRoutes.delete(id);
483
+ }
484
+ /**
485
+ * The open tab this caller owns in `sessionId` (the server's tabOwners, under its routing id or its client id): the
486
+ * 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
487
+ * another owner's, is never returned). null for a session it has no open tab in, or one that is not the default browser.
488
+ */
489
+ function ownedTabIn(listing, sessionId, id, tabId) {
490
+ const session = (listing.sessions || []).find(s => s.id === sessionId);
491
+ if (!session || !servesDefault(session))
492
+ return null;
493
+ const owners = session.tabOwners || {};
494
+ const mine = [owners[terminalIdFor(id)], owners[id.clientId]].filter((t) => typeof t === 'string' && t.length > 0);
495
+ const open = (t) => !session.tabs || session.tabs.some(x => x.id === t);
496
+ if (tabId && mine.includes(tabId) && open(tabId))
497
+ return tabId;
498
+ return mine.find(open) || null;
499
+ }
500
+ /**
501
+ * 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
502
+ * as the run's route (POST /api/loop/recover-browser `adopt`), so a later MCP process of the run (a Codex turn, a
503
+ * restarted stdio child) follows it through yourRoute instead of the route the server knew before. Only a server
504
+ * that says it records it (`adoptRoute` in its session list): an older one would read the request as a recovery and
505
+ * open one more tab. Best-effort: the move holds in this process either way.
506
+ */
507
+ async function recordOwnRoute(id, listing, sessionId, tabId) {
508
+ if (listing.adoptRoute !== true)
509
+ return;
510
+ const terminalSessionId = effectivePins(id).terminalSessionId || id.state.ancestorPinnedTerminal || undefined;
511
+ if (!terminalSessionId)
512
+ return;
513
+ const recorded = await request('POST', '/api/loop/recover-browser', { terminalSessionId, adopt: { sessionId, tabId } });
514
+ if (recorded.error)
515
+ console.error(`[MCP] the run's move to session ${sessionId} tab ${tabId} was not recorded: ${recorded.error}`);
516
+ }
517
+ /**
518
+ * A pinned run gets a new tab of its own in SynaBun's shared browser (POST /api/loop/recover-browser), started when
519
+ * none runs. `lost`: the route it found gone (the server hands back the run's current route when that one is still
520
+ * open, e.g. after another MCP process of the run recovered first). `reason: 'create'`: the run's own
521
+ * browser_session create, always a new tab. The server records the move on the run (state file, run record).
522
+ */
523
+ async function recoverRunBrowser(id, lost, reason) {
524
+ const pins = effectivePins(id);
525
+ const terminalSessionId = pins.terminalSessionId || id.state.ancestorPinnedTerminal || undefined;
526
+ const body = {};
527
+ if (terminalSessionId)
528
+ body.terminalSessionId = terminalSessionId;
529
+ if (reason)
530
+ body.reason = reason;
531
+ if (lost?.sessionId)
532
+ body.lost = { sessionId: lost.sessionId, tabId: lost.tabId || null };
533
+ const recovered = await request('POST', '/api/loop/recover-browser', body, SESSION_CREATE_TIMEOUT);
534
+ if (!recovered.error && typeof recovered.sessionId === 'string' && !isBrowserStarting(recovered)) {
535
+ const tabId = typeof recovered.tabId === 'string' ? recovered.tabId : null;
536
+ repin(id, recovered.sessionId, tabId);
537
+ // A recovery (a new tab, or the route another process of the run moved to: `current`) serves this call; the
538
+ // run's own create is not a replacement it has to be told about.
539
+ if (reason === 'create')
540
+ id.state.lostRoute = null;
541
+ else
542
+ announceReplacement(id, { sessionId: recovered.sessionId, tabId }, id.state.lostRoute || (lost?.sessionId ? { sessionId: lost.sessionId, tabId: lost.tabId || null } : null));
543
+ }
544
+ return recovered;
545
+ }
323
546
  // Pages (localhost included) only run where the server says the default browser
324
547
  // is. Absent servesDefault (older server, or a managed / real-Chrome setup) keeps
325
548
  // the previous behavior.
@@ -341,11 +564,15 @@ function describeDefault(list) {
341
564
  function releaseTabFor(id) {
342
565
  if (!id.state.interactiveSessionId)
343
566
  return;
567
+ // The id the tab was acquired under (acquireInteractive), as the caller it is: the server releases a caller's own
568
+ // tabs only, and a run's only with its terminal token (a stdio child's own; an HTTP identity evicted outside any
569
+ // request has none, and the run's end releases its tabs on the server anyway).
570
+ const owner = terminalIdFor(id);
344
571
  try {
345
572
  void fetch(`${BASE_URL}/api/browser/release`, {
346
573
  method: 'POST',
347
- headers: { 'Content-Type': 'application/json' },
348
- body: JSON.stringify({ clientId: id.clientId }),
574
+ headers: { 'Content-Type': 'application/json', ...terminalHeaders(id) },
575
+ body: JSON.stringify({ clientId: owner }),
349
576
  }).catch(() => { });
350
577
  }
351
578
  catch { /* best-effort */ }
@@ -472,8 +699,10 @@ async function resolveSessionUncached(sessionId, autoCreate, tabId, platform = f
472
699
  // tool is refused, since the page it names is in the other browser. The
473
700
  // server refuses them too (NOT_DEFAULT_BROWSER).
474
701
  const wantsDefaultBrowser = platform || !!autoCreate;
702
+ let namedListing = null;
475
703
  if (sessionId && sessionId !== (pins.browserSessionId || id.state.ancestorPinnedSession)) {
476
704
  const listed = await request('GET', '/api/browser/sessions');
705
+ namedListing = listed;
477
706
  const named = (listed.sessions || []).find(s => s.id === sessionId);
478
707
  if (named && !servesDefault(named)) {
479
708
  if (!wantsDefaultBrowser) {
@@ -493,7 +722,7 @@ async function resolveSessionUncached(sessionId, autoCreate, tabId, platform = f
493
722
  await resolveFromAncestors(id);
494
723
  }
495
724
  const pinnedTab = pins.browserTabId || id.state.ancestorPinnedTab || undefined;
496
- const resolvedTabId = pinnedTab || tabId || undefined;
725
+ let resolvedTabId = pinnedTab || tabId || undefined;
497
726
  if (pinnedTab && tabId && tabId !== pinnedTab) {
498
727
  console.error(`[MCP] tabId override ignored: pinned=${pinnedTab} requested=${tabId}`);
499
728
  }
@@ -501,23 +730,75 @@ async function resolveSessionUncached(sessionId, autoCreate, tabId, platform = f
501
730
  // this caller to a specific browser session (multi-session isolation).
502
731
  // If pinned session died, check recovery cache first, then auto-create.
503
732
  const pinnedSession = pins.browserSessionId || id.state.ancestorPinnedSession || undefined;
733
+ // A pinned run that names a session of its own by hand (the one its browser_session create returned, or one it
734
+ // recovered into in an earlier process): that session and its own open tab there, never the dead pinned tab paired
735
+ // with it. The run's route moves there, here and on the server (recordOwnRoute). A session that is not the run's
736
+ // (another run's, or one that is gone) is ignored like a tab the pin overrides: the run works in its own route.
737
+ // Before 2026-11-04 it was paired with the pinned tab, a pair that exists nowhere (the server refused it, and the
738
+ // call reported the run's tab lost).
739
+ if (pinnedSession && sessionId && sessionId !== pinnedSession && sessionId !== id.state.recoveredSessionId) {
740
+ const listed = namedListing || await request('GET', '/api/browser/sessions');
741
+ const owned = ownedTabIn(listed, sessionId, id, tabId);
742
+ if (owned) {
743
+ repin(id, sessionId, owned);
744
+ await recordOwnRoute(id, listed, sessionId, owned);
745
+ return { sessionId, tabId: owned };
746
+ }
747
+ console.error(`[MCP] session ${sessionId} is not one of this run's: ignored, the run's own route is used`);
748
+ sessionId = undefined;
749
+ tabId = undefined;
750
+ resolvedTabId = pinnedTab;
751
+ }
504
752
  // Loop prompts intentionally pass their injected sessionId/tabId on every
505
753
  // call. Treat an explicit session that matches the pin as pinned traffic too;
506
754
  // otherwise the old fast path skipped liveness checks and returned a stale
507
- // tab forever after a renderer/page closed.
508
- if (pinnedSession && (!sessionId || sessionId === pinnedSession)) {
755
+ // tab forever after a renderer/page closed. The session the run moved to (a
756
+ // recovery, its own browser_session create) is the run's pinned traffic now.
757
+ if (pinnedSession && (!sessionId || sessionId === pinnedSession || sessionId === id.state.recoveredSessionId)) {
509
758
  // Check recovery cache first — avoids re-creating on every call after recovery.
510
759
  // Return the RECOVERED tab, never the stale pinned tab (which 404s).
511
760
  if (id.state.recoveredSessionId) {
512
761
  const recheck = await request('GET', '/api/browser/sessions');
513
762
  const alive = (recheck.sessions || []).find(s => s.id === id.state.recoveredSessionId);
514
- if (alive)
515
- return { sessionId: id.state.recoveredSessionId, tabId: id.state.recoveredTabId || undefined };
516
- id.state.recoveredSessionId = null; // recovered session also died — try fresh recovery
763
+ // The recovered TAB must still be there too: one closed while its session lives was returned forever
764
+ // ("Tab … not found in session" on every call, 2026-10-04).
765
+ const recoveredTab = id.state.recoveredTabId;
766
+ const tabAlive = !!alive && (!recoveredTab || !alive.tabs || alive.tabs.some(t => t.id === recoveredTab));
767
+ if (alive && tabAlive)
768
+ return { sessionId: id.state.recoveredSessionId, tabId: recoveredTab || undefined };
769
+ id.state.recoveredSessionId = null; // recovered session or tab also died — try fresh recovery
517
770
  id.state.recoveredTabId = null;
518
771
  }
519
772
  const check = await request('GET', '/api/browser/sessions');
520
- const active = (check.sessions || []).find(s => s.id === pinnedSession);
773
+ const listed = (check.sessions || []);
774
+ // The route the server recorded for this run (yourRoute): where a recovery or the run's own browser_session
775
+ // create moved it, also when that happened in an earlier MCP process of the run (a Codex turn, a restarted
776
+ // stdio child) that this one never heard of. Used while its tab is open; the pin otherwise.
777
+ const yours = check.yourRoute;
778
+ if (yours && typeof yours.sessionId === 'string' && typeof yours.tabId === 'string'
779
+ && (yours.sessionId !== pinnedSession || yours.tabId !== resolvedTabId)) {
780
+ const moved = listed.find(s => s.id === yours.sessionId);
781
+ if (moved && servesDefault(moved) && (!moved.tabs || moved.tabs.some(t => t.id === yours.tabId))) {
782
+ // A route this process already served calls on: a recorded route that differs from it is a move it is told
783
+ // about. The pin alone is not (the launch route, or a route that moved before this process started: status
784
+ // reports that one, from the pin, without a notice).
785
+ const served = id.state.servedRoute;
786
+ const servedElsewhere = !!served?.tabId && isOtherRoute(served, { sessionId: yours.sessionId, tabId: yours.tabId });
787
+ repin(id, yours.sessionId, yours.tabId);
788
+ // The server moved this run's route earlier (a recovery or a create in another MCP process of the run). A call
789
+ // that still names other ids, or that worked in another tab before, is told where it ran; one that names none
790
+ // in a process that never worked elsewhere just works there.
791
+ const namedTab = tabId || null;
792
+ if (id.state.lostRoute || servedElsewhere || (namedTab && namedTab !== yours.tabId) || (sessionId && sessionId !== yours.sessionId)) {
793
+ const pinnedListed = listed.find(s => s.id === pinnedSession);
794
+ const formerTab = namedTab || (servedElsewhere ? served.tabId : null) || resolvedTabId || null;
795
+ const formerOpen = !!pinnedListed && !!formerTab && (!pinnedListed.tabs || pinnedListed.tabs.some(t => t.id === formerTab));
796
+ announceReplacement(id, { sessionId: yours.sessionId, tabId: yours.tabId }, id.state.lostRoute || { sessionId: sessionId || pinnedSession, tabId: formerTab }, formerOpen ? 'moved' : 'lost');
797
+ }
798
+ return { sessionId: yours.sessionId, tabId: yours.tabId };
799
+ }
800
+ }
801
+ const active = listed.find(s => s.id === pinnedSession);
521
802
  // A run's pinned browser must be the default one. Hard-fail rather than work
522
803
  // in the wrong browser.
523
804
  if (active && !servesDefault(active)) {
@@ -530,27 +811,41 @@ async function resolveSessionUncached(sessionId, autoCreate, tabId, platform = f
530
811
  if (tabAlive)
531
812
  return { sessionId: pinnedSession, tabId: resolvedTabId };
532
813
  console.error(`[MCP] Pinned tab ${resolvedTabId} not found in active session ${pinnedSession} — recovering`);
533
- const terminalSessionId = pins.terminalSessionId || undefined;
534
- const recovered = await request('POST', '/api/loop/recover-browser', terminalSessionId ? { terminalSessionId } : {}, SESSION_CREATE_TIMEOUT);
814
+ const recovered = await recoverRunBrowser(id, { sessionId: pinnedSession, tabId: resolvedTabId });
815
+ if (isBrowserStarting(recovered))
816
+ return { error: String(recovered.error), starting: true };
535
817
  if (!recovered.error && recovered.sessionId) {
536
- id.state.recoveredSessionId = recovered.sessionId;
537
- id.state.recoveredTabId = recovered.tabId || null;
538
- return { sessionId: id.state.recoveredSessionId, tabId: id.state.recoveredTabId || undefined };
818
+ return { sessionId: recovered.sessionId, tabId: recovered.tabId || undefined };
539
819
  }
540
- return { sessionId: pinnedSession, tabId: resolvedTabId }; // fall through to old tab (will fail gracefully)
820
+ // Never hand back the dead tab: every call would answer "Tab … not found" and none would recover. An
821
+ // error is not cached, so the next call tries the recovery again.
822
+ return { error: `Browser tab ${resolvedTabId} of session ${pinnedSession} is gone and recovery failed: ${recovered.error || 'no tab returned'}\n${LOST_ROUTE_HINT}` };
541
823
  }
542
824
  // Pinned session is gone — rejoin the SHARED loop browser with a fresh owned
543
825
  // tab (not an isolated new browser), and adopt the NEW tabId. Forwarding the
544
826
  // stale pinned tab into a different session would 404 every subsequent call.
545
827
  console.error(`[MCP] Pinned browser session ${pinnedSession} is gone — recovering via shared loop browser`);
546
- const terminalSessionId = pins.terminalSessionId || undefined;
547
- const recovered = await request('POST', '/api/loop/recover-browser', terminalSessionId ? { terminalSessionId } : {}, SESSION_CREATE_TIMEOUT);
828
+ const recovered = await recoverRunBrowser(id, { sessionId: pinnedSession, tabId: resolvedTabId });
829
+ if (isBrowserStarting(recovered))
830
+ return { error: String(recovered.error), starting: true };
548
831
  if (recovered.error || !recovered.sessionId) {
549
- return { error: `Pinned browser session ${pinnedSession} is no longer available and recovery failed: ${recovered.error || 'no session returned'}` };
832
+ return { error: `Pinned browser session ${pinnedSession} is no longer available and recovery failed: ${recovered.error || 'no session returned'}\n${LOST_ROUTE_HINT}` };
833
+ }
834
+ return { sessionId: recovered.sessionId, tabId: recovered.tabId || undefined };
835
+ }
836
+ // Ids of a tab of this caller's that went away. One SynaBun already replaced: the call goes to its replacement (the
837
+ // notice was given with the replacement). The one just lost (its own close, say): the call resolves its route as if
838
+ // it named none, which opens a tab of its own and says so, instead of failing on the old ids until it creates one.
839
+ if (tabId && !pinnedSession) {
840
+ const replaced = id.state.replacedTabs.get(tabId);
841
+ if (replaced)
842
+ return { sessionId: replaced.sessionId, tabId: replaced.tabId || undefined };
843
+ const lost = id.state.lostRoute;
844
+ if (lost && lost.tabId === tabId && (!sessionId || lost.sessionId === sessionId)) {
845
+ sessionId = undefined;
846
+ tabId = undefined;
847
+ resolvedTabId = undefined;
550
848
  }
551
- id.state.recoveredSessionId = recovered.sessionId;
552
- id.state.recoveredTabId = recovered.tabId || null;
553
- return { sessionId: id.state.recoveredSessionId, tabId: id.state.recoveredTabId || undefined };
554
849
  }
555
850
  if (sessionId) {
556
851
  // Checked above against the default browser; the server 404s a session that
@@ -571,6 +866,7 @@ async function resolveSessionUncached(sessionId, autoCreate, tabId, platform = f
571
866
  const alive = (check.sessions || []).find(s => s.id === id.state.interactiveSessionId);
572
867
  if (alive && servesDefault(alive))
573
868
  return { sessionId: id.state.interactiveSessionId, tabId: resolvedTabId || id.state.interactiveTabId || undefined };
869
+ id.state.lostRoute = { sessionId: id.state.interactiveSessionId, tabId: id.state.interactiveTabId };
574
870
  id.state.interactiveSessionId = null;
575
871
  id.state.interactiveTabId = null; // session gone — fall through to re-acquire
576
872
  }
@@ -582,6 +878,9 @@ async function resolveSessionUncached(sessionId, autoCreate, tabId, platform = f
582
878
  const created = await request('POST', '/api/browser/sessions', {
583
879
  url: autoCreate.url || 'about:blank',
584
880
  }, SESSION_CREATE_TIMEOUT);
881
+ // Still starting: not a failure (the server keeps the start for this caller's next call).
882
+ if (isBrowserStarting(created))
883
+ return { error: AUTO_CREATE_STARTING, starting: true };
585
884
  if (created.error) {
586
885
  if (/lock/i.test(created.error))
587
886
  return acquireInteractive(id, autoCreate.url);
@@ -618,6 +917,9 @@ async function resolveSessionUncached(sessionId, autoCreate, tabId, platform = f
618
917
  const created = await request('POST', '/api/browser/sessions', {
619
918
  url: autoCreate?.url || 'about:blank',
620
919
  }, SESSION_CREATE_TIMEOUT);
920
+ // Still starting: not a failure (the server keeps the start for this caller's next call).
921
+ if (isBrowserStarting(created))
922
+ return { error: AUTO_CREATE_STARTING, starting: true };
621
923
  if (created.error) {
622
924
  if (/lock/i.test(created.error))
623
925
  return acquireInteractive(id, autoCreate?.url);
@@ -631,20 +933,25 @@ async function resolveSessionUncached(sessionId, autoCreate, tabId, platform = f
631
933
  if (sessions.length > 0 && autoCreate) {
632
934
  return autoCreateSession();
633
935
  }
634
- if (sessions.length === 1) {
635
- // No autoCreate — caller wants to interact with an existing page (click, snapshot, etc.).
636
- // Adopting is ONLY safe for a pristine, unowned session (e.g. a page the user opened
637
- // manually in the NI UI). If ANOTHER automation already owns a tab here (it plain-created
638
- // the session or acquired a tab — see _tabOwners), adopting makes us a tab-less freeloader
639
- // that FAILS CLOSED (404) the moment the session goes multi-tab — the sidepanel-vs-CLI
640
- // collision. In that case acquire our OWN dedicated tab in the shared browser instead.
936
+ if (sessions.length > 0 && !resolvedTabId) {
937
+ // No autoCreate — the caller wants to interact with a page (click, snapshot, etc.). The server hands an automation
938
+ // only a tab it owns (server.js getTargetPage, since 2026-11-05): a page the user opened by hand in SynaBun's
939
+ // browser panel, or another automation's tab, is never adopted. A tab of its own there (a session it created, which
940
+ // this process forgot) is used; else acquire our OWN dedicated tab in the shared browser (it starts at about:blank:
941
+ // navigate it where the work is).
641
942
  const myTerminalId = terminalIdFor(id);
642
- const loneOwners = sessions[0].tabOwners || {};
643
- const ownedByOther = Object.keys(loneOwners).some(k => k !== id.clientId && k !== myTerminalId);
644
- if (ownedByOther) {
645
- return acquireInteractive(id, autoCreate?.url);
943
+ for (const s of sessions) {
944
+ const owners = s.tabOwners || {};
945
+ const mine = owners[myTerminalId] || owners[id.clientId];
946
+ if (mine && (s.tabs || []).some(t => t.id === mine)) {
947
+ id.state.affinitySessionId = s.id;
948
+ return { sessionId: s.id, tabId: mine };
949
+ }
646
950
  }
647
- id.state.affinitySessionId = sessions[0].id;
951
+ return acquireInteractive(id, undefined);
952
+ }
953
+ if (sessions.length === 1) {
954
+ // An explicit tab with no session: the server checks that the tab is this caller's own.
648
955
  return { sessionId: sessions[0].id, tabId: resolvedTabId };
649
956
  }
650
957
  if (sessions.length === 0) {
@@ -659,10 +966,10 @@ async function resolveSessionUncached(sessionId, autoCreate, tabId, platform = f
659
966
  // navigate reuses this same owned tab via the X-Synabun-Terminal routing.
660
967
  return acquireInteractive(id, undefined);
661
968
  }
662
- return { error: 'No browser sessions open. Use browser_session to create one first, or use browser_navigate with a URL to auto-create.' };
969
+ 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.' };
663
970
  }
664
971
  // Multiple available sessions — require explicit ID
665
- const list = sessions.map(s => ` ${s.id} — ${s.title || s.url}`).join('\n');
972
+ const list = sessions.map(s => ` ${s.id}${s.title || s.url ? ` — ${s.title || s.url}` : ''}`).join('\n');
666
973
  return { error: `Multiple browser sessions open. Specify sessionId:\n${list}` };
667
974
  }
668
975
  /**
@@ -684,11 +991,25 @@ export async function resolveSession(sessionId, autoCreate, tabId, opts = {}) {
684
991
  return { ...cached.route };
685
992
  }
686
993
  const result = await resolveSessionUncached(sessionId, autoCreate, tabId, platform);
687
- if (!('error' in result))
994
+ if (!('error' in result)) {
688
995
  resolvedRoutes.set(id, { key: routeKey(id, sessionId, tabId, platform || !!autoCreate), route: { ...result }, sessionId, tabId, autoCreate, platform });
996
+ id.state.servedRoute = { sessionId: result.sessionId, tabId: result.tabId || null };
997
+ }
689
998
  browserMetric({ phase: 'session-resolution', cached: false, durationMs: performance.now() - startedAt });
690
999
  return result;
691
1000
  }
1001
+ /**
1002
+ * resolveSession without the route cache: for a caller whose request found its session or tab gone (isMissingRoute)
1003
+ * and that recovers by itself. A pinned run gets its session again or a replacement tab (POST /api/loop/recover-browser),
1004
+ * and the next resolveSession reuses what this found. Batches stay on their route and never recover midway.
1005
+ */
1006
+ export async function refreshSession(sessionId, autoCreate, tabId, opts = {}) {
1007
+ const context = batchContext.getStore();
1008
+ if (context)
1009
+ return context.route;
1010
+ resolvedRoutes.delete(getIdentity());
1011
+ return resolutionRefresh.run(true, () => resolveSession(sessionId, autoCreate, tabId, opts));
1012
+ }
692
1013
  /** Batches require a concrete tab owned by this caller, verified once up front. */
693
1014
  export async function resolveBatchRoute(sessionId, tabId) {
694
1015
  const resolved = await resolveSession(sessionId, undefined, tabId);
@@ -721,13 +1042,185 @@ export async function invalidateCache(reason, id) {
721
1042
  export async function listSessions() {
722
1043
  return request('GET', '/api/browser/sessions');
723
1044
  }
1045
+ /**
1046
+ * What browser_session list / status show: the sessions this caller can see, each with the caller's own tabs only
1047
+ * (the server lists an automation nothing else, ownTabsOnly; an older server's other tabs are left out here by their
1048
+ * owner), and the route its next call uses. Reads only: never opens, recovers or moves a tab.
1049
+ */
1050
+ export async function browserRouteStatus() {
1051
+ const id = getIdentity();
1052
+ const pins = effectivePins(id);
1053
+ if (!pins.browserSessionId && !pins.browserTabId)
1054
+ await resolveFromAncestors(id);
1055
+ const listing = await request('GET', '/api/browser/sessions');
1056
+ const empty = { sessions: [], current: null, replacedTabs: [], lost: id.state.lostRoute, movedFromPin: false };
1057
+ if (listing.error)
1058
+ return { ...empty, error: listing.error };
1059
+ const raw = (listing.sessions || []);
1060
+ const keys = [terminalIdFor(id), id.clientId];
1061
+ const sessions = raw.map((s) => {
1062
+ const owners = s.tabOwners || {};
1063
+ const mine = new Set(keys.map(k => owners[k]).filter((t) => typeof t === 'string' && t.length > 0));
1064
+ const all = s.tabs || [];
1065
+ const tabs = all.filter(t => mine.has(t.id)).map(t => ({ id: t.id, url: t.url || '', title: t.title || '' }));
1066
+ const otherTabs = typeof s.otherTabs === 'number' ? s.otherTabs : all.length - tabs.length;
1067
+ return { id: s.id, tabs, otherTabs, servesDefault: servesDefault(s), profile: describeSession(s) };
1068
+ });
1069
+ const openTab = (sessionId, tabId) => {
1070
+ const session = sessions.find(x => x.id === sessionId);
1071
+ if (!session)
1072
+ return null;
1073
+ if (!tabId)
1074
+ return session.tabs[0] || null;
1075
+ return session.tabs.find(t => t.id === tabId) || null;
1076
+ };
1077
+ const pinnedSession = pins.browserSessionId || id.state.ancestorPinnedSession || null;
1078
+ const pinnedTab = pins.browserTabId || id.state.ancestorPinnedTab || null;
1079
+ const yours = listing.yourRoute;
1080
+ const cached = resolvedRoutes.get(id)?.route;
1081
+ const candidates = [];
1082
+ if (cached)
1083
+ candidates.push({ sessionId: cached.sessionId, tabId: cached.tabId || null, source: 'current' });
1084
+ if (id.state.recoveredSessionId)
1085
+ candidates.push({ sessionId: id.state.recoveredSessionId, tabId: id.state.recoveredTabId, source: 'recovered' });
1086
+ if (yours && typeof yours.sessionId === 'string' && typeof yours.tabId === 'string')
1087
+ candidates.push({ sessionId: yours.sessionId, tabId: yours.tabId, source: 'recorded' });
1088
+ if (pinnedSession)
1089
+ candidates.push({ sessionId: pinnedSession, tabId: pinnedTab, source: 'pinned' });
1090
+ if (id.state.interactiveSessionId)
1091
+ candidates.push({ sessionId: id.state.interactiveSessionId, tabId: id.state.interactiveTabId, source: 'own' });
1092
+ if (id.state.affinitySessionId)
1093
+ candidates.push({ sessionId: id.state.affinitySessionId, tabId: null, source: 'own' });
1094
+ for (const s of sessions)
1095
+ if (s.tabs[0])
1096
+ candidates.push({ sessionId: s.id, tabId: s.tabs[0].id, source: 'own' });
1097
+ let current = null;
1098
+ for (const c of candidates) {
1099
+ const tab = openTab(c.sessionId, c.tabId);
1100
+ if (tab) {
1101
+ current = { sessionId: c.sessionId, tabId: tab.id, open: true, url: tab.url, title: tab.title, source: c.source };
1102
+ break;
1103
+ }
1104
+ }
1105
+ // Nothing open: the route it had (pinned or last used), reported as gone.
1106
+ if (!current && candidates[0] && candidates[0].source !== 'own')
1107
+ current = { ...candidates[0], open: false };
1108
+ const replacedTabs = current?.open
1109
+ ? [...id.state.replacedTabs].filter(([, to]) => to.sessionId === current.sessionId && to.tabId === current.tabId).map(([from]) => from)
1110
+ : [];
1111
+ // Moved: the current route is not the launch pin, or it is where this process moved from a tab it knew. The route
1112
+ // the server recorded is not a move by itself: on a fresh run it is the launch route (live runs 188b4ed7, 2ed620e8
1113
+ // said "Replaced: yes" on their first call). A fresh process of a run that another process moved knows the move
1114
+ // from its launch pin only; with no tab pinned it cannot tell, and says no.
1115
+ const here = current?.open ? { sessionId: current.sessionId, tabId: current.tabId } : null;
1116
+ const fromPin = !!here && !!pinnedSession && isOtherRoute({ sessionId: pinnedSession, tabId: pinnedTab }, here);
1117
+ const moved = id.state.routeMoved;
1118
+ const fromHere = !!here && !!moved && moved.to.sessionId === here.sessionId && (!moved.to.tabId || moved.to.tabId === here.tabId);
1119
+ const movedFromPin = fromPin || fromHere;
1120
+ const movedFrom = fromHere ? moved.from : fromPin ? { sessionId: pinnedSession, tabId: pinnedTab } : null;
1121
+ return { sessions, current, replacedTabs, lost: id.state.lostRoute, movedFromPin, movedFrom };
1122
+ }
1123
+ /**
1124
+ * browser_session create: a new browser tab of this caller's own, where it continues.
1125
+ * - A pinned run (a loop, a dispatched worker): a new tab in SynaBun's shared browser (started when none runs). The
1126
+ * run's route moves there (repinned): its next calls go to it with or without ids, and the server records it on the
1127
+ * run (state file, run record, agent_status).
1128
+ * - Any other caller: what browser_navigate's auto-create gives it. Its own tab in the shared browser when that runs
1129
+ * on a persistent profile or other automations hold it (a second browser on that profile fails, or ends the shared
1130
+ * one); else a new browser, which becomes its session.
1131
+ * A url other than about:blank is opened in the new tab. A start the server is still running answers
1132
+ * BROWSER_STARTING (isBrowserStarting): the next create gets that same start, never a second browser.
1133
+ */
724
1134
  export async function createSession(url) {
725
- return request('POST', '/api/browser/sessions', {
726
- url: url || 'about:blank',
727
- }, SESSION_CREATE_TIMEOUT);
1135
+ const id = getIdentity();
1136
+ const pins = effectivePins(id);
1137
+ const target = url || 'about:blank';
1138
+ // The caller's own create is where it continues: nothing to announce about a tab it lost before.
1139
+ id.state.lostRoute = null;
1140
+ if (!pins.browserSessionId && !pins.browserTabId)
1141
+ await resolveFromAncestors(id);
1142
+ const pinned = pins.browserSessionId || id.state.ancestorPinnedSession;
1143
+ let created;
1144
+ let opened = false; // the new tab is already at `target`
1145
+ if (pinned) {
1146
+ created = await recoverRunBrowser(id, null, 'create');
1147
+ if (created.error || isBrowserStarting(created) || typeof created.sessionId !== 'string')
1148
+ return created;
1149
+ created = { ...created, repinned: true };
1150
+ }
1151
+ else {
1152
+ const listed = await request('GET', '/api/browser/sessions');
1153
+ if (listed.error)
1154
+ return listed;
1155
+ const all = (listed.sessions || []);
1156
+ const lockRisk = all.some(s => s.persistent || s.loopOwned || s.agentOwned || s.interactiveOwned);
1157
+ let shared = lockRisk;
1158
+ created = {};
1159
+ if (!lockRisk) {
1160
+ created = await request('POST', '/api/browser/sessions', { url: target }, SESSION_CREATE_TIMEOUT);
1161
+ if (isBrowserStarting(created))
1162
+ return created;
1163
+ if (created.error && /lock/i.test(created.error))
1164
+ shared = true;
1165
+ else if (created.error || typeof created.sessionId !== 'string')
1166
+ return created;
1167
+ else {
1168
+ id.state.affinitySessionId = created.sessionId;
1169
+ resolvedRoutes.delete(id);
1170
+ // A start handed over from an earlier create may not be at this URL yet.
1171
+ opened = !created.handedOver;
1172
+ }
1173
+ }
1174
+ if (shared) {
1175
+ const acquired = await acquireInteractive(id, target);
1176
+ if ('error' in acquired)
1177
+ return { error: acquired.error, ...(acquired.starting && { starting: true, code: 'BROWSER_STARTING' }) };
1178
+ resolvedRoutes.delete(id);
1179
+ created = { ok: true, sessionId: acquired.sessionId, tabId: acquired.tabId || null, shared: true };
1180
+ }
1181
+ }
1182
+ const sessionId = created.sessionId;
1183
+ const tabId = typeof created.tabId === 'string' ? created.tabId : undefined;
1184
+ if (!opened && target !== 'about:blank') {
1185
+ const went = await navigate(sessionId, target, tabId, undefined, 'none');
1186
+ if (went.error)
1187
+ return { ...created, url: 'about:blank', navigateError: went.error };
1188
+ return { ...created, url: typeof went.url === 'string' ? went.url : target };
1189
+ }
1190
+ return { ...created, url: typeof created.url === 'string' ? created.url : target };
728
1191
  }
1192
+ /**
1193
+ * Close a session. One that other automations still have tabs in is kept by the server, which closes only this
1194
+ * caller's own tab there (`sessionKept`). Either way this caller's cached route to it is forgotten: the next call
1195
+ * resolves again (a pinned run gets a tab back through its recovery).
1196
+ */
729
1197
  export async function closeSession(sessionId) {
730
- return request('DELETE', `/api/browser/sessions/${sessionId}`);
1198
+ const result = await request('DELETE', `/api/browser/sessions/${sessionId}`);
1199
+ if (!result.error) {
1200
+ const id = getIdentity();
1201
+ // The tab that went (the server's releasedTabId, else the one this caller routed to there): the next call that
1202
+ // opens a tab for this caller says it replaced this one.
1203
+ const cachedRoute = resolvedRoutes.get(id)?.route;
1204
+ const closedTab = typeof result.releasedTabId === 'string' ? result.releasedTabId
1205
+ : cachedRoute?.sessionId === sessionId ? cachedRoute.tabId || null
1206
+ : id.state.recoveredSessionId === sessionId ? id.state.recoveredTabId
1207
+ : id.state.interactiveSessionId === sessionId ? id.state.interactiveTabId : null;
1208
+ if (result.sessionKept !== true || closedTab)
1209
+ id.state.lostRoute = { sessionId, tabId: closedTab };
1210
+ if (resolvedRoutes.get(id)?.route.sessionId === sessionId)
1211
+ resolvedRoutes.delete(id);
1212
+ if (id.state.interactiveSessionId === sessionId) {
1213
+ id.state.interactiveSessionId = null;
1214
+ id.state.interactiveTabId = null;
1215
+ }
1216
+ if (id.state.affinitySessionId === sessionId)
1217
+ id.state.affinitySessionId = null;
1218
+ if (id.state.recoveredSessionId === sessionId) {
1219
+ id.state.recoveredSessionId = null;
1220
+ id.state.recoveredTabId = null;
1221
+ }
1222
+ }
1223
+ return result;
731
1224
  }
732
1225
  // ── Navigation ──
733
1226
  export async function navigate(sessionId, url, tabId, returnSnapshot, snapshot, snapshotOptions, assist) {
@@ -881,9 +1374,10 @@ export async function consoleMessages(sessionId, tabId, opts) {
881
1374
  const qs = params.size ? `?${params}` : '';
882
1375
  return request('GET', `/api/browser/sessions/${sessionId}/console${qs}`);
883
1376
  }
884
- // ── Advanced ──
885
- export async function evaluate(sessionId, script, tabId) {
886
- return request('POST', `/api/browser/sessions/${sessionId}/evaluate`, { script, ...(tabId && { tabId }) }, LONG_TIMEOUT);
1377
+ /** `recover: false`: a missing session or tab is reported, never retried on a replacement tab (see request()). */
1378
+ export async function evaluate(sessionId, script, tabId, opts) {
1379
+ const pace = opts?.pace ? { platform: opts.pace.platform, maxWaitMs: Math.max(0, Math.floor(opts.pace.maxWaitMs || 0)) } : null;
1380
+ return request('POST', `/api/browser/sessions/${sessionId}/evaluate`, { script, ...(tabId && { tabId }), ...(pace && { pace }) }, LONG_TIMEOUT + (pace?.maxWaitMs || 0), { recover: opts?.recover });
887
1381
  }
888
1382
  export async function extract(sessionId, script, tabId, opts) {
889
1383
  return request('POST', `/api/browser/sessions/${sessionId}/extract`, {