synabun 2.2.0 → 2.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -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 +27 -0
- package/neural-interface/i18n/pt-BR.json +27 -0
- package/neural-interface/lib/assistant-api.js +64 -23
- package/neural-interface/lib/assistant-brains/codex.js +6 -1
- package/neural-interface/lib/assistant-catalog.js +20 -2
- package/neural-interface/lib/assistant-dispatch.js +31 -2
- 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 +64 -13
- package/neural-interface/lib/native-loop-providers.js +122 -10
- package/neural-interface/lib/native-loop-runtime.js +112 -11
- package/neural-interface/lib/opencode-native-boundary.js +155 -21
- 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 +311 -47
- 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-api.js +14 -2
- package/neural-interface/public/shared/assistant/asst-computer.js +73 -4
- package/neural-interface/public/shared/assistant/asst-limit-wait.js +3 -1
- package/neural-interface/public/shared/assistant/asst-motion-gate.js +80 -0
- package/neural-interface/public/shared/assistant/asst-panel.js +8 -4
- package/neural-interface/public/shared/assistant/asst-render.js +72 -11
- package/neural-interface/public/shared/assistant/asst-scene-styles.js +55 -23
- package/neural-interface/public/shared/assistant/asst-scenes.js +225 -79
- package/neural-interface/public/shared/assistant/asst-sidepanel-styles.js +4 -4
- package/neural-interface/public/shared/assistant/asst-style-cache.js +44 -0
- package/neural-interface/public/shared/assistant/asst-styles.js +26 -5
- 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 +18 -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/loading-teardown.js +34 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +6 -1
- 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 +5 -2
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +16 -86
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +6 -0
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +88 -72
- 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/storage-retry.js +47 -0
- package/neural-interface/public/shared/storage.js +25 -4
- package/neural-interface/public/shared/styles.css +109 -8
- package/neural-interface/public/shared/synabun-mascot.js +27 -8
- package/neural-interface/public/shared/synabun-ticker.js +147 -12
- 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 +238 -90
- package/neural-interface/public/shared/ui-judgments.js +37 -10
- package/neural-interface/public/shared/ui-loading.js +5 -4
- 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 +1240 -238
- 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';
|
|
@@ -25,8 +25,8 @@ import { SANDBOX_EXEC, buildWorkerSandboxProfile, canonicalPath, sandboxExecArgv
|
|
|
25
25
|
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
|
-
import { createPeerIdentity } from './lib/peer-identity.js';
|
|
29
|
-
import { createOwnerAuthority } from './lib/owner-authority.js';
|
|
28
|
+
import { createPeerIdentity, debugClientPolicy } from './lib/peer-identity.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,8 +211,8 @@ 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';
|
|
208
|
-
import { createNativeServeBoundary, nativeServeCapability } from './lib/opencode-native-boundary.js';
|
|
214
|
+
import { browserServePortDenial, browserSessionLossRule } from './lib/browser-tool-policy.js';
|
|
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';
|
|
211
218
|
import { browserPolicyRoots } from './lib/browser-policy-roots.js';
|
|
@@ -447,6 +454,9 @@ try {
|
|
|
447
454
|
// allowed until a restart. What the environment itself gives is noted first and put back after the load; the
|
|
448
455
|
// file's own line is read when a request asks (publicWebOrigins).
|
|
449
456
|
const startedAllowedHosts = startedValueOf(process.env);
|
|
457
|
+
// The profiling exemption (lib/peer-identity.js debugClientPolicy) is read from the started environment only, before
|
|
458
|
+
// the data home's .env can add to it.
|
|
459
|
+
const startedDebugClient = debugClientPolicy(process.env);
|
|
450
460
|
dotenvConfig({ path: resolve(getDataHome(), '.env') });
|
|
451
461
|
startedAllowedHosts.restore();
|
|
452
462
|
|
|
@@ -552,11 +562,17 @@ app.use(requestGates.features);
|
|
|
552
562
|
// for automation, an AI agent's process tree, another SynaBun server or a relay (ssh, socat, a proxy, a tunnel, any
|
|
553
563
|
// program that listens and calls SynaBun) is never handed the secret and never counts as the owner, whatever host,
|
|
554
564
|
// cookie or marker it sends. A brain credential (X-Synabun-Brain-Token) from a process outside the brain's own tree
|
|
555
|
-
// is dropped from the request.
|
|
556
|
-
//
|
|
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).
|
|
557
571
|
// This install's root (PACKAGE_ROOT, defined further down): SynaBun's own MCP server over HTTP is the one listening
|
|
558
572
|
// program the lookup knows, by its main script under it (mcp-server/dist/http.js, `npm run start:http`).
|
|
559
|
-
const _peerIdentity = createPeerIdentity({ log: (line) => console.warn(line), disabled: String(process.env.SYNABUN_PEER_IDENTITY || '').toLowerCase() === 'off', synabunRoots: [resolve(__dirname, '..')] });
|
|
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();
|
|
560
576
|
// The one decision for the owner's routes and sockets (lib/owner-authority.js): every write to /api but the hooks'
|
|
561
577
|
// and the agents' feature data, the two reads that hand out a secret, and the owner's sockets are refused to the
|
|
562
578
|
// automation browser (its marker or its process), relays, other SynaBun servers, remote logins and an agent's tree
|
|
@@ -2413,6 +2429,11 @@ async function runGracefulShutdown(reason) {
|
|
|
2413
2429
|
let keepRuns = [];
|
|
2414
2430
|
try { keepRuns = _assistantDispatcher?.suspendForShutdown?.(reason) || []; } catch (err) { console.warn(' assistant suspend err:', err?.message); }
|
|
2415
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); }
|
|
2416
2437
|
try { stopAllIsolatedServes(); } catch (err) { console.warn(' isolated opencode stop err:', err?.message); }
|
|
2417
2438
|
// The Antigravity panel's `agy acp` processes (one per open panel socket).
|
|
2418
2439
|
try { await antigravityPanel.closeAll(); } catch (err) { console.warn(' antigravity panel stop err:', err?.message); }
|
|
@@ -3755,22 +3776,25 @@ function opencodeServeLaunch(port, { env = process.env, password = null, passwor
|
|
|
3755
3776
|
_noteCliLookup('opencode', found, 'OpenCode');
|
|
3756
3777
|
const line = configuredCommandLine('opencode');
|
|
3757
3778
|
const nativeWebSocketSafe = nativeServeCapability({ version: found.version, commandLine: !!line, passwordFrom });
|
|
3758
|
-
|
|
3779
|
+
// What the browser boundary names when this serve is the one that blocks a native (MoreLogin) context. A command
|
|
3780
|
+
// line from Settings runs whatever it names: the resolver's version is of another binary, so none is reported.
|
|
3781
|
+
const nativeServe = { version: line ? null : (found.version || null), path: line || found.launchPath || found.path || null, reason: nativeServeReason({ version: found.version, commandLine: !!line, passwordFrom }) };
|
|
3782
|
+
nativeServeBoundary.assertLaunch(nativeWebSocketSafe, { port, ...nativeServe });
|
|
3759
3783
|
const spec = serveSpecFor(port, { env, password, passwordFrom });
|
|
3760
3784
|
const words = spec.args.join(' ');
|
|
3761
3785
|
if (IS_WIN) {
|
|
3762
3786
|
const spawnEnv = withPathEnv(spec.env, getAugmentedPath());
|
|
3763
3787
|
if (!line && found.spec) {
|
|
3764
3788
|
const launch = spawnArgsFor(found.spec, spec.args, { env: spawnEnv });
|
|
3765
|
-
return { command: launch.command, args: launch.args, options: { ...launch.options, env: spawnEnv, windowsHide: true }, label: `${found.launchPath} ${words}`, password: spec.password, passwordFrom: spec.passwordFrom, nativeWebSocketSafe };
|
|
3789
|
+
return { command: launch.command, args: launch.args, options: { ...launch.options, env: spawnEnv, windowsHide: true }, label: `${found.launchPath} ${words}`, password: spec.password, passwordFrom: spec.passwordFrom, nativeWebSocketSafe, nativeServe };
|
|
3766
3790
|
}
|
|
3767
3791
|
const text = `${line || 'opencode'} ${words}`;
|
|
3768
|
-
return { command: DEFAULT_SHELL, args: ['/d', '/s', '/c', text], options: { env: spawnEnv, windowsHide: true }, label: text, password: spec.password, passwordFrom: spec.passwordFrom, nativeWebSocketSafe };
|
|
3792
|
+
return { command: DEFAULT_SHELL, args: ['/d', '/s', '/c', text], options: { env: spawnEnv, windowsHide: true }, label: text, password: spec.password, passwordFrom: spec.passwordFrom, nativeWebSocketSafe, nativeServe };
|
|
3769
3793
|
}
|
|
3770
3794
|
const cmd = line || (found.path ? shellSingleQuote(found.path) : 'opencode');
|
|
3771
3795
|
const unset = spec.passwordFrom === 'stdout' ? `${serveUnsetCommand()}; ` : '';
|
|
3772
3796
|
// A packaged application's runtime and npm after the user's own (the login shell adds the user's profile on top).
|
|
3773
|
-
return { command: DEFAULT_SHELL, args: ['-lc', `${unset}exec ${cmd} ${words}`], options: { env: withPackagedPathLast(spec.env) }, label: `${cmd} ${words}`, password: spec.password, passwordFrom: spec.passwordFrom, nativeWebSocketSafe };
|
|
3797
|
+
return { command: DEFAULT_SHELL, args: ['-lc', `${unset}exec ${cmd} ${words}`], options: { env: withPackagedPathLast(spec.env) }, label: `${cmd} ${words}`, password: spec.password, passwordFrom: spec.passwordFrom, nativeWebSocketSafe, nativeServe };
|
|
3774
3798
|
}
|
|
3775
3799
|
|
|
3776
3800
|
// Which OpenCode the binary SynaBun starts is: the resolver's `--version` of it
|
|
@@ -4094,6 +4118,10 @@ function codexSandboxArgs() { return codexWindowsSandboxArgs(adminSandboxOn());
|
|
|
4094
4118
|
// live restart never loses worker dispatch to a sandbox that could not be built. Codex is handled differently
|
|
4095
4119
|
// (its own sandbox cannot be wrapped): a guarded Codex worker runs with its network off (lib/native-loop-providers.js).
|
|
4096
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) });
|
|
4097
4125
|
/** The launch beacon's loopback port (lib/start-launcher.js startBeaconPort): a SynaBun listener while a launch lives. */
|
|
4098
4126
|
function workerBeaconPort() { const p = Number(PORT) || 3344; return p + 10000 <= 65535 ? p + 10000 : p - 10000; }
|
|
4099
4127
|
/** Browser-control ports a guarded worker must not reach, by fixed knowledge (dynamic ones come from detection,
|
|
@@ -4625,6 +4653,9 @@ CRITICAL — When you need clarification during planning:
|
|
|
4625
4653
|
if (_codexToolsRuntimes.get(codexMcpRuntimeId) === codexMcpRuntimeBinding) {
|
|
4626
4654
|
_codexToolsRuntimes.delete(codexMcpRuntimeId);
|
|
4627
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);
|
|
4628
4659
|
cancelRuntimeMcpToolsRefresh(codexMcpRuntimeId);
|
|
4629
4660
|
codexMcpRuntimeBinding = null;
|
|
4630
4661
|
if (cleanup) cleanupCodexRuntimeTools(codexMcpRuntimeId);
|
|
@@ -5766,6 +5797,13 @@ CRITICAL — When you need clarification during planning:
|
|
|
5766
5797
|
activeCodexHome = launch.home;
|
|
5767
5798
|
let codexBin = getCodexBin();
|
|
5768
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);
|
|
5769
5807
|
const args = [
|
|
5770
5808
|
'-c',
|
|
5771
5809
|
`mcp_servers.SynaBun.env.SYNABUN_TOOLS=${JSON.stringify('all')}`,
|
|
@@ -5786,6 +5824,7 @@ CRITICAL — When you need clarification during planning:
|
|
|
5786
5824
|
if (codexDesktopGrant) args.splice(args.length - 1, 0, '-c', `mcp_servers.SynaBun.env.SYNABUN_DESKTOP_GRANT=${JSON.stringify(codexDesktopGrant)}`);
|
|
5787
5825
|
// The variable's name on the command line, its value only in the app-server's environment (below).
|
|
5788
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}"]`);
|
|
5789
5828
|
if (codexRole === 'assistant' && codexRouteGate?.flags?.length) args.splice(args.length - 1, 0, ...codexRouteGate.flags);
|
|
5790
5829
|
if (/\.js$/i.test(codexBin)) {
|
|
5791
5830
|
args.unshift(codexBin);
|
|
@@ -5806,9 +5845,12 @@ CRITICAL — When you need clarification during planning:
|
|
|
5806
5845
|
...(codexDesktopGrant ? { SYNABUN_DESKTOP_GRANT: codexDesktopGrant } : {}),
|
|
5807
5846
|
...(codexRole === 'assistant' && codexRouteGate?.env ? codexRouteGate.env : {}),
|
|
5808
5847
|
...(codexRole === 'assistant' && codexBrainCredential ? { SYNABUN_BRAIN_TOKEN: codexBrainCredential } : {}),
|
|
5848
|
+
...(codexTerminalToken ? { [TERMINAL_TOKEN_ENV]: codexTerminalToken } : {}),
|
|
5809
5849
|
};
|
|
5810
5850
|
// Never one inherited from the launching shell: only this brain's own credential reaches its MCP child.
|
|
5811
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];
|
|
5812
5854
|
delete env.FORCE_COLOR;
|
|
5813
5855
|
delete env.CLICOLOR_FORCE;
|
|
5814
5856
|
const proc = spawn(shellCommand(codexBin, useShell, { isFile: existsSync }), args, {
|
|
@@ -8261,8 +8303,8 @@ function noteOpencodeServePort(port, delta) {
|
|
|
8261
8303
|
if (next > 0) _opencodeServePortCounts.set(p, next); else _opencodeServePortCounts.delete(p);
|
|
8262
8304
|
}
|
|
8263
8305
|
|
|
8264
|
-
function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocketSafe = false }) {
|
|
8265
|
-
nativeServeBoundary.track(proc, { port, safe: nativeWebSocketSafe });
|
|
8306
|
+
function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocketSafe = false, nativeServe = null }) {
|
|
8307
|
+
nativeServeBoundary.track(proc, { ...(nativeServe || {}), port, safe: nativeWebSocketSafe });
|
|
8266
8308
|
const pid = Number(proc?.pid) || null;
|
|
8267
8309
|
const exited = () => !proc || proc.exitCode != null || proc.signalCode != null;
|
|
8268
8310
|
if (!exited()) {
|
|
@@ -8430,7 +8472,9 @@ function broadcastToOpencodeV2Clients(data, { nativeRunId = null } = {}) {
|
|
|
8430
8472
|
nativeRootSessionId,
|
|
8431
8473
|
}
|
|
8432
8474
|
: data;
|
|
8433
|
-
|
|
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));
|
|
8434
8478
|
for (const ws of _ocpV2WsClients) {
|
|
8435
8479
|
if (nativeRun && !opencodeV2ClientOwnsRun(ws, nativeRun)) continue;
|
|
8436
8480
|
if (ws.readyState === 1) {
|
|
@@ -8563,6 +8607,7 @@ function killIsolatedServeProcess(proc) {
|
|
|
8563
8607
|
// bindings and its config folder, which has the same path.
|
|
8564
8608
|
function endIsolatedStart(termId, entry) {
|
|
8565
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).
|
|
8566
8611
|
try { entry.unsub?.(); } catch {}
|
|
8567
8612
|
try { entry.client?.stop(); } catch {}
|
|
8568
8613
|
killIsolatedServeProcess(entry.proc);
|
|
@@ -8643,7 +8688,7 @@ function buildOpencodeRuntimeConfigOverlay(xdgRoot, { unattended = false } = {})
|
|
|
8643
8688
|
return JSON.stringify(overlay);
|
|
8644
8689
|
}
|
|
8645
8690
|
|
|
8646
|
-
function setupOpencodeSidepanelConfig(termId, selection = null, { cwd = PACKAGE_ROOT, scopeExternal = true } = {}) {
|
|
8691
|
+
function setupOpencodeSidepanelConfig(termId, selection = null, { cwd = PACKAGE_ROOT, scopeExternal = true, terminalToken = false } = {}) {
|
|
8647
8692
|
const xdgRoot = resolve(DATA_HOME, 'data', 'sidepanel-configs', `opencode-${termId}`);
|
|
8648
8693
|
const targetDir = resolve(xdgRoot, 'opencode');
|
|
8649
8694
|
if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });
|
|
@@ -8663,8 +8708,11 @@ function setupOpencodeSidepanelConfig(termId, selection = null, { cwd = PACKAGE_
|
|
|
8663
8708
|
SYNABUN_TERMINAL_SESSION: termId,
|
|
8664
8709
|
SYNABUN_TOOLS: runtimeToolsValue(resolvedTools),
|
|
8665
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}}` } : {}),
|
|
8666
8714
|
},
|
|
8667
|
-
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])],
|
|
8668
8716
|
}));
|
|
8669
8717
|
ensureOpenCodeCoreMcpPermissions(baseCfg);
|
|
8670
8718
|
if (scopeExternal) applyOpenCodeExternalScope(xdgRoot, baseCfg, resolvedTools, cwd);
|
|
@@ -8688,7 +8736,7 @@ function updateOpencodeRuntimeToolsConfig(xdgRoot, selection) {
|
|
|
8688
8736
|
return true;
|
|
8689
8737
|
}
|
|
8690
8738
|
|
|
8691
|
-
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 } = {}) {
|
|
8692
8740
|
if (_ocpHistoryClearInProgress) throw new Error('OpenCode history is being cleared');
|
|
8693
8741
|
const requestedTools = toolsFromSelection(tools);
|
|
8694
8742
|
let entry = _ocpIsoServes.get(termId);
|
|
@@ -8711,10 +8759,10 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8711
8759
|
const refusal = await opencodeStartRefusal();
|
|
8712
8760
|
if (refusal) { console.warn(`[ocp-iso] serve ${termId.slice(-8)}: ${refusal.message}`); throw refusal; }
|
|
8713
8761
|
let xdgRoot;
|
|
8714
|
-
try { xdgRoot = requestedXdgRoot || setupOpencodeSidepanelConfig(termId, requestedTools, { cwd }); }
|
|
8762
|
+
try { xdgRoot = requestedXdgRoot || setupOpencodeSidepanelConfig(termId, requestedTools, { cwd, terminalToken: !!panelToken && !terminalToken && !brainCredential }); }
|
|
8715
8763
|
catch (err) { console.warn(`[ocp-iso] config setup failed: ${err.message}`); return null; }
|
|
8716
8764
|
// Registered before anything is waited for: a second start for the same term id waits for this one.
|
|
8717
|
-
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 };
|
|
8718
8766
|
_ocpIsoServes.set(termId, entry);
|
|
8719
8767
|
// What an earlier SynaBun left running goes first (its ports with it); then the port is picked.
|
|
8720
8768
|
await sweepLeftoverOpencodeServes();
|
|
@@ -8727,6 +8775,13 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8727
8775
|
if (port == null) { console.warn('[ocp-iso] no free port for isolated serve'); endIsolatedStart(termId, entry); return null; }
|
|
8728
8776
|
entry.port = port;
|
|
8729
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'; }
|
|
8730
8785
|
const isolatedEnv = {
|
|
8731
8786
|
...process.env,
|
|
8732
8787
|
XDG_CONFIG_HOME: xdgRoot,
|
|
@@ -8739,12 +8794,17 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8739
8794
|
// Keep this above the script's own deadlines while retaining a hard cap.
|
|
8740
8795
|
OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS:
|
|
8741
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 } : {}),
|
|
8742
8801
|
// A WhatsApp conversation's brain credential: the config names it ({env:SYNABUN_BRAIN_TOKEN}), only this
|
|
8743
8802
|
// serve's environment holds it (a fresh serve per brain launch: the brain stops its serve when it ends).
|
|
8744
8803
|
...(brainCredential ? { SYNABUN_BRAIN_TOKEN: brainCredential } : {}),
|
|
8745
8804
|
};
|
|
8746
8805
|
delete isolatedEnv.CLAUDECODE;
|
|
8747
8806
|
if (!brainCredential) delete isolatedEnv.SYNABUN_BRAIN_TOKEN;
|
|
8807
|
+
if (!serveToken) delete isolatedEnv[TERMINAL_TOKEN_ENV];
|
|
8748
8808
|
// A run's own settings for its serve (an evaluation run's, a protected worker's: lib/native-loop-providers.js
|
|
8749
8809
|
// openCodeRunEnvFor), last: a string is set, null removes the variable (an inherited OPENCODE_CONFIG_DIR, GIT_DIR).
|
|
8750
8810
|
if (extraEnv && typeof extraEnv === 'object') {
|
|
@@ -8788,7 +8848,7 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8788
8848
|
entry.proc = proc;
|
|
8789
8849
|
entry.password = launch.password || null;
|
|
8790
8850
|
// On record from its spawn: a crash of SynaBun from here on does not leave it running for good.
|
|
8791
|
-
const tracked = trackOpencodeServe(proc, { kind: 'isolated', id: termId, port, token, nativeWebSocketSafe: launch.nativeWebSocketSafe });
|
|
8851
|
+
const tracked = trackOpencodeServe(proc, { kind: 'isolated', id: termId, port, token, nativeWebSocketSafe: launch.nativeWebSocketSafe, nativeServe: launch.nativeServe });
|
|
8792
8852
|
// While it boots, its start sees an exit itself (another server on the port is a collision); afterwards
|
|
8793
8853
|
// its exit ends the serve.
|
|
8794
8854
|
let booting = true;
|
|
@@ -8908,6 +8968,8 @@ function stopIsolatedServe(termId, { preserveBindings = false } = {}) {
|
|
|
8908
8968
|
if (!entry) return;
|
|
8909
8969
|
cancelRuntimeMcpToolsRefresh(termId);
|
|
8910
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);
|
|
8911
8973
|
if (!preserveBindings) {
|
|
8912
8974
|
for (const sid of entry.sessions) {
|
|
8913
8975
|
if (_ocpSessionToServe.get(sid) === termId) _ocpSessionToServe.delete(sid);
|
|
@@ -8960,7 +9022,7 @@ async function turnClientForSession(sessionId, requestedTools = null) {
|
|
|
8960
9022
|
const session = await opencodeV2Client.session.get({ sessionID: sessionId });
|
|
8961
9023
|
const cwd = session?.data?.directory;
|
|
8962
9024
|
if (!cwd) throw new Error('OpenCode session directory is unavailable for MCP scope discovery');
|
|
8963
|
-
const entry = await ensureIsolatedServe(termId, { tools, cwd });
|
|
9025
|
+
const entry = await ensureIsolatedServe(termId, { tools, cwd, panelToken: true });
|
|
8964
9026
|
if (!entry || !entry.client) throw new Error('OpenCode isolated session runtime failed to start');
|
|
8965
9027
|
// Publish the binding only after the isolated serve is ready. Every waiter
|
|
8966
9028
|
// shares this promise, so one cold session can never fork two serves.
|
|
@@ -9027,14 +9089,14 @@ async function restartOpenCodeSessionTools(sessionId, selection) {
|
|
|
9027
9089
|
_ocpSessionTools.set(familySessionId, tools);
|
|
9028
9090
|
}
|
|
9029
9091
|
let entry, startError;
|
|
9030
|
-
try { entry = await ensureIsolatedServe(termId, { tools, cwd }); }
|
|
9092
|
+
try { entry = await ensureIsolatedServe(termId, { tools, cwd, panelToken: true }); }
|
|
9031
9093
|
catch (error) { startError = error; }
|
|
9032
9094
|
if (!entry?.client) {
|
|
9033
9095
|
for (const familySessionId of familySessionIds) {
|
|
9034
9096
|
_ocpSessionToServe.set(familySessionId, termId);
|
|
9035
9097
|
_ocpSessionTools.set(familySessionId, previousTools);
|
|
9036
9098
|
}
|
|
9037
|
-
try { entry = await ensureIsolatedServe(termId, { tools: previousTools, cwd }); }
|
|
9099
|
+
try { entry = await ensureIsolatedServe(termId, { tools: previousTools, cwd, panelToken: true }); }
|
|
9038
9100
|
catch { entry = null; }
|
|
9039
9101
|
if (entry?.client) {
|
|
9040
9102
|
for (const familySessionId of familySessionIds) entry.sessions.add(familySessionId);
|
|
@@ -9147,7 +9209,8 @@ function handleOpencodeV2Ws(ws) {
|
|
|
9147
9209
|
|
|
9148
9210
|
const send = (data) => {
|
|
9149
9211
|
if (ws.readyState === 1) {
|
|
9150
|
-
|
|
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 {}
|
|
9151
9214
|
}
|
|
9152
9215
|
};
|
|
9153
9216
|
// Request bodies that live in lib/opencode-v2-ws-requests.js get these.
|
|
@@ -9658,7 +9721,7 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
|
|
|
9658
9721
|
});
|
|
9659
9722
|
_ocpProc = proc;
|
|
9660
9723
|
// On record from its spawn: a crash of SynaBun from here on does not leave it running for good.
|
|
9661
|
-
tracked = trackOpencodeServe(proc, { kind: 'shared', id: 'shared', port: _ocpPort, token, nativeWebSocketSafe: launch.nativeWebSocketSafe });
|
|
9724
|
+
tracked = trackOpencodeServe(proc, { kind: 'shared', id: 'shared', port: _ocpPort, token, nativeWebSocketSafe: launch.nativeWebSocketSafe, nativeServe: launch.nativeServe });
|
|
9662
9725
|
const readPassword = servePasswordReader();
|
|
9663
9726
|
const outLog = createServeLogRedactor(line => console.log(`[opencode:stdout] ${line.trim()}`));
|
|
9664
9727
|
const errLog = createServeLogRedactor(line => console.log(`[opencode:stderr] ${line.trim()}`));
|
|
@@ -10795,6 +10858,9 @@ const _claudeBridgeReady = (async () => {
|
|
|
10795
10858
|
// Per-chat-session SynaBun MCP entry (HTTP + X-Synabun-Terminal header)
|
|
10796
10859
|
// so each sidepanel session gets its own browser tab.
|
|
10797
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,
|
|
10798
10864
|
// In-process release of a sidepanel session's owned tab on destroy.
|
|
10799
10865
|
releaseBrowserOwner: (ownerKey) => {
|
|
10800
10866
|
if (!ownerKey) return;
|
|
@@ -14522,6 +14588,8 @@ app.post('/api/sidepanel-runs/:runId/release', (req, res) => {
|
|
|
14522
14588
|
// POST /api/loop/launch — create loop state + provider runtime atomically
|
|
14523
14589
|
app.post('/api/loop/launch', async (req, res) => {
|
|
14524
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;
|
|
14525
14593
|
try {
|
|
14526
14594
|
const { task: rawTask, context, iterations, maxMinutes, usesBrowser, cwd, profile, model: requestedModel, contextMode: requestedContextMode, effort, tools, platform, codexAccountId, browserSessionId: requestedBrowserSessionId, sidepanelWindowId, sidepanelClaimToken } = req.body;
|
|
14527
14595
|
if (!rawTask?.trim()) return res.status(400).json({ error: 'task is required' });
|
|
@@ -14602,6 +14670,9 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14602
14670
|
let browserTabId = null;
|
|
14603
14671
|
const terminalSessionId = randomBytes(16).toString('hex');
|
|
14604
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;
|
|
14605
14676
|
if (usesBrowser) {
|
|
14606
14677
|
// Serialized reuse-or-create of the shared loop browser + a dedicated tab.
|
|
14607
14678
|
// The mutex inside acquireLoopBrowserAndTab() prevents concurrent launches
|
|
@@ -14609,7 +14680,7 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14609
14680
|
const acq = await acquireLoopBrowserAndTab({ requestedBrowserSessionId, terminalSessionId });
|
|
14610
14681
|
if (acq.error) {
|
|
14611
14682
|
loopLog(terminalSessionId, 'launch:browser', 'ABORT: browser acquisition failed — returning 500', { error: acq.error });
|
|
14612
|
-
return res.status(500).json({ error: acq.error });
|
|
14683
|
+
return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
|
|
14613
14684
|
}
|
|
14614
14685
|
browserSessionId = acq.browserSessionId;
|
|
14615
14686
|
browserTabId = acq.browserTabId;
|
|
@@ -14663,6 +14734,10 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14663
14734
|
// SYNABUN_TERMINAL_SESSION lets hooks correlate with the correct loop file
|
|
14664
14735
|
// after /clear changes the Claude session ID. This is the key to multi-loop isolation.
|
|
14665
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;
|
|
14666
14741
|
if (browserSessionId) loopExtraEnv.SYNABUN_BROWSER_SESSION = browserSessionId;
|
|
14667
14742
|
if (browserTabId) loopExtraEnv.SYNABUN_BROWSER_TAB = browserTabId;
|
|
14668
14743
|
// Codex reads auth.json from CODEX_HOME — pin the selected ChatGPT account.
|
|
@@ -14691,7 +14766,7 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14691
14766
|
browserSessionId,
|
|
14692
14767
|
browserTabId,
|
|
14693
14768
|
cliTools,
|
|
14694
|
-
model, {}, { cwd: loopCwd },
|
|
14769
|
+
model, {}, { cwd: loopCwd, terminalToken: !!loopTerminalToken },
|
|
14695
14770
|
);
|
|
14696
14771
|
if (xdgRoot) {
|
|
14697
14772
|
loopExtraEnv.XDG_CONFIG_HOME = xdgRoot;
|
|
@@ -14778,8 +14853,9 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14778
14853
|
}
|
|
14779
14854
|
|
|
14780
14855
|
// Browser ownership is now held by the successfully launched PTY; normal
|
|
14781
|
-
// 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).
|
|
14782
14857
|
pendingNativeBrowserCleanup = null;
|
|
14858
|
+
issuedLoopTerminal = null;
|
|
14783
14859
|
broadcastSync({ type: 'terminal:session-created', sessionId: terminalSessionId, profile: cliProfile });
|
|
14784
14860
|
|
|
14785
14861
|
const responsePayload = {
|
|
@@ -14803,6 +14879,8 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14803
14879
|
pendingNativeBrowserCleanup.ownerKey,
|
|
14804
14880
|
).catch(() => {});
|
|
14805
14881
|
}
|
|
14882
|
+
// The loop never ran: nothing may act as it.
|
|
14883
|
+
if (issuedLoopTerminal) _terminalTokens.revoke(issuedLoopTerminal);
|
|
14806
14884
|
loopLog(null, 'launch:error', 'POST /api/loop/launch threw', { err: err.message, stack: err.stack?.slice(0, 800) });
|
|
14807
14885
|
res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
|
|
14808
14886
|
}
|
|
@@ -14810,9 +14888,24 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14810
14888
|
|
|
14811
14889
|
// POST /api/loop/stop — force-stop loops and clean up PTY sessions
|
|
14812
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.
|
|
14813
14897
|
app.post('/api/loop/stop', async (req, res) => {
|
|
14814
14898
|
try {
|
|
14815
|
-
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;
|
|
14816
14909
|
let directlyStopped = false;
|
|
14817
14910
|
if (targetTerminalId && _nativeLoopRuntime?.isAlive(targetTerminalId)) {
|
|
14818
14911
|
directlyStopped = await _nativeLoopRuntime.stop(targetTerminalId, 'user');
|
|
@@ -14870,6 +14963,9 @@ app.post('/api/loop/stop', async (req, res) => {
|
|
|
14870
14963
|
}
|
|
14871
14964
|
}
|
|
14872
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);
|
|
14873
14969
|
// Per-CLI per-loop config dir cleanup (opencode XDG_CONFIG_HOME, etc.)
|
|
14874
14970
|
if (data.profile === 'opencode' && data.terminalSessionId) {
|
|
14875
14971
|
cleanupOpencodeLoopConfig(data.terminalSessionId);
|
|
@@ -14923,38 +15019,100 @@ app.post('/api/loop/resolve-from-ancestors', (req, res) => {
|
|
|
14923
15019
|
}
|
|
14924
15020
|
});
|
|
14925
15021
|
|
|
14926
|
-
// 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.
|
|
14927
15023
|
// When a loop's pinned browser session has died, the MCP server calls this to
|
|
14928
15024
|
// rejoin the SHARED loop browser with a FRESH, owned tab — instead of spawning
|
|
14929
15025
|
// an isolated new browser and reusing a now-invalid tabId (which 404s on every
|
|
14930
|
-
// subsequent call). If terminalSessionId is known, the
|
|
14931
|
-
//
|
|
14932
|
-
//
|
|
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).
|
|
14933
15047
|
app.post('/api/loop/recover-browser', async (req, res) => {
|
|
14934
15048
|
try {
|
|
14935
|
-
const
|
|
14936
|
-
const
|
|
14937
|
-
if (
|
|
14938
|
-
return res.status(
|
|
14939
|
-
}
|
|
14940
|
-
//
|
|
14941
|
-
// so
|
|
14942
|
-
|
|
14943
|
-
|
|
14944
|
-
|
|
14945
|
-
|
|
14946
|
-
|
|
14947
|
-
|
|
14948
|
-
|
|
14949
|
-
|
|
14950
|
-
|
|
14951
|
-
|
|
14952
|
-
|
|
14953
|
-
|
|
14954
|
-
|
|
14955
|
-
|
|
14956
|
-
|
|
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 }) });
|
|
14957
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 } : {}) });
|
|
14958
15116
|
res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
|
|
14959
15117
|
}
|
|
14960
15118
|
});
|
|
@@ -15405,6 +15563,8 @@ async function launchScheduledLoop(schedule) {
|
|
|
15405
15563
|
let scheduledLaunchTerminalId = null;
|
|
15406
15564
|
let scheduledLaunchPendingId = null;
|
|
15407
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;
|
|
15408
15568
|
try {
|
|
15409
15569
|
if (!existsSync(LOOP_DIR)) mkdirSync(LOOP_DIR, { recursive: true });
|
|
15410
15570
|
|
|
@@ -15467,11 +15627,16 @@ async function launchScheduledLoop(schedule) {
|
|
|
15467
15627
|
// (e.g., a sidepanel plan session and a scheduled CLI loop in the same cwd).
|
|
15468
15628
|
const terminalSessionId = randomBytes(16).toString('hex');
|
|
15469
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;
|
|
15470
15633
|
|
|
15471
15634
|
// Reuse the shared browser session and create a fresh tab for this scheduled loop.
|
|
15472
15635
|
let scheduledBrowserSessionId = null;
|
|
15473
15636
|
let scheduledBrowserTabId = null;
|
|
15474
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;
|
|
15475
15640
|
schedExtraEnv.SYNABUN_TOOLS = runtimeToolsValue(cliTools);
|
|
15476
15641
|
// Codex reads auth.json from CODEX_HOME — pin the schedule's selected ChatGPT account.
|
|
15477
15642
|
if (cliProfile === 'codex') {
|
|
@@ -15502,7 +15667,7 @@ async function launchScheduledLoop(schedule) {
|
|
|
15502
15667
|
scheduledBrowserSessionId,
|
|
15503
15668
|
scheduledBrowserTabId,
|
|
15504
15669
|
cliTools,
|
|
15505
|
-
cliModel, {}, { cwd: PACKAGE_ROOT },
|
|
15670
|
+
cliModel, {}, { cwd: PACKAGE_ROOT, terminalToken: !!schedTerminalToken },
|
|
15506
15671
|
);
|
|
15507
15672
|
if (xdgRoot) {
|
|
15508
15673
|
schedExtraEnv.XDG_CONFIG_HOME = xdgRoot;
|
|
@@ -15722,11 +15887,12 @@ async function launchScheduledLoop(schedule) {
|
|
|
15722
15887
|
attachExecLoopDriver(terminalSessionId);
|
|
15723
15888
|
}
|
|
15724
15889
|
// Browser ownership is now held by the successfully launched runtime/PTY;
|
|
15725
|
-
// 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).
|
|
15726
15891
|
pendingNativeBrowserCleanup = null;
|
|
15727
15892
|
scheduledLaunchTerminalId = null;
|
|
15728
15893
|
scheduledLaunchPendingId = null;
|
|
15729
15894
|
scheduledLaunchProfile = null;
|
|
15895
|
+
issuedSchedTerminal = null;
|
|
15730
15896
|
if (!nativeRuntime) {
|
|
15731
15897
|
broadcastSync({ type: 'terminal:session-created', sessionId: terminalSessionId, profile: cliProfile });
|
|
15732
15898
|
}
|
|
@@ -15747,6 +15913,8 @@ async function launchScheduledLoop(schedule) {
|
|
|
15747
15913
|
console.log(`[schedule] Launched loop for "${schedule.name}" → ${nativeRuntime ? 'sidepanel run' : 'terminal'} ${terminalSessionId} (${cliProfile}/${cliModel || 'default'}/${cliEffort || 'off'}${'/tools:' + serializeToolList(cliTools)})`);
|
|
15748
15914
|
} catch (err) {
|
|
15749
15915
|
if (registeredScheduledRunId) _runningScheduledLoops.delete(registeredScheduledRunId);
|
|
15916
|
+
// The loop never ran: nothing may act as it.
|
|
15917
|
+
if (issuedSchedTerminal) _terminalTokens.revoke(issuedSchedTerminal);
|
|
15750
15918
|
if (scheduledLaunchTerminalId) {
|
|
15751
15919
|
const terminal = terminalSessions.get(scheduledLaunchTerminalId);
|
|
15752
15920
|
if (terminal) {
|
|
@@ -16911,6 +17079,9 @@ function buildAgentMcpConfig(withSynabun, browserSessionId, browserTabId, termin
|
|
|
16911
17079
|
// matches this agent's _tabOwners key on the server (tab-less calls route to the
|
|
16912
17080
|
// agent's own dedicated tab instead of the shared activeTab).
|
|
16913
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}}`;
|
|
16914
17085
|
// Agents run with --strict-mcp-config, so they see only what this file lists.
|
|
16915
17086
|
// External servers come from the captured list and owner switches; SynaBun is added last
|
|
16916
17087
|
// so its per-agent pins always win over a same-named registry entry.
|
|
@@ -16934,7 +17105,12 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
|
|
|
16934
17105
|
const sessionId = agent._activeSessionId || agent.sessionId;
|
|
16935
17106
|
|
|
16936
17107
|
const serverMap = JSON.parse(agent._mcpConfig).mcpServers;
|
|
16937
|
-
|
|
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] : [])];
|
|
16938
17114
|
const mcpConfigPath = writePrivateMcpConfig(resolve(DATA_HOME, 'data', 'agents', agent.id, 'mcp.json'), serverMap);
|
|
16939
17115
|
const args = [
|
|
16940
17116
|
'--print',
|
|
@@ -16967,8 +17143,11 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
|
|
|
16967
17143
|
const cleanEnv = Object.fromEntries(
|
|
16968
17144
|
Object.entries(process.env).filter(([k]) =>
|
|
16969
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
|
|
16970
17148
|
)
|
|
16971
17149
|
);
|
|
17150
|
+
if (terminalToken) cleanEnv[TERMINAL_TOKEN_ENV] = terminalToken;
|
|
16972
17151
|
|
|
16973
17152
|
console.log(`[agent] ${agent.id} spawn: ${claudeBin} ${args.map(a => a.length > 80 ? a.slice(0, 80) + '…' : a).join(' ')}`);
|
|
16974
17153
|
|
|
@@ -17074,7 +17253,12 @@ async function launchAgentController(opts) {
|
|
|
17074
17253
|
const agentId = providedAgentId || randomUUID();
|
|
17075
17254
|
const agentTerminalId = `agent:${agentId}`;
|
|
17076
17255
|
const agentTools = requireToolList(resolveToolList(opts.tools ?? [], { source: 'runtime' })).items;
|
|
17077
|
-
|
|
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; }
|
|
17078
17262
|
const agentCwd = cwd || PACKAGE_ROOT;
|
|
17079
17263
|
|
|
17080
17264
|
// Build default system prompt for agents — overrides the boot sequence in the agent's instructions
|
|
@@ -17196,13 +17380,9 @@ async function launchAgentController(opts) {
|
|
|
17196
17380
|
// share it under the persistent profile) then acquire a fresh dedicated tab.
|
|
17197
17381
|
// This keeps the "fresh per iteration" intent without nuking co-owners' tabs.
|
|
17198
17382
|
if (agent._usesBrowser && i > 1) {
|
|
17199
|
-
|
|
17200
|
-
|
|
17201
|
-
|
|
17202
|
-
);
|
|
17203
|
-
agent.browserSessionId = null;
|
|
17204
|
-
agent.browserTabId = null;
|
|
17205
|
-
}
|
|
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}`));
|
|
17206
17386
|
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
17207
17387
|
const acq = await acquireSharedBrowserTab({ ownerKey: agent._agentTerminalId, ownerType: 'interactive', logTag: 'agent:browser' });
|
|
17208
17388
|
if (!acq.error) {
|
|
@@ -17347,13 +17527,10 @@ async function launchAgentController(opts) {
|
|
|
17347
17527
|
// Clean up the agent's tab when the loop ends — release just this agent's tab and
|
|
17348
17528
|
// clear its ownership markers. The shared browser is left for co-owners (the grace
|
|
17349
17529
|
// timer reaps it once no loop/interactive/agent owner remains).
|
|
17350
|
-
|
|
17351
|
-
|
|
17352
|
-
|
|
17353
|
-
|
|
17354
|
-
agent.browserSessionId = null;
|
|
17355
|
-
agent.browserTabId = null;
|
|
17356
|
-
}
|
|
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);
|
|
17357
17534
|
|
|
17358
17535
|
agent.endedAt = new Date().toISOString();
|
|
17359
17536
|
agent.exitCode = agent._stopped ? null : 0;
|
|
@@ -17369,13 +17546,9 @@ async function launchAgentController(opts) {
|
|
|
17369
17546
|
const message = err?.message || String(err);
|
|
17370
17547
|
console.error(`[agent] ${agentId} failed in iteration ${agent.currentIteration}/${iterations}: ${message}`);
|
|
17371
17548
|
try {
|
|
17372
|
-
if (agent._usesBrowser
|
|
17373
|
-
browserSessions.get(agent.browserSessionId)?._agentOwnedSet?.delete(agentId);
|
|
17374
|
-
await releaseSharedBrowserTab(agent.browserSessionId, agent._agentTerminalId).catch(() => {});
|
|
17375
|
-
agent.browserSessionId = null;
|
|
17376
|
-
agent.browserTabId = null;
|
|
17377
|
-
}
|
|
17549
|
+
if (agent._usesBrowser) await releaseAgentBrowser(agent, { ended: true }).catch(() => {});
|
|
17378
17550
|
} catch {}
|
|
17551
|
+
_terminalTokens.revoke(agent._agentTerminalId);
|
|
17379
17552
|
agent.error = message;
|
|
17380
17553
|
agent.endedAt = new Date().toISOString();
|
|
17381
17554
|
agent.exitCode = -1;
|
|
@@ -17415,7 +17588,7 @@ app.post('/api/agents/launch', async (req, res) => {
|
|
|
17415
17588
|
const acq = await acquireSharedBrowserTab({ ownerKey: `agent:${agentId}`, ownerType: 'interactive', logTag: 'agent:browser' });
|
|
17416
17589
|
if (acq.error) {
|
|
17417
17590
|
console.warn(`[agent] Browser tab acquire failed: ${acq.error}`);
|
|
17418
|
-
return res.status(500).json({ error: `Could not start browser session for this automation: ${acq.error}
|
|
17591
|
+
return res.status(500).json({ error: `Could not start browser session for this automation: ${acq.error}`, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
|
|
17419
17592
|
}
|
|
17420
17593
|
browserSessionId = acq.browserSessionId;
|
|
17421
17594
|
browserTabId = acq.browserTabId;
|
|
@@ -18668,7 +18841,7 @@ const editorCompletionServe = createOpencodeCompletionEngine({
|
|
|
18668
18841
|
const token = opencodeServeRecords.newToken();
|
|
18669
18842
|
const launch = opencodeServeLaunch(port, { env: { ...env, [SERVE_TOKEN_ENV]: token }, passwordFrom: 'stdout' });
|
|
18670
18843
|
const proc = spawn(launch.command, launch.args, { stdio: ['ignore', 'pipe', 'pipe'], ...launch.options, cwd, detached: false, shell: false, windowsHide: true });
|
|
18671
|
-
editorCompletionServeTracks.set(proc, trackOpencodeServe(proc, { kind: 'completion', id: 'editor-complete', port, token, nativeWebSocketSafe: launch.nativeWebSocketSafe }));
|
|
18844
|
+
editorCompletionServeTracks.set(proc, trackOpencodeServe(proc, { kind: 'completion', id: 'editor-complete', port, token, nativeWebSocketSafe: launch.nativeWebSocketSafe, nativeServe: launch.nativeServe }));
|
|
18672
18845
|
const outLog = createServeLogRedactor(line => console.log(`[editor-complete:out] ${line.trim().slice(0, 500)}`));
|
|
18673
18846
|
const errLog = createServeLogRedactor(line => console.log(`[editor-complete:err] ${line.trim().slice(0, 500)}`));
|
|
18674
18847
|
proc.stdout?.on('data', d => outLog.push(d));
|
|
@@ -19243,6 +19416,51 @@ app.post('/api/discord/test', async (req, res) => {
|
|
|
19243
19416
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
19244
19417
|
function _moreLoginOpts() { return { savedCfg: loadBrowserConfig() }; }
|
|
19245
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
|
+
|
|
19246
19464
|
// GET /api/morelogin/status — install + running + port + default-profile state
|
|
19247
19465
|
app.get('/api/morelogin/status', async (req, res) => {
|
|
19248
19466
|
try {
|
|
@@ -19331,7 +19549,18 @@ app.post('/api/morelogin/start', async (req, res) => {
|
|
|
19331
19549
|
const envId = req.body && req.body.envId;
|
|
19332
19550
|
if (!envId) return res.status(400).json({ ok: false, error: 'envId is required' });
|
|
19333
19551
|
const out = await moreLogin.startProfile(envId, _moreLoginOpts());
|
|
19334
|
-
|
|
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) });
|
|
19335
19564
|
} catch (err) {
|
|
19336
19565
|
res.status(500).json({ ok: false, error: err.message });
|
|
19337
19566
|
}
|
|
@@ -19342,7 +19571,27 @@ app.post('/api/morelogin/stop', async (req, res) => {
|
|
|
19342
19571
|
try {
|
|
19343
19572
|
const envId = req.body && req.body.envId;
|
|
19344
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
|
+
}
|
|
19345
19593
|
await moreLogin.stopProfile(envId, _moreLoginOpts());
|
|
19594
|
+
_moreLoginStartedBy.delete(String(envId));
|
|
19346
19595
|
res.json({ ok: true });
|
|
19347
19596
|
} catch (err) {
|
|
19348
19597
|
res.status(500).json({ ok: false, error: err.message });
|
|
@@ -19351,8 +19600,20 @@ app.post('/api/morelogin/stop', async (req, res) => {
|
|
|
19351
19600
|
|
|
19352
19601
|
// POST /api/morelogin/use-default — make a MoreLogin profile the default AI browser
|
|
19353
19602
|
// { envId } to set, or { clear: true } to revert to the normal mirror browser.
|
|
19354
|
-
app.post('/api/morelogin/use-default', (req, res) => {
|
|
19355
|
-
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
|
+
}
|
|
19356
19617
|
const cfg = loadBrowserConfig();
|
|
19357
19618
|
if (req.body && req.body.clear) {
|
|
19358
19619
|
cfg.connectMode = 'mirror';
|
|
@@ -22890,6 +23151,8 @@ registerSkillsV2Routes(app, {
|
|
|
22890
23151
|
assistantOf: (req) => skillsAssistantOf(req),
|
|
22891
23152
|
// The owner's writes carry the page secret (lib/page-session.js); the Studio's reads hand it to the page.
|
|
22892
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 }; },
|
|
22893
23156
|
});
|
|
22894
23157
|
|
|
22895
23158
|
// ── AI skill creation (docs/skills-studio.md → AI creation (P3)) ──
|
|
@@ -23026,12 +23289,16 @@ function skillsAssistantOf(req) {
|
|
|
23026
23289
|
/**
|
|
23027
23290
|
* Who an agent's request to the creation routes is: an Assistant brain, by the credential its launch was given
|
|
23028
23291
|
* (resolved to its session by the runtime; X-Synabun-Role and X-Synabun-Terminal prove nothing, any local process can
|
|
23029
|
-
* 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.
|
|
23030
23295
|
*/
|
|
23031
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 };
|
|
23032
23299
|
const sessionId = skillsAssistantOf(req);
|
|
23033
23300
|
if (sessionId) return { kind: 'assistant', assistantSessionId: sessionId };
|
|
23034
|
-
const pin = String(
|
|
23301
|
+
const pin = String(who.id || '').trim();
|
|
23035
23302
|
if (pin && _assistantDispatcher?.peek?.(pin)) return { kind: 'worker' };
|
|
23036
23303
|
return null;
|
|
23037
23304
|
}
|
|
@@ -25118,6 +25385,10 @@ app.get('/api/health', (req, res) => {
|
|
|
25118
25385
|
// page showing the restart tells this one from the one that replaces it.
|
|
25119
25386
|
bootId: SERVER_BOOT_ID,
|
|
25120
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(),
|
|
25121
25392
|
});
|
|
25122
25393
|
} catch (err) {
|
|
25123
25394
|
res.json({ ok: false, reason: 'db_error', detail: err.message });
|
|
@@ -25195,21 +25466,31 @@ function redactOpenCodeMcpOutput(text, xdgRoot, env, captured = null) {
|
|
|
25195
25466
|
function externalInventory(provider, cwd = PACKAGE_ROOT, options = {}) {
|
|
25196
25467
|
return { ...externalServerInventory({ provider, cwd, dataHome: DATA_HOME, registry: readMcpRegistry(), ...(provider === 'opencode' ? { opencodeConfig: readOpencodeGlobalConfig().config } : {}), ...options }), catalog: () => externalToolsCatalog(cwd) };
|
|
25197
25468
|
}
|
|
25198
|
-
|
|
25199
|
-
|
|
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();
|
|
25200
25474
|
const roots = cwd ? [cwd] : [PACKAGE_ROOT, ...loadHookProjects().map(project => project.path).filter(Boolean)];
|
|
25201
|
-
for (const directory of new Set(roots))
|
|
25202
|
-
const
|
|
25203
|
-
if (!
|
|
25204
|
-
|
|
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
|
+
}
|
|
25205
25483
|
}
|
|
25206
|
-
|
|
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()] };
|
|
25207
25487
|
}
|
|
25488
|
+
function externalToolsCatalog(cwd = null) { return externalToolsCatalogReport(cwd).servers; }
|
|
25208
25489
|
|
|
25209
25490
|
function applyOpenCodeExternalScope(xdgRoot, config, tools, cwd, { readProject = true } = {}) {
|
|
25210
25491
|
const scoped = scopeOpenCodeServers(config, tools, externalInventory('opencode', cwd || PACKAGE_ROOT, { readProject }));
|
|
25211
25492
|
Object.assign(config, scoped.config);
|
|
25212
|
-
_externalMcpLogValues.set(xdgRoot,
|
|
25493
|
+
_externalMcpLogValues.set(xdgRoot, mcpSecretValues(scoped.config.mcp.servers));
|
|
25213
25494
|
writeFileSync(resolve(xdgRoot, 'synabun-external-scope.json'), JSON.stringify(scoped.scope), { mode: 0o600 });
|
|
25214
25495
|
return scoped.scope;
|
|
25215
25496
|
}
|
|
@@ -25225,7 +25506,12 @@ function toolsFromSelection(value) {
|
|
|
25225
25506
|
return launchToolList(Array.isArray(value) ? { tools: value } : { mcpProfile: value }).items;
|
|
25226
25507
|
}
|
|
25227
25508
|
app.get('/api/mcp/tools', (req, res) => {
|
|
25228
|
-
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
|
+
}
|
|
25229
25515
|
catch (err) { res.status(err.status || 500).json({ ok: false, code: err.code, problems: err.problems, error: err.message }); }
|
|
25230
25516
|
});
|
|
25231
25517
|
// Read-time conversion for a saved page preference. This never launches a runtime or writes a default.
|
|
@@ -25239,23 +25525,40 @@ app.put('/api/mcp/tools/default', (req, res) => {
|
|
|
25239
25525
|
try {
|
|
25240
25526
|
const requested = storedToolList({ tools: req.body?.tools });
|
|
25241
25527
|
if (requested === null) throw Object.assign(new Error('tools must be an array'), { code: 'TOOLS_INVALID', status: 400 });
|
|
25242
|
-
|
|
25243
|
-
|
|
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
|
+
}
|
|
25244
25538
|
const tools = writeDefaultTools(DATA_HOME, requested);
|
|
25245
25539
|
broadcastSync({ type: 'mcp:tools-default-changed', tools, source: 'api' });
|
|
25246
|
-
res.json({ ok: true, tools, defaultTools: tools });
|
|
25247
|
-
} 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 } : {}) }); }
|
|
25248
25542
|
});
|
|
25249
25543
|
|
|
25250
25544
|
// An MCP child can change its own enabled tools through the always-on tool_groups
|
|
25251
25545
|
// tool. Reconcile only the runtime named by its launch identity header; never
|
|
25252
25546
|
// accept a sidepanel session/run id from the body and never touch the shared
|
|
25253
|
-
// 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).
|
|
25254
25551
|
function applyRuntimeTools(req, res) {
|
|
25255
|
-
const
|
|
25256
|
-
if (!
|
|
25552
|
+
const asserted = String(req.get('X-Synabun-Terminal') || '').trim();
|
|
25553
|
+
if (!asserted) {
|
|
25257
25554
|
return res.status(400).json({ ok: false, error: 'Missing X-Synabun-Terminal runtime identity' });
|
|
25258
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;
|
|
25259
25562
|
let tools;
|
|
25260
25563
|
try {
|
|
25261
25564
|
if (!Array.isArray(req.body?.tools)) throw Object.assign(new Error('tools must be an array'), { status: 400, code: 'TOOLS_INVALID' });
|
|
@@ -26335,7 +26638,11 @@ try {
|
|
|
26335
26638
|
console.error(' MCP HTTP eager init failed:', err.message);
|
|
26336
26639
|
});
|
|
26337
26640
|
|
|
26338
|
-
|
|
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 });
|
|
26339
26646
|
|
|
26340
26647
|
// Keyed path: /mcp/<key> — validates key, then forwards to MCP router
|
|
26341
26648
|
app.use('/mcp/:key', (req, res, next) => {
|
|
@@ -26358,7 +26665,8 @@ try {
|
|
|
26358
26665
|
// guard) and dispatch is never blocked. macOS only; elsewhere nothing uses it.
|
|
26359
26666
|
if (sandboxSupported() && sandboxExecAvailable()) {
|
|
26360
26667
|
try {
|
|
26361
|
-
|
|
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 });
|
|
26362
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; });
|
|
26363
26671
|
} catch (error) {
|
|
26364
26672
|
console.warn(' worker-only MCP channel unavailable:', error?.message || error);
|
|
@@ -26698,6 +27006,8 @@ function createTerminalSession(profile, cols, rows, cwd, opts = {}) {
|
|
|
26698
27006
|
// data/loop-configs until they piled into multi-GB. Clean it here too.
|
|
26699
27007
|
cleanupOpencodeLoopConfig(sessionId);
|
|
26700
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(() => {});
|
|
26701
27011
|
}
|
|
26702
27012
|
|
|
26703
27013
|
// Clean up loop driver interval
|
|
@@ -26734,6 +27044,9 @@ function createTerminalSession(profile, cols, rows, cwd, opts = {}) {
|
|
|
26734
27044
|
name: 'xterm-256color',
|
|
26735
27045
|
tap: isLoopOwned,
|
|
26736
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],
|
|
26737
27050
|
profile,
|
|
26738
27051
|
}, {
|
|
26739
27052
|
onSpawned: ({ pid }) => {
|
|
@@ -27224,6 +27537,9 @@ function buildLoopTaskPrompt(loopState, iteration = null) {
|
|
|
27224
27537
|
? `Pass sessionId: "${loopState.browserSessionId}"${loopState.browserTabId ? ` and tabId: "${loopState.browserTabId}"` : ''} to EVERY browser tool call. Omitting them can hijack another loop's browser.`
|
|
27225
27538
|
: 'Use the SynaBun browser tools only. Do not use external browser/search tools for visual browsing.',
|
|
27226
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.',
|
|
27227
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.',
|
|
27228
27544
|
'=== END BROWSER ENFORCEMENT ===',
|
|
27229
27545
|
'',
|
|
@@ -27248,9 +27564,12 @@ function buildLoopTaskPrompt(loopState, iteration = null) {
|
|
|
27248
27564
|
`NATIVE LOOP ITERATION: ${iteration}/${loopState.totalIterations || 1}`,
|
|
27249
27565
|
'Continue the same native conversation and make concrete progress on the task.',
|
|
27250
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.',
|
|
27251
27568
|
'',
|
|
27252
27569
|
].join('\n') : '';
|
|
27253
|
-
|
|
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}`;
|
|
27254
27573
|
return loopState.context ? `${wrappedTask}\n\nCONTEXT:\n${loopState.context}` : wrappedTask;
|
|
27255
27574
|
}
|
|
27256
27575
|
|
|
@@ -27356,6 +27675,8 @@ async function releaseNativeLoopResources(run) {
|
|
|
27356
27675
|
await closeSessionTab(session, run.browserSessionId, run.browserTabId).catch(() => {});
|
|
27357
27676
|
}
|
|
27358
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);
|
|
27359
27680
|
reconcileKeepAwake();
|
|
27360
27681
|
}
|
|
27361
27682
|
|
|
@@ -27364,6 +27685,9 @@ const openCodeWorkerActivity = createOpenCodeActivityRelay({ send: (message) =>
|
|
|
27364
27685
|
|
|
27365
27686
|
_nativeLoopRuntime = new NativeLoopRuntime({
|
|
27366
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,
|
|
27367
27691
|
stateDir: LOOP_DIR,
|
|
27368
27692
|
ledgerPath: resolve(LOOP_DATA_DIR, 'native-loop-runs.json'),
|
|
27369
27693
|
buildPrompt: (state, iteration) => buildLoopTaskPrompt(state, iteration),
|
|
@@ -27522,6 +27846,11 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
27522
27846
|
},
|
|
27523
27847
|
} : null;
|
|
27524
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;
|
|
27525
27854
|
const xdgRoot = setupOpencodeLoopConfig(
|
|
27526
27855
|
state.runId,
|
|
27527
27856
|
state.browserSessionId,
|
|
@@ -27535,7 +27864,7 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
27535
27864
|
// Assistant task runs: the browser policy plugin (loops and schedules unchanged) with the registered code
|
|
27536
27865
|
// projects its test runners may run in (the sandboxed serve cannot read the registry), and the run's confinement
|
|
27537
27866
|
// (lib/worker-confinement.js, lib/skills/draft-confinement.js): its permission rules, tool switches, MCP.
|
|
27538
|
-
{ 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 },
|
|
27539
27868
|
);
|
|
27540
27869
|
// An evaluation trial with the skill: its copy goes into this run's own configuration folder, which OpenCode reads
|
|
27541
27870
|
// as its global one (never OPENCODE_CONFIG_DIR, which would take the place of this configuration).
|
|
@@ -27553,6 +27882,7 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
27553
27882
|
...(evalEnv || evalShell ? { extraEnv: { ...(evalEnv || {}), ...(evalShell ? evalShell.env : {}) } } : {}),
|
|
27554
27883
|
hidePassword: protectedWorker,
|
|
27555
27884
|
persistentData: !!state.persistentOpenCode,
|
|
27885
|
+
terminalToken: runTerminalToken,
|
|
27556
27886
|
});
|
|
27557
27887
|
if (!entry?.client) throw new Error('OpenCode isolated native serve failed to start');
|
|
27558
27888
|
let providerSessionId = null;
|
|
@@ -27721,14 +28051,21 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
27721
28051
|
// Model catalog (tier · price · vision) for routing, the persona and agent_catalog.
|
|
27722
28052
|
const assistantCatalog = createAssistantCatalog({
|
|
27723
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.
|
|
27724
28056
|
getExternalServers: (projects = []) => {
|
|
27725
|
-
const rows = new Map();
|
|
27726
|
-
for (const cwd of new Set([PACKAGE_ROOT, ...projects.map(project => project.path || project.cwd).filter(Boolean)]))
|
|
27727
|
-
const
|
|
27728
|
-
if (!
|
|
27729
|
-
|
|
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
|
+
}
|
|
27730
28066
|
}
|
|
27731
|
-
|
|
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()] };
|
|
27732
28069
|
},
|
|
27733
28070
|
codexPrice: (model) => assistantPricing.codexPrice(model),
|
|
27734
28071
|
listAccounts: () => accountUsage.list(),
|
|
@@ -28143,6 +28480,8 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
28143
28480
|
greeting: _greeting,
|
|
28144
28481
|
// The Admin sandbox setting: every session view shows it (features.adminSandbox gates the panel's control).
|
|
28145
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,
|
|
28146
28485
|
});
|
|
28147
28486
|
assistantDesktop?.attach?.({ runtime: _assistantRuntime, dispatcher: _assistantDispatcher });
|
|
28148
28487
|
// Warm the catalog so brain capabilities (vision, tier) are known on first attach,
|
|
@@ -28205,6 +28544,8 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
28205
28544
|
workerGuard: _workerGuard,
|
|
28206
28545
|
// A request without an agent pin is the owner's page only with this boot's page secret (lib/page-session.js).
|
|
28207
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)),
|
|
28208
28549
|
}));
|
|
28209
28550
|
const shutdownAssistant = () => {
|
|
28210
28551
|
// Running skill creations first: what their workers wrote is kept as drafts before the workers go.
|
|
@@ -28245,7 +28586,7 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
28245
28586
|
* plugin (lib/assistant-brains/opencode2-browser-policy/), `cwd` the run's project, `policyRoots` the registered code
|
|
28246
28587
|
* projects its test runners may also run in.
|
|
28247
28588
|
*/
|
|
28248
|
-
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 } = {}) {
|
|
28249
28590
|
const xdgRoot = resolve(DATA_HOME, 'data', 'loop-configs', `opencode-${terminalSessionId}`);
|
|
28250
28591
|
const targetDir = resolve(xdgRoot, 'opencode');
|
|
28251
28592
|
if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });
|
|
@@ -28273,6 +28614,10 @@ function setupOpencodeLoopConfig(terminalSessionId, browserSessionId, browserTab
|
|
|
28273
28614
|
};
|
|
28274
28615
|
if (browserSessionId) pinOverrides.SYNABUN_BROWSER_SESSION = browserSessionId;
|
|
28275
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}}`;
|
|
28276
28621
|
// Assistant task runs: e.g. SYNABUN_DESKTOP_GRANT for computer-use workers.
|
|
28277
28622
|
for (const [key, value] of Object.entries(extraMcpEnv || {})) if (value) pinOverrides[key] = String(value);
|
|
28278
28623
|
setMcpServer(baseCfg, 'SynaBun', buildManagedOpenCodeSynabunEntry(existingEntry, {
|
|
@@ -28287,6 +28632,7 @@ function setupOpencodeLoopConfig(terminalSessionId, browserSessionId, browserTab
|
|
|
28287
28632
|
...(!browserSessionId ? ['SYNABUN_BROWSER_SESSION'] : []),
|
|
28288
28633
|
...(!browserTabId ? ['SYNABUN_BROWSER_TAB'] : []),
|
|
28289
28634
|
...(!extraMcpEnv?.SYNABUN_DESKTOP_GRANT ? ['SYNABUN_DESKTOP_GRANT'] : []),
|
|
28635
|
+
...(!terminalToken ? [TERMINAL_TOKEN_ENV] : []),
|
|
28290
28636
|
'CLAUDECODE', 'SYNABUN_PROFILE', 'SYNABUN_RUNTIME_PROFILE_PATH',
|
|
28291
28637
|
],
|
|
28292
28638
|
}));
|
|
@@ -28338,6 +28684,9 @@ function setupClaudeLoopMcpConfig(terminalSessionId, browserSessionId, browserTa
|
|
|
28338
28684
|
const dir = resolve(DATA_HOME, 'data', 'loop-configs');
|
|
28339
28685
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
28340
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}}`;
|
|
28341
28690
|
if (browserSessionId) headers['X-Synabun-Browser-Session'] = browserSessionId;
|
|
28342
28691
|
if (browserTabId) headers['X-Synabun-Browser-Tab'] = browserTabId;
|
|
28343
28692
|
const inventory = externalInventory('claude-code', cwd);
|
|
@@ -28446,6 +28795,9 @@ function prepareExecWrapperFile(terminalSessionId, loopState, taskFile, sentinel
|
|
|
28446
28795
|
model: loopState.model,
|
|
28447
28796
|
effort: loopState.effort,
|
|
28448
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] : [],
|
|
28449
28801
|
// The Admin sandbox setting the loop started with (a loop file from before it: the current one).
|
|
28450
28802
|
codexConfigArgs: codexWindowsSandboxArgs(typeof loopState.adminSandbox === 'boolean' ? loopState.adminSandbox : adminSandboxOn()),
|
|
28451
28803
|
});
|
|
@@ -28563,6 +28915,8 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28563
28915
|
if (!loopState.active) {
|
|
28564
28916
|
clearInterval(interval);
|
|
28565
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(() => {});
|
|
28566
28920
|
console.log('[exec-loop-driver] Loop inactive, stopping driver');
|
|
28567
28921
|
return;
|
|
28568
28922
|
}
|
|
@@ -28610,6 +28964,8 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28610
28964
|
clearInterval(interval);
|
|
28611
28965
|
console.log(`[exec-loop-driver] Loop complete: ${iter}/${loopState.totalIterations}`);
|
|
28612
28966
|
cleanupExecLoopArtifacts(session);
|
|
28967
|
+
// Its browser tabs, wherever its route moved (a recovery, its own browser_session create).
|
|
28968
|
+
await endAutomationBrowser(terminalSessionId).catch(() => {});
|
|
28613
28969
|
driving = false;
|
|
28614
28970
|
return;
|
|
28615
28971
|
}
|
|
@@ -28625,15 +28981,22 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28625
28981
|
clearInterval(interval);
|
|
28626
28982
|
console.log(`[exec-loop-driver] Time cap reached: ${Math.round(elapsedMin)}/${loopState.maxMinutes}min`);
|
|
28627
28983
|
cleanupExecLoopArtifacts(session);
|
|
28984
|
+
await endAutomationBrowser(terminalSessionId).catch(() => {});
|
|
28628
28985
|
driving = false;
|
|
28629
28986
|
return;
|
|
28630
28987
|
}
|
|
28631
28988
|
|
|
28632
|
-
//
|
|
28633
|
-
|
|
28634
|
-
|
|
28635
|
-
|
|
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 });
|
|
28636
28997
|
}
|
|
28998
|
+
session._execTaskFile = taskFile;
|
|
28999
|
+
session._execTaskRoute = `${loopState.browserSessionId || ''}/${loopState.browserTabId || ''}`;
|
|
28637
29000
|
|
|
28638
29001
|
// Generate the platform-native wrapper. It owns exit-code capture and
|
|
28639
29002
|
// sentinel output; the PTY receives only the short wrapper invocation.
|
|
@@ -28704,6 +29067,7 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28704
29067
|
});
|
|
28705
29068
|
clearInterval(interval);
|
|
28706
29069
|
cleanupExecLoopArtifacts(session);
|
|
29070
|
+
await endAutomationBrowser(terminalSessionId).catch(() => {});
|
|
28707
29071
|
try { session.pty?.kill?.(); } catch { /* ok */ }
|
|
28708
29072
|
driving = false;
|
|
28709
29073
|
return;
|
|
@@ -28726,6 +29090,7 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28726
29090
|
loopLog(terminalSessionId, 'exec-driver:error', 'fatal exec driver error', { error: err.message });
|
|
28727
29091
|
clearInterval(interval);
|
|
28728
29092
|
cleanupExecLoopArtifacts(session);
|
|
29093
|
+
endAutomationBrowser(terminalSessionId).catch(() => {});
|
|
28729
29094
|
try { session.pty?.kill?.(); } catch {}
|
|
28730
29095
|
}
|
|
28731
29096
|
driving = false;
|
|
@@ -28738,18 +29103,22 @@ function attachExecLoopDriver(terminalSessionId) {
|
|
|
28738
29103
|
|
|
28739
29104
|
const LAST_SESSION_PATH = resolve(DATA_HOME, 'data', 'last-session.json');
|
|
28740
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 });
|
|
28741
29110
|
app.get('/api/last-session', (req, res) => {
|
|
28742
29111
|
try {
|
|
28743
29112
|
const fileExists = existsSync(LAST_SESSION_PATH);
|
|
28744
29113
|
const activeCount = [...terminalSessions.values()].filter(s => s.profile === 'claude-code').length;
|
|
29114
|
+
if (!fileExists) return noLastSession(res, 'none');
|
|
28745
29115
|
console.log(`[last-session] Check: file=${fileExists}, activeClaude=${activeCount}`);
|
|
28746
|
-
if (!fileExists) return res.status(404).json({ error: 'No saved session' });
|
|
28747
29116
|
// If there are currently active claude-code sessions, the snapshot is live — don't offer resume
|
|
28748
|
-
if (activeCount > 0) return res
|
|
29117
|
+
if (activeCount > 0) return noLastSession(res, 'active');
|
|
28749
29118
|
const raw = readFileSync(LAST_SESSION_PATH, 'utf-8').trim();
|
|
28750
29119
|
if (!raw) {
|
|
28751
29120
|
unlinkSync(LAST_SESSION_PATH);
|
|
28752
|
-
return res
|
|
29121
|
+
return noLastSession(res, 'empty');
|
|
28753
29122
|
}
|
|
28754
29123
|
const data = JSON.parse(raw);
|
|
28755
29124
|
// Enrich with labels from ui-state
|
|
@@ -28765,7 +29134,7 @@ app.get('/api/last-session', (req, res) => {
|
|
|
28765
29134
|
// Corrupt file — clean it up so it doesn't keep failing
|
|
28766
29135
|
if (err instanceof SyntaxError) {
|
|
28767
29136
|
try { unlinkSync(LAST_SESSION_PATH); } catch {}
|
|
28768
|
-
return res
|
|
29137
|
+
return noLastSession(res, 'corrupt');
|
|
28769
29138
|
}
|
|
28770
29139
|
res.status(500).json({ error: err.message });
|
|
28771
29140
|
}
|
|
@@ -30991,7 +31360,7 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
30991
31360
|
profileMode: result.profileMode, profileSource: result.profileSource,
|
|
30992
31361
|
});
|
|
30993
31362
|
} catch (err) {
|
|
30994
|
-
createError = err
|
|
31363
|
+
createError = browserStartFailure(err);
|
|
30995
31364
|
loopLog(ownerKey, logTag, 'strategy 2 FAILED: createBrowserSession threw', { err: err.message, stack: err.stack?.slice(0, 600) });
|
|
30996
31365
|
}
|
|
30997
31366
|
}
|
|
@@ -31001,8 +31370,9 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
31001
31370
|
// run's log, lastRunResult and the schedule:failed toast.
|
|
31002
31371
|
return {
|
|
31003
31372
|
error: createError
|
|
31004
|
-
? `Could not start the shared browser session: ${createError}`
|
|
31373
|
+
? `Could not start the shared browser session: ${createError.error}`
|
|
31005
31374
|
: 'Could not start the shared browser session. Open Browser Settings and verify the selected profile can launch.',
|
|
31375
|
+
...(createError?.code ? { code: createError.code, offenders: createError.offenders } : {}),
|
|
31006
31376
|
};
|
|
31007
31377
|
}
|
|
31008
31378
|
|
|
@@ -31055,7 +31425,16 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
31055
31425
|
// owner back to its own tab instead of the shared activeTab.
|
|
31056
31426
|
if (claimedSession && browserTabId) {
|
|
31057
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);
|
|
31058
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
|
+
}
|
|
31059
31438
|
}
|
|
31060
31439
|
|
|
31061
31440
|
return { browserSessionId, browserTabId };
|
|
@@ -31090,6 +31469,227 @@ async function releaseSharedBrowserTab(sessionId, ownerKey) {
|
|
|
31090
31469
|
}
|
|
31091
31470
|
}
|
|
31092
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
|
+
|
|
31093
31693
|
// ── Real-time sync WebSocket (multi-client state broadcast) ──
|
|
31094
31694
|
const syncClients = new Set(); // Set<WebSocket>
|
|
31095
31695
|
|
|
@@ -32167,34 +32767,73 @@ async function installMoneyGuardRoute(ctx) {
|
|
|
32167
32767
|
// still aborted. Managed contexts also block WS through Playwright. MoreLogin
|
|
32168
32768
|
// retains native WS only behind the verified server authentication boundary and
|
|
32169
32769
|
// credentials confined to this server, never an environment, page or log.
|
|
32170
|
-
|
|
32171
|
-
|
|
32172
|
-
|
|
32173
|
-
|
|
32174
|
-
|
|
32175
|
-
|
|
32770
|
+
// Records of serves this server did not start that may still run: each one could answer a page's WebSocket.
|
|
32771
|
+
function unverifiedServeRecords() {
|
|
32772
|
+
return opencodeServeRecords.list().filter(record =>
|
|
32773
|
+
!opencodeServeRecords.ownedHere(record) && opencodeServeRecords.verifySync(record) !== 'gone')
|
|
32774
|
+
.map(record => ({ ...record, claimable: (() => { try { return opencodeServeRecords.claimable(record); } catch { return false; } })() }));
|
|
32775
|
+
}
|
|
32776
|
+
const NATIVE_SERVE_WAIT_MS = Number(process.env.SYNABUN_NATIVE_SERVE_WAIT_MS) || 20_000;
|
|
32777
|
+
const NATIVE_SERVE_SWEEP_MS = Number(process.env.SYNABUN_NATIVE_SERVE_SWEEP_MS) || 10_000;
|
|
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).
|
|
32780
|
+
const NATIVE_SERVE_REPLY_MARGIN_MS = 5_000;
|
|
32781
|
+
// Before refusing, repair what SynaBun can itself, bounded: stop the serves an ended SynaBun left running (the records'
|
|
32782
|
+
// own sweep, which signals only a provably-SynaBun process whose owner has ended; at most NATIVE_SERVE_SWEEP_MS, in the
|
|
32783
|
+
// background while the rest is read) and wait for SynaBun's own verified serves still starting (at most
|
|
32784
|
+
// NATIVE_SERVE_WAIT_MS), both inside the request's deadline. The context is held by the boundary from before the
|
|
32785
|
+
// first look (nativeServeBoundary.attach), so no unverified serve starts meanwhile. Nothing is cached: every attempt
|
|
32786
|
+
// reads the live state again. Authentication is never relaxed: what is left is named.
|
|
32787
|
+
async function protectNativeServeContext(ctx, { deadline = Infinity, signal = null } = {}) {
|
|
32788
|
+
try {
|
|
32789
|
+
return await nativeServeBoundary.attach(ctx, {
|
|
32790
|
+
state: () => ({ ports: [...liveOpencodeServePorts()], unverifiedRecords: unverifiedServeRecords() }),
|
|
32791
|
+
sweep: () => opencodeServeRecords.sweep(),
|
|
32792
|
+
waitMs: NATIVE_SERVE_WAIT_MS, sweepMs: NATIVE_SERVE_SWEEP_MS,
|
|
32793
|
+
deadline: Number.isFinite(deadline) ? deadline - NATIVE_SERVE_REPLY_MARGIN_MS : Infinity, signal,
|
|
32794
|
+
});
|
|
32795
|
+
} catch (error) {
|
|
32796
|
+
if (error?.offenders) console.warn(`[browser] native serve boundary refused: ${JSON.stringify(error.offenders)}`);
|
|
32797
|
+
throw error;
|
|
32798
|
+
}
|
|
32799
|
+
}
|
|
32800
|
+
|
|
32801
|
+
// The answer a failed browser start gives its caller: the sentence, and for the native serve boundary its code and
|
|
32802
|
+
// the serves it names (narrowed: never a token or a whole record).
|
|
32803
|
+
function browserStartFailure(err) {
|
|
32804
|
+
const out = { error: err?.message || String(err) };
|
|
32805
|
+
if (err?.code === 'NATIVE_SERVE_UNVERIFIED') { out.code = err.code; out.offenders = narrowOffenders(err.offenders); }
|
|
32806
|
+
return out;
|
|
32176
32807
|
}
|
|
32177
32808
|
|
|
32178
|
-
async function installServePortGuard(ctx) {
|
|
32809
|
+
async function installServePortGuard(ctx, { deadline = Infinity, signal = null } = {}) {
|
|
32179
32810
|
if (!ctx || ctx.__servePortGuardInstalled) return;
|
|
32180
32811
|
// routeWebSocket installs page bindings and replaces WebSocket on navigation,
|
|
32181
32812
|
// even with an empty matcher. Native contexts rely on the verified server's
|
|
32182
32813
|
// authentication; never silently route or drop protection for unknown serves.
|
|
32183
32814
|
const native = usesNativeBrowserNetworkGuard(ctx);
|
|
32184
|
-
const release = native ? protectNativeServeContext(ctx) : null;
|
|
32185
32815
|
const refused = (url) => { try { return !!browserServePortDenial(url?.href ?? url, liveOpencodeServePorts()); } catch { return false; } };
|
|
32816
|
+
const installRule = () => setBrowserNetworkRule(ctx, 'serve-port', {
|
|
32817
|
+
patterns: SERVE_PORT_PATTERNS,
|
|
32818
|
+
decide: request => refused(request.url) ? { abort: true } : null,
|
|
32819
|
+
});
|
|
32820
|
+
if (native) {
|
|
32821
|
+
// Held first (assertLaunch refuses an unverified start from here on), then the HTTP rule, then the bounded check.
|
|
32822
|
+
const release = nativeServeBoundary.reserve(ctx);
|
|
32823
|
+
try { await installRule(); } catch (error) {
|
|
32824
|
+
release();
|
|
32825
|
+
throw new Error(`Failed to install the OpenCode serve guard: ${error.message}`);
|
|
32826
|
+
}
|
|
32827
|
+
await protectNativeServeContext(ctx, { deadline, signal });
|
|
32828
|
+
ctx.__servePortGuardInstalled = true;
|
|
32829
|
+
return;
|
|
32830
|
+
}
|
|
32186
32831
|
try {
|
|
32187
|
-
await
|
|
32188
|
-
|
|
32189
|
-
|
|
32190
|
-
});
|
|
32191
|
-
if (!native) {
|
|
32192
|
-
if (typeof ctx.routeWebSocket !== 'function') throw new Error('WebSocket routing is unavailable');
|
|
32193
|
-
await ctx.routeWebSocket(refused, ws => Promise.resolve(ws.close({ code: 1008, reason: 'SynaBun: not an address the browser opens' })).catch(() => {}));
|
|
32194
|
-
}
|
|
32832
|
+
await installRule();
|
|
32833
|
+
if (typeof ctx.routeWebSocket !== 'function') throw new Error('WebSocket routing is unavailable');
|
|
32834
|
+
await ctx.routeWebSocket(refused, ws => Promise.resolve(ws.close({ code: 1008, reason: 'SynaBun: not an address the browser opens' })).catch(() => {}));
|
|
32195
32835
|
ctx.__servePortGuardInstalled = true;
|
|
32196
32836
|
} catch (error) {
|
|
32197
|
-
release?.();
|
|
32198
32837
|
throw new Error(`Failed to install the OpenCode serve guard: ${error.message}`);
|
|
32199
32838
|
}
|
|
32200
32839
|
}
|
|
@@ -32874,7 +33513,7 @@ async function createBrowserSession(options = {}) {
|
|
|
32874
33513
|
const startServeDenial = browserServePortDenial(startUrl, liveOpencodeServePorts());
|
|
32875
33514
|
if (startServeDenial) throw new Error(startServeDenial);
|
|
32876
33515
|
await installMoneyGuardRoute(context);
|
|
32877
|
-
await installServePortGuard(context);
|
|
33516
|
+
await installServePortGuard(context, { deadline: options.browserRequest?.deadline, signal: options.browserRequest?.signal });
|
|
32878
33517
|
if (typeof _pageSession !== 'undefined') {
|
|
32879
33518
|
const marked = await _pageSession.markWorkerBrowserContext(context, { port: PORT, hostNames: machineNames.names() });
|
|
32880
33519
|
if (!marked) throw new Error('Cannot protect browser owner authority: local worker marker failed');
|
|
@@ -33406,6 +34045,24 @@ async function recoverSessionTabPage(session, sessionId, tabId, reason = 'page b
|
|
|
33406
34045
|
}
|
|
33407
34046
|
|
|
33408
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
|
+
}
|
|
33409
34066
|
if (!session._invalidating) {
|
|
33410
34067
|
session._invalidating = true;
|
|
33411
34068
|
// destroyBrowserSession removes the registry entry synchronously before
|
|
@@ -33488,6 +34145,9 @@ function browserRecoveryErrorMessage(error, recovery) {
|
|
|
33488
34145
|
if (recovery?.sessionInvalidated) {
|
|
33489
34146
|
return `${error.message} The unhealthy browser session was retired and will be reacquired on the next browser call.`;
|
|
33490
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
|
+
}
|
|
33491
34151
|
if (recovery?.error) return `${error.message} Automatic tab recovery failed: ${recovery.error}`;
|
|
33492
34152
|
return error.message;
|
|
33493
34153
|
}
|
|
@@ -33748,6 +34408,165 @@ async function otherOpenPageCount(session, own) {
|
|
|
33748
34408
|
}
|
|
33749
34409
|
}
|
|
33750
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
|
+
|
|
33751
34570
|
// ── Tab-level page routing (concurrent loop isolation) ──
|
|
33752
34571
|
|
|
33753
34572
|
/** Automation owners (loops, interactive MCP processes, agents) on a session. */
|
|
@@ -33771,24 +34590,33 @@ function trackRoute(session, identityKey, tabId, source) {
|
|
|
33771
34590
|
|
|
33772
34591
|
/**
|
|
33773
34592
|
* Resolve the Playwright page for an API request.
|
|
33774
|
-
*
|
|
33775
|
-
*
|
|
33776
|
-
*
|
|
33777
|
-
* 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).
|
|
33778
34601
|
*/
|
|
33779
34602
|
function getTargetPage(session, req) {
|
|
33780
|
-
const
|
|
33781
|
-
|
|
33782
|
-
|
|
33783
|
-
//
|
|
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.
|
|
33784
34613
|
const tabId = req.body?.tabId || req.query?.tabId;
|
|
33785
34614
|
if (tabId) {
|
|
33786
34615
|
const tab = session.tabs?.get(tabId);
|
|
33787
34616
|
if (!tab) return null;
|
|
33788
|
-
if (
|
|
33789
|
-
|
|
33790
|
-
|
|
33791
|
-
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;
|
|
33792
34620
|
}
|
|
33793
34621
|
trackRoute(session, terminalId, tabId, 'explicit-tab');
|
|
33794
34622
|
return { page: tab.page, cdpSession: tab.cdpSession, tabId };
|
|
@@ -33797,60 +34625,45 @@ function getTargetPage(session, req) {
|
|
|
33797
34625
|
// 2. No tabId — route by caller identity. The MCP child sends X-Synabun-Terminal
|
|
33798
34626
|
// (its loop terminalSessionId, sidepanel owner key, or per-caller client id).
|
|
33799
34627
|
// If that caller owns a tab here, use it — never the shared activeTab.
|
|
33800
|
-
if (
|
|
33801
|
-
const
|
|
33802
|
-
const tab = session.tabs?.get(ownedTabId);
|
|
34628
|
+
if (ownTabId) {
|
|
34629
|
+
const tab = session.tabs?.get(ownTabId);
|
|
33803
34630
|
if (tab) {
|
|
33804
|
-
trackRoute(session, terminalId,
|
|
33805
|
-
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 };
|
|
33806
34633
|
}
|
|
33807
34634
|
// Owned tab vanished — drop the stale mapping and fall through.
|
|
33808
34635
|
session._tabOwners.delete(terminalId);
|
|
33809
34636
|
}
|
|
33810
34637
|
|
|
33811
|
-
//
|
|
33812
|
-
//
|
|
33813
|
-
|
|
33814
|
-
|
|
33815
|
-
|
|
33816
|
-
|
|
33817
|
-
|
|
33818
|
-
|
|
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.
|
|
33819
34647
|
|
|
33820
|
-
//
|
|
33821
|
-
// this means its own tab is gone (or never registered): fail closed so the
|
|
33822
|
-
// MCP-side recovery acquires it a fresh owned tab instead of hijacking the
|
|
33823
|
-
// lone tab another automation may own.
|
|
34648
|
+
// 4. Single-tab session — unambiguous for the owner's page.
|
|
33824
34649
|
if (session.tabs && session.tabs.size === 1) {
|
|
33825
34650
|
const onlyTabId = session.tabs.keys().next().value;
|
|
33826
34651
|
const only = session.tabs.get(onlyTabId);
|
|
33827
|
-
|
|
33828
|
-
if (only && (!isAutomation || (sessionOwnerCount(session) === 0 && !tabClaimed))) {
|
|
34652
|
+
if (only) {
|
|
33829
34653
|
trackRoute(session, terminalId, onlyTabId, 'single-tab');
|
|
33830
34654
|
return { page: only.page, cdpSession: only.cdpSession, tabId: onlyTabId };
|
|
33831
34655
|
}
|
|
33832
|
-
if (only) {
|
|
33833
|
-
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`);
|
|
33834
|
-
return null;
|
|
33835
|
-
}
|
|
33836
34656
|
}
|
|
33837
34657
|
|
|
33838
|
-
//
|
|
33839
|
-
//
|
|
33840
|
-
//
|
|
33841
|
-
// cross-automation website leaks. The NI UI drives multi-tab sessions via explicit
|
|
33842
|
-
// 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.
|
|
33843
34661
|
if (session.tabs && session.tabs.size > 1) {
|
|
33844
|
-
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`);
|
|
33845
34663
|
return null;
|
|
33846
34664
|
}
|
|
33847
34665
|
|
|
33848
|
-
//
|
|
33849
|
-
// session). Automations with a lost pin fail closed here too.
|
|
33850
|
-
if (isAutomation && sessionOwnerCount(session) > 0) {
|
|
33851
|
-
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`);
|
|
33852
|
-
return null;
|
|
33853
|
-
}
|
|
34666
|
+
// 6. Zero/uninitialized tabs — legacy single active-tab behavior (local UI session).
|
|
33854
34667
|
// No active page at all (the last tab closed or was retired): there is nothing to route to.
|
|
33855
34668
|
if (!session.page) return null;
|
|
33856
34669
|
trackRoute(session, terminalId, session.activeTabId, 'legacy');
|
|
@@ -33877,6 +34690,8 @@ async function getBrowserActionState(session, routed, compact) {
|
|
|
33877
34690
|
|
|
33878
34691
|
// ── Browser REST endpoints ──
|
|
33879
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);
|
|
33880
34695
|
app.use('/api/browser', browserRequestMiddleware);
|
|
33881
34696
|
app.use('/api/browser', (req, res, next) => { res.setHeader('X-Synabun-Browser-Default', browserDefaultSignature()); next(); });
|
|
33882
34697
|
// Agents act on the default browser only. MCP callers (browser tools, platform
|
|
@@ -33902,7 +34717,8 @@ app.use('/api/browser/sessions/:id', (req, res, next) => {
|
|
|
33902
34717
|
res.once('finish', release);
|
|
33903
34718
|
res.once('close', release);
|
|
33904
34719
|
}
|
|
33905
|
-
|
|
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();
|
|
33906
34722
|
const session = browserSessions.get(req.params.id);
|
|
33907
34723
|
if (!session) return next();
|
|
33908
34724
|
const cfg = loadBrowserConfig();
|
|
@@ -33929,12 +34745,34 @@ app.get('/api/browser/sessions', (req, res) => {
|
|
|
33929
34745
|
// The server decides which sessions may carry normal-page work: with MoreLogin as
|
|
33930
34746
|
// the default, only a MoreLogin session on the default env does (MCP callers
|
|
33931
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
|
+
}
|
|
33932
34756
|
const policyCfg = loadBrowserConfig();
|
|
33933
34757
|
const moreLoginDefault = policyCfg.connectMode === 'morelogin';
|
|
33934
|
-
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 {
|
|
33935
34773
|
id,
|
|
33936
|
-
url: s.currentUrl,
|
|
33937
|
-
title: s.title,
|
|
34774
|
+
url: automationView ? (ownTab ? liveUrl(ownTab) : null) : s.currentUrl,
|
|
34775
|
+
title: automationView ? (ownTab ? ownTab.title || '' : null) : s.title,
|
|
33938
34776
|
createdAt: s.createdAt,
|
|
33939
34777
|
clients: s.clients.size,
|
|
33940
34778
|
persistent: !!s._isPersistent,
|
|
@@ -33942,38 +34780,50 @@ app.get('/api/browser/sessions', (req, res) => {
|
|
|
33942
34780
|
profileSource: s._profileSourceName || null,
|
|
33943
34781
|
moreloginEnvId: s._mlEnvId || null,
|
|
33944
34782
|
servesDefault: moreLoginDefault ? sessionServesMoreLoginDefault(s, policyCfg) : true,
|
|
33945
|
-
|
|
33946
|
-
|
|
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),
|
|
33947
34786
|
loopOwned: (s._loopOwned?.size || 0) > 0,
|
|
33948
34787
|
interactiveOwned: (s._interactiveOwned?.size || 0) > 0,
|
|
33949
34788
|
// Also check agent registry as fallback — covers the race window between
|
|
33950
34789
|
// session creation and agent ownership being set
|
|
33951
34790
|
agentOwned: (s._agentOwnedSet?.size || 0) > 0 || [...agentRegistry.values()].some(a => a.status === 'running' && a.browserSessionId === id),
|
|
33952
|
-
// Identity → tab attribution for
|
|
33953
|
-
// `
|
|
33954
|
-
|
|
33955
|
-
|
|
33956
|
-
interactive: [...(s._interactiveOwned || [])],
|
|
33957
|
-
agents: [...(s._agentOwnedSet || [])],
|
|
33958
|
-
},
|
|
33959
|
-
tabOwners: s._tabOwners ? Object.fromEntries(s._tabOwners) : {},
|
|
33960
|
-
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]) => ({
|
|
33961
34795
|
id: tid,
|
|
33962
|
-
url: t.url,
|
|
34796
|
+
url: automationView ? liveUrl(t) : t.url,
|
|
33963
34797
|
title: t.title,
|
|
33964
34798
|
active: tid === s.activeTabId,
|
|
33965
|
-
}))
|
|
33966
|
-
|
|
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;
|
|
33967
34806
|
res.json({
|
|
33968
34807
|
sessions,
|
|
33969
34808
|
defaultBrowser: moreLoginDefault
|
|
33970
34809
|
? { connectMode: 'morelogin', moreloginEnvId: moreLoginDefaultEnvId(policyCfg) }
|
|
33971
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,
|
|
33972
34815
|
});
|
|
33973
34816
|
});
|
|
33974
34817
|
|
|
33975
34818
|
app.post('/api/browser/sessions', async (req, res) => {
|
|
33976
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
|
+
}
|
|
33977
34827
|
// A create-session startUrl that points at one of SynaBun's own live OpenCode serve ports is refused up front, like
|
|
33978
34828
|
// navigate and new-tab: the serve's API can change what a worker session may do, and createBrowserSession navigates
|
|
33979
34829
|
// to the startUrl while the rest of the session is still being wired. (createBrowserSession enforces the same denial
|
|
@@ -33987,12 +34837,6 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
33987
34837
|
const _realHeaders = {
|
|
33988
34838
|
'accept-language': req.headers['accept-language'],
|
|
33989
34839
|
};
|
|
33990
|
-
const result = await createBrowserSession({
|
|
33991
|
-
url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, _realHeaders,
|
|
33992
|
-
// Optional per-session override to target a specific MoreLogin env (multi-identity)
|
|
33993
|
-
...(connectMode === 'morelogin' ? { connectMode } : {}),
|
|
33994
|
-
...(moreloginEnvId ? { moreloginEnvId: String(moreloginEnvId) } : {}),
|
|
33995
|
-
});
|
|
33996
34840
|
// Tab ownership for the creating automation. An MCP child sends its routing
|
|
33997
34841
|
// identity in X-Synabun-Terminal; register it as the owner of this session's
|
|
33998
34842
|
// active tab. Without this, a plain-created tab is "unowned" and the creator's
|
|
@@ -34000,27 +34844,78 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
34000
34844
|
// acquires a second tab in the same shared persistent browser — the root of the
|
|
34001
34845
|
// sidepanel-vs-CLI "lost browser session" collision. Manual NI-UI creates send
|
|
34002
34846
|
// no header → stay unowned (legacy activeTab semantics preserved).
|
|
34003
|
-
|
|
34004
|
-
|
|
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
|
+
});
|
|
34005
34862
|
const createdSession = browserSessions.get(result.sessionId);
|
|
34006
|
-
if (createdSession) {
|
|
34863
|
+
if (creatorTerminalId && createdSession) {
|
|
34007
34864
|
if (!createdSession._tabOwners) createdSession._tabOwners = new Map();
|
|
34008
34865
|
createdSession._tabOwners.set(creatorTerminalId, createdSession.activeTabId);
|
|
34009
34866
|
}
|
|
34010
|
-
|
|
34011
|
-
|
|
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');
|
|
34012
34886
|
res.json({
|
|
34013
|
-
|
|
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,
|
|
34014
34889
|
...(result.moreLoginBlocked && { moreLoginBlocked: true, notice: result.moreLoginBlocked }),
|
|
34890
|
+
...(handedOver && { handedOver }),
|
|
34015
34891
|
});
|
|
34016
34892
|
} catch (err) {
|
|
34017
34893
|
console.error('Browser session create error:', err.message);
|
|
34018
|
-
res.status(500).json(
|
|
34894
|
+
res.status(500).json(browserStartFailure(err));
|
|
34019
34895
|
}
|
|
34020
34896
|
});
|
|
34021
34897
|
|
|
34022
34898
|
app.delete('/api/browser/sessions/:id', async (req, res) => {
|
|
34023
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
|
+
}
|
|
34024
34919
|
// An explicit close (browser_session close, the UI): in MoreLogin or the user's Chrome, the tabs SynaBun opened for it close too.
|
|
34025
34920
|
await destroyBrowserSession(req.params.id, { closeOwnTabs: true });
|
|
34026
34921
|
res.json({ ok: true });
|
|
@@ -34031,29 +34926,58 @@ app.delete('/api/browser/sessions/:id', async (req, res) => {
|
|
|
34031
34926
|
|
|
34032
34927
|
// POST /api/browser/acquire — interactive (non-loop) MCP process claims a dedicated
|
|
34033
34928
|
// tab in the ONE shared browser instead of launching a second browser on the same
|
|
34034
|
-
// persistent profile (which fails with "Browser profile is locked"). The
|
|
34035
|
-
//
|
|
34036
|
-
//
|
|
34037
|
-
//
|
|
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 }.
|
|
34038
34935
|
app.post('/api/browser/acquire', async (req, res) => {
|
|
34039
34936
|
try {
|
|
34040
|
-
|
|
34041
|
-
|
|
34042
|
-
|
|
34043
|
-
if (
|
|
34044
|
-
|
|
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 }) });
|
|
34045
34959
|
} catch (err) {
|
|
34046
|
-
|
|
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 } : {}) });
|
|
34047
34963
|
}
|
|
34048
34964
|
});
|
|
34049
34965
|
|
|
34050
34966
|
// POST /api/browser/release — interactive MCP process relinquishes its owned tab on
|
|
34051
34967
|
// exit. Closes the dedicated tab and drops the ownership/routing entries so the shared
|
|
34052
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).
|
|
34053
34971
|
app.post('/api/browser/release', async (req, res) => {
|
|
34054
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);
|
|
34055
34976
|
const clientId = req.body?.clientId;
|
|
34056
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' });
|
|
34057
34981
|
let released = 0;
|
|
34058
34982
|
for (const [sessionId, session] of browserSessions) {
|
|
34059
34983
|
if (!session._interactiveOwned?.has(clientId)) continue;
|
|
@@ -34124,8 +35048,9 @@ app.delete('/api/browser/sessions/:id/tabs/:tabId', async (req, res) => {
|
|
|
34124
35048
|
const engagementScheduler = createEngagementScheduler();
|
|
34125
35049
|
const _paceRand = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
|
|
34126
35050
|
|
|
35051
|
+
/** The run a browser request may act as (browserCaller: a run's id only with its terminal token), or null. */
|
|
34127
35052
|
function _paceTerminalId(req) {
|
|
34128
|
-
return (req
|
|
35053
|
+
return browserCaller(req).id;
|
|
34129
35054
|
}
|
|
34130
35055
|
function isLoopPaced(session, req) {
|
|
34131
35056
|
if (process.env.SYNABUN_HUMAN_PACING === '0') return false;
|
|
@@ -34146,6 +35071,40 @@ async function rateLimitEngagement(session, req, selector, execute) {
|
|
|
34146
35071
|
if (!isLoopPaced(session, req) || !isEngagementWriteSelector(selector)) return execute();
|
|
34147
35072
|
return engagementScheduler.run(req.params.id, req, execute);
|
|
34148
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
|
+
}
|
|
34149
35108
|
|
|
34150
35109
|
// ── X/Twitter compose-state probe + publish gate ──
|
|
34151
35110
|
// Deterministic read of the X composer so loops branch on structured state instead of
|
|
@@ -34371,6 +35330,7 @@ app.post('/api/browser/sessions/:id/navigate', async (req, res) => {
|
|
|
34371
35330
|
error: browserRecoveryErrorMessage(err, recovery),
|
|
34372
35331
|
...(recovery && { tabRecovered: !!recovery.recovered }),
|
|
34373
35332
|
...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
|
|
35333
|
+
...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
|
|
34374
35334
|
});
|
|
34375
35335
|
}
|
|
34376
35336
|
});
|
|
@@ -34395,6 +35355,7 @@ app.post('/api/browser/sessions/:id/back', async (req, res) => {
|
|
|
34395
35355
|
error: browserRecoveryErrorMessage(err, recovery),
|
|
34396
35356
|
...(recovery && { tabRecovered: !!recovery.recovered }),
|
|
34397
35357
|
...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
|
|
35358
|
+
...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
|
|
34398
35359
|
});
|
|
34399
35360
|
}
|
|
34400
35361
|
});
|
|
@@ -34419,6 +35380,7 @@ app.post('/api/browser/sessions/:id/forward', async (req, res) => {
|
|
|
34419
35380
|
error: browserRecoveryErrorMessage(err, recovery),
|
|
34420
35381
|
...(recovery && { tabRecovered: !!recovery.recovered }),
|
|
34421
35382
|
...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
|
|
35383
|
+
...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
|
|
34422
35384
|
});
|
|
34423
35385
|
}
|
|
34424
35386
|
});
|
|
@@ -34440,6 +35402,7 @@ app.post('/api/browser/sessions/:id/reload', async (req, res) => {
|
|
|
34440
35402
|
error: browserRecoveryErrorMessage(err, recovery),
|
|
34441
35403
|
...(recovery && { tabRecovered: !!recovery.recovered }),
|
|
34442
35404
|
...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
|
|
35405
|
+
...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
|
|
34443
35406
|
});
|
|
34444
35407
|
}
|
|
34445
35408
|
});
|
|
@@ -34898,21 +35861,43 @@ app.post('/api/browser/sessions/:id/evaluate', async (req, res) => {
|
|
|
34898
35861
|
if (!script) return res.status(400).json({ error: 'script required' });
|
|
34899
35862
|
const xRefusal = xGateBypassRefusal(session, req, routed, 'evaluate', script);
|
|
34900
35863
|
if (xRefusal) return res.status(409).json(xRefusal);
|
|
34901
|
-
|
|
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 });
|
|
34902
35869
|
markBrowserActionStarted(req);
|
|
34903
|
-
|
|
35870
|
+
return withBrowserOperationDeadline(
|
|
34904
35871
|
routed.page.evaluate(script),
|
|
34905
35872
|
BROWSER_EVALUATE_DEADLINE_MS,
|
|
34906
35873
|
'browser_evaluate',
|
|
34907
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();
|
|
34908
35890
|
// Ensure result is JSON-serializable (undefined becomes null)
|
|
34909
35891
|
res.json({ ok: true, result: result === undefined ? null : result });
|
|
34910
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 });
|
|
34911
35895
|
const recovery = await recoverBrowserRouteFailure(session, req.params.id, routed, req, 'evaluate', err);
|
|
34912
35896
|
res.status(500).json({
|
|
34913
35897
|
error: browserRecoveryErrorMessage(err, recovery),
|
|
34914
35898
|
...(recovery && { tabRecovered: !!recovery.recovered }),
|
|
34915
35899
|
...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
|
|
35900
|
+
...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
|
|
34916
35901
|
});
|
|
34917
35902
|
}
|
|
34918
35903
|
});
|
|
@@ -36352,14 +37337,18 @@ httpServer.on('upgrade', function onUpgrade(req, socket, head) {
|
|
|
36352
37337
|
// Owner authority by peer identity (lib/owner-authority.js): an owner's socket (a terminal, the agent panels, the
|
|
36353
37338
|
// Assistant, the browser panel) is refused to SynaBun's automation browser, a relay, another SynaBun server, a
|
|
36354
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,
|
|
36355
|
-
// 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.
|
|
36356
37344
|
if (!req._synabunOwnerChecked && (_ownerAuthority.socketScope(url.pathname).owner || _ownerAuthority.socketScope(url.pathname).readOnly)) {
|
|
36357
37345
|
req._synabunOwnerChecked = true;
|
|
36358
|
-
|
|
36359
|
-
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; }
|
|
36360
37348
|
if (verdict.readOnly) req._synabunReadOnly = true;
|
|
36361
37349
|
onUpgrade(req, socket, head);
|
|
36362
|
-
}
|
|
37350
|
+
};
|
|
37351
|
+
_ownerAuthority.checkUpgrade(req, url.pathname).then(settle, (error) => settle(_ownerAuthority.upgradeFailed(req, url.pathname, error)));
|
|
36363
37352
|
return;
|
|
36364
37353
|
}
|
|
36365
37354
|
|
|
@@ -36373,6 +37362,19 @@ httpServer.on('upgrade', function onUpgrade(req, socket, head) {
|
|
|
36373
37362
|
return;
|
|
36374
37363
|
}
|
|
36375
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
|
+
|
|
36376
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') {
|
|
36377
37379
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
36378
37380
|
wss.emit('connection', ws, req);
|