scope-agent-workbench 0.0.0-stage → 0.2.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 +18 -0
- package/LICENSE +21 -0
- package/README.md +174 -2
- package/README.zh-CN.md +175 -0
- package/bin/scope.mjs +111 -0
- package/bridge/account-quotas.mjs +881 -0
- package/bridge/agent-email-relay.mjs +160 -0
- package/bridge/app-server-client.mjs +2522 -0
- package/bridge/app-server-websocket-transport.mjs +219 -0
- package/bridge/archive/routes.mjs +19 -0
- package/bridge/archive/service.mjs +130 -0
- package/bridge/archive/thread-lifecycle.mjs +52 -0
- package/bridge/attachment-store.mjs +184 -0
- package/bridge/auth-profile-failover.mjs +58 -0
- package/bridge/auth-profile-manager.mjs +215 -0
- package/bridge/capacity-recovery.mjs +90 -0
- package/bridge/codex-upgrade.mjs +150 -0
- package/bridge/deployment-profile.mjs +64 -0
- package/bridge/email-notifier.mjs +616 -0
- package/bridge/gpu-usage-history.mjs +322 -0
- package/bridge/host-session-restart.mjs +35 -0
- package/bridge/http.mjs +69 -0
- package/bridge/idle-sessions.mjs +185 -0
- package/bridge/inventory-scanner.mjs +517 -0
- package/bridge/local/dialogue.mjs +150 -0
- package/bridge/local/directories.mjs +40 -0
- package/bridge/local/executable.mjs +29 -0
- package/bridge/local/history.mjs +21 -0
- package/bridge/local/python-probe.mjs +35 -0
- package/bridge/local/runtime.mjs +188 -0
- package/bridge/local/transport.mjs +70 -0
- package/bridge/maintenance/install-command.mjs +141 -0
- package/bridge/maintenance/routes.mjs +21 -0
- package/bridge/maintenance/service.mjs +175 -0
- package/bridge/model-catalog.mjs +21 -0
- package/bridge/persistent-home-guard.mjs +6 -0
- package/bridge/plugins/aliyun-dlc/index.mjs +47 -0
- package/bridge/plugins/aliyun-dlc/manifest.mjs +12 -0
- package/bridge/plugins/aliyun-dlc/monitor.mjs +236 -0
- package/bridge/plugins/aliyun-dlc/probe.mjs +701 -0
- package/bridge/plugins/config-store.mjs +35 -0
- package/bridge/plugins/external.mjs +87 -0
- package/bridge/plugins/package.mjs +96 -0
- package/bridge/plugins/registry.mjs +37 -0
- package/bridge/plugins/routes.mjs +27 -0
- package/bridge/private-gateway.mjs +371 -0
- package/bridge/private-start.mjs +22 -0
- package/bridge/probes/app-server-handoff-probe.mjs +89 -0
- package/bridge/probes/app-server-writer-probe.mjs +72 -0
- package/bridge/probes/assistant-search-probe.mjs +323 -0
- package/bridge/probes/dialogue-probe.mjs +464 -0
- package/bridge/probes/history-probe.mjs +347 -0
- package/bridge/probes/index.mjs +15 -0
- package/bridge/probes/new-session-preflight.mjs +16 -0
- package/bridge/probes/profile-cancel-probe.mjs +19 -0
- package/bridge/probes/profile-delete-probe.mjs +28 -0
- package/bridge/probes/profile-list-probe.mjs +117 -0
- package/bridge/probes/profile-write-probe.mjs +111 -0
- package/bridge/probes/raw-context-probe.mjs +53 -0
- package/bridge/probes/remote-probe.mjs +636 -0
- package/bridge/probes/submission-probe.mjs +2 -0
- package/bridge/probes/takeover-probe.mjs +328 -0
- package/bridge/probes/vscode-open-preflight.mjs +23 -0
- package/bridge/profile-capacity-policy.mjs +14 -0
- package/bridge/providers/acp-forms.py +49 -0
- package/bridge/providers/antigravity-interactive.mjs +14 -0
- package/bridge/providers/antigravity-interactive.py +349 -0
- package/bridge/providers/claude-capabilities.py +52 -0
- package/bridge/providers/claude-interactive.mjs +14 -0
- package/bridge/providers/claude-interactive.py +341 -0
- package/bridge/providers/cli-command.mjs +103 -0
- package/bridge/providers/codex-workbench.mjs +164 -0
- package/bridge/providers/conversation-routes.mjs +28 -0
- package/bridge/providers/conversations.mjs +231 -0
- package/bridge/providers/native-commands.mjs +48 -0
- package/bridge/providers/native-commands.py +38 -0
- package/bridge/providers/native-models.mjs +129 -0
- package/bridge/providers/native-session-state.mjs +14 -0
- package/bridge/providers/native-session-state.py +96 -0
- package/bridge/providers/remote-cli.mjs +75 -0
- package/bridge/providers/remote-job.py +130 -0
- package/bridge/remote-app-server-command.mjs +203 -0
- package/bridge/remote-bootstrap/routes.mjs +51 -0
- package/bridge/remote-bootstrap/scope-protocol.mjs +125 -0
- package/bridge/remote-bootstrap/service.mjs +597 -0
- package/bridge/remote-bootstrap/tunnels.mjs +347 -0
- package/bridge/remote-directory-listing.mjs +148 -0
- package/bridge/remote-images.mjs +140 -0
- package/bridge/remote-profile-home.mjs +39 -0
- package/bridge/remote-rollout-locks.mjs +31 -0
- package/bridge/remote-videos.mjs +129 -0
- package/bridge/research/insights.mjs +522 -0
- package/bridge/research/scan-host.mjs +18 -0
- package/bridge/rollout-summary.mjs +159 -0
- package/bridge/routes/accounts.mjs +326 -0
- package/bridge/routes/dialogue.mjs +120 -0
- package/bridge/routes/email.mjs +50 -0
- package/bridge/routes/management.mjs +291 -0
- package/bridge/routes/models.mjs +312 -0
- package/bridge/routes/runtime.mjs +82 -0
- package/bridge/routes/session-commands.mjs +12 -0
- package/bridge/routes/session-delivery.mjs +328 -0
- package/bridge/routes/session-lifecycle.mjs +839 -0
- package/bridge/routes/system.mjs +289 -0
- package/bridge/server.mjs +3332 -0
- package/bridge/session-attachments.mjs +150 -0
- package/bridge/session-cache-archive.mjs +22 -0
- package/bridge/session-catalog/agy-history.py +249 -0
- package/bridge/session-catalog/catalog.mjs +93 -0
- package/bridge/session-catalog/probe.py +331 -0
- package/bridge/session-catalog/routes.mjs +28 -0
- package/bridge/session-profiles.mjs +115 -0
- package/bridge/shared-start.mjs +22 -0
- package/bridge/start.mjs +205 -0
- package/bridge/state-persistence.mjs +397 -0
- package/bridge/submissions/settings.mjs +50 -0
- package/bridge/terminal-gateway.mjs +171 -0
- package/bridge/tmux-delivery.mjs +390 -0
- package/bridge/tmux-session-control.mjs +29 -0
- package/bridge/transport/ssh-command.mjs +119 -0
- package/bridge/ui-server.mjs +257 -0
- package/bridge/vscode-opener.mjs +157 -0
- package/bridge/web-terminal.mjs +52 -0
- package/bridge/workbench/conversation-routes.mjs +31 -0
- package/bridge/workbench/directory-probe.mjs +41 -0
- package/bridge/workbench/directory-routes.mjs +112 -0
- package/bridge/workbench/manager-context.mjs +51 -0
- package/bridge/workbench/routes.mjs +40 -0
- package/bridge/workbench/scheduler.mjs +131 -0
- package/bridge/workbench/service.mjs +301 -0
- package/bridge/workbench/store.mjs +64 -0
- package/bridge/workbench/task-archive.mjs +46 -0
- package/dist/client/.assetsignore +2 -0
- package/dist/client/.vite/manifest.json +366 -0
- package/dist/client/_headers +3 -0
- package/dist/client/agents/LICENSE.lobe-icons +21 -0
- package/dist/client/agents/README.md +14 -0
- package/dist/client/agents/antigravity.svg +39 -0
- package/dist/client/agents/claude.svg +1 -0
- package/dist/client/agents/codex.svg +1 -0
- package/dist/client/agents/dsh.svg +4 -0
- package/dist/client/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/dist/client/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/dist/client/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/dist/client/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/dist/client/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/dist/client/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/dist/client/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/dist/client/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/dist/client/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/dist/client/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/dist/client/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/dist/client/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/dist/client/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/dist/client/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/dist/client/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/dist/client/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/dist/client/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/dist/client/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/dist/client/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/dist/client/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/dist/client/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/dist/client/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/dist/client/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/dist/client/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/dist/client/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/dist/client/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/dist/client/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/dist/client/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/dist/client/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/dist/client/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/dist/client/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/dist/client/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/dist/client/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/dist/client/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/dist/client/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/dist/client/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/dist/client/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/dist/client/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/dist/client/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/dist/client/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/dist/client/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/dist/client/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/dist/client/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/dist/client/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/dist/client/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/dist/client/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/dist/client/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/dist/client/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/dist/client/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/dist/client/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/dist/client/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/dist/client/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/dist/client/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/dist/client/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/dist/client/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/dist/client/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/dist/client/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/dist/client/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/dist/client/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/dist/client/assets/_vinext_fonts/geist-8ac0455e797f/geist-001175b1.woff2 +0 -0
- package/dist/client/assets/_vinext_fonts/geist-8ac0455e797f/geist-52306abf.woff2 +0 -0
- package/dist/client/assets/_vinext_fonts/geist-8ac0455e797f/geist-875ccdd4.woff2 +0 -0
- package/dist/client/assets/_vinext_fonts/geist-8ac0455e797f/geist-98bbbccb.woff2 +0 -0
- package/dist/client/assets/_vinext_fonts/geist-8ac0455e797f/geist-ff2310f5.woff2 +0 -0
- package/dist/client/assets/_vinext_fonts/geist-mono-00e989178794/geist-mono-013b2f2f.woff2 +0 -0
- package/dist/client/assets/_vinext_fonts/geist-mono-00e989178794/geist-mono-0638449e.woff2 +0 -0
- package/dist/client/assets/_vinext_fonts/geist-mono-00e989178794/geist-mono-44745446.woff2 +0 -0
- package/dist/client/assets/_vinext_fonts/geist-mono-00e989178794/geist-mono-44e03052.woff2 +0 -0
- package/dist/client/assets/_vinext_fonts/geist-mono-00e989178794/geist-mono-971fb274.woff2 +0 -0
- package/dist/client/assets/_vinext_fonts/geist-mono-00e989178794/geist-mono-f6b33328.woff2 +0 -0
- package/dist/client/assets/addon-fit-BZbxZs2G.js +1 -0
- package/dist/client/assets/framework-CXnKph_e.js +9 -0
- package/dist/client/assets/index-CNnP2Ses.css +2 -0
- package/dist/client/assets/index-Enu1x0PS.js +3 -0
- package/dist/client/assets/layout-segment-context-CmJzExWq.js +1 -0
- package/dist/client/assets/page-COBv6VWj.css +1 -0
- package/dist/client/assets/page-DVjU6VG_.js +550 -0
- package/dist/client/assets/rolldown-runtime-S-ySWqyJ.js +1 -0
- package/dist/client/assets/xterm-BBgU7shl.js +36 -0
- package/dist/client/favicon.svg +6 -0
- package/dist/client/file.svg +1 -0
- package/dist/client/globe.svg +1 -0
- package/dist/client/og.png +0 -0
- package/dist/client/scope-logo.svg +11 -0
- package/dist/client/window.svg +1 -0
- package/dist/server/.vite/manifest.json +14 -0
- package/dist/server/__vite_rsc_assets_manifest.js +49 -0
- package/dist/server/assets/index-CNnP2Ses.css +2 -0
- package/dist/server/image-config.json +1 -0
- package/dist/server/index.js +15201 -0
- package/dist/server/ssr/__vite_rsc_assets_manifest.js +49 -0
- package/dist/server/ssr/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/dist/server/ssr/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/dist/server/ssr/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/dist/server/ssr/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/dist/server/ssr/assets/addon-fit-C09Jj0_f.js +42 -0
- package/dist/server/ssr/assets/error-boundary-Dd2ZYXA8.js +277 -0
- package/dist/server/ssr/assets/layout-segment-context-HV_Mvyzf.js +37 -0
- package/dist/server/ssr/assets/page-COBv6VWj.css +1 -0
- package/dist/server/ssr/assets/page-CYYyCnKD.js +102541 -0
- package/dist/server/ssr/assets/xterm-DgzE4ZZ1.js +10232 -0
- package/dist/server/ssr/index.js +11840 -0
- package/dist/server/ssr/vinext-server.json +1 -0
- package/dist/server/vinext-externals.json +1 -0
- package/dist/server/vinext-server.json +1 -0
- package/dist/server/wrangler.json +1 -0
- package/examples/agents/global-agreements.example.md +10 -0
- package/examples/agents/research-project.example.md +10 -0
- package/examples/agents-media-previews.md +22 -0
- package/examples/deployment.example.json +6 -0
- package/examples/leak-denylist.example.json +10 -0
- package/examples/plugins/hello/index.mjs +4 -0
- package/examples/plugins/hello/scope-plugin.json +13 -0
- package/examples/workbench.config.json +44 -0
- package/lib/account-quota.d.ts +42 -0
- package/lib/account-quota.js +121 -0
- package/lib/browser-snapshot-cache.js +61 -0
- package/lib/conversation-location.js +26 -0
- package/lib/conversation.js +62 -0
- package/lib/dialogue-refresh.js +14 -0
- package/lib/execution-host.js +22 -0
- package/lib/formula-preview.js +48 -0
- package/lib/i18n.tsx +81 -0
- package/lib/incremental-snapshot.js +324 -0
- package/lib/manager-plan.js +37 -0
- package/lib/markdown-images.js +22 -0
- package/lib/markdown-math.js +151 -0
- package/lib/markdown-url.js +13 -0
- package/lib/model-effort.js +13 -0
- package/lib/native-history.d.ts +32 -0
- package/lib/native-history.js +94 -0
- package/lib/overview-delta.js +41 -0
- package/lib/project-view.js +86 -0
- package/lib/projects.js +74 -0
- package/lib/remote-links.js +95 -0
- package/lib/runtime-config.js +70 -0
- package/lib/session-activity.js +34 -0
- package/lib/session-cache-guard.js +52 -0
- package/lib/session-filters.js +38 -0
- package/lib/ssh-config.js +26 -0
- package/lib/stable-order.js +39 -0
- package/lib/workbench-config.js +172 -0
- package/package.json +105 -4
- package/scripts/agent-email-relay.mjs +104 -0
- package/scripts/benchmark-bridge.mjs +38 -0
- package/scripts/cli-integration-smoke.mjs +64 -0
- package/scripts/email-notification-cli.mjs +28 -0
- package/scripts/enable-private-access.ps1 +109 -0
- package/scripts/export-opensource.mjs +112 -0
- package/scripts/fixtures/media/convergence.png +0 -0
- package/scripts/fixtures/media/rollout_demo.mp4 +0 -0
- package/scripts/fixtures/native-conversations.mjs +307 -0
- package/scripts/fixtures/workbench-conversations.mjs +352 -0
- package/scripts/install-remote-server.sh +67 -0
- package/scripts/lib/export-directory.mjs +38 -0
- package/scripts/lib/secret-scanner.mjs +139 -0
- package/scripts/plugin-cli.mjs +19 -0
- package/scripts/preview-workbench.mjs +669 -0
- package/scripts/probe-antigravity-acp.mjs +35 -0
- package/scripts/remote-bootstrap-cli.mjs +52 -0
- package/scripts/remote-email-tool.py +383 -0
|
@@ -0,0 +1,3332 @@
|
|
|
1
|
+
import { loadDeploymentProfile } from "./deployment-profile.mjs";
|
|
2
|
+
import { nativeSessionState } from "./providers/native-session-state.mjs";
|
|
3
|
+
import { idleSessionTimeout, startIdleSessionReaper } from "./idle-sessions.mjs";
|
|
4
|
+
import { submissionSettingsRoutes } from "./submissions/settings.mjs";
|
|
5
|
+
import { PluginRegistry } from "./plugins/registry.mjs";
|
|
6
|
+
import { loadExternalPlugins } from "./plugins/external.mjs";
|
|
7
|
+
import { pluginRoutes } from "./plugins/routes.mjs";
|
|
8
|
+
import { createAliyunDlcPlugin } from "./plugins/aliyun-dlc/index.mjs";
|
|
9
|
+
const deployment = loadDeploymentProfile();
|
|
10
|
+
import { SessionCatalog } from "./session-catalog/catalog.mjs";
|
|
11
|
+
import { catalogRoutes } from "./session-catalog/routes.mjs";
|
|
12
|
+
import { NativeModels } from "./providers/native-models.mjs";
|
|
13
|
+
import { NativeCommands } from "./providers/native-commands.mjs";
|
|
14
|
+
import { sessionCommandRoutes } from "./routes/session-commands.mjs";
|
|
15
|
+
import { CliConversations } from "./providers/conversations.mjs";
|
|
16
|
+
import { cliConversationRoutes } from "./providers/conversation-routes.mjs";
|
|
17
|
+
import { AgentMaintenance } from "./maintenance/service.mjs";
|
|
18
|
+
import { maintenanceRoutes } from "./maintenance/routes.mjs";
|
|
19
|
+
import { localHistoryReader } from "./local/history.mjs";
|
|
20
|
+
import { LOCAL_HOST } from "../lib/execution-host.js";
|
|
21
|
+
import { LocalCodexRuntime } from "./local/runtime.mjs";
|
|
22
|
+
import { localDirectories, localDirectory } from "./local/directories.mjs";
|
|
23
|
+
import { sessionArchiveService } from "./archive/service.mjs";
|
|
24
|
+
import { archiveRoutes } from "./archive/routes.mjs";
|
|
25
|
+
import { createSshCommand, shellQuote } from "./transport/ssh-command.mjs";
|
|
26
|
+
import { readJsonBody, jsonResponse, requestHandler } from "./http.mjs";
|
|
27
|
+
import { modelRoutes } from './routes/models.mjs';
|
|
28
|
+
import { dialogueRoutes } from './routes/dialogue.mjs';
|
|
29
|
+
import { runtimeRoutes } from './routes/runtime.mjs';
|
|
30
|
+
import { authRoutes } from './routes/accounts.mjs';
|
|
31
|
+
import { emailRoutes } from "./routes/email.mjs";
|
|
32
|
+
import { systemRoutes } from "./routes/system.mjs";
|
|
33
|
+
import { sessionLifecycleRoutes } from "./routes/session-lifecycle.mjs";
|
|
34
|
+
import { managementRoutes } from "./routes/management.mjs";
|
|
35
|
+
import { sessionDeliveryRoutes } from "./routes/session-delivery.mjs";
|
|
36
|
+
import { RemoteTunnelManager } from "./remote-bootstrap/tunnels.mjs";
|
|
37
|
+
import { RemoteBootstrapService } from "./remote-bootstrap/service.mjs";
|
|
38
|
+
import { remoteBootstrapRoutes } from "./remote-bootstrap/routes.mjs";
|
|
39
|
+
import { PROFILE_LIST_PROBE, PROFILE_WRITE_PROBE, PROFILE_CANCEL_PROBE, PROFILE_DELETE_PROBE, REMOTE_PROBE, DIALOGUE_PROBE, RAW_CONTEXT_PROBE, TAKEOVER_PROBE, APP_SERVER_WRITER_PROBE } from './probes/index.mjs';
|
|
40
|
+
import { REMOTE_DIRECTORY_PROBE } from "./workbench/directory-probe.mjs";
|
|
41
|
+
import { spawn } from "node:child_process";
|
|
42
|
+
import { randomUUID } from "node:crypto";
|
|
43
|
+
import { createServer } from "node:http";
|
|
44
|
+
import { WorkbenchStore } from "./workbench/store.mjs";
|
|
45
|
+
import { directoryRoutes } from "./workbench/directory-routes.mjs";
|
|
46
|
+
import { conversationRoutes } from "./workbench/conversation-routes.mjs";
|
|
47
|
+
import { WorkbenchService } from "./workbench/service.mjs";
|
|
48
|
+
import { workbenchRoutes } from "./workbench/routes.mjs";
|
|
49
|
+
import { remoteCliAdapter } from "./providers/remote-cli.mjs";
|
|
50
|
+
import { codexWorkbenchAdapter } from "./providers/codex-workbench.mjs";
|
|
51
|
+
import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
52
|
+
import os from "node:os";
|
|
53
|
+
import path from "node:path";
|
|
54
|
+
import {
|
|
55
|
+
AppServerManager,
|
|
56
|
+
JsonlAppServerConnection,
|
|
57
|
+
isAuthenticationRefreshError,
|
|
58
|
+
} from "./app-server-client.mjs";
|
|
59
|
+
import { WebSocketJsonlChild } from "./app-server-websocket-transport.mjs";
|
|
60
|
+
import { remoteResumeValidator } from "./remote-rollout-locks.mjs";
|
|
61
|
+
import { profileCapacityRetryDelays } from "./profile-capacity-policy.mjs";
|
|
62
|
+
import { HostSessionRestarts } from "./host-session-restart.mjs";
|
|
63
|
+
import {
|
|
64
|
+
CodexUpgrades,
|
|
65
|
+
parseCodexUpgradeOutput,
|
|
66
|
+
remoteCodexUpgradeScript,
|
|
67
|
+
stableVersion,
|
|
68
|
+
wrapCodexUpgradeCommand,
|
|
69
|
+
} from "./codex-upgrade.mjs";
|
|
70
|
+
import { SessionProfileAssignments, sessionProfileKey, profileFromConnection, boundConnectionKey, profileHandoffPending } from "./session-profiles.mjs";
|
|
71
|
+
import { modelCatalogTarget, modelCatalogHomeCommands } from "./model-catalog.mjs";
|
|
72
|
+
import {
|
|
73
|
+
emptyGpuUsageHistory,
|
|
74
|
+
updateGpuUsageHistory,
|
|
75
|
+
} from "./gpu-usage-history.mjs";
|
|
76
|
+
import {
|
|
77
|
+
createEmailNotifier,
|
|
78
|
+
dlcAlertEmailEvent,
|
|
79
|
+
humanRequestEmailEvent,
|
|
80
|
+
} from "./email-notifier.mjs";
|
|
81
|
+
import {
|
|
82
|
+
AuthProfileManager,
|
|
83
|
+
normalizeProfileName,
|
|
84
|
+
} from "./auth-profile-manager.mjs";
|
|
85
|
+
import {
|
|
86
|
+
markProfileUnavailable,
|
|
87
|
+
orderedReadyProfileCandidates,
|
|
88
|
+
publicProfileFailoverJob,
|
|
89
|
+
} from "./auth-profile-failover.mjs";
|
|
90
|
+
import { createIncrementalSnapshotStore } from "../lib/incremental-snapshot.js";
|
|
91
|
+
import { preserveHostSessions } from "../lib/session-cache-guard.js";
|
|
92
|
+
import { guardPersistentCodexHome } from "./persistent-home-guard.mjs";
|
|
93
|
+
import { sshAliasesForHostname } from "../lib/ssh-config.js";
|
|
94
|
+
import {
|
|
95
|
+
normalizeHostRuntimeConfig,
|
|
96
|
+
runtimePolicy,
|
|
97
|
+
} from "../lib/runtime-config.js";
|
|
98
|
+
import {
|
|
99
|
+
durableRemoteAppServerCommand,
|
|
100
|
+
retireProfileAppServerCommand,
|
|
101
|
+
retireScopedAppServerCommand,
|
|
102
|
+
wrapBootstrapAppServer,
|
|
103
|
+
} from "./remote-app-server-command.mjs";
|
|
104
|
+
import {
|
|
105
|
+
createAgentEnricher,
|
|
106
|
+
heuristicSummary,
|
|
107
|
+
historicalAgent,
|
|
108
|
+
} from "./rollout-summary.mjs";
|
|
109
|
+
import { createStatePersistence } from "./state-persistence.mjs";
|
|
110
|
+
import { createAttachmentStore } from "./attachment-store.mjs";
|
|
111
|
+
import { createResearchInsights } from "./research/insights.mjs";
|
|
112
|
+
import { createTmuxDelivery } from "./tmux-delivery.mjs";
|
|
113
|
+
import {
|
|
114
|
+
cleanSshError,
|
|
115
|
+
createInventoryScanner,
|
|
116
|
+
mapLimit,
|
|
117
|
+
parseSshAliases,
|
|
118
|
+
} from "./inventory-scanner.mjs";
|
|
119
|
+
import { attachTerminalGateway } from "./terminal-gateway.mjs";
|
|
120
|
+
import {
|
|
121
|
+
createAccountQuotaService,
|
|
122
|
+
readLocalAuthProfiles,
|
|
123
|
+
} from "./account-quotas.mjs";
|
|
124
|
+
|
|
125
|
+
const PORT = Number(process.env.SCOPE_BRIDGE_PORT || 4815);
|
|
126
|
+
const UI_PORT = Number(process.env.SCOPE_UI_PORT || 3000);
|
|
127
|
+
const HOST = "127.0.0.1";
|
|
128
|
+
const TRUSTED_BROWSER_ORIGINS = new Set([
|
|
129
|
+
"http://localhost:3000",
|
|
130
|
+
"http://127.0.0.1:3000",
|
|
131
|
+
"http://[::1]:3000",
|
|
132
|
+
`http://localhost:${UI_PORT}`,
|
|
133
|
+
`http://127.0.0.1:${UI_PORT}`,
|
|
134
|
+
`http://[::1]:${UI_PORT}`,
|
|
135
|
+
]);
|
|
136
|
+
const SSH_CONFIG =
|
|
137
|
+
process.env.SCOPE_SSH_CONFIG || path.join(os.homedir(), ".ssh", "config");
|
|
138
|
+
const POLL_MS = Math.max(5_000, Number(process.env.SCOPE_POLL_MS || 15_000));
|
|
139
|
+
const SSH_TIMEOUT_MS = Math.max(
|
|
140
|
+
2_000,
|
|
141
|
+
Number(process.env.SCOPE_SSH_TIMEOUT_MS || 7_000),
|
|
142
|
+
);
|
|
143
|
+
const INVENTORY_TIMEOUT_MS = Math.max(
|
|
144
|
+
10_000,
|
|
145
|
+
Number(process.env.SCOPE_INVENTORY_TIMEOUT_MS || 20_000),
|
|
146
|
+
);
|
|
147
|
+
const INVENTORY_STALE_GRACE_MS = Math.max(
|
|
148
|
+
60_000,
|
|
149
|
+
Number(process.env.SCOPE_INVENTORY_STALE_GRACE_MS || 10 * 60_000),
|
|
150
|
+
);
|
|
151
|
+
const CONCURRENCY = Math.max(
|
|
152
|
+
1,
|
|
153
|
+
Math.min(12, Number(process.env.SCOPE_CONCURRENCY || 6)),
|
|
154
|
+
);
|
|
155
|
+
const STATE_DIR = process.env.SCOPE_STATE_DIR
|
|
156
|
+
? path.resolve(process.env.SCOPE_STATE_DIR)
|
|
157
|
+
: path.resolve(process.cwd(), ".scope");
|
|
158
|
+
const localCodex = new LocalCodexRuntime(STATE_DIR);
|
|
159
|
+
const persistentCodexHomes = JSON.parse(await readFile(path.join(STATE_DIR, "persistent-codex-homes.json"), "utf8").catch(error => {
|
|
160
|
+
if (error.code === "ENOENT") return "{}";
|
|
161
|
+
throw error;
|
|
162
|
+
}));
|
|
163
|
+
const STATE_FILE = path.join(STATE_DIR, "state.json");
|
|
164
|
+
const GPU_USAGE_HISTORY_FILE = path.join(STATE_DIR, "gpu-usage-history.json");
|
|
165
|
+
const SNAPSHOT_CACHE_FILE = path.join(STATE_DIR, "snapshot-cache.json");
|
|
166
|
+
const HISTORY_INDEX_FILE = path.join(STATE_DIR, "history-index.json");
|
|
167
|
+
const AUTH_RESTART_JOBS_FILE = path.join(STATE_DIR, "auth-restart-jobs.json");
|
|
168
|
+
const APP_SERVER_SESSIONS_FILE = path.join(
|
|
169
|
+
STATE_DIR,
|
|
170
|
+
"app-server-sessions.json",
|
|
171
|
+
);
|
|
172
|
+
const LIFECYCLE_AUDIT_FILE = path.join(STATE_DIR, "lifecycle-audit.jsonl");
|
|
173
|
+
const EMAIL_NOTIFICATION_CONFIG_FILE = path.join(
|
|
174
|
+
STATE_DIR,
|
|
175
|
+
"email-notifications.json",
|
|
176
|
+
);
|
|
177
|
+
const EMAIL_NOTIFICATION_STATE_FILE = path.join(
|
|
178
|
+
STATE_DIR,
|
|
179
|
+
"email-notification-state.json",
|
|
180
|
+
);
|
|
181
|
+
const SUMMARY_TIMEOUT_MS = Math.max(
|
|
182
|
+
20_000,
|
|
183
|
+
Number(process.env.SCOPE_SUMMARY_TIMEOUT_MS || 75_000),
|
|
184
|
+
);
|
|
185
|
+
const DIALOGUE_TIMEOUT_MS = Math.max(
|
|
186
|
+
10_000,
|
|
187
|
+
Number(process.env.SCOPE_DIALOGUE_TIMEOUT_MS || 30_000),
|
|
188
|
+
);
|
|
189
|
+
const HISTORY_TIMEOUT_MS = Math.max(
|
|
190
|
+
20_000,
|
|
191
|
+
Number(process.env.SCOPE_HISTORY_TIMEOUT_MS || 60_000),
|
|
192
|
+
);
|
|
193
|
+
const ASSISTANT_SEARCH_TIMEOUT_MS = Math.max(
|
|
194
|
+
20_000,
|
|
195
|
+
Number(process.env.SCOPE_ASSISTANT_SEARCH_TIMEOUT_MS || 45_000),
|
|
196
|
+
);
|
|
197
|
+
const ASSISTANT_CODEX_TIMEOUT_MS = Math.max(
|
|
198
|
+
20_000,
|
|
199
|
+
Number(process.env.SCOPE_ASSISTANT_CODEX_TIMEOUT_MS || 120_000),
|
|
200
|
+
);
|
|
201
|
+
const DEFAULT_SUBMISSION_WINDOW_DAYS = Math.max(
|
|
202
|
+
1,
|
|
203
|
+
Math.min(365, Number(process.env.SCOPE_SUBMISSION_WINDOW_DAYS || 1)),
|
|
204
|
+
);
|
|
205
|
+
const TAKEOVER_TIMEOUT_MS = Math.max(
|
|
206
|
+
15_000,
|
|
207
|
+
Number(process.env.SCOPE_TAKEOVER_TIMEOUT_MS || 30_000),
|
|
208
|
+
);
|
|
209
|
+
const APP_SERVER_TIMEOUT_MS = Math.max(
|
|
210
|
+
15_000,
|
|
211
|
+
Number(process.env.SCOPE_APP_SERVER_TIMEOUT_MS || 45_000),
|
|
212
|
+
);
|
|
213
|
+
const AUTH_LOGIN_TIMEOUT_MS = Math.max(
|
|
214
|
+
30_000,
|
|
215
|
+
Number(process.env.SCOPE_AUTH_LOGIN_TIMEOUT_MS || 120_000),
|
|
216
|
+
);
|
|
217
|
+
const ATTACHMENT_TTL_MS = 6 * 60 * 60 * 1_000;
|
|
218
|
+
const ATTACHMENT_UPLOAD_TIMEOUT_MS = 2 * 60 * 1_000;
|
|
219
|
+
const AUTH_PROFILE_FAILOVER_WAIT_MS = Math.max(
|
|
220
|
+
2_000,
|
|
221
|
+
Number(process.env.SCOPE_AUTH_PROFILE_FAILOVER_WAIT_MS || 5_000),
|
|
222
|
+
);
|
|
223
|
+
const PROXY_BOOTSTRAP_HOSTS = new Set(deployment.proxyBootstrapHosts);
|
|
224
|
+
|
|
225
|
+
let snapshot = {
|
|
226
|
+
generatedAt: null,
|
|
227
|
+
scanning: true,
|
|
228
|
+
cached: false,
|
|
229
|
+
cacheSavedAt: null,
|
|
230
|
+
sshConfig: SSH_CONFIG,
|
|
231
|
+
hosts: [localCodex.host()],
|
|
232
|
+
summary: { hosts: 0, online: 0, codex: 0, tmux: 0, attention: 0 },
|
|
233
|
+
management: null,
|
|
234
|
+
};
|
|
235
|
+
let scanPromise = null;
|
|
236
|
+
let authRestartWritePromise = Promise.resolve();
|
|
237
|
+
let appServerSessionWritePromise = Promise.resolve();
|
|
238
|
+
let lifecycleAuditWritePromise = Promise.resolve();
|
|
239
|
+
const persistedAppServerSessions = new Map();
|
|
240
|
+
let appServerSessionsLoaded = false;
|
|
241
|
+
let appServerRestorePromise = null;
|
|
242
|
+
const appServerRestoreFailures = new Map();
|
|
243
|
+
const appServerReconnectTimers = new Map();
|
|
244
|
+
const appServerReconnectAttempts = new Map();
|
|
245
|
+
const appServerReconnectInFlight = new Set();
|
|
246
|
+
const appServerHostRecoveryJobs = new Map();
|
|
247
|
+
const appServerAuthRecoveryJobs = new Map();
|
|
248
|
+
const appServerAuthRecoveryHosts = new Set();
|
|
249
|
+
const appServerActiveAuthFailoverJobs = new Map();
|
|
250
|
+
const authProfileFailedUntil = new Map();
|
|
251
|
+
|
|
252
|
+
function auditLifecycle(action, details = {}) {
|
|
253
|
+
const line = `${JSON.stringify({
|
|
254
|
+
timestamp: new Date().toISOString(),
|
|
255
|
+
action,
|
|
256
|
+
...details,
|
|
257
|
+
})}\n`;
|
|
258
|
+
lifecycleAuditWritePromise = lifecycleAuditWritePromise
|
|
259
|
+
.catch(() => {})
|
|
260
|
+
.then(async () => {
|
|
261
|
+
await mkdir(STATE_DIR, { recursive: true });
|
|
262
|
+
await appendFile(LIFECYCLE_AUDIT_FILE, line, "utf8");
|
|
263
|
+
})
|
|
264
|
+
.catch((error) =>
|
|
265
|
+
console.error(`lifecycle audit 写入失败:${error.message}`),
|
|
266
|
+
);
|
|
267
|
+
return lifecycleAuditWritePromise;
|
|
268
|
+
}
|
|
269
|
+
const sshOperationCounts = new Map();
|
|
270
|
+
const inventoryOperations = new Map();
|
|
271
|
+
const hostFailureStreaks = new Map();
|
|
272
|
+
const hostNextScanAt = new Map();
|
|
273
|
+
|
|
274
|
+
const clients = new Map();
|
|
275
|
+
const snapshotSyncStore = createIncrementalSnapshotStore({
|
|
276
|
+
epoch: randomUUID(),
|
|
277
|
+
maxHistory: 32,
|
|
278
|
+
maxHistoryBytes: 16 * 1024 * 1024,
|
|
279
|
+
});
|
|
280
|
+
let snapshotNotifyTimer = null;
|
|
281
|
+
const takeoverHostQueues = new Map();
|
|
282
|
+
const authRestartJobs = new Map();
|
|
283
|
+
const historicalSessions = new Map();
|
|
284
|
+
let historyIndex = {
|
|
285
|
+
version: 1,
|
|
286
|
+
updatedAt: null,
|
|
287
|
+
hosts: {},
|
|
288
|
+
};
|
|
289
|
+
const plugins = new PluginRegistry();
|
|
290
|
+
const aliyunPlugin = createAliyunDlcPlugin({
|
|
291
|
+
stateDirectory: STATE_DIR, legacyHost: deployment.dlcHostname,
|
|
292
|
+
defaultWindowDays: DEFAULT_SUBMISSION_WINDOW_DAYS,
|
|
293
|
+
context: () => ({ readSshConfig: () => readFile(SSH_CONFIG, "utf8"), sshAliasesForHostname,
|
|
294
|
+
getSnapshot: () => snapshot, runSshCommand, cleanSshError, mapLimit, findAgent,
|
|
295
|
+
getManagement: () => managementState, sessionKey, heuristicSummary }),
|
|
296
|
+
notify: notifyClients, onScanComplete: syncDlcAlertNotifications,
|
|
297
|
+
});
|
|
298
|
+
plugins.register(aliyunPlugin);
|
|
299
|
+
loadExternalPlugins(plugins, STATE_DIR);
|
|
300
|
+
|
|
301
|
+
let gpuUsageHistory = emptyGpuUsageHistory();
|
|
302
|
+
let managementState = {
|
|
303
|
+
operatorName: "Operator",
|
|
304
|
+
sessions: {},
|
|
305
|
+
projects: [],
|
|
306
|
+
hostRuntimeConfigs: {},
|
|
307
|
+
resourcePolicy: {
|
|
308
|
+
prompt: "",
|
|
309
|
+
updatedAt: null,
|
|
310
|
+
version: 0,
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
function defaultHostRuntimeConfig(host) {
|
|
315
|
+
return normalizeHostRuntimeConfig({
|
|
316
|
+
preLaunchCommand: PROXY_BOOTSTRAP_HOSTS.has(host) ? (process.env.SCOPE_HOST_BOOTSTRAP_COMMAND?.trim() || "") : "",
|
|
317
|
+
yolo: true,
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function hostRuntimeConfig(host, override = null) {
|
|
322
|
+
const stored = normalizeHostRuntimeConfig(
|
|
323
|
+
managementState.hostRuntimeConfigs?.[host],
|
|
324
|
+
defaultHostRuntimeConfig(host),
|
|
325
|
+
);
|
|
326
|
+
return normalizeHostRuntimeConfig(override, stored);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function sessionYolo(rollout, fallback = true) {
|
|
330
|
+
if (
|
|
331
|
+
rollout?.approvalPolicy === "never" &&
|
|
332
|
+
["danger-full-access", "dangerFullAccess"].includes(
|
|
333
|
+
rollout?.sandboxPolicy,
|
|
334
|
+
)
|
|
335
|
+
) {
|
|
336
|
+
return true;
|
|
337
|
+
}
|
|
338
|
+
if (rollout?.approvalPolicy || rollout?.sandboxPolicy) return false;
|
|
339
|
+
return fallback !== false;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async function saveHostRuntimeConfig(host, value) {
|
|
343
|
+
const config = {
|
|
344
|
+
...hostRuntimeConfig(host, value),
|
|
345
|
+
updatedAt: new Date().toISOString(),
|
|
346
|
+
};
|
|
347
|
+
managementState = {
|
|
348
|
+
...managementState,
|
|
349
|
+
hostRuntimeConfigs: {
|
|
350
|
+
...managementState.hostRuntimeConfigs,
|
|
351
|
+
[host]: config,
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
await persistManagementState();
|
|
355
|
+
notifyClients();
|
|
356
|
+
return config;
|
|
357
|
+
}
|
|
358
|
+
const emailNotifier = await createEmailNotifier({
|
|
359
|
+
configPath: EMAIL_NOTIFICATION_CONFIG_FILE,
|
|
360
|
+
statePath: EMAIL_NOTIFICATION_STATE_FILE,
|
|
361
|
+
});
|
|
362
|
+
let humanRequestNotificationsPrimed = false;
|
|
363
|
+
let dlcAlertNotificationsPrimed = false;
|
|
364
|
+
|
|
365
|
+
function sessionKey(host, sessionId) {
|
|
366
|
+
return `${host}:${sessionId}`;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function withTakeoverHostQueue(host, operation) {
|
|
370
|
+
const previous = takeoverHostQueues.get(host) || Promise.resolve();
|
|
371
|
+
let release;
|
|
372
|
+
const turn = new Promise((resolve) => {
|
|
373
|
+
release = resolve;
|
|
374
|
+
});
|
|
375
|
+
const tail = previous.catch(() => {}).then(() => turn);
|
|
376
|
+
takeoverHostQueues.set(host, tail);
|
|
377
|
+
await previous.catch(() => {});
|
|
378
|
+
try {
|
|
379
|
+
return await operation();
|
|
380
|
+
} finally {
|
|
381
|
+
release();
|
|
382
|
+
if (takeoverHostQueues.get(host) === tail) {
|
|
383
|
+
takeoverHostQueues.delete(host);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const enrichAgentRelations = createAgentEnricher({
|
|
389
|
+
getSubmissionItems: () => aliyunPlugin.snapshot().items,
|
|
390
|
+
});
|
|
391
|
+
const {
|
|
392
|
+
storeUploadedAttachment,
|
|
393
|
+
resolveUploadedAttachments,
|
|
394
|
+
streamAttachmentToHost,
|
|
395
|
+
} = createAttachmentStore({
|
|
396
|
+
cleanSshError,
|
|
397
|
+
inventoryOperations,
|
|
398
|
+
sshOperationCounts,
|
|
399
|
+
SSH_TIMEOUT_MS,
|
|
400
|
+
ATTACHMENT_TTL_MS,
|
|
401
|
+
ATTACHMENT_UPLOAD_TIMEOUT_MS,
|
|
402
|
+
});
|
|
403
|
+
const { runSsh, parseHost } = createInventoryScanner({
|
|
404
|
+
REMOTE_PROBE,
|
|
405
|
+
shellQuote,
|
|
406
|
+
guardPersistentCodexHome,
|
|
407
|
+
persistentCodexHomes,
|
|
408
|
+
SSH_TIMEOUT_MS,
|
|
409
|
+
INVENTORY_TIMEOUT_MS,
|
|
410
|
+
inventoryOperations,
|
|
411
|
+
spawn,
|
|
412
|
+
heuristicSummary,
|
|
413
|
+
preserveHostSessions,
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
function publicGpuUsage(hosts) {
|
|
417
|
+
const episodes = gpuUsageHistory.episodes.map((episode) => {
|
|
418
|
+
const host = hosts.find((candidate) => candidate.alias === episode.host);
|
|
419
|
+
const agent = host?.agents.find(
|
|
420
|
+
(candidate) => candidate.rollout?.id === episode.ownerSessionId,
|
|
421
|
+
);
|
|
422
|
+
const session = host?.sessions.find(
|
|
423
|
+
(candidate) => candidate.id === episode.ownerSessionId,
|
|
424
|
+
);
|
|
425
|
+
const managed = episode.ownerSessionId
|
|
426
|
+
? managementState.sessions[
|
|
427
|
+
sessionKey(episode.host, episode.ownerSessionId)
|
|
428
|
+
] || {}
|
|
429
|
+
: {};
|
|
430
|
+
return {
|
|
431
|
+
...episode,
|
|
432
|
+
sessionTheme:
|
|
433
|
+
managed.displayName ||
|
|
434
|
+
managed.summary?.theme ||
|
|
435
|
+
agent?.suggestedSummary?.theme ||
|
|
436
|
+
episode.sessionTheme ||
|
|
437
|
+
session?.lastUser ||
|
|
438
|
+
"",
|
|
439
|
+
sessionCwd:
|
|
440
|
+
agent?.cwd || session?.cwd || episode.sessionCwd || episode.cwd,
|
|
441
|
+
sessionActive: Boolean(agent),
|
|
442
|
+
};
|
|
443
|
+
});
|
|
444
|
+
return {
|
|
445
|
+
updatedAt: gpuUsageHistory.updatedAt,
|
|
446
|
+
retentionHours: gpuUsageHistory.retentionHours,
|
|
447
|
+
episodes,
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function publicSnapshot() {
|
|
452
|
+
const appServer = appServerManager.publicState();
|
|
453
|
+
appServer.sessions = appServer.sessions.map((session) => ({ ...session,
|
|
454
|
+
profileAssignment: sessionProfileAssignment(session.host, session.sessionId),
|
|
455
|
+
}));
|
|
456
|
+
appServer.restorePending = Array.from(persistedAppServerSessions.values())
|
|
457
|
+
.filter(
|
|
458
|
+
(record) =>
|
|
459
|
+
!appServerManager.isManaged(record.host, record.sessionId),
|
|
460
|
+
)
|
|
461
|
+
.map((record) => {
|
|
462
|
+
const failure = appServerRestoreFailures.get(
|
|
463
|
+
sessionKey(record.host, record.sessionId),
|
|
464
|
+
);
|
|
465
|
+
return {
|
|
466
|
+
host: record.host,
|
|
467
|
+
sessionId: record.sessionId,
|
|
468
|
+
cwd: record.cwd,
|
|
469
|
+
error: failure?.error || null,
|
|
470
|
+
attempt: failure?.attempt || 0,
|
|
471
|
+
retryAt: failure?.retryAt
|
|
472
|
+
? new Date(failure.retryAt).toISOString()
|
|
473
|
+
: null,
|
|
474
|
+
};
|
|
475
|
+
});
|
|
476
|
+
const hosts = snapshot.hosts.map((host) => ({
|
|
477
|
+
...host,
|
|
478
|
+
agents: host.agents.filter(agent => !["archived", "restoring"].includes(managementState.sessions[sessionKey(host.alias, agent.rollout?.id)]?.archive?.phase)).map((agent) => ({
|
|
479
|
+
...agent,
|
|
480
|
+
mapping: { ...agent.mapping },
|
|
481
|
+
capacityRecovery: publicTmuxCapacityRecovery(agent),
|
|
482
|
+
})),
|
|
483
|
+
}));
|
|
484
|
+
for (const managed of appServer.sessions) {
|
|
485
|
+
const host = hosts.find((candidate) => candidate.alias === managed.host);
|
|
486
|
+
if (!host) continue;
|
|
487
|
+
const existing = host.agents.find(
|
|
488
|
+
(agent) => agent.rollout?.id === managed.sessionId,
|
|
489
|
+
);
|
|
490
|
+
if (existing) {
|
|
491
|
+
existing.appServerManaged = true;
|
|
492
|
+
existing.transport = "app-server";
|
|
493
|
+
existing.status =
|
|
494
|
+
managed.status === "offline" ? "attention" : managed.status;
|
|
495
|
+
existing.capacityRecovery = managed.capacityRecovery || null;
|
|
496
|
+
if (existing.rollout) {
|
|
497
|
+
const policy = runtimePolicy(managed.yolo);
|
|
498
|
+
existing.rollout = {
|
|
499
|
+
...existing.rollout,
|
|
500
|
+
model: managed.model || existing.rollout.model || "",
|
|
501
|
+
reasoningEffort:
|
|
502
|
+
managed.effort || existing.rollout.reasoningEffort || "",
|
|
503
|
+
approvalPolicy: policy.approvalPolicy,
|
|
504
|
+
sandboxPolicy: policy.sandbox,
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
const storedRollout = host.sessions.find(
|
|
510
|
+
(session) => session.id === managed.sessionId,
|
|
511
|
+
);
|
|
512
|
+
const managedPolicy = runtimePolicy(managed.yolo);
|
|
513
|
+
const rollout = storedRollout
|
|
514
|
+
? {
|
|
515
|
+
...storedRollout,
|
|
516
|
+
model: managed.model || storedRollout.model || "",
|
|
517
|
+
reasoningEffort:
|
|
518
|
+
managed.effort || storedRollout.reasoningEffort || "",
|
|
519
|
+
approvalPolicy: managedPolicy.approvalPolicy,
|
|
520
|
+
sandboxPolicy: managedPolicy.sandbox,
|
|
521
|
+
}
|
|
522
|
+
: {
|
|
523
|
+
id: managed.sessionId,
|
|
524
|
+
rootSessionId: managed.sessionId,
|
|
525
|
+
cwd: managed.cwd || "",
|
|
526
|
+
path: managed.path || null,
|
|
527
|
+
model: managed.model || "",
|
|
528
|
+
reasoningEffort: managed.effort || "",
|
|
529
|
+
approvalPolicy: managedPolicy.approvalPolicy,
|
|
530
|
+
sandboxPolicy: managedPolicy.sandbox,
|
|
531
|
+
mtimeMs:
|
|
532
|
+
Date.parse(managed.lastEventAt || managed.connectedAt) || Date.now(),
|
|
533
|
+
startedAt: managed.connectedAt,
|
|
534
|
+
lastEventAt: managed.lastEventAt,
|
|
535
|
+
firstUser: "",
|
|
536
|
+
lastUser: "",
|
|
537
|
+
lastAssistant: "",
|
|
538
|
+
lastAction: "",
|
|
539
|
+
lastError: "",
|
|
540
|
+
userMessages: [],
|
|
541
|
+
assistantMessages: [],
|
|
542
|
+
launches: [],
|
|
543
|
+
turnState: managed.status,
|
|
544
|
+
};
|
|
545
|
+
host.agents.push({
|
|
546
|
+
id: `app-server:${host.alias}:${managed.sessionId}`,
|
|
547
|
+
host: host.alias,
|
|
548
|
+
hostname: host.hostname,
|
|
549
|
+
pid: 0,
|
|
550
|
+
tty: "app-server",
|
|
551
|
+
cwd: managed.cwd || rollout.cwd,
|
|
552
|
+
executable: "codex",
|
|
553
|
+
elapsedSeconds: 0,
|
|
554
|
+
status: managed.status === "offline" ? "attention" : managed.status,
|
|
555
|
+
pane: null,
|
|
556
|
+
rollout,
|
|
557
|
+
subagents: [],
|
|
558
|
+
historical: false,
|
|
559
|
+
appServerManaged: true,
|
|
560
|
+
transport: "app-server",
|
|
561
|
+
capacityRecovery: managed.capacityRecovery || null,
|
|
562
|
+
mapping: {
|
|
563
|
+
rollout: "app-server",
|
|
564
|
+
tmux: "unmatched",
|
|
565
|
+
},
|
|
566
|
+
lastActivityAt:
|
|
567
|
+
Date.parse(managed.lastEventAt || managed.connectedAt) ||
|
|
568
|
+
rollout.mtimeMs,
|
|
569
|
+
suggestedSummary: heuristicSummary(rollout, managed.cwd || rollout.cwd),
|
|
570
|
+
title:
|
|
571
|
+
rollout.lastUser ||
|
|
572
|
+
`App-server · ${path.posix.basename(managed.cwd || rollout.cwd)}`,
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
for (const host of hosts) {
|
|
576
|
+
host.agents = host.agents.map((agent) => enrichAgentRelations(host, agent));
|
|
577
|
+
}
|
|
578
|
+
const allAgents = hosts.flatMap((host) => host.agents);
|
|
579
|
+
const effectiveRuntimeConfigs = Object.fromEntries(
|
|
580
|
+
hosts.map((host) => [host.alias, hostRuntimeConfig(host.alias)]),
|
|
581
|
+
);
|
|
582
|
+
return {
|
|
583
|
+
...snapshot,
|
|
584
|
+
hosts,
|
|
585
|
+
summary: {
|
|
586
|
+
...snapshot.summary,
|
|
587
|
+
codex: allAgents.length,
|
|
588
|
+
attention: allAgents.filter((agent) => agent.status === "attention")
|
|
589
|
+
.length,
|
|
590
|
+
},
|
|
591
|
+
management: {
|
|
592
|
+
...managementState,
|
|
593
|
+
hostRuntimeConfigs: effectiveRuntimeConfigs,
|
|
594
|
+
},
|
|
595
|
+
appServer,
|
|
596
|
+
submissionTracker: aliyunPlugin.snapshot(),
|
|
597
|
+
gpuUsage: publicGpuUsage(hosts),
|
|
598
|
+
notifications: {
|
|
599
|
+
email: emailNotifier.publicState(),
|
|
600
|
+
},
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function findLiveAgent(host, sessionId) {
|
|
605
|
+
const direct = snapshot.hosts
|
|
606
|
+
.find((candidate) => candidate.alias === host)
|
|
607
|
+
?.agents.find((agent) => agent.rollout?.id === sessionId);
|
|
608
|
+
if (direct) return direct;
|
|
609
|
+
const managed = publicSnapshot()
|
|
610
|
+
.hosts.find((candidate) => candidate.alias === host)
|
|
611
|
+
?.agents.find((agent) => agent.rollout?.id === sessionId);
|
|
612
|
+
if (managed) return managed;
|
|
613
|
+
return null;
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
function findAgent(host, sessionId) {
|
|
617
|
+
const live = findLiveAgent(host, sessionId);
|
|
618
|
+
if (live) return live;
|
|
619
|
+
return historicalSessions.get(sessionKey(host, sessionId));
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
function temporaryRemoteCwd(value) {
|
|
623
|
+
return /^\/(?:tmp|var\/tmp)(?:\/|$)/.test(String(value || ""));
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
async function recoveryAgent(agent, activeAgent, requestedCwd) {
|
|
627
|
+
if (activeAgent) return agent;
|
|
628
|
+
const cwd = typeof requestedCwd === "string" ? requestedCwd.trim() : "";
|
|
629
|
+
if (!cwd) {
|
|
630
|
+
const error = new Error(
|
|
631
|
+
"历史 Session 必须明确选择新的恢复工作目录;不会使用 rollout 中记录的旧目录",
|
|
632
|
+
);
|
|
633
|
+
error.statusCode = 400;
|
|
634
|
+
throw error;
|
|
635
|
+
}
|
|
636
|
+
if (temporaryRemoteCwd(cwd)) {
|
|
637
|
+
const error = new Error(
|
|
638
|
+
`拒绝恢复到临时目录 ${cwd};请选择持久项目目录或 recovery worktree`,
|
|
639
|
+
);
|
|
640
|
+
error.statusCode = 400;
|
|
641
|
+
throw error;
|
|
642
|
+
}
|
|
643
|
+
const preflight = await runSshCommand(
|
|
644
|
+
agent.host,
|
|
645
|
+
`python3 - ${shellQuote(cwd)}`,
|
|
646
|
+
NEW_SESSION_PREFLIGHT,
|
|
647
|
+
15_000,
|
|
648
|
+
);
|
|
649
|
+
if (preflight.code !== 0) {
|
|
650
|
+
const error = new Error(
|
|
651
|
+
`恢复工作目录不可用:${cleanSshError(preflight.stderr || preflight.stdout)}`,
|
|
652
|
+
);
|
|
653
|
+
error.statusCode = 400;
|
|
654
|
+
throw error;
|
|
655
|
+
}
|
|
656
|
+
const resolved = JSON.parse(preflight.stdout.trim());
|
|
657
|
+
return { ...agent, cwd: resolved.cwd };
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
const runSshCommand = createSshCommand({ inventoryOperations, operationCounts: sshOperationCounts, connectTimeoutMs: SSH_TIMEOUT_MS, audit: auditLifecycle });
|
|
661
|
+
|
|
662
|
+
async function resumeAgentInTmux(
|
|
663
|
+
agent,
|
|
664
|
+
pid = 0,
|
|
665
|
+
model = agent?.rollout?.model || "",
|
|
666
|
+
runtimeOverride = null,
|
|
667
|
+
) {
|
|
668
|
+
if (!agent?.rollout?.id || !agent.rollout.path) {
|
|
669
|
+
throw new Error("Session 缺少可恢复的 rollout 路径");
|
|
670
|
+
}
|
|
671
|
+
if (Number(pid) > 0) {
|
|
672
|
+
throw new Error(
|
|
673
|
+
"安全策略禁止接管活动 CLI/VS Code Session;请先让原 Session 正常退出,再从 Inactive 恢复",
|
|
674
|
+
);
|
|
675
|
+
}
|
|
676
|
+
const tmuxName = `scope-${agent.rollout.id.slice(0, 8)}`.replace(
|
|
677
|
+
/[^a-zA-Z0-9_-]/g,
|
|
678
|
+
"-",
|
|
679
|
+
);
|
|
680
|
+
const runtime = hostRuntimeConfig(agent.host, runtimeOverride);
|
|
681
|
+
const command = [
|
|
682
|
+
"python3 -",
|
|
683
|
+
shellQuote(String(pid)),
|
|
684
|
+
shellQuote(agent.rollout.path),
|
|
685
|
+
shellQuote(agent.cwd || "."),
|
|
686
|
+
shellQuote(agent.executable || "codex"),
|
|
687
|
+
shellQuote(agent.rollout.id),
|
|
688
|
+
shellQuote(tmuxName),
|
|
689
|
+
shellQuote(runtime.preLaunchCommand),
|
|
690
|
+
shellQuote(model || ""),
|
|
691
|
+
runtime.yolo ? "1" : "0",
|
|
692
|
+
].join(" ");
|
|
693
|
+
const result = await withTakeoverHostQueue(agent.host, () =>
|
|
694
|
+
runSshCommand(
|
|
695
|
+
agent.host,
|
|
696
|
+
command,
|
|
697
|
+
TAKEOVER_PROBE,
|
|
698
|
+
TAKEOVER_TIMEOUT_MS,
|
|
699
|
+
1_000_000,
|
|
700
|
+
),
|
|
701
|
+
);
|
|
702
|
+
if (result.code !== 0) {
|
|
703
|
+
throw new Error(cleanSshError(result.stderr || result.stdout));
|
|
704
|
+
}
|
|
705
|
+
try {
|
|
706
|
+
const resumed = JSON.parse(result.stdout.trim());
|
|
707
|
+
auditLifecycle(resumed.reused ? "tmux-reused" : "tmux-created", {
|
|
708
|
+
host: agent.host,
|
|
709
|
+
sessionId: agent.rollout.id,
|
|
710
|
+
tmux: resumed.tmux,
|
|
711
|
+
yolo: runtime.yolo,
|
|
712
|
+
preLaunchConfigured: Boolean(runtime.preLaunchCommand),
|
|
713
|
+
remoteSessionSignalSent: false,
|
|
714
|
+
});
|
|
715
|
+
return {
|
|
716
|
+
...resumed,
|
|
717
|
+
yolo: runtime.yolo,
|
|
718
|
+
preLaunchConfigured: Boolean(runtime.preLaunchCommand),
|
|
719
|
+
};
|
|
720
|
+
} catch {
|
|
721
|
+
throw new Error("远端 tmux 恢复结果无法解析");
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function tmuxAgentForDelivery(agent, resumed) {
|
|
726
|
+
return {
|
|
727
|
+
host: agent.host,
|
|
728
|
+
rollout: agent.rollout,
|
|
729
|
+
pane: {
|
|
730
|
+
session: resumed.tmux,
|
|
731
|
+
pane: "0.0",
|
|
732
|
+
},
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
function rememberTmuxAgent(agent, resumed) {
|
|
737
|
+
const policy = runtimePolicy(resumed.yolo);
|
|
738
|
+
const record = {
|
|
739
|
+
...agent,
|
|
740
|
+
rollout: agent.rollout
|
|
741
|
+
? {
|
|
742
|
+
...agent.rollout,
|
|
743
|
+
approvalPolicy: policy.approvalPolicy,
|
|
744
|
+
sandboxPolicy: policy.sandbox,
|
|
745
|
+
}
|
|
746
|
+
: agent.rollout,
|
|
747
|
+
pid: resumed.panePid || agent.pid || 0,
|
|
748
|
+
tty: `tmux:${resumed.target}`,
|
|
749
|
+
status: "idle",
|
|
750
|
+
pane: {
|
|
751
|
+
session: resumed.tmux,
|
|
752
|
+
pane: "0.0",
|
|
753
|
+
command: resumed.paneCommand || "node",
|
|
754
|
+
pid: resumed.panePid || 0,
|
|
755
|
+
},
|
|
756
|
+
historical: false,
|
|
757
|
+
appServerManaged: false,
|
|
758
|
+
transport: "tmux",
|
|
759
|
+
mapping: {
|
|
760
|
+
rollout: "open-fd",
|
|
761
|
+
tmux: "exact",
|
|
762
|
+
},
|
|
763
|
+
};
|
|
764
|
+
historicalSessions.set(
|
|
765
|
+
sessionKey(agent.host, agent.rollout.id),
|
|
766
|
+
record,
|
|
767
|
+
);
|
|
768
|
+
return record;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
function spawnRemoteAppServer(
|
|
772
|
+
alias,
|
|
773
|
+
executable = "codex",
|
|
774
|
+
connectionKey = "active",
|
|
775
|
+
) {
|
|
776
|
+
if (alias === LOCAL_HOST) return localCodex.connect();
|
|
777
|
+
const runtime = hostRuntimeConfig(alias);
|
|
778
|
+
const appServerCommand = durableRemoteAppServerCommand({
|
|
779
|
+
// Scanner process rows can begin with `node` because the Codex launcher is
|
|
780
|
+
// a Node wrapper. `node app-server` is not Codex (and resolves as a local
|
|
781
|
+
// script such as /root/app-server), so it must never become the durable
|
|
782
|
+
// writer executable.
|
|
783
|
+
executable: codexExecutable(executable),
|
|
784
|
+
key: connectionKey === "active" ? "default" : connectionKey,
|
|
785
|
+
useActiveProfile: connectionKey === "active",
|
|
786
|
+
isolatedProfile: profileFromConnection(connectionKey) || "",
|
|
787
|
+
});
|
|
788
|
+
const bootstrapCommand = runtime.preLaunchCommand
|
|
789
|
+
? wrapBootstrapAppServer(appServerCommand, runtime.preLaunchCommand)
|
|
790
|
+
: appServerCommand;
|
|
791
|
+
const command = guardPersistentCodexHome(bootstrapCommand, persistentCodexHomes[alias]);
|
|
792
|
+
const child = spawn(
|
|
793
|
+
(typeof process !== "undefined" && process.platform === "win32" ? "ssh.exe" : "ssh"),
|
|
794
|
+
[
|
|
795
|
+
"-T",
|
|
796
|
+
"-o",
|
|
797
|
+
"BatchMode=yes",
|
|
798
|
+
"-o",
|
|
799
|
+
"StrictHostKeyChecking=yes",
|
|
800
|
+
"-o",
|
|
801
|
+
"ConnectionAttempts=1",
|
|
802
|
+
"-o",
|
|
803
|
+
`ConnectTimeout=${Math.ceil(SSH_TIMEOUT_MS / 1000)}`,
|
|
804
|
+
"-o",
|
|
805
|
+
"ServerAliveInterval=20",
|
|
806
|
+
"-o",
|
|
807
|
+
"ServerAliveCountMax=3",
|
|
808
|
+
"-o",
|
|
809
|
+
"TCPKeepAlive=yes",
|
|
810
|
+
"--",
|
|
811
|
+
alias,
|
|
812
|
+
command,
|
|
813
|
+
],
|
|
814
|
+
{
|
|
815
|
+
windowsHide: true,
|
|
816
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
817
|
+
},
|
|
818
|
+
);
|
|
819
|
+
auditLifecycle("app-server-proxy-spawned", {
|
|
820
|
+
host: alias,
|
|
821
|
+
connectionKey,
|
|
822
|
+
transport: "ssh-websocket-unix-socket",
|
|
823
|
+
remoteSessionSignalSent: false,
|
|
824
|
+
});
|
|
825
|
+
return new WebSocketJsonlChild(child);
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
// Catalog probes run the installed CLI, never the months-old durable writer.
|
|
829
|
+
// They cannot acquire a research thread and exit as soon as stdin is closed.
|
|
830
|
+
const modelCatalogCache = new Map();
|
|
831
|
+
const modelCatalogJobs = new Map();
|
|
832
|
+
async function readInstalledModels(host, force = false, connectionKey = "active") {
|
|
833
|
+
// A profile-bound session must be queried with its own credentials, but a
|
|
834
|
+
// fresh CLI: durable writers can retain an obsolete model catalog for months.
|
|
835
|
+
const target = modelCatalogTarget(host.alias, connectionKey);
|
|
836
|
+
const catalogKey = target.key;
|
|
837
|
+
const cached = modelCatalogCache.get(catalogKey);
|
|
838
|
+
if (!force && cached && Date.now() - cached.fetchedAt < 60_000) return cached;
|
|
839
|
+
if (modelCatalogJobs.has(catalogKey)) return modelCatalogJobs.get(catalogKey);
|
|
840
|
+
const job = (async () => {
|
|
841
|
+
const executable = hostCodexExecutable(host);
|
|
842
|
+
const command = wrapBootstrapAppServer([
|
|
843
|
+
...modelCatalogHomeCommands(target),
|
|
844
|
+
`scope_catalog_exe=$(command -v codex 2>/dev/null || printf '%s' ${shellQuote(executable)})`,
|
|
845
|
+
'exec "$scope_catalog_exe" app-server --listen stdio://',
|
|
846
|
+
].join('; '), hostRuntimeConfig(host.alias).preLaunchCommand);
|
|
847
|
+
const probe = new AppServerManager({
|
|
848
|
+
spawnConnection: () => host.alias === LOCAL_HOST ? localCodex.probe() : spawn((typeof process !== "undefined" && process.platform === "win32" ? "ssh.exe" : "ssh"), ["-T", "-o", "BatchMode=yes",
|
|
849
|
+
"-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=20", "--", host.alias, command],
|
|
850
|
+
{ windowsHide: true, stdio: ["pipe", "pipe", "pipe"] }),
|
|
851
|
+
requestTimeoutMs: 30_000,
|
|
852
|
+
});
|
|
853
|
+
try {
|
|
854
|
+
const models = await probe.listModels(host.alias, executable);
|
|
855
|
+
const result = { models, fetchedAt: Date.now(),
|
|
856
|
+
serverInfo: (await probe.prepareHost(host.alias)).serverInfo };
|
|
857
|
+
modelCatalogCache.set(catalogKey, result);
|
|
858
|
+
return result;
|
|
859
|
+
} finally { probe.close(); }
|
|
860
|
+
})().finally(() => modelCatalogJobs.delete(catalogKey));
|
|
861
|
+
modelCatalogJobs.set(catalogKey, job);
|
|
862
|
+
return job;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
function hostCodexExecutable(host) {
|
|
866
|
+
return (
|
|
867
|
+
host?.agents
|
|
868
|
+
?.map((agent) => agent.executable)
|
|
869
|
+
.find(
|
|
870
|
+
(candidate) => codexExecutable(candidate) !== "codex",
|
|
871
|
+
) || "codex"
|
|
872
|
+
);
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
function codexExecutable(value) {
|
|
876
|
+
const candidate = typeof value === "string" ? value.trim() : "";
|
|
877
|
+
// We accept the CLI command or an absolute Codex binary recorded by the
|
|
878
|
+
// process scanner, but never a runtime such as node/python/bash.
|
|
879
|
+
if (candidate === "codex" || /(?:^|[\\/])codex$/.test(candidate)) {
|
|
880
|
+
return candidate;
|
|
881
|
+
}
|
|
882
|
+
return "codex";
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
function spawnRemoteProfileAppServer({ host, executable = "codex", profile }) {
|
|
886
|
+
const runtime = hostRuntimeConfig(host);
|
|
887
|
+
const profileHome = `$HOME/.codex/scope-auth-profiles/${profile.slug}/home`;
|
|
888
|
+
// Device-auth transports are short lived and never execute research turns.
|
|
889
|
+
// Keep them on JSONL stdio so cancelling or deleting a login cannot leave an
|
|
890
|
+
// orphan per-profile daemon behind.
|
|
891
|
+
const appServerCommand = [
|
|
892
|
+
`export CODEX_HOME="${profileHome}"`,
|
|
893
|
+
`exec ${shellQuote(executable || "codex")} -c cli_auth_credentials_store=file app-server --listen stdio://`,
|
|
894
|
+
].join("; ");
|
|
895
|
+
const command = runtime.preLaunchCommand
|
|
896
|
+
? wrapBootstrapAppServer(appServerCommand, runtime.preLaunchCommand)
|
|
897
|
+
: `sh -lc ${shellQuote(appServerCommand)}`;
|
|
898
|
+
return spawn(
|
|
899
|
+
(typeof process !== "undefined" && process.platform === "win32" ? "ssh.exe" : "ssh"),
|
|
900
|
+
[
|
|
901
|
+
"-T",
|
|
902
|
+
"-o",
|
|
903
|
+
"BatchMode=yes",
|
|
904
|
+
"-o",
|
|
905
|
+
"StrictHostKeyChecking=yes",
|
|
906
|
+
"-o",
|
|
907
|
+
"ConnectionAttempts=1",
|
|
908
|
+
"-o",
|
|
909
|
+
`ConnectTimeout=${Math.ceil(SSH_TIMEOUT_MS / 1000)}`,
|
|
910
|
+
"--",
|
|
911
|
+
host,
|
|
912
|
+
command,
|
|
913
|
+
],
|
|
914
|
+
{ windowsHide: true, stdio: ["pipe", "pipe", "pipe"] },
|
|
915
|
+
);
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
function profilePayload(profile, account = null) {
|
|
919
|
+
return Buffer.from(
|
|
920
|
+
JSON.stringify({ name: profile.name, account }),
|
|
921
|
+
"utf8",
|
|
922
|
+
).toString("base64");
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
function checkedProfileSlug(value) {
|
|
926
|
+
const slug = typeof value === "string" ? value.trim() : "";
|
|
927
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,47}$/.test(slug)) {
|
|
928
|
+
throw new Error("Profile 标识无效");
|
|
929
|
+
}
|
|
930
|
+
return slug;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
async function runProfileWrite(host, action, profile, account = null) {
|
|
934
|
+
const result = await runSshCommand(
|
|
935
|
+
host,
|
|
936
|
+
`python3 - ${shellQuote(action)} ${shellQuote(profile.slug)} ${shellQuote(
|
|
937
|
+
profilePayload(profile, account),
|
|
938
|
+
)}`,
|
|
939
|
+
PROFILE_WRITE_PROBE,
|
|
940
|
+
20_000,
|
|
941
|
+
100_000,
|
|
942
|
+
);
|
|
943
|
+
if (result.code !== 0) {
|
|
944
|
+
throw new Error(cleanSshError(result.stderr || result.stdout));
|
|
945
|
+
}
|
|
946
|
+
return JSON.parse(result.stdout.trim());
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
async function listAuthProfiles(host) {
|
|
950
|
+
if (host === LOCAL_HOST) return { profiles: [], activeProfile: null, local: true };
|
|
951
|
+
const result = await runSshCommand(
|
|
952
|
+
host,
|
|
953
|
+
"python3 -",
|
|
954
|
+
PROFILE_LIST_PROBE,
|
|
955
|
+
15_000,
|
|
956
|
+
300_000,
|
|
957
|
+
);
|
|
958
|
+
if (result.code !== 0) {
|
|
959
|
+
throw new Error(cleanSshError(result.stderr || result.stdout));
|
|
960
|
+
}
|
|
961
|
+
return JSON.parse(result.stdout.trim());
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
function failedProfilesForHost(host) {
|
|
965
|
+
let failed = authProfileFailedUntil.get(host);
|
|
966
|
+
if (!failed) {
|
|
967
|
+
failed = new Map();
|
|
968
|
+
authProfileFailedUntil.set(host, failed);
|
|
969
|
+
}
|
|
970
|
+
return failed;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
async function probeAuthProfile(host, executable, profile) {
|
|
974
|
+
const child = spawnRemoteProfileAppServer({ host, executable, profile });
|
|
975
|
+
const connection = new JsonlAppServerConnection({
|
|
976
|
+
host: `${host}:${profile.slug}:failover-probe`,
|
|
977
|
+
child,
|
|
978
|
+
requestTimeoutMs: Math.min(AUTH_LOGIN_TIMEOUT_MS, 45_000),
|
|
979
|
+
});
|
|
980
|
+
try {
|
|
981
|
+
await connection.start();
|
|
982
|
+
const response = await connection.request("account/read", {
|
|
983
|
+
// A metadata-only read can succeed with an already decoded ID token even
|
|
984
|
+
// when the refresh token is dead. Force the same refresh path used by a
|
|
985
|
+
// real turn before treating a saved profile as a failover candidate.
|
|
986
|
+
refreshToken: true,
|
|
987
|
+
});
|
|
988
|
+
if (!response?.account) {
|
|
989
|
+
throw new Error("Profile 未返回可用的 Codex 账号");
|
|
990
|
+
}
|
|
991
|
+
return response.account;
|
|
992
|
+
} finally {
|
|
993
|
+
connection.close();
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
async function deleteAuthProfile(host, slug) {
|
|
998
|
+
const result = await runSshCommand(
|
|
999
|
+
host,
|
|
1000
|
+
`python3 - ${shellQuote(slug)} ${shellQuote(slug)}`,
|
|
1001
|
+
PROFILE_DELETE_PROBE,
|
|
1002
|
+
15_000,
|
|
1003
|
+
100_000,
|
|
1004
|
+
);
|
|
1005
|
+
if (result.code !== 0) {
|
|
1006
|
+
throw new Error(cleanSshError(result.stderr || result.stdout));
|
|
1007
|
+
}
|
|
1008
|
+
return JSON.parse(result.stdout.trim());
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
const appServerManager = new AppServerManager({
|
|
1012
|
+
spawnConnection: spawnRemoteAppServer,
|
|
1013
|
+
validateResume: remoteResumeValidator(runSshCommand),
|
|
1014
|
+
requestTimeoutMs: APP_SERVER_TIMEOUT_MS,
|
|
1015
|
+
async resolveCapacityRetryDelays(host, connection) {
|
|
1016
|
+
if (host === LOCAL_HOST) return [];
|
|
1017
|
+
const [profiles, response] = await Promise.all([
|
|
1018
|
+
listAuthProfiles(host),
|
|
1019
|
+
connection.request("account/read", { refreshToken: true }),
|
|
1020
|
+
]);
|
|
1021
|
+
return profileCapacityRetryDelays(profiles, response?.account);
|
|
1022
|
+
},
|
|
1023
|
+
});
|
|
1024
|
+
|
|
1025
|
+
const {
|
|
1026
|
+
loadManagementState,
|
|
1027
|
+
loadGpuUsageHistory,
|
|
1028
|
+
loadSnapshotCache,
|
|
1029
|
+
loadHistoryIndex,
|
|
1030
|
+
persistSnapshotCache,
|
|
1031
|
+
persistHistoryIndex,
|
|
1032
|
+
revealUnarchivedSession,
|
|
1033
|
+
cachedHistoryResult,
|
|
1034
|
+
updateHistoryIndex,
|
|
1035
|
+
persistManagementState,
|
|
1036
|
+
persistGpuUsageHistory,
|
|
1037
|
+
} = createStatePersistence({
|
|
1038
|
+
STATE_DIR,
|
|
1039
|
+
STATE_FILE,
|
|
1040
|
+
GPU_USAGE_HISTORY_FILE,
|
|
1041
|
+
SNAPSHOT_CACHE_FILE,
|
|
1042
|
+
HISTORY_INDEX_FILE,
|
|
1043
|
+
sessionKey,
|
|
1044
|
+
appServerManager,
|
|
1045
|
+
localCodex,
|
|
1046
|
+
historicalSessions,
|
|
1047
|
+
hostNextScanAt,
|
|
1048
|
+
hostFailureStreaks,
|
|
1049
|
+
getSnapshot: () => snapshot,
|
|
1050
|
+
setSnapshot: (next) => { snapshot = next; },
|
|
1051
|
+
getManagementState: () => managementState,
|
|
1052
|
+
setManagementState: (next) => { managementState = next; },
|
|
1053
|
+
getGpuUsageHistory: () => gpuUsageHistory,
|
|
1054
|
+
setGpuUsageHistory: (next) => { gpuUsageHistory = next; },
|
|
1055
|
+
getHistoryIndex: () => historyIndex,
|
|
1056
|
+
setHistoryIndex: (next) => { historyIndex = next; },
|
|
1057
|
+
});
|
|
1058
|
+
|
|
1059
|
+
const {
|
|
1060
|
+
sendTmuxText,
|
|
1061
|
+
publicTmuxCapacityRecovery,
|
|
1062
|
+
cancelTmuxCapacityRecovery,
|
|
1063
|
+
detectTmuxCapacityFailures,
|
|
1064
|
+
selectTmuxModel,
|
|
1065
|
+
} = createTmuxDelivery({
|
|
1066
|
+
findAgent,
|
|
1067
|
+
sessionKey,
|
|
1068
|
+
shellQuote,
|
|
1069
|
+
runSshCommand,
|
|
1070
|
+
cleanSshError,
|
|
1071
|
+
notifyClients: () => notifyClients(),
|
|
1072
|
+
});
|
|
1073
|
+
|
|
1074
|
+
const {
|
|
1075
|
+
generateCodexSummary,
|
|
1076
|
+
searchAssistantSessions,
|
|
1077
|
+
discoverWandbRuns,
|
|
1078
|
+
renderResourcePrompt,
|
|
1079
|
+
} = createResearchInsights({
|
|
1080
|
+
SUMMARY_TIMEOUT_MS,
|
|
1081
|
+
ASSISTANT_SEARCH_TIMEOUT_MS,
|
|
1082
|
+
ASSISTANT_CODEX_TIMEOUT_MS,
|
|
1083
|
+
getSnapshot: () => snapshot,
|
|
1084
|
+
publicSnapshot: () => publicSnapshot(),
|
|
1085
|
+
getManagementState: () => managementState,
|
|
1086
|
+
historicalSessions,
|
|
1087
|
+
enrichAgentRelations,
|
|
1088
|
+
historicalAgent,
|
|
1089
|
+
sessionKey,
|
|
1090
|
+
shellQuote,
|
|
1091
|
+
runSshCommand,
|
|
1092
|
+
cleanSshError,
|
|
1093
|
+
mapLimit,
|
|
1094
|
+
});
|
|
1095
|
+
|
|
1096
|
+
// A completed account migration must survive a Bridge restart even when one
|
|
1097
|
+
// thread needs a later retry. Without this marker the stale persisted writer
|
|
1098
|
+
// key could silently recreate a previous account's app-server daemon.
|
|
1099
|
+
const activeProfileMigrationSessions = new Set();
|
|
1100
|
+
|
|
1101
|
+
function sessionProfileAssignment(host, sessionId) {
|
|
1102
|
+
return managementState.sessions[sessionKey(host, sessionId)]?.profileAssignment || null;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
function assertProfileNotBound(host, slug) {
|
|
1106
|
+
if (Object.entries(managementState.sessions).some(([key, state]) => key.startsWith(`${host}:`) &&
|
|
1107
|
+
[state.profileAssignment?.profile, state.profileAssignment?.desiredProfile].includes(slug))) {
|
|
1108
|
+
throw new Error("该 Profile 仍绑定了 Session;请先改绑,再删除或覆盖其登录凭据");
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
function fixedProfileSession(session) {
|
|
1113
|
+
return Boolean(profileFromConnection(session.connectionKey) ||
|
|
1114
|
+
sessionProfileAssignment(session.host, session.sessionId)?.desiredProfile);
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
function closeUnboundHostConnections(host) {
|
|
1118
|
+
for (const connection of appServerManager.publicState().connections) {
|
|
1119
|
+
if (connection.host === host && !profileFromConnection(connection.connectionKey)) {
|
|
1120
|
+
appServerManager.closeConnection(host, connection.connectionKey);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
function assertNoPendingProfileMigration(host) {
|
|
1126
|
+
if (appServerManager.sessionRecords().some((s) => s.host === host && fixedProfileSession(s) &&
|
|
1127
|
+
!profileFromConnection(s.connectionKey))) {
|
|
1128
|
+
throw new Error("该主机还有会话尚未完成独立账号绑定;请先完成或重试这些会话的切换,再修改主机账号");
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
const sessionProfiles = new SessionProfileAssignments({
|
|
1133
|
+
read: sessionProfileAssignment,
|
|
1134
|
+
async write(host, sessionId, assignment) {
|
|
1135
|
+
const key = sessionKey(host, sessionId);
|
|
1136
|
+
managementState.sessions[key] = { ...managementState.sessions[key], profileAssignment: assignment };
|
|
1137
|
+
await persistManagementState();
|
|
1138
|
+
notifyClients();
|
|
1139
|
+
},
|
|
1140
|
+
session: (host, sessionId) => appServerManager.sessionRecords().find((s) => s.host === host && s.sessionId === sessionId),
|
|
1141
|
+
blocked: (host, sessionId) => appServerAuthRecoveryHosts.has(host) ||
|
|
1142
|
+
appServerManager.sessionRecords().some((s) => s.host === host && s.sessionId === sessionId && (s.status === "working" || s.turnStarting)) ||
|
|
1143
|
+
appServerManager.publicState().pendingRequests.some((r) => r.host === host && r.threadId === sessionId),
|
|
1144
|
+
async verify(host, slug, executable) {
|
|
1145
|
+
const profiles = await listAuthProfiles(host);
|
|
1146
|
+
const profile = profiles.profiles.find((p) => p.slug === slug && p.ready);
|
|
1147
|
+
if (!profile) throw new Error("该 Profile 不存在或尚未登录");
|
|
1148
|
+
const connection = await appServerManager.prepareHost(host, codexExecutable(executable), sessionProfileKey(slug));
|
|
1149
|
+
const { account } = await connection.request("account/read", { refreshToken: true });
|
|
1150
|
+
if (!account || account.type !== "chatgpt" || !account.email ||
|
|
1151
|
+
account.email.toLowerCase() !== profile.account?.email?.toLowerCase()) {
|
|
1152
|
+
throw new Error("目标 writer 的实际账号与 Profile 不匹配;未切换会话,请重新登录该 Profile");
|
|
1153
|
+
}
|
|
1154
|
+
return { type: account.type, email: account.email, planType: account.planType };
|
|
1155
|
+
},
|
|
1156
|
+
hold: (...args) => appServerManager.holdSessionForProfile(...args),
|
|
1157
|
+
release: (...args) => appServerManager.releaseProfileWriter(...args),
|
|
1158
|
+
migrate: (...args) => appServerManager.finishProfileHandoff(...args),
|
|
1159
|
+
restore: (host, sessionId, source) => appServerManager.finishProfileHandoff(host, sessionId, source.connectionKey || "active", source.executable, source),
|
|
1160
|
+
});
|
|
1161
|
+
|
|
1162
|
+
const sessionProfileTimer = setInterval(() => {
|
|
1163
|
+
for (const record of appServerManager.sessionRecords()) {
|
|
1164
|
+
sessionProfiles.apply(record.host, record.sessionId).catch(() => {});
|
|
1165
|
+
}
|
|
1166
|
+
}, 3000);
|
|
1167
|
+
sessionProfileTimer.unref();
|
|
1168
|
+
|
|
1169
|
+
function appServerConnectionKey(value) {
|
|
1170
|
+
const key = typeof value === "string" ? value.trim() : "";
|
|
1171
|
+
return /^[A-Za-z0-9_.-]{1,100}$/.test(key) ? key : "active";
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
async function detectRemoteSessionWriter(host, sessionId) {
|
|
1175
|
+
if (host === LOCAL_HOST) return null;
|
|
1176
|
+
const result = await runSshCommand(
|
|
1177
|
+
host,
|
|
1178
|
+
`python3 - ${shellQuote(sessionId)}`,
|
|
1179
|
+
APP_SERVER_WRITER_PROBE,
|
|
1180
|
+
12_000,
|
|
1181
|
+
100_000,
|
|
1182
|
+
);
|
|
1183
|
+
if (result.code !== 0) return null;
|
|
1184
|
+
try {
|
|
1185
|
+
const parsed = JSON.parse(result.stdout.trim());
|
|
1186
|
+
const connectionKey = appServerConnectionKey(parsed.connectionKey);
|
|
1187
|
+
if (!parsed.connectionKey || connectionKey === "active") return null;
|
|
1188
|
+
return {
|
|
1189
|
+
connectionKey,
|
|
1190
|
+
ownerPid: Number(parsed.ownerPid) || 0,
|
|
1191
|
+
endpoint: typeof parsed.endpoint === "string" ? parsed.endpoint : "",
|
|
1192
|
+
};
|
|
1193
|
+
} catch {
|
|
1194
|
+
return null;
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
async function resumeManagedAppServerSession(options) {
|
|
1199
|
+
const binding = sessionProfileAssignment(options.host, options.sessionId);
|
|
1200
|
+
if (profileHandoffPending(binding)) throw new Error("此会话正在交接账号;不会重新加载旧 writer,请等待或取消交接");
|
|
1201
|
+
const existing = appServerManager.sessionRecords().find((record) =>
|
|
1202
|
+
record.host === options.host && record.sessionId === options.sessionId);
|
|
1203
|
+
const recoveredWriter = !existing && !options.connectionKey && !binding?.profile
|
|
1204
|
+
? await detectRemoteSessionWriter(options.host, options.sessionId) : null;
|
|
1205
|
+
const requestedConnectionKey = boundConnectionKey(binding,
|
|
1206
|
+
managementState.sessions[sessionKey(options.host, options.sessionId)]?.restartConnectionKey ||
|
|
1207
|
+
existing?.connectionKey || options.connectionKey || recoveredWriter?.connectionKey || await newSessionConnectionKey(options.host));
|
|
1208
|
+
const normalizedOptions = {
|
|
1209
|
+
...options,
|
|
1210
|
+
executable: codexExecutable(options.executable),
|
|
1211
|
+
};
|
|
1212
|
+
try {
|
|
1213
|
+
return await appServerManager.resumeSession({
|
|
1214
|
+
...normalizedOptions,
|
|
1215
|
+
connectionKey: requestedConnectionKey,
|
|
1216
|
+
});
|
|
1217
|
+
} catch (error) {
|
|
1218
|
+
if (binding?.profile || profileFromConnection(requestedConnectionKey)) throw error;
|
|
1219
|
+
if (!/already has an active writer/i.test(error?.message || "")) throw error;
|
|
1220
|
+
const writer = await detectRemoteSessionWriter(
|
|
1221
|
+
options.host,
|
|
1222
|
+
options.sessionId,
|
|
1223
|
+
);
|
|
1224
|
+
if (!writer || writer.connectionKey === requestedConnectionKey) throw error;
|
|
1225
|
+
const resumed = await appServerManager.resumeSession({
|
|
1226
|
+
...normalizedOptions,
|
|
1227
|
+
connectionKey: writer.connectionKey,
|
|
1228
|
+
});
|
|
1229
|
+
await auditLifecycle("app-server-session-writer-routed", {
|
|
1230
|
+
host: options.host,
|
|
1231
|
+
sessionId: options.sessionId,
|
|
1232
|
+
fromConnectionKey: requestedConnectionKey,
|
|
1233
|
+
toConnectionKey: writer.connectionKey,
|
|
1234
|
+
ownerPid: writer.ownerPid,
|
|
1235
|
+
remoteSessionSignalSent: false,
|
|
1236
|
+
});
|
|
1237
|
+
return resumed;
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
async function newSessionConnectionKey(host) {
|
|
1241
|
+
if (host === LOCAL_HOST) return "active";
|
|
1242
|
+
const profiles = await listAuthProfiles(host);
|
|
1243
|
+
return profiles.activeProfile ? sessionProfileKey(profiles.activeProfile) : "active";
|
|
1244
|
+
}
|
|
1245
|
+
const authProfileManager = new AuthProfileManager({
|
|
1246
|
+
spawnConnection: spawnRemoteProfileAppServer,
|
|
1247
|
+
requestTimeoutMs: AUTH_LOGIN_TIMEOUT_MS,
|
|
1248
|
+
prepareProfile: async (host, profile) => {
|
|
1249
|
+
const result = await runSshCommand(
|
|
1250
|
+
host,
|
|
1251
|
+
`umask 077; mkdir -p "$HOME/.codex/scope-auth-profiles/${profile.slug}/home"`,
|
|
1252
|
+
"",
|
|
1253
|
+
15_000,
|
|
1254
|
+
);
|
|
1255
|
+
if (result.code !== 0) {
|
|
1256
|
+
throw new Error(cleanSshError(result.stderr || result.stdout));
|
|
1257
|
+
}
|
|
1258
|
+
},
|
|
1259
|
+
finalizeProfile: (host, profile, account) =>
|
|
1260
|
+
runProfileWrite(host, "finalize", profile, account),
|
|
1261
|
+
cancelProfile: async (host, profile) => {
|
|
1262
|
+
const result = await runSshCommand(
|
|
1263
|
+
host,
|
|
1264
|
+
`python3 - ${shellQuote(profile.slug)}`,
|
|
1265
|
+
PROFILE_CANCEL_PROBE,
|
|
1266
|
+
15_000,
|
|
1267
|
+
100_000,
|
|
1268
|
+
);
|
|
1269
|
+
if (result.code !== 0) {
|
|
1270
|
+
throw new Error(cleanSshError(result.stderr || result.stdout));
|
|
1271
|
+
}
|
|
1272
|
+
},
|
|
1273
|
+
});
|
|
1274
|
+
|
|
1275
|
+
function persistedAppServerSession(record) {
|
|
1276
|
+
if (!record?.host || !record?.sessionId) return null;
|
|
1277
|
+
return {
|
|
1278
|
+
host: String(record.host).slice(0, 200),
|
|
1279
|
+
sessionId: String(record.sessionId).slice(0, 200),
|
|
1280
|
+
path: typeof record.path === "string" ? record.path.slice(0, 8_000) : null,
|
|
1281
|
+
cwd: typeof record.cwd === "string" ? record.cwd.slice(0, 8_000) : "",
|
|
1282
|
+
model: typeof record.model === "string" ? record.model.slice(0, 200) : "",
|
|
1283
|
+
effort: typeof record.effort === "string" ? record.effort.slice(0, 40) : "",
|
|
1284
|
+
yolo: record.yolo !== false,
|
|
1285
|
+
readOnly: record.readOnly === true,
|
|
1286
|
+
executable:
|
|
1287
|
+
typeof record.executable === "string"
|
|
1288
|
+
? record.executable.slice(0, 8_000)
|
|
1289
|
+
: "codex",
|
|
1290
|
+
resumeOnRecovery:
|
|
1291
|
+
typeof record.resumeOnRecovery === "boolean"
|
|
1292
|
+
? record.resumeOnRecovery
|
|
1293
|
+
: record.status === "working",
|
|
1294
|
+
connectionKey: appServerConnectionKey(record.connectionKey),
|
|
1295
|
+
updatedAt: new Date().toISOString(),
|
|
1296
|
+
};
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
async function loadPersistedAppServerSessions() {
|
|
1300
|
+
try {
|
|
1301
|
+
const parsed = JSON.parse(await readFile(APP_SERVER_SESSIONS_FILE, "utf8"));
|
|
1302
|
+
for (const raw of Array.isArray(parsed?.sessions) ? parsed.sessions : []) {
|
|
1303
|
+
const record = persistedAppServerSession(raw);
|
|
1304
|
+
if (!record) continue;
|
|
1305
|
+
persistedAppServerSessions.set(
|
|
1306
|
+
sessionKey(record.host, record.sessionId),
|
|
1307
|
+
{ ...record, updatedAt: raw.updatedAt || record.updatedAt },
|
|
1308
|
+
);
|
|
1309
|
+
}
|
|
1310
|
+
} catch (error) {
|
|
1311
|
+
if (error?.code !== "ENOENT") {
|
|
1312
|
+
console.error(`无法读取 ${APP_SERVER_SESSIONS_FILE}: ${error.message}`);
|
|
1313
|
+
}
|
|
1314
|
+
} finally {
|
|
1315
|
+
appServerSessionsLoaded = true;
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
function persistAppServerSessions() {
|
|
1320
|
+
if (!appServerSessionsLoaded) return Promise.resolve();
|
|
1321
|
+
for (const raw of appServerManager.sessionRecords()) {
|
|
1322
|
+
const record = persistedAppServerSession(raw);
|
|
1323
|
+
if (!record) continue;
|
|
1324
|
+
if (!fixedProfileSession(record) && activeProfileMigrationSessions.has(sessionKey(record.host, record.sessionId))) {
|
|
1325
|
+
record.connectionKey = "active";
|
|
1326
|
+
}
|
|
1327
|
+
persistedAppServerSessions.set(
|
|
1328
|
+
sessionKey(record.host, record.sessionId),
|
|
1329
|
+
record,
|
|
1330
|
+
);
|
|
1331
|
+
}
|
|
1332
|
+
const serialized = `${JSON.stringify(
|
|
1333
|
+
{
|
|
1334
|
+
version: 1,
|
|
1335
|
+
sessions: Array.from(persistedAppServerSessions.values()),
|
|
1336
|
+
},
|
|
1337
|
+
null,
|
|
1338
|
+
2,
|
|
1339
|
+
)}\n`;
|
|
1340
|
+
appServerSessionWritePromise = appServerSessionWritePromise
|
|
1341
|
+
.catch(() => {})
|
|
1342
|
+
.then(async () => {
|
|
1343
|
+
await mkdir(STATE_DIR, { recursive: true });
|
|
1344
|
+
const temporary = `${APP_SERVER_SESSIONS_FILE}.tmp`;
|
|
1345
|
+
await writeFile(temporary, serialized, "utf8");
|
|
1346
|
+
await rename(temporary, APP_SERVER_SESSIONS_FILE);
|
|
1347
|
+
});
|
|
1348
|
+
return appServerSessionWritePromise;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
function restorePersistedAppServerSessions() {
|
|
1352
|
+
if (appServerRestorePromise) return appServerRestorePromise;
|
|
1353
|
+
appServerRestorePromise = (async () => {
|
|
1354
|
+
const records = Array.from(persistedAppServerSessions.values());
|
|
1355
|
+
for (const record of records) {
|
|
1356
|
+
const key = sessionKey(record.host, record.sessionId);
|
|
1357
|
+
if (managementState.sessions[key]?.archive && managementState.sessions[key].archive.phase !== "restored") continue;
|
|
1358
|
+
const assignment = sessionProfileAssignment(record.host, record.sessionId);
|
|
1359
|
+
if (profileHandoffPending(assignment)) {
|
|
1360
|
+
appServerManager.hydrateProfileHandoff(assignment.handoff.source);
|
|
1361
|
+
continue;
|
|
1362
|
+
}
|
|
1363
|
+
if (appServerManager.isManaged(record.host, record.sessionId)) {
|
|
1364
|
+
appServerRestoreFailures.delete(key);
|
|
1365
|
+
continue;
|
|
1366
|
+
}
|
|
1367
|
+
const previousFailure = appServerRestoreFailures.get(key);
|
|
1368
|
+
if ((previousFailure?.retryAt || 0) > Date.now()) continue;
|
|
1369
|
+
const currentHost = snapshot.hosts.find(
|
|
1370
|
+
(candidate) => candidate.alias === record.host,
|
|
1371
|
+
);
|
|
1372
|
+
const externalOwner = currentHost?.agents?.find(
|
|
1373
|
+
(agent) =>
|
|
1374
|
+
agent.rollout?.id === record.sessionId && !agent.appServerManaged,
|
|
1375
|
+
);
|
|
1376
|
+
if (externalOwner) {
|
|
1377
|
+
appServerRestoreFailures.set(key, {
|
|
1378
|
+
attempt: previousFailure?.attempt || 0,
|
|
1379
|
+
error: `当前由外部 CLI/VS Code PID ${externalOwner.pid} 持有`,
|
|
1380
|
+
retryAt: Date.now() + 30_000,
|
|
1381
|
+
});
|
|
1382
|
+
continue;
|
|
1383
|
+
}
|
|
1384
|
+
if (!currentHost?.reachable) continue;
|
|
1385
|
+
try {
|
|
1386
|
+
await resumeManagedAppServerSession({
|
|
1387
|
+
host: record.host,
|
|
1388
|
+
sessionId: record.sessionId,
|
|
1389
|
+
path: record.path,
|
|
1390
|
+
cwd: record.cwd,
|
|
1391
|
+
model: record.model || null,
|
|
1392
|
+
effort: record.effort || null,
|
|
1393
|
+
yolo: record.yolo !== false,
|
|
1394
|
+
readOnly: record.readOnly === true,
|
|
1395
|
+
executable: record.executable || "codex",
|
|
1396
|
+
resumeOnRecovery: record.resumeOnRecovery === true,
|
|
1397
|
+
connectionKey: record.connectionKey,
|
|
1398
|
+
});
|
|
1399
|
+
appServerRestoreFailures.delete(key);
|
|
1400
|
+
auditLifecycle("app-server-session-restored", {
|
|
1401
|
+
host: record.host,
|
|
1402
|
+
sessionId: record.sessionId,
|
|
1403
|
+
remoteSessionSignalSent: false,
|
|
1404
|
+
});
|
|
1405
|
+
} catch (error) {
|
|
1406
|
+
const attempt = (previousFailure?.attempt || 0) + 1;
|
|
1407
|
+
const retryDelay = Math.min(
|
|
1408
|
+
5 * 60_000,
|
|
1409
|
+
5_000 * 2 ** Math.min(attempt - 1, 6),
|
|
1410
|
+
);
|
|
1411
|
+
appServerRestoreFailures.set(key, {
|
|
1412
|
+
attempt,
|
|
1413
|
+
error: error.message,
|
|
1414
|
+
retryAt: Date.now() + retryDelay,
|
|
1415
|
+
});
|
|
1416
|
+
console.error(
|
|
1417
|
+
`[app-server] 自动恢复 ${record.host}:${record.sessionId} 失败:${error.message};${Math.round(retryDelay / 1000)} 秒后重试`,
|
|
1418
|
+
);
|
|
1419
|
+
if (previousFailure?.error !== error.message) {
|
|
1420
|
+
auditLifecycle("app-server-session-restore-failed", {
|
|
1421
|
+
host: record.host,
|
|
1422
|
+
sessionId: record.sessionId,
|
|
1423
|
+
error: error.message,
|
|
1424
|
+
remoteSessionSignalSent: false,
|
|
1425
|
+
});
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
await persistAppServerSessions();
|
|
1430
|
+
})().finally(() => {
|
|
1431
|
+
appServerRestorePromise = null;
|
|
1432
|
+
});
|
|
1433
|
+
return appServerRestorePromise;
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
function scheduleAppServerReconnects() {
|
|
1437
|
+
if (!appServerSessionsLoaded) return;
|
|
1438
|
+
const offlineHosts = new Set(
|
|
1439
|
+
appServerManager
|
|
1440
|
+
.sessionRecords()
|
|
1441
|
+
.filter((session) => session.status === "offline" && !profileHandoffPending(sessionProfileAssignment(session.host, session.sessionId)))
|
|
1442
|
+
.map((session) => session.host),
|
|
1443
|
+
);
|
|
1444
|
+
for (const [host, timer] of appServerReconnectTimers.entries()) {
|
|
1445
|
+
if (offlineHosts.has(host)) continue;
|
|
1446
|
+
clearTimeout(timer);
|
|
1447
|
+
appServerReconnectTimers.delete(host);
|
|
1448
|
+
appServerReconnectAttempts.delete(host);
|
|
1449
|
+
}
|
|
1450
|
+
for (const host of offlineHosts) {
|
|
1451
|
+
if (
|
|
1452
|
+
appServerAuthRecoveryHosts.has(host) ||
|
|
1453
|
+
appServerReconnectTimers.has(host) ||
|
|
1454
|
+
appServerReconnectInFlight.has(host)
|
|
1455
|
+
)
|
|
1456
|
+
continue;
|
|
1457
|
+
const attempt = appServerReconnectAttempts.get(host) || 0;
|
|
1458
|
+
// A dropped proxy has no useful grace period: rebuild the whole managed
|
|
1459
|
+
// app-server stream immediately. Further failures retain exponential
|
|
1460
|
+
// backoff so a genuinely unreachable host is not hammered.
|
|
1461
|
+
const delay =
|
|
1462
|
+
attempt === 0 ? 0 : Math.min(30_000, 2_000 * 2 ** Math.min(attempt, 4));
|
|
1463
|
+
const timer = setTimeout(async () => {
|
|
1464
|
+
appServerReconnectTimers.delete(host);
|
|
1465
|
+
appServerReconnectInFlight.add(host);
|
|
1466
|
+
const records = Array.from(persistedAppServerSessions.values()).filter(
|
|
1467
|
+
(record) => record.host === host,
|
|
1468
|
+
);
|
|
1469
|
+
if (!records.length) {
|
|
1470
|
+
appServerReconnectAttempts.delete(host);
|
|
1471
|
+
appServerReconnectInFlight.delete(host);
|
|
1472
|
+
return;
|
|
1473
|
+
}
|
|
1474
|
+
try {
|
|
1475
|
+
const currentHost = snapshot.hosts.find(
|
|
1476
|
+
(candidate) => candidate.alias === host,
|
|
1477
|
+
);
|
|
1478
|
+
if (!currentHost?.reachable) throw new Error("SSH 主机当前不可连接");
|
|
1479
|
+
for (const record of records) {
|
|
1480
|
+
if (profileHandoffPending(sessionProfileAssignment(record.host, record.sessionId))) continue;
|
|
1481
|
+
const externalOwner = currentHost.agents?.find(
|
|
1482
|
+
(agent) =>
|
|
1483
|
+
agent.rollout?.id === record.sessionId &&
|
|
1484
|
+
!agent.appServerManaged,
|
|
1485
|
+
);
|
|
1486
|
+
if (externalOwner) {
|
|
1487
|
+
persistedAppServerSessions.delete(
|
|
1488
|
+
sessionKey(record.host, record.sessionId),
|
|
1489
|
+
);
|
|
1490
|
+
continue;
|
|
1491
|
+
}
|
|
1492
|
+
await resumeManagedAppServerSession({
|
|
1493
|
+
host: record.host,
|
|
1494
|
+
sessionId: record.sessionId,
|
|
1495
|
+
path: record.path,
|
|
1496
|
+
cwd: record.cwd,
|
|
1497
|
+
model: record.model || null,
|
|
1498
|
+
effort: record.effort || null,
|
|
1499
|
+
yolo: record.yolo !== false,
|
|
1500
|
+
readOnly: record.readOnly === true,
|
|
1501
|
+
executable: record.executable || "codex",
|
|
1502
|
+
resumeOnRecovery: record.resumeOnRecovery === true,
|
|
1503
|
+
connectionKey: record.connectionKey,
|
|
1504
|
+
});
|
|
1505
|
+
}
|
|
1506
|
+
appServerReconnectAttempts.delete(host);
|
|
1507
|
+
await persistAppServerSessions();
|
|
1508
|
+
} catch (error) {
|
|
1509
|
+
appServerReconnectAttempts.set(host, attempt + 1);
|
|
1510
|
+
console.error(`[app-server] ${host} 重连失败:${error.message}`);
|
|
1511
|
+
} finally {
|
|
1512
|
+
appServerReconnectInFlight.delete(host);
|
|
1513
|
+
scheduleAppServerReconnects();
|
|
1514
|
+
}
|
|
1515
|
+
}, delay);
|
|
1516
|
+
timer.unref();
|
|
1517
|
+
appServerReconnectTimers.set(host, timer);
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
const configRestartHeld = new Map();
|
|
1522
|
+
const hostConfigRestarts = new HostSessionRestarts({
|
|
1523
|
+
async prepare(host) {
|
|
1524
|
+
if (!snapshot.hosts.some((h) => h.alias === host && h.reachable)) throw new Error("主机不可连接");
|
|
1525
|
+
if (appServerAuthRecoveryHosts.has(host)) throw new Error("主机正在恢复或迁移账号,请稍后重试");
|
|
1526
|
+
const sessions = appServerManager.sessionRecords().filter((s) => s.host === host);
|
|
1527
|
+
if (!sessions.length) throw new Error("没有 SCOPE 托管会话");
|
|
1528
|
+
if (sessions.some((s) => s.status === "working" || s.turnStarting || s.profileHandoff)) {
|
|
1529
|
+
throw new Error("仍有工作中或账号交接中的会话;请先结束当前回合。未停止任何进程");
|
|
1530
|
+
}
|
|
1531
|
+
const profiles = await listAuthProfiles(host);
|
|
1532
|
+
const groups = new Map();
|
|
1533
|
+
for (const s of sessions) {
|
|
1534
|
+
const owner = await detectRemoteSessionWriter(host, s.sessionId);
|
|
1535
|
+
if (!owner) throw new Error(`无法确认 ${s.sessionId} 的 writer,未停止任何进程`);
|
|
1536
|
+
retireScopedAppServerCommand(owner.connectionKey); // validates the exact daemon key
|
|
1537
|
+
let group = groups.get(owner.connectionKey);
|
|
1538
|
+
if (!group) {
|
|
1539
|
+
const connection = await appServerManager.prepareHost(host, s.executable, s.connectionKey);
|
|
1540
|
+
const account = (await connection.request("account/read", { refreshToken: false }))?.account;
|
|
1541
|
+
const profile = profiles.profiles.find((p) => p.account?.email && account?.type === "chatgpt" &&
|
|
1542
|
+
p.account.email.toLowerCase() === account.email?.toLowerCase());
|
|
1543
|
+
if (!profile) throw new Error("无法确定原会话实际账号,拒绝按主机默认账号重启");
|
|
1544
|
+
if (owner.connectionKey.startsWith("profile-") &&
|
|
1545
|
+
profiles.currentAccount?.email?.toLowerCase() !== account.email?.toLowerCase()) {
|
|
1546
|
+
throw new Error("旧共享进程的账号与磁盘凭据不同;请先完成会话账号迁移,避免重启后换错账号");
|
|
1547
|
+
}
|
|
1548
|
+
group = { key: owner.connectionKey, connection, targetKey: owner.connectionKey, sessions: [] };
|
|
1549
|
+
groups.set(owner.connectionKey, group);
|
|
1550
|
+
}
|
|
1551
|
+
group.sessions.push(s);
|
|
1552
|
+
}
|
|
1553
|
+
for (const group of groups.values()) {
|
|
1554
|
+
let cursor = null;
|
|
1555
|
+
do {
|
|
1556
|
+
const loaded = await group.connection.request("thread/loaded/list", { cursor, limit: 100 });
|
|
1557
|
+
if (!Array.isArray(loaded.data)) throw new Error("无法核验 daemon 已加载会话,未停止任何进程");
|
|
1558
|
+
for (const id of loaded.data) {
|
|
1559
|
+
if (!group.sessions.some((s) => s.sessionId === id)) throw new Error(`daemon 还有未纳入重启的会话 ${id},未停止任何进程`);
|
|
1560
|
+
const current = await group.connection.request("thread/read", { threadId: id, includeTurns: false });
|
|
1561
|
+
if (!current?.thread?.status || current.thread.status.type === "active") {
|
|
1562
|
+
throw new Error(`会话 ${id} 远端仍活跃或无法核验,未停止任何进程`);
|
|
1563
|
+
}
|
|
1564
|
+
const terminals = await group.connection.request("thread/backgroundTerminals/list", { threadId: id, limit: 1 });
|
|
1565
|
+
if (!Array.isArray(terminals.data) || terminals.data.length || terminals.nextCursor) {
|
|
1566
|
+
throw new Error(`会话 ${id} 仍有后台命令或无法核验,未停止任何进程`);
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
cursor = loaded.nextCursor;
|
|
1570
|
+
} while (cursor);
|
|
1571
|
+
}
|
|
1572
|
+
// Synchronously prevent instructions/retries racing the completed preflight.
|
|
1573
|
+
const held = [];
|
|
1574
|
+
try {
|
|
1575
|
+
for (const s of sessions) { appServerManager.holdSessionForProfile(host, s.sessionId); held.push(s); }
|
|
1576
|
+
} catch (error) {
|
|
1577
|
+
for (const s of held) appServerManager.clearSessionRestartHold(host, s.sessionId);
|
|
1578
|
+
throw error;
|
|
1579
|
+
}
|
|
1580
|
+
appServerAuthRecoveryHosts.add(host);
|
|
1581
|
+
configRestartHeld.set(host, held.map((s) => s.sessionId));
|
|
1582
|
+
return [...groups.values()];
|
|
1583
|
+
},
|
|
1584
|
+
async restart(host, group) {
|
|
1585
|
+
// Persist each original thread's intended account before retiring its daemon.
|
|
1586
|
+
for (const s of group.sessions) {
|
|
1587
|
+
const key = sessionKey(host, s.sessionId);
|
|
1588
|
+
managementState.sessions[key] = { ...managementState.sessions[key], restartConnectionKey: group.targetKey };
|
|
1589
|
+
}
|
|
1590
|
+
await persistManagementState();
|
|
1591
|
+
const retired = await runSshCommand(host, retireScopedAppServerCommand(group.key), "", 15_000, 100_000);
|
|
1592
|
+
if (retired.code !== 0) throw new Error(cleanSshError(retired.stderr || retired.stdout));
|
|
1593
|
+
for (const key of new Set(group.sessions.map((s) => s.connectionKey))) appServerManager.closeConnection(host, key);
|
|
1594
|
+
const results = [];
|
|
1595
|
+
for (const s of group.sessions) {
|
|
1596
|
+
try {
|
|
1597
|
+
await appServerManager.resumeSession({ ...s, connectionKey: group.targetKey, resumeOnRecovery: false, allowProfileHandoff: true });
|
|
1598
|
+
results.push({ sessionId: s.sessionId, ok: true });
|
|
1599
|
+
} catch (error) { results.push({ sessionId: s.sessionId, ok: false, error: error.message }); }
|
|
1600
|
+
}
|
|
1601
|
+
await persistAppServerSessions();
|
|
1602
|
+
return results;
|
|
1603
|
+
},
|
|
1604
|
+
async publish(job) {
|
|
1605
|
+
if (job.status !== "running") {
|
|
1606
|
+
for (const id of configRestartHeld.get(job.host) || []) {
|
|
1607
|
+
appServerManager.clearSessionRestartHold(job.host, id);
|
|
1608
|
+
}
|
|
1609
|
+
if (configRestartHeld.has(job.host)) appServerAuthRecoveryHosts.delete(job.host);
|
|
1610
|
+
configRestartHeld.delete(job.host);
|
|
1611
|
+
if (job.status === "completed") {
|
|
1612
|
+
for (const result of job.results) {
|
|
1613
|
+
const state = managementState.sessions[sessionKey(job.host, result.sessionId)];
|
|
1614
|
+
if (state) delete state.restartConnectionKey;
|
|
1615
|
+
}
|
|
1616
|
+
await persistManagementState();
|
|
1617
|
+
}
|
|
1618
|
+
await auditLifecycle("host-config-restart-result", { host: job.host, status: job.status, results: job.results, error: job.error });
|
|
1619
|
+
}
|
|
1620
|
+
notifyClients();
|
|
1621
|
+
},
|
|
1622
|
+
});
|
|
1623
|
+
|
|
1624
|
+
const codexUpgrades = new CodexUpgrades({
|
|
1625
|
+
async inspect(host) {
|
|
1626
|
+
// Query npm registry locally first; if local egress is restricted, let the
|
|
1627
|
+
// remote host query via its configured updatePreCommand / preLaunchCommand.
|
|
1628
|
+
let latest = null;
|
|
1629
|
+
try {
|
|
1630
|
+
const registry = await fetch("https://registry.npmjs.org/@openai%2Fcodex/latest", { signal: AbortSignal.timeout(15_000) });
|
|
1631
|
+
if (registry.ok) latest = stableVersion((await registry.json()).version);
|
|
1632
|
+
} catch {
|
|
1633
|
+
latest = null;
|
|
1634
|
+
}
|
|
1635
|
+
const runtime = hostRuntimeConfig(host);
|
|
1636
|
+
const updatePre = runtime?.updatePreCommand?.trim() || runtime?.preLaunchCommand?.trim() || "";
|
|
1637
|
+
const wrapped = wrapCodexUpgradeCommand(remoteCodexUpgradeScript(null, latest), updatePre);
|
|
1638
|
+
const result = await runSshCommand(host, wrapped.command, wrapped.stdin, 60_000, 60_000);
|
|
1639
|
+
if (result.code !== 0) throw new Error((result.stderr || result.stdout).trim().split(/\r?\n/).filter(Boolean).at(-1) || "远端 Codex 检查失败");
|
|
1640
|
+
return parseCodexUpgradeOutput(result.stdout);
|
|
1641
|
+
},
|
|
1642
|
+
async install(host, target) {
|
|
1643
|
+
if (hostConfigRestarts.view(host)?.status === "running" || appServerAuthRecoveryHosts.has(host)) {
|
|
1644
|
+
throw new Error("主机正在重启或迁移账号,请稍后再升级");
|
|
1645
|
+
}
|
|
1646
|
+
const runtime = hostRuntimeConfig(host);
|
|
1647
|
+
const updatePre = runtime?.updatePreCommand?.trim() || runtime?.preLaunchCommand?.trim() || "";
|
|
1648
|
+
const wrapped = wrapCodexUpgradeCommand(remoteCodexUpgradeScript(target), updatePre);
|
|
1649
|
+
const result = await runSshCommand(host, wrapped.command, wrapped.stdin, 360_000, 60_000);
|
|
1650
|
+
if (result.code !== 0) throw new Error((result.stderr || result.stdout).trim().split(/\r?\n/).filter(Boolean).at(-1) || "远端 Codex 安装失败");
|
|
1651
|
+
return parseCodexUpgradeOutput(result.stdout);
|
|
1652
|
+
},
|
|
1653
|
+
async restart(host) {
|
|
1654
|
+
if (!appServerManager.sessionRecords().some((s) => s.host === host)) return { status: "completed", results: [] };
|
|
1655
|
+
await hostConfigRestarts.start(host).done;
|
|
1656
|
+
return hostConfigRestarts.view(host);
|
|
1657
|
+
},
|
|
1658
|
+
running(host) {
|
|
1659
|
+
return appServerManager.publicState().connections
|
|
1660
|
+
.filter((c) => c.host === host && c.sessionIds.length)
|
|
1661
|
+
.map((c) => ({ connectionKey: c.connectionKey, status: c.status,
|
|
1662
|
+
version: c.serverInfo?.userAgent?.match(/scope-ssh-monitor\/(\d+\.\d+\.\d+)/)?.[1] || null,
|
|
1663
|
+
sessions: c.sessionIds.length }));
|
|
1664
|
+
},
|
|
1665
|
+
});
|
|
1666
|
+
|
|
1667
|
+
function recoverHostAppServerSessions(hostAlias) {
|
|
1668
|
+
const inFlight = appServerHostRecoveryJobs.get(hostAlias);
|
|
1669
|
+
if (inFlight) return inFlight;
|
|
1670
|
+
|
|
1671
|
+
const recovery = (async () => {
|
|
1672
|
+
const records = Array.from(persistedAppServerSessions.values()).filter(
|
|
1673
|
+
(record) => record.host === hostAlias,
|
|
1674
|
+
);
|
|
1675
|
+
if (!records.length) {
|
|
1676
|
+
const error = new Error(`主机 ${hostAlias} 没有 SCOPE 托管的 app-server Session`);
|
|
1677
|
+
error.statusCode = 404;
|
|
1678
|
+
throw error;
|
|
1679
|
+
}
|
|
1680
|
+
if (!snapshot.hosts.some((host) => host.alias === hostAlias)) {
|
|
1681
|
+
const error = new Error(`SSH 配置中找不到主机 ${hostAlias}`);
|
|
1682
|
+
error.statusCode = 404;
|
|
1683
|
+
throw error;
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
const reconnectTimer = appServerReconnectTimers.get(hostAlias);
|
|
1687
|
+
if (reconnectTimer) clearTimeout(reconnectTimer);
|
|
1688
|
+
appServerReconnectTimers.delete(hostAlias);
|
|
1689
|
+
appServerReconnectAttempts.delete(hostAlias);
|
|
1690
|
+
|
|
1691
|
+
const before = new Map(
|
|
1692
|
+
appServerManager
|
|
1693
|
+
.sessionRecords()
|
|
1694
|
+
.filter((session) => session.host === hostAlias)
|
|
1695
|
+
.map((session) => [session.sessionId, session]),
|
|
1696
|
+
);
|
|
1697
|
+
const results = [];
|
|
1698
|
+
|
|
1699
|
+
try {
|
|
1700
|
+
await appServerManager.prepareHost(
|
|
1701
|
+
hostAlias,
|
|
1702
|
+
records.find((record) => record.executable)?.executable || "codex",
|
|
1703
|
+
);
|
|
1704
|
+
} catch (error) {
|
|
1705
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1706
|
+
for (const record of records) {
|
|
1707
|
+
results.push({
|
|
1708
|
+
sessionId: record.sessionId,
|
|
1709
|
+
status: "failed",
|
|
1710
|
+
error: message,
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
await auditLifecycle("app-server-host-recovery-failed", {
|
|
1714
|
+
host: hostAlias,
|
|
1715
|
+
sessions: records.length,
|
|
1716
|
+
error: message,
|
|
1717
|
+
remoteSessionSignalSent: false,
|
|
1718
|
+
});
|
|
1719
|
+
return {
|
|
1720
|
+
ok: false,
|
|
1721
|
+
host: hostAlias,
|
|
1722
|
+
total: records.length,
|
|
1723
|
+
reconnected: 0,
|
|
1724
|
+
continued: 0,
|
|
1725
|
+
alreadyWorking: 0,
|
|
1726
|
+
alreadyRecovering: 0,
|
|
1727
|
+
idle: 0,
|
|
1728
|
+
failed: records.length,
|
|
1729
|
+
results,
|
|
1730
|
+
};
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
const currentHost = snapshot.hosts.find((host) => host.alias === hostAlias);
|
|
1734
|
+
for (const record of records) {
|
|
1735
|
+
const previous = before.get(record.sessionId);
|
|
1736
|
+
const shouldContinue = Boolean(
|
|
1737
|
+
previous?.resumeOnRecovery ||
|
|
1738
|
+
previous?.status === "working" ||
|
|
1739
|
+
record.resumeOnRecovery,
|
|
1740
|
+
);
|
|
1741
|
+
const externalOwner = currentHost?.agents?.find(
|
|
1742
|
+
(agent) =>
|
|
1743
|
+
agent.rollout?.id === record.sessionId && !agent.appServerManaged,
|
|
1744
|
+
);
|
|
1745
|
+
if (externalOwner) {
|
|
1746
|
+
results.push({
|
|
1747
|
+
sessionId: record.sessionId,
|
|
1748
|
+
status: "failed",
|
|
1749
|
+
error: `当前由外部 CLI/VS Code PID ${externalOwner.pid} 持有`,
|
|
1750
|
+
});
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
try {
|
|
1755
|
+
let session = appServerManager
|
|
1756
|
+
.sessionRecords()
|
|
1757
|
+
.find(
|
|
1758
|
+
(candidate) =>
|
|
1759
|
+
candidate.host === hostAlias &&
|
|
1760
|
+
candidate.sessionId === record.sessionId &&
|
|
1761
|
+
candidate.status !== "offline",
|
|
1762
|
+
);
|
|
1763
|
+
let reconnected = false;
|
|
1764
|
+
if (!session) {
|
|
1765
|
+
session = await resumeManagedAppServerSession({
|
|
1766
|
+
host: record.host,
|
|
1767
|
+
sessionId: record.sessionId,
|
|
1768
|
+
path: record.path,
|
|
1769
|
+
cwd: record.cwd,
|
|
1770
|
+
model: record.model || null,
|
|
1771
|
+
effort: record.effort || null,
|
|
1772
|
+
yolo: record.yolo !== false,
|
|
1773
|
+
readOnly: record.readOnly === true,
|
|
1774
|
+
executable: record.executable || "codex",
|
|
1775
|
+
resumeOnRecovery: shouldContinue,
|
|
1776
|
+
connectionKey: record.connectionKey,
|
|
1777
|
+
});
|
|
1778
|
+
reconnected = true;
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
if (session.status === "working") {
|
|
1782
|
+
results.push({
|
|
1783
|
+
sessionId: record.sessionId,
|
|
1784
|
+
status: "already-working",
|
|
1785
|
+
reconnected,
|
|
1786
|
+
});
|
|
1787
|
+
continue;
|
|
1788
|
+
}
|
|
1789
|
+
if (
|
|
1790
|
+
session.capacityRecovery &&
|
|
1791
|
+
["scheduled", "waiting", "sending", "sent"].includes(
|
|
1792
|
+
session.capacityRecovery.status,
|
|
1793
|
+
)
|
|
1794
|
+
) {
|
|
1795
|
+
results.push({
|
|
1796
|
+
sessionId: record.sessionId,
|
|
1797
|
+
status: "already-recovering",
|
|
1798
|
+
reconnected,
|
|
1799
|
+
});
|
|
1800
|
+
continue;
|
|
1801
|
+
}
|
|
1802
|
+
if (shouldContinue) {
|
|
1803
|
+
await appServerManager.startTurn(hostAlias, record.sessionId, "继续", {
|
|
1804
|
+
automaticRecovery: true,
|
|
1805
|
+
effort: record.effort || null,
|
|
1806
|
+
});
|
|
1807
|
+
results.push({
|
|
1808
|
+
sessionId: record.sessionId,
|
|
1809
|
+
status: "continued",
|
|
1810
|
+
reconnected,
|
|
1811
|
+
});
|
|
1812
|
+
continue;
|
|
1813
|
+
}
|
|
1814
|
+
results.push({
|
|
1815
|
+
sessionId: record.sessionId,
|
|
1816
|
+
status: reconnected ? "reconnected-idle" : "idle",
|
|
1817
|
+
reconnected,
|
|
1818
|
+
});
|
|
1819
|
+
} catch (error) {
|
|
1820
|
+
results.push({
|
|
1821
|
+
sessionId: record.sessionId,
|
|
1822
|
+
status: "failed",
|
|
1823
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1824
|
+
});
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1828
|
+
await persistAppServerSessions();
|
|
1829
|
+
const summary = {
|
|
1830
|
+
ok: results.every((result) => result.status !== "failed"),
|
|
1831
|
+
host: hostAlias,
|
|
1832
|
+
total: results.length,
|
|
1833
|
+
reconnected: results.filter((result) => result.reconnected).length,
|
|
1834
|
+
continued: results.filter((result) => result.status === "continued").length,
|
|
1835
|
+
alreadyWorking: results.filter(
|
|
1836
|
+
(result) => result.status === "already-working",
|
|
1837
|
+
).length,
|
|
1838
|
+
alreadyRecovering: results.filter(
|
|
1839
|
+
(result) => result.status === "already-recovering",
|
|
1840
|
+
).length,
|
|
1841
|
+
idle: results.filter((result) =>
|
|
1842
|
+
["idle", "reconnected-idle"].includes(result.status),
|
|
1843
|
+
).length,
|
|
1844
|
+
failed: results.filter((result) => result.status === "failed").length,
|
|
1845
|
+
results,
|
|
1846
|
+
};
|
|
1847
|
+
await auditLifecycle("app-server-host-recovered", {
|
|
1848
|
+
host: hostAlias,
|
|
1849
|
+
total: summary.total,
|
|
1850
|
+
reconnected: summary.reconnected,
|
|
1851
|
+
continued: summary.continued,
|
|
1852
|
+
alreadyWorking: summary.alreadyWorking,
|
|
1853
|
+
alreadyRecovering: summary.alreadyRecovering,
|
|
1854
|
+
idle: summary.idle,
|
|
1855
|
+
failed: summary.failed,
|
|
1856
|
+
remoteSessionSignalSent: summary.continued > 0,
|
|
1857
|
+
});
|
|
1858
|
+
notifyClients();
|
|
1859
|
+
setTimeout(() => scanAll({ force: true, hosts: [hostAlias] }).catch(() => {}), 300);
|
|
1860
|
+
return summary;
|
|
1861
|
+
})().finally(() => appServerHostRecoveryJobs.delete(hostAlias));
|
|
1862
|
+
|
|
1863
|
+
appServerHostRecoveryJobs.set(hostAlias, recovery);
|
|
1864
|
+
return recovery;
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
function recoverAuthenticationFailedSessions(
|
|
1868
|
+
hostAlias,
|
|
1869
|
+
{ sessionIds = null, sourceConnectionKey = null } = {},
|
|
1870
|
+
) {
|
|
1871
|
+
const jobKey = `${hostAlias}:${sourceConnectionKey || "explicit"}`;
|
|
1872
|
+
const existing = appServerAuthRecoveryJobs.get(jobKey);
|
|
1873
|
+
if (existing) return existing;
|
|
1874
|
+
|
|
1875
|
+
appServerAuthRecoveryHosts.add(hostAlias);
|
|
1876
|
+
const reconnectTimer = appServerReconnectTimers.get(hostAlias);
|
|
1877
|
+
if (reconnectTimer) clearTimeout(reconnectTimer);
|
|
1878
|
+
appServerReconnectTimers.delete(hostAlias);
|
|
1879
|
+
appServerReconnectAttempts.delete(hostAlias);
|
|
1880
|
+
|
|
1881
|
+
const recovery = (async () => {
|
|
1882
|
+
const requestedIds = Array.isArray(sessionIds)
|
|
1883
|
+
? new Set(sessionIds.map((value) => String(value || "").trim()).filter(Boolean))
|
|
1884
|
+
: null;
|
|
1885
|
+
const requestedSessions = appServerManager.sessionRecords().filter((session) => {
|
|
1886
|
+
if (fixedProfileSession(session)) return false;
|
|
1887
|
+
if (session.host !== hostAlias || session.status === "working") return false;
|
|
1888
|
+
if (requestedIds && !requestedIds.has(session.sessionId)) return false;
|
|
1889
|
+
if (
|
|
1890
|
+
sourceConnectionKey &&
|
|
1891
|
+
appServerConnectionKey(session.connectionKey) !==
|
|
1892
|
+
appServerConnectionKey(sourceConnectionKey)
|
|
1893
|
+
) {
|
|
1894
|
+
return false;
|
|
1895
|
+
}
|
|
1896
|
+
return appServerConnectionKey(session.connectionKey) !== "active";
|
|
1897
|
+
});
|
|
1898
|
+
const results = [];
|
|
1899
|
+
|
|
1900
|
+
// An explicit recovery request is scoped to individual interrupted threads.
|
|
1901
|
+
// Moving the whole profile writer would also stop unrelated working turns that
|
|
1902
|
+
// still share it, so migrate each selected thread to the active profile instead.
|
|
1903
|
+
if (requestedIds) {
|
|
1904
|
+
for (const previous of requestedSessions) {
|
|
1905
|
+
try {
|
|
1906
|
+
const fromConnectionKey = appServerConnectionKey(previous.connectionKey);
|
|
1907
|
+
let migrated;
|
|
1908
|
+
let forkedFromSessionId = null;
|
|
1909
|
+
try {
|
|
1910
|
+
migrated = await appServerManager.migrateSessionConnection(
|
|
1911
|
+
hostAlias,
|
|
1912
|
+
previous.sessionId,
|
|
1913
|
+
"active",
|
|
1914
|
+
previous.executable || "codex",
|
|
1915
|
+
);
|
|
1916
|
+
} catch (error) {
|
|
1917
|
+
if (!/already has an active writer/i.test(error?.message || "")) {
|
|
1918
|
+
throw error;
|
|
1919
|
+
}
|
|
1920
|
+
migrated = await appServerManager.forkSessionConnection(
|
|
1921
|
+
hostAlias,
|
|
1922
|
+
previous.sessionId,
|
|
1923
|
+
"active",
|
|
1924
|
+
previous.executable || "codex",
|
|
1925
|
+
);
|
|
1926
|
+
forkedFromSessionId = previous.sessionId;
|
|
1927
|
+
}
|
|
1928
|
+
await appServerManager.startTurn(hostAlias, migrated.sessionId, "继续", {
|
|
1929
|
+
automaticRecovery: true,
|
|
1930
|
+
effort: previous.effort || null,
|
|
1931
|
+
});
|
|
1932
|
+
results.push({
|
|
1933
|
+
sessionId: migrated.sessionId,
|
|
1934
|
+
forkedFromSessionId,
|
|
1935
|
+
status: forkedFromSessionId ? "forked-continued" : "continued",
|
|
1936
|
+
});
|
|
1937
|
+
await auditLifecycle("app-server-auth-writer-migrated", {
|
|
1938
|
+
host: hostAlias,
|
|
1939
|
+
sessionId: migrated.sessionId,
|
|
1940
|
+
forkedFromSessionId,
|
|
1941
|
+
fromConnectionKey,
|
|
1942
|
+
toConnectionKey: migrated.connectionKey,
|
|
1943
|
+
continued: true,
|
|
1944
|
+
remoteSessionSignalSent: true,
|
|
1945
|
+
});
|
|
1946
|
+
} catch (error) {
|
|
1947
|
+
results.push({
|
|
1948
|
+
sessionId: previous.sessionId,
|
|
1949
|
+
status: "failed",
|
|
1950
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1951
|
+
});
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
await persistAppServerSessions();
|
|
1955
|
+
notifyClients();
|
|
1956
|
+
return {
|
|
1957
|
+
ok: results.every((result) => result.status !== "failed"),
|
|
1958
|
+
host: hostAlias,
|
|
1959
|
+
total: results.length,
|
|
1960
|
+
migrated: 0,
|
|
1961
|
+
continued: results.filter((result) =>
|
|
1962
|
+
["continued", "forked-continued"].includes(result.status),
|
|
1963
|
+
).length,
|
|
1964
|
+
forked: results.filter((result) => result.status === "forked-continued").length,
|
|
1965
|
+
failed: results.filter((result) => result.status === "failed").length,
|
|
1966
|
+
results,
|
|
1967
|
+
};
|
|
1968
|
+
}
|
|
1969
|
+
|
|
1970
|
+
const sourceKeys = new Set(
|
|
1971
|
+
requestedSessions.map((session) => appServerConnectionKey(session.connectionKey)),
|
|
1972
|
+
);
|
|
1973
|
+
for (const sourceKey of sourceKeys) {
|
|
1974
|
+
const sourceSessions = appServerManager
|
|
1975
|
+
.sessionRecords()
|
|
1976
|
+
.filter(
|
|
1977
|
+
(session) =>
|
|
1978
|
+
session.host === hostAlias &&
|
|
1979
|
+
appServerConnectionKey(session.connectionKey) === sourceKey,
|
|
1980
|
+
);
|
|
1981
|
+
const working = sourceSessions.filter((session) => session.status === "working");
|
|
1982
|
+
if (working.length) {
|
|
1983
|
+
for (const session of sourceSessions) {
|
|
1984
|
+
if (requestedIds && !requestedIds.has(session.sessionId)) continue;
|
|
1985
|
+
results.push({
|
|
1986
|
+
sessionId: session.sessionId,
|
|
1987
|
+
status: "failed",
|
|
1988
|
+
error: `旧账号 writer 仍有 ${working.length} 个 Turn 在运行,未终止 daemon`,
|
|
1989
|
+
});
|
|
1990
|
+
}
|
|
1991
|
+
continue;
|
|
1992
|
+
}
|
|
1993
|
+
try {
|
|
1994
|
+
await retireStaleProfileAppServer(hostAlias, sourceKey, sourceSessions);
|
|
1995
|
+
} catch (error) {
|
|
1996
|
+
for (const session of sourceSessions) {
|
|
1997
|
+
if (requestedIds && !requestedIds.has(session.sessionId)) continue;
|
|
1998
|
+
results.push({
|
|
1999
|
+
sessionId: session.sessionId,
|
|
2000
|
+
status: "failed",
|
|
2001
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2002
|
+
});
|
|
2003
|
+
}
|
|
2004
|
+
continue;
|
|
2005
|
+
}
|
|
2006
|
+
for (const previous of sourceSessions) {
|
|
2007
|
+
const shouldContinue =
|
|
2008
|
+
previous.resumeOnRecovery === true ||
|
|
2009
|
+
isAuthenticationRefreshError(previous.lastProtocolError) ||
|
|
2010
|
+
Boolean(requestedIds?.has(previous.sessionId));
|
|
2011
|
+
try {
|
|
2012
|
+
const migrated = await appServerManager.resumeSession({
|
|
2013
|
+
host: hostAlias,
|
|
2014
|
+
sessionId: previous.sessionId,
|
|
2015
|
+
path: previous.path,
|
|
2016
|
+
cwd: previous.cwd,
|
|
2017
|
+
model: previous.model || null,
|
|
2018
|
+
effort: previous.effort || null,
|
|
2019
|
+
yolo: previous.yolo !== false,
|
|
2020
|
+
executable: previous.executable || "codex",
|
|
2021
|
+
resumeOnRecovery: shouldContinue,
|
|
2022
|
+
connectionKey: "active",
|
|
2023
|
+
});
|
|
2024
|
+
let status = "migrated";
|
|
2025
|
+
if (shouldContinue) {
|
|
2026
|
+
await appServerManager.startTurn(hostAlias, previous.sessionId, "继续", {
|
|
2027
|
+
automaticRecovery: true,
|
|
2028
|
+
effort: previous.effort || null,
|
|
2029
|
+
});
|
|
2030
|
+
status = "continued";
|
|
2031
|
+
}
|
|
2032
|
+
results.push({ sessionId: previous.sessionId, status });
|
|
2033
|
+
await auditLifecycle("app-server-auth-writer-migrated", {
|
|
2034
|
+
host: hostAlias,
|
|
2035
|
+
sessionId: previous.sessionId,
|
|
2036
|
+
fromConnectionKey: sourceKey,
|
|
2037
|
+
toConnectionKey: migrated.connectionKey,
|
|
2038
|
+
continued: shouldContinue,
|
|
2039
|
+
remoteSessionSignalSent: shouldContinue,
|
|
2040
|
+
});
|
|
2041
|
+
} catch (error) {
|
|
2042
|
+
results.push({
|
|
2043
|
+
sessionId: previous.sessionId,
|
|
2044
|
+
status: "failed",
|
|
2045
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2046
|
+
});
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
await persistAppServerSessions();
|
|
2051
|
+
notifyClients();
|
|
2052
|
+
return {
|
|
2053
|
+
ok: results.every((result) => result.status !== "failed"),
|
|
2054
|
+
host: hostAlias,
|
|
2055
|
+
total: results.length,
|
|
2056
|
+
migrated: results.filter((result) => result.status === "migrated").length,
|
|
2057
|
+
continued: results.filter((result) => result.status === "continued").length,
|
|
2058
|
+
failed: results.filter((result) => result.status === "failed").length,
|
|
2059
|
+
results,
|
|
2060
|
+
};
|
|
2061
|
+
})().finally(() => {
|
|
2062
|
+
appServerAuthRecoveryJobs.delete(jobKey);
|
|
2063
|
+
appServerAuthRecoveryHosts.delete(hostAlias);
|
|
2064
|
+
scheduleAppServerReconnects();
|
|
2065
|
+
});
|
|
2066
|
+
appServerAuthRecoveryJobs.set(jobKey, recovery);
|
|
2067
|
+
return recovery;
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
async function retireStaleProfileAppServer(host, connectionKey, sessions) {
|
|
2071
|
+
const key = appServerConnectionKey(connectionKey);
|
|
2072
|
+
if (key === "active" || !key.startsWith("profile-")) {
|
|
2073
|
+
throw new Error("拒绝终止非 Profile 的 app-server writer");
|
|
2074
|
+
}
|
|
2075
|
+
if (sessions.some((session) => session.status === "working")) {
|
|
2076
|
+
throw new Error("旧账号 writer 仍有 Turn 在运行,拒绝终止");
|
|
2077
|
+
}
|
|
2078
|
+
const pending = appServerManager
|
|
2079
|
+
.publicState()
|
|
2080
|
+
.pendingRequests.some(
|
|
2081
|
+
(request) =>
|
|
2082
|
+
request.host === host &&
|
|
2083
|
+
appServerConnectionKey(request.connectionKey) === key &&
|
|
2084
|
+
["pending", "responding", "disconnected"].includes(request.status),
|
|
2085
|
+
);
|
|
2086
|
+
if (pending) throw new Error("旧账号 writer 仍有待回答问题或审批,拒绝终止");
|
|
2087
|
+
|
|
2088
|
+
appServerManager.closeConnection(host, key);
|
|
2089
|
+
const command = retireProfileAppServerCommand(key);
|
|
2090
|
+
const result = await runSshCommand(host, command, "", 15_000, 100_000);
|
|
2091
|
+
if (result.code !== 0) {
|
|
2092
|
+
throw new Error(cleanSshError(result.stderr || result.stdout));
|
|
2093
|
+
}
|
|
2094
|
+
await auditLifecycle("app-server-stale-auth-writer-retired", {
|
|
2095
|
+
host,
|
|
2096
|
+
connectionKey: key,
|
|
2097
|
+
sessions: sessions.length,
|
|
2098
|
+
tmux: `scope-app-server-${key}`,
|
|
2099
|
+
remoteSessionSignalSent: false,
|
|
2100
|
+
});
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
function pendingRequestsForConnection(host, connectionKey) {
|
|
2104
|
+
const key = appServerConnectionKey(connectionKey);
|
|
2105
|
+
return appServerManager
|
|
2106
|
+
.publicState()
|
|
2107
|
+
.pendingRequests.filter(
|
|
2108
|
+
(request) =>
|
|
2109
|
+
request.host === host &&
|
|
2110
|
+
appServerConnectionKey(request.connectionKey) === key &&
|
|
2111
|
+
["pending", "responding", "disconnected"].includes(request.status),
|
|
2112
|
+
);
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
function scheduleActiveAuthFailoverAttempt(job, delay = AUTH_PROFILE_FAILOVER_WAIT_MS) {
|
|
2116
|
+
if (appServerActiveAuthFailoverJobs.get(job.host) !== job) return;
|
|
2117
|
+
if (job.timer) clearTimeout(job.timer);
|
|
2118
|
+
job.nextAttemptAt = new Date(Date.now() + delay).toISOString();
|
|
2119
|
+
job.timer = setTimeout(() => {
|
|
2120
|
+
job.timer = null;
|
|
2121
|
+
attemptActiveAuthProfileFailover(job).catch((error) =>
|
|
2122
|
+
finishActiveAuthProfileFailover(job, error),
|
|
2123
|
+
);
|
|
2124
|
+
}, delay);
|
|
2125
|
+
job.timer.unref?.();
|
|
2126
|
+
notifyClients();
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
function finishActiveAuthProfileFailover(job, error = null) {
|
|
2130
|
+
if (job.timer) clearTimeout(job.timer);
|
|
2131
|
+
job.timer = null;
|
|
2132
|
+
job.nextAttemptAt = null;
|
|
2133
|
+
job.completedAt = new Date().toISOString();
|
|
2134
|
+
if (error) {
|
|
2135
|
+
job.status = "failed";
|
|
2136
|
+
job.error = error instanceof Error ? error.message : String(error);
|
|
2137
|
+
auditLifecycle("app-server-auth-profile-failover-failed", {
|
|
2138
|
+
host: job.host,
|
|
2139
|
+
failedProfile: job.failedProfile,
|
|
2140
|
+
targetProfile: job.targetProfile,
|
|
2141
|
+
interruptedSessions: Array.from(job.interruptedSessions),
|
|
2142
|
+
error: job.error,
|
|
2143
|
+
remoteSessionSignalSent: false,
|
|
2144
|
+
}).catch(() => {});
|
|
2145
|
+
} else {
|
|
2146
|
+
job.status = "completed";
|
|
2147
|
+
job.error = null;
|
|
2148
|
+
auditLifecycle("app-server-auth-profile-failover-completed", {
|
|
2149
|
+
host: job.host,
|
|
2150
|
+
failedProfile: job.failedProfile,
|
|
2151
|
+
targetProfile: job.targetProfile,
|
|
2152
|
+
interruptedSessions: Array.from(job.interruptedSessions),
|
|
2153
|
+
continued: job.continued || 0,
|
|
2154
|
+
failed: job.failed || 0,
|
|
2155
|
+
remoteSessionSignalSent: (job.continued || 0) > 0,
|
|
2156
|
+
}).catch(() => {});
|
|
2157
|
+
}
|
|
2158
|
+
appServerAuthRecoveryHosts.delete(job.host);
|
|
2159
|
+
notifyClients();
|
|
2160
|
+
scheduleAppServerReconnects();
|
|
2161
|
+
// Keep the completed state briefly so the profile panel can explain what
|
|
2162
|
+
// happened, while allowing a newly observed auth failure to start a fresh
|
|
2163
|
+
// rotation immediately after the cooldown window is recorded.
|
|
2164
|
+
const cleanup = setTimeout(() => {
|
|
2165
|
+
if (appServerActiveAuthFailoverJobs.get(job.host) === job) {
|
|
2166
|
+
appServerActiveAuthFailoverJobs.delete(job.host);
|
|
2167
|
+
notifyClients();
|
|
2168
|
+
}
|
|
2169
|
+
}, 60_000);
|
|
2170
|
+
cleanup.unref?.();
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
async function chooseActiveAuthFailoverTarget(job) {
|
|
2174
|
+
const profiles = await listAuthProfiles(job.host);
|
|
2175
|
+
const activeSlug = profiles.activeProfile;
|
|
2176
|
+
if (!activeSlug) {
|
|
2177
|
+
throw new Error("当前账号尚未绑定到已保存 Profile,无法安全自动轮换");
|
|
2178
|
+
}
|
|
2179
|
+
if (!job.failedProfile) job.failedProfile = activeSlug;
|
|
2180
|
+
if (activeSlug !== job.failedProfile) {
|
|
2181
|
+
// A manual switch won the race. Use the newly selected profile and only
|
|
2182
|
+
// perform the safe writer restart/resume phase below.
|
|
2183
|
+
const manuallySelected = profiles.profiles.find(
|
|
2184
|
+
(profile) => profile.slug === activeSlug && profile.ready,
|
|
2185
|
+
);
|
|
2186
|
+
if (!manuallySelected) throw new Error("手动切换后的 Profile 不可用");
|
|
2187
|
+
job.targetProfile = manuallySelected.slug;
|
|
2188
|
+
job.targetProfileRecord = manuallySelected;
|
|
2189
|
+
return;
|
|
2190
|
+
}
|
|
2191
|
+
|
|
2192
|
+
const failedUntil = failedProfilesForHost(job.host);
|
|
2193
|
+
markProfileUnavailable(failedUntil, activeSlug);
|
|
2194
|
+
const candidates = orderedReadyProfileCandidates(
|
|
2195
|
+
profiles.profiles,
|
|
2196
|
+
activeSlug,
|
|
2197
|
+
{ failedUntil },
|
|
2198
|
+
);
|
|
2199
|
+
if (!candidates.length) {
|
|
2200
|
+
throw new Error("没有另一套已登录且未处于冷却期的 Profile");
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
for (const candidate of candidates) {
|
|
2204
|
+
job.attemptedProfiles.push(candidate.slug);
|
|
2205
|
+
const candidateKey = `profile-${candidate.slug}`;
|
|
2206
|
+
const candidateSessions = appServerManager
|
|
2207
|
+
.sessionRecords()
|
|
2208
|
+
.filter(
|
|
2209
|
+
(session) =>
|
|
2210
|
+
session.host === job.host &&
|
|
2211
|
+
appServerConnectionKey(session.connectionKey) === candidateKey,
|
|
2212
|
+
);
|
|
2213
|
+
if (
|
|
2214
|
+
candidateSessions.some((session) => session.status === "working") ||
|
|
2215
|
+
pendingRequestsForConnection(job.host, candidateKey).length
|
|
2216
|
+
) {
|
|
2217
|
+
continue;
|
|
2218
|
+
}
|
|
2219
|
+
try {
|
|
2220
|
+
await probeAuthProfile(job.host, job.executable, candidate);
|
|
2221
|
+
job.targetProfile = candidate.slug;
|
|
2222
|
+
job.targetProfileRecord = candidate;
|
|
2223
|
+
await auditLifecycle("app-server-auth-profile-probe-succeeded", {
|
|
2224
|
+
host: job.host,
|
|
2225
|
+
profile: candidate.slug,
|
|
2226
|
+
remoteSessionSignalSent: false,
|
|
2227
|
+
});
|
|
2228
|
+
return;
|
|
2229
|
+
} catch (error) {
|
|
2230
|
+
markProfileUnavailable(failedUntil, candidate.slug);
|
|
2231
|
+
await auditLifecycle("app-server-auth-profile-probe-failed", {
|
|
2232
|
+
host: job.host,
|
|
2233
|
+
profile: candidate.slug,
|
|
2234
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2235
|
+
remoteSessionSignalSent: false,
|
|
2236
|
+
});
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
throw new Error("其余 Profile 均未通过 refresh-token 可用性检查");
|
|
2240
|
+
}
|
|
2241
|
+
|
|
2242
|
+
async function attemptActiveAuthProfileFailover(job) {
|
|
2243
|
+
if (appServerActiveAuthFailoverJobs.get(job.host) !== job) return;
|
|
2244
|
+
assertNoPendingProfileMigration(job.host);
|
|
2245
|
+
if (!job.targetProfileRecord) await chooseActiveAuthFailoverTarget(job);
|
|
2246
|
+
|
|
2247
|
+
const sourceSessions = appServerManager
|
|
2248
|
+
.sessionRecords()
|
|
2249
|
+
.filter(
|
|
2250
|
+
(session) =>
|
|
2251
|
+
session.host === job.host &&
|
|
2252
|
+
appServerConnectionKey(session.connectionKey) === "active",
|
|
2253
|
+
);
|
|
2254
|
+
const working = sourceSessions.filter((session) => session.status === "working");
|
|
2255
|
+
const pending = pendingRequestsForConnection(job.host, "active");
|
|
2256
|
+
if (working.length || pending.length) {
|
|
2257
|
+
job.status = "waiting-for-turns";
|
|
2258
|
+
job.waitingForSessions = new Set([
|
|
2259
|
+
...working.map((session) => session.sessionId),
|
|
2260
|
+
...pending.map((request) => request.threadId).filter(Boolean),
|
|
2261
|
+
]);
|
|
2262
|
+
if (!job.waitingAuditWritten) {
|
|
2263
|
+
job.waitingAuditWritten = true;
|
|
2264
|
+
await auditLifecycle("app-server-auth-profile-failover-deferred", {
|
|
2265
|
+
host: job.host,
|
|
2266
|
+
failedProfile: job.failedProfile,
|
|
2267
|
+
targetProfile: job.targetProfile,
|
|
2268
|
+
waitingForSessions: Array.from(job.waitingForSessions),
|
|
2269
|
+
reason: "preserving active turns and pending approvals",
|
|
2270
|
+
remoteSessionSignalSent: false,
|
|
2271
|
+
});
|
|
2272
|
+
}
|
|
2273
|
+
scheduleActiveAuthFailoverAttempt(job);
|
|
2274
|
+
return;
|
|
2275
|
+
}
|
|
2276
|
+
|
|
2277
|
+
job.status = "switching";
|
|
2278
|
+
job.waitingForSessions = new Set();
|
|
2279
|
+
job.nextAttemptAt = null;
|
|
2280
|
+
appServerAuthRecoveryHosts.add(job.host);
|
|
2281
|
+
const reconnectTimer = appServerReconnectTimers.get(job.host);
|
|
2282
|
+
if (reconnectTimer) clearTimeout(reconnectTimer);
|
|
2283
|
+
appServerReconnectTimers.delete(job.host);
|
|
2284
|
+
appServerReconnectAttempts.delete(job.host);
|
|
2285
|
+
notifyClients();
|
|
2286
|
+
|
|
2287
|
+
const sourceSnapshot = sourceSessions.map((session) => ({ ...session }));
|
|
2288
|
+
const targetKey = `profile-${job.targetProfile}`;
|
|
2289
|
+
const targetSessions = appServerManager
|
|
2290
|
+
.sessionRecords()
|
|
2291
|
+
.filter(
|
|
2292
|
+
(session) =>
|
|
2293
|
+
session.host === job.host &&
|
|
2294
|
+
appServerConnectionKey(session.connectionKey) === targetKey,
|
|
2295
|
+
);
|
|
2296
|
+
let activeConnectionClosed = false;
|
|
2297
|
+
let targetActivated = false;
|
|
2298
|
+
try {
|
|
2299
|
+
await retireStaleProfileAppServer(job.host, targetKey, targetSessions);
|
|
2300
|
+
|
|
2301
|
+
appServerManager.closeConnection(job.host, "active");
|
|
2302
|
+
activeConnectionClosed = true;
|
|
2303
|
+
if (job.failedProfile) {
|
|
2304
|
+
const failedKey = `profile-${job.failedProfile}`;
|
|
2305
|
+
const result = await runSshCommand(
|
|
2306
|
+
job.host,
|
|
2307
|
+
retireProfileAppServerCommand(failedKey),
|
|
2308
|
+
"",
|
|
2309
|
+
15_000,
|
|
2310
|
+
100_000,
|
|
2311
|
+
);
|
|
2312
|
+
if (result.code !== 0) {
|
|
2313
|
+
throw new Error(cleanSshError(result.stderr || result.stdout));
|
|
2314
|
+
}
|
|
2315
|
+
await auditLifecycle("app-server-failed-active-writer-retired", {
|
|
2316
|
+
host: job.host,
|
|
2317
|
+
connectionKey: failedKey,
|
|
2318
|
+
sessions: sourceSnapshot.length,
|
|
2319
|
+
remoteSessionSignalSent: false,
|
|
2320
|
+
});
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
await runProfileWrite(
|
|
2324
|
+
job.host,
|
|
2325
|
+
"activate",
|
|
2326
|
+
{
|
|
2327
|
+
slug: job.targetProfileRecord.slug,
|
|
2328
|
+
name: job.targetProfileRecord.name || job.targetProfileRecord.slug,
|
|
2329
|
+
},
|
|
2330
|
+
null,
|
|
2331
|
+
);
|
|
2332
|
+
targetActivated = true;
|
|
2333
|
+
} catch (error) {
|
|
2334
|
+
// Until activation succeeds, the remote marker still points at the old
|
|
2335
|
+
// profile. Reconnect every captured thread to that writer so a failed
|
|
2336
|
+
// switch cannot strand otherwise healthy sessions offline.
|
|
2337
|
+
if (activeConnectionClosed && !targetActivated) {
|
|
2338
|
+
let rollbackFailures = 0;
|
|
2339
|
+
for (const previous of sourceSnapshot) {
|
|
2340
|
+
try {
|
|
2341
|
+
await appServerManager.resumeSession({
|
|
2342
|
+
host: job.host,
|
|
2343
|
+
sessionId: previous.sessionId,
|
|
2344
|
+
path: previous.path,
|
|
2345
|
+
cwd: previous.cwd,
|
|
2346
|
+
model: previous.model || null,
|
|
2347
|
+
effort: previous.effort || null,
|
|
2348
|
+
yolo: previous.yolo !== false,
|
|
2349
|
+
executable: previous.executable || job.executable || "codex",
|
|
2350
|
+
resumeOnRecovery: previous.resumeOnRecovery === true,
|
|
2351
|
+
connectionKey: "active",
|
|
2352
|
+
});
|
|
2353
|
+
} catch {
|
|
2354
|
+
rollbackFailures += 1;
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
await auditLifecycle("app-server-auth-profile-failover-rolled-back", {
|
|
2358
|
+
host: job.host,
|
|
2359
|
+
failedProfile: job.failedProfile,
|
|
2360
|
+
targetProfile: job.targetProfile,
|
|
2361
|
+
restored: sourceSnapshot.length - rollbackFailures,
|
|
2362
|
+
failed: rollbackFailures,
|
|
2363
|
+
remoteSessionSignalSent: false,
|
|
2364
|
+
});
|
|
2365
|
+
}
|
|
2366
|
+
throw error;
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
const results = [];
|
|
2370
|
+
for (const previous of sourceSnapshot) {
|
|
2371
|
+
const shouldContinue =
|
|
2372
|
+
previous.resumeOnRecovery === true ||
|
|
2373
|
+
job.interruptedSessions.has(previous.sessionId);
|
|
2374
|
+
try {
|
|
2375
|
+
await appServerManager.resumeSession({
|
|
2376
|
+
host: job.host,
|
|
2377
|
+
sessionId: previous.sessionId,
|
|
2378
|
+
path: previous.path,
|
|
2379
|
+
cwd: previous.cwd,
|
|
2380
|
+
model: previous.model || null,
|
|
2381
|
+
effort: previous.effort || null,
|
|
2382
|
+
yolo: previous.yolo !== false,
|
|
2383
|
+
executable: previous.executable || job.executable || "codex",
|
|
2384
|
+
resumeOnRecovery: shouldContinue,
|
|
2385
|
+
connectionKey: "active",
|
|
2386
|
+
});
|
|
2387
|
+
if (shouldContinue) {
|
|
2388
|
+
await appServerManager.startTurn(job.host, previous.sessionId, "继续", {
|
|
2389
|
+
automaticRecovery: true,
|
|
2390
|
+
effort: previous.effort || null,
|
|
2391
|
+
});
|
|
2392
|
+
}
|
|
2393
|
+
results.push({
|
|
2394
|
+
sessionId: previous.sessionId,
|
|
2395
|
+
status: shouldContinue ? "continued" : "migrated",
|
|
2396
|
+
});
|
|
2397
|
+
} catch (error) {
|
|
2398
|
+
results.push({
|
|
2399
|
+
sessionId: previous.sessionId,
|
|
2400
|
+
status: "failed",
|
|
2401
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2402
|
+
});
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
job.results = results;
|
|
2406
|
+
job.continued = results.filter((result) => result.status === "continued").length;
|
|
2407
|
+
job.failed = results.filter((result) => result.status === "failed").length;
|
|
2408
|
+
await persistAppServerSessions();
|
|
2409
|
+
finishActiveAuthProfileFailover(
|
|
2410
|
+
job,
|
|
2411
|
+
job.failed ? new Error(`${job.failed} 个 Session 在账号轮换后恢复失败`) : null,
|
|
2412
|
+
);
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
function beginActiveAuthProfileFailover({ host, sessionId, error }) {
|
|
2416
|
+
const current = appServerActiveAuthFailoverJobs.get(host);
|
|
2417
|
+
if (current && !["completed", "failed"].includes(current.status)) {
|
|
2418
|
+
current.interruptedSessions.add(sessionId);
|
|
2419
|
+
current.error = current.error || error || null;
|
|
2420
|
+
notifyClients();
|
|
2421
|
+
return publicProfileFailoverJob(current);
|
|
2422
|
+
}
|
|
2423
|
+
const hostSnapshot = snapshot.hosts.find(
|
|
2424
|
+
(candidate) => candidate.alias === host && candidate.reachable,
|
|
2425
|
+
);
|
|
2426
|
+
const job = {
|
|
2427
|
+
host,
|
|
2428
|
+
executable: hostCodexExecutable(hostSnapshot),
|
|
2429
|
+
status: "checking-profiles",
|
|
2430
|
+
failedProfile: null,
|
|
2431
|
+
targetProfile: null,
|
|
2432
|
+
targetProfileRecord: null,
|
|
2433
|
+
interruptedSessions: new Set([sessionId]),
|
|
2434
|
+
waitingForSessions: new Set(),
|
|
2435
|
+
attemptedProfiles: [],
|
|
2436
|
+
startedAt: new Date().toISOString(),
|
|
2437
|
+
completedAt: null,
|
|
2438
|
+
nextAttemptAt: null,
|
|
2439
|
+
error: error || null,
|
|
2440
|
+
timer: null,
|
|
2441
|
+
results: [],
|
|
2442
|
+
};
|
|
2443
|
+
appServerActiveAuthFailoverJobs.set(host, job);
|
|
2444
|
+
auditLifecycle("app-server-auth-profile-failover-started", {
|
|
2445
|
+
host,
|
|
2446
|
+
sessionId,
|
|
2447
|
+
authenticationError: error,
|
|
2448
|
+
remoteSessionSignalSent: false,
|
|
2449
|
+
}).catch(() => {});
|
|
2450
|
+
attemptActiveAuthProfileFailover(job).catch((failure) =>
|
|
2451
|
+
finishActiveAuthProfileFailover(job, failure),
|
|
2452
|
+
);
|
|
2453
|
+
notifyClients();
|
|
2454
|
+
return publicProfileFailoverJob(job);
|
|
2455
|
+
}
|
|
2456
|
+
|
|
2457
|
+
function publicAuthRestartJob(job) {
|
|
2458
|
+
return {
|
|
2459
|
+
id: job.id,
|
|
2460
|
+
host: job.host,
|
|
2461
|
+
status: job.status,
|
|
2462
|
+
total: job.total,
|
|
2463
|
+
completed: job.completed,
|
|
2464
|
+
startedAt: job.startedAt,
|
|
2465
|
+
completedAt: job.completedAt,
|
|
2466
|
+
results: job.results,
|
|
2467
|
+
error: job.error,
|
|
2468
|
+
};
|
|
2469
|
+
}
|
|
2470
|
+
|
|
2471
|
+
function latestAuthRestartJob(host) {
|
|
2472
|
+
return Array.from(authRestartJobs.values())
|
|
2473
|
+
.filter((job) => job.host === host)
|
|
2474
|
+
.sort((left, right) => Date.parse(right.startedAt) - Date.parse(left.startedAt))[0] || null;
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
async function loadAuthRestartJobs() {
|
|
2478
|
+
try {
|
|
2479
|
+
const parsed = JSON.parse(await readFile(AUTH_RESTART_JOBS_FILE, "utf8"));
|
|
2480
|
+
for (const stored of Array.isArray(parsed?.jobs) ? parsed.jobs : []) {
|
|
2481
|
+
if (!stored?.id || !stored?.host) continue;
|
|
2482
|
+
const interrupted = ["queued", "running"].includes(stored.status);
|
|
2483
|
+
authRestartJobs.set(stored.id, {
|
|
2484
|
+
...stored,
|
|
2485
|
+
status: interrupted ? "failed" : stored.status,
|
|
2486
|
+
completedAt: interrupted
|
|
2487
|
+
? stored.completedAt || new Date().toISOString()
|
|
2488
|
+
: stored.completedAt,
|
|
2489
|
+
error: interrupted
|
|
2490
|
+
? stored.error || "Bridge 重启中断了批量恢复;可从 Inactive 逐项重试"
|
|
2491
|
+
: stored.error || null,
|
|
2492
|
+
});
|
|
2493
|
+
}
|
|
2494
|
+
} catch (error) {
|
|
2495
|
+
if (error?.code !== "ENOENT") {
|
|
2496
|
+
console.error(`无法读取 ${AUTH_RESTART_JOBS_FILE}: ${error.message}`);
|
|
2497
|
+
}
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
|
|
2501
|
+
function persistAuthRestartJobs() {
|
|
2502
|
+
const jobs = Array.from(authRestartJobs.values())
|
|
2503
|
+
.sort((left, right) => Date.parse(right.startedAt) - Date.parse(left.startedAt))
|
|
2504
|
+
.slice(0, 20)
|
|
2505
|
+
.map(publicAuthRestartJob);
|
|
2506
|
+
const serialized = `${JSON.stringify({ version: 1, jobs }, null, 2)}\n`;
|
|
2507
|
+
authRestartWritePromise = authRestartWritePromise
|
|
2508
|
+
.catch(() => {})
|
|
2509
|
+
.then(async () => {
|
|
2510
|
+
await mkdir(STATE_DIR, { recursive: true });
|
|
2511
|
+
const temporary = `${AUTH_RESTART_JOBS_FILE}.tmp`;
|
|
2512
|
+
await writeFile(temporary, serialized, "utf8");
|
|
2513
|
+
await rename(temporary, AUTH_RESTART_JOBS_FILE);
|
|
2514
|
+
});
|
|
2515
|
+
return authRestartWritePromise;
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
function startAuthRestart(hostAlias) {
|
|
2519
|
+
assertNoPendingProfileMigration(hostAlias);
|
|
2520
|
+
const existing = Array.from(authRestartJobs.values()).find(
|
|
2521
|
+
(job) => job.host === hostAlias && ["queued", "running"].includes(job.status),
|
|
2522
|
+
);
|
|
2523
|
+
if (existing) return publicAuthRestartJob(existing);
|
|
2524
|
+
const host = publicSnapshot().hosts.find(
|
|
2525
|
+
(candidate) => candidate.alias === hostAlias && candidate.reachable,
|
|
2526
|
+
);
|
|
2527
|
+
if (!host) throw new Error(`主机 ${hostAlias} 当前不可连接`);
|
|
2528
|
+
const appServerSessions = appServerManager
|
|
2529
|
+
.sessionRecords()
|
|
2530
|
+
.filter((session) => session.host === hostAlias && !fixedProfileSession(session));
|
|
2531
|
+
// Account changes may restart transports owned by this Bridge, but must never
|
|
2532
|
+
// terminate CLI processes launched from VS Code or another terminal. Those
|
|
2533
|
+
// processes can own foreground evaluations and their lifecycle is external.
|
|
2534
|
+
const candidates = appServerSessions.map((session) => ({
|
|
2535
|
+
sessionId: session.sessionId,
|
|
2536
|
+
transport: "app-server",
|
|
2537
|
+
// closeHost mutates the live record to offline. Preserve the pre-restart
|
|
2538
|
+
// state so interrupted work can receive one continuation turn afterward.
|
|
2539
|
+
session: { ...session },
|
|
2540
|
+
}));
|
|
2541
|
+
const job = {
|
|
2542
|
+
id: randomUUID(),
|
|
2543
|
+
host: hostAlias,
|
|
2544
|
+
status: "queued",
|
|
2545
|
+
total: candidates.length,
|
|
2546
|
+
completed: 0,
|
|
2547
|
+
startedAt: new Date().toISOString(),
|
|
2548
|
+
completedAt: null,
|
|
2549
|
+
results: [],
|
|
2550
|
+
error: null,
|
|
2551
|
+
};
|
|
2552
|
+
authRestartJobs.set(job.id, job);
|
|
2553
|
+
persistAuthRestartJobs().catch(() => {});
|
|
2554
|
+
|
|
2555
|
+
(async () => {
|
|
2556
|
+
appServerAuthRecoveryHosts.add(hostAlias);
|
|
2557
|
+
const reconnectTimer = appServerReconnectTimers.get(hostAlias);
|
|
2558
|
+
if (reconnectTimer) clearTimeout(reconnectTimer);
|
|
2559
|
+
appServerReconnectTimers.delete(hostAlias);
|
|
2560
|
+
appServerReconnectAttempts.delete(hostAlias);
|
|
2561
|
+
try {
|
|
2562
|
+
job.status = "running";
|
|
2563
|
+
persistAuthRestartJobs().catch(() => {});
|
|
2564
|
+
const profiles = await listAuthProfiles(hostAlias);
|
|
2565
|
+
const writerKeys = new Set(
|
|
2566
|
+
appServerSessions
|
|
2567
|
+
.map((session) => appServerConnectionKey(session.connectionKey))
|
|
2568
|
+
.filter((connectionKey) => connectionKey.startsWith("profile-")),
|
|
2569
|
+
);
|
|
2570
|
+
if (profiles.activeProfile) writerKeys.add(`profile-${profiles.activeProfile}`);
|
|
2571
|
+
|
|
2572
|
+
// These are only SCOPE-owned app-server tmux daemons. They retain the
|
|
2573
|
+
// per-thread writer lock after an SSH proxy disconnect, so force restart
|
|
2574
|
+
// must retire them before resuming every thread through the active profile.
|
|
2575
|
+
if (appServerSessions.length) closeUnboundHostConnections(hostAlias);
|
|
2576
|
+
for (const writerKey of writerKeys) {
|
|
2577
|
+
const retired = await runSshCommand(
|
|
2578
|
+
hostAlias,
|
|
2579
|
+
retireProfileAppServerCommand(writerKey),
|
|
2580
|
+
"",
|
|
2581
|
+
15_000,
|
|
2582
|
+
100_000,
|
|
2583
|
+
);
|
|
2584
|
+
if (retired.code !== 0) {
|
|
2585
|
+
throw new Error(
|
|
2586
|
+
`无法终止旧账号 writer ${writerKey}: ${cleanSshError(retired.stderr || retired.stdout)}`,
|
|
2587
|
+
);
|
|
2588
|
+
}
|
|
2589
|
+
await auditLifecycle("app-server-profile-writer-force-restarted", {
|
|
2590
|
+
host: hostAlias,
|
|
2591
|
+
connectionKey: writerKey,
|
|
2592
|
+
remoteSessionSignalSent: false,
|
|
2593
|
+
});
|
|
2594
|
+
}
|
|
2595
|
+
// Persist the target writer before the individual resumes. If a first
|
|
2596
|
+
// attempt races daemon startup, the later retry (or a Bridge restart)
|
|
2597
|
+
// still goes to the newly selected account instead of reviving pro-lite.
|
|
2598
|
+
for (const candidate of candidates) {
|
|
2599
|
+
activeProfileMigrationSessions.add(sessionKey(hostAlias, candidate.sessionId));
|
|
2600
|
+
}
|
|
2601
|
+
await persistAppServerSessions();
|
|
2602
|
+
// Give tmux/codex a moment to close the filesystem writer locks before
|
|
2603
|
+
// opening the same rollout under the newly active profile.
|
|
2604
|
+
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
2605
|
+
|
|
2606
|
+
// Use the real Codex CLI, not the first scanned process executable. A
|
|
2607
|
+
// Codex process can be represented as `node .../codex`, which would make
|
|
2608
|
+
// a durable daemon invoke `node app-server` and immediately exit.
|
|
2609
|
+
const fallbackExecutable = hostCodexExecutable(host);
|
|
2610
|
+
for (const candidate of candidates) {
|
|
2611
|
+
const { sessionId } = candidate;
|
|
2612
|
+
try {
|
|
2613
|
+
if (candidate.transport === "app-server") {
|
|
2614
|
+
const { session } = candidate;
|
|
2615
|
+
const shouldContinue =
|
|
2616
|
+
session.resumeOnRecovery === true ||
|
|
2617
|
+
["working", "attention"].includes(session.status);
|
|
2618
|
+
const resumed = await appServerManager.resumeSession({
|
|
2619
|
+
host: hostAlias,
|
|
2620
|
+
sessionId,
|
|
2621
|
+
path: session.path,
|
|
2622
|
+
cwd: session.cwd,
|
|
2623
|
+
model: session.model || null,
|
|
2624
|
+
effort: session.effort || null,
|
|
2625
|
+
yolo: session.yolo !== false,
|
|
2626
|
+
executable: fallbackExecutable,
|
|
2627
|
+
resumeOnRecovery: shouldContinue,
|
|
2628
|
+
connectionKey: "active",
|
|
2629
|
+
});
|
|
2630
|
+
if (shouldContinue) {
|
|
2631
|
+
await appServerManager.startTurn(hostAlias, resumed.sessionId, "继续", {
|
|
2632
|
+
automaticRecovery: true,
|
|
2633
|
+
effort: session.effort || null,
|
|
2634
|
+
});
|
|
2635
|
+
}
|
|
2636
|
+
job.results.push({
|
|
2637
|
+
sessionId,
|
|
2638
|
+
ok: true,
|
|
2639
|
+
transport: "app-server",
|
|
2640
|
+
target: resumed.sessionId,
|
|
2641
|
+
connectionKey: resumed.connectionKey,
|
|
2642
|
+
continued: shouldContinue,
|
|
2643
|
+
});
|
|
2644
|
+
}
|
|
2645
|
+
} catch (error) {
|
|
2646
|
+
job.results.push({
|
|
2647
|
+
sessionId,
|
|
2648
|
+
ok: false,
|
|
2649
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2650
|
+
});
|
|
2651
|
+
}
|
|
2652
|
+
job.completed += 1;
|
|
2653
|
+
persistAuthRestartJobs().catch(() => {});
|
|
2654
|
+
notifyClients();
|
|
2655
|
+
}
|
|
2656
|
+
job.status = "completed";
|
|
2657
|
+
job.completedAt = new Date().toISOString();
|
|
2658
|
+
persistAuthRestartJobs().catch(() => {});
|
|
2659
|
+
setTimeout(() => scanAll({ hosts: [hostAlias] }).catch(() => {}), 700);
|
|
2660
|
+
} finally {
|
|
2661
|
+
appServerAuthRecoveryHosts.delete(hostAlias);
|
|
2662
|
+
scheduleAppServerReconnects();
|
|
2663
|
+
}
|
|
2664
|
+
})().catch((error) => {
|
|
2665
|
+
job.status = "failed";
|
|
2666
|
+
job.error = error instanceof Error ? error.message : String(error);
|
|
2667
|
+
job.completedAt = new Date().toISOString();
|
|
2668
|
+
persistAuthRestartJobs().catch(() => {});
|
|
2669
|
+
});
|
|
2670
|
+
return publicAuthRestartJob(job);
|
|
2671
|
+
}
|
|
2672
|
+
appServerManager.on("change", () => {
|
|
2673
|
+
persistAppServerSessions().catch((error) =>
|
|
2674
|
+
console.error(`app-server Session 清单写入失败:${error.message}`),
|
|
2675
|
+
);
|
|
2676
|
+
notifyClients();
|
|
2677
|
+
syncHumanRequestNotifications().catch((error) =>
|
|
2678
|
+
console.error(`邮件通知同步失败:${error.message}`),
|
|
2679
|
+
);
|
|
2680
|
+
scheduleAppServerReconnects();
|
|
2681
|
+
});
|
|
2682
|
+
appServerManager.on(
|
|
2683
|
+
"authentication-failure",
|
|
2684
|
+
async ({ host, connectionKey, sessionId, error }) => {
|
|
2685
|
+
if (!await appServerManager.canAutoContinue(host, sessionId)) return;
|
|
2686
|
+
if (profileFromConnection(connectionKey) || sessionProfileAssignment(host, sessionId)?.desiredProfile) return;
|
|
2687
|
+
if (appServerConnectionKey(connectionKey) === "active") {
|
|
2688
|
+
beginActiveAuthProfileFailover({ host, sessionId, error });
|
|
2689
|
+
return;
|
|
2690
|
+
}
|
|
2691
|
+
recoverAuthenticationFailedSessions(host, { sourceConnectionKey: connectionKey }).catch(
|
|
2692
|
+
(recoveryError) =>
|
|
2693
|
+
auditLifecycle("app-server-auth-recovery-failed", {
|
|
2694
|
+
host,
|
|
2695
|
+
sessionId,
|
|
2696
|
+
connectionKey,
|
|
2697
|
+
error: recoveryError instanceof Error ? recoveryError.message : String(recoveryError),
|
|
2698
|
+
authenticationError: error,
|
|
2699
|
+
remoteSessionSignalSent: false,
|
|
2700
|
+
}),
|
|
2701
|
+
);
|
|
2702
|
+
},
|
|
2703
|
+
);
|
|
2704
|
+
appServerManager.on("turn-failure", (failure) => {
|
|
2705
|
+
auditLifecycle("app-server-turn-failed", {
|
|
2706
|
+
...failure,
|
|
2707
|
+
remoteSessionSignalSent: false,
|
|
2708
|
+
}).catch(() => {});
|
|
2709
|
+
});
|
|
2710
|
+
appServerManager.on("thread-system-error", (failure) => {
|
|
2711
|
+
auditLifecycle("app-server-thread-system-error", {
|
|
2712
|
+
...failure,
|
|
2713
|
+
remoteSessionSignalSent: false,
|
|
2714
|
+
}).catch(() => {});
|
|
2715
|
+
});
|
|
2716
|
+
appServerManager.on("thread-archived", ({ host, sessionId, connectionKey }) => {
|
|
2717
|
+
const key = sessionKey(host, sessionId);
|
|
2718
|
+
// Includes descendants acknowledged by the server; never infer that every child succeeded.
|
|
2719
|
+
const existing = managementState.sessions[key]?.archive;
|
|
2720
|
+
const agent = findAgent(host, sessionId);
|
|
2721
|
+
managementState.sessions[key] = { ...managementState.sessions[key], archive: {
|
|
2722
|
+
...existing, host, sessionId, connectionKey, executable: existing?.executable || hostCodexExecutable(host),
|
|
2723
|
+
title: existing?.title || agent?.title || sessionId, cwd: existing?.cwd || agent?.cwd || "",
|
|
2724
|
+
phase: "archived", error: null, archivedAt: new Date().toISOString(),
|
|
2725
|
+
} };
|
|
2726
|
+
persistManagementState().then(notifyClients).catch(error => console.error(`归档记录保存失败:${error.message}`));
|
|
2727
|
+
});
|
|
2728
|
+
appServerManager.on("session-release", ({ host, sessionId, reason, record }) => {
|
|
2729
|
+
if (["stop", "idle"].includes(reason) && record) {
|
|
2730
|
+
const key = sessionKey(host, sessionId);
|
|
2731
|
+
managementState.sessions[key] = { ...managementState.sessions[key],
|
|
2732
|
+
closedSession: persistedAppServerSession(record) };
|
|
2733
|
+
persistManagementState().catch((error) => console.error(`恢复记录保存失败:${error.message}`));
|
|
2734
|
+
}
|
|
2735
|
+
persistedAppServerSessions.delete(sessionKey(host, sessionId));
|
|
2736
|
+
persistAppServerSessions().catch((error) =>
|
|
2737
|
+
console.error(`app-server Session 清单删除失败:${error.message}`),
|
|
2738
|
+
);
|
|
2739
|
+
});
|
|
2740
|
+
syncHumanRequestNotifications().catch((error) =>
|
|
2741
|
+
console.error(`邮件通知初始化失败:${error.message}`),
|
|
2742
|
+
);
|
|
2743
|
+
|
|
2744
|
+
function snapshotInvalidationPayload() {
|
|
2745
|
+
const sync = snapshotSyncStore.info();
|
|
2746
|
+
return `data: ${JSON.stringify({
|
|
2747
|
+
type: "snapshot-invalidated",
|
|
2748
|
+
generatedAt: snapshot.generatedAt,
|
|
2749
|
+
scanning: snapshot.scanning,
|
|
2750
|
+
epoch: sync.epoch,
|
|
2751
|
+
revision: sync.revision,
|
|
2752
|
+
})}\n\n`;
|
|
2753
|
+
}
|
|
2754
|
+
|
|
2755
|
+
function removeEventClient(response) {
|
|
2756
|
+
const client = clients.get(response);
|
|
2757
|
+
if (client?.onDrain) response.removeListener("drain", client.onDrain);
|
|
2758
|
+
clients.delete(response);
|
|
2759
|
+
}
|
|
2760
|
+
|
|
2761
|
+
function writeEventClient(client, payload) {
|
|
2762
|
+
const { response } = client;
|
|
2763
|
+
if (response.destroyed || response.writableEnded) {
|
|
2764
|
+
removeEventClient(response);
|
|
2765
|
+
return;
|
|
2766
|
+
}
|
|
2767
|
+
if (client.blocked) {
|
|
2768
|
+
// Keep only the newest invalidation. Never retain repeated multi-megabyte
|
|
2769
|
+
// snapshots behind a slow or backgrounded browser tab.
|
|
2770
|
+
client.pending = payload;
|
|
2771
|
+
return;
|
|
2772
|
+
}
|
|
2773
|
+
try {
|
|
2774
|
+
if (response.write(payload)) return;
|
|
2775
|
+
client.blocked = true;
|
|
2776
|
+
client.onDrain = () => {
|
|
2777
|
+
client.blocked = false;
|
|
2778
|
+
client.onDrain = null;
|
|
2779
|
+
const pending = client.pending;
|
|
2780
|
+
client.pending = null;
|
|
2781
|
+
if (pending) writeEventClient(client, pending);
|
|
2782
|
+
};
|
|
2783
|
+
response.once("drain", client.onDrain);
|
|
2784
|
+
} catch {
|
|
2785
|
+
removeEventClient(response);
|
|
2786
|
+
}
|
|
2787
|
+
}
|
|
2788
|
+
|
|
2789
|
+
function publishSnapshotSync() {
|
|
2790
|
+
snapshotSyncStore.publish(publicSnapshot());
|
|
2791
|
+
}
|
|
2792
|
+
|
|
2793
|
+
function flushClientNotification() {
|
|
2794
|
+
snapshotNotifyTimer = null;
|
|
2795
|
+
publishSnapshotSync();
|
|
2796
|
+
const payload = snapshotInvalidationPayload();
|
|
2797
|
+
for (const client of clients.values()) writeEventClient(client, payload);
|
|
2798
|
+
}
|
|
2799
|
+
|
|
2800
|
+
function notifyClients() {
|
|
2801
|
+
// App-server streaming can emit many changes per second. Coalesce them into
|
|
2802
|
+
// one bounded sync revision instead of making every browser re-fetch and
|
|
2803
|
+
// parse a multi-megabyte snapshot for every protocol event.
|
|
2804
|
+
if (snapshotNotifyTimer) return;
|
|
2805
|
+
snapshotNotifyTimer = setTimeout(flushClientNotification, 750);
|
|
2806
|
+
snapshotNotifyTimer.unref?.();
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
async function syncHumanRequestNotifications() {
|
|
2810
|
+
const events = appServerManager
|
|
2811
|
+
.publicState()
|
|
2812
|
+
.pendingRequests.map(humanRequestEmailEvent);
|
|
2813
|
+
if (!humanRequestNotificationsPrimed) {
|
|
2814
|
+
humanRequestNotificationsPrimed = true;
|
|
2815
|
+
await emailNotifier.prime(events);
|
|
2816
|
+
return;
|
|
2817
|
+
}
|
|
2818
|
+
await Promise.all(events.map((event) => emailNotifier.notify(event)));
|
|
2819
|
+
}
|
|
2820
|
+
|
|
2821
|
+
async function syncDlcAlertNotifications() {
|
|
2822
|
+
const events = aliyunPlugin.snapshot().alerts.map((alert) =>
|
|
2823
|
+
dlcAlertEmailEvent(alert, aliyunPlugin.snapshot().scannedAt),
|
|
2824
|
+
);
|
|
2825
|
+
if (!dlcAlertNotificationsPrimed) {
|
|
2826
|
+
dlcAlertNotificationsPrimed = true;
|
|
2827
|
+
await emailNotifier.prime(events);
|
|
2828
|
+
return;
|
|
2829
|
+
}
|
|
2830
|
+
await Promise.all(events.map((event) => emailNotifier.notify(event)));
|
|
2831
|
+
}
|
|
2832
|
+
|
|
2833
|
+
function hasConnectedAppServer(alias) {
|
|
2834
|
+
return appServerManager
|
|
2835
|
+
.publicState()
|
|
2836
|
+
.connections.some(
|
|
2837
|
+
(connection) =>
|
|
2838
|
+
connection.host === alias && connection.status === "connected",
|
|
2839
|
+
);
|
|
2840
|
+
}
|
|
2841
|
+
|
|
2842
|
+
async function scanAll({ force = false, hosts: forcedHostList = [] } = {}) {
|
|
2843
|
+
if (scanPromise) return scanPromise;
|
|
2844
|
+
scanPromise = (async () => {
|
|
2845
|
+
snapshot = { ...snapshot, scanning: true };
|
|
2846
|
+
notifyClients();
|
|
2847
|
+
|
|
2848
|
+
let aliases = [];
|
|
2849
|
+
try {
|
|
2850
|
+
aliases = parseSshAliases(await readFile(SSH_CONFIG, "utf8")).filter(alias => alias !== LOCAL_HOST);
|
|
2851
|
+
} catch (error) {
|
|
2852
|
+
snapshot = {
|
|
2853
|
+
...snapshot,
|
|
2854
|
+
generatedAt: snapshot.generatedAt || new Date().toISOString(),
|
|
2855
|
+
scanning: false,
|
|
2856
|
+
sshConfig: SSH_CONFIG,
|
|
2857
|
+
error: `无法读取 SSH Config:${error.message}`,
|
|
2858
|
+
};
|
|
2859
|
+
notifyClients();
|
|
2860
|
+
return snapshot;
|
|
2861
|
+
}
|
|
2862
|
+
|
|
2863
|
+
const scanStartedAt = Date.now();
|
|
2864
|
+
const forcedHosts = new Set(forcedHostList);
|
|
2865
|
+
const previousHosts = new Map(
|
|
2866
|
+
snapshot.hosts.map((host) => [host.alias, host]),
|
|
2867
|
+
);
|
|
2868
|
+
const hosts = await mapLimit(aliases, CONCURRENCY, async (alias) => {
|
|
2869
|
+
const previous = previousHosts.get(alias);
|
|
2870
|
+
const dueAt = hostNextScanAt.get(alias) || 0;
|
|
2871
|
+
if (!force && !forcedHosts.has(alias) && previous && dueAt > scanStartedAt) {
|
|
2872
|
+
return { ...previous, scanDeferred: true };
|
|
2873
|
+
}
|
|
2874
|
+
// Management requests use a separate short-lived SSH connection. Do not
|
|
2875
|
+
// race a full inventory probe against it or replace healthy data with a
|
|
2876
|
+
// transient MaxStartups/timeout failure.
|
|
2877
|
+
if ((sshOperationCounts.get(alias) || 0) > 0 && previous) {
|
|
2878
|
+
return { ...previous, scanDeferred: true };
|
|
2879
|
+
}
|
|
2880
|
+
|
|
2881
|
+
const scanned = parseHost(alias, await runSsh(alias, previous), previous);
|
|
2882
|
+
if (scanned.reachable) {
|
|
2883
|
+
hostFailureStreaks.delete(alias);
|
|
2884
|
+
hostNextScanAt.set(alias, scanStartedAt + POLL_MS);
|
|
2885
|
+
return { ...scanned, scanDeferred: false, stale: false };
|
|
2886
|
+
}
|
|
2887
|
+
|
|
2888
|
+
const streak = (hostFailureStreaks.get(alias) || 0) + 1;
|
|
2889
|
+
hostFailureStreaks.set(alias, streak);
|
|
2890
|
+
const appServerConnected = hasConnectedAppServer(alias);
|
|
2891
|
+
const retryDelay = appServerConnected
|
|
2892
|
+
? Math.min(60_000, POLL_MS * 2 ** Math.min(streak, 3))
|
|
2893
|
+
: Math.min(5 * 60_000, POLL_MS * 2 ** Math.min(streak, 5));
|
|
2894
|
+
hostNextScanAt.set(alias, scanStartedAt + retryDelay);
|
|
2895
|
+
const lastInventoryAt =
|
|
2896
|
+
previous?.inventoryUpdatedAt || snapshot.generatedAt || null;
|
|
2897
|
+
const lastInventoryMs = Date.parse(lastInventoryAt || "");
|
|
2898
|
+
const withinStaleGrace =
|
|
2899
|
+
Number.isFinite(lastInventoryMs) &&
|
|
2900
|
+
scanStartedAt - lastInventoryMs <= INVENTORY_STALE_GRACE_MS;
|
|
2901
|
+
if (
|
|
2902
|
+
previous &&
|
|
2903
|
+
(appServerConnected || (previous.reachable && withinStaleGrace))
|
|
2904
|
+
) {
|
|
2905
|
+
return {
|
|
2906
|
+
...previous,
|
|
2907
|
+
reachable: true,
|
|
2908
|
+
hostname: previous.hostname || alias,
|
|
2909
|
+
latencyMs: scanned.latencyMs,
|
|
2910
|
+
error: null,
|
|
2911
|
+
inventoryError: scanned.error,
|
|
2912
|
+
inventoryUpdatedAt: lastInventoryAt,
|
|
2913
|
+
scanDeferred: false,
|
|
2914
|
+
stale: true,
|
|
2915
|
+
};
|
|
2916
|
+
}
|
|
2917
|
+
return preserveHostSessions(previous, { ...scanned, scanDeferred: false, stale: true });
|
|
2918
|
+
});
|
|
2919
|
+
hosts.unshift(localCodex.host());
|
|
2920
|
+
hosts.sort((a, b) => {
|
|
2921
|
+
if (a.alias === LOCAL_HOST || b.alias === LOCAL_HOST) return a.alias === LOCAL_HOST ? -1 : 1;
|
|
2922
|
+
if (a.reachable !== b.reachable) return a.reachable ? -1 : 1;
|
|
2923
|
+
if (a.agents.length !== b.agents.length) return b.agents.length - a.agents.length;
|
|
2924
|
+
return a.alias.localeCompare(b.alias);
|
|
2925
|
+
});
|
|
2926
|
+
|
|
2927
|
+
gpuUsageHistory = updateGpuUsageHistory(
|
|
2928
|
+
gpuUsageHistory,
|
|
2929
|
+
hosts,
|
|
2930
|
+
Date.now(),
|
|
2931
|
+
);
|
|
2932
|
+
await persistGpuUsageHistory().catch((error) => {
|
|
2933
|
+
console.error(`无法保存 GPU 占用历史: ${error.message}`);
|
|
2934
|
+
});
|
|
2935
|
+
|
|
2936
|
+
const allAgents = hosts.flatMap((host) => host.agents);
|
|
2937
|
+
snapshot = {
|
|
2938
|
+
generatedAt: new Date().toISOString(),
|
|
2939
|
+
scanning: false,
|
|
2940
|
+
cached: false,
|
|
2941
|
+
cacheSavedAt: null,
|
|
2942
|
+
sshConfig: SSH_CONFIG,
|
|
2943
|
+
hosts,
|
|
2944
|
+
summary: {
|
|
2945
|
+
hosts: hosts.length,
|
|
2946
|
+
online: hosts.filter((host) => host.reachable).length,
|
|
2947
|
+
codex: allAgents.length,
|
|
2948
|
+
tmux: hosts.reduce((total, host) => total + host.panes.length, 0),
|
|
2949
|
+
attention: allAgents.filter((agent) => agent.status === "attention").length,
|
|
2950
|
+
},
|
|
2951
|
+
};
|
|
2952
|
+
void sessionCatalog.refresh(force).catch((error) => console.error(`会话目录扫描失败:${error.message}`));
|
|
2953
|
+
detectTmuxCapacityFailures(hosts);
|
|
2954
|
+
await persistSnapshotCache().catch((error) => {
|
|
2955
|
+
console.error(`无法保存 snapshot 缓存: ${error.message}`);
|
|
2956
|
+
});
|
|
2957
|
+
notifyClients();
|
|
2958
|
+
restorePersistedAppServerSessions().catch((error) =>
|
|
2959
|
+
console.error(`app-server Session 补连失败:${error.message}`),
|
|
2960
|
+
);
|
|
2961
|
+
return snapshot;
|
|
2962
|
+
})().finally(() => {
|
|
2963
|
+
scanPromise = null;
|
|
2964
|
+
});
|
|
2965
|
+
return scanPromise;
|
|
2966
|
+
}
|
|
2967
|
+
|
|
2968
|
+
|
|
2969
|
+
const sessionArchives = sessionArchiveService({
|
|
2970
|
+
manager: appServerManager, getState: () => managementState, persist: persistManagementState,
|
|
2971
|
+
findAgent, getHost: alias => snapshot.hosts.find(h => h.alias === alias),
|
|
2972
|
+
executable: hostCodexExecutable,
|
|
2973
|
+
connectionKey: async (host, id) => {
|
|
2974
|
+
const binding = sessionProfileAssignment(host, id);
|
|
2975
|
+
if (profileHandoffPending(binding)) throw new Error("正在交接账号,请完成后再归档");
|
|
2976
|
+
const saved = persistedAppServerSessions.get(sessionKey(host, id)) || managementState.sessions[sessionKey(host, id)]?.closedSession;
|
|
2977
|
+
const writer = !saved?.connectionKey && !binding?.profile ? await detectRemoteSessionWriter(host, id) : null;
|
|
2978
|
+
return boundConnectionKey(binding, saved?.connectionKey || writer?.connectionKey || await newSessionConnectionKey(host));
|
|
2979
|
+
}, notify: notifyClients,
|
|
2980
|
+
protectedSession: (host, id) => { const state = workbench.store.read(); return state.config.manager.host === host && state.managerSession?.sessionId === id; },
|
|
2981
|
+
restored: async (host, sessionId, thread) => { revealUnarchivedSession(host, sessionId, thread); await persistHistoryIndex(); },
|
|
2982
|
+
});
|
|
2983
|
+
const handleArchives = archiveRoutes(sessionArchives, { readJsonBody, jsonResponse });
|
|
2984
|
+
const cliAdapter = remoteCliAdapter(runSshCommand, {
|
|
2985
|
+
hostPreLaunch: (host) => hostRuntimeConfig(host).preLaunchCommand,
|
|
2986
|
+
});
|
|
2987
|
+
const workbench = new WorkbenchService({
|
|
2988
|
+
taskQueueEnabled: deployment.taskQueue,
|
|
2989
|
+
store: await new WorkbenchStore(path.join(STATE_DIR, "workbench.json"), { configFile: process.env.SCOPE_WORKBENCH_CONFIG }).load(),
|
|
2990
|
+
snapshot: publicSnapshot,
|
|
2991
|
+
resolveAttachments: (items, host, expected) =>
|
|
2992
|
+
resolveUploadedAttachments(items, host, expected),
|
|
2993
|
+
adapters: {
|
|
2994
|
+
codex: codexWorkbenchAdapter({ archives: sessionArchives, manager: appServerManager, getHost: alias => snapshot.hosts.find(h => h.alias === alias), readModels: readInstalledModels, connectionKey: newSessionConnectionKey }),
|
|
2995
|
+
claude: cliAdapter,
|
|
2996
|
+
antigravity: cliAdapter,
|
|
2997
|
+
dsh: cliAdapter,
|
|
2998
|
+
},
|
|
2999
|
+
});
|
|
3000
|
+
function effectiveProviderSettings(provider, host) {
|
|
3001
|
+
const base = workbench.state().config.providers[provider] || {};
|
|
3002
|
+
const hostSetup = host ? hostRuntimeConfig(host)?.preLaunchCommand?.trim() || "" : "";
|
|
3003
|
+
return {
|
|
3004
|
+
...base,
|
|
3005
|
+
preLaunchCommand: base.preLaunchCommand?.trim() || hostSetup,
|
|
3006
|
+
};
|
|
3007
|
+
}
|
|
3008
|
+
function effectiveMaintenanceSettings(provider, host) {
|
|
3009
|
+
const base = workbench.state().config.providers[provider] || {};
|
|
3010
|
+
const runtime = host ? hostRuntimeConfig(host) : null;
|
|
3011
|
+
const hostUpdate = runtime?.updatePreCommand?.trim() || "";
|
|
3012
|
+
const hostLaunch = runtime?.preLaunchCommand?.trim() || "";
|
|
3013
|
+
return {
|
|
3014
|
+
...base,
|
|
3015
|
+
updatePreCommand: hostUpdate || hostLaunch || base.preLaunchCommand?.trim() || "",
|
|
3016
|
+
preLaunchCommand: hostLaunch || base.preLaunchCommand?.trim() || "",
|
|
3017
|
+
};
|
|
3018
|
+
}
|
|
3019
|
+
const maintenance = await new AgentMaintenance({ directory: STATE_DIR, run: runSshCommand,
|
|
3020
|
+
getHost: alias => snapshot.hosts.find(h => h.alias === alias),
|
|
3021
|
+
settings: effectiveMaintenanceSettings,
|
|
3022
|
+
}).load();
|
|
3023
|
+
const sessionCatalog = new SessionCatalog({ hosts: () => snapshot.hosts, run: runSshCommand });
|
|
3024
|
+
const handleCatalog = catalogRoutes(sessionCatalog, { jsonResponse, readJsonBody, resolveCodex: (entry) => {
|
|
3025
|
+
const host = snapshot.hosts.find((item) => item.alias === entry.host);
|
|
3026
|
+
if (!host) throw new Error("设备不在当前配置中");
|
|
3027
|
+
const agent = findAgent(entry.host, entry.sessionId) || historicalAgent(host, {
|
|
3028
|
+
id: entry.sessionId, path: entry.path, cwd: entry.cwd, model: entry.model,
|
|
3029
|
+
reasoningEffort: "", mtimeMs: Number(entry.updatedAt) || 0, firstUser: entry.title,
|
|
3030
|
+
lastUser: entry.title, lastAssistant: "", userMessages: [entry.title], assistantMessages: [],
|
|
3031
|
+
});
|
|
3032
|
+
historicalSessions.set(sessionKey(entry.host, entry.sessionId), agent);
|
|
3033
|
+
return agent;
|
|
3034
|
+
} });
|
|
3035
|
+
const nativeModels = new NativeModels({ hosts: () => snapshot.hosts, run: runSshCommand, settings: effectiveProviderSettings });
|
|
3036
|
+
const nativeCommands = new NativeCommands({ hosts: () => snapshot.hosts, run: runSshCommand, settings: effectiveProviderSettings });
|
|
3037
|
+
const cliConversations = await new CliConversations({ filename: path.join(STATE_DIR, "cli-conversations.json"), adapter: cliAdapter, models: nativeModels, commands: nativeCommands, lifecycle: nativeSessionState(runSshCommand),
|
|
3038
|
+
hosts: () => snapshot.hosts, settings: effectiveProviderSettings, catalog: sessionCatalog,
|
|
3039
|
+
resolveAttachments: (items, host, expected) =>
|
|
3040
|
+
resolveUploadedAttachments(items, host, expected),
|
|
3041
|
+
}).load();
|
|
3042
|
+
const handleCliConversations = cliConversationRoutes(cliConversations, { readJsonBody, jsonResponse, models: nativeModels, commands: nativeCommands });
|
|
3043
|
+
const handleSessionCommands = sessionCommandRoutes({manager:appServerManager,jsonResponse});
|
|
3044
|
+
cliConversations.start();
|
|
3045
|
+
process.once("exit", () => cliConversations.stop());
|
|
3046
|
+
const handleMaintenance = maintenanceRoutes(maintenance);
|
|
3047
|
+
const handleModels = modelRoutes(() => ({appServerManager, auditLifecycle, checkedProfileSlug, findAgent, hostRuntimeConfig, jsonResponse, listAuthProfiles, persistAppServerSessions, readInstalledModels, readJsonBody, selectTmuxModel, sessionProfileAssignment, sessionProfiles, sessionYolo, snapshot}));
|
|
3048
|
+
const localDialogue = localHistoryReader({ manager: appServerManager,
|
|
3049
|
+
findRollout: (host, id) => findAgent(host, id)?.rollout || historicalSessions.get(sessionKey(host, id))?.rollout || sessionCatalog.get(JSON.stringify([host, "codex", id])),
|
|
3050
|
+
});
|
|
3051
|
+
const handleDialogue = dialogueRoutes(() => ({localDialogue, DIALOGUE_PROBE, DIALOGUE_TIMEOUT_MS, RAW_CONTEXT_PROBE, cleanSshError, findAgent, historicalSessions, jsonResponse, readJsonBody, runSshCommand, sessionKey, shellQuote}));
|
|
3052
|
+
const handleRuntime = runtimeRoutes(() => ({hostRuntimeConfig, jsonResponse, readJsonBody, saveHostRuntimeConfig, snapshot}));
|
|
3053
|
+
const accountQuotas = createAccountQuotaService({
|
|
3054
|
+
appServerManager,
|
|
3055
|
+
localCodex,
|
|
3056
|
+
listAuthProfiles,
|
|
3057
|
+
hostCodexExecutable,
|
|
3058
|
+
hostRuntimeConfig,
|
|
3059
|
+
wrapBootstrapAppServer,
|
|
3060
|
+
shellQuote,
|
|
3061
|
+
mapLimit,
|
|
3062
|
+
sshTimeoutMs: SSH_TIMEOUT_MS,
|
|
3063
|
+
getSnapshot: () => snapshot,
|
|
3064
|
+
runSshCommand,
|
|
3065
|
+
providerSettings: effectiveProviderSettings,
|
|
3066
|
+
});
|
|
3067
|
+
const handleAccounts = authRoutes(() => ({accountQuotas, appServerActiveAuthFailoverJobs, assertProfileNotBound, auditLifecycle, authProfileManager, authRestartJobs, checkedProfileSlug, deleteAuthProfile, hostCodexExecutable, jsonResponse, latestAuthRestartJob, listAuthProfiles, normalizeProfileName, publicAuthRestartJob, publicProfileFailoverJob, readJsonBody, readLocalAuthProfiles: () => readLocalAuthProfiles({ localCodex }), runProfileWrite, snapshot, startAuthRestart}));
|
|
3068
|
+
const handleWorkbench = workbenchRoutes(workbench, { readJsonBody, jsonResponse });
|
|
3069
|
+
const handleDirectories = directoryRoutes({ local: (input, creating) => localDirectories(input, creating, localCodex.defaultCwd), getHost: alias => snapshot.hosts.find(host => host.alias === alias), run: runSshCommand, readJsonBody, jsonResponse, listScript: REMOTE_DIRECTORY_PROBE, shellQuote, cleanError: cleanSshError });
|
|
3070
|
+
const handleConversation = conversationRoutes(appServerManager, { readJsonBody, jsonResponse, persist: persistAppServerSessions });
|
|
3071
|
+
const tunnelManager = await new RemoteTunnelManager({
|
|
3072
|
+
stateDir: STATE_DIR,
|
|
3073
|
+
emailNotifier,
|
|
3074
|
+
legacyTunnelHost: deployment.emailTunnelHost,
|
|
3075
|
+
}).load();
|
|
3076
|
+
await tunnelManager.start();
|
|
3077
|
+
const remoteBootstrap = new RemoteBootstrapService({
|
|
3078
|
+
run: runSshCommand,
|
|
3079
|
+
getHost: (alias) => snapshot.hosts.find((host) => host.alias === alias),
|
|
3080
|
+
getOperatorName: () => managementState.operatorName,
|
|
3081
|
+
tunnels: tunnelManager,
|
|
3082
|
+
});
|
|
3083
|
+
const handleEmail = emailRoutes({
|
|
3084
|
+
emailNotifier,
|
|
3085
|
+
readJsonBody,
|
|
3086
|
+
jsonResponse,
|
|
3087
|
+
onChanged: () => notifyClients(),
|
|
3088
|
+
});
|
|
3089
|
+
const handleRemoteBootstrap = remoteBootstrapRoutes({
|
|
3090
|
+
bootstrap: remoteBootstrap,
|
|
3091
|
+
readJsonBody,
|
|
3092
|
+
jsonResponse,
|
|
3093
|
+
});
|
|
3094
|
+
const handlePlugins = pluginRoutes(plugins);
|
|
3095
|
+
// Compatibility facade: both old and new endpoints share the plugin store.
|
|
3096
|
+
const handleSubmissionSettings = submissionSettingsRoutes({
|
|
3097
|
+
store: {
|
|
3098
|
+
read: () => { const s = aliyunPlugin.store.read(); return { enabled: s.enabled, host: s.config.host }; },
|
|
3099
|
+
save: value => { const s = plugins.configure("aliyun-dlc", { enabled: value.enabled, config: { host: value.host } }, aliyunPlugin.store.read().revision); return { enabled: s.enabled, host: s.config.host }; },
|
|
3100
|
+
}, isScanning: aliyunPlugin.busy, apply: () => {},
|
|
3101
|
+
});
|
|
3102
|
+
const handleSystem = systemRoutes(() => ({
|
|
3103
|
+
HISTORY_TIMEOUT_MS,
|
|
3104
|
+
appServerManager,
|
|
3105
|
+
cachedHistoryResult,
|
|
3106
|
+
cleanSshError,
|
|
3107
|
+
clients,
|
|
3108
|
+
enrichAgentRelations,
|
|
3109
|
+
getSnapshot: () => snapshot,
|
|
3110
|
+
historicalAgent,
|
|
3111
|
+
historicalSessions,
|
|
3112
|
+
jsonResponse,
|
|
3113
|
+
mapLimit,
|
|
3114
|
+
persistHistoryIndex,
|
|
3115
|
+
plugins,
|
|
3116
|
+
publicSnapshot,
|
|
3117
|
+
publishSnapshotSync,
|
|
3118
|
+
readJsonBody,
|
|
3119
|
+
runSshCommand,
|
|
3120
|
+
scanAll,
|
|
3121
|
+
sessionKey,
|
|
3122
|
+
shellQuote,
|
|
3123
|
+
snapshotSyncStore,
|
|
3124
|
+
updateHistoryIndex,
|
|
3125
|
+
}));
|
|
3126
|
+
const handleSessionLifecycle = sessionLifecycleRoutes(() => ({
|
|
3127
|
+
TAKEOVER_TIMEOUT_MS,
|
|
3128
|
+
appServerAuthRecoveryHosts,
|
|
3129
|
+
appServerManager,
|
|
3130
|
+
appServerRestoreFailures,
|
|
3131
|
+
auditLifecycle,
|
|
3132
|
+
cleanSshError,
|
|
3133
|
+
clients,
|
|
3134
|
+
codexExecutable,
|
|
3135
|
+
codexUpgrades,
|
|
3136
|
+
detectRemoteSessionWriter,
|
|
3137
|
+
findLiveAgent,
|
|
3138
|
+
getManagementState: () => managementState,
|
|
3139
|
+
getSnapshot: () => snapshot,
|
|
3140
|
+
historicalSessions,
|
|
3141
|
+
hostConfigRestarts,
|
|
3142
|
+
hostRuntimeConfig,
|
|
3143
|
+
jsonResponse,
|
|
3144
|
+
localDirectory,
|
|
3145
|
+
newSessionConnectionKey,
|
|
3146
|
+
notifyClients,
|
|
3147
|
+
persistAppServerSessions,
|
|
3148
|
+
persistHistoryIndex,
|
|
3149
|
+
persistManagementState,
|
|
3150
|
+
persistSnapshotCache,
|
|
3151
|
+
publishSnapshotSync,
|
|
3152
|
+
readJsonBody,
|
|
3153
|
+
recoverAuthenticationFailedSessions,
|
|
3154
|
+
recoverHostAppServerSessions,
|
|
3155
|
+
recoveryAgent,
|
|
3156
|
+
rememberTmuxAgent,
|
|
3157
|
+
removeEventClient,
|
|
3158
|
+
resolveUploadedAttachments,
|
|
3159
|
+
resumeAgentInTmux,
|
|
3160
|
+
resumeManagedAppServerSession,
|
|
3161
|
+
revealUnarchivedSession,
|
|
3162
|
+
runSshCommand,
|
|
3163
|
+
saveHostRuntimeConfig,
|
|
3164
|
+
scanAll,
|
|
3165
|
+
sendTmuxText,
|
|
3166
|
+
sessionKey,
|
|
3167
|
+
sessionProfileAssignment,
|
|
3168
|
+
sessionYolo,
|
|
3169
|
+
setSnapshot: (next) => { snapshot = next; },
|
|
3170
|
+
shellQuote,
|
|
3171
|
+
snapshotInvalidationPayload,
|
|
3172
|
+
snapshotSyncStore,
|
|
3173
|
+
tmuxAgentForDelivery,
|
|
3174
|
+
writeEventClient,
|
|
3175
|
+
}));
|
|
3176
|
+
const handleManagement = managementRoutes(() => ({
|
|
3177
|
+
appServerManager,
|
|
3178
|
+
discoverWandbRuns,
|
|
3179
|
+
findAgent,
|
|
3180
|
+
generateCodexSummary,
|
|
3181
|
+
getManagementState: () => managementState,
|
|
3182
|
+
jsonResponse,
|
|
3183
|
+
notifyClients,
|
|
3184
|
+
persistManagementState,
|
|
3185
|
+
readJsonBody,
|
|
3186
|
+
searchAssistantSessions,
|
|
3187
|
+
sessionKey,
|
|
3188
|
+
setManagementState: (next) => { managementState = next; },
|
|
3189
|
+
}));
|
|
3190
|
+
const handleSessionDelivery = sessionDeliveryRoutes(() => ({
|
|
3191
|
+
ATTACHMENT_TTL_MS,
|
|
3192
|
+
appServerManager,
|
|
3193
|
+
auditLifecycle,
|
|
3194
|
+
cancelTmuxCapacityRecovery,
|
|
3195
|
+
findAgent,
|
|
3196
|
+
getManagementState: () => managementState,
|
|
3197
|
+
getSnapshot: () => snapshot,
|
|
3198
|
+
jsonResponse,
|
|
3199
|
+
localCodex,
|
|
3200
|
+
notifyClients,
|
|
3201
|
+
persistManagementState,
|
|
3202
|
+
readJsonBody,
|
|
3203
|
+
recoverHostAppServerSessions,
|
|
3204
|
+
renderResourcePrompt,
|
|
3205
|
+
resolveUploadedAttachments,
|
|
3206
|
+
sendTmuxText,
|
|
3207
|
+
sessionKey,
|
|
3208
|
+
setManagementState: (next) => { managementState = next; },
|
|
3209
|
+
shellQuote,
|
|
3210
|
+
storeUploadedAttachment,
|
|
3211
|
+
streamAttachmentToHost,
|
|
3212
|
+
}));
|
|
3213
|
+
process.once("exit", () => tunnelManager.stop());
|
|
3214
|
+
process.once("exit", () => plugins.stop());
|
|
3215
|
+
process.once("exit", () => workbench.stop());
|
|
3216
|
+
const server = createServer(requestHandler(async (request, response, url) => {
|
|
3217
|
+
if (await handleEmail(request, response, url)) return;
|
|
3218
|
+
if (await handleRemoteBootstrap(request, response, url)) return;
|
|
3219
|
+
if (await handlePlugins(request, response, url)) return;
|
|
3220
|
+
if (await handleSubmissionSettings(request, response, url)) return;
|
|
3221
|
+
if (await handleCatalog(request, response, url)) return;
|
|
3222
|
+
if (await handleCliConversations(request, response, url)) return;
|
|
3223
|
+
if (await handleSessionCommands(request, response, url)) return;
|
|
3224
|
+
if (await handleMaintenance(request, response, url)) return;
|
|
3225
|
+
if (await handleArchives(request, response, url)) return;
|
|
3226
|
+
if (await handleConversation(request, response, url)) return;
|
|
3227
|
+
if (await handleDirectories(request, response, url)) return;
|
|
3228
|
+
if (await handleWorkbench(request, response, url)) return;
|
|
3229
|
+
if (await handleModels(request,response,url)) return;
|
|
3230
|
+
if (await handleDialogue(request,response,url)) return;
|
|
3231
|
+
if (await handleRuntime(request,response,url)) return;
|
|
3232
|
+
if (await handleAccounts(request,response,url)) return;
|
|
3233
|
+
if (await handleSystem(request, response, url)) return;
|
|
3234
|
+
if (await handleSessionLifecycle(request, response, url)) return;
|
|
3235
|
+
if (await handleManagement(request, response, url)) return;
|
|
3236
|
+
if (await handleSessionDelivery(request, response, url)) return;
|
|
3237
|
+
|
|
3238
|
+
response.writeHead(404, { "Content-Type": "application/json; charset=utf-8" });
|
|
3239
|
+
response.end(JSON.stringify({ error: "Not found" }));
|
|
3240
|
+
}, { host: HOST, trustedOrigins: TRUSTED_BROWSER_ORIGINS }));
|
|
3241
|
+
|
|
3242
|
+
attachTerminalGateway({
|
|
3243
|
+
server,
|
|
3244
|
+
host: HOST,
|
|
3245
|
+
trustedOrigins: TRUSTED_BROWSER_ORIGINS,
|
|
3246
|
+
getSnapshot: () => snapshot,
|
|
3247
|
+
sshTimeoutMs: SSH_TIMEOUT_MS,
|
|
3248
|
+
auditLifecycle,
|
|
3249
|
+
});
|
|
3250
|
+
|
|
3251
|
+
process.once("exit", () => appServerManager.close());
|
|
3252
|
+
process.once("exit", () => authProfileManager.close());
|
|
3253
|
+
process.once("exit", () => {
|
|
3254
|
+
for (const timer of appServerReconnectTimers.values()) clearTimeout(timer);
|
|
3255
|
+
appServerReconnectTimers.clear();
|
|
3256
|
+
appServerReconnectInFlight.clear();
|
|
3257
|
+
});
|
|
3258
|
+
|
|
3259
|
+
await Promise.all([
|
|
3260
|
+
loadManagementState(),
|
|
3261
|
+
loadGpuUsageHistory(),
|
|
3262
|
+
loadSnapshotCache(),
|
|
3263
|
+
loadHistoryIndex(),
|
|
3264
|
+
loadAuthRestartJobs(),
|
|
3265
|
+
loadPersistedAppServerSessions(),
|
|
3266
|
+
]);
|
|
3267
|
+
|
|
3268
|
+
server.listen(PORT, HOST, () => {
|
|
3269
|
+
workbench.start();
|
|
3270
|
+
auditLifecycle("bridge-started", {
|
|
3271
|
+
pid: process.pid,
|
|
3272
|
+
remoteSessionSignalSent: false,
|
|
3273
|
+
});
|
|
3274
|
+
console.log(`SCOPE SSH Bridge: http://${HOST}:${PORT}`);
|
|
3275
|
+
console.log(`SSH Config: ${SSH_CONFIG}`);
|
|
3276
|
+
// Reconnect sessions that belonged to hosts in the persisted snapshot before
|
|
3277
|
+
// a slow first inventory pass over every SSH alias. The scan then retries any
|
|
3278
|
+
// records skipped because their cached host was offline or missing.
|
|
3279
|
+
restorePersistedAppServerSessions()
|
|
3280
|
+
.catch((error) =>
|
|
3281
|
+
console.error(`app-server Session 快速恢复失败:${error.message}`),
|
|
3282
|
+
)
|
|
3283
|
+
.then(() => scanAll())
|
|
3284
|
+
.then(() => {
|
|
3285
|
+
restorePersistedAppServerSessions().catch((error) =>
|
|
3286
|
+
console.error(`app-server Session 自动恢复失败:${error.message}`),
|
|
3287
|
+
);
|
|
3288
|
+
plugins.start();
|
|
3289
|
+
})
|
|
3290
|
+
.catch((error) => console.error(error));
|
|
3291
|
+
setInterval(() => scanAll().catch(() => {}), POLL_MS).unref();
|
|
3292
|
+
startIdleSessionReaper(appServerManager, {
|
|
3293
|
+
timeoutMs: () => {
|
|
3294
|
+
const envVal = process.env.SCOPE_SESSION_IDLE_MINUTES;
|
|
3295
|
+
if (envVal !== undefined && envVal !== "") return idleSessionTimeout(envVal);
|
|
3296
|
+
const mins = workbench.state().config?.scheduler?.sessionIdleGraceMinutes;
|
|
3297
|
+
return Number.isFinite(mins) && mins > 0 ? mins * 60_000 : 15 * 60_000;
|
|
3298
|
+
},
|
|
3299
|
+
residentLimit: (host) => {
|
|
3300
|
+
const override = hostRuntimeConfig(host)?.residentSessionLimit;
|
|
3301
|
+
if (Number.isInteger(override) && override >= 0) return override;
|
|
3302
|
+
const globalPool = workbench.state().config?.scheduler?.residentSessionsPerHost;
|
|
3303
|
+
return Number.isInteger(globalPool) && globalPool >= 0 ? globalPool : 5;
|
|
3304
|
+
},
|
|
3305
|
+
isReserved: (host, sessionId) => {
|
|
3306
|
+
const wb = workbench.store.read();
|
|
3307
|
+
if (wb.config?.manager?.host === host && wb.managerSession?.sessionId === sessionId) {
|
|
3308
|
+
return true;
|
|
3309
|
+
}
|
|
3310
|
+
if (Boolean(managementState.sessions[sessionKey(host, sessionId)]?.reserved)) {
|
|
3311
|
+
return true;
|
|
3312
|
+
}
|
|
3313
|
+
const live = findLiveAgent(host, sessionId);
|
|
3314
|
+
if (live?.subagents?.some((sub) => sub.turnState === "working")) {
|
|
3315
|
+
return true;
|
|
3316
|
+
}
|
|
3317
|
+
if (Array.isArray(live?.localWorkloads) && live.localWorkloads.length > 0) {
|
|
3318
|
+
return true;
|
|
3319
|
+
}
|
|
3320
|
+
if (
|
|
3321
|
+
gpuUsageHistory?.episodes?.some(
|
|
3322
|
+
(ep) => ep.active && ep.host === host && ep.ownerSessionId === sessionId,
|
|
3323
|
+
)
|
|
3324
|
+
) {
|
|
3325
|
+
return true;
|
|
3326
|
+
}
|
|
3327
|
+
return false;
|
|
3328
|
+
},
|
|
3329
|
+
onError: (error, session) => console.error(`空闲会话释放失败 ${session.host}/${session.sessionId}: ${error.message}`),
|
|
3330
|
+
});
|
|
3331
|
+
|
|
3332
|
+
});
|