synabun 2.3.0 → 2.4.0
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 +38 -0
- package/README.md +1 -1
- package/browser-extension/content.js +169 -0
- package/browser-extension/engine.js +477 -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 +244 -0
- package/browser-extension/popup-view.js +151 -0
- package/browser-extension/popup.css +165 -0
- package/browser-extension/popup.html +105 -0
- package/browser-extension/popup.js +347 -0
- package/browser-extension/protocol.js +226 -0
- package/browser-extension/service-worker.js +267 -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/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 +94 -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 +91 -9
- package/mcp-server/dist/tools/agents.d.ts.map +1 -1
- package/mcp-server/dist/tools/agents.js +161 -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 +190 -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 +175 -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 +1174 -47
- package/neural-interface/i18n/pt-BR.json +1174 -47
- package/neural-interface/lib/account-usage.js +1 -1
- 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 +840 -0
- package/neural-interface/lib/agents/resolve.js +544 -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-catalog.js +2 -0
- package/neural-interface/lib/assistant-continuity.js +49 -0
- package/neural-interface/lib/assistant-dispatch.js +229 -102
- 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 +384 -42
- 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 +440 -93
- 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/browser-close-evidence.js +80 -0
- package/neural-interface/lib/browser-default.js +210 -0
- package/neural-interface/lib/browser-extension-adapter.js +255 -0
- package/neural-interface/lib/browser-extension-bridge.js +418 -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-profiles.js +1 -1
- 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/cli-install-api.js +23 -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/editor-completion-opencode.js +4 -3
- package/neural-interface/lib/effort-levels.js +10 -1
- package/neural-interface/lib/maritaca/opencode-proxy.js +7 -2
- package/neural-interface/lib/maritaca/opencode.js +35 -0
- 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 +219 -7
- package/neural-interface/lib/native-loop-runtime.js +24 -1
- package/neural-interface/lib/opencode-build-preflight.js +116 -0
- package/neural-interface/lib/opencode-launch-error.js +13 -0
- package/neural-interface/lib/opencode-native-boundary.js +800 -84
- package/neural-interface/lib/opencode-serve-probe.js +426 -0
- package/neural-interface/lib/opencode-serve-records.js +14 -9
- package/neural-interface/lib/opencode-serve-scan.js +108 -0
- package/neural-interface/lib/page-session.js +1 -1
- package/neural-interface/lib/peer-identity.js +60 -21
- package/neural-interface/lib/process-identity.js +235 -7
- package/neural-interface/lib/request-gate.js +3 -0
- package/neural-interface/lib/screenshot-location.js +33 -0
- 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/lib/worker-mcp-channel.js +38 -1
- package/neural-interface/package-lock.json +4 -2
- package/neural-interface/package.json +3 -1
- package/neural-interface/public/extension-setup.html +107 -0
- package/neural-interface/public/index.html +52 -12
- 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/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 +36 -6
- package/neural-interface/public/shared/assistant/asst-route.js +78 -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/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 +33 -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/opencode-verify-view.js +175 -0
- 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/storage.js +6 -1
- package/neural-interface/public/shared/studio-attention.js +83 -0
- package/neural-interface/public/shared/styles.css +713 -61
- 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 +12 -1
- 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 +1 -1
- 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-opencode-verify.js +120 -0
- 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 +372 -402
- 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 +5 -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/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 +21 -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 +1164 -157
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -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';
|
|
@@ -166,7 +168,7 @@ import {
|
|
|
166
168
|
import { createCliResolver, spawnArgsFor } from './lib/cli-resolver.js';
|
|
167
169
|
import { osPath } from './lib/os-path.js';
|
|
168
170
|
import { createCliInstaller, CLI_INSTALL_GUIDES } from './lib/cli-install.js';
|
|
169
|
-
import { createCliInstallApi, createCliPathApi, createGitBashApi } from './lib/cli-install-api.js';
|
|
171
|
+
import { createCliInstallApi, createCliPathApi, createGitBashApi, createOpencodeServeVerifyApi } from './lib/cli-install-api.js';
|
|
170
172
|
import { createAppControlsApi, createAppSettingsStore } from './lib/app-controls-api.js';
|
|
171
173
|
import { createCrashNoticeApi } from './lib/crash-notice-api.js';
|
|
172
174
|
import { createLoginStart } from './lib/login-start.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,8 +229,41 @@ 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, nativeServeCapability, nativeServeReason, narrowOffenders } from './lib/opencode-native-boundary.js';
|
|
230
|
-
|
|
232
|
+
import { createNativeServeBoundary, createVerdictFile, nativeContextRevocation, nativeServeCapability, nativeServeReason, nativeServeVersionPolicy, narrowOffenders } from './lib/opencode-native-boundary.js';
|
|
233
|
+
import { isolatedServeFailure } from './lib/opencode-launch-error.js';
|
|
234
|
+
import { reconcilePreflightProfiles, preflightExcludedPorts, runOpencodeBuildPreflight } from './lib/opencode-build-preflight.js';
|
|
235
|
+
import { binaryIdentity as opencodeBinaryIdentity, binaryKey as opencodeBinaryKey } from './lib/opencode-serve-probe.js';
|
|
236
|
+
// Every OpenCode serve SynaBun starts is probed once it answers (lib/opencode-serve-probe.js: loopback only, every
|
|
237
|
+
// sensitive /api request and WebSocket upgrade refused without its password, SynaBun's password accepted); what is
|
|
238
|
+
// learned about a build is kept in DATA_HOME/data/opencode-serve-verdicts.json (read on first use).
|
|
239
|
+
const nativePreflightProfiles = new Set();
|
|
240
|
+
const nativeStaleProfilesLogged = new Set();
|
|
241
|
+
const nativeServeBoundary = createNativeServeBoundary({
|
|
242
|
+
preflight: async (info, operations) => {
|
|
243
|
+
const cfg = loadBrowserConfig();
|
|
244
|
+
const profiles = new Map(normalizeAgentProfiles(cfg).map(p => [p.envId, p]));
|
|
245
|
+
const defaultId = moreLoginDefaultEnvId(cfg);
|
|
246
|
+
if (defaultId) profiles.set(String(defaultId), { envId: String(defaultId) });
|
|
247
|
+
for (const envId of nativePreflightProfiles) profiles.set(envId, { envId });
|
|
248
|
+
const remote = [...profiles.values()].filter(p => !moreLogin.isLocalProfileId(p.envId));
|
|
249
|
+
const liveProfiles = remote.length ? await reconcilePreflightProfiles(remote,
|
|
250
|
+
() => moreLogin.listCompleteProfiles({ savedCfg: cfg, firstPageTimeout: 5000 }),
|
|
251
|
+
{ allowUnavailable: true, log: line => { if (!nativeStaleProfilesLogged.has(line)) { nativeStaleProfilesLogged.add(line); console.warn(`[opencode] ${line}`); } } }) : [];
|
|
252
|
+
const excludedPorts = await preflightExcludedPorts(liveProfiles,
|
|
253
|
+
envId => moreLogin.profileDetail(envId, { savedCfg: cfg, timeout: 5000 }));
|
|
254
|
+
const token = opencodeServeRecords.newToken();
|
|
255
|
+
return runOpencodeBuildPreflight(info, { ...operations, excludedPorts,
|
|
256
|
+
spawnProcess: (command, args, options) => spawn(command, args, { ...options, env: { ...options.env, [SERVE_TOKEN_ENV]: token } }),
|
|
257
|
+
track: (proc, detail) => {
|
|
258
|
+
operations.track(proc, { ...detail, kill: signal => signalOpencodeServeProcess(proc, signal) });
|
|
259
|
+
// A crash must leave the throwaway serve on the same ownership record as every normal serve.
|
|
260
|
+
trackOpencodeServe(proc, { kind: 'isolated', id: 'build-preflight', port: detail.port, token, boundaryTracked: true, recordOnAnswer: false });
|
|
261
|
+
},
|
|
262
|
+
});
|
|
263
|
+
},
|
|
264
|
+
verdicts: createVerdictFile({ file: () => resolve(DATA_HOME, 'data', 'opencode-serve-verdicts.json') }),
|
|
265
|
+
log: (line) => console.warn(`[opencode] ${line}`),
|
|
266
|
+
});
|
|
231
267
|
import { setBrowserNetworkRule, usesNativeBrowserNetworkGuard, disposeBrowserNetworkGuard, recoverBrowserNetworkGuard, MONEY_PATTERNS, SERVE_PORT_PATTERNS } from './lib/browser-network-guard.js';
|
|
232
268
|
import { browserPolicyRoots } from './lib/browser-policy-roots.js';
|
|
233
269
|
import {
|
|
@@ -278,7 +314,7 @@ import { createMaritacaKeyStore } from './lib/maritaca/key-store.js';
|
|
|
278
314
|
import { createMaritacaSessionStore } from './lib/maritaca/sessions.js';
|
|
279
315
|
import { createMaritacaPanelBridge } from './lib/maritaca/panel-bridge.js';
|
|
280
316
|
import { registerMaritacaRoutes } from './lib/maritaca/api.js';
|
|
281
|
-
import { createMaritacaOpencodeSync } from './lib/maritaca/opencode.js';
|
|
317
|
+
import { createMaritacaOpencodeSync, maritacaWorkerChannelProvider } from './lib/maritaca/opencode.js';
|
|
282
318
|
import { createMaritacaOpencodeProxy, maritacaOpencodeProxyBaseUrl } from './lib/maritaca/opencode-proxy.js';
|
|
283
319
|
import { antigravityHomeDir, antigravityHomesRoot, pruneAntigravityHomes } from './lib/antigravity/home.js';
|
|
284
320
|
import { antigravityStores, findUserConversation, parseAntigravityTranscript, readTranscriptText } from './lib/antigravity/transcripts.js';
|
|
@@ -409,10 +445,13 @@ import { applyPackagedChildPath, durableEntry, mcpStdioCommand, npmGlobalBinFor,
|
|
|
409
445
|
import { dataHomeId } from '../lib/desktop-app.js';
|
|
410
446
|
import { pruneExternalTools } from '../lib/external-tools.js';
|
|
411
447
|
import { renderOfflinePage } from './lib/offline-page.js';
|
|
448
|
+
import { logUnexpectedProfileClose } from './lib/browser-close-evidence.js';
|
|
449
|
+
import { etagMatches, memoryListEtag, memoryListStamp } from './lib/memory-list-stamp.js';
|
|
450
|
+
import { parseMemoryPage, pageEtagPart, describePage, isLastPage } from './lib/memory-list-page.js';
|
|
412
451
|
import {
|
|
413
452
|
getDb, closeDb, getDbPath, getEmbedding, getEmbeddingBatch, getEmbeddingDims, warmupEmbeddings,
|
|
414
453
|
encodeVector, decodeVector, cosineSimilarity,
|
|
415
|
-
searchMemories as dbSearchMemories, getAllMemories, getAllMemoriesWithVectors,
|
|
454
|
+
searchMemories as dbSearchMemories, getAllMemories, getMemoriesPage, getAllMemoriesWithVectors,
|
|
416
455
|
getMemoryById, getMemoryWithVector, updateMemoryPayload,
|
|
417
456
|
softDeleteMemory, hardDeleteMemory, restoreMemory as dbRestoreMemory,
|
|
418
457
|
getTrashedMemories, purgeTrash, countMemories, getMemoryStats,
|
|
@@ -494,6 +533,11 @@ let _greeting = null;
|
|
|
494
533
|
let _greetingRouter = null;
|
|
495
534
|
let _greetingError = null;
|
|
496
535
|
let _assistantDispatcher = null;
|
|
536
|
+
// The server's one coordination service (lib/coordination/service.js, DATA_HOME/data/coordination.db), once the
|
|
537
|
+
// Assistant's block made and shared it: the dispatcher, the runtime, and later a team scheduler (its `.store` is what
|
|
538
|
+
// lib/teams takes) all use this instance. Kept here so that every stop path closes it (runGracefulShutdown).
|
|
539
|
+
let _assistantCoordination = null;
|
|
540
|
+
let _assistantTeamScheduler = null;
|
|
497
541
|
// The Assistant's settings store (assistant-config.json), once the Assistant is built: Skills Studio's AI drafting reads
|
|
498
542
|
// the owner's saved route for Coding from it (skillDraftDefaultTarget).
|
|
499
543
|
let _assistantConfigStore = null;
|
|
@@ -619,6 +663,12 @@ import {
|
|
|
619
663
|
import { createOpencodeCompletionEngine } from './lib/editor-completion-opencode.js';
|
|
620
664
|
import { createEndpointCompletionEngine } from './lib/editor-completion-endpoint.js';
|
|
621
665
|
import { ownerRouteGuard } from './lib/http-guards.js';
|
|
666
|
+
import { createBridgeStore, createExtensionBridge } from './lib/browser-extension-bridge.js';
|
|
667
|
+
import { createExtensionAdapter, EXTENSION_FOLDER } from './lib/browser-extension-adapter.js';
|
|
668
|
+
import { detectBrowsers } from './lib/browser-default.js';
|
|
669
|
+
import { extensionFolderState, prepareExtensionFolder } from './lib/browser-extension-folder.js';
|
|
670
|
+
import { createExtensionSetup, setupError as extensionSetupError } from './lib/browser-extension-setup.js';
|
|
671
|
+
import { safeError as extensionSafeError } from '../browser-extension/protocol.js';
|
|
622
672
|
import { setUntrustedFileHeaders } from './lib/untrusted-file-headers.js';
|
|
623
673
|
import { BUNDLED_LOGO_FILES, UPLOADED_IMAGE_PATH } from './lib/request-gate.js';
|
|
624
674
|
import { createCloudflaredManager } from './lib/cloudflared/manager.js';
|
|
@@ -1037,6 +1087,11 @@ function peerLookupWanted(req) {
|
|
|
1037
1087
|
app.use(_pageSession.serviceWorker); // GET /sw.js: a worker that takes itself away, for a browser refused the secret
|
|
1038
1088
|
app.use(_pageSession.pages);
|
|
1039
1089
|
app.get('/api/page-session', (req, res) => _pageSession.refresh(req, res)); // PAGE_SECRET_REFRESH_PATH
|
|
1090
|
+
// The extension's "Connect your browser" page, opened by the one-button setup in the owner's everyday browser. One of
|
|
1091
|
+
// 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
|
|
1092
|
+
// status and its one ticket are the owner's, under the same owner guard; an automation browser and an agent's process
|
|
1093
|
+
// never get the secret (lib/page-session.js). The extension's content script runs on this exact origin and path only.
|
|
1094
|
+
app.get('/extension-setup', (_req, res) => { res.setHeader('Cache-Control', 'no-store'); res.sendFile(join(__dirname, 'public', 'extension-setup.html')); });
|
|
1040
1095
|
// Retired 2D bookmarks and explicit variant links always enter the 3D page. Keep their other URL state.
|
|
1041
1096
|
app.get(['/', '/index.html', '/index2d.html'], (req, res, next) => {
|
|
1042
1097
|
const target = normalizeViewUrl(req.originalUrl);
|
|
@@ -1420,10 +1475,39 @@ app.get('/api/memories', async (req, res) => {
|
|
|
1420
1475
|
// metadata columns dropped. ~4x smaller JSON for large graphs.
|
|
1421
1476
|
const slim = req.query.fields === 'graph';
|
|
1422
1477
|
const SLIM_CONTENT_CHARS = 500;
|
|
1478
|
+
// One page of the list (lib/memory-list-page.js), only without links: `offset` / `limit`. Without `limit`,
|
|
1479
|
+
// every memory, as always (the same body and the same ETag).
|
|
1480
|
+
const page = includeLinks ? null : parseMemoryPage(req.query);
|
|
1481
|
+
if (page?.error) return res.status(400).json({ error: page.error });
|
|
1482
|
+
|
|
1483
|
+
// The list without links (the page's first load): a page that still holds this very answer is told
|
|
1484
|
+
// so before a row is read (lib/memory-list-stamp.js). 32 MB were read, built and serialised on every
|
|
1485
|
+
// load only to find out, from the finished body, that nothing had changed.
|
|
1486
|
+
let listVersion = null;
|
|
1487
|
+
if (!includeLinks) {
|
|
1488
|
+
const ocBridgeNow = loadBridgeConfig('openclaw');
|
|
1489
|
+
if (_openclawNodes !== _openclawNodesSeen) { _openclawNodesSeen = _openclawNodes; _openclawNodesRev += 1; }
|
|
1490
|
+
let listStamp = null;
|
|
1491
|
+
try { listStamp = memoryListStamp(getDb()); } catch { /* no stamp: the full answer, as before */ }
|
|
1492
|
+
const listParts = [
|
|
1493
|
+
listStamp, slim ? 'graph' : 'full', SLIM_CONTENT_CHARS,
|
|
1494
|
+
ocBridgeNow?.enabled ? `openclaw:${_openclawNodesRev}:${_openclawNodes.length}` : 'openclaw:off',
|
|
1495
|
+
];
|
|
1496
|
+
listVersion = memoryListEtag(listParts);
|
|
1497
|
+
// A page's ETag is the list's plus the page's place: an unchanged list is a 304 page by page.
|
|
1498
|
+
const listEtag = page ? memoryListEtag([...listParts, pageEtagPart(page)]) : listVersion;
|
|
1499
|
+
if (listEtag) {
|
|
1500
|
+
res.set('ETag', listEtag);
|
|
1501
|
+
res.set('Cache-Control', 'no-cache');
|
|
1502
|
+
if (etagMatches(req.headers['if-none-match'], listEtag)) return res.status(304).end();
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1423
1505
|
|
|
1424
1506
|
const cachedLinks = includeLinks ? getValidLinkCache() : null;
|
|
1425
1507
|
const needVectors = includeLinks && !cachedLinks;
|
|
1426
|
-
|
|
1508
|
+
// A page reads its own rows only (and how many there are); the whole list reads them all.
|
|
1509
|
+
const pageRead = page ? getMemoriesPage(page) : null;
|
|
1510
|
+
const allPoints = pageRead ? pageRead.rows : (needVectors ? getAllMemoriesWithVectors() : getAllMemories());
|
|
1427
1511
|
|
|
1428
1512
|
// Build nodes
|
|
1429
1513
|
const nodes = allPoints.map(p => ({
|
|
@@ -1432,9 +1516,9 @@ app.get('/api/memories', async (req, res) => {
|
|
|
1432
1516
|
vector: p.vector || null,
|
|
1433
1517
|
}));
|
|
1434
1518
|
|
|
1435
|
-
// Merge OpenClaw bridge nodes
|
|
1519
|
+
// Merge OpenClaw bridge nodes (after the stored memories: in a paged list, on the last page)
|
|
1436
1520
|
const ocBridge = loadBridgeConfig('openclaw');
|
|
1437
|
-
if (ocBridge?.enabled && _openclawNodes.length > 0) {
|
|
1521
|
+
if (ocBridge?.enabled && _openclawNodes.length > 0 && (!page || isLastPage({ ...page, total: pageRead.total }))) {
|
|
1438
1522
|
for (const ocNode of _openclawNodes) {
|
|
1439
1523
|
nodes.push({ ...ocNode, vector: null });
|
|
1440
1524
|
}
|
|
@@ -1471,7 +1555,9 @@ app.get('/api/memories', async (req, res) => {
|
|
|
1471
1555
|
return { ...rest, payload: slimPayload };
|
|
1472
1556
|
});
|
|
1473
1557
|
|
|
1474
|
-
|
|
1558
|
+
const body = { nodes: clientNodes, links, totalVectors: pageRead ? pageRead.total : allPoints.length, openclawNodes: ocBridge?.enabled ? _openclawNodes.length : 0 };
|
|
1559
|
+
if (page) body.page = describePage({ ...page, total: pageRead.total, count: clientNodes.length, version: listVersion });
|
|
1560
|
+
res.json(body);
|
|
1475
1561
|
} catch (err) {
|
|
1476
1562
|
console.error('GET /api/memories error:', err.message);
|
|
1477
1563
|
res.status(500).json({ error: err.message });
|
|
@@ -2454,6 +2540,8 @@ async function runGracefulShutdown(reason) {
|
|
|
2454
2540
|
// Assistant's Claude Code workers that can continue are suspended (they resume
|
|
2455
2541
|
// on the next start, lib/assistant-dispatch.js), and the runtime keeps them;
|
|
2456
2542
|
// every other run is stopped. Either way each worker's CLI is ended now.
|
|
2543
|
+
// Stop team work on every exit path before the workers and the shared store close.
|
|
2544
|
+
try { await _assistantTeamScheduler?.shutdown(); } catch (err) { console.warn(' team scheduler stop err:', err?.message); }
|
|
2457
2545
|
let keepRuns = [];
|
|
2458
2546
|
try { keepRuns = _assistantDispatcher?.suspendForShutdown?.(reason) || []; } catch (err) { console.warn(' assistant suspend err:', err?.message); }
|
|
2459
2547
|
try { await _nativeLoopRuntime?.shutdown(reason, { keep: keepRuns }); } catch (err) { console.warn(' native loop stop err:', err?.message); }
|
|
@@ -2519,6 +2607,10 @@ async function runGracefulShutdown(reason) {
|
|
|
2519
2607
|
// The judge backfill flushes its last counters and releases its lease so
|
|
2520
2608
|
// the respawned server resumes immediately instead of waiting out the lease.
|
|
2521
2609
|
try { stopJudgeBackfill(); } catch {}
|
|
2610
|
+
// The coordination store (agent events, the Assistant's mailbox, the follow-up outbox): closed once the workers
|
|
2611
|
+
// are stopped or suspended and what that changed is recorded. Every open wait is answered, the write-ahead log is
|
|
2612
|
+
// folded into the file. Signals and the restart/update/shutdown routes all use this teardown.
|
|
2613
|
+
try { _assistantCoordination?.close(); } catch (err) { console.warn(' coordination close err:', err?.message); }
|
|
2522
2614
|
try { closeDb(); } catch {}
|
|
2523
2615
|
try { closeBlobStore(); } catch {}
|
|
2524
2616
|
|
|
@@ -3813,15 +3905,23 @@ function getNativeCodexBin() {
|
|
|
3813
3905
|
// serveSpecFor). Every production serve uses `passwordFrom: 'stdout'`: no password variable at all
|
|
3814
3906
|
// (the login shell unsets both after the profile ran): the serve prints the
|
|
3815
3907
|
// password it made, `password` is null and the caller reads it from stdout.
|
|
3816
|
-
function opencodeServeLaunch(port, { env = process.env, password = null, passwordFrom = 'stdout' } = {}) {
|
|
3908
|
+
async function opencodeServeLaunch(port, { env = process.env, password = null, passwordFrom = 'stdout', preflightOnly = false } = {}) {
|
|
3817
3909
|
const found = cliResolver.launcher('opencode');
|
|
3818
3910
|
_noteCliLookup('opencode', found, 'OpenCode');
|
|
3819
3911
|
const line = configuredCommandLine('opencode');
|
|
3820
3912
|
const nativeWebSocketSafe = nativeServeCapability({ version: found.version, commandLine: !!line, passwordFrom });
|
|
3821
3913
|
// What the browser boundary names when this serve is the one that blocks a native (MoreLogin) context. A command
|
|
3822
3914
|
// line from Settings runs whatever it names: the resolver's version is of another binary, so none is reported.
|
|
3823
|
-
|
|
3915
|
+
// The binary's identity (real path, size, times) and version are the build its runtime check is filed under: a
|
|
3916
|
+
// Homebrew update is a new build, checked again.
|
|
3917
|
+
const policy = line ? null : nativeServeVersionPolicy(found.version);
|
|
3918
|
+
const identity = line ? null : opencodeBinaryIdentity(found.launchPath || found.path || null);
|
|
3919
|
+
const nativeServe = { version: line ? null : (policy?.version || found.version || null), path: line || found.launchPath || found.path || null,
|
|
3920
|
+
reason: nativeServeReason({ version: found.version, commandLine: !!line, passwordFrom }),
|
|
3921
|
+
identity, key: opencodeBinaryKey(identity, policy?.version || null), knownGood: !!policy?.knownGood };
|
|
3922
|
+
await nativeServeBoundary.prepareBuild(nativeWebSocketSafe, { port, ...nativeServe });
|
|
3824
3923
|
nativeServeBoundary.assertLaunch(nativeWebSocketSafe, { port, ...nativeServe });
|
|
3924
|
+
if (preflightOnly) return nativeServe;
|
|
3825
3925
|
const spec = serveSpecFor(port, { env, password, passwordFrom });
|
|
3826
3926
|
const words = spec.args.join(' ');
|
|
3827
3927
|
if (IS_WIN) {
|
|
@@ -3833,7 +3933,9 @@ function opencodeServeLaunch(port, { env = process.env, password = null, passwor
|
|
|
3833
3933
|
const text = `${line || 'opencode'} ${words}`;
|
|
3834
3934
|
return { command: DEFAULT_SHELL, args: ['/d', '/s', '/c', text], options: { env: spawnEnv, windowsHide: true }, label: text, password: spec.password, passwordFrom: spec.passwordFrom, nativeWebSocketSafe, nativeServe };
|
|
3835
3935
|
}
|
|
3836
|
-
|
|
3936
|
+
// The file whose identity and version were just read is the one exec'd: its real path, not a link that could be
|
|
3937
|
+
// pointed elsewhere between the read and the start (the boundary checks the listening process runs that file).
|
|
3938
|
+
const cmd = line || (identity?.realpath ? shellSingleQuote(identity.realpath) : found.path ? shellSingleQuote(found.path) : 'opencode');
|
|
3837
3939
|
const unset = spec.passwordFrom === 'stdout' ? `${serveUnsetCommand()}; ` : '';
|
|
3838
3940
|
// A packaged application's runtime and npm after the user's own (the login shell adds the user's profile on top).
|
|
3839
3941
|
return { command: DEFAULT_SHELL, args: ['-lc', `${unset}exec ${cmd} ${words}`], options: { env: withPackagedPathLast(spec.env) }, label: `${cmd} ${words}`, password: spec.password, passwordFrom: spec.passwordFrom, nativeWebSocketSafe, nativeServe };
|
|
@@ -4109,9 +4211,10 @@ async function resolveOpenCodeMcpDirectory(entry, sessionIds) {
|
|
|
4109
4211
|
|
|
4110
4212
|
// ── Multi-account Codex (per-tab CODEX_HOME) ────────────────────────────────
|
|
4111
4213
|
// Each ChatGPT account gets its own CODEX_HOME directory holding its own
|
|
4112
|
-
// auth.json + sessions/ + state DB, while config.toml and prompts/ are
|
|
4113
|
-
//
|
|
4114
|
-
// and custom prompts stay shared
|
|
4214
|
+
// auth.json + sessions/ + state DB, while config.toml, AGENTS.md and prompts/ are
|
|
4215
|
+
// linked back to the canonical ~/.codex so model/MCP/tool-permission config
|
|
4216
|
+
// and custom prompts stay shared (how, on each system: lib/claude-account-links.js).
|
|
4217
|
+
// The "default" account IS ~/.codex itself.
|
|
4115
4218
|
const CODEX_DEFAULT_HOME = resolve(process.env.CODEX_HOME || resolve(getHomePath(), '.codex'));
|
|
4116
4219
|
const CODEX_ACCOUNTS_ROOT = resolve(getHomePath(), '.codex-accounts');
|
|
4117
4220
|
|
|
@@ -4445,6 +4548,13 @@ function _codexAccounts() {
|
|
|
4445
4548
|
return _codexAccountsInstance;
|
|
4446
4549
|
}
|
|
4447
4550
|
|
|
4551
|
+
// Default's config.toml was written (by SynaBun, or by Codex for a panel's settings): every named account
|
|
4552
|
+
// reads the same again. Only where an account shares it by a hard link or a copy (Windows without symbolic
|
|
4553
|
+
// links, lib/claude-account-links.js): a symbolic link has nothing to bring in step. Never stops a write.
|
|
4554
|
+
function codexSharedFilesChanged() {
|
|
4555
|
+
try { _codexAccounts().syncShared?.(); } catch { /* the next launch of an account puts it in step */ }
|
|
4556
|
+
}
|
|
4557
|
+
|
|
4448
4558
|
// The registry rows (id, label, home, …) for readers that only need where an account lives.
|
|
4449
4559
|
function loadCodexAccounts() {
|
|
4450
4560
|
return { accounts: _codexAccounts().registryRows(), defaultId: 'default' };
|
|
@@ -7392,6 +7502,8 @@ CRITICAL — When you need clarification during planning:
|
|
|
7392
7502
|
const nextConfig = validateCodexConfigRequirements(supported, await readCodexRequirements());
|
|
7393
7503
|
const edits = buildCodexConfigEdits(nextConfig);
|
|
7394
7504
|
await request('config/batchWrite', { edits, reloadUserConfig: true }, 10000);
|
|
7505
|
+
// Codex wrote this account's config.toml as a new file: Default and the other accounts get it too.
|
|
7506
|
+
try { codexSharedFilesChanged(); } catch { /* never stops a save */ }
|
|
7395
7507
|
const config = await readConfigState(msg.cwd || PACKAGE_ROOT);
|
|
7396
7508
|
codexContextModels = [];
|
|
7397
7509
|
// config.toml is every account's (shared): their kept model lists are read again.
|
|
@@ -8373,8 +8485,12 @@ function noteOpencodeServePort(port, delta) {
|
|
|
8373
8485
|
if (next > 0) _opencodeServePortCounts.set(p, next); else _opencodeServePortCounts.delete(p);
|
|
8374
8486
|
}
|
|
8375
8487
|
|
|
8376
|
-
function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocketSafe = false, nativeServe = null }) {
|
|
8377
|
-
|
|
8488
|
+
function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocketSafe = false, nativeServe = null, boundaryTracked = false, recordOnAnswer = true }) {
|
|
8489
|
+
// A serve that fails its runtime check while a native context is attached is stopped (its pages could reach it).
|
|
8490
|
+
// A serve that fails its runtime check is stopped by the boundary: SIGTERM, then SIGKILL, until the OS confirms
|
|
8491
|
+
// its process and its listener are gone (lib/opencode-native-boundary.js terminate).
|
|
8492
|
+
// The pre-flight coordinator already tracked this handle and retained its cleanup evidence.
|
|
8493
|
+
if (!boundaryTracked) nativeServeBoundary.track(proc, { ...(nativeServe || {}), port, safe: nativeWebSocketSafe, kill: (signal) => signalOpencodeServeProcess(proc, signal) });
|
|
8378
8494
|
const pid = Number(proc?.pid) || null;
|
|
8379
8495
|
const exited = () => !proc || proc.exitCode != null || proc.signalCode != null;
|
|
8380
8496
|
if (!exited()) {
|
|
@@ -8385,7 +8501,10 @@ function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocke
|
|
|
8385
8501
|
// A spawn that failed (no pid) may never exit; a failed kill leaves the process running.
|
|
8386
8502
|
proc.once?.('error', () => { if (!proc.pid || exited()) release(); });
|
|
8387
8503
|
}
|
|
8388
|
-
|
|
8504
|
+
// Right after the spawn the process may not show its environment yet (its token): a miss here is expected when
|
|
8505
|
+
// answering() records it again once it answers, and only that second try says why (recordOnAnswer: the caller
|
|
8506
|
+
// calls answering(); the build pre-flight does not, so its one try says it).
|
|
8507
|
+
const spawned = pid ? opencodeServeRecords.record({ kind, id, port, pid, token, quiet: recordOnAnswer }).catch(() => null) : Promise.resolve(null);
|
|
8389
8508
|
let started = Promise.resolve(null);
|
|
8390
8509
|
const forget = () => {
|
|
8391
8510
|
spawned.then((record) => { if (record) opencodeServeRecords.remove(record); }).catch(() => {});
|
|
@@ -8395,13 +8514,15 @@ function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocke
|
|
|
8395
8514
|
else proc.once?.('exit', forget);
|
|
8396
8515
|
return {
|
|
8397
8516
|
spawned,
|
|
8398
|
-
|
|
8517
|
+
// `password`: the one the serve printed, which its runtime check proves it accepts.
|
|
8518
|
+
async answering({ password = null } = {}) {
|
|
8399
8519
|
await spawned;
|
|
8400
8520
|
const who = await opencodeServeRecords.answering({ port, pid, exited });
|
|
8401
8521
|
// Every caller has already passed private HTTP/WS readiness. A port
|
|
8402
8522
|
// collision never becomes a native capability; a new native attachment
|
|
8403
|
-
// must wait until this check, including starts already under way
|
|
8404
|
-
|
|
8523
|
+
// must wait until this check, including starts already under way, and
|
|
8524
|
+
// until the serve's runtime check (started here, in the background) passed.
|
|
8525
|
+
if (who.state !== 'foreign' && !exited()) nativeServeBoundary.ready(proc, { pid: who.state === 'ours' ? who.pid : pid, password });
|
|
8405
8526
|
if (who.state !== 'ours') return who.state;
|
|
8406
8527
|
// Read again now that it answers (its login shell has exec'd OpenCode by now), and the process that answers
|
|
8407
8528
|
// when the spawned one started it.
|
|
@@ -8655,6 +8776,16 @@ async function endOpencodeChild(proc, timeoutMs = 3000) {
|
|
|
8655
8776
|
return false;
|
|
8656
8777
|
}
|
|
8657
8778
|
|
|
8779
|
+
// One signal to a serve SynaBun spawned. Windows has no SIGTERM: taskkill ends the tree, /F for SIGKILL.
|
|
8780
|
+
function signalOpencodeServeProcess(proc, signal = 'SIGTERM') {
|
|
8781
|
+
if (!proc || proc.exitCode != null || proc.signalCode != null) return;
|
|
8782
|
+
if (IS_WIN && proc.pid) {
|
|
8783
|
+
spawn('taskkill', ['/pid', String(proc.pid), '/T', ...(signal === 'SIGKILL' ? ['/F'] : [])], { windowsHide: true, stdio: 'ignore' }).on?.('error', () => {});
|
|
8784
|
+
return;
|
|
8785
|
+
}
|
|
8786
|
+
proc.kill(signal);
|
|
8787
|
+
}
|
|
8788
|
+
|
|
8658
8789
|
function killIsolatedServeProcess(proc) {
|
|
8659
8790
|
try {
|
|
8660
8791
|
if (proc && !proc.killed && proc.exitCode == null) {
|
|
@@ -8820,7 +8951,8 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8820
8951
|
if (serializeToolList(entry.tools) !== serializeToolList(requestedTools)) {
|
|
8821
8952
|
throw new Error(`OpenCode serve ${termId} is starting with ${serializeToolList(entry.tools)}; scoped restart required for ${serializeToolList(requestedTools)}`);
|
|
8822
8953
|
}
|
|
8823
|
-
for (let i = 0; i < 60 && !entry.ready; i++) await new Promise(r => setTimeout(r, 250));
|
|
8954
|
+
for (let i = 0; i < 60 && !entry.ready && !entry.startError; i++) await new Promise(r => setTimeout(r, 250));
|
|
8955
|
+
if (entry.startError) throw entry.startError;
|
|
8824
8956
|
return entry.ready ? entry : null;
|
|
8825
8957
|
}
|
|
8826
8958
|
// An OpenCode SynaBun does not drive (OpenCode 0 / 1, an OpenCode 2 older than the minimum, OpenCode 3) never
|
|
@@ -8892,6 +9024,11 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8892
9024
|
const wanted = () => _ocpIsoServes.get(termId) === entry;
|
|
8893
9025
|
let check = null;
|
|
8894
9026
|
let started = 'cancelled';
|
|
9027
|
+
// Validate this run's pin once, before taking the global start lock. An offline API must not delay every
|
|
9028
|
+
// other start, nor be listed again for each port collision. Later live pages retain the normal 15s budget.
|
|
9029
|
+
const pin = runMoreLoginPin(termId);
|
|
9030
|
+
if (pin?.envId && !moreLogin.isLocalProfileId(pin.envId)) await reconcilePreflightProfiles([],
|
|
9031
|
+
() => moreLogin.listCompleteProfiles({ ..._moreLoginOpts(), firstPageTimeout: 5000 }), { requested: [pin.envId], allowUnavailable: true });
|
|
8895
9032
|
// Another server that takes the port while this serve boots is a start collision: it is left running (and never
|
|
8896
9033
|
// put on record), this start's own process is ended, and the start tries the next free port (three at most).
|
|
8897
9034
|
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
@@ -8902,7 +9039,7 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8902
9039
|
const token = opencodeServeRecords.newToken();
|
|
8903
9040
|
// A protected worker's serve (hidePassword): no password variable in any environment, its own shell's
|
|
8904
9041
|
// included; the serve prints the password it made, read here from its output (and never logged).
|
|
8905
|
-
const launch = opencodeServeLaunch(port, { env: { ...isolatedEnv, [SERVE_TOKEN_ENV]: token }, passwordFrom: 'stdout' });
|
|
9042
|
+
const launch = await opencodeServeLaunch(port, { env: { ...isolatedEnv, [SERVE_TOKEN_ENV]: token }, passwordFrom: 'stdout' });
|
|
8906
9043
|
const readPassword = launch.passwordFrom === 'stdout' ? servePasswordReader() : null;
|
|
8907
9044
|
// A guarded worker's serve (macOS): run the whole serve tree under the run's Seatbelt profile, so its shell
|
|
8908
9045
|
// commands cannot reach SynaBun's control port. The profile leaves the worker-only channel open, which the
|
|
@@ -8959,7 +9096,7 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
8959
9096
|
if (readPassword && !entry.password) { if (proc.exitCode != null || proc.signalCode != null) { outcome = 'exited'; break; } continue; }
|
|
8960
9097
|
check = await checkOpencodeServer({ port, password: entry.password, timeoutMs: 3000 });
|
|
8961
9098
|
if (check.ok) {
|
|
8962
|
-
if (await tracked.answering() !== 'foreign') { booting = false; return 'ready'; }
|
|
9099
|
+
if (await tracked.answering({ password: entry.password }) !== 'foreign') { booting = false; return 'ready'; }
|
|
8963
9100
|
outcome = 'collision';
|
|
8964
9101
|
break;
|
|
8965
9102
|
}
|
|
@@ -9026,9 +9163,11 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
|
|
|
9026
9163
|
console.log(`[ocp-iso] isolated serve ready term=${tag} port=${port} tools=${serializeToolList(requestedTools)}`);
|
|
9027
9164
|
return entry;
|
|
9028
9165
|
} catch (err) {
|
|
9029
|
-
|
|
9166
|
+
const failure = isolatedServeFailure(err);
|
|
9167
|
+
entry.startError = failure;
|
|
9168
|
+
console.warn(`[ocp-iso] spawn failed: ${failure.message}`);
|
|
9030
9169
|
endIsolatedStart(termId, entry);
|
|
9031
|
-
|
|
9170
|
+
throw failure;
|
|
9032
9171
|
}
|
|
9033
9172
|
}
|
|
9034
9173
|
|
|
@@ -9811,7 +9950,7 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
|
|
|
9811
9950
|
try {
|
|
9812
9951
|
// A token of this spawn in its environment: what tells its processes from any other (lib/opencode-serve-records.js).
|
|
9813
9952
|
const token = opencodeServeRecords.newToken();
|
|
9814
|
-
const launch = opencodeServeLaunch(_ocpPort, { env: { ...process.env, FORCE_COLOR: '0', OPENCODE_DISABLE_CLAUDE_CODE: '1', [SERVE_TOKEN_ENV]: token,
|
|
9953
|
+
const launch = await opencodeServeLaunch(_ocpPort, { env: { ...process.env, FORCE_COLOR: '0', OPENCODE_DISABLE_CLAUDE_CODE: '1', [SERVE_TOKEN_ENV]: token,
|
|
9815
9954
|
OPENCODE_CONFIG_CONTENT: buildSharedOpenCodeConfigOverlay(opencodeServeBaseConfig(), process.env.OPENCODE_CONFIG_CONTENT),
|
|
9816
9955
|
} });
|
|
9817
9956
|
_ocpPassword = launch.password;
|
|
@@ -9856,7 +9995,7 @@ async function ensureOpencodeServer({ allowDuringHistoryClear = false } = {}) {
|
|
|
9856
9995
|
if (await checkOpencodeHealth()) {
|
|
9857
9996
|
// Only SynaBun's own process counts (the spawned one, or one it started): another server that took the
|
|
9858
9997
|
// port meanwhile answers for itself.
|
|
9859
|
-
if (await tracked.answering() !== 'foreign') return 'ready';
|
|
9998
|
+
if (await tracked.answering({ password: _ocpPassword }) !== 'foreign') return 'ready';
|
|
9860
9999
|
if (_ocpProc === proc) _ocpProc = null;
|
|
9861
10000
|
killIsolatedServeProcess(proc);
|
|
9862
10001
|
await endOpencodeChild(proc);
|
|
@@ -13803,6 +13942,10 @@ function parseDailyLogs(memoryDir) {
|
|
|
13803
13942
|
// --- OpenClaw Bridge: In-Memory Store ---
|
|
13804
13943
|
|
|
13805
13944
|
let _openclawNodes = [];
|
|
13945
|
+
// The list above is replaced whole when the bridge syncs: which one GET /api/memories last saw, and how
|
|
13946
|
+
// many times it has changed (part of that route's ETag).
|
|
13947
|
+
let _openclawNodesSeen = null;
|
|
13948
|
+
let _openclawNodesRev = 0;
|
|
13806
13949
|
let _openclawCategories = [];
|
|
13807
13950
|
let _openclawLastSync = null;
|
|
13808
13951
|
|
|
@@ -14136,6 +14279,7 @@ function writeLoopTemplates(templates) {
|
|
|
14136
14279
|
for (const [path, fileTemplates] of byPath) {
|
|
14137
14280
|
writeLoopTemplateFile(path, fileTemplates, formatByPath.get(path) || 'array');
|
|
14138
14281
|
}
|
|
14282
|
+
if (!_scheduleFilesWatcher) broadcastSync({ type: 'assistant:automation-records-changed', templates: true });
|
|
14139
14283
|
}
|
|
14140
14284
|
|
|
14141
14285
|
function readLoopFolders() {
|
|
@@ -14835,7 +14979,7 @@ app.post('/api/loop/launch', async (req, res) => {
|
|
|
14835
14979
|
const loopTerminalToken = nativeRuntime ? null : _terminalTokens.issue(terminalSessionId);
|
|
14836
14980
|
if (loopTerminalToken) issuedLoopTerminal = terminalSessionId;
|
|
14837
14981
|
// The launch's MoreLogin profile (decided above) becomes the run's pin, as a schedule's does. None: the default
|
|
14838
|
-
// browser
|
|
14982
|
+
// AI browser (Settings → Connected tools → MoreLogin), as before.
|
|
14839
14983
|
if (launchMoreLogin) {
|
|
14840
14984
|
pinRunMoreLoginProfile(terminalSessionId, launchMoreLogin.moreloginEnvId, launchMoreLogin.moreloginEnvName, launchMoreLogin.moreloginEnvBy);
|
|
14841
14985
|
pinnedLoopTerminal = terminalSessionId;
|
|
@@ -15228,6 +15372,9 @@ app.post('/api/loop/recover-browser', async (req, res) => {
|
|
|
15228
15372
|
// token, so naming a run (or routing as it) moves nothing without it (403 TERMINAL_TOKEN_REQUIRED / _INVALID).
|
|
15229
15373
|
const who = browserCaller(req);
|
|
15230
15374
|
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
15375
|
+
if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(who.id) && who.status !== 'verified') {
|
|
15376
|
+
return res.status(403).json(extensionSafeError({ code: 'AUTH_FAILED' }));
|
|
15377
|
+
}
|
|
15231
15378
|
const caller = browserOwnerId(who.id);
|
|
15232
15379
|
if (!caller) {
|
|
15233
15380
|
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' });
|
|
@@ -15255,6 +15402,11 @@ app.post('/api/loop/recover-browser', async (req, res) => {
|
|
|
15255
15402
|
return res.json({ ok: true, sessionId, tabId, adopted: true });
|
|
15256
15403
|
}
|
|
15257
15404
|
const fresh = req.body?.reason === 'create';
|
|
15405
|
+
// A create that takes over one of the owner's tabs in the everyday browser (extension mode only).
|
|
15406
|
+
const takeOverTab = fresh && typeof req.body?.takeOverTab === 'string' && loadBrowserConfig().connectMode === 'extension' ? req.body.takeOverTab : null;
|
|
15407
|
+
if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(who.id) && !fresh) {
|
|
15408
|
+
return res.status(410).json(extensionSafeError({ code: 'TAB_CLOSED' }));
|
|
15409
|
+
}
|
|
15258
15410
|
const lost = req.body?.lost && typeof req.body.lost === 'object' ? req.body.lost : null;
|
|
15259
15411
|
if (named && !fresh) {
|
|
15260
15412
|
const current = liveAutomationRoute(named, { files: true });
|
|
@@ -15263,7 +15415,10 @@ app.post('/api/loop/recover-browser', async (req, res) => {
|
|
|
15263
15415
|
}
|
|
15264
15416
|
}
|
|
15265
15417
|
const start = async () => {
|
|
15266
|
-
const acq = await acquireLoopBrowserAndTab({ terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser' });
|
|
15418
|
+
const acq = await acquireLoopBrowserAndTab({ terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser', takeOverTab });
|
|
15419
|
+
// Its profile was closed outside SynaBun under it and is not started again for it: the loop ends when its turn
|
|
15420
|
+
// ends, never asking again iteration after iteration.
|
|
15421
|
+
if (acq.code === 'MORELOGIN_CLOSED_OUTSIDE') finishBlockedLoop(owner, acq);
|
|
15267
15422
|
if (acq.error) throw Object.assign(new Error(acq.error), { acquisition: acq });
|
|
15268
15423
|
// The run ended while its tab was being opened (a cold start): the tab goes at once, never left to a dead run.
|
|
15269
15424
|
if (named && automationRunState(named, { files: true }) === 'ended') {
|
|
@@ -15277,7 +15432,7 @@ app.post('/api/loop/recover-browser', async (req, res) => {
|
|
|
15277
15432
|
if (named) noteAutomationBrowserRoute(named, acq, fresh ? 'created' : 'recovered');
|
|
15278
15433
|
return acq;
|
|
15279
15434
|
};
|
|
15280
|
-
const outcome = await browserStartHandoff.run(`run:${owner}`, start, {
|
|
15435
|
+
const outcome = await browserStartHandoff.run(takeOverTab ? `run:${owner}:take:${takeOverTab}` : `run:${owner}`, start, {
|
|
15281
15436
|
gone: browserCallerGone(req, res),
|
|
15282
15437
|
waitMs: startWaitMs(browserRequestDeadline(req)),
|
|
15283
15438
|
alive: (acq) => startedTabAlive(acq.browserSessionId, acq.browserTabId, owner),
|
|
@@ -15289,11 +15444,57 @@ app.post('/api/loop/recover-browser', async (req, res) => {
|
|
|
15289
15444
|
res.json({ ok: true, sessionId: acq.browserSessionId, tabId: acq.browserTabId || null, ...(outcome.from !== 'started' && { handedOver: outcome.from }) });
|
|
15290
15445
|
} catch (err) {
|
|
15291
15446
|
const acq = err?.acquisition;
|
|
15292
|
-
|
|
15447
|
+
// A run blocked by a close outside SynaBun: 409 (nothing is wrong with the server, the run is refused on purpose).
|
|
15448
|
+
if (acq?.code === 'MORELOGIN_CLOSED_OUTSIDE') {
|
|
15449
|
+
return res.status(409).json(closedOutsideAnswer(acq));
|
|
15450
|
+
}
|
|
15451
|
+
if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}), ...(acq.needsUser ? { needsUser: true } : {}) });
|
|
15293
15452
|
res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
|
|
15294
15453
|
}
|
|
15295
15454
|
});
|
|
15296
15455
|
|
|
15456
|
+
/**
|
|
15457
|
+
* A loop whose browser was refused because its MoreLogin profile was closed outside SynaBun under it
|
|
15458
|
+
* (lib/morelogin-outside-close.js): it ends when its current turn ends, stoppedReason 'browser_closed_outside', in
|
|
15459
|
+
* place of starting its next iteration and asking again. A native loop through NativeLoopRuntime.finishAfterTurn
|
|
15460
|
+
* (the turn under way reports the refusal it got); a terminal loop's state file is marked inactive the way a PTY
|
|
15461
|
+
* exit marks it, which its driver reads before the next iteration. A dispatched task run is left to its brain (it
|
|
15462
|
+
* gets the refusal, needsUser). Once per run. Returns whether the loop was set to end.
|
|
15463
|
+
*/
|
|
15464
|
+
const _blockedLoopsEnded = new Set();
|
|
15465
|
+
function finishBlockedLoop(ownerKey, acq = null) {
|
|
15466
|
+
if (!ownerKey || _blockedLoopsEnded.has(ownerKey)) return false;
|
|
15467
|
+
let ended = false;
|
|
15468
|
+
try {
|
|
15469
|
+
if (_nativeLoopRuntime?.isAlive?.(ownerKey)) {
|
|
15470
|
+
ended = !!_nativeLoopRuntime.finishAfterTurn?.(ownerKey, 'browser_closed_outside');
|
|
15471
|
+
} else {
|
|
15472
|
+
const loopFile = findLoopFileForTerminal(ownerKey);
|
|
15473
|
+
if (loopFile) {
|
|
15474
|
+
const loopPath = resolve(LOOP_DIR, loopFile);
|
|
15475
|
+
const ls = JSON.parse(readFileSync(loopPath, 'utf-8'));
|
|
15476
|
+
if (ls.active && ls.runtimeType !== 'native' && ls.driverType !== 'native' && ls.runMode !== 'task') {
|
|
15477
|
+
ls.active = false;
|
|
15478
|
+
ls.pending = false;
|
|
15479
|
+
ls.completedAt = new Date().toISOString();
|
|
15480
|
+
ls.stoppedReason = 'browser_closed_outside';
|
|
15481
|
+
writeFileSync(loopPath, JSON.stringify(ls, null, 2));
|
|
15482
|
+
if (ls.driverType === 'exec' && ls.scheduledBy) persistExecScheduleOutcome(ls, 'stopped', 'browser_closed_outside');
|
|
15483
|
+
ended = true;
|
|
15484
|
+
}
|
|
15485
|
+
}
|
|
15486
|
+
}
|
|
15487
|
+
} catch (err) {
|
|
15488
|
+
loopLog(ownerKey, 'browser:blocked', 'could not set the loop to end after its turn', { err: err?.message || String(err) });
|
|
15489
|
+
}
|
|
15490
|
+
if (ended) {
|
|
15491
|
+
if (_blockedLoopsEnded.size > 2000) _blockedLoopsEnded.delete(_blockedLoopsEnded.values().next().value);
|
|
15492
|
+
_blockedLoopsEnded.add(ownerKey);
|
|
15493
|
+
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 });
|
|
15494
|
+
}
|
|
15495
|
+
return ended;
|
|
15496
|
+
}
|
|
15497
|
+
|
|
15297
15498
|
// GET /api/loop/history — no history keeping, always empty
|
|
15298
15499
|
app.get('/api/loop/history', (_req, res) => { res.json([]); });
|
|
15299
15500
|
|
|
@@ -15354,8 +15555,10 @@ function _armScheduleFilesWatcher() {
|
|
|
15354
15555
|
if (_scheduleFilesWatcher) return true;
|
|
15355
15556
|
try {
|
|
15356
15557
|
const w = fsWatch(LOOP_DATA_DIR, (eventType, filename) => {
|
|
15357
|
-
|
|
15358
|
-
|
|
15558
|
+
const schedules = !filename || LOOP_SCHEDULES_PATTERN.test(filename);
|
|
15559
|
+
const templates = !filename || LOOP_TEMPLATES_PATTERN.test(filename);
|
|
15560
|
+
if (schedules) _scheduleFilesCache = null;
|
|
15561
|
+
if (schedules || templates) broadcastSync({ type: 'assistant:automation-records-changed', schedules, templates });
|
|
15359
15562
|
});
|
|
15360
15563
|
w.unref?.();
|
|
15361
15564
|
w.on('error', () => {
|
|
@@ -15473,6 +15676,7 @@ function saveScheduleStore(store) {
|
|
|
15473
15676
|
for (const [path, schedules] of byPath) {
|
|
15474
15677
|
writeLoopScheduleFile(path, schedules, path === LOOP_SCHEDULES_PATH ? groups : [], formatByPath.get(path) || 'object', files);
|
|
15475
15678
|
}
|
|
15679
|
+
if (!_scheduleFilesWatcher) broadcastSync({ type: 'assistant:automation-records-changed', schedules: true });
|
|
15476
15680
|
}
|
|
15477
15681
|
|
|
15478
15682
|
function loadSchedules() {
|
|
@@ -15519,7 +15723,7 @@ function applyScheduleLaunchOverrides(schedule, source) {
|
|
|
15519
15723
|
}
|
|
15520
15724
|
|
|
15521
15725
|
// A schedule's or a schedule group's own MoreLogin profile (optional). Empty / null clears it: the run then opens the
|
|
15522
|
-
// default browser
|
|
15726
|
+
// default AI browser (Settings → Connected tools → MoreLogin), as every record without the field does. The name is kept for display only.
|
|
15523
15727
|
// At launch a schedule's own profile wins, then its group's (scheduleMoreLoginProfile); nothing is copied from a group
|
|
15524
15728
|
// onto its schedules.
|
|
15525
15729
|
function applyScheduleMoreLoginProfile(schedule, source) {
|
|
@@ -16066,8 +16270,9 @@ async function launchScheduledLoop(schedule) {
|
|
|
16066
16270
|
console.log(`[schedule] "${schedule.name}" runs in ${describeMoreLoginPin(runMoreLoginPin(terminalSessionId))}${scheduledMoreLogin.source === 'group' ? ' (its group\'s profile)' : ''}`);
|
|
16067
16271
|
}
|
|
16068
16272
|
if (scheduledUsesBrowser) {
|
|
16069
|
-
// Same serialized shared-browser + dedicated-tab acquisition as manual loops.
|
|
16070
|
-
|
|
16273
|
+
// Same serialized shared-browser + dedicated-tab acquisition as manual loops. A new firing may start a profile
|
|
16274
|
+
// closed outside SynaBun (lib/morelogin-outside-close.js): that is what the schedule is for.
|
|
16275
|
+
const acq = await acquireLoopBrowserAndTab({ terminalSessionId, logTag: 'schedule:browser', scheduledFiring: true });
|
|
16071
16276
|
if (acq.error) {
|
|
16072
16277
|
throw new Error(acq.error);
|
|
16073
16278
|
}
|
|
@@ -18914,6 +19119,20 @@ const cliInstaller = createCliInstaller({
|
|
|
18914
19119
|
app.use('/api/cli/install', createCliInstallApi({ installer: cliInstaller, isGuestRequest, port: () => PORT, log: (line) => console.warn(line) }));
|
|
18915
19120
|
// Settings beside the CLIs: the Git Bash Claude Code gets on Windows, its download and a new look (lib/git-bash/).
|
|
18916
19121
|
app.use('/api/cli/git-bash', createGitBashApi({ manager: gitBash, isGuestRequest, port: () => PORT, onRecheck: async () => { syncGitBashSettings(); } }));
|
|
19122
|
+
// Settings → Executable paths → Verify OpenCode: the serves SynaBun runs, each one's runtime authentication check
|
|
19123
|
+
// (lib/opencode-serve-probe.js through nativeServeBoundary), a check again on request, and the OpenCode SynaBun would
|
|
19124
|
+
// start with what is known about that build.
|
|
19125
|
+
app.use('/api/cli/opencode-serves', createOpencodeServeVerifyApi({ boundary: nativeServeBoundary, isGuestRequest, port: () => PORT,
|
|
19126
|
+
executable: () => {
|
|
19127
|
+
if (configuredCommandLine('opencode')) return { commandLine: true, path: null, version: null, policy: 'command-line', verdict: null };
|
|
19128
|
+
const found = cliResolver.launcher('opencode');
|
|
19129
|
+
if (!found.path) return { commandLine: false, path: null, version: null, policy: 'missing', verdict: null };
|
|
19130
|
+
const policy = nativeServeVersionPolicy(found.version);
|
|
19131
|
+
const key = opencodeBinaryKey(opencodeBinaryIdentity(found.launchPath || found.path), policy.version);
|
|
19132
|
+
const known = key ? nativeServeBoundary.buildVerdict(key) : null;
|
|
19133
|
+
return { commandLine: false, path: found.path, version: policy.version || found.version || null, knownGood: policy.knownGood,
|
|
19134
|
+
policy: policy.ok ? 'ok' : policy.reason, verdict: known ? { ok: known.ok, failed: known.failed || null, detail: known.detail || null, at: known.at || null } : null };
|
|
19135
|
+
} }));
|
|
18917
19136
|
|
|
18918
19137
|
// ═══════════════════════════════════════════
|
|
18919
19138
|
// FULL SYSTEM BACKUP & RESTORE
|
|
@@ -19457,7 +19676,7 @@ const editorCompletionServe = createOpencodeCompletionEngine({
|
|
|
19457
19676
|
// On record from its spawn (spawnServe), its record gone with its process: a crash of SynaBun does not leave it
|
|
19458
19677
|
// running. Once something answers on its port: is it this start's own serve ('foreign': another server took the
|
|
19459
19678
|
// port, which the engine leaves running while it tries another)?
|
|
19460
|
-
trackServe: ({ proc }) => editorCompletionServeTracks.get(proc)?.answering(),
|
|
19679
|
+
trackServe: ({ proc, password }) => editorCompletionServeTracks.get(proc)?.answering({ password }),
|
|
19461
19680
|
// As the isolated serves are started (opencodeServeLaunch): the CLI the resolver found, through the login shell,
|
|
19462
19681
|
// with the password OpenCode prints privately for this start; its start waits its turn among every serve SynaBun starts
|
|
19463
19682
|
// (one OpenCode database cannot be opened by two serves at once).
|
|
@@ -19465,9 +19684,9 @@ const editorCompletionServe = createOpencodeCompletionEngine({
|
|
|
19465
19684
|
startOneAtATime: oneOpencodeStartAtATime,
|
|
19466
19685
|
passwordFrom: 'stdout',
|
|
19467
19686
|
checkServer: checkOpencodeServer,
|
|
19468
|
-
spawnServe: ({ port, env, cwd }) => {
|
|
19687
|
+
spawnServe: async ({ port, env, cwd }) => {
|
|
19469
19688
|
const token = opencodeServeRecords.newToken();
|
|
19470
|
-
const launch = opencodeServeLaunch(port, { env: { ...env, [SERVE_TOKEN_ENV]: token }, passwordFrom: 'stdout' });
|
|
19689
|
+
const launch = await opencodeServeLaunch(port, { env: { ...env, [SERVE_TOKEN_ENV]: token }, passwordFrom: 'stdout' });
|
|
19471
19690
|
const proc = spawn(launch.command, launch.args, { stdio: ['ignore', 'pipe', 'pipe'], ...launch.options, cwd, detached: false, shell: false, windowsHide: true });
|
|
19472
19691
|
editorCompletionServeTracks.set(proc, trackOpencodeServe(proc, { kind: 'completion', id: 'editor-complete', port, token, nativeWebSocketSafe: launch.nativeWebSocketSafe, nativeServe: launch.nativeServe }));
|
|
19473
19692
|
const outLog = createServeLogRedactor(line => console.log(`[editor-complete:out] ${line.trim().slice(0, 500)}`));
|
|
@@ -20171,7 +20390,7 @@ function moreLoginAutomationProfileCheck(req, envId) {
|
|
|
20171
20390
|
function refuseDefaultBrowserChange(res) {
|
|
20172
20391
|
return res.status(403).json({
|
|
20173
20392
|
ok: false, code: 'MORELOGIN_DEFAULT_OWNER_ONLY',
|
|
20174
|
-
error: 'The default AI browser (the default MoreLogin profile and the browser connect mode) is the owner\'s choice, made in SynaBun → Settings →
|
|
20393
|
+
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).',
|
|
20175
20394
|
});
|
|
20176
20395
|
}
|
|
20177
20396
|
/** Whether a write of the browser settings would change the default (connect mode or default profile) and its caller may not. */
|
|
@@ -20194,21 +20413,21 @@ function moreLoginGate(req, res, next) {
|
|
|
20194
20413
|
if (browserOwnerPageOnly(req)) return next();
|
|
20195
20414
|
if (caller.id && MORELOGIN_AUTOMATION_ROUTES.has(key)) {
|
|
20196
20415
|
if (MORELOGIN_VERIFIED_ROUTES.has(key) && caller.status !== 'verified') {
|
|
20197
|
-
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
|
|
20416
|
+
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).` });
|
|
20198
20417
|
}
|
|
20199
20418
|
// An id that holds a profile pin and was not proven by this request reaches no MoreLogin route (finding 2). A pin
|
|
20200
20419
|
// off the owner's list does not close these routes: the session needs status, list and `use` to go back.
|
|
20201
20420
|
const pinRefused = callerProfileRefusal(caller);
|
|
20202
20421
|
if (pinRefused && pinRefused.code === 'PROFILE_PIN_UNVERIFIED') return res.status(pinRefused.status).json({ ok: false, code: pinRefused.code, error: pinRefused.error });
|
|
20203
20422
|
if (MORELOGIN_RUN_ONLY_ROUTES.has(key) && isMcpSessionOwner(caller.id)) {
|
|
20204
|
-
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 →
|
|
20423
|
+
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).' });
|
|
20205
20424
|
}
|
|
20206
20425
|
return next();
|
|
20207
20426
|
}
|
|
20208
20427
|
let guest = false;
|
|
20209
20428
|
try { guest = !!isGuestRequest(req); } catch { guest = true; }
|
|
20210
20429
|
if (caller.id || guest) {
|
|
20211
|
-
return res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'This MoreLogin route is the owner\'s (SynaBun\'s page, Settings →
|
|
20430
|
+
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).' });
|
|
20212
20431
|
}
|
|
20213
20432
|
if (caller.automation) {
|
|
20214
20433
|
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.' });
|
|
@@ -20283,7 +20502,7 @@ app.delete('/api/morelogin/local-profiles/:id', async (req, res) => {
|
|
|
20283
20502
|
const id = String(req.params.id);
|
|
20284
20503
|
const cfg = loadBrowserConfig();
|
|
20285
20504
|
if (cfg.connectMode === 'morelogin' && String(cfg.moreloginEnvId || '') === id) {
|
|
20286
|
-
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 →
|
|
20505
|
+
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.' });
|
|
20287
20506
|
}
|
|
20288
20507
|
const removed = await moreLogin.deleteLocalProfile(id);
|
|
20289
20508
|
_moreLoginStartedBy.delete(id);
|
|
@@ -20316,6 +20535,13 @@ app.get('/api/morelogin/status', async (req, res) => {
|
|
|
20316
20535
|
defaultEnvId: cfg.moreloginEnvId || null,
|
|
20317
20536
|
// SynaBun's own local profiles (lib/local-profiles.js): `installed`, `running` and `profileCount` are MoreLogin's.
|
|
20318
20537
|
localProfileCount: moreLogin.localProfileCount(),
|
|
20538
|
+
// Profiles MoreLogin refused to start for its plan's daily limit, until its day resets (lib/morelogin-start-cooldown.js):
|
|
20539
|
+
// meanwhile SynaBun does not ask MoreLogin to start them. [{ envId, name, resetAt, resetLocal, since, apiCode }]
|
|
20540
|
+
startCooldowns: moreLoginStartCooldowns(),
|
|
20541
|
+
// Profiles closed outside SynaBun (lib/morelogin-outside-close.js): no automatic path starts them again until the
|
|
20542
|
+
// owner starts them, a new scheduled run fires, or MoreLogin's daily reset (`holdUntil`).
|
|
20543
|
+
// [{ envId, name, closedAt, closedLocal, holdUntil, holdUntilLocal, runs }] (the orphaned runs counted, not listed).
|
|
20544
|
+
closedOutside: moreLoginClosedOutside(),
|
|
20319
20545
|
// The profile the calling session's own browser tools work in (POST /api/morelogin/use, or the profile its run
|
|
20320
20546
|
// was launched with), when that is not the default.
|
|
20321
20547
|
// Only for a caller this request proved (finding 2): an id merely said learns nothing about a pin.
|
|
@@ -20386,12 +20612,14 @@ app.get('/api/morelogin/profiles', async (req, res) => {
|
|
|
20386
20612
|
// Each with the browser it runs (`browser`): "use as default" is not offered for a Firefox-type one.
|
|
20387
20613
|
// MoreLogin's profiles and SynaBun's local ones (`kind: 'local'`). With MoreLogin closed the local ones are still
|
|
20388
20614
|
// listed, and `moreloginError` says why MoreLogin's are missing.
|
|
20389
|
-
const rows = await moreLogin.listProfiles(_moreLoginOpts());
|
|
20615
|
+
const rows = await moreLogin.listProfiles({ ..._moreLoginOpts(), complete: true });
|
|
20390
20616
|
const listed = await withMoreLoginBrowsers(rows, _moreLoginOpts());
|
|
20617
|
+
rememberMoreLoginEnvNames(rows);
|
|
20391
20618
|
// `agentsMayChoose`: on the owner's list (the Settings toggle, and what the `morelogin` tool's "list" shows).
|
|
20392
20619
|
const allowed = moreLoginAgentProfiles();
|
|
20393
20620
|
res.json({
|
|
20394
20621
|
ok: true, envs: listed.envs.map((env) => ({ ...env, agentsMayChoose: allowed.some((row) => row.envId === String(env.id)) })), browsersPending: listed.browsersPending, agentProfiles: allowed,
|
|
20622
|
+
staleProfiles: rows.moreloginError ? [] : [...new Map([...allowed, ...(moreLoginDefaultEnvId(loadBrowserConfig()) ? [{ envId: String(moreLoginDefaultEnvId(loadBrowserConfig())) }] : [])].map(p => [p.envId, p])).values()].filter(p => !moreLogin.isLocalProfileId(p.envId) && !rows.some(e => String(e.id) === p.envId)),
|
|
20395
20623
|
local: { count: listed.envs.filter((env) => env.kind === 'local').length },
|
|
20396
20624
|
...(rows.moreloginError ? { moreloginError: rows.moreloginError.message } : {}),
|
|
20397
20625
|
});
|
|
@@ -20427,8 +20655,33 @@ app.post('/api/morelogin/start', async (req, res) => {
|
|
|
20427
20655
|
// Only that may end a running local profile to start it again (lib/local-profiles.js startNow); an automation
|
|
20428
20656
|
// gets LOCAL_PROFILE_RESTART_NEEDED / LOCAL_PROFILE_BUSY by name below, and no browser.
|
|
20429
20657
|
const who = browserCaller(req);
|
|
20430
|
-
|
|
20658
|
+
// A profile closed outside SynaBun (lib/morelogin-outside-close.js) is not started here for an automation (a run's
|
|
20659
|
+
// or an agent's morelogin "start") or anybody else; the owner's own Start lifts the mark (it starts the profile).
|
|
20660
|
+
const startOwner = who.automation && who.id ? browserOwnerId(who.id) : null;
|
|
20661
|
+
// A run whose own profile failed in this run does not start another one either (each start spends one of
|
|
20662
|
+
// MoreLogin's daily launches, and it may not move there: lib/morelogin-profile-failures.js). A start of the failed
|
|
20663
|
+
// profile itself is how it is fixed, and goes on. The owner's Start is never asked.
|
|
20664
|
+
const failedBar = startOwner ? runProfileSwitchRefusal(startOwner, { envId: String(envId), name: _moreLoginEnvNames.get(String(envId)) || null, resolved: true }, { action: 'start' }) : null;
|
|
20665
|
+
if (failedBar) return refuseProfileSwitchAfterFailure(res, failedBar);
|
|
20666
|
+
nativePreflightProfiles.add(String(envId));
|
|
20667
|
+
// The run's own profile (its pin, else the MoreLogin default) that fails to start here bars it from switching, as a
|
|
20668
|
+
// failed browser start does (acquireSharedBrowserTab).
|
|
20669
|
+
const ownProfile = startOwner ? runEffectiveProfile(startOwner) : null;
|
|
20670
|
+
let out;
|
|
20671
|
+
try {
|
|
20672
|
+
out = await moreLogin.startProfile(envId, { ..._moreLoginOpts(), owner: !who.automation && moreLoginOwnerPageCall(req),
|
|
20673
|
+
...(startOwner ? { refuseStart: moreLoginStartGuardFor(startOwner) } : {}), profileLabel: moreLoginProfileLabel });
|
|
20674
|
+
} catch (err) {
|
|
20675
|
+
if (ownProfile && ownProfile.envId === String(envId)) noteRunProfileFailure(startOwner, ownProfile, err);
|
|
20676
|
+
throw err;
|
|
20677
|
+
}
|
|
20678
|
+
// Running now: a close outside SynaBun is over. Started (by the owner, or by an automation the mark did not hold),
|
|
20679
|
+
// or found running by the owner. An automation that only found it running has not attached to it yet: its browser
|
|
20680
|
+
// call clears the mark when it attaches (a profile MoreLogin still lists while it closes must not lose it here).
|
|
20681
|
+
if (!out.alreadyRunning || !who.automation) { try { moreLogin.clearOutsideClose(String(envId)); } catch { /* nothing held */ } }
|
|
20431
20682
|
if (!who.automation) return res.json({ ok: true, ...out });
|
|
20683
|
+
// Already running (MoreLogin's status said so, nothing was started): the profile is not the caller's to stop.
|
|
20684
|
+
if (out.alreadyRunning) return res.json({ ok: true, started: false, alreadyRunning: true, envId: String(envId) });
|
|
20432
20685
|
// An automation's start: the profile is the caller's to stop later (POST /api/morelogin/stop), and the answer
|
|
20433
20686
|
// carries no CDP port (a raw debugging connection drives the profile's browser past every check SynaBun makes;
|
|
20434
20687
|
// SynaBun's browser tools reach the caller's own profile without it: POST /api/morelogin/use).
|
|
@@ -20440,7 +20693,8 @@ app.post('/api/morelogin/start', async (req, res) => {
|
|
|
20440
20693
|
}
|
|
20441
20694
|
res.json({ ok: true, started: true, envId: String(envId) });
|
|
20442
20695
|
} catch (err) {
|
|
20443
|
-
res.status(err.status || 500).json({ ok: false, error: err.message, ...(err.code ? { code: err.code } : {})
|
|
20696
|
+
res.status(err.status || 500).json({ ok: false, error: err.message, ...(err.code ? { code: err.code } : {}),
|
|
20697
|
+
...(err.needsUser ? { needsUser: true } : {}), ...(err.closedAt ? { closedAt: err.closedAt } : {}), ...(err.holdUntil ? { holdUntil: err.holdUntil } : {}) });
|
|
20444
20698
|
}
|
|
20445
20699
|
});
|
|
20446
20700
|
|
|
@@ -20459,7 +20713,7 @@ app.post('/api/morelogin/stop', async (req, res) => {
|
|
|
20459
20713
|
const decision = profileStopDecision(browserSessions, envId, caller, { startedBy: (id) => _moreLoginStartedBy.get(id) || [] });
|
|
20460
20714
|
if (decision.action === 'refuse' && decision.reason === 'not_owned') {
|
|
20461
20715
|
console.warn(`[morelogin] stop of env ${envId} by ${logOwnerId(caller)} refused: it holds nothing on that profile`);
|
|
20462
|
-
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
|
|
20716
|
+
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.` });
|
|
20463
20717
|
}
|
|
20464
20718
|
if (decision.action === 'refuse') {
|
|
20465
20719
|
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(', ')})`);
|
|
@@ -20468,6 +20722,8 @@ app.post('/api/morelogin/stop', async (req, res) => {
|
|
|
20468
20722
|
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.`,
|
|
20469
20723
|
});
|
|
20470
20724
|
}
|
|
20725
|
+
// SynaBun's own stop: the sessions in that profile see their browser go, and that is not a close by someone else.
|
|
20726
|
+
_moreLoginStoppedBySynaBun.set(String(envId), Date.now());
|
|
20471
20727
|
await moreLogin.stopProfile(envId, _moreLoginOpts());
|
|
20472
20728
|
_moreLoginStartedBy.delete(String(envId));
|
|
20473
20729
|
res.json({ ok: true });
|
|
@@ -20504,8 +20760,8 @@ app.post('/api/morelogin/use-default', async (req, res) => {
|
|
|
20504
20760
|
|
|
20505
20761
|
// ── A session's own MoreLogin profile (2026-11-10) ──
|
|
20506
20762
|
// POST /api/morelogin/use — the calling session works in a MoreLogin profile of its own from now on:
|
|
20507
|
-
// { envId }, { name } or { profile } (either; a profile MoreLogin lists), or { default: true } to go back to the default
|
|
20508
|
-
//
|
|
20763
|
+
// { envId }, { name } or { profile } (either; a profile MoreLogin lists), or { default: true } to go back to the default AI
|
|
20764
|
+
// browser (Settings → Connected tools → MoreLogin). The choice is the caller's pin (pinRunMoreLoginProfile, the pin a schedule's run is launched with), so its
|
|
20509
20765
|
// acquisitions, its recoveries, the per-request gate and its view of GET /api/browser/sessions all follow it. Nothing
|
|
20510
20766
|
// else changes: not the default AI browser, not another session's pin, tab or route. This is what an agent uses to
|
|
20511
20767
|
// work in a second profile while other automations work in the default one; use-default (which moves everybody) keeps
|
|
@@ -20516,11 +20772,17 @@ app.post('/api/morelogin/use-default', async (req, res) => {
|
|
|
20516
20772
|
// Chrome). A Firefox-type profile is refused (400 MORELOGIN_NOT_CHROMIUM) and the choice stays what it was.
|
|
20517
20773
|
// For a session that proves its id (moreLoginGate: a run's terminal token, a brain's credential, or a plain CLI MCP
|
|
20518
20774
|
// session's own proof, MCP_SESSION_PROOFS), never the owner's page (which has no session: the
|
|
20519
|
-
// owner picks in Settings →
|
|
20775
|
+
// owner picks in Settings → Connected tools → MoreLogin (Default AI browser) or where the run is set up).
|
|
20520
20776
|
const _profileChoiceStore = createProfileChoiceStore({
|
|
20521
20777
|
file: resolve(LOOP_DATA_DIR, 'browser-profile-choices.json'),
|
|
20522
20778
|
log: (line) => console.warn(`[morelogin] ${line}`),
|
|
20523
20779
|
});
|
|
20780
|
+
// A run whose own profile failed to start or connect in this run (lib/morelogin-profile-failures.js): it may not move to
|
|
20781
|
+
// another profile until that profile connects again for it, the owner moves it, or it ends (runProfileSwitchRefusal).
|
|
20782
|
+
const _runProfileFailures = createProfileFailureStore({
|
|
20783
|
+
file: resolve(LOOP_DATA_DIR, 'morelogin-profile-failures.json'),
|
|
20784
|
+
log: (line) => console.warn(`[morelogin] ${line}`),
|
|
20785
|
+
});
|
|
20524
20786
|
|
|
20525
20787
|
/**
|
|
20526
20788
|
* The owners of the saved choices are retired when the server starts (called once, as it starts listening, before any
|
|
@@ -20546,10 +20808,11 @@ function retireSavedProfileChoiceOwners() {
|
|
|
20546
20808
|
async function resolveMoreLoginProfileChoice(ref) {
|
|
20547
20809
|
let envs = [];
|
|
20548
20810
|
const unreachable = (reason) => Object.assign(new Error(`MoreLogin's profile list could not be read: ${reason}. Open the MoreLogin app (its Local API must be on).`), { status: 502, code: 'MORELOGIN_UNREACHABLE' });
|
|
20549
|
-
try { envs = await moreLogin.listProfiles(_moreLoginOpts()); } catch (err) { throw unreachable(err.message); }
|
|
20811
|
+
try { envs = await moreLogin.listProfiles({ ..._moreLoginOpts(), complete: true }); } catch (err) { throw unreachable(err.message); }
|
|
20550
20812
|
let found;
|
|
20551
20813
|
try { found = resolveProfileRef(ref, envs); } catch (err) {
|
|
20552
20814
|
if (envs.moreloginError && err?.code === 'ENV_NOT_FOUND') throw unreachable(envs.moreloginError.message);
|
|
20815
|
+
if (err?.code === 'ENV_NOT_FOUND' && !/^lp-[0-9a-f]{12}$/.test(String(ref?.envId || ''))) err.code = 'MORELOGIN_PROFILE_MISSING';
|
|
20553
20816
|
throw err;
|
|
20554
20817
|
}
|
|
20555
20818
|
await refuseFirefoxMoreLoginChoice({ moreloginEnvId: found.envId, moreloginEnvName: found.name });
|
|
@@ -20565,8 +20828,8 @@ async function resolveMoreLoginProfileChoice(ref) {
|
|
|
20565
20828
|
async function chooseSessionMoreLoginProfile(ownerKey, choice) {
|
|
20566
20829
|
const previous = runMoreLoginPin(ownerKey);
|
|
20567
20830
|
// 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
|
|
20568
|
-
// every use (moreLoginPinRefusal).
|
|
20569
|
-
pinRunMoreLoginProfile(ownerKey, choice?.envId || null, choice?.name || null, 'agent');
|
|
20831
|
+
// every use (moreLoginPinRefusal). Not locked: the session chose it, and may choose again.
|
|
20832
|
+
pinRunMoreLoginProfile(ownerKey, choice?.envId || null, choice?.name || null, 'agent', { locked: false });
|
|
20570
20833
|
// A plain MCP session's id dies with this server: its choice is never kept for a restart (MCP_SESSION_PROOFS).
|
|
20571
20834
|
if (!isMcpSessionOwner(ownerKey)) _profileChoiceStore.set(ownerKey, choice?.envId ? choice : null);
|
|
20572
20835
|
const cfg = loadBrowserConfig();
|
|
@@ -20587,28 +20850,62 @@ async function chooseSessionMoreLoginProfile(ownerKey, choice) {
|
|
|
20587
20850
|
return { previous, released };
|
|
20588
20851
|
}
|
|
20589
20852
|
|
|
20853
|
+
/**
|
|
20854
|
+
* 409 PROFILE_PINNED: `owner`'s profile was set up with the run (`pin.locked`), and it asked to move to `choice` (a
|
|
20855
|
+
* profile { envId, name }, or null for the default browser). Nothing changes.
|
|
20856
|
+
*/
|
|
20857
|
+
function refusePinnedProfileMove(res, owner, pin, choice) {
|
|
20858
|
+
const here = describeMoreLoginPin(pin);
|
|
20859
|
+
const there = choice?.envId ? describeMoreLoginPin(choice) : 'the default browser';
|
|
20860
|
+
console.warn(`[morelogin] ${logOwnerId(owner)} is pinned to ${here}: its move to ${there} was refused`);
|
|
20861
|
+
loopLog(owner, 'browser:profile', `refused: this run is pinned to ${here} and cannot move to ${there}`, { pinned: pin.envId, asked: choice?.envId || null });
|
|
20862
|
+
return res.status(409).json({
|
|
20863
|
+
ok: false, code: 'PROFILE_PINNED', envId: pin.envId, name: pin.name || null,
|
|
20864
|
+
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.`,
|
|
20865
|
+
});
|
|
20866
|
+
}
|
|
20867
|
+
|
|
20590
20868
|
app.post('/api/morelogin/use', async (req, res) => {
|
|
20591
20869
|
try {
|
|
20592
20870
|
const who = browserCaller(req);
|
|
20593
20871
|
if (!who.accepted) return refuseBrowserCaller(res, who);
|
|
20594
20872
|
const owner = who.automation ? browserOwnerId(who.id) : null;
|
|
20595
20873
|
if (!owner) {
|
|
20596
|
-
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 →
|
|
20874
|
+
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.' });
|
|
20597
20875
|
}
|
|
20598
20876
|
if (automationRunState(owner) === 'ended') {
|
|
20599
20877
|
return res.status(409).json({ ok: false, code: 'RUN_ENDED', error: `Run ${owner} has ended: its browser profile is not changed.` });
|
|
20600
20878
|
}
|
|
20601
20879
|
const body = req.body || {};
|
|
20602
20880
|
const toDefault = body.default === true || body.default === 'true';
|
|
20881
|
+
// A run whose own profile failed to start or connect in this run does not move to another profile or browser, even
|
|
20882
|
+
// 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
|
|
20883
|
+
// itself to P-1 and its next browser call started P-1, one of MoreLogin's daily launches). Refused here, before
|
|
20884
|
+
// MoreLogin is asked for anything; naming the failed profile itself is no move and goes on below. Lifted when that
|
|
20885
|
+
// profile connects again for the run, the owner moves the run, or it ends (lib/morelogin-profile-failures.js).
|
|
20886
|
+
const failedBar = runProfileSwitchRefusal(owner, toDefault ? { toDefault: true } : { envId: body.envId, name: body.name, profile: body.profile });
|
|
20887
|
+
if (failedBar) return refuseProfileSwitchAfterFailure(res, failedBar);
|
|
20888
|
+
// A run whose setup pinned its profile (a schedule, a group, a timer, a launch, a dispatch's morelogin_profile)
|
|
20889
|
+
// stays there: it is refused before anything is resolved or changed when it asks for the default browser, and
|
|
20890
|
+
// below when it names another profile (2026-11-15: a run on P-4 whose profile had gone moved itself to P-1, and
|
|
20891
|
+
// its recovery started P-1, one of MoreLogin's daily launches). A session that chose its profile itself may still
|
|
20892
|
+
// choose again (today's behaviour).
|
|
20893
|
+
const pinnedBefore = runMoreLoginPin(owner);
|
|
20894
|
+
if (pinnedBefore?.locked && toDefault) return refusePinnedProfileMove(res, owner, pinnedBefore, null);
|
|
20603
20895
|
// The owner's list (review b6631e9d, finding 1): a session works only in a profile the owner allowed agents to
|
|
20604
20896
|
// choose. Going back to the default needs no entry. Whoever calls this is never the owner's page (SESSION_REQUIRED
|
|
20605
20897
|
// above), so there is no exception here. The gate in front proved the caller's id (MORELOGIN_VERIFIED_ROUTES).
|
|
20606
20898
|
const choice = toDefault ? null : await agentMoreLoginProfileChoice({ envId: body.envId, name: body.name, profile: body.profile });
|
|
20899
|
+
// Asked again with what the name resolved to (a name the failed profile had may now be another profile's).
|
|
20900
|
+
const resolvedBar = choice ? runProfileSwitchRefusal(owner, { envId: choice.envId, name: choice.name, resolved: true }) : null;
|
|
20901
|
+
if (resolvedBar) return refuseProfileSwitchAfterFailure(res, resolvedBar);
|
|
20607
20902
|
const before = runMoreLoginPin(owner);
|
|
20608
|
-
|
|
20609
|
-
//
|
|
20903
|
+
if (before?.locked && (before.envId || null) !== (choice?.envId || null)) return refusePinnedProfileMove(res, owner, before, choice);
|
|
20904
|
+
// Asked again for what it already has: nothing is released (its tab there stays its tab), a pin the owner's
|
|
20905
|
+
// page set at launch stays the owner's (it is not rewritten as the session's own), and a pin its setup made stays
|
|
20906
|
+
// locked.
|
|
20610
20907
|
if ((before?.envId || null) === (choice?.envId || null)) {
|
|
20611
|
-
if (choice && before?.by !== 'owner') { pinRunMoreLoginProfile(owner, choice.envId, choice.name, 'agent'); if (!isMcpSessionOwner(owner)) _profileChoiceStore.set(owner, choice); }
|
|
20908
|
+
if (choice && before?.by !== 'owner' && !before?.locked) { pinRunMoreLoginProfile(owner, choice.envId, choice.name, 'agent', { locked: false }); if (!isMcpSessionOwner(owner)) _profileChoiceStore.set(owner, choice); }
|
|
20612
20909
|
return res.json({ ok: true, changed: false, envId: choice?.envId || null, name: choice?.name || null, default: !choice, released: [] });
|
|
20613
20910
|
}
|
|
20614
20911
|
const { previous, released } = await chooseSessionMoreLoginProfile(owner, choice);
|
|
@@ -21131,16 +21428,31 @@ function readClaudeSettingsForWrite(filePath) {
|
|
|
21131
21428
|
function writeClaudeSettings(filePath, data) {
|
|
21132
21429
|
const dir = dirname(filePath);
|
|
21133
21430
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
21431
|
+
// The settings file may be a link (dotfiles, a synced folder): the file behind it is the one written, and the
|
|
21432
|
+
// link stays. A rename over the link would leave a plain file here and the linked one as it was, so whatever
|
|
21433
|
+
// makes the link again later brings the old content back, without anything changed through SynaBun.
|
|
21434
|
+
let target = filePath;
|
|
21435
|
+
try { if (existsSync(filePath)) target = realpathSync(filePath); } catch { /* written where it was asked */ }
|
|
21134
21436
|
// Write atomically. A half-written settings.json (crash or full disk during
|
|
21135
21437
|
// writeFileSync) is what makes the corrupt-read path reachable to begin with.
|
|
21136
|
-
const tmpPath = `${
|
|
21438
|
+
const tmpPath = `${target}.tmp-${process.pid}`;
|
|
21439
|
+
// A file with other names (a named Claude account on Windows shares settings.json by a hard link,
|
|
21440
|
+
// lib/claude-account-links.js) is written in place: a rename would leave the other names the old file.
|
|
21441
|
+
let names = 1;
|
|
21442
|
+
try { names = Number(statSync(target).nlink) || 1; } catch {}
|
|
21137
21443
|
try {
|
|
21138
21444
|
writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf-8');
|
|
21139
|
-
renameSync(tmpPath,
|
|
21445
|
+
if (names > 1) { writeFileSync(target, readFileSync(tmpPath)); unlinkSync(tmpPath); } else renameSync(tmpPath, target);
|
|
21140
21446
|
} catch (err) {
|
|
21141
21447
|
try { if (existsSync(tmpPath)) unlinkSync(tmpPath); } catch {}
|
|
21142
21448
|
throw err;
|
|
21143
21449
|
}
|
|
21450
|
+
// The default's settings changed: every named account reads the same (a hard link that Claude Code's own
|
|
21451
|
+
// rename-write split, or a copy, is brought back in step). Never stops a write.
|
|
21452
|
+
try {
|
|
21453
|
+
const accounts = _panelClaudeAccounts();
|
|
21454
|
+
if ([getGlobalClaudeSettingsPath(), join(accounts.defaultHome, 'settings.json')].some((path) => resolve(path) === resolve(filePath))) accounts.syncShared();
|
|
21455
|
+
} catch {}
|
|
21144
21456
|
}
|
|
21145
21457
|
|
|
21146
21458
|
function isHookInstalled(settings, targetProjectPath) {
|
|
@@ -21517,11 +21829,51 @@ const SYNABUN_TOOL_CATEGORIES = [
|
|
|
21517
21829
|
},
|
|
21518
21830
|
];
|
|
21519
21831
|
|
|
21832
|
+
// ── The owner's tool-permission choices (lib/tool-permission-choices.js) ──
|
|
21833
|
+
// The switches of Settings → Tool permissions are drawn from, and change, the allow list of the user's
|
|
21834
|
+
// ~/.claude/settings.json: Claude Code's own file, which other things rewrite and replace. SynaBun keeps what the
|
|
21835
|
+
// owner chose in its data home too (DATA_HOME/data/tool-permissions.json, never touched by an install or an
|
|
21836
|
+
// update) and puts back what went missing: every saved tool at a start (an update is a start), and at a read
|
|
21837
|
+
// only when all of them are gone at once. A tool the owner switched off is never allowed by SynaBun itself; a
|
|
21838
|
+
// tool nobody chose (one that is new in an update) keeps the default: off until it is switched on.
|
|
21839
|
+
const TOOL_PERMISSION_KEYS = new Set(SYNABUN_TOOL_CATEGORIES.flatMap(cat => cat.tools.map(t => t.key)));
|
|
21840
|
+
const toolChoices = createToolPermissionChoices({
|
|
21841
|
+
path: resolve(DATA_HOME, 'data', TOOL_CHOICES_FILE),
|
|
21842
|
+
appVersion: SERVER_VERSION,
|
|
21843
|
+
log: (line) => console.log(line),
|
|
21844
|
+
});
|
|
21845
|
+
/** Bring the allow list in line with the saved choices. `reason`: 'start' | 'read'. Never throws. */
|
|
21846
|
+
function reconcileSavedToolPermissions(reason) {
|
|
21847
|
+
try {
|
|
21848
|
+
const result = reconcileToolPermissions({
|
|
21849
|
+
store: toolChoices, settingsPath: getGlobalClaudeSettingsPath(), known: TOOL_PERMISSION_KEYS, reason,
|
|
21850
|
+
read: readClaudeSettingsForWrite, write: writeClaudeSettings, log: (line) => console.log(line),
|
|
21851
|
+
});
|
|
21852
|
+
if (result.state === 'error' && reason === 'start') console.warn(`[tool-permissions] the saved choices were not applied: ${result.message}`);
|
|
21853
|
+
// Codex reads its own copy of the list (config.toml): it gets what was put back.
|
|
21854
|
+
if (result.state === 'restored') { try { syncCodexToolPermissions(result.allow); } catch { /* Codex's file is its own matter */ } }
|
|
21855
|
+
return result;
|
|
21856
|
+
} catch (err) {
|
|
21857
|
+
console.warn(`[tool-permissions] the saved choices were not applied: ${err.message}`);
|
|
21858
|
+
return { state: 'error', restored: [], adopted: [], allow: [], message: err.message };
|
|
21859
|
+
}
|
|
21860
|
+
}
|
|
21861
|
+
/** The on / off state of every tool, as the allow list has it. */
|
|
21862
|
+
function toolPermissionStates(allow) {
|
|
21863
|
+
const allowed = new Set(Array.isArray(allow) ? allow : []);
|
|
21864
|
+
const tools = {};
|
|
21865
|
+
for (const cat of SYNABUN_TOOL_CATEGORIES) {
|
|
21866
|
+
for (const t of cat.tools) tools[t.key] = allowed.has(t.key);
|
|
21867
|
+
}
|
|
21868
|
+
return tools;
|
|
21869
|
+
}
|
|
21870
|
+
|
|
21520
21871
|
// ── Memory-tool permission auto-injection ──
|
|
21521
|
-
// On MCP enable for any provider,
|
|
21872
|
+
// On MCP enable for any provider, allow the 7 SynaBun memory tools
|
|
21522
21873
|
// (recall/remember/reflect/forget/memories/restore/sync) so PTY/CLI sessions
|
|
21523
21874
|
// can use SynaBun memory without per-call permission prompts. Inject-only,
|
|
21524
|
-
// never overwrites existing entries
|
|
21875
|
+
// never overwrites existing entries, and never a tool the owner switched off
|
|
21876
|
+
// in Settings → Tool permissions. Falls back to project-scoped settings
|
|
21525
21877
|
// when the user has no global settings file.
|
|
21526
21878
|
function getMemoryToolKeys() {
|
|
21527
21879
|
const cat = SYNABUN_TOOL_CATEGORIES.find(c => c.id === 'memory');
|
|
@@ -21541,7 +21893,7 @@ function ensureOpenCodeCoreMcpPermissions(config) {
|
|
|
21541
21893
|
}
|
|
21542
21894
|
|
|
21543
21895
|
function injectClaudeMemoryPerms() {
|
|
21544
|
-
const keys = getMemoryToolKeys();
|
|
21896
|
+
const keys = getMemoryToolKeys().filter(k => !toolChoices.isOff(k));
|
|
21545
21897
|
const globalPath = getGlobalClaudeSettingsPath();
|
|
21546
21898
|
|
|
21547
21899
|
if (existsSync(globalPath)) {
|
|
@@ -21552,6 +21904,7 @@ function injectClaudeMemoryPerms() {
|
|
|
21552
21904
|
for (const k of keys) set.add(k);
|
|
21553
21905
|
settings.permissions.allow = [...set];
|
|
21554
21906
|
writeClaudeSettings(globalPath, settings);
|
|
21907
|
+
toolChoices.adopt(settings.permissions.allow, TOOL_PERMISSION_KEYS);
|
|
21555
21908
|
return { scope: 'global', paths: [globalPath] };
|
|
21556
21909
|
}
|
|
21557
21910
|
|
|
@@ -23507,19 +23860,20 @@ app.get('/api/claude-code/tool-categories', (req, res) => {
|
|
|
23507
23860
|
});
|
|
23508
23861
|
|
|
23509
23862
|
// GET /api/claude-code/tool-permissions — current permission state for all SynaBun tools
|
|
23863
|
+
// `capabilities`: what the PUT below takes beyond one tool or one category (`categories`: several groups in one
|
|
23864
|
+
// request), so a page that was reloaded before this server was restarted knows what it can ask.
|
|
23510
23865
|
app.get('/api/claude-code/tool-permissions', (req, res) => {
|
|
23511
23866
|
try {
|
|
23867
|
+
// A file that lost every saved tool at once was replaced: the saved choices go back before it is read.
|
|
23868
|
+
const reconciled = reconcileSavedToolPermissions('read');
|
|
23512
23869
|
const globalPath = getGlobalClaudeSettingsPath();
|
|
23513
23870
|
const settings = readClaudeSettings(globalPath) || {};
|
|
23514
|
-
|
|
23515
|
-
|
|
23516
|
-
|
|
23517
|
-
|
|
23518
|
-
|
|
23519
|
-
|
|
23520
|
-
}
|
|
23521
|
-
}
|
|
23522
|
-
res.json({ ok: true, tools });
|
|
23871
|
+
res.json({
|
|
23872
|
+
ok: true,
|
|
23873
|
+
tools: toolPermissionStates(settings.permissions?.allow),
|
|
23874
|
+
capabilities: ['categories'],
|
|
23875
|
+
...(reconciled.restored.length ? { restored: reconciled.restored.length } : {}),
|
|
23876
|
+
});
|
|
23523
23877
|
} catch (err) {
|
|
23524
23878
|
res.status(500).json({ error: err.message });
|
|
23525
23879
|
}
|
|
@@ -23604,30 +23958,48 @@ app.delete('/api/claude-code/permission-rules', express.json(), (req, res) => {
|
|
|
23604
23958
|
// The user scope of a tab under a named account is that account's file.
|
|
23605
23959
|
const accountHome = panelAccountHome(req.body?.account);
|
|
23606
23960
|
const result = removePermissionRule({ home: process.env.USERPROFILE || process.env.HOME, accountHome, project, scope, list, rule });
|
|
23961
|
+
// 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
|
|
23962
|
+
// choice from now on, so a start does not put it back (lib/tool-permission-choices.js).
|
|
23963
|
+
if (result.removed && scope === 'user' && list === 'allow' && TOOL_PERMISSION_KEYS.has(rule)
|
|
23964
|
+
&& (!accountHome || userSettingsFile({ home: process.env.USERPROFILE || process.env.HOME, accountHome }).shared)) {
|
|
23965
|
+
toolChoices.note([rule], false);
|
|
23966
|
+
}
|
|
23607
23967
|
res.json({ ok: true, removed: result.removed });
|
|
23608
23968
|
} catch (err) {
|
|
23609
23969
|
res.status(err?.status || 500).json({ ok: false, error: err.message, ...(err?.code ? { code: err.code } : {}) });
|
|
23610
23970
|
}
|
|
23611
23971
|
});
|
|
23612
23972
|
|
|
23613
|
-
// PUT /api/claude-code/tool-permissions — toggle
|
|
23973
|
+
// PUT /api/claude-code/tool-permissions — toggle one tool, one category group, or several groups at once
|
|
23974
|
+
// (`categories`: the switch in the section's header sends the groups it shows). What is switched is also
|
|
23975
|
+
// written down as the owner's choice (toolChoices), which is what a later start puts back.
|
|
23614
23976
|
app.put('/api/claude-code/tool-permissions', (req, res) => {
|
|
23615
23977
|
try {
|
|
23616
|
-
const { tool, category, enabled } = req.body;
|
|
23978
|
+
const { tool, category, categories, enabled } = req.body || {};
|
|
23617
23979
|
if (typeof enabled !== 'boolean') {
|
|
23618
23980
|
return res.status(400).json({ error: 'enabled (boolean) is required.' });
|
|
23619
23981
|
}
|
|
23620
|
-
if (
|
|
23621
|
-
return res.status(400).json({ error: '
|
|
23982
|
+
if (categories !== undefined && (!Array.isArray(categories) || !categories.length || categories.some(id => typeof id !== 'string'))) {
|
|
23983
|
+
return res.status(400).json({ error: 'categories must be a list of category ids.' });
|
|
23984
|
+
}
|
|
23985
|
+
if (!tool && !category && !categories) {
|
|
23986
|
+
return res.status(400).json({ error: 'Provide tool (string), category (string) or categories (list).' });
|
|
23622
23987
|
}
|
|
23623
23988
|
|
|
23624
23989
|
// Resolve which tool keys to toggle
|
|
23625
23990
|
let keys = [];
|
|
23626
|
-
if (
|
|
23991
|
+
if (categories) {
|
|
23992
|
+
for (const id of new Set(categories)) {
|
|
23993
|
+
const cat = SYNABUN_TOOL_CATEGORIES.find(c => c.id === id);
|
|
23994
|
+
if (!cat) return res.status(400).json({ error: `Unknown category: ${id}` });
|
|
23995
|
+
keys.push(...cat.tools.map(t => t.key));
|
|
23996
|
+
}
|
|
23997
|
+
} else if (category) {
|
|
23627
23998
|
const cat = SYNABUN_TOOL_CATEGORIES.find(c => c.id === category);
|
|
23628
23999
|
if (!cat) return res.status(400).json({ error: `Unknown category: ${category}` });
|
|
23629
24000
|
keys = cat.tools.map(t => t.key);
|
|
23630
24001
|
} else {
|
|
24002
|
+
if (typeof tool !== 'string') return res.status(400).json({ error: 'tool must be a string.' });
|
|
23631
24003
|
keys = [tool];
|
|
23632
24004
|
}
|
|
23633
24005
|
|
|
@@ -23644,6 +24016,8 @@ app.put('/api/claude-code/tool-permissions', (req, res) => {
|
|
|
23644
24016
|
}
|
|
23645
24017
|
settings.permissions.allow = [...allowSet];
|
|
23646
24018
|
writeClaudeSettings(globalPath, settings);
|
|
24019
|
+
// The owner's choice, in SynaBun's own data home: what an update, a restore or a replaced file cannot take.
|
|
24020
|
+
toolChoices.note(keys, enabled);
|
|
23647
24021
|
|
|
23648
24022
|
// Cascade to registered projects
|
|
23649
24023
|
const projects = loadHookProjects();
|
|
@@ -23667,14 +24041,7 @@ app.put('/api/claude-code/tool-permissions', (req, res) => {
|
|
|
23667
24041
|
syncCodexToolPermissions(settings.permissions.allow);
|
|
23668
24042
|
|
|
23669
24043
|
// Return updated state
|
|
23670
|
-
|
|
23671
|
-
const tools = {};
|
|
23672
|
-
for (const cat of SYNABUN_TOOL_CATEGORIES) {
|
|
23673
|
-
for (const t of cat.tools) {
|
|
23674
|
-
tools[t.key] = updatedAllowed.has(t.key);
|
|
23675
|
-
}
|
|
23676
|
-
}
|
|
23677
|
-
res.json({ ok: true, tools });
|
|
24044
|
+
res.json({ ok: true, tools: toolPermissionStates(settings.permissions.allow) });
|
|
23678
24045
|
} catch (err) {
|
|
23679
24046
|
res.status(500).json({ error: err.message });
|
|
23680
24047
|
}
|
|
@@ -23896,6 +24263,7 @@ function syncCodexToolPermissions(allowedKeys, codexHome = CODEX_DEFAULT_HOME) {
|
|
|
23896
24263
|
}
|
|
23897
24264
|
|
|
23898
24265
|
writeFileSync(configPath, content, 'utf-8');
|
|
24266
|
+
try { codexSharedFilesChanged(); } catch { /* never stops the write */ }
|
|
23899
24267
|
} catch (err) {
|
|
23900
24268
|
console.error('[codex-perm-sync] Failed to sync Codex tool permissions:', err.message);
|
|
23901
24269
|
}
|
|
@@ -24019,6 +24387,7 @@ app.post('/api/setup/codex/mcp', (req, res) => {
|
|
|
24019
24387
|
const health = upsertCodexMcpConfig(configPath, buildCodexMcpDefinition());
|
|
24020
24388
|
// Force-allow the 7 SynaBun memory tools so CLI sessions skip prompts.
|
|
24021
24389
|
injectCodexMemoryPerms();
|
|
24390
|
+
codexSharedFilesChanged();
|
|
24022
24391
|
res.json({ ok: true, ...health, message: 'SynaBun MCP registered in Codex CLI. Restart Codex to connect.', rules: syncRulesWithMcp('codex', 'install', req.body) });
|
|
24023
24392
|
} catch (err) {
|
|
24024
24393
|
res.status(500).json({ error: err.message });
|
|
@@ -24030,6 +24399,7 @@ app.delete('/api/setup/codex/mcp', (req, res) => {
|
|
|
24030
24399
|
const configPath = join(CODEX_DEFAULT_HOME, 'config.toml');
|
|
24031
24400
|
if (!existsSync(configPath)) return res.json({ ok: true, rules: syncRulesWithMcp('codex', 'remove') });
|
|
24032
24401
|
const health = removeCodexMcpConfig(configPath);
|
|
24402
|
+
codexSharedFilesChanged();
|
|
24033
24403
|
res.json({ ok: true, ...health, message: 'SynaBun MCP removed from Codex CLI.', rules: syncRulesWithMcp('codex', 'remove') });
|
|
24034
24404
|
} catch (err) {
|
|
24035
24405
|
res.status(500).json({ error: err.message });
|
|
@@ -24262,6 +24632,70 @@ registerSkillEvalRoutes(app, {
|
|
|
24262
24632
|
pageSession: _pageSession,
|
|
24263
24633
|
});
|
|
24264
24634
|
|
|
24635
|
+
// ════ agents-p1 BEGIN: the Agents system's registry, resolver and API (docs/agents.md, lib/coordination/README.md) ════
|
|
24636
|
+
// The one block of the Agents system's phase P1 in this file. The registry of agent definitions
|
|
24637
|
+
// (DATA_HOME/data/agents: one editable draft and immutable approved revisions per agent and scope, lib/agents/registry.js),
|
|
24638
|
+
// the resolver that turns a dispatch's `agent_ref` into a run (lib/agents/resolve.js: the dispatcher's intake and the
|
|
24639
|
+
// Assistant's /route ask the resolver of the process, which is set here, so nothing else in this file hands it over),
|
|
24640
|
+
// and the routes of Agents Studio under /api/agents-studio/v1 (lib/agents-studio-api.js: approving, deleting and test
|
|
24641
|
+
// runs are the owner's page only, as the Skills Service's installs are). The older /api/agents routes above (isolated
|
|
24642
|
+
// agent processes) are another thing and stay as they are.
|
|
24643
|
+
import { createAgentRegistry } from './lib/agents/registry.js';
|
|
24644
|
+
import { createAgentResolver, setAgentResolver } from './lib/agents/resolve.js';
|
|
24645
|
+
import { registerStudioAttention } from './lib/studio-attention.js';
|
|
24646
|
+
import { registerAgentsStudioRoutes } from './lib/agents-studio-api.js';
|
|
24647
|
+
const agentDefinitions = createAgentRegistry({
|
|
24648
|
+
dir: resolve(DATA_HOME, 'data', 'agents'),
|
|
24649
|
+
// Every page of the owner hears of a change; invite guests do not (broadcastSync keeps `assistant:` to the owner).
|
|
24650
|
+
emit: (event) => { try { broadcastSync({ type: 'assistant:agents-changed', event }); } catch { /* no page is listening */ } },
|
|
24651
|
+
});
|
|
24652
|
+
registerStudioAttention(app, {
|
|
24653
|
+
ownerPage: (req, res, next) => ownerPageApprovalCall(req) ? next() : refuseNotOwnerPage(req, res, 'The Studio attention indicator is available on the owner’s page.'),
|
|
24654
|
+
agents: () => agentDefinitions.list({ status: 'in_review' }),
|
|
24655
|
+
teams: () => _assistantTeamScheduler?.list({ open: true }) || [],
|
|
24656
|
+
reviews: () => skillReviews.list({ state: 'pending' }),
|
|
24657
|
+
// Only the marks and schedule state are used. No tool resolution or approval evidence is needed.
|
|
24658
|
+
templates: () => mergeLoopItemsById(readLoopTemplateFiles(), 'templates'),
|
|
24659
|
+
schedules: () => mergeLoopItemsById(readLoopScheduleFiles(), 'schedules'),
|
|
24660
|
+
workers: () => _assistantDispatcher?.hasRunAwaitingOwner() || false,
|
|
24661
|
+
nativeRuns: () => _nativeLoopRuntime?.list({ activeOnly: true }) || [],
|
|
24662
|
+
});
|
|
24663
|
+
const agentDefinitionResolver = setAgentResolver(createAgentResolver({ registry: agentDefinitions }));
|
|
24664
|
+
// ── agents-p6 BEGIN: what agent-forge and native export read from this server (lib/agents/forge-host.js) ──
|
|
24665
|
+
// The guide is the shipped skill skills/agent-forge; the catalog a definition is filled from is asked of the parts
|
|
24666
|
+
// that own it (the Assistant's model catalog, the tool catalog, the project's style guide, the MoreLogin profiles
|
|
24667
|
+
// the owner lets agents choose); a native export goes where Skills Studio's own agent files go (Claude Code's config
|
|
24668
|
+
// dir, OpenCode's configuration folder, or a registered project), and only the owner's page writes one.
|
|
24669
|
+
import { createAgentForgeHost } from './lib/agents/forge-host.js';
|
|
24670
|
+
const agentForgeHost = createAgentForgeHost({
|
|
24671
|
+
skillsDir: SKILLS_SOURCE_DIR,
|
|
24672
|
+
catalog: async ({ provider = null, q = null } = {}) => (_assistantCatalog ? _assistantCatalog.get({ view: 'brain', provider, q }) : null),
|
|
24673
|
+
styleGuide: (projectPath) => { const guide = styleGuideStore.load(projectPath); return guide?.saved ? guide.config : null; },
|
|
24674
|
+
moreloginProfiles: () => moreLoginAgentProfiles(),
|
|
24675
|
+
projects: () => { try { return loadHookProjects().filter((p) => p?.path).map((p) => ({ path: p.path, label: p.label || basename(p.path) })); } catch { return []; } },
|
|
24676
|
+
claudeHome: () => studioClaudeHome(),
|
|
24677
|
+
claudeHomes: () => { try { return _panelClaudeAccounts().list().map((row) => ({ id: row.id, home: row.home })); } catch { return []; } },
|
|
24678
|
+
opencodeConfigDir: () => getOpencodeConfigDir(),
|
|
24679
|
+
homeDir: getHomePath(),
|
|
24680
|
+
onExport: (event) => { try { broadcastSync({ type: 'assistant:agents-changed', event }); } catch { /* no page is listening */ } },
|
|
24681
|
+
});
|
|
24682
|
+
// ── agents-p6 END ──
|
|
24683
|
+
registerAgentsStudioRoutes(app, {
|
|
24684
|
+
registry: agentDefinitions, resolver: agentDefinitionResolver, isGuestRequest,
|
|
24685
|
+
forge: agentForgeHost, // agents-p6
|
|
24686
|
+
// The runs of an agent and the owner's test run (the dispatcher is made later, with the Assistant).
|
|
24687
|
+
dispatcher: () => _assistantDispatcher,
|
|
24688
|
+
ownerGuard: ownerRouteGuard({ isGuestRequest, port: PORT, allowedOrigins: publicWebOrigins, refuseCrossSite: true, ownOriginsOnly: true, requireOrigin: true }),
|
|
24689
|
+
// The owner's writes carry the page secret (lib/page-session.js): a local process without it is refused.
|
|
24690
|
+
pageSession: _pageSession,
|
|
24691
|
+
// An agent is the Assistant only by its brain's launch credential (never by X-Synabun-Role alone).
|
|
24692
|
+
assistantOf: (req) => skillsAssistantOf(req),
|
|
24693
|
+
// An agent's X-Synabun-Terminal (its author's name) counts only with its proof (browserCaller).
|
|
24694
|
+
terminalRefusal: (req) => { const who = browserCaller(req); return who.accepted ? null : { status: who.httpStatus || 403, code: who.code, error: who.error }; },
|
|
24695
|
+
projects: () => { try { return loadHookProjects().filter((p) => p?.path).map((p) => ({ path: p.path, label: p.label || basename(p.path) })); } catch { return []; } },
|
|
24696
|
+
});
|
|
24697
|
+
// ════ agents-p1 END ════
|
|
24698
|
+
|
|
24265
24699
|
/**
|
|
24266
24700
|
* Each runtime an evaluation can run on here: found (the same answer as drafting's), held to its folder, and whether
|
|
24267
24701
|
* a case that needs a shell can have one (Codex: its own sandbox, always, and Codex is the owner's opt-in per skill
|
|
@@ -24383,7 +24817,7 @@ function skillDraftingAvailability() {
|
|
|
24383
24817
|
return { available: !!any, reason: any ? null : (claude?.reason || 'No provider that can draft was found on this computer.'), providers };
|
|
24384
24818
|
}
|
|
24385
24819
|
|
|
24386
|
-
/** Whether the SynaBun browser (the
|
|
24820
|
+
/** 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. */
|
|
24387
24821
|
function skillBrowserAvailability() {
|
|
24388
24822
|
try {
|
|
24389
24823
|
const cfg = loadBrowserConfig();
|
|
@@ -24393,14 +24827,14 @@ function skillBrowserAvailability() {
|
|
|
24393
24827
|
// The default is one of SynaBun's own local profiles: MoreLogin is not needed for it.
|
|
24394
24828
|
return moreLogin.localProfileName(String(cfg.moreloginEnvId))
|
|
24395
24829
|
? { available: true, reason: null }
|
|
24396
|
-
: { available: false, reason: 'The default browser (Settings →
|
|
24830
|
+
: { available: false, reason: 'The default AI browser (Settings → Connected tools → MoreLogin) is a local profile that no longer exists: choose another one.' };
|
|
24397
24831
|
}
|
|
24398
24832
|
if (cfg.connectMode === 'morelogin') {
|
|
24399
24833
|
// The exe in a known folder, or the local API answered lately (an install in a custom folder). This is read
|
|
24400
24834
|
// synchronously, so a miss refreshes the answer in the background for the next call.
|
|
24401
24835
|
const installed = moreLogin.isMoreLoginPresent();
|
|
24402
24836
|
if (!installed) moreLogin.probeMoreLoginApi({ savedCfg: cfg, timeout: 1500 }).catch(() => {});
|
|
24403
|
-
return installed ? { available: true, reason: null } : { available: false, reason: 'MoreLogin is the default browser (Settings →
|
|
24837
|
+
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.' };
|
|
24404
24838
|
}
|
|
24405
24839
|
if ([...browserSessions.values()].some((s) => s?.context)) return { available: true, reason: null };
|
|
24406
24840
|
if (findBrowserExecutable(cfg.channel)) return { available: true, reason: null };
|
|
@@ -27718,7 +28152,9 @@ try {
|
|
|
27718
28152
|
if (sandboxSupported() && sandboxExecAvailable()) {
|
|
27719
28153
|
try {
|
|
27720
28154
|
// The channel's path token names the run; the channel adds that run's terminal token itself (never the worker's).
|
|
27721
|
-
_workerMcpChannel = createWorkerMcpChannel({ createMcpRoutes, mainPort: Number(PORT) || 3344, log: (line) => console.log(line), terminalToken: (runId) => _terminalTokens.tokenFor(runId), terminalAuth
|
|
28155
|
+
_workerMcpChannel = createWorkerMcpChannel({ createMcpRoutes, mainPort: Number(PORT) || 3344, log: (line) => console.log(line), terminalToken: (runId) => _terminalTokens.tokenFor(runId), terminalAuth,
|
|
28156
|
+
// A sandboxed OpenCode worker's Maritaca requests (its block points here: maritacaWorkerChannelProvider).
|
|
28157
|
+
maritaca: (req, res) => maritacaOpencodeProxy.handle(req, res, { channel: true }) });
|
|
27722
28158
|
_workerMcpChannel.start().catch((error) => { console.warn(' worker-only MCP channel did not start (guarded workers run without OS isolation):', error?.message || error); _workerMcpChannel = null; });
|
|
27723
28159
|
} catch (error) {
|
|
27724
28160
|
console.warn(' worker-only MCP channel unavailable:', error?.message || error);
|
|
@@ -28894,6 +29330,8 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
28894
29330
|
// data home — nothing in the sandbox opens the memory DB. The run's routing travels as headers.
|
|
28895
29331
|
const remoteMcp = iso?.profilePath && iso.mcpUrl ? {
|
|
28896
29332
|
url: iso.mcpUrl,
|
|
29333
|
+
// The run's channel base (…/w/<token>), for a Maritaca block (setupOpencodeLoopConfig) when the channel carries it.
|
|
29334
|
+
base: _workerMcpChannel?.carriesMaritaca?.() ? (iso.browserBase || null) : null,
|
|
28897
29335
|
headers: {
|
|
28898
29336
|
'X-Synabun-Browser-Session': state.browserSessionId || '',
|
|
28899
29337
|
'X-Synabun-Browser-Tab': state.browserTabId || '',
|
|
@@ -28926,6 +29364,9 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
28926
29364
|
// An evaluation trial with the skill: its copy goes into this run's own configuration folder, which OpenCode reads
|
|
28927
29365
|
// as its global one (never OPENCODE_CONFIG_DIR, which would take the place of this configuration).
|
|
28928
29366
|
if (evalEnv) openCodeEvalSkillFor(state, resolve(xdgRoot, 'opencode'));
|
|
29367
|
+
if (remoteMcp?.maritaca && !_workerMcpChannel?.allowMaritaca?.(state.runId)) {
|
|
29368
|
+
try { state.onNote?.('Maritaca through the worker channel could not be enabled for this run: its Sabiá models will not answer.'); } catch {}
|
|
29369
|
+
}
|
|
28929
29370
|
const entry = await ensureIsolatedServe(state.runId, {
|
|
28930
29371
|
xdgRoot,
|
|
28931
29372
|
keepAlive: true,
|
|
@@ -28970,6 +29411,48 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
28970
29411
|
},
|
|
28971
29412
|
});
|
|
28972
29413
|
|
|
29414
|
+
// What the computer-use service says about who holds the desktop now (its `status().control`), once it exists: read by
|
|
29415
|
+
// the evidence line of a MoreLogin profile closed outside SynaBun (lib/browser-close-evidence.js). null until then.
|
|
29416
|
+
let _desktopControlProbe = null;
|
|
29417
|
+
// MoreLogin profiles SynaBun itself stopped (POST /api/morelogin/stop): envId → when. A browser that goes within
|
|
29418
|
+
// a minute of that is not reported as closed outside SynaBun.
|
|
29419
|
+
const _moreLoginStoppedBySynaBun = new Map();
|
|
29420
|
+
|
|
29421
|
+
/**
|
|
29422
|
+
* A MoreLogin profile session's browser context closed (createBrowserSession's context 'close' handler): who closed
|
|
29423
|
+
* it, said once. Returns what it decided:
|
|
29424
|
+
* 'revoked' — SynaBun's OpenCode serve boundary let go of the context (lib/opencode-native-boundary.js
|
|
29425
|
+
* revokeNativeContext: the profile's window is kept). Never "outside SynaBun", never a mark.
|
|
29426
|
+
* 'synabun' — SynaBun closed it: its own teardown (destroyBrowserSession took the session out of the map first) or
|
|
29427
|
+
* POST /api/morelogin/stop in the last minute.
|
|
29428
|
+
* 'outside' — nobody in SynaBun: the evidence line (lib/browser-close-evidence.js), and the close is remembered for
|
|
29429
|
+
* the profile (lib/morelogin-outside-close.js): no automatic path starts it again (each start spends one
|
|
29430
|
+
* of MoreLogin's daily launches) until the owner starts it, a new scheduled run fires, or MoreLogin's
|
|
29431
|
+
* daily reset. The runs it orphaned are kept on the mark (their loops end after their turn).
|
|
29432
|
+
* null — not a MoreLogin profile (a local profile, another browser).
|
|
29433
|
+
* Before 2026-11-15 a revocation was reported as closed outside SynaBun: the 21:13:30 and 21:14:22 lines of that night
|
|
29434
|
+
* were SynaBun's own (a foreign OpenCode serve failed its check while it was exiting, and the revocation closed every
|
|
29435
|
+
* page of P-1 and P-4).
|
|
29436
|
+
*/
|
|
29437
|
+
function noteMoreLoginContextClose(session, sessionId, context = session?.context) {
|
|
29438
|
+
if (session?._profileMode !== 'morelogin' || !session._mlEnvId || moreLogin.isLocalProfileId(String(session._mlEnvId))) return null;
|
|
29439
|
+
const envId = String(session._mlEnvId);
|
|
29440
|
+
const revoked = nativeContextRevocation(context);
|
|
29441
|
+
if (revoked) {
|
|
29442
|
+
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`);
|
|
29443
|
+
return 'revoked';
|
|
29444
|
+
}
|
|
29445
|
+
if (browserSessions.get(sessionId) !== session || session._tearingDown
|
|
29446
|
+
|| Date.now() - (_moreLoginStoppedBySynaBun.get(envId) || 0) < 60_000) return 'synabun';
|
|
29447
|
+
const owners = [...(session._loopOwned || [])];
|
|
29448
|
+
logUnexpectedProfileClose({ envId, sessionId, desktopControl: () => _desktopControlProbe?.() || null }).catch(() => {});
|
|
29449
|
+
let mark = null;
|
|
29450
|
+
try { mark = moreLogin.noteOutsideClose(envId, { at: Date.now(), sessionId, owners, name: _moreLoginEnvNames.get(envId) || null }); }
|
|
29451
|
+
catch (err) { console.warn(`[morelogin] the close of profile ${envId} outside SynaBun was not remembered: ${err?.message || err}`); }
|
|
29452
|
+
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()}`);
|
|
29453
|
+
return 'outside';
|
|
29454
|
+
}
|
|
29455
|
+
|
|
28973
29456
|
// ── Main assistant: brains + orchestration (lib/assistant-*.js) ──
|
|
28974
29457
|
// Everything lives in lib/; this block only wires dependencies and mounts the
|
|
28975
29458
|
// router + WebSocket handler. Failure here degrades to "assistant unavailable"
|
|
@@ -29437,10 +29920,26 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29437
29920
|
log: (tag, message) => assistantLog(tag, message),
|
|
29438
29921
|
});
|
|
29439
29922
|
app.use('/api/desktop', createDesktopApi({ desktop: assistantDesktop, isGuestRequest, log: (tag, message) => assistantLog(tag, message) }));
|
|
29923
|
+
{ const desktop = assistantDesktop; _desktopControlProbe = () => desktop.status()?.control || null; }
|
|
29440
29924
|
} catch (err) {
|
|
29441
29925
|
console.warn('[assistant] computer use unavailable:', err.message);
|
|
29442
29926
|
assistantDesktop = null;
|
|
29443
29927
|
}
|
|
29928
|
+
// ══ Agents P2: durable agent messaging ═════════════════════════════════════════════════════════════════════
|
|
29929
|
+
// This server's one coordination store (DATA_HOME/data/coordination.db; lib/coordination/README.md): the run
|
|
29930
|
+
// events the dispatcher records, the Assistant's mailbox, the follow-up outbox. The dispatcher and the Assistant
|
|
29931
|
+
// runtime made right below take the shared service by themselves, so this block is the only place in this file
|
|
29932
|
+
// that creates it. runGracefulShutdown closes it after the scheduler and workers stop, including on signals;
|
|
29933
|
+
// an abrupt exit leaves the write-ahead log, which the next start reads back.
|
|
29934
|
+
{
|
|
29935
|
+
const { createCoordinationService, shareCoordinationService } = await import('./lib/coordination/service.js');
|
|
29936
|
+
const assistantCoordination = shareCoordinationService(createCoordinationService({ dataDir: LOOP_DATA_DIR, log: (tag, message) => assistantLog(tag, message) }));
|
|
29937
|
+
// The one instance of this server (never a second createCoordinationService in this file): a stop that is not
|
|
29938
|
+
// a signal (Restart Server, /api/server/shutdown, an update) closes it at the end of runGracefulShutdown.
|
|
29939
|
+
_assistantCoordination = assistantCoordination;
|
|
29940
|
+
if (assistantCoordination.degraded) console.warn(`[assistant] coordination store unavailable (${assistantCoordination.degraded.message}): agent events are kept in memory until the next start`);
|
|
29941
|
+
}
|
|
29942
|
+
// ══ end Agents P2 ══════════════════════════════════════════════════════════════════════════════════════════
|
|
29444
29943
|
_assistantDispatcher = createAssistantDispatcher({
|
|
29445
29944
|
resolveExternalTools: (spec, tools) => spec.provider
|
|
29446
29945
|
? selectExternalServers(tools, externalInventory(spec.provider, spec.cwd || PACKAGE_ROOT, { readProject: spec.provider !== 'opencode' || !openCodeProtectedWorker({ ...spec, cwd: spec.cwd || PACKAGE_ROOT, guardMode: _workerGuard.mode() }) }))
|
|
@@ -29470,8 +29969,13 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29470
29969
|
// Held to the owner's list of profiles agents may choose (agentMoreLoginProfileChoice: 403
|
|
29471
29970
|
// MORELOGIN_PROFILE_NOT_ALLOWED), whoever dispatches; the pin is an agent's, so the list is asked again when the
|
|
29472
29971
|
// worker's tab is acquired (a start, a resume) and at each of its browser calls.
|
|
29972
|
+
// pinBrowserProfile: a dispatch's morelogin_profile is the run's setup, locked (POST /api/morelogin/use refuses a
|
|
29973
|
+
// move). A resume re-pins the run's record, which a worker's own `use` rewrote (noteBrowserProfile): that one
|
|
29974
|
+
// stays the worker's own choice, as its saved choice says (_profileChoiceStore), and is not locked.
|
|
29473
29975
|
resolveBrowserProfile: (ref) => agentMoreLoginProfileChoice(ref),
|
|
29474
|
-
pinBrowserProfile: (runId, envId, name) => pinRunMoreLoginProfile(runId, envId, name, 'agent'
|
|
29976
|
+
pinBrowserProfile: (runId, envId, name) => pinRunMoreLoginProfile(runId, envId, name, 'agent', {
|
|
29977
|
+
locked: (() => { try { return String(_profileChoiceStore.get(runId)?.envId || '') !== String(envId || ''); } catch { return true; } })(),
|
|
29978
|
+
}),
|
|
29475
29979
|
memory: assistantMemory, detectProject: assistantDetectProject,
|
|
29476
29980
|
// Limits are read live from assistant-config.json `limits`; the money is the session budget (the planner).
|
|
29477
29981
|
limits: {},
|
|
@@ -29487,6 +29991,8 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29487
29991
|
clarifier: assistantClarifier,
|
|
29488
29992
|
// The session's Test density, read when a worker's prompt is composed (assistant-test-density.js).
|
|
29489
29993
|
testDensity: (sessionId) => _assistantRuntime?.testDensityFor?.(sessionId) ?? null,
|
|
29994
|
+
// agents-p4: the session's Agent density (lib/agents/density.js): the cap the team scheduler enforces.
|
|
29995
|
+
agentDensity: (sessionId) => _assistantRuntime?.agentDensityFor?.(sessionId) ?? null,
|
|
29490
29996
|
// After a restart, workers are resumed once this server listens and the worker-only MCP channel (a sandboxed
|
|
29491
29997
|
// worker's) is up or known to be off: a resumed CLI connects to SynaBun's MCP as it starts. 15 s at most.
|
|
29492
29998
|
serverReady: () => new Promise((resolveReady) => {
|
|
@@ -29546,6 +30052,57 @@ _nativeLoopRuntime = new NativeLoopRuntime({
|
|
|
29546
30052
|
// A brain's pin is proven by its launch credential (lib/terminal-tokens.js bind), revoked with the brain.
|
|
29547
30053
|
terminalTokens: _terminalTokens,
|
|
29548
30054
|
});
|
|
30055
|
+
// ════ agents-p4 BEGIN: the team scheduler (lib/teams/scheduler.js; docs/agents.md → Teams) ════
|
|
30056
|
+
// One task given to several workers, each in its own git worktree (lib/teams/, phase P3), within the session's
|
|
30057
|
+
// Agent density. The one scheduler of this server: it takes the coordination service's own store (claims, the
|
|
30058
|
+
// journal, the team channel and the run events are one file), dispatches through the Assistant's dispatcher and
|
|
30059
|
+
// is shared (shareTeamScheduler) for the Assistant's API (agent_team, a worker's team tool) and Agents Studio's
|
|
30060
|
+
// routes. The integration tests run under the worker sandbox where the platform has one (lib/teams/test-sandbox.js);
|
|
30061
|
+
// ignored node_modules folders are cloned into each worktree where the file system can (cloneNodeModules).
|
|
30062
|
+
// In its own try/catch: the Assistant runs without teams when this fails, and the team routes then answer 503.
|
|
30063
|
+
try {
|
|
30064
|
+
const { createTeams, createGitRunner, cloneNodeModules } = await import('./lib/teams/index.js');
|
|
30065
|
+
const { createTeamScheduler, shareTeamScheduler } = await import('./lib/teams/scheduler.js');
|
|
30066
|
+
const { createSandboxedTestRunner } = await import('./lib/teams/test-sandbox.js');
|
|
30067
|
+
const teamGit = createGitRunner();
|
|
30068
|
+
const teamScheduler = shareTeamScheduler(createTeamScheduler({
|
|
30069
|
+
teams: createTeams({
|
|
30070
|
+
store: _assistantCoordination.store, git: teamGit, setup: cloneNodeModules(),
|
|
30071
|
+
runTests: createSandboxedTestRunner({
|
|
30072
|
+
serverPort: () => Number(PORT) || null,
|
|
30073
|
+
reservedPortRange: () => ({ from: OCP_SHARED_PORT_MIN, to: OCP_ISO_PORT_MAX }),
|
|
30074
|
+
denyPaths: () => workerSecretTrees(),
|
|
30075
|
+
profileDir: resolve(LOOP_DATA_DIR, 'teams', 'sandbox'),
|
|
30076
|
+
log: (tag, message) => assistantLog(tag, message),
|
|
30077
|
+
}),
|
|
30078
|
+
log: (tag, detail) => assistantLog(tag, typeof detail === 'string' ? detail : JSON.stringify(detail)),
|
|
30079
|
+
}),
|
|
30080
|
+
coordination: _assistantCoordination,
|
|
30081
|
+
dispatcher: () => _assistantDispatcher,
|
|
30082
|
+
router: assistantRouter,
|
|
30083
|
+
// A remote conversation (WhatsApp) starts no team: one approved route covers one worker there.
|
|
30084
|
+
session: (sessionId) => ({ remote: !!_assistantRuntime?.sessionPolicy?.(sessionId), taskId: _assistantRuntime?.currentTask?.(sessionId) }),
|
|
30085
|
+
// 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.
|
|
30086
|
+
lastOwnerTurnAt: (sessionId) => _assistantRuntime?.lastOwnerTurnAt?.(sessionId) ?? null,
|
|
30087
|
+
git: teamGit,
|
|
30088
|
+
dataDir: LOOP_DATA_DIR,
|
|
30089
|
+
// Every team event, to the owner's pages (broadcastSync keeps `assistant:` messages to the owner).
|
|
30090
|
+
broadcast: (message) => { try { broadcastSync(message); } catch { /* no page is listening */ } },
|
|
30091
|
+
log: (tag, detail) => assistantLog(tag, typeof detail === 'string' ? detail : JSON.stringify(detail)),
|
|
30092
|
+
}));
|
|
30093
|
+
// The `team` tool is advertised to a run that works a team slice (mcp-server/src/services/team-context.ts):
|
|
30094
|
+
// this server's answer for a run id, asked by its own /mcp mount and the worker-only channel.
|
|
30095
|
+
import('../mcp-server/dist/services/team-context.js')
|
|
30096
|
+
.then((m) => m.setTeamContextResolver((runId) => !!teamScheduler.member(runId)))
|
|
30097
|
+
.catch((err) => console.warn('[assistant] team tool unavailable (mcp-server needs a build):', err?.message || err));
|
|
30098
|
+
// After a restart: the library's own recovery, then every team under way is taken up again. Never awaited here.
|
|
30099
|
+
teamScheduler.recover().catch((err) => console.warn('[assistant] team recovery failed:', err?.message || err))
|
|
30100
|
+
.finally(() => broadcastSync({ type: 'assistant:team-changed', event: 'recovered' }));
|
|
30101
|
+
_assistantTeamScheduler = teamScheduler;
|
|
30102
|
+
} catch (err) {
|
|
30103
|
+
console.warn('[assistant] teams unavailable:', err?.message || err);
|
|
30104
|
+
}
|
|
30105
|
+
// ════ agents-p4 END ════
|
|
29549
30106
|
assistantDesktop?.attach?.({ runtime: _assistantRuntime, dispatcher: _assistantDispatcher });
|
|
29550
30107
|
// Warm the catalog so brain capabilities (vision, tier) are known on first attach,
|
|
29551
30108
|
// then repair saved routes whose effort their model does not run (idempotent;
|
|
@@ -29671,6 +30228,10 @@ function setupOpencodeLoopConfig(terminalSessionId, browserSessionId, browserTab
|
|
|
29671
30228
|
const headers = {};
|
|
29672
30229
|
for (const [k, v] of Object.entries(remoteMcp.headers || {})) if (v) headers[k] = String(v);
|
|
29673
30230
|
setMcpServer(baseCfg, 'SynaBun', { type: 'remote', codemode: false, url: String(remoteMcp.url), ...(Object.keys(headers).length ? { headers } : {}) });
|
|
30231
|
+
// Maritaca's block reaches SynaBun's proxy on the control port with a key file in the data home: the sandbox
|
|
30232
|
+
// blocks both, and OpenCode retried a connection that never opened ("Transport: ECONNRESET"). The run's copy goes
|
|
30233
|
+
// through the same proxy on the worker channel; the launch then lets this run use that route (remoteMcp.maritaca).
|
|
30234
|
+
if (remoteMcp.base && maritacaWorkerChannelProvider(baseCfg, remoteMcp.base)) remoteMcp.maritaca = true;
|
|
29674
30235
|
} else {
|
|
29675
30236
|
const pinOverrides = {
|
|
29676
30237
|
SYNABUN_TERMINAL_SESSION: terminalSessionId,
|
|
@@ -32207,6 +32768,69 @@ app.post('/api/terminal/links/:id/nudge', (req, res) => {
|
|
|
32207
32768
|
// Exposes CDP endpoint so Claude Code's Playwright MCP can connect.
|
|
32208
32769
|
|
|
32209
32770
|
const browserSessions = new Map(); // sessionId → { browser, context, page, clients, cdpSession, screencastActive, ... }
|
|
32771
|
+
// The listener is lazy: the owner's pairing action opens its loopback port, and so does a pairing a previous process
|
|
32772
|
+
// stored (restore() below), so the extension reconnects by itself after a restart.
|
|
32773
|
+
const extensionUploadRoot = resolve(DATA_HOME, 'data/extension-uploads');
|
|
32774
|
+
// SynaBun's own ports, which no agent reaches through the owner's browser (docs/browser-extension-bridge.md): this
|
|
32775
|
+
// server and its launch beacon unless the owner lets the automation browser act as owner (Settings → Browser), and
|
|
32776
|
+
// always the browser-control ports (the CDP port, MoreLogin's local API) and SynaBun's live OpenCode serves.
|
|
32777
|
+
function extensionBlockedPorts() {
|
|
32778
|
+
const ports = new Set([CDP_PORT, ...moreLogin.MORELOGIN_FIXED_API_PORTS]);
|
|
32779
|
+
try { for (const p of liveOpencodeServePorts()) ports.add(Number(p)); } catch {}
|
|
32780
|
+
if (!_automationBrowserOwnerAccess.enabled()) { ports.add(Number(PORT) || 3344); ports.add(workerBeaconPort()); }
|
|
32781
|
+
return [...ports].filter(p => Number.isInteger(p) && p > 0 && p <= 65535);
|
|
32782
|
+
}
|
|
32783
|
+
// This computer's names and interface addresses: one of SynaBun's ports on any of them is SynaBun.
|
|
32784
|
+
function extensionSelfHosts() {
|
|
32785
|
+
const hosts = new Set(machineNames.names().flatMap(name => [name, `${name}.local`]));
|
|
32786
|
+
try { for (const list of Object.values(os.networkInterfaces())) for (const entry of list || []) if (entry?.address) hosts.add(entry.address.split('%')[0]); } catch {}
|
|
32787
|
+
return [...hosts];
|
|
32788
|
+
}
|
|
32789
|
+
const extensionBridge = createExtensionBridge({
|
|
32790
|
+
forbiddenOrigins: publicWebOrigins,
|
|
32791
|
+
blockedPorts: extensionBlockedPorts,
|
|
32792
|
+
selfHosts: extensionSelfHosts,
|
|
32793
|
+
// The pairing and the owner's mode, across restarts: outside data/ (no backup carries the credential), 0600.
|
|
32794
|
+
store: createBridgeStore(resolve(DATA_HOME, 'browser-extension', 'bridge.json')),
|
|
32795
|
+
log: record => console.log('[extension-bridge]', JSON.stringify(record)),
|
|
32796
|
+
onInventory: state => extensionAdapter.sync(state),
|
|
32797
|
+
});
|
|
32798
|
+
const extensionAdapter = createExtensionAdapter({
|
|
32799
|
+
bridge: extensionBridge, sessions: browserSessions, uploadRoot: extensionUploadRoot, dataHome: DATA_HOME,
|
|
32800
|
+
caller: browserCaller, ownerPage: browserOwnerPageOnly,
|
|
32801
|
+
selected: req => loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(browserCaller(req).id),
|
|
32802
|
+
});
|
|
32803
|
+
// The extension folder the owner loads (DATA_HOME/browser-extension/unpacked): refreshed at start when the bundled
|
|
32804
|
+
// extension changed and is not older (lib/browser-extension-folder.js). The browser then needs the extension's Reload,
|
|
32805
|
+
// which Settings and the setup page say (`reloadNeeded`). Never fatal: a folder that cannot be written is prepared
|
|
32806
|
+
// again by the one-button setup, which says so.
|
|
32807
|
+
const prepareOwnerExtensionFolder = () => prepareExtensionFolder({ source: EXTENSION_FOLDER, home: DATA_HOME, appPort: Number(PORT) || 3344 });
|
|
32808
|
+
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`); }
|
|
32809
|
+
catch (error) { console.warn(`[extension-bridge] extension folder not prepared (${error?.code || 'error'})`); }
|
|
32810
|
+
// The one-button setup (Settings → Browser → "Connect your browser"; docs/browser-extension-bridge.md → One-button
|
|
32811
|
+
// setup). Programs are started with execFile/spawn and argument arrays, never a shell; reads time out.
|
|
32812
|
+
const extensionSetup = createExtensionSetup({
|
|
32813
|
+
bridge: extensionBridge,
|
|
32814
|
+
detect: () => detectBrowsers({
|
|
32815
|
+
platform: process.platform, home: os.homedir(),
|
|
32816
|
+
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 }))),
|
|
32817
|
+
exists: path => { try { return existsSync(path); } catch { return false; } },
|
|
32818
|
+
list: dir => { try { return readdirSync(dir); } catch { return []; } },
|
|
32819
|
+
}),
|
|
32820
|
+
prepare: () => prepareOwnerExtensionFolder(),
|
|
32821
|
+
exec: (cmd, args) => new Promise((resolveExec, rejectExec) => {
|
|
32822
|
+
const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true, shell: false });
|
|
32823
|
+
child.once('error', rejectExec); child.once('spawn', () => { child.unref(); resolveExec(); });
|
|
32824
|
+
}),
|
|
32825
|
+
appOrigin: () => `http://127.0.0.1:${Number(PORT) || 3344}`,
|
|
32826
|
+
folderVersion: () => extensionFolderState(DATA_HOME).version,
|
|
32827
|
+
});
|
|
32828
|
+
{
|
|
32829
|
+
const restored = extensionBridge.restore();
|
|
32830
|
+
restored.listening?.then(
|
|
32831
|
+
port => console.log(`[extension-bridge] pairing restored; listening on 127.0.0.1:${port}`),
|
|
32832
|
+
error => console.warn(`[extension-bridge] pairing restored, but the bridge port could not open (${error?.code || 'error'})`));
|
|
32833
|
+
}
|
|
32210
32834
|
const BROWSER_GRACE_PERIOD_MS = 5 * 60 * 1000; // 5 min before orphaned browser is killed
|
|
32211
32835
|
|
|
32212
32836
|
/** Check if a browser session is actively used by a running automation loop or agent.
|
|
@@ -32238,7 +32862,7 @@ setInterval(() => {
|
|
|
32238
32862
|
for (const [id, session] of browserSessions) {
|
|
32239
32863
|
// Never reap an attach (CDP) session — it backs a live Chrome window the user is
|
|
32240
32864
|
// using; reaping would disconnect it and a later call would spawn a 2nd debug Chrome.
|
|
32241
|
-
if (
|
|
32865
|
+
if (['cdp', 'morelogin', 'extension'].includes(session._profileMode)) { session._idleSince = null; continue; }
|
|
32242
32866
|
const idle = (session.clients?.size || 0) === 0
|
|
32243
32867
|
&& sessionOwnerCount(session) === 0
|
|
32244
32868
|
&& !isSessionUsedByActiveLoop(id);
|
|
@@ -32302,8 +32926,11 @@ const RUN_MORELOGIN_SESSION_PINS_MAX = 200;
|
|
|
32302
32926
|
* `ownerKey` works in MoreLogin profile `envId` from now on, or (no envId) in the default browser by its own choice.
|
|
32303
32927
|
* Only for code that decided it: a launch, POST /api/morelogin/use after its checks, a dispatch. `by`: 'owner' when
|
|
32304
32928
|
* the owner's page chose the profile, else 'agent'. Throws 503 PROFILE_PINS_FULL in place of evicting another pin.
|
|
32929
|
+
* `locked` (the default): the run's setup chose the profile (a schedule, a group, a timer, a launch, an agent's
|
|
32930
|
+
* spawn, a dispatch's morelogin_profile), and the run cannot move to another one (POST /api/morelogin/use answers 409
|
|
32931
|
+
* PROFILE_PINNED, 2026-11-15). Only a session's own choice (`use`) is not locked: such a session may choose again.
|
|
32305
32932
|
*/
|
|
32306
|
-
function pinRunMoreLoginProfile(ownerKey, envId, name = null, by = 'agent') {
|
|
32933
|
+
function pinRunMoreLoginProfile(ownerKey, envId, name = null, by = 'agent', { locked = true } = {}) {
|
|
32307
32934
|
if (!ownerKey) return;
|
|
32308
32935
|
_runMoreLoginNoPin.delete(ownerKey);
|
|
32309
32936
|
if (!_runMoreLoginPins.has(ownerKey)) {
|
|
@@ -32313,7 +32940,7 @@ function pinRunMoreLoginProfile(ownerKey, envId, name = null, by = 'agent') {
|
|
|
32313
32940
|
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' });
|
|
32314
32941
|
}
|
|
32315
32942
|
}
|
|
32316
|
-
_runMoreLoginPins.set(ownerKey, envId ? { envId: String(envId), name: name ? String(name) : null, by: by === 'owner' ? 'owner' : 'agent' } : null);
|
|
32943
|
+
_runMoreLoginPins.set(ownerKey, envId ? { envId: String(envId), name: name ? String(name) : null, by: by === 'owner' ? 'owner' : 'agent', locked: locked !== false } : null);
|
|
32317
32944
|
}
|
|
32318
32945
|
|
|
32319
32946
|
/** `ownerKey` ended, or its launch failed: its pin and its saved choice are forgotten (nothing outlives its owner). */
|
|
@@ -32322,6 +32949,93 @@ function forgetRunMoreLoginProfile(ownerKey) {
|
|
|
32322
32949
|
_runMoreLoginPins.delete(ownerKey);
|
|
32323
32950
|
_runMoreLoginNoPin.delete(ownerKey);
|
|
32324
32951
|
_profileChoiceStore.delete(ownerKey);
|
|
32952
|
+
// A failure of its profile bars nothing once it has ended (lib/morelogin-profile-failures.js).
|
|
32953
|
+
_runProfileFailures.clear(ownerKey);
|
|
32954
|
+
}
|
|
32955
|
+
|
|
32956
|
+
// ── A run's own profile failed in this run: it does not move to another one (lib/morelogin-profile-failures.js) ──
|
|
32957
|
+
// Noted where a run's start or connection fails (acquireSharedBrowserTab, an automation's POST /api/browser/sessions,
|
|
32958
|
+
// its own POST /api/morelogin/start of its profile); asked by POST /api/morelogin/use and an automation's POST
|
|
32959
|
+
// /api/morelogin/start of another profile (409 PROFILE_FAILED_NO_SWITCH). Lifted by a connection of the run to that
|
|
32960
|
+
// profile again (noteRunProfileConnected), by the owner moving the run (its effective profile changed: `lifted`), or by
|
|
32961
|
+
// the run's end (forgetRunMoreLoginProfile).
|
|
32962
|
+
/**
|
|
32963
|
+
* The profile `ownerKey` works in now ({ envId, name, pinned }): its pin, else the MoreLogin (or local) profile that is
|
|
32964
|
+
* the default AI browser (Settings → Connected tools → MoreLogin); null when that default is no profile (Chrome, the
|
|
32965
|
+
* mirror, the extension).
|
|
32966
|
+
*/
|
|
32967
|
+
function runEffectiveProfile(ownerKey, cfg = loadBrowserConfig()) {
|
|
32968
|
+
const pin = runMoreLoginPin(ownerKey);
|
|
32969
|
+
if (pin?.envId) return { envId: String(pin.envId), name: pin.name || null, pinned: true };
|
|
32970
|
+
const defaultEnv = cfg?.connectMode === 'morelogin' ? moreLoginDefaultEnvId(cfg) : null;
|
|
32971
|
+
return defaultEnv ? { envId: String(defaultEnv), name: _moreLoginEnvNames.get(String(defaultEnv)) || null, pinned: false } : null;
|
|
32972
|
+
}
|
|
32973
|
+
|
|
32974
|
+
/**
|
|
32975
|
+
* `ownerKey`'s own profile (`profile`: { envId, name }) failed to start or connect in this run (`failure`: what the
|
|
32976
|
+
* start answered, { code, error } or an Error). From now on the run may not move to another profile. Never throws.
|
|
32977
|
+
*/
|
|
32978
|
+
function noteRunProfileFailure(ownerKey, profile, failure) {
|
|
32979
|
+
if (!ownerKey || !profile?.envId) return null;
|
|
32980
|
+
try {
|
|
32981
|
+
const entry = _runProfileFailures.note(ownerKey, {
|
|
32982
|
+
envId: String(profile.envId), name: profile.name || _moreLoginEnvNames.get(String(profile.envId)) || null,
|
|
32983
|
+
code: failure?.code || null, reason: failure?.error || failure?.message || null,
|
|
32984
|
+
});
|
|
32985
|
+
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`);
|
|
32986
|
+
return entry;
|
|
32987
|
+
} catch { return null; }
|
|
32988
|
+
}
|
|
32989
|
+
|
|
32990
|
+
/** `ownerKey` is connected to profile `envId`: a failure noted for that profile in this run is over. Never throws. */
|
|
32991
|
+
function noteRunProfileConnected(ownerKey, envId) {
|
|
32992
|
+
if (!ownerKey || !envId) return null;
|
|
32993
|
+
try {
|
|
32994
|
+
const dropped = _runProfileFailures.clear(ownerKey, { envId: String(envId) });
|
|
32995
|
+
if (dropped) console.log(`[morelogin] ${logOwnerId(ownerKey)}: ${describeProfile(dropped.envId, dropped.name)} connects again in this run: it may switch profiles again`);
|
|
32996
|
+
return dropped;
|
|
32997
|
+
} catch { return null; }
|
|
32998
|
+
}
|
|
32999
|
+
|
|
33000
|
+
/**
|
|
33001
|
+
* Why `ownerKey` may not switch now, or null. `target`: `{ toDefault: true }` (back to the default AI browser,
|
|
33002
|
+
* Settings → Connected tools → MoreLogin), or the profile it names ({ envId, name, profile }, resolved or as a request said it). `action`: 'use' (a
|
|
33003
|
+
* move, POST /api/morelogin/use) or 'start' (an automation's start of a profile). → an Error with code
|
|
33004
|
+
* PROFILE_FAILED_NO_SWITCH, status 409 (refuseProfileSwitchAfterFailure answers it). A failure of a profile the run no
|
|
33005
|
+
* longer works in (the owner moved it) is dropped here; naming the failed profile itself is no move.
|
|
33006
|
+
*/
|
|
33007
|
+
function runProfileSwitchRefusal(ownerKey, target = {}, { action = 'use', cfg = loadBrowserConfig() } = {}) {
|
|
33008
|
+
let failure = null;
|
|
33009
|
+
try { failure = _runProfileFailures.get(ownerKey); } catch { failure = null; }
|
|
33010
|
+
if (!failure) return null;
|
|
33011
|
+
const defaultEnv = cfg?.connectMode === 'morelogin' ? moreLoginDefaultEnvId(cfg) : null;
|
|
33012
|
+
// A resolved profile is compared by its id alone; a request's words by id or name (namesFailedProfile).
|
|
33013
|
+
const sameTarget = target?.toDefault ? String(defaultEnv || '') === failure.envId
|
|
33014
|
+
: target?.resolved ? String(target.envId || '') === failure.envId : namesFailedProfile(target, failure);
|
|
33015
|
+
const decision = profileSwitchDecision({ failure, current: runEffectiveProfile(ownerKey, cfg)?.envId || null, sameTarget });
|
|
33016
|
+
if (decision === 'lifted') {
|
|
33017
|
+
_runProfileFailures.clear(ownerKey, { envId: failure.envId });
|
|
33018
|
+
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`);
|
|
33019
|
+
return null;
|
|
33020
|
+
}
|
|
33021
|
+
if (decision !== 'barred') return null;
|
|
33022
|
+
const named = target?.toDefault
|
|
33023
|
+
? (defaultEnv ? `the default browser, ${describeProfile(String(defaultEnv), _moreLoginEnvNames.get(String(defaultEnv)) || null)}` : 'the default browser')
|
|
33024
|
+
: target?.envId ? describeProfile(String(target.envId), target.name || _moreLoginEnvNames.get(String(target.envId)) || null)
|
|
33025
|
+
: (target?.name || target?.profile) ? `the profile "${String(target.name || target.profile).slice(0, 64)}"` : 'another profile';
|
|
33026
|
+
const err = profileSwitchBarError(failure, { label: describeProfile(failure.envId, failure.name), targetLabel: named, action });
|
|
33027
|
+
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'})`);
|
|
33028
|
+
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) });
|
|
33029
|
+
return err;
|
|
33030
|
+
}
|
|
33031
|
+
|
|
33032
|
+
/** 409 PROFILE_FAILED_NO_SWITCH: the answer of a refusal from runProfileSwitchRefusal. Nothing was changed or started. */
|
|
33033
|
+
function refuseProfileSwitchAfterFailure(res, err) {
|
|
33034
|
+
return res.status(err.status || 409).json({
|
|
33035
|
+
ok: false, code: err.code, envId: err.envId, needsUser: true,
|
|
33036
|
+
...(err.failedAt ? { failedAt: err.failedAt } : {}), ...(err.failedCode ? { failedCode: err.failedCode } : {}),
|
|
33037
|
+
error: err.message,
|
|
33038
|
+
});
|
|
32325
33039
|
}
|
|
32326
33040
|
|
|
32327
33041
|
/**
|
|
@@ -32340,12 +33054,14 @@ function runMoreLoginPin(ownerKey) {
|
|
|
32340
33054
|
const chosen = _profileChoiceStore.get(ownerKey);
|
|
32341
33055
|
if (chosen !== undefined) {
|
|
32342
33056
|
decided = true;
|
|
32343
|
-
|
|
33057
|
+
// The session's own choice (`use`): it may choose again.
|
|
33058
|
+
pin = chosen.envId ? { envId: String(chosen.envId), name: chosen.name || null, by: 'agent', locked: false } : null;
|
|
32344
33059
|
} else {
|
|
32345
33060
|
const loopFile = findLoopFileForTerminal(ownerKey);
|
|
32346
33061
|
if (loopFile) {
|
|
32347
33062
|
const data = JSON.parse(readFileSync(resolve(LOOP_DIR, loopFile), 'utf-8'));
|
|
32348
|
-
|
|
33063
|
+
// The run was launched with this profile (its schedule, group, timer or launch): it stays there.
|
|
33064
|
+
if (data.moreloginEnvId) pin = { envId: String(data.moreloginEnvId), name: data.moreloginEnvName ? String(data.moreloginEnvName) : null, by: data.moreloginEnvBy === 'owner' ? 'owner' : 'agent', locked: true };
|
|
32349
33065
|
}
|
|
32350
33066
|
}
|
|
32351
33067
|
} catch { /* no pin */ }
|
|
@@ -32359,6 +33075,34 @@ function runMoreLoginPin(ownerKey) {
|
|
|
32359
33075
|
return pin;
|
|
32360
33076
|
}
|
|
32361
33077
|
|
|
33078
|
+
// MoreLogin profile names last read from its list (GET /api/browser/morelogin-envs, /api/morelogin/profiles): what the
|
|
33079
|
+
// start cooldowns are called by. id → name, bounded.
|
|
33080
|
+
const _moreLoginEnvNames = new Map();
|
|
33081
|
+
function rememberMoreLoginEnvNames(envs) {
|
|
33082
|
+
for (const env of envs || []) {
|
|
33083
|
+
if (env?.id == null || !env.name || env.kind === 'local') continue;
|
|
33084
|
+
_moreLoginEnvNames.delete(String(env.id));
|
|
33085
|
+
_moreLoginEnvNames.set(String(env.id), String(env.name));
|
|
33086
|
+
}
|
|
33087
|
+
while (_moreLoginEnvNames.size > 500) _moreLoginEnvNames.delete(_moreLoginEnvNames.keys().next().value);
|
|
33088
|
+
}
|
|
33089
|
+
/**
|
|
33090
|
+
* The profiles MoreLogin refused to start for its plan's daily limit, held until its day resets
|
|
33091
|
+
* (lib/morelogin-start-cooldown.js): [{ envId, name, since, resetAt, resetLocal, apiCode }]. Never throws.
|
|
33092
|
+
*/
|
|
33093
|
+
function moreLoginStartCooldowns(envs = null) {
|
|
33094
|
+
let list = [];
|
|
33095
|
+
try { list = moreLogin.listStartCooldowns(); } catch { return []; }
|
|
33096
|
+
if (!list.length) return [];
|
|
33097
|
+
if (envs) rememberMoreLoginEnvNames(envs);
|
|
33098
|
+
const names = new Map(_moreLoginEnvNames);
|
|
33099
|
+
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 */ }
|
|
33100
|
+
return list.map((c) => ({
|
|
33101
|
+
envId: c.envId, name: names.get(c.envId) || null,
|
|
33102
|
+
since: c.since ? new Date(c.since).toISOString() : null, resetAt: c.resetAt, resetLocal: c.resetLocal, apiCode: c.apiCode ?? null,
|
|
33103
|
+
}));
|
|
33104
|
+
}
|
|
33105
|
+
|
|
32362
33106
|
function describeMoreLoginPin(pin) {
|
|
32363
33107
|
if (!pin) return 'the default browser';
|
|
32364
33108
|
// `MoreLogin profile "X" (id)`, or `local profile "X" (id)` for one of SynaBun's own (lib/local-profiles.js).
|
|
@@ -32410,6 +33154,7 @@ function sessionServesRun(session, cfg, ownerKey) {
|
|
|
32410
33154
|
// 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
|
|
32411
33155
|
// profile's, and never the default browser's.
|
|
32412
33156
|
if (pin) return !pinUseRefusal(pin, cfg) && sessionServesMoreLoginEnv(session, pin.envId);
|
|
33157
|
+
if (cfg.connectMode === 'extension' || session?._profileMode === 'extension') return cfg.connectMode === 'extension' && session?._profileMode === 'extension';
|
|
32413
33158
|
return cfg.connectMode !== 'morelogin' || sessionServesMoreLoginDefault(session, cfg);
|
|
32414
33159
|
}
|
|
32415
33160
|
|
|
@@ -32435,6 +33180,10 @@ async function findReusableBrowserSession(opts = {}) {
|
|
|
32435
33180
|
const normalize = (p) => (p || '').replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
|
|
32436
33181
|
const selectedNorm = normalize(selectedPath);
|
|
32437
33182
|
for (const [id, session] of browserSessions) {
|
|
33183
|
+
if (session._profileMode === 'extension' || cfg.connectMode === 'extension' && !moreloginEnvId) {
|
|
33184
|
+
if (session._profileMode === 'extension' && cfg.connectMode === 'extension' && extensionBridge.status().connected && !moreloginEnvId) return { id, session };
|
|
33185
|
+
continue;
|
|
33186
|
+
}
|
|
32438
33187
|
if (excludeAgentOwned && session._agentOwnedSet?.size > 0) continue;
|
|
32439
33188
|
if (excludeLoopOwned && session._loopOwned?.size > 0) continue;
|
|
32440
33189
|
// Belt-and-suspenders: also check agent registry in case the ownership set
|
|
@@ -32568,10 +33317,15 @@ function loopBrowserLockKey(ownerKey, requestedBrowserSessionId, cfg) {
|
|
|
32568
33317
|
*
|
|
32569
33318
|
* Returns { browserSessionId, browserTabId } on success, or { error } on failure.
|
|
32570
33319
|
*/
|
|
32571
|
-
async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser' }) {
|
|
33320
|
+
async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false }) {
|
|
33321
|
+
if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(ownerKey)) {
|
|
33322
|
+
// takeOverTab: one of the owner's open tabs in the everyday browser (full control), named by browser_session create.
|
|
33323
|
+
try { return await extensionAdapter.acquire(ownerKey, ownerType, { adopt: takeOverTab || undefined }); }
|
|
33324
|
+
catch (error) { return extensionSafeError(error); }
|
|
33325
|
+
}
|
|
32572
33326
|
const lockKey = loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig());
|
|
32573
33327
|
const acquired = await withLoopBrowserLock(lockKey, async () => {
|
|
32574
|
-
// The browser this owner gets changed while it waited (
|
|
33328
|
+
// The browser this owner gets changed while it waited (the owner's settings, a requested session that went away):
|
|
32575
33329
|
// it queues again for the right one, outside this turn.
|
|
32576
33330
|
if (loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig()) !== lockKey) return { requeue: true };
|
|
32577
33331
|
let browserSessionId = null;
|
|
@@ -32640,9 +33394,14 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
32640
33394
|
let createError = null;
|
|
32641
33395
|
if (!browserSessionId) {
|
|
32642
33396
|
try {
|
|
33397
|
+
// The start guard: a profile closed outside SynaBun is not started again by this acquisition (an attach to the
|
|
33398
|
+
// profile running again is always allowed). Only a new scheduled firing's launch may start it
|
|
33399
|
+
// (`scheduledFiring`, the schedule:browser acquisition; never a recovery or a create of a run under way).
|
|
33400
|
+
const moreloginStartGuard = moreLoginStartGuardFor(ownerKey, pin, { scheduled: scheduledFiring === true });
|
|
33401
|
+
const moreloginAfterOutsideClose = scheduledFiring === true ? 'schedule' : null;
|
|
32643
33402
|
const result = await createBrowserSession(pin
|
|
32644
|
-
? { url: 'about:blank', connectMode: 'morelogin', moreloginEnvId: pin.envId, _mlPinned: true }
|
|
32645
|
-
: { url: 'about:blank' });
|
|
33403
|
+
? { url: 'about:blank', connectMode: 'morelogin', moreloginEnvId: pin.envId, _mlPinned: true, moreloginStartGuard, moreloginAfterOutsideClose }
|
|
33404
|
+
: { url: 'about:blank', moreloginStartGuard, moreloginAfterOutsideClose });
|
|
32646
33405
|
browserSessionId = result.sessionId;
|
|
32647
33406
|
loopLog(ownerKey, logTag, 'strategy 2: created shared browser session', {
|
|
32648
33407
|
browserSessionId, profileMode: result.profileMode, profileSource: result.profileSource,
|
|
@@ -32659,6 +33418,19 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
32659
33418
|
}
|
|
32660
33419
|
|
|
32661
33420
|
if (!browserSessionId) {
|
|
33421
|
+
// The run's own profile (its pin, else the MoreLogin default) failed to start or connect in this run: from now on
|
|
33422
|
+
// it may not move to another profile (POST /api/morelogin/use answers 409 PROFILE_FAILED_NO_SWITCH) until that
|
|
33423
|
+
// profile connects again for it (below), the owner moves it, or it ends (lib/morelogin-profile-failures.js).
|
|
33424
|
+
if (createError) {
|
|
33425
|
+
const own = pin || (moreLoginDefault && moreLoginDefaultEnvId(policyCfg) ? { envId: String(moreLoginDefaultEnvId(policyCfg)), name: null } : null);
|
|
33426
|
+
noteRunProfileFailure(ownerKey, own, createError);
|
|
33427
|
+
}
|
|
33428
|
+
// The profile was closed outside SynaBun: the sentence says it all (which profile, when, that SynaBun does not
|
|
33429
|
+
// reopen it, how to go on); no "could not start" around it.
|
|
33430
|
+
if (createError?.code === 'MORELOGIN_CLOSED_OUTSIDE') {
|
|
33431
|
+
loopLog(ownerKey, logTag, 'BLOCKED: the MoreLogin profile was closed outside SynaBun; SynaBun does not reopen it', { closedAt: createError.closedAt || null, holdUntil: createError.holdUntil || null });
|
|
33432
|
+
return { error: createError.error, code: createError.code, needsUser: true, blocked: true, ...(createError.closedAt ? { closedAt: createError.closedAt } : {}), ...(createError.holdUntil ? { holdUntil: createError.holdUntil } : {}) };
|
|
33433
|
+
}
|
|
32662
33434
|
// Carry the real reason (e.g. "MoreLogin connect failed: … unreachable") into the
|
|
32663
33435
|
// run's log, lastRunResult and the schedule:failed toast.
|
|
32664
33436
|
return {
|
|
@@ -32667,11 +33439,17 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
32667
33439
|
? `Could not start ${describeMoreLoginPin(pin)} for this run${createError ? `: ${createError.error}` : '.'} The run was not started in another profile or browser: ${
|
|
32668
33440
|
createError?.code === 'MORELOGIN_NOT_CHROMIUM' || createError?.code === 'MORELOGIN_NOT_DEVTOOLS'
|
|
32669
33441
|
? 'pick a Chrome-type profile where this run is set up.'
|
|
33442
|
+
: createError?.code === 'MORELOGIN_START_REFUSED'
|
|
33443
|
+
? `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'}.`
|
|
33444
|
+
: createError?.code === 'MORELOGIN_PROFILE_WINDOWLESS'
|
|
33445
|
+
? 'this needs the user, not a retry: open the profile\'s window again in MoreLogin (or close it fully there and start it again).'
|
|
32670
33446
|
: 'check that MoreLogin is open and that the profile still exists, or pick another profile where this run is set up.'}`
|
|
32671
33447
|
: createError
|
|
32672
33448
|
? `Could not start the shared browser session: ${createError.error}`
|
|
32673
33449
|
: 'Could not start the shared browser session. Open Browser Settings and verify the selected profile can launch.',
|
|
32674
33450
|
...(createError?.code ? { code: createError.code, offenders: createError.offenders } : {}),
|
|
33451
|
+
...(createError?.needsUser ? { needsUser: true } : {}),
|
|
33452
|
+
...(createError?.resetAt ? { resetAt: createError.resetAt } : {}),
|
|
32675
33453
|
};
|
|
32676
33454
|
}
|
|
32677
33455
|
|
|
@@ -32755,17 +33533,56 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
|
|
|
32755
33533
|
return { requeue: true };
|
|
32756
33534
|
}
|
|
32757
33535
|
|
|
33536
|
+
// Connected to its profile: a failure of that profile noted earlier in this run is over (it may switch again).
|
|
33537
|
+
if (claimedSession._mlEnvId) noteRunProfileConnected(ownerKey, claimedSession._mlEnvId);
|
|
32758
33538
|
return { browserSessionId, browserTabId };
|
|
32759
33539
|
});
|
|
32760
|
-
return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag }) : acquired;
|
|
33540
|
+
return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag, scheduledFiring }) : acquired;
|
|
33541
|
+
}
|
|
33542
|
+
|
|
33543
|
+
/**
|
|
33544
|
+
* The start guard of `ownerKey`'s acquisition (createBrowserSession `moreloginStartGuard` → lib/morelogin.js
|
|
33545
|
+
* startProfile `refuseStart`, asked only when MoreLogin says the profile is not running): a profile closed outside
|
|
33546
|
+
* SynaBun (lib/morelogin-outside-close.js) is not started again, for this run or any other, named the way the run
|
|
33547
|
+
* knows it. `scheduled`: the launch acquisition of a new scheduled firing, which may start it (startProfile is told
|
|
33548
|
+
* the same through `allowAfterOutsideClose`). → (envId) => Error | null.
|
|
33549
|
+
*/
|
|
33550
|
+
function moreLoginStartGuardFor(ownerKey, pin = null, { scheduled = false } = {}) {
|
|
33551
|
+
return (envId) => {
|
|
33552
|
+
if (scheduled) return null;
|
|
33553
|
+
const held = moreLogin.outsideCloseFor(String(envId));
|
|
33554
|
+
if (!held) return null;
|
|
33555
|
+
const name = (pin && String(pin.envId) === String(envId) ? pin.name : null) || _moreLoginEnvNames.get(String(envId)) || held.name || null;
|
|
33556
|
+
return moreLogin.outsideCloseError(String(envId), held, { label: describeProfile(String(envId), name) });
|
|
33557
|
+
};
|
|
33558
|
+
}
|
|
33559
|
+
|
|
33560
|
+
/**
|
|
33561
|
+
* The profiles closed outside SynaBun that SynaBun does not reopen (lib/morelogin-outside-close.js), for the status
|
|
33562
|
+
* answers and Settings: [{ envId, name, closedAt, closedLocal, holdUntil, holdUntilLocal, runs }] (the orphaned runs
|
|
33563
|
+
* counted, never listed). `envs`: a list just read, for names. Never throws.
|
|
33564
|
+
*/
|
|
33565
|
+
function moreLoginClosedOutside(envs = null) {
|
|
33566
|
+
try {
|
|
33567
|
+
const listed = new Map((envs || []).filter((e) => e?.id != null && e.name).map((e) => [String(e.id), String(e.name)]));
|
|
33568
|
+
return moreLogin.listOutsideCloses().map((c) => ({
|
|
33569
|
+
envId: c.envId, name: listed.get(c.envId) || _moreLoginEnvNames.get(c.envId) || c.name || null,
|
|
33570
|
+
closedAt: c.closedAt, closedLocal: c.closedLocal, holdUntil: c.holdUntil, holdUntilLocal: c.holdUntilLocal, runs: c.owners.length,
|
|
33571
|
+
}));
|
|
33572
|
+
} catch { return []; }
|
|
33573
|
+
}
|
|
33574
|
+
|
|
33575
|
+
/** A profile as a refusal names it (lib/morelogin.js startProfile `profileLabel`): its name as MoreLogin last listed it. */
|
|
33576
|
+
function moreLoginProfileLabel(envId, name = null) {
|
|
33577
|
+
return describeProfile(String(envId), _moreLoginEnvNames.get(String(envId)) || name || null);
|
|
32761
33578
|
}
|
|
32762
33579
|
|
|
32763
33580
|
/**
|
|
32764
33581
|
* Backward-compatible loop wrapper around acquireSharedBrowserTab. Existing callers
|
|
32765
33582
|
* pass { terminalSessionId } and expect loop-owned semantics.
|
|
32766
33583
|
*/
|
|
32767
|
-
async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, terminalSessionId, logTag = 'launch:browser' }) {
|
|
32768
|
-
return acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey: terminalSessionId, ownerType: 'loop', logTag });
|
|
33584
|
+
async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, terminalSessionId, logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false }) {
|
|
33585
|
+
return acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey: terminalSessionId, ownerType: 'loop', logTag, takeOverTab, scheduledFiring });
|
|
32769
33586
|
}
|
|
32770
33587
|
|
|
32771
33588
|
/**
|
|
@@ -32776,6 +33593,7 @@ async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, term
|
|
|
32776
33593
|
*/
|
|
32777
33594
|
async function releaseSharedBrowserTab(sessionId, ownerKey) {
|
|
32778
33595
|
const session = browserSessions.get(sessionId);
|
|
33596
|
+
if (session?._profileMode === 'extension') return extensionAdapter.release(sessionId, ownerKey);
|
|
32779
33597
|
if (!session) return;
|
|
32780
33598
|
session._interactiveOwned?.delete(ownerKey);
|
|
32781
33599
|
session._loopOwned?.delete(ownerKey);
|
|
@@ -32830,7 +33648,7 @@ function startedTabAlive(sessionId, tabId, ownerKey) {
|
|
|
32830
33648
|
const session = sessionId ? browserSessions.get(sessionId) : null;
|
|
32831
33649
|
if (!session) return false;
|
|
32832
33650
|
if (tabId && session.tabs && !session.tabs.has(tabId)) return false;
|
|
32833
|
-
if (ownerKey && tabId && session._tabOwners?.get(ownerKey)
|
|
33651
|
+
if (ownerKey && tabId && !(session._profileMode === 'extension' ? extensionAdapter.ownsTab(session, ownerKey, tabId) : session._tabOwners?.get(ownerKey) === tabId)) return false;
|
|
32834
33652
|
return true;
|
|
32835
33653
|
}
|
|
32836
33654
|
|
|
@@ -34125,6 +34943,22 @@ function browserStartFailure(err) {
|
|
|
34125
34943
|
const out = { error: err?.message || String(err) };
|
|
34126
34944
|
if (err?.code === 'NATIVE_SERVE_UNVERIFIED') { out.code = err.code; out.offenders = narrowOffenders(err.offenders); }
|
|
34127
34945
|
if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS') out.code = err.code;
|
|
34946
|
+
// MoreLogin refused the start (a plan limit, …): the user has to act, a retry or another run hits the same answer.
|
|
34947
|
+
if (err?.code === 'MORELOGIN_START_REFUSED') {
|
|
34948
|
+
out.code = err.code;
|
|
34949
|
+
out.needsUser = true;
|
|
34950
|
+
if (err.apiCode != null) out.apiCode = err.apiCode;
|
|
34951
|
+
if (err.planLimit) out.planLimit = true;
|
|
34952
|
+
if (err.resetAt) out.resetAt = err.resetAt;
|
|
34953
|
+
}
|
|
34954
|
+
// The run's profile was closed outside SynaBun and is not started again for it (lib/morelogin-outside-close.js), or
|
|
34955
|
+
// MoreLogin lists it running with no window: the user acts (starts or reopens it), a retry gets the same answer.
|
|
34956
|
+
if (err?.code === 'MORELOGIN_CLOSED_OUTSIDE' || err?.code === 'MORELOGIN_PROFILE_WINDOWLESS') {
|
|
34957
|
+
out.code = err.code;
|
|
34958
|
+
out.needsUser = true;
|
|
34959
|
+
if (err.closedAt) out.closedAt = err.closedAt;
|
|
34960
|
+
if (err.holdUntil) out.holdUntil = err.holdUntil;
|
|
34961
|
+
}
|
|
34128
34962
|
return out;
|
|
34129
34963
|
}
|
|
34130
34964
|
|
|
@@ -34141,6 +34975,9 @@ async function installServePortGuard(ctx, { deadline = Infinity, signal = null }
|
|
|
34141
34975
|
});
|
|
34142
34976
|
if (native) {
|
|
34143
34977
|
// Held first (assertLaunch refuses an unverified start from here on), then the HTTP rule, then the bounded check.
|
|
34978
|
+
// Warm the selected build before reserving/admitting this context. An existing attached context refuses a
|
|
34979
|
+
// new build here; its pre-flight must never be exposed through MoreLogin's 0.0.0.0 bypass.
|
|
34980
|
+
await opencodeServeLaunch(0, { preflightOnly: true });
|
|
34144
34981
|
const release = nativeServeBoundary.reserve(ctx);
|
|
34145
34982
|
try { await installRule(); } catch (error) {
|
|
34146
34983
|
release();
|
|
@@ -34230,6 +35067,10 @@ function moreLoginBlockError(session, requestedUrl, landedUrl) {
|
|
|
34230
35067
|
async function createBrowserSession(options = {}) {
|
|
34231
35068
|
const sessionId = randomBytes(16).toString('hex');
|
|
34232
35069
|
const savedCfg = loadBrowserConfig();
|
|
35070
|
+
if (savedCfg.connectMode === 'extension' && options.connectMode !== 'morelogin') {
|
|
35071
|
+
const acquired = await extensionAdapter.acquire(options._extensionOwner || 'owner-page');
|
|
35072
|
+
return { sessionId: acquired.browserSessionId, tabId: acquired.browserTabId, profileMode: 'extension', wsEndpoint: null };
|
|
35073
|
+
}
|
|
34233
35074
|
// Settings that exist but cannot be read are not "no settings": never fall back to Chrome.
|
|
34234
35075
|
const unreadableCfg = browserConfigUnreadable(savedCfg);
|
|
34235
35076
|
if (unreadableCfg) throw new Error(`browser-config.json is unreadable; fix it in Settings → Browser (${unreadableCfg})`);
|
|
@@ -34492,7 +35333,7 @@ async function createBrowserSession(options = {}) {
|
|
|
34492
35333
|
let _launchProfileDirectory = _profileDirectory || (userDataDir ? 'Default' : null);
|
|
34493
35334
|
|
|
34494
35335
|
// ── MoreLogin connect mode ──
|
|
34495
|
-
// When configured (Settings →
|
|
35336
|
+
// When configured (Settings → Connected tools → MoreLogin → Default AI browser, or an explicit per-session
|
|
34496
35337
|
// moreloginEnvId), launch/attach a MoreLogin anti-detect profile and drive it
|
|
34497
35338
|
// over CDP. MoreLogin's /api/env/start returns a debugPort — the exact same CDP
|
|
34498
35339
|
// path as "attach" mode, so we reuse connectOverCDP + probeCdpEndpoint here.
|
|
@@ -34545,27 +35386,49 @@ async function createBrowserSession(options = {}) {
|
|
|
34545
35386
|
}
|
|
34546
35387
|
// requireCdp: a Firefox-type profile has no DevTools endpoint and is refused, before it is started when
|
|
34547
35388
|
// MoreLogin says what it is up front.
|
|
34548
|
-
|
|
34549
|
-
//
|
|
35389
|
+
nativePreflightProfiles.add(String(envId));
|
|
35390
|
+
// `moreloginStartGuard` (acquireSharedBrowserTab): the run's own reason not to spend a launch. Asked only when
|
|
35391
|
+
// MoreLogin says the profile is not running. A profile closed outside SynaBun is refused by startProfile for
|
|
35392
|
+
// everybody but `moreloginAfterOutsideClose` ('owner': the owner's page; 'schedule': a new scheduled firing).
|
|
35393
|
+
const startOpts = { ...mlOpts, requireCdp: true, ...(typeof options.moreloginStartGuard === 'function' ? { refuseStart: options.moreloginStartGuard } : {}),
|
|
35394
|
+
...(options.moreloginAfterOutsideClose ? { allowAfterOutsideClose: options.moreloginAfterOutsideClose } : {}), profileLabel: moreLoginProfileLabel };
|
|
35395
|
+
let { debugPort } = await moreLogin.startProfile(envId, startOpts);
|
|
34550
35396
|
let endpoint = null;
|
|
34551
|
-
|
|
34552
|
-
|
|
34553
|
-
|
|
34554
|
-
|
|
34555
|
-
|
|
34556
|
-
|
|
34557
|
-
|
|
34558
|
-
|
|
34559
|
-
|
|
34560
|
-
|
|
34561
|
-
|
|
34562
|
-
|
|
34563
|
-
|
|
34564
|
-
|
|
34565
|
-
|
|
34566
|
-
|
|
34567
|
-
|
|
34568
|
-
|
|
35397
|
+
let attached = null;
|
|
35398
|
+
for (let attempt = 0; !attached; attempt++) {
|
|
35399
|
+
// Wait for MoreLogin's Chromium DevTools endpoint to come up.
|
|
35400
|
+
endpoint = null;
|
|
35401
|
+
for (let i = 0; i < 40; i++) {
|
|
35402
|
+
const probed = await probeCdpEndpoint(debugPort);
|
|
35403
|
+
if (probed.ok) { endpoint = probed.httpEndpoint; break; }
|
|
35404
|
+
await new Promise(r => setTimeout(r, 250));
|
|
35405
|
+
}
|
|
35406
|
+
if (!endpoint) {
|
|
35407
|
+
// Ten seconds without a DevTools answer. A port that answers HTTP as something else will never become
|
|
35408
|
+
// one: say what it is, in place of Playwright's "Unexpected status 404 … try connecting via ws://". A
|
|
35409
|
+
// port nothing listens on yet still gets the connect attempt below.
|
|
35410
|
+
const seen = await moreLogin.describeDebugEndpoint(debugPort);
|
|
35411
|
+
if (seen.kind === 'not-devtools') throw moreLogin.notDevToolsError(envId, debugPort, seen);
|
|
35412
|
+
endpoint = `http://127.0.0.1:${debugPort}`;
|
|
35413
|
+
}
|
|
35414
|
+
try {
|
|
35415
|
+
attached = await moreLogin.attachProfileBrowser(
|
|
35416
|
+
chromium, endpoint,
|
|
35417
|
+
(cdpBrowser, cdpContext) => newSessionPage({ browser: cdpBrowser, context: cdpContext, _profileMode: 'morelogin' }),
|
|
35418
|
+
); // fresh tab in the real profile; never substitute an incognito context
|
|
35419
|
+
} catch (attachError) {
|
|
35420
|
+
// MoreLogin lists the profile running, but its browser holds no profile (its window was closed and the
|
|
35421
|
+
// process lives on, or it is still starting: P-4 at 21:13:36 on 2026-11-15). Asked once more after a short
|
|
35422
|
+
// wait, through the status again (a profile that finished closing is then started only as startProfile and
|
|
35423
|
+
// the run's guard allow); never a start of a profile MoreLogin still lists as running.
|
|
35424
|
+
if (attachError?.code !== 'MORELOGIN_PROFILE_WINDOWLESS') throw attachError;
|
|
35425
|
+
if (attempt >= 1) throw moreLogin.windowlessProfileError(envId, endpoint, attachError.cause || attachError);
|
|
35426
|
+
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`);
|
|
35427
|
+
await new Promise(r => setTimeout(r, 2000));
|
|
35428
|
+
({ debugPort } = await moreLogin.startProfile(envId, startOpts));
|
|
35429
|
+
}
|
|
35430
|
+
}
|
|
35431
|
+
const { browser: cdpBrowser, context: cdpContext, page: cdpPage } = attached;
|
|
34569
35432
|
// A local profile's timezone on this first tab (every later tab gets it in newSessionPage, from the session).
|
|
34570
35433
|
if (_localProfileInfo?.timezone) await applyPageTimezone(cdpContext, cdpPage, _localProfileInfo.timezone);
|
|
34571
35434
|
|
|
@@ -34580,6 +35443,8 @@ async function createBrowserSession(options = {}) {
|
|
|
34580
35443
|
_profileSourceName = _localProfile ? `Local · ${_localProfileInfo?.name || envId}` : `MoreLogin · ${envId}`;
|
|
34581
35444
|
_localProfileTimezone = _localProfile ? (_localProfileInfo?.timezone || null) : null;
|
|
34582
35445
|
_moreLoginConnected = true;
|
|
35446
|
+
// The profile runs and SynaBun is attached: a close outside SynaBun remembered for it is over, for every run.
|
|
35447
|
+
if (!_localProfile) { try { moreLogin.clearOutsideClose(String(envId)); } catch { /* nothing held */ } }
|
|
34583
35448
|
console.log(`[browser] Connected to ${_localProfile ? `local profile ${envId}` : `MoreLogin env ${envId}`} via CDP at ${endpoint}`);
|
|
34584
35449
|
} catch (err) {
|
|
34585
35450
|
if (_localProfile) {
|
|
@@ -34589,14 +35454,27 @@ async function createBrowserSession(options = {}) {
|
|
|
34589
35454
|
throw refused;
|
|
34590
35455
|
}
|
|
34591
35456
|
const port = moreLogin.getMoreLoginPort(savedCfg);
|
|
34592
|
-
if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS'
|
|
34593
|
-
|
|
34594
|
-
// MoreLogin
|
|
35457
|
+
if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS' || err?.code === 'MORELOGIN_START_REFUSED'
|
|
35458
|
+
|| err?.code === 'MORELOGIN_CLOSED_OUTSIDE' || err?.code === 'MORELOGIN_PROFILE_WINDOWLESS') {
|
|
35459
|
+
// MoreLogin is open and the profile exists: it is the profile's browser SynaBun cannot drive, MoreLogin
|
|
35460
|
+
// itself refused the start (a plan limit, …), the run's profile was closed outside SynaBun and is not started
|
|
35461
|
+
// again for it, or MoreLogin lists it running with no window. No "open the MoreLogin app" advice, and the code
|
|
35462
|
+
// travels so the run's message does not add it either.
|
|
34595
35463
|
const rule = options.moreloginEnvId
|
|
34596
35464
|
? 'a session asked for a MoreLogin profile never falls back to another profile or to Chrome'
|
|
34597
35465
|
: 'sessions will not fall back to Chrome while MoreLogin is the default browser';
|
|
34598
|
-
|
|
35466
|
+
// A run whose profile was closed outside SynaBun: nothing failed to connect, SynaBun chose not to start it, and
|
|
35467
|
+
// the sentence (lib/morelogin-outside-close.js outsideCloseError) already says all of it.
|
|
35468
|
+
const refused = new Error(err.code === 'MORELOGIN_CLOSED_OUTSIDE'
|
|
35469
|
+
? `${err.message}.`
|
|
35470
|
+
: `MoreLogin connect failed: ${err.message}. Nothing was opened elsewhere: ${rule}.`);
|
|
34599
35471
|
refused.code = err.code;
|
|
35472
|
+
if (err.needsUser) refused.needsUser = true;
|
|
35473
|
+
if (err.apiCode != null) refused.apiCode = err.apiCode;
|
|
35474
|
+
if (err.planLimit) refused.planLimit = true;
|
|
35475
|
+
if (err.resetAt) refused.resetAt = err.resetAt;
|
|
35476
|
+
if (err.closedAt) refused.closedAt = err.closedAt;
|
|
35477
|
+
if (err.holdUntil) refused.holdUntil = err.holdUntil;
|
|
34600
35478
|
throw refused;
|
|
34601
35479
|
}
|
|
34602
35480
|
if (options.moreloginEnvId) {
|
|
@@ -35052,6 +35930,10 @@ async function createBrowserSession(options = {}) {
|
|
|
35052
35930
|
context.on('close', () => {
|
|
35053
35931
|
const orphanedLoops = session._loopOwned?.size > 0 ? [...session._loopOwned] : [];
|
|
35054
35932
|
console.log(`Browser context closed for session ${sessionId}${session._agentOwnedSet?.size ? ` (agent-owned: ${[...session._agentOwnedSet].join(',')})` : ''}${orphanedLoops.length ? ` (orphaning loops: ${orphanedLoops.map(logOwnerId).join(', ')})` : ''}`);
|
|
35933
|
+
// A MoreLogin profile's browser went away: who closed it (SynaBun's own revocation or teardown, or somebody
|
|
35934
|
+
// else: then one line of evidence, and the runs it orphaned do not start it again). The profile is never
|
|
35935
|
+
// reopened from here (each start spends one of MoreLogin's daily launches).
|
|
35936
|
+
try { noteMoreLoginContextClose(session, sessionId, context); } catch { /* the close goes on */ }
|
|
35055
35937
|
session.screencastActive = false;
|
|
35056
35938
|
detachScreencastFrameHandler(session);
|
|
35057
35939
|
// Stop autosave interval
|
|
@@ -35238,6 +36120,7 @@ async function stopScreencast(session) {
|
|
|
35238
36120
|
* of such a session closes those, and only those (closeOwnTabsBeforeDisconnect).
|
|
35239
36121
|
*/
|
|
35240
36122
|
async function newSessionPage(session, { timeoutMs } = {}) {
|
|
36123
|
+
if (session._profileMode === 'extension') throw Object.assign(new Error('Use the extension adapter to create tabs.'), { code: 'UNSUPPORTED_IN_EXTENSION_MODE' });
|
|
35241
36124
|
let page;
|
|
35242
36125
|
if (backgroundTabsEnabled(loadBrowserConfig())) {
|
|
35243
36126
|
page = await openBackgroundPageStrict(session.browser, session.context, {
|
|
@@ -35589,6 +36472,11 @@ async function _switchSessionTab(session, sessionId, tabId) {
|
|
|
35589
36472
|
* Close a single tab in a session. If it's the last tab, destroys the whole session.
|
|
35590
36473
|
*/
|
|
35591
36474
|
async function closeSessionTab(session, sessionId, tabId) {
|
|
36475
|
+
if (session._profileMode === 'extension') {
|
|
36476
|
+
const owner = [...session._tabOwners.keys()].find(key => extensionAdapter.ownsTab(session, key, tabId));
|
|
36477
|
+
if (owner) await extensionAdapter.release(sessionId, owner, tabId);
|
|
36478
|
+
return;
|
|
36479
|
+
}
|
|
35592
36480
|
const tabEntry = session.tabs.get(tabId);
|
|
35593
36481
|
if (!tabEntry) return;
|
|
35594
36482
|
|
|
@@ -35646,6 +36534,7 @@ async function closeSessionTab(session, sessionId, tabId) {
|
|
|
35646
36534
|
*/
|
|
35647
36535
|
async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingPage = null } = {}) {
|
|
35648
36536
|
const session = browserSessions.get(sessionId);
|
|
36537
|
+
if (session?._profileMode === 'extension') return extensionAdapter.destroy(sessionId);
|
|
35649
36538
|
if (!session) return;
|
|
35650
36539
|
|
|
35651
36540
|
try {
|
|
@@ -36183,7 +37072,47 @@ app.use('/api/browser/sessions/:id', (req, res, next) => {
|
|
|
36183
37072
|
}
|
|
36184
37073
|
return gate();
|
|
36185
37074
|
});
|
|
36186
|
-
// Read-only semantic context for the browser judgments
|
|
37075
|
+
// Read-only semantic context for the browser judgments and extension backend dispatch.
|
|
37076
|
+
// All extension endpoints terminate here; none falls through to Playwright or raw CDP.
|
|
37077
|
+
app.use('/api/browser', extensionAdapter.middleware);
|
|
37078
|
+
const extensionOwnerGuard = ownerRouteGuard({ isGuestRequest, port: PORT, allowedOrigins: publicWebOrigins, refuseCrossSite: true, ownOriginsOnly: true, requireOrigin: true });
|
|
37079
|
+
app.use('/api/browser/extension', extensionOwnerGuard, (req, res, next) => {
|
|
37080
|
+
if (browserCaller(req).automation || !browserOwnerPageOnly(req)) return res.status(403).json({ code: 'OWNER_ROUTE', error: 'Extension pairing and approval belong to the owner.' });
|
|
37081
|
+
res.setHeader('Cache-Control', 'no-store'); next();
|
|
37082
|
+
});
|
|
37083
|
+
app.get('/api/browser/extension', (_req, res) => {
|
|
37084
|
+
const folderState = extensionFolderState(DATA_HOME), status = extensionBridge.status();
|
|
37085
|
+
// `folder`: the folder the owner loads (the prepared copy; the bundled one only when none could be prepared).
|
|
37086
|
+
res.json({ ...status, folder: folderState.prepared ? folderState.folder : EXTENSION_FOLDER, bundledFolder: EXTENSION_FOLDER, uploadFolder: extensionUploadRoot,
|
|
37087
|
+
folderVersion: folderState.version, reloadNeeded: !!(status.connected && folderState.version && status.extensionVersion !== folderState.version),
|
|
37088
|
+
setup: extensionSetup.status().state });
|
|
37089
|
+
});
|
|
37090
|
+
// The one-button setup. Owner only: these sit under the guard above (ownerRouteGuard, the page secret, no automation
|
|
37091
|
+
// caller), like pairing and the mode. The token (ticket) goes to SynaBun's own setup page only, never into a log or URL.
|
|
37092
|
+
const sendSetup = (res, run) => Promise.resolve().then(run).then(value => res.json({ ok: true, ...value }),
|
|
37093
|
+
error => res.status(400).json(extensionSetupError(error) || extensionSafeError(error)));
|
|
37094
|
+
app.get('/api/browser/extension/setup/status', (_req, res) => sendSetup(res, () => extensionSetup.status()));
|
|
37095
|
+
app.post('/api/browser/extension/setup/start', (req, res) => sendSetup(res, () => extensionSetup.start({ browserId: typeof req.body?.browser === 'string' ? req.body.browser : undefined })));
|
|
37096
|
+
app.post('/api/browser/extension/setup/ticket', (_req, res) => { res.setHeader('Cache-Control', 'no-store'); return sendSetup(res, () => extensionSetup.ticket()); });
|
|
37097
|
+
app.post('/api/browser/extension/setup/cancel', (_req, res) => sendSetup(res, () => extensionSetup.cancel()));
|
|
37098
|
+
app.post('/api/browser/extension/setup/reveal', (_req, res) => sendSetup(res, () => extensionSetup.reveal()));
|
|
37099
|
+
app.post('/api/browser/extension/setup/reopen', (_req, res) => sendSetup(res, () => extensionSetup.reopen()));
|
|
37100
|
+
app.post('/api/browser/extension/:action', async (req, res) => {
|
|
37101
|
+
try {
|
|
37102
|
+
const action = req.params.action;
|
|
37103
|
+
if (action === 'pair') return res.json(await extensionBridge.beginPairing(Number(req.body?.port || 3345)));
|
|
37104
|
+
if (action === 'disconnect') extensionBridge.disconnect();
|
|
37105
|
+
else if (action === 'resume') extensionBridge.resume();
|
|
37106
|
+
else if (action === 'revoke') extensionBridge.revoke();
|
|
37107
|
+
else if (action === 'revoke-tab') await extensionBridge.revokeTab(req.body?.tab);
|
|
37108
|
+
else if (action === 'revoke-site') await extensionBridge.revokeSite(req.body?.site);
|
|
37109
|
+
// The owner's mode: full control (any site and tab of the paired browser) or only what the owner shares.
|
|
37110
|
+
else if (action === 'mode') await extensionBridge.setMode(req.body?.fullControl);
|
|
37111
|
+
else return res.status(400).json({ code: 'INVALID_MESSAGE', error: 'Unknown extension action.' });
|
|
37112
|
+
return res.json({ ok: true, ...extensionBridge.status() });
|
|
37113
|
+
} catch (error) { return res.status(400).json(extensionSafeError(error)); }
|
|
37114
|
+
});
|
|
37115
|
+
// Semantic context itself runs only on Playwright sessions; the extension adapter has already answered.
|
|
36187
37116
|
app.use('/api/browser', createBrowserAssistRouter({ browserSessions, getTargetPage, normalizeSelector }));
|
|
36188
37117
|
|
|
36189
37118
|
app.get('/api/browser/sessions', (req, res) => {
|
|
@@ -36213,7 +37142,7 @@ app.get('/api/browser/sessions', (req, res) => {
|
|
|
36213
37142
|
const sessions = [...browserSessions.entries()].map(([id, s]) => {
|
|
36214
37143
|
const allTabs = s.tabs ? [...s.tabs.entries()] : [];
|
|
36215
37144
|
const ownTabId = automationView && caller ? (s._tabOwners?.get(caller) || null) : null;
|
|
36216
|
-
const shownTabs = automationView ? allTabs.filter(([tid]) => tid === ownTabId) : allTabs;
|
|
37145
|
+
const shownTabs = automationView ? allTabs.filter(([tid]) => s._profileMode === 'extension' ? extensionAdapter.ownsTab(s, caller, tid) : tid === ownTabId) : allTabs;
|
|
36217
37146
|
const ownTab = automationView && shownTabs.length ? shownTabs[0][1] : null;
|
|
36218
37147
|
return {
|
|
36219
37148
|
id,
|
|
@@ -36226,9 +37155,9 @@ app.get('/api/browser/sessions', (req, res) => {
|
|
|
36226
37155
|
profileSource: s._profileSourceName || null,
|
|
36227
37156
|
moreloginEnvId: s._mlEnvId || null,
|
|
36228
37157
|
// For a run pinned to a MoreLogin profile of its own, "the default" is that profile's session (sessionServesRun).
|
|
36229
|
-
servesDefault:
|
|
37158
|
+
servesDefault: sessionServesRun(s, policyCfg, caller),
|
|
36230
37159
|
// The browser's own CDP endpoint drives every tab past every check here: the owner's page's only.
|
|
36231
|
-
wsEndpoint: who.automation || s._isPersistent ? null : (s.browser
|
|
37160
|
+
wsEndpoint: who.automation || s._isPersistent ? null : (s.browser?.wsEndpoint?.() || null),
|
|
36232
37161
|
activeTabId: automationView ? (ownTabId && s.activeTabId === ownTabId ? ownTabId : null) : (s.activeTabId || null),
|
|
36233
37162
|
loopOwned: (s._loopOwned?.size || 0) > 0,
|
|
36234
37163
|
interactiveOwned: (s._interactiveOwned?.size || 0) > 0,
|
|
@@ -36267,12 +37196,18 @@ app.get('/api/browser/sessions', (req, res) => {
|
|
|
36267
37196
|
// POST /api/loop/recover-browser records a run's move to a tab of its own (`adopt`): an MCP asks it only of a
|
|
36268
37197
|
// server that says so (an older one reads the request as a recovery and opens a tab).
|
|
36269
37198
|
adoptRoute: true,
|
|
37199
|
+
// The everyday browser through the extension, in full control: the owner's open tabs no agent holds, which an
|
|
37200
|
+
// agent may take over (browser_session create with that tabId). Only for a verified run or the owner's page.
|
|
37201
|
+
...(policyCfg.connectMode === 'extension' && !callerPin && (who.automation ? who.status === 'verified' : browserOwnerPageOnly(req))
|
|
37202
|
+
? (() => { const tabs = extensionAdapter.ownerTabs({ caller, includeOwned: true }); return tabs ? { extensionTabs: { fullControl: true, tabs } } : {}; })()
|
|
37203
|
+
: {}),
|
|
36270
37204
|
});
|
|
36271
37205
|
});
|
|
36272
37206
|
|
|
36273
37207
|
app.post('/api/browser/sessions', async (req, res) => {
|
|
36274
37208
|
const { url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, connectMode, moreloginEnvId } = req.body;
|
|
36275
|
-
// Which browser or MoreLogin profile a session starts on is the owner's choice (Settings → Browser
|
|
37209
|
+
// Which browser or MoreLogin profile a session starts on is the owner's choice (Settings → Browser for SynaBun's own
|
|
37210
|
+
// browser, Settings → Connected tools → MoreLogin for the default AI browser profile): an automation's
|
|
36276
37211
|
// create opens the default browser and names neither (lib/browser-automation-routes.js; review 972afb74, finding 1).
|
|
36277
37212
|
// N1 (re-review of 2026-11-10): the check asked `creator.automation` only, so an invite guest with the `browser`
|
|
36278
37213
|
// permission (browserTerminalGate lets a guest reach this route: browserPageOwner) who knew a profile's id opened
|
|
@@ -36282,7 +37217,12 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
36282
37217
|
const ownerFields = (creator.automation || !browserOwnerPageOnly(req)) ? ownerOnlyCreateFields(req.body) : [];
|
|
36283
37218
|
if (ownerFields.length) {
|
|
36284
37219
|
const guestCreate = !creator.automation;
|
|
36285
|
-
|
|
37220
|
+
// Where the owner makes each choice: a MoreLogin profile (the default AI browser) in the MoreLogin tab, SynaBun's
|
|
37221
|
+
// own browser (connect mode, folders, executable) in Settings → Browser.
|
|
37222
|
+
const profileFields = ownerFields.some((f) => /^morelogin/i.test(f));
|
|
37223
|
+
const browserFields = ownerFields.some((f) => !/^morelogin/i.test(f));
|
|
37224
|
+
const where = [profileFields && 'Settings → Connected tools → MoreLogin (Default AI browser)', browserFields && 'Settings → Browser'].filter(Boolean).join('; ');
|
|
37225
|
+
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.` });
|
|
36286
37226
|
}
|
|
36287
37227
|
// A create-session startUrl that points at one of SynaBun's own live OpenCode serve ports is refused up front, like
|
|
36288
37228
|
// navigate and new-tab: the serve's API can change what a worker session may do, and createBrowserSession navigates
|
|
@@ -36330,15 +37270,28 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
36330
37270
|
}
|
|
36331
37271
|
// The start, its owner and its broadcast: once per start, whoever ends up with it.
|
|
36332
37272
|
const start = async () => {
|
|
36333
|
-
|
|
36334
|
-
|
|
36335
|
-
|
|
36336
|
-
|
|
36337
|
-
|
|
36338
|
-
|
|
36339
|
-
|
|
36340
|
-
|
|
37273
|
+
let result;
|
|
37274
|
+
try {
|
|
37275
|
+
result = await createBrowserSession({
|
|
37276
|
+
url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, _realHeaders,
|
|
37277
|
+
// Its deadline bounds the native serve check (installServePortGuard) inside the caller's timeout.
|
|
37278
|
+
browserRequest: req.browserRequest,
|
|
37279
|
+
// Optional per-session override to target a specific MoreLogin env (multi-identity)
|
|
37280
|
+
...(connectMode === 'morelogin' ? { connectMode } : {}),
|
|
37281
|
+
...(moreloginEnvId ? { moreloginEnvId: String(moreloginEnvId) } : {}),
|
|
37282
|
+
// The owner's own page (its page secret, no run or agent header) opening a session is the owner starting
|
|
37283
|
+
// the profile: it may start one closed outside SynaBun (lib/morelogin-outside-close.js). Nobody else may.
|
|
37284
|
+
...(!creator.automation && browserOwnerPageOnly(req) ? { moreloginAfterOutsideClose: 'owner' } : {}),
|
|
37285
|
+
});
|
|
37286
|
+
} catch (err) {
|
|
37287
|
+
// An automation's own profile here is the MoreLogin default: when it fails to start or connect, the run may not
|
|
37288
|
+
// move to another profile (lib/morelogin-profile-failures.js). The owner's page has no run to bar.
|
|
37289
|
+
if (who.automation && creatorTerminalId) noteRunProfileFailure(creatorTerminalId, runEffectiveProfile(creatorTerminalId), browserStartFailure(err));
|
|
37290
|
+
throw err;
|
|
37291
|
+
}
|
|
36341
37292
|
const createdSession = browserSessions.get(result.sessionId);
|
|
37293
|
+
// Connected to the profile: a failure of it noted earlier in this run is over.
|
|
37294
|
+
if (who.automation && creatorTerminalId && createdSession?._mlEnvId) noteRunProfileConnected(creatorTerminalId, createdSession._mlEnvId);
|
|
36342
37295
|
if (creatorTerminalId && createdSession) {
|
|
36343
37296
|
if (!createdSession._tabOwners) createdSession._tabOwners = new Map();
|
|
36344
37297
|
createdSession._tabOwners.set(creatorTerminalId, createdSession.activeTabId);
|
|
@@ -36371,8 +37324,11 @@ app.post('/api/browser/sessions', async (req, res) => {
|
|
|
36371
37324
|
} catch (err) {
|
|
36372
37325
|
console.error('Browser session create error:', err.message);
|
|
36373
37326
|
const acq = err?.acquisition;
|
|
36374
|
-
if (acq) return res.status(
|
|
36375
|
-
res.status(500).json(
|
|
37327
|
+
if (acq?.code === 'MORELOGIN_CLOSED_OUTSIDE') return res.status(409).json(closedOutsideAnswer(acq));
|
|
37328
|
+
if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}), ...(acq.needsUser ? { needsUser: true } : {}) });
|
|
37329
|
+
const failure = browserStartFailure(err);
|
|
37330
|
+
if (failure.code === 'MORELOGIN_CLOSED_OUTSIDE') return res.status(409).json(closedOutsideAnswer(failure));
|
|
37331
|
+
res.status(500).json(failure);
|
|
36376
37332
|
}
|
|
36377
37333
|
});
|
|
36378
37334
|
|
|
@@ -36439,11 +37395,19 @@ app.post('/api/browser/acquire', async (req, res) => {
|
|
|
36439
37395
|
res.json({ ok: true, sessionId: acq.browserSessionId, tabId: acq.browserTabId || null, ...(outcome.from !== 'started' && { handedOver: outcome.from }) });
|
|
36440
37396
|
} catch (err) {
|
|
36441
37397
|
const acq = err?.acquisition;
|
|
36442
|
-
|
|
37398
|
+
// The profile was closed outside SynaBun and SynaBun does not reopen it: 409, the user acts (never a replacement).
|
|
37399
|
+
if (acq?.code === 'MORELOGIN_CLOSED_OUTSIDE') return res.status(409).json(closedOutsideAnswer(acq));
|
|
37400
|
+
if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}), ...(acq.needsUser ? { needsUser: true } : {}) });
|
|
36443
37401
|
res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code } : {}) });
|
|
36444
37402
|
}
|
|
36445
37403
|
});
|
|
36446
37404
|
|
|
37405
|
+
/** The answer of a browser route refused because its MoreLogin profile was closed outside SynaBun (409). */
|
|
37406
|
+
function closedOutsideAnswer(acq) {
|
|
37407
|
+
return { ok: false, error: acq.error, code: 'MORELOGIN_CLOSED_OUTSIDE', needsUser: true, blocked: true,
|
|
37408
|
+
...(acq.closedAt ? { closedAt: acq.closedAt } : {}), ...(acq.holdUntil ? { holdUntil: acq.holdUntil } : {}) };
|
|
37409
|
+
}
|
|
37410
|
+
|
|
36447
37411
|
// POST /api/browser/release — interactive MCP process relinquishes its owned tab on
|
|
36448
37412
|
// exit. Closes the dedicated tab and drops the ownership/routing entries so the shared
|
|
36449
37413
|
// browser can be grace-reaped once no owners remain. Best-effort; body: { clientId }.
|
|
@@ -38287,7 +39251,7 @@ app.put('/api/browser/config', async (req, res) => {
|
|
|
38287
39251
|
// Finding 1 of the re-review of 2026-11-11: only the owner's page changes the default AI browser (connect mode,
|
|
38288
39252
|
// default MoreLogin profile). browserTerminalGate already keeps this route from automations; this is the route's own.
|
|
38289
39253
|
if (browserDefaultChangeRefused(req, body, loadBrowserConfig())) return refuseDefaultBrowserChange(res);
|
|
38290
|
-
if (body.connectMode !== undefined) body.connectMode = ['attach', 'morelogin'].includes(body.connectMode) ? body.connectMode : 'mirror';
|
|
39254
|
+
if (body.connectMode !== undefined) body.connectMode = ['attach', 'morelogin', 'extension'].includes(body.connectMode) ? body.connectMode : 'mirror';
|
|
38291
39255
|
if (body.attachSeed !== undefined) body.attachSeed = body.attachSeed === 'fresh' ? 'fresh' : 'real';
|
|
38292
39256
|
if (body.moreloginEnvId !== undefined && body.moreloginEnvId !== null && body.moreloginEnvId !== '') body.moreloginEnvId = String(body.moreloginEnvId);
|
|
38293
39257
|
// The default MoreLogin profile is driven over CDP: a newly chosen one known to be Firefox-type is refused. The
|
|
@@ -38331,7 +39295,7 @@ app.get('/api/browser/detect-profiles', (req, res) => {
|
|
|
38331
39295
|
}
|
|
38332
39296
|
});
|
|
38333
39297
|
|
|
38334
|
-
// List MoreLogin profiles (environments) for the
|
|
39298
|
+
// List MoreLogin profiles (environments) for the profile pickers (the MoreLogin tab's Default AI browser, schedules)
|
|
38335
39299
|
app.get('/api/browser/morelogin-envs', async (req, res) => {
|
|
38336
39300
|
try {
|
|
38337
39301
|
const cfg = loadBrowserConfig();
|
|
@@ -38346,19 +39310,25 @@ app.get('/api/browser/morelogin-envs', async (req, res) => {
|
|
|
38346
39310
|
try { localEnvs = (await moreLogin.listLocalProfiles()).map((env) => ({ ...env, browser: 'chromium' })); }
|
|
38347
39311
|
catch (err) { localError = err.message; }
|
|
38348
39312
|
const local = { count: localEnvs.length, ...(localError ? { error: localError } : {}) };
|
|
39313
|
+
// Profiles whose start MoreLogin refused for its plan's daily limit, until its day resets (SynaBun's own record:
|
|
39314
|
+
// said whatever state MoreLogin is in). Named from the list below when it is read.
|
|
39315
|
+
const startCooldowns = moreLoginStartCooldowns();
|
|
39316
|
+
// Profiles closed outside SynaBun that SynaBun does not reopen (lib/morelogin-outside-close.js), said in every
|
|
39317
|
+
// answer too: [{ envId, name, closedAt, closedLocal, holdUntil, holdUntilLocal, runs }].
|
|
39318
|
+
const closedOutside = moreLoginClosedOutside();
|
|
38349
39319
|
// Probe first: the install-folder check knows only the default folders, and an
|
|
38350
39320
|
// answering local API proves the app is there wherever it was installed.
|
|
38351
39321
|
const probe = await moreLogin.probeMoreLoginApi({ savedCfg: cfg, port });
|
|
38352
39322
|
const installed = probe.running || moreLogin.isMoreLoginInstalled().installed;
|
|
38353
|
-
if (!installed) return res.json({ connectMode, ok: true, installed: false, running: false, port, envs: localEnvs, local, error: probe.error || null });
|
|
38354
|
-
if (!probe.running) return res.json({ connectMode, ok: true, installed: true, running: false, port, envs: localEnvs, local, error: probe.error || null });
|
|
39323
|
+
if (!installed) return res.json({ connectMode, ok: true, installed: false, running: false, port, envs: localEnvs, local, startCooldowns, closedOutside, error: probe.error || null });
|
|
39324
|
+
if (!probe.running) return res.json({ connectMode, ok: true, installed: true, running: false, port, envs: localEnvs, local, startCooldowns, closedOutside, error: probe.error || null });
|
|
38355
39325
|
// The API answered with an error (signature required, API off): say why, never an empty list.
|
|
38356
|
-
if (probe.apiError) return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, error: probe.apiError });
|
|
39326
|
+
if (probe.apiError) return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, startCooldowns, closedOutside, error: probe.apiError });
|
|
38357
39327
|
// MoreLogin's own rows (the list holds the local ones too: they are added once, below).
|
|
38358
39328
|
const listedEnvs = (await moreLogin.listProfiles({ savedCfg: cfg, port })).filter((env) => env.kind !== 'local');
|
|
38359
39329
|
// The API counted profiles but none could be read: a shape problem, never "no profiles yet".
|
|
38360
39330
|
if (probe.count > 0 && !listedEnvs.length) {
|
|
38361
|
-
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.` });
|
|
39331
|
+
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.` });
|
|
38362
39332
|
}
|
|
38363
39333
|
// Each profile with the browser it runs (`browser`: 'chromium' | 'firefox' | null = not known): the list call
|
|
38364
39334
|
// does not say it, so it is looked up per profile, kept, and never waited for longer than the lookup's budget.
|
|
@@ -38366,6 +39336,8 @@ app.get('/api/browser/morelogin-envs', async (req, res) => {
|
|
|
38366
39336
|
const { envs, browsersPending } = await withMoreLoginBrowsers(listedEnvs, { savedCfg: cfg, port });
|
|
38367
39337
|
res.json({
|
|
38368
39338
|
connectMode, ok: true, installed: true, running: true, port, envs: [...envs, ...localEnvs], local, browsersPending,
|
|
39339
|
+
startCooldowns: moreLoginStartCooldowns(listedEnvs),
|
|
39340
|
+
closedOutside: moreLoginClosedOutside(listedEnvs),
|
|
38369
39341
|
// Observed website-policy blocks — MoreLogin's local API never exposes the
|
|
38370
39342
|
// blacklist/whitelist itself, so the picker reports what actually happened.
|
|
38371
39343
|
blockedNavigations: moreLoginBlockStats.count,
|
|
@@ -38626,7 +39598,7 @@ const httpServer = app.listen(PORT, async () => {
|
|
|
38626
39598
|
}, 200);
|
|
38627
39599
|
|
|
38628
39600
|
// Detect MoreLogin (anti-detect browser) — DETECTION ONLY, never auto-activates.
|
|
38629
|
-
// Activation is an explicit user choice
|
|
39601
|
+
// Activation is an explicit user choice in the MoreLogin tab (Default AI browser).
|
|
38630
39602
|
setTimeout(async () => {
|
|
38631
39603
|
try {
|
|
38632
39604
|
const mlBootCfg = loadBrowserConfig();
|
|
@@ -38769,6 +39741,39 @@ const httpServer = app.listen(PORT, async () => {
|
|
|
38769
39741
|
console.warn(' Rules reconcile warning:', err.message);
|
|
38770
39742
|
}
|
|
38771
39743
|
|
|
39744
|
+
// The owner's tool permissions (Settings → Tool permissions): what was switched on and is missing from the
|
|
39745
|
+
// allow list of ~/.claude/settings.json is put back, and what the list allows is written down as chosen
|
|
39746
|
+
// (lib/tool-permission-choices.js). An update is a start, so this is what keeps the choices across one.
|
|
39747
|
+
{
|
|
39748
|
+
const kept = reconcileSavedToolPermissions('start');
|
|
39749
|
+
if (kept.restored.length) console.log(` Tools: ${kept.restored.length} saved tool permission${kept.restored.length === 1 ? '' : 's'} put back in ${getGlobalClaudeSettingsPath()}`);
|
|
39750
|
+
}
|
|
39751
|
+
|
|
39752
|
+
// Every named Claude account reads the default's settings.json (allow list, hooks), CLAUDE.md, rules and skills
|
|
39753
|
+
// (lib/claude-account-links.js): a missing link is made, the junction to a file that an older SynaBun made
|
|
39754
|
+
// on Windows (it opens as a broken folder, so the account read no settings at all) is replaced, and a hard
|
|
39755
|
+
// link or copy two writes apart is brought back in step. Never stops the boot.
|
|
39756
|
+
try {
|
|
39757
|
+
const shared = _panelClaudeAccounts().syncShared();
|
|
39758
|
+
const repaired = shared.filter((row) => row.repaired.length);
|
|
39759
|
+
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(', ')})`);
|
|
39760
|
+
} catch (err) {
|
|
39761
|
+
console.warn(' Claude accounts warning:', err.message);
|
|
39762
|
+
}
|
|
39763
|
+
|
|
39764
|
+
// Every named Codex account reads Default's config.toml (model, MCP servers, tool settings), AGENTS.md and
|
|
39765
|
+
// prompts/ the same way (lib/codex-accounts.js syncShared). On Windows SynaBun linked the two files with a
|
|
39766
|
+
// symbolic link only, which Windows refuses without Developer Mode or administrator rights: such an account
|
|
39767
|
+
// ran on a config.toml of its own and without AGENTS.md. Put in order once here; a hard link or a copy two
|
|
39768
|
+
// writes apart is brought back in step at every start. Never stops the boot.
|
|
39769
|
+
try {
|
|
39770
|
+
const shared = _codexAccounts().syncShared();
|
|
39771
|
+
const changed = shared.filter((row) => row.repaired.length || row.linked.length);
|
|
39772
|
+
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(', ')})`);
|
|
39773
|
+
} catch (err) {
|
|
39774
|
+
console.warn(' Codex accounts warning:', err.message);
|
|
39775
|
+
}
|
|
39776
|
+
|
|
38772
39777
|
// SynaBun's Antigravity homes (lib/antigravity/home.js): a run's home lives a week past its last use (a run resumes
|
|
38773
39778
|
// within minutes of a restart), an Assistant brain's two months (its conversation can be picked up later).
|
|
38774
39779
|
try {
|
|
@@ -39180,10 +40185,8 @@ function handleWhiteboardWebSocket(ws, req) {
|
|
|
39180
40185
|
let _screenshotPattern = null;
|
|
39181
40186
|
|
|
39182
40187
|
if (process.platform === 'darwin') {
|
|
39183
|
-
|
|
39184
|
-
|
|
39185
|
-
} catch { /* not set — use default */ }
|
|
39186
|
-
if (!_screenshotDir || !existsSync(_screenshotDir)) _screenshotDir = join(os.homedir(), 'Desktop');
|
|
40188
|
+
// The Screenshot app's folder, else ~/Desktop (lib/screenshot-location.js: quiet when none was ever set).
|
|
40189
|
+
_screenshotDir = macScreenshotDir();
|
|
39187
40190
|
// macOS screenshot filenames: "Screenshot ..." (EN), "Captura de..." (ES/PT)
|
|
39188
40191
|
_screenshotPattern = /^(Screenshot\b|Captura de).*\.png$/i;
|
|
39189
40192
|
} else if (process.platform === 'win32') {
|
|
@@ -39358,6 +40361,10 @@ function handleCardsWebSocket(ws) {
|
|
|
39358
40361
|
async function handleBrowserWebSocket(ws, url) {
|
|
39359
40362
|
const sessionId = url.pathname.replace('/ws/browser/', '');
|
|
39360
40363
|
const session = browserSessions.get(sessionId);
|
|
40364
|
+
if (session?._profileMode === 'extension') {
|
|
40365
|
+
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.' }));
|
|
40366
|
+
ws.close(); return;
|
|
40367
|
+
}
|
|
39361
40368
|
|
|
39362
40369
|
if (!session) {
|
|
39363
40370
|
ws.send(JSON.stringify({ type: 'error', message: 'Browser session not found' }));
|