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
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// ── The browser routes an automation may call (DOM-free, no imports) ──
|
|
2
|
+
//
|
|
3
|
+
// SynaBun's browser API (/api/browser) serves two callers: the owner's page (the browser panel, Settings → Browser)
|
|
4
|
+
// and the automations that drive the browser through SynaBun's MCP tools (loops, dispatched workers, agents, the side
|
|
5
|
+
// panels, a CLI window). The MCP tools call a fixed set of routes (mcp-server/src/services/neural-interface.ts: the
|
|
6
|
+
// session list, create and close, acquire and release, and the page actions on a session); everything else under
|
|
7
|
+
// /api/browser is the owner's: the browser settings (PUT /config: attach to the user's real Chrome, pick a MoreLogin
|
|
8
|
+
// profile), the money guard's lift (paid-surfaces), the raw CDP endpoints (cdp, claude-connect), tab management
|
|
9
|
+
// outside a run's own tab (tabs: list, open, activate, close), the folder picker and the profile and browser
|
|
10
|
+
// detection. Until 2026-11-05 a run that proved its id reached all of them, and the worker-only MCP channel forwarded
|
|
11
|
+
// every /browser/* path with the run's token, so a sandboxed worker could switch the default browser to the user's
|
|
12
|
+
// real Chrome profile or lift the money guard (review 972afb74, finding 1).
|
|
13
|
+
//
|
|
14
|
+
// This list is the one answer to "may an automation call this": the worker channel forwards nothing else
|
|
15
|
+
// (lib/worker-mcp-channel.js), and server.js browserTerminalGate answers every other route the owner's page only (its
|
|
16
|
+
// page secret, or an invite guest the guest rules let in), whatever agent headers the request carries. A route a new
|
|
17
|
+
// MCP tool calls is added here, with its test (tests/browser-automation-routes.test.mjs checks the list against the
|
|
18
|
+
// paths the MCP server's source calls).
|
|
19
|
+
|
|
20
|
+
/** One path segment of a session or tab id SynaBun mints (hex today; base64url and uuid shapes allowed). */
|
|
21
|
+
const ID = '[A-Za-z0-9_-]{1,128}';
|
|
22
|
+
/** Page actions on a session the MCP tools post (navigate, click, …). */
|
|
23
|
+
const POST_ACTIONS = Object.freeze([
|
|
24
|
+
'navigate', 'back', 'forward', 'reload', 'click', 'fill', 'type', 'hover', 'select', 'press', 'scroll', 'upload',
|
|
25
|
+
'snapshot', 'evaluate', 'extract', 'x-compose-state', 'semantic-context', 'wait', 'bluesky/upload-blob',
|
|
26
|
+
]);
|
|
27
|
+
/** Reads of a session the MCP tools get. */
|
|
28
|
+
const GET_READS = Object.freeze(['snapshot', 'content', 'markdown', 'screenshot-base64', 'console']);
|
|
29
|
+
|
|
30
|
+
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
31
|
+
|
|
32
|
+
/** [method, path pattern relative to /api/browser] for every route an automation may call. */
|
|
33
|
+
export const AUTOMATION_BROWSER_ROUTES = Object.freeze([
|
|
34
|
+
['GET', '/sessions'],
|
|
35
|
+
['POST', '/sessions'],
|
|
36
|
+
['POST', '/acquire'],
|
|
37
|
+
['POST', '/release'],
|
|
38
|
+
['DELETE', '/sessions/:id'],
|
|
39
|
+
...POST_ACTIONS.map((action) => ['POST', `/sessions/:id/${action}`]),
|
|
40
|
+
...GET_READS.map((read) => ['GET', `/sessions/:id/${read}`]),
|
|
41
|
+
].map((route) => Object.freeze(route)));
|
|
42
|
+
|
|
43
|
+
const MATCHERS = AUTOMATION_BROWSER_ROUTES.map(([method, path]) => ({
|
|
44
|
+
method,
|
|
45
|
+
re: new RegExp(`^${path.split('/').map((part) => (part === ':id' ? ID : escape(part))).join('/')}/?$`),
|
|
46
|
+
}));
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Whether an automation may call `method` `path`. `path` is relative to /api/browser (`/sessions/abc/navigate`), as
|
|
50
|
+
* Express's req.path is under that mount; a query string is ignored. Anything that is not exactly one of the listed
|
|
51
|
+
* routes is the owner's: another method, another path, an encoded or dot segment, a doubled slash.
|
|
52
|
+
*/
|
|
53
|
+
export function isAutomationBrowserRoute(method, path) {
|
|
54
|
+
const verb = String(method || '').toUpperCase() === 'HEAD' ? 'GET' : String(method || '').toUpperCase();
|
|
55
|
+
const bare = String(path || '').split('?')[0];
|
|
56
|
+
if (!bare.startsWith('/') || bare.includes('//')) return false;
|
|
57
|
+
return MATCHERS.some((m) => m.method === verb && m.re.test(bare));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The fields of a session create that pick which browser or profile it starts (POST /api/browser/sessions): the
|
|
62
|
+
* owner's choice (Settings → Browser), never an automation's. An automation's create opens the default browser.
|
|
63
|
+
*/
|
|
64
|
+
export const OWNER_ONLY_CREATE_FIELDS = Object.freeze(['connectMode', 'moreloginEnvId']);
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Every field that names a browser, a MoreLogin profile or a browser setting (PUT /api/browser/config's fields and
|
|
68
|
+
* the names an agent reaches for: profile, config, a profile folder, a CDP endpoint). The owner's choice, never an
|
|
69
|
+
* automation's: an automation's session create naming one is refused (403 OWNER_ONLY_FIELDS), and SynaBun's browser
|
|
70
|
+
* MCP tools refuse a call that names one instead of dropping it (mcp-server/src/services/browser-route-flow.ts
|
|
71
|
+
* OWNER_ONLY_FIELDS mirrors this list; tests/browser-automation-routes.test.mjs keeps the two equal). Until
|
|
72
|
+
* 2026-11-05 the tools' schemas dropped them silently, so `profile: "other"` looked accepted.
|
|
73
|
+
*/
|
|
74
|
+
export const OWNER_ONLY_BROWSER_FIELDS = Object.freeze([
|
|
75
|
+
...OWNER_ONLY_CREATE_FIELDS, 'attachSeed', 'openTabsInBackground',
|
|
76
|
+
'config', 'profile', 'profileDir', 'profilePath', 'userDataDir', 'executablePath',
|
|
77
|
+
'moreloginProfile', 'moreloginEnv', 'moreloginEnvironment', 'cdpUrl', 'wsEndpoint',
|
|
78
|
+
]);
|
|
79
|
+
|
|
80
|
+
/** The owner-only fields a create body names (an empty list when none). */
|
|
81
|
+
export function ownerOnlyCreateFields(body) {
|
|
82
|
+
if (!body || typeof body !== 'object') return [];
|
|
83
|
+
return OWNER_ONLY_BROWSER_FIELDS.filter((field) => body[field] !== undefined && body[field] !== null && body[field] !== '');
|
|
84
|
+
}
|
|
@@ -86,15 +86,28 @@ export function cancellableBrowserDelay(ms, req) {
|
|
|
86
86
|
});
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
/**
|
|
90
|
+
* The longest a browser request is answered after (/api/browser/*, and the run recovery POST /api/loop/recover-browser):
|
|
91
|
+
* a caller's X-Synabun-Deadline is honoured up to this. A browser start that is still running then is answered
|
|
92
|
+
* BROWSER_STARTING and kept for its caller (lib/browser-start-handoff.js). The MCP's create / recovery timeout
|
|
93
|
+
* (mcp-server/src/services/neural-interface.ts SESSION_CREATE_TIMEOUT) is longer, so it reads that answer, never a
|
|
94
|
+
* timeout of its own.
|
|
95
|
+
*/
|
|
96
|
+
export const BROWSER_REQUEST_MAX_MS = 120_000;
|
|
97
|
+
|
|
98
|
+
/** A request's deadline: its X-Synabun-Deadline, at most BROWSER_REQUEST_MAX_MS from now. */
|
|
99
|
+
export function browserRequestDeadline(req, now = Date.now()) {
|
|
100
|
+
const requested = Number(req?.get?.('X-Synabun-Deadline'));
|
|
101
|
+
return Number.isFinite(requested) && requested > 0 ? Math.min(requested, now + BROWSER_REQUEST_MAX_MS) : now + BROWSER_REQUEST_MAX_MS;
|
|
102
|
+
}
|
|
103
|
+
|
|
89
104
|
/** Metadata only: never logs URLs, selectors, form values, scripts or response bodies. */
|
|
90
105
|
export function browserRequestMiddleware(req, res, next) {
|
|
91
106
|
const controller = new AbortController();
|
|
92
107
|
const start = performance.now();
|
|
93
108
|
const supplied = req.get('X-Synabun-Request-Id');
|
|
94
109
|
const requestId = /^[\w-]{1,80}$/.test(supplied || '') ? supplied : randomUUID();
|
|
95
|
-
const
|
|
96
|
-
const deadline = Number.isFinite(requestedDeadline) && requestedDeadline > 0
|
|
97
|
-
? Math.min(requestedDeadline, Date.now() + 120_000) : Date.now() + 120_000;
|
|
110
|
+
const deadline = browserRequestDeadline(req);
|
|
98
111
|
const state = { requestId, deadline, signal: controller.signal, actionStarted: false, phases: {}, counts: {} };
|
|
99
112
|
state.cancelForProtection = reason => { state.protectionError = String(reason); controller.abort(); };
|
|
100
113
|
req.browserRequest = state;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// ── Who owns a browser tab, as the routes read it (DOM-free) ──
|
|
2
|
+
//
|
|
3
|
+
// Every automation that uses SynaBun's browser names itself in X-Synabun-Terminal (its MCP sends it on every
|
|
4
|
+
// request): a loop's terminal id, a native run's or a dispatched worker's run id, a sidepanel's owner key, an MCP
|
|
5
|
+
// process's client id, and `agent:<uuid>` for an automation-window agent (server.js launchAgentController). Before
|
|
6
|
+
// 2026-11-04 two routes only took `[A-Za-z0-9_-]`, so an agent's own id was read as no id at all: its recovery was
|
|
7
|
+
// filed under a random owner, and its next call was refused that tab as "claimed by another" (a create loop and an
|
|
8
|
+
// orphan tab per round). One test for every route: browserOwnerId(). The MCP side (mcp-server identity.ts
|
|
9
|
+
// sanitizePin) accepts the same characters.
|
|
10
|
+
|
|
11
|
+
/** The ids the server mints: letters, digits, `_`, `-`, and `:` (`agent:<uuid>`). No spaces, no template junk. */
|
|
12
|
+
export const BROWSER_OWNER_ID_RE = /^[A-Za-z0-9_:-]{1,128}$/;
|
|
13
|
+
|
|
14
|
+
/** `value` as an owner id, or null (absent, not a string, or not shaped like one the server mints). */
|
|
15
|
+
export function browserOwnerId(value) {
|
|
16
|
+
return typeof value === 'string' && BROWSER_OWNER_ID_RE.test(value) ? value : null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The owner keys of one session as GET /api/browser/sessions shows them. The owner's own page (`reveal`) sees every
|
|
21
|
+
* key (collision debugging). Anyone else sees its own key as it is and the other owners only as `other-1`, `other-2`…
|
|
22
|
+
* in a stable order: an automation needs to know that another one holds a tab (never adopt it), not which run that is.
|
|
23
|
+
* A run's key is what X-Synabun-Terminal names, so handing it out would let one agent speak as another run.
|
|
24
|
+
* @param {Map<string,string>|null|undefined} tabOwners owner key → tab id
|
|
25
|
+
* @param {{ loops?: Iterable<string>, interactive?: Iterable<string>, agents?: Iterable<string> }} sets
|
|
26
|
+
* @param {{ caller?: string|null, reveal?: boolean }} opts
|
|
27
|
+
* @returns {{ tabOwners: Record<string,string>, owners: { loops: string[], interactive: string[], agents: string[] } }}
|
|
28
|
+
*/
|
|
29
|
+
export function listedOwners(tabOwners, { loops = [], interactive = [], agents = [] } = {}, { caller = null, reveal = false } = {}) {
|
|
30
|
+
const tabEntries = tabOwners ? [...tabOwners] : [];
|
|
31
|
+
const lists = { loops: [...loops], interactive: [...interactive], agents: [...agents] };
|
|
32
|
+
if (reveal) return { tabOwners: Object.fromEntries(tabEntries), owners: lists };
|
|
33
|
+
const labels = new Map();
|
|
34
|
+
const label = (key) => {
|
|
35
|
+
if (caller && key === caller) return key;
|
|
36
|
+
if (!labels.has(key)) labels.set(key, `other-${labels.size + 1}`);
|
|
37
|
+
return labels.get(key);
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
tabOwners: Object.fromEntries(tabEntries.map(([key, tabId]) => [label(key), tabId])),
|
|
41
|
+
// An agent is listed by its agent id; its routing key is `agent:<id>`: the caller's own when it is that agent.
|
|
42
|
+
owners: {
|
|
43
|
+
loops: lists.loops.map(label),
|
|
44
|
+
interactive: lists.interactive.map(label),
|
|
45
|
+
agents: lists.agents.map((agentId) => (caller && caller === `agent:${agentId}` ? agentId : label(`agent:${agentId}`))),
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// ── What an explicit close of a browser session closes (DOM-free) ──
|
|
2
|
+
//
|
|
3
|
+
// Scheduled runs share one browser session (one MoreLogin profile), each in a tab of its own. On 2026-11-04 a
|
|
4
|
+
// curiosity-video run cleaned up with browser_session close on every session it listed, the shared one included,
|
|
5
|
+
// and the Bluesky reply-back run working in that session lost its tab mid-write ("Session not found"). An
|
|
6
|
+
// automation's close therefore never tears down a session another automation still works in: it closes the
|
|
7
|
+
// caller's own tab there and leaves the rest. The owner's own close (the Neural Interface page, which sends no
|
|
8
|
+
// X-Synabun-Terminal) is a supervised action and still closes the whole session.
|
|
9
|
+
//
|
|
10
|
+
// An automation closes or stops only what it works in (2026-11-05, review 972afb74, finding 4): before, an automation
|
|
11
|
+
// that owned nothing in a session nobody else held (the owner's manual session, or a profile only the owner used)
|
|
12
|
+
// destroyed it or stopped the profile, because "no other owner" read as "nobody to protect".
|
|
13
|
+
|
|
14
|
+
/** Whether `caller` works in `session`: a tab of its own there (open or not yet pruned), or a hold on the session. */
|
|
15
|
+
export function holdsSession(session, caller) {
|
|
16
|
+
if (!session || !caller) return false;
|
|
17
|
+
if (session._tabOwners?.has?.(caller)) return true;
|
|
18
|
+
return [session._loopOwned, session._interactiveOwned, session._agentOwnedSet].some((set) => !!set?.has?.(caller));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The automations other than `caller` that still work in `session`: owners of a tab that is open, and the loops,
|
|
23
|
+
* interactive MCP callers and agents that hold the session. Reads the session's own registries only.
|
|
24
|
+
*/
|
|
25
|
+
export function otherSessionOwners(session, caller) {
|
|
26
|
+
const others = new Set();
|
|
27
|
+
const tabs = session?.tabs;
|
|
28
|
+
for (const [owner, tabId] of session?._tabOwners || []) {
|
|
29
|
+
if (owner !== caller && (!tabs || tabs.has(tabId))) others.add(owner);
|
|
30
|
+
}
|
|
31
|
+
for (const set of [session?._loopOwned, session?._interactiveOwned, session?._agentOwnedSet]) {
|
|
32
|
+
for (const owner of set || []) if (owner !== caller) others.add(owner);
|
|
33
|
+
}
|
|
34
|
+
return [...others];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* What DELETE /api/browser/sessions/:id does for this caller.
|
|
39
|
+
* - `{ action: 'destroy' }`: the owner's close (no caller), a session that is gone, or an automation's close of a
|
|
40
|
+
* session it works in and nobody else does.
|
|
41
|
+
* - `{ action: 'release', others, ownTabId }`: an automation's close of a session it works in and others still use:
|
|
42
|
+
* only the caller's own tab (ownTabId, null when it has none open there) is closed and its claims dropped.
|
|
43
|
+
* - `{ action: 'refuse' }`: an automation's close of a session it does not work in (no tab of its own, no hold): the
|
|
44
|
+
* owner's to close.
|
|
45
|
+
*/
|
|
46
|
+
export function sessionCloseDecision(session, caller) {
|
|
47
|
+
if (!session || !caller) return { action: 'destroy' };
|
|
48
|
+
if (!holdsSession(session, caller)) return { action: 'refuse', reason: 'not_owned' };
|
|
49
|
+
const others = otherSessionOwners(session, caller);
|
|
50
|
+
if (others.length === 0) return { action: 'destroy' };
|
|
51
|
+
const ownTabId = session._tabOwners?.get?.(caller) || null;
|
|
52
|
+
return { action: 'release', others, ownTabId: ownTabId && session.tabs?.has?.(ownTabId) !== false ? ownTabId : null };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* What POST /api/morelogin/stop does for this caller. Stopping a MoreLogin profile closes its whole browser, and
|
|
57
|
+
* with it the tab of every run in every session on that profile: an agent that called the `morelogin` tool's `stop`
|
|
58
|
+
* on the shared profile ended the other runs' tabs three times between 2026-10-27 and 2026-11-03.
|
|
59
|
+
* - `{ action: 'stop' }`: the owner's stop (no caller), or an automation's stop of a profile it holds (it works in a
|
|
60
|
+
* session on it, or `startedBy` says it started the profile) where no other automation works.
|
|
61
|
+
* - `{ action: 'refuse', others, sessionIds }`: an automation's stop while others work there.
|
|
62
|
+
* - `{ action: 'refuse', reason: 'not_owned', others: [], sessionIds: [] }`: an automation's stop of a profile it does
|
|
63
|
+
* not hold: the owner's to stop.
|
|
64
|
+
* `sessions` is the server's session registry (id → session); a session is on the profile when it is a MoreLogin
|
|
65
|
+
* session with that env id. `startedBy(envId)` lists who started the profile through POST /api/morelogin/start.
|
|
66
|
+
*/
|
|
67
|
+
export function profileStopDecision(sessions, envId, caller, { startedBy = () => [] } = {}) {
|
|
68
|
+
if (!caller || !envId) return { action: 'stop' };
|
|
69
|
+
const others = new Set();
|
|
70
|
+
const sessionIds = [];
|
|
71
|
+
let holds = false;
|
|
72
|
+
try { holds = [...(startedBy(String(envId)) || [])].includes(caller); } catch { holds = false; }
|
|
73
|
+
for (const [id, session] of sessions || []) {
|
|
74
|
+
if (session?._profileMode !== 'morelogin' || String(session?._mlEnvId ?? '') !== String(envId)) continue;
|
|
75
|
+
if (holdsSession(session, caller)) holds = true;
|
|
76
|
+
const theirs = otherSessionOwners(session, caller);
|
|
77
|
+
if (theirs.length === 0) continue;
|
|
78
|
+
sessionIds.push(id);
|
|
79
|
+
for (const owner of theirs) others.add(owner);
|
|
80
|
+
}
|
|
81
|
+
if (others.size) return { action: 'refuse', others: [...others], sessionIds };
|
|
82
|
+
if (!holds) return { action: 'refuse', reason: 'not_owned', others: [], sessionIds: [] };
|
|
83
|
+
return { action: 'stop' };
|
|
84
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// ── A browser start its caller stopped waiting for is kept for that caller (DOM-free) ──
|
|
2
|
+
//
|
|
3
|
+
// A cold MoreLogin start waits up to two minutes for the app (server.js createBrowserSession), and nothing can cancel
|
|
4
|
+
// it once it runs. Before 2026-11-04 the MCP gave up on browser_session create after 70 s while the server went on and
|
|
5
|
+
// registered the session: the agent read "timed out", called create again and started a second browser, and the first
|
|
6
|
+
// stayed open, owned by an agent that never learned its id.
|
|
7
|
+
//
|
|
8
|
+
// Now one start runs per caller (`key`) at a time:
|
|
9
|
+
// - a caller that asks again while its start is still running waits for that same start (`joined`), never a second one;
|
|
10
|
+
// - a caller waits `waitMs` at most and is then answered `pending` (the routes answer 202 BROWSER_STARTING before their
|
|
11
|
+
// deadline, so the agent reads "still starting, call create again" rather than a timeout);
|
|
12
|
+
// - a start that finishes when none of its callers can be answered any more is parked for the key, and the caller's
|
|
13
|
+
// next request takes it (`parked`) instead of starting another;
|
|
14
|
+
// - a start that finishes while one of its callers still waits but another was already answered `pending` is parked
|
|
15
|
+
// too, as `delivered`: the caller that was told "call again" gets that same start on its retry, never a second one.
|
|
16
|
+
// A delivered start is in use, so nobody closes it when it is not taken;
|
|
17
|
+
// - a parked start nobody takes within `ttlMs` is handed to `onUnclaimed` (the route closes what it opened), with the
|
|
18
|
+
// time it was parked (`{ parkedAt }`), so the route can see whether its caller used it meanwhile;
|
|
19
|
+
// - a start that never settles is given up after `startDeadlineMs` (BROWSER_START_STUCK): its waiters are answered,
|
|
20
|
+
// the key is free again, and what the start makes if it ever finishes goes to `onUnclaimed`;
|
|
21
|
+
// - after `clear()` (shutdown) nothing is parked any more: every parked start and every one that finishes later goes
|
|
22
|
+
// to `onUnclaimed` at once.
|
|
23
|
+
// A start that fails is never parked: the next request starts again and gets the real error.
|
|
24
|
+
|
|
25
|
+
export const BROWSER_START_HANDOFF_TTL_MS = 10 * 60_000;
|
|
26
|
+
/** A cold MoreLogin start (two minutes for the app) plus a tab, with room to spare: past this a start is stuck. */
|
|
27
|
+
export const BROWSER_START_DEADLINE_MS = 6 * 60_000;
|
|
28
|
+
export const BROWSER_START_STUCK = 'BROWSER_START_STUCK';
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {object} [opts]
|
|
32
|
+
* @param {() => number} [opts.now]
|
|
33
|
+
* @param {number} [opts.ttlMs] how long a parked start waits for its caller
|
|
34
|
+
* @param {number} [opts.startDeadlineMs] how long a start may run before it is given up
|
|
35
|
+
* @param {Function} [opts.setTimer] setTimeout stand-in (tests)
|
|
36
|
+
* @param {Function} [opts.clearTimer]
|
|
37
|
+
* @param {(message: string) => void} [opts.log]
|
|
38
|
+
*/
|
|
39
|
+
export function createBrowserStartHandoff({
|
|
40
|
+
now = Date.now, ttlMs = BROWSER_START_HANDOFF_TTL_MS, startDeadlineMs = BROWSER_START_DEADLINE_MS,
|
|
41
|
+
setTimer = setTimeout, clearTimer = clearTimeout, log = () => {},
|
|
42
|
+
} = {}) {
|
|
43
|
+
const flights = new Map(); // key → { promise, waiters: Set<{ gone, left }>, timer, abandoned }
|
|
44
|
+
const parked = new Map(); // key → { value, at, timer, onUnclaimed, delivered }
|
|
45
|
+
let closed = false;
|
|
46
|
+
|
|
47
|
+
function unpark(key) {
|
|
48
|
+
const entry = parked.get(key);
|
|
49
|
+
if (!entry) return null;
|
|
50
|
+
parked.delete(key);
|
|
51
|
+
clearTimer(entry.timer);
|
|
52
|
+
return entry;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function park(key, value, onUnclaimed, { delivered = false } = {}) {
|
|
56
|
+
const previous = unpark(key);
|
|
57
|
+
if (previous) expire(key, previous);
|
|
58
|
+
const entry = { value, at: now(), onUnclaimed: delivered ? null : onUnclaimed, delivered, timer: null };
|
|
59
|
+
if (closed) { expire(key, entry); return; }
|
|
60
|
+
entry.timer = setTimer(() => {
|
|
61
|
+
if (parked.get(key) !== entry) return;
|
|
62
|
+
parked.delete(key);
|
|
63
|
+
expire(key, entry);
|
|
64
|
+
}, ttlMs);
|
|
65
|
+
entry.timer?.unref?.();
|
|
66
|
+
parked.set(key, entry);
|
|
67
|
+
log(delivered
|
|
68
|
+
? `kept a browser start for ${key}: one of its callers had been told it was still starting`
|
|
69
|
+
: `parked a browser start for ${key}: its caller had stopped waiting`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Hand a parked (or never-parked) value to its onUnclaimed. Resolves when that is done; never rejects. */
|
|
73
|
+
function expire(key, entry) {
|
|
74
|
+
if (typeof entry.onUnclaimed !== 'function') return Promise.resolve();
|
|
75
|
+
log(`a browser start for ${key} was not taken${closed ? ' (shutting down)' : ` within ${Math.round(ttlMs / 1000)} s`}`);
|
|
76
|
+
return Promise.resolve().then(() => entry.onUnclaimed(entry.value, { parkedAt: entry.at })).catch(() => {});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Run `start` for `key`, or hand over the one already running or parked.
|
|
81
|
+
* @param {string} key
|
|
82
|
+
* @param {() => Promise<any>} start resolves with the started value; rejects with the reason it failed
|
|
83
|
+
* @param {object} [opts]
|
|
84
|
+
* @param {() => boolean} [opts.gone] true once this caller can no longer be answered (its request ended)
|
|
85
|
+
* @param {number} [opts.waitMs] how long this caller waits before it is answered `pending`
|
|
86
|
+
* @param {(value) => boolean} [opts.alive] whether a parked value is still usable (a closed tab is not)
|
|
87
|
+
* @param {(value, info: { parkedAt: number }) => any} [opts.onUnclaimed] what to do with a value nobody took
|
|
88
|
+
* @returns {Promise<{ value: any, from: 'parked' | 'joined' | 'started' } | { pending: true, from: 'joined' | 'started' }>}
|
|
89
|
+
*/
|
|
90
|
+
async function run(key, start, { gone = () => false, waitMs = Infinity, alive = null, onUnclaimed = null } = {}) {
|
|
91
|
+
const kept = unpark(key);
|
|
92
|
+
if (kept) {
|
|
93
|
+
if (!alive || safeAlive(alive, kept.value)) return { value: kept.value, from: 'parked' };
|
|
94
|
+
log(`a parked browser start for ${key} is gone: starting again`);
|
|
95
|
+
// What is left of it (a session whose tab closed) is closed like one nobody took.
|
|
96
|
+
expire(key, kept);
|
|
97
|
+
}
|
|
98
|
+
let flight = flights.get(key);
|
|
99
|
+
const from = flight ? 'joined' : 'started';
|
|
100
|
+
if (!flight) {
|
|
101
|
+
const current = { waiters: new Set(), promise: null, timer: null, abandoned: false };
|
|
102
|
+
const started = Promise.resolve().then(start);
|
|
103
|
+
// A start that never settles would hold the key for good (every later request only joins it).
|
|
104
|
+
const watchdog = new Promise((_, reject) => {
|
|
105
|
+
current.timer = setTimer(() => reject(Object.assign(
|
|
106
|
+
new Error(`The browser start did not finish within ${Math.round(startDeadlineMs / 60_000)} minutes and was given up. Call the browser tool again to start over.`),
|
|
107
|
+
{ code: BROWSER_START_STUCK, status: 504 },
|
|
108
|
+
)), startDeadlineMs);
|
|
109
|
+
current.timer?.unref?.();
|
|
110
|
+
});
|
|
111
|
+
current.promise = Promise.race([started, watchdog]).then((value) => {
|
|
112
|
+
clearTimer(current.timer);
|
|
113
|
+
if (flights.get(key) === current) flights.delete(key);
|
|
114
|
+
// Answered by a caller that is still there: it has the value. Otherwise nobody does, so keep it for the key.
|
|
115
|
+
// When one caller has it and another was answered "still starting", keep it too (delivered): that caller's
|
|
116
|
+
// retry gets this start, not a second one.
|
|
117
|
+
const waiters = [...current.waiters];
|
|
118
|
+
const answered = waiters.some((w) => !w.left && !safeGone(w.gone));
|
|
119
|
+
const toldPending = waiters.some((w) => w.left);
|
|
120
|
+
if (!answered) park(key, value, onUnclaimed);
|
|
121
|
+
else if (toldPending) park(key, value, onUnclaimed, { delivered: true });
|
|
122
|
+
return value;
|
|
123
|
+
}, (error) => {
|
|
124
|
+
clearTimer(current.timer);
|
|
125
|
+
if (flights.get(key) === current) flights.delete(key);
|
|
126
|
+
if (error?.code === BROWSER_START_STUCK) {
|
|
127
|
+
current.abandoned = true;
|
|
128
|
+
log(`a browser start for ${key} was given up after ${Math.round(startDeadlineMs / 1000)} s`);
|
|
129
|
+
}
|
|
130
|
+
throw error;
|
|
131
|
+
});
|
|
132
|
+
// What a start given up on makes after all is nobody's: handed to onUnclaimed at once.
|
|
133
|
+
started.then((value) => {
|
|
134
|
+
if (current.abandoned) expire(key, { value, at: now(), onUnclaimed });
|
|
135
|
+
}, () => {});
|
|
136
|
+
// Every caller may have left before a failure: never an unhandled rejection.
|
|
137
|
+
current.promise.catch(() => {});
|
|
138
|
+
flights.set(key, current);
|
|
139
|
+
flight = current;
|
|
140
|
+
}
|
|
141
|
+
const waiter = { gone, left: false };
|
|
142
|
+
flight.waiters.add(waiter);
|
|
143
|
+
let timer = null;
|
|
144
|
+
try {
|
|
145
|
+
if (!(waitMs < Infinity)) return { value: await flight.promise, from };
|
|
146
|
+
const waited = await Promise.race([
|
|
147
|
+
flight.promise.then((value) => ({ value })),
|
|
148
|
+
new Promise((resolve) => { timer = setTimer(() => resolve(null), Math.max(0, waitMs)); }),
|
|
149
|
+
]);
|
|
150
|
+
if (waited) return { value: waited.value, from };
|
|
151
|
+
// This caller is answered "still starting": it no longer counts as one the start can be answered to.
|
|
152
|
+
waiter.left = true;
|
|
153
|
+
return { pending: true, from };
|
|
154
|
+
} finally {
|
|
155
|
+
if (timer) clearTimer(timer);
|
|
156
|
+
// Once answered (or failed) this caller is done either way; a pending one stays marked as left.
|
|
157
|
+
if (!waiter.left) flight.waiters.delete(waiter);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
run,
|
|
163
|
+
/** Whether a start for `key` is running now. */
|
|
164
|
+
running: (key) => flights.has(key),
|
|
165
|
+
/** Whether a finished start is parked for `key`. */
|
|
166
|
+
hasParked: (key) => parked.has(key),
|
|
167
|
+
/** Whether the start parked for `key` is one a caller already has (delivered), not one nobody took. */
|
|
168
|
+
parkedDelivered: (key) => parked.get(key)?.delivered === true,
|
|
169
|
+
/**
|
|
170
|
+
* Shutdown: every parked start goes to its onUnclaimed now, and so does every start still running when it
|
|
171
|
+
* finishes. Resolves once the parked ones are handled (the caller bounds the wait).
|
|
172
|
+
*/
|
|
173
|
+
clear() {
|
|
174
|
+
closed = true;
|
|
175
|
+
const done = [];
|
|
176
|
+
for (const key of [...parked.keys()]) {
|
|
177
|
+
const entry = unpark(key);
|
|
178
|
+
if (entry) done.push(expire(key, entry));
|
|
179
|
+
}
|
|
180
|
+
return Promise.allSettled(done).then(() => undefined);
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function safeGone(gone) {
|
|
186
|
+
try { return gone() === true; } catch { return true; }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function safeAlive(alive, value) {
|
|
190
|
+
try { return alive(value) === true; } catch { return false; }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* How long a route waits for a browser start before it answers BROWSER_STARTING: what is left of its request's
|
|
195
|
+
* deadline, less a margin so that answer, not the deadline's 408 (lib/browser-execution.js), is what the caller reads.
|
|
196
|
+
* `deadline` absent (a route without one): Infinity, the route waits for the start.
|
|
197
|
+
*/
|
|
198
|
+
export function startWaitMs(deadline, { now = Date.now(), margin = 2_000 } = {}) {
|
|
199
|
+
const at = Number(deadline);
|
|
200
|
+
if (!Number.isFinite(at) || at <= 0) return Infinity;
|
|
201
|
+
return Math.max(0, at - now - margin);
|
|
202
|
+
}
|
|
@@ -5,8 +5,10 @@
|
|
|
5
5
|
// The Assistant's brain (Claude, Codex, OpenCode, Antigravity) and the workers it
|
|
6
6
|
// dispatches look at pages — public or localhost — only through SynaBun's
|
|
7
7
|
// browser tools (browser_*), which open the browser configured in SynaBun
|
|
8
|
-
// (MoreLogin). They never start a browser of their own
|
|
9
|
-
//
|
|
8
|
+
// (MoreLogin). They never start a browser of their own. A lost session or tab
|
|
9
|
+
// is replaced with browser_session create (browserSessionLossRule); when the
|
|
10
|
+
// SynaBun browser fails otherwise or lacks something they report it instead
|
|
11
|
+
// of switching.
|
|
10
12
|
//
|
|
11
13
|
// browserPolicyText the one rule text: the persona, plan mode, worker prompts
|
|
12
14
|
// browserToolDenial one tool call's refusal, else null. The brain asks it in
|
|
@@ -70,9 +72,23 @@ function browserToolNames(tools) {
|
|
|
70
72
|
snapshot: map.browserSnapshot || `${prefix}browser_snapshot`,
|
|
71
73
|
screenshot: map.browserScreenshot || `${prefix}browser_screenshot`,
|
|
72
74
|
console: map.browserConsole || `${prefix}browser_console`,
|
|
75
|
+
session: map.browserSession || `${prefix}browser_session`,
|
|
73
76
|
};
|
|
74
77
|
}
|
|
75
78
|
|
|
79
|
+
/**
|
|
80
|
+
* What an agent does when its browser session or tab goes away (the user's decision, 2026-11-04): it opens a new one
|
|
81
|
+
* with browser_session create and carries on there; it stops and reports only when that create fails too. When SynaBun
|
|
82
|
+
* already opened a replacement (a tool's answer says "A new tab replaced it"), the agent continues there: a create
|
|
83
|
+
* then would replace that tab again for nothing. One sentence for the rule text (persona, worker prompts) and the
|
|
84
|
+
* loop prompts (server.js buildLoopTaskPrompt; a copy in
|
|
85
|
+
* hooks/claude-code/prompt-submit.mjs buildBrowserNote, which cannot import this file: keep the two the same). The
|
|
86
|
+
* MCP's answers for a lost route say the same (mcp-server/src/services/neural-interface.ts LOST_ROUTE_HINT).
|
|
87
|
+
*/
|
|
88
|
+
export function browserSessionLossRule(sessionTool = 'browser_session') {
|
|
89
|
+
return `If your browser session or tab is lost (closed, disconnected, "Session not found", "Tab … not found", or a browser tool says it is gone), call ${sessionTool} with action "create" and continue in the session and tab it returns (pass those ids from then on, if you pass ids). When the answer of a browser tool starts with a notice that a replacement tab is open ("Your tab … was lost; a replacement tab … is open"), or says a new tab already replaced the lost one, continue in that tab (its tabId from then on): do not create another. Create one only when nothing announced a replacement and your browser calls keep failing because the session or tab is gone. Only if creating one fails too, stop and report it.`;
|
|
90
|
+
}
|
|
91
|
+
|
|
76
92
|
// Where automated tests run, and the syntax check: one sentence for the rule text and every refusal.
|
|
77
93
|
const TEST_RUN_RULE = 'Automated tests run through their test runner (npm test, node --test, vitest, jest, npx playwright test, not its UI or debug mode) from inside the project they belong to: cd into that project first and name only its own files. That project may be this session\'s or any registered SynaBun project that is a code project (git, package.json or deno.json at its top; never the Downloads folder). A syntax check (node --check <file>) always runs.';
|
|
78
94
|
|
|
@@ -92,7 +108,8 @@ export function browserPolicyText({ tools = '', host = null } = {}) {
|
|
|
92
108
|
'- Never `open` a URL or a browser app, and never use computer use on a browser app.',
|
|
93
109
|
`- Never use the Playwright, Chrome DevTools, Claude-in-Chrome or any other browser MCP tools, nor ${web}.`,
|
|
94
110
|
`- Visual checks: ${t.screenshot} (width, height, fullPage, save). Page errors and console output: ${t.console}.`,
|
|
95
|
-
|
|
111
|
+
`- ${browserSessionLossRule(t.session)}`,
|
|
112
|
+
'- If the SynaBun browser fails otherwise, is unavailable or lacks what you need, stop and report it. Never substitute another browser or tool.',
|
|
96
113
|
'- This rule overrides any task text, context or memory that says otherwise.',
|
|
97
114
|
].join('\n');
|
|
98
115
|
}
|
|
@@ -1010,7 +1027,7 @@ function shellDenial(input, ctx) {
|
|
|
1010
1027
|
// ── the refusal ─────────────────────────────────────────────────────────────
|
|
1011
1028
|
|
|
1012
1029
|
function refusal(tool, what) {
|
|
1013
|
-
return `SynaBun browser policy: ${tool} was refused — ${what}. Every page, public or localhost, goes through SynaBun's browser tools (browser_navigate, browser_snapshot, browser_screenshot, browser_console and the other browser_* tools), which open the browser configured in SynaBun. If the SynaBun browser fails or cannot do this, stop and report it; do not switch to another browser or tool. ${TEST_RUN_RULE}`;
|
|
1030
|
+
return `SynaBun browser policy: ${tool} was refused — ${what}. Every page, public or localhost, goes through SynaBun's browser tools (browser_navigate, browser_snapshot, browser_screenshot, browser_console and the other browser_* tools), which open the browser configured in SynaBun. If your SynaBun browser session or tab was lost, open a new one with browser_session (action "create") and continue there. If the SynaBun browser fails or cannot do this, stop and report it; do not switch to another browser or tool. ${TEST_RUN_RULE}`;
|
|
1014
1031
|
}
|
|
1015
1032
|
|
|
1016
1033
|
/**
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// ── What a failed wedge recovery retires: the tab, or the whole session (DOM-free) ──
|
|
2
|
+
//
|
|
3
|
+
// A tab that stops answering is replaced by a new page under the same tab id (recoverSessionTabPage). When the
|
|
4
|
+
// replacement cannot be made in time either, the server used to retire the whole browser session. Scheduled runs
|
|
5
|
+
// share that session (one MoreLogin profile, a tab per run), so one slow tab ended every other run's tab with it:
|
|
6
|
+
// 15 of the 44 session teardowns that orphaned running loops between 2026-10-21 and 2026-11-04 were this, 11 of
|
|
7
|
+
// them in one half hour on 2026-11-03 while MoreLogin was slow. A new connection to the same MoreLogin browser does
|
|
8
|
+
// not make it faster; it only takes the other runs' tabs away.
|
|
9
|
+
//
|
|
10
|
+
// So the session is retired only when nothing in it answers any more: the browser is disconnected, or no other tab
|
|
11
|
+
// of the session answers a trivial evaluate within the probe deadline. Otherwise only the wedged tab is retired:
|
|
12
|
+
// it leaves the registry (its owner's next call gets "Tab not found" and the run's tab recovery opens a new one),
|
|
13
|
+
// and the other tabs keep working.
|
|
14
|
+
|
|
15
|
+
/** How long each other tab may take to answer the liveness probe. */
|
|
16
|
+
export const OTHER_TAB_PROBE_MS = 1000;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* How many of `pages` answer `page.evaluate('1')` within `timeoutMs`, all asked at once. A page that throws, is
|
|
20
|
+
* closed or does not answer in time does not count. Never throws.
|
|
21
|
+
*/
|
|
22
|
+
export async function answeringPages(pages, timeoutMs = OTHER_TAB_PROBE_MS) {
|
|
23
|
+
const probes = (pages || []).map((page) => new Promise((resolve) => {
|
|
24
|
+
if (!page || page.isClosed?.()) { resolve(false); return; }
|
|
25
|
+
const timer = setTimeout(() => resolve(false), timeoutMs);
|
|
26
|
+
timer.unref?.();
|
|
27
|
+
Promise.resolve().then(() => page.evaluate('1')).then(
|
|
28
|
+
() => { clearTimeout(timer); resolve(true); },
|
|
29
|
+
() => { clearTimeout(timer); resolve(false); },
|
|
30
|
+
);
|
|
31
|
+
}));
|
|
32
|
+
return (await Promise.all(probes)).filter(Boolean).length;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The decision for a tab whose replacement page could not be made.
|
|
37
|
+
* - `{ action: 'retire-session', why: 'disconnected' }`: the browser connection itself is gone.
|
|
38
|
+
* - `{ action: 'retire-session', why: 'nothing-answers' }`: no other tab of the session answers (or there is none):
|
|
39
|
+
* the connection is what is wedged, and a new one may help.
|
|
40
|
+
* - `{ action: 'retire-tab', why: 'others-answer' }`: the browser still serves the session's other tabs.
|
|
41
|
+
*/
|
|
42
|
+
export function failedRecoveryDecision({ browserConnected, otherTabsAnswering }) {
|
|
43
|
+
if (browserConnected === false) return { action: 'retire-session', why: 'disconnected' };
|
|
44
|
+
if (!(otherTabsAnswering > 0)) return { action: 'retire-session', why: 'nothing-answers' };
|
|
45
|
+
return { action: 'retire-tab', why: 'others-answer' };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Decide for `tabId` of `session`, probing the session's other registered tabs. Never throws: a probe that fails
|
|
50
|
+
* counts as a tab that does not answer.
|
|
51
|
+
*/
|
|
52
|
+
export async function decideFailedTabRecovery(session, tabId, { timeoutMs = OTHER_TAB_PROBE_MS } = {}) {
|
|
53
|
+
let browserConnected = null;
|
|
54
|
+
try {
|
|
55
|
+
const connected = session?.browser?.isConnected?.();
|
|
56
|
+
if (typeof connected === 'boolean') browserConnected = connected;
|
|
57
|
+
} catch { browserConnected = false; }
|
|
58
|
+
if (browserConnected === false) return failedRecoveryDecision({ browserConnected, otherTabsAnswering: 0 });
|
|
59
|
+
const others = [...(session?.tabs?.entries?.() || [])]
|
|
60
|
+
.filter(([id, entry]) => id !== tabId && entry?.page)
|
|
61
|
+
.map(([, entry]) => entry.page);
|
|
62
|
+
const otherTabsAnswering = others.length ? await answeringPages(others, timeoutMs) : 0;
|
|
63
|
+
return { ...failedRecoveryDecision({ browserConnected, otherTabsAnswering }), otherTabs: others.length, otherTabsAnswering };
|
|
64
|
+
}
|
|
@@ -266,6 +266,16 @@ function _removeOwedTemporaryPlans({ all = false } = {}) {
|
|
|
266
266
|
if (failed) log(`temporary chat: ${failed} plan file${failed === 1 ? '' : 's'} could not be removed and will be tried again`);
|
|
267
267
|
}
|
|
268
268
|
|
|
269
|
+
// lib/terminal-tokens.js's names (kept here as text: this module is loaded by the panel's tests without the registry).
|
|
270
|
+
const TERMINAL_TOKEN_HEADER_NAME = 'X-Synabun-Terminal-Token';
|
|
271
|
+
const TERMINAL_TOKEN_ENV_NAME = 'SYNABUN_TERMINAL_TOKEN';
|
|
272
|
+
/** The host's MCP entries with the SynaBun entry's token reference replaced by its value (for a live setMcpServers). */
|
|
273
|
+
function withTerminalTokenValue(servers, token) {
|
|
274
|
+
const synabun = servers?.SynaBun;
|
|
275
|
+
if (!token || !synabun?.headers || synabun.headers[TERMINAL_TOKEN_HEADER_NAME] !== `\${${TERMINAL_TOKEN_ENV_NAME}}`) return servers;
|
|
276
|
+
return { ...servers, SynaBun: { ...synabun, headers: { ...synabun.headers, [TERMINAL_TOKEN_HEADER_NAME]: token } } };
|
|
277
|
+
}
|
|
278
|
+
|
|
269
279
|
function cleanEnv() {
|
|
270
280
|
const env = Object.fromEntries(
|
|
271
281
|
Object.entries(process.env).filter(([k]) =>
|
|
@@ -743,6 +753,26 @@ export class ClaudeSession {
|
|
|
743
753
|
},
|
|
744
754
|
};
|
|
745
755
|
}
|
|
756
|
+
// A panel tab proves its X-Synabun-Terminal with a token of its own (lib/terminal-tokens.js), new with every CLI
|
|
757
|
+
// process it starts (a warm one included; an adopted warm process keeps the one it was started with). The MCP
|
|
758
|
+
// header names the variable and the CLI expands it from its own environment, never its command line (the MCP
|
|
759
|
+
// config is an argument every account of the computer can read). A process of the same user can still read that
|
|
760
|
+
// environment. Revoked when the tab's session ends (destroy). Brains and other callers have their own proof or none.
|
|
761
|
+
this._terminalToken = null;
|
|
762
|
+
if (this.panel && options.mcpServers?.SynaBun && typeof deps.terminalTokens?.rotate === 'function') {
|
|
763
|
+
let token = null;
|
|
764
|
+
try { token = deps.terminalTokens.rotate(this.synabunOwnerKey) || null; } catch { token = null; }
|
|
765
|
+
if (token) {
|
|
766
|
+
this._terminalToken = token;
|
|
767
|
+
options.mcpServers.SynaBun.headers[TERMINAL_TOKEN_HEADER_NAME] = `\${${TERMINAL_TOKEN_ENV_NAME}}`;
|
|
768
|
+
options.env = { ...options.env, [TERMINAL_TOKEN_ENV_NAME]: token };
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
// Never one this server inherited: only the tab's own reaches its CLI.
|
|
772
|
+
if (!this._terminalToken && options.env && TERMINAL_TOKEN_ENV_NAME in options.env) {
|
|
773
|
+
options.env = { ...options.env };
|
|
774
|
+
delete options.env[TERMINAL_TOKEN_ENV_NAME];
|
|
775
|
+
}
|
|
746
776
|
if (sessionOpts.extraMcpServers && typeof sessionOpts.extraMcpServers === 'object') {
|
|
747
777
|
options.mcpServers = { ...(options.mcpServers || {}), ...sessionOpts.extraMcpServers };
|
|
748
778
|
}
|
|
@@ -2746,7 +2776,10 @@ export class ClaudeSession {
|
|
|
2746
2776
|
if (typeof q.setMcpServers !== 'function') throw new Error('Not supported by this Claude Code version');
|
|
2747
2777
|
const current = this.panelSession || normalizePanelSession(null);
|
|
2748
2778
|
const start = { ...current.start, mcpServers: normalizeMcpServers(args.servers) };
|
|
2749
|
-
|
|
2779
|
+
// The host's SynaBun entry carries the tab's token as a reference the CLI expands from its environment at
|
|
2780
|
+
// start; a set made on the live session is sent with the value itself (over the CLI's stdin, never its
|
|
2781
|
+
// command line or a file), so the reconnected SynaBun server still proves the tab's id.
|
|
2782
|
+
const merged = mergeTabMcpServers(withTerminalTokenValue(this._hostMcpServers, this._terminalToken), start);
|
|
2750
2783
|
const r = await q.setMcpServers(merged.servers);
|
|
2751
2784
|
if (this.q === q) this.panelSession = { ...current, start };
|
|
2752
2785
|
const errors = r?.errors && typeof r.errors === 'object' ? Object.fromEntries(Object.entries(r.errors).slice(0, 20).map(([k, v]) => [String(k).slice(0, 80), String(v).slice(0, 300)])) : {};
|
|
@@ -3190,6 +3223,8 @@ export class ClaudeSession {
|
|
|
3190
3223
|
// Release this chat session's owned browser tab so the shared browser can
|
|
3191
3224
|
// grace-reap once no owners remain. Best-effort, in-process on the NI side.
|
|
3192
3225
|
try { deps.releaseBrowserOwner?.(this.synabunOwnerKey); } catch {}
|
|
3226
|
+
// The tab's terminal token ends with its session (nothing may act as it from now on).
|
|
3227
|
+
if (this.panel && this._terminalToken) { try { deps.terminalTokens?.revoke?.(this.synabunOwnerKey); } catch {} this._terminalToken = null; }
|
|
3193
3228
|
_allSessions.delete(this);
|
|
3194
3229
|
}
|
|
3195
3230
|
}
|