synabun 2.2.1 → 2.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/README.md +1 -1
- package/hooks/claude-code/pre-websearch.mjs +4 -1
- package/hooks/claude-code/prompt-submit.mjs +7 -0
- package/lib/release-scan.mjs +23 -10
- package/lib/virustotal.mjs +143 -39
- package/mcp-server/dist/http.d.ts +19 -0
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +55 -13
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +14 -9
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-route-flow.d.ts +118 -0
- package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -0
- package/mcp-server/dist/services/browser-route-flow.js +339 -0
- package/mcp-server/dist/services/browser-route-flow.js.map +1 -0
- package/mcp-server/dist/services/desktop-client.js +2 -2
- package/mcp-server/dist/services/desktop-client.js.map +1 -1
- package/mcp-server/dist/services/identity.d.ts +66 -3
- package/mcp-server/dist/services/identity.d.ts.map +1 -1
- package/mcp-server/dist/services/identity.js +61 -4
- package/mcp-server/dist/services/identity.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +112 -1
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +555 -61
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/tools/bluesky.d.ts +20 -7
- package/mcp-server/dist/tools/bluesky.d.ts.map +1 -1
- package/mcp-server/dist/tools/bluesky.js +147 -45
- package/mcp-server/dist/tools/bluesky.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +11 -2
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +131 -18
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/browser-cheatsheet.d.ts +2 -0
- package/mcp-server/dist/tools/browser-cheatsheet.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-cheatsheet.js +3 -0
- package/mcp-server/dist/tools/browser-cheatsheet.js.map +1 -1
- package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
- package/mcp-server/dist/tools/morelogin.js +4 -2
- package/mcp-server/dist/tools/morelogin.js.map +1 -1
- package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
- package/mcp-server/dist/tools/youtube/helpers.d.ts +1 -0
- package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
- package/mcp-server/dist/tools/youtube/helpers.js +1 -1
- package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +58 -12
- package/mcp-server/src/index.ts +15 -9
- package/mcp-server/src/services/browser-route-flow.ts +402 -0
- package/mcp-server/src/services/desktop-client.ts +2 -2
- package/mcp-server/src/services/identity.ts +80 -4
- package/mcp-server/src/services/neural-interface.ts +572 -70
- package/mcp-server/src/tools/bluesky.ts +164 -51
- package/mcp-server/src/tools/browser-advanced.ts +121 -17
- package/mcp-server/src/tools/browser-cheatsheet.ts +3 -0
- package/mcp-server/src/tools/morelogin.ts +4 -2
- package/mcp-server/src/tools/youtube/helpers.ts +2 -2
- package/neural-interface/i18n/en.json +24 -0
- package/neural-interface/i18n/pt-BR.json +24 -0
- package/neural-interface/lib/assistant-api.js +64 -23
- package/neural-interface/lib/assistant-catalog.js +20 -2
- package/neural-interface/lib/assistant-dispatch.js +27 -1
- package/neural-interface/lib/assistant-persona.js +1 -0
- package/neural-interface/lib/assistant-runtime.js +15 -1
- package/neural-interface/lib/assistant-tools.js +10 -1
- package/neural-interface/lib/browser-automation-routes.js +84 -0
- package/neural-interface/lib/browser-execution.js +16 -3
- package/neural-interface/lib/browser-owner.js +48 -0
- package/neural-interface/lib/browser-session-close.js +84 -0
- package/neural-interface/lib/browser-start-handoff.js +202 -0
- package/neural-interface/lib/browser-tool-policy.js +21 -4
- package/neural-interface/lib/browser-wedge-retire.js +64 -0
- package/neural-interface/lib/claude-agent-bridge.js +36 -1
- package/neural-interface/lib/claude-background-hold.js +239 -0
- package/neural-interface/lib/exec-loop-command.js +8 -0
- package/neural-interface/lib/http-guards.js +11 -6
- package/neural-interface/lib/loop-logger.js +6 -1
- package/neural-interface/lib/mcp-external-servers.js +37 -10
- package/neural-interface/lib/native-loop-providers.js +121 -10
- package/neural-interface/lib/native-loop-runtime.js +112 -11
- package/neural-interface/lib/owner-authority.js +113 -37
- package/neural-interface/lib/page-session.js +81 -23
- package/neural-interface/lib/peer-identity.js +263 -43
- package/neural-interface/lib/provider-panel-api-key-auth.js +7 -2
- package/neural-interface/lib/pty-host/core.js +36 -0
- package/neural-interface/lib/pty-host/protocol.js +2 -0
- package/neural-interface/lib/skills/api-v2.js +13 -2
- package/neural-interface/lib/skills/creation-api.js +3 -1
- package/neural-interface/lib/skills/evals-api.js +5 -1
- package/neural-interface/lib/social-write-pacing.js +151 -0
- package/neural-interface/lib/terminal-token-redaction.js +293 -0
- package/neural-interface/lib/terminal-tokens.js +359 -0
- package/neural-interface/lib/worker-mcp-channel.js +45 -10
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/shared/agy/agy-render.js +41 -1
- package/neural-interface/public/shared/agy/agy-styles.js +5 -0
- package/neural-interface/public/shared/api.js +1 -0
- package/neural-interface/public/shared/assistant/asst-computer.js +47 -2
- package/neural-interface/public/shared/assistant/asst-limit-wait.js +3 -1
- package/neural-interface/public/shared/assistant/asst-panel.js +7 -3
- package/neural-interface/public/shared/assistant/asst-render.js +10 -4
- package/neural-interface/public/shared/assistant/asst-styles.js +2 -1
- package/neural-interface/public/shared/cdx/cdx-render.js +73 -7
- package/neural-interface/public/shared/cdx/cdx-tabs.js +3 -3
- package/neural-interface/public/shared/cp/cp-agents.js +8 -0
- package/neural-interface/public/shared/cp/cp-permissions.js +6 -2
- package/neural-interface/public/shared/cp/cp-rehydrate.js +25 -1
- package/neural-interface/public/shared/cp/cp-tasks-model.js +33 -0
- package/neural-interface/public/shared/judgments-log-origins.js +29 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +13 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-icons.js +3 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +4 -2
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +6 -86
- package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +5 -2
- package/neural-interface/public/shared/owner-access.js +134 -0
- package/neural-interface/public/shared/owner-authority-view.js +92 -0
- package/neural-interface/public/shared/page-session.js +143 -14
- package/neural-interface/public/shared/poll-backoff.js +59 -0
- package/neural-interface/public/shared/settings/settings-data.js +6 -1
- package/neural-interface/public/shared/settings/settings-kit.js +11 -3
- package/neural-interface/public/shared/settings/settings-shell.js +7 -0
- package/neural-interface/public/shared/shown-children.js +72 -0
- package/neural-interface/public/shared/static-bg-state.js +22 -0
- package/neural-interface/public/shared/styles.css +101 -7
- package/neural-interface/public/shared/synabun-tools.js +173 -0
- package/neural-interface/public/shared/tool-heartbeat.js +43 -0
- package/neural-interface/public/shared/tool-list-picker.js +3 -1
- package/neural-interface/public/shared/tool-list-view.js +23 -4
- package/neural-interface/public/shared/ui-automation-studio.js +8 -1
- package/neural-interface/public/shared/ui-claude-panel.js +159 -29
- package/neural-interface/public/shared/ui-judgments.js +37 -10
- package/neural-interface/public/shared/ui-navbar.js +6 -0
- package/neural-interface/public/shared/ui-owner-access.js +191 -0
- package/neural-interface/public/shared/ui-owner-authority.js +162 -0
- package/neural-interface/public/shared/ui-sessions.js +45 -16
- package/neural-interface/public/shared/ui-settings.js +86 -15
- package/neural-interface/public/shared/ui-terminal.js +15 -7
- package/neural-interface/public/shared/ui-tutorial-preview.js +4 -0
- package/neural-interface/public/shared/ui-update.js +3 -0
- package/neural-interface/public/shared/ui-whiteboard.js +4 -0
- package/neural-interface/public/shared/window-keys.js +38 -0
- package/neural-interface/server.js +1160 -205
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { readStoredToolListRecord, toolListRecordForUpdate } from './lib/tool-lists.js';
|
|
2
|
-
import { externalServerInventory, selectExternalServers,
|
|
2
|
+
import { externalServerInventory, selectExternalServers, externalCatalogReport, mergeExternalAvailability, EXTERNAL_SERVER_LIMITATIONS, scopeOpenCodeServers, retainExternalRefs, writePrivateMcpConfig, redactMcpValues, mcpSecretValues } from './lib/mcp-external-servers.js';
|
|
3
3
|
import { openCodeWorkerData } from './lib/opencode-worker-data.js';
|
|
4
4
|
import { resumeSandboxPlan } from './lib/worker-resume.js';
|
|
5
5
|
import { waitForSynabunTools, synabunConfigured, invalidateSynabunTools, synabunToolsTimeoutText } from './lib/opencode-mcp-ready.js';
|
|
@@ -26,7 +26,7 @@ import { createWorkerMcpChannel } from './lib/worker-mcp-channel.js';
|
|
|
26
26
|
import { createPageSession, PAGE_SECRET_PATHS, PAGE_SECRET_REFRESH_PATH, SERVICE_WORKER_PATH } from './lib/page-session.js';
|
|
27
27
|
import { normalizeViewUrl } from './public/shared/view-variant.js';
|
|
28
28
|
import { createPeerIdentity, debugClientPolicy } from './lib/peer-identity.js';
|
|
29
|
-
import { createOwnerAuthority } from './lib/owner-authority.js';
|
|
29
|
+
import { createOwnerAuthority, isAgentCall } from './lib/owner-authority.js';
|
|
30
30
|
import { collectRelayListenerPorts, localProxyPorts } from './lib/worker-relay-ports.js';
|
|
31
31
|
import { machineNames } from './lib/machine-names.js';
|
|
32
32
|
import { draftConfinementSupport } from './lib/skills/draft-confinement.js';
|
|
@@ -36,7 +36,14 @@ import { createProviderPanelTerminalAuth, providerLoginSpec, registerProviderPan
|
|
|
36
36
|
import { claudeLegacyPricing, claudeUsageCostUsd } from './lib/assistant-pricing.js';
|
|
37
37
|
import { HOOK_SCRIPTS, hookDefinitionsForEvent, hookCommandString, hookInstallBlocker, hookInstallPlan, isSynaBunHookCommand, sweepSettingsHooks, ensureHookRoot } from '../lib/claude-hooks.js';
|
|
38
38
|
import { claudeHooksStatus } from './lib/claude-hooks-status.js';
|
|
39
|
-
import {
|
|
39
|
+
import { createBrowserStartHandoff, startWaitMs } from './lib/browser-start-handoff.js';
|
|
40
|
+
import { browserRequestDeadline, browserV2Enabled, browserRequestMiddleware, assertBrowserRequestActive, browserActionTimeout, markBrowserActionStarted, runBrowserRequest, cancellableBrowserDelay, measureBrowserPhase, createEngagementScheduler, engagementTargetSelector, isEngagementWriteSelector, isXShortcutPublish, isXScriptedWrite } from './lib/browser-execution.js';
|
|
41
|
+
import { sessionCloseDecision, profileStopDecision, otherSessionOwners } from './lib/browser-session-close.js';
|
|
42
|
+
import { isAutomationBrowserRoute, ownerOnlyCreateFields } from './lib/browser-automation-routes.js';
|
|
43
|
+
import { browserOwnerId, listedOwners } from './lib/browser-owner.js';
|
|
44
|
+
import { createTerminalTokenRegistry, TERMINAL_TOKEN_ENV, TERMINAL_TOKEN_HEADER, BRAIN_CREDENTIAL_HEADER, redactTerminalSecrets } from './lib/terminal-tokens.js';
|
|
45
|
+
import { decideFailedTabRecovery } from './lib/browser-wedge-retire.js';
|
|
46
|
+
import { createSocialWritePacer, socialPaceAccountKey, socialPaceRequest, socialPacingBlock, SOCIAL_PACE_LIMITS, SOCIAL_WRITE_GAPS } from './lib/social-write-pacing.js';
|
|
40
47
|
import { describeLocatorMatches, healLocatorByText, validNthMatch, captureTargetIdentity, matchesTargetIdentity } from './lib/browser-targets.js';
|
|
41
48
|
import { getInteractiveHints, collectSemanticContext, buildAssist, describeTargetFacts, verifyHealTarget, createAssistContextStore } from './lib/browser-semantic-context.js';
|
|
42
49
|
import { createBrowserAssistRouter } from './lib/browser-assist-api.js';
|
|
@@ -204,7 +211,7 @@ import {
|
|
|
204
211
|
LIVE_DATA_ENV,
|
|
205
212
|
} from './lib/native-loop-providers.js';
|
|
206
213
|
import { createOpenCodeActivityRelay } from './lib/opencode-worker-activity.js';
|
|
207
|
-
import { browserServePortDenial } from './lib/browser-tool-policy.js';
|
|
214
|
+
import { browserServePortDenial, browserSessionLossRule } from './lib/browser-tool-policy.js';
|
|
208
215
|
import { createNativeServeBoundary, nativeServeCapability, nativeServeReason, narrowOffenders } from './lib/opencode-native-boundary.js';
|
|
209
216
|
const nativeServeBoundary = createNativeServeBoundary();
|
|
210
217
|
import { setBrowserNetworkRule, usesNativeBrowserNetworkGuard, disposeBrowserNetworkGuard, recoverBrowserNetworkGuard, MONEY_PATTERNS, SERVE_PORT_PATTERNS } from './lib/browser-network-guard.js';
|
|
@@ -555,11 +562,17 @@ app.use(requestGates.features);
|
|
|
555
562
|
// for automation, an AI agent's process tree, another SynaBun server or a relay (ssh, socat, a proxy, a tunnel, any
|
|
556
563
|
// program that listens and calls SynaBun) is never handed the secret and never counts as the owner, whatever host,
|
|
557
564
|
// cookie or marker it sends. A brain credential (X-Synabun-Brain-Token) from a process outside the brain's own tree
|
|
558
|
-
// is dropped from the request.
|
|
559
|
-
//
|
|
565
|
+
// is dropped from the request. Where the lookup does not run (Windows, Linux, SYNABUN_PEER_IDENTITY=off) nothing
|
|
566
|
+
// changes: the rules from before apply. On macOS a lookup that fails (netstat or ps missing, denied, slow past the
|
|
567
|
+
// cap) is no proof of who is asking: no page secret, no brain credential, and the owner's writes, reads and sockets
|
|
568
|
+
// answer 503 PEER_UNAVAILABLE until a lookup works again (the start probe below says so in the log at once, GET
|
|
569
|
+
// /api/health says so as `ownerAuthority`, and the page shows a banner). Mounted here, in front of every route (the
|
|
570
|
+
// page secret's pieces are made further down and read only when a request comes).
|
|
560
571
|
// This install's root (PACKAGE_ROOT, defined further down): SynaBun's own MCP server over HTTP is the one listening
|
|
561
572
|
// program the lookup knows, by its main script under it (mcp-server/dist/http.js, `npm run start:http`).
|
|
562
573
|
const _peerIdentity = createPeerIdentity({ log: (line) => console.warn(line), disabled: String(process.env.SYNABUN_PEER_IDENTITY || '').toLowerCase() === 'off', synabunRoots: [resolve(__dirname, '..')], debugClient: startedDebugClient });
|
|
574
|
+
// netstat and ps once, now: a server that cannot identify its callers says so before the first owner's request does.
|
|
575
|
+
_peerIdentity.probe();
|
|
563
576
|
// The one decision for the owner's routes and sockets (lib/owner-authority.js): every write to /api but the hooks'
|
|
564
577
|
// and the agents' feature data, the two reads that hand out a secret, and the owner's sockets are refused to the
|
|
565
578
|
// automation browser (its marker or its process), relays, other SynaBun servers, remote logins and an agent's tree
|
|
@@ -2416,6 +2429,11 @@ async function runGracefulShutdown(reason) {
|
|
|
2416
2429
|
let keepRuns = [];
|
|
2417
2430
|
try { keepRuns = _assistantDispatcher?.suspendForShutdown?.(reason) || []; } catch (err) { console.warn(' assistant suspend err:', err?.message); }
|
|
2418
2431
|
try { await _nativeLoopRuntime?.shutdown(reason, { keep: keepRuns }); } catch (err) { console.warn(' native loop stop err:', err?.message); }
|
|
2432
|
+
// Browser starts kept for a caller that never came back (lib/browser-start-handoff.js): closed now, never left open
|
|
2433
|
+
// in MoreLogin after the server is gone; a start still running is closed when it finishes. Bounded wait.
|
|
2434
|
+
try {
|
|
2435
|
+
await Promise.race([browserStartHandoff.clear(), new Promise((r) => setTimeout(r, 1500).unref?.())]);
|
|
2436
|
+
} catch (err) { console.warn(' browser start handoff clear err:', err?.message); }
|
|
2419
2437
|
try { stopAllIsolatedServes(); } catch (err) { console.warn(' isolated opencode stop err:', err?.message); }
|
|
2420
2438
|
// The Antigravity panel's `agy acp` processes (one per open panel socket).
|
|
2421
2439
|
try { await antigravityPanel.closeAll(); } catch (err) { console.warn(' antigravity panel stop err:', err?.message); }
|
|
@@ -4100,6 +4118,10 @@ function codexSandboxArgs() { return codexWindowsSandboxArgs(adminSandboxOn());
|
|
|
4100
4118
|
// live restart never loses worker dispatch to a sandbox that could not be built. Codex is handled differently
|
|
4101
4119
|
// (its own sandbox cannot be wrapped): a guarded Codex worker runs with its network off (lib/native-loop-providers.js).
|
|
4102
4120
|
let _workerMcpChannel = null;
|
|
4121
|
+
// Who a run is (lib/terminal-tokens.js): one token per run SynaBun starts (an agent, a terminal or exec loop, a native
|
|
4122
|
+
// run, a dispatched worker), minted with its terminal id, handed to that run's SynaBun MCP alone, revoked at its end.
|
|
4123
|
+
// The browser routes take a run's X-Synabun-Terminal only with that run's token (browserCaller). In memory only.
|
|
4124
|
+
const _terminalTokens = createTerminalTokenRegistry({ log: (line) => console.warn(line) });
|
|
4103
4125
|
/** The launch beacon's loopback port (lib/start-launcher.js startBeaconPort): a SynaBun listener while a launch lives. */
|
|
4104
4126
|
function workerBeaconPort() { const p = Number(PORT) || 3344; return p + 10000 <= 65535 ? p + 10000 : p - 10000; }
|
|
4105
4127
|
/** Browser-control ports a guarded worker must not reach, by fixed knowledge (dynamic ones come from detection,
|
|
@@ -4631,6 +4653,9 @@ CRITICAL — When you need clarification during planning:
|
|
|
4631
4653
|
if (_codexToolsRuntimes.get(codexMcpRuntimeId) === codexMcpRuntimeBinding) {
|
|
4632
4654
|
_codexToolsRuntimes.delete(codexMcpRuntimeId);
|
|
4633
4655
|
}
|
|
4656
|
+
// Every end of this connection's app-server comes through here: its MCP child's proof goes with it (the next
|
|
4657
|
+
// app-server gets a new one), and the id is refused until then.
|
|
4658
|
+
_terminalTokens.revoke(codexMcpRuntimeId);
|
|
4634
4659
|
cancelRuntimeMcpToolsRefresh(codexMcpRuntimeId);
|
|
4635
4660
|
codexMcpRuntimeBinding = null;
|
|
4636
4661
|
if (cleanup) cleanupCodexRuntimeTools(codexMcpRuntimeId);
|
|
@@ -5772,6 +5797,13 @@ CRITICAL — When you need clarification during planning:
|
|
|
5772
5797
|
activeCodexHome = launch.home;
|
|
5773
5798
|
let codexBin = getCodexBin();
|
|
5774
5799
|
const runtimeToolsPath = writeCodexRuntimeTools(codexMcpRuntimeId, ['all']);
|
|
5800
|
+
// The MCP child's proof of codexMcpRuntimeId (lib/terminal-tokens.js): an Assistant brain's launch credential, bound
|
|
5801
|
+
// to it (no second secret: the child already holds it), else a token of this app-server's own, new with every
|
|
5802
|
+
// process. Its value is only in the app-server's environment, forwarded to the MCP child by name (env_vars), never
|
|
5803
|
+
// on this command line; Codex's default shell policy keeps a *TOKEN* variable out of the commands it runs.
|
|
5804
|
+
let codexTerminalToken = null;
|
|
5805
|
+
if (codexRole === 'assistant' && codexBrainCredential) _terminalTokens.bind(codexMcpRuntimeId, codexBrainCredential);
|
|
5806
|
+
else codexTerminalToken = _terminalTokens.rotate(codexMcpRuntimeId);
|
|
5775
5807
|
const args = [
|
|
5776
5808
|
'-c',
|
|
5777
5809
|
`mcp_servers.SynaBun.env.SYNABUN_TOOLS=${JSON.stringify('all')}`,
|
|
@@ -5792,6 +5824,7 @@ CRITICAL — When you need clarification during planning:
|
|
|
5792
5824
|
if (codexDesktopGrant) args.splice(args.length - 1, 0, '-c', `mcp_servers.SynaBun.env.SYNABUN_DESKTOP_GRANT=${JSON.stringify(codexDesktopGrant)}`);
|
|
5793
5825
|
// The variable's name on the command line, its value only in the app-server's environment (below).
|
|
5794
5826
|
if (codexRole === 'assistant' && codexBrainCredential) args.splice(args.length - 1, 0, '-c', 'mcp_servers.SynaBun.env_vars=["SYNABUN_BRAIN_TOKEN"]');
|
|
5827
|
+
else if (codexTerminalToken) args.splice(args.length - 1, 0, '-c', `mcp_servers.SynaBun.env_vars=["${TERMINAL_TOKEN_ENV}"]`);
|
|
5795
5828
|
if (codexRole === 'assistant' && codexRouteGate?.flags?.length) args.splice(args.length - 1, 0, ...codexRouteGate.flags);
|
|
5796
5829
|
if (/\.js$/i.test(codexBin)) {
|
|
5797
5830
|
args.unshift(codexBin);
|
|
@@ -5812,9 +5845,12 @@ CRITICAL — When you need clarification during planning:
|
|
|
5812
5845
|
...(codexDesktopGrant ? { SYNABUN_DESKTOP_GRANT: codexDesktopGrant } : {}),
|
|
5813
5846
|
...(codexRole === 'assistant' && codexRouteGate?.env ? codexRouteGate.env : {}),
|
|
5814
5847
|
...(codexRole === 'assistant' && codexBrainCredential ? { SYNABUN_BRAIN_TOKEN: codexBrainCredential } : {}),
|
|
5848
|
+
...(codexTerminalToken ? { [TERMINAL_TOKEN_ENV]: codexTerminalToken } : {}),
|
|
5815
5849
|
};
|
|
5816
5850
|
// Never one inherited from the launching shell: only this brain's own credential reaches its MCP child.
|
|
5817
5851
|
if (!(codexRole === 'assistant' && codexBrainCredential)) delete env.SYNABUN_BRAIN_TOKEN;
|
|
5852
|
+
// …and only this app-server's own terminal token.
|
|
5853
|
+
if (!codexTerminalToken) delete env[TERMINAL_TOKEN_ENV];
|
|
5818
5854
|
delete env.FORCE_COLOR;
|
|
5819
5855
|
delete env.CLICOLOR_FORCE;
|
|
5820
5856
|
const proc = spawn(shellCommand(codexBin, useShell, { isFile: existsSync }), args, {
|
|
@@ -8436,7 +8472,9 @@ function broadcastToOpencodeV2Clients(data, { nativeRunId = null } = {}) {
|
|
|
8436
8472
|
nativeRootSessionId,
|
|
8437
8473
|
}
|
|
8438
8474
|
: data;
|
|
8439
|
-
|
|
8475
|
+
// An OpenCode panel's, brain's or run's output never carries a SynaBun run secret an agent printed (its serve's
|
|
8476
|
+
// environment holds the panel's token or the brain's credential): lib/terminal-token-redaction.js.
|
|
8477
|
+
const payload = JSON.stringify(redactTerminalSecrets(wireData));
|
|
8440
8478
|
for (const ws of _ocpV2WsClients) {
|
|
8441
8479
|
if (nativeRun && !opencodeV2ClientOwnsRun(ws, nativeRun)) continue;
|
|
8442
8480
|
if (ws.readyState === 1) {
|
|
@@ -8569,6 +8607,7 @@ function killIsolatedServeProcess(proc) {
|
|
|
8569
8607
|
// bindings and its config folder, which has the same path.
|
|
8570
8608
|
function endIsolatedStart(termId, entry) {
|
|
8571
8609
|
if (_ocpIsoServes.get(termId) === entry) { stopIsolatedServe(termId); return; }
|
|
8610
|
+
// A start a newer one replaced: its own proof was replaced too (the newer start bound or rotated the id).
|
|
8572
8611
|
try { entry.unsub?.(); } catch {}
|
|
8573
8612
|
try { entry.client?.stop(); } catch {}
|
|
8574
8613
|
killIsolatedServeProcess(entry.proc);
|
|
@@ -8649,7 +8688,7 @@ function buildOpencodeRuntimeConfigOverlay(xdgRoot, { unattended = false } = {})
|
|
|
8649
8688
|
return JSON.stringify(overlay);
|
|
8650
8689
|
}
|
|
8651
8690
|
|
|
8652
|
-
function setupOpencodeSidepanelConfig(termId, selection = null, { cwd = PACKAGE_ROOT, scopeExternal = true } = {}) {
|
|
8691
|
+
function setupOpencodeSidepanelConfig(termId, selection = null, { cwd = PACKAGE_ROOT, scopeExternal = true, terminalToken = false } = {}) {
|
|
8653
8692
|
const xdgRoot = resolve(DATA_HOME, 'data', 'sidepanel-configs', `opencode-${termId}`);
|
|
8654
8693
|
const targetDir = resolve(xdgRoot, 'opencode');
|
|
8655
8694
|
if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });
|
|
@@ -8669,8 +8708,11 @@ function setupOpencodeSidepanelConfig(termId, selection = null, { cwd = PACKAGE_
|
|
|
8669
8708
|
SYNABUN_TERMINAL_SESSION: termId,
|
|
8670
8709
|
SYNABUN_TOOLS: runtimeToolsValue(resolvedTools),
|
|
8671
8710
|
SYNABUN_TOOLS_PATH: runtimeToolsPath,
|
|
8711
|
+
// A side panel's serve: its token's name only, never its value (only the serve's environment holds it; OpenCode
|
|
8712
|
+
// expands the reference for the MCP child). ensureIsolatedServe({ panelToken }).
|
|
8713
|
+
...(terminalToken ? { [TERMINAL_TOKEN_ENV]: `{env:${TERMINAL_TOKEN_ENV}}` } : {}),
|
|
8672
8714
|
},
|
|
8673
|
-
clearEnv: ['SYNABUN_BROWSER_SESSION', 'SYNABUN_BROWSER_TAB', 'CLAUDECODE', 'SYNABUN_PROFILE', 'SYNABUN_RUNTIME_PROFILE_PATH'],
|
|
8715
|
+
clearEnv: ['SYNABUN_BROWSER_SESSION', 'SYNABUN_BROWSER_TAB', 'CLAUDECODE', 'SYNABUN_PROFILE', 'SYNABUN_RUNTIME_PROFILE_PATH', ...(terminalToken ? [] : [TERMINAL_TOKEN_ENV])],
|
|
8674
8716
|
}));
|
|
8675
8717
|
ensureOpenCodeCoreMcpPermissions(baseCfg);
|
|
8676
8718
|
if (scopeExternal) applyOpenCodeExternalScope(xdgRoot, baseCfg, resolvedTools, cwd);
|
|
@@ -8694,7 +8736,7 @@ function updateOpencodeRuntimeToolsConfig(xdgRoot, selection) {
|
|
|
8694
8736
|
return true;
|
|
8695
8737
|
}
|
|
8696
8738
|
|
|
8697
|
-
async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, cwd = PACKAGE_ROOT, keepAlive = false, tools = undefined, brainCredential = null, worker = false, sandboxProfile = null, extraEnv = null, hidePassword = false, persistentData = false } = {}) {
|
|
8739
|
+
async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, cwd = PACKAGE_ROOT, keepAlive = false, tools = undefined, brainCredential = null, worker = false, sandboxProfile = null, extraEnv = null, hidePassword = false, persistentData = false, terminalToken = null, panelToken = false } = {}) {
|
|
8698
8740
|
if (_ocpHistoryClearInProgress) throw new Error('OpenCode history is being cleared');
|
|
8699
8741
|
const requestedTools = toolsFromSelection(tools);
|
|
8700
8742
|
let entry = _ocpIsoServes.get(termId);
|
|
@@ -8717,10 +8759,10 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8717
8759
|
const refusal = await opencodeStartRefusal();
|
|
8718
8760
|
if (refusal) { console.warn(`[ocp-iso] serve ${termId.slice(-8)}: ${refusal.message}`); throw refusal; }
|
|
8719
8761
|
let xdgRoot;
|
|
8720
|
-
try { xdgRoot = requestedXdgRoot || setupOpencodeSidepanelConfig(termId, requestedTools, { cwd }); }
|
|
8762
|
+
try { xdgRoot = requestedXdgRoot || setupOpencodeSidepanelConfig(termId, requestedTools, { cwd, terminalToken: !!panelToken && !terminalToken && !brainCredential }); }
|
|
8721
8763
|
catch (err) { console.warn(`[ocp-iso] config setup failed: ${err.message}`); return null; }
|
|
8722
8764
|
// Registered before anything is waited for: a second start for the same term id waits for this one.
|
|
8723
|
-
entry = { termId, port: null, xdgRoot, persistentData, tools: requestedTools, toolsRefreshFailed: false, proc: null, client: null, ready: false, starting: true, keepAlive: !!keepAlive, unsub: null, sessions: new Set(), lastUsed: Date.now() };
|
|
8765
|
+
entry = { termId, port: null, xdgRoot, persistentData, tools: requestedTools, toolsRefreshFailed: false, proc: null, client: null, ready: false, starting: true, keepAlive: !!keepAlive, unsub: null, sessions: new Set(), lastUsed: Date.now(), ownProof: null };
|
|
8724
8766
|
_ocpIsoServes.set(termId, entry);
|
|
8725
8767
|
// What an earlier SynaBun left running goes first (its ports with it); then the port is picked.
|
|
8726
8768
|
await sweepLeftoverOpencodeServes();
|
|
@@ -8733,6 +8775,13 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8733
8775
|
if (port == null) { console.warn('[ocp-iso] no free port for isolated serve'); endIsolatedStart(termId, entry); return null; }
|
|
8734
8776
|
entry.port = port;
|
|
8735
8777
|
try {
|
|
8778
|
+
// What the serve's SynaBun MCP child proves termId with (lib/terminal-tokens.js): a run's token (handed in by its
|
|
8779
|
+
// provider), an Assistant brain's launch credential (bound to termId: the credential the child already has is its
|
|
8780
|
+
// proof, no second secret), or a side panel's own token (panelToken), new with every serve. A brain's or a panel's
|
|
8781
|
+
// proof is this serve's: revoked when it stops (stopIsolatedServe). A run's is its runtime's (revoked at its end).
|
|
8782
|
+
let serveToken = terminalToken || null;
|
|
8783
|
+
if (brainCredential) { if (_terminalTokens.bind(termId, brainCredential)) entry.ownProof = 'brain'; }
|
|
8784
|
+
else if (!serveToken && panelToken) { serveToken = _terminalTokens.rotate(termId); if (serveToken) entry.ownProof = 'panel'; }
|
|
8736
8785
|
const isolatedEnv = {
|
|
8737
8786
|
...process.env,
|
|
8738
8787
|
XDG_CONFIG_HOME: xdgRoot,
|
|
@@ -8745,12 +8794,17 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8745
8794
|
// Keep this above the script's own deadlines while retaining a hard cap.
|
|
8746
8795
|
OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS:
|
|
8747
8796
|
process.env.OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS || '300000',
|
|
8797
|
+
// A run's terminal token (lib/terminal-tokens.js): its loop config names it ({env:SYNABUN_TERMINAL_TOKEN},
|
|
8798
|
+
// setupOpencodeLoopConfig), only this serve's environment holds it (never one this server inherited: below).
|
|
8799
|
+
// A side panel's serve holds its own the same way (setupOpencodeSidepanelConfig names it).
|
|
8800
|
+
...(serveToken ? { [TERMINAL_TOKEN_ENV]: serveToken } : {}),
|
|
8748
8801
|
// A WhatsApp conversation's brain credential: the config names it ({env:SYNABUN_BRAIN_TOKEN}), only this
|
|
8749
8802
|
// serve's environment holds it (a fresh serve per brain launch: the brain stops its serve when it ends).
|
|
8750
8803
|
...(brainCredential ? { SYNABUN_BRAIN_TOKEN: brainCredential } : {}),
|
|
8751
8804
|
};
|
|
8752
8805
|
delete isolatedEnv.CLAUDECODE;
|
|
8753
8806
|
if (!brainCredential) delete isolatedEnv.SYNABUN_BRAIN_TOKEN;
|
|
8807
|
+
if (!serveToken) delete isolatedEnv[TERMINAL_TOKEN_ENV];
|
|
8754
8808
|
// A run's own settings for its serve (an evaluation run's, a protected worker's: lib/native-loop-providers.js
|
|
8755
8809
|
// openCodeRunEnvFor), last: a string is set, null removes the variable (an inherited OPENCODE_CONFIG_DIR, GIT_DIR).
|
|
8756
8810
|
if (extraEnv && typeof extraEnv === 'object') {
|
|
@@ -8914,6 +8968,8 @@ function stopIsolatedServe(termId, { preserveBindings = false } = {}) {
|
|
|
8914
8968
|
if (!entry) return;
|
|
8915
8969
|
cancelRuntimeMcpToolsRefresh(termId);
|
|
8916
8970
|
_ocpIsoServes.delete(termId);
|
|
8971
|
+
// A panel's or a brain's proof ends with its serve (a run's token is its runtime's, revoked at the run's end).
|
|
8972
|
+
if (entry.ownProof) _terminalTokens.revoke(termId);
|
|
8917
8973
|
if (!preserveBindings) {
|
|
8918
8974
|
for (const sid of entry.sessions) {
|
|
8919
8975
|
if (_ocpSessionToServe.get(sid) === termId) _ocpSessionToServe.delete(sid);
|
|
@@ -8966,7 +9022,7 @@ async function turnClientForSession(sessionId, requestedTools = null) {
|
|
|
8966
9022
|
const session = await opencodeV2Client.session.get({ sessionID: sessionId });
|
|
8967
9023
|
const cwd = session?.data?.directory;
|
|
8968
9024
|
if (!cwd) throw new Error('OpenCode session directory is unavailable for MCP scope discovery');
|
|
8969
|
-
const entry = await ensureIsolatedServe(termId, { tools, cwd });
|
|
9025
|
+
const entry = await ensureIsolatedServe(termId, { tools, cwd, panelToken: true });
|
|
8970
9026
|
if (!entry || !entry.client) throw new Error('OpenCode isolated session runtime failed to start');
|
|
8971
9027
|
// Publish the binding only after the isolated serve is ready. Every waiter
|
|
8972
9028
|
// shares this promise, so one cold session can never fork two serves.
|
|
@@ -9033,14 +9089,14 @@ async function restartOpenCodeSessionTools(sessionId, selection) {
|
|
|
9033
9089
|
_ocpSessionTools.set(familySessionId, tools);
|
|
9034
9090
|
}
|
|
9035
9091
|
let entry, startError;
|
|
9036
|
-
try { entry = await ensureIsolatedServe(termId, { tools, cwd }); }
|
|
9092
|
+
try { entry = await ensureIsolatedServe(termId, { tools, cwd, panelToken: true }); }
|
|
9037
9093
|
catch (error) { startError = error; }
|
|
9038
9094
|
if (!entry?.client) {
|
|
9039
9095
|
for (const familySessionId of familySessionIds) {
|
|
9040
9096
|
_ocpSessionToServe.set(familySessionId, termId);
|
|
9041
9097
|
_ocpSessionTools.set(familySessionId, previousTools);
|
|
9042
9098
|
}
|
|
9043
|
-
try { entry = await ensureIsolatedServe(termId, { tools: previousTools, cwd }); }
|
|
9099
|
+
try { entry = await ensureIsolatedServe(termId, { tools: previousTools, cwd, panelToken: true }); }
|
|
9044
9100
|
catch { entry = null; }
|
|
9045
9101
|
if (entry?.client) {
|
|
9046
9102
|
for (const familySessionId of familySessionIds) entry.sessions.add(familySessionId);
|
|
@@ -9153,7 +9209,8 @@ function handleOpencodeV2Ws(ws) {
|
|
|
9153
9209
|
|
|
9154
9210
|
const send = (data) => {
|
|
9155
9211
|
if (ws.readyState === 1) {
|
|
9156
|
-
|
|
9212
|
+
// A session's history and every answer of this socket: scrubbed of SynaBun's run secrets like the broadcast.
|
|
9213
|
+
try { ws.send(JSON.stringify(redactTerminalSecrets(data))); } catch {}
|
|
9157
9214
|
}
|
|
9158
9215
|
};
|
|
9159
9216
|
// Request bodies that live in lib/opencode-v2-ws-requests.js get these.
|
|
@@ -10801,6 +10858,9 @@ const _claudeBridgeReady = (async () => {
|
|
|
10801
10858
|
// Per-chat-session SynaBun MCP entry (HTTP + X-Synabun-Terminal header)
|
|
10802
10859
|
// so each sidepanel session gets its own browser tab.
|
|
10803
10860
|
mcpUrl: `http://localhost:${PORT}/mcp`,
|
|
10861
|
+
// A panel tab's id is proven by a token of its own (lib/terminal-tokens.js): minted with every CLI process the
|
|
10862
|
+
// tab starts, named by its MCP header, revoked when the tab's session ends.
|
|
10863
|
+
terminalTokens: _terminalTokens,
|
|
10804
10864
|
// In-process release of a sidepanel session's owned tab on destroy.
|
|
10805
10865
|
releaseBrowserOwner: (ownerKey) => {
|
|
10806
10866
|
if (!ownerKey) return;
|
|
@@ -14528,6 +14588,8 @@ app.post('/api/sidepanel-runs/:runId/release', (req, res) => {
|
|
|
14528
14588
|
// POST /api/loop/launch — create loop state + provider runtime atomically
|
|
14529
14589
|
app.post('/api/loop/launch', async (req, res) => {
|
|
14530
14590
|
let pendingNativeBrowserCleanup = null;
|
|
14591
|
+
// A terminal or exec loop's terminal token (lib/terminal-tokens.js), revoked when the launch fails before it runs.
|
|
14592
|
+
let issuedLoopTerminal = null;
|
|
14531
14593
|
try {
|
|
14532
14594
|
const { task: rawTask, context, iterations, maxMinutes, usesBrowser, cwd, profile, model: requestedModel, contextMode: requestedContextMode, effort, tools, platform, codexAccountId, browserSessionId: requestedBrowserSessionId, sidepanelWindowId, sidepanelClaimToken } = req.body;
|
|
14533
14595
|
if (!rawTask?.trim()) return res.status(400).json({ error: 'task is required' });
|
|
@@ -14608,6 +14670,9 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14608
14670
|
let browserTabId = null;
|
|
14609
14671
|
const terminalSessionId = randomBytes(16).toString('hex');
|
|
14610
14672
|
loopLog(terminalSessionId, 'launch:id', 'minted terminalSessionId', { terminalSessionId });
|
|
14673
|
+
// A terminal or exec loop's token is minted with its id; a native run's by its runtime (NativeLoopRuntime.launch).
|
|
14674
|
+
const loopTerminalToken = nativeRuntime ? null : _terminalTokens.issue(terminalSessionId);
|
|
14675
|
+
if (loopTerminalToken) issuedLoopTerminal = terminalSessionId;
|
|
14611
14676
|
if (usesBrowser) {
|
|
14612
14677
|
// Serialized reuse-or-create of the shared loop browser + a dedicated tab.
|
|
14613
14678
|
// The mutex inside acquireLoopBrowserAndTab() prevents concurrent launches
|
|
@@ -14669,6 +14734,10 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14669
14734
|
// SYNABUN_TERMINAL_SESSION lets hooks correlate with the correct loop file
|
|
14670
14735
|
// after /clear changes the Claude session ID. This is the key to multi-loop isolation.
|
|
14671
14736
|
const loopExtraEnv = { SYNABUN_TERMINAL_SESSION: terminalSessionId };
|
|
14737
|
+
// The loop's terminal token, in the PTY's environment only: its MCP config names the variable (Claude Code's
|
|
14738
|
+
// header, OpenCode's {env:…}), Codex forwards it by name (env_vars), Antigravity's MCP child inherits it. The
|
|
14739
|
+
// launch logs below name the keys of this environment, never its values.
|
|
14740
|
+
if (loopTerminalToken) loopExtraEnv[TERMINAL_TOKEN_ENV] = loopTerminalToken;
|
|
14672
14741
|
if (browserSessionId) loopExtraEnv.SYNABUN_BROWSER_SESSION = browserSessionId;
|
|
14673
14742
|
if (browserTabId) loopExtraEnv.SYNABUN_BROWSER_TAB = browserTabId;
|
|
14674
14743
|
// Codex reads auth.json from CODEX_HOME — pin the selected ChatGPT account.
|
|
@@ -14697,7 +14766,7 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14697
14766
|
browserSessionId,
|
|
14698
14767
|
browserTabId,
|
|
14699
14768
|
cliTools,
|
|
14700
|
-
model, {}, { cwd: loopCwd },
|
|
14769
|
+
model, {}, { cwd: loopCwd, terminalToken: !!loopTerminalToken },
|
|
14701
14770
|
);
|
|
14702
14771
|
if (xdgRoot) {
|
|
14703
14772
|
loopExtraEnv.XDG_CONFIG_HOME = xdgRoot;
|
|
@@ -14784,8 +14853,9 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14784
14853
|
}
|
|
14785
14854
|
|
|
14786
14855
|
// Browser ownership is now held by the successfully launched PTY; normal
|
|
14787
|
-
// loop-stop cleanup owns it from this point onward.
|
|
14856
|
+
// loop-stop cleanup owns it from this point onward (its terminal token too: endAutomationBrowser revokes it).
|
|
14788
14857
|
pendingNativeBrowserCleanup = null;
|
|
14858
|
+
issuedLoopTerminal = null;
|
|
14789
14859
|
broadcastSync({ type: 'terminal:session-created', sessionId: terminalSessionId, profile: cliProfile });
|
|
14790
14860
|
|
|
14791
14861
|
const responsePayload = {
|
|
@@ -14809,6 +14879,8 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14809
14879
|
pendingNativeBrowserCleanup.ownerKey,
|
|
14810
14880
|
).catch(() => {});
|
|
14811
14881
|
}
|
|
14882
|
+
// The loop never ran: nothing may act as it.
|
|
14883
|
+
if (issuedLoopTerminal) _terminalTokens.revoke(issuedLoopTerminal);
|
|
14812
14884
|
loopLog(null, 'launch:error', 'POST /api/loop/launch threw', { err: err.message, stack: err.stack?.slice(0, 800) });
|
|
14813
14885
|
res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
|
|
14814
14886
|
}
|
|
@@ -14816,9 +14888,24 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14816
14888
|
|
|
14817
14889
|
// POST /api/loop/stop — force-stop loops and clean up PTY sessions
|
|
14818
14890
|
// Body: { runId?: string, terminalSessionId?: string } — if provided, stop only that loop; otherwise stop all
|
|
14891
|
+
// Who may stop what: the owner's page (no agent header, this boot's page secret: every loop, or the one it names) and a
|
|
14892
|
+
// run its own loop only. A request that names a run (X-Synabun-Terminal) counts as it only with its proof (browserCaller:
|
|
14893
|
+
// its terminal token, a brain's launch credential), names nothing else in the body (403 TERMINAL_MISMATCH) and never
|
|
14894
|
+
// stops every loop; an automation that names no run (an agent header alone) stops nothing (403 TERMINAL_REQUIRED); a
|
|
14895
|
+
// request with neither an agent header nor the page secret is refused (403 PAGE_SECRET_REQUIRED). Before 2026-11-04
|
|
14896
|
+
// the header was not read here at all, and any local process stopped any loop.
|
|
14819
14897
|
app.post('/api/loop/stop', async (req, res) => {
|
|
14820
14898
|
try {
|
|
14821
|
-
const
|
|
14899
|
+
const who = browserCaller(req);
|
|
14900
|
+
if (!who.accepted) return res.status(who.httpStatus || 403).json({ ok: false, code: who.code, error: who.error });
|
|
14901
|
+
const named = req.body?.runId || req.body?.terminalSessionId || null;
|
|
14902
|
+
if (who.automation) {
|
|
14903
|
+
if (!who.id) return res.status(403).json({ ok: false, code: 'TERMINAL_REQUIRED', error: 'An automation stops its own loop only, and this request does not say which run it is (X-Synabun-Terminal).' });
|
|
14904
|
+
if (named && String(named) !== who.id) return res.status(403).json({ ok: false, code: 'TERMINAL_MISMATCH', error: `This caller (${who.id}) may not stop run ${String(named).slice(0, 128)}.` });
|
|
14905
|
+
}
|
|
14906
|
+
// No agent header at all: the owner's page, with its page secret (or an invite guest, whom the guest rules decide).
|
|
14907
|
+
if (!who.automation && !browserPageOwner(req)) return refuseNotOwnerPage(req, res, 'Loops are stopped from SynaBun\'s own page (its page secret, which the page\'s browser sends by itself), or by a run itself (X-Synabun-Terminal with its terminal token). This request is neither: reload SynaBun\'s page and stop it there.');
|
|
14908
|
+
const targetTerminalId = who.automation ? who.id : named;
|
|
14822
14909
|
let directlyStopped = false;
|
|
14823
14910
|
if (targetTerminalId && _nativeLoopRuntime?.isAlive(targetTerminalId)) {
|
|
14824
14911
|
directlyStopped = await _nativeLoopRuntime.stop(targetTerminalId, 'user');
|
|
@@ -14876,6 +14963,9 @@ app.post('/api/loop/stop', async (req, res) => {
|
|
|
14876
14963
|
}
|
|
14877
14964
|
}
|
|
14878
14965
|
}
|
|
14966
|
+
// The loop's route may have moved (a recovery, its own browser_session create): what it owns elsewhere goes
|
|
14967
|
+
// too, and a recovery that finishes after this stop opens nothing for it (endAutomationBrowser).
|
|
14968
|
+
if (data.terminalSessionId) await endAutomationBrowser(data.terminalSessionId);
|
|
14879
14969
|
// Per-CLI per-loop config dir cleanup (opencode XDG_CONFIG_HOME, etc.)
|
|
14880
14970
|
if (data.profile === 'opencode' && data.terminalSessionId) {
|
|
14881
14971
|
cleanupOpencodeLoopConfig(data.terminalSessionId);
|
|
@@ -14929,38 +15019,100 @@ app.post('/api/loop/resolve-from-ancestors', (req, res) => {
|
|
|
14929
15019
|
}
|
|
14930
15020
|
});
|
|
14931
15021
|
|
|
14932
|
-
// POST /api/loop/recover-browser —
|
|
15022
|
+
// POST /api/loop/recover-browser — a run's own browser tab: a recovery, its own create, or a tab of its own it moved to.
|
|
14933
15023
|
// When a loop's pinned browser session has died, the MCP server calls this to
|
|
14934
15024
|
// rejoin the SHARED loop browser with a FRESH, owned tab — instead of spawning
|
|
14935
15025
|
// an isolated new browser and reusing a now-invalid tabId (which 404s on every
|
|
14936
|
-
// subsequent call). If terminalSessionId is known, the
|
|
14937
|
-
//
|
|
14938
|
-
//
|
|
15026
|
+
// subsequent call). If terminalSessionId is known, the run's route is recorded
|
|
15027
|
+
// (noteAutomationBrowserRoute: its state file, the native run, the Assistant's
|
|
15028
|
+
// run record) so ancestor lookups, /api/loop/stop and agent_status follow it.
|
|
15029
|
+
// Body: { terminalSessionId?: string, reason?: 'create', lost?: { sessionId, tabId }, adopt?: { sessionId, tabId } }.
|
|
15030
|
+
// The caller is who it routes as (X-Synabun-Terminal, which SynaBun's MCP sends on every request): it is required,
|
|
15031
|
+
// a run named in the body must be that caller (403 TERMINAL_REQUIRED / TERMINAL_MISMATCH: no run moves another
|
|
15032
|
+
// run's browser), and with no run named the new tab is the caller's own (its routing id owns it, so its next call
|
|
15033
|
+
// with that tab is not refused as another owner's). An id is a server-minted one (lib/browser-owner.js: `agent:<uuid>`
|
|
15034
|
+
// included), and a run SynaBun gave a terminal token to is the caller only with that token (X-Synabun-Terminal-Token,
|
|
15035
|
+
// lib/terminal-tokens.js: 403 TERMINAL_TOKEN_REQUIRED without it, TERMINAL_TOKEN_INVALID with another or after the
|
|
15036
|
+
// run ended), so the header alone moves, adopts or opens nothing for a run.
|
|
15037
|
+
// - `adopt`: the run moved by itself to a tab it already owns (the MCP honours ids of a session of its own): that
|
|
15038
|
+
// tab is recorded as its route, nothing is opened (409 NOT_OWNED for a tab that is not the run's).
|
|
15039
|
+
// - `reason: 'create'`: the run's own browser_session create: always a new tab.
|
|
15040
|
+
// - otherwise (a recovery) a run whose route already moved (another MCP process of the same run recovered or
|
|
15041
|
+
// created first) gets that route back instead of one more tab.
|
|
15042
|
+
// A new tab is the run's one route: what the run owned in other sessions is released, and a tab it had in the same
|
|
15043
|
+
// session was replaced by acquireSharedBrowserTab (no orphan tab per re-create). A run that ended gets nothing (409
|
|
15044
|
+
// RUN_ENDED), and a tab that finished opening after its run ended is released at once.
|
|
15045
|
+
// Returns { ok, sessionId, tabId }, or 202 BROWSER_STARTING while the browser is still starting (the tab is kept for
|
|
15046
|
+
// the run's next request; one nobody takes is released, browserStartHandoff onUnclaimed).
|
|
14939
15047
|
app.post('/api/loop/recover-browser', async (req, res) => {
|
|
14940
15048
|
try {
|
|
14941
|
-
const
|
|
14942
|
-
const
|
|
14943
|
-
if (
|
|
14944
|
-
return res.status(
|
|
14945
|
-
}
|
|
14946
|
-
//
|
|
14947
|
-
// so
|
|
14948
|
-
|
|
14949
|
-
|
|
14950
|
-
|
|
14951
|
-
|
|
14952
|
-
|
|
14953
|
-
|
|
14954
|
-
|
|
14955
|
-
|
|
14956
|
-
|
|
14957
|
-
|
|
14958
|
-
|
|
14959
|
-
|
|
14960
|
-
|
|
14961
|
-
|
|
14962
|
-
|
|
15049
|
+
const rawName = req.body?.terminalSessionId;
|
|
15050
|
+
const named = browserOwnerId(rawName);
|
|
15051
|
+
if (rawName !== undefined && rawName !== null && rawName !== '' && !named) {
|
|
15052
|
+
return res.status(400).json({ error: 'terminalSessionId is not a run id SynaBun minted.', code: 'BAD_TERMINAL' });
|
|
15053
|
+
}
|
|
15054
|
+
// The caller is the run it proves it is (browserCaller): a run SynaBun gave a terminal token to only with that
|
|
15055
|
+
// token, so naming a run (or routing as it) moves nothing without it (403 TERMINAL_TOKEN_REQUIRED / _INVALID).
|
|
15056
|
+
const who = browserCaller(req);
|
|
15057
|
+
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
15058
|
+
const caller = browserOwnerId(who.id);
|
|
15059
|
+
if (!caller) {
|
|
15060
|
+
return res.status(403).json({ error: 'A browser recovery says who asks (X-Synabun-Terminal, sent by SynaBun\'s MCP on every request); this request did not.', code: 'TERMINAL_REQUIRED' });
|
|
15061
|
+
}
|
|
15062
|
+
if (named && caller !== named) {
|
|
15063
|
+
return res.status(403).json({ error: `This caller (${caller}) may not take over the browser of run ${named}.`, code: 'TERMINAL_MISMATCH' });
|
|
15064
|
+
}
|
|
15065
|
+
const owner = named || caller;
|
|
15066
|
+
if (named && automationRunState(named, { files: true }) === 'ended') {
|
|
15067
|
+
return res.status(409).json({ error: `Run ${named} has ended: its browser is not reopened.`, code: 'RUN_ENDED' });
|
|
15068
|
+
}
|
|
15069
|
+
const adopt = req.body?.adopt && typeof req.body.adopt === 'object' ? req.body.adopt : null;
|
|
15070
|
+
if (adopt) {
|
|
15071
|
+
const sessionId = browserOwnerId(adopt.sessionId);
|
|
15072
|
+
const tabId = browserOwnerId(adopt.tabId);
|
|
15073
|
+
const cfg = loadBrowserConfig();
|
|
15074
|
+
const owned = !!named && !!sessionId && !!tabId && startedTabAlive(sessionId, tabId, named)
|
|
15075
|
+
&& (cfg.connectMode !== 'morelogin' || sessionServesMoreLoginDefault(browserSessions.get(sessionId), cfg));
|
|
15076
|
+
if (!owned) return res.status(409).json({ error: `That tab is not an open tab of run ${named || caller} in the default browser.`, code: 'NOT_OWNED' });
|
|
15077
|
+
noteAutomationBrowserRoute(named, { browserSessionId: sessionId, browserTabId: tabId }, 'adopted');
|
|
15078
|
+
return res.json({ ok: true, sessionId, tabId, adopted: true });
|
|
15079
|
+
}
|
|
15080
|
+
const fresh = req.body?.reason === 'create';
|
|
15081
|
+
const lost = req.body?.lost && typeof req.body.lost === 'object' ? req.body.lost : null;
|
|
15082
|
+
if (named && !fresh) {
|
|
15083
|
+
const current = liveAutomationRoute(named, { files: true });
|
|
15084
|
+
if (current && !(current.browserSessionId === lost?.sessionId && (current.browserTabId || null) === (lost?.tabId || null))) {
|
|
15085
|
+
return res.json({ ok: true, sessionId: current.browserSessionId, tabId: current.browserTabId || null, current: true });
|
|
15086
|
+
}
|
|
15087
|
+
}
|
|
15088
|
+
const start = async () => {
|
|
15089
|
+
const acq = await acquireLoopBrowserAndTab({ terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser' });
|
|
15090
|
+
if (acq.error) throw Object.assign(new Error(acq.error), { acquisition: acq });
|
|
15091
|
+
// The run ended while its tab was being opened (a cold start): the tab goes at once, never left to a dead run.
|
|
15092
|
+
if (named && automationRunState(named, { files: true }) === 'ended') {
|
|
15093
|
+
await releaseSharedBrowserTab(acq.browserSessionId, owner).catch(() => {});
|
|
15094
|
+
throw Object.assign(new Error(`Run ${named} ended while its browser tab was being opened; the tab was closed.`), { status: 409, code: 'RUN_ENDED' });
|
|
15095
|
+
}
|
|
15096
|
+
// One route per run: what it still owned in other sessions goes (acquireSharedBrowserTab replaced a tab it had
|
|
15097
|
+
// in this one).
|
|
15098
|
+
await releaseBrowserOwnerEverywhere(owner, { except: acq.browserSessionId });
|
|
15099
|
+
// Recorded when the tab exists, whether or not its caller still waits: the run's next request finds it.
|
|
15100
|
+
if (named) noteAutomationBrowserRoute(named, acq, fresh ? 'created' : 'recovered');
|
|
15101
|
+
return acq;
|
|
15102
|
+
};
|
|
15103
|
+
const outcome = await browserStartHandoff.run(`run:${owner}`, start, {
|
|
15104
|
+
gone: browserCallerGone(req, res),
|
|
15105
|
+
waitMs: startWaitMs(browserRequestDeadline(req)),
|
|
15106
|
+
alive: (acq) => startedTabAlive(acq.browserSessionId, acq.browserTabId, owner),
|
|
15107
|
+
// Nobody took it: released unless the run uses it (its recorded route, or a call went there since).
|
|
15108
|
+
onUnclaimed: (acq, info) => closeUnclaimedBrowserStart(acq.browserSessionId, owner, { tabId: acq.browserTabId, since: info?.parkedAt, run: named }),
|
|
15109
|
+
});
|
|
15110
|
+
if (outcome.pending) return res.status(202).json(browserStartingAnswer('tab'));
|
|
15111
|
+
const acq = outcome.value;
|
|
15112
|
+
res.json({ ok: true, sessionId: acq.browserSessionId, tabId: acq.browserTabId || null, ...(outcome.from !== 'started' && { handedOver: outcome.from }) });
|
|
14963
15113
|
} catch (err) {
|
|
15114
|
+
const acq = err?.acquisition;
|
|
15115
|
+
if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
|
|
14964
15116
|
res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
|
|
14965
15117
|
}
|
|
14966
15118
|
});
|
|
@@ -15411,6 +15563,8 @@ async function launchScheduledLoop(schedule) {
|
|
|
15411
15563
|
let scheduledLaunchTerminalId = null;
|
|
15412
15564
|
let scheduledLaunchPendingId = null;
|
|
15413
15565
|
let scheduledLaunchProfile = null;
|
|
15566
|
+
// The terminal token this launcher issued (a terminal or exec loop's), revoked when the launch fails before it runs.
|
|
15567
|
+
let issuedSchedTerminal = null;
|
|
15414
15568
|
try {
|
|
15415
15569
|
if (!existsSync(LOOP_DIR)) mkdirSync(LOOP_DIR, { recursive: true });
|
|
15416
15570
|
|
|
@@ -15473,11 +15627,16 @@ async function launchScheduledLoop(schedule) {
|
|
|
15473
15627
|
// (e.g., a sidepanel plan session and a scheduled CLI loop in the same cwd).
|
|
15474
15628
|
const terminalSessionId = randomBytes(16).toString('hex');
|
|
15475
15629
|
scheduledLaunchTerminalId = terminalSessionId;
|
|
15630
|
+
// A terminal or exec loop's token is minted with its id (lib/terminal-tokens.js); a native run's by its runtime.
|
|
15631
|
+
const schedTerminalToken = nativeRuntime ? null : _terminalTokens.issue(terminalSessionId);
|
|
15632
|
+
if (schedTerminalToken) issuedSchedTerminal = terminalSessionId;
|
|
15476
15633
|
|
|
15477
15634
|
// Reuse the shared browser session and create a fresh tab for this scheduled loop.
|
|
15478
15635
|
let scheduledBrowserSessionId = null;
|
|
15479
15636
|
let scheduledBrowserTabId = null;
|
|
15480
15637
|
const schedExtraEnv = { SYNABUN_TERMINAL_SESSION: terminalSessionId };
|
|
15638
|
+
// In the PTY's environment only (the loop's MCP config names it): never in the loop file or a log.
|
|
15639
|
+
if (schedTerminalToken) schedExtraEnv[TERMINAL_TOKEN_ENV] = schedTerminalToken;
|
|
15481
15640
|
schedExtraEnv.SYNABUN_TOOLS = runtimeToolsValue(cliTools);
|
|
15482
15641
|
// Codex reads auth.json from CODEX_HOME — pin the schedule's selected ChatGPT account.
|
|
15483
15642
|
if (cliProfile === 'codex') {
|
|
@@ -15508,7 +15667,7 @@ async function launchScheduledLoop(schedule) {
|
|
|
15508
15667
|
scheduledBrowserSessionId,
|
|
15509
15668
|
scheduledBrowserTabId,
|
|
15510
15669
|
cliTools,
|
|
15511
|
-
cliModel, {}, { cwd: PACKAGE_ROOT },
|
|
15670
|
+
cliModel, {}, { cwd: PACKAGE_ROOT, terminalToken: !!schedTerminalToken },
|
|
15512
15671
|
);
|
|
15513
15672
|
if (xdgRoot) {
|
|
15514
15673
|
schedExtraEnv.XDG_CONFIG_HOME = xdgRoot;
|
|
@@ -15728,11 +15887,12 @@ async function launchScheduledLoop(schedule) {
|
|
|
15728
15887
|
attachExecLoopDriver(terminalSessionId);
|
|
15729
15888
|
}
|
|
15730
15889
|
// Browser ownership is now held by the successfully launched runtime/PTY;
|
|
15731
|
-
// from this point normal loop-stop cleanup owns it rather than this catch.
|
|
15890
|
+
// from this point normal loop-stop cleanup owns it rather than this catch (its terminal token too).
|
|
15732
15891
|
pendingNativeBrowserCleanup = null;
|
|
15733
15892
|
scheduledLaunchTerminalId = null;
|
|
15734
15893
|
scheduledLaunchPendingId = null;
|
|
15735
15894
|
scheduledLaunchProfile = null;
|
|
15895
|
+
issuedSchedTerminal = null;
|
|
15736
15896
|
if (!nativeRuntime) {
|
|
15737
15897
|
broadcastSync({ type: 'terminal:session-created', sessionId: terminalSessionId, profile: cliProfile });
|
|
15738
15898
|
}
|
|
@@ -15753,6 +15913,8 @@ async function launchScheduledLoop(schedule) {
|
|
|
15753
15913
|
console.log(`[schedule] Launched loop for "${schedule.name}" → ${nativeRuntime ? 'sidepanel run' : 'terminal'} ${terminalSessionId} (${cliProfile}/${cliModel || 'default'}/${cliEffort || 'off'}${'/tools:' + serializeToolList(cliTools)})`);
|
|
15754
15914
|
} catch (err) {
|
|
15755
15915
|
if (registeredScheduledRunId) _runningScheduledLoops.delete(registeredScheduledRunId);
|
|
15916
|
+
// The loop never ran: nothing may act as it.
|
|
15917
|
+
if (issuedSchedTerminal) _terminalTokens.revoke(issuedSchedTerminal);
|
|
15756
15918
|
if (scheduledLaunchTerminalId) {
|
|
15757
15919
|
const terminal = terminalSessions.get(scheduledLaunchTerminalId);
|
|
15758
15920
|
if (terminal) {
|
|
@@ -16917,6 +17079,9 @@ function buildAgentMcpConfig(withSynabun, browserSessionId, browserTabId, termin
|
|
|
16917
17079
|
// matches this agent's _tabOwners key on the server (tab-less calls route to the
|
|
16918
17080
|
// agent's own dedicated tab instead of the shared activeTab).
|
|
16919
17081
|
if (terminalSessionId) env.SYNABUN_TERMINAL_SESSION = terminalSessionId;
|
|
17082
|
+
// The agent's terminal token (lib/terminal-tokens.js) proves that identity: this file (it is under data/, in every
|
|
17083
|
+
// backup) only names the variable; the CLI expands it from its own environment (spawnAgentProcess).
|
|
17084
|
+
if (terminalSessionId && _terminalTokens.has(terminalSessionId)) env[TERMINAL_TOKEN_ENV] = `\${${TERMINAL_TOKEN_ENV}}`;
|
|
16920
17085
|
// Agents run with --strict-mcp-config, so they see only what this file lists.
|
|
16921
17086
|
// External servers come from the captured list and owner switches; SynaBun is added last
|
|
16922
17087
|
// so its per-agent pins always win over a same-named registry entry.
|
|
@@ -16940,7 +17105,12 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
|
|
|
16940
17105
|
const sessionId = agent._activeSessionId || agent.sessionId;
|
|
16941
17106
|
|
|
16942
17107
|
const serverMap = JSON.parse(agent._mcpConfig).mcpServers;
|
|
16943
|
-
|
|
17108
|
+
// The agent's terminal token: in the CLI's environment only, which the SynaBun entry names (buildAgentMcpConfig).
|
|
17109
|
+
// An entry that names it while the agent holds none (revoked) loses the name, so the CLI never fails to expand it.
|
|
17110
|
+
const terminalToken = _terminalTokens.tokenFor(agent._agentTerminalId);
|
|
17111
|
+
if (!terminalToken && serverMap.SynaBun?.env && TERMINAL_TOKEN_ENV in serverMap.SynaBun.env) delete serverMap.SynaBun.env[TERMINAL_TOKEN_ENV];
|
|
17112
|
+
// The token is redacted from the agent's events and stderr like the external servers' secrets.
|
|
17113
|
+
const mcpValues = [...mcpSecretValues(serverMap, { env: process.env }), ...(terminalToken ? [terminalToken] : [])];
|
|
16944
17114
|
const mcpConfigPath = writePrivateMcpConfig(resolve(DATA_HOME, 'data', 'agents', agent.id, 'mcp.json'), serverMap);
|
|
16945
17115
|
const args = [
|
|
16946
17116
|
'--print',
|
|
@@ -16973,8 +17143,11 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
|
|
|
16973
17143
|
const cleanEnv = Object.fromEntries(
|
|
16974
17144
|
Object.entries(process.env).filter(([k]) =>
|
|
16975
17145
|
!k.startsWith('VSCODE_') && k !== 'TERM_PROGRAM' && k !== 'TERM_PROGRAM_VERSION'
|
|
17146
|
+
// Only this agent's own token, never one this server inherited.
|
|
17147
|
+
&& k !== TERMINAL_TOKEN_ENV
|
|
16976
17148
|
)
|
|
16977
17149
|
);
|
|
17150
|
+
if (terminalToken) cleanEnv[TERMINAL_TOKEN_ENV] = terminalToken;
|
|
16978
17151
|
|
|
16979
17152
|
console.log(`[agent] ${agent.id} spawn: ${claudeBin} ${args.map(a => a.length > 80 ? a.slice(0, 80) + '…' : a).join(' ')}`);
|
|
16980
17153
|
|
|
@@ -17080,7 +17253,12 @@ async function launchAgentController(opts) {
|
|
|
17080
17253
|
const agentId = providedAgentId || randomUUID();
|
|
17081
17254
|
const agentTerminalId = `agent:${agentId}`;
|
|
17082
17255
|
const agentTools = requireToolList(resolveToolList(opts.tools ?? [], { source: 'runtime' })).items;
|
|
17083
|
-
|
|
17256
|
+
// Minted with the agent's terminal id, before its MCP config names it (lib/terminal-tokens.js); revoked at its end,
|
|
17257
|
+
// or now when the launch fails before it runs.
|
|
17258
|
+
if (withSynabun) _terminalTokens.issue(agentTerminalId);
|
|
17259
|
+
let mcpConfig;
|
|
17260
|
+
try { mcpConfig = buildAgentMcpConfig(withSynabun, browserSessionId, browserTabId, agentTerminalId, agentTools, cwd || PACKAGE_ROOT); }
|
|
17261
|
+
catch (error) { _terminalTokens.revoke(agentTerminalId); throw error; }
|
|
17084
17262
|
const agentCwd = cwd || PACKAGE_ROOT;
|
|
17085
17263
|
|
|
17086
17264
|
// Build default system prompt for agents — overrides the boot sequence in the agent's instructions
|
|
@@ -17202,13 +17380,9 @@ async function launchAgentController(opts) {
|
|
|
17202
17380
|
// share it under the persistent profile) then acquire a fresh dedicated tab.
|
|
17203
17381
|
// This keeps the "fresh per iteration" intent without nuking co-owners' tabs.
|
|
17204
17382
|
if (agent._usesBrowser && i > 1) {
|
|
17205
|
-
|
|
17206
|
-
|
|
17207
|
-
|
|
17208
|
-
);
|
|
17209
|
-
agent.browserSessionId = null;
|
|
17210
|
-
agent.browserTabId = null;
|
|
17211
|
-
}
|
|
17383
|
+
// Everything the agent owns, wherever its route moved during the last iteration (a recovery, its own
|
|
17384
|
+
// browser_session create: noteAutomationBrowserRoute), not only the session it started the iteration in.
|
|
17385
|
+
await releaseAgentBrowser(agent).catch(e => console.warn(`[agent] ${agentId} tab release: ${e.message}`));
|
|
17212
17386
|
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
17213
17387
|
const acq = await acquireSharedBrowserTab({ ownerKey: agent._agentTerminalId, ownerType: 'interactive', logTag: 'agent:browser' });
|
|
17214
17388
|
if (!acq.error) {
|
|
@@ -17353,13 +17527,10 @@ async function launchAgentController(opts) {
|
|
|
17353
17527
|
// Clean up the agent's tab when the loop ends — release just this agent's tab and
|
|
17354
17528
|
// clear its ownership markers. The shared browser is left for co-owners (the grace
|
|
17355
17529
|
// timer reaps it once no loop/interactive/agent owner remains).
|
|
17356
|
-
|
|
17357
|
-
|
|
17358
|
-
|
|
17359
|
-
|
|
17360
|
-
agent.browserSessionId = null;
|
|
17361
|
-
agent.browserTabId = null;
|
|
17362
|
-
}
|
|
17530
|
+
// Wherever its route moved (releaseAgentBrowser), and also when its last tab acquisition failed.
|
|
17531
|
+
if (agent._usesBrowser) await releaseAgentBrowser(agent, { ended: true }).catch(() => {});
|
|
17532
|
+
// Nothing may act as the agent any more (endAutomationBrowser revokes too, for an agent with a browser).
|
|
17533
|
+
_terminalTokens.revoke(agent._agentTerminalId);
|
|
17363
17534
|
|
|
17364
17535
|
agent.endedAt = new Date().toISOString();
|
|
17365
17536
|
agent.exitCode = agent._stopped ? null : 0;
|
|
@@ -17375,13 +17546,9 @@ async function launchAgentController(opts) {
|
|
|
17375
17546
|
const message = err?.message || String(err);
|
|
17376
17547
|
console.error(`[agent] ${agentId} failed in iteration ${agent.currentIteration}/${iterations}: ${message}`);
|
|
17377
17548
|
try {
|
|
17378
|
-
if (agent._usesBrowser
|
|
17379
|
-
browserSessions.get(agent.browserSessionId)?._agentOwnedSet?.delete(agentId);
|
|
17380
|
-
await releaseSharedBrowserTab(agent.browserSessionId, agent._agentTerminalId).catch(() => {});
|
|
17381
|
-
agent.browserSessionId = null;
|
|
17382
|
-
agent.browserTabId = null;
|
|
17383
|
-
}
|
|
17549
|
+
if (agent._usesBrowser) await releaseAgentBrowser(agent, { ended: true }).catch(() => {});
|
|
17384
17550
|
} catch {}
|
|
17551
|
+
_terminalTokens.revoke(agent._agentTerminalId);
|
|
17385
17552
|
agent.error = message;
|
|
17386
17553
|
agent.endedAt = new Date().toISOString();
|
|
17387
17554
|
agent.exitCode = -1;
|
|
@@ -19249,6 +19416,51 @@ app.post('/api/discord/test', async (req, res) => {
|
|
|
19249
19416
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
19250
19417
|
function _moreLoginOpts() { return { savedCfg: loadBrowserConfig() }; }
|
|
19251
19418
|
|
|
19419
|
+
// ── Who may call the MoreLogin routes (2026-11-05, review 972afb74, finding 7) ──
|
|
19420
|
+
// They act with the owner's powers: MoreLogin's local API with the owner's credentials, the default AI browser (a
|
|
19421
|
+
// setting), the profiles' browsers. The owner's page (this boot's page secret, never an invite guest) calls every one
|
|
19422
|
+
// of them; an automation that says who it is calls the ones the `morelogin` MCP tool uses (status, list, create, start,
|
|
19423
|
+
// stop, use_default) with rails: start and use_default only for a run SynaBun started (its terminal token, never an id
|
|
19424
|
+
// merely said), start answers no CDP port, stop only a profile the caller holds, use_default never while another
|
|
19425
|
+
// automation works in the browser. The API settings (config), the probe (test) and MoreLogin's own MCP registration
|
|
19426
|
+
// (register-mcp, which writes a command into the agents' configurations) are the owner's page's only. Before, every
|
|
19427
|
+
// route answered whatever asked, and a request with no header stopped any profile as the owner.
|
|
19428
|
+
/** [method path] under /api/morelogin an automation may call (the `morelogin` MCP tool, mcp-server services). */
|
|
19429
|
+
const MORELOGIN_AUTOMATION_ROUTES = new Set(['GET /status', 'GET /profiles', 'POST /profiles', 'POST /start', 'POST /stop', 'POST /use-default']);
|
|
19430
|
+
/** Of those, the ones a run must prove (verified: its terminal token or a brain's credential), never an id said. */
|
|
19431
|
+
const MORELOGIN_VERIFIED_ROUTES = new Set(['POST /start', 'POST /use-default']);
|
|
19432
|
+
/** envId → the automations that started that profile through POST /api/morelogin/start (what stop counts as held). */
|
|
19433
|
+
const _moreLoginStartedBy = new Map();
|
|
19434
|
+
function moreLoginGate(req, res, next) {
|
|
19435
|
+
const caller = browserCaller(req);
|
|
19436
|
+
if (!caller.accepted) return refuseBrowserCaller(res, caller);
|
|
19437
|
+
const method = String(req.method || '').toUpperCase() === 'HEAD' ? 'GET' : String(req.method || '').toUpperCase();
|
|
19438
|
+
const key = `${method} ${String(req.path || '').replace(/\/$/, '')}`;
|
|
19439
|
+
if (browserOwnerPageOnly(req)) return next();
|
|
19440
|
+
if (caller.id && MORELOGIN_AUTOMATION_ROUTES.has(key)) {
|
|
19441
|
+
if (MORELOGIN_VERIFIED_ROUTES.has(key) && caller.status !== 'verified') {
|
|
19442
|
+
return res.status(403).json({ ok: false, code: 'VERIFIED_RUN_REQUIRED', error: `Starting a MoreLogin profile or making one the default AI browser is for a run SynaBun started (it proves its id with its terminal token), or the owner in Settings → Browser. ${String(caller.id).slice(0, 128)} is an id SynaBun gave no token.` });
|
|
19443
|
+
}
|
|
19444
|
+
return next();
|
|
19445
|
+
}
|
|
19446
|
+
let guest = false;
|
|
19447
|
+
try { guest = !!isGuestRequest(req); } catch { guest = true; }
|
|
19448
|
+
if (caller.id || guest) {
|
|
19449
|
+
return res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'This MoreLogin route is the owner\'s (SynaBun\'s page, Settings → Browser).' });
|
|
19450
|
+
}
|
|
19451
|
+
if (caller.automation) {
|
|
19452
|
+
return res.status(403).json({ ok: false, code: 'TERMINAL_REQUIRED', error: 'An automation says which run it is (X-Synabun-Terminal, sent by SynaBun\'s MCP on every request); an agent header alone is not the owner\'s page.' });
|
|
19453
|
+
}
|
|
19454
|
+
return refuseNotOwnerPage(req, res, 'The MoreLogin routes answer SynaBun\'s own page (its page secret, which the page\'s browser sends by itself) or an automation that says who it is through SynaBun\'s MCP tools. This request is neither: reload SynaBun\'s page.');
|
|
19455
|
+
}
|
|
19456
|
+
/** Whether any automation other than `caller` works in a browser session (its tab, or a hold on the session). */
|
|
19457
|
+
function otherAutomationsInBrowser(caller) {
|
|
19458
|
+
const others = new Set();
|
|
19459
|
+
for (const session of browserSessions.values()) for (const owner of otherSessionOwners(session, caller)) others.add(owner);
|
|
19460
|
+
return [...others];
|
|
19461
|
+
}
|
|
19462
|
+
app.use('/api/morelogin', moreLoginGate);
|
|
19463
|
+
|
|
19252
19464
|
// GET /api/morelogin/status — install + running + port + default-profile state
|
|
19253
19465
|
app.get('/api/morelogin/status', async (req, res) => {
|
|
19254
19466
|
try {
|
|
@@ -19337,7 +19549,18 @@ app.post('/api/morelogin/start', async (req, res) => {
|
|
|
19337
19549
|
const envId = req.body && req.body.envId;
|
|
19338
19550
|
if (!envId) return res.status(400).json({ ok: false, error: 'envId is required' });
|
|
19339
19551
|
const out = await moreLogin.startProfile(envId, _moreLoginOpts());
|
|
19340
|
-
|
|
19552
|
+
const who = browserCaller(req);
|
|
19553
|
+
if (!who.automation) return res.json({ ok: true, ...out });
|
|
19554
|
+
// An automation's start: the profile is the caller's to stop later (POST /api/morelogin/stop), and the answer
|
|
19555
|
+
// carries no CDP port (a raw debugging connection drives the profile's browser past every check SynaBun makes;
|
|
19556
|
+
// SynaBun's browser tools reach the default profile without it).
|
|
19557
|
+
if (who.id) {
|
|
19558
|
+
const starters = _moreLoginStartedBy.get(String(envId)) || new Set();
|
|
19559
|
+
starters.add(who.id);
|
|
19560
|
+
_moreLoginStartedBy.set(String(envId), starters);
|
|
19561
|
+
if (_moreLoginStartedBy.size > 200) _moreLoginStartedBy.delete(_moreLoginStartedBy.keys().next().value);
|
|
19562
|
+
}
|
|
19563
|
+
res.json({ ok: true, started: true, envId: String(envId) });
|
|
19341
19564
|
} catch (err) {
|
|
19342
19565
|
res.status(500).json({ ok: false, error: err.message });
|
|
19343
19566
|
}
|
|
@@ -19348,7 +19571,27 @@ app.post('/api/morelogin/stop', async (req, res) => {
|
|
|
19348
19571
|
try {
|
|
19349
19572
|
const envId = req.body && req.body.envId;
|
|
19350
19573
|
if (!envId) return res.status(400).json({ ok: false, error: 'envId is required' });
|
|
19574
|
+
// Stopping the profile closes every run's tab in it (lib/browser-session-close.js): an automation may stop only a
|
|
19575
|
+
// profile it holds (a tab or a hold on a session there, or it started the profile) and no other automation works
|
|
19576
|
+
// in. The owner's stop (Settings: the page secret, moreLoginGate) is unchanged. A run is the caller only with its
|
|
19577
|
+
// terminal token (browserCaller: a forged one is refused, so it cannot pass for the one run left there).
|
|
19578
|
+
const who = browserCaller(req);
|
|
19579
|
+
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
19580
|
+
const caller = who.automation ? who.ownerKey : null;
|
|
19581
|
+
const decision = profileStopDecision(browserSessions, envId, caller, { startedBy: (id) => _moreLoginStartedBy.get(id) || [] });
|
|
19582
|
+
if (decision.action === 'refuse' && decision.reason === 'not_owned') {
|
|
19583
|
+
console.warn(`[morelogin] stop of env ${envId} by ${caller} refused: it holds nothing on that profile`);
|
|
19584
|
+
return res.status(403).json({ ok: false, code: 'NOT_OWNED', error: `MoreLogin profile ${envId} was not stopped: you did not start it and have no tab in it. Stop only a profile you started; the owner stops the others in Settings → Browser.` });
|
|
19585
|
+
}
|
|
19586
|
+
if (decision.action === 'refuse') {
|
|
19587
|
+
console.warn(`[morelogin] stop of env ${envId} by ${caller} refused: ${decision.others.length} other automation(s) work in it (${decision.others.join(', ')})`);
|
|
19588
|
+
return res.status(409).json({
|
|
19589
|
+
ok: false, code: 'PROFILE_IN_USE', others: decision.others.length, sessionIds: decision.sessionIds,
|
|
19590
|
+
error: `MoreLogin profile ${envId} was not stopped: ${decision.others.length} other automation(s) have a tab in it, and stopping the profile would close their tabs. To start over in a fresh tab, close only your own (browser_session close, which keeps a shared session for the others); to stop the profile, ask the owner or wait until the other runs end.`,
|
|
19591
|
+
});
|
|
19592
|
+
}
|
|
19351
19593
|
await moreLogin.stopProfile(envId, _moreLoginOpts());
|
|
19594
|
+
_moreLoginStartedBy.delete(String(envId));
|
|
19352
19595
|
res.json({ ok: true });
|
|
19353
19596
|
} catch (err) {
|
|
19354
19597
|
res.status(500).json({ ok: false, error: err.message });
|
|
@@ -19357,8 +19600,20 @@ app.post('/api/morelogin/stop', async (req, res) => {
|
|
|
19357
19600
|
|
|
19358
19601
|
// POST /api/morelogin/use-default — make a MoreLogin profile the default AI browser
|
|
19359
19602
|
// { envId } to set, or { clear: true } to revert to the normal mirror browser.
|
|
19360
|
-
app.post('/api/morelogin/use-default', (req, res) => {
|
|
19361
|
-
try {
|
|
19603
|
+
app.post('/api/morelogin/use-default', async (req, res) => {
|
|
19604
|
+
try {
|
|
19605
|
+
// An automation's change of the default AI browser (moreLoginGate let a verified run through): to a profile
|
|
19606
|
+
// MoreLogin lists, never back to another browser (`clear` is the owner's), and never while another automation works
|
|
19607
|
+
// in the browser (its next call would be refused NOT_DEFAULT_BROWSER mid-task).
|
|
19608
|
+
const who = browserCaller(req);
|
|
19609
|
+
if (who.automation) {
|
|
19610
|
+
if (req.body?.clear || !req.body?.envId) return res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'Going back from MoreLogin to another default browser is the owner\'s (Settings → Browser).' });
|
|
19611
|
+
const busy = otherAutomationsInBrowser(who.ownerKey);
|
|
19612
|
+
if (busy.length) return res.status(409).json({ ok: false, code: 'BROWSER_IN_USE', others: busy.length, error: `The default AI browser was not changed: ${busy.length} other automation(s) work in the browser now, and their next call would land in another profile. Try again when they are done, or ask the owner.` });
|
|
19613
|
+
let envs = [];
|
|
19614
|
+
try { envs = await moreLogin.listProfiles(_moreLoginOpts()); } catch (err) { return res.status(502).json({ ok: false, error: `MoreLogin's profile list could not be read: ${err.message}` }); }
|
|
19615
|
+
if (!(envs || []).some((env) => String(env?.id) === String(req.body.envId))) return res.status(404).json({ ok: false, code: 'ENV_NOT_FOUND', error: `MoreLogin has no profile ${String(req.body.envId).slice(0, 64)}. Use the "list" action for its ids.` });
|
|
19616
|
+
}
|
|
19362
19617
|
const cfg = loadBrowserConfig();
|
|
19363
19618
|
if (req.body && req.body.clear) {
|
|
19364
19619
|
cfg.connectMode = 'mirror';
|
|
@@ -22896,6 +23151,8 @@ registerSkillsV2Routes(app, {
|
|
|
22896
23151
|
assistantOf: (req) => skillsAssistantOf(req),
|
|
22897
23152
|
// The owner's writes carry the page secret (lib/page-session.js); the Studio's reads hand it to the page.
|
|
22898
23153
|
pageSession: _pageSession,
|
|
23154
|
+
// An agent's X-Synabun-Terminal (its author's name) counts only with its proof (browserCaller).
|
|
23155
|
+
terminalRefusal: (req) => { const who = browserCaller(req); return who.accepted ? null : { status: who.httpStatus || 403, code: who.code, error: who.error }; },
|
|
22899
23156
|
});
|
|
22900
23157
|
|
|
22901
23158
|
// ── AI skill creation (docs/skills-studio.md → AI creation (P3)) ──
|
|
@@ -23032,12 +23289,16 @@ function skillsAssistantOf(req) {
|
|
|
23032
23289
|
/**
|
|
23033
23290
|
* Who an agent's request to the creation routes is: an Assistant brain, by the credential its launch was given
|
|
23034
23291
|
* (resolved to its session by the runtime; X-Synabun-Role and X-Synabun-Terminal prove nothing, any local process can
|
|
23035
|
-
* send them), a dispatched worker (its terminal is a run id: refused), or nobody known.
|
|
23292
|
+
* send them), a dispatched worker (its terminal is a run id: refused), or nobody known. The pin counts only with its
|
|
23293
|
+
* proof (browserCaller): a request that names a run or a brain it cannot prove it is gets that refusal (kind
|
|
23294
|
+
* 'refused', 403 TERMINAL_TOKEN_REQUIRED / _INVALID), whatever credential it also carries.
|
|
23036
23295
|
*/
|
|
23037
23296
|
function skillCreationCaller(req) {
|
|
23297
|
+
const who = browserCaller(req);
|
|
23298
|
+
if (!who.accepted) return { kind: 'refused', code: who.code, error: who.error, status: who.httpStatus || 403 };
|
|
23038
23299
|
const sessionId = skillsAssistantOf(req);
|
|
23039
23300
|
if (sessionId) return { kind: 'assistant', assistantSessionId: sessionId };
|
|
23040
|
-
const pin = String(
|
|
23301
|
+
const pin = String(who.id || '').trim();
|
|
23041
23302
|
if (pin && _assistantDispatcher?.peek?.(pin)) return { kind: 'worker' };
|
|
23042
23303
|
return null;
|
|
23043
23304
|
}
|
|
@@ -25124,6 +25385,10 @@ app.get('/api/health', (req, res) => {
|
|
|
25124
25385
|
// page showing the restart tells this one from the one that replaces it.
|
|
25125
25386
|
bootId: SERVER_BOOT_ID,
|
|
25126
25387
|
...(_restartRequestedAt && !_stopOverridesRestart ? { restarting: true } : {}),
|
|
25388
|
+
// Whether the owner's authority can be checked (lib/peer-identity.js): ok / degraded (macOS, the lookup fails:
|
|
25389
|
+
// the owner's actions answer 503 until it works) / unsupported (no lookup on this platform) / off
|
|
25390
|
+
// (SYNABUN_PEER_IDENTITY=off). The page's banner reads it (public/shared/ui-owner-authority.js).
|
|
25391
|
+
ownerAuthority: _peerIdentity.authorityState(),
|
|
25127
25392
|
});
|
|
25128
25393
|
} catch (err) {
|
|
25129
25394
|
res.json({ ok: false, reason: 'db_error', detail: err.message });
|
|
@@ -25201,16 +25466,26 @@ function redactOpenCodeMcpOutput(text, xdgRoot, env, captured = null) {
|
|
|
25201
25466
|
function externalInventory(provider, cwd = PACKAGE_ROOT, options = {}) {
|
|
25202
25467
|
return { ...externalServerInventory({ provider, cwd, dataHome: DATA_HOME, registry: readMcpRegistry(), ...(provider === 'opencode' ? { opencodeConfig: readOpencodeGlobalConfig().config } : {}), ...options }), catalog: () => externalToolsCatalog(cwd) };
|
|
25203
25468
|
}
|
|
25204
|
-
|
|
25205
|
-
|
|
25469
|
+
// Strict unless `strict: false`: a provider whose configuration cannot be read fails the catalog, which is what
|
|
25470
|
+
// every validation and grant path needs. Only the page's read (GET /api/mcp/tools) asks for the degraded report,
|
|
25471
|
+
// where that provider is `unknown` on every row and named in `errors`.
|
|
25472
|
+
function externalToolsCatalogReport(cwd = null, { strict = true } = {}) {
|
|
25473
|
+
const rows = new Map(), errors = new Map();
|
|
25206
25474
|
const roots = cwd ? [cwd] : [PACKAGE_ROOT, ...loadHookProjects().map(project => project.path).filter(Boolean)];
|
|
25207
|
-
for (const directory of new Set(roots))
|
|
25208
|
-
const
|
|
25209
|
-
if (!
|
|
25210
|
-
|
|
25475
|
+
for (const directory of new Set(roots)) {
|
|
25476
|
+
const report = externalCatalogReport({ cwd: directory, dataHome: DATA_HOME, registry: readMcpRegistry(), opencodeConfig: readOpencodeGlobalConfig().config }, { strict });
|
|
25477
|
+
for (const error of report.errors) if (!errors.has(error.provider)) errors.set(error.provider, error);
|
|
25478
|
+
for (const row of report.servers) {
|
|
25479
|
+
const previous = rows.get(row.ref);
|
|
25480
|
+
if (!previous) rows.set(row.ref, row);
|
|
25481
|
+
else for (const [provider, availability] of Object.entries(row.providers)) previous.providers[provider] = mergeExternalAvailability(previous.providers[provider], availability);
|
|
25482
|
+
}
|
|
25211
25483
|
}
|
|
25212
|
-
|
|
25484
|
+
// A provider unreadable in one folder is unknown everywhere: another folder's answer is not the whole answer.
|
|
25485
|
+
for (const provider of errors.keys()) for (const row of rows.values()) if (row.providers[provider] !== 'deliverable') row.providers[provider] = 'unknown';
|
|
25486
|
+
return { servers: [...rows.values()], errors: [...errors.values()] };
|
|
25213
25487
|
}
|
|
25488
|
+
function externalToolsCatalog(cwd = null) { return externalToolsCatalogReport(cwd).servers; }
|
|
25214
25489
|
|
|
25215
25490
|
function applyOpenCodeExternalScope(xdgRoot, config, tools, cwd, { readProject = true } = {}) {
|
|
25216
25491
|
const scoped = scopeOpenCodeServers(config, tools, externalInventory('opencode', cwd || PACKAGE_ROOT, { readProject }));
|
|
@@ -25231,7 +25506,12 @@ function toolsFromSelection(value) {
|
|
|
25231
25506
|
return launchToolList(Array.isArray(value) ? { tools: value } : { mcpProfile: value }).items;
|
|
25232
25507
|
}
|
|
25233
25508
|
app.get('/api/mcp/tools', (req, res) => {
|
|
25234
|
-
try {
|
|
25509
|
+
try {
|
|
25510
|
+
// One provider's unreadable configuration degrades that provider only; the rest of the catalog still answers.
|
|
25511
|
+
const external = externalToolsCatalogReport(req.query?.cwd || null, { strict: false });
|
|
25512
|
+
for (const error of external.errors) console.warn(`[mcp/tools] ${error.provider} MCP configuration ${error.reason}${error.errno ? ` (${error.errno})` : ''}; its servers are reported as unknown`);
|
|
25513
|
+
res.json({ ok: true, ...toolCatalogView({ browserV2: process.env.SYNABUN_BROWSER_V2 !== '0' }), defaultTools: defaultToolList(), externalServersVersion: 2, externalServerLimitations: EXTERNAL_SERVER_LIMITATIONS, servers: external.servers, externalServerErrors: external.errors });
|
|
25514
|
+
}
|
|
25235
25515
|
catch (err) { res.status(err.status || 500).json({ ok: false, code: err.code, problems: err.problems, error: err.message }); }
|
|
25236
25516
|
});
|
|
25237
25517
|
// Read-time conversion for a saved page preference. This never launches a runtime or writes a default.
|
|
@@ -25245,23 +25525,40 @@ app.put('/api/mcp/tools/default', (req, res) => {
|
|
|
25245
25525
|
try {
|
|
25246
25526
|
const requested = storedToolList({ tools: req.body?.tools });
|
|
25247
25527
|
if (requested === null) throw Object.assign(new Error('tools must be an array'), { code: 'TOOLS_INVALID', status: 400 });
|
|
25248
|
-
|
|
25249
|
-
|
|
25528
|
+
// The default list is a preference, never a grant (every launch re-reads its provider strictly), so an
|
|
25529
|
+
// unreadable provider does not stop a save. A ref only that provider could hold is still refused: it cannot be checked.
|
|
25530
|
+
const external = externalToolsCatalogReport(null, { strict: false });
|
|
25531
|
+
const servers = external.servers.map(row => ({ name: row.ref.slice(4), blocked: row.blocked, deliverable: Object.values(row.providers).includes('deliverable') }));
|
|
25532
|
+
try { selectExternalServers(requested, { servers }); }
|
|
25533
|
+
catch (err) {
|
|
25534
|
+
if (!external.errors.length || !Array.isArray(err.problems)) throw err;
|
|
25535
|
+
const unread = external.errors.map(error => error.provider).join(', ');
|
|
25536
|
+
throw Object.assign(err, { message: `${err.message} The MCP configuration of ${unread} could not be read, so a server configured only there cannot be checked.`, externalServerErrors: external.errors });
|
|
25537
|
+
}
|
|
25250
25538
|
const tools = writeDefaultTools(DATA_HOME, requested);
|
|
25251
25539
|
broadcastSync({ type: 'mcp:tools-default-changed', tools, source: 'api' });
|
|
25252
|
-
res.json({ ok: true, tools, defaultTools: tools });
|
|
25253
|
-
} catch (err) { res.status(err.status || 500).json({ ok: false, code: err.code, problems: err.problems, error: err.message }); }
|
|
25540
|
+
res.json({ ok: true, tools, defaultTools: tools, externalServerErrors: external.errors });
|
|
25541
|
+
} catch (err) { res.status(err.status || 500).json({ ok: false, code: err.code, problems: err.problems, error: err.message, ...(err.externalServerErrors ? { externalServerErrors: err.externalServerErrors } : {}) }); }
|
|
25254
25542
|
});
|
|
25255
25543
|
|
|
25256
25544
|
// An MCP child can change its own enabled tools through the always-on tool_groups
|
|
25257
25545
|
// tool. Reconcile only the runtime named by its launch identity header; never
|
|
25258
25546
|
// accept a sidepanel session/run id from the body and never touch the shared
|
|
25259
|
-
// future-session default from this path.
|
|
25547
|
+
// future-session default from this path. The header counts only with that runtime's
|
|
25548
|
+
// proof (browserCaller: its terminal token, or a brain's launch credential): a runtime
|
|
25549
|
+
// SynaBun gave one to is never re-scoped by another process that merely names it
|
|
25550
|
+
// (403 TERMINAL_TOKEN_REQUIRED / TERMINAL_TOKEN_INVALID).
|
|
25260
25551
|
function applyRuntimeTools(req, res) {
|
|
25261
|
-
const
|
|
25262
|
-
if (!
|
|
25552
|
+
const asserted = String(req.get('X-Synabun-Terminal') || '').trim();
|
|
25553
|
+
if (!asserted) {
|
|
25263
25554
|
return res.status(400).json({ ok: false, error: 'Missing X-Synabun-Terminal runtime identity' });
|
|
25264
25555
|
}
|
|
25556
|
+
const who = browserCaller(req);
|
|
25557
|
+
if (!who.accepted) {
|
|
25558
|
+
noteRefusedBrowserCaller(`runtime-tools:${who.code}:${asserted.slice(0, 128)}`, `[mcp/tools] runtime tools of ${asserted.slice(0, 128)} refused: ${who.code}`);
|
|
25559
|
+
return res.status(who.httpStatus || 403).json({ ok: false, code: who.code, error: who.error });
|
|
25560
|
+
}
|
|
25561
|
+
const terminalId = who.id || asserted;
|
|
25265
25562
|
let tools;
|
|
25266
25563
|
try {
|
|
25267
25564
|
if (!Array.isArray(req.body?.tools)) throw Object.assign(new Error('tools must be an array'), { status: 400, code: 'TOOLS_INVALID' });
|
|
@@ -26341,7 +26638,11 @@ try {
|
|
|
26341
26638
|
console.error(' MCP HTTP eager init failed:', err.message);
|
|
26342
26639
|
});
|
|
26343
26640
|
|
|
26344
|
-
|
|
26641
|
+
// A request that names a run (X-Synabun-Terminal) without that run's terminal token is not that run here either
|
|
26642
|
+
// (lib/terminal-tokens.js): the MCP server routes it as its own MCP session, so it never shares the run's identity
|
|
26643
|
+
// (its browser pins, its recovered tab) and never sends the run's id to the browser routes.
|
|
26644
|
+
const terminalAuth = (pin, token) => _terminalTokens.accepts(pin, token);
|
|
26645
|
+
const mcpRouter = createMcpRoutes({ terminalAuth });
|
|
26345
26646
|
|
|
26346
26647
|
// Keyed path: /mcp/<key> — validates key, then forwards to MCP router
|
|
26347
26648
|
app.use('/mcp/:key', (req, res, next) => {
|
|
@@ -26364,7 +26665,8 @@ try {
|
|
|
26364
26665
|
// guard) and dispatch is never blocked. macOS only; elsewhere nothing uses it.
|
|
26365
26666
|
if (sandboxSupported() && sandboxExecAvailable()) {
|
|
26366
26667
|
try {
|
|
26367
|
-
|
|
26668
|
+
// The channel's path token names the run; the channel adds that run's terminal token itself (never the worker's).
|
|
26669
|
+
_workerMcpChannel = createWorkerMcpChannel({ createMcpRoutes, mainPort: Number(PORT) || 3344, log: (line) => console.log(line), terminalToken: (runId) => _terminalTokens.tokenFor(runId), terminalAuth });
|
|
26368
26670
|
_workerMcpChannel.start().catch((error) => { console.warn(' worker-only MCP channel did not start (guarded workers run without OS isolation):', error?.message || error); _workerMcpChannel = null; });
|
|
26369
26671
|
} catch (error) {
|
|
26370
26672
|
console.warn(' worker-only MCP channel unavailable:', error?.message || error);
|
|
@@ -26704,6 +27006,8 @@ function createTerminalSession(profile, cols, rows, cwd, opts = {}) {
|
|
|
26704
27006
|
// data/loop-configs until they piled into multi-GB. Clean it here too.
|
|
26705
27007
|
cleanupOpencodeLoopConfig(sessionId);
|
|
26706
27008
|
cleanupExecLoopArtifacts(session);
|
|
27009
|
+
// The loop's terminal is gone, so is the loop: its browser tabs, wherever its route moved.
|
|
27010
|
+
endAutomationBrowser(sessionId).catch(() => {});
|
|
26707
27011
|
}
|
|
26708
27012
|
|
|
26709
27013
|
// Clean up loop driver interval
|
|
@@ -26740,6 +27044,9 @@ function createTerminalSession(profile, cols, rows, cwd, opts = {}) {
|
|
|
26740
27044
|
name: 'xterm-256color',
|
|
26741
27045
|
tap: isLoopOwned,
|
|
26742
27046
|
loopOwned: isLoopOwned,
|
|
27047
|
+
// A loop's PTY holds its run's terminal token: what it prints is scrubbed of tokens in the terminal host
|
|
27048
|
+
// (lib/pty-host/core.js), before its clients, its reconnect snapshot and the tap (loop logs, link captures).
|
|
27049
|
+
redactTokens: isLoopOwned || !!opts.extraEnv?.[TERMINAL_TOKEN_ENV],
|
|
26743
27050
|
profile,
|
|
26744
27051
|
}, {
|
|
26745
27052
|
onSpawned: ({ pid }) => {
|
|
@@ -27230,6 +27537,9 @@ function buildLoopTaskPrompt(loopState, iteration = null) {
|
|
|
27230
27537
|
? `Pass sessionId: "${loopState.browserSessionId}"${loopState.browserTabId ? ` and tabId: "${loopState.browserTabId}"` : ''} to EVERY browser tool call. Omitting them can hijack another loop's browser.`
|
|
27231
27538
|
: 'Use the SynaBun browser tools only. Do not use external browser/search tools for visual browsing.',
|
|
27232
27539
|
'Use ONLY SynaBun MCP browser tools such as browser_navigate, browser_click, browser_snapshot, browser_content, browser_evaluate, browser_wait, and the browser_extract_* tools.',
|
|
27540
|
+
// The rule the worker prompts and the Assistant get (lib/browser-tool-policy.js): a lost session is replaced, never another browser.
|
|
27541
|
+
browserSessionLossRule(),
|
|
27542
|
+
'Never substitute another browser or tool for the SynaBun browser.',
|
|
27233
27543
|
'If the browser shows a login page, CAPTCHA, 2FA, or any wall requiring human action, stop and report the blocker. Do not bypass it or fall back to web search.',
|
|
27234
27544
|
'=== END BROWSER ENFORCEMENT ===',
|
|
27235
27545
|
'',
|
|
@@ -27254,9 +27564,12 @@ function buildLoopTaskPrompt(loopState, iteration = null) {
|
|
|
27254
27564
|
`NATIVE LOOP ITERATION: ${iteration}/${loopState.totalIterations || 1}`,
|
|
27255
27565
|
'Continue the same native conversation and make concrete progress on the task.',
|
|
27256
27566
|
'This run is unattended. Do not ask the user questions, enter plan mode, or wait for interactive approval. If blocked, record the blocker in your final response and stop this iteration cleanly.',
|
|
27567
|
+
'Do not end your turn to wait for something (a pacing gap, a timer): keep working, or call the tool that does the wait for you.',
|
|
27257
27568
|
'',
|
|
27258
27569
|
].join('\n') : '';
|
|
27259
|
-
|
|
27570
|
+
// Social writes are spaced by SynaBun's own tools (lib/social-write-pacing.js): the agent must not pace them itself.
|
|
27571
|
+
const pacingBlock = socialPacingBlock(loopState);
|
|
27572
|
+
const wrappedTask = `${iterationBlock}AUTHORIZATION: This task is running inside SynaBun Automation Studio, a user-supervised automation platform. The user has explicitly configured and launched this automation. All browser tools are first-party MCP tools under user control. Execute the task as instructed.${browserBlock}${pacingBlock}${fbPlaybook}${resumeBlock}\n\nTASK:\n${loopState.task}`;
|
|
27260
27573
|
return loopState.context ? `${wrappedTask}\n\nCONTEXT:\n${loopState.context}` : wrappedTask;
|
|
27261
27574
|
}
|
|
27262
27575
|
|
|
@@ -27362,6 +27675,8 @@ async function releaseNativeLoopResources(run) {
|
|
|
27362
27675
|
await closeSessionTab(session, run.browserSessionId, run.browserTabId).catch(() => {});
|
|
27363
27676
|
}
|
|
27364
27677
|
}
|
|
27678
|
+
// Its route may have moved during the run (a recovery, its own browser_session create): what it owns elsewhere goes too.
|
|
27679
|
+
await releaseBrowserOwnerEverywhere(run.runId);
|
|
27365
27680
|
reconcileKeepAwake();
|
|
27366
27681
|
}
|
|
27367
27682
|
|
|
@@ -27370,6 +27685,9 @@ const openCodeWorkerActivity = createOpenCodeActivityRelay({ send: (message) =>
|
|
|
27370
27685
|
|
|
27371
27686
|
_nativeLoopRuntime = new NativeLoopRuntime({
|
|
27372
27687
|
toolListOptions,
|
|
27688
|
+
// Every native run (a loop, a schedule, a dispatched worker) gets its terminal token at launch and resume, and loses it
|
|
27689
|
+
// at its end (lib/terminal-tokens.js).
|
|
27690
|
+
terminalTokens: _terminalTokens,
|
|
27373
27691
|
stateDir: LOOP_DIR,
|
|
27374
27692
|
ledgerPath: resolve(LOOP_DATA_DIR, 'native-loop-runs.json'),
|
|
27375
27693
|
buildPrompt: (state, iteration) => buildLoopTaskPrompt(state, iteration),
|
|
@@ -27528,6 +27846,11 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
27528
27846
|
},
|
|
27529
27847
|
} : null;
|
|
27530
27848
|
if (state.resumingWorker) openCodeWorkerData(resolve(DATA_HOME, 'data', 'loop-configs', `opencode-${state.runId}`), { resume: true });
|
|
27849
|
+
// The run's terminal token (lib/terminal-tokens.js): its local SynaBun entry names the variable and only the serve's
|
|
27850
|
+
// environment holds it. Through the worker-only channel (remoteMcp) the channel adds it by itself, and a drafting
|
|
27851
|
+
// or evaluation run starts no MCP server: neither gets it in its serve's environment.
|
|
27852
|
+
const runTerminalToken = !remoteMcp && !state.confinement && typeof state.terminalTokenProvider === 'function'
|
|
27853
|
+
? (state.terminalTokenProvider() || null) : null;
|
|
27531
27854
|
const xdgRoot = setupOpencodeLoopConfig(
|
|
27532
27855
|
state.runId,
|
|
27533
27856
|
state.browserSessionId,
|
|
@@ -27541,7 +27864,7 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
27541
27864
|
// Assistant task runs: the browser policy plugin (loops and schedules unchanged) with the registered code
|
|
27542
27865
|
// projects its test runners may run in (the sandboxed serve cannot read the registry), and the run's confinement
|
|
27543
27866
|
// (lib/worker-confinement.js, lib/skills/draft-confinement.js): its permission rules, tool switches, MCP.
|
|
27544
|
-
{ browserPolicy: state.runMode === 'task', cwd: state.cwd || null, policyRoots: taskBrowserPolicyRoots(state), confinement: openCodeRunConfigFor(state), remoteMcp, readProject: !(protectedWorker || state.confinement) },
|
|
27867
|
+
{ browserPolicy: state.runMode === 'task', cwd: state.cwd || null, policyRoots: taskBrowserPolicyRoots(state), confinement: openCodeRunConfigFor(state), remoteMcp, readProject: !(protectedWorker || state.confinement), terminalToken: !!runTerminalToken },
|
|
27545
27868
|
);
|
|
27546
27869
|
// An evaluation trial with the skill: its copy goes into this run's own configuration folder, which OpenCode reads
|
|
27547
27870
|
// as its global one (never OPENCODE_CONFIG_DIR, which would take the place of this configuration).
|
|
@@ -27559,6 +27882,7 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
27559
27882
|
...(evalEnv || evalShell ? { extraEnv: { ...(evalEnv || {}), ...(evalShell ? evalShell.env : {}) } } : {}),
|
|
27560
27883
|
hidePassword: protectedWorker,
|
|
27561
27884
|
persistentData: !!state.persistentOpenCode,
|
|
27885
|
+
terminalToken: runTerminalToken,
|
|
27562
27886
|
});
|
|
27563
27887
|
if (!entry?.client) throw new Error('OpenCode isolated native serve failed to start');
|
|
27564
27888
|
let providerSessionId = null;
|
|
@@ -27727,14 +28051,21 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
27727
28051
|
// Model catalog (tier · price · vision) for routing, the persona and agent_catalog.
|
|
27728
28052
|
const assistantCatalog = createAssistantCatalog({
|
|
27729
28053
|
fetchJson: catalogFetch,
|
|
28054
|
+
// Degraded on purpose (the catalog only lists): an unreadable provider is named in `errors` and is
|
|
28055
|
+
// `unknown` on its rows. Dispatch and worker launch keep the strict externalToolsCatalog / inventories.
|
|
27730
28056
|
getExternalServers: (projects = []) => {
|
|
27731
|
-
const rows = new Map();
|
|
27732
|
-
for (const cwd of new Set([PACKAGE_ROOT, ...projects.map(project => project.path || project.cwd).filter(Boolean)]))
|
|
27733
|
-
const
|
|
27734
|
-
if (!
|
|
27735
|
-
|
|
28057
|
+
const rows = new Map(), errors = new Map();
|
|
28058
|
+
for (const cwd of new Set([PACKAGE_ROOT, ...projects.map(project => project.path || project.cwd).filter(Boolean)])) {
|
|
28059
|
+
const report = externalToolsCatalogReport(cwd, { strict: false });
|
|
28060
|
+
for (const error of report.errors) if (!errors.has(error.provider)) errors.set(error.provider, error);
|
|
28061
|
+
for (const row of report.servers) {
|
|
28062
|
+
const previous = rows.get(row.ref);
|
|
28063
|
+
if (!previous) rows.set(row.ref, row);
|
|
28064
|
+
else for (const [provider, availability] of Object.entries(row.providers)) previous.providers[provider] = mergeExternalAvailability(previous.providers[provider], availability);
|
|
28065
|
+
}
|
|
27736
28066
|
}
|
|
27737
|
-
|
|
28067
|
+
for (const provider of errors.keys()) for (const row of rows.values()) if (row.providers[provider] !== 'deliverable') row.providers[provider] = 'unknown';
|
|
28068
|
+
return { servers: [...rows.values()], errors: [...errors.values()] };
|
|
27738
28069
|
},
|
|
27739
28070
|
codexPrice: (model) => assistantPricing.codexPrice(model),
|
|
27740
28071
|
listAccounts: () => accountUsage.list(),
|
|
@@ -28149,6 +28480,8 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
28149
28480
|
greeting: _greeting,
|
|
28150
28481
|
// The Admin sandbox setting: every session view shows it (features.adminSandbox gates the panel's control).
|
|
28151
28482
|
adminSandbox: _agentSandbox,
|
|
28483
|
+
// A brain's pin is proven by its launch credential (lib/terminal-tokens.js bind), revoked with the brain.
|
|
28484
|
+
terminalTokens: _terminalTokens,
|
|
28152
28485
|
});
|
|
28153
28486
|
assistantDesktop?.attach?.({ runtime: _assistantRuntime, dispatcher: _assistantDispatcher });
|
|
28154
28487
|
// Warm the catalog so brain capabilities (vision, tier) are known on first attach,
|
|
@@ -28211,6 +28544,8 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
28211
28544
|
workerGuard: _workerGuard,
|
|
28212
28545
|
// A request without an agent pin is the owner's page only with this boot's page secret (lib/page-session.js).
|
|
28213
28546
|
pageSession: _pageSession,
|
|
28547
|
+
// A pin counts only with its proof (lib/terminal-tokens.js): a worker's run id, a brain's id.
|
|
28548
|
+
terminalVerdict: (pin, req) => _terminalTokens.verdict(pin, presentedTerminalProof(req)),
|
|
28214
28549
|
}));
|
|
28215
28550
|
const shutdownAssistant = () => {
|
|
28216
28551
|
// Running skill creations first: what their workers wrote is kept as drafts before the workers go.
|
|
@@ -28251,7 +28586,7 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
28251
28586
|
* plugin (lib/assistant-brains/opencode2-browser-policy/), `cwd` the run's project, `policyRoots` the registered code
|
|
28252
28587
|
* projects its test runners may also run in.
|
|
28253
28588
|
*/
|
|
28254
|
-
function setupOpencodeLoopConfig(terminalSessionId, browserSessionId, browserTabId, selection = null, model = null, extraMcpEnv = {}, { browserPolicy = false, cwd = null, policyRoots = [], confinement = null, remoteMcp = null, readProject = true } = {}) {
|
|
28589
|
+
function setupOpencodeLoopConfig(terminalSessionId, browserSessionId, browserTabId, selection = null, model = null, extraMcpEnv = {}, { browserPolicy = false, cwd = null, policyRoots = [], confinement = null, remoteMcp = null, readProject = true, terminalToken = false } = {}) {
|
|
28255
28590
|
const xdgRoot = resolve(DATA_HOME, 'data', 'loop-configs', `opencode-${terminalSessionId}`);
|
|
28256
28591
|
const targetDir = resolve(xdgRoot, 'opencode');
|
|
28257
28592
|
if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });
|
|
@@ -28279,6 +28614,10 @@ function setupOpencodeLoopConfig(terminalSessionId, browserSessionId, browserTab
|
|
|
28279
28614
|
};
|
|
28280
28615
|
if (browserSessionId) pinOverrides.SYNABUN_BROWSER_SESSION = browserSessionId;
|
|
28281
28616
|
if (browserTabId) pinOverrides.SYNABUN_BROWSER_TAB = browserTabId;
|
|
28617
|
+
// The run's terminal token (lib/terminal-tokens.js): this file (under data/, in every backup) and the
|
|
28618
|
+
// OPENCODE_CONFIG_CONTENT overlay copied from it only name the variable; the value is in the environment of the
|
|
28619
|
+
// opencode process that reads them (the loop's PTY, the worker's serve).
|
|
28620
|
+
if (terminalToken) pinOverrides[TERMINAL_TOKEN_ENV] = `{env:${TERMINAL_TOKEN_ENV}}`;
|
|
28282
28621
|
// Assistant task runs: e.g. SYNABUN_DESKTOP_GRANT for computer-use workers.
|
|
28283
28622
|
for (const [key, value] of Object.entries(extraMcpEnv || {})) if (value) pinOverrides[key] = String(value);
|
|
28284
28623
|
setMcpServer(baseCfg, 'SynaBun', buildManagedOpenCodeSynabunEntry(existingEntry, {
|
|
@@ -28293,6 +28632,7 @@ function setupOpencodeLoopConfig(terminalSessionId, browserSessionId, browserTab
|
|
|
28293
28632
|
...(!browserSessionId ? ['SYNABUN_BROWSER_SESSION'] : []),
|
|
28294
28633
|
...(!browserTabId ? ['SYNABUN_BROWSER_TAB'] : []),
|
|
28295
28634
|
...(!extraMcpEnv?.SYNABUN_DESKTOP_GRANT ? ['SYNABUN_DESKTOP_GRANT'] : []),
|
|
28635
|
+
...(!terminalToken ? [TERMINAL_TOKEN_ENV] : []),
|
|
28296
28636
|
'CLAUDECODE', 'SYNABUN_PROFILE', 'SYNABUN_RUNTIME_PROFILE_PATH',
|
|
28297
28637
|
],
|
|
28298
28638
|
}));
|
|
@@ -28344,6 +28684,9 @@ function setupClaudeLoopMcpConfig(terminalSessionId, browserSessionId, browserTa
|
|
|
28344
28684
|
const dir = resolve(DATA_HOME, 'data', 'loop-configs');
|
|
28345
28685
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
28346
28686
|
const headers = { 'X-Synabun-Terminal': terminalSessionId };
|
|
28687
|
+
// The loop's terminal token (lib/terminal-tokens.js): the header names the variable, the CLI expands it from the
|
|
28688
|
+
// PTY's environment (the launch sets it with the token it issued): never the value in this file or in argv.
|
|
28689
|
+
if (_terminalTokens.has(terminalSessionId)) headers['X-Synabun-Terminal-Token'] = `\${${TERMINAL_TOKEN_ENV}}`;
|
|
28347
28690
|
if (browserSessionId) headers['X-Synabun-Browser-Session'] = browserSessionId;
|
|
28348
28691
|
if (browserTabId) headers['X-Synabun-Browser-Tab'] = browserTabId;
|
|
28349
28692
|
const inventory = externalInventory('claude-code', cwd);
|
|
@@ -28452,6 +28795,9 @@ function prepareExecWrapperFile(terminalSessionId, loopState, taskFile, sentinel
|
|
|
28452
28795
|
model: loopState.model,
|
|
28453
28796
|
effort: loopState.effort,
|
|
28454
28797
|
mcpEnvOverrides,
|
|
28798
|
+
// The loop's terminal token is in the PTY's environment (the launch issued it): Codex's SynaBun MCP takes it by
|
|
28799
|
+
// name, so neither this wrapper file nor the command line holds it.
|
|
28800
|
+
mcpEnvVars: _terminalTokens.has(terminalSessionId) ? [TERMINAL_TOKEN_ENV] : [],
|
|
28455
28801
|
// The Admin sandbox setting the loop started with (a loop file from before it: the current one).
|
|
28456
28802
|
codexConfigArgs: codexWindowsSandboxArgs(typeof loopState.adminSandbox === 'boolean' ? loopState.adminSandbox : adminSandboxOn()),
|
|
28457
28803
|
});
|
|
@@ -28569,6 +28915,8 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28569
28915
|
if (!loopState.active) {
|
|
28570
28916
|
clearInterval(interval);
|
|
28571
28917
|
cleanupExecLoopArtifacts(session);
|
|
28918
|
+
// Ended elsewhere (a PTY exit, a stop that left the file): its browser tabs go too (idempotent).
|
|
28919
|
+
endAutomationBrowser(terminalSessionId).catch(() => {});
|
|
28572
28920
|
console.log('[exec-loop-driver] Loop inactive, stopping driver');
|
|
28573
28921
|
return;
|
|
28574
28922
|
}
|
|
@@ -28616,6 +28964,8 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28616
28964
|
clearInterval(interval);
|
|
28617
28965
|
console.log(`[exec-loop-driver] Loop complete: ${iter}/${loopState.totalIterations}`);
|
|
28618
28966
|
cleanupExecLoopArtifacts(session);
|
|
28967
|
+
// Its browser tabs, wherever its route moved (a recovery, its own browser_session create).
|
|
28968
|
+
await endAutomationBrowser(terminalSessionId).catch(() => {});
|
|
28619
28969
|
driving = false;
|
|
28620
28970
|
return;
|
|
28621
28971
|
}
|
|
@@ -28631,15 +28981,22 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28631
28981
|
clearInterval(interval);
|
|
28632
28982
|
console.log(`[exec-loop-driver] Time cap reached: ${Math.round(elapsedMin)}/${loopState.maxMinutes}min`);
|
|
28633
28983
|
cleanupExecLoopArtifacts(session);
|
|
28984
|
+
await endAutomationBrowser(terminalSessionId).catch(() => {});
|
|
28634
28985
|
driving = false;
|
|
28635
28986
|
return;
|
|
28636
28987
|
}
|
|
28637
28988
|
|
|
28638
|
-
//
|
|
28639
|
-
|
|
28640
|
-
|
|
28641
|
-
|
|
28989
|
+
// The task file is written again for every iteration (same path): the prompt names the loop's browser
|
|
28990
|
+
// session and tab, and a recovery or the loop's own browser_session create moves them during a run
|
|
28991
|
+
// (noteAutomationBrowserRoute writes the new ones to the state file read above). Written once, every later
|
|
28992
|
+
// iteration was told the dead ids.
|
|
28993
|
+
const taskFile = prepareExecTaskFile(terminalSessionId, loopState);
|
|
28994
|
+
if (!session._execTaskFile) loopLog(terminalSessionId, 'exec-driver:taskfile', 'task file prepared', { path: taskFile });
|
|
28995
|
+
else if (session._execTaskRoute !== `${loopState.browserSessionId || ''}/${loopState.browserTabId || ''}`) {
|
|
28996
|
+
loopLog(terminalSessionId, 'exec-driver:taskfile', 'task file rewritten: the loop\'s browser route moved', { browserSessionId: loopState.browserSessionId || null, browserTabId: loopState.browserTabId || null });
|
|
28642
28997
|
}
|
|
28998
|
+
session._execTaskFile = taskFile;
|
|
28999
|
+
session._execTaskRoute = `${loopState.browserSessionId || ''}/${loopState.browserTabId || ''}`;
|
|
28643
29000
|
|
|
28644
29001
|
// Generate the platform-native wrapper. It owns exit-code capture and
|
|
28645
29002
|
// sentinel output; the PTY receives only the short wrapper invocation.
|
|
@@ -28710,6 +29067,7 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28710
29067
|
});
|
|
28711
29068
|
clearInterval(interval);
|
|
28712
29069
|
cleanupExecLoopArtifacts(session);
|
|
29070
|
+
await endAutomationBrowser(terminalSessionId).catch(() => {});
|
|
28713
29071
|
try { session.pty?.kill?.(); } catch { /* ok */ }
|
|
28714
29072
|
driving = false;
|
|
28715
29073
|
return;
|
|
@@ -28732,6 +29090,7 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28732
29090
|
loopLog(terminalSessionId, 'exec-driver:error', 'fatal exec driver error', { error: err.message });
|
|
28733
29091
|
clearInterval(interval);
|
|
28734
29092
|
cleanupExecLoopArtifacts(session);
|
|
29093
|
+
endAutomationBrowser(terminalSessionId).catch(() => {});
|
|
28735
29094
|
try { session.pty?.kill?.(); } catch {}
|
|
28736
29095
|
}
|
|
28737
29096
|
driving = false;
|
|
@@ -28744,18 +29103,22 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28744
29103
|
|
|
28745
29104
|
const LAST_SESSION_PATH = resolve(DATA_HOME, 'data', 'last-session.json');
|
|
28746
29105
|
|
|
29106
|
+
// Nothing to resume is the usual answer, not a missing route: 200 with no sessions and the reason (the page's
|
|
29107
|
+
// checkResumePrompt offers a resume only when `sessions` has some). Before 2026-11-05 these were 404s, which every
|
|
29108
|
+
// page load logged as a failed request.
|
|
29109
|
+
const noLastSession = (res, reason) => res.json({ sessions: [], reason });
|
|
28747
29110
|
app.get('/api/last-session', (req, res) => {
|
|
28748
29111
|
try {
|
|
28749
29112
|
const fileExists = existsSync(LAST_SESSION_PATH);
|
|
28750
29113
|
const activeCount = [...terminalSessions.values()].filter(s => s.profile === 'claude-code').length;
|
|
29114
|
+
if (!fileExists) return noLastSession(res, 'none');
|
|
28751
29115
|
console.log(`[last-session] Check: file=${fileExists}, activeClaude=${activeCount}`);
|
|
28752
|
-
if (!fileExists) return res.status(404).json({ error: 'No saved session' });
|
|
28753
29116
|
// If there are currently active claude-code sessions, the snapshot is live — don't offer resume
|
|
28754
|
-
if (activeCount > 0) return res
|
|
29117
|
+
if (activeCount > 0) return noLastSession(res, 'active');
|
|
28755
29118
|
const raw = readFileSync(LAST_SESSION_PATH, 'utf-8').trim();
|
|
28756
29119
|
if (!raw) {
|
|
28757
29120
|
unlinkSync(LAST_SESSION_PATH);
|
|
28758
|
-
return res
|
|
29121
|
+
return noLastSession(res, 'empty');
|
|
28759
29122
|
}
|
|
28760
29123
|
const data = JSON.parse(raw);
|
|
28761
29124
|
// Enrich with labels from ui-state
|
|
@@ -28771,7 +29134,7 @@ app.get('/api/last-session', (req, res) => {
|
|
|
28771
29134
|
// Corrupt file — clean it up so it doesn't keep failing
|
|
28772
29135
|
if (err instanceof SyntaxError) {
|
|
28773
29136
|
try { unlinkSync(LAST_SESSION_PATH); } catch {}
|
|
28774
|
-
return res
|
|
29137
|
+
return noLastSession(res, 'corrupt');
|
|
28775
29138
|
}
|
|
28776
29139
|
res.status(500).json({ error: err.message });
|
|
28777
29140
|
}
|
|
@@ -31062,7 +31425,16 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
31062
31425
|
// owner back to its own tab instead of the shared activeTab.
|
|
31063
31426
|
if (claimedSession && browserTabId) {
|
|
31064
31427
|
if (!claimedSession._tabOwners) claimedSession._tabOwners = new Map();
|
|
31428
|
+
// An owner routes to one tab per session: a tab it already had here (a re-create, a recovery whose old tab
|
|
31429
|
+
// still answers) is closed, not left open and unowned. MoreLogin sessions are never idle-reaped, so before
|
|
31430
|
+
// 2026-11-04 every re-create left one more tab there. The new tab exists first, so this is never the last tab.
|
|
31431
|
+
const previousTabId = claimedSession._tabOwners.get(ownerKey);
|
|
31065
31432
|
claimedSession._tabOwners.set(ownerKey, browserTabId);
|
|
31433
|
+
if (previousTabId && previousTabId !== browserTabId && claimedSession.tabs.has(previousTabId)
|
|
31434
|
+
&& ![...claimedSession._tabOwners].some(([owner, tid]) => owner !== ownerKey && tid === previousTabId)) {
|
|
31435
|
+
await closeSessionTab(claimedSession, browserSessionId, previousTabId).catch(() => {});
|
|
31436
|
+
loopLog(ownerKey, logTag, `closed the ${ownerType} owner's previous tab in this session`, { browserSessionId, previousTabId, browserTabId });
|
|
31437
|
+
}
|
|
31066
31438
|
}
|
|
31067
31439
|
|
|
31068
31440
|
return { browserSessionId, browserTabId };
|
|
@@ -31097,6 +31469,227 @@ async function releaseSharedBrowserTab(sessionId, ownerKey) {
|
|
|
31097
31469
|
}
|
|
31098
31470
|
}
|
|
31099
31471
|
|
|
31472
|
+
/**
|
|
31473
|
+
* Release every tab and claim `ownerKey` holds in any session. A run's route can move during its life (a recovery,
|
|
31474
|
+
* its own browser_session create), so its end releases what it owns now, not only the session it started with.
|
|
31475
|
+
* `except`: a session to leave alone (the one a new tab of the run was just opened in).
|
|
31476
|
+
*/
|
|
31477
|
+
async function releaseBrowserOwnerEverywhere(ownerKey, { except = null } = {}) {
|
|
31478
|
+
if (!ownerKey) return;
|
|
31479
|
+
for (const [sessionId, session] of [...browserSessions]) {
|
|
31480
|
+
if (except && sessionId === except) continue;
|
|
31481
|
+
if (session._tabOwners?.has(ownerKey) || session._loopOwned?.has(ownerKey) || session._interactiveOwned?.has(ownerKey)) {
|
|
31482
|
+
await releaseSharedBrowserTab(sessionId, ownerKey).catch(() => {});
|
|
31483
|
+
}
|
|
31484
|
+
}
|
|
31485
|
+
}
|
|
31486
|
+
|
|
31487
|
+
// ── Browser starts its caller stopped waiting for, and a run's own route ──
|
|
31488
|
+
// lib/browser-start-handoff.js: one start per caller at a time; a start that finishes after its request ended is kept
|
|
31489
|
+
// for that caller's next create / acquire / recovery (no second browser, no session nobody knows about).
|
|
31490
|
+
const browserStartHandoff = createBrowserStartHandoff({ log: (line) => console.log(`[browser] ${line}`) });
|
|
31491
|
+
|
|
31492
|
+
/** gone() for browserStartHandoff.run: true once this request can no longer be answered (408 sent, client left). */
|
|
31493
|
+
function browserCallerGone(req, res) {
|
|
31494
|
+
let closed = false;
|
|
31495
|
+
res.once?.('close', () => { closed = true; });
|
|
31496
|
+
return () => closed || res.headersSent === true || res.writableEnded === true || req.browserRequest?.signal?.aborted === true;
|
|
31497
|
+
}
|
|
31498
|
+
|
|
31499
|
+
/** The answer of a create / acquire / recovery whose browser is still starting when its caller's time is up. */
|
|
31500
|
+
function browserStartingAnswer(kind = 'create') {
|
|
31501
|
+
return {
|
|
31502
|
+
ok: false, starting: true, code: 'BROWSER_STARTING',
|
|
31503
|
+
error: kind === 'create'
|
|
31504
|
+
? 'The browser is still starting (a cold MoreLogin start can take about two minutes). Call browser_session with action "create" again: it returns this browser as soon as it is ready and never starts a second one.'
|
|
31505
|
+
: 'The browser is still starting (a cold MoreLogin start can take about two minutes). Call the browser tool again in a moment: the tab being opened for you is kept for you.',
|
|
31506
|
+
};
|
|
31507
|
+
}
|
|
31508
|
+
|
|
31509
|
+
/** A started session (and tab) still exists, and the tab is still `ownerKey`'s. */
|
|
31510
|
+
function startedTabAlive(sessionId, tabId, ownerKey) {
|
|
31511
|
+
const session = sessionId ? browserSessions.get(sessionId) : null;
|
|
31512
|
+
if (!session) return false;
|
|
31513
|
+
if (tabId && session.tabs && !session.tabs.has(tabId)) return false;
|
|
31514
|
+
if (ownerKey && tabId && session._tabOwners?.get(ownerKey) !== tabId) return false;
|
|
31515
|
+
return true;
|
|
31516
|
+
}
|
|
31517
|
+
|
|
31518
|
+
/** A call of `ownerKey` (the page's: 'anon') was routed to `tabId` of this session at or after `since` (getTargetPage trackRoute). */
|
|
31519
|
+
function browserStartUsedSince(session, ownerKey, tabId, since) {
|
|
31520
|
+
const seen = session?._routeLog?.get(ownerKey || 'anon');
|
|
31521
|
+
return !!seen && Number(seen.lastSeen) >= Number(since || 0) && (!tabId || seen.tabId === tabId);
|
|
31522
|
+
}
|
|
31523
|
+
|
|
31524
|
+
/**
|
|
31525
|
+
* A start nobody took (BROWSER_START_HANDOFF_TTL_MS, or a shutdown): closed, or only its owner's tab when others
|
|
31526
|
+
* joined the session since. Kept when its owner took it after all by another way than the hand-over: a run whose
|
|
31527
|
+
* recorded route it is (its MCP followed yourRoute; the run's end releases it), a call routed to it since it was
|
|
31528
|
+
* parked, or (a session the owner's page created: no owner key) a page watching it or an automation working in it.
|
|
31529
|
+
* @param {{ tabId?: string|null, since?: number, run?: string|null }} [opts]
|
|
31530
|
+
*/
|
|
31531
|
+
async function closeUnclaimedBrowserStart(sessionId, ownerKey, { tabId = null, since = 0, run = null } = {}) {
|
|
31532
|
+
const session = browserSessions.get(sessionId);
|
|
31533
|
+
if (!session) return;
|
|
31534
|
+
if (run && automationRunState(run) !== 'ended') {
|
|
31535
|
+
const current = recordedAutomationRoute(run, { files: true });
|
|
31536
|
+
if (current && current.browserSessionId === sessionId && (!tabId || current.browserTabId === tabId)) return;
|
|
31537
|
+
}
|
|
31538
|
+
if (browserStartUsedSince(session, ownerKey, tabId, since)) return;
|
|
31539
|
+
if (!ownerKey) {
|
|
31540
|
+
if ((session.clients?.size || 0) > 0 || otherSessionOwners(session, null).length > 0) return;
|
|
31541
|
+
} else if (tabId && session._tabOwners?.get(ownerKey) !== tabId) {
|
|
31542
|
+
// Not this owner's tab any more (closed, or the owner has another one there now): nothing of this start is left.
|
|
31543
|
+
return;
|
|
31544
|
+
}
|
|
31545
|
+
const decision = sessionCloseDecision(session, ownerKey);
|
|
31546
|
+
if (decision.action === 'release') await releaseSharedBrowserTab(sessionId, ownerKey);
|
|
31547
|
+
else await destroyBrowserSession(sessionId, { closeOwnTabs: true });
|
|
31548
|
+
console.warn(`[browser] a browser start nobody took was ${decision.action === 'release' ? 'released' : 'closed'}: session ${sessionId} of ${ownerKey || 'the page'}`);
|
|
31549
|
+
}
|
|
31550
|
+
|
|
31551
|
+
// Native runs the runtime still runs (or will resume): every other status has ended.
|
|
31552
|
+
const LIVE_NATIVE_RUN_STATUSES = new Set(['starting', 'running', 'suspended']);
|
|
31553
|
+
// Where a PTY / exec loop's or an agent's route moved (noteAutomationBrowserRoute). Native runs keep it on their record.
|
|
31554
|
+
// Read from memory by GET /api/browser/sessions (yourRoute) on every resolve; forgotten at the run's end.
|
|
31555
|
+
const _movedAutomationRoutes = new Map();
|
|
31556
|
+
// PTY / exec loops and agents that ended (endAutomationBrowser): a late recovery for them opens nothing. Bounded.
|
|
31557
|
+
const _endedAutomationRuns = new Set();
|
|
31558
|
+
const ENDED_AUTOMATION_RUNS_MAX = 2000;
|
|
31559
|
+
|
|
31560
|
+
/** The automation-window agent whose routing id (`agent:<uuid>`) this is, or null. */
|
|
31561
|
+
function agentForTerminal(terminalSessionId) {
|
|
31562
|
+
if (!terminalSessionId || !String(terminalSessionId).startsWith('agent:')) return null;
|
|
31563
|
+
for (const agent of agentRegistry.values()) if (agent._agentTerminalId === terminalSessionId) return agent;
|
|
31564
|
+
return null;
|
|
31565
|
+
}
|
|
31566
|
+
|
|
31567
|
+
/**
|
|
31568
|
+
* Whether a run is 'live', 'ended' or 'unknown' (not a run the server knows: a sidepanel, an interactive caller, a
|
|
31569
|
+
* loop whose state file is gone). `files`: a PTY / exec loop's state file is read too (a recovery; never per resolve).
|
|
31570
|
+
*/
|
|
31571
|
+
function automationRunState(terminalSessionId, { files = false } = {}) {
|
|
31572
|
+
if (!terminalSessionId) return 'unknown';
|
|
31573
|
+
if (_endedAutomationRuns.has(terminalSessionId)) return 'ended';
|
|
31574
|
+
const run = _nativeLoopRuntime?.get?.(terminalSessionId);
|
|
31575
|
+
if (run) return LIVE_NATIVE_RUN_STATUSES.has(run.status) ? 'live' : 'ended';
|
|
31576
|
+
const agent = agentForTerminal(terminalSessionId);
|
|
31577
|
+
if (agent) return agent.status === 'running' ? 'live' : 'ended';
|
|
31578
|
+
if (!files) return _movedAutomationRoutes.has(terminalSessionId) ? 'live' : 'unknown';
|
|
31579
|
+
const loopFile = findLoopFileForTerminal(terminalSessionId);
|
|
31580
|
+
if (!loopFile) return 'unknown';
|
|
31581
|
+
try {
|
|
31582
|
+
return JSON.parse(readFileSync(resolve(LOOP_DIR, loopFile), 'utf-8')).active === false ? 'ended' : 'live';
|
|
31583
|
+
} catch { return 'unknown'; }
|
|
31584
|
+
}
|
|
31585
|
+
|
|
31586
|
+
/**
|
|
31587
|
+
* A PTY / exec loop or an agent ended (its natural end, its time cap, a failure, a stop, its terminal closing): what
|
|
31588
|
+
* it owns in any session is released, its moved route forgotten, and a recovery that finishes later opens nothing for
|
|
31589
|
+
* it. Native runs end through releaseNativeLoopResources.
|
|
31590
|
+
*/
|
|
31591
|
+
async function endAutomationBrowser(terminalSessionId) {
|
|
31592
|
+
if (!terminalSessionId) return;
|
|
31593
|
+
// Nothing may act as the run any more (lib/terminal-tokens.js): its token stops working, its id stays refused.
|
|
31594
|
+
_terminalTokens.revoke(terminalSessionId);
|
|
31595
|
+
_endedAutomationRuns.add(terminalSessionId);
|
|
31596
|
+
while (_endedAutomationRuns.size > ENDED_AUTOMATION_RUNS_MAX) _endedAutomationRuns.delete(_endedAutomationRuns.values().next().value);
|
|
31597
|
+
_movedAutomationRoutes.delete(terminalSessionId);
|
|
31598
|
+
await releaseBrowserOwnerEverywhere(terminalSessionId);
|
|
31599
|
+
}
|
|
31600
|
+
|
|
31601
|
+
/**
|
|
31602
|
+
* The route the server last recorded for a run: its native run record, its agent, the move recorded for a PTY / exec
|
|
31603
|
+
* loop, else (`files`) its loop state file. Nothing for a run that ended. The state files are read only on request (a
|
|
31604
|
+
* recovery): GET /api/browser/sessions asks on every resolve and reads memory only.
|
|
31605
|
+
*/
|
|
31606
|
+
function recordedAutomationRoute(terminalSessionId, { files = false } = {}) {
|
|
31607
|
+
if (!terminalSessionId || _endedAutomationRuns.has(terminalSessionId)) return null;
|
|
31608
|
+
const run = _nativeLoopRuntime?.get?.(terminalSessionId);
|
|
31609
|
+
if (run) {
|
|
31610
|
+
if (!LIVE_NATIVE_RUN_STATUSES.has(run.status)) return null;
|
|
31611
|
+
return run.browserSessionId ? { browserSessionId: run.browserSessionId, browserTabId: run.browserTabId || null } : null;
|
|
31612
|
+
}
|
|
31613
|
+
const agent = agentForTerminal(terminalSessionId);
|
|
31614
|
+
if (agent) {
|
|
31615
|
+
if (agent.status !== 'running') return null;
|
|
31616
|
+
return agent.browserSessionId ? { browserSessionId: agent.browserSessionId, browserTabId: agent.browserTabId || null } : null;
|
|
31617
|
+
}
|
|
31618
|
+
const moved = _movedAutomationRoutes.get(terminalSessionId);
|
|
31619
|
+
if (moved) return { ...moved };
|
|
31620
|
+
if (!files) return null;
|
|
31621
|
+
const loopFile = findLoopFileForTerminal(terminalSessionId);
|
|
31622
|
+
if (!loopFile) return null;
|
|
31623
|
+
try {
|
|
31624
|
+
const data = JSON.parse(readFileSync(resolve(LOOP_DIR, loopFile), 'utf-8'));
|
|
31625
|
+
if (data.active === false) return null;
|
|
31626
|
+
return data.browserSessionId ? { browserSessionId: data.browserSessionId, browserTabId: data.browserTabId || null } : null;
|
|
31627
|
+
} catch { return null; }
|
|
31628
|
+
}
|
|
31629
|
+
|
|
31630
|
+
/** The run's recorded route when it is still usable: its tab open, still the run's, in the default browser. */
|
|
31631
|
+
function liveAutomationRoute(terminalSessionId, { files = false, cfg: knownCfg = null } = {}) {
|
|
31632
|
+
const route = recordedAutomationRoute(terminalSessionId, { files });
|
|
31633
|
+
if (!route?.browserTabId || !startedTabAlive(route.browserSessionId, route.browserTabId, terminalSessionId)) return null;
|
|
31634
|
+
const cfg = knownCfg || loadBrowserConfig();
|
|
31635
|
+
if (cfg.connectMode === 'morelogin' && !sessionServesMoreLoginDefault(browserSessions.get(route.browserSessionId), cfg)) return null;
|
|
31636
|
+
return route;
|
|
31637
|
+
}
|
|
31638
|
+
|
|
31639
|
+
/**
|
|
31640
|
+
* A run's browser route moved (a recovery, its own browser_session create, a tab of its own it moved to): its state
|
|
31641
|
+
* file (ancestor lookups, /api/loop/stop, the exec loop's next iteration), the native run's record or the agent's
|
|
31642
|
+
* (GET /api/browser/sessions yourRoute, the agent's iteration and end) and the Assistant's run record (agent_status)
|
|
31643
|
+
* say where it is now. A run that ended is not moved.
|
|
31644
|
+
*/
|
|
31645
|
+
function noteAutomationBrowserRoute(terminalSessionId, acq, reason = 'recovered') {
|
|
31646
|
+
const route = { browserSessionId: acq?.browserSessionId || null, browserTabId: acq?.browserTabId || null };
|
|
31647
|
+
if (!terminalSessionId || !route.browserSessionId) return;
|
|
31648
|
+
if (automationRunState(terminalSessionId) === 'ended') return;
|
|
31649
|
+
const agent = agentForTerminal(terminalSessionId);
|
|
31650
|
+
if (_nativeLoopRuntime?.get?.(terminalSessionId)) {
|
|
31651
|
+
try { _nativeLoopRuntime.setBrowserRoute(terminalSessionId, route); } catch (err) { console.warn(`[browser] run ${terminalSessionId}: route not recorded: ${err.message}`); }
|
|
31652
|
+
} else if (agent) {
|
|
31653
|
+
// The agent's record and its claim on the session (grace / reuse checks) move with it; its iteration and its end
|
|
31654
|
+
// release what it owns wherever that is (releaseAgentBrowser).
|
|
31655
|
+
if (agent.browserSessionId && agent.browserSessionId !== route.browserSessionId) browserSessions.get(agent.browserSessionId)?._agentOwnedSet?.delete(agent.id);
|
|
31656
|
+
const now = browserSessions.get(route.browserSessionId);
|
|
31657
|
+
if (now) (now._agentOwnedSet ||= new Set()).add(agent.id);
|
|
31658
|
+
agent.browserSessionId = route.browserSessionId;
|
|
31659
|
+
agent.browserTabId = route.browserTabId;
|
|
31660
|
+
} else {
|
|
31661
|
+
_movedAutomationRoutes.set(terminalSessionId, { ...route });
|
|
31662
|
+
const loopFile = findLoopFileForTerminal(terminalSessionId);
|
|
31663
|
+
if (loopFile) {
|
|
31664
|
+
try {
|
|
31665
|
+
const fp = resolve(LOOP_DIR, loopFile);
|
|
31666
|
+
const data = JSON.parse(readFileSync(fp, 'utf-8'));
|
|
31667
|
+
data.browserSessionId = route.browserSessionId;
|
|
31668
|
+
data.browserTabId = route.browserTabId;
|
|
31669
|
+
writeFileSync(fp, JSON.stringify(data, null, 2));
|
|
31670
|
+
} catch (err) {
|
|
31671
|
+
console.warn(`[loop/recover-browser] Failed to update loop state file: ${err.message}`);
|
|
31672
|
+
}
|
|
31673
|
+
}
|
|
31674
|
+
}
|
|
31675
|
+
try { _assistantDispatcher?.noteBrowserRoute?.(terminalSessionId, { ...route, reason }); } catch (err) { console.warn(`[browser] run ${terminalSessionId}: run record not updated: ${err.message}`); }
|
|
31676
|
+
loopLog(terminalSessionId, 'browser:route', `browser route ${reason}`, route);
|
|
31677
|
+
}
|
|
31678
|
+
|
|
31679
|
+
/**
|
|
31680
|
+
* An automation-window agent's browser goes (between iterations, at its end, on a failure): every tab and claim of
|
|
31681
|
+
* its routing id in any session (its route may have moved), and its agent mark on every session.
|
|
31682
|
+
*/
|
|
31683
|
+
async function releaseAgentBrowser(agent, { ended = false } = {}) {
|
|
31684
|
+
if (!agent) return;
|
|
31685
|
+
for (const session of browserSessions.values()) session._agentOwnedSet?.delete(agent.id);
|
|
31686
|
+
// At its end the agent is marked ended first, so a recovery that finishes later opens nothing for it.
|
|
31687
|
+
if (ended) await endAutomationBrowser(agent._agentTerminalId);
|
|
31688
|
+
else await releaseBrowserOwnerEverywhere(agent._agentTerminalId);
|
|
31689
|
+
agent.browserSessionId = null;
|
|
31690
|
+
agent.browserTabId = null;
|
|
31691
|
+
}
|
|
31692
|
+
|
|
31100
31693
|
// ── Real-time sync WebSocket (multi-client state broadcast) ──
|
|
31101
31694
|
const syncClients = new Set(); // Set<WebSocket>
|
|
31102
31695
|
|
|
@@ -32182,7 +32775,8 @@ function unverifiedServeRecords() {
|
|
|
32182
32775
|
}
|
|
32183
32776
|
const NATIVE_SERVE_WAIT_MS = Number(process.env.SYNABUN_NATIVE_SERVE_WAIT_MS) || 20_000;
|
|
32184
32777
|
const NATIVE_SERVE_SWEEP_MS = Number(process.env.SYNABUN_NATIVE_SERVE_SWEEP_MS) || 10_000;
|
|
32185
|
-
// Left of a request's deadline for the answer itself (
|
|
32778
|
+
// Left of a request's deadline for the answer itself (a browser request is answered within BROWSER_REQUEST_MAX_MS,
|
|
32779
|
+
// 120 s, lib/browser-execution.js; the MCP client waits 150 s for a create, SESSION_CREATE_TIMEOUT).
|
|
32186
32780
|
const NATIVE_SERVE_REPLY_MARGIN_MS = 5_000;
|
|
32187
32781
|
// Before refusing, repair what SynaBun can itself, bounded: stop the serves an ended SynaBun left running (the records'
|
|
32188
32782
|
// own sweep, which signals only a provably-SynaBun process whose owner has ended; at most NATIVE_SERVE_SWEEP_MS, in the
|
|
@@ -33451,6 +34045,24 @@ async function recoverSessionTabPage(session, sessionId, tabId, reason = 'page b
|
|
|
33451
34045
|
}
|
|
33452
34046
|
|
|
33453
34047
|
console.warn(`[browser] Failed during ${recoveryStage} for tab ${tabId} in session ${sessionId}: ${error.message}`);
|
|
34048
|
+
// One slow tab does not end the other runs' tabs (lib/browser-wedge-retire.js): while the session's other
|
|
34049
|
+
// tabs still answer, only this tab is retired; its owner's next call gets "Tab not found" and a new tab.
|
|
34050
|
+
if (!session._invalidating && browserSessions.get(sessionId) === session && session.tabs.get(tabId)?.page === oldPage) {
|
|
34051
|
+
const verdict = await decideFailedTabRecovery(session, tabId);
|
|
34052
|
+
if (verdict.action === 'retire-tab' && !session._invalidating && browserSessions.get(sessionId) === session
|
|
34053
|
+
&& session.tabs.get(tabId)?.page === oldPage) {
|
|
34054
|
+
unrouteScreenshotTab(session, sessionId, tabId, oldPage);
|
|
34055
|
+
if (oldEntry?.cdpSession?.detach) {
|
|
34056
|
+
await withBrowserOperationDeadline(oldEntry.cdpSession.detach(), 1_000, 'Detaching wedged browser tab CDP session').catch(() => {});
|
|
34057
|
+
}
|
|
34058
|
+
if (oldPage && !oldPage.isClosed?.()) {
|
|
34059
|
+
await withBrowserOperationDeadline(oldPage.close({ runBeforeUnload: false }), 1_000, 'Closing wedged browser tab').catch(() => {});
|
|
34060
|
+
}
|
|
34061
|
+
console.warn(`[browser] Retired only the wedged tab ${tabId} of session ${sessionId}: ${verdict.otherTabsAnswering} of its ${verdict.otherTabs} other tab(s) still answer, so the session stays (remaining: ${session.tabs.size})`);
|
|
34062
|
+
return { recovered: false, wedgedTabRetired: true, error: error.message };
|
|
34063
|
+
}
|
|
34064
|
+
console.warn(`[browser] Retiring session ${sessionId}: ${verdict.why === 'disconnected' ? 'its browser is disconnected' : `none of its ${verdict.otherTabs ?? 0} other tab(s) answers`}`);
|
|
34065
|
+
}
|
|
33454
34066
|
if (!session._invalidating) {
|
|
33455
34067
|
session._invalidating = true;
|
|
33456
34068
|
// destroyBrowserSession removes the registry entry synchronously before
|
|
@@ -33533,6 +34145,9 @@ function browserRecoveryErrorMessage(error, recovery) {
|
|
|
33533
34145
|
if (recovery?.sessionInvalidated) {
|
|
33534
34146
|
return `${error.message} The unhealthy browser session was retired and will be reacquired on the next browser call.`;
|
|
33535
34147
|
}
|
|
34148
|
+
if (recovery?.wedgedTabRetired) {
|
|
34149
|
+
return `${error.message} The tab stopped answering and no replacement could be opened in time, so it was closed; the browser session stays for its other tabs. The next browser call gets a new tab.`;
|
|
34150
|
+
}
|
|
33536
34151
|
if (recovery?.error) return `${error.message} Automatic tab recovery failed: ${recovery.error}`;
|
|
33537
34152
|
return error.message;
|
|
33538
34153
|
}
|
|
@@ -33793,6 +34408,165 @@ async function otherOpenPageCount(session, own) {
|
|
|
33793
34408
|
}
|
|
33794
34409
|
}
|
|
33795
34410
|
|
|
34411
|
+
// ── Who a browser request is (lib/terminal-tokens.js) ──
|
|
34412
|
+
// A run's X-Synabun-Terminal counts only with that run's terminal token (X-Synabun-Terminal-Token): a request that
|
|
34413
|
+
// names a run SynaBun gave a token to without it, with another one, or after the run ended is refused before any
|
|
34414
|
+
// browser route runs (browserTerminalGate on /api/browser, and /api/loop/recover-browser and /api/morelogin/stop,
|
|
34415
|
+
// which live elsewhere). The same reading decides who a request is on the other routes that act for the run a header
|
|
34416
|
+
// names (POST /api/mcp/runtime-tools, POST /api/loop/stop, the Skills creation and evaluation routes, the Assistant
|
|
34417
|
+
// API's callerContext) and on the browser panel's socket (/ws/browser/:id). Side panels and Assistant brains prove
|
|
34418
|
+
// their ids too: a panel with a token of its own, a brain with its launch credential (bound to its pin; read from
|
|
34419
|
+
// X-Synabun-Brain-Token when no X-Synabun-Terminal-Token came). An id SynaBun gave no proof (an MCP process's own
|
|
34420
|
+
// client id, a CLI window's MCP session, a run from before this server started) is taken as it is said, as before. A
|
|
34421
|
+
// request that carries an agent header (lib/owner-authority.js isAgentCall) but names no run is an automation without
|
|
34422
|
+
// an id, never the owner's page, and since 2026-11-05 no automation at all for the gate either: an agent header proves
|
|
34423
|
+
// nothing (any local process can send one), so such a request needs the page secret like a bare one, but for the
|
|
34424
|
+
// pre-websearch hook's read of which sessions exist (review 972afb74, finding 2). An automation drives only the tabs
|
|
34425
|
+
// it owns (getTargetPage) and calls only the routes SynaBun's browser tools call (lib/browser-automation-routes.js);
|
|
34426
|
+
// every other /api/browser route is the owner's page's (its page secret, or an invite guest the guest rules let in),
|
|
34427
|
+
// whatever agent headers the request carries (finding 1).
|
|
34428
|
+
const BROWSER_CALLER = Symbol('synabun.browserCaller');
|
|
34429
|
+
/** The owner key of an automation that names no run: no owner id can look like it (lib/browser-owner.js). */
|
|
34430
|
+
const ANONYMOUS_AUTOMATION = 'anonymous automation';
|
|
34431
|
+
/** What a request presents as the proof of the id it names: its terminal token, else a brain's launch credential. */
|
|
34432
|
+
function presentedTerminalProof(req) {
|
|
34433
|
+
const header = (name) => (req?.get && req.get(name)) || req?.headers?.[name] || null;
|
|
34434
|
+
return header(TERMINAL_TOKEN_HEADER) || header(BRAIN_CREDENTIAL_HEADER) || null;
|
|
34435
|
+
}
|
|
34436
|
+
/**
|
|
34437
|
+
* Who `req` is to the browser routes (read once per request).
|
|
34438
|
+
* @returns {{ id: string|null, ownerKey: string|null, automation: boolean, accepted: boolean, status: string,
|
|
34439
|
+
* asserted: string|null, code?: string, error?: string, httpStatus?: number, grace?: boolean }}
|
|
34440
|
+
* `id`: the run id the request may act as (null for the owner's page, an automation that names none, a refusal);
|
|
34441
|
+
* `ownerKey`: `id`, else ANONYMOUS_AUTOMATION for an automation, else null (the owner's page);
|
|
34442
|
+
* `accepted`: false when it names a run it cannot prove it is (then `code` / `error` / `httpStatus` say why).
|
|
34443
|
+
*/
|
|
34444
|
+
function browserCaller(req) {
|
|
34445
|
+
if (req && req[BROWSER_CALLER]) return req[BROWSER_CALLER];
|
|
34446
|
+
const raw = (req?.get && req.get('X-Synabun-Terminal')) || req?.headers?.['x-synabun-terminal'] || null;
|
|
34447
|
+
const asserted = typeof raw === 'string' && raw ? raw : null;
|
|
34448
|
+
const presented = presentedTerminalProof(req);
|
|
34449
|
+
const verdict = asserted ? _terminalTokens.verdict(asserted, presented) : { status: 'none', accepted: true };
|
|
34450
|
+
const automation = !!asserted || isAgentCall(req);
|
|
34451
|
+
const id = verdict.accepted ? asserted : null;
|
|
34452
|
+
const caller = { ...verdict, asserted, automation, id, ownerKey: id || (automation ? ANONYMOUS_AUTOMATION : null) };
|
|
34453
|
+
if (req && typeof req === 'object') { try { Object.defineProperty(req, BROWSER_CALLER, { value: caller, configurable: true }); } catch { /* frozen */ } }
|
|
34454
|
+
return caller;
|
|
34455
|
+
}
|
|
34456
|
+
/** The answer to a request that names a run it cannot prove it is (TERMINAL_TOKEN_REQUIRED / TERMINAL_TOKEN_INVALID). */
|
|
34457
|
+
function refuseBrowserCaller(res, caller) {
|
|
34458
|
+
return res.status(caller.httpStatus || 403).json({ error: caller.error, code: caller.code });
|
|
34459
|
+
}
|
|
34460
|
+
/** When each refused id was last logged (one line a minute per id and code, so a stale MCP cannot flood the log). */
|
|
34461
|
+
const _refusedBrowserCallersLogged = new Map();
|
|
34462
|
+
/** Log a refusal once a minute per key (never a token: the code and the id only). */
|
|
34463
|
+
function noteRefusedBrowserCaller(key, line) {
|
|
34464
|
+
const now = Date.now();
|
|
34465
|
+
if (now - (_refusedBrowserCallersLogged.get(key) || 0) < 60_000) return;
|
|
34466
|
+
_refusedBrowserCallersLogged.set(key, now);
|
|
34467
|
+
if (_refusedBrowserCallersLogged.size > 500) _refusedBrowserCallersLogged.delete(_refusedBrowserCallersLogged.keys().next().value);
|
|
34468
|
+
console.warn(line);
|
|
34469
|
+
}
|
|
34470
|
+
/**
|
|
34471
|
+
* Whether a request with no agent header at all may act as the owner's page on the browser routes: this boot's page
|
|
34472
|
+
* secret (lib/page-session.js verify: the cookie the app's own pages carry, never with the automation browser's marker
|
|
34473
|
+
* or from a peer the owner-authority lookup refuses), or an invite guest, whom the guest rules in front decided.
|
|
34474
|
+
*/
|
|
34475
|
+
function browserPageOwner(req) {
|
|
34476
|
+
try { if (isGuestRequest(req)) return true; } catch { return false; }
|
|
34477
|
+
try { return _pageSession.verify(req) === true; } catch { return false; }
|
|
34478
|
+
}
|
|
34479
|
+
/**
|
|
34480
|
+
* Whether a request is the owner's own page, an invite guest excluded: this boot's page secret, never a guest's
|
|
34481
|
+
* session. The owner's browser routes (the browser settings, the money guard, CDP, tab management) and the MoreLogin
|
|
34482
|
+
* settings ask this one: a guest the owner let use the browser drives it through the browser panel's routes, never
|
|
34483
|
+
* the owner's settings.
|
|
34484
|
+
*/
|
|
34485
|
+
function browserOwnerPageOnly(req) {
|
|
34486
|
+
try { if (isGuestRequest(req)) return false; } catch { return false; }
|
|
34487
|
+
try { return _pageSession.verify(req) === true; } catch { return false; }
|
|
34488
|
+
}
|
|
34489
|
+
/**
|
|
34490
|
+
* Whether `req` is the pre-websearch hook's read of which sessions exist (hooks/claude-code/pre-websearch.mjs): an
|
|
34491
|
+
* agent's call that names no run (X-Synabun-Role: hook) and lists the sessions. It is answered the sessions' ids and
|
|
34492
|
+
* nothing else (GET /api/browser/sessions: no address, title, tab or owner key), so the hook can block WebSearch while
|
|
34493
|
+
* a browser session is open without a page secret it cannot have.
|
|
34494
|
+
*/
|
|
34495
|
+
function browserSessionCountRead(req, caller = browserCaller(req)) {
|
|
34496
|
+
const method = String(req?.method || 'GET').toUpperCase();
|
|
34497
|
+
// req.path is '/sessions' under the gate's mount and '/api/browser/sessions' in the route itself.
|
|
34498
|
+
const path = String(req?.path || '').replace(/^\/api\/browser(?=\/)/, '').replace(/\/$/, '');
|
|
34499
|
+
return caller.automation && !caller.id && (method === 'GET' || method === 'HEAD') && path === '/sessions';
|
|
34500
|
+
}
|
|
34501
|
+
/**
|
|
34502
|
+
* Mounted before every /api/browser route: a refused caller reaches none of them. A request that names a run it cannot
|
|
34503
|
+
* prove it is gets 403 TERMINAL_TOKEN_REQUIRED / _INVALID. An automation that names its id (a run with its token, an id
|
|
34504
|
+
* SynaBun gave none) reaches the routes SynaBun's browser tools call (lib/browser-automation-routes.js) and no other:
|
|
34505
|
+
* the browser settings, the money guard's lift, the CDP endpoints and tab management are the owner's page's (403
|
|
34506
|
+
* OWNER_ROUTE; review 972afb74, finding 1). Every other request is the owner's page only with this boot's page secret, or
|
|
34507
|
+
* an invite guest the guest rules let in: an agent header that names no run proves nothing (403 TERMINAL_REQUIRED; the
|
|
34508
|
+
* hook's session count is the one read it gets, browserSessionCountRead; finding 2), a bare request is refused 403
|
|
34509
|
+
* PAGE_SECRET_REQUIRED (503 PEER_UNAVAILABLE where the caller could not be identified on macOS). Before 2026-11-04 a bare
|
|
34510
|
+
* request was the owner's page whatever sent it (review c0eab425, M2); before 2026-11-05 any agent header was enough.
|
|
34511
|
+
*/
|
|
34512
|
+
function browserTerminalGate(req, res, next) {
|
|
34513
|
+
const caller = browserCaller(req);
|
|
34514
|
+
if (!caller.accepted) {
|
|
34515
|
+
noteRefusedBrowserCaller(`${caller.code}:${String(caller.asserted).slice(0, 128)}`, `[browser] ${req.method} ${String(req.path || '').slice(0, 80)} refused: ${caller.code} (X-Synabun-Terminal ${String(caller.asserted).slice(0, 128)})`);
|
|
34516
|
+
return refuseBrowserCaller(res, caller);
|
|
34517
|
+
}
|
|
34518
|
+
const automationRoute = isAutomationBrowserRoute(req.method, req.path);
|
|
34519
|
+
if (caller.id && automationRoute) return next();
|
|
34520
|
+
// The owner's page; an invite guest the guest rules let use the browser, on the browser panel's routes only.
|
|
34521
|
+
if (automationRoute ? browserPageOwner(req) : browserOwnerPageOnly(req)) return next();
|
|
34522
|
+
if (browserSessionCountRead(req, caller)) return next();
|
|
34523
|
+
let guest = false;
|
|
34524
|
+
try { guest = !!isGuestRequest(req); } catch { guest = true; }
|
|
34525
|
+
if (caller.id || guest) {
|
|
34526
|
+
noteRefusedBrowserCaller(`OWNER_ROUTE:${String(req.path || '').slice(0, 80)}`, `[browser] ${req.method} ${String(req.path || '').slice(0, 80)} refused: OWNER_ROUTE (automation ${String(caller.id).slice(0, 128)})`);
|
|
34527
|
+
return res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'This browser route is the owner\'s (SynaBun\'s page: the browser settings, the money guard, CDP, tab management). An automation drives the browser through SynaBun\'s browser tools only.' });
|
|
34528
|
+
}
|
|
34529
|
+
if (caller.automation) {
|
|
34530
|
+
noteRefusedBrowserCaller(`TERMINAL_REQUIRED:${String(req.path || '').slice(0, 80)}`, `[browser] ${req.method} ${String(req.path || '').slice(0, 80)} refused: TERMINAL_REQUIRED (an agent header without X-Synabun-Terminal)`);
|
|
34531
|
+
return res.status(403).json({ ok: false, code: 'TERMINAL_REQUIRED', error: 'An automation says which run it is (X-Synabun-Terminal, sent by SynaBun\'s MCP on every request); an agent header alone is not the owner\'s page. Call the browser through SynaBun\'s MCP tools, or reload SynaBun\'s page.' });
|
|
34532
|
+
}
|
|
34533
|
+
return refuseNotOwnerPage(req, res, 'The browser routes answer SynaBun\'s own page (its page secret, which the page\'s browser sends by itself) or an automation that says who it is (X-Synabun-Terminal, sent by SynaBun\'s MCP on every request). This request is neither: reload SynaBun\'s page, or call the browser through SynaBun\'s MCP tools.');
|
|
34534
|
+
}
|
|
34535
|
+
/**
|
|
34536
|
+
* The answer to a request with no agent header and no page secret on a route that is the owner's page's (the browser
|
|
34537
|
+
* routes, a loop's stop): 503 PEER_UNAVAILABLE where the caller could not be identified on macOS (a reload may cure it),
|
|
34538
|
+
* else 403 PAGE_SECRET_REQUIRED, which the page's fetch recovers by itself after a restart (public/shared/page-session.js).
|
|
34539
|
+
*/
|
|
34540
|
+
function refuseNotOwnerPage(req, res, error) {
|
|
34541
|
+
let down = null;
|
|
34542
|
+
try { down = _pageSession.peerUnavailable?.(req) || null; } catch { down = null; }
|
|
34543
|
+
if (down) return _pageSession.sendUnavailable(res, req, down);
|
|
34544
|
+
noteRefusedBrowserCaller(`PAGE_SECRET_REQUIRED:${String(req.path || '').slice(0, 80)}`, `[browser] ${req.method} ${String(req.path || '').slice(0, 80)} refused: PAGE_SECRET_REQUIRED (no agent header and no page secret)`);
|
|
34545
|
+
return res.status(403).json({ ok: false, code: 'PAGE_SECRET_REQUIRED', error });
|
|
34546
|
+
}
|
|
34547
|
+
/**
|
|
34548
|
+
* Why the browser panel's socket for session `sessionId` (/ws/browser/:id) is refused, or null when it may open: the
|
|
34549
|
+
* owner's page (this boot's page secret) or an invite guest the upgrade's guest rules let in, and nobody else. The
|
|
34550
|
+
* socket drives any tab of the session (switch tab, close tab, navigate, click, type: handleBrowserWebSocket never knows
|
|
34551
|
+
* who sent a command), and only the browser panel of SynaBun's own pages opens it: a run drives its own tab through the
|
|
34552
|
+
* browser routes, which check the tab of every call (getTargetPage). Until 2026-11-05 a run that owned one tab of the
|
|
34553
|
+
* session opened its socket and drove every tab there (review 972afb74, finding 3). → { status, code, retryable? } | null
|
|
34554
|
+
*/
|
|
34555
|
+
function browserSocketRefusal(req, sessionId) {
|
|
34556
|
+
if (browserPageOwner(req)) return null;
|
|
34557
|
+
const who = browserCaller(req);
|
|
34558
|
+
const logRefusal = (code) => noteRefusedBrowserCaller(`ws:${code}:${String(who.asserted || '').slice(0, 128)}`, `[ws-browser] socket for session ${String(sessionId).slice(0, 80)} refused: ${code}${who.asserted ? ` (X-Synabun-Terminal ${String(who.asserted).slice(0, 128)})` : ''}`);
|
|
34559
|
+
if (!who.accepted) { logRefusal(who.code); return { status: who.httpStatus || 403, code: who.code }; }
|
|
34560
|
+
if (!who.automation) {
|
|
34561
|
+
let down = null;
|
|
34562
|
+
try { down = _pageSession.peerUnavailable?.(req) || null; } catch { down = null; }
|
|
34563
|
+
if (down) return { status: 503, code: 'PEER_UNAVAILABLE', retryable: down.retryable === true };
|
|
34564
|
+
}
|
|
34565
|
+
const code = who.automation ? 'OWNER_SOCKET' : 'PAGE_SECRET_REQUIRED';
|
|
34566
|
+
logRefusal(code);
|
|
34567
|
+
return { status: 403, code };
|
|
34568
|
+
}
|
|
34569
|
+
|
|
33796
34570
|
// ── Tab-level page routing (concurrent loop isolation) ──
|
|
33797
34571
|
|
|
33798
34572
|
/** Automation owners (loops, interactive MCP processes, agents) on a session. */
|
|
@@ -33816,24 +34590,33 @@ function trackRoute(session, identityKey, tabId, source) {
|
|
|
33816
34590
|
|
|
33817
34591
|
/**
|
|
33818
34592
|
* Resolve the Playwright page for an API request.
|
|
33819
|
-
*
|
|
33820
|
-
*
|
|
33821
|
-
*
|
|
33822
|
-
* a
|
|
34593
|
+
* An automation (a run id, or any agent header: browserCaller) gets the tab it owns (session._tabOwners) and no other:
|
|
34594
|
+
* an explicit tabId must be its own, and a tab-less call routes to its own tab. A tab it does not own, a manual tab
|
|
34595
|
+
* of the owner's included, is never handed to it (null: the route answers 404 and the MCP-side recovery gives the run
|
|
34596
|
+
* a tab of its own). Until 2026-11-05 an automation also got an explicit tab nobody owned and the lone tab of a session
|
|
34597
|
+
* nobody held, so any local process that said an id read and drove the owner's manual tab (review 972afb74, finding 2).
|
|
34598
|
+
* The owner's page (no agent header, its page secret) keeps the manual-control fallbacks.
|
|
34599
|
+
* The caller is browserCaller's: a run's id only with its terminal token (a request that names a run without it never
|
|
34600
|
+
* gets here: browserTerminalGate).
|
|
33823
34601
|
*/
|
|
33824
34602
|
function getTargetPage(session, req) {
|
|
33825
|
-
const
|
|
33826
|
-
|
|
33827
|
-
|
|
33828
|
-
//
|
|
34603
|
+
const caller = browserCaller(req);
|
|
34604
|
+
// null for the owner's page, an automation that names no run, and (never routed here) a refused one.
|
|
34605
|
+
const terminalId = caller.id;
|
|
34606
|
+
// An automation (a run id, or any agent header) drives its own tab only; only the owner's page (no agent header at
|
|
34607
|
+
// all) keeps the manual-control fallbacks.
|
|
34608
|
+
const isAutomation = caller.automation;
|
|
34609
|
+
const ownTabId = terminalId ? (session._tabOwners?.get(terminalId) || null) : null;
|
|
34610
|
+
|
|
34611
|
+
// 1. An explicit tab: an automation's own only. Manual UI requests carry no agent header and may intentionally
|
|
34612
|
+
// inspect any tab.
|
|
33829
34613
|
const tabId = req.body?.tabId || req.query?.tabId;
|
|
33830
34614
|
if (tabId) {
|
|
33831
34615
|
const tab = session.tabs?.get(tabId);
|
|
33832
34616
|
if (!tab) return null;
|
|
33833
|
-
if (
|
|
33834
|
-
|
|
33835
|
-
|
|
33836
|
-
if ((owned && owned !== tabId) || claimedByOther) return null;
|
|
34617
|
+
if (isAutomation && ownTabId !== tabId) {
|
|
34618
|
+
console.warn(`[browser] tab-not-owned: refusing explicit tab ${String(tabId).slice(0, 40)} to an automation that does not own it (id=${terminalId || 'none'})`);
|
|
34619
|
+
return null;
|
|
33837
34620
|
}
|
|
33838
34621
|
trackRoute(session, terminalId, tabId, 'explicit-tab');
|
|
33839
34622
|
return { page: tab.page, cdpSession: tab.cdpSession, tabId };
|
|
@@ -33842,60 +34625,45 @@ function getTargetPage(session, req) {
|
|
|
33842
34625
|
// 2. No tabId — route by caller identity. The MCP child sends X-Synabun-Terminal
|
|
33843
34626
|
// (its loop terminalSessionId, sidepanel owner key, or per-caller client id).
|
|
33844
34627
|
// If that caller owns a tab here, use it — never the shared activeTab.
|
|
33845
|
-
if (
|
|
33846
|
-
const
|
|
33847
|
-
const tab = session.tabs?.get(ownedTabId);
|
|
34628
|
+
if (ownTabId) {
|
|
34629
|
+
const tab = session.tabs?.get(ownTabId);
|
|
33848
34630
|
if (tab) {
|
|
33849
|
-
trackRoute(session, terminalId,
|
|
33850
|
-
return { page: tab.page, cdpSession: tab.cdpSession, tabId:
|
|
34631
|
+
trackRoute(session, terminalId, ownTabId, 'owner-map');
|
|
34632
|
+
return { page: tab.page, cdpSession: tab.cdpSession, tabId: ownTabId };
|
|
33851
34633
|
}
|
|
33852
34634
|
// Owned tab vanished — drop the stale mapping and fall through.
|
|
33853
34635
|
session._tabOwners.delete(terminalId);
|
|
33854
34636
|
}
|
|
33855
34637
|
|
|
33856
|
-
//
|
|
33857
|
-
//
|
|
33858
|
-
|
|
33859
|
-
|
|
33860
|
-
|
|
33861
|
-
|
|
33862
|
-
|
|
33863
|
-
|
|
34638
|
+
// 3. An automation that owns no open tab here: FAIL CLOSED. It never inherits another automation's tab, a tab nobody
|
|
34639
|
+
// owns, or the owner's manual tab; the MCP-side recovery acquires it a fresh owned tab instead.
|
|
34640
|
+
if (isAutomation) {
|
|
34641
|
+
console.warn(`[browser] tab-pin-missing: refusing a tab the automation does not own (id=${terminalId || 'none'}, tabs=${session.tabs?.size ?? 0}, owners=${sessionOwnerCount(session)}) — returning 404 to avoid cross-automation leak`);
|
|
34642
|
+
return null;
|
|
34643
|
+
}
|
|
34644
|
+
|
|
34645
|
+
// The owner's page (no agent header, its page secret): manual control. Taking over an automation's session is a
|
|
34646
|
+
// supervised user action, not a cross-automation collision.
|
|
33864
34647
|
|
|
33865
|
-
//
|
|
33866
|
-
// this means its own tab is gone (or never registered): fail closed so the
|
|
33867
|
-
// MCP-side recovery acquires it a fresh owned tab instead of hijacking the
|
|
33868
|
-
// lone tab another automation may own.
|
|
34648
|
+
// 4. Single-tab session — unambiguous for the owner's page.
|
|
33869
34649
|
if (session.tabs && session.tabs.size === 1) {
|
|
33870
34650
|
const onlyTabId = session.tabs.keys().next().value;
|
|
33871
34651
|
const only = session.tabs.get(onlyTabId);
|
|
33872
|
-
|
|
33873
|
-
if (only && (!isAutomation || (sessionOwnerCount(session) === 0 && !tabClaimed))) {
|
|
34652
|
+
if (only) {
|
|
33874
34653
|
trackRoute(session, terminalId, onlyTabId, 'single-tab');
|
|
33875
34654
|
return { page: only.page, cdpSession: only.cdpSession, tabId: onlyTabId };
|
|
33876
34655
|
}
|
|
33877
|
-
if (only) {
|
|
33878
|
-
console.warn(`[browser] tab-pin-missing:single: refusing lone tab for unmatched automation (id=${terminalId}, owners=${sessionOwnerCount(session)}, claimed=${tabClaimed}) — returning 404 to avoid cross-automation leak`);
|
|
33879
|
-
return null;
|
|
33880
|
-
}
|
|
33881
34656
|
}
|
|
33882
34657
|
|
|
33883
|
-
//
|
|
33884
|
-
//
|
|
33885
|
-
//
|
|
33886
|
-
// cross-automation website leaks. The NI UI drives multi-tab sessions via explicit
|
|
33887
|
-
// tab activation / CDP input, not tab-less REST calls.
|
|
34658
|
+
// 5. Multi-tab session with a tab-less call: FAIL CLOSED (pre-existing behavior). Falling back to the shared activeTab
|
|
34659
|
+
// hands the caller whatever tab an automation navigated last. The NI UI drives multi-tab sessions via explicit tab
|
|
34660
|
+
// activation / CDP input, not tab-less REST calls.
|
|
33888
34661
|
if (session.tabs && session.tabs.size > 1) {
|
|
33889
|
-
console.warn(`[browser] tab-pin-missing: refusing activeTab fallback (id
|
|
34662
|
+
console.warn(`[browser] tab-pin-missing: refusing activeTab fallback (id=none, tabs=${session.tabs.size}, owners=${sessionOwnerCount(session)}, persistent=${!!session._isPersistent}) — returning 404 to avoid cross-automation leak`);
|
|
33890
34663
|
return null;
|
|
33891
34664
|
}
|
|
33892
34665
|
|
|
33893
|
-
//
|
|
33894
|
-
// session). Automations with a lost pin fail closed here too.
|
|
33895
|
-
if (isAutomation && sessionOwnerCount(session) > 0) {
|
|
33896
|
-
console.warn(`[browser] tab-pin-missing:legacy: refusing activeTab on owner-held session (id=${terminalId}, owners=${sessionOwnerCount(session)}) — returning 404 to avoid cross-automation leak`);
|
|
33897
|
-
return null;
|
|
33898
|
-
}
|
|
34666
|
+
// 6. Zero/uninitialized tabs — legacy single active-tab behavior (local UI session).
|
|
33899
34667
|
// No active page at all (the last tab closed or was retired): there is nothing to route to.
|
|
33900
34668
|
if (!session.page) return null;
|
|
33901
34669
|
trackRoute(session, terminalId, session.activeTabId, 'legacy');
|
|
@@ -33922,6 +34690,8 @@ async function getBrowserActionState(session, routed, compact) {
|
|
|
33922
34690
|
|
|
33923
34691
|
// ── Browser REST endpoints ──
|
|
33924
34692
|
|
|
34693
|
+
// First: a request that names a run it cannot prove it is (its terminal token) reaches no browser route at all.
|
|
34694
|
+
app.use('/api/browser', browserTerminalGate);
|
|
33925
34695
|
app.use('/api/browser', browserRequestMiddleware);
|
|
33926
34696
|
app.use('/api/browser', (req, res, next) => { res.setHeader('X-Synabun-Browser-Default', browserDefaultSignature()); next(); });
|
|
33927
34697
|
// Agents act on the default browser only. MCP callers (browser tools, platform
|
|
@@ -33947,7 +34717,8 @@ app.use('/api/browser/sessions/:id', (req, res, next) => {
|
|
|
33947
34717
|
res.once('finish', release);
|
|
33948
34718
|
res.once('close', release);
|
|
33949
34719
|
}
|
|
33950
|
-
|
|
34720
|
+
// An agent's request (a run id, or any agent header: browserCaller) acts on the default browser only.
|
|
34721
|
+
if (!browserCaller(req).automation || exempt) return next();
|
|
33951
34722
|
const session = browserSessions.get(req.params.id);
|
|
33952
34723
|
if (!session) return next();
|
|
33953
34724
|
const cfg = loadBrowserConfig();
|
|
@@ -33974,12 +34745,34 @@ app.get('/api/browser/sessions', (req, res) => {
|
|
|
33974
34745
|
// The server decides which sessions may carry normal-page work: with MoreLogin as
|
|
33975
34746
|
// the default, only a MoreLogin session on the default env does (MCP callers
|
|
33976
34747
|
// require servesDefault). Every session serves the default in other setups.
|
|
34748
|
+
// A run named without its terminal token learns nothing here, not even its own route (browserTerminalGate too).
|
|
34749
|
+
const who = browserCaller(req);
|
|
34750
|
+
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
34751
|
+
// The pre-websearch hook's read (an agent header that names no run, no page secret: browserSessionCountRead) learns
|
|
34752
|
+
// which sessions exist and nothing of them: it blocks WebSearch while one is open.
|
|
34753
|
+
if (browserSessionCountRead(req, who) && !browserPageOwner(req)) {
|
|
34754
|
+
return res.json({ sessions: [...browserSessions.keys()].map((id) => ({ id })), countOnly: true });
|
|
34755
|
+
}
|
|
33977
34756
|
const policyCfg = loadBrowserConfig();
|
|
33978
34757
|
const moreLoginDefault = policyCfg.connectMode === 'morelogin';
|
|
33979
|
-
const
|
|
34758
|
+
const caller = browserOwnerId(who.id);
|
|
34759
|
+
// Owner keys are what X-Synabun-Terminal names: only the owner's own page sees them all (collision debugging); an
|
|
34760
|
+
// automation sees its own and the others as `other-N` (lib/browser-owner.js listedOwners), never another run's id.
|
|
34761
|
+
const revealOwners = (() => { try { return _pageSession.verify(req) === true; } catch { return false; } })();
|
|
34762
|
+
// An automation sees its own tab of a session (id, live URL, title) and how many others there are, never another
|
|
34763
|
+
// run's or the owner's tabs, nor the session's address and title, which are its active tab's (2026-11-05: workers
|
|
34764
|
+
// listed every tab of the shared MoreLogin session and could not tell theirs).
|
|
34765
|
+
const automationView = who.automation && !revealOwners;
|
|
34766
|
+
const liveUrl = (t) => { try { return t.page?.url?.() || t.url; } catch { return t.url; } };
|
|
34767
|
+
const sessions = [...browserSessions.entries()].map(([id, s]) => {
|
|
34768
|
+
const allTabs = s.tabs ? [...s.tabs.entries()] : [];
|
|
34769
|
+
const ownTabId = automationView && caller ? (s._tabOwners?.get(caller) || null) : null;
|
|
34770
|
+
const shownTabs = automationView ? allTabs.filter(([tid]) => tid === ownTabId) : allTabs;
|
|
34771
|
+
const ownTab = automationView && shownTabs.length ? shownTabs[0][1] : null;
|
|
34772
|
+
return {
|
|
33980
34773
|
id,
|
|
33981
|
-
url: s.currentUrl,
|
|
33982
|
-
title: s.title,
|
|
34774
|
+
url: automationView ? (ownTab ? liveUrl(ownTab) : null) : s.currentUrl,
|
|
34775
|
+
title: automationView ? (ownTab ? ownTab.title || '' : null) : s.title,
|
|
33983
34776
|
createdAt: s.createdAt,
|
|
33984
34777
|
clients: s.clients.size,
|
|
33985
34778
|
persistent: !!s._isPersistent,
|
|
@@ -33987,38 +34780,50 @@ app.get('/api/browser/sessions', (req, res) => {
|
|
|
33987
34780
|
profileSource: s._profileSourceName || null,
|
|
33988
34781
|
moreloginEnvId: s._mlEnvId || null,
|
|
33989
34782
|
servesDefault: moreLoginDefault ? sessionServesMoreLoginDefault(s, policyCfg) : true,
|
|
33990
|
-
|
|
33991
|
-
|
|
34783
|
+
// The browser's own CDP endpoint drives every tab past every check here: the owner's page's only.
|
|
34784
|
+
wsEndpoint: who.automation || s._isPersistent ? null : (s.browser.wsEndpoint?.() || null),
|
|
34785
|
+
activeTabId: automationView ? (ownTabId && s.activeTabId === ownTabId ? ownTabId : null) : (s.activeTabId || null),
|
|
33992
34786
|
loopOwned: (s._loopOwned?.size || 0) > 0,
|
|
33993
34787
|
interactiveOwned: (s._interactiveOwned?.size || 0) > 0,
|
|
33994
34788
|
// Also check agent registry as fallback — covers the race window between
|
|
33995
34789
|
// session creation and agent ownership being set
|
|
33996
34790
|
agentOwned: (s._agentOwnedSet?.size || 0) > 0 || [...agentRegistry.values()].some(a => a.status === 'running' && a.browserSessionId === id),
|
|
33997
|
-
// Identity → tab attribution for
|
|
33998
|
-
// `
|
|
33999
|
-
|
|
34000
|
-
|
|
34001
|
-
interactive: [...(s._interactiveOwned || [])],
|
|
34002
|
-
agents: [...(s._agentOwnedSet || [])],
|
|
34003
|
-
},
|
|
34004
|
-
tabOwners: s._tabOwners ? Object.fromEntries(s._tabOwners) : {},
|
|
34005
|
-
tabs: s.tabs ? [...s.tabs.entries()].map(([tid, t]) => ({
|
|
34791
|
+
// Identity → tab attribution (owners, tabOwners): every key for the owner's page, an automation's own key and
|
|
34792
|
+
// `other-N` for the rest otherwise.
|
|
34793
|
+
...listedOwners(s._tabOwners, { loops: s._loopOwned || [], interactive: s._interactiveOwned || [], agents: s._agentOwnedSet || [] }, { caller, reveal: revealOwners }),
|
|
34794
|
+
tabs: shownTabs.map(([tid, t]) => ({
|
|
34006
34795
|
id: tid,
|
|
34007
|
-
url: t.url,
|
|
34796
|
+
url: automationView ? liveUrl(t) : t.url,
|
|
34008
34797
|
title: t.title,
|
|
34009
34798
|
active: tid === s.activeTabId,
|
|
34010
|
-
}))
|
|
34011
|
-
|
|
34799
|
+
})),
|
|
34800
|
+
...(automationView && { otherTabs: allTabs.length - shownTabs.length, ownTabsOnly: true }),
|
|
34801
|
+
};
|
|
34802
|
+
});
|
|
34803
|
+
// A run's own route as the server last recorded it (a recovery or a browser_session create moved it): the MCP
|
|
34804
|
+
// follows it even after its process restarted and forgot (mcp-server neural-interface.ts resolveSessionUncached).
|
|
34805
|
+
const yourRoute = caller ? liveAutomationRoute(caller, { cfg: policyCfg }) : null;
|
|
34012
34806
|
res.json({
|
|
34013
34807
|
sessions,
|
|
34014
34808
|
defaultBrowser: moreLoginDefault
|
|
34015
34809
|
? { connectMode: 'morelogin', moreloginEnvId: moreLoginDefaultEnvId(policyCfg) }
|
|
34016
34810
|
: { connectMode: policyCfg.connectMode || null },
|
|
34811
|
+
...(yourRoute ? { yourRoute: { sessionId: yourRoute.browserSessionId, tabId: yourRoute.browserTabId } } : {}),
|
|
34812
|
+
// POST /api/loop/recover-browser records a run's move to a tab of its own (`adopt`): an MCP asks it only of a
|
|
34813
|
+
// server that says so (an older one reads the request as a recovery and opens a tab).
|
|
34814
|
+
adoptRoute: true,
|
|
34017
34815
|
});
|
|
34018
34816
|
});
|
|
34019
34817
|
|
|
34020
34818
|
app.post('/api/browser/sessions', async (req, res) => {
|
|
34021
34819
|
const { url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, connectMode, moreloginEnvId } = req.body;
|
|
34820
|
+
// Which browser or MoreLogin profile a session starts on is the owner's choice (Settings → Browser): an automation's
|
|
34821
|
+
// create opens the default browser and names neither (lib/browser-automation-routes.js; review 972afb74, finding 1).
|
|
34822
|
+
const creator = browserCaller(req);
|
|
34823
|
+
const ownerFields = creator.automation ? ownerOnlyCreateFields(req.body) : [];
|
|
34824
|
+
if (ownerFields.length) {
|
|
34825
|
+
return res.status(403).json({ ok: false, code: 'OWNER_ONLY_FIELDS', fields: ownerFields, error: `An automation opens the default browser: ${ownerFields.join(' and ')} ${ownerFields.length === 1 ? 'is' : 'are'} the owner's choice (Settings → Browser). Leave ${ownerFields.length === 1 ? 'it' : 'them'} out.` });
|
|
34826
|
+
}
|
|
34022
34827
|
// A create-session startUrl that points at one of SynaBun's own live OpenCode serve ports is refused up front, like
|
|
34023
34828
|
// navigate and new-tab: the serve's API can change what a worker session may do, and createBrowserSession navigates
|
|
34024
34829
|
// to the startUrl while the rest of the session is still being wired. (createBrowserSession enforces the same denial
|
|
@@ -34032,14 +34837,6 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
34032
34837
|
const _realHeaders = {
|
|
34033
34838
|
'accept-language': req.headers['accept-language'],
|
|
34034
34839
|
};
|
|
34035
|
-
const result = await createBrowserSession({
|
|
34036
|
-
url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, _realHeaders,
|
|
34037
|
-
// Its deadline bounds the native serve check (installServePortGuard) inside the caller's timeout.
|
|
34038
|
-
browserRequest: req.browserRequest,
|
|
34039
|
-
// Optional per-session override to target a specific MoreLogin env (multi-identity)
|
|
34040
|
-
...(connectMode === 'morelogin' ? { connectMode } : {}),
|
|
34041
|
-
...(moreloginEnvId ? { moreloginEnvId: String(moreloginEnvId) } : {}),
|
|
34042
|
-
});
|
|
34043
34840
|
// Tab ownership for the creating automation. An MCP child sends its routing
|
|
34044
34841
|
// identity in X-Synabun-Terminal; register it as the owner of this session's
|
|
34045
34842
|
// active tab. Without this, a plain-created tab is "unowned" and the creator's
|
|
@@ -34047,18 +34844,50 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
34047
34844
|
// acquires a second tab in the same shared persistent browser — the root of the
|
|
34048
34845
|
// sidepanel-vs-CLI "lost browser session" collision. Manual NI-UI creates send
|
|
34049
34846
|
// no header → stay unowned (legacy activeTab semantics preserved).
|
|
34050
|
-
|
|
34051
|
-
|
|
34847
|
+
// An id the server minted (lib/browser-owner.js), `agent:<uuid>` included, and a run's only with its terminal token
|
|
34848
|
+
// (browserCaller: a forged one is refused here and by browserTerminalGate, never the owner of a new tab).
|
|
34849
|
+
const who = browserCaller(req);
|
|
34850
|
+
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
34851
|
+
const creatorTerminalId = browserOwnerId(who.id);
|
|
34852
|
+
// The start, its owner and its broadcast: once per start, whoever ends up with it.
|
|
34853
|
+
const start = async () => {
|
|
34854
|
+
const result = await createBrowserSession({
|
|
34855
|
+
url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, _realHeaders,
|
|
34856
|
+
// Its deadline bounds the native serve check (installServePortGuard) inside the caller's timeout.
|
|
34857
|
+
browserRequest: req.browserRequest,
|
|
34858
|
+
// Optional per-session override to target a specific MoreLogin env (multi-identity)
|
|
34859
|
+
...(connectMode === 'morelogin' ? { connectMode } : {}),
|
|
34860
|
+
...(moreloginEnvId ? { moreloginEnvId: String(moreloginEnvId) } : {}),
|
|
34861
|
+
});
|
|
34052
34862
|
const createdSession = browserSessions.get(result.sessionId);
|
|
34053
|
-
if (createdSession) {
|
|
34863
|
+
if (creatorTerminalId && createdSession) {
|
|
34054
34864
|
if (!createdSession._tabOwners) createdSession._tabOwners = new Map();
|
|
34055
34865
|
createdSession._tabOwners.set(creatorTerminalId, createdSession.activeTabId);
|
|
34056
34866
|
}
|
|
34057
|
-
|
|
34058
|
-
|
|
34867
|
+
broadcastSync({ type: 'browser:session-created', sessionId: result.sessionId, url: url || 'about:blank', profileMode: result.profileMode, profileSource: result.profileSource });
|
|
34868
|
+
return { ...result, tabId: createdSession?.activeTabId || null };
|
|
34869
|
+
};
|
|
34870
|
+
// A create runs once at a time per caller, and a start its caller stopped waiting for (a cold MoreLogin start
|
|
34871
|
+
// takes up to two minutes) is handed to its next create instead of starting a second browser
|
|
34872
|
+
// (lib/browser-start-handoff.js). An automation is answered 202 BROWSER_STARTING before its deadline. The owner's
|
|
34873
|
+
// page (no X-Synabun-Terminal) reads no 202, so it waits for the start as before; one that outlives its request
|
|
34874
|
+
// (the deadline's 408) is kept for the page's next create, and closed when nobody takes, watches or joins it.
|
|
34875
|
+
const outcome = await browserStartHandoff.run(creatorTerminalId ? `create:${creatorTerminalId}` : 'create:page', start, {
|
|
34876
|
+
gone: browserCallerGone(req, res),
|
|
34877
|
+
waitMs: creatorTerminalId ? startWaitMs(req.browserRequest?.deadline) : Infinity,
|
|
34878
|
+
alive: (value) => startedTabAlive(value.sessionId, value.tabId, creatorTerminalId),
|
|
34879
|
+
onUnclaimed: (value, info) => closeUnclaimedBrowserStart(value.sessionId, creatorTerminalId, { tabId: value.tabId, since: info?.parkedAt }),
|
|
34880
|
+
});
|
|
34881
|
+
if (outcome.pending) return res.status(202).json(browserStartingAnswer('create'));
|
|
34882
|
+
const result = outcome.value;
|
|
34883
|
+
const handedOver = outcome.from !== 'started' ? outcome.from : null;
|
|
34884
|
+
// A start handed over from an earlier request may not be at this request's URL: say where it is.
|
|
34885
|
+
const landedUrl = handedOver ? (browserSessions.get(result.sessionId)?.page?.url?.() || 'about:blank') : (url || 'about:blank');
|
|
34059
34886
|
res.json({
|
|
34060
|
-
|
|
34887
|
+
// The CDP endpoint drives every tab past every check: the owner's page's only.
|
|
34888
|
+
sessionId: result.sessionId, tabId: result.tabId || null, url: landedUrl, wsEndpoint: who.automation ? null : result.wsEndpoint, profileMode: result.profileMode, profileSource: result.profileSource,
|
|
34061
34889
|
...(result.moreLoginBlocked && { moreLoginBlocked: true, notice: result.moreLoginBlocked }),
|
|
34890
|
+
...(handedOver && { handedOver }),
|
|
34062
34891
|
});
|
|
34063
34892
|
} catch (err) {
|
|
34064
34893
|
console.error('Browser session create error:', err.message);
|
|
@@ -34068,6 +34897,25 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
34068
34897
|
|
|
34069
34898
|
app.delete('/api/browser/sessions/:id', async (req, res) => {
|
|
34070
34899
|
try {
|
|
34900
|
+
// An automation's close of a session other automations still work in closes only its own tab there
|
|
34901
|
+
// (lib/browser-session-close.js): one run's cleanup must not end the others' tabs mid-write. The caller is
|
|
34902
|
+
// browserCaller's: a run only with its terminal token (a forged one is refused), and an agent's request that
|
|
34903
|
+
// names no run closes as an automation that owns nothing there, never as the owner's page.
|
|
34904
|
+
const who = browserCaller(req);
|
|
34905
|
+
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
34906
|
+
const caller = who.ownerKey;
|
|
34907
|
+
const decision = sessionCloseDecision(browserSessions.get(req.params.id), caller);
|
|
34908
|
+
// An automation closes only a session it works in (a tab of its own, or a hold on the session): the owner's manual
|
|
34909
|
+
// session, or a session nobody holds, is the owner's to close (review 972afb74, finding 4).
|
|
34910
|
+
if (decision.action === 'refuse') {
|
|
34911
|
+
console.warn(`[browser] close of session ${req.params.id} by ${caller} refused: it owns no tab and holds nothing there`);
|
|
34912
|
+
return res.status(403).json({ ok: false, code: 'NOT_OWNED', error: `Session ${req.params.id} is not yours to close: you have no tab in it. Close only the sessions you opened; the owner closes the others from SynaBun's page.` });
|
|
34913
|
+
}
|
|
34914
|
+
if (decision.action === 'release') {
|
|
34915
|
+
await releaseSharedBrowserTab(req.params.id, caller);
|
|
34916
|
+
console.warn(`[browser] close of shared session ${req.params.id} by ${caller}: kept for ${decision.others.length} other owner(s) (${decision.others.join(', ')}); ${decision.ownTabId ? `closed only its tab ${decision.ownTabId}` : 'it had no tab of its own there'}`);
|
|
34917
|
+
return res.json({ ok: true, sessionKept: true, releasedTabId: decision.ownTabId, otherOwners: decision.others.length });
|
|
34918
|
+
}
|
|
34071
34919
|
// An explicit close (browser_session close, the UI): in MoreLogin or the user's Chrome, the tabs SynaBun opened for it close too.
|
|
34072
34920
|
await destroyBrowserSession(req.params.id, { closeOwnTabs: true });
|
|
34073
34921
|
res.json({ ok: true });
|
|
@@ -34078,29 +34926,58 @@ app.delete('/api/browser/sessions/:id', async (req, res) => {
|
|
|
34078
34926
|
|
|
34079
34927
|
// POST /api/browser/acquire — interactive (non-loop) MCP process claims a dedicated
|
|
34080
34928
|
// tab in the ONE shared browser instead of launching a second browser on the same
|
|
34081
|
-
// persistent profile (which fails with "Browser profile is locked"). The
|
|
34082
|
-
//
|
|
34083
|
-
//
|
|
34084
|
-
//
|
|
34929
|
+
// persistent profile (which fails with "Browser profile is locked"). The tab is owned
|
|
34930
|
+
// by the id the caller routes as (X-Synabun-Terminal, required): getTargetPage checks
|
|
34931
|
+
// an explicit tab against that header, so a tab filed under anything else (before
|
|
34932
|
+
// 2026-11-04 the MCP sent its process id here while a run without browser pins routed
|
|
34933
|
+
// as its run id) was refused to its own caller. Body: { clientId, url? } (clientId is
|
|
34934
|
+
// what an older MCP sent; the header decides). Returns { ok, sessionId, tabId }.
|
|
34085
34935
|
app.post('/api/browser/acquire', async (req, res) => {
|
|
34086
34936
|
try {
|
|
34087
|
-
|
|
34088
|
-
|
|
34089
|
-
|
|
34090
|
-
if (
|
|
34091
|
-
|
|
34937
|
+
// A run's id only with its terminal token (browserCaller; browserTerminalGate refuses it first).
|
|
34938
|
+
const who = browserCaller(req);
|
|
34939
|
+
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
34940
|
+
if (!req.body?.clientId) return res.status(400).json({ error: 'clientId is required' });
|
|
34941
|
+
const owner = browserOwnerId(who.id);
|
|
34942
|
+
if (!owner) return res.status(403).json({ error: 'A tab is acquired for the caller that routes as it (X-Synabun-Terminal, sent by SynaBun\'s MCP on every request); this request did not say who it is.', code: 'TERMINAL_REQUIRED' });
|
|
34943
|
+
// One acquisition per caller at a time; one it stopped waiting for (a cold browser start) is handed to its next
|
|
34944
|
+
// request (lib/browser-start-handoff.js), and one nobody takes is released. The tab stays the caller's:
|
|
34945
|
+
// /api/browser/release closes it on exit.
|
|
34946
|
+
const outcome = await browserStartHandoff.run(`acquire:${owner}`, async () => {
|
|
34947
|
+
const acq = await acquireSharedBrowserTab({ ownerKey: owner, ownerType: 'interactive', logTag: 'acquire:interactive' });
|
|
34948
|
+
if (acq.error) throw Object.assign(new Error(acq.error), { acquisition: acq });
|
|
34949
|
+
return acq;
|
|
34950
|
+
}, {
|
|
34951
|
+
gone: browserCallerGone(req, res),
|
|
34952
|
+
waitMs: startWaitMs(req.browserRequest?.deadline),
|
|
34953
|
+
alive: (acq) => startedTabAlive(acq.browserSessionId, acq.browserTabId, owner),
|
|
34954
|
+
onUnclaimed: (acq, info) => closeUnclaimedBrowserStart(acq.browserSessionId, owner, { tabId: acq.browserTabId, since: info?.parkedAt, run: owner }),
|
|
34955
|
+
});
|
|
34956
|
+
if (outcome.pending) return res.status(202).json(browserStartingAnswer('tab'));
|
|
34957
|
+
const acq = outcome.value;
|
|
34958
|
+
res.json({ ok: true, sessionId: acq.browserSessionId, tabId: acq.browserTabId || null, ...(outcome.from !== 'started' && { handedOver: outcome.from }) });
|
|
34092
34959
|
} catch (err) {
|
|
34093
|
-
|
|
34960
|
+
const acq = err?.acquisition;
|
|
34961
|
+
if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
|
|
34962
|
+
res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code } : {}) });
|
|
34094
34963
|
}
|
|
34095
34964
|
});
|
|
34096
34965
|
|
|
34097
34966
|
// POST /api/browser/release — interactive MCP process relinquishes its owned tab on
|
|
34098
34967
|
// exit. Closes the dedicated tab and drops the ownership/routing entries so the shared
|
|
34099
34968
|
// browser can be grace-reaped once no owners remain. Best-effort; body: { clientId }.
|
|
34969
|
+
// A caller releases its own tabs only: the id it routes as (X-Synabun-Terminal), which
|
|
34970
|
+
// a clientId in the body must match (403 TERMINAL_REQUIRED / TERMINAL_MISMATCH).
|
|
34100
34971
|
app.post('/api/browser/release', async (req, res) => {
|
|
34101
34972
|
try {
|
|
34973
|
+
// A run's id only with its terminal token (browserCaller; browserTerminalGate refuses it first).
|
|
34974
|
+
const who = browserCaller(req);
|
|
34975
|
+
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
34102
34976
|
const clientId = req.body?.clientId;
|
|
34103
34977
|
if (!clientId) return res.status(400).json({ error: 'clientId is required' });
|
|
34978
|
+
const caller = browserOwnerId(who.id);
|
|
34979
|
+
if (!caller) return res.status(403).json({ error: 'A release names its caller (X-Synabun-Terminal).', code: 'TERMINAL_REQUIRED' });
|
|
34980
|
+
if (caller !== clientId) return res.status(403).json({ error: `This caller (${caller}) may not release the tabs of ${clientId}.`, code: 'TERMINAL_MISMATCH' });
|
|
34104
34981
|
let released = 0;
|
|
34105
34982
|
for (const [sessionId, session] of browserSessions) {
|
|
34106
34983
|
if (!session._interactiveOwned?.has(clientId)) continue;
|
|
@@ -34171,8 +35048,9 @@ app.delete('/api/browser/sessions/:id/tabs/:tabId', async (req, res) => {
|
|
|
34171
35048
|
const engagementScheduler = createEngagementScheduler();
|
|
34172
35049
|
const _paceRand = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
|
|
34173
35050
|
|
|
35051
|
+
/** The run a browser request may act as (browserCaller: a run's id only with its terminal token), or null. */
|
|
34174
35052
|
function _paceTerminalId(req) {
|
|
34175
|
-
return (req
|
|
35053
|
+
return browserCaller(req).id;
|
|
34176
35054
|
}
|
|
34177
35055
|
function isLoopPaced(session, req) {
|
|
34178
35056
|
if (process.env.SYNABUN_HUMAN_PACING === '0') return false;
|
|
@@ -34193,6 +35071,40 @@ async function rateLimitEngagement(session, req, selector, execute) {
|
|
|
34193
35071
|
if (!isLoopPaced(session, req) || !isEngagementWriteSelector(selector)) return execute();
|
|
34194
35072
|
return engagementScheduler.run(req.params.id, req, execute);
|
|
34195
35073
|
}
|
|
35074
|
+
// Social writes a tool makes through a page script (Bluesky's bluesky_post / bluesky_action / bluesky_dm send) name
|
|
35075
|
+
// their platform in the evaluate body (`pace`): a loop's write waits out the account's gap inside this call, or
|
|
35076
|
+
// answers how much is left when more than the call may wait (lib/social-write-pacing.js). Never the agent's sleep.
|
|
35077
|
+
const socialWritePacer = createSocialWritePacer({ delay: (ms, req) => measureBrowserPhase('intentionalPacing', () => cancellableBrowserDelay(ms, req)) });
|
|
35078
|
+
function socialPaceWaitBudget(req, requested) {
|
|
35079
|
+
const state = req?.browserRequest;
|
|
35080
|
+
const byDeadline = state ? state.deadline - Date.now() - SOCIAL_PACE_LIMITS.writeReserveMs : requested;
|
|
35081
|
+
return Math.max(0, Math.min(requested, byDeadline));
|
|
35082
|
+
}
|
|
35083
|
+
/** The account a session's writes go out as (its browser profile), so a session closed and opened again keeps the gap. */
|
|
35084
|
+
function socialPaceKey(platform, session, sessionId) {
|
|
35085
|
+
return socialPaceAccountKey(platform, {
|
|
35086
|
+
profileMode: session?._profileMode,
|
|
35087
|
+
moreloginEnvId: session?._mlEnvId,
|
|
35088
|
+
profileDir: session?._selectedProfilePath || session?._launchUserDataDir || null,
|
|
35089
|
+
storageStatePath: session?._storageStatePath || null,
|
|
35090
|
+
}, sessionId);
|
|
35091
|
+
}
|
|
35092
|
+
/**
|
|
35093
|
+
* Why a page routed earlier in this request may no longer be used, or null. A request that awaited before acting
|
|
35094
|
+
* (a paced write waits up to 90 s) can find its session closed meanwhile (another automation's browser_session
|
|
35095
|
+
* close, a retired wedged session) or its tab gone. The answer is the error the routes give for a missing session or
|
|
35096
|
+
* tab, so the client knows nothing started and finds the run's tab again.
|
|
35097
|
+
*/
|
|
35098
|
+
function routedPageGone(sessionId, session, routed) {
|
|
35099
|
+
if (browserSessions.get(sessionId) !== session) return 'Session not found';
|
|
35100
|
+
const tabGone = routed.tabId
|
|
35101
|
+
? (session.tabs?.size && session.tabs.get(routed.tabId)?.page !== routed.page)
|
|
35102
|
+
: false;
|
|
35103
|
+
let closed = false;
|
|
35104
|
+
try { closed = routed.page?.isClosed?.() === true; } catch { closed = false; }
|
|
35105
|
+
if (tabGone || closed) return routed.tabId ? `Tab ${routed.tabId} not found in session` : 'Session not found';
|
|
35106
|
+
return null;
|
|
35107
|
+
}
|
|
34196
35108
|
|
|
34197
35109
|
// ── X/Twitter compose-state probe + publish gate ──
|
|
34198
35110
|
// Deterministic read of the X composer so loops branch on structured state instead of
|
|
@@ -34418,6 +35330,7 @@ app.post('/api/browser/sessions/:id/navigate', async (req, res) => {
|
|
|
34418
35330
|
error: browserRecoveryErrorMessage(err, recovery),
|
|
34419
35331
|
...(recovery && { tabRecovered: !!recovery.recovered }),
|
|
34420
35332
|
...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
|
|
35333
|
+
...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
|
|
34421
35334
|
});
|
|
34422
35335
|
}
|
|
34423
35336
|
});
|
|
@@ -34442,6 +35355,7 @@ app.post('/api/browser/sessions/:id/back', async (req, res) => {
|
|
|
34442
35355
|
error: browserRecoveryErrorMessage(err, recovery),
|
|
34443
35356
|
...(recovery && { tabRecovered: !!recovery.recovered }),
|
|
34444
35357
|
...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
|
|
35358
|
+
...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
|
|
34445
35359
|
});
|
|
34446
35360
|
}
|
|
34447
35361
|
});
|
|
@@ -34466,6 +35380,7 @@ app.post('/api/browser/sessions/:id/forward', async (req, res) => {
|
|
|
34466
35380
|
error: browserRecoveryErrorMessage(err, recovery),
|
|
34467
35381
|
...(recovery && { tabRecovered: !!recovery.recovered }),
|
|
34468
35382
|
...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
|
|
35383
|
+
...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
|
|
34469
35384
|
});
|
|
34470
35385
|
}
|
|
34471
35386
|
});
|
|
@@ -34487,6 +35402,7 @@ app.post('/api/browser/sessions/:id/reload', async (req, res) => {
|
|
|
34487
35402
|
error: browserRecoveryErrorMessage(err, recovery),
|
|
34488
35403
|
...(recovery && { tabRecovered: !!recovery.recovered }),
|
|
34489
35404
|
...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
|
|
35405
|
+
...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
|
|
34490
35406
|
});
|
|
34491
35407
|
}
|
|
34492
35408
|
});
|
|
@@ -34945,21 +35861,43 @@ app.post('/api/browser/sessions/:id/evaluate', async (req, res) => {
|
|
|
34945
35861
|
if (!script) return res.status(400).json({ error: 'script required' });
|
|
34946
35862
|
const xRefusal = xGateBypassRefusal(session, req, routed, 'evaluate', script);
|
|
34947
35863
|
if (xRefusal) return res.status(409).json(xRefusal);
|
|
34948
|
-
|
|
35864
|
+
const run = async () => {
|
|
35865
|
+
// A paced write may have waited a minute: run it only on the page this request was routed to, if it is still
|
|
35866
|
+
// there. Otherwise nothing starts (no pacing slot is taken) and the answer is a missing session or tab.
|
|
35867
|
+
const gone = routedPageGone(req.params.id, session, routed);
|
|
35868
|
+
if (gone) throw Object.assign(new Error(gone), { writeStarted: false, routeGone: true });
|
|
34949
35869
|
markBrowserActionStarted(req);
|
|
34950
|
-
|
|
35870
|
+
return withBrowserOperationDeadline(
|
|
34951
35871
|
routed.page.evaluate(script),
|
|
34952
35872
|
BROWSER_EVALUATE_DEADLINE_MS,
|
|
34953
35873
|
'browser_evaluate',
|
|
34954
35874
|
);
|
|
35875
|
+
};
|
|
35876
|
+
const pace = socialPaceRequest(req.body);
|
|
35877
|
+
try {
|
|
35878
|
+
if (pace && isLoopPaced(session, req)) {
|
|
35879
|
+
const outcome = await socialWritePacer.run(socialPaceKey(pace.platform, session, req.params.id), {
|
|
35880
|
+
platform: pace.platform, maxWaitMs: socialPaceWaitBudget(req, pace.maxWaitMs), signal: req,
|
|
35881
|
+
}, run);
|
|
35882
|
+
const gap = SOCIAL_WRITE_GAPS[pace.platform];
|
|
35883
|
+
if (outcome.status === 'paced') {
|
|
35884
|
+
return res.json({ ok: true, paced: { pending: true, retryAfterMs: outcome.retryAfterMs, waitedMs: outcome.waitedMs, gapMinMs: gap.minMs, gapMaxMs: gap.maxMs } });
|
|
35885
|
+
}
|
|
35886
|
+
const result = outcome.result;
|
|
35887
|
+
return res.json({ ok: true, result: result === undefined ? null : result, paced: { pending: false, waitedMs: outcome.waitedMs, gapMinMs: gap.minMs, gapMaxMs: gap.maxMs } });
|
|
35888
|
+
}
|
|
35889
|
+
const result = await run();
|
|
34955
35890
|
// Ensure result is JSON-serializable (undefined becomes null)
|
|
34956
35891
|
res.json({ ok: true, result: result === undefined ? null : result });
|
|
34957
35892
|
} catch (err) {
|
|
35893
|
+
// Gone before it started: never "recover" a tab of a session that is closed (that would open a page in it).
|
|
35894
|
+
if (err?.routeGone) return res.status(404).json({ error: err.message });
|
|
34958
35895
|
const recovery = await recoverBrowserRouteFailure(session, req.params.id, routed, req, 'evaluate', err);
|
|
34959
35896
|
res.status(500).json({
|
|
34960
35897
|
error: browserRecoveryErrorMessage(err, recovery),
|
|
34961
35898
|
...(recovery && { tabRecovered: !!recovery.recovered }),
|
|
34962
35899
|
...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
|
|
35900
|
+
...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
|
|
34963
35901
|
});
|
|
34964
35902
|
}
|
|
34965
35903
|
});
|
|
@@ -36399,14 +37337,18 @@ httpServer.on('upgrade', function onUpgrade(req, socket, head) {
|
|
|
36399
37337
|
// Owner authority by peer identity (lib/owner-authority.js): an owner's socket (a terminal, the agent panels, the
|
|
36400
37338
|
// Assistant, the browser panel) is refused to SynaBun's automation browser, a relay, another SynaBun server, a
|
|
36401
37339
|
// remote login and an agent's tree that does not say it is an agent's call; the sync socket stays open for them,
|
|
36402
|
-
// read-only.
|
|
37340
|
+
// read-only. On macOS a caller that could not be identified gets no owner socket either (503: the lookup failed) and a
|
|
37341
|
+
// read-only sync socket. The peer is looked up once, then the handler runs again from the top with the answer on the
|
|
37342
|
+
// request. checkUpgrade never rejects; should it, upgradeFailed() decides as for a failed lookup (on macOS an owner
|
|
37343
|
+
// socket is refused and the sync socket read-only), never the rules from before by accident.
|
|
36403
37344
|
if (!req._synabunOwnerChecked && (_ownerAuthority.socketScope(url.pathname).owner || _ownerAuthority.socketScope(url.pathname).readOnly)) {
|
|
36404
37345
|
req._synabunOwnerChecked = true;
|
|
36405
|
-
|
|
36406
|
-
if (verdict.refuse) { refuseUpgrade(socket, 403); return; }
|
|
37346
|
+
const settle = (verdict) => {
|
|
37347
|
+
if (verdict.refuse) { if (verdict.status === 503) refuseUpgrade(socket, 503, 'Service Unavailable', { 'Retry-After': verdict.retryable ? '2' : '30' }); else refuseUpgrade(socket, 403); return; }
|
|
36407
37348
|
if (verdict.readOnly) req._synabunReadOnly = true;
|
|
36408
37349
|
onUpgrade(req, socket, head);
|
|
36409
|
-
}
|
|
37350
|
+
};
|
|
37351
|
+
_ownerAuthority.checkUpgrade(req, url.pathname).then(settle, (error) => settle(_ownerAuthority.upgradeFailed(req, url.pathname, error)));
|
|
36410
37352
|
return;
|
|
36411
37353
|
}
|
|
36412
37354
|
|
|
@@ -36420,6 +37362,19 @@ httpServer.on('upgrade', function onUpgrade(req, socket, head) {
|
|
|
36420
37362
|
return;
|
|
36421
37363
|
}
|
|
36422
37364
|
|
|
37365
|
+
// The browser panel's socket drives a session's tabs (navigate, click, type, new tab, switch tab): the owner's page
|
|
37366
|
+
// (this boot's page secret) or an invite guest the rules above let in, and nobody else (browserSocketRefusal). Before
|
|
37367
|
+
// 2026-11-04 nothing asked who opened it, so any local client without an Origin drove any session (review c0eab425,
|
|
37368
|
+
// finding L3); until 2026-11-05 a run that owned one tab of the session drove all of them (review 972afb74, finding 3).
|
|
37369
|
+
if (url.pathname.startsWith('/ws/browser/')) {
|
|
37370
|
+
const refused = browserSocketRefusal(req, url.pathname.slice('/ws/browser/'.length));
|
|
37371
|
+
if (refused) {
|
|
37372
|
+
if (refused.status === 503) refuseUpgrade(socket, 503, 'Service Unavailable', { 'Retry-After': refused.retryable ? '2' : '30' });
|
|
37373
|
+
else refuseUpgrade(socket, 403);
|
|
37374
|
+
return;
|
|
37375
|
+
}
|
|
37376
|
+
}
|
|
37377
|
+
|
|
36423
37378
|
if (url.pathname.startsWith('/ws/browser/') || url.pathname.startsWith('/ws/assistant/') || url.pathname === '/ws/whiteboard' || url.pathname === '/ws/cards' || url.pathname === '/ws/sync' || url.pathname === '/ws/claude-skin' || url.pathname === '/ws/codex-skin' || url.pathname === '/ws/opencode-v2' || url.pathname === '/ws/antigravity' || url.pathname === '/ws/sessions') {
|
|
36424
37379
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
36425
37380
|
wss.emit('connection', ws, req);
|