synabun 2.3.1 → 2.4.1
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 +41 -0
- package/README.md +1 -1
- package/browser-extension/content.js +189 -0
- package/browser-extension/engine.js +508 -0
- package/browser-extension/icons/icon-128.png +0 -0
- package/browser-extension/icons/icon-16.png +0 -0
- package/browser-extension/icons/icon-32.png +0 -0
- package/browser-extension/icons/icon-48.png +0 -0
- package/browser-extension/icons/status-off-16.png +0 -0
- package/browser-extension/icons/status-off-32.png +0 -0
- package/browser-extension/icons/status-off-48.png +0 -0
- package/browser-extension/icons/status-on-16.png +0 -0
- package/browser-extension/icons/status-on-32.png +0 -0
- package/browser-extension/icons/status-on-48.png +0 -0
- package/browser-extension/manifest.json +56 -0
- package/browser-extension/popup-strings.js +250 -0
- package/browser-extension/popup-view.js +151 -0
- package/browser-extension/popup.css +166 -0
- package/browser-extension/popup.html +108 -0
- package/browser-extension/popup.js +359 -0
- package/browser-extension/protocol.js +232 -0
- package/browser-extension/service-worker.js +275 -0
- package/browser-extension/setup-content.js +36 -0
- package/browser-extension/tokens.css +326 -0
- package/docs/browser-extension-bridge.md +84 -0
- package/docs/whatsapp.md +1 -1
- package/lib/data-home-files.js +45 -0
- package/lib/data-home-migration.js +34 -58
- package/mcp-server/dist/http.d.ts +2 -0
- package/mcp-server/dist/http.d.ts.map +1 -1
- package/mcp-server/dist/http.js +9 -1
- package/mcp-server/dist/http.js.map +1 -1
- package/mcp-server/dist/index.d.ts +11 -0
- package/mcp-server/dist/index.d.ts.map +1 -1
- package/mcp-server/dist/index.js +38 -3
- package/mcp-server/dist/index.js.map +1 -1
- package/mcp-server/dist/services/browser-route-flow.d.ts +6 -2
- package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
- package/mcp-server/dist/services/browser-route-flow.js +10 -3
- package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
- package/mcp-server/dist/services/codex-config-heal.d.ts.map +1 -1
- package/mcp-server/dist/services/codex-config-heal.js +7 -0
- package/mcp-server/dist/services/codex-config-heal.js.map +1 -1
- package/mcp-server/dist/services/neural-interface.d.ts +95 -3
- package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
- package/mcp-server/dist/services/neural-interface.js +168 -23
- package/mcp-server/dist/services/neural-interface.js.map +1 -1
- package/mcp-server/dist/services/team-context.d.ts +18 -0
- package/mcp-server/dist/services/team-context.d.ts.map +1 -0
- package/mcp-server/dist/services/team-context.js +29 -0
- package/mcp-server/dist/services/team-context.js.map +1 -0
- package/mcp-server/dist/services/tool-catalog.d.ts +5 -2
- package/mcp-server/dist/services/tool-catalog.d.ts.map +1 -1
- package/mcp-server/dist/services/tool-catalog.js +22 -6
- package/mcp-server/dist/services/tool-catalog.js.map +1 -1
- package/mcp-server/dist/services/tool-list.d.ts.map +1 -1
- package/mcp-server/dist/services/tool-list.js +4 -0
- package/mcp-server/dist/services/tool-list.js.map +1 -1
- package/mcp-server/dist/services/tool-runtime.d.ts +8 -1
- package/mcp-server/dist/services/tool-runtime.d.ts.map +1 -1
- package/mcp-server/dist/services/tool-runtime.js +18 -1
- package/mcp-server/dist/services/tool-runtime.js.map +1 -1
- package/mcp-server/dist/tools/agent-definition.d.ts +133 -0
- package/mcp-server/dist/tools/agent-definition.d.ts.map +1 -0
- package/mcp-server/dist/tools/agent-definition.js +483 -0
- package/mcp-server/dist/tools/agent-definition.js.map +1 -0
- package/mcp-server/dist/tools/agents.d.ts +92 -9
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +163 -20
- package/mcp-server/dist/tools/agents.js.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts +8 -1
- package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
- package/mcp-server/dist/tools/browser-advanced.js +70 -6
- package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
- package/mcp-server/dist/tools/git-tools.d.ts +4 -2
- package/mcp-server/dist/tools/git-tools.d.ts.map +1 -1
- package/mcp-server/dist/tools/git-tools.js +283 -2
- package/mcp-server/dist/tools/git-tools.js.map +1 -1
- package/mcp-server/dist/tools/morelogin.d.ts +8 -2
- package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
- package/mcp-server/dist/tools/morelogin.js +22 -5
- package/mcp-server/dist/tools/morelogin.js.map +1 -1
- package/mcp-server/dist/tools/team.d.ts +32 -0
- package/mcp-server/dist/tools/team.d.ts.map +1 -0
- package/mcp-server/dist/tools/team.js +87 -0
- package/mcp-server/dist/tools/team.js.map +1 -0
- package/mcp-server/package-lock.json +2 -2
- package/mcp-server/package.json +1 -1
- package/mcp-server/src/http.ts +9 -1
- package/mcp-server/src/index.ts +34 -4
- package/mcp-server/src/services/browser-route-flow.ts +12 -5
- package/mcp-server/src/services/codex-config-heal.ts +7 -0
- package/mcp-server/src/services/neural-interface.ts +191 -29
- package/mcp-server/src/services/team-context.ts +27 -0
- package/mcp-server/src/services/tool-catalog.ts +26 -8
- package/mcp-server/src/services/tool-list.ts +4 -0
- package/mcp-server/src/services/tool-runtime.ts +21 -2
- package/mcp-server/src/tools/agent-definition.ts +458 -0
- package/mcp-server/src/tools/agents.ts +177 -19
- package/mcp-server/src/tools/browser-advanced.ts +60 -6
- package/mcp-server/src/tools/git-tools.ts +249 -3
- package/mcp-server/src/tools/morelogin.ts +20 -5
- package/mcp-server/src/tools/team.ts +97 -0
- package/neural-interface/i18n/en.json +1119 -47
- package/neural-interface/i18n/pt-BR.json +1119 -47
- package/neural-interface/lib/account-usage.js +1 -1
- package/neural-interface/lib/agents/builtins.json +207 -0
- package/neural-interface/lib/agents/density.js +101 -0
- package/neural-interface/lib/agents/forge-host.js +223 -0
- package/neural-interface/lib/agents/native-export-targets.js +190 -0
- package/neural-interface/lib/agents/native-export.js +365 -0
- package/neural-interface/lib/agents/registry.js +885 -0
- package/neural-interface/lib/agents/resolve.js +603 -0
- package/neural-interface/lib/agents/schema.js +642 -0
- package/neural-interface/lib/agents/split.js +37 -0
- package/neural-interface/lib/agents-studio-api.js +591 -0
- package/neural-interface/lib/assistant-api.js +76 -7
- package/neural-interface/lib/assistant-brains/opencode.js +60 -11
- package/neural-interface/lib/assistant-catalog.js +2 -0
- package/neural-interface/lib/assistant-continuity.js +49 -0
- package/neural-interface/lib/assistant-dispatch.js +351 -121
- package/neural-interface/lib/assistant-persona.js +105 -8
- package/neural-interface/lib/assistant-route-gate.js +24 -9
- package/neural-interface/lib/assistant-router.js +432 -47
- package/neural-interface/lib/assistant-run-tail.js +151 -0
- package/neural-interface/lib/assistant-run-wait.js +183 -0
- package/neural-interface/lib/assistant-runtime.js +449 -94
- package/neural-interface/lib/assistant-task-prompt.js +11 -2
- package/neural-interface/lib/assistant-usage.js +3 -2
- package/neural-interface/lib/automation-approval.js +2 -2
- package/neural-interface/lib/backup-service.js +64 -105
- package/neural-interface/lib/browser-close-evidence.js +80 -0
- package/neural-interface/lib/browser-default.js +210 -0
- package/neural-interface/lib/browser-extension-adapter.js +264 -0
- package/neural-interface/lib/browser-extension-bridge.js +441 -0
- package/neural-interface/lib/browser-extension-folder.js +116 -0
- package/neural-interface/lib/browser-extension-setup.js +140 -0
- package/neural-interface/lib/browser-profile-choices.js +3 -3
- package/neural-interface/lib/browser-tool-policy.js +1 -1
- package/neural-interface/lib/claude-account-links.js +301 -0
- package/neural-interface/lib/claude-accounts.js +45 -20
- package/neural-interface/lib/claude-agent-bridge.js +142 -10
- package/neural-interface/lib/claude-model-catalog.js +6 -0
- package/neural-interface/lib/claude-panel-session.js +33 -0
- package/neural-interface/lib/codex-accounts.js +67 -24
- package/neural-interface/lib/coordination/README.md +384 -0
- package/neural-interface/lib/coordination/service.js +563 -0
- package/neural-interface/lib/coordination/store.js +1138 -0
- package/neural-interface/lib/db.js +22 -1
- package/neural-interface/lib/effort-levels.js +10 -1
- package/neural-interface/lib/memory-list-page.js +49 -0
- package/neural-interface/lib/memory-list-stamp.js +60 -0
- package/neural-interface/lib/morelogin-outside-close.js +186 -0
- package/neural-interface/lib/morelogin-profile-failures.js +206 -0
- package/neural-interface/lib/morelogin-start-cooldown.js +160 -0
- package/neural-interface/lib/morelogin.js +194 -8
- package/neural-interface/lib/native-loop-runtime.js +26 -7
- package/neural-interface/lib/opencode-build-preflight.js +28 -8
- package/neural-interface/lib/opencode-native-boundary.js +83 -13
- package/neural-interface/lib/opencode-serve-records.js +14 -9
- package/neural-interface/lib/page-session.js +1 -1
- package/neural-interface/lib/peer-identity.js +73 -29
- package/neural-interface/lib/process-identity.js +68 -7
- package/neural-interface/lib/request-gate.js +3 -0
- package/neural-interface/lib/screenshot-location.js +33 -0
- package/neural-interface/lib/session-cache-builder.js +41 -3
- package/neural-interface/lib/skills/creation.js +1 -1
- package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
- package/neural-interface/lib/studio-attention.js +56 -0
- package/neural-interface/lib/teams/README.md +382 -0
- package/neural-interface/lib/teams/api.js +287 -0
- package/neural-interface/lib/teams/brief.js +185 -0
- package/neural-interface/lib/teams/claims.js +315 -0
- package/neural-interface/lib/teams/git.js +293 -0
- package/neural-interface/lib/teams/index.js +122 -0
- package/neural-interface/lib/teams/integration.js +580 -0
- package/neural-interface/lib/teams/landing.js +184 -0
- package/neural-interface/lib/teams/recovery.js +256 -0
- package/neural-interface/lib/teams/scheduler.js +1474 -0
- package/neural-interface/lib/teams/schema.js +559 -0
- package/neural-interface/lib/teams/state.js +181 -0
- package/neural-interface/lib/teams/test-runner.js +86 -0
- package/neural-interface/lib/teams/test-sandbox.js +99 -0
- package/neural-interface/lib/teams/worktrees.js +757 -0
- package/neural-interface/lib/tool-permission-choices.js +226 -0
- package/neural-interface/lib/whatsapp/cards.js +24 -10
- package/neural-interface/lib/worker-confinement.js +206 -6
- package/neural-interface/package-lock.json +2 -2
- package/neural-interface/package.json +1 -1
- package/neural-interface/public/extension-setup.html +107 -0
- package/neural-interface/public/index.html +103 -12
- package/neural-interface/public/offline.html +4 -3
- package/neural-interface/public/shared/agent-runtime-options.js +3 -1
- package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
- package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
- package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
- package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
- package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
- package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
- package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
- package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
- package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
- package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
- package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
- package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
- package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
- package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
- package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
- package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
- package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
- package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
- package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
- package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
- package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
- package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
- package/neural-interface/public/shared/agy/agy-panel.js +142 -28
- package/neural-interface/public/shared/agy/agy-styles.js +25 -5
- package/neural-interface/public/shared/api.js +2 -1
- package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
- package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
- package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
- package/neural-interface/public/shared/assistant/asst-control.js +3 -0
- package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
- package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
- package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
- package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
- package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
- package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
- package/neural-interface/public/shared/assistant/asst-render.js +37 -6
- package/neural-interface/public/shared/assistant/asst-route.js +80 -12
- package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
- package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
- package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
- package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
- package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
- package/neural-interface/public/shared/assistant/asst-state.js +66 -1
- package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
- package/neural-interface/public/shared/assistant/route-identity.js +16 -0
- package/neural-interface/public/shared/cc-dropdown.js +21 -15
- package/neural-interface/public/shared/cdx/cdx-output.js +10 -0
- package/neural-interface/public/shared/cdx/cdx-panel.js +18 -16
- package/neural-interface/public/shared/cdx/cdx-plan.js +3 -2
- package/neural-interface/public/shared/cdx/cdx-render.js +122 -45
- package/neural-interface/public/shared/cdx/cdx-requests.js +4 -4
- package/neural-interface/public/shared/cdx/cdx-styles.js +8 -36
- package/neural-interface/public/shared/cdx/cdx-tabs.js +110 -42
- package/neural-interface/public/shared/claude-panel-lazy.js +12 -0
- package/neural-interface/public/shared/code-copy.js +120 -0
- package/neural-interface/public/shared/constants.js +7 -0
- package/neural-interface/public/shared/context-menu-model.js +1 -0
- package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
- package/neural-interface/public/shared/cp/cp-session-model.js +86 -5
- package/neural-interface/public/shared/cp/cp-session-settings.js +58 -30
- package/neural-interface/public/shared/cp/cp-styles.js +9 -0
- package/neural-interface/public/shared/dom-change-flag.js +66 -0
- package/neural-interface/public/shared/dom-morph.js +124 -0
- package/neural-interface/public/shared/extension-setup/es-page.css +134 -0
- package/neural-interface/public/shared/extension-setup/es-page.js +120 -0
- package/neural-interface/public/shared/extension-setup/es-view.js +100 -0
- package/neural-interface/public/shared/html-shell.js +34 -4
- package/neural-interface/public/shared/i18n.js +14 -1
- package/neural-interface/public/shared/idle-queue.js +78 -0
- package/neural-interface/public/shared/iface-config.js +227 -0
- package/neural-interface/public/shared/lazy-module.js +108 -0
- package/neural-interface/public/shared/memory-list.js +117 -0
- package/neural-interface/public/shared/morelogin-profile-choices.js +1 -1
- package/neural-interface/public/shared/morelogin-profile-field.js +3 -3
- package/neural-interface/public/shared/mtc/mtc-panel.js +3 -1
- package/neural-interface/public/shared/mtc/mtc-styles.js +4 -1
- package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +35 -15
- package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +77 -23
- package/neural-interface/public/shared/ocp-v2/ocp-v2-projectbar.js +3 -6
- package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +24 -21
- package/neural-interface/public/shared/ocp-v2/ocp-v2-send-logic.js +16 -5
- package/neural-interface/public/shared/ocp-v2/ocp-v2-sessions-logic.js +16 -2
- package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -43
- package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +73 -9
- package/neural-interface/public/shared/owner-authority-view.js +4 -10
- package/neural-interface/public/shared/page-session.js +1 -1
- package/neural-interface/public/shared/schedules-view.js +2 -2
- package/neural-interface/public/shared/session-project-items.js +11 -0
- package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
- package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
- package/neural-interface/public/shared/settings/settings-ia.js +4 -2
- package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
- package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
- package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
- package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
- package/neural-interface/public/shared/sidepanel-shown.js +73 -0
- package/neural-interface/public/shared/start-bridge.js +2 -2
- package/neural-interface/public/shared/storage.js +6 -1
- package/neural-interface/public/shared/studio-attention.js +83 -0
- package/neural-interface/public/shared/styles.css +694 -50
- package/neural-interface/public/shared/term-browser-tabs.js +34 -0
- package/neural-interface/public/shared/transcript-rows.js +334 -0
- package/neural-interface/public/shared/tray-auto-close.js +106 -0
- package/neural-interface/public/shared/ui-agents.js +97 -0
- package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
- package/neural-interface/public/shared/ui-automation-studio.js +3 -3
- package/neural-interface/public/shared/ui-claude-panel.js +162 -95
- package/neural-interface/public/shared/ui-code-copy.js +256 -0
- package/neural-interface/public/shared/ui-codex-panel.js +14 -10
- package/neural-interface/public/shared/ui-context-menu.js +1 -1
- package/neural-interface/public/shared/ui-file-explorer.js +2 -3
- package/neural-interface/public/shared/ui-games.js +1 -1
- package/neural-interface/public/shared/ui-loading.js +83 -19
- package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
- package/neural-interface/public/shared/ui-menubar.js +23 -0
- package/neural-interface/public/shared/ui-native-loop-router.js +50 -21
- package/neural-interface/public/shared/ui-navbar.js +15 -9
- package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
- package/neural-interface/public/shared/ui-owner-authority.js +48 -25
- package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
- package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
- package/neural-interface/public/shared/ui-sessions.js +3 -3
- package/neural-interface/public/shared/ui-settings-entry.js +55 -0
- package/neural-interface/public/shared/ui-settings.js +363 -400
- package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
- package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
- package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
- package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
- package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
- package/neural-interface/public/shared/ui-styleguide.js +10 -2
- package/neural-interface/public/shared/ui-sync.js +6 -0
- package/neural-interface/public/shared/ui-terminal.js +13 -9
- package/neural-interface/public/shared/ui-tooltip.js +28 -7
- package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
- package/neural-interface/public/shared/ui-tray-columns.js +375 -0
- package/neural-interface/public/shared/ui-whiteboard.js +51 -6
- package/neural-interface/public/shared/ui-worker-end.js +28 -1
- package/neural-interface/public/shared/ui-workspaces.js +13 -0
- package/neural-interface/public/shared/window-keys.js +71 -0
- package/neural-interface/public/sw.js +4 -3
- package/neural-interface/public/variant/2d/main.js +2 -0
- package/neural-interface/public/variant/3d/app.js +620 -0
- package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
- package/neural-interface/public/variant/3d/main.js +30 -544
- package/neural-interface/public/variant/3d/map-controls.js +4 -2
- package/neural-interface/public/vendor/fonts/fonts.css +508 -0
- package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
- package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
- package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/manifest.json +142 -0
- package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
- package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
- package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
- package/neural-interface/scripts/boot-graph.mjs +270 -0
- package/neural-interface/scripts/vendor-fonts.mjs +124 -0
- package/neural-interface/server.js +1083 -164
- package/npm-shrinkwrap.json +2 -2
- package/package.json +4 -1
- package/skills/agent-forge/SKILL.md +182 -0
- package/skills/agent-forge/evals/evals.json +56 -0
- package/skills/agent-forge/references/definition-fields.md +61 -0
- package/skills/agent-forge/references/examples.md +105 -0
- package/skills/agent-forge/references/instructions.md +51 -0
- package/skills/agent-forge/references/review-and-export.md +84 -0
|
@@ -37,6 +37,7 @@ import { createProviderPanelTerminalAuth, providerLoginSpec, registerProviderPan
|
|
|
37
37
|
import { claudeLegacyPricing, claudeUsageCostUsd } from './lib/assistant-pricing.js';
|
|
38
38
|
import { HOOK_SCRIPTS, hookDefinitionsForEvent, hookCommandString, hookInstallBlocker, hookInstallPlan, isSynaBunHookCommand, sweepSettingsHooks, ensureHookRoot } from '../lib/claude-hooks.js';
|
|
39
39
|
import { claudeHooksStatus } from './lib/claude-hooks-status.js';
|
|
40
|
+
import { createToolPermissionChoices, reconcileToolPermissions, TOOL_CHOICES_FILE } from './lib/tool-permission-choices.js';
|
|
40
41
|
import { createBrowserStartHandoff, startWaitMs } from './lib/browser-start-handoff.js';
|
|
41
42
|
import { browserRequestDeadline, browserV2Enabled, browserRequestMiddleware, assertBrowserRequestActive, browserActionTimeout, markBrowserActionStarted, runBrowserRequest, cancellableBrowserDelay, measureBrowserPhase, createEngagementScheduler, engagementTargetSelector, isEngagementWriteSelector, isXShortcutPublish, isXScriptedWrite } from './lib/browser-execution.js';
|
|
42
43
|
import { sessionCloseDecision, profileStopDecision, otherSessionOwners } from './lib/browser-session-close.js';
|
|
@@ -44,6 +45,7 @@ import { isAutomationBrowserRoute, ownerOnlyCreateFields } from './lib/browser-a
|
|
|
44
45
|
import { withOnDeviceModelBlocked } from './lib/chromium-on-device-model.js';
|
|
45
46
|
import { browserOwnerId, listedOwners } from './lib/browser-owner.js';
|
|
46
47
|
import { createProfileChoiceStore, resolveProfileRef } from './lib/browser-profile-choices.js';
|
|
48
|
+
import { createProfileFailureStore, namesFailedProfile, profileSwitchBarError, profileSwitchDecision } from './lib/morelogin-profile-failures.js';
|
|
47
49
|
import { scheduleReview, templateReview, sameDigest, scheduleMarked, templateMarked, clearScheduleMark, clearTemplateMark, markRecordsUnreviewed, REVIEW_CHANGED, UNREVIEWED_SOURCES } from './lib/automation-approval.js';
|
|
48
50
|
import { AGENT_PROFILES_KEY, PROFILE_NOT_ALLOWED, normalizeAgentProfiles, agentProfileAllowed, withAgentProfile, profileNotAllowedError, pinUseRefusal, scheduleProfileAuthority, scheduleProfileRefusalText, describeProfile, profileKindLabel } from './lib/morelogin-agent-profiles.js';
|
|
49
51
|
import { createTerminalTokenRegistry, TERMINAL_TOKEN_ENV, TERMINAL_TOKEN_HEADER, BRAIN_CREDENTIAL_HEADER, redactTerminalSecrets, logIdOf } from './lib/terminal-tokens.js';
|
|
@@ -194,6 +196,7 @@ import { OPENCODE_MIN_VERSION, basicAuthHeader, checkPrivateOpencodeServer as ch
|
|
|
194
196
|
import { SERVE_TOKEN_ENV } from './lib/process-identity.js';
|
|
195
197
|
import { commandArgs, createServeRecords } from './lib/opencode-serve-records.js';
|
|
196
198
|
import { opencode2Proxy } from './lib/opencode2-proxy.js';
|
|
199
|
+
import { macScreenshotDir } from './lib/screenshot-location.js';
|
|
197
200
|
import { integrationCredentialIds, integrationsWithCredentials } from './lib/opencode2-translate.js';
|
|
198
201
|
import { OPENCODE_SESSION_TABLES, hasOpencodeSessionTables } from './lib/opencode-db-schema.js';
|
|
199
202
|
import {
|
|
@@ -226,7 +229,7 @@ import {
|
|
|
226
229
|
} from './lib/native-loop-providers.js';
|
|
227
230
|
import { createOpenCodeActivityRelay } from './lib/opencode-worker-activity.js';
|
|
228
231
|
import { browserServePortDenial, browserSessionLossRule } from './lib/browser-tool-policy.js';
|
|
229
|
-
import { createNativeServeBoundary, createVerdictFile, nativeServeCapability, nativeServeReason, nativeServeVersionPolicy, narrowOffenders } from './lib/opencode-native-boundary.js';
|
|
232
|
+
import { createNativeServeBoundary, createVerdictFile, nativeContextRevocation, nativeServeCapability, nativeServeReason, nativeServeVersionPolicy, narrowOffenders } from './lib/opencode-native-boundary.js';
|
|
230
233
|
import { isolatedServeFailure } from './lib/opencode-launch-error.js';
|
|
231
234
|
import { reconcilePreflightProfiles, preflightExcludedPorts, runOpencodeBuildPreflight } from './lib/opencode-build-preflight.js';
|
|
232
235
|
import { binaryIdentity as opencodeBinaryIdentity, binaryKey as opencodeBinaryKey } from './lib/opencode-serve-probe.js';
|
|
@@ -240,12 +243,14 @@ const nativeServeBoundary = createNativeServeBoundary({
|
|
|
240
243
|
const cfg = loadBrowserConfig();
|
|
241
244
|
const profiles = new Map(normalizeAgentProfiles(cfg).map(p => [p.envId, p]));
|
|
242
245
|
const defaultId = moreLoginDefaultEnvId(cfg);
|
|
243
|
-
if (defaultId) profiles.set(String(defaultId), { envId: String(defaultId) });
|
|
244
|
-
for (const envId of nativePreflightProfiles)
|
|
246
|
+
if (defaultId && !profiles.has(String(defaultId))) profiles.set(String(defaultId), { envId: String(defaultId) });
|
|
247
|
+
for (const envId of nativePreflightProfiles) {
|
|
248
|
+
if (!profiles.has(envId)) profiles.set(envId, { envId });
|
|
249
|
+
}
|
|
245
250
|
const remote = [...profiles.values()].filter(p => !moreLogin.isLocalProfileId(p.envId));
|
|
246
251
|
const liveProfiles = remote.length ? await reconcilePreflightProfiles(remote,
|
|
247
|
-
() => moreLogin.listCompleteProfiles({ savedCfg: cfg,
|
|
248
|
-
{ log: line => { if (!nativeStaleProfilesLogged.has(line)) { nativeStaleProfilesLogged.add(line); console.warn(`[opencode] ${line}`); } } }) : [];
|
|
252
|
+
() => moreLogin.listCompleteProfiles({ savedCfg: cfg, firstPageTimeout: 5000 }),
|
|
253
|
+
{ allowUnavailable: true, log: line => { if (!nativeStaleProfilesLogged.has(line)) { nativeStaleProfilesLogged.add(line); console.warn(`[opencode] ${line}`); } } }) : [];
|
|
249
254
|
const excludedPorts = await preflightExcludedPorts(liveProfiles,
|
|
250
255
|
envId => moreLogin.profileDetail(envId, { savedCfg: cfg, timeout: 5000 }));
|
|
251
256
|
const token = opencodeServeRecords.newToken();
|
|
@@ -254,7 +259,7 @@ const nativeServeBoundary = createNativeServeBoundary({
|
|
|
254
259
|
track: (proc, detail) => {
|
|
255
260
|
operations.track(proc, { ...detail, kill: signal => signalOpencodeServeProcess(proc, signal) });
|
|
256
261
|
// A crash must leave the throwaway serve on the same ownership record as every normal serve.
|
|
257
|
-
trackOpencodeServe(proc, { kind: 'isolated', id: 'build-preflight', port: detail.port, token, boundaryTracked: true });
|
|
262
|
+
trackOpencodeServe(proc, { kind: 'isolated', id: 'build-preflight', port: detail.port, token, boundaryTracked: true, recordOnAnswer: false });
|
|
258
263
|
},
|
|
259
264
|
});
|
|
260
265
|
},
|
|
@@ -442,10 +447,13 @@ import { applyPackagedChildPath, durableEntry, mcpStdioCommand, npmGlobalBinFor,
|
|
|
442
447
|
import { dataHomeId } from '../lib/desktop-app.js';
|
|
443
448
|
import { pruneExternalTools } from '../lib/external-tools.js';
|
|
444
449
|
import { renderOfflinePage } from './lib/offline-page.js';
|
|
450
|
+
import { logUnexpectedProfileClose } from './lib/browser-close-evidence.js';
|
|
451
|
+
import { etagMatches, memoryListEtag, memoryListStamp } from './lib/memory-list-stamp.js';
|
|
452
|
+
import { parseMemoryPage, pageEtagPart, describePage, isLastPage } from './lib/memory-list-page.js';
|
|
445
453
|
import {
|
|
446
454
|
getDb, closeDb, getDbPath, getEmbedding, getEmbeddingBatch, getEmbeddingDims, warmupEmbeddings,
|
|
447
455
|
encodeVector, decodeVector, cosineSimilarity,
|
|
448
|
-
searchMemories as dbSearchMemories, getAllMemories, getAllMemoriesWithVectors,
|
|
456
|
+
searchMemories as dbSearchMemories, getAllMemories, getMemoriesPage, getAllMemoriesWithVectors,
|
|
449
457
|
getMemoryById, getMemoryWithVector, updateMemoryPayload,
|
|
450
458
|
softDeleteMemory, hardDeleteMemory, restoreMemory as dbRestoreMemory,
|
|
451
459
|
getTrashedMemories, purgeTrash, countMemories, getMemoryStats,
|
|
@@ -527,6 +535,11 @@ let _greeting = null;
|
|
|
527
535
|
let _greetingRouter = null;
|
|
528
536
|
let _greetingError = null;
|
|
529
537
|
let _assistantDispatcher = null;
|
|
538
|
+
// The server's one coordination service (lib/coordination/service.js, DATA_HOME/data/coordination.db), once the
|
|
539
|
+
// Assistant's block made and shared it: the dispatcher, the runtime, and later a team scheduler (its `.store` is what
|
|
540
|
+
// lib/teams takes) all use this instance. Kept here so that every stop path closes it (runGracefulShutdown).
|
|
541
|
+
let _assistantCoordination = null;
|
|
542
|
+
let _assistantTeamScheduler = null;
|
|
530
543
|
// The Assistant's settings store (assistant-config.json), once the Assistant is built: Skills Studio's AI drafting reads
|
|
531
544
|
// the owner's saved route for Coding from it (skillDraftDefaultTarget).
|
|
532
545
|
let _assistantConfigStore = null;
|
|
@@ -652,6 +665,12 @@ import {
|
|
|
652
665
|
import { createOpencodeCompletionEngine } from './lib/editor-completion-opencode.js';
|
|
653
666
|
import { createEndpointCompletionEngine } from './lib/editor-completion-endpoint.js';
|
|
654
667
|
import { ownerRouteGuard } from './lib/http-guards.js';
|
|
668
|
+
import { createBridgeStore, createExtensionBridge } from './lib/browser-extension-bridge.js';
|
|
669
|
+
import { createExtensionAdapter, EXTENSION_FOLDER } from './lib/browser-extension-adapter.js';
|
|
670
|
+
import { detectBrowsers } from './lib/browser-default.js';
|
|
671
|
+
import { extensionFolderState, prepareExtensionFolder } from './lib/browser-extension-folder.js';
|
|
672
|
+
import { createExtensionSetup, setupError as extensionSetupError } from './lib/browser-extension-setup.js';
|
|
673
|
+
import { safeError as extensionSafeError } from '../browser-extension/protocol.js';
|
|
655
674
|
import { setUntrustedFileHeaders } from './lib/untrusted-file-headers.js';
|
|
656
675
|
import { BUNDLED_LOGO_FILES, UPLOADED_IMAGE_PATH } from './lib/request-gate.js';
|
|
657
676
|
import { createCloudflaredManager } from './lib/cloudflared/manager.js';
|
|
@@ -1070,6 +1089,11 @@ function peerLookupWanted(req) {
|
|
|
1070
1089
|
app.use(_pageSession.serviceWorker); // GET /sw.js: a worker that takes itself away, for a browser refused the secret
|
|
1071
1090
|
app.use(_pageSession.pages);
|
|
1072
1091
|
app.get('/api/page-session', (req, res) => _pageSession.refresh(req, res)); // PAGE_SECRET_REFRESH_PATH
|
|
1092
|
+
// The extension's "Connect your browser" page, opened by the one-button setup in the owner's everyday browser. One of
|
|
1093
|
+
// the app's pages (PAGE_SECRET_PATHS): it gets this boot's page secret like any of them, so its reads of the setup's
|
|
1094
|
+
// status and its one ticket are the owner's, under the same owner guard; an automation browser and an agent's process
|
|
1095
|
+
// never get the secret (lib/page-session.js). The extension's content script runs on this exact origin and path only.
|
|
1096
|
+
app.get('/extension-setup', (_req, res) => { res.setHeader('Cache-Control', 'no-store'); res.sendFile(join(__dirname, 'public', 'extension-setup.html')); });
|
|
1073
1097
|
// Retired 2D bookmarks and explicit variant links always enter the 3D page. Keep their other URL state.
|
|
1074
1098
|
app.get(['/', '/index.html', '/index2d.html'], (req, res, next) => {
|
|
1075
1099
|
const target = normalizeViewUrl(req.originalUrl);
|
|
@@ -1453,10 +1477,39 @@ app.get('/api/memories', async (req, res) => {
|
|
|
1453
1477
|
// metadata columns dropped. ~4x smaller JSON for large graphs.
|
|
1454
1478
|
const slim = req.query.fields === 'graph';
|
|
1455
1479
|
const SLIM_CONTENT_CHARS = 500;
|
|
1480
|
+
// One page of the list (lib/memory-list-page.js), only without links: `offset` / `limit`. Without `limit`,
|
|
1481
|
+
// every memory, as always (the same body and the same ETag).
|
|
1482
|
+
const page = includeLinks ? null : parseMemoryPage(req.query);
|
|
1483
|
+
if (page?.error) return res.status(400).json({ error: page.error });
|
|
1484
|
+
|
|
1485
|
+
// The list without links (the page's first load): a page that still holds this very answer is told
|
|
1486
|
+
// so before a row is read (lib/memory-list-stamp.js). 32 MB were read, built and serialised on every
|
|
1487
|
+
// load only to find out, from the finished body, that nothing had changed.
|
|
1488
|
+
let listVersion = null;
|
|
1489
|
+
if (!includeLinks) {
|
|
1490
|
+
const ocBridgeNow = loadBridgeConfig('openclaw');
|
|
1491
|
+
if (_openclawNodes !== _openclawNodesSeen) { _openclawNodesSeen = _openclawNodes; _openclawNodesRev += 1; }
|
|
1492
|
+
let listStamp = null;
|
|
1493
|
+
try { listStamp = memoryListStamp(getDb()); } catch { /* no stamp: the full answer, as before */ }
|
|
1494
|
+
const listParts = [
|
|
1495
|
+
listStamp, slim ? 'graph' : 'full', SLIM_CONTENT_CHARS,
|
|
1496
|
+
ocBridgeNow?.enabled ? `openclaw:${_openclawNodesRev}:${_openclawNodes.length}` : 'openclaw:off',
|
|
1497
|
+
];
|
|
1498
|
+
listVersion = memoryListEtag(listParts);
|
|
1499
|
+
// A page's ETag is the list's plus the page's place: an unchanged list is a 304 page by page.
|
|
1500
|
+
const listEtag = page ? memoryListEtag([...listParts, pageEtagPart(page)]) : listVersion;
|
|
1501
|
+
if (listEtag) {
|
|
1502
|
+
res.set('ETag', listEtag);
|
|
1503
|
+
res.set('Cache-Control', 'no-cache');
|
|
1504
|
+
if (etagMatches(req.headers['if-none-match'], listEtag)) return res.status(304).end();
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1456
1507
|
|
|
1457
1508
|
const cachedLinks = includeLinks ? getValidLinkCache() : null;
|
|
1458
1509
|
const needVectors = includeLinks && !cachedLinks;
|
|
1459
|
-
|
|
1510
|
+
// A page reads its own rows only (and how many there are); the whole list reads them all.
|
|
1511
|
+
const pageRead = page ? getMemoriesPage(page) : null;
|
|
1512
|
+
const allPoints = pageRead ? pageRead.rows : (needVectors ? getAllMemoriesWithVectors() : getAllMemories());
|
|
1460
1513
|
|
|
1461
1514
|
// Build nodes
|
|
1462
1515
|
const nodes = allPoints.map(p => ({
|
|
@@ -1465,9 +1518,9 @@ app.get('/api/memories', async (req, res) => {
|
|
|
1465
1518
|
vector: p.vector || null,
|
|
1466
1519
|
}));
|
|
1467
1520
|
|
|
1468
|
-
// Merge OpenClaw bridge nodes
|
|
1521
|
+
// Merge OpenClaw bridge nodes (after the stored memories: in a paged list, on the last page)
|
|
1469
1522
|
const ocBridge = loadBridgeConfig('openclaw');
|
|
1470
|
-
if (ocBridge?.enabled && _openclawNodes.length > 0) {
|
|
1523
|
+
if (ocBridge?.enabled && _openclawNodes.length > 0 && (!page || isLastPage({ ...page, total: pageRead.total }))) {
|
|
1471
1524
|
for (const ocNode of _openclawNodes) {
|
|
1472
1525
|
nodes.push({ ...ocNode, vector: null });
|
|
1473
1526
|
}
|
|
@@ -1504,7 +1557,9 @@ app.get('/api/memories', async (req, res) => {
|
|
|
1504
1557
|
return { ...rest, payload: slimPayload };
|
|
1505
1558
|
});
|
|
1506
1559
|
|
|
1507
|
-
|
|
1560
|
+
const body = { nodes: clientNodes, links, totalVectors: pageRead ? pageRead.total : allPoints.length, openclawNodes: ocBridge?.enabled ? _openclawNodes.length : 0 };
|
|
1561
|
+
if (page) body.page = describePage({ ...page, total: pageRead.total, count: clientNodes.length, version: listVersion });
|
|
1562
|
+
res.json(body);
|
|
1508
1563
|
} catch (err) {
|
|
1509
1564
|
console.error('GET /api/memories error:', err.message);
|
|
1510
1565
|
res.status(500).json({ error: err.message });
|
|
@@ -2487,6 +2542,8 @@ async function runGracefulShutdown(reason) {
|
|
|
2487
2542
|
// Assistant's Claude Code workers that can continue are suspended (they resume
|
|
2488
2543
|
// on the next start, lib/assistant-dispatch.js), and the runtime keeps them;
|
|
2489
2544
|
// every other run is stopped. Either way each worker's CLI is ended now.
|
|
2545
|
+
// Stop team work on every exit path before the workers and the shared store close.
|
|
2546
|
+
try { await _assistantTeamScheduler?.shutdown(); } catch (err) { console.warn(' team scheduler stop err:', err?.message); }
|
|
2490
2547
|
let keepRuns = [];
|
|
2491
2548
|
try { keepRuns = _assistantDispatcher?.suspendForShutdown?.(reason) || []; } catch (err) { console.warn(' assistant suspend err:', err?.message); }
|
|
2492
2549
|
try { await _nativeLoopRuntime?.shutdown(reason, { keep: keepRuns }); } catch (err) { console.warn(' native loop stop err:', err?.message); }
|
|
@@ -2552,6 +2609,10 @@ async function runGracefulShutdown(reason) {
|
|
|
2552
2609
|
// The judge backfill flushes its last counters and releases its lease so
|
|
2553
2610
|
// the respawned server resumes immediately instead of waiting out the lease.
|
|
2554
2611
|
try { stopJudgeBackfill(); } catch {}
|
|
2612
|
+
// The coordination store (agent events, the Assistant's mailbox, the follow-up outbox): closed once the workers
|
|
2613
|
+
// are stopped or suspended and what that changed is recorded. Every open wait is answered, the write-ahead log is
|
|
2614
|
+
// folded into the file. Signals and the restart/update/shutdown routes all use this teardown.
|
|
2615
|
+
try { _assistantCoordination?.close(); } catch (err) { console.warn(' coordination close err:', err?.message); }
|
|
2555
2616
|
try { closeDb(); } catch {}
|
|
2556
2617
|
try { closeBlobStore(); } catch {}
|
|
2557
2618
|
|
|
@@ -4152,9 +4213,10 @@ async function resolveOpenCodeMcpDirectory(entry, sessionIds) {
|
|
|
4152
4213
|
|
|
4153
4214
|
// ── Multi-account Codex (per-tab CODEX_HOME) ────────────────────────────────
|
|
4154
4215
|
// Each ChatGPT account gets its own CODEX_HOME directory holding its own
|
|
4155
|
-
// auth.json + sessions/ + state DB, while config.toml and prompts/ are
|
|
4156
|
-
//
|
|
4157
|
-
// and custom prompts stay shared
|
|
4216
|
+
// auth.json + sessions/ + state DB, while config.toml, AGENTS.md and prompts/ are
|
|
4217
|
+
// linked back to the canonical ~/.codex so model/MCP/tool-permission config
|
|
4218
|
+
// and custom prompts stay shared (how, on each system: lib/claude-account-links.js).
|
|
4219
|
+
// The "default" account IS ~/.codex itself.
|
|
4158
4220
|
const CODEX_DEFAULT_HOME = resolve(process.env.CODEX_HOME || resolve(getHomePath(), '.codex'));
|
|
4159
4221
|
const CODEX_ACCOUNTS_ROOT = resolve(getHomePath(), '.codex-accounts');
|
|
4160
4222
|
|
|
@@ -4488,6 +4550,13 @@ function _codexAccounts() {
|
|
|
4488
4550
|
return _codexAccountsInstance;
|
|
4489
4551
|
}
|
|
4490
4552
|
|
|
4553
|
+
// Default's config.toml was written (by SynaBun, or by Codex for a panel's settings): every named account
|
|
4554
|
+
// reads the same again. Only where an account shares it by a hard link or a copy (Windows without symbolic
|
|
4555
|
+
// links, lib/claude-account-links.js): a symbolic link has nothing to bring in step. Never stops a write.
|
|
4556
|
+
function codexSharedFilesChanged() {
|
|
4557
|
+
try { _codexAccounts().syncShared?.(); } catch { /* the next launch of an account puts it in step */ }
|
|
4558
|
+
}
|
|
4559
|
+
|
|
4491
4560
|
// The registry rows (id, label, home, …) for readers that only need where an account lives.
|
|
4492
4561
|
function loadCodexAccounts() {
|
|
4493
4562
|
return { accounts: _codexAccounts().registryRows(), defaultId: 'default' };
|
|
@@ -7435,6 +7504,8 @@ CRITICAL — When you need clarification during planning:
|
|
|
7435
7504
|
const nextConfig = validateCodexConfigRequirements(supported, await readCodexRequirements());
|
|
7436
7505
|
const edits = buildCodexConfigEdits(nextConfig);
|
|
7437
7506
|
await request('config/batchWrite', { edits, reloadUserConfig: true }, 10000);
|
|
7507
|
+
// Codex wrote this account's config.toml as a new file: Default and the other accounts get it too.
|
|
7508
|
+
try { codexSharedFilesChanged(); } catch { /* never stops a save */ }
|
|
7438
7509
|
const config = await readConfigState(msg.cwd || PACKAGE_ROOT);
|
|
7439
7510
|
codexContextModels = [];
|
|
7440
7511
|
// config.toml is every account's (shared): their kept model lists are read again.
|
|
@@ -8318,6 +8389,7 @@ let _ocpVersion = null;
|
|
|
8318
8389
|
let _ocpPassword = null;
|
|
8319
8390
|
let _ocpProblem = null;
|
|
8320
8391
|
let _ocpHistoryClearInProgress = false;
|
|
8392
|
+
let _ocpSessionCacheWarmup = null;
|
|
8321
8393
|
|
|
8322
8394
|
// ── OpenCode V2 (clean-slate sidepanel) — client set & bridge ──
|
|
8323
8395
|
const _ocpV2WsClients = new Set(); // all connected /ws/opencode-v2 clients
|
|
@@ -8416,7 +8488,7 @@ function noteOpencodeServePort(port, delta) {
|
|
|
8416
8488
|
if (next > 0) _opencodeServePortCounts.set(p, next); else _opencodeServePortCounts.delete(p);
|
|
8417
8489
|
}
|
|
8418
8490
|
|
|
8419
|
-
function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocketSafe = false, nativeServe = null, boundaryTracked = false }) {
|
|
8491
|
+
function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocketSafe = false, nativeServe = null, boundaryTracked = false, recordOnAnswer = true }) {
|
|
8420
8492
|
// A serve that fails its runtime check while a native context is attached is stopped (its pages could reach it).
|
|
8421
8493
|
// A serve that fails its runtime check is stopped by the boundary: SIGTERM, then SIGKILL, until the OS confirms
|
|
8422
8494
|
// its process and its listener are gone (lib/opencode-native-boundary.js terminate).
|
|
@@ -8432,7 +8504,10 @@ function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocke
|
|
|
8432
8504
|
// A spawn that failed (no pid) may never exit; a failed kill leaves the process running.
|
|
8433
8505
|
proc.once?.('error', () => { if (!proc.pid || exited()) release(); });
|
|
8434
8506
|
}
|
|
8435
|
-
|
|
8507
|
+
// Right after the spawn the process may not show its environment yet (its token): a miss here is expected when
|
|
8508
|
+
// answering() records it again once it answers, and only that second try says why (recordOnAnswer: the caller
|
|
8509
|
+
// calls answering(); the build pre-flight does not, so its one try says it).
|
|
8510
|
+
const spawned = pid ? opencodeServeRecords.record({ kind, id, port, pid, token, quiet: recordOnAnswer }).catch(() => null) : Promise.resolve(null);
|
|
8436
8511
|
let started = Promise.resolve(null);
|
|
8437
8512
|
const forget = () => {
|
|
8438
8513
|
spawned.then((record) => { if (record) opencodeServeRecords.remove(record); }).catch(() => {});
|
|
@@ -8952,6 +9027,11 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8952
9027
|
const wanted = () => _ocpIsoServes.get(termId) === entry;
|
|
8953
9028
|
let check = null;
|
|
8954
9029
|
let started = 'cancelled';
|
|
9030
|
+
// Validate this run's pin once, before taking the global start lock. An offline API must not delay every
|
|
9031
|
+
// other start, nor be listed again for each port collision. Later live pages retain the normal 15s budget.
|
|
9032
|
+
const pin = runMoreLoginPin(termId);
|
|
9033
|
+
if (pin?.envId && !moreLogin.isLocalProfileId(pin.envId)) await reconcilePreflightProfiles([],
|
|
9034
|
+
() => moreLogin.listCompleteProfiles({ ..._moreLoginOpts(), firstPageTimeout: 5000 }), { requested: [pin.envId], allowUnavailable: true });
|
|
8955
9035
|
// Another server that takes the port while this serve boots is a start collision: it is left running (and never
|
|
8956
9036
|
// put on record), this start's own process is ended, and the start tries the next free port (three at most).
|
|
8957
9037
|
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
@@ -8962,9 +9042,6 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8962
9042
|
const token = opencodeServeRecords.newToken();
|
|
8963
9043
|
// A protected worker's serve (hidePassword): no password variable in any environment, its own shell's
|
|
8964
9044
|
// included; the serve prints the password it made, read here from its output (and never logged).
|
|
8965
|
-
const pin = runMoreLoginPin(termId);
|
|
8966
|
-
if (pin?.envId && !moreLogin.isLocalProfileId(pin.envId)) await reconcilePreflightProfiles([],
|
|
8967
|
-
() => moreLogin.listCompleteProfiles(_moreLoginOpts()), { requested: [pin.envId] });
|
|
8968
9045
|
const launch = await opencodeServeLaunch(port, { env: { ...isolatedEnv, [SERVE_TOKEN_ENV]: token }, passwordFrom: 'stdout' });
|
|
8969
9046
|
const readPassword = launch.passwordFrom === 'stdout' ? servePasswordReader() : null;
|
|
8970
9047
|
// A guarded worker's serve (macOS): run the whole serve tree under the run's Seatbelt profile, so its shell
|
|
@@ -10421,6 +10498,9 @@ app.delete('/api/opencode/history', async (req, res) => {
|
|
|
10421
10498
|
try { result.databaseBytesAfter = getOpenCodeHistoryStats({ dbPath, dataRoot: dirname(dbPath) }).databaseBytes; } catch { result.databaseBytesAfter = before.databaseBytes; }
|
|
10422
10499
|
|
|
10423
10500
|
try {
|
|
10501
|
+
// A startup scan may still hold session rows it read before deletion.
|
|
10502
|
+
// Finish that pass before clearing the index so none can be put back.
|
|
10503
|
+
if (_ocpSessionCacheWarmup) await _ocpSessionCacheWarmup.catch(() => {});
|
|
10424
10504
|
result.resumeCache = clearSessionCacheProvider('opencode');
|
|
10425
10505
|
} catch (error) {
|
|
10426
10506
|
result.warnings.push(`OpenCode Resume cache could not be cleared: ${error.message}`);
|
|
@@ -13868,6 +13948,10 @@ function parseDailyLogs(memoryDir) {
|
|
|
13868
13948
|
// --- OpenClaw Bridge: In-Memory Store ---
|
|
13869
13949
|
|
|
13870
13950
|
let _openclawNodes = [];
|
|
13951
|
+
// The list above is replaced whole when the bridge syncs: which one GET /api/memories last saw, and how
|
|
13952
|
+
// many times it has changed (part of that route's ETag).
|
|
13953
|
+
let _openclawNodesSeen = null;
|
|
13954
|
+
let _openclawNodesRev = 0;
|
|
13871
13955
|
let _openclawCategories = [];
|
|
13872
13956
|
let _openclawLastSync = null;
|
|
13873
13957
|
|
|
@@ -14201,6 +14285,7 @@ function writeLoopTemplates(templates) {
|
|
|
14201
14285
|
for (const [path, fileTemplates] of byPath) {
|
|
14202
14286
|
writeLoopTemplateFile(path, fileTemplates, formatByPath.get(path) || 'array');
|
|
14203
14287
|
}
|
|
14288
|
+
if (!_scheduleFilesWatcher) broadcastSync({ type: 'assistant:automation-records-changed', templates: true });
|
|
14204
14289
|
}
|
|
14205
14290
|
|
|
14206
14291
|
function readLoopFolders() {
|
|
@@ -14900,7 +14985,7 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14900
14985
|
const loopTerminalToken = nativeRuntime ? null : _terminalTokens.issue(terminalSessionId);
|
|
14901
14986
|
if (loopTerminalToken) issuedLoopTerminal = terminalSessionId;
|
|
14902
14987
|
// The launch's MoreLogin profile (decided above) becomes the run's pin, as a schedule's does. None: the default
|
|
14903
|
-
// browser
|
|
14988
|
+
// AI browser (Settings → Connected tools → MoreLogin), as before.
|
|
14904
14989
|
if (launchMoreLogin) {
|
|
14905
14990
|
pinRunMoreLoginProfile(terminalSessionId, launchMoreLogin.moreloginEnvId, launchMoreLogin.moreloginEnvName, launchMoreLogin.moreloginEnvBy);
|
|
14906
14991
|
pinnedLoopTerminal = terminalSessionId;
|
|
@@ -15293,6 +15378,9 @@ app.post('/api/loop/recover-browser', async (req, res) => {
|
|
|
15293
15378
|
// token, so naming a run (or routing as it) moves nothing without it (403 TERMINAL_TOKEN_REQUIRED / _INVALID).
|
|
15294
15379
|
const who = browserCaller(req);
|
|
15295
15380
|
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
15381
|
+
if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(who.id) && who.status !== 'verified') {
|
|
15382
|
+
return res.status(403).json(extensionSafeError({ code: 'AUTH_FAILED' }));
|
|
15383
|
+
}
|
|
15296
15384
|
const caller = browserOwnerId(who.id);
|
|
15297
15385
|
if (!caller) {
|
|
15298
15386
|
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' });
|
|
@@ -15320,6 +15408,11 @@ app.post('/api/loop/recover-browser', async (req, res) => {
|
|
|
15320
15408
|
return res.json({ ok: true, sessionId, tabId, adopted: true });
|
|
15321
15409
|
}
|
|
15322
15410
|
const fresh = req.body?.reason === 'create';
|
|
15411
|
+
// A create that takes over one of the owner's tabs in the everyday browser (extension mode only).
|
|
15412
|
+
const takeOverTab = fresh && typeof req.body?.takeOverTab === 'string' && loadBrowserConfig().connectMode === 'extension' ? req.body.takeOverTab : null;
|
|
15413
|
+
if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(who.id) && !fresh) {
|
|
15414
|
+
return res.status(410).json(extensionSafeError({ code: 'TAB_CLOSED' }));
|
|
15415
|
+
}
|
|
15323
15416
|
const lost = req.body?.lost && typeof req.body.lost === 'object' ? req.body.lost : null;
|
|
15324
15417
|
if (named && !fresh) {
|
|
15325
15418
|
const current = liveAutomationRoute(named, { files: true });
|
|
@@ -15328,7 +15421,10 @@ app.post('/api/loop/recover-browser', async (req, res) => {
|
|
|
15328
15421
|
}
|
|
15329
15422
|
}
|
|
15330
15423
|
const start = async () => {
|
|
15331
|
-
const acq = await acquireLoopBrowserAndTab({ terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser' });
|
|
15424
|
+
const acq = await acquireLoopBrowserAndTab({ terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser', takeOverTab });
|
|
15425
|
+
// Its profile was closed outside SynaBun under it and is not started again for it: the loop ends when its turn
|
|
15426
|
+
// ends, never asking again iteration after iteration.
|
|
15427
|
+
if (acq.code === 'MORELOGIN_CLOSED_OUTSIDE') finishBlockedLoop(owner, acq);
|
|
15332
15428
|
if (acq.error) throw Object.assign(new Error(acq.error), { acquisition: acq });
|
|
15333
15429
|
// The run ended while its tab was being opened (a cold start): the tab goes at once, never left to a dead run.
|
|
15334
15430
|
if (named && automationRunState(named, { files: true }) === 'ended') {
|
|
@@ -15342,7 +15438,7 @@ app.post('/api/loop/recover-browser', async (req, res) => {
|
|
|
15342
15438
|
if (named) noteAutomationBrowserRoute(named, acq, fresh ? 'created' : 'recovered');
|
|
15343
15439
|
return acq;
|
|
15344
15440
|
};
|
|
15345
|
-
const outcome = await browserStartHandoff.run(`run:${owner}`, start, {
|
|
15441
|
+
const outcome = await browserStartHandoff.run(takeOverTab ? `run:${owner}:take:${takeOverTab}` : `run:${owner}`, start, {
|
|
15346
15442
|
gone: browserCallerGone(req, res),
|
|
15347
15443
|
waitMs: startWaitMs(browserRequestDeadline(req)),
|
|
15348
15444
|
alive: (acq) => startedTabAlive(acq.browserSessionId, acq.browserTabId, owner),
|
|
@@ -15354,11 +15450,57 @@ app.post('/api/loop/recover-browser', async (req, res) => {
|
|
|
15354
15450
|
res.json({ ok: true, sessionId: acq.browserSessionId, tabId: acq.browserTabId || null, ...(outcome.from !== 'started' && { handedOver: outcome.from }) });
|
|
15355
15451
|
} catch (err) {
|
|
15356
15452
|
const acq = err?.acquisition;
|
|
15357
|
-
|
|
15453
|
+
// A run blocked by a close outside SynaBun: 409 (nothing is wrong with the server, the run is refused on purpose).
|
|
15454
|
+
if (acq?.code === 'MORELOGIN_CLOSED_OUTSIDE') {
|
|
15455
|
+
return res.status(409).json(closedOutsideAnswer(acq));
|
|
15456
|
+
}
|
|
15457
|
+
if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}), ...(acq.needsUser ? { needsUser: true } : {}) });
|
|
15358
15458
|
res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
|
|
15359
15459
|
}
|
|
15360
15460
|
});
|
|
15361
15461
|
|
|
15462
|
+
/**
|
|
15463
|
+
* A loop whose browser was refused because its MoreLogin profile was closed outside SynaBun under it
|
|
15464
|
+
* (lib/morelogin-outside-close.js): it ends when its current turn ends, stoppedReason 'browser_closed_outside', in
|
|
15465
|
+
* place of starting its next iteration and asking again. A native loop through NativeLoopRuntime.finishAfterTurn
|
|
15466
|
+
* (the turn under way reports the refusal it got); a terminal loop's state file is marked inactive the way a PTY
|
|
15467
|
+
* exit marks it, which its driver reads before the next iteration. A dispatched task run is left to its brain (it
|
|
15468
|
+
* gets the refusal, needsUser). Once per run. Returns whether the loop was set to end.
|
|
15469
|
+
*/
|
|
15470
|
+
const _blockedLoopsEnded = new Set();
|
|
15471
|
+
function finishBlockedLoop(ownerKey, acq = null) {
|
|
15472
|
+
if (!ownerKey || _blockedLoopsEnded.has(ownerKey)) return false;
|
|
15473
|
+
let ended = false;
|
|
15474
|
+
try {
|
|
15475
|
+
if (_nativeLoopRuntime?.isAlive?.(ownerKey)) {
|
|
15476
|
+
ended = !!_nativeLoopRuntime.finishAfterTurn?.(ownerKey, 'browser_closed_outside');
|
|
15477
|
+
} else {
|
|
15478
|
+
const loopFile = findLoopFileForTerminal(ownerKey);
|
|
15479
|
+
if (loopFile) {
|
|
15480
|
+
const loopPath = resolve(LOOP_DIR, loopFile);
|
|
15481
|
+
const ls = JSON.parse(readFileSync(loopPath, 'utf-8'));
|
|
15482
|
+
if (ls.active && ls.runtimeType !== 'native' && ls.driverType !== 'native' && ls.runMode !== 'task') {
|
|
15483
|
+
ls.active = false;
|
|
15484
|
+
ls.pending = false;
|
|
15485
|
+
ls.completedAt = new Date().toISOString();
|
|
15486
|
+
ls.stoppedReason = 'browser_closed_outside';
|
|
15487
|
+
writeFileSync(loopPath, JSON.stringify(ls, null, 2));
|
|
15488
|
+
if (ls.driverType === 'exec' && ls.scheduledBy) persistExecScheduleOutcome(ls, 'stopped', 'browser_closed_outside');
|
|
15489
|
+
ended = true;
|
|
15490
|
+
}
|
|
15491
|
+
}
|
|
15492
|
+
}
|
|
15493
|
+
} catch (err) {
|
|
15494
|
+
loopLog(ownerKey, 'browser:blocked', 'could not set the loop to end after its turn', { err: err?.message || String(err) });
|
|
15495
|
+
}
|
|
15496
|
+
if (ended) {
|
|
15497
|
+
if (_blockedLoopsEnded.size > 2000) _blockedLoopsEnded.delete(_blockedLoopsEnded.values().next().value);
|
|
15498
|
+
_blockedLoopsEnded.add(ownerKey);
|
|
15499
|
+
loopLog(ownerKey, 'browser:blocked', 'the loop ends when this turn ends: its MoreLogin profile was closed outside SynaBun and is not started again for it', { closedAt: acq?.closedAt || null });
|
|
15500
|
+
}
|
|
15501
|
+
return ended;
|
|
15502
|
+
}
|
|
15503
|
+
|
|
15362
15504
|
// GET /api/loop/history — no history keeping, always empty
|
|
15363
15505
|
app.get('/api/loop/history', (_req, res) => { res.json([]); });
|
|
15364
15506
|
|
|
@@ -15419,8 +15561,10 @@ function _armScheduleFilesWatcher() {
|
|
|
15419
15561
|
if (_scheduleFilesWatcher) return true;
|
|
15420
15562
|
try {
|
|
15421
15563
|
const w = fsWatch(LOOP_DATA_DIR, (eventType, filename) => {
|
|
15422
|
-
|
|
15423
|
-
|
|
15564
|
+
const schedules = !filename || LOOP_SCHEDULES_PATTERN.test(filename);
|
|
15565
|
+
const templates = !filename || LOOP_TEMPLATES_PATTERN.test(filename);
|
|
15566
|
+
if (schedules) _scheduleFilesCache = null;
|
|
15567
|
+
if (schedules || templates) broadcastSync({ type: 'assistant:automation-records-changed', schedules, templates });
|
|
15424
15568
|
});
|
|
15425
15569
|
w.unref?.();
|
|
15426
15570
|
w.on('error', () => {
|
|
@@ -15538,6 +15682,7 @@ function saveScheduleStore(store) {
|
|
|
15538
15682
|
for (const [path, schedules] of byPath) {
|
|
15539
15683
|
writeLoopScheduleFile(path, schedules, path === LOOP_SCHEDULES_PATH ? groups : [], formatByPath.get(path) || 'object', files);
|
|
15540
15684
|
}
|
|
15685
|
+
if (!_scheduleFilesWatcher) broadcastSync({ type: 'assistant:automation-records-changed', schedules: true });
|
|
15541
15686
|
}
|
|
15542
15687
|
|
|
15543
15688
|
function loadSchedules() {
|
|
@@ -15584,7 +15729,7 @@ function applyScheduleLaunchOverrides(schedule, source) {
|
|
|
15584
15729
|
}
|
|
15585
15730
|
|
|
15586
15731
|
// A schedule's or a schedule group's own MoreLogin profile (optional). Empty / null clears it: the run then opens the
|
|
15587
|
-
// default browser
|
|
15732
|
+
// default AI browser (Settings → Connected tools → MoreLogin), as every record without the field does. The name is kept for display only.
|
|
15588
15733
|
// At launch a schedule's own profile wins, then its group's (scheduleMoreLoginProfile); nothing is copied from a group
|
|
15589
15734
|
// onto its schedules.
|
|
15590
15735
|
function applyScheduleMoreLoginProfile(schedule, source) {
|
|
@@ -16131,8 +16276,9 @@ async function launchScheduledLoop(schedule) {
|
|
|
16131
16276
|
console.log(`[schedule] "${schedule.name}" runs in ${describeMoreLoginPin(runMoreLoginPin(terminalSessionId))}${scheduledMoreLogin.source === 'group' ? ' (its group\'s profile)' : ''}`);
|
|
16132
16277
|
}
|
|
16133
16278
|
if (scheduledUsesBrowser) {
|
|
16134
|
-
// Same serialized shared-browser + dedicated-tab acquisition as manual loops.
|
|
16135
|
-
|
|
16279
|
+
// Same serialized shared-browser + dedicated-tab acquisition as manual loops. A new firing may start a profile
|
|
16280
|
+
// closed outside SynaBun (lib/morelogin-outside-close.js): that is what the schedule is for.
|
|
16281
|
+
const acq = await acquireLoopBrowserAndTab({ terminalSessionId, logTag: 'schedule:browser', scheduledFiring: true });
|
|
16136
16282
|
if (acq.error) {
|
|
16137
16283
|
throw new Error(acq.error);
|
|
16138
16284
|
}
|
|
@@ -20250,7 +20396,7 @@ function moreLoginAutomationProfileCheck(req, envId) {
|
|
|
20250
20396
|
function refuseDefaultBrowserChange(res) {
|
|
20251
20397
|
return res.status(403).json({
|
|
20252
20398
|
ok: false, code: 'MORELOGIN_DEFAULT_OWNER_ONLY',
|
|
20253
|
-
error: 'The default AI browser (the default MoreLogin profile and the browser connect mode) is the owner\'s choice, made in SynaBun → Settings →
|
|
20399
|
+
error: 'The default AI browser (the default MoreLogin profile and the browser connect mode) is the owner\'s choice, made in SynaBun → Settings → Connected tools → MoreLogin (Default AI browser). No agent, run, session or program can change it, whatever the profile. Nothing was changed. To work in another MoreLogin profile yourself, call morelogin with action "use" (envId or name): only your own browser tools move there. Tell the user: if every automation should use that profile by default, set it in Settings → Connected tools → MoreLogin (Default AI browser).',
|
|
20254
20400
|
});
|
|
20255
20401
|
}
|
|
20256
20402
|
/** Whether a write of the browser settings would change the default (connect mode or default profile) and its caller may not. */
|
|
@@ -20273,21 +20419,21 @@ function moreLoginGate(req, res, next) {
|
|
|
20273
20419
|
if (browserOwnerPageOnly(req)) return next();
|
|
20274
20420
|
if (caller.id && MORELOGIN_AUTOMATION_ROUTES.has(key)) {
|
|
20275
20421
|
if (MORELOGIN_VERIFIED_ROUTES.has(key) && caller.status !== 'verified') {
|
|
20276
|
-
return res.status(403).json({ ok: false, code: 'VERIFIED_RUN_REQUIRED', error: `Starting a MoreLogin profile, working in one, or making one the default AI browser is for a session that proves its id: a run SynaBun started (its terminal token), or a CLI window's own session of SynaBun's HTTP MCP (working in a profile only), or the owner in
|
|
20422
|
+
return res.status(403).json({ ok: false, code: 'VERIFIED_RUN_REQUIRED', error: `Starting a MoreLogin profile, working in one, or making one the default AI browser is for a session that proves its id: a run SynaBun started (its terminal token), or a CLI window's own session of SynaBun's HTTP MCP (working in a profile only), or the owner in the MoreLogin tab in Settings. ${String(caller.id).slice(0, 128)} is an id SynaBun gave no proof (a stdio MCP server's own id, for one).` });
|
|
20277
20423
|
}
|
|
20278
20424
|
// An id that holds a profile pin and was not proven by this request reaches no MoreLogin route (finding 2). A pin
|
|
20279
20425
|
// off the owner's list does not close these routes: the session needs status, list and `use` to go back.
|
|
20280
20426
|
const pinRefused = callerProfileRefusal(caller);
|
|
20281
20427
|
if (pinRefused && pinRefused.code === 'PROFILE_PIN_UNVERIFIED') return res.status(pinRefused.status).json({ ok: false, code: pinRefused.code, error: pinRefused.error });
|
|
20282
20428
|
if (MORELOGIN_RUN_ONLY_ROUTES.has(key) && isMcpSessionOwner(caller.id)) {
|
|
20283
|
-
return res.status(403).json({ ok: false, code: 'VERIFIED_RUN_REQUIRED', error: 'Starting a MoreLogin profile by itself or changing the default AI browser is for a run SynaBun started, or the owner in Settings →
|
|
20429
|
+
return res.status(403).json({ ok: false, code: 'VERIFIED_RUN_REQUIRED', error: 'Starting a MoreLogin profile by itself or changing the default AI browser is for a run SynaBun started, or the owner in Settings → Connected tools → MoreLogin (Default AI browser). This session can work in a profile of its own: call morelogin with action "use" (the profile is started by your next browser call).' });
|
|
20284
20430
|
}
|
|
20285
20431
|
return next();
|
|
20286
20432
|
}
|
|
20287
20433
|
let guest = false;
|
|
20288
20434
|
try { guest = !!isGuestRequest(req); } catch { guest = true; }
|
|
20289
20435
|
if (caller.id || guest) {
|
|
20290
|
-
return res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'This MoreLogin route is the owner\'s (SynaBun\'s page, Settings →
|
|
20436
|
+
return res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'This MoreLogin route is the owner\'s (SynaBun\'s page, Settings → Connected tools → MoreLogin).' });
|
|
20291
20437
|
}
|
|
20292
20438
|
if (caller.automation) {
|
|
20293
20439
|
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.' });
|
|
@@ -20362,7 +20508,7 @@ app.delete('/api/morelogin/local-profiles/:id', async (req, res) => {
|
|
|
20362
20508
|
const id = String(req.params.id);
|
|
20363
20509
|
const cfg = loadBrowserConfig();
|
|
20364
20510
|
if (cfg.connectMode === 'morelogin' && String(cfg.moreloginEnvId || '') === id) {
|
|
20365
|
-
return res.status(409).json({ ok: false, code: 'LOCAL_PROFILE_IS_DEFAULT', error: 'This local profile is the default AI browser: choose another default first (Settings →
|
|
20511
|
+
return res.status(409).json({ ok: false, code: 'LOCAL_PROFILE_IS_DEFAULT', error: 'This local profile is the default AI browser: choose another default first (Settings → Connected tools → MoreLogin (Default AI browser), or "Use as default" on another profile), then delete it.' });
|
|
20366
20512
|
}
|
|
20367
20513
|
const removed = await moreLogin.deleteLocalProfile(id);
|
|
20368
20514
|
_moreLoginStartedBy.delete(id);
|
|
@@ -20395,6 +20541,13 @@ app.get('/api/morelogin/status', async (req, res) => {
|
|
|
20395
20541
|
defaultEnvId: cfg.moreloginEnvId || null,
|
|
20396
20542
|
// SynaBun's own local profiles (lib/local-profiles.js): `installed`, `running` and `profileCount` are MoreLogin's.
|
|
20397
20543
|
localProfileCount: moreLogin.localProfileCount(),
|
|
20544
|
+
// Profiles MoreLogin refused to start for its plan's daily limit, until its day resets (lib/morelogin-start-cooldown.js):
|
|
20545
|
+
// meanwhile SynaBun does not ask MoreLogin to start them. [{ envId, name, resetAt, resetLocal, since, apiCode }]
|
|
20546
|
+
startCooldowns: moreLoginStartCooldowns(),
|
|
20547
|
+
// Profiles closed outside SynaBun (lib/morelogin-outside-close.js): no automatic path starts them again until the
|
|
20548
|
+
// owner starts them, a new scheduled run fires, or MoreLogin's daily reset (`holdUntil`).
|
|
20549
|
+
// [{ envId, name, closedAt, closedLocal, holdUntil, holdUntilLocal, runs }] (the orphaned runs counted, not listed).
|
|
20550
|
+
closedOutside: moreLoginClosedOutside(),
|
|
20398
20551
|
// The profile the calling session's own browser tools work in (POST /api/morelogin/use, or the profile its run
|
|
20399
20552
|
// was launched with), when that is not the default.
|
|
20400
20553
|
// Only for a caller this request proved (finding 2): an id merely said learns nothing about a pin.
|
|
@@ -20467,6 +20620,7 @@ app.get('/api/morelogin/profiles', async (req, res) => {
|
|
|
20467
20620
|
// listed, and `moreloginError` says why MoreLogin's are missing.
|
|
20468
20621
|
const rows = await moreLogin.listProfiles({ ..._moreLoginOpts(), complete: true });
|
|
20469
20622
|
const listed = await withMoreLoginBrowsers(rows, _moreLoginOpts());
|
|
20623
|
+
rememberMoreLoginEnvNames(rows);
|
|
20470
20624
|
// `agentsMayChoose`: on the owner's list (the Settings toggle, and what the `morelogin` tool's "list" shows).
|
|
20471
20625
|
const allowed = moreLoginAgentProfiles();
|
|
20472
20626
|
res.json({
|
|
@@ -20507,9 +20661,33 @@ app.post('/api/morelogin/start', async (req, res) => {
|
|
|
20507
20661
|
// Only that may end a running local profile to start it again (lib/local-profiles.js startNow); an automation
|
|
20508
20662
|
// gets LOCAL_PROFILE_RESTART_NEEDED / LOCAL_PROFILE_BUSY by name below, and no browser.
|
|
20509
20663
|
const who = browserCaller(req);
|
|
20664
|
+
// A profile closed outside SynaBun (lib/morelogin-outside-close.js) is not started here for an automation (a run's
|
|
20665
|
+
// or an agent's morelogin "start") or anybody else; the owner's own Start lifts the mark (it starts the profile).
|
|
20666
|
+
const startOwner = who.automation && who.id ? browserOwnerId(who.id) : null;
|
|
20667
|
+
// A run whose own profile failed in this run does not start another one either (each start spends one of
|
|
20668
|
+
// MoreLogin's daily launches, and it may not move there: lib/morelogin-profile-failures.js). A start of the failed
|
|
20669
|
+
// profile itself is how it is fixed, and goes on. The owner's Start is never asked.
|
|
20670
|
+
const failedBar = startOwner ? runProfileSwitchRefusal(startOwner, { envId: String(envId), name: _moreLoginEnvNames.get(String(envId)) || null, resolved: true }, { action: 'start' }) : null;
|
|
20671
|
+
if (failedBar) return refuseProfileSwitchAfterFailure(res, failedBar);
|
|
20510
20672
|
nativePreflightProfiles.add(String(envId));
|
|
20511
|
-
|
|
20673
|
+
// The run's own profile (its pin, else the MoreLogin default) that fails to start here bars it from switching, as a
|
|
20674
|
+
// failed browser start does (acquireSharedBrowserTab).
|
|
20675
|
+
const ownProfile = startOwner ? runEffectiveProfile(startOwner) : null;
|
|
20676
|
+
let out;
|
|
20677
|
+
try {
|
|
20678
|
+
out = await moreLogin.startProfile(envId, { ..._moreLoginOpts(), owner: !who.automation && moreLoginOwnerPageCall(req),
|
|
20679
|
+
...(startOwner ? { refuseStart: moreLoginStartGuardFor(startOwner) } : {}), profileLabel: moreLoginProfileLabel });
|
|
20680
|
+
} catch (err) {
|
|
20681
|
+
if (ownProfile && ownProfile.envId === String(envId)) noteRunProfileFailure(startOwner, ownProfile, err);
|
|
20682
|
+
throw err;
|
|
20683
|
+
}
|
|
20684
|
+
// Running now: a close outside SynaBun is over. Started (by the owner, or by an automation the mark did not hold),
|
|
20685
|
+
// or found running by the owner. An automation that only found it running has not attached to it yet: its browser
|
|
20686
|
+
// call clears the mark when it attaches (a profile MoreLogin still lists while it closes must not lose it here).
|
|
20687
|
+
if (!out.alreadyRunning || !who.automation) { try { moreLogin.clearOutsideClose(String(envId)); } catch { /* nothing held */ } }
|
|
20512
20688
|
if (!who.automation) return res.json({ ok: true, ...out });
|
|
20689
|
+
// Already running (MoreLogin's status said so, nothing was started): the profile is not the caller's to stop.
|
|
20690
|
+
if (out.alreadyRunning) return res.json({ ok: true, started: false, alreadyRunning: true, envId: String(envId) });
|
|
20513
20691
|
// An automation's start: the profile is the caller's to stop later (POST /api/morelogin/stop), and the answer
|
|
20514
20692
|
// carries no CDP port (a raw debugging connection drives the profile's browser past every check SynaBun makes;
|
|
20515
20693
|
// SynaBun's browser tools reach the caller's own profile without it: POST /api/morelogin/use).
|
|
@@ -20521,7 +20699,8 @@ app.post('/api/morelogin/start', async (req, res) => {
|
|
|
20521
20699
|
}
|
|
20522
20700
|
res.json({ ok: true, started: true, envId: String(envId) });
|
|
20523
20701
|
} catch (err) {
|
|
20524
|
-
res.status(err.status || 500).json({ ok: false, error: err.message, ...(err.code ? { code: err.code } : {})
|
|
20702
|
+
res.status(err.status || 500).json({ ok: false, error: err.message, ...(err.code ? { code: err.code } : {}),
|
|
20703
|
+
...(err.needsUser ? { needsUser: true } : {}), ...(err.closedAt ? { closedAt: err.closedAt } : {}), ...(err.holdUntil ? { holdUntil: err.holdUntil } : {}) });
|
|
20525
20704
|
}
|
|
20526
20705
|
});
|
|
20527
20706
|
|
|
@@ -20540,7 +20719,7 @@ app.post('/api/morelogin/stop', async (req, res) => {
|
|
|
20540
20719
|
const decision = profileStopDecision(browserSessions, envId, caller, { startedBy: (id) => _moreLoginStartedBy.get(id) || [] });
|
|
20541
20720
|
if (decision.action === 'refuse' && decision.reason === 'not_owned') {
|
|
20542
20721
|
console.warn(`[morelogin] stop of env ${envId} by ${logOwnerId(caller)} refused: it holds nothing on that profile`);
|
|
20543
|
-
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
|
|
20722
|
+
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 the MoreLogin tab in Settings.` });
|
|
20544
20723
|
}
|
|
20545
20724
|
if (decision.action === 'refuse') {
|
|
20546
20725
|
console.warn(`[morelogin] stop of env ${envId} by ${logOwnerId(caller)} refused: ${decision.others.length} other automation(s) work in it (${decision.others.map(logOwnerId).join(', ')})`);
|
|
@@ -20549,6 +20728,8 @@ app.post('/api/morelogin/stop', async (req, res) => {
|
|
|
20549
20728
|
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.`,
|
|
20550
20729
|
});
|
|
20551
20730
|
}
|
|
20731
|
+
// SynaBun's own stop: the sessions in that profile see their browser go, and that is not a close by someone else.
|
|
20732
|
+
_moreLoginStoppedBySynaBun.set(String(envId), Date.now());
|
|
20552
20733
|
await moreLogin.stopProfile(envId, _moreLoginOpts());
|
|
20553
20734
|
_moreLoginStartedBy.delete(String(envId));
|
|
20554
20735
|
res.json({ ok: true });
|
|
@@ -20585,8 +20766,8 @@ app.post('/api/morelogin/use-default', async (req, res) => {
|
|
|
20585
20766
|
|
|
20586
20767
|
// ── A session's own MoreLogin profile (2026-11-10) ──
|
|
20587
20768
|
// POST /api/morelogin/use — the calling session works in a MoreLogin profile of its own from now on:
|
|
20588
|
-
// { envId }, { name } or { profile } (either; a profile MoreLogin lists), or { default: true } to go back to the default
|
|
20589
|
-
//
|
|
20769
|
+
// { envId }, { name } or { profile } (either; a profile MoreLogin lists), or { default: true } to go back to the default AI
|
|
20770
|
+
// browser (Settings → Connected tools → MoreLogin). The choice is the caller's pin (pinRunMoreLoginProfile, the pin a schedule's run is launched with), so its
|
|
20590
20771
|
// acquisitions, its recoveries, the per-request gate and its view of GET /api/browser/sessions all follow it. Nothing
|
|
20591
20772
|
// else changes: not the default AI browser, not another session's pin, tab or route. This is what an agent uses to
|
|
20592
20773
|
// work in a second profile while other automations work in the default one; use-default (which moves everybody) keeps
|
|
@@ -20597,11 +20778,17 @@ app.post('/api/morelogin/use-default', async (req, res) => {
|
|
|
20597
20778
|
// Chrome). A Firefox-type profile is refused (400 MORELOGIN_NOT_CHROMIUM) and the choice stays what it was.
|
|
20598
20779
|
// For a session that proves its id (moreLoginGate: a run's terminal token, a brain's credential, or a plain CLI MCP
|
|
20599
20780
|
// session's own proof, MCP_SESSION_PROOFS), never the owner's page (which has no session: the
|
|
20600
|
-
// owner picks in Settings →
|
|
20781
|
+
// owner picks in Settings → Connected tools → MoreLogin (Default AI browser) or where the run is set up).
|
|
20601
20782
|
const _profileChoiceStore = createProfileChoiceStore({
|
|
20602
20783
|
file: resolve(LOOP_DATA_DIR, 'browser-profile-choices.json'),
|
|
20603
20784
|
log: (line) => console.warn(`[morelogin] ${line}`),
|
|
20604
20785
|
});
|
|
20786
|
+
// A run whose own profile failed to start or connect in this run (lib/morelogin-profile-failures.js): it may not move to
|
|
20787
|
+
// another profile until that profile connects again for it, the owner moves it, or it ends (runProfileSwitchRefusal).
|
|
20788
|
+
const _runProfileFailures = createProfileFailureStore({
|
|
20789
|
+
file: resolve(LOOP_DATA_DIR, 'morelogin-profile-failures.json'),
|
|
20790
|
+
log: (line) => console.warn(`[morelogin] ${line}`),
|
|
20791
|
+
});
|
|
20605
20792
|
|
|
20606
20793
|
/**
|
|
20607
20794
|
* The owners of the saved choices are retired when the server starts (called once, as it starts listening, before any
|
|
@@ -20647,8 +20834,8 @@ async function resolveMoreLoginProfileChoice(ref) {
|
|
|
20647
20834
|
async function chooseSessionMoreLoginProfile(ownerKey, choice) {
|
|
20648
20835
|
const previous = runMoreLoginPin(ownerKey);
|
|
20649
20836
|
// A session's own choice is always an agent's ('agent'): held to the owner's list when it is set (the route) and at
|
|
20650
|
-
// every use (moreLoginPinRefusal).
|
|
20651
|
-
pinRunMoreLoginProfile(ownerKey, choice?.envId || null, choice?.name || null, 'agent');
|
|
20837
|
+
// every use (moreLoginPinRefusal). Not locked: the session chose it, and may choose again.
|
|
20838
|
+
pinRunMoreLoginProfile(ownerKey, choice?.envId || null, choice?.name || null, 'agent', { locked: false });
|
|
20652
20839
|
// A plain MCP session's id dies with this server: its choice is never kept for a restart (MCP_SESSION_PROOFS).
|
|
20653
20840
|
if (!isMcpSessionOwner(ownerKey)) _profileChoiceStore.set(ownerKey, choice?.envId ? choice : null);
|
|
20654
20841
|
const cfg = loadBrowserConfig();
|
|
@@ -20669,28 +20856,62 @@ async function chooseSessionMoreLoginProfile(ownerKey, choice) {
|
|
|
20669
20856
|
return { previous, released };
|
|
20670
20857
|
}
|
|
20671
20858
|
|
|
20859
|
+
/**
|
|
20860
|
+
* 409 PROFILE_PINNED: `owner`'s profile was set up with the run (`pin.locked`), and it asked to move to `choice` (a
|
|
20861
|
+
* profile { envId, name }, or null for the default browser). Nothing changes.
|
|
20862
|
+
*/
|
|
20863
|
+
function refusePinnedProfileMove(res, owner, pin, choice) {
|
|
20864
|
+
const here = describeMoreLoginPin(pin);
|
|
20865
|
+
const there = choice?.envId ? describeMoreLoginPin(choice) : 'the default browser';
|
|
20866
|
+
console.warn(`[morelogin] ${logOwnerId(owner)} is pinned to ${here}: its move to ${there} was refused`);
|
|
20867
|
+
loopLog(owner, 'browser:profile', `refused: this run is pinned to ${here} and cannot move to ${there}`, { pinned: pin.envId, asked: choice?.envId || null });
|
|
20868
|
+
return res.status(409).json({
|
|
20869
|
+
ok: false, code: 'PROFILE_PINNED', envId: pin.envId, name: pin.name || null,
|
|
20870
|
+
error: `This run is pinned to ${here} (set where the run is set up: its schedule, group, launch or dispatch); it cannot move to ${there}. Nothing was changed: it still works in ${here}. A pinned run never switches profiles by itself: if its profile cannot be used (closed, not running, refused by MoreLogin), report that to the user and stop. The owner changes a run's profile where the run is set up.`,
|
|
20871
|
+
});
|
|
20872
|
+
}
|
|
20873
|
+
|
|
20672
20874
|
app.post('/api/morelogin/use', async (req, res) => {
|
|
20673
20875
|
try {
|
|
20674
20876
|
const who = browserCaller(req);
|
|
20675
20877
|
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
20676
20878
|
const owner = who.automation ? browserOwnerId(who.id) : null;
|
|
20677
20879
|
if (!owner) {
|
|
20678
|
-
return res.status(400).json({ ok: false, code: 'SESSION_REQUIRED', error: 'This picks the MoreLogin profile of the calling agent session (the morelogin tool\'s "use" action). The owner picks the default in Settings →
|
|
20880
|
+
return res.status(400).json({ ok: false, code: 'SESSION_REQUIRED', error: 'This picks the MoreLogin profile of the calling agent session (the morelogin tool\'s "use" action). The owner picks the default in Settings → Connected tools → MoreLogin (Default AI browser), and a run\'s profile where the run is set up.' });
|
|
20679
20881
|
}
|
|
20680
20882
|
if (automationRunState(owner) === 'ended') {
|
|
20681
20883
|
return res.status(409).json({ ok: false, code: 'RUN_ENDED', error: `Run ${owner} has ended: its browser profile is not changed.` });
|
|
20682
20884
|
}
|
|
20683
20885
|
const body = req.body || {};
|
|
20684
20886
|
const toDefault = body.default === true || body.default === 'true';
|
|
20887
|
+
// A run whose own profile failed to start or connect in this run does not move to another profile or browser, even
|
|
20888
|
+
// one it chose itself (2026-11-15 21:13:43: run 8d50b030 had chosen P-4 with `use`, P-4 failed to connect, it moved
|
|
20889
|
+
// itself to P-1 and its next browser call started P-1, one of MoreLogin's daily launches). Refused here, before
|
|
20890
|
+
// MoreLogin is asked for anything; naming the failed profile itself is no move and goes on below. Lifted when that
|
|
20891
|
+
// profile connects again for the run, the owner moves the run, or it ends (lib/morelogin-profile-failures.js).
|
|
20892
|
+
const failedBar = runProfileSwitchRefusal(owner, toDefault ? { toDefault: true } : { envId: body.envId, name: body.name, profile: body.profile });
|
|
20893
|
+
if (failedBar) return refuseProfileSwitchAfterFailure(res, failedBar);
|
|
20894
|
+
// A run whose setup pinned its profile (a schedule, a group, a timer, a launch, a dispatch's morelogin_profile)
|
|
20895
|
+
// stays there: it is refused before anything is resolved or changed when it asks for the default browser, and
|
|
20896
|
+
// below when it names another profile (2026-11-15: a run on P-4 whose profile had gone moved itself to P-1, and
|
|
20897
|
+
// its recovery started P-1, one of MoreLogin's daily launches). A session that chose its profile itself may still
|
|
20898
|
+
// choose again (today's behaviour).
|
|
20899
|
+
const pinnedBefore = runMoreLoginPin(owner);
|
|
20900
|
+
if (pinnedBefore?.locked && toDefault) return refusePinnedProfileMove(res, owner, pinnedBefore, null);
|
|
20685
20901
|
// The owner's list (review b6631e9d, finding 1): a session works only in a profile the owner allowed agents to
|
|
20686
20902
|
// choose. Going back to the default needs no entry. Whoever calls this is never the owner's page (SESSION_REQUIRED
|
|
20687
20903
|
// above), so there is no exception here. The gate in front proved the caller's id (MORELOGIN_VERIFIED_ROUTES).
|
|
20688
20904
|
const choice = toDefault ? null : await agentMoreLoginProfileChoice({ envId: body.envId, name: body.name, profile: body.profile });
|
|
20905
|
+
// Asked again with what the name resolved to (a name the failed profile had may now be another profile's).
|
|
20906
|
+
const resolvedBar = choice ? runProfileSwitchRefusal(owner, { envId: choice.envId, name: choice.name, resolved: true }) : null;
|
|
20907
|
+
if (resolvedBar) return refuseProfileSwitchAfterFailure(res, resolvedBar);
|
|
20689
20908
|
const before = runMoreLoginPin(owner);
|
|
20690
|
-
|
|
20691
|
-
//
|
|
20909
|
+
if (before?.locked && (before.envId || null) !== (choice?.envId || null)) return refusePinnedProfileMove(res, owner, before, choice);
|
|
20910
|
+
// Asked again for what it already has: nothing is released (its tab there stays its tab), a pin the owner's
|
|
20911
|
+
// page set at launch stays the owner's (it is not rewritten as the session's own), and a pin its setup made stays
|
|
20912
|
+
// locked.
|
|
20692
20913
|
if ((before?.envId || null) === (choice?.envId || null)) {
|
|
20693
|
-
if (choice && before?.by !== 'owner') { pinRunMoreLoginProfile(owner, choice.envId, choice.name, 'agent'); if (!isMcpSessionOwner(owner)) _profileChoiceStore.set(owner, choice); }
|
|
20914
|
+
if (choice && before?.by !== 'owner' && !before?.locked) { pinRunMoreLoginProfile(owner, choice.envId, choice.name, 'agent', { locked: false }); if (!isMcpSessionOwner(owner)) _profileChoiceStore.set(owner, choice); }
|
|
20694
20915
|
return res.json({ ok: true, changed: false, envId: choice?.envId || null, name: choice?.name || null, default: !choice, released: [] });
|
|
20695
20916
|
}
|
|
20696
20917
|
const { previous, released } = await chooseSessionMoreLoginProfile(owner, choice);
|
|
@@ -21213,16 +21434,31 @@ function readClaudeSettingsForWrite(filePath) {
|
|
|
21213
21434
|
function writeClaudeSettings(filePath, data) {
|
|
21214
21435
|
const dir = dirname(filePath);
|
|
21215
21436
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
21437
|
+
// The settings file may be a link (dotfiles, a synced folder): the file behind it is the one written, and the
|
|
21438
|
+
// link stays. A rename over the link would leave a plain file here and the linked one as it was, so whatever
|
|
21439
|
+
// makes the link again later brings the old content back, without anything changed through SynaBun.
|
|
21440
|
+
let target = filePath;
|
|
21441
|
+
try { if (existsSync(filePath)) target = realpathSync(filePath); } catch { /* written where it was asked */ }
|
|
21216
21442
|
// Write atomically. A half-written settings.json (crash or full disk during
|
|
21217
21443
|
// writeFileSync) is what makes the corrupt-read path reachable to begin with.
|
|
21218
|
-
const tmpPath = `${
|
|
21444
|
+
const tmpPath = `${target}.tmp-${process.pid}`;
|
|
21445
|
+
// A file with other names (a named Claude account on Windows shares settings.json by a hard link,
|
|
21446
|
+
// lib/claude-account-links.js) is written in place: a rename would leave the other names the old file.
|
|
21447
|
+
let names = 1;
|
|
21448
|
+
try { names = Number(statSync(target).nlink) || 1; } catch {}
|
|
21219
21449
|
try {
|
|
21220
21450
|
writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf-8');
|
|
21221
|
-
renameSync(tmpPath,
|
|
21451
|
+
if (names > 1) { writeFileSync(target, readFileSync(tmpPath)); unlinkSync(tmpPath); } else renameSync(tmpPath, target);
|
|
21222
21452
|
} catch (err) {
|
|
21223
21453
|
try { if (existsSync(tmpPath)) unlinkSync(tmpPath); } catch {}
|
|
21224
21454
|
throw err;
|
|
21225
21455
|
}
|
|
21456
|
+
// The default's settings changed: every named account reads the same (a hard link that Claude Code's own
|
|
21457
|
+
// rename-write split, or a copy, is brought back in step). Never stops a write.
|
|
21458
|
+
try {
|
|
21459
|
+
const accounts = _panelClaudeAccounts();
|
|
21460
|
+
if ([getGlobalClaudeSettingsPath(), join(accounts.defaultHome, 'settings.json')].some((path) => resolve(path) === resolve(filePath))) accounts.syncShared();
|
|
21461
|
+
} catch {}
|
|
21226
21462
|
}
|
|
21227
21463
|
|
|
21228
21464
|
function isHookInstalled(settings, targetProjectPath) {
|
|
@@ -21599,11 +21835,51 @@ const SYNABUN_TOOL_CATEGORIES = [
|
|
|
21599
21835
|
},
|
|
21600
21836
|
];
|
|
21601
21837
|
|
|
21838
|
+
// ── The owner's tool-permission choices (lib/tool-permission-choices.js) ──
|
|
21839
|
+
// The switches of Settings → Tool permissions are drawn from, and change, the allow list of the user's
|
|
21840
|
+
// ~/.claude/settings.json: Claude Code's own file, which other things rewrite and replace. SynaBun keeps what the
|
|
21841
|
+
// owner chose in its data home too (DATA_HOME/data/tool-permissions.json, never touched by an install or an
|
|
21842
|
+
// update) and puts back what went missing: every saved tool at a start (an update is a start), and at a read
|
|
21843
|
+
// only when all of them are gone at once. A tool the owner switched off is never allowed by SynaBun itself; a
|
|
21844
|
+
// tool nobody chose (one that is new in an update) keeps the default: off until it is switched on.
|
|
21845
|
+
const TOOL_PERMISSION_KEYS = new Set(SYNABUN_TOOL_CATEGORIES.flatMap(cat => cat.tools.map(t => t.key)));
|
|
21846
|
+
const toolChoices = createToolPermissionChoices({
|
|
21847
|
+
path: resolve(DATA_HOME, 'data', TOOL_CHOICES_FILE),
|
|
21848
|
+
appVersion: SERVER_VERSION,
|
|
21849
|
+
log: (line) => console.log(line),
|
|
21850
|
+
});
|
|
21851
|
+
/** Bring the allow list in line with the saved choices. `reason`: 'start' | 'read'. Never throws. */
|
|
21852
|
+
function reconcileSavedToolPermissions(reason) {
|
|
21853
|
+
try {
|
|
21854
|
+
const result = reconcileToolPermissions({
|
|
21855
|
+
store: toolChoices, settingsPath: getGlobalClaudeSettingsPath(), known: TOOL_PERMISSION_KEYS, reason,
|
|
21856
|
+
read: readClaudeSettingsForWrite, write: writeClaudeSettings, log: (line) => console.log(line),
|
|
21857
|
+
});
|
|
21858
|
+
if (result.state === 'error' && reason === 'start') console.warn(`[tool-permissions] the saved choices were not applied: ${result.message}`);
|
|
21859
|
+
// Codex reads its own copy of the list (config.toml): it gets what was put back.
|
|
21860
|
+
if (result.state === 'restored') { try { syncCodexToolPermissions(result.allow); } catch { /* Codex's file is its own matter */ } }
|
|
21861
|
+
return result;
|
|
21862
|
+
} catch (err) {
|
|
21863
|
+
console.warn(`[tool-permissions] the saved choices were not applied: ${err.message}`);
|
|
21864
|
+
return { state: 'error', restored: [], adopted: [], allow: [], message: err.message };
|
|
21865
|
+
}
|
|
21866
|
+
}
|
|
21867
|
+
/** The on / off state of every tool, as the allow list has it. */
|
|
21868
|
+
function toolPermissionStates(allow) {
|
|
21869
|
+
const allowed = new Set(Array.isArray(allow) ? allow : []);
|
|
21870
|
+
const tools = {};
|
|
21871
|
+
for (const cat of SYNABUN_TOOL_CATEGORIES) {
|
|
21872
|
+
for (const t of cat.tools) tools[t.key] = allowed.has(t.key);
|
|
21873
|
+
}
|
|
21874
|
+
return tools;
|
|
21875
|
+
}
|
|
21876
|
+
|
|
21602
21877
|
// ── Memory-tool permission auto-injection ──
|
|
21603
|
-
// On MCP enable for any provider,
|
|
21878
|
+
// On MCP enable for any provider, allow the 7 SynaBun memory tools
|
|
21604
21879
|
// (recall/remember/reflect/forget/memories/restore/sync) so PTY/CLI sessions
|
|
21605
21880
|
// can use SynaBun memory without per-call permission prompts. Inject-only,
|
|
21606
|
-
// never overwrites existing entries
|
|
21881
|
+
// never overwrites existing entries, and never a tool the owner switched off
|
|
21882
|
+
// in Settings → Tool permissions. Falls back to project-scoped settings
|
|
21607
21883
|
// when the user has no global settings file.
|
|
21608
21884
|
function getMemoryToolKeys() {
|
|
21609
21885
|
const cat = SYNABUN_TOOL_CATEGORIES.find(c => c.id === 'memory');
|
|
@@ -21623,7 +21899,7 @@ function ensureOpenCodeCoreMcpPermissions(config) {
|
|
|
21623
21899
|
}
|
|
21624
21900
|
|
|
21625
21901
|
function injectClaudeMemoryPerms() {
|
|
21626
|
-
const keys = getMemoryToolKeys();
|
|
21902
|
+
const keys = getMemoryToolKeys().filter(k => !toolChoices.isOff(k));
|
|
21627
21903
|
const globalPath = getGlobalClaudeSettingsPath();
|
|
21628
21904
|
|
|
21629
21905
|
if (existsSync(globalPath)) {
|
|
@@ -21634,6 +21910,7 @@ function injectClaudeMemoryPerms() {
|
|
|
21634
21910
|
for (const k of keys) set.add(k);
|
|
21635
21911
|
settings.permissions.allow = [...set];
|
|
21636
21912
|
writeClaudeSettings(globalPath, settings);
|
|
21913
|
+
toolChoices.adopt(settings.permissions.allow, TOOL_PERMISSION_KEYS);
|
|
21637
21914
|
return { scope: 'global', paths: [globalPath] };
|
|
21638
21915
|
}
|
|
21639
21916
|
|
|
@@ -22325,6 +22602,7 @@ let _codexSessionCatalogRefresh = null;
|
|
|
22325
22602
|
function getCodexSessionCatalogRefresh() {
|
|
22326
22603
|
if (!_codexSessionCatalogRefresh) {
|
|
22327
22604
|
_codexSessionCatalogRefresh = memoCache(() => rebuildCodexCache({
|
|
22605
|
+
background: true,
|
|
22328
22606
|
accounts: loadCodexAccounts().accounts,
|
|
22329
22607
|
projects: loadHookProjects(),
|
|
22330
22608
|
}), { ttlMs: 15000 });
|
|
@@ -23589,19 +23867,20 @@ app.get('/api/claude-code/tool-categories', (req, res) => {
|
|
|
23589
23867
|
});
|
|
23590
23868
|
|
|
23591
23869
|
// GET /api/claude-code/tool-permissions — current permission state for all SynaBun tools
|
|
23870
|
+
// `capabilities`: what the PUT below takes beyond one tool or one category (`categories`: several groups in one
|
|
23871
|
+
// request), so a page that was reloaded before this server was restarted knows what it can ask.
|
|
23592
23872
|
app.get('/api/claude-code/tool-permissions', (req, res) => {
|
|
23593
23873
|
try {
|
|
23874
|
+
// A file that lost every saved tool at once was replaced: the saved choices go back before it is read.
|
|
23875
|
+
const reconciled = reconcileSavedToolPermissions('read');
|
|
23594
23876
|
const globalPath = getGlobalClaudeSettingsPath();
|
|
23595
23877
|
const settings = readClaudeSettings(globalPath) || {};
|
|
23596
|
-
|
|
23597
|
-
|
|
23598
|
-
|
|
23599
|
-
|
|
23600
|
-
|
|
23601
|
-
|
|
23602
|
-
}
|
|
23603
|
-
}
|
|
23604
|
-
res.json({ ok: true, tools });
|
|
23878
|
+
res.json({
|
|
23879
|
+
ok: true,
|
|
23880
|
+
tools: toolPermissionStates(settings.permissions?.allow),
|
|
23881
|
+
capabilities: ['categories'],
|
|
23882
|
+
...(reconciled.restored.length ? { restored: reconciled.restored.length } : {}),
|
|
23883
|
+
});
|
|
23605
23884
|
} catch (err) {
|
|
23606
23885
|
res.status(500).json({ error: err.message });
|
|
23607
23886
|
}
|
|
@@ -23686,30 +23965,48 @@ app.delete('/api/claude-code/permission-rules', express.json(), (req, res) => {
|
|
|
23686
23965
|
// The user scope of a tab under a named account is that account's file.
|
|
23687
23966
|
const accountHome = panelAccountHome(req.body?.account);
|
|
23688
23967
|
const result = removePermissionRule({ home: process.env.USERPROFILE || process.env.HOME, accountHome, project, scope, list, rule });
|
|
23968
|
+
// An allow rule of one of SynaBun's tools, taken out of the user's own settings: that tool is off by the owner's
|
|
23969
|
+
// choice from now on, so a start does not put it back (lib/tool-permission-choices.js).
|
|
23970
|
+
if (result.removed && scope === 'user' && list === 'allow' && TOOL_PERMISSION_KEYS.has(rule)
|
|
23971
|
+
&& (!accountHome || userSettingsFile({ home: process.env.USERPROFILE || process.env.HOME, accountHome }).shared)) {
|
|
23972
|
+
toolChoices.note([rule], false);
|
|
23973
|
+
}
|
|
23689
23974
|
res.json({ ok: true, removed: result.removed });
|
|
23690
23975
|
} catch (err) {
|
|
23691
23976
|
res.status(err?.status || 500).json({ ok: false, error: err.message, ...(err?.code ? { code: err.code } : {}) });
|
|
23692
23977
|
}
|
|
23693
23978
|
});
|
|
23694
23979
|
|
|
23695
|
-
// PUT /api/claude-code/tool-permissions — toggle
|
|
23980
|
+
// PUT /api/claude-code/tool-permissions — toggle one tool, one category group, or several groups at once
|
|
23981
|
+
// (`categories`: the switch in the section's header sends the groups it shows). What is switched is also
|
|
23982
|
+
// written down as the owner's choice (toolChoices), which is what a later start puts back.
|
|
23696
23983
|
app.put('/api/claude-code/tool-permissions', (req, res) => {
|
|
23697
23984
|
try {
|
|
23698
|
-
const { tool, category, enabled } = req.body;
|
|
23985
|
+
const { tool, category, categories, enabled } = req.body || {};
|
|
23699
23986
|
if (typeof enabled !== 'boolean') {
|
|
23700
23987
|
return res.status(400).json({ error: 'enabled (boolean) is required.' });
|
|
23701
23988
|
}
|
|
23702
|
-
if (
|
|
23703
|
-
return res.status(400).json({ error: '
|
|
23989
|
+
if (categories !== undefined && (!Array.isArray(categories) || !categories.length || categories.some(id => typeof id !== 'string'))) {
|
|
23990
|
+
return res.status(400).json({ error: 'categories must be a list of category ids.' });
|
|
23991
|
+
}
|
|
23992
|
+
if (!tool && !category && !categories) {
|
|
23993
|
+
return res.status(400).json({ error: 'Provide tool (string), category (string) or categories (list).' });
|
|
23704
23994
|
}
|
|
23705
23995
|
|
|
23706
23996
|
// Resolve which tool keys to toggle
|
|
23707
23997
|
let keys = [];
|
|
23708
|
-
if (
|
|
23998
|
+
if (categories) {
|
|
23999
|
+
for (const id of new Set(categories)) {
|
|
24000
|
+
const cat = SYNABUN_TOOL_CATEGORIES.find(c => c.id === id);
|
|
24001
|
+
if (!cat) return res.status(400).json({ error: `Unknown category: ${id}` });
|
|
24002
|
+
keys.push(...cat.tools.map(t => t.key));
|
|
24003
|
+
}
|
|
24004
|
+
} else if (category) {
|
|
23709
24005
|
const cat = SYNABUN_TOOL_CATEGORIES.find(c => c.id === category);
|
|
23710
24006
|
if (!cat) return res.status(400).json({ error: `Unknown category: ${category}` });
|
|
23711
24007
|
keys = cat.tools.map(t => t.key);
|
|
23712
24008
|
} else {
|
|
24009
|
+
if (typeof tool !== 'string') return res.status(400).json({ error: 'tool must be a string.' });
|
|
23713
24010
|
keys = [tool];
|
|
23714
24011
|
}
|
|
23715
24012
|
|
|
@@ -23726,6 +24023,8 @@ app.put('/api/claude-code/tool-permissions', (req, res) => {
|
|
|
23726
24023
|
}
|
|
23727
24024
|
settings.permissions.allow = [...allowSet];
|
|
23728
24025
|
writeClaudeSettings(globalPath, settings);
|
|
24026
|
+
// The owner's choice, in SynaBun's own data home: what an update, a restore or a replaced file cannot take.
|
|
24027
|
+
toolChoices.note(keys, enabled);
|
|
23729
24028
|
|
|
23730
24029
|
// Cascade to registered projects
|
|
23731
24030
|
const projects = loadHookProjects();
|
|
@@ -23749,14 +24048,7 @@ app.put('/api/claude-code/tool-permissions', (req, res) => {
|
|
|
23749
24048
|
syncCodexToolPermissions(settings.permissions.allow);
|
|
23750
24049
|
|
|
23751
24050
|
// Return updated state
|
|
23752
|
-
|
|
23753
|
-
const tools = {};
|
|
23754
|
-
for (const cat of SYNABUN_TOOL_CATEGORIES) {
|
|
23755
|
-
for (const t of cat.tools) {
|
|
23756
|
-
tools[t.key] = updatedAllowed.has(t.key);
|
|
23757
|
-
}
|
|
23758
|
-
}
|
|
23759
|
-
res.json({ ok: true, tools });
|
|
24051
|
+
res.json({ ok: true, tools: toolPermissionStates(settings.permissions.allow) });
|
|
23760
24052
|
} catch (err) {
|
|
23761
24053
|
res.status(500).json({ error: err.message });
|
|
23762
24054
|
}
|
|
@@ -23978,6 +24270,7 @@ function syncCodexToolPermissions(allowedKeys, codexHome = CODEX_DEFAULT_HOME) {
|
|
|
23978
24270
|
}
|
|
23979
24271
|
|
|
23980
24272
|
writeFileSync(configPath, content, 'utf-8');
|
|
24273
|
+
try { codexSharedFilesChanged(); } catch { /* never stops the write */ }
|
|
23981
24274
|
} catch (err) {
|
|
23982
24275
|
console.error('[codex-perm-sync] Failed to sync Codex tool permissions:', err.message);
|
|
23983
24276
|
}
|
|
@@ -24101,6 +24394,7 @@ app.post('/api/setup/codex/mcp', (req, res) => {
|
|
|
24101
24394
|
const health = upsertCodexMcpConfig(configPath, buildCodexMcpDefinition());
|
|
24102
24395
|
// Force-allow the 7 SynaBun memory tools so CLI sessions skip prompts.
|
|
24103
24396
|
injectCodexMemoryPerms();
|
|
24397
|
+
codexSharedFilesChanged();
|
|
24104
24398
|
res.json({ ok: true, ...health, message: 'SynaBun MCP registered in Codex CLI. Restart Codex to connect.', rules: syncRulesWithMcp('codex', 'install', req.body) });
|
|
24105
24399
|
} catch (err) {
|
|
24106
24400
|
res.status(500).json({ error: err.message });
|
|
@@ -24112,6 +24406,7 @@ app.delete('/api/setup/codex/mcp', (req, res) => {
|
|
|
24112
24406
|
const configPath = join(CODEX_DEFAULT_HOME, 'config.toml');
|
|
24113
24407
|
if (!existsSync(configPath)) return res.json({ ok: true, rules: syncRulesWithMcp('codex', 'remove') });
|
|
24114
24408
|
const health = removeCodexMcpConfig(configPath);
|
|
24409
|
+
codexSharedFilesChanged();
|
|
24115
24410
|
res.json({ ok: true, ...health, message: 'SynaBun MCP removed from Codex CLI.', rules: syncRulesWithMcp('codex', 'remove') });
|
|
24116
24411
|
} catch (err) {
|
|
24117
24412
|
res.status(500).json({ error: err.message });
|
|
@@ -24344,6 +24639,71 @@ registerSkillEvalRoutes(app, {
|
|
|
24344
24639
|
pageSession: _pageSession,
|
|
24345
24640
|
});
|
|
24346
24641
|
|
|
24642
|
+
// ════ agents-p1 BEGIN: the Agents system's registry, resolver and API (docs/agents.md, lib/coordination/README.md) ════
|
|
24643
|
+
// The one block of the Agents system's phase P1 in this file. The registry of agent definitions
|
|
24644
|
+
// (DATA_HOME/data/agents: one editable draft and immutable approved revisions per agent and scope, lib/agents/registry.js),
|
|
24645
|
+
// the resolver that turns a dispatch's `agent_ref` into a run (lib/agents/resolve.js: the dispatcher's intake and the
|
|
24646
|
+
// Assistant's /route ask the resolver of the process, which is set here, so nothing else in this file hands it over),
|
|
24647
|
+
// and the routes of Agents Studio under /api/agents-studio/v1 (lib/agents-studio-api.js: approving, deleting and test
|
|
24648
|
+
// runs are the owner's page only, as the Skills Service's installs are). The older /api/agents routes above (isolated
|
|
24649
|
+
// agent processes) are another thing and stay as they are.
|
|
24650
|
+
import { createAgentRegistry, loadBuiltinAgents } from './lib/agents/registry.js';
|
|
24651
|
+
import { createAgentResolver, setAgentResolver } from './lib/agents/resolve.js';
|
|
24652
|
+
import { registerStudioAttention } from './lib/studio-attention.js';
|
|
24653
|
+
import { registerAgentsStudioRoutes } from './lib/agents-studio-api.js';
|
|
24654
|
+
const agentDefinitions = createAgentRegistry({
|
|
24655
|
+
builtins: loadBuiltinAgents(),
|
|
24656
|
+
dir: resolve(DATA_HOME, 'data', 'agents'),
|
|
24657
|
+
// Every page of the owner hears of a change; invite guests do not (broadcastSync keeps `assistant:` to the owner).
|
|
24658
|
+
emit: (event) => { try { broadcastSync({ type: 'assistant:agents-changed', event }); } catch { /* no page is listening */ } },
|
|
24659
|
+
});
|
|
24660
|
+
registerStudioAttention(app, {
|
|
24661
|
+
ownerPage: (req, res, next) => ownerPageApprovalCall(req) ? next() : refuseNotOwnerPage(req, res, 'The Studio attention indicator is available on the owner’s page.'),
|
|
24662
|
+
agents: () => agentDefinitions.list({ status: 'in_review' }),
|
|
24663
|
+
teams: () => _assistantTeamScheduler?.list({ open: true }) || [],
|
|
24664
|
+
reviews: () => skillReviews.list({ state: 'pending' }),
|
|
24665
|
+
// Only the marks and schedule state are used. No tool resolution or approval evidence is needed.
|
|
24666
|
+
templates: () => mergeLoopItemsById(readLoopTemplateFiles(), 'templates'),
|
|
24667
|
+
schedules: () => mergeLoopItemsById(readLoopScheduleFiles(), 'schedules'),
|
|
24668
|
+
workers: () => _assistantDispatcher?.hasRunAwaitingOwner() || false,
|
|
24669
|
+
nativeRuns: () => _nativeLoopRuntime?.list({ activeOnly: true }) || [],
|
|
24670
|
+
});
|
|
24671
|
+
const agentDefinitionResolver = setAgentResolver(createAgentResolver({ registry: agentDefinitions }));
|
|
24672
|
+
// ── agents-p6 BEGIN: what agent-forge and native export read from this server (lib/agents/forge-host.js) ──
|
|
24673
|
+
// The guide is the shipped skill skills/agent-forge; the catalog a definition is filled from is asked of the parts
|
|
24674
|
+
// that own it (the Assistant's model catalog, the tool catalog, the project's style guide, the MoreLogin profiles
|
|
24675
|
+
// the owner lets agents choose); a native export goes where Skills Studio's own agent files go (Claude Code's config
|
|
24676
|
+
// dir, OpenCode's configuration folder, or a registered project), and only the owner's page writes one.
|
|
24677
|
+
import { createAgentForgeHost } from './lib/agents/forge-host.js';
|
|
24678
|
+
const agentForgeHost = createAgentForgeHost({
|
|
24679
|
+
skillsDir: SKILLS_SOURCE_DIR,
|
|
24680
|
+
catalog: async ({ provider = null, q = null } = {}) => (_assistantCatalog ? _assistantCatalog.get({ view: 'brain', provider, q }) : null),
|
|
24681
|
+
styleGuide: (projectPath) => { const guide = styleGuideStore.load(projectPath); return guide?.saved ? guide.config : null; },
|
|
24682
|
+
moreloginProfiles: () => moreLoginAgentProfiles(),
|
|
24683
|
+
projects: () => { try { return loadHookProjects().filter((p) => p?.path).map((p) => ({ path: p.path, label: p.label || basename(p.path) })); } catch { return []; } },
|
|
24684
|
+
claudeHome: () => studioClaudeHome(),
|
|
24685
|
+
claudeHomes: () => { try { return _panelClaudeAccounts().list().map((row) => ({ id: row.id, home: row.home })); } catch { return []; } },
|
|
24686
|
+
opencodeConfigDir: () => getOpencodeConfigDir(),
|
|
24687
|
+
homeDir: getHomePath(),
|
|
24688
|
+
onExport: (event) => { try { broadcastSync({ type: 'assistant:agents-changed', event }); } catch { /* no page is listening */ } },
|
|
24689
|
+
});
|
|
24690
|
+
// ── agents-p6 END ──
|
|
24691
|
+
registerAgentsStudioRoutes(app, {
|
|
24692
|
+
registry: agentDefinitions, resolver: agentDefinitionResolver, isGuestRequest,
|
|
24693
|
+
forge: agentForgeHost, // agents-p6
|
|
24694
|
+
// The runs of an agent and the owner's test run (the dispatcher is made later, with the Assistant).
|
|
24695
|
+
dispatcher: () => _assistantDispatcher,
|
|
24696
|
+
ownerGuard: ownerRouteGuard({ isGuestRequest, port: PORT, allowedOrigins: publicWebOrigins, refuseCrossSite: true, ownOriginsOnly: true, requireOrigin: true }),
|
|
24697
|
+
// The owner's writes carry the page secret (lib/page-session.js): a local process without it is refused.
|
|
24698
|
+
pageSession: _pageSession,
|
|
24699
|
+
// An agent is the Assistant only by its brain's launch credential (never by X-Synabun-Role alone).
|
|
24700
|
+
assistantOf: (req) => skillsAssistantOf(req),
|
|
24701
|
+
// An agent's X-Synabun-Terminal (its author's name) counts only with its proof (browserCaller).
|
|
24702
|
+
terminalRefusal: (req) => { const who = browserCaller(req); return who.accepted ? null : { status: who.httpStatus || 403, code: who.code, error: who.error }; },
|
|
24703
|
+
projects: () => { try { return loadHookProjects().filter((p) => p?.path).map((p) => ({ path: p.path, label: p.label || basename(p.path) })); } catch { return []; } },
|
|
24704
|
+
});
|
|
24705
|
+
// ════ agents-p1 END ════
|
|
24706
|
+
|
|
24347
24707
|
/**
|
|
24348
24708
|
* Each runtime an evaluation can run on here: found (the same answer as drafting's), held to its folder, and whether
|
|
24349
24709
|
* a case that needs a shell can have one (Codex: its own sandbox, always, and Codex is the owner's opt-in per skill
|
|
@@ -24465,7 +24825,7 @@ function skillDraftingAvailability() {
|
|
|
24465
24825
|
return { available: !!any, reason: any ? null : (claude?.reason || 'No provider that can draft was found on this computer.'), providers };
|
|
24466
24826
|
}
|
|
24467
24827
|
|
|
24468
|
-
/** Whether the SynaBun browser (the
|
|
24828
|
+
/** Whether the SynaBun browser (the default AI browser: a MoreLogin tab profile, else SynaBun's own) can open a page for a draft now, and if not why. */
|
|
24469
24829
|
function skillBrowserAvailability() {
|
|
24470
24830
|
try {
|
|
24471
24831
|
const cfg = loadBrowserConfig();
|
|
@@ -24475,14 +24835,14 @@ function skillBrowserAvailability() {
|
|
|
24475
24835
|
// The default is one of SynaBun's own local profiles: MoreLogin is not needed for it.
|
|
24476
24836
|
return moreLogin.localProfileName(String(cfg.moreloginEnvId))
|
|
24477
24837
|
? { available: true, reason: null }
|
|
24478
|
-
: { available: false, reason: 'The default browser (Settings →
|
|
24838
|
+
: { available: false, reason: 'The default AI browser (Settings → Connected tools → MoreLogin) is a local profile that no longer exists: choose another one.' };
|
|
24479
24839
|
}
|
|
24480
24840
|
if (cfg.connectMode === 'morelogin') {
|
|
24481
24841
|
// The exe in a known folder, or the local API answered lately (an install in a custom folder). This is read
|
|
24482
24842
|
// synchronously, so a miss refreshes the answer in the background for the next call.
|
|
24483
24843
|
const installed = moreLogin.isMoreLoginPresent();
|
|
24484
24844
|
if (!installed) moreLogin.probeMoreLoginApi({ savedCfg: cfg, timeout: 1500 }).catch(() => {});
|
|
24485
|
-
return installed ? { available: true, reason: null } : { available: false, reason: 'MoreLogin is the default browser (Settings →
|
|
24845
|
+
return installed ? { available: true, reason: null } : { available: false, reason: 'MoreLogin is the default AI browser (Settings → Connected tools → MoreLogin) and it was not found: its app is in no known folder and its local API does not answer.' };
|
|
24486
24846
|
}
|
|
24487
24847
|
if ([...browserSessions.values()].some((s) => s?.context)) return { available: true, reason: null };
|
|
24488
24848
|
if (findBrowserExecutable(cfg.channel)) return { available: true, reason: null };
|
|
@@ -26514,7 +26874,7 @@ app.get('/api/health', (req, res) => {
|
|
|
26514
26874
|
// page showing the restart tells this one from the one that replaces it.
|
|
26515
26875
|
bootId: SERVER_BOOT_ID,
|
|
26516
26876
|
...(_restartRequestedAt && !_stopOverridesRestart ? { restarting: true } : {}),
|
|
26517
|
-
// Whether the owner's authority can be checked (lib/peer-identity.js): ok / degraded (macOS, the lookup fails:
|
|
26877
|
+
// Whether the owner's authority can be checked (lib/peer-identity.js): pending at boot / ok / degraded (macOS, the lookup fails:
|
|
26518
26878
|
// the owner's actions answer 503 until it works) / unsupported (no lookup on this platform) / off
|
|
26519
26879
|
// (SYNABUN_PEER_IDENTITY=off). The page's banner reads it (public/shared/ui-owner-authority.js).
|
|
26520
26880
|
ownerAuthority: _peerIdentity.authorityState(),
|
|
@@ -29059,6 +29419,48 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29059
29419
|
},
|
|
29060
29420
|
});
|
|
29061
29421
|
|
|
29422
|
+
// What the computer-use service says about who holds the desktop now (its `status().control`), once it exists: read by
|
|
29423
|
+
// the evidence line of a MoreLogin profile closed outside SynaBun (lib/browser-close-evidence.js). null until then.
|
|
29424
|
+
let _desktopControlProbe = null;
|
|
29425
|
+
// MoreLogin profiles SynaBun itself stopped (POST /api/morelogin/stop): envId → when. A browser that goes within
|
|
29426
|
+
// a minute of that is not reported as closed outside SynaBun.
|
|
29427
|
+
const _moreLoginStoppedBySynaBun = new Map();
|
|
29428
|
+
|
|
29429
|
+
/**
|
|
29430
|
+
* A MoreLogin profile session's browser context closed (createBrowserSession's context 'close' handler): who closed
|
|
29431
|
+
* it, said once. Returns what it decided:
|
|
29432
|
+
* 'revoked' — SynaBun's OpenCode serve boundary let go of the context (lib/opencode-native-boundary.js
|
|
29433
|
+
* revokeNativeContext: the profile's window is kept). Never "outside SynaBun", never a mark.
|
|
29434
|
+
* 'synabun' — SynaBun closed it: its own teardown (destroyBrowserSession took the session out of the map first) or
|
|
29435
|
+
* POST /api/morelogin/stop in the last minute.
|
|
29436
|
+
* 'outside' — nobody in SynaBun: the evidence line (lib/browser-close-evidence.js), and the close is remembered for
|
|
29437
|
+
* the profile (lib/morelogin-outside-close.js): no automatic path starts it again (each start spends one
|
|
29438
|
+
* of MoreLogin's daily launches) until the owner starts it, a new scheduled run fires, or MoreLogin's
|
|
29439
|
+
* daily reset. The runs it orphaned are kept on the mark (their loops end after their turn).
|
|
29440
|
+
* null — not a MoreLogin profile (a local profile, another browser).
|
|
29441
|
+
* Before 2026-11-15 a revocation was reported as closed outside SynaBun: the 21:13:30 and 21:14:22 lines of that night
|
|
29442
|
+
* were SynaBun's own (a foreign OpenCode serve failed its check while it was exiting, and the revocation closed every
|
|
29443
|
+
* page of P-1 and P-4).
|
|
29444
|
+
*/
|
|
29445
|
+
function noteMoreLoginContextClose(session, sessionId, context = session?.context) {
|
|
29446
|
+
if (session?._profileMode !== 'morelogin' || !session._mlEnvId || moreLogin.isLocalProfileId(String(session._mlEnvId))) return null;
|
|
29447
|
+
const envId = String(session._mlEnvId);
|
|
29448
|
+
const revoked = nativeContextRevocation(context);
|
|
29449
|
+
if (revoked) {
|
|
29450
|
+
console.log(`[morelogin] SynaBun let go of profile ${envId} (session ${sessionId}): the OpenCode serve check revoked its browser context (${revoked.why || 'no reason given'}). Its window was kept open; nobody else closed it, and the runs there attach again without a new start`);
|
|
29451
|
+
return 'revoked';
|
|
29452
|
+
}
|
|
29453
|
+
if (browserSessions.get(sessionId) !== session || session._tearingDown
|
|
29454
|
+
|| Date.now() - (_moreLoginStoppedBySynaBun.get(envId) || 0) < 60_000) return 'synabun';
|
|
29455
|
+
const owners = [...(session._loopOwned || [])];
|
|
29456
|
+
logUnexpectedProfileClose({ envId, sessionId, desktopControl: () => _desktopControlProbe?.() || null }).catch(() => {});
|
|
29457
|
+
let mark = null;
|
|
29458
|
+
try { mark = moreLogin.noteOutsideClose(envId, { at: Date.now(), sessionId, owners, name: _moreLoginEnvNames.get(envId) || null }); }
|
|
29459
|
+
catch (err) { console.warn(`[morelogin] the close of profile ${envId} outside SynaBun was not remembered: ${err?.message || err}`); }
|
|
29460
|
+
if (mark) console.log(`[morelogin] profile ${envId} is not started again by SynaBun for anybody (${owners.length ? `it served ${owners.map(logOwnerId).join(', ')}` : 'it served no run'}) until the owner starts it, a new scheduled run fires, or MoreLogin's daily reset at ${new Date(mark.until).toISOString()}`);
|
|
29461
|
+
return 'outside';
|
|
29462
|
+
}
|
|
29463
|
+
|
|
29062
29464
|
// ── Main assistant: brains + orchestration (lib/assistant-*.js) ──
|
|
29063
29465
|
// Everything lives in lib/; this block only wires dependencies and mounts the
|
|
29064
29466
|
// router + WebSocket handler. Failure here degrades to "assistant unavailable"
|
|
@@ -29448,6 +29850,7 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29448
29850
|
// DeepSeek-Harness-style routing: the brain proposes, the router enforces the
|
|
29449
29851
|
// session's route mode. Sinks reach the runtime/dispatcher lazily.
|
|
29450
29852
|
const assistantRouter = createAssistantRouter({
|
|
29853
|
+
agents: agentDefinitionResolver,
|
|
29451
29854
|
accountUsage,
|
|
29452
29855
|
budget: assistantBudget,
|
|
29453
29856
|
catalog: assistantCatalog,
|
|
@@ -29467,7 +29870,7 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29467
29870
|
computerApproved: (sessionId, payload) => _assistantRuntime?.routerComputerApproved?.(sessionId, payload),
|
|
29468
29871
|
startHeld: (runId, target, meta) => _assistantDispatcher?.resolveRoute?.(runId, { target, ...meta }),
|
|
29469
29872
|
// Asked before a card's pick is approved: a held run that would refuse it keeps the card open.
|
|
29470
|
-
checkHeld: (runId, target) => _assistantDispatcher?.heldRouteRefusal?.(runId, target) || null,
|
|
29873
|
+
checkHeld: (runId, target, role) => _assistantDispatcher?.heldRouteRefusal?.(runId, target, role) || null,
|
|
29471
29874
|
declineHeld: (runId, reason) => _assistantDispatcher?.declineRoute?.(runId, { reason }),
|
|
29472
29875
|
},
|
|
29473
29876
|
log: (tag, message) => assistantLog(tag, message),
|
|
@@ -29526,10 +29929,26 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29526
29929
|
log: (tag, message) => assistantLog(tag, message),
|
|
29527
29930
|
});
|
|
29528
29931
|
app.use('/api/desktop', createDesktopApi({ desktop: assistantDesktop, isGuestRequest, log: (tag, message) => assistantLog(tag, message) }));
|
|
29932
|
+
{ const desktop = assistantDesktop; _desktopControlProbe = () => desktop.status()?.control || null; }
|
|
29529
29933
|
} catch (err) {
|
|
29530
29934
|
console.warn('[assistant] computer use unavailable:', err.message);
|
|
29531
29935
|
assistantDesktop = null;
|
|
29532
29936
|
}
|
|
29937
|
+
// ══ Agents P2: durable agent messaging ═════════════════════════════════════════════════════════════════════
|
|
29938
|
+
// This server's one coordination store (DATA_HOME/data/coordination.db; lib/coordination/README.md): the run
|
|
29939
|
+
// events the dispatcher records, the Assistant's mailbox, the follow-up outbox. The dispatcher and the Assistant
|
|
29940
|
+
// runtime made right below take the shared service by themselves, so this block is the only place in this file
|
|
29941
|
+
// that creates it. runGracefulShutdown closes it after the scheduler and workers stop, including on signals;
|
|
29942
|
+
// an abrupt exit leaves the write-ahead log, which the next start reads back.
|
|
29943
|
+
{
|
|
29944
|
+
const { createCoordinationService, shareCoordinationService } = await import('./lib/coordination/service.js');
|
|
29945
|
+
const assistantCoordination = shareCoordinationService(createCoordinationService({ dataDir: LOOP_DATA_DIR, log: (tag, message) => assistantLog(tag, message) }));
|
|
29946
|
+
// The one instance of this server (never a second createCoordinationService in this file): a stop that is not
|
|
29947
|
+
// a signal (Restart Server, /api/server/shutdown, an update) closes it at the end of runGracefulShutdown.
|
|
29948
|
+
_assistantCoordination = assistantCoordination;
|
|
29949
|
+
if (assistantCoordination.degraded) console.warn(`[assistant] coordination store unavailable (${assistantCoordination.degraded.message}): agent events are kept in memory until the next start`);
|
|
29950
|
+
}
|
|
29951
|
+
// ══ end Agents P2 ══════════════════════════════════════════════════════════════════════════════════════════
|
|
29533
29952
|
_assistantDispatcher = createAssistantDispatcher({
|
|
29534
29953
|
resolveExternalTools: (spec, tools) => spec.provider
|
|
29535
29954
|
? selectExternalServers(tools, externalInventory(spec.provider, spec.cwd || PACKAGE_ROOT, { readProject: spec.provider !== 'opencode' || !openCodeProtectedWorker({ ...spec, cwd: spec.cwd || PACKAGE_ROOT, guardMode: _workerGuard.mode() }) }))
|
|
@@ -29559,8 +29978,13 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29559
29978
|
// Held to the owner's list of profiles agents may choose (agentMoreLoginProfileChoice: 403
|
|
29560
29979
|
// MORELOGIN_PROFILE_NOT_ALLOWED), whoever dispatches; the pin is an agent's, so the list is asked again when the
|
|
29561
29980
|
// worker's tab is acquired (a start, a resume) and at each of its browser calls.
|
|
29981
|
+
// pinBrowserProfile: a dispatch's morelogin_profile is the run's setup, locked (POST /api/morelogin/use refuses a
|
|
29982
|
+
// move). A resume re-pins the run's record, which a worker's own `use` rewrote (noteBrowserProfile): that one
|
|
29983
|
+
// stays the worker's own choice, as its saved choice says (_profileChoiceStore), and is not locked.
|
|
29562
29984
|
resolveBrowserProfile: (ref) => agentMoreLoginProfileChoice(ref),
|
|
29563
|
-
pinBrowserProfile: (runId, envId, name) => pinRunMoreLoginProfile(runId, envId, name, 'agent'
|
|
29985
|
+
pinBrowserProfile: (runId, envId, name) => pinRunMoreLoginProfile(runId, envId, name, 'agent', {
|
|
29986
|
+
locked: (() => { try { return String(_profileChoiceStore.get(runId)?.envId || '') !== String(envId || ''); } catch { return true; } })(),
|
|
29987
|
+
}),
|
|
29564
29988
|
memory: assistantMemory, detectProject: assistantDetectProject,
|
|
29565
29989
|
// Limits are read live from assistant-config.json `limits`; the money is the session budget (the planner).
|
|
29566
29990
|
limits: {},
|
|
@@ -29576,6 +30000,8 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29576
30000
|
clarifier: assistantClarifier,
|
|
29577
30001
|
// The session's Test density, read when a worker's prompt is composed (assistant-test-density.js).
|
|
29578
30002
|
testDensity: (sessionId) => _assistantRuntime?.testDensityFor?.(sessionId) ?? null,
|
|
30003
|
+
// agents-p4: the session's Agent density (lib/agents/density.js): the cap the team scheduler enforces.
|
|
30004
|
+
agentDensity: (sessionId) => _assistantRuntime?.agentDensityFor?.(sessionId) ?? null,
|
|
29579
30005
|
// After a restart, workers are resumed once this server listens and the worker-only MCP channel (a sandboxed
|
|
29580
30006
|
// worker's) is up or known to be off: a resumed CLI connects to SynaBun's MCP as it starts. 15 s at most.
|
|
29581
30007
|
serverReady: () => new Promise((resolveReady) => {
|
|
@@ -29635,6 +30061,57 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29635
30061
|
// A brain's pin is proven by its launch credential (lib/terminal-tokens.js bind), revoked with the brain.
|
|
29636
30062
|
terminalTokens: _terminalTokens,
|
|
29637
30063
|
});
|
|
30064
|
+
// ════ agents-p4 BEGIN: the team scheduler (lib/teams/scheduler.js; docs/agents.md → Teams) ════
|
|
30065
|
+
// One task given to several workers, each in its own git worktree (lib/teams/, phase P3), within the session's
|
|
30066
|
+
// Agent density. The one scheduler of this server: it takes the coordination service's own store (claims, the
|
|
30067
|
+
// journal, the team channel and the run events are one file), dispatches through the Assistant's dispatcher and
|
|
30068
|
+
// is shared (shareTeamScheduler) for the Assistant's API (agent_team, a worker's team tool) and Agents Studio's
|
|
30069
|
+
// routes. The integration tests run under the worker sandbox where the platform has one (lib/teams/test-sandbox.js);
|
|
30070
|
+
// ignored node_modules folders are cloned into each worktree where the file system can (cloneNodeModules).
|
|
30071
|
+
// In its own try/catch: the Assistant runs without teams when this fails, and the team routes then answer 503.
|
|
30072
|
+
try {
|
|
30073
|
+
const { createTeams, createGitRunner, cloneNodeModules } = await import('./lib/teams/index.js');
|
|
30074
|
+
const { createTeamScheduler, shareTeamScheduler } = await import('./lib/teams/scheduler.js');
|
|
30075
|
+
const { createSandboxedTestRunner } = await import('./lib/teams/test-sandbox.js');
|
|
30076
|
+
const teamGit = createGitRunner();
|
|
30077
|
+
const teamScheduler = shareTeamScheduler(createTeamScheduler({
|
|
30078
|
+
teams: createTeams({
|
|
30079
|
+
store: _assistantCoordination.store, git: teamGit, setup: cloneNodeModules(),
|
|
30080
|
+
runTests: createSandboxedTestRunner({
|
|
30081
|
+
serverPort: () => Number(PORT) || null,
|
|
30082
|
+
reservedPortRange: () => ({ from: OCP_SHARED_PORT_MIN, to: OCP_ISO_PORT_MAX }),
|
|
30083
|
+
denyPaths: () => workerSecretTrees(),
|
|
30084
|
+
profileDir: resolve(LOOP_DATA_DIR, 'teams', 'sandbox'),
|
|
30085
|
+
log: (tag, message) => assistantLog(tag, message),
|
|
30086
|
+
}),
|
|
30087
|
+
log: (tag, detail) => assistantLog(tag, typeof detail === 'string' ? detail : JSON.stringify(detail)),
|
|
30088
|
+
}),
|
|
30089
|
+
coordination: _assistantCoordination,
|
|
30090
|
+
dispatcher: () => _assistantDispatcher,
|
|
30091
|
+
router: assistantRouter,
|
|
30092
|
+
// A remote conversation (WhatsApp) starts no team: one approved route covers one worker there.
|
|
30093
|
+
session: (sessionId) => ({ remote: !!_assistantRuntime?.sessionPolicy?.(sessionId), taskId: _assistantRuntime?.currentTask?.(sessionId) }),
|
|
30094
|
+
// The owner's latest UI turn: cleanup needs one after the team landed, so a worktree is never deleted on the model's word alone.
|
|
30095
|
+
lastOwnerTurnAt: (sessionId) => _assistantRuntime?.lastOwnerTurnAt?.(sessionId) ?? null,
|
|
30096
|
+
git: teamGit,
|
|
30097
|
+
dataDir: LOOP_DATA_DIR,
|
|
30098
|
+
// Every team event, to the owner's pages (broadcastSync keeps `assistant:` messages to the owner).
|
|
30099
|
+
broadcast: (message) => { try { broadcastSync(message); } catch { /* no page is listening */ } },
|
|
30100
|
+
log: (tag, detail) => assistantLog(tag, typeof detail === 'string' ? detail : JSON.stringify(detail)),
|
|
30101
|
+
}));
|
|
30102
|
+
// The `team` tool is advertised to a run that works a team slice (mcp-server/src/services/team-context.ts):
|
|
30103
|
+
// this server's answer for a run id, asked by its own /mcp mount and the worker-only channel.
|
|
30104
|
+
import('../mcp-server/dist/services/team-context.js')
|
|
30105
|
+
.then((m) => m.setTeamContextResolver((runId) => !!teamScheduler.member(runId)))
|
|
30106
|
+
.catch((err) => console.warn('[assistant] team tool unavailable (mcp-server needs a build):', err?.message || err));
|
|
30107
|
+
// After a restart: the library's own recovery, then every team under way is taken up again. Never awaited here.
|
|
30108
|
+
teamScheduler.recover().catch((err) => console.warn('[assistant] team recovery failed:', err?.message || err))
|
|
30109
|
+
.finally(() => broadcastSync({ type: 'assistant:team-changed', event: 'recovered' }));
|
|
30110
|
+
_assistantTeamScheduler = teamScheduler;
|
|
30111
|
+
} catch (err) {
|
|
30112
|
+
console.warn('[assistant] teams unavailable:', err?.message || err);
|
|
30113
|
+
}
|
|
30114
|
+
// ════ agents-p4 END ════
|
|
29638
30115
|
assistantDesktop?.attach?.({ runtime: _assistantRuntime, dispatcher: _assistantDispatcher });
|
|
29639
30116
|
// Warm the catalog so brain capabilities (vision, tier) are known on first attach,
|
|
29640
30117
|
// then repair saved routes whose effort their model does not run (idempotent;
|
|
@@ -32300,6 +32777,69 @@ app.post('/api/terminal/links/:id/nudge', (req, res) => {
|
|
|
32300
32777
|
// Exposes CDP endpoint so Claude Code's Playwright MCP can connect.
|
|
32301
32778
|
|
|
32302
32779
|
const browserSessions = new Map(); // sessionId → { browser, context, page, clients, cdpSession, screencastActive, ... }
|
|
32780
|
+
// The listener is lazy: the owner's pairing action opens its loopback port, and so does a pairing a previous process
|
|
32781
|
+
// stored (restore() below), so the extension reconnects by itself after a restart.
|
|
32782
|
+
const extensionUploadRoot = resolve(DATA_HOME, 'data/extension-uploads');
|
|
32783
|
+
// SynaBun's own ports, which no agent reaches through the owner's browser (docs/browser-extension-bridge.md): this
|
|
32784
|
+
// server and its launch beacon unless the owner lets the automation browser act as owner (Settings → Browser), and
|
|
32785
|
+
// always the browser-control ports (the CDP port, MoreLogin's local API) and SynaBun's live OpenCode serves.
|
|
32786
|
+
function extensionBlockedPorts() {
|
|
32787
|
+
const ports = new Set([CDP_PORT, ...moreLogin.MORELOGIN_FIXED_API_PORTS]);
|
|
32788
|
+
try { for (const p of liveOpencodeServePorts()) ports.add(Number(p)); } catch {}
|
|
32789
|
+
if (!_automationBrowserOwnerAccess.enabled()) { ports.add(Number(PORT) || 3344); ports.add(workerBeaconPort()); }
|
|
32790
|
+
return [...ports].filter(p => Number.isInteger(p) && p > 0 && p <= 65535);
|
|
32791
|
+
}
|
|
32792
|
+
// This computer's names and interface addresses: one of SynaBun's ports on any of them is SynaBun.
|
|
32793
|
+
function extensionSelfHosts() {
|
|
32794
|
+
const hosts = new Set(machineNames.names().flatMap(name => [name, `${name}.local`]));
|
|
32795
|
+
try { for (const list of Object.values(os.networkInterfaces())) for (const entry of list || []) if (entry?.address) hosts.add(entry.address.split('%')[0]); } catch {}
|
|
32796
|
+
return [...hosts];
|
|
32797
|
+
}
|
|
32798
|
+
const extensionBridge = createExtensionBridge({
|
|
32799
|
+
forbiddenOrigins: publicWebOrigins,
|
|
32800
|
+
blockedPorts: extensionBlockedPorts,
|
|
32801
|
+
selfHosts: extensionSelfHosts,
|
|
32802
|
+
// The pairing and the owner's mode, across restarts: outside data/ (no backup carries the credential), 0600.
|
|
32803
|
+
store: createBridgeStore(resolve(DATA_HOME, 'browser-extension', 'bridge.json')),
|
|
32804
|
+
log: record => console.log('[extension-bridge]', JSON.stringify(record)),
|
|
32805
|
+
onInventory: state => extensionAdapter.sync(state),
|
|
32806
|
+
});
|
|
32807
|
+
const extensionAdapter = createExtensionAdapter({
|
|
32808
|
+
bridge: extensionBridge, sessions: browserSessions, uploadRoot: extensionUploadRoot, dataHome: DATA_HOME,
|
|
32809
|
+
caller: browserCaller, ownerPage: browserOwnerPageOnly,
|
|
32810
|
+
selected: req => loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(browserCaller(req).id),
|
|
32811
|
+
});
|
|
32812
|
+
// The extension folder the owner loads (DATA_HOME/browser-extension/unpacked): refreshed at start when the bundled
|
|
32813
|
+
// extension changed and is not older (lib/browser-extension-folder.js). The browser then needs the extension's Reload,
|
|
32814
|
+
// which Settings and the setup page say (`reloadNeeded`). Never fatal: a folder that cannot be written is prepared
|
|
32815
|
+
// again by the one-button setup, which says so.
|
|
32816
|
+
const prepareOwnerExtensionFolder = () => prepareExtensionFolder({ source: EXTENSION_FOLDER, home: DATA_HOME, appPort: Number(PORT) || 3344 });
|
|
32817
|
+
try { const prepared = prepareOwnerExtensionFolder(); if (prepared.changed) console.log(`[extension-bridge] extension folder ${prepared.previousVersion ? `refreshed ${prepared.previousVersion} → ${prepared.version}` : `prepared (${prepared.version})`}; reload the extension in the browser`); }
|
|
32818
|
+
catch (error) { console.warn(`[extension-bridge] extension folder not prepared (${error?.code || 'error'})`); }
|
|
32819
|
+
// The one-button setup (Settings → Browser → "Connect your browser"; docs/browser-extension-bridge.md → One-button
|
|
32820
|
+
// setup). Programs are started with execFile/spawn and argument arrays, never a shell; reads time out.
|
|
32821
|
+
const extensionSetup = createExtensionSetup({
|
|
32822
|
+
bridge: extensionBridge,
|
|
32823
|
+
detect: () => detectBrowsers({
|
|
32824
|
+
platform: process.platform, home: os.homedir(),
|
|
32825
|
+
run: (cmd, args) => new Promise((resolveRun, rejectRun) => execFile(cmd, args, { timeout: 5000, windowsHide: true, maxBuffer: 1024 * 1024, encoding: 'utf8' }, (error, stdout) => error ? rejectRun(error) : resolveRun({ stdout }))),
|
|
32826
|
+
exists: path => { try { return existsSync(path); } catch { return false; } },
|
|
32827
|
+
list: dir => { try { return readdirSync(dir); } catch { return []; } },
|
|
32828
|
+
}),
|
|
32829
|
+
prepare: () => prepareOwnerExtensionFolder(),
|
|
32830
|
+
exec: (cmd, args) => new Promise((resolveExec, rejectExec) => {
|
|
32831
|
+
const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true, shell: false });
|
|
32832
|
+
child.once('error', rejectExec); child.once('spawn', () => { child.unref(); resolveExec(); });
|
|
32833
|
+
}),
|
|
32834
|
+
appOrigin: () => `http://127.0.0.1:${Number(PORT) || 3344}`,
|
|
32835
|
+
folderVersion: () => extensionFolderState(DATA_HOME).version,
|
|
32836
|
+
});
|
|
32837
|
+
{
|
|
32838
|
+
const restored = extensionBridge.restore();
|
|
32839
|
+
restored.listening?.then(
|
|
32840
|
+
port => console.log(`[extension-bridge] pairing restored; listening on 127.0.0.1:${port}`),
|
|
32841
|
+
error => console.warn(`[extension-bridge] pairing restored, but the bridge port could not open (${error?.code || 'error'})`));
|
|
32842
|
+
}
|
|
32303
32843
|
const BROWSER_GRACE_PERIOD_MS = 5 * 60 * 1000; // 5 min before orphaned browser is killed
|
|
32304
32844
|
|
|
32305
32845
|
/** Check if a browser session is actively used by a running automation loop or agent.
|
|
@@ -32331,7 +32871,7 @@ setInterval(() => {
|
|
|
32331
32871
|
for (const [id, session] of browserSessions) {
|
|
32332
32872
|
// Never reap an attach (CDP) session — it backs a live Chrome window the user is
|
|
32333
32873
|
// using; reaping would disconnect it and a later call would spawn a 2nd debug Chrome.
|
|
32334
|
-
if (
|
|
32874
|
+
if (['cdp', 'morelogin', 'extension'].includes(session._profileMode)) { session._idleSince = null; continue; }
|
|
32335
32875
|
const idle = (session.clients?.size || 0) === 0
|
|
32336
32876
|
&& sessionOwnerCount(session) === 0
|
|
32337
32877
|
&& !isSessionUsedByActiveLoop(id);
|
|
@@ -32395,8 +32935,11 @@ const RUN_MORELOGIN_SESSION_PINS_MAX = 200;
|
|
|
32395
32935
|
* `ownerKey` works in MoreLogin profile `envId` from now on, or (no envId) in the default browser by its own choice.
|
|
32396
32936
|
* Only for code that decided it: a launch, POST /api/morelogin/use after its checks, a dispatch. `by`: 'owner' when
|
|
32397
32937
|
* the owner's page chose the profile, else 'agent'. Throws 503 PROFILE_PINS_FULL in place of evicting another pin.
|
|
32938
|
+
* `locked` (the default): the run's setup chose the profile (a schedule, a group, a timer, a launch, an agent's
|
|
32939
|
+
* spawn, a dispatch's morelogin_profile), and the run cannot move to another one (POST /api/morelogin/use answers 409
|
|
32940
|
+
* PROFILE_PINNED, 2026-11-15). Only a session's own choice (`use`) is not locked: such a session may choose again.
|
|
32398
32941
|
*/
|
|
32399
|
-
function pinRunMoreLoginProfile(ownerKey, envId, name = null, by = 'agent') {
|
|
32942
|
+
function pinRunMoreLoginProfile(ownerKey, envId, name = null, by = 'agent', { locked = true } = {}) {
|
|
32400
32943
|
if (!ownerKey) return;
|
|
32401
32944
|
_runMoreLoginNoPin.delete(ownerKey);
|
|
32402
32945
|
if (!_runMoreLoginPins.has(ownerKey)) {
|
|
@@ -32406,7 +32949,7 @@ function pinRunMoreLoginProfile(ownerKey, envId, name = null, by = 'agent') {
|
|
|
32406
32949
|
throw Object.assign(new Error('Too many sessions hold a browser profile of their own right now; nothing was changed. Try again when some have ended.'), { status: 503, code: 'PROFILE_PINS_FULL' });
|
|
32407
32950
|
}
|
|
32408
32951
|
}
|
|
32409
|
-
_runMoreLoginPins.set(ownerKey, envId ? { envId: String(envId), name: name ? String(name) : null, by: by === 'owner' ? 'owner' : 'agent' } : null);
|
|
32952
|
+
_runMoreLoginPins.set(ownerKey, envId ? { envId: String(envId), name: name ? String(name) : null, by: by === 'owner' ? 'owner' : 'agent', locked: locked !== false } : null);
|
|
32410
32953
|
}
|
|
32411
32954
|
|
|
32412
32955
|
/** `ownerKey` ended, or its launch failed: its pin and its saved choice are forgotten (nothing outlives its owner). */
|
|
@@ -32415,6 +32958,93 @@ function forgetRunMoreLoginProfile(ownerKey) {
|
|
|
32415
32958
|
_runMoreLoginPins.delete(ownerKey);
|
|
32416
32959
|
_runMoreLoginNoPin.delete(ownerKey);
|
|
32417
32960
|
_profileChoiceStore.delete(ownerKey);
|
|
32961
|
+
// A failure of its profile bars nothing once it has ended (lib/morelogin-profile-failures.js).
|
|
32962
|
+
_runProfileFailures.clear(ownerKey);
|
|
32963
|
+
}
|
|
32964
|
+
|
|
32965
|
+
// ── A run's own profile failed in this run: it does not move to another one (lib/morelogin-profile-failures.js) ──
|
|
32966
|
+
// Noted where a run's start or connection fails (acquireSharedBrowserTab, an automation's POST /api/browser/sessions,
|
|
32967
|
+
// its own POST /api/morelogin/start of its profile); asked by POST /api/morelogin/use and an automation's POST
|
|
32968
|
+
// /api/morelogin/start of another profile (409 PROFILE_FAILED_NO_SWITCH). Lifted by a connection of the run to that
|
|
32969
|
+
// profile again (noteRunProfileConnected), by the owner moving the run (its effective profile changed: `lifted`), or by
|
|
32970
|
+
// the run's end (forgetRunMoreLoginProfile).
|
|
32971
|
+
/**
|
|
32972
|
+
* The profile `ownerKey` works in now ({ envId, name, pinned }): its pin, else the MoreLogin (or local) profile that is
|
|
32973
|
+
* the default AI browser (Settings → Connected tools → MoreLogin); null when that default is no profile (Chrome, the
|
|
32974
|
+
* mirror, the extension).
|
|
32975
|
+
*/
|
|
32976
|
+
function runEffectiveProfile(ownerKey, cfg = loadBrowserConfig()) {
|
|
32977
|
+
const pin = runMoreLoginPin(ownerKey);
|
|
32978
|
+
if (pin?.envId) return { envId: String(pin.envId), name: pin.name || null, pinned: true };
|
|
32979
|
+
const defaultEnv = cfg?.connectMode === 'morelogin' ? moreLoginDefaultEnvId(cfg) : null;
|
|
32980
|
+
return defaultEnv ? { envId: String(defaultEnv), name: _moreLoginEnvNames.get(String(defaultEnv)) || null, pinned: false } : null;
|
|
32981
|
+
}
|
|
32982
|
+
|
|
32983
|
+
/**
|
|
32984
|
+
* `ownerKey`'s own profile (`profile`: { envId, name }) failed to start or connect in this run (`failure`: what the
|
|
32985
|
+
* start answered, { code, error } or an Error). From now on the run may not move to another profile. Never throws.
|
|
32986
|
+
*/
|
|
32987
|
+
function noteRunProfileFailure(ownerKey, profile, failure) {
|
|
32988
|
+
if (!ownerKey || !profile?.envId) return null;
|
|
32989
|
+
try {
|
|
32990
|
+
const entry = _runProfileFailures.note(ownerKey, {
|
|
32991
|
+
envId: String(profile.envId), name: profile.name || _moreLoginEnvNames.get(String(profile.envId)) || null,
|
|
32992
|
+
code: failure?.code || null, reason: failure?.error || failure?.message || null,
|
|
32993
|
+
});
|
|
32994
|
+
if (entry) console.warn(`[morelogin] ${logOwnerId(ownerKey)}: its own profile ${describeProfile(entry.envId, entry.name)} failed to start or connect (${entry.code || 'no code'}); it may not move to another profile until that one connects again for it, the owner moves it, or it ends`);
|
|
32995
|
+
return entry;
|
|
32996
|
+
} catch { return null; }
|
|
32997
|
+
}
|
|
32998
|
+
|
|
32999
|
+
/** `ownerKey` is connected to profile `envId`: a failure noted for that profile in this run is over. Never throws. */
|
|
33000
|
+
function noteRunProfileConnected(ownerKey, envId) {
|
|
33001
|
+
if (!ownerKey || !envId) return null;
|
|
33002
|
+
try {
|
|
33003
|
+
const dropped = _runProfileFailures.clear(ownerKey, { envId: String(envId) });
|
|
33004
|
+
if (dropped) console.log(`[morelogin] ${logOwnerId(ownerKey)}: ${describeProfile(dropped.envId, dropped.name)} connects again in this run: it may switch profiles again`);
|
|
33005
|
+
return dropped;
|
|
33006
|
+
} catch { return null; }
|
|
33007
|
+
}
|
|
33008
|
+
|
|
33009
|
+
/**
|
|
33010
|
+
* Why `ownerKey` may not switch now, or null. `target`: `{ toDefault: true }` (back to the default AI browser,
|
|
33011
|
+
* Settings → Connected tools → MoreLogin), or the profile it names ({ envId, name, profile }, resolved or as a request said it). `action`: 'use' (a
|
|
33012
|
+
* move, POST /api/morelogin/use) or 'start' (an automation's start of a profile). → an Error with code
|
|
33013
|
+
* PROFILE_FAILED_NO_SWITCH, status 409 (refuseProfileSwitchAfterFailure answers it). A failure of a profile the run no
|
|
33014
|
+
* longer works in (the owner moved it) is dropped here; naming the failed profile itself is no move.
|
|
33015
|
+
*/
|
|
33016
|
+
function runProfileSwitchRefusal(ownerKey, target = {}, { action = 'use', cfg = loadBrowserConfig() } = {}) {
|
|
33017
|
+
let failure = null;
|
|
33018
|
+
try { failure = _runProfileFailures.get(ownerKey); } catch { failure = null; }
|
|
33019
|
+
if (!failure) return null;
|
|
33020
|
+
const defaultEnv = cfg?.connectMode === 'morelogin' ? moreLoginDefaultEnvId(cfg) : null;
|
|
33021
|
+
// A resolved profile is compared by its id alone; a request's words by id or name (namesFailedProfile).
|
|
33022
|
+
const sameTarget = target?.toDefault ? String(defaultEnv || '') === failure.envId
|
|
33023
|
+
: target?.resolved ? String(target.envId || '') === failure.envId : namesFailedProfile(target, failure);
|
|
33024
|
+
const decision = profileSwitchDecision({ failure, current: runEffectiveProfile(ownerKey, cfg)?.envId || null, sameTarget });
|
|
33025
|
+
if (decision === 'lifted') {
|
|
33026
|
+
_runProfileFailures.clear(ownerKey, { envId: failure.envId });
|
|
33027
|
+
console.log(`[morelogin] ${logOwnerId(ownerKey)} no longer works in ${describeProfile(failure.envId, failure.name)} (the owner moved it): its failure there no longer bars a switch`);
|
|
33028
|
+
return null;
|
|
33029
|
+
}
|
|
33030
|
+
if (decision !== 'barred') return null;
|
|
33031
|
+
const named = target?.toDefault
|
|
33032
|
+
? (defaultEnv ? `the default browser, ${describeProfile(String(defaultEnv), _moreLoginEnvNames.get(String(defaultEnv)) || null)}` : 'the default browser')
|
|
33033
|
+
: target?.envId ? describeProfile(String(target.envId), target.name || _moreLoginEnvNames.get(String(target.envId)) || null)
|
|
33034
|
+
: (target?.name || target?.profile) ? `the profile "${String(target.name || target.profile).slice(0, 64)}"` : 'another profile';
|
|
33035
|
+
const err = profileSwitchBarError(failure, { label: describeProfile(failure.envId, failure.name), targetLabel: named, action });
|
|
33036
|
+
console.warn(`[morelogin] ${logOwnerId(ownerKey)}: its ${action === 'start' ? 'start of' : 'move to'} ${named} was refused: its own profile ${describeProfile(failure.envId, failure.name)} failed in this run (${failure.code || 'no code'})`);
|
|
33037
|
+
loopLog(ownerKey, 'browser:profile', `refused: its own profile failed in this run, so it does not ${action === 'start' ? 'start' : 'move to'} ${named}`, { failed: failure.envId, failedAt: err.failedAt || null, code: failure.code || null, asked: target?.toDefault ? 'default' : (target?.envId || target?.name || target?.profile || null) });
|
|
33038
|
+
return err;
|
|
33039
|
+
}
|
|
33040
|
+
|
|
33041
|
+
/** 409 PROFILE_FAILED_NO_SWITCH: the answer of a refusal from runProfileSwitchRefusal. Nothing was changed or started. */
|
|
33042
|
+
function refuseProfileSwitchAfterFailure(res, err) {
|
|
33043
|
+
return res.status(err.status || 409).json({
|
|
33044
|
+
ok: false, code: err.code, envId: err.envId, needsUser: true,
|
|
33045
|
+
...(err.failedAt ? { failedAt: err.failedAt } : {}), ...(err.failedCode ? { failedCode: err.failedCode } : {}),
|
|
33046
|
+
error: err.message,
|
|
33047
|
+
});
|
|
32418
33048
|
}
|
|
32419
33049
|
|
|
32420
33050
|
/**
|
|
@@ -32433,12 +33063,14 @@ function runMoreLoginPin(ownerKey) {
|
|
|
32433
33063
|
const chosen = _profileChoiceStore.get(ownerKey);
|
|
32434
33064
|
if (chosen !== undefined) {
|
|
32435
33065
|
decided = true;
|
|
32436
|
-
|
|
33066
|
+
// The session's own choice (`use`): it may choose again.
|
|
33067
|
+
pin = chosen.envId ? { envId: String(chosen.envId), name: chosen.name || null, by: 'agent', locked: false } : null;
|
|
32437
33068
|
} else {
|
|
32438
33069
|
const loopFile = findLoopFileForTerminal(ownerKey);
|
|
32439
33070
|
if (loopFile) {
|
|
32440
33071
|
const data = JSON.parse(readFileSync(resolve(LOOP_DIR, loopFile), 'utf-8'));
|
|
32441
|
-
|
|
33072
|
+
// The run was launched with this profile (its schedule, group, timer or launch): it stays there.
|
|
33073
|
+
if (data.moreloginEnvId) pin = { envId: String(data.moreloginEnvId), name: data.moreloginEnvName ? String(data.moreloginEnvName) : null, by: data.moreloginEnvBy === 'owner' ? 'owner' : 'agent', locked: true };
|
|
32442
33074
|
}
|
|
32443
33075
|
}
|
|
32444
33076
|
} catch { /* no pin */ }
|
|
@@ -32452,6 +33084,34 @@ function runMoreLoginPin(ownerKey) {
|
|
|
32452
33084
|
return pin;
|
|
32453
33085
|
}
|
|
32454
33086
|
|
|
33087
|
+
// MoreLogin profile names last read from its list (GET /api/browser/morelogin-envs, /api/morelogin/profiles): what the
|
|
33088
|
+
// start cooldowns are called by. id → name, bounded.
|
|
33089
|
+
const _moreLoginEnvNames = new Map();
|
|
33090
|
+
function rememberMoreLoginEnvNames(envs) {
|
|
33091
|
+
for (const env of envs || []) {
|
|
33092
|
+
if (env?.id == null || !env.name || env.kind === 'local') continue;
|
|
33093
|
+
_moreLoginEnvNames.delete(String(env.id));
|
|
33094
|
+
_moreLoginEnvNames.set(String(env.id), String(env.name));
|
|
33095
|
+
}
|
|
33096
|
+
while (_moreLoginEnvNames.size > 500) _moreLoginEnvNames.delete(_moreLoginEnvNames.keys().next().value);
|
|
33097
|
+
}
|
|
33098
|
+
/**
|
|
33099
|
+
* The profiles MoreLogin refused to start for its plan's daily limit, held until its day resets
|
|
33100
|
+
* (lib/morelogin-start-cooldown.js): [{ envId, name, since, resetAt, resetLocal, apiCode }]. Never throws.
|
|
33101
|
+
*/
|
|
33102
|
+
function moreLoginStartCooldowns(envs = null) {
|
|
33103
|
+
let list = [];
|
|
33104
|
+
try { list = moreLogin.listStartCooldowns(); } catch { return []; }
|
|
33105
|
+
if (!list.length) return [];
|
|
33106
|
+
if (envs) rememberMoreLoginEnvNames(envs);
|
|
33107
|
+
const names = new Map(_moreLoginEnvNames);
|
|
33108
|
+
try { for (const p of moreLoginAgentProfiles()) if (p?.envId && p.name && !names.has(String(p.envId))) names.set(String(p.envId), p.name); } catch { /* unreadable config: ids only */ }
|
|
33109
|
+
return list.map((c) => ({
|
|
33110
|
+
envId: c.envId, name: names.get(c.envId) || null,
|
|
33111
|
+
since: c.since ? new Date(c.since).toISOString() : null, resetAt: c.resetAt, resetLocal: c.resetLocal, apiCode: c.apiCode ?? null,
|
|
33112
|
+
}));
|
|
33113
|
+
}
|
|
33114
|
+
|
|
32455
33115
|
function describeMoreLoginPin(pin) {
|
|
32456
33116
|
if (!pin) return 'the default browser';
|
|
32457
33117
|
// `MoreLogin profile "X" (id)`, or `local profile "X" (id)` for one of SynaBun's own (lib/local-profiles.js).
|
|
@@ -32503,6 +33163,7 @@ function sessionServesRun(session, cfg, ownerKey) {
|
|
|
32503
33163
|
// A pin that may not be used (an agent's, its profile off the owner's list) serves in no session at all: not its
|
|
32504
33164
|
// profile's, and never the default browser's.
|
|
32505
33165
|
if (pin) return !pinUseRefusal(pin, cfg) && sessionServesMoreLoginEnv(session, pin.envId);
|
|
33166
|
+
if (cfg.connectMode === 'extension' || session?._profileMode === 'extension') return cfg.connectMode === 'extension' && session?._profileMode === 'extension';
|
|
32506
33167
|
return cfg.connectMode !== 'morelogin' || sessionServesMoreLoginDefault(session, cfg);
|
|
32507
33168
|
}
|
|
32508
33169
|
|
|
@@ -32528,6 +33189,10 @@ async function findReusableBrowserSession(opts = {}) {
|
|
|
32528
33189
|
const normalize = (p) => (p || '').replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
|
|
32529
33190
|
const selectedNorm = normalize(selectedPath);
|
|
32530
33191
|
for (const [id, session] of browserSessions) {
|
|
33192
|
+
if (session._profileMode === 'extension' || cfg.connectMode === 'extension' && !moreloginEnvId) {
|
|
33193
|
+
if (session._profileMode === 'extension' && cfg.connectMode === 'extension' && extensionBridge.status().connected && !moreloginEnvId) return { id, session };
|
|
33194
|
+
continue;
|
|
33195
|
+
}
|
|
32531
33196
|
if (excludeAgentOwned && session._agentOwnedSet?.size > 0) continue;
|
|
32532
33197
|
if (excludeLoopOwned && session._loopOwned?.size > 0) continue;
|
|
32533
33198
|
// Belt-and-suspenders: also check agent registry in case the ownership set
|
|
@@ -32661,10 +33326,15 @@ function loopBrowserLockKey(ownerKey, requestedBrowserSessionId, cfg) {
|
|
|
32661
33326
|
*
|
|
32662
33327
|
* Returns { browserSessionId, browserTabId } on success, or { error } on failure.
|
|
32663
33328
|
*/
|
|
32664
|
-
async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser' }) {
|
|
33329
|
+
async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false }) {
|
|
33330
|
+
if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(ownerKey)) {
|
|
33331
|
+
// takeOverTab: one of the owner's open tabs in the everyday browser (full control), named by browser_session create.
|
|
33332
|
+
try { return await extensionAdapter.acquire(ownerKey, ownerType, { adopt: takeOverTab || undefined }); }
|
|
33333
|
+
catch (error) { return extensionSafeError(error); }
|
|
33334
|
+
}
|
|
32665
33335
|
const lockKey = loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig());
|
|
32666
33336
|
const acquired = await withLoopBrowserLock(lockKey, async () => {
|
|
32667
|
-
// The browser this owner gets changed while it waited (
|
|
33337
|
+
// The browser this owner gets changed while it waited (the owner's settings, a requested session that went away):
|
|
32668
33338
|
// it queues again for the right one, outside this turn.
|
|
32669
33339
|
if (loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig()) !== lockKey) return { requeue: true };
|
|
32670
33340
|
let browserSessionId = null;
|
|
@@ -32733,9 +33403,14 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
32733
33403
|
let createError = null;
|
|
32734
33404
|
if (!browserSessionId) {
|
|
32735
33405
|
try {
|
|
33406
|
+
// The start guard: a profile closed outside SynaBun is not started again by this acquisition (an attach to the
|
|
33407
|
+
// profile running again is always allowed). Only a new scheduled firing's launch may start it
|
|
33408
|
+
// (`scheduledFiring`, the schedule:browser acquisition; never a recovery or a create of a run under way).
|
|
33409
|
+
const moreloginStartGuard = moreLoginStartGuardFor(ownerKey, pin, { scheduled: scheduledFiring === true });
|
|
33410
|
+
const moreloginAfterOutsideClose = scheduledFiring === true ? 'schedule' : null;
|
|
32736
33411
|
const result = await createBrowserSession(pin
|
|
32737
|
-
? { url: 'about:blank', connectMode: 'morelogin', moreloginEnvId: pin.envId, _mlPinned: true }
|
|
32738
|
-
: { url: 'about:blank' });
|
|
33412
|
+
? { url: 'about:blank', connectMode: 'morelogin', moreloginEnvId: pin.envId, _mlPinned: true, moreloginStartGuard, moreloginAfterOutsideClose }
|
|
33413
|
+
: { url: 'about:blank', moreloginStartGuard, moreloginAfterOutsideClose });
|
|
32739
33414
|
browserSessionId = result.sessionId;
|
|
32740
33415
|
loopLog(ownerKey, logTag, 'strategy 2: created shared browser session', {
|
|
32741
33416
|
browserSessionId, profileMode: result.profileMode, profileSource: result.profileSource,
|
|
@@ -32752,6 +33427,20 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
32752
33427
|
}
|
|
32753
33428
|
|
|
32754
33429
|
if (!browserSessionId) {
|
|
33430
|
+
if (createError?.sharedPreflight) return createError;
|
|
33431
|
+
// The run's own profile (its pin, else the MoreLogin default) failed to start or connect in this run: from now on
|
|
33432
|
+
// it may not move to another profile (POST /api/morelogin/use answers 409 PROFILE_FAILED_NO_SWITCH) until that
|
|
33433
|
+
// profile connects again for it (below), the owner moves it, or it ends (lib/morelogin-profile-failures.js).
|
|
33434
|
+
if (createError) {
|
|
33435
|
+
const own = pin || (moreLoginDefault && moreLoginDefaultEnvId(policyCfg) ? { envId: String(moreLoginDefaultEnvId(policyCfg)), name: null } : null);
|
|
33436
|
+
noteRunProfileFailure(ownerKey, own, createError);
|
|
33437
|
+
}
|
|
33438
|
+
// The profile was closed outside SynaBun: the sentence says it all (which profile, when, that SynaBun does not
|
|
33439
|
+
// reopen it, how to go on); no "could not start" around it.
|
|
33440
|
+
if (createError?.code === 'MORELOGIN_CLOSED_OUTSIDE') {
|
|
33441
|
+
loopLog(ownerKey, logTag, 'BLOCKED: the MoreLogin profile was closed outside SynaBun; SynaBun does not reopen it', { closedAt: createError.closedAt || null, holdUntil: createError.holdUntil || null });
|
|
33442
|
+
return { error: createError.error, code: createError.code, needsUser: true, blocked: true, ...(createError.closedAt ? { closedAt: createError.closedAt } : {}), ...(createError.holdUntil ? { holdUntil: createError.holdUntil } : {}) };
|
|
33443
|
+
}
|
|
32755
33444
|
// Carry the real reason (e.g. "MoreLogin connect failed: … unreachable") into the
|
|
32756
33445
|
// run's log, lastRunResult and the schedule:failed toast.
|
|
32757
33446
|
return {
|
|
@@ -32760,11 +33449,17 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
32760
33449
|
? `Could not start ${describeMoreLoginPin(pin)} for this run${createError ? `: ${createError.error}` : '.'} The run was not started in another profile or browser: ${
|
|
32761
33450
|
createError?.code === 'MORELOGIN_NOT_CHROMIUM' || createError?.code === 'MORELOGIN_NOT_DEVTOOLS'
|
|
32762
33451
|
? 'pick a Chrome-type profile where this run is set up.'
|
|
33452
|
+
: createError?.code === 'MORELOGIN_START_REFUSED'
|
|
33453
|
+
? `this needs the user, not a retry: ${createError.planLimit ? 'wait for MoreLogin\'s daily reset, upgrade the MoreLogin plan, or keep the profile open so runs need no new start' : 'fix what MoreLogin names in the MoreLogin app'}.`
|
|
33454
|
+
: createError?.code === 'MORELOGIN_PROFILE_WINDOWLESS'
|
|
33455
|
+
? 'this needs the user, not a retry: open the profile\'s window again in MoreLogin (or close it fully there and start it again).'
|
|
32763
33456
|
: 'check that MoreLogin is open and that the profile still exists, or pick another profile where this run is set up.'}`
|
|
32764
33457
|
: createError
|
|
32765
33458
|
? `Could not start the shared browser session: ${createError.error}`
|
|
32766
33459
|
: 'Could not start the shared browser session. Open Browser Settings and verify the selected profile can launch.',
|
|
32767
33460
|
...(createError?.code ? { code: createError.code, offenders: createError.offenders } : {}),
|
|
33461
|
+
...(createError?.needsUser ? { needsUser: true } : {}),
|
|
33462
|
+
...(createError?.resetAt ? { resetAt: createError.resetAt } : {}),
|
|
32768
33463
|
};
|
|
32769
33464
|
}
|
|
32770
33465
|
|
|
@@ -32848,17 +33543,56 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
32848
33543
|
return { requeue: true };
|
|
32849
33544
|
}
|
|
32850
33545
|
|
|
33546
|
+
// Connected to its profile: a failure of that profile noted earlier in this run is over (it may switch again).
|
|
33547
|
+
if (claimedSession._mlEnvId) noteRunProfileConnected(ownerKey, claimedSession._mlEnvId);
|
|
32851
33548
|
return { browserSessionId, browserTabId };
|
|
32852
33549
|
});
|
|
32853
|
-
return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag }) : acquired;
|
|
33550
|
+
return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag, scheduledFiring }) : acquired;
|
|
33551
|
+
}
|
|
33552
|
+
|
|
33553
|
+
/**
|
|
33554
|
+
* The start guard of `ownerKey`'s acquisition (createBrowserSession `moreloginStartGuard` → lib/morelogin.js
|
|
33555
|
+
* startProfile `refuseStart`, asked only when MoreLogin says the profile is not running): a profile closed outside
|
|
33556
|
+
* SynaBun (lib/morelogin-outside-close.js) is not started again, for this run or any other, named the way the run
|
|
33557
|
+
* knows it. `scheduled`: the launch acquisition of a new scheduled firing, which may start it (startProfile is told
|
|
33558
|
+
* the same through `allowAfterOutsideClose`). → (envId) => Error | null.
|
|
33559
|
+
*/
|
|
33560
|
+
function moreLoginStartGuardFor(ownerKey, pin = null, { scheduled = false } = {}) {
|
|
33561
|
+
return (envId) => {
|
|
33562
|
+
if (scheduled) return null;
|
|
33563
|
+
const held = moreLogin.outsideCloseFor(String(envId));
|
|
33564
|
+
if (!held) return null;
|
|
33565
|
+
const name = (pin && String(pin.envId) === String(envId) ? pin.name : null) || _moreLoginEnvNames.get(String(envId)) || held.name || null;
|
|
33566
|
+
return moreLogin.outsideCloseError(String(envId), held, { label: describeProfile(String(envId), name) });
|
|
33567
|
+
};
|
|
33568
|
+
}
|
|
33569
|
+
|
|
33570
|
+
/**
|
|
33571
|
+
* The profiles closed outside SynaBun that SynaBun does not reopen (lib/morelogin-outside-close.js), for the status
|
|
33572
|
+
* answers and Settings: [{ envId, name, closedAt, closedLocal, holdUntil, holdUntilLocal, runs }] (the orphaned runs
|
|
33573
|
+
* counted, never listed). `envs`: a list just read, for names. Never throws.
|
|
33574
|
+
*/
|
|
33575
|
+
function moreLoginClosedOutside(envs = null) {
|
|
33576
|
+
try {
|
|
33577
|
+
const listed = new Map((envs || []).filter((e) => e?.id != null && e.name).map((e) => [String(e.id), String(e.name)]));
|
|
33578
|
+
return moreLogin.listOutsideCloses().map((c) => ({
|
|
33579
|
+
envId: c.envId, name: listed.get(c.envId) || _moreLoginEnvNames.get(c.envId) || c.name || null,
|
|
33580
|
+
closedAt: c.closedAt, closedLocal: c.closedLocal, holdUntil: c.holdUntil, holdUntilLocal: c.holdUntilLocal, runs: c.owners.length,
|
|
33581
|
+
}));
|
|
33582
|
+
} catch { return []; }
|
|
33583
|
+
}
|
|
33584
|
+
|
|
33585
|
+
/** A profile as a refusal names it (lib/morelogin.js startProfile `profileLabel`): its name as MoreLogin last listed it. */
|
|
33586
|
+
function moreLoginProfileLabel(envId, name = null) {
|
|
33587
|
+
return describeProfile(String(envId), _moreLoginEnvNames.get(String(envId)) || name || null);
|
|
32854
33588
|
}
|
|
32855
33589
|
|
|
32856
33590
|
/**
|
|
32857
33591
|
* Backward-compatible loop wrapper around acquireSharedBrowserTab. Existing callers
|
|
32858
33592
|
* pass { terminalSessionId } and expect loop-owned semantics.
|
|
32859
33593
|
*/
|
|
32860
|
-
async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, terminalSessionId, logTag = 'launch:browser' }) {
|
|
32861
|
-
return acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey: terminalSessionId, ownerType: 'loop', logTag });
|
|
33594
|
+
async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, terminalSessionId, logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false }) {
|
|
33595
|
+
return acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey: terminalSessionId, ownerType: 'loop', logTag, takeOverTab, scheduledFiring });
|
|
32862
33596
|
}
|
|
32863
33597
|
|
|
32864
33598
|
/**
|
|
@@ -32869,6 +33603,7 @@ async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, term
|
|
|
32869
33603
|
*/
|
|
32870
33604
|
async function releaseSharedBrowserTab(sessionId, ownerKey) {
|
|
32871
33605
|
const session = browserSessions.get(sessionId);
|
|
33606
|
+
if (session?._profileMode === 'extension') return extensionAdapter.release(sessionId, ownerKey);
|
|
32872
33607
|
if (!session) return;
|
|
32873
33608
|
session._interactiveOwned?.delete(ownerKey);
|
|
32874
33609
|
session._loopOwned?.delete(ownerKey);
|
|
@@ -32923,7 +33658,7 @@ function startedTabAlive(sessionId, tabId, ownerKey) {
|
|
|
32923
33658
|
const session = sessionId ? browserSessions.get(sessionId) : null;
|
|
32924
33659
|
if (!session) return false;
|
|
32925
33660
|
if (tabId && session.tabs && !session.tabs.has(tabId)) return false;
|
|
32926
|
-
if (ownerKey && tabId && session._tabOwners?.get(ownerKey)
|
|
33661
|
+
if (ownerKey && tabId && !(session._profileMode === 'extension' ? extensionAdapter.ownsTab(session, ownerKey, tabId) : session._tabOwners?.get(ownerKey) === tabId)) return false;
|
|
32927
33662
|
return true;
|
|
32928
33663
|
}
|
|
32929
33664
|
|
|
@@ -34216,8 +34951,28 @@ async function protectNativeServeContext(ctx, { deadline = Infinity, signal = nu
|
|
|
34216
34951
|
// the serves it names (narrowed: never a token or a whole record).
|
|
34217
34952
|
function browserStartFailure(err) {
|
|
34218
34953
|
const out = { error: err?.message || String(err) };
|
|
34954
|
+
if (err?.sharedPreflight) {
|
|
34955
|
+
return { error: `Shared OpenCode build verification blocked browser acquisition. ${out.error}`,
|
|
34956
|
+
sharedPreflight: true, code: err.code, offenders: err.offenders.map(({ envId, reason }) => ({ envId, reason })) };
|
|
34957
|
+
}
|
|
34219
34958
|
if (err?.code === 'NATIVE_SERVE_UNVERIFIED') { out.code = err.code; out.offenders = narrowOffenders(err.offenders); }
|
|
34220
34959
|
if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS') out.code = err.code;
|
|
34960
|
+
// MoreLogin refused the start (a plan limit, …): the user has to act, a retry or another run hits the same answer.
|
|
34961
|
+
if (err?.code === 'MORELOGIN_START_REFUSED') {
|
|
34962
|
+
out.code = err.code;
|
|
34963
|
+
out.needsUser = true;
|
|
34964
|
+
if (err.apiCode != null) out.apiCode = err.apiCode;
|
|
34965
|
+
if (err.planLimit) out.planLimit = true;
|
|
34966
|
+
if (err.resetAt) out.resetAt = err.resetAt;
|
|
34967
|
+
}
|
|
34968
|
+
// The run's profile was closed outside SynaBun and is not started again for it (lib/morelogin-outside-close.js), or
|
|
34969
|
+
// MoreLogin lists it running with no window: the user acts (starts or reopens it), a retry gets the same answer.
|
|
34970
|
+
if (err?.code === 'MORELOGIN_CLOSED_OUTSIDE' || err?.code === 'MORELOGIN_PROFILE_WINDOWLESS') {
|
|
34971
|
+
out.code = err.code;
|
|
34972
|
+
out.needsUser = true;
|
|
34973
|
+
if (err.closedAt) out.closedAt = err.closedAt;
|
|
34974
|
+
if (err.holdUntil) out.holdUntil = err.holdUntil;
|
|
34975
|
+
}
|
|
34221
34976
|
return out;
|
|
34222
34977
|
}
|
|
34223
34978
|
|
|
@@ -34326,6 +35081,10 @@ function moreLoginBlockError(session, requestedUrl, landedUrl) {
|
|
|
34326
35081
|
async function createBrowserSession(options = {}) {
|
|
34327
35082
|
const sessionId = randomBytes(16).toString('hex');
|
|
34328
35083
|
const savedCfg = loadBrowserConfig();
|
|
35084
|
+
if (savedCfg.connectMode === 'extension' && options.connectMode !== 'morelogin') {
|
|
35085
|
+
const acquired = await extensionAdapter.acquire(options._extensionOwner || 'owner-page');
|
|
35086
|
+
return { sessionId: acquired.browserSessionId, tabId: acquired.browserTabId, profileMode: 'extension', wsEndpoint: null };
|
|
35087
|
+
}
|
|
34329
35088
|
// Settings that exist but cannot be read are not "no settings": never fall back to Chrome.
|
|
34330
35089
|
const unreadableCfg = browserConfigUnreadable(savedCfg);
|
|
34331
35090
|
if (unreadableCfg) throw new Error(`browser-config.json is unreadable; fix it in Settings → Browser (${unreadableCfg})`);
|
|
@@ -34588,7 +35347,7 @@ async function createBrowserSession(options = {}) {
|
|
|
34588
35347
|
let _launchProfileDirectory = _profileDirectory || (userDataDir ? 'Default' : null);
|
|
34589
35348
|
|
|
34590
35349
|
// ── MoreLogin connect mode ──
|
|
34591
|
-
// When configured (Settings →
|
|
35350
|
+
// When configured (Settings → Connected tools → MoreLogin → Default AI browser, or an explicit per-session
|
|
34592
35351
|
// moreloginEnvId), launch/attach a MoreLogin anti-detect profile and drive it
|
|
34593
35352
|
// over CDP. MoreLogin's /api/env/start returns a debugPort — the exact same CDP
|
|
34594
35353
|
// path as "attach" mode, so we reuse connectOverCDP + probeCdpEndpoint here.
|
|
@@ -34642,27 +35401,48 @@ async function createBrowserSession(options = {}) {
|
|
|
34642
35401
|
// requireCdp: a Firefox-type profile has no DevTools endpoint and is refused, before it is started when
|
|
34643
35402
|
// MoreLogin says what it is up front.
|
|
34644
35403
|
nativePreflightProfiles.add(String(envId));
|
|
34645
|
-
|
|
34646
|
-
//
|
|
35404
|
+
// `moreloginStartGuard` (acquireSharedBrowserTab): the run's own reason not to spend a launch. Asked only when
|
|
35405
|
+
// MoreLogin says the profile is not running. A profile closed outside SynaBun is refused by startProfile for
|
|
35406
|
+
// everybody but `moreloginAfterOutsideClose` ('owner': the owner's page; 'schedule': a new scheduled firing).
|
|
35407
|
+
const startOpts = { ...mlOpts, requireCdp: true, ...(typeof options.moreloginStartGuard === 'function' ? { refuseStart: options.moreloginStartGuard } : {}),
|
|
35408
|
+
...(options.moreloginAfterOutsideClose ? { allowAfterOutsideClose: options.moreloginAfterOutsideClose } : {}), profileLabel: moreLoginProfileLabel };
|
|
35409
|
+
let { debugPort } = await moreLogin.startProfile(envId, startOpts);
|
|
34647
35410
|
let endpoint = null;
|
|
34648
|
-
|
|
34649
|
-
|
|
34650
|
-
|
|
34651
|
-
|
|
34652
|
-
|
|
34653
|
-
|
|
34654
|
-
|
|
34655
|
-
|
|
34656
|
-
|
|
34657
|
-
|
|
34658
|
-
|
|
34659
|
-
|
|
34660
|
-
|
|
34661
|
-
|
|
34662
|
-
|
|
34663
|
-
|
|
34664
|
-
|
|
34665
|
-
|
|
35411
|
+
let attached = null;
|
|
35412
|
+
for (let attempt = 0; !attached; attempt++) {
|
|
35413
|
+
// Wait for MoreLogin's Chromium DevTools endpoint to come up.
|
|
35414
|
+
endpoint = null;
|
|
35415
|
+
for (let i = 0; i < 40; i++) {
|
|
35416
|
+
const probed = await probeCdpEndpoint(debugPort);
|
|
35417
|
+
if (probed.ok) { endpoint = probed.httpEndpoint; break; }
|
|
35418
|
+
await new Promise(r => setTimeout(r, 250));
|
|
35419
|
+
}
|
|
35420
|
+
if (!endpoint) {
|
|
35421
|
+
// Ten seconds without a DevTools answer. A port that answers HTTP as something else will never become
|
|
35422
|
+
// one: say what it is, in place of Playwright's "Unexpected status 404 … try connecting via ws://". A
|
|
35423
|
+
// port nothing listens on yet still gets the connect attempt below.
|
|
35424
|
+
const seen = await moreLogin.describeDebugEndpoint(debugPort);
|
|
35425
|
+
if (seen.kind === 'not-devtools') throw moreLogin.notDevToolsError(envId, debugPort, seen);
|
|
35426
|
+
endpoint = `http://127.0.0.1:${debugPort}`;
|
|
35427
|
+
}
|
|
35428
|
+
try {
|
|
35429
|
+
attached = await moreLogin.attachProfileBrowser(
|
|
35430
|
+
chromium, endpoint,
|
|
35431
|
+
(cdpBrowser, cdpContext) => newSessionPage({ browser: cdpBrowser, context: cdpContext, _profileMode: 'morelogin' }),
|
|
35432
|
+
); // fresh tab in the real profile; never substitute an incognito context
|
|
35433
|
+
} catch (attachError) {
|
|
35434
|
+
// MoreLogin lists the profile running, but its browser holds no profile (its window was closed and the
|
|
35435
|
+
// process lives on, or it is still starting: P-4 at 21:13:36 on 2026-11-15). Asked once more after a short
|
|
35436
|
+
// wait, through the status again (a profile that finished closing is then started only as startProfile and
|
|
35437
|
+
// the run's guard allow); never a start of a profile MoreLogin still lists as running.
|
|
35438
|
+
if (attachError?.code !== 'MORELOGIN_PROFILE_WINDOWLESS') throw attachError;
|
|
35439
|
+
if (attempt >= 1) throw moreLogin.windowlessProfileError(envId, endpoint, attachError.cause || attachError);
|
|
35440
|
+
console.warn(`[browser] MoreLogin profile ${envId}: DevTools port ${debugPort} answers but its browser has no profile (closing or still starting); asking MoreLogin again in 2 s`);
|
|
35441
|
+
await new Promise(r => setTimeout(r, 2000));
|
|
35442
|
+
({ debugPort } = await moreLogin.startProfile(envId, startOpts));
|
|
35443
|
+
}
|
|
35444
|
+
}
|
|
35445
|
+
const { browser: cdpBrowser, context: cdpContext, page: cdpPage } = attached;
|
|
34666
35446
|
// A local profile's timezone on this first tab (every later tab gets it in newSessionPage, from the session).
|
|
34667
35447
|
if (_localProfileInfo?.timezone) await applyPageTimezone(cdpContext, cdpPage, _localProfileInfo.timezone);
|
|
34668
35448
|
|
|
@@ -34677,6 +35457,8 @@ async function createBrowserSession(options = {}) {
|
|
|
34677
35457
|
_profileSourceName = _localProfile ? `Local · ${_localProfileInfo?.name || envId}` : `MoreLogin · ${envId}`;
|
|
34678
35458
|
_localProfileTimezone = _localProfile ? (_localProfileInfo?.timezone || null) : null;
|
|
34679
35459
|
_moreLoginConnected = true;
|
|
35460
|
+
// The profile runs and SynaBun is attached: a close outside SynaBun remembered for it is over, for every run.
|
|
35461
|
+
if (!_localProfile) { try { moreLogin.clearOutsideClose(String(envId)); } catch { /* nothing held */ } }
|
|
34680
35462
|
console.log(`[browser] Connected to ${_localProfile ? `local profile ${envId}` : `MoreLogin env ${envId}`} via CDP at ${endpoint}`);
|
|
34681
35463
|
} catch (err) {
|
|
34682
35464
|
if (_localProfile) {
|
|
@@ -34686,14 +35468,27 @@ async function createBrowserSession(options = {}) {
|
|
|
34686
35468
|
throw refused;
|
|
34687
35469
|
}
|
|
34688
35470
|
const port = moreLogin.getMoreLoginPort(savedCfg);
|
|
34689
|
-
if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS'
|
|
34690
|
-
|
|
34691
|
-
// MoreLogin
|
|
35471
|
+
if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS' || err?.code === 'MORELOGIN_START_REFUSED'
|
|
35472
|
+
|| err?.code === 'MORELOGIN_CLOSED_OUTSIDE' || err?.code === 'MORELOGIN_PROFILE_WINDOWLESS') {
|
|
35473
|
+
// MoreLogin is open and the profile exists: it is the profile's browser SynaBun cannot drive, MoreLogin
|
|
35474
|
+
// itself refused the start (a plan limit, …), the run's profile was closed outside SynaBun and is not started
|
|
35475
|
+
// again for it, or MoreLogin lists it running with no window. No "open the MoreLogin app" advice, and the code
|
|
35476
|
+
// travels so the run's message does not add it either.
|
|
34692
35477
|
const rule = options.moreloginEnvId
|
|
34693
35478
|
? 'a session asked for a MoreLogin profile never falls back to another profile or to Chrome'
|
|
34694
35479
|
: 'sessions will not fall back to Chrome while MoreLogin is the default browser';
|
|
34695
|
-
|
|
35480
|
+
// A run whose profile was closed outside SynaBun: nothing failed to connect, SynaBun chose not to start it, and
|
|
35481
|
+
// the sentence (lib/morelogin-outside-close.js outsideCloseError) already says all of it.
|
|
35482
|
+
const refused = new Error(err.code === 'MORELOGIN_CLOSED_OUTSIDE'
|
|
35483
|
+
? `${err.message}.`
|
|
35484
|
+
: `MoreLogin connect failed: ${err.message}. Nothing was opened elsewhere: ${rule}.`);
|
|
34696
35485
|
refused.code = err.code;
|
|
35486
|
+
if (err.needsUser) refused.needsUser = true;
|
|
35487
|
+
if (err.apiCode != null) refused.apiCode = err.apiCode;
|
|
35488
|
+
if (err.planLimit) refused.planLimit = true;
|
|
35489
|
+
if (err.resetAt) refused.resetAt = err.resetAt;
|
|
35490
|
+
if (err.closedAt) refused.closedAt = err.closedAt;
|
|
35491
|
+
if (err.holdUntil) refused.holdUntil = err.holdUntil;
|
|
34697
35492
|
throw refused;
|
|
34698
35493
|
}
|
|
34699
35494
|
if (options.moreloginEnvId) {
|
|
@@ -35149,6 +35944,10 @@ async function createBrowserSession(options = {}) {
|
|
|
35149
35944
|
context.on('close', () => {
|
|
35150
35945
|
const orphanedLoops = session._loopOwned?.size > 0 ? [...session._loopOwned] : [];
|
|
35151
35946
|
console.log(`Browser context closed for session ${sessionId}${session._agentOwnedSet?.size ? ` (agent-owned: ${[...session._agentOwnedSet].join(',')})` : ''}${orphanedLoops.length ? ` (orphaning loops: ${orphanedLoops.map(logOwnerId).join(', ')})` : ''}`);
|
|
35947
|
+
// A MoreLogin profile's browser went away: who closed it (SynaBun's own revocation or teardown, or somebody
|
|
35948
|
+
// else: then one line of evidence, and the runs it orphaned do not start it again). The profile is never
|
|
35949
|
+
// reopened from here (each start spends one of MoreLogin's daily launches).
|
|
35950
|
+
try { noteMoreLoginContextClose(session, sessionId, context); } catch { /* the close goes on */ }
|
|
35152
35951
|
session.screencastActive = false;
|
|
35153
35952
|
detachScreencastFrameHandler(session);
|
|
35154
35953
|
// Stop autosave interval
|
|
@@ -35335,6 +36134,7 @@ async function stopScreencast(session) {
|
|
|
35335
36134
|
* of such a session closes those, and only those (closeOwnTabsBeforeDisconnect).
|
|
35336
36135
|
*/
|
|
35337
36136
|
async function newSessionPage(session, { timeoutMs } = {}) {
|
|
36137
|
+
if (session._profileMode === 'extension') throw Object.assign(new Error('Use the extension adapter to create tabs.'), { code: 'UNSUPPORTED_IN_EXTENSION_MODE' });
|
|
35338
36138
|
let page;
|
|
35339
36139
|
if (backgroundTabsEnabled(loadBrowserConfig())) {
|
|
35340
36140
|
page = await openBackgroundPageStrict(session.browser, session.context, {
|
|
@@ -35686,6 +36486,11 @@ async function _switchSessionTab(session, sessionId, tabId) {
|
|
|
35686
36486
|
* Close a single tab in a session. If it's the last tab, destroys the whole session.
|
|
35687
36487
|
*/
|
|
35688
36488
|
async function closeSessionTab(session, sessionId, tabId) {
|
|
36489
|
+
if (session._profileMode === 'extension') {
|
|
36490
|
+
const owner = [...session._tabOwners.keys()].find(key => extensionAdapter.ownsTab(session, key, tabId));
|
|
36491
|
+
if (owner) await extensionAdapter.release(sessionId, owner, tabId);
|
|
36492
|
+
return;
|
|
36493
|
+
}
|
|
35689
36494
|
const tabEntry = session.tabs.get(tabId);
|
|
35690
36495
|
if (!tabEntry) return;
|
|
35691
36496
|
|
|
@@ -35743,6 +36548,7 @@ async function closeSessionTab(session, sessionId, tabId) {
|
|
|
35743
36548
|
*/
|
|
35744
36549
|
async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingPage = null } = {}) {
|
|
35745
36550
|
const session = browserSessions.get(sessionId);
|
|
36551
|
+
if (session?._profileMode === 'extension') return extensionAdapter.destroy(sessionId);
|
|
35746
36552
|
if (!session) return;
|
|
35747
36553
|
|
|
35748
36554
|
try {
|
|
@@ -36280,7 +37086,47 @@ app.use('/api/browser/sessions/:id', (req, res, next) => {
|
|
|
36280
37086
|
}
|
|
36281
37087
|
return gate();
|
|
36282
37088
|
});
|
|
36283
|
-
// Read-only semantic context for the browser judgments
|
|
37089
|
+
// Read-only semantic context for the browser judgments and extension backend dispatch.
|
|
37090
|
+
// All extension endpoints terminate here; none falls through to Playwright or raw CDP.
|
|
37091
|
+
app.use('/api/browser', extensionAdapter.middleware);
|
|
37092
|
+
const extensionOwnerGuard = ownerRouteGuard({ isGuestRequest, port: PORT, allowedOrigins: publicWebOrigins, refuseCrossSite: true, ownOriginsOnly: true, requireOrigin: true });
|
|
37093
|
+
app.use('/api/browser/extension', extensionOwnerGuard, (req, res, next) => {
|
|
37094
|
+
if (browserCaller(req).automation || !browserOwnerPageOnly(req)) return res.status(403).json({ code: 'OWNER_ROUTE', error: 'Extension pairing and approval belong to the owner.' });
|
|
37095
|
+
res.setHeader('Cache-Control', 'no-store'); next();
|
|
37096
|
+
});
|
|
37097
|
+
app.get('/api/browser/extension', (_req, res) => {
|
|
37098
|
+
const folderState = extensionFolderState(DATA_HOME), status = extensionBridge.status();
|
|
37099
|
+
// `folder`: the folder the owner loads (the prepared copy; the bundled one only when none could be prepared).
|
|
37100
|
+
res.json({ ...status, folder: folderState.prepared ? folderState.folder : EXTENSION_FOLDER, bundledFolder: EXTENSION_FOLDER, uploadFolder: extensionUploadRoot,
|
|
37101
|
+
folderVersion: folderState.version, reloadNeeded: !!(status.connected && folderState.version && status.extensionVersion !== folderState.version),
|
|
37102
|
+
setup: extensionSetup.status().state });
|
|
37103
|
+
});
|
|
37104
|
+
// The one-button setup. Owner only: these sit under the guard above (ownerRouteGuard, the page secret, no automation
|
|
37105
|
+
// caller), like pairing and the mode. The token (ticket) goes to SynaBun's own setup page only, never into a log or URL.
|
|
37106
|
+
const sendSetup = (res, run) => Promise.resolve().then(run).then(value => res.json({ ok: true, ...value }),
|
|
37107
|
+
error => res.status(400).json(extensionSetupError(error) || extensionSafeError(error)));
|
|
37108
|
+
app.get('/api/browser/extension/setup/status', (_req, res) => sendSetup(res, () => extensionSetup.status()));
|
|
37109
|
+
app.post('/api/browser/extension/setup/start', (req, res) => sendSetup(res, () => extensionSetup.start({ browserId: typeof req.body?.browser === 'string' ? req.body.browser : undefined })));
|
|
37110
|
+
app.post('/api/browser/extension/setup/ticket', (_req, res) => { res.setHeader('Cache-Control', 'no-store'); return sendSetup(res, () => extensionSetup.ticket()); });
|
|
37111
|
+
app.post('/api/browser/extension/setup/cancel', (_req, res) => sendSetup(res, () => extensionSetup.cancel()));
|
|
37112
|
+
app.post('/api/browser/extension/setup/reveal', (_req, res) => sendSetup(res, () => extensionSetup.reveal()));
|
|
37113
|
+
app.post('/api/browser/extension/setup/reopen', (_req, res) => sendSetup(res, () => extensionSetup.reopen()));
|
|
37114
|
+
app.post('/api/browser/extension/:action', async (req, res) => {
|
|
37115
|
+
try {
|
|
37116
|
+
const action = req.params.action;
|
|
37117
|
+
if (action === 'pair') return res.json(await extensionBridge.beginPairing(Number(req.body?.port || 3345)));
|
|
37118
|
+
if (action === 'disconnect') extensionBridge.disconnect();
|
|
37119
|
+
else if (action === 'resume') extensionBridge.resume();
|
|
37120
|
+
else if (action === 'revoke') extensionBridge.revoke();
|
|
37121
|
+
else if (action === 'revoke-tab') await extensionBridge.revokeTab(req.body?.tab);
|
|
37122
|
+
else if (action === 'revoke-site') await extensionBridge.revokeSite(req.body?.site);
|
|
37123
|
+
// The owner's mode: full control (any site and tab of the paired browser) or only what the owner shares.
|
|
37124
|
+
else if (action === 'mode') await extensionBridge.setMode(req.body?.fullControl);
|
|
37125
|
+
else return res.status(400).json({ code: 'INVALID_MESSAGE', error: 'Unknown extension action.' });
|
|
37126
|
+
return res.json({ ok: true, ...extensionBridge.status() });
|
|
37127
|
+
} catch (error) { return res.status(400).json(extensionSafeError(error)); }
|
|
37128
|
+
});
|
|
37129
|
+
// Semantic context itself runs only on Playwright sessions; the extension adapter has already answered.
|
|
36284
37130
|
app.use('/api/browser', createBrowserAssistRouter({ browserSessions, getTargetPage, normalizeSelector }));
|
|
36285
37131
|
|
|
36286
37132
|
app.get('/api/browser/sessions', (req, res) => {
|
|
@@ -36310,7 +37156,7 @@ app.get('/api/browser/sessions', (req, res) => {
|
|
|
36310
37156
|
const sessions = [...browserSessions.entries()].map(([id, s]) => {
|
|
36311
37157
|
const allTabs = s.tabs ? [...s.tabs.entries()] : [];
|
|
36312
37158
|
const ownTabId = automationView && caller ? (s._tabOwners?.get(caller) || null) : null;
|
|
36313
|
-
const shownTabs = automationView ? allTabs.filter(([tid]) => tid === ownTabId) : allTabs;
|
|
37159
|
+
const shownTabs = automationView ? allTabs.filter(([tid]) => s._profileMode === 'extension' ? extensionAdapter.ownsTab(s, caller, tid) : tid === ownTabId) : allTabs;
|
|
36314
37160
|
const ownTab = automationView && shownTabs.length ? shownTabs[0][1] : null;
|
|
36315
37161
|
return {
|
|
36316
37162
|
id,
|
|
@@ -36323,9 +37169,9 @@ app.get('/api/browser/sessions', (req, res) => {
|
|
|
36323
37169
|
profileSource: s._profileSourceName || null,
|
|
36324
37170
|
moreloginEnvId: s._mlEnvId || null,
|
|
36325
37171
|
// For a run pinned to a MoreLogin profile of its own, "the default" is that profile's session (sessionServesRun).
|
|
36326
|
-
servesDefault:
|
|
37172
|
+
servesDefault: sessionServesRun(s, policyCfg, caller),
|
|
36327
37173
|
// The browser's own CDP endpoint drives every tab past every check here: the owner's page's only.
|
|
36328
|
-
wsEndpoint: who.automation || s._isPersistent ? null : (s.browser
|
|
37174
|
+
wsEndpoint: who.automation || s._isPersistent ? null : (s.browser?.wsEndpoint?.() || null),
|
|
36329
37175
|
activeTabId: automationView ? (ownTabId && s.activeTabId === ownTabId ? ownTabId : null) : (s.activeTabId || null),
|
|
36330
37176
|
loopOwned: (s._loopOwned?.size || 0) > 0,
|
|
36331
37177
|
interactiveOwned: (s._interactiveOwned?.size || 0) > 0,
|
|
@@ -36364,12 +37210,18 @@ app.get('/api/browser/sessions', (req, res) => {
|
|
|
36364
37210
|
// POST /api/loop/recover-browser records a run's move to a tab of its own (`adopt`): an MCP asks it only of a
|
|
36365
37211
|
// server that says so (an older one reads the request as a recovery and opens a tab).
|
|
36366
37212
|
adoptRoute: true,
|
|
37213
|
+
// The everyday browser through the extension, in full control: the owner's open tabs no agent holds, which an
|
|
37214
|
+
// agent may take over (browser_session create with that tabId). Only for a verified run or the owner's page.
|
|
37215
|
+
...(policyCfg.connectMode === 'extension' && !callerPin && (who.automation ? who.status === 'verified' : browserOwnerPageOnly(req))
|
|
37216
|
+
? (() => { const tabs = extensionAdapter.ownerTabs({ caller, includeOwned: true }); return tabs ? { extensionTabs: { fullControl: true, tabs } } : {}; })()
|
|
37217
|
+
: {}),
|
|
36367
37218
|
});
|
|
36368
37219
|
});
|
|
36369
37220
|
|
|
36370
37221
|
app.post('/api/browser/sessions', async (req, res) => {
|
|
36371
37222
|
const { url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, connectMode, moreloginEnvId } = req.body;
|
|
36372
|
-
// Which browser or MoreLogin profile a session starts on is the owner's choice (Settings → Browser
|
|
37223
|
+
// Which browser or MoreLogin profile a session starts on is the owner's choice (Settings → Browser for SynaBun's own
|
|
37224
|
+
// browser, Settings → Connected tools → MoreLogin for the default AI browser profile): an automation's
|
|
36373
37225
|
// create opens the default browser and names neither (lib/browser-automation-routes.js; review 972afb74, finding 1).
|
|
36374
37226
|
// N1 (re-review of 2026-11-10): the check asked `creator.automation` only, so an invite guest with the `browser`
|
|
36375
37227
|
// permission (browserTerminalGate lets a guest reach this route: browserPageOwner) who knew a profile's id opened
|
|
@@ -36379,7 +37231,12 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
36379
37231
|
const ownerFields = (creator.automation || !browserOwnerPageOnly(req)) ? ownerOnlyCreateFields(req.body) : [];
|
|
36380
37232
|
if (ownerFields.length) {
|
|
36381
37233
|
const guestCreate = !creator.automation;
|
|
36382
|
-
|
|
37234
|
+
// Where the owner makes each choice: a MoreLogin profile (the default AI browser) in the MoreLogin tab, SynaBun's
|
|
37235
|
+
// own browser (connect mode, folders, executable) in Settings → Browser.
|
|
37236
|
+
const profileFields = ownerFields.some((f) => /^morelogin/i.test(f));
|
|
37237
|
+
const browserFields = ownerFields.some((f) => !/^morelogin/i.test(f));
|
|
37238
|
+
const where = [profileFields && 'Settings → Connected tools → MoreLogin (Default AI browser)', browserFields && 'Settings → Browser'].filter(Boolean).join('; ');
|
|
37239
|
+
return res.status(403).json({ ok: false, code: 'OWNER_ONLY_FIELDS', fields: ownerFields, error: `${guestCreate ? 'A guest' : 'An automation'} opens the default browser: ${ownerFields.join(' and ')} ${ownerFields.length === 1 ? 'is' : 'are'} the owner's choice (${where}). Leave ${ownerFields.length === 1 ? 'it' : 'them'} out.` });
|
|
36383
37240
|
}
|
|
36384
37241
|
// A create-session startUrl that points at one of SynaBun's own live OpenCode serve ports is refused up front, like
|
|
36385
37242
|
// navigate and new-tab: the serve's API can change what a worker session may do, and createBrowserSession navigates
|
|
@@ -36427,15 +37284,28 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
36427
37284
|
}
|
|
36428
37285
|
// The start, its owner and its broadcast: once per start, whoever ends up with it.
|
|
36429
37286
|
const start = async () => {
|
|
36430
|
-
|
|
36431
|
-
|
|
36432
|
-
|
|
36433
|
-
|
|
36434
|
-
|
|
36435
|
-
|
|
36436
|
-
|
|
36437
|
-
|
|
37287
|
+
let result;
|
|
37288
|
+
try {
|
|
37289
|
+
result = await createBrowserSession({
|
|
37290
|
+
url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, _realHeaders,
|
|
37291
|
+
// Its deadline bounds the native serve check (installServePortGuard) inside the caller's timeout.
|
|
37292
|
+
browserRequest: req.browserRequest,
|
|
37293
|
+
// Optional per-session override to target a specific MoreLogin env (multi-identity)
|
|
37294
|
+
...(connectMode === 'morelogin' ? { connectMode } : {}),
|
|
37295
|
+
...(moreloginEnvId ? { moreloginEnvId: String(moreloginEnvId) } : {}),
|
|
37296
|
+
// The owner's own page (its page secret, no run or agent header) opening a session is the owner starting
|
|
37297
|
+
// the profile: it may start one closed outside SynaBun (lib/morelogin-outside-close.js). Nobody else may.
|
|
37298
|
+
...(!creator.automation && browserOwnerPageOnly(req) ? { moreloginAfterOutsideClose: 'owner' } : {}),
|
|
37299
|
+
});
|
|
37300
|
+
} catch (err) {
|
|
37301
|
+
// An automation's own profile here is the MoreLogin default: when it fails to start or connect, the run may not
|
|
37302
|
+
// move to another profile (lib/morelogin-profile-failures.js). The owner's page has no run to bar.
|
|
37303
|
+
if (who.automation && creatorTerminalId) noteRunProfileFailure(creatorTerminalId, runEffectiveProfile(creatorTerminalId), browserStartFailure(err));
|
|
37304
|
+
throw err;
|
|
37305
|
+
}
|
|
36438
37306
|
const createdSession = browserSessions.get(result.sessionId);
|
|
37307
|
+
// Connected to the profile: a failure of it noted earlier in this run is over.
|
|
37308
|
+
if (who.automation && creatorTerminalId && createdSession?._mlEnvId) noteRunProfileConnected(creatorTerminalId, createdSession._mlEnvId);
|
|
36439
37309
|
if (creatorTerminalId && createdSession) {
|
|
36440
37310
|
if (!createdSession._tabOwners) createdSession._tabOwners = new Map();
|
|
36441
37311
|
createdSession._tabOwners.set(creatorTerminalId, createdSession.activeTabId);
|
|
@@ -36468,8 +37338,11 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
36468
37338
|
} catch (err) {
|
|
36469
37339
|
console.error('Browser session create error:', err.message);
|
|
36470
37340
|
const acq = err?.acquisition;
|
|
36471
|
-
if (acq) return res.status(
|
|
36472
|
-
res.status(500).json(
|
|
37341
|
+
if (acq?.code === 'MORELOGIN_CLOSED_OUTSIDE') return res.status(409).json(closedOutsideAnswer(acq));
|
|
37342
|
+
if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}), ...(acq.needsUser ? { needsUser: true } : {}) });
|
|
37343
|
+
const failure = browserStartFailure(err);
|
|
37344
|
+
if (failure.code === 'MORELOGIN_CLOSED_OUTSIDE') return res.status(409).json(closedOutsideAnswer(failure));
|
|
37345
|
+
res.status(500).json(failure);
|
|
36473
37346
|
}
|
|
36474
37347
|
});
|
|
36475
37348
|
|
|
@@ -36536,11 +37409,19 @@ app.post('/api/browser/acquire', async (req, res) => {
|
|
|
36536
37409
|
res.json({ ok: true, sessionId: acq.browserSessionId, tabId: acq.browserTabId || null, ...(outcome.from !== 'started' && { handedOver: outcome.from }) });
|
|
36537
37410
|
} catch (err) {
|
|
36538
37411
|
const acq = err?.acquisition;
|
|
36539
|
-
|
|
37412
|
+
// The profile was closed outside SynaBun and SynaBun does not reopen it: 409, the user acts (never a replacement).
|
|
37413
|
+
if (acq?.code === 'MORELOGIN_CLOSED_OUTSIDE') return res.status(409).json(closedOutsideAnswer(acq));
|
|
37414
|
+
if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}), ...(acq.needsUser ? { needsUser: true } : {}) });
|
|
36540
37415
|
res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code } : {}) });
|
|
36541
37416
|
}
|
|
36542
37417
|
});
|
|
36543
37418
|
|
|
37419
|
+
/** The answer of a browser route refused because its MoreLogin profile was closed outside SynaBun (409). */
|
|
37420
|
+
function closedOutsideAnswer(acq) {
|
|
37421
|
+
return { ok: false, error: acq.error, code: 'MORELOGIN_CLOSED_OUTSIDE', needsUser: true, blocked: true,
|
|
37422
|
+
...(acq.closedAt ? { closedAt: acq.closedAt } : {}), ...(acq.holdUntil ? { holdUntil: acq.holdUntil } : {}) };
|
|
37423
|
+
}
|
|
37424
|
+
|
|
36544
37425
|
// POST /api/browser/release — interactive MCP process relinquishes its owned tab on
|
|
36545
37426
|
// exit. Closes the dedicated tab and drops the ownership/routing entries so the shared
|
|
36546
37427
|
// browser can be grace-reaped once no owners remain. Best-effort; body: { clientId }.
|
|
@@ -38384,7 +39265,7 @@ app.put('/api/browser/config', async (req, res) => {
|
|
|
38384
39265
|
// Finding 1 of the re-review of 2026-11-11: only the owner's page changes the default AI browser (connect mode,
|
|
38385
39266
|
// default MoreLogin profile). browserTerminalGate already keeps this route from automations; this is the route's own.
|
|
38386
39267
|
if (browserDefaultChangeRefused(req, body, loadBrowserConfig())) return refuseDefaultBrowserChange(res);
|
|
38387
|
-
if (body.connectMode !== undefined) body.connectMode = ['attach', 'morelogin'].includes(body.connectMode) ? body.connectMode : 'mirror';
|
|
39268
|
+
if (body.connectMode !== undefined) body.connectMode = ['attach', 'morelogin', 'extension'].includes(body.connectMode) ? body.connectMode : 'mirror';
|
|
38388
39269
|
if (body.attachSeed !== undefined) body.attachSeed = body.attachSeed === 'fresh' ? 'fresh' : 'real';
|
|
38389
39270
|
if (body.moreloginEnvId !== undefined && body.moreloginEnvId !== null && body.moreloginEnvId !== '') body.moreloginEnvId = String(body.moreloginEnvId);
|
|
38390
39271
|
// The default MoreLogin profile is driven over CDP: a newly chosen one known to be Firefox-type is refused. The
|
|
@@ -38428,7 +39309,7 @@ app.get('/api/browser/detect-profiles', (req, res) => {
|
|
|
38428
39309
|
}
|
|
38429
39310
|
});
|
|
38430
39311
|
|
|
38431
|
-
// List MoreLogin profiles (environments) for the
|
|
39312
|
+
// List MoreLogin profiles (environments) for the profile pickers (the MoreLogin tab's Default AI browser, schedules)
|
|
38432
39313
|
app.get('/api/browser/morelogin-envs', async (req, res) => {
|
|
38433
39314
|
try {
|
|
38434
39315
|
const cfg = loadBrowserConfig();
|
|
@@ -38443,19 +39324,25 @@ app.get('/api/browser/morelogin-envs', async (req, res) => {
|
|
|
38443
39324
|
try { localEnvs = (await moreLogin.listLocalProfiles()).map((env) => ({ ...env, browser: 'chromium' })); }
|
|
38444
39325
|
catch (err) { localError = err.message; }
|
|
38445
39326
|
const local = { count: localEnvs.length, ...(localError ? { error: localError } : {}) };
|
|
39327
|
+
// Profiles whose start MoreLogin refused for its plan's daily limit, until its day resets (SynaBun's own record:
|
|
39328
|
+
// said whatever state MoreLogin is in). Named from the list below when it is read.
|
|
39329
|
+
const startCooldowns = moreLoginStartCooldowns();
|
|
39330
|
+
// Profiles closed outside SynaBun that SynaBun does not reopen (lib/morelogin-outside-close.js), said in every
|
|
39331
|
+
// answer too: [{ envId, name, closedAt, closedLocal, holdUntil, holdUntilLocal, runs }].
|
|
39332
|
+
const closedOutside = moreLoginClosedOutside();
|
|
38446
39333
|
// Probe first: the install-folder check knows only the default folders, and an
|
|
38447
39334
|
// answering local API proves the app is there wherever it was installed.
|
|
38448
39335
|
const probe = await moreLogin.probeMoreLoginApi({ savedCfg: cfg, port });
|
|
38449
39336
|
const installed = probe.running || moreLogin.isMoreLoginInstalled().installed;
|
|
38450
|
-
if (!installed) return res.json({ connectMode, ok: true, installed: false, running: false, port, envs: localEnvs, local, error: probe.error || null });
|
|
38451
|
-
if (!probe.running) return res.json({ connectMode, ok: true, installed: true, running: false, port, envs: localEnvs, local, error: probe.error || null });
|
|
39337
|
+
if (!installed) return res.json({ connectMode, ok: true, installed: false, running: false, port, envs: localEnvs, local, startCooldowns, closedOutside, error: probe.error || null });
|
|
39338
|
+
if (!probe.running) return res.json({ connectMode, ok: true, installed: true, running: false, port, envs: localEnvs, local, startCooldowns, closedOutside, error: probe.error || null });
|
|
38452
39339
|
// The API answered with an error (signature required, API off): say why, never an empty list.
|
|
38453
|
-
if (probe.apiError) return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, error: probe.apiError });
|
|
39340
|
+
if (probe.apiError) return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, startCooldowns, closedOutside, error: probe.apiError });
|
|
38454
39341
|
// MoreLogin's own rows (the list holds the local ones too: they are added once, below).
|
|
38455
39342
|
const listedEnvs = (await moreLogin.listProfiles({ savedCfg: cfg, port })).filter((env) => env.kind !== 'local');
|
|
38456
39343
|
// The API counted profiles but none could be read: a shape problem, never "no profiles yet".
|
|
38457
39344
|
if (probe.count > 0 && !listedEnvs.length) {
|
|
38458
|
-
return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, error: `MoreLogin reports ${probe.count} profile(s) but SynaBun could not read them from its answer; a newer MoreLogin may have changed its API.` });
|
|
39345
|
+
return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, startCooldowns, closedOutside, error: `MoreLogin reports ${probe.count} profile(s) but SynaBun could not read them from its answer; a newer MoreLogin may have changed its API.` });
|
|
38459
39346
|
}
|
|
38460
39347
|
// Each profile with the browser it runs (`browser`: 'chromium' | 'firefox' | null = not known): the list call
|
|
38461
39348
|
// does not say it, so it is looked up per profile, kept, and never waited for longer than the lookup's budget.
|
|
@@ -38463,6 +39350,8 @@ app.get('/api/browser/morelogin-envs', async (req, res) => {
|
|
|
38463
39350
|
const { envs, browsersPending } = await withMoreLoginBrowsers(listedEnvs, { savedCfg: cfg, port });
|
|
38464
39351
|
res.json({
|
|
38465
39352
|
connectMode, ok: true, installed: true, running: true, port, envs: [...envs, ...localEnvs], local, browsersPending,
|
|
39353
|
+
startCooldowns: moreLoginStartCooldowns(listedEnvs),
|
|
39354
|
+
closedOutside: moreLoginClosedOutside(listedEnvs),
|
|
38466
39355
|
// Observed website-policy blocks — MoreLogin's local API never exposes the
|
|
38467
39356
|
// blacklist/whitelist itself, so the picker reports what actually happened.
|
|
38468
39357
|
blockedNavigations: moreLoginBlockStats.count,
|
|
@@ -38723,7 +39612,7 @@ const httpServer = app.listen(PORT, async () => {
|
|
|
38723
39612
|
}, 200);
|
|
38724
39613
|
|
|
38725
39614
|
// Detect MoreLogin (anti-detect browser) — DETECTION ONLY, never auto-activates.
|
|
38726
|
-
// Activation is an explicit user choice
|
|
39615
|
+
// Activation is an explicit user choice in the MoreLogin tab (Default AI browser).
|
|
38727
39616
|
setTimeout(async () => {
|
|
38728
39617
|
try {
|
|
38729
39618
|
const mlBootCfg = loadBrowserConfig();
|
|
@@ -38768,31 +39657,29 @@ const httpServer = app.listen(PORT, async () => {
|
|
|
38768
39657
|
}, 2500);
|
|
38769
39658
|
|
|
38770
39659
|
// Warm the session_cache + session_fts tables so the hybrid search has data
|
|
38771
|
-
// on first keystroke.
|
|
38772
|
-
//
|
|
38773
|
-
|
|
38774
|
-
setTimeout(() => {
|
|
39660
|
+
// on first keystroke. The large history scans yield between sessions, and
|
|
39661
|
+
// a Codex catalog request shares the same refresh with this startup pass.
|
|
39662
|
+
setTimeout(async () => {
|
|
38775
39663
|
const passes = [
|
|
38776
|
-
() => {
|
|
39664
|
+
async () => {
|
|
38777
39665
|
try {
|
|
38778
|
-
const claude = rebuildClaudeCache();
|
|
39666
|
+
const claude = await rebuildClaudeCache({ background: true });
|
|
38779
39667
|
if (claude.updated > 0) console.log(` Session cache (claude): indexed ${claude.updated}/${claude.sessions}`);
|
|
38780
39668
|
} catch (err) { console.warn(' Session cache (claude) error:', err.message); }
|
|
38781
39669
|
},
|
|
38782
|
-
() => {
|
|
39670
|
+
async () => {
|
|
38783
39671
|
try {
|
|
38784
|
-
const codex =
|
|
38785
|
-
accounts: loadCodexAccounts().accounts,
|
|
38786
|
-
projects: loadHookProjects(),
|
|
38787
|
-
});
|
|
39672
|
+
const codex = await refreshCodexSessionCatalog();
|
|
38788
39673
|
if (codex.updated > 0) console.log(` Session cache (codex): indexed ${codex.updated}/${codex.sessions}`);
|
|
38789
39674
|
} catch (err) { console.warn(' Session cache (codex) error:', err.message); }
|
|
38790
39675
|
},
|
|
38791
|
-
() => {
|
|
39676
|
+
async () => {
|
|
38792
39677
|
try {
|
|
38793
|
-
|
|
39678
|
+
_ocpSessionCacheWarmup = rebuildOpencodeCache({ getOpencodeDb, background: true });
|
|
39679
|
+
const oc = await _ocpSessionCacheWarmup;
|
|
38794
39680
|
if (oc.updated > 0) console.log(` Session cache (opencode): indexed ${oc.updated}/${oc.sessions}`);
|
|
38795
39681
|
} catch (err) { console.warn(' Session cache (opencode) error:', err.message); }
|
|
39682
|
+
finally { _ocpSessionCacheWarmup = null; }
|
|
38796
39683
|
},
|
|
38797
39684
|
() => {
|
|
38798
39685
|
const agy = refreshAntigravityCatalog({ force: true });
|
|
@@ -38801,13 +39688,10 @@ const httpServer = app.listen(PORT, async () => {
|
|
|
38801
39688
|
setInterval(() => refreshAntigravityCatalog({ force: true }), 5 * 60 * 1000).unref?.();
|
|
38802
39689
|
},
|
|
38803
39690
|
];
|
|
38804
|
-
const
|
|
38805
|
-
|
|
38806
|
-
|
|
38807
|
-
|
|
38808
|
-
setImmediate(next);
|
|
38809
|
-
};
|
|
38810
|
-
next();
|
|
39691
|
+
for (const pass of passes) {
|
|
39692
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
39693
|
+
await pass();
|
|
39694
|
+
}
|
|
38811
39695
|
}, 2000);
|
|
38812
39696
|
|
|
38813
39697
|
// Auto-sync OpenClaw bridge if enabled
|
|
@@ -38866,6 +39750,39 @@ const httpServer = app.listen(PORT, async () => {
|
|
|
38866
39750
|
console.warn(' Rules reconcile warning:', err.message);
|
|
38867
39751
|
}
|
|
38868
39752
|
|
|
39753
|
+
// The owner's tool permissions (Settings → Tool permissions): what was switched on and is missing from the
|
|
39754
|
+
// allow list of ~/.claude/settings.json is put back, and what the list allows is written down as chosen
|
|
39755
|
+
// (lib/tool-permission-choices.js). An update is a start, so this is what keeps the choices across one.
|
|
39756
|
+
{
|
|
39757
|
+
const kept = reconcileSavedToolPermissions('start');
|
|
39758
|
+
if (kept.restored.length) console.log(` Tools: ${kept.restored.length} saved tool permission${kept.restored.length === 1 ? '' : 's'} put back in ${getGlobalClaudeSettingsPath()}`);
|
|
39759
|
+
}
|
|
39760
|
+
|
|
39761
|
+
// Every named Claude account reads the default's settings.json (allow list, hooks), CLAUDE.md, rules and skills
|
|
39762
|
+
// (lib/claude-account-links.js): a missing link is made, the junction to a file that an older SynaBun made
|
|
39763
|
+
// on Windows (it opens as a broken folder, so the account read no settings at all) is replaced, and a hard
|
|
39764
|
+
// link or copy two writes apart is brought back in step. Never stops the boot.
|
|
39765
|
+
try {
|
|
39766
|
+
const shared = _panelClaudeAccounts().syncShared();
|
|
39767
|
+
const repaired = shared.filter((row) => row.repaired.length);
|
|
39768
|
+
if (repaired.length) console.log(` Accounts: shared Claude settings put back in order for ${repaired.length} account${repaired.length === 1 ? '' : 's'} (${[...new Set(repaired.flatMap((row) => row.repaired))].join(', ')})`);
|
|
39769
|
+
} catch (err) {
|
|
39770
|
+
console.warn(' Claude accounts warning:', err.message);
|
|
39771
|
+
}
|
|
39772
|
+
|
|
39773
|
+
// Every named Codex account reads Default's config.toml (model, MCP servers, tool settings), AGENTS.md and
|
|
39774
|
+
// prompts/ the same way (lib/codex-accounts.js syncShared). On Windows SynaBun linked the two files with a
|
|
39775
|
+
// symbolic link only, which Windows refuses without Developer Mode or administrator rights: such an account
|
|
39776
|
+
// ran on a config.toml of its own and without AGENTS.md. Put in order once here; a hard link or a copy two
|
|
39777
|
+
// writes apart is brought back in step at every start. Never stops the boot.
|
|
39778
|
+
try {
|
|
39779
|
+
const shared = _codexAccounts().syncShared();
|
|
39780
|
+
const changed = shared.filter((row) => row.repaired.length || row.linked.length);
|
|
39781
|
+
if (changed.length) console.log(` Accounts: shared Codex files put back in order for ${changed.length} account${changed.length === 1 ? '' : 's'} (${[...new Set(changed.flatMap((row) => [...row.repaired, ...row.linked]))].join(', ')})`);
|
|
39782
|
+
} catch (err) {
|
|
39783
|
+
console.warn(' Codex accounts warning:', err.message);
|
|
39784
|
+
}
|
|
39785
|
+
|
|
38869
39786
|
// SynaBun's Antigravity homes (lib/antigravity/home.js): a run's home lives a week past its last use (a run resumes
|
|
38870
39787
|
// within minutes of a restart), an Assistant brain's two months (its conversation can be picked up later).
|
|
38871
39788
|
try {
|
|
@@ -39277,10 +40194,8 @@ function handleWhiteboardWebSocket(ws, req) {
|
|
|
39277
40194
|
let _screenshotPattern = null;
|
|
39278
40195
|
|
|
39279
40196
|
if (process.platform === 'darwin') {
|
|
39280
|
-
|
|
39281
|
-
|
|
39282
|
-
} catch { /* not set — use default */ }
|
|
39283
|
-
if (!_screenshotDir || !existsSync(_screenshotDir)) _screenshotDir = join(os.homedir(), 'Desktop');
|
|
40197
|
+
// The Screenshot app's folder, else ~/Desktop (lib/screenshot-location.js: quiet when none was ever set).
|
|
40198
|
+
_screenshotDir = macScreenshotDir();
|
|
39284
40199
|
// macOS screenshot filenames: "Screenshot ..." (EN), "Captura de..." (ES/PT)
|
|
39285
40200
|
_screenshotPattern = /^(Screenshot\b|Captura de).*\.png$/i;
|
|
39286
40201
|
} else if (process.platform === 'win32') {
|
|
@@ -39455,6 +40370,10 @@ function handleCardsWebSocket(ws) {
|
|
|
39455
40370
|
async function handleBrowserWebSocket(ws, url) {
|
|
39456
40371
|
const sessionId = url.pathname.replace('/ws/browser/', '');
|
|
39457
40372
|
const session = browserSessions.get(sessionId);
|
|
40373
|
+
if (session?._profileMode === 'extension') {
|
|
40374
|
+
ws.send(JSON.stringify({ type: 'error', code: 'UNSUPPORTED_IN_EXTENSION_MODE', message: 'Use the everyday browser window. Extension mode has no CDP screencast or remote input socket.' }));
|
|
40375
|
+
ws.close(); return;
|
|
40376
|
+
}
|
|
39458
40377
|
|
|
39459
40378
|
if (!session) {
|
|
39460
40379
|
ws.send(JSON.stringify({ type: 'error', message: 'Browser session not found' }));
|