scope-agent-workbench 0.0.0-stage → 0.2.3
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 +59 -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 +36 -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 +432 -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 +637 -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 +463 -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 +177 -0
- package/bridge/routes/accounts.mjs +326 -0
- package/bridge/routes/dialogue.mjs +165 -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 +3357 -0
- package/bridge/session-attachments.mjs +150 -0
- package/bridge/session-cache-archive.mjs +22 -0
- package/bridge/session-catalog/agy-history.py +388 -0
- package/bridge/session-catalog/catalog.mjs +110 -0
- package/bridge/session-catalog/probe.py +1207 -0
- package/bridge/session-catalog/routes.mjs +34 -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 +405 -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-BMior55c.js +3 -0
- package/dist/client/assets/index-CNnP2Ses.css +2 -0
- package/dist/client/assets/layout-segment-context-DjGudgXn.js +1 -0
- package/dist/client/assets/page-CJqXlhDs.js +551 -0
- package/dist/client/assets/page-LYzRz6_S.css +1 -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-BB9Dri2u.js +104686 -0
- package/dist/server/ssr/assets/page-LYzRz6_S.css +1 -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/subagent-display-prefs.ts +130 -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 +465 -0
- package/scripts/fixtures/workbench-conversations.mjs +475 -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,2522 @@
|
|
|
1
|
+
import { archiveThread, isArchiving } from "./archive/thread-lifecycle.mjs";
|
|
2
|
+
import { LOCAL_HOST, workingDirectory } from "../lib/execution-host.js";
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import readline from "node:readline";
|
|
5
|
+
import {
|
|
6
|
+
CAPACITY_CONTINUE_PROMPT,
|
|
7
|
+
DEFAULT_CAPACITY_RETRY_DELAYS_MS,
|
|
8
|
+
errorText,
|
|
9
|
+
isModelCapacityError,
|
|
10
|
+
isTransientCodexBackendError,
|
|
11
|
+
} from "./capacity-recovery.mjs";
|
|
12
|
+
import { runtimePolicy } from "../lib/runtime-config.js";
|
|
13
|
+
import { normalizeAccountQuota } from "../lib/account-quota.js";
|
|
14
|
+
import { appServerTurnInput } from "./session-attachments.mjs";
|
|
15
|
+
|
|
16
|
+
const USER_INPUT_METHOD = "item/tool/requestUserInput";
|
|
17
|
+
const HUMAN_REQUEST_METHODS = new Map([
|
|
18
|
+
[USER_INPUT_METHOD, "user-input"],
|
|
19
|
+
["item/commandExecution/requestApproval", "command-approval"],
|
|
20
|
+
["item/fileChange/requestApproval", "file-change-approval"],
|
|
21
|
+
["item/permissions/requestApproval", "permissions-approval"],
|
|
22
|
+
["mcpServer/elicitation/request", "mcp-elicitation"],
|
|
23
|
+
["execCommandApproval", "legacy-command-approval"],
|
|
24
|
+
["applyPatchApproval", "legacy-file-change-approval"],
|
|
25
|
+
]);
|
|
26
|
+
const MACHINE_REQUEST_METHODS = new Set([
|
|
27
|
+
"item/tool/call",
|
|
28
|
+
"account/chatgptAuthTokens/refresh",
|
|
29
|
+
"attestation/generate",
|
|
30
|
+
]);
|
|
31
|
+
const CURRENT_TIME_METHOD = "currentTime/read";
|
|
32
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
|
|
33
|
+
const MAX_ANSWER_LENGTH = 20_000;
|
|
34
|
+
|
|
35
|
+
function rpcIdKey(value) {
|
|
36
|
+
return `${typeof value}:${JSON.stringify(value)}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function cleanString(value, limit = 20_000) {
|
|
40
|
+
return typeof value === "string" ? value.slice(0, limit) : "";
|
|
41
|
+
}
|
|
42
|
+
function sessionDirectory(host, cwd) {
|
|
43
|
+
return host === LOCAL_HOST && cwd ? workingDirectory(host, cwd) : cwd;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function publicConnectionError(value) {
|
|
47
|
+
return cleanString(value instanceof Error ? value.message : String(value), 800);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isAuthenticationRefreshError(value) {
|
|
51
|
+
const text = errorText(value).toLowerCase();
|
|
52
|
+
if (!text) return false;
|
|
53
|
+
return (
|
|
54
|
+
text.includes("access token could not be refreshed") ||
|
|
55
|
+
text.includes("logged out or signed in to another account") ||
|
|
56
|
+
(text.includes("unauthorized") && text.includes("sign in again"))
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function normalizedConnectionKey(value) {
|
|
61
|
+
const key = cleanString(value, 100).trim();
|
|
62
|
+
return key || "active";
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function connectionMapKey(host, connectionKey = "active") {
|
|
66
|
+
return JSON.stringify([host, normalizedConnectionKey(connectionKey)]);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function connectionMapParts(value) {
|
|
70
|
+
try {
|
|
71
|
+
const [host, connectionKey] = JSON.parse(value);
|
|
72
|
+
return { host, connectionKey: normalizedConnectionKey(connectionKey) };
|
|
73
|
+
} catch {
|
|
74
|
+
return { host: "", connectionKey: "active" };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function requestScopeHost(host, connectionKey = "active") {
|
|
79
|
+
const key = normalizedConnectionKey(connectionKey);
|
|
80
|
+
return key === "active" ? host : `${host}#${key}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function safeHttpUrl(value) {
|
|
84
|
+
const text = cleanString(value, 8_000);
|
|
85
|
+
try {
|
|
86
|
+
const url = new URL(text);
|
|
87
|
+
return ["http:", "https:"].includes(url.protocol) ? url.href : null;
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function inputRequestKey(host, requestId) {
|
|
94
|
+
return Buffer.from(JSON.stringify([host, requestId]), "utf8").toString(
|
|
95
|
+
"base64url",
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export const humanRequestKey = inputRequestKey;
|
|
100
|
+
|
|
101
|
+
function baseHumanRequest(host, message, kind, receivedAt) {
|
|
102
|
+
const params = message.params || {};
|
|
103
|
+
return {
|
|
104
|
+
key: humanRequestKey(host, message.id),
|
|
105
|
+
kind,
|
|
106
|
+
method: message.method,
|
|
107
|
+
host,
|
|
108
|
+
requestId: message.id,
|
|
109
|
+
threadId: cleanString(params.threadId || params.conversationId, 200),
|
|
110
|
+
turnId: cleanString(params.turnId, 200) || null,
|
|
111
|
+
itemId: cleanString(params.itemId || params.callId, 200) || null,
|
|
112
|
+
receivedAt: new Date(receivedAt).toISOString(),
|
|
113
|
+
expiresAt: null,
|
|
114
|
+
status: "pending",
|
|
115
|
+
error: null,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function decisionName(decision) {
|
|
120
|
+
if (typeof decision === "string") return decision;
|
|
121
|
+
if (decision && typeof decision === "object") {
|
|
122
|
+
return Object.keys(decision)[0] || "custom";
|
|
123
|
+
}
|
|
124
|
+
return "";
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function decisionOption(decision) {
|
|
128
|
+
const name = decisionName(decision);
|
|
129
|
+
const labels = {
|
|
130
|
+
accept: ["允许一次", "仅允许这一次操作"],
|
|
131
|
+
acceptForSession: ["本 Session 允许", "当前 Session 后续同类操作不再询问"],
|
|
132
|
+
acceptWithExecpolicyAmendment: [
|
|
133
|
+
"允许并记住命令规则",
|
|
134
|
+
"应用 Codex 建议的 exec policy 规则",
|
|
135
|
+
],
|
|
136
|
+
applyNetworkPolicyAmendment: [
|
|
137
|
+
"允许并记住网络规则",
|
|
138
|
+
"应用 Codex 建议的网络访问规则",
|
|
139
|
+
],
|
|
140
|
+
decline: ["拒绝", "不执行该操作,Codex 可继续调整方案"],
|
|
141
|
+
cancel: ["取消 Turn", "取消当前操作或 Turn"],
|
|
142
|
+
approved: ["允许一次", "仅允许这一次操作"],
|
|
143
|
+
approved_for_session: [
|
|
144
|
+
"本 Session 允许",
|
|
145
|
+
"当前 Session 后续同类操作不再询问",
|
|
146
|
+
],
|
|
147
|
+
denied: ["拒绝", "不执行该操作,Codex 可继续调整方案"],
|
|
148
|
+
abort: ["中止", "中止当前操作"],
|
|
149
|
+
};
|
|
150
|
+
const [label, description] = labels[name] || [
|
|
151
|
+
name || "自定义决策",
|
|
152
|
+
"使用 Codex 提供的原始决策",
|
|
153
|
+
];
|
|
154
|
+
return {
|
|
155
|
+
id: Buffer.from(JSON.stringify(decision), "utf8").toString("base64url"),
|
|
156
|
+
label,
|
|
157
|
+
description,
|
|
158
|
+
value: decision,
|
|
159
|
+
tone: ["decline", "denied", "cancel", "abort"].includes(name)
|
|
160
|
+
? "danger"
|
|
161
|
+
: name.includes("Session") || name.includes("session")
|
|
162
|
+
? "persistent"
|
|
163
|
+
: "accept",
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function normalizedDecisionOptions(raw, fallback) {
|
|
168
|
+
const decisions = Array.isArray(raw) && raw.length ? raw : fallback;
|
|
169
|
+
return decisions
|
|
170
|
+
.slice(0, 12)
|
|
171
|
+
.filter(
|
|
172
|
+
(decision) =>
|
|
173
|
+
typeof decision === "string" ||
|
|
174
|
+
(decision && typeof decision === "object" && !Array.isArray(decision)),
|
|
175
|
+
)
|
|
176
|
+
.map(decisionOption);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function normalizePermissionProfile(profile) {
|
|
180
|
+
const result = {};
|
|
181
|
+
if (profile?.network && typeof profile.network === "object") {
|
|
182
|
+
result.network = {
|
|
183
|
+
enabled:
|
|
184
|
+
typeof profile.network.enabled === "boolean"
|
|
185
|
+
? profile.network.enabled
|
|
186
|
+
: null,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
if (profile?.fileSystem && typeof profile.fileSystem === "object") {
|
|
190
|
+
const fileSystem = profile.fileSystem;
|
|
191
|
+
result.fileSystem = {
|
|
192
|
+
read: Array.isArray(fileSystem.read)
|
|
193
|
+
? fileSystem.read.map((value) => cleanString(value, 2_000)).slice(0, 200)
|
|
194
|
+
: null,
|
|
195
|
+
write: Array.isArray(fileSystem.write)
|
|
196
|
+
? fileSystem.write.map((value) => cleanString(value, 2_000)).slice(0, 200)
|
|
197
|
+
: null,
|
|
198
|
+
};
|
|
199
|
+
if (Number.isFinite(fileSystem.globScanMaxDepth)) {
|
|
200
|
+
result.fileSystem.globScanMaxDepth = Number(fileSystem.globScanMaxDepth);
|
|
201
|
+
}
|
|
202
|
+
if (Array.isArray(fileSystem.entries)) {
|
|
203
|
+
result.fileSystem.entries = fileSystem.entries.slice(0, 200);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return result;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function normalizeElicitationFields(schema) {
|
|
210
|
+
if (!schema || typeof schema !== "object") return null;
|
|
211
|
+
const properties =
|
|
212
|
+
schema.properties && typeof schema.properties === "object"
|
|
213
|
+
? schema.properties
|
|
214
|
+
: null;
|
|
215
|
+
if (!properties) return null;
|
|
216
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
|
|
217
|
+
return Object.entries(properties)
|
|
218
|
+
.slice(0, 100)
|
|
219
|
+
.map(([name, raw]) => {
|
|
220
|
+
if (!raw || typeof raw !== "object") return null;
|
|
221
|
+
let options = null;
|
|
222
|
+
if (Array.isArray(raw.enum)) {
|
|
223
|
+
options = raw.enum.map((value, index) => ({
|
|
224
|
+
value,
|
|
225
|
+
label: cleanString(raw.enumNames?.[index], 300) || String(value),
|
|
226
|
+
}));
|
|
227
|
+
} else if (Array.isArray(raw.oneOf)) {
|
|
228
|
+
options = raw.oneOf.map((option) => ({
|
|
229
|
+
value: option?.const,
|
|
230
|
+
label: cleanString(option?.title, 300) || String(option?.const ?? ""),
|
|
231
|
+
}));
|
|
232
|
+
} else if (Array.isArray(raw.items?.enum)) {
|
|
233
|
+
options = raw.items.enum.map((value) => ({
|
|
234
|
+
value,
|
|
235
|
+
label: String(value),
|
|
236
|
+
}));
|
|
237
|
+
} else if (Array.isArray(raw.items?.anyOf)) {
|
|
238
|
+
options = raw.items.anyOf.map((option) => ({
|
|
239
|
+
value: option?.const,
|
|
240
|
+
label: cleanString(option?.title, 300) || String(option?.const ?? ""),
|
|
241
|
+
}));
|
|
242
|
+
}
|
|
243
|
+
return {
|
|
244
|
+
name: cleanString(name, 200),
|
|
245
|
+
title: cleanString(raw.title, 500) || cleanString(name, 200),
|
|
246
|
+
description: cleanString(raw.description, 2_000),
|
|
247
|
+
type: ["string", "number", "integer", "boolean", "array"].includes(
|
|
248
|
+
raw.type,
|
|
249
|
+
)
|
|
250
|
+
? raw.type
|
|
251
|
+
: "unsupported",
|
|
252
|
+
format: cleanString(raw.format, 100) || null,
|
|
253
|
+
required: required.has(name),
|
|
254
|
+
default: raw.default ?? null,
|
|
255
|
+
minimum: Number.isFinite(raw.minimum) ? Number(raw.minimum) : null,
|
|
256
|
+
maximum: Number.isFinite(raw.maximum) ? Number(raw.maximum) : null,
|
|
257
|
+
minLength: Number.isFinite(raw.minLength) ? Number(raw.minLength) : null,
|
|
258
|
+
maxLength: Number.isFinite(raw.maxLength) ? Number(raw.maxLength) : null,
|
|
259
|
+
minItems: Number.isFinite(raw.minItems) ? Number(raw.minItems) : null,
|
|
260
|
+
maxItems: Number.isFinite(raw.maxItems) ? Number(raw.maxItems) : null,
|
|
261
|
+
options,
|
|
262
|
+
};
|
|
263
|
+
})
|
|
264
|
+
.filter((field) => field?.name);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function parseUserInputRequest(host, message, receivedAt = Date.now()) {
|
|
268
|
+
if (
|
|
269
|
+
!message ||
|
|
270
|
+
message.method !== USER_INPUT_METHOD ||
|
|
271
|
+
!["string", "number"].includes(typeof message.id) ||
|
|
272
|
+
!message.params ||
|
|
273
|
+
typeof message.params !== "object"
|
|
274
|
+
) {
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const rawQuestions = Array.isArray(message.params.questions)
|
|
279
|
+
? message.params.questions
|
|
280
|
+
: [];
|
|
281
|
+
if (!rawQuestions.length || rawQuestions.length > 3) return null;
|
|
282
|
+
|
|
283
|
+
const ids = new Set();
|
|
284
|
+
const questions = [];
|
|
285
|
+
for (const raw of rawQuestions) {
|
|
286
|
+
const id = cleanString(raw?.id, 120).trim();
|
|
287
|
+
const header = cleanString(raw?.header, 120).trim();
|
|
288
|
+
const question = cleanString(raw?.question, 4_000).trim();
|
|
289
|
+
if (!id || !header || !question || ids.has(id)) return null;
|
|
290
|
+
ids.add(id);
|
|
291
|
+
|
|
292
|
+
let options = null;
|
|
293
|
+
if (Array.isArray(raw.options)) {
|
|
294
|
+
options = raw.options
|
|
295
|
+
.slice(0, 20)
|
|
296
|
+
.map((option) => ({
|
|
297
|
+
label: cleanString(option?.label, 300).trim(),
|
|
298
|
+
description: cleanString(option?.description, 1_000).trim(),
|
|
299
|
+
}))
|
|
300
|
+
.filter((option) => option.label && option.description);
|
|
301
|
+
if (!options.length) options = null;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
questions.push({
|
|
305
|
+
id,
|
|
306
|
+
header,
|
|
307
|
+
question,
|
|
308
|
+
isOther: Boolean(raw.isOther),
|
|
309
|
+
isSecret: Boolean(raw.isSecret),
|
|
310
|
+
options,
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const autoResolutionMs = Number.isFinite(message.params.autoResolutionMs)
|
|
315
|
+
? Math.max(0, Number(message.params.autoResolutionMs))
|
|
316
|
+
: null;
|
|
317
|
+
const threadId = cleanString(message.params.threadId, 200);
|
|
318
|
+
const turnId = cleanString(message.params.turnId, 200);
|
|
319
|
+
const itemId = cleanString(message.params.itemId, 200);
|
|
320
|
+
if (!threadId || !turnId || !itemId) return null;
|
|
321
|
+
|
|
322
|
+
return {
|
|
323
|
+
...baseHumanRequest(host, message, "user-input", receivedAt),
|
|
324
|
+
title: "Codex 需要你的回答",
|
|
325
|
+
threadId,
|
|
326
|
+
turnId,
|
|
327
|
+
itemId,
|
|
328
|
+
questions,
|
|
329
|
+
autoResolutionMs,
|
|
330
|
+
expiresAt:
|
|
331
|
+
autoResolutionMs === null
|
|
332
|
+
? null
|
|
333
|
+
: new Date(receivedAt + autoResolutionMs).toISOString(),
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export function parseHumanRequest(host, message, receivedAt = Date.now()) {
|
|
338
|
+
if (
|
|
339
|
+
!message ||
|
|
340
|
+
!HUMAN_REQUEST_METHODS.has(message.method) ||
|
|
341
|
+
!["string", "number"].includes(typeof message.id) ||
|
|
342
|
+
!message.params ||
|
|
343
|
+
typeof message.params !== "object"
|
|
344
|
+
) {
|
|
345
|
+
return null;
|
|
346
|
+
}
|
|
347
|
+
if (message.method === USER_INPUT_METHOD) {
|
|
348
|
+
return parseUserInputRequest(host, message, receivedAt);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const params = message.params;
|
|
352
|
+
const kind = HUMAN_REQUEST_METHODS.get(message.method);
|
|
353
|
+
const base = baseHumanRequest(host, message, kind, receivedAt);
|
|
354
|
+
if (!base.threadId) return null;
|
|
355
|
+
|
|
356
|
+
if (kind === "command-approval") {
|
|
357
|
+
if (!base.turnId || !base.itemId) return null;
|
|
358
|
+
return {
|
|
359
|
+
...base,
|
|
360
|
+
title: "命令执行审批",
|
|
361
|
+
reason: cleanString(params.reason, 4_000) || null,
|
|
362
|
+
command: cleanString(params.command, 20_000) || null,
|
|
363
|
+
cwd: cleanString(params.cwd, 4_000) || null,
|
|
364
|
+
networkApprovalContext: params.networkApprovalContext || null,
|
|
365
|
+
commandActions: Array.isArray(params.commandActions)
|
|
366
|
+
? params.commandActions.slice(0, 100)
|
|
367
|
+
: [],
|
|
368
|
+
additionalPermissions: normalizePermissionProfile(
|
|
369
|
+
params.additionalPermissions,
|
|
370
|
+
),
|
|
371
|
+
decisionOptions: normalizedDecisionOptions(params.availableDecisions, [
|
|
372
|
+
"accept",
|
|
373
|
+
"acceptForSession",
|
|
374
|
+
...(params.proposedExecpolicyAmendment
|
|
375
|
+
? [
|
|
376
|
+
{
|
|
377
|
+
acceptWithExecpolicyAmendment: {
|
|
378
|
+
execpolicy_amendment: params.proposedExecpolicyAmendment,
|
|
379
|
+
},
|
|
380
|
+
},
|
|
381
|
+
]
|
|
382
|
+
: []),
|
|
383
|
+
...(Array.isArray(params.proposedNetworkPolicyAmendments)
|
|
384
|
+
? params.proposedNetworkPolicyAmendments.map((amendment) => ({
|
|
385
|
+
applyNetworkPolicyAmendment: {
|
|
386
|
+
network_policy_amendment: amendment,
|
|
387
|
+
},
|
|
388
|
+
}))
|
|
389
|
+
: []),
|
|
390
|
+
"decline",
|
|
391
|
+
"cancel",
|
|
392
|
+
]),
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
if (kind === "file-change-approval") {
|
|
397
|
+
if (!base.turnId || !base.itemId) return null;
|
|
398
|
+
return {
|
|
399
|
+
...base,
|
|
400
|
+
title: "文件修改审批",
|
|
401
|
+
reason: cleanString(params.reason, 4_000) || null,
|
|
402
|
+
grantRoot: cleanString(params.grantRoot, 4_000) || null,
|
|
403
|
+
decisionOptions: normalizedDecisionOptions(null, [
|
|
404
|
+
"accept",
|
|
405
|
+
"acceptForSession",
|
|
406
|
+
"decline",
|
|
407
|
+
"cancel",
|
|
408
|
+
]),
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
if (kind === "permissions-approval") {
|
|
413
|
+
if (!base.turnId || !base.itemId) return null;
|
|
414
|
+
return {
|
|
415
|
+
...base,
|
|
416
|
+
title: "额外权限申请",
|
|
417
|
+
reason: cleanString(params.reason, 4_000) || null,
|
|
418
|
+
cwd: cleanString(params.cwd, 4_000),
|
|
419
|
+
environmentId: cleanString(params.environmentId, 500) || null,
|
|
420
|
+
permissions: normalizePermissionProfile(params.permissions),
|
|
421
|
+
decisionOptions: [
|
|
422
|
+
{
|
|
423
|
+
id: "grant-turn",
|
|
424
|
+
label: "仅本轮授权",
|
|
425
|
+
description: "授予本次请求中的全部权限,Turn 结束后失效",
|
|
426
|
+
value: "grant-turn",
|
|
427
|
+
tone: "accept",
|
|
428
|
+
},
|
|
429
|
+
{
|
|
430
|
+
id: "grant-session",
|
|
431
|
+
label: "本 Session 授权",
|
|
432
|
+
description: "授予本次请求中的全部权限,并在当前 Session 保持",
|
|
433
|
+
value: "grant-session",
|
|
434
|
+
tone: "persistent",
|
|
435
|
+
},
|
|
436
|
+
{
|
|
437
|
+
id: "decline",
|
|
438
|
+
label: "拒绝",
|
|
439
|
+
description: "返回空权限集合;Codex 会把未授予部分视为拒绝",
|
|
440
|
+
value: "decline",
|
|
441
|
+
tone: "danger",
|
|
442
|
+
},
|
|
443
|
+
],
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (kind === "mcp-elicitation") {
|
|
448
|
+
const mode = cleanString(params.mode, 100);
|
|
449
|
+
const fields = ["form", "openai/form"].includes(mode)
|
|
450
|
+
? normalizeElicitationFields(params.requestedSchema)
|
|
451
|
+
: null;
|
|
452
|
+
const url = mode === "url" ? safeHttpUrl(params.url) : null;
|
|
453
|
+
const persist = params?._meta?.persist;
|
|
454
|
+
const meta =
|
|
455
|
+
params?._meta?.codex_approval_kind === "mcp_tool_call"
|
|
456
|
+
? {
|
|
457
|
+
codexApprovalKind: "mcp_tool_call",
|
|
458
|
+
persist:
|
|
459
|
+
typeof persist === "string"
|
|
460
|
+
? persist
|
|
461
|
+
: Array.isArray(persist)
|
|
462
|
+
? persist.filter((value) => typeof value === "string")
|
|
463
|
+
: null,
|
|
464
|
+
}
|
|
465
|
+
: null;
|
|
466
|
+
return {
|
|
467
|
+
...base,
|
|
468
|
+
title:
|
|
469
|
+
params?._meta?.codex_approval_kind === "mcp_tool_call"
|
|
470
|
+
? "MCP 工具审批"
|
|
471
|
+
: "MCP Server 需要输入",
|
|
472
|
+
mode,
|
|
473
|
+
serverName: cleanString(params.serverName, 500),
|
|
474
|
+
message: cleanString(params.message, 8_000),
|
|
475
|
+
url,
|
|
476
|
+
elicitationId:
|
|
477
|
+
mode === "url" ? cleanString(params.elicitationId, 500) : null,
|
|
478
|
+
fields,
|
|
479
|
+
renderable:
|
|
480
|
+
(mode === "url" && Boolean(url)) ||
|
|
481
|
+
(["form", "openai/form"].includes(mode) && fields !== null),
|
|
482
|
+
meta,
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
if (kind === "legacy-command-approval") {
|
|
487
|
+
if (!base.itemId) return null;
|
|
488
|
+
return {
|
|
489
|
+
...base,
|
|
490
|
+
title: "旧版命令执行审批",
|
|
491
|
+
reason: cleanString(params.reason, 4_000) || null,
|
|
492
|
+
command: Array.isArray(params.command)
|
|
493
|
+
? params.command.map((value) => cleanString(value, 4_000)).join(" ")
|
|
494
|
+
: cleanString(params.command, 20_000),
|
|
495
|
+
cwd: cleanString(params.cwd, 4_000) || null,
|
|
496
|
+
commandActions: Array.isArray(params.parsedCmd)
|
|
497
|
+
? params.parsedCmd.slice(0, 100)
|
|
498
|
+
: [],
|
|
499
|
+
decisionOptions: normalizedDecisionOptions(null, [
|
|
500
|
+
"approved",
|
|
501
|
+
"approved_for_session",
|
|
502
|
+
"denied",
|
|
503
|
+
"abort",
|
|
504
|
+
]),
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
if (kind === "legacy-file-change-approval") {
|
|
509
|
+
if (!base.itemId) return null;
|
|
510
|
+
const fileChanges =
|
|
511
|
+
params.fileChanges && typeof params.fileChanges === "object"
|
|
512
|
+
? Object.entries(params.fileChanges)
|
|
513
|
+
.slice(0, 100)
|
|
514
|
+
.map(([path, change]) => ({
|
|
515
|
+
path: cleanString(path, 4_000),
|
|
516
|
+
type: cleanString(change?.type, 100),
|
|
517
|
+
preview: cleanString(
|
|
518
|
+
change?.unified_diff || change?.content,
|
|
519
|
+
12_000,
|
|
520
|
+
),
|
|
521
|
+
movePath: cleanString(change?.move_path, 4_000) || null,
|
|
522
|
+
}))
|
|
523
|
+
: [];
|
|
524
|
+
return {
|
|
525
|
+
...base,
|
|
526
|
+
title: "旧版补丁审批",
|
|
527
|
+
reason: cleanString(params.reason, 4_000) || null,
|
|
528
|
+
grantRoot: cleanString(params.grantRoot, 4_000) || null,
|
|
529
|
+
fileChanges,
|
|
530
|
+
decisionOptions: normalizedDecisionOptions(null, [
|
|
531
|
+
"approved",
|
|
532
|
+
"approved_for_session",
|
|
533
|
+
"denied",
|
|
534
|
+
"abort",
|
|
535
|
+
]),
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export function normalizeUserInputAnswers(input, rawAnswers) {
|
|
543
|
+
if (!input || input.status !== "pending") {
|
|
544
|
+
throw new Error("该问题已经失效或已回答");
|
|
545
|
+
}
|
|
546
|
+
if (!rawAnswers || typeof rawAnswers !== "object" || Array.isArray(rawAnswers)) {
|
|
547
|
+
throw new Error("answers 必须是按问题 ID 索引的对象");
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const expectedIds = new Set(input.questions.map((question) => question.id));
|
|
551
|
+
for (const answerId of Object.keys(rawAnswers)) {
|
|
552
|
+
if (!expectedIds.has(answerId)) {
|
|
553
|
+
throw new Error(`未知的问题 ID:${answerId}`);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const normalized = {};
|
|
558
|
+
for (const question of input.questions) {
|
|
559
|
+
const raw = rawAnswers[question.id];
|
|
560
|
+
const values = Array.isArray(raw?.answers) ? raw.answers : [];
|
|
561
|
+
if (!values.length || values.length > 20) {
|
|
562
|
+
throw new Error(`问题“${question.header}”需要至少一个答案`);
|
|
563
|
+
}
|
|
564
|
+
const answers = values.map((value) => {
|
|
565
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
566
|
+
throw new Error(`问题“${question.header}”的答案不能为空`);
|
|
567
|
+
}
|
|
568
|
+
if (value.length > MAX_ANSWER_LENGTH) {
|
|
569
|
+
throw new Error(`问题“${question.header}”的答案过长`);
|
|
570
|
+
}
|
|
571
|
+
return value.trim();
|
|
572
|
+
});
|
|
573
|
+
normalized[question.id] = { answers };
|
|
574
|
+
}
|
|
575
|
+
return { answers: normalized };
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function sameDecision(left, right) {
|
|
579
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function normalizeDecisionResponse(request, rawResponse) {
|
|
583
|
+
const decision = rawResponse?.decision;
|
|
584
|
+
if (
|
|
585
|
+
!request.decisionOptions?.some((option) =>
|
|
586
|
+
sameDecision(option.value, decision),
|
|
587
|
+
)
|
|
588
|
+
) {
|
|
589
|
+
throw new Error("该审批决策不在 Codex 提供的可选范围内");
|
|
590
|
+
}
|
|
591
|
+
return { decision };
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function normalizeElicitationContent(request, rawContent) {
|
|
595
|
+
if (!request.fields) {
|
|
596
|
+
throw new Error("当前客户端无法安全渲染这个 MCP 表单,请选择拒绝或取消");
|
|
597
|
+
}
|
|
598
|
+
if (!rawContent || typeof rawContent !== "object" || Array.isArray(rawContent)) {
|
|
599
|
+
throw new Error("MCP 表单内容必须是对象");
|
|
600
|
+
}
|
|
601
|
+
const content = {};
|
|
602
|
+
const knownFields = new Set(request.fields.map((field) => field.name));
|
|
603
|
+
for (const name of Object.keys(rawContent)) {
|
|
604
|
+
if (!knownFields.has(name)) throw new Error(`未知的 MCP 表单字段:${name}`);
|
|
605
|
+
}
|
|
606
|
+
for (const field of request.fields) {
|
|
607
|
+
let value = rawContent[field.name];
|
|
608
|
+
const missing =
|
|
609
|
+
value === undefined || value === null || (value === "" && field.required);
|
|
610
|
+
if (missing) {
|
|
611
|
+
if (field.required) throw new Error(`请填写“${field.title}”`);
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
if (field.type === "string") {
|
|
615
|
+
if (typeof value !== "string") throw new Error(`“${field.title}”必须是文本`);
|
|
616
|
+
if (field.minLength !== null && value.length < field.minLength) {
|
|
617
|
+
throw new Error(`“${field.title}”长度不能少于 ${field.minLength}`);
|
|
618
|
+
}
|
|
619
|
+
if (field.maxLength !== null && value.length > field.maxLength) {
|
|
620
|
+
throw new Error(`“${field.title}”长度不能超过 ${field.maxLength}`);
|
|
621
|
+
}
|
|
622
|
+
} else if (field.type === "number" || field.type === "integer") {
|
|
623
|
+
if (typeof value === "string" && value.trim()) value = Number(value);
|
|
624
|
+
if (
|
|
625
|
+
!Number.isFinite(value) ||
|
|
626
|
+
(field.type === "integer" && !Number.isInteger(value))
|
|
627
|
+
) {
|
|
628
|
+
throw new Error(`“${field.title}”必须是有效数字`);
|
|
629
|
+
}
|
|
630
|
+
if (field.minimum !== null && value < field.minimum) {
|
|
631
|
+
throw new Error(`“${field.title}”不能小于 ${field.minimum}`);
|
|
632
|
+
}
|
|
633
|
+
if (field.maximum !== null && value > field.maximum) {
|
|
634
|
+
throw new Error(`“${field.title}”不能大于 ${field.maximum}`);
|
|
635
|
+
}
|
|
636
|
+
} else if (field.type === "boolean") {
|
|
637
|
+
if (typeof value !== "boolean") {
|
|
638
|
+
throw new Error(`“${field.title}”必须是布尔值`);
|
|
639
|
+
}
|
|
640
|
+
} else if (field.type === "array") {
|
|
641
|
+
if (!Array.isArray(value)) throw new Error(`“${field.title}”必须是多选值`);
|
|
642
|
+
if (field.minItems !== null && value.length < field.minItems) {
|
|
643
|
+
throw new Error(`“${field.title}”至少选择 ${field.minItems} 项`);
|
|
644
|
+
}
|
|
645
|
+
if (field.maxItems !== null && value.length > field.maxItems) {
|
|
646
|
+
throw new Error(`“${field.title}”最多选择 ${field.maxItems} 项`);
|
|
647
|
+
}
|
|
648
|
+
} else {
|
|
649
|
+
throw new Error(`暂不支持 MCP 字段“${field.title}”的类型`);
|
|
650
|
+
}
|
|
651
|
+
if (
|
|
652
|
+
field.options &&
|
|
653
|
+
field.type !== "array" &&
|
|
654
|
+
!field.options.some((option) => sameDecision(option.value, value))
|
|
655
|
+
) {
|
|
656
|
+
throw new Error(`“${field.title}”不是有效选项`);
|
|
657
|
+
}
|
|
658
|
+
if (
|
|
659
|
+
field.options &&
|
|
660
|
+
field.type === "array" &&
|
|
661
|
+
value.some(
|
|
662
|
+
(entry) =>
|
|
663
|
+
!field.options.some((option) => sameDecision(option.value, entry)),
|
|
664
|
+
)
|
|
665
|
+
) {
|
|
666
|
+
throw new Error(`“${field.title}”包含无效选项`);
|
|
667
|
+
}
|
|
668
|
+
content[field.name] = value;
|
|
669
|
+
}
|
|
670
|
+
return content;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
export function normalizeHumanResponse(request, rawResponse) {
|
|
674
|
+
if (!request || request.status !== "pending") {
|
|
675
|
+
throw new Error("该请求已经失效或已回答");
|
|
676
|
+
}
|
|
677
|
+
if (request.kind === "user-input") {
|
|
678
|
+
return normalizeUserInputAnswers(
|
|
679
|
+
request,
|
|
680
|
+
rawResponse?.answers || rawResponse,
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
if (
|
|
684
|
+
[
|
|
685
|
+
"command-approval",
|
|
686
|
+
"file-change-approval",
|
|
687
|
+
"legacy-command-approval",
|
|
688
|
+
"legacy-file-change-approval",
|
|
689
|
+
].includes(request.kind)
|
|
690
|
+
) {
|
|
691
|
+
return normalizeDecisionResponse(request, rawResponse);
|
|
692
|
+
}
|
|
693
|
+
if (request.kind === "permissions-approval") {
|
|
694
|
+
const choice = rawResponse?.choice;
|
|
695
|
+
if (!["grant-turn", "grant-session", "decline"].includes(choice)) {
|
|
696
|
+
throw new Error("请选择权限申请的处理方式");
|
|
697
|
+
}
|
|
698
|
+
return {
|
|
699
|
+
permissions: choice === "decline" ? {} : request.permissions,
|
|
700
|
+
scope: choice === "grant-session" ? "session" : "turn",
|
|
701
|
+
...(rawResponse?.strictAutoReview === true
|
|
702
|
+
? { strictAutoReview: true }
|
|
703
|
+
: {}),
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
if (request.kind === "mcp-elicitation") {
|
|
707
|
+
const action = rawResponse?.action;
|
|
708
|
+
if (!["accept", "decline", "cancel"].includes(action)) {
|
|
709
|
+
throw new Error("请选择接受、拒绝或取消");
|
|
710
|
+
}
|
|
711
|
+
if (action === "accept") {
|
|
712
|
+
if (!request.renderable) {
|
|
713
|
+
throw new Error("当前 MCP 请求无法安全渲染,只能拒绝或取消");
|
|
714
|
+
}
|
|
715
|
+
return {
|
|
716
|
+
action,
|
|
717
|
+
content:
|
|
718
|
+
request.mode === "form"
|
|
719
|
+
? normalizeElicitationContent(request, rawResponse.content)
|
|
720
|
+
: null,
|
|
721
|
+
_meta:
|
|
722
|
+
rawResponse._meta &&
|
|
723
|
+
typeof rawResponse._meta === "object" &&
|
|
724
|
+
!Array.isArray(rawResponse._meta)
|
|
725
|
+
? rawResponse._meta
|
|
726
|
+
: null,
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
return { action, content: null, _meta: null };
|
|
730
|
+
}
|
|
731
|
+
throw new Error(`不支持的人工请求类型:${request.kind}`);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
export class JsonlAppServerConnection extends EventEmitter {
|
|
735
|
+
constructor({
|
|
736
|
+
host,
|
|
737
|
+
child,
|
|
738
|
+
requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
|
|
739
|
+
now = () => Date.now(),
|
|
740
|
+
}) {
|
|
741
|
+
super();
|
|
742
|
+
this.host = host;
|
|
743
|
+
this.child = child;
|
|
744
|
+
this.requestTimeoutMs = requestTimeoutMs;
|
|
745
|
+
this.now = now;
|
|
746
|
+
this.status = "connecting";
|
|
747
|
+
this.error = null;
|
|
748
|
+
this.serverInfo = null;
|
|
749
|
+
this.sequence = 0;
|
|
750
|
+
this.pendingRequests = new Map();
|
|
751
|
+
this.stderr = "";
|
|
752
|
+
this.closed = false;
|
|
753
|
+
this.lineReader = null;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
async start() {
|
|
757
|
+
if (this.closed) throw new Error("app-server transport 已关闭");
|
|
758
|
+
this.child.stdout.setEncoding("utf8");
|
|
759
|
+
this.child.stderr.setEncoding("utf8");
|
|
760
|
+
this.lineReader = readline.createInterface({
|
|
761
|
+
input: this.child.stdout,
|
|
762
|
+
crlfDelay: Infinity,
|
|
763
|
+
});
|
|
764
|
+
this.lineReader.on("line", (line) => this.#handleLine(line));
|
|
765
|
+
this.child.stdin.on("error", (error) => this.#handleClose(error));
|
|
766
|
+
this.child.stderr.on("data", (chunk) => {
|
|
767
|
+
this.stderr = `${this.stderr}${chunk}`.slice(-20_000);
|
|
768
|
+
});
|
|
769
|
+
this.child.once("error", (error) => this.#handleClose(error));
|
|
770
|
+
this.child.once("exit", (code, signal) => {
|
|
771
|
+
const suffix = this.stderr.trim().split(/\r?\n/).at(-1);
|
|
772
|
+
const viaProxy = ["ssh-websocket", "local-websocket"].includes(this.child?.scopeTransport);
|
|
773
|
+
this.#handleClose(
|
|
774
|
+
new Error(
|
|
775
|
+
`${viaProxy ? "app-server 连接已断开" : "app-server 已退出"}(${signal || `code ${code ?? "unknown"}`})${
|
|
776
|
+
suffix ? `:${suffix}` : ""
|
|
777
|
+
}`,
|
|
778
|
+
),
|
|
779
|
+
);
|
|
780
|
+
});
|
|
781
|
+
|
|
782
|
+
try {
|
|
783
|
+
this.serverInfo = await this.request("initialize", {
|
|
784
|
+
clientInfo: {
|
|
785
|
+
name: "scope-ssh-monitor",
|
|
786
|
+
title: "SCOPE SSH Codex Monitor",
|
|
787
|
+
version: "0.2.0",
|
|
788
|
+
},
|
|
789
|
+
capabilities: {
|
|
790
|
+
experimentalApi: true,
|
|
791
|
+
requestAttestation: false,
|
|
792
|
+
},
|
|
793
|
+
});
|
|
794
|
+
this.notify("initialized");
|
|
795
|
+
this.status = "connected";
|
|
796
|
+
this.error = null;
|
|
797
|
+
this.emit("change");
|
|
798
|
+
return this.serverInfo;
|
|
799
|
+
} catch (error) {
|
|
800
|
+
this.#handleClose(error);
|
|
801
|
+
throw error;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
request(method, params) {
|
|
806
|
+
if (this.closed) {
|
|
807
|
+
return Promise.reject(new Error("app-server transport 已关闭"));
|
|
808
|
+
}
|
|
809
|
+
const id = `scope-client-${++this.sequence}`;
|
|
810
|
+
return new Promise((resolve, reject) => {
|
|
811
|
+
const timer = setTimeout(() => {
|
|
812
|
+
this.pendingRequests.delete(rpcIdKey(id));
|
|
813
|
+
reject(new Error(`app-server 请求超时:${method}`));
|
|
814
|
+
}, this.requestTimeoutMs);
|
|
815
|
+
this.pendingRequests.set(rpcIdKey(id), { resolve, reject, timer, method });
|
|
816
|
+
try {
|
|
817
|
+
this.#write({ id, method, params });
|
|
818
|
+
} catch (error) {
|
|
819
|
+
clearTimeout(timer);
|
|
820
|
+
this.pendingRequests.delete(rpcIdKey(id));
|
|
821
|
+
reject(error);
|
|
822
|
+
}
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
notify(method, params) {
|
|
827
|
+
this.#write(params === undefined ? { method } : { method, params });
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
respond(requestId, result) {
|
|
831
|
+
this.#write({ id: requestId, result });
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
respondError(requestId, code, message) {
|
|
835
|
+
this.#write({
|
|
836
|
+
id: requestId,
|
|
837
|
+
error: { code, message: cleanString(message, 2_000) },
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
close() {
|
|
842
|
+
if (this.closed) return;
|
|
843
|
+
this.closed = true;
|
|
844
|
+
this.lineReader?.close();
|
|
845
|
+
// Never signal the SSH/app-server child as a side effect of closing the
|
|
846
|
+
// Bridge. Ending stdin lets an idle stdio proxy finish gracefully while a
|
|
847
|
+
// durable remote app-server remains independent from this process.
|
|
848
|
+
if (!this.child.stdin.destroyed) this.child.stdin.end();
|
|
849
|
+
this.#rejectPending(new Error("app-server transport 已关闭"));
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
publicState(sessionIds = []) {
|
|
853
|
+
return {
|
|
854
|
+
host: this.host,
|
|
855
|
+
status: this.status,
|
|
856
|
+
error: this.error,
|
|
857
|
+
serverInfo: this.serverInfo,
|
|
858
|
+
sessionIds,
|
|
859
|
+
automaticContinuationAllowed: Array.isArray(this.capacityRetryDelaysMs) ? this.capacityRetryDelaysMs.length > 0 : null,
|
|
860
|
+
capacityRetryLimit: this.capacityRetryDelaysMs?.length ?? null,
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
#write(message) {
|
|
865
|
+
if (this.closed || !this.child.stdin.writable) {
|
|
866
|
+
throw new Error("app-server stdin 不可写");
|
|
867
|
+
}
|
|
868
|
+
this.child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
#handleLine(line) {
|
|
872
|
+
const trimmed = line.trim();
|
|
873
|
+
if (!trimmed) return;
|
|
874
|
+
let message;
|
|
875
|
+
try {
|
|
876
|
+
message = JSON.parse(trimmed);
|
|
877
|
+
} catch {
|
|
878
|
+
this.emit("protocol-error", new Error("app-server 返回了非 JSONL 数据"));
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
if (
|
|
883
|
+
Object.hasOwn(message, "id") &&
|
|
884
|
+
!message.method &&
|
|
885
|
+
(Object.hasOwn(message, "result") || Object.hasOwn(message, "error"))
|
|
886
|
+
) {
|
|
887
|
+
const pending = this.pendingRequests.get(rpcIdKey(message.id));
|
|
888
|
+
if (!pending) return;
|
|
889
|
+
clearTimeout(pending.timer);
|
|
890
|
+
this.pendingRequests.delete(rpcIdKey(message.id));
|
|
891
|
+
if (message.error) {
|
|
892
|
+
pending.reject(
|
|
893
|
+
new Error(
|
|
894
|
+
cleanString(message.error.message, 2_000) ||
|
|
895
|
+
`app-server ${pending.method} 请求失败`,
|
|
896
|
+
),
|
|
897
|
+
);
|
|
898
|
+
} else {
|
|
899
|
+
pending.resolve(message.result);
|
|
900
|
+
}
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
if (
|
|
905
|
+
HUMAN_REQUEST_METHODS.has(message.method) &&
|
|
906
|
+
Object.hasOwn(message, "id")
|
|
907
|
+
) {
|
|
908
|
+
const request = parseHumanRequest(this.host, message, this.now());
|
|
909
|
+
if (!request) {
|
|
910
|
+
this.emit(
|
|
911
|
+
"protocol-error",
|
|
912
|
+
new Error(`收到无法验证的人工请求:${message.method}`),
|
|
913
|
+
);
|
|
914
|
+
this.respondError(message.id, -32602, "Invalid human request payload");
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
this.emit("human-request", request);
|
|
918
|
+
if (request.kind === "user-input") this.emit("user-input", request);
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
if (Object.hasOwn(message, "id") && message.method) {
|
|
923
|
+
if (message.method === CURRENT_TIME_METHOD) {
|
|
924
|
+
this.respond(message.id, {
|
|
925
|
+
currentTimeAt: Math.floor(this.now() / 1_000),
|
|
926
|
+
});
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
const knownMachineRequest = MACHINE_REQUEST_METHODS.has(message.method);
|
|
930
|
+
this.respondError(
|
|
931
|
+
message.id,
|
|
932
|
+
-32601,
|
|
933
|
+
knownMachineRequest
|
|
934
|
+
? `SCOPE does not provide the machine capability required by ${message.method}`
|
|
935
|
+
: `Unsupported app-server request: ${message.method}`,
|
|
936
|
+
);
|
|
937
|
+
this.emit("machine-request", {
|
|
938
|
+
method: message.method,
|
|
939
|
+
known: knownMachineRequest,
|
|
940
|
+
});
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
if (message.method) this.emit("notification", message);
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
#rejectPending(error) {
|
|
948
|
+
for (const pending of this.pendingRequests.values()) {
|
|
949
|
+
clearTimeout(pending.timer);
|
|
950
|
+
pending.reject(error);
|
|
951
|
+
}
|
|
952
|
+
this.pendingRequests.clear();
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
#handleClose(error) {
|
|
956
|
+
if (this.closed && this.status === "offline") return;
|
|
957
|
+
this.closed = true;
|
|
958
|
+
this.status = "offline";
|
|
959
|
+
this.error = publicConnectionError(error);
|
|
960
|
+
this.#rejectPending(error instanceof Error ? error : new Error(String(error)));
|
|
961
|
+
this.emit("close", error);
|
|
962
|
+
this.emit("change");
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
export class AppServerManager extends EventEmitter {
|
|
967
|
+
constructor({
|
|
968
|
+
spawnConnection,
|
|
969
|
+
requestTimeoutMs,
|
|
970
|
+
now = () => Date.now(),
|
|
971
|
+
setTimer = (callback, delay) => setTimeout(callback, delay),
|
|
972
|
+
clearTimer = (timer) => clearTimeout(timer),
|
|
973
|
+
capacityRetryDelaysMs = DEFAULT_CAPACITY_RETRY_DELAYS_MS,
|
|
974
|
+
resolveCapacityRetryDelays = null,
|
|
975
|
+
validateResume = async () => {},
|
|
976
|
+
transientRetryDelaysMs = [15_000, 45_000, 120_000],
|
|
977
|
+
}) {
|
|
978
|
+
super();
|
|
979
|
+
this.spawnConnection = spawnConnection;
|
|
980
|
+
this.requestTimeoutMs = requestTimeoutMs;
|
|
981
|
+
this.now = now;
|
|
982
|
+
this.setTimer = setTimer;
|
|
983
|
+
this.clearTimer = clearTimer;
|
|
984
|
+
this.capacityRetryDelaysMs = [...capacityRetryDelaysMs];
|
|
985
|
+
this.resolveCapacityRetryDelays = resolveCapacityRetryDelays;
|
|
986
|
+
this.validateResume = validateResume;
|
|
987
|
+
this.transientRetryDelaysMs = [...transientRetryDelaysMs];
|
|
988
|
+
this.connections = new Map();
|
|
989
|
+
this.connecting = new Map();
|
|
990
|
+
this.sessions = new Map();
|
|
991
|
+
this.items = new Map();
|
|
992
|
+
this.requests = new Map();
|
|
993
|
+
this.capacityRecoveries = new Map();
|
|
994
|
+
// Compatibility alias for callers that still inspect the original Plan-only map.
|
|
995
|
+
this.inputs = this.requests;
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
async prepareHost(host, executable = "codex", connectionKey = "active") {
|
|
999
|
+
const selectedConnectionKey = normalizedConnectionKey(connectionKey);
|
|
1000
|
+
const mapKey = connectionMapKey(host, selectedConnectionKey);
|
|
1001
|
+
const current = this.connections.get(mapKey);
|
|
1002
|
+
if (current?.status === "connected" && !current.closed) return current;
|
|
1003
|
+
const inFlight = this.connecting.get(mapKey);
|
|
1004
|
+
if (inFlight) return inFlight;
|
|
1005
|
+
|
|
1006
|
+
const promise = (async () => {
|
|
1007
|
+
const child = this.spawnConnection(
|
|
1008
|
+
host,
|
|
1009
|
+
executable,
|
|
1010
|
+
selectedConnectionKey,
|
|
1011
|
+
);
|
|
1012
|
+
const connection = new JsonlAppServerConnection({
|
|
1013
|
+
host,
|
|
1014
|
+
child,
|
|
1015
|
+
requestTimeoutMs: this.requestTimeoutMs,
|
|
1016
|
+
now: this.now,
|
|
1017
|
+
});
|
|
1018
|
+
connection.connectionKey = selectedConnectionKey;
|
|
1019
|
+
this.connections.set(mapKey, connection);
|
|
1020
|
+
connection.on("human-request", (request) => {
|
|
1021
|
+
request.connectionKey = selectedConnectionKey;
|
|
1022
|
+
request.key = humanRequestKey(
|
|
1023
|
+
requestScopeHost(host, selectedConnectionKey),
|
|
1024
|
+
request.requestId,
|
|
1025
|
+
);
|
|
1026
|
+
const item = request.itemId
|
|
1027
|
+
? this.items.get(`${host}:${request.threadId}:${request.itemId}`)
|
|
1028
|
+
: null;
|
|
1029
|
+
if (
|
|
1030
|
+
item?.type === "fileChange" &&
|
|
1031
|
+
["file-change-approval", "legacy-file-change-approval"].includes(
|
|
1032
|
+
request.kind,
|
|
1033
|
+
)
|
|
1034
|
+
) {
|
|
1035
|
+
request.fileChanges = Array.isArray(item.changes)
|
|
1036
|
+
? item.changes.slice(0, 100).map((change) => ({
|
|
1037
|
+
path: cleanString(change?.path, 4_000),
|
|
1038
|
+
type: cleanString(change?.kind, 100) || "update",
|
|
1039
|
+
preview: cleanString(change?.diff, 12_000),
|
|
1040
|
+
movePath: null,
|
|
1041
|
+
}))
|
|
1042
|
+
: request.fileChanges || [];
|
|
1043
|
+
}
|
|
1044
|
+
this.requests.set(request.key, request);
|
|
1045
|
+
this.emit("change");
|
|
1046
|
+
});
|
|
1047
|
+
connection.on("notification", (message) =>
|
|
1048
|
+
this.#handleNotification(host, selectedConnectionKey, message),
|
|
1049
|
+
);
|
|
1050
|
+
connection.on("protocol-error", (error) => {
|
|
1051
|
+
connection.error = publicConnectionError(error);
|
|
1052
|
+
this.emit("change");
|
|
1053
|
+
});
|
|
1054
|
+
connection.on("change", () => this.emit("change"));
|
|
1055
|
+
connection.on("close", () => {
|
|
1056
|
+
if (this.connections.get(mapKey) !== connection) return;
|
|
1057
|
+
for (const session of this.sessions.values()) {
|
|
1058
|
+
if (
|
|
1059
|
+
session.host === host &&
|
|
1060
|
+
normalizedConnectionKey(session.connectionKey) ===
|
|
1061
|
+
selectedConnectionKey
|
|
1062
|
+
) {
|
|
1063
|
+
this.#cancelCapacityRecovery(host, session.sessionId);
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
for (const request of this.requests.values()) {
|
|
1067
|
+
if (
|
|
1068
|
+
request.host === host &&
|
|
1069
|
+
normalizedConnectionKey(request.connectionKey) ===
|
|
1070
|
+
selectedConnectionKey &&
|
|
1071
|
+
request.status === "pending"
|
|
1072
|
+
) {
|
|
1073
|
+
request.status = "disconnected";
|
|
1074
|
+
request.error = connection.error;
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
for (const session of this.sessions.values()) {
|
|
1078
|
+
if (
|
|
1079
|
+
session.host === host &&
|
|
1080
|
+
normalizedConnectionKey(session.connectionKey) ===
|
|
1081
|
+
selectedConnectionKey
|
|
1082
|
+
) {
|
|
1083
|
+
session.status = "offline";
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
this.emit("change");
|
|
1087
|
+
});
|
|
1088
|
+
await connection.start();
|
|
1089
|
+
if (this.resolveCapacityRetryDelays) {
|
|
1090
|
+
connection.capacityRetryDelaysMs = [];
|
|
1091
|
+
try {
|
|
1092
|
+
const delays = await this.resolveCapacityRetryDelays(host, connection);
|
|
1093
|
+
if (Array.isArray(delays) && delays.length <= 100 &&
|
|
1094
|
+
delays.every((delay) => Number.isFinite(delay) && delay >= 0)) {
|
|
1095
|
+
connection.capacityRetryDelaysMs = [...delays];
|
|
1096
|
+
}
|
|
1097
|
+
} catch {
|
|
1098
|
+
// An unavailable profile probe must not prevent connecting or broaden retries.
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
return connection;
|
|
1102
|
+
})().finally(() => this.connecting.delete(mapKey));
|
|
1103
|
+
this.connecting.set(mapKey, promise);
|
|
1104
|
+
return promise;
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
async resumeSession({
|
|
1108
|
+
host,
|
|
1109
|
+
sessionId,
|
|
1110
|
+
path,
|
|
1111
|
+
cwd,
|
|
1112
|
+
model = null,
|
|
1113
|
+
effort = null,
|
|
1114
|
+
yolo = true,
|
|
1115
|
+
executable = "codex",
|
|
1116
|
+
resumeOnRecovery = null,
|
|
1117
|
+
connectionKey = "active",
|
|
1118
|
+
allowProfileHandoff = false,
|
|
1119
|
+
readOnly = false,
|
|
1120
|
+
}) {
|
|
1121
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
1122
|
+
if (isArchiving(this, host, sessionId)) throw new Error("会话正在归档,请稍后重试");
|
|
1123
|
+
const previous = this.sessions.get(`${host}:${sessionId}`);
|
|
1124
|
+
if (previous?.idleReleasing) throw new Error("会话正在释放空闲资源,请稍后恢复");
|
|
1125
|
+
if (previous?.profileHandoff && !allowProfileHandoff) throw new Error("正在等待旧账号释放 writer;请等待切换完成或取消交接");
|
|
1126
|
+
const selectedConnectionKey = normalizedConnectionKey(connectionKey);
|
|
1127
|
+
await this.validateResume({ host, sessionId, path, connectionKey: selectedConnectionKey });
|
|
1128
|
+
const connection = await this.prepareHost(
|
|
1129
|
+
host,
|
|
1130
|
+
executable,
|
|
1131
|
+
selectedConnectionKey,
|
|
1132
|
+
);
|
|
1133
|
+
if (this.sessions.get(`${host}:${sessionId}`)?.profileHandoff && !allowProfileHandoff) throw new Error("正在交接账号,暂不恢复旧 writer");
|
|
1134
|
+
if (isArchiving(this, host, sessionId)) throw new Error("会话正在归档,请稍后重试");
|
|
1135
|
+
const policy = readOnly || previous?.readOnly ? { yolo: false, approvalPolicy: "never", sandbox: "read-only" } : runtimePolicy(yolo);
|
|
1136
|
+
if (this.sessions.get(`${host}:${sessionId}`)?.idleReleasing) throw new Error("会话正在释放空闲资源,请稍后恢复");
|
|
1137
|
+
const result = await connection.request("thread/resume", {
|
|
1138
|
+
threadId: sessionId,
|
|
1139
|
+
path: path || null,
|
|
1140
|
+
cwd: cwd || null,
|
|
1141
|
+
model: model || null,
|
|
1142
|
+
approvalPolicy: policy.approvalPolicy,
|
|
1143
|
+
sandbox: policy.sandbox,
|
|
1144
|
+
excludeTurns: true,
|
|
1145
|
+
});
|
|
1146
|
+
const thread = result?.thread || {};
|
|
1147
|
+
const record = {
|
|
1148
|
+
host,
|
|
1149
|
+
sessionId: thread.id || sessionId,
|
|
1150
|
+
path: thread.path || path || null,
|
|
1151
|
+
cwd: sessionDirectory(host, result?.cwd || thread.cwd || cwd || ""),
|
|
1152
|
+
model: model || result?.model || "",
|
|
1153
|
+
effort: cleanString(effort, 40),
|
|
1154
|
+
yolo: policy.yolo,
|
|
1155
|
+
readOnly: readOnly || Boolean(previous?.readOnly),
|
|
1156
|
+
executable,
|
|
1157
|
+
connectionKey: selectedConnectionKey,
|
|
1158
|
+
status: this.#statusName(thread.status),
|
|
1159
|
+
resumeOnRecovery:
|
|
1160
|
+
this.#statusName(thread.status) === "working"
|
|
1161
|
+
? true
|
|
1162
|
+
: typeof resumeOnRecovery === "boolean"
|
|
1163
|
+
? resumeOnRecovery
|
|
1164
|
+
: Boolean(previous?.resumeOnRecovery),
|
|
1165
|
+
connectedAt: new Date(this.now()).toISOString(),
|
|
1166
|
+
lastEventAt: new Date(this.now()).toISOString(),
|
|
1167
|
+
};
|
|
1168
|
+
this.sessions.set(`${host}:${record.sessionId}`, record);
|
|
1169
|
+
this.emit("change");
|
|
1170
|
+
return record;
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
async createSession({
|
|
1174
|
+
host,
|
|
1175
|
+
cwd,
|
|
1176
|
+
prompt,
|
|
1177
|
+
attachments = [],
|
|
1178
|
+
model = null,
|
|
1179
|
+
effort = null,
|
|
1180
|
+
yolo = true,
|
|
1181
|
+
executable = "codex",
|
|
1182
|
+
connectionKey = "active",
|
|
1183
|
+
readOnly = false,
|
|
1184
|
+
}) {
|
|
1185
|
+
const selectedConnectionKey = normalizedConnectionKey(connectionKey);
|
|
1186
|
+
const connection = await this.prepareHost(host, executable, selectedConnectionKey);
|
|
1187
|
+
const policy = readOnly ? { yolo: false, approvalPolicy: "never", sandbox: "read-only" } : runtimePolicy(yolo);
|
|
1188
|
+
const result = await connection.request("thread/start", {
|
|
1189
|
+
cwd,
|
|
1190
|
+
model: model || null,
|
|
1191
|
+
approvalPolicy: policy.approvalPolicy,
|
|
1192
|
+
sandbox: policy.sandbox,
|
|
1193
|
+
ephemeral: false,
|
|
1194
|
+
});
|
|
1195
|
+
const thread = result?.thread || {};
|
|
1196
|
+
const sessionId = thread.id;
|
|
1197
|
+
if (!sessionId) {
|
|
1198
|
+
throw new Error("app-server 未返回新 Session ID");
|
|
1199
|
+
}
|
|
1200
|
+
const now = new Date(this.now()).toISOString();
|
|
1201
|
+
const record = {
|
|
1202
|
+
host,
|
|
1203
|
+
sessionId,
|
|
1204
|
+
path: thread.path || null,
|
|
1205
|
+
cwd: sessionDirectory(host, result?.cwd || thread.cwd || cwd),
|
|
1206
|
+
model: result?.model || model || "",
|
|
1207
|
+
effort: cleanString(effort, 40),
|
|
1208
|
+
yolo: policy.yolo,
|
|
1209
|
+
readOnly,
|
|
1210
|
+
executable,
|
|
1211
|
+
connectionKey: selectedConnectionKey,
|
|
1212
|
+
status: "idle",
|
|
1213
|
+
resumeOnRecovery: false,
|
|
1214
|
+
connectedAt: now,
|
|
1215
|
+
lastEventAt: now,
|
|
1216
|
+
};
|
|
1217
|
+
this.sessions.set(`${host}:${sessionId}`, record);
|
|
1218
|
+
if (prompt?.trim() || attachments.length) {
|
|
1219
|
+
await this.startTurn(host, sessionId, prompt || "", {
|
|
1220
|
+
effort,
|
|
1221
|
+
...(attachments.length ? { attachments } : {}),
|
|
1222
|
+
});
|
|
1223
|
+
}
|
|
1224
|
+
this.emit("change");
|
|
1225
|
+
return { ...record };
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
async createDetachedSession({
|
|
1229
|
+
host,
|
|
1230
|
+
cwd,
|
|
1231
|
+
model = null,
|
|
1232
|
+
effort = null,
|
|
1233
|
+
yolo = true,
|
|
1234
|
+
executable = "codex",
|
|
1235
|
+
}) {
|
|
1236
|
+
const child = this.spawnConnection(host, executable);
|
|
1237
|
+
const connection = new JsonlAppServerConnection({
|
|
1238
|
+
host,
|
|
1239
|
+
child,
|
|
1240
|
+
requestTimeoutMs: this.requestTimeoutMs,
|
|
1241
|
+
now: this.now,
|
|
1242
|
+
});
|
|
1243
|
+
try {
|
|
1244
|
+
await connection.start();
|
|
1245
|
+
const policy = runtimePolicy(yolo);
|
|
1246
|
+
const result = await connection.request("thread/start", {
|
|
1247
|
+
cwd,
|
|
1248
|
+
model: model || null,
|
|
1249
|
+
approvalPolicy: policy.approvalPolicy,
|
|
1250
|
+
sandbox: policy.sandbox,
|
|
1251
|
+
ephemeral: false,
|
|
1252
|
+
});
|
|
1253
|
+
const thread = result?.thread || {};
|
|
1254
|
+
if (!thread.id) throw new Error("app-server 未返回新 Session ID");
|
|
1255
|
+
const now = new Date(this.now()).toISOString();
|
|
1256
|
+
const record = {
|
|
1257
|
+
host,
|
|
1258
|
+
sessionId: thread.id,
|
|
1259
|
+
path: thread.path || null,
|
|
1260
|
+
cwd: sessionDirectory(host, result?.cwd || thread.cwd || cwd),
|
|
1261
|
+
model: result?.model || model || "",
|
|
1262
|
+
effort: cleanString(effort, 40),
|
|
1263
|
+
yolo: policy.yolo,
|
|
1264
|
+
status: "idle",
|
|
1265
|
+
resumeOnRecovery: false,
|
|
1266
|
+
connectedAt: now,
|
|
1267
|
+
lastEventAt: now,
|
|
1268
|
+
};
|
|
1269
|
+
// A zero-turn thread can have an id before its rollout exists on disk.
|
|
1270
|
+
// Persist an empty, non-visible item so the CLI can immediately resume
|
|
1271
|
+
// this thread after the isolated app-server transport closes.
|
|
1272
|
+
await connection.request("thread/inject_items", {
|
|
1273
|
+
threadId: record.sessionId,
|
|
1274
|
+
items: [
|
|
1275
|
+
{
|
|
1276
|
+
type: "message",
|
|
1277
|
+
role: "assistant",
|
|
1278
|
+
content: [{ type: "output_text", text: "" }],
|
|
1279
|
+
},
|
|
1280
|
+
],
|
|
1281
|
+
});
|
|
1282
|
+
await connection.request("thread/unsubscribe", {
|
|
1283
|
+
threadId: record.sessionId,
|
|
1284
|
+
});
|
|
1285
|
+
return record;
|
|
1286
|
+
} finally {
|
|
1287
|
+
connection.close();
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
async startTurn(
|
|
1292
|
+
host,
|
|
1293
|
+
sessionId,
|
|
1294
|
+
prompt,
|
|
1295
|
+
{ effort = null, capacityRecovery = false, automaticRecovery = false, attachments = [] } = {},
|
|
1296
|
+
) {
|
|
1297
|
+
if (/^\/[\w:-]+(?:\s|$)/.test(String(prompt).trim())) throw new Error("Codex app-server 不执行 CLI 斜杠命令;请使用命令菜单或 $技能名");
|
|
1298
|
+
if (isArchiving(this, host, sessionId)) throw new Error("会话正在归档,请稍后重试");
|
|
1299
|
+
const session = this.sessions.get(`${host}:${sessionId}`);
|
|
1300
|
+
if (session?.profileSwitching) throw new Error("该 Session 正在切换账号,请稍后发送 instruction");
|
|
1301
|
+
const connection = session
|
|
1302
|
+
? this.connections.get(connectionMapKey(host, session.connectionKey))
|
|
1303
|
+
: null;
|
|
1304
|
+
if (!connection || connection.status !== "connected" || !session) {
|
|
1305
|
+
throw new Error("该 Session 尚未连接 app-server");
|
|
1306
|
+
}
|
|
1307
|
+
if ((capacityRecovery || automaticRecovery) && !await this.canAutoContinue(host, sessionId)) {
|
|
1308
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
1309
|
+
throw new Error("该实际账号未获准自动继续;请手动发送指令");
|
|
1310
|
+
}
|
|
1311
|
+
if (isArchiving(this, host, sessionId) || session.profileSwitching || this.sessions.get(`${host}:${sessionId}`) !== session) {
|
|
1312
|
+
throw new Error("会话状态已变化,未发送指令");
|
|
1313
|
+
}
|
|
1314
|
+
const input = appServerTurnInput(cleanString(prompt, 20_000), attachments);
|
|
1315
|
+
if (!input.length) throw new Error("instruction 和附件不能同时为空");
|
|
1316
|
+
if (!capacityRecovery) this.#cancelCapacityRecovery(host, sessionId);
|
|
1317
|
+
const policy = session.readOnly ? { approvalPolicy: "never", sandboxPolicy: { type: "readOnly" } } : runtimePolicy(session.yolo);
|
|
1318
|
+
session.turnStarting = true;
|
|
1319
|
+
let result;
|
|
1320
|
+
try { result = await connection.request("turn/start", {
|
|
1321
|
+
threadId: sessionId,
|
|
1322
|
+
input,
|
|
1323
|
+
cwd: session.cwd || null,
|
|
1324
|
+
approvalPolicy: policy.approvalPolicy,
|
|
1325
|
+
// `thread/start`/`thread/resume` use the SandboxMode string, while
|
|
1326
|
+
// `turn/start` uses the v2 SandboxPolicy object. Always override the
|
|
1327
|
+
// sticky policy here: a resumed thread must follow the policy selected
|
|
1328
|
+
// in SCOPE instead of silently inheriting an older rollout setting.
|
|
1329
|
+
sandboxPolicy: policy.sandboxPolicy,
|
|
1330
|
+
model: session.model || null,
|
|
1331
|
+
effort: effort || session.effort || null,
|
|
1332
|
+
}); } finally { delete session.turnStarting; }
|
|
1333
|
+
session.status = "working";
|
|
1334
|
+
session.resumeOnRecovery = true;
|
|
1335
|
+
session.activeTurnId = cleanString(result?.turn?.id, 200) || null;
|
|
1336
|
+
session.lastProtocolError = null;
|
|
1337
|
+
session.lastEventAt = new Date(this.now()).toISOString();
|
|
1338
|
+
this.emit("change");
|
|
1339
|
+
return result;
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
clearSessionRestartHold(host, sessionId) {
|
|
1343
|
+
if (isArchiving(this, host, sessionId)) return;
|
|
1344
|
+
const session = this.sessions.get(`${host}:${sessionId}`);
|
|
1345
|
+
if (session) { delete session.profileHandoff; delete session.profileSwitching; }
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
async canAutoContinue(host, sessionId) {
|
|
1349
|
+
if (isArchiving(this, host, sessionId)) return false;
|
|
1350
|
+
if (!this.resolveCapacityRetryDelays) return true;
|
|
1351
|
+
const session = this.sessions.get(`${host}:${sessionId}`);
|
|
1352
|
+
const connection = session && this.connections.get(connectionMapKey(host, session.connectionKey));
|
|
1353
|
+
if (!connection || connection.closed || session.profileHandoff) return false;
|
|
1354
|
+
try {
|
|
1355
|
+
const delays = await this.resolveCapacityRetryDelays(host, connection);
|
|
1356
|
+
connection.capacityRetryDelaysMs = Array.isArray(delays) ? delays : [];
|
|
1357
|
+
return connection.capacityRetryDelaysMs.length > 0;
|
|
1358
|
+
} catch {
|
|
1359
|
+
connection.capacityRetryDelaysMs = [];
|
|
1360
|
+
return false;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
async steerTurn(host, sessionId, prompt, { attachments = [] } = {}) {
|
|
1365
|
+
if (isArchiving(this, host, sessionId)) throw new Error("会话正在归档,请稍后重试");
|
|
1366
|
+
const session = this.sessions.get(`${host}:${sessionId}`);
|
|
1367
|
+
if (session?.profileHandoff) throw new Error("正在交接账号,请等待完成或取消交接后发送 instruction");
|
|
1368
|
+
const connection = session
|
|
1369
|
+
? this.connections.get(connectionMapKey(host, session.connectionKey))
|
|
1370
|
+
: null;
|
|
1371
|
+
if (!connection || connection.status !== "connected" || !session) {
|
|
1372
|
+
throw new Error("该 Session 尚未连接 app-server");
|
|
1373
|
+
}
|
|
1374
|
+
const input = appServerTurnInput(cleanString(prompt, 20_000), attachments);
|
|
1375
|
+
if (!input.length) throw new Error("instruction 和附件不能同时为空");
|
|
1376
|
+
let activeTurnId = cleanString(session.activeTurnId, 200);
|
|
1377
|
+
if (!activeTurnId) {
|
|
1378
|
+
const current = await connection.request("thread/read", {
|
|
1379
|
+
threadId: sessionId,
|
|
1380
|
+
includeTurns: true,
|
|
1381
|
+
});
|
|
1382
|
+
activeTurnId = cleanString(
|
|
1383
|
+
[...(Array.isArray(current?.thread?.turns) ? current.thread.turns : [])]
|
|
1384
|
+
.reverse()
|
|
1385
|
+
.find((turn) => turn?.status === "inProgress")?.id,
|
|
1386
|
+
200,
|
|
1387
|
+
);
|
|
1388
|
+
}
|
|
1389
|
+
if (!activeTurnId) {
|
|
1390
|
+
throw new Error("当前 Session 没有可接收追加 context 的活动 Turn;请刷新后重试");
|
|
1391
|
+
}
|
|
1392
|
+
const result = await connection.request("turn/steer", {
|
|
1393
|
+
threadId: sessionId,
|
|
1394
|
+
expectedTurnId: activeTurnId,
|
|
1395
|
+
input,
|
|
1396
|
+
additionalContext: null,
|
|
1397
|
+
});
|
|
1398
|
+
session.activeTurnId = activeTurnId;
|
|
1399
|
+
session.lastEventAt = new Date(this.now()).toISOString();
|
|
1400
|
+
session.resumeOnRecovery = true;
|
|
1401
|
+
this.emit("change");
|
|
1402
|
+
return result;
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
async listModels(host, executable = "codex", connectionKey = "active") {
|
|
1406
|
+
const connection = await this.prepareHost(host, executable, connectionKey);
|
|
1407
|
+
const models = [];
|
|
1408
|
+
let cursor = null;
|
|
1409
|
+
do {
|
|
1410
|
+
const result = await connection.request("model/list", {
|
|
1411
|
+
cursor,
|
|
1412
|
+
limit: 100,
|
|
1413
|
+
includeHidden: false,
|
|
1414
|
+
});
|
|
1415
|
+
for (const model of result?.data || []) {
|
|
1416
|
+
if (!model?.id) continue;
|
|
1417
|
+
models.push({
|
|
1418
|
+
id: cleanString(model.id, 200),
|
|
1419
|
+
model: cleanString(model.model, 200),
|
|
1420
|
+
displayName: cleanString(model.displayName, 200),
|
|
1421
|
+
description: cleanString(model.description, 600),
|
|
1422
|
+
isDefault: Boolean(model.isDefault),
|
|
1423
|
+
defaultReasoningEffort: cleanString(
|
|
1424
|
+
model.defaultReasoningEffort,
|
|
1425
|
+
40,
|
|
1426
|
+
),
|
|
1427
|
+
supportedReasoningEfforts: (model.supportedReasoningEfforts || [])
|
|
1428
|
+
.map((option) => cleanString(option?.reasoningEffort, 40))
|
|
1429
|
+
.filter(Boolean),
|
|
1430
|
+
});
|
|
1431
|
+
}
|
|
1432
|
+
cursor = result?.nextCursor || null;
|
|
1433
|
+
} while (cursor && models.length < 300);
|
|
1434
|
+
return models;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
async getAccount(host, executable = "codex", connectionKey = "active") {
|
|
1438
|
+
const connection = await this.prepareHost(host, executable, connectionKey);
|
|
1439
|
+
return connection.request("account/read", { refreshToken: false });
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
async getRateLimits(host, executable = "codex", connectionKey = "active") {
|
|
1443
|
+
const connection = await this.prepareHost(host, executable, connectionKey);
|
|
1444
|
+
const result = await connection.request("account/rateLimits/read", {});
|
|
1445
|
+
connection.rateLimits = normalizeAccountQuota(result?.rateLimits || result);
|
|
1446
|
+
this.emit("change");
|
|
1447
|
+
return connection.rateLimits;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
async setSessionModel(host, sessionId, model, effort = null, yolo = null) {
|
|
1451
|
+
if (isArchiving(this, host, sessionId)) throw new Error("会话正在归档,请稍后重试");
|
|
1452
|
+
const session = this.sessions.get(`${host}:${sessionId}`);
|
|
1453
|
+
if (session?.profileHandoff) throw new Error("正在交接账号,请等待完成或取消后修改模型");
|
|
1454
|
+
const connection = session
|
|
1455
|
+
? this.connections.get(connectionMapKey(host, session.connectionKey))
|
|
1456
|
+
: null;
|
|
1457
|
+
if (!session) {
|
|
1458
|
+
throw new Error("该 Session 尚未由 app-server 托管");
|
|
1459
|
+
}
|
|
1460
|
+
if (session.status !== "working" && session.status !== "offline" && (!connection || connection.status !== "connected")) {
|
|
1461
|
+
throw new Error("该 Session 尚未连接 app-server");
|
|
1462
|
+
}
|
|
1463
|
+
const selectedModel = cleanString(model, 200);
|
|
1464
|
+
const selectedEffort = cleanString(effort, 40);
|
|
1465
|
+
if (!selectedModel) throw new Error("模型不能为空");
|
|
1466
|
+
const policy = session.readOnly
|
|
1467
|
+
? { yolo: false, approvalPolicy: "never", sandbox: "read-only" }
|
|
1468
|
+
: runtimePolicy(typeof yolo === "boolean" ? yolo : session.yolo);
|
|
1469
|
+
// A running turn keeps its existing model. Persist the override now so
|
|
1470
|
+
// turn/start (including recovery) uses it without interrupting that turn.
|
|
1471
|
+
const deferred = session.status === "working" || session.status === "offline";
|
|
1472
|
+
if (!deferred) await connection.request("thread/resume", {
|
|
1473
|
+
threadId: sessionId,
|
|
1474
|
+
path: session.path || null,
|
|
1475
|
+
cwd: session.cwd || null,
|
|
1476
|
+
model: selectedModel,
|
|
1477
|
+
approvalPolicy: policy.approvalPolicy,
|
|
1478
|
+
sandbox: policy.sandbox,
|
|
1479
|
+
excludeTurns: true,
|
|
1480
|
+
});
|
|
1481
|
+
// A loaded thread may report its previous model from thread/resume even
|
|
1482
|
+
// though the requested override is valid for the next turn. Keep the UI
|
|
1483
|
+
// selection authoritative and send it explicitly on every turn/start.
|
|
1484
|
+
session.model = selectedModel;
|
|
1485
|
+
session.effort = selectedEffort;
|
|
1486
|
+
session.yolo = policy.yolo;
|
|
1487
|
+
session.lastEventAt = new Date(this.now()).toISOString();
|
|
1488
|
+
this.emit("change");
|
|
1489
|
+
return { ...session, deferred };
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
async setHostModel(host, selectedModel, effort = null) {
|
|
1493
|
+
const results = [];
|
|
1494
|
+
for (const session of this.sessionRecords().filter((record) => record.host === host)) {
|
|
1495
|
+
const supported = selectedModel.supportedReasoningEfforts || [];
|
|
1496
|
+
const nextEffort = effort || (supported.includes(session.effort)
|
|
1497
|
+
? session.effort : selectedModel.defaultReasoningEffort || supported[0] || "");
|
|
1498
|
+
try {
|
|
1499
|
+
const updated = await this.setSessionModel(host, session.sessionId,
|
|
1500
|
+
selectedModel.model || selectedModel.id, nextEffort);
|
|
1501
|
+
results.push({ sessionId: session.sessionId, transport: "app-server",
|
|
1502
|
+
status: updated.deferred ? "next-turn" : "applied", effort: updated.effort });
|
|
1503
|
+
} catch (error) {
|
|
1504
|
+
results.push({ sessionId: session.sessionId, transport: "app-server",
|
|
1505
|
+
status: "failed", error: error.message });
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
return results;
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
async sessionCommands(host, sessionId) {
|
|
1512
|
+
const session = this.sessions.get(`${host}:${sessionId}`);
|
|
1513
|
+
const connection = session && this.connections.get(connectionMapKey(host, session.connectionKey));
|
|
1514
|
+
if (!session || !connection || connection.status !== "connected") throw new Error("恢复 app-server 会话后可读取项目技能");
|
|
1515
|
+
const result = await connection.request("skills/list", { cwds: [session.cwd], forceReload: true });
|
|
1516
|
+
return (result.data || []).flatMap(group => (group.skills || []).filter(skill => skill.enabled !== false).map(skill => ({
|
|
1517
|
+
name: `skills:${skill.name}`, description: skill.description || skill.interface?.shortDescription || "项目技能",
|
|
1518
|
+
kind: "skill", insertion: `$${skill.name} `,
|
|
1519
|
+
})));
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
async compactSession(host, sessionId) {
|
|
1523
|
+
if (this.sessions.get(`${host}:${sessionId}`)?.profileHandoff) throw new Error("正在交接账号,请等待完成或先取消交接");
|
|
1524
|
+
if (isArchiving(this, host, sessionId)) throw new Error("会话正在归档,请稍后重试");
|
|
1525
|
+
const session = this.sessions.get(`${host}:${sessionId}`);
|
|
1526
|
+
const connection = session
|
|
1527
|
+
? this.connections.get(connectionMapKey(host, session.connectionKey))
|
|
1528
|
+
: null;
|
|
1529
|
+
if (!connection || connection.status !== "connected" || !session) {
|
|
1530
|
+
throw new Error("该 Session 尚未连接 app-server");
|
|
1531
|
+
}
|
|
1532
|
+
const result = await connection.request("thread/compact/start", {
|
|
1533
|
+
threadId: sessionId,
|
|
1534
|
+
});
|
|
1535
|
+
session.status = "working";
|
|
1536
|
+
session.lastEventAt = new Date(this.now()).toISOString();
|
|
1537
|
+
this.emit("change");
|
|
1538
|
+
return result;
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
/** Stop only this turn. Keep the chat subscribed and ready for another message. */
|
|
1542
|
+
async interruptTurn(host, sessionId) {
|
|
1543
|
+
if (isArchiving(this, host, sessionId)) throw new Error("会话正在归档,请稍后重试");
|
|
1544
|
+
const session = this.sessions.get(`${host}:${sessionId}`);
|
|
1545
|
+
if (!session || session.profileHandoff) throw new Error("会话未连接或正在交接账号");
|
|
1546
|
+
const connection = this.connections.get(connectionMapKey(host, session.connectionKey));
|
|
1547
|
+
if (!connection || connection.status !== "connected" || connection.closed || session.status === "offline")
|
|
1548
|
+
throw new Error("主机离线,无法确认生成已停止");
|
|
1549
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
1550
|
+
let turnId = cleanString(session.activeTurnId, 200);
|
|
1551
|
+
if (!turnId && session.status === "working") {
|
|
1552
|
+
const current = await connection.request("thread/read", { threadId: sessionId, includeTurns: true });
|
|
1553
|
+
turnId = cleanString([...(current.thread?.turns || [])].reverse().find(turn => turn.status === "inProgress")?.id, 200);
|
|
1554
|
+
if (!turnId && this.#statusName(current.thread?.status) === "working") throw new Error("尚未定位活动 Turn,请稍后重试");
|
|
1555
|
+
}
|
|
1556
|
+
if (turnId) await connection.request("turn/interrupt", { threadId: sessionId, turnId });
|
|
1557
|
+
session.activeTurnId = null;
|
|
1558
|
+
session.status = "idle";
|
|
1559
|
+
session.resumeOnRecovery = false;
|
|
1560
|
+
session.lastEventAt = new Date(this.now()).toISOString();
|
|
1561
|
+
this.emit("change");
|
|
1562
|
+
return { interrupted: Boolean(turnId), sessionId };
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
async stopSession(host, sessionId) {
|
|
1566
|
+
if (isArchiving(this, host, sessionId)) throw new Error("会话正在归档,请稍后重试");
|
|
1567
|
+
if (this.sessions.get(`${host}:${sessionId}`)?.profileHandoff) throw new Error("正在交接账号,请先取消交接再关闭会话");
|
|
1568
|
+
const key = `${host}:${sessionId}`;
|
|
1569
|
+
const session = this.sessions.get(key);
|
|
1570
|
+
const connection = session
|
|
1571
|
+
? this.connections.get(connectionMapKey(host, session.connectionKey))
|
|
1572
|
+
: null;
|
|
1573
|
+
if (!session) {
|
|
1574
|
+
throw new Error("该 Session 尚未由 app-server 托管");
|
|
1575
|
+
}
|
|
1576
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
1577
|
+
if (
|
|
1578
|
+
!connection ||
|
|
1579
|
+
connection.status !== "connected" ||
|
|
1580
|
+
connection.closed ||
|
|
1581
|
+
session.status === "offline"
|
|
1582
|
+
) {
|
|
1583
|
+
throw new Error(
|
|
1584
|
+
"该主机当前离线,无法确认远端 Turn 已停止;请恢复连接后重试",
|
|
1585
|
+
);
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
let activeTurnId = cleanString(session.activeTurnId, 200);
|
|
1589
|
+
if (session.status === "working" && !activeTurnId) {
|
|
1590
|
+
const current = await connection.request("thread/read", {
|
|
1591
|
+
threadId: sessionId,
|
|
1592
|
+
includeTurns: true,
|
|
1593
|
+
});
|
|
1594
|
+
activeTurnId = cleanString(
|
|
1595
|
+
[...(current?.thread?.turns || [])]
|
|
1596
|
+
.reverse()
|
|
1597
|
+
.find((turn) => turn?.status === "inProgress")?.id,
|
|
1598
|
+
200,
|
|
1599
|
+
);
|
|
1600
|
+
if (
|
|
1601
|
+
!activeTurnId &&
|
|
1602
|
+
this.#statusName(current?.thread?.status) === "working"
|
|
1603
|
+
) {
|
|
1604
|
+
throw new Error(
|
|
1605
|
+
"远端仍报告 Session 活跃,但无法定位可中止的 Turn;为避免误报已关闭,操作已取消",
|
|
1606
|
+
);
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
let interrupted = false;
|
|
1611
|
+
if (activeTurnId) {
|
|
1612
|
+
await connection.request("turn/interrupt", {
|
|
1613
|
+
threadId: sessionId,
|
|
1614
|
+
turnId: activeTurnId,
|
|
1615
|
+
});
|
|
1616
|
+
interrupted = true;
|
|
1617
|
+
}
|
|
1618
|
+
await connection.request("thread/unsubscribe", { threadId: sessionId });
|
|
1619
|
+
|
|
1620
|
+
this.sessions.delete(key);
|
|
1621
|
+
for (const itemKey of this.items.keys()) {
|
|
1622
|
+
if (itemKey.startsWith(`${host}:${sessionId}:`)) {
|
|
1623
|
+
this.items.delete(itemKey);
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
for (const [requestKey, request] of this.requests.entries()) {
|
|
1627
|
+
if (request.host === host && request.threadId === sessionId) {
|
|
1628
|
+
this.requests.delete(requestKey);
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
// Stopping a logical app-server session only interrupts its active turn and
|
|
1632
|
+
// releases this monitor's subscription. The durable rollout stays in
|
|
1633
|
+
// ~/.codex/sessions and the shared host daemon remains available to sibling
|
|
1634
|
+
// sessions.
|
|
1635
|
+
this.emit("session-release", {
|
|
1636
|
+
host,
|
|
1637
|
+
sessionId,
|
|
1638
|
+
reason: "stop",
|
|
1639
|
+
record: { ...session, resumeOnRecovery: false },
|
|
1640
|
+
});
|
|
1641
|
+
this.emit("change");
|
|
1642
|
+
return {
|
|
1643
|
+
...session,
|
|
1644
|
+
stopped: true,
|
|
1645
|
+
interrupted,
|
|
1646
|
+
};
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
async archiveSession(host, sessionId, executable = "codex", connectionKey = "active") {
|
|
1650
|
+
return archiveThread(this, host, sessionId, executable, connectionKey);
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
forgetArchivedSession(host, sessionId) {
|
|
1654
|
+
const key = `${host}:${sessionId}`;
|
|
1655
|
+
const session = this.sessions.get(key);
|
|
1656
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
1657
|
+
this.sessions.delete(key);
|
|
1658
|
+
for (const itemKey of this.items.keys()) if (itemKey.startsWith(`${key}:`)) this.items.delete(itemKey);
|
|
1659
|
+
for (const [requestKey, request] of this.requests) if (request.host === host && request.threadId === sessionId) this.requests.delete(requestKey);
|
|
1660
|
+
this.emit("session-release", { host, sessionId, reason: "archive", record: session });
|
|
1661
|
+
this.emit("change");
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
async unarchiveSession(host, sessionId, executable = "codex", connectionKey = "active") {
|
|
1665
|
+
const connection = await this.prepareHost(host, executable, connectionKey);
|
|
1666
|
+
try {
|
|
1667
|
+
const result = await connection.request("thread/unarchive", { threadId: sessionId });
|
|
1668
|
+
return result?.thread || { id: sessionId };
|
|
1669
|
+
} catch (error) {
|
|
1670
|
+
// Recover when the earlier unarchive succeeded but its reply was lost.
|
|
1671
|
+
const current = await connection.request("thread/read", { threadId: sessionId, includeTurns: false }).catch(() => null);
|
|
1672
|
+
if (/[\\/]sessions[\\/]/.test(current?.thread?.path || "")) return current.thread;
|
|
1673
|
+
throw error;
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
async releaseSession(host, sessionId, executable = "codex") {
|
|
1678
|
+
if (isArchiving(this, host, sessionId)) throw new Error("会话正在归档,请稍后重试");
|
|
1679
|
+
if (this.sessions.get(`${host}:${sessionId}`)?.profileHandoff) throw new Error("正在交接账号,请先取消交接");
|
|
1680
|
+
const key = `${host}:${sessionId}`;
|
|
1681
|
+
const session = this.sessions.get(key);
|
|
1682
|
+
const connection = session
|
|
1683
|
+
? this.connections.get(connectionMapKey(host, session.connectionKey))
|
|
1684
|
+
: null;
|
|
1685
|
+
if (!session) {
|
|
1686
|
+
throw new Error("该 Session 尚未连接 app-server");
|
|
1687
|
+
}
|
|
1688
|
+
if (
|
|
1689
|
+
!connection ||
|
|
1690
|
+
connection.status !== "connected" ||
|
|
1691
|
+
connection.closed ||
|
|
1692
|
+
session.status === "offline"
|
|
1693
|
+
) {
|
|
1694
|
+
// The SSH stdio transport may have disappeared while the last known
|
|
1695
|
+
// session record remains useful for recovery. There is nothing remote
|
|
1696
|
+
// left to unsubscribe in that case; discard only the stale local
|
|
1697
|
+
// subscription so the same rollout can be resumed through tmux.
|
|
1698
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
1699
|
+
this.sessions.delete(key);
|
|
1700
|
+
this.emit("session-release", { host, sessionId });
|
|
1701
|
+
for (const itemKey of this.items.keys()) {
|
|
1702
|
+
if (itemKey.startsWith(`${host}:${sessionId}:`)) {
|
|
1703
|
+
this.items.delete(itemKey);
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
for (const [requestKey, request] of this.requests.entries()) {
|
|
1707
|
+
if (request.host === host && request.threadId === sessionId) {
|
|
1708
|
+
this.requests.delete(requestKey);
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
this.emit("change");
|
|
1712
|
+
return { ...session, status: "offline", releasedOffline: true };
|
|
1713
|
+
}
|
|
1714
|
+
if (session.status === "working") {
|
|
1715
|
+
throw new Error("当前 app-server Turn 仍在运行,请等待回复完成后再切换到 tmux");
|
|
1716
|
+
}
|
|
1717
|
+
const pendingRequest = Array.from(this.requests.values()).find(
|
|
1718
|
+
(request) =>
|
|
1719
|
+
request.host === host &&
|
|
1720
|
+
request.threadId === sessionId &&
|
|
1721
|
+
["pending", "responding", "disconnected"].includes(request.status),
|
|
1722
|
+
);
|
|
1723
|
+
if (pendingRequest) {
|
|
1724
|
+
throw new Error("该 Session 仍有待回答问题或审批,请处理后再切换到 tmux");
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
const siblingSessions = Array.from(this.sessions.values()).filter(
|
|
1728
|
+
(candidate) =>
|
|
1729
|
+
candidate.host === host &&
|
|
1730
|
+
candidate.sessionId !== sessionId &&
|
|
1731
|
+
normalizedConnectionKey(candidate.connectionKey) ===
|
|
1732
|
+
normalizedConnectionKey(session.connectionKey) &&
|
|
1733
|
+
candidate.status !== "offline",
|
|
1734
|
+
);
|
|
1735
|
+
if (siblingSessions.some((candidate) => candidate.status === "working")) {
|
|
1736
|
+
throw new Error(
|
|
1737
|
+
"同一主机还有正在运行的 app-server Turn;为避免中断其他 Session,请等待它完成后再切换",
|
|
1738
|
+
);
|
|
1739
|
+
}
|
|
1740
|
+
const siblingRequest = Array.from(this.requests.values()).find(
|
|
1741
|
+
(request) =>
|
|
1742
|
+
request.host === host &&
|
|
1743
|
+
request.threadId !== sessionId &&
|
|
1744
|
+
["pending", "responding", "disconnected"].includes(request.status),
|
|
1745
|
+
);
|
|
1746
|
+
if (siblingRequest) {
|
|
1747
|
+
throw new Error(
|
|
1748
|
+
"同一主机还有待回答的 app-server 请求;请先处理后再切换该 Session",
|
|
1749
|
+
);
|
|
1750
|
+
}
|
|
1751
|
+
|
|
1752
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
1753
|
+
await connection.request("thread/unsubscribe", { threadId: sessionId });
|
|
1754
|
+
this.sessions.delete(key);
|
|
1755
|
+
this.emit("session-release", { host, sessionId });
|
|
1756
|
+
for (const itemKey of this.items.keys()) {
|
|
1757
|
+
if (itemKey.startsWith(`${host}:${sessionId}:`)) {
|
|
1758
|
+
this.items.delete(itemKey);
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
// Keep the shared host transport connected. Sibling sessions can continue
|
|
1762
|
+
// and an idle connection is safer than terminating its process tree.
|
|
1763
|
+
|
|
1764
|
+
try {
|
|
1765
|
+
for (const sibling of siblingSessions) {
|
|
1766
|
+
await this.resumeSession({
|
|
1767
|
+
host,
|
|
1768
|
+
sessionId: sibling.sessionId,
|
|
1769
|
+
path: sibling.path,
|
|
1770
|
+
cwd: sibling.cwd,
|
|
1771
|
+
model: sibling.model || null,
|
|
1772
|
+
effort: sibling.effort || null,
|
|
1773
|
+
yolo: sibling.yolo !== false,
|
|
1774
|
+
executable,
|
|
1775
|
+
connectionKey: sibling.connectionKey,
|
|
1776
|
+
});
|
|
1777
|
+
}
|
|
1778
|
+
this.emit("change");
|
|
1779
|
+
return { ...session };
|
|
1780
|
+
} catch (error) {
|
|
1781
|
+
try {
|
|
1782
|
+
for (const original of [...siblingSessions, session]) {
|
|
1783
|
+
await this.resumeSession({
|
|
1784
|
+
host,
|
|
1785
|
+
sessionId: original.sessionId,
|
|
1786
|
+
path: original.path,
|
|
1787
|
+
cwd: original.cwd,
|
|
1788
|
+
model: original.model || null,
|
|
1789
|
+
effort: original.effort || null,
|
|
1790
|
+
yolo: original.yolo !== false,
|
|
1791
|
+
executable,
|
|
1792
|
+
connectionKey: original.connectionKey,
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
} catch (rollbackError) {
|
|
1796
|
+
throw new Error(
|
|
1797
|
+
`${error.message};恢复该主机 app-server Sessions 也失败:${rollbackError.message}`,
|
|
1798
|
+
);
|
|
1799
|
+
}
|
|
1800
|
+
throw error;
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
holdSessionForProfile(host, sessionId) {
|
|
1805
|
+
if (isArchiving(this, host, sessionId)) throw new Error("会话正在归档,请稍后重试");
|
|
1806
|
+
const session = this.sessions.get(`${host}:${sessionId}`);
|
|
1807
|
+
if (!session || session.status === "working" || session.turnStarting || session.profileSwitching ||
|
|
1808
|
+
Array.from(this.requests.values()).some((r) => r.host === host && r.threadId === sessionId &&
|
|
1809
|
+
["pending", "responding", "disconnected"].includes(r.status))) {
|
|
1810
|
+
throw new Error("该会话仍在执行或处理审批,暂不能交接账号");
|
|
1811
|
+
}
|
|
1812
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
1813
|
+
session.profileHandoff = true;
|
|
1814
|
+
session.profileSwitching = true;
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
hydrateProfileHandoff(source) {
|
|
1818
|
+
const key = `${source.host}:${source.sessionId}`;
|
|
1819
|
+
if (this.sessions.has(key)) return;
|
|
1820
|
+
this.sessions.set(key, { ...source, status: "attention", profileHandoff: true,
|
|
1821
|
+
profileSwitching: true, connectedAt: new Date(this.now()).toISOString(), lastEventAt: new Date(this.now()).toISOString() });
|
|
1822
|
+
this.emit("change");
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1825
|
+
async releaseProfileWriter(host, sessionId, source) {
|
|
1826
|
+
const connection = await this.prepareHost(host, source.executable || "codex", source.connectionKey || "active");
|
|
1827
|
+
await connection.request("thread/unsubscribe", { threadId: sessionId });
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
async finishProfileHandoff(host, sessionId, connectionKey, executable, source) {
|
|
1831
|
+
return this.resumeSession({ ...source, host, sessionId, connectionKey, executable: executable || source.executable || "codex",
|
|
1832
|
+
allowProfileHandoff: true });
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
async migrateSessionConnection(
|
|
1836
|
+
host,
|
|
1837
|
+
sessionId,
|
|
1838
|
+
connectionKey = "active",
|
|
1839
|
+
executable = "codex",
|
|
1840
|
+
) {
|
|
1841
|
+
const key = `${host}:${sessionId}`;
|
|
1842
|
+
const session = this.sessions.get(key);
|
|
1843
|
+
if (!session) throw new Error("该 Session 尚未连接 app-server");
|
|
1844
|
+
const sourceConnectionKey = normalizedConnectionKey(session.connectionKey);
|
|
1845
|
+
const targetConnectionKey = normalizedConnectionKey(connectionKey);
|
|
1846
|
+
if (sourceConnectionKey === targetConnectionKey) return { ...session };
|
|
1847
|
+
if (session.status === "working" || session.turnStarting) {
|
|
1848
|
+
throw new Error("当前 app-server Turn 仍在运行,不能迁移 writer");
|
|
1849
|
+
}
|
|
1850
|
+
const pendingRequest = Array.from(this.requests.values()).find(
|
|
1851
|
+
(request) =>
|
|
1852
|
+
request.host === host &&
|
|
1853
|
+
request.threadId === sessionId &&
|
|
1854
|
+
["pending", "responding", "disconnected"].includes(request.status),
|
|
1855
|
+
);
|
|
1856
|
+
if (pendingRequest) {
|
|
1857
|
+
throw new Error("该 Session 仍有待回答问题或审批,不能迁移 writer");
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
const sourceConnection = this.connections.get(
|
|
1861
|
+
connectionMapKey(host, sourceConnectionKey),
|
|
1862
|
+
);
|
|
1863
|
+
if (
|
|
1864
|
+
!sourceConnection ||
|
|
1865
|
+
sourceConnection.status !== "connected" ||
|
|
1866
|
+
sourceConnection.closed
|
|
1867
|
+
) {
|
|
1868
|
+
throw new Error("原 app-server writer 已断开,无法安全释放 Session");
|
|
1869
|
+
}
|
|
1870
|
+
await this.prepareHost(host, executable, targetConnectionKey);
|
|
1871
|
+
if (session.status === "working" || session.turnStarting || session.profileSwitching || Array.from(this.requests.values()).some(
|
|
1872
|
+
(request) => request.host === host && request.threadId === sessionId &&
|
|
1873
|
+
["pending", "responding", "disconnected"].includes(request.status),
|
|
1874
|
+
)) throw new Error("当前 Session 已开始执行或有待处理请求,请稍后切换账号");
|
|
1875
|
+
const original = { ...session };
|
|
1876
|
+
session.profileSwitching = true;
|
|
1877
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
1878
|
+
try {
|
|
1879
|
+
await sourceConnection.request("thread/unsubscribe", { threadId: sessionId });
|
|
1880
|
+
} catch (error) {
|
|
1881
|
+
delete session.profileSwitching;
|
|
1882
|
+
throw error;
|
|
1883
|
+
}
|
|
1884
|
+
try {
|
|
1885
|
+
return await this.resumeSession({
|
|
1886
|
+
host,
|
|
1887
|
+
sessionId,
|
|
1888
|
+
path: original.path,
|
|
1889
|
+
cwd: original.cwd,
|
|
1890
|
+
model: original.model || null,
|
|
1891
|
+
effort: original.effort || null,
|
|
1892
|
+
yolo: original.yolo !== false,
|
|
1893
|
+
executable: original.executable || executable,
|
|
1894
|
+
resumeOnRecovery: original.resumeOnRecovery === true,
|
|
1895
|
+
connectionKey: targetConnectionKey,
|
|
1896
|
+
});
|
|
1897
|
+
} catch (error) {
|
|
1898
|
+
try {
|
|
1899
|
+
await this.resumeSession({
|
|
1900
|
+
host,
|
|
1901
|
+
sessionId,
|
|
1902
|
+
path: original.path,
|
|
1903
|
+
cwd: original.cwd,
|
|
1904
|
+
model: original.model || null,
|
|
1905
|
+
effort: original.effort || null,
|
|
1906
|
+
yolo: original.yolo !== false,
|
|
1907
|
+
executable: original.executable || executable,
|
|
1908
|
+
resumeOnRecovery: original.resumeOnRecovery === true,
|
|
1909
|
+
connectionKey: sourceConnectionKey,
|
|
1910
|
+
});
|
|
1911
|
+
} catch (rollbackError) {
|
|
1912
|
+
throw new Error(
|
|
1913
|
+
`${error.message};回滚原 app-server writer 也失败:${rollbackError.message}`,
|
|
1914
|
+
);
|
|
1915
|
+
}
|
|
1916
|
+
throw error;
|
|
1917
|
+
} finally {
|
|
1918
|
+
delete session.profileSwitching;
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
async forkSessionConnection(
|
|
1923
|
+
host,
|
|
1924
|
+
sessionId,
|
|
1925
|
+
connectionKey = "active",
|
|
1926
|
+
executable = "codex",
|
|
1927
|
+
) {
|
|
1928
|
+
const key = `${host}:${sessionId}`;
|
|
1929
|
+
const session = this.sessions.get(key);
|
|
1930
|
+
if (!session) throw new Error("该 Session 尚未连接 app-server");
|
|
1931
|
+
if (session.status === "working") {
|
|
1932
|
+
throw new Error("当前 app-server Turn 仍在运行,不能创建恢复分支");
|
|
1933
|
+
}
|
|
1934
|
+
const pendingRequest = Array.from(this.requests.values()).find(
|
|
1935
|
+
(request) =>
|
|
1936
|
+
request.host === host &&
|
|
1937
|
+
request.threadId === sessionId &&
|
|
1938
|
+
["pending", "responding", "disconnected"].includes(request.status),
|
|
1939
|
+
);
|
|
1940
|
+
if (pendingRequest) {
|
|
1941
|
+
throw new Error("该 Session 仍有待回答问题或审批,不能创建恢复分支");
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
const selectedConnectionKey = normalizedConnectionKey(connectionKey);
|
|
1945
|
+
const connection = await this.prepareHost(
|
|
1946
|
+
host,
|
|
1947
|
+
executable,
|
|
1948
|
+
selectedConnectionKey,
|
|
1949
|
+
);
|
|
1950
|
+
const policy = runtimePolicy(session.yolo);
|
|
1951
|
+
const result = await connection.request("thread/fork", {
|
|
1952
|
+
threadId: sessionId,
|
|
1953
|
+
path: null,
|
|
1954
|
+
cwd: session.cwd || null,
|
|
1955
|
+
model: session.model || null,
|
|
1956
|
+
approvalPolicy: policy.approvalPolicy,
|
|
1957
|
+
sandbox: policy.sandbox,
|
|
1958
|
+
ephemeral: false,
|
|
1959
|
+
excludeTurns: true,
|
|
1960
|
+
});
|
|
1961
|
+
const thread = result?.thread || {};
|
|
1962
|
+
if (!thread.id || thread.id === sessionId) {
|
|
1963
|
+
throw new Error("app-server 未返回有效的恢复分支 Session ID");
|
|
1964
|
+
}
|
|
1965
|
+
const now = new Date(this.now()).toISOString();
|
|
1966
|
+
const record = {
|
|
1967
|
+
host,
|
|
1968
|
+
sessionId: thread.id,
|
|
1969
|
+
path: thread.path || null,
|
|
1970
|
+
cwd: sessionDirectory(host, result?.cwd || thread.cwd || session.cwd || ""),
|
|
1971
|
+
model: session.model || result?.model || "",
|
|
1972
|
+
effort: cleanString(session.effort, 40),
|
|
1973
|
+
yolo: policy.yolo,
|
|
1974
|
+
executable: session.executable || executable,
|
|
1975
|
+
connectionKey: selectedConnectionKey,
|
|
1976
|
+
status: this.#statusName(thread.status),
|
|
1977
|
+
resumeOnRecovery: true,
|
|
1978
|
+
connectedAt: now,
|
|
1979
|
+
lastEventAt: now,
|
|
1980
|
+
forkedFromSessionId: sessionId,
|
|
1981
|
+
};
|
|
1982
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
1983
|
+
this.sessions.delete(key);
|
|
1984
|
+
this.sessions.set(`${host}:${record.sessionId}`, record);
|
|
1985
|
+
this.emit("session-release", {
|
|
1986
|
+
host,
|
|
1987
|
+
sessionId,
|
|
1988
|
+
reason: "forked-to-active-profile",
|
|
1989
|
+
replacementSessionId: record.sessionId,
|
|
1990
|
+
});
|
|
1991
|
+
this.emit("change");
|
|
1992
|
+
return { ...record };
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
isManaged(host, sessionId) {
|
|
1996
|
+
return this.sessions.has(`${host}:${sessionId}`);
|
|
1997
|
+
}
|
|
1998
|
+
|
|
1999
|
+
isConnected(host, sessionId) {
|
|
2000
|
+
const session = this.sessions.get(`${host}:${sessionId}`);
|
|
2001
|
+
const connection = session
|
|
2002
|
+
? this.connections.get(connectionMapKey(host, session.connectionKey))
|
|
2003
|
+
: null;
|
|
2004
|
+
return Boolean(
|
|
2005
|
+
session &&
|
|
2006
|
+
connection &&
|
|
2007
|
+
connection.status === "connected" &&
|
|
2008
|
+
!connection.closed &&
|
|
2009
|
+
session.status !== "offline",
|
|
2010
|
+
);
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
async answerInput(key, rawAnswers) {
|
|
2014
|
+
return this.answerHumanRequest(key, { answers: rawAnswers });
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
async answerHumanRequest(key, rawResponse) {
|
|
2018
|
+
const request = this.requests.get(key);
|
|
2019
|
+
if (!request) throw new Error("找不到这条待处理请求");
|
|
2020
|
+
if (request.expiresAt && Date.parse(request.expiresAt) <= this.now()) {
|
|
2021
|
+
request.status = "expired";
|
|
2022
|
+
request.error = "请求已自动超时";
|
|
2023
|
+
this.emit("change");
|
|
2024
|
+
throw new Error(request.error);
|
|
2025
|
+
}
|
|
2026
|
+
const payload = normalizeHumanResponse(request, rawResponse);
|
|
2027
|
+
const connection = this.connections.get(
|
|
2028
|
+
connectionMapKey(request.host, request.connectionKey),
|
|
2029
|
+
);
|
|
2030
|
+
if (!connection || connection.status !== "connected") {
|
|
2031
|
+
throw new Error("对应主机的 app-server 已断开");
|
|
2032
|
+
}
|
|
2033
|
+
request.status = "responding";
|
|
2034
|
+
request.error = null;
|
|
2035
|
+
this.emit("change");
|
|
2036
|
+
try {
|
|
2037
|
+
connection.respond(request.requestId, payload);
|
|
2038
|
+
request.status = "answered";
|
|
2039
|
+
request.answeredAt = new Date(this.now()).toISOString();
|
|
2040
|
+
this.emit("change");
|
|
2041
|
+
return {
|
|
2042
|
+
key: request.key,
|
|
2043
|
+
kind: request.kind,
|
|
2044
|
+
host: request.host,
|
|
2045
|
+
threadId: request.threadId,
|
|
2046
|
+
answeredAt: request.answeredAt,
|
|
2047
|
+
};
|
|
2048
|
+
} catch (error) {
|
|
2049
|
+
request.status = "pending";
|
|
2050
|
+
request.error = publicConnectionError(error);
|
|
2051
|
+
this.emit("change");
|
|
2052
|
+
throw error;
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
sessionRecords() {
|
|
2057
|
+
return Array.from(this.sessions.values()).map((session) => {
|
|
2058
|
+
const recovery = this.capacityRecoveries.get(
|
|
2059
|
+
`${session.host}:${session.sessionId}`,
|
|
2060
|
+
);
|
|
2061
|
+
const connection = this.connections.get(
|
|
2062
|
+
connectionMapKey(session.host, session.connectionKey),
|
|
2063
|
+
);
|
|
2064
|
+
return {
|
|
2065
|
+
...session,
|
|
2066
|
+
capacityRecovery: recovery ? this.#publicCapacityRecovery(recovery) : null,
|
|
2067
|
+
rateLimits: connection?.rateLimits || null,
|
|
2068
|
+
};
|
|
2069
|
+
});
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
publicState() {
|
|
2073
|
+
const activeRequests = [];
|
|
2074
|
+
for (const request of this.requests.values()) {
|
|
2075
|
+
if (
|
|
2076
|
+
request.status === "pending" &&
|
|
2077
|
+
request.expiresAt &&
|
|
2078
|
+
Date.parse(request.expiresAt) <= this.now()
|
|
2079
|
+
) {
|
|
2080
|
+
request.status = "expired";
|
|
2081
|
+
request.error = "请求已自动超时";
|
|
2082
|
+
}
|
|
2083
|
+
if (["pending", "responding", "disconnected"].includes(request.status)) {
|
|
2084
|
+
activeRequests.push({
|
|
2085
|
+
...request,
|
|
2086
|
+
...(request.questions
|
|
2087
|
+
? {
|
|
2088
|
+
questions: request.questions.map((question) => ({
|
|
2089
|
+
...question,
|
|
2090
|
+
})),
|
|
2091
|
+
}
|
|
2092
|
+
: {}),
|
|
2093
|
+
});
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
activeRequests.sort(
|
|
2097
|
+
(a, b) => Date.parse(a.receivedAt) - Date.parse(b.receivedAt),
|
|
2098
|
+
);
|
|
2099
|
+
|
|
2100
|
+
return {
|
|
2101
|
+
experimental: true,
|
|
2102
|
+
connections: Array.from(this.connections.entries()).map(
|
|
2103
|
+
([mapKey, connection]) => {
|
|
2104
|
+
const { host, connectionKey } = connectionMapParts(mapKey);
|
|
2105
|
+
return {
|
|
2106
|
+
...connection.publicState(
|
|
2107
|
+
Array.from(this.sessions.values())
|
|
2108
|
+
.filter(
|
|
2109
|
+
(session) =>
|
|
2110
|
+
session.host === host &&
|
|
2111
|
+
normalizedConnectionKey(session.connectionKey) ===
|
|
2112
|
+
connectionKey &&
|
|
2113
|
+
session.status !== "offline",
|
|
2114
|
+
)
|
|
2115
|
+
.map((session) => session.sessionId),
|
|
2116
|
+
),
|
|
2117
|
+
connectionKey,
|
|
2118
|
+
rateLimits: connection.rateLimits || null,
|
|
2119
|
+
};
|
|
2120
|
+
},
|
|
2121
|
+
),
|
|
2122
|
+
sessions: this.sessionRecords(),
|
|
2123
|
+
pendingRequests: activeRequests,
|
|
2124
|
+
pendingInputs: activeRequests.filter(
|
|
2125
|
+
(request) => request.kind === "user-input",
|
|
2126
|
+
),
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
closeHost(host) {
|
|
2131
|
+
this.#cancelHostCapacityRecoveries(host);
|
|
2132
|
+
for (const [mapKey, connection] of this.connections.entries()) {
|
|
2133
|
+
if (connectionMapParts(mapKey).host !== host) continue;
|
|
2134
|
+
connection.close();
|
|
2135
|
+
this.connections.delete(mapKey);
|
|
2136
|
+
}
|
|
2137
|
+
for (const mapKey of this.connecting.keys()) {
|
|
2138
|
+
if (connectionMapParts(mapKey).host === host) {
|
|
2139
|
+
this.connecting.delete(mapKey);
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
for (const session of this.sessions.values()) {
|
|
2143
|
+
if (session.host === host) session.status = "offline";
|
|
2144
|
+
}
|
|
2145
|
+
this.emit("change");
|
|
2146
|
+
}
|
|
2147
|
+
|
|
2148
|
+
closeConnection(host, connectionKey = "active") {
|
|
2149
|
+
const selectedConnectionKey = normalizedConnectionKey(connectionKey);
|
|
2150
|
+
const mapKey = connectionMapKey(host, selectedConnectionKey);
|
|
2151
|
+
for (const session of this.sessions.values()) {
|
|
2152
|
+
if (
|
|
2153
|
+
session.host === host &&
|
|
2154
|
+
normalizedConnectionKey(session.connectionKey) === selectedConnectionKey
|
|
2155
|
+
) {
|
|
2156
|
+
this.#cancelCapacityRecovery(host, session.sessionId);
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
const connection = this.connections.get(mapKey);
|
|
2160
|
+
if (connection) {
|
|
2161
|
+
connection.close();
|
|
2162
|
+
this.connections.delete(mapKey);
|
|
2163
|
+
}
|
|
2164
|
+
this.connecting.delete(mapKey);
|
|
2165
|
+
for (const request of this.requests.values()) {
|
|
2166
|
+
if (
|
|
2167
|
+
request.host === host &&
|
|
2168
|
+
normalizedConnectionKey(request.connectionKey) === selectedConnectionKey &&
|
|
2169
|
+
request.status === "pending"
|
|
2170
|
+
) {
|
|
2171
|
+
request.status = "disconnected";
|
|
2172
|
+
request.error = "app-server writer 正在迁移";
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
for (const session of this.sessions.values()) {
|
|
2176
|
+
if (
|
|
2177
|
+
session.host === host &&
|
|
2178
|
+
normalizedConnectionKey(session.connectionKey) === selectedConnectionKey
|
|
2179
|
+
) {
|
|
2180
|
+
session.status = "offline";
|
|
2181
|
+
session.activeTurnId = null;
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
this.emit("change");
|
|
2185
|
+
}
|
|
2186
|
+
|
|
2187
|
+
close() {
|
|
2188
|
+
for (const recovery of this.capacityRecoveries.values()) {
|
|
2189
|
+
if (recovery.timer) this.clearTimer(recovery.timer);
|
|
2190
|
+
}
|
|
2191
|
+
this.capacityRecoveries.clear();
|
|
2192
|
+
// Each connection is a disposable WebSocket proxy to a durable remote
|
|
2193
|
+
// app-server. Close the proxy stream without terminating the remote daemon.
|
|
2194
|
+
for (const connection of this.connections.values()) connection.close();
|
|
2195
|
+
this.connections.clear();
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
#handleNotification(host, connectionKey, message) {
|
|
2199
|
+
const params = message.params || {};
|
|
2200
|
+
let authenticationFailure = null;
|
|
2201
|
+
let turnFailure = null;
|
|
2202
|
+
let threadSystemError = null;
|
|
2203
|
+
const threadId = cleanString(
|
|
2204
|
+
params.threadId || params.turn?.threadId || params.conversationId,
|
|
2205
|
+
200,
|
|
2206
|
+
);
|
|
2207
|
+
if (
|
|
2208
|
+
threadId &&
|
|
2209
|
+
["item/started", "item/completed"].includes(message.method) &&
|
|
2210
|
+
params.item?.id
|
|
2211
|
+
) {
|
|
2212
|
+
this.items.set(
|
|
2213
|
+
`${host}:${threadId}:${cleanString(params.item.id, 200)}`,
|
|
2214
|
+
params.item,
|
|
2215
|
+
);
|
|
2216
|
+
}
|
|
2217
|
+
if (message.method === "thread/archived" && threadId) {
|
|
2218
|
+
this.forgetArchivedSession(host, threadId);
|
|
2219
|
+
this.emit("thread-archived", { host, sessionId: threadId, connectionKey });
|
|
2220
|
+
return;
|
|
2221
|
+
}
|
|
2222
|
+
if (message.method === "serverRequest/resolved") {
|
|
2223
|
+
const key = humanRequestKey(
|
|
2224
|
+
requestScopeHost(host, connectionKey),
|
|
2225
|
+
params.requestId,
|
|
2226
|
+
);
|
|
2227
|
+
const request = this.requests.get(key);
|
|
2228
|
+
if (request && request.status !== "answered") {
|
|
2229
|
+
request.status = "resolved";
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
if (threadId) {
|
|
2233
|
+
const session = this.sessions.get(`${host}:${threadId}`);
|
|
2234
|
+
if (session) {
|
|
2235
|
+
session.lastEventAt = new Date(this.now()).toISOString();
|
|
2236
|
+
if (message.method === "turn/started") {
|
|
2237
|
+
session.status = "working";
|
|
2238
|
+
session.resumeOnRecovery = true;
|
|
2239
|
+
session.activeTurnId =
|
|
2240
|
+
cleanString(params.turn?.id || params.turnId, 200) ||
|
|
2241
|
+
session.activeTurnId ||
|
|
2242
|
+
null;
|
|
2243
|
+
}
|
|
2244
|
+
if (message.method === "error") {
|
|
2245
|
+
session.lastProtocolError = errorText(params.error || params);
|
|
2246
|
+
if (isModelCapacityError(params.error || params)) {
|
|
2247
|
+
this.#scheduleCapacityContinuation(host, threadId, {
|
|
2248
|
+
turnId: cleanString(params.turnId, 200),
|
|
2249
|
+
error: session.lastProtocolError,
|
|
2250
|
+
});
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
if (message.method === "turn/completed") {
|
|
2254
|
+
const turn = params.turn || {};
|
|
2255
|
+
const turnStatus = cleanString(turn.status, 80).toLowerCase();
|
|
2256
|
+
const failure = turn.error || params.error || session.lastProtocolError;
|
|
2257
|
+
if (turnStatus === "failed" && isModelCapacityError(failure)) {
|
|
2258
|
+
session.status = "idle";
|
|
2259
|
+
this.#scheduleCapacityContinuation(host, threadId, {
|
|
2260
|
+
turnId: cleanString(turn.id || params.turnId, 200),
|
|
2261
|
+
error: errorText(failure),
|
|
2262
|
+
});
|
|
2263
|
+
} else if (
|
|
2264
|
+
turnStatus === "failed" &&
|
|
2265
|
+
isTransientCodexBackendError(failure)
|
|
2266
|
+
) {
|
|
2267
|
+
// Codex has already stored the user item. Continue rather than
|
|
2268
|
+
// replaying the original (possibly side-effectful) instruction.
|
|
2269
|
+
session.status = "idle";
|
|
2270
|
+
this.#scheduleCapacityContinuation(host, threadId, {
|
|
2271
|
+
turnId: cleanString(turn.id || params.turnId, 200),
|
|
2272
|
+
error: errorText(failure),
|
|
2273
|
+
kind: "backend",
|
|
2274
|
+
});
|
|
2275
|
+
} else if (turnStatus === "failed") {
|
|
2276
|
+
session.status = "attention";
|
|
2277
|
+
const authFailure = isAuthenticationRefreshError(failure);
|
|
2278
|
+
// app-server appends the user item before token refresh fails. Keep
|
|
2279
|
+
// the interrupted-work bit so a healthy writer can resume with a
|
|
2280
|
+
// single "continue" rather than duplicating the original prompt.
|
|
2281
|
+
session.resumeOnRecovery = authFailure;
|
|
2282
|
+
this.#failCapacityRecovery(host, threadId, errorText(failure));
|
|
2283
|
+
turnFailure = {
|
|
2284
|
+
host,
|
|
2285
|
+
sessionId: threadId,
|
|
2286
|
+
turnId: cleanString(turn.id || params.turnId, 200),
|
|
2287
|
+
connectionKey: normalizedConnectionKey(session.connectionKey),
|
|
2288
|
+
error: errorText(failure),
|
|
2289
|
+
authenticationFailure: authFailure,
|
|
2290
|
+
};
|
|
2291
|
+
if (authFailure) {
|
|
2292
|
+
authenticationFailure = {
|
|
2293
|
+
host,
|
|
2294
|
+
sessionId: threadId,
|
|
2295
|
+
connectionKey: normalizedConnectionKey(session.connectionKey),
|
|
2296
|
+
error: errorText(failure),
|
|
2297
|
+
};
|
|
2298
|
+
}
|
|
2299
|
+
} else {
|
|
2300
|
+
session.status = "idle";
|
|
2301
|
+
session.resumeOnRecovery = false;
|
|
2302
|
+
session.lastProtocolError = null;
|
|
2303
|
+
this.#cancelCapacityRecovery(host, threadId);
|
|
2304
|
+
}
|
|
2305
|
+
session.activeTurnId = null;
|
|
2306
|
+
}
|
|
2307
|
+
if (message.method === "thread/status/changed") {
|
|
2308
|
+
session.status = this.#statusName(params.status);
|
|
2309
|
+
if (params.status?.type === "systemError") {
|
|
2310
|
+
threadSystemError = {
|
|
2311
|
+
host,
|
|
2312
|
+
sessionId: threadId,
|
|
2313
|
+
connectionKey: normalizedConnectionKey(session.connectionKey),
|
|
2314
|
+
error: errorText(params.status),
|
|
2315
|
+
};
|
|
2316
|
+
}
|
|
2317
|
+
if (session.status === "working") session.resumeOnRecovery = true;
|
|
2318
|
+
if (session.status !== "working") session.activeTurnId = null;
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
if (message.method === "account/rateLimits/updated") {
|
|
2323
|
+
const connection = this.connections.get(
|
|
2324
|
+
connectionMapKey(host, connectionKey),
|
|
2325
|
+
);
|
|
2326
|
+
if (connection) {
|
|
2327
|
+
connection.rateLimits = normalizeAccountQuota(
|
|
2328
|
+
params?.rateLimits || params,
|
|
2329
|
+
);
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
this.emit("change");
|
|
2333
|
+
if (authenticationFailure) {
|
|
2334
|
+
this.emit("authentication-failure", authenticationFailure);
|
|
2335
|
+
}
|
|
2336
|
+
if (turnFailure) this.emit("turn-failure", turnFailure);
|
|
2337
|
+
if (threadSystemError) this.emit("thread-system-error", threadSystemError);
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
#scheduleCapacityContinuation(
|
|
2341
|
+
host,
|
|
2342
|
+
sessionId,
|
|
2343
|
+
{ turnId = "", error = "", kind = "capacity" } = {},
|
|
2344
|
+
) {
|
|
2345
|
+
const key = `${host}:${sessionId}`;
|
|
2346
|
+
const session = this.sessions.get(key);
|
|
2347
|
+
if (!session || session.profileHandoff) return;
|
|
2348
|
+
if (this.resolveCapacityRetryDelays &&
|
|
2349
|
+
!this.connections.get(connectionMapKey(host, session.connectionKey))?.capacityRetryDelaysMs?.length) {
|
|
2350
|
+
this.#cancelCapacityRecovery(host, sessionId);
|
|
2351
|
+
session.status = "attention";
|
|
2352
|
+
return;
|
|
2353
|
+
}
|
|
2354
|
+
const failureId = turnId || `${session.lastEventAt}:${error}`;
|
|
2355
|
+
const current = this.capacityRecoveries.get(key);
|
|
2356
|
+
if (current?.lastFailureId === failureId) return;
|
|
2357
|
+
if (
|
|
2358
|
+
current?.lastError === error &&
|
|
2359
|
+
["scheduled", "waiting"].includes(current.status)
|
|
2360
|
+
) {
|
|
2361
|
+
current.lastFailureId = failureId;
|
|
2362
|
+
return;
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
if (
|
|
2366
|
+
Array.from(this.requests.values()).some(
|
|
2367
|
+
(request) =>
|
|
2368
|
+
request.host === host &&
|
|
2369
|
+
request.threadId === sessionId &&
|
|
2370
|
+
["pending", "responding", "disconnected"].includes(request.status),
|
|
2371
|
+
)
|
|
2372
|
+
) {
|
|
2373
|
+
return;
|
|
2374
|
+
}
|
|
2375
|
+
|
|
2376
|
+
const retryDelays =
|
|
2377
|
+
kind === "backend"
|
|
2378
|
+
? this.transientRetryDelaysMs
|
|
2379
|
+
: this.connections.get(connectionMapKey(host, session.connectionKey))?.capacityRetryDelaysMs || this.capacityRetryDelaysMs;
|
|
2380
|
+
const fallbackError =
|
|
2381
|
+
kind === "backend"
|
|
2382
|
+
? "Codex backend temporarily unavailable"
|
|
2383
|
+
: "Selected model is at capacity";
|
|
2384
|
+
const attempt = current?.kind === kind ? current.attempt || 0 : 0;
|
|
2385
|
+
if (current?.timer) this.clearTimer(current.timer);
|
|
2386
|
+
if (attempt >= retryDelays.length) {
|
|
2387
|
+
const exhausted = {
|
|
2388
|
+
host,
|
|
2389
|
+
sessionId,
|
|
2390
|
+
attempt,
|
|
2391
|
+
status: "exhausted",
|
|
2392
|
+
kind,
|
|
2393
|
+
maxAttempts: retryDelays.length,
|
|
2394
|
+
nextRetryAt: null,
|
|
2395
|
+
lastFailureId: failureId,
|
|
2396
|
+
lastError: error || fallbackError,
|
|
2397
|
+
lastContinueAt: current?.lastContinueAt || null,
|
|
2398
|
+
timer: null,
|
|
2399
|
+
};
|
|
2400
|
+
this.capacityRecoveries.set(key, exhausted);
|
|
2401
|
+
session.status = "attention";
|
|
2402
|
+
this.emit("change");
|
|
2403
|
+
return;
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
const delay = retryDelays[attempt];
|
|
2407
|
+
const recovery = {
|
|
2408
|
+
host,
|
|
2409
|
+
sessionId,
|
|
2410
|
+
attempt: attempt + 1,
|
|
2411
|
+
status: "scheduled",
|
|
2412
|
+
kind,
|
|
2413
|
+
maxAttempts: retryDelays.length,
|
|
2414
|
+
nextRetryAt: new Date(this.now() + delay).toISOString(),
|
|
2415
|
+
lastFailureId: failureId,
|
|
2416
|
+
lastError: error || fallbackError,
|
|
2417
|
+
lastContinueAt: current?.lastContinueAt || null,
|
|
2418
|
+
timer: null,
|
|
2419
|
+
};
|
|
2420
|
+
recovery.timer = this.setTimer(
|
|
2421
|
+
() => this.#runCapacityContinuation(key, recovery),
|
|
2422
|
+
delay,
|
|
2423
|
+
);
|
|
2424
|
+
recovery.timer?.unref?.();
|
|
2425
|
+
this.capacityRecoveries.set(key, recovery);
|
|
2426
|
+
this.emit("change");
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
async #runCapacityContinuation(key, recovery) {
|
|
2430
|
+
if (this.capacityRecoveries.get(key) !== recovery) return;
|
|
2431
|
+
recovery.timer = null;
|
|
2432
|
+
recovery.nextRetryAt = null;
|
|
2433
|
+
const session = this.sessions.get(key);
|
|
2434
|
+
if (!session) {
|
|
2435
|
+
this.capacityRecoveries.delete(key);
|
|
2436
|
+
return;
|
|
2437
|
+
}
|
|
2438
|
+
const hasPendingRequest = Array.from(this.requests.values()).some(
|
|
2439
|
+
(request) =>
|
|
2440
|
+
request.host === recovery.host &&
|
|
2441
|
+
request.threadId === recovery.sessionId &&
|
|
2442
|
+
["pending", "responding", "disconnected"].includes(request.status),
|
|
2443
|
+
);
|
|
2444
|
+
if (session.status === "working" || hasPendingRequest) {
|
|
2445
|
+
recovery.status = "waiting";
|
|
2446
|
+
recovery.nextRetryAt = new Date(this.now() + 2_000).toISOString();
|
|
2447
|
+
recovery.timer = this.setTimer(
|
|
2448
|
+
() => this.#runCapacityContinuation(key, recovery),
|
|
2449
|
+
2_000,
|
|
2450
|
+
);
|
|
2451
|
+
recovery.timer?.unref?.();
|
|
2452
|
+
this.emit("change");
|
|
2453
|
+
return;
|
|
2454
|
+
}
|
|
2455
|
+
|
|
2456
|
+
recovery.status = "sending";
|
|
2457
|
+
this.emit("change");
|
|
2458
|
+
try {
|
|
2459
|
+
await this.startTurn(
|
|
2460
|
+
recovery.host,
|
|
2461
|
+
recovery.sessionId,
|
|
2462
|
+
CAPACITY_CONTINUE_PROMPT,
|
|
2463
|
+
{ capacityRecovery: true },
|
|
2464
|
+
);
|
|
2465
|
+
if (this.capacityRecoveries.get(key) !== recovery) return;
|
|
2466
|
+
recovery.status = "sent";
|
|
2467
|
+
recovery.lastContinueAt = new Date(this.now()).toISOString();
|
|
2468
|
+
this.emit("change");
|
|
2469
|
+
} catch (failure) {
|
|
2470
|
+
if (this.capacityRecoveries.get(key) !== recovery) return;
|
|
2471
|
+
recovery.status = "failed";
|
|
2472
|
+
recovery.lastError = publicConnectionError(failure);
|
|
2473
|
+
session.status = "attention";
|
|
2474
|
+
this.emit("change");
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
#failCapacityRecovery(host, sessionId, failure) {
|
|
2479
|
+
const key = `${host}:${sessionId}`;
|
|
2480
|
+
const recovery = this.capacityRecoveries.get(key);
|
|
2481
|
+
if (!recovery) return;
|
|
2482
|
+
if (recovery.timer) this.clearTimer(recovery.timer);
|
|
2483
|
+
recovery.timer = null;
|
|
2484
|
+
recovery.status = "failed";
|
|
2485
|
+
recovery.nextRetryAt = null;
|
|
2486
|
+
recovery.lastError = failure || recovery.lastError;
|
|
2487
|
+
}
|
|
2488
|
+
|
|
2489
|
+
#cancelCapacityRecovery(host, sessionId) {
|
|
2490
|
+
const key = `${host}:${sessionId}`;
|
|
2491
|
+
const recovery = this.capacityRecoveries.get(key);
|
|
2492
|
+
if (recovery?.timer) this.clearTimer(recovery.timer);
|
|
2493
|
+
this.capacityRecoveries.delete(key);
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
#cancelHostCapacityRecoveries(host) {
|
|
2497
|
+
for (const recovery of this.capacityRecoveries.values()) {
|
|
2498
|
+
if (recovery.host !== host) continue;
|
|
2499
|
+
if (recovery.timer) this.clearTimer(recovery.timer);
|
|
2500
|
+
this.capacityRecoveries.delete(`${recovery.host}:${recovery.sessionId}`);
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
|
|
2504
|
+
#publicCapacityRecovery(recovery) {
|
|
2505
|
+
return {
|
|
2506
|
+
status: recovery.status,
|
|
2507
|
+
kind: recovery.kind || "capacity",
|
|
2508
|
+
attempt: recovery.attempt,
|
|
2509
|
+
maxAttempts: recovery.maxAttempts ?? this.capacityRetryDelaysMs.length,
|
|
2510
|
+
nextRetryAt: recovery.nextRetryAt,
|
|
2511
|
+
lastError: recovery.lastError,
|
|
2512
|
+
lastContinueAt: recovery.lastContinueAt,
|
|
2513
|
+
};
|
|
2514
|
+
}
|
|
2515
|
+
|
|
2516
|
+
#statusName(status) {
|
|
2517
|
+
if (status?.type === "active") return "working";
|
|
2518
|
+
if (status?.type === "systemError") return "attention";
|
|
2519
|
+
if (status?.type === "notLoaded") return "offline";
|
|
2520
|
+
return "idle";
|
|
2521
|
+
}
|
|
2522
|
+
}
|