@walkhi/code-relax 0.1.0-beta.8 → 0.1.0-beta.80
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/README.md +67 -45
- package/dist/bin/cleanup-accounts.mjs +63 -0
- package/dist/bin/codex-remote.mjs +382 -262
- package/dist/bin/manage-relay-admin.mjs +20 -0
- package/dist/bin/migrate-relay-db.mjs +109 -0
- package/dist/bin/publish-android-release.mjs +63 -0
- package/dist/bin/publish-harmony-release.mjs +46 -0
- package/dist/bin/release-upload-server.mjs +190 -0
- package/dist/bin/self-relay-admin.mjs +8 -0
- package/dist/bin/self-relay-demo.mjs +2 -2
- package/dist/bin/self-relay-server.mjs +43 -30
- package/dist/bin/set-relay-admin-password.mjs +11 -0
- package/dist/build-platform.json +1 -0
- package/dist/get-shared-service-url.ps1 +12 -4
- package/dist/shared/app-server-events.cjs +457 -238
- package/dist/shared/code-browser.cjs +159 -0
- package/dist/shared/file-changes.cjs +31 -0
- package/dist/shared/file-citations.cjs +117 -0
- package/dist/shared/file-mentions.cjs +92 -0
- package/dist/shared/message-delivery.cjs +115 -0
- package/dist/shared/p2p-data-channel.cjs +22 -0
- package/dist/shared/p2p-diagnostics.cjs +1 -1
- package/dist/shared/p2p-file-channel.cjs +87 -0
- package/dist/shared/p2p-ice-policy.cjs +22 -0
- package/dist/shared/plan-pricing.cjs +32 -0
- package/dist/shared/question-attention.cjs +69 -0
- package/dist/shared/release-version.cjs +31 -0
- package/dist/shared/server-requests.cjs +311 -67
- package/dist/shared/service-endpoints.cjs +21 -0
- package/dist/shared/timeline-sync.cjs +173 -67
- package/dist/skills/code-relax/SKILL.md +22 -17
- package/dist/src/archived-threads.mjs +22 -0
- package/dist/src/bounded-process-log.mjs +63 -0
- package/dist/src/celsius-client.mjs +107 -0
- package/dist/src/code-browser.mjs +99 -0
- package/dist/src/desktop-launcher.mjs +62 -42
- package/dist/src/dots-approval-timeline.mjs +99 -0
- package/dist/src/dots-avatar.mjs +42 -0
- package/dist/src/dots-chat-projection.mjs +50 -0
- package/dist/src/dots-chat-server.mjs +531 -0
- package/dist/src/dots-message-images.mjs +318 -0
- package/dist/src/dots-profile.mjs +77 -0
- package/dist/src/dots-room-activity.mjs +199 -0
- package/dist/src/dots-room-client.mjs +163 -0
- package/dist/src/dots-room-projection.mjs +94 -0
- package/dist/src/dots-schedules.mjs +66 -0
- package/dist/src/dots-summary-tasks.mjs +32 -0
- package/dist/src/dots-task-catalog.mjs +433 -0
- package/dist/src/dots-task-files.mjs +52 -0
- package/dist/src/file-transfer-range.mjs +22 -0
- package/dist/src/file-upload-session.mjs +153 -0
- package/dist/src/hosted-history-app-server.mjs +103 -0
- package/dist/src/hosted-history-cache.mjs +113 -0
- package/dist/src/lan-socket-server.mjs +269 -37
- package/dist/src/managed-app-server.mjs +398 -216
- package/dist/src/managed-endpoint.mjs +25 -0
- package/dist/src/message-images.mjs +0 -18
- package/dist/src/message-upload-files.mjs +115 -0
- package/dist/src/onboarding.mjs +9 -28
- package/dist/src/plan-pricing.mjs +47 -0
- package/dist/src/platform/README.md +7 -12
- package/dist/src/platform/codex-protocol.mjs +51 -0
- package/dist/src/platform/codex-runtime.mjs +4 -0
- package/dist/src/platform/credential-store.mjs +19 -0
- package/dist/src/platform/desktop-host.mjs +3 -0
- package/dist/src/platform/desktop-permission-mode.mjs +17 -0
- package/dist/src/platform/desktop-project-registration.mjs +3 -0
- package/dist/src/platform/desktop-project-store.mjs +219 -0
- package/dist/src/platform/file-opener.mjs +9 -0
- package/dist/src/platform/linux/codex-runtime.mjs +56 -0
- package/dist/src/platform/linux/desktop-host.mjs +87 -0
- package/dist/src/platform/linux/desktop-installation.mjs +36 -0
- package/dist/src/platform/linux/desktop-project-registration.mjs +11 -0
- package/dist/src/platform/linux/network-info.mjs +11 -0
- package/dist/src/platform/linux/process.mjs +53 -0
- package/dist/src/platform/linux/project-locations.mjs +17 -0
- package/dist/src/platform/linux/resident-startup.mjs +52 -0
- package/dist/src/platform/linux/retained-runtime.mjs +76 -0
- package/dist/src/platform/linux/service-host.mjs +18 -0
- package/dist/src/platform/linux/system.mjs +50 -0
- package/dist/src/platform/linux/user-environment.mjs +31 -0
- package/dist/src/platform/macos/codex-runtime.mjs +121 -0
- package/dist/src/platform/macos/desktop-host.mjs +86 -0
- package/dist/src/platform/macos/desktop-project-registration.mjs +11 -0
- package/dist/src/platform/macos/network-info.mjs +8 -0
- package/dist/src/platform/macos/project-locations.mjs +8 -0
- package/dist/src/platform/macos/resident-startup.mjs +84 -0
- package/dist/src/platform/macos/retained-runtime.mjs +127 -0
- package/dist/src/platform/macos/service-host.mjs +18 -0
- package/dist/src/platform/macos/system.mjs +29 -0
- package/dist/src/platform/macos/user-environment.mjs +31 -0
- package/dist/src/platform/managed-user-environment.mjs +78 -0
- package/dist/src/platform/native-package.mjs +58 -0
- package/dist/src/platform/network-info.mjs +3 -0
- package/dist/src/platform/path-identity.mjs +5 -0
- package/dist/src/platform/posix/network-candidates.mjs +23 -0
- package/dist/src/platform/posix/runtime-paths.mjs +25 -0
- package/dist/src/platform/power-inhibitor.mjs +22 -0
- package/dist/src/platform/project-locations.mjs +3 -0
- package/dist/src/platform/runtime-paths.mjs +8 -0
- package/dist/src/platform/select.mjs +5 -0
- package/dist/src/platform/service-host.mjs +3 -0
- package/dist/src/platform/user-environment.mjs +3 -0
- package/dist/src/platform/windows/activate-desktop.ps1 +49 -0
- package/dist/src/platform/windows/codex-runtime.mjs +225 -0
- package/dist/src/platform/windows/desktop-helper.mjs +179 -0
- package/dist/src/platform/windows/desktop-host.mjs +45 -18
- package/dist/src/platform/windows/desktop-info.ps1 +27 -5
- package/dist/src/platform/windows/desktop-project-registration.mjs +4 -0
- package/dist/src/platform/windows/desktop-runtime.ps1 +10 -0
- package/dist/src/platform/windows/desktop-shortcuts.ps1 +7 -14
- package/dist/src/platform/windows/dots-profile.mjs +49 -0
- package/dist/src/platform/windows/keep-awake.ps1 +20 -0
- package/dist/src/platform/windows/launch-worker.mjs +41 -42
- package/dist/src/platform/windows/project-locations.mjs +16 -0
- package/dist/src/platform/windows/resident-start.js +20 -0
- package/dist/src/platform/windows/resident-startup.ps1 +27 -11
- package/dist/src/platform/windows/rustdesk-video-probe.mjs +168 -0
- package/dist/src/platform/windows/service-host.mjs +15 -23
- package/dist/src/platform/windows/start-hidden-console.ps1 +11 -2
- package/dist/src/platform/windows/user-environment.mjs +52 -50
- package/dist/src/project-create.mjs +121 -0
- package/dist/src/project-management.mjs +59 -0
- package/dist/src/project-remove.mjs +55 -0
- package/dist/src/project-update.mjs +59 -0
- package/dist/src/relay-config-import.mjs +45 -0
- package/dist/src/runtime-discovery.mjs +67 -0
- package/dist/src/self-relay/account-cleanup.mjs +30 -0
- package/dist/src/self-relay/account-connections.mjs +52 -0
- package/dist/src/self-relay/admin-auth.mjs +59 -0
- package/dist/src/self-relay/admin-cloud.mjs +101 -0
- package/dist/src/self-relay/admin-login-page.mjs +7 -0
- package/dist/src/self-relay/admin-page.mjs +87 -0
- package/dist/src/self-relay/admin-server.mjs +105 -0
- package/dist/src/self-relay/admin-state.mjs +85 -19
- package/dist/src/self-relay/admin-style.mjs +58 -0
- package/dist/src/self-relay/admin-workstations-page.mjs +95 -0
- package/dist/src/self-relay/admin-workstations.mjs +143 -0
- package/dist/src/self-relay/android-releases.mjs +61 -0
- package/dist/src/self-relay/client.mjs +45 -45
- package/dist/src/self-relay/connection-reporting.mjs +38 -0
- package/dist/src/self-relay/connector.mjs +456 -145
- package/dist/src/self-relay/demo.mjs +3 -4
- package/dist/src/self-relay/device-info.mjs +27 -0
- package/dist/src/self-relay/device-store.mjs +10 -2
- package/dist/src/self-relay/diagnostics.mjs +54 -0
- package/dist/src/self-relay/email-accounts.mjs +183 -0
- package/dist/src/self-relay/file-wire.mjs +76 -0
- package/dist/src/self-relay/lan-authorizations.mjs +44 -2
- package/dist/src/self-relay/lifecycle.mjs +255 -262
- package/dist/src/self-relay/long-pairing.mjs +40 -0
- package/dist/src/self-relay/mysql-state.mjs +118 -0
- package/dist/src/self-relay/p2p-probe.mjs +168 -123
- package/dist/src/self-relay/phone-connections.mjs +55 -0
- package/dist/src/self-relay/privacy-page.mjs +26 -0
- package/dist/src/self-relay/public-releases.mjs +67 -0
- package/dist/src/self-relay/rtc-file-bridge.mjs +46 -0
- package/dist/src/self-relay/server.mjs +1064 -428
- package/dist/src/self-relay/usage-daily.mjs +55 -0
- package/dist/src/self-relay/usage-meter.mjs +141 -0
- package/dist/src/server.mjs +1592 -1797
- package/dist/src/service-control.mjs +17 -7
- package/dist/src/service-doctor.mjs +150 -70
- package/dist/src/service-health.mjs +2 -2
- package/dist/src/service-install.mjs +16 -10
- package/dist/src/service-lifecycle.mjs +51 -46
- package/dist/src/service-power.mjs +58 -0
- package/dist/src/service-restart.mjs +45 -12
- package/dist/src/service-update-worker.mjs +42 -0
- package/dist/src/service-update.mjs +80 -0
- package/dist/src/shared-app-server.mjs +490 -305
- package/dist/src/shared-catalog.mjs +132 -50
- package/dist/src/shared-recovery.mjs +24 -14
- package/dist/src/shared-thread-stream.mjs +136 -51
- package/dist/src/skill-install.mjs +0 -13
- package/dist/src/turn-model-history.mjs +47 -0
- package/dist/src/usage-reset.mjs +17 -0
- package/dist/src/workstation-downloads.mjs +120 -0
- package/package.json +35 -37
- package/tools/postinstall.mjs +186 -146
- package/dist/src/app-server-client.mjs +0 -468
- package/dist/src/app-server-tasks.mjs +0 -358
- package/dist/src/debug-ui.mjs +0 -131
- package/dist/src/platform/windows/credential-store.mjs +0 -27
- package/dist/src/platform/windows/credential-store.ps1 +0 -49
- package/dist/src/platform/windows/desktop-monitor.mjs +0 -34
- package/dist/src/platform/windows/desktop-shortcut-run.ps1 +0 -5
- package/dist/src/platform/windows/desktop-tools.mjs +0 -48
- package/dist/src/thread-catalog.mjs +0 -47
- package/dist/tools/find-desktop-pipe.mjs +0 -10
- package/dist/web/activity-view.js +0 -283
- package/dist/web/approval-ui.js +0 -188
- package/dist/web/capabilities.js +0 -57
- package/dist/web/chat-transport.js +0 -202
- package/dist/web/chat.css +0 -782
- package/dist/web/chat.js +0 -3830
- package/dist/web/client-platform.js +0 -11
- package/dist/web/community-view.js +0 -20
- package/dist/web/community.css +0 -77
- package/dist/web/community.html +0 -37
- package/dist/web/composer-controller.js +0 -101
- package/dist/web/conversation-controller.js +0 -99
- package/dist/web/disclosure-state-controller.js +0 -95
- package/dist/web/draft-controller.js +0 -103
- package/dist/web/harmony-platform.js +0 -52
- package/dist/web/highlight-powershell.min.js +0 -39
- package/dist/web/highlight.min.js +0 -1262
- package/dist/web/history-cache.js +0 -240
- package/dist/web/history-controller.js +0 -167
- package/dist/web/index.html +0 -325
- package/dist/web/lan-session.js +0 -122
- package/dist/web/link-action-controller.js +0 -212
- package/dist/web/message-send-controller.js +0 -177
- package/dist/web/message-view.js +0 -98
- package/dist/web/p2p-data-channel.js +0 -50
- package/dist/web/p2p-diagnostics.js +0 -28
- package/dist/web/p2p-probe.js +0 -123
- package/dist/web/page-resume.js +0 -28
- package/dist/web/pending-message-store.js +0 -108
- package/dist/web/queue-controller.js +0 -82
- package/dist/web/resources.json +0 -1
- package/dist/web/self-relay-session.js +0 -129
- package/dist/web/server-requests.js +0 -67
- package/dist/web/station-connection-controller.js +0 -75
- package/dist/web/task-list-view.js +0 -296
- package/dist/web/thread-attention-controller.js +0 -124
- package/dist/web/thread-context-controller.js +0 -30
- package/dist/web/thread-list-controller.js +0 -61
- package/dist/web/thread-list-sync.js +0 -86
- package/dist/web/thread-title-controller.js +0 -57
- package/dist/web/timeline-formatters.js +0 -249
- package/dist/web/timeline-reducer.js +0 -81
- package/dist/web/timeline-renderer.js +0 -161
- package/dist/web/timeline-scroll-controller.js +0 -50
- package/dist/web/timeline-sync.js +0 -67
- package/dist/web/usage-controller.js +0 -258
- package/dist/web/vendor/README.md +0 -14
- package/dist/web/vendor/highlight-powershell.min.js +0 -39
- package/dist/web/vendor/highlight.LICENSE.txt +0 -29
- package/dist/web/vendor/highlight.min.js +0 -1262
- package/dist/web/vendor/lucide.LICENSE.txt +0 -17
- package/node_modules/@img/colour/LICENSE.md +0 -82
- package/node_modules/@img/colour/README.md +0 -15
- package/node_modules/@img/colour/color.cjs +0 -1596
- package/node_modules/@img/colour/index.cjs +0 -1
- package/node_modules/@img/colour/index.d.ts +0 -929
- package/node_modules/@img/colour/package.json +0 -58
- package/node_modules/@img/sharp-win32-x64/LICENSE +0 -191
- package/node_modules/@img/sharp-win32-x64/README.md +0 -59
- package/node_modules/@img/sharp-win32-x64/index.cjs +0 -1
- package/node_modules/@img/sharp-win32-x64/lib/libvips-42.dll +0 -0
- package/node_modules/@img/sharp-win32-x64/lib/libvips-cpp-8.18.6.dll +0 -0
- package/node_modules/@img/sharp-win32-x64/lib/sharp-win32-x64-0.35.4.node +0 -0
- package/node_modules/@img/sharp-win32-x64/package.json +0 -40
- package/node_modules/@img/sharp-win32-x64/versions.json +0 -30
- package/node_modules/@node-datachannel/win32-x64-msvc/node_datachannel.node +0 -0
- package/node_modules/@node-datachannel/win32-x64-msvc/package.json +0 -20
- package/node_modules/ansi-regex/index.d.ts +0 -37
- package/node_modules/ansi-regex/index.js +0 -10
- package/node_modules/ansi-regex/license +0 -9
- package/node_modules/ansi-regex/package.json +0 -55
- package/node_modules/ansi-regex/readme.md +0 -78
- package/node_modules/ansi-styles/index.d.ts +0 -345
- package/node_modules/ansi-styles/index.js +0 -163
- package/node_modules/ansi-styles/license +0 -9
- package/node_modules/ansi-styles/package.json +0 -56
- package/node_modules/ansi-styles/readme.md +0 -152
- package/node_modules/camelcase/index.d.ts +0 -63
- package/node_modules/camelcase/index.js +0 -76
- package/node_modules/camelcase/license +0 -9
- package/node_modules/camelcase/package.json +0 -43
- package/node_modules/camelcase/readme.md +0 -99
- package/node_modules/cliui/CHANGELOG.md +0 -76
- package/node_modules/cliui/LICENSE.txt +0 -14
- package/node_modules/cliui/README.md +0 -115
- package/node_modules/cliui/index.js +0 -354
- package/node_modules/cliui/package.json +0 -65
- package/node_modules/color-convert/CHANGELOG.md +0 -54
- package/node_modules/color-convert/LICENSE +0 -21
- package/node_modules/color-convert/README.md +0 -68
- package/node_modules/color-convert/conversions.js +0 -839
- package/node_modules/color-convert/index.js +0 -81
- package/node_modules/color-convert/package.json +0 -48
- package/node_modules/color-convert/route.js +0 -97
- package/node_modules/color-name/LICENSE +0 -8
- package/node_modules/color-name/README.md +0 -11
- package/node_modules/color-name/index.js +0 -152
- package/node_modules/color-name/package.json +0 -28
- package/node_modules/decamelize/index.js +0 -13
- package/node_modules/decamelize/license +0 -21
- package/node_modules/decamelize/package.json +0 -38
- package/node_modules/decamelize/readme.md +0 -48
- package/node_modules/detect-libc/LICENSE +0 -201
- package/node_modules/detect-libc/README.md +0 -163
- package/node_modules/detect-libc/index.d.ts +0 -14
- package/node_modules/detect-libc/lib/detect-libc.js +0 -313
- package/node_modules/detect-libc/lib/elf.js +0 -39
- package/node_modules/detect-libc/lib/filesystem.js +0 -51
- package/node_modules/detect-libc/lib/process.js +0 -24
- package/node_modules/detect-libc/package.json +0 -44
- package/node_modules/dijkstrajs/.travis.yml +0 -4
- package/node_modules/dijkstrajs/CONTRIBUTING.md +0 -8
- package/node_modules/dijkstrajs/LICENSE.md +0 -19
- package/node_modules/dijkstrajs/README.md +0 -18
- package/node_modules/dijkstrajs/dijkstra.js +0 -165
- package/node_modules/dijkstrajs/package.json +0 -60
- package/node_modules/dijkstrajs/test/dijkstra.test.js +0 -96
- package/node_modules/emoji-regex/LICENSE-MIT.txt +0 -20
- package/node_modules/emoji-regex/README.md +0 -73
- package/node_modules/emoji-regex/es2015/index.js +0 -6
- package/node_modules/emoji-regex/es2015/text.js +0 -6
- package/node_modules/emoji-regex/index.d.ts +0 -23
- package/node_modules/emoji-regex/index.js +0 -6
- package/node_modules/emoji-regex/package.json +0 -50
- package/node_modules/emoji-regex/text.js +0 -6
- package/node_modules/find-up/index.d.ts +0 -137
- package/node_modules/find-up/index.js +0 -89
- package/node_modules/find-up/license +0 -9
- package/node_modules/find-up/package.json +0 -53
- package/node_modules/find-up/readme.md +0 -156
- package/node_modules/get-caller-file/LICENSE.md +0 -6
- package/node_modules/get-caller-file/README.md +0 -41
- package/node_modules/get-caller-file/index.d.ts +0 -2
- package/node_modules/get-caller-file/index.js +0 -22
- package/node_modules/get-caller-file/index.js.map +0 -1
- package/node_modules/get-caller-file/package.json +0 -42
- package/node_modules/is-fullwidth-code-point/index.d.ts +0 -17
- package/node_modules/is-fullwidth-code-point/index.js +0 -50
- package/node_modules/is-fullwidth-code-point/license +0 -9
- package/node_modules/is-fullwidth-code-point/package.json +0 -42
- package/node_modules/is-fullwidth-code-point/readme.md +0 -39
- package/node_modules/locate-path/index.d.ts +0 -83
- package/node_modules/locate-path/index.js +0 -65
- package/node_modules/locate-path/license +0 -9
- package/node_modules/locate-path/package.json +0 -45
- package/node_modules/locate-path/readme.md +0 -122
- package/node_modules/node-datachannel/.clang-format +0 -17
- package/node_modules/node-datachannel/.editorconfig +0 -12
- package/node_modules/node-datachannel/.eslintignore +0 -8
- package/node_modules/node-datachannel/.eslintrc.json +0 -27
- package/node_modules/node-datachannel/.gitmodules +0 -3
- package/node_modules/node-datachannel/.prettierignore +0 -7
- package/node_modules/node-datachannel/.prettierrc +0 -13
- package/node_modules/node-datachannel/API.md +0 -247
- package/node_modules/node-datachannel/BULDING.md +0 -26
- package/node_modules/node-datachannel/CMakeLists.txt +0 -153
- package/node_modules/node-datachannel/LICENSE +0 -373
- package/node_modules/node-datachannel/README.md +0 -129
- package/node_modules/node-datachannel/dist/cjs/index.cjs +0 -11
- package/node_modules/node-datachannel/dist/cjs/index.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/lib/datachannel-stream.cjs +0 -101
- package/node_modules/node-datachannel/dist/cjs/lib/datachannel-stream.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/lib/index.cjs +0 -91
- package/node_modules/node-datachannel/dist/cjs/lib/index.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/lib/node-datachannel.cjs +0 -94
- package/node_modules/node-datachannel/dist/cjs/lib/node-datachannel.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/lib/websocket-server.cjs +0 -45
- package/node_modules/node-datachannel/dist/cjs/lib/websocket-server.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/lib/websocket.cjs +0 -8
- package/node_modules/node-datachannel/dist/cjs/lib/websocket.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/Events.cjs +0 -86
- package/node_modules/node-datachannel/dist/cjs/polyfill/Events.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/Exception.cjs +0 -34
- package/node_modules/node-datachannel/dist/cjs/polyfill/Exception.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCCertificate.cjs +0 -34
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCCertificate.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCDataChannel.cjs +0 -214
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCDataChannel.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCDtlsTransport.cjs +0 -53
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCDtlsTransport.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCError.cjs +0 -83
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCError.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCIceCandidate.cjs +0 -132
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCIceCandidate.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCIceTransport.cjs +0 -94
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCIceTransport.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCPeerConnection.cjs +0 -434
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCPeerConnection.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCSctpTransport.cjs +0 -59
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCSctpTransport.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCSessionDescription.cjs +0 -45
- package/node_modules/node-datachannel/dist/cjs/polyfill/RTCSessionDescription.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/cjs/polyfill/index.cjs +0 -42
- package/node_modules/node-datachannel/dist/cjs/polyfill/index.cjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/index.mjs +0 -8
- package/node_modules/node-datachannel/dist/esm/index.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/lib/datachannel-stream.mjs +0 -78
- package/node_modules/node-datachannel/dist/esm/lib/datachannel-stream.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/lib/index.mjs +0 -64
- package/node_modules/node-datachannel/dist/esm/lib/index.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/lib/node-datachannel.mjs +0 -78
- package/node_modules/node-datachannel/dist/esm/lib/node-datachannel.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/lib/websocket-server.mjs +0 -43
- package/node_modules/node-datachannel/dist/esm/lib/websocket-server.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/lib/websocket.mjs +0 -6
- package/node_modules/node-datachannel/dist/esm/lib/websocket.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/Events.mjs +0 -82
- package/node_modules/node-datachannel/dist/esm/polyfill/Events.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/Exception.mjs +0 -28
- package/node_modules/node-datachannel/dist/esm/polyfill/Exception.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCCertificate.mjs +0 -30
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCCertificate.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCDataChannel.mjs +0 -210
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCDataChannel.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCDtlsTransport.mjs +0 -49
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCDtlsTransport.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCError.mjs +0 -79
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCError.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCIceCandidate.mjs +0 -128
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCIceCandidate.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCIceTransport.mjs +0 -89
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCIceTransport.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCPeerConnection.mjs +0 -430
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCPeerConnection.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCSctpTransport.mjs +0 -55
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCSctpTransport.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCSessionDescription.mjs +0 -41
- package/node_modules/node-datachannel/dist/esm/polyfill/RTCSessionDescription.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/esm/polyfill/index.mjs +0 -27
- package/node_modules/node-datachannel/dist/esm/polyfill/index.mjs.map +0 -1
- package/node_modules/node-datachannel/dist/types/lib/datachannel-stream.d.ts +0 -24
- package/node_modules/node-datachannel/dist/types/lib/index.d.ts +0 -241
- package/node_modules/node-datachannel/dist/types/lib/types.d.ts +0 -119
- package/node_modules/node-datachannel/dist/types/lib/websocket-server.d.ts +0 -13
- package/node_modules/node-datachannel/dist/types/lib/websocket.d.ts +0 -25
- package/node_modules/node-datachannel/dist/types/polyfill/Events.d.ts +0 -15
- package/node_modules/node-datachannel/dist/types/polyfill/RTCCertificate.d.ts +0 -9
- package/node_modules/node-datachannel/dist/types/polyfill/RTCDataChannel.d.ts +0 -29
- package/node_modules/node-datachannel/dist/types/polyfill/RTCDtlsTransport.d.ts +0 -15
- package/node_modules/node-datachannel/dist/types/polyfill/RTCError.d.ts +0 -17
- package/node_modules/node-datachannel/dist/types/polyfill/RTCIceCandidate.d.ts +0 -21
- package/node_modules/node-datachannel/dist/types/polyfill/RTCIceTransport.d.ts +0 -30
- package/node_modules/node-datachannel/dist/types/polyfill/RTCPeerConnection.d.ts +0 -64
- package/node_modules/node-datachannel/dist/types/polyfill/RTCSctpTransport.d.ts +0 -15
- package/node_modules/node-datachannel/dist/types/polyfill/RTCSessionDescription.d.ts +0 -10
- package/node_modules/node-datachannel/dist/types/polyfill/index.d.ts +0 -26
- package/node_modules/node-datachannel/jest.config.ts +0 -14
- package/node_modules/node-datachannel/package.json +0 -133
- package/node_modules/node-datachannel/rollup.config.mjs +0 -67
- package/node_modules/node-datachannel/src/cpp/data-channel-wrapper.cpp +0 -530
- package/node_modules/node-datachannel/src/cpp/data-channel-wrapper.h +0 -63
- package/node_modules/node-datachannel/src/cpp/ice-udp-mux-listener-wrapper.cpp +0 -172
- package/node_modules/node-datachannel/src/cpp/ice-udp-mux-listener-wrapper.h +0 -43
- package/node_modules/node-datachannel/src/cpp/main.cpp +0 -58
- package/node_modules/node-datachannel/src/cpp/media-audio-wrapper.cpp +0 -457
- package/node_modules/node-datachannel/src/cpp/media-audio-wrapper.h +0 -52
- package/node_modules/node-datachannel/src/cpp/media-av1packetization.cpp +0 -24
- package/node_modules/node-datachannel/src/cpp/media-av1packetization.h +0 -11
- package/node_modules/node-datachannel/src/cpp/media-av1rtppacketizer-wrapper.cpp +0 -126
- package/node_modules/node-datachannel/src/cpp/media-av1rtppacketizer-wrapper.h +0 -29
- package/node_modules/node-datachannel/src/cpp/media-direction.cpp +0 -43
- package/node_modules/node-datachannel/src/cpp/media-direction.h +0 -10
- package/node_modules/node-datachannel/src/cpp/media-h264rtppacketizer-wrapper.cpp +0 -126
- package/node_modules/node-datachannel/src/cpp/media-h264rtppacketizer-wrapper.h +0 -30
- package/node_modules/node-datachannel/src/cpp/media-h265rtppacketizer-wrapper.cpp +0 -126
- package/node_modules/node-datachannel/src/cpp/media-h265rtppacketizer-wrapper.h +0 -30
- package/node_modules/node-datachannel/src/cpp/media-h26xseparator.cpp +0 -32
- package/node_modules/node-datachannel/src/cpp/media-h26xseparator.h +0 -11
- package/node_modules/node-datachannel/src/cpp/media-mediahandler-helper.cpp +0 -31
- package/node_modules/node-datachannel/src/cpp/media-mediahandler-helper.h +0 -11
- package/node_modules/node-datachannel/src/cpp/media-pacinghandler-wrapper.cpp +0 -79
- package/node_modules/node-datachannel/src/cpp/media-pacinghandler-wrapper.h +0 -28
- package/node_modules/node-datachannel/src/cpp/media-rtcpnackresponder-wrapper.cpp +0 -68
- package/node_modules/node-datachannel/src/cpp/media-rtcpnackresponder-wrapper.h +0 -28
- package/node_modules/node-datachannel/src/cpp/media-rtcpreceivingsession-wrapper.cpp +0 -57
- package/node_modules/node-datachannel/src/cpp/media-rtcpreceivingsession-wrapper.h +0 -28
- package/node_modules/node-datachannel/src/cpp/media-rtcpsrreporter-wrapper.cpp +0 -93
- package/node_modules/node-datachannel/src/cpp/media-rtcpsrreporter-wrapper.h +0 -30
- package/node_modules/node-datachannel/src/cpp/media-rtppacketizationconfig-wrapper.cpp +0 -167
- package/node_modules/node-datachannel/src/cpp/media-rtppacketizationconfig-wrapper.h +0 -35
- package/node_modules/node-datachannel/src/cpp/media-rtppacketizer-wrapper.cpp +0 -95
- package/node_modules/node-datachannel/src/cpp/media-rtppacketizer-wrapper.h +0 -30
- package/node_modules/node-datachannel/src/cpp/media-track-wrapper.cpp +0 -458
- package/node_modules/node-datachannel/src/cpp/media-track-wrapper.h +0 -61
- package/node_modules/node-datachannel/src/cpp/media-video-wrapper.cpp +0 -526
- package/node_modules/node-datachannel/src/cpp/media-video-wrapper.h +0 -56
- package/node_modules/node-datachannel/src/cpp/peer-connection-wrapper.cpp +0 -1298
- package/node_modules/node-datachannel/src/cpp/peer-connection-wrapper.h +0 -89
- package/node_modules/node-datachannel/src/cpp/rtc-wrapper.cpp +0 -205
- package/node_modules/node-datachannel/src/cpp/rtc-wrapper.h +0 -24
- package/node_modules/node-datachannel/src/cpp/thread-safe-callback.cpp +0 -57
- package/node_modules/node-datachannel/src/cpp/thread-safe-callback.h +0 -47
- package/node_modules/node-datachannel/src/cpp/web-socket-server-wrapper.cpp +0 -275
- package/node_modules/node-datachannel/src/cpp/web-socket-server-wrapper.h +0 -41
- package/node_modules/node-datachannel/src/cpp/web-socket-wrapper.cpp +0 -796
- package/node_modules/node-datachannel/src/cpp/web-socket-wrapper.h +0 -63
- package/node_modules/node-datachannel/src/index.ts +0 -9
- package/node_modules/node-datachannel/src/lib/datachannel-stream.ts +0 -100
- package/node_modules/node-datachannel/src/lib/index.ts +0 -290
- package/node_modules/node-datachannel/src/lib/node-datachannel.ts +0 -84
- package/node_modules/node-datachannel/src/lib/types.ts +0 -169
- package/node_modules/node-datachannel/src/lib/websocket-server.ts +0 -37
- package/node_modules/node-datachannel/src/lib/websocket.ts +0 -26
- package/node_modules/node-datachannel/src/polyfill/Events.ts +0 -82
- package/node_modules/node-datachannel/src/polyfill/Exception.ts +0 -37
- package/node_modules/node-datachannel/src/polyfill/README.md +0 -41
- package/node_modules/node-datachannel/src/polyfill/RTCCertificate.ts +0 -21
- package/node_modules/node-datachannel/src/polyfill/RTCDataChannel.ts +0 -225
- package/node_modules/node-datachannel/src/polyfill/RTCDtlsTransport.ts +0 -46
- package/node_modules/node-datachannel/src/polyfill/RTCError.ts +0 -78
- package/node_modules/node-datachannel/src/polyfill/RTCIceCandidate.ts +0 -128
- package/node_modules/node-datachannel/src/polyfill/RTCIceTransport.ts +0 -90
- package/node_modules/node-datachannel/src/polyfill/RTCPeerConnection.ts +0 -527
- package/node_modules/node-datachannel/src/polyfill/RTCSctpTransport.ts +0 -51
- package/node_modules/node-datachannel/src/polyfill/RTCSessionDescription.ts +0 -41
- package/node_modules/node-datachannel/src/polyfill/index.ts +0 -38
- package/node_modules/node-datachannel/tsconfig.json +0 -21
- package/node_modules/p-limit/index.d.ts +0 -38
- package/node_modules/p-limit/index.js +0 -57
- package/node_modules/p-limit/license +0 -9
- package/node_modules/p-limit/package.json +0 -52
- package/node_modules/p-limit/readme.md +0 -101
- package/node_modules/p-locate/index.d.ts +0 -64
- package/node_modules/p-locate/index.js +0 -52
- package/node_modules/p-locate/license +0 -9
- package/node_modules/p-locate/package.json +0 -53
- package/node_modules/p-locate/readme.md +0 -90
- package/node_modules/p-try/index.d.ts +0 -39
- package/node_modules/p-try/index.js +0 -9
- package/node_modules/p-try/license +0 -9
- package/node_modules/p-try/package.json +0 -42
- package/node_modules/p-try/readme.md +0 -58
- package/node_modules/path-exists/index.d.ts +0 -28
- package/node_modules/path-exists/index.js +0 -23
- package/node_modules/path-exists/license +0 -9
- package/node_modules/path-exists/package.json +0 -39
- package/node_modules/path-exists/readme.md +0 -52
- package/node_modules/pngjs/.eslintignore +0 -2
- package/node_modules/pngjs/.eslintrc.json +0 -19
- package/node_modules/pngjs/.prettierignore +0 -3
- package/node_modules/pngjs/LICENSE +0 -20
- package/node_modules/pngjs/README.md +0 -429
- package/node_modules/pngjs/browser.js +0 -16096
- package/node_modules/pngjs/coverage/lcov-report/base.css +0 -354
- package/node_modules/pngjs/coverage/lcov-report/bitmapper.js.html +0 -881
- package/node_modules/pngjs/coverage/lcov-report/bitpacker.js.html +0 -554
- package/node_modules/pngjs/coverage/lcov-report/block-navigation.js +0 -77
- package/node_modules/pngjs/coverage/lcov-report/chunkstream.js.html +0 -647
- package/node_modules/pngjs/coverage/lcov-report/constants.js.html +0 -176
- package/node_modules/pngjs/coverage/lcov-report/crc.js.html +0 -200
- package/node_modules/pngjs/coverage/lcov-report/favicon.png +0 -0
- package/node_modules/pngjs/coverage/lcov-report/filter-pack.js.html +0 -593
- package/node_modules/pngjs/coverage/lcov-report/filter-parse-async.js.html +0 -152
- package/node_modules/pngjs/coverage/lcov-report/filter-parse-sync.js.html +0 -143
- package/node_modules/pngjs/coverage/lcov-report/filter-parse.js.html +0 -611
- package/node_modules/pngjs/coverage/lcov-report/format-normaliser.js.html +0 -359
- package/node_modules/pngjs/coverage/lcov-report/index.html +0 -426
- package/node_modules/pngjs/coverage/lcov-report/interlace.js.html +0 -365
- package/node_modules/pngjs/coverage/lcov-report/packer-async.js.html +0 -230
- package/node_modules/pngjs/coverage/lcov-report/packer-sync.js.html +0 -248
- package/node_modules/pngjs/coverage/lcov-report/packer.js.html +0 -467
- package/node_modules/pngjs/coverage/lcov-report/paeth-predictor.js.html +0 -128
- package/node_modules/pngjs/coverage/lcov-report/parser-async.js.html +0 -575
- package/node_modules/pngjs/coverage/lcov-report/parser-sync.js.html +0 -404
- package/node_modules/pngjs/coverage/lcov-report/parser.js.html +0 -950
- package/node_modules/pngjs/coverage/lcov-report/png-sync.js.html +0 -116
- package/node_modules/pngjs/coverage/lcov-report/png.js.html +0 -662
- package/node_modules/pngjs/coverage/lcov-report/prettify.css +0 -101
- package/node_modules/pngjs/coverage/lcov-report/prettify.js +0 -1007
- package/node_modules/pngjs/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/node_modules/pngjs/coverage/lcov-report/sorter.js +0 -169
- package/node_modules/pngjs/coverage/lcov-report/sync-inflate.js.html +0 -584
- package/node_modules/pngjs/coverage/lcov-report/sync-reader.js.html +0 -215
- package/node_modules/pngjs/coverage/lcov.info +0 -2177
- package/node_modules/pngjs/lib/bitmapper.js +0 -267
- package/node_modules/pngjs/lib/bitpacker.js +0 -158
- package/node_modules/pngjs/lib/chunkstream.js +0 -189
- package/node_modules/pngjs/lib/constants.js +0 -32
- package/node_modules/pngjs/lib/crc.js +0 -40
- package/node_modules/pngjs/lib/filter-pack.js +0 -171
- package/node_modules/pngjs/lib/filter-parse-async.js +0 -24
- package/node_modules/pngjs/lib/filter-parse-sync.js +0 -21
- package/node_modules/pngjs/lib/filter-parse.js +0 -177
- package/node_modules/pngjs/lib/format-normaliser.js +0 -93
- package/node_modules/pngjs/lib/interlace.js +0 -95
- package/node_modules/pngjs/lib/packer-async.js +0 -50
- package/node_modules/pngjs/lib/packer-sync.js +0 -56
- package/node_modules/pngjs/lib/packer.js +0 -129
- package/node_modules/pngjs/lib/paeth-predictor.js +0 -16
- package/node_modules/pngjs/lib/parser-async.js +0 -165
- package/node_modules/pngjs/lib/parser-sync.js +0 -108
- package/node_modules/pngjs/lib/parser.js +0 -290
- package/node_modules/pngjs/lib/png-sync.js +0 -12
- package/node_modules/pngjs/lib/png.js +0 -194
- package/node_modules/pngjs/lib/sync-inflate.js +0 -168
- package/node_modules/pngjs/lib/sync-reader.js +0 -45
- package/node_modules/pngjs/package.json +0 -73
- package/node_modules/qrcode/README.md +0 -770
- package/node_modules/qrcode/bin/qrcode +0 -159
- package/node_modules/qrcode/helper/to-sjis-browser.js +0 -2
- package/node_modules/qrcode/helper/to-sjis.js +0 -105
- package/node_modules/qrcode/lib/browser.js +0 -76
- package/node_modules/qrcode/lib/can-promise.js +0 -7
- package/node_modules/qrcode/lib/core/alignment-pattern.js +0 -83
- package/node_modules/qrcode/lib/core/alphanumeric-data.js +0 -59
- package/node_modules/qrcode/lib/core/bit-buffer.js +0 -37
- package/node_modules/qrcode/lib/core/bit-matrix.js +0 -65
- package/node_modules/qrcode/lib/core/byte-data.js +0 -30
- package/node_modules/qrcode/lib/core/error-correction-code.js +0 -135
- package/node_modules/qrcode/lib/core/error-correction-level.js +0 -50
- package/node_modules/qrcode/lib/core/finder-pattern.js +0 -22
- package/node_modules/qrcode/lib/core/format-info.js +0 -29
- package/node_modules/qrcode/lib/core/galois-field.js +0 -69
- package/node_modules/qrcode/lib/core/kanji-data.js +0 -54
- package/node_modules/qrcode/lib/core/mask-pattern.js +0 -234
- package/node_modules/qrcode/lib/core/mode.js +0 -167
- package/node_modules/qrcode/lib/core/numeric-data.js +0 -43
- package/node_modules/qrcode/lib/core/polynomial.js +0 -62
- package/node_modules/qrcode/lib/core/qrcode.js +0 -495
- package/node_modules/qrcode/lib/core/reed-solomon-encoder.js +0 -56
- package/node_modules/qrcode/lib/core/regex.js +0 -31
- package/node_modules/qrcode/lib/core/segments.js +0 -330
- package/node_modules/qrcode/lib/core/utils.js +0 -63
- package/node_modules/qrcode/lib/core/version-check.js +0 -9
- package/node_modules/qrcode/lib/core/version.js +0 -163
- package/node_modules/qrcode/lib/index.js +0 -12
- package/node_modules/qrcode/lib/renderer/canvas.js +0 -63
- package/node_modules/qrcode/lib/renderer/png.js +0 -78
- package/node_modules/qrcode/lib/renderer/svg-tag.js +0 -81
- package/node_modules/qrcode/lib/renderer/svg.js +0 -19
- package/node_modules/qrcode/lib/renderer/terminal/terminal-small.js +0 -85
- package/node_modules/qrcode/lib/renderer/terminal/terminal.js +0 -49
- package/node_modules/qrcode/lib/renderer/terminal.js +0 -9
- package/node_modules/qrcode/lib/renderer/utf8.js +0 -71
- package/node_modules/qrcode/lib/renderer/utils.js +0 -99
- package/node_modules/qrcode/lib/server.js +0 -138
- package/node_modules/qrcode/license +0 -10
- package/node_modules/qrcode/package.json +0 -77
- package/node_modules/require-directory/.jshintrc +0 -67
- package/node_modules/require-directory/.npmignore +0 -1
- package/node_modules/require-directory/.travis.yml +0 -3
- package/node_modules/require-directory/LICENSE +0 -22
- package/node_modules/require-directory/README.markdown +0 -184
- package/node_modules/require-directory/index.js +0 -86
- package/node_modules/require-directory/package.json +0 -40
- package/node_modules/require-main-filename/CHANGELOG.md +0 -26
- package/node_modules/require-main-filename/LICENSE.txt +0 -14
- package/node_modules/require-main-filename/README.md +0 -26
- package/node_modules/require-main-filename/index.js +0 -18
- package/node_modules/require-main-filename/package.json +0 -35
- package/node_modules/semver/LICENSE +0 -15
- package/node_modules/semver/README.md +0 -680
- package/node_modules/semver/bin/semver.js +0 -195
- package/node_modules/semver/classes/comparator.js +0 -143
- package/node_modules/semver/classes/index.js +0 -7
- package/node_modules/semver/classes/range.js +0 -577
- package/node_modules/semver/classes/semver.js +0 -350
- package/node_modules/semver/functions/clean.js +0 -8
- package/node_modules/semver/functions/cmp.js +0 -54
- package/node_modules/semver/functions/coerce.js +0 -62
- package/node_modules/semver/functions/compare-build.js +0 -9
- package/node_modules/semver/functions/compare-loose.js +0 -5
- package/node_modules/semver/functions/compare.js +0 -7
- package/node_modules/semver/functions/diff.js +0 -60
- package/node_modules/semver/functions/eq.js +0 -5
- package/node_modules/semver/functions/gt.js +0 -5
- package/node_modules/semver/functions/gte.js +0 -5
- package/node_modules/semver/functions/inc.js +0 -21
- package/node_modules/semver/functions/lt.js +0 -5
- package/node_modules/semver/functions/lte.js +0 -5
- package/node_modules/semver/functions/major.js +0 -5
- package/node_modules/semver/functions/minor.js +0 -5
- package/node_modules/semver/functions/neq.js +0 -5
- package/node_modules/semver/functions/parse.js +0 -18
- package/node_modules/semver/functions/patch.js +0 -5
- package/node_modules/semver/functions/prerelease.js +0 -8
- package/node_modules/semver/functions/rcompare.js +0 -5
- package/node_modules/semver/functions/rsort.js +0 -5
- package/node_modules/semver/functions/satisfies.js +0 -12
- package/node_modules/semver/functions/sort.js +0 -5
- package/node_modules/semver/functions/truncate.js +0 -48
- package/node_modules/semver/functions/valid.js +0 -8
- package/node_modules/semver/index.js +0 -93
- package/node_modules/semver/internal/constants.js +0 -37
- package/node_modules/semver/internal/debug.js +0 -11
- package/node_modules/semver/internal/identifiers.js +0 -29
- package/node_modules/semver/internal/lrucache.js +0 -42
- package/node_modules/semver/internal/parse-options.js +0 -17
- package/node_modules/semver/internal/re.js +0 -223
- package/node_modules/semver/package.json +0 -78
- package/node_modules/semver/preload.js +0 -4
- package/node_modules/semver/range.bnf +0 -17
- package/node_modules/semver/ranges/gtr.js +0 -6
- package/node_modules/semver/ranges/intersects.js +0 -9
- package/node_modules/semver/ranges/ltr.js +0 -6
- package/node_modules/semver/ranges/max-satisfying.js +0 -27
- package/node_modules/semver/ranges/min-satisfying.js +0 -26
- package/node_modules/semver/ranges/min-version.js +0 -63
- package/node_modules/semver/ranges/outside.js +0 -82
- package/node_modules/semver/ranges/simplify.js +0 -49
- package/node_modules/semver/ranges/subset.js +0 -249
- package/node_modules/semver/ranges/to-comparators.js +0 -10
- package/node_modules/semver/ranges/valid.js +0 -13
- package/node_modules/set-blocking/CHANGELOG.md +0 -26
- package/node_modules/set-blocking/LICENSE.txt +0 -14
- package/node_modules/set-blocking/README.md +0 -31
- package/node_modules/set-blocking/index.js +0 -7
- package/node_modules/set-blocking/package.json +0 -42
- package/node_modules/sharp/LICENSE +0 -191
- package/node_modules/sharp/README.md +0 -112
- package/node_modules/sharp/dist/channel.cjs +0 -177
- package/node_modules/sharp/dist/channel.mjs +0 -177
- package/node_modules/sharp/dist/colour.cjs +0 -199
- package/node_modules/sharp/dist/colour.mjs +0 -199
- package/node_modules/sharp/dist/composite.cjs +0 -213
- package/node_modules/sharp/dist/composite.mjs +0 -213
- package/node_modules/sharp/dist/constructor.cjs +0 -511
- package/node_modules/sharp/dist/constructor.mjs +0 -511
- package/node_modules/sharp/dist/index.cjs +0 -25
- package/node_modules/sharp/dist/index.d.cts +0 -1999
- package/node_modules/sharp/dist/index.d.mts +0 -2046
- package/node_modules/sharp/dist/index.mjs +0 -25
- package/node_modules/sharp/dist/input.cjs +0 -819
- package/node_modules/sharp/dist/input.mjs +0 -819
- package/node_modules/sharp/dist/is.cjs +0 -143
- package/node_modules/sharp/dist/is.mjs +0 -143
- package/node_modules/sharp/dist/libvips.cjs +0 -212
- package/node_modules/sharp/dist/libvips.mjs +0 -212
- package/node_modules/sharp/dist/operation.cjs +0 -1002
- package/node_modules/sharp/dist/operation.mjs +0 -1002
- package/node_modules/sharp/dist/output.cjs +0 -1785
- package/node_modules/sharp/dist/output.mjs +0 -1785
- package/node_modules/sharp/dist/resize.cjs +0 -617
- package/node_modules/sharp/dist/resize.mjs +0 -617
- package/node_modules/sharp/dist/sharp.cjs +0 -174
- package/node_modules/sharp/dist/sharp.mjs +0 -174
- package/node_modules/sharp/dist/utility.cjs +0 -301
- package/node_modules/sharp/dist/utility.mjs +0 -301
- package/node_modules/sharp/install/build.js +0 -38
- package/node_modules/sharp/lib/index.d.ts +0 -1999
- package/node_modules/sharp/package.json +0 -227
- package/node_modules/sharp/src/binding.gyp +0 -303
- package/node_modules/sharp/src/common.cc +0 -1186
- package/node_modules/sharp/src/common.h +0 -421
- package/node_modules/sharp/src/metadata.cc +0 -404
- package/node_modules/sharp/src/metadata.h +0 -95
- package/node_modules/sharp/src/operations.cc +0 -516
- package/node_modules/sharp/src/operations.h +0 -137
- package/node_modules/sharp/src/pipeline.cc +0 -1948
- package/node_modules/sharp/src/pipeline.h +0 -422
- package/node_modules/sharp/src/sharp.cc +0 -43
- package/node_modules/sharp/src/stats.cc +0 -186
- package/node_modules/sharp/src/stats.h +0 -62
- package/node_modules/sharp/src/utilities.cc +0 -289
- package/node_modules/sharp/src/utilities.h +0 -22
- package/node_modules/string-width/index.d.ts +0 -29
- package/node_modules/string-width/index.js +0 -47
- package/node_modules/string-width/license +0 -9
- package/node_modules/string-width/package.json +0 -56
- package/node_modules/string-width/readme.md +0 -50
- package/node_modules/strip-ansi/index.d.ts +0 -17
- package/node_modules/strip-ansi/index.js +0 -4
- package/node_modules/strip-ansi/license +0 -9
- package/node_modules/strip-ansi/package.json +0 -54
- package/node_modules/strip-ansi/readme.md +0 -46
- package/node_modules/which-module/LICENSE +0 -13
- package/node_modules/which-module/README.md +0 -58
- package/node_modules/which-module/index.js +0 -9
- package/node_modules/which-module/package.json +0 -41
- package/node_modules/wrap-ansi/index.js +0 -186
- package/node_modules/wrap-ansi/license +0 -9
- package/node_modules/wrap-ansi/package.json +0 -61
- package/node_modules/wrap-ansi/readme.md +0 -97
- package/node_modules/ws/LICENSE +0 -20
- package/node_modules/ws/README.md +0 -548
- package/node_modules/ws/browser.js +0 -8
- package/node_modules/ws/index.js +0 -22
- package/node_modules/ws/lib/buffer-util.js +0 -131
- package/node_modules/ws/lib/constants.js +0 -19
- package/node_modules/ws/lib/event-target.js +0 -292
- package/node_modules/ws/lib/extension.js +0 -203
- package/node_modules/ws/lib/limiter.js +0 -55
- package/node_modules/ws/lib/permessage-deflate.js +0 -530
- package/node_modules/ws/lib/receiver.js +0 -743
- package/node_modules/ws/lib/sender.js +0 -607
- package/node_modules/ws/lib/stream.js +0 -161
- package/node_modules/ws/lib/subprotocol.js +0 -62
- package/node_modules/ws/lib/validation.js +0 -152
- package/node_modules/ws/lib/websocket-server.js +0 -562
- package/node_modules/ws/lib/websocket.js +0 -1407
- package/node_modules/ws/package.json +0 -74
- package/node_modules/ws/wrapper.mjs +0 -21
- package/node_modules/y18n/CHANGELOG.md +0 -35
- package/node_modules/y18n/LICENSE +0 -13
- package/node_modules/y18n/README.md +0 -109
- package/node_modules/y18n/index.js +0 -188
- package/node_modules/y18n/package.json +0 -39
- package/node_modules/yargs/CHANGELOG.md +0 -420
- package/node_modules/yargs/LICENSE +0 -21
- package/node_modules/yargs/README.md +0 -140
- package/node_modules/yargs/build/lib/apply-extends.d.ts +0 -2
- package/node_modules/yargs/build/lib/apply-extends.js +0 -65
- package/node_modules/yargs/build/lib/argsert.d.ts +0 -2
- package/node_modules/yargs/build/lib/argsert.js +0 -65
- package/node_modules/yargs/build/lib/command.d.ts +0 -64
- package/node_modules/yargs/build/lib/command.js +0 -416
- package/node_modules/yargs/build/lib/common-types.d.ts +0 -36
- package/node_modules/yargs/build/lib/common-types.js +0 -25
- package/node_modules/yargs/build/lib/completion-templates.d.ts +0 -2
- package/node_modules/yargs/build/lib/completion-templates.js +0 -50
- package/node_modules/yargs/build/lib/completion.d.ts +0 -21
- package/node_modules/yargs/build/lib/completion.js +0 -135
- package/node_modules/yargs/build/lib/is-promise.d.ts +0 -1
- package/node_modules/yargs/build/lib/is-promise.js +0 -9
- package/node_modules/yargs/build/lib/levenshtein.d.ts +0 -1
- package/node_modules/yargs/build/lib/levenshtein.js +0 -58
- package/node_modules/yargs/build/lib/middleware.d.ts +0 -10
- package/node_modules/yargs/build/lib/middleware.js +0 -57
- package/node_modules/yargs/build/lib/obj-filter.d.ts +0 -1
- package/node_modules/yargs/build/lib/obj-filter.js +0 -14
- package/node_modules/yargs/build/lib/parse-command.d.ts +0 -11
- package/node_modules/yargs/build/lib/parse-command.js +0 -36
- package/node_modules/yargs/build/lib/process-argv.d.ts +0 -2
- package/node_modules/yargs/build/lib/process-argv.js +0 -31
- package/node_modules/yargs/build/lib/usage.d.ts +0 -49
- package/node_modules/yargs/build/lib/usage.js +0 -540
- package/node_modules/yargs/build/lib/validation.d.ts +0 -34
- package/node_modules/yargs/build/lib/validation.js +0 -330
- package/node_modules/yargs/build/lib/yargs.d.ts +0 -274
- package/node_modules/yargs/build/lib/yargs.js +0 -1190
- package/node_modules/yargs/build/lib/yerror.d.ts +0 -4
- package/node_modules/yargs/build/lib/yerror.js +0 -11
- package/node_modules/yargs/index.js +0 -40
- package/node_modules/yargs/locales/be.json +0 -46
- package/node_modules/yargs/locales/de.json +0 -46
- package/node_modules/yargs/locales/en.json +0 -51
- package/node_modules/yargs/locales/es.json +0 -46
- package/node_modules/yargs/locales/fi.json +0 -49
- package/node_modules/yargs/locales/fr.json +0 -53
- package/node_modules/yargs/locales/hi.json +0 -49
- package/node_modules/yargs/locales/hu.json +0 -46
- package/node_modules/yargs/locales/id.json +0 -50
- package/node_modules/yargs/locales/it.json +0 -46
- package/node_modules/yargs/locales/ja.json +0 -51
- package/node_modules/yargs/locales/ko.json +0 -49
- package/node_modules/yargs/locales/nb.json +0 -44
- package/node_modules/yargs/locales/nl.json +0 -49
- package/node_modules/yargs/locales/nn.json +0 -44
- package/node_modules/yargs/locales/pirate.json +0 -13
- package/node_modules/yargs/locales/pl.json +0 -49
- package/node_modules/yargs/locales/pt.json +0 -45
- package/node_modules/yargs/locales/pt_BR.json +0 -48
- package/node_modules/yargs/locales/ru.json +0 -46
- package/node_modules/yargs/locales/th.json +0 -46
- package/node_modules/yargs/locales/tr.json +0 -48
- package/node_modules/yargs/locales/zh_CN.json +0 -48
- package/node_modules/yargs/locales/zh_TW.json +0 -47
- package/node_modules/yargs/package.json +0 -92
- package/node_modules/yargs/yargs.js +0 -14
- package/node_modules/yargs-parser/CHANGELOG.md +0 -601
- package/node_modules/yargs-parser/LICENSE.txt +0 -14
- package/node_modules/yargs-parser/README.md +0 -449
- package/node_modules/yargs-parser/index.js +0 -1032
- package/node_modules/yargs-parser/lib/tokenize-arg-string.js +0 -40
- package/node_modules/yargs-parser/package.json +0 -46
package/dist/src/server.mjs
CHANGED
|
@@ -1,61 +1,83 @@
|
|
|
1
|
-
import crypto from 'node:crypto';
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { RustDeskVideoProbe } from './platform/windows/rustdesk-video-probe.mjs';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import http from 'node:http';
|
|
5
|
+
import { createPowerManager } from './service-power.mjs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
8
9
|
import vm from 'node:vm';
|
|
9
10
|
import sharp from 'sharp';
|
|
10
|
-
import { attachLanSocket } from './lan-socket-server.mjs';
|
|
11
|
-
import {
|
|
11
|
+
import { attachLanSocket } from './lan-socket-server.mjs';
|
|
12
|
+
import { connectionReporting } from './self-relay/connection-reporting.mjs';
|
|
13
|
+
import fileMentions from '../shared/file-mentions.cjs';
|
|
14
|
+
import fileCitations from '../shared/file-citations.cjs';
|
|
15
|
+
import { validateInlineImage } from './message-images.mjs';
|
|
12
16
|
import { ThreadWriterConflictError } from './shared-app-server.mjs';
|
|
13
|
-
import { ManagedAppServer
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import
|
|
17
|
-
import
|
|
18
|
-
import
|
|
19
|
-
import
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import { authorizeLanDevice } from './self-relay/lan-authorizations.mjs';
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import { desktopHost } from './platform/
|
|
28
|
-
import { SharedCatalog } from './shared-catalog.mjs';
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
17
|
+
import { ManagedAppServer } from './managed-app-server.mjs';
|
|
18
|
+
import { RuntimeDiscovery } from './runtime-discovery.mjs';
|
|
19
|
+
import { streamSharedThread, threadListNotificationMethods } from './shared-thread-stream.mjs';
|
|
20
|
+
import appServerEvents from '../shared/app-server-events.cjs';
|
|
21
|
+
import questionAttention from '../shared/question-attention.cjs';
|
|
22
|
+
import messageDelivery from '../shared/message-delivery.cjs';
|
|
23
|
+
import fileChanges from '../shared/file-changes.cjs';
|
|
24
|
+
import { runtimePaths } from './platform/runtime-paths.mjs';
|
|
25
|
+
import { openControl } from './service-control.mjs';
|
|
26
|
+
import { writeRecord, readRecord } from './service-lifecycle.mjs';
|
|
27
|
+
import { ExecutionHealth } from './execution-health.mjs';
|
|
28
|
+
import { authorizeLanDevice, onLanAuthorizationsChanged, recordLanConnection } from './self-relay/lan-authorizations.mjs';
|
|
29
|
+
import { createRelayManager } from './self-relay/lifecycle.mjs';
|
|
30
|
+
import { generateAndSetThreadTitle } from './thread-title-generation.mjs';
|
|
31
|
+
import { desktopHost } from './platform/desktop-host.mjs';
|
|
32
|
+
import { SharedCatalog } from './shared-catalog.mjs';
|
|
33
|
+
import { DotsAppServer } from './dots-task-catalog.mjs';
|
|
34
|
+
import { DotsChatServer } from './dots-chat-server.mjs';
|
|
35
|
+
import { HostedHistoryCache } from './hosted-history-cache.mjs';
|
|
36
|
+
import { readDotsSummaryTasks } from './dots-summary-tasks.mjs';
|
|
37
|
+
import { readDotsSchedules } from './dots-schedules.mjs';
|
|
38
|
+
import { DotsMessageImages } from './dots-message-images.mjs';
|
|
39
|
+
import { desktopDotsProfiles } from './platform/windows/dots-profile.mjs';
|
|
40
|
+
import { readPlanPricing } from './plan-pricing.mjs';
|
|
41
|
+
import { requestRecovery, recoveryStatus } from './shared-recovery.mjs';
|
|
42
|
+
import { startDesktop } from './desktop-launcher.mjs';
|
|
43
|
+
import { requestServiceRestart } from './service-restart.mjs';
|
|
44
|
+
import { checkServiceUpdate, requestServiceUpdate, serviceUpdateStatus } from './service-update.mjs';
|
|
45
|
+
import { TurnModelHistory } from './turn-model-history.mjs';
|
|
46
|
+
import { browseCode } from './code-browser.mjs';
|
|
47
|
+
import { fileRange, fileRevision, FileRangeError } from './file-transfer-range.mjs';
|
|
48
|
+
import { browseProjectFolders, createProjectFolder } from './project-management.mjs';
|
|
49
|
+
import { projectLocations } from './platform/project-locations.mjs';
|
|
50
|
+
import { createWorkstationProject } from './project-create.mjs';
|
|
51
|
+
import { removeWorkstationProject } from './project-remove.mjs';
|
|
52
|
+
import { archivedThreadsPage } from './archived-threads.mjs';
|
|
53
|
+
import { updateWorkstationProject } from './project-update.mjs';
|
|
54
|
+
import { WorkstationDownloads } from './workstation-downloads.mjs';
|
|
55
|
+
import { stageWorkstationMessageFile } from './message-upload-files.mjs';
|
|
56
|
+
import { consumeUsageReset } from './usage-reset.mjs';
|
|
57
|
+
import { DesktopHelper } from './platform/windows/desktop-helper.mjs';
|
|
58
|
+
|
|
59
|
+
const turnModelHistory = new TurnModelHistory();
|
|
60
|
+
const messageReceipts = new messageDelivery.Store();
|
|
61
|
+
const desktopHelper = process.platform === 'win32' ? new DesktopHelper() : null;
|
|
62
|
+
|
|
63
|
+
const MAX_IMAGE_PREVIEW_BYTES = 20 * 1024 * 1024;
|
|
64
|
+
const MAX_CACHED_ATTACHMENTS = 32;
|
|
65
|
+
const MAX_CACHED_FILES = 64;
|
|
66
|
+
const MAX_CONTEXT_TAIL_BYTES = 4 * 1024 * 1024;
|
|
37
67
|
const MAX_LIVE_ACTIVITY_TAIL_BYTES = 1024 * 1024;
|
|
38
68
|
const SHARED_HISTORY_PAGE_BYTES = 500 * 1024;
|
|
39
69
|
const SHARED_HISTORY_PAGE_TURNS = 8;
|
|
40
|
-
const MAX_SETTINGS_SCAN_BYTES = 64 * 1024 * 1024;
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
'create_thread',
|
|
52
|
-
'get_usage_limits',
|
|
53
|
-
'list_projects',
|
|
54
|
-
'list_threads',
|
|
55
|
-
'read_thread',
|
|
56
|
-
'send_message_to_thread',
|
|
57
|
-
'wait_threads',
|
|
58
|
-
]);
|
|
70
|
+
const MAX_SETTINGS_SCAN_BYTES = 64 * 1024 * 1024;
|
|
71
|
+
const ALLOWED_THINKING = new Set(['low', 'medium', 'high', 'xhigh', 'max', 'ultra']);
|
|
72
|
+
|
|
73
|
+
class RequestError extends Error {
|
|
74
|
+
constructor(statusCode, message, details) {
|
|
75
|
+
super(message);
|
|
76
|
+
this.statusCode = statusCode;
|
|
77
|
+
this.details = details;
|
|
78
|
+
this.code = details?.code;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
59
81
|
|
|
60
82
|
function readRuntimeVersion() {
|
|
61
83
|
let directory = path.dirname(fileURLToPath(import.meta.url));
|
|
@@ -70,129 +92,226 @@ function readRuntimeVersion() {
|
|
|
70
92
|
|
|
71
93
|
const options = parseOptions(process.argv.slice(2));
|
|
72
94
|
const runtimeVersion = readRuntimeVersion();
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
const
|
|
84
|
-
|
|
95
|
+
const serviceInstanceId = crypto.randomUUID();
|
|
96
|
+
|
|
97
|
+
function runtimeDiagnostic(event, details) {
|
|
98
|
+
console.log('[CodeRelax:runtime]', JSON.stringify({ at: new Date().toISOString(),
|
|
99
|
+
serviceVersion: runtimeVersion, servicePid: process.pid, serviceInstanceId, event, ...details }));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const webRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'web');
|
|
103
|
+
const projectRoot = os.homedir();
|
|
104
|
+
const { codexDataRoot, stateRoot, sessionsRoot, uploadsRoot } = runtimePaths();
|
|
105
|
+
const desktopVideoProbe = process.platform === 'win32' ? new RustDeskVideoProbe({ stateRoot }) : null;
|
|
106
|
+
process.once('exit', () => desktopVideoProbe?.stop());
|
|
107
|
+
const workstationDownloads = new WorkstationDownloads(stateRoot);
|
|
108
|
+
const markdownItScript = fs.readFileSync(path.join(webRoot, 'vendor', 'markdown-it.umd.min.js'));
|
|
109
|
+
const markdownSandbox = { atob };
|
|
110
|
+
vm.runInNewContext(markdownItScript.toString(), markdownSandbox);
|
|
111
|
+
const imageMarkdown = markdownSandbox.markdownit({ html: false });
|
|
112
|
+
fileCitations.install(imageMarkdown);
|
|
85
113
|
const attachmentCache = new Map();
|
|
86
114
|
const fileCache = new Map();
|
|
87
115
|
const fileCapabilitySecret = crypto.randomBytes(32);
|
|
88
116
|
const imageCapabilityKey = crypto.createHash('sha256')
|
|
89
117
|
.update('code-relax-image-capability\0').update(options.token || fileCapabilitySecret).digest();
|
|
90
|
-
const
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
const sessionPathCache = new Map();
|
|
94
|
-
const sessionSettingsCache = new Map();
|
|
95
|
-
const liveActivityCache = new Map();
|
|
96
|
-
const messageQueues = new Map();
|
|
118
|
+
const sessionPathCache = new Map();
|
|
119
|
+
const sessionSettingsCache = new Map();
|
|
120
|
+
const liveActivityCache = new Map();
|
|
97
121
|
let sharedServer = null;
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
});
|
|
101
|
-
const
|
|
122
|
+
const managedAppServer = new ManagedAppServer({ stateRoot, host: desktopHost, diagnose: runtimeDiagnostic });
|
|
123
|
+
const hostedHistoryCache = new HostedHistoryCache(stateRoot);
|
|
124
|
+
const dotsServer = new DotsAppServer(managedAppServer.client, desktopDotsProfiles(codexDataRoot, stateRoot), hostedHistoryCache, { uploadsRoot });
|
|
125
|
+
const dotsImages = new DotsMessageImages({ localServer: managedAppServer.client, identity: () => dotsServer.profileIdentity,
|
|
126
|
+
cache: attachmentCache, capabilityKey: imageCapabilityKey, maxEntries: MAX_CACHED_ATTACHMENTS, maxBytes: MAX_IMAGE_PREVIEW_BYTES });
|
|
127
|
+
const dotsChat = new DotsChatServer(dotsServer, undefined, { uploadsRoot });
|
|
128
|
+
managedAppServer.on('state', state => { if (state.ready) dotsChat.startBackgroundActivity(); });
|
|
129
|
+
const runtimeDiscovery = new RuntimeDiscovery({ stateRoot, host: desktopHost,
|
|
130
|
+
url: () => managedAppServer.snapshot().url, diagnose: runtimeDiagnostic });
|
|
131
|
+
const relayManager = createRelayManager(stateRoot);
|
|
102
132
|
let sharedCatalog = null, executionMode = 'ordinary';
|
|
103
133
|
function selectSharedExecution(enabled) {
|
|
104
134
|
const next = enabled ? managedAppServer.client : null;
|
|
105
135
|
if (sharedServer === next) return;
|
|
106
136
|
sharedServer = next;
|
|
107
|
-
sharedCatalog = sharedServer ? new SharedCatalog(sharedServer) : null;
|
|
137
|
+
sharedCatalog = sharedServer ? new SharedCatalog(sharedServer, dotsServer, dotsChat) : null;
|
|
108
138
|
}
|
|
109
139
|
const executionHealth = new ExecutionHealth(async () => {
|
|
110
140
|
await managedAppServer.ensure();
|
|
111
|
-
const [desktop, attachedUrl] = await Promise.all([desktopHost.inspect(), desktopHost.sharedServiceUrl()]);
|
|
112
|
-
const attached = Boolean(desktop.running && attachedUrl === managedAppServerUrl);
|
|
113
141
|
const managed = managedAppServer.snapshot();
|
|
114
142
|
// The managed app-server owns execution. Desktop is another client of the
|
|
115
143
|
// same service, so closing Desktop must not disable phone writes.
|
|
116
144
|
selectSharedExecution(managed.ready);
|
|
117
145
|
executionMode = sharedServer ? 'shared' : 'ordinary';
|
|
118
|
-
const basicReady = Boolean(desktop.running && sourceThreadId && desktopMonitor.pipe);
|
|
119
146
|
const managedRestarting = managed.state === 'restarting';
|
|
120
|
-
const ready = !managedRestarting &&
|
|
147
|
+
const ready = !managedRestarting && sharedServer?.ready === true;
|
|
121
148
|
const state = managedRestarting ? 'restarting'
|
|
122
|
-
: ready ?
|
|
123
|
-
return { state, ready, canWrite: ready, mode: executionMode
|
|
124
|
-
desktop: { state: !desktop.running ? 'stopped' : attached ? 'managed' : 'ordinary', attachedToManagedServer: attached } };
|
|
149
|
+
: ready ? 'full' : 'unavailable';
|
|
150
|
+
return { state, ready, canWrite: ready, mode: executionMode };
|
|
125
151
|
});
|
|
152
|
+
function workstationHealth() {
|
|
153
|
+
const executionReady = executionHealth.state.ready && sharedServer?.ready === true;
|
|
154
|
+
return {
|
|
155
|
+
status: 'ok', resident: true, version: runtimeVersion, serviceInstanceId,
|
|
156
|
+
keepAwake: powerManager.snapshot(),
|
|
157
|
+
serviceUpdate: serviceUpdateStatus(stateRoot),
|
|
158
|
+
execution: { ...executionHealth.state, ready: executionReady, canWrite: executionReady,
|
|
159
|
+
mode: executionMode },
|
|
160
|
+
managedAppServer: managedAppServer.snapshot(),
|
|
161
|
+
...runtimeDiscovery.state,
|
|
162
|
+
sharedAppServerConnected: sharedServer?.ready === true,
|
|
163
|
+
sharedRecoveryAvailable: runtimeDiscovery.state.desktop?.installed === true,
|
|
164
|
+
mode: options.lan ? 'lan' : 'loopback',
|
|
165
|
+
tokenRequired: Boolean(options.token),
|
|
166
|
+
nativeImageTransport: sharedServer ? 'shared-app-server' : null,
|
|
167
|
+
transportMode: sharedServer?.ready === true ? 'lan-shared' : 'unavailable',
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
126
171
|
async function refreshExecution() {
|
|
127
|
-
sourceThreadId = readRecord(path.join(stateRoot, 'bridge-startup-context.json'))?.sourceThreadId || sourceThreadId;
|
|
128
172
|
await executionHealth.refresh();
|
|
129
173
|
return { mode: executionMode };
|
|
130
174
|
}
|
|
131
|
-
async function requireExecutionWritable(threadId) {
|
|
132
|
-
const recovery = readRecord(path.join(stateRoot, 'shared-recovery.json'));
|
|
133
|
-
if (['scheduled', 'running'].includes(recovery?.status)) {
|
|
134
|
-
throw new RequestError(409, 'Codex 正在重新启动,当前不能提交写操作。', { code: 'desktop_recovering' });
|
|
135
|
-
}
|
|
175
|
+
async function requireExecutionWritable(threadId, client = sharedServer) {
|
|
136
176
|
const execution = await executionHealth.refresh();
|
|
137
177
|
if (!execution.canWrite) {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
: 'Codex Desktop 尚未建立基础控制连接,请稍后重新检测。';
|
|
141
|
-
throw new RequestError(409, message, { code: 'execution_not_writable', execution });
|
|
178
|
+
throw new RequestError(503, 'Codex 内核未就绪。请重启工作站服务;若仍失败,运行 relax doctor。',
|
|
179
|
+
{ code: 'full_control_required', execution });
|
|
142
180
|
}
|
|
143
|
-
if (threadId &&
|
|
181
|
+
if (threadId && client) client.requireWritable(threadId);
|
|
144
182
|
return execution;
|
|
145
183
|
}
|
|
146
|
-
managedAppServer.client.on('subscription-error', error => console.error('
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
if (
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
184
|
+
managedAppServer.client.on('subscription-error', error => console.error('Codex 内核任务取消订阅失败:', error.message));
|
|
185
|
+
dotsServer.on('subscription-error', error => console.error('Dots 任务取消订阅失败:', error.message));
|
|
186
|
+
dotsChat.on('subscription-error', error => console.error('Dots 对话取消订阅失败:', error.message));
|
|
187
|
+
dotsChat.on('activity-error', error => console.error('点点状态通道不可用:', error.message));
|
|
188
|
+
|
|
189
|
+
dotsServer.on('profile-error', error => console.error(error.message));
|
|
190
|
+
async function handleRequest(request, response) {
|
|
191
|
+
let messageSubmissionStarted = false;
|
|
192
|
+
try {
|
|
193
|
+
const url = new URL(request.url || '/', `http://${request.headers.host || 'localhost'}`);
|
|
194
|
+
|
|
195
|
+
if (!request.socketRequest) {
|
|
196
|
+
sendJson(response, 404, { error: '此端口不提供网页。' });
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (process.platform !== 'win32' && url.pathname.startsWith('/api/desktop/'))
|
|
201
|
+
throw new RequestError(501, 'Mac 版不提供远程桌面控制。', { code: 'desktop_control_unsupported' });
|
|
202
|
+
|
|
203
|
+
if (url.pathname === '/api/desktop/video-probe') {
|
|
204
|
+
if (request.method === 'POST') {
|
|
205
|
+
try { sendJson(response, 200, await desktopVideoProbe.begin()); }
|
|
206
|
+
catch (error) { throw new RequestError(error.statusCode || 502, error.message, { code: error.code || 'desktop_video_failed' }); }
|
|
207
|
+
}
|
|
208
|
+
else if (request.method === 'PUT' || request.method === 'DELETE') {
|
|
209
|
+
const body = await readJsonBody(request);
|
|
210
|
+
if (typeof body.leaseId !== 'string' || !/^[a-f0-9]{32}$/.test(body.leaseId)) throw new RequestError(400, '无效的视频会话');
|
|
211
|
+
sendJson(response, 200, request.method === 'PUT' ? desktopVideoProbe.renew(body.leaseId) : desktopVideoProbe.release(body.leaseId));
|
|
212
|
+
} else throw new RequestError(405, '不支持的操作');
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (request.method === 'GET' && url.pathname === '/api/desktop/frame') {
|
|
216
|
+
const started = Date.now();
|
|
217
|
+
try {
|
|
218
|
+
const preview = url.searchParams.get('preview') === '1';
|
|
219
|
+
const frame = await desktopHelper.frame({ preview });
|
|
220
|
+
if (!preview) console.info(JSON.stringify({ time: new Date().toISOString(), event: 'desktop-frame', state: frame.state,
|
|
221
|
+
kind: frame.kind, width: frame.width, height: frame.height, bytes: frame.size, ms: Date.now() - started }));
|
|
222
|
+
if (response.writableEnded) { desktopHelper.release(frame.frameId); return; }
|
|
223
|
+
sendJson(response, 200, frame);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
console.error(JSON.stringify({ time: new Date().toISOString(), event: 'desktop-frame', state: 'failed',
|
|
226
|
+
error: error.message.slice(0, 160), ms: Date.now() - started }));
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const desktopImage = /^\/api\/desktop\/frames\/([a-f0-9]{32})$/.exec(url.pathname);
|
|
232
|
+
if (request.method === 'GET' && desktopImage) {
|
|
233
|
+
if (!request.fileTransfer) throw new RequestError(400, '请通过文件通道读取桌面画面。');
|
|
234
|
+
const image = desktopHelper.image(desktopImage[1]);
|
|
235
|
+
const { offset, length } = fileRange(url.searchParams, image.length, desktopImage[1]);
|
|
236
|
+
const mimeType = desktopHelper.active.frame.mimeType;
|
|
237
|
+
response.filePart({ name: mimeType === 'image/jpeg' ? 'desktop.jpg' : 'desktop.png', size: image.length, offset, revision: desktopImage[1], mimeType },
|
|
238
|
+
image.subarray(offset, offset + length));
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (request.method === 'POST' && url.pathname === '/api/desktop/move') {
|
|
242
|
+
try { sendJson(response, 200, await desktopHelper.move(await readJsonBody(request))); }
|
|
243
|
+
catch (error) {
|
|
244
|
+
console.error(JSON.stringify({ time: new Date().toISOString(), event: 'desktop-move', state: 'failed',
|
|
245
|
+
code: error.code, error: error.message.slice(0, 160) }));
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (request.method === 'POST' && url.pathname === '/api/desktop/click') {
|
|
251
|
+
const started = Date.now();
|
|
252
|
+
console.info(JSON.stringify({ time: new Date().toISOString(), event: 'desktop-click', state: 'received' }));
|
|
253
|
+
try {
|
|
254
|
+
const result = await desktopHelper.click(await readJsonBody(request));
|
|
255
|
+
console.info(JSON.stringify({ time: new Date().toISOString(), event: 'desktop-click', state: result.state,
|
|
256
|
+
inputCount: result.inputCount, ms: Date.now() - started }));
|
|
257
|
+
sendJson(response, 200, result);
|
|
258
|
+
} catch (error) {
|
|
259
|
+
console.error(JSON.stringify({ time: new Date().toISOString(), event: 'desktop-click', state: 'failed',
|
|
260
|
+
code: error.code, error: error.message.slice(0, 160), ms: Date.now() - started }));
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (request.method === 'DELETE' && url.pathname === '/api/desktop/frame') {
|
|
266
|
+
const body = await readJsonBody(request);
|
|
267
|
+
if (typeof body.sessionId !== 'string' || !/^[a-f0-9]{32}$/.test(body.sessionId)) throw new RequestError(400, '无效的桌面会话');
|
|
268
|
+
desktopHelper.release(undefined, body.sessionId);
|
|
269
|
+
sendJson(response, 200, { released: true });
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// These routes never wait on Desktop tools or a stuck thread. They remain
|
|
274
|
+
// available to authenticated paired controllers during an app-server stall.
|
|
275
|
+
if (request.method === 'GET' && url.pathname === '/api/shared-recovery/events') {
|
|
276
|
+
response.startEvents();
|
|
277
|
+
let stopped = false, timer, previous = '';
|
|
278
|
+
response.once('close', () => { stopped = true; clearTimeout(timer); });
|
|
279
|
+
const publish = async () => {
|
|
280
|
+
try {
|
|
281
|
+
const state = await recoveryStatus(stateRoot);
|
|
282
|
+
const serialized = JSON.stringify(state);
|
|
283
|
+
if (!stopped && serialized !== previous) { previous = serialized; response.event('progress', state); }
|
|
284
|
+
} catch (error) { if (!stopped) response.event('progress-error', { error: error.message }); }
|
|
285
|
+
if (!stopped) timer = setTimeout(publish, 1000);
|
|
286
|
+
};
|
|
287
|
+
void publish(); return;
|
|
288
|
+
}
|
|
289
|
+
if (request.method === 'GET' && url.pathname === '/api/shared-recovery') {
|
|
290
|
+
sendJson(response, 200, await recoveryStatus(stateRoot)); return;
|
|
291
|
+
}
|
|
292
|
+
if (request.method === 'POST' && ['/api/desktop/start', '/api/desktop/restart'].includes(url.pathname)) {
|
|
293
|
+
const body = await readJsonBody(request);
|
|
294
|
+
if (body.confirmed !== true) throw new RequestError(400, '请确认启动桌面端。');
|
|
295
|
+
let result, observed;
|
|
296
|
+
try { result = await startDesktop({ stateRoot, host: desktopHost, restart: url.pathname === '/api/desktop/restart' }); }
|
|
297
|
+
finally { observed = await runtimeDiscovery.sample(); }
|
|
298
|
+
sendJson(response, 202, { ...result, desktop: observed.desktop, checkedAt: observed.checkedAt }); return;
|
|
299
|
+
}
|
|
300
|
+
if (request.method === 'POST' && url.pathname === '/api/shared-recovery') {
|
|
301
|
+
const body = await readJsonBody(request);
|
|
302
|
+
if (body.confirmed !== true || typeof body.operationId !== 'string') throw new RequestError(400, '请确认重新打开当前 Codex 并接入 Codex 内核后再继续。');
|
|
303
|
+
sendJson(response, 202, await requestRecovery(stateRoot, body)); return;
|
|
304
|
+
}
|
|
305
|
+
if (url.pathname === '/api/service/update' && request.method === 'GET') {
|
|
306
|
+
sendJson(response, 200, await checkServiceUpdate(stateRoot)); return;
|
|
307
|
+
}
|
|
308
|
+
if (url.pathname === '/api/service/update' && request.method === 'POST') {
|
|
309
|
+
sendJson(response, 202, await requestServiceUpdate(stateRoot, await readJsonBody(request))); return;
|
|
310
|
+
}
|
|
192
311
|
if (request.method === 'POST' && url.pathname === '/api/service/restart') {
|
|
193
312
|
const body = await readJsonBody(request);
|
|
194
313
|
if (body.confirmed !== true) throw new RequestError(400, '请确认重启工作站服务后再继续。');
|
|
195
|
-
sendJson(response, 202, await requestServiceRestart(stateRoot)); return;
|
|
314
|
+
sendJson(response, 202, { ...await requestServiceRestart(stateRoot), serviceInstanceId }); return;
|
|
196
315
|
}
|
|
197
316
|
if (request.method === 'POST' && url.pathname === '/api/managed-app-server/restart') {
|
|
198
317
|
const body = await readJsonBody(request);
|
|
@@ -208,42 +327,62 @@ async function handleRequest(request, response) {
|
|
|
208
327
|
return;
|
|
209
328
|
}
|
|
210
329
|
|
|
330
|
+
if (request.method === 'GET' && url.pathname === '/api/official-remote/status') {
|
|
331
|
+
if (!managedAppServer.client.ready) throw new RequestError(503, 'Codex 内核未就绪,无法读取官方工作站状态。');
|
|
332
|
+
const result = await managedAppServer.client.request('remoteControl/status/read', {});
|
|
333
|
+
sendJson(response, 200, { status: result.status, environmentId: result.environmentId });
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
if (request.method === 'POST' && url.pathname === '/api/official-remote/pairing') {
|
|
337
|
+
if (!managedAppServer.client.ready) throw new RequestError(503, 'Codex 内核未就绪,无法生成官方配对码。');
|
|
338
|
+
const status = await managedAppServer.client.request('remoteControl/status/read', {});
|
|
339
|
+
if (status.status !== 'connected') throw new RequestError(409, '当前 Codex 内核未连接 OpenAI Remote,无法配对。');
|
|
340
|
+
const result = await managedAppServer.client.request('remoteControl/pairing/start', { manualCode: true });
|
|
341
|
+
if (!result.manualPairingCode || !result.environmentId) throw new RequestError(502, 'Codex 内核未返回有效的官方配对码。');
|
|
342
|
+
// One-time code: return only to the authenticated station controller; never persist or log it.
|
|
343
|
+
sendJson(response, 200, { manualPairingCode: result.manualPairingCode,
|
|
344
|
+
environmentId: result.environmentId, expiresAt: result.expiresAt });
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
|
|
211
348
|
if (request.method === 'GET' && url.pathname === '/api/health') {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
349
|
+
sendJson(response, 200, workstationHealth()); return;
|
|
350
|
+
}
|
|
351
|
+
if (request.method === 'GET' && url.pathname === '/api/health/events') {
|
|
352
|
+
response.startEvents();
|
|
353
|
+
let previous = '', stopped = false, timer;
|
|
354
|
+
const publish = () => {
|
|
355
|
+
if (stopped) return;
|
|
356
|
+
try {
|
|
357
|
+
const health = workstationHealth();
|
|
358
|
+
// Sampling timestamps alone do not change a workstation's visible state.
|
|
359
|
+
const signature = JSON.stringify(health, (key, value) => key === 'checkedAt' ? undefined : value);
|
|
360
|
+
if (signature !== previous) { previous = signature; response.event('health', health); }
|
|
361
|
+
} catch (error) { previous = ''; response.event('health-error', { error: error.message }); }
|
|
362
|
+
};
|
|
363
|
+
const close = () => { stopped = true; clearInterval(timer); managedAppServer.off('state', publish); };
|
|
364
|
+
response.once('close', close);
|
|
365
|
+
managedAppServer.on('state', publish);
|
|
366
|
+
publish();
|
|
367
|
+
// Reads only existing local samples and operation records, never chat history
|
|
368
|
+
// or an extra Desktop/process probe. Idle snapshots are not sent over the network.
|
|
369
|
+
timer = setInterval(publish, 1000); timer.unref?.();
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const fileLinkMatch = /^\/api\/files\/([a-f0-9]{64})\/link$/.exec(url.pathname);
|
|
374
|
+
if (request.method === 'GET' && fileLinkMatch) {
|
|
375
|
+
const attachment = attachmentCache.get(fileLinkMatch[1])
|
|
376
|
+
|| dotsImages.restore(fileLinkMatch[1], url.searchParams.get('recovery') || '');
|
|
377
|
+
if (!attachment?.dotsFile) throw new RequestError(404, '此附件没有网络链接,请重新读取对话。');
|
|
378
|
+
sendJson(response, 200, { url: await dotsImages.fileLink(attachment) });
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
|
|
244
382
|
const imageMatch = /^\/api\/images\/([a-f0-9]{64})$/.exec(url.pathname);
|
|
245
383
|
if (request.method === 'GET' && imageMatch) {
|
|
246
384
|
let image = attachmentCache.get(imageMatch[1])
|
|
385
|
+
|| dotsImages.restore(imageMatch[1], url.searchParams.get('recovery') || '')
|
|
247
386
|
|| recoverLocalImage(imageMatch[1], url.searchParams.get('recovery') || '');
|
|
248
387
|
const contextThreadId = url.searchParams.get('threadId') || '';
|
|
249
388
|
const contextTurnId = url.searchParams.get('turnId') || '';
|
|
@@ -255,1336 +394,1015 @@ async function handleRequest(request, response) {
|
|
|
255
394
|
} catch {}
|
|
256
395
|
}
|
|
257
396
|
if (!image) throw new RequestError(404, '这张图片已失效,无法从工作站重新读取。');
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
if (
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
if (
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
if (
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
if (
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
397
|
+
if (image.dotsFile) await dotsImages.load(image);
|
|
398
|
+
if (url.searchParams.get('variant') === 'thumbnail') {
|
|
399
|
+
const asset = await attachmentThumbnail(image);
|
|
400
|
+
sendJson(response, 200, { url: `data:${asset.mimeType};base64,${asset.buffer.toString('base64')}` });
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const size = image.buffer.length;
|
|
404
|
+
if (!size) throw new RequestError(400, '图片为空,无法下载。');
|
|
405
|
+
if (!request.fileTransfer) throw new RequestError(400, '请通过文件通道读取原图。');
|
|
406
|
+
const revision = imageMatch[1];
|
|
407
|
+
const { offset, length } = fileRange(url.searchParams, size, revision);
|
|
408
|
+
response.filePart({ name: image.name || '图片', size, offset, revision, mimeType: image.mimeType },
|
|
409
|
+
image.buffer.subarray(offset, offset + length));
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const localFileRequest = url.pathname === '/api/files/local';
|
|
414
|
+
const fileMatch = /^\/api\/files\/([a-f0-9]{64})$/.exec(url.pathname);
|
|
415
|
+
if (request.method === 'GET' && (fileMatch || localFileRequest)) {
|
|
416
|
+
if (!request.fileTransfer) throw new RequestError(400, '请通过文件通道下载附件。');
|
|
417
|
+
const hosted = !localFileRequest && (attachmentCache.get(fileMatch[1])
|
|
418
|
+
|| dotsImages.restore(fileMatch[1], url.searchParams.get('recovery') || ''));
|
|
419
|
+
if (hosted?.dotsFile) {
|
|
420
|
+
const { bytes, ...metadata } = await dotsImages.readPart(hosted, url.searchParams);
|
|
421
|
+
response.filePart(metadata, bytes);
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
const localPath = url.searchParams.get('path') || '';
|
|
425
|
+
if (localFileRequest && (/[\x00-\x1f]/.test(localPath)
|
|
426
|
+
|| !(process.platform === 'win32' ? /^[a-z]:[\\/]/i : /^\/(?!\/)/).test(localPath))) {
|
|
427
|
+
throw new RequestError(400, '无效的工作站文件路径。');
|
|
428
|
+
}
|
|
429
|
+
const file = localFileRequest ? describeLocalFile(localPath) : fileCache.get(fileMatch[1]);
|
|
430
|
+
if (!file) throw new RequestError(404, '电脑上的文件不存在或无法读取。');
|
|
431
|
+
if (file.externalIdentity) await dotsImages.authorization(file.externalIdentity);
|
|
432
|
+
const { offset, length } = fileRange(url.searchParams, file.size, file.revision);
|
|
433
|
+
let handle;
|
|
434
|
+
try { handle = fs.openSync(file.path, 'r'); }
|
|
435
|
+
catch (error) {
|
|
436
|
+
if (error.code === 'ENOENT') throw new RequestError(404, '电脑上的文件已不存在。');
|
|
437
|
+
throw error;
|
|
438
|
+
}
|
|
439
|
+
try {
|
|
440
|
+
const validate = () => {
|
|
441
|
+
const stat = fs.fstatSync(handle);
|
|
442
|
+
if (!stat.isFile() || fileRevision(stat) !== file.revision || fileRevision(fs.statSync(file.path)) !== file.revision) {
|
|
443
|
+
if (fileMatch) fileCache.delete(fileMatch[1]);
|
|
444
|
+
throw new RequestError(409, '电脑上的文件已发生变化,请重新读取对话。');
|
|
445
|
+
}
|
|
446
|
+
if (!stat.size) throw new RequestError(400, '文件为空,无法下载。');
|
|
447
|
+
};
|
|
448
|
+
validate();
|
|
449
|
+
const data = Buffer.alloc(length);
|
|
450
|
+
let bytesRead = 0;
|
|
451
|
+
while (bytesRead < data.length) {
|
|
452
|
+
const count = fs.readSync(handle, data, bytesRead, data.length - bytesRead, offset + bytesRead);
|
|
453
|
+
if (!count) throw new RequestError(409, '电脑上的文件读取不完整,请重新读取对话。');
|
|
454
|
+
bytesRead += count;
|
|
455
|
+
}
|
|
456
|
+
validate();
|
|
457
|
+
response.filePart({ name: file.name, size: file.size, offset, revision: file.revision }, data);
|
|
458
|
+
} finally { fs.closeSync(handle); }
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
if (url.pathname.startsWith('/api/app-server/') || url.pathname === '/api/wait') {
|
|
463
|
+
throw new RequestError(410, '此连接方式已停用。请检查 Codex 内核状态。', { code: 'unsupported_control' });
|
|
464
|
+
}
|
|
465
|
+
const taskPath = /^\/api\/threads\/([^/]+)/.exec(url.pathname);
|
|
466
|
+
if (taskPath && (url.pathname.endsWith('/takeover') || url.pathname === `/api/threads/${taskPath[1]}`)) {
|
|
467
|
+
throw new RequestError(410, '此连接方式已停用。', { code: 'unsupported_control' });
|
|
468
|
+
}
|
|
469
|
+
const hostId = url.searchParams.get('hostId') || 'local';
|
|
470
|
+
if (!['local', 'durable'].includes(hostId)) {
|
|
471
|
+
throw new RequestError(410, '此对话的连接方式已停用,请检查 Codex 内核状态。', { code: 'unsupported_control' });
|
|
472
|
+
}
|
|
473
|
+
if (!executionHealth.state.ready || sharedServer?.ready !== true) {
|
|
474
|
+
throw new RequestError(503, 'Codex 内核未就绪。请重启工作站服务;若仍失败,运行 relax doctor。',
|
|
475
|
+
{ code: 'full_control_required' });
|
|
476
|
+
}
|
|
477
|
+
const rootChat = hostId === 'durable' && taskPath
|
|
478
|
+
&& await dotsServer.source(decodeURIComponent(taskPath[1])) === 'aeon';
|
|
479
|
+
const execution = rootChat ? dotsChat : hostId === 'durable' ? dotsServer : sharedServer;
|
|
480
|
+
|
|
481
|
+
if (url.pathname === '/api/permissions' && ['GET', 'POST'].includes(request.method)) {
|
|
482
|
+
if (hostId !== 'local') throw new RequestError(405, '当前来源不提供工作站全局审批方式。');
|
|
483
|
+
const body = request.method === 'POST' ? await readJsonBody(request) : {};
|
|
484
|
+
if (request.method === 'POST' && typeof body.mode !== 'string') throw new RequestError(400, '缺少审批方式。');
|
|
485
|
+
sendJson(response, 200, await sharedServer.globalPermissions(body.mode, {
|
|
486
|
+
threadId: url.searchParams.get('threadId') || '', cwd: url.searchParams.get('cwd') || '',
|
|
487
|
+
}));
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
const dotsActivityRetryMatch = /^\/api\/threads\/([^/]+)\/dots-activity\/retry$/.exec(url.pathname);
|
|
492
|
+
if (request.method === 'POST' && dotsActivityRetryMatch) {
|
|
493
|
+
if (!rootChat) throw new RequestError(405, '只有点点主聊天提供活动状态。');
|
|
494
|
+
sendJson(response, 200, { started: dotsChat.retryActivity(decodeURIComponent(dotsActivityRetryMatch[1])) });
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
const dotsActivityMatch = /^\/api\/threads\/([^/]+)\/dots-activity-events$/.exec(url.pathname);
|
|
498
|
+
if (request.method === 'GET' && dotsActivityMatch) {
|
|
499
|
+
if (!rootChat) throw new RequestError(405, '只有点点主聊天提供此活动面板。');
|
|
500
|
+
response.startEvents();
|
|
501
|
+
const disconnected = () => response.end();
|
|
502
|
+
dotsChat.on('disconnected', disconnected);
|
|
503
|
+
const release = dotsChat.acquirePanelActivity(decodeURIComponent(dotsActivityMatch[1]), value => {
|
|
504
|
+
if (!response.destroyed) response.event('dots-activity', { threadId: value.threadId, activity: value.activity });
|
|
505
|
+
});
|
|
506
|
+
response.once('close', () => { release(); dotsChat.off('disconnected', disconnected); });
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const dotsTasksMatch = /^\/api\/threads\/([^/]+)\/dots-tasks$/.exec(url.pathname);
|
|
511
|
+
if (request.method === 'GET' && dotsTasksMatch) {
|
|
512
|
+
if (!rootChat) throw new RequestError(405, '只有点点主聊天提供此任务面板。');
|
|
513
|
+
sendJson(response, 200, await readDotsSummaryTasks(dotsServer, decodeURIComponent(dotsTasksMatch[1])));
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const dotsSchedulesMatch = /^\/api\/threads\/([^/]+)\/dots-schedules$/.exec(url.pathname);
|
|
518
|
+
if (request.method === 'GET' && dotsSchedulesMatch) {
|
|
519
|
+
if (!rootChat) throw new RequestError(405, '只有点点主聊天提供此定时任务列表。');
|
|
520
|
+
sendJson(response, 200, await readDotsSchedules(dotsServer, decodeURIComponent(dotsSchedulesMatch[1])));
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
if (request.method === 'GET' && url.pathname.startsWith('/api/code/')) {
|
|
525
|
+
const operation = url.pathname.slice('/api/code/'.length);
|
|
526
|
+
if (hostId === 'durable' && operation !== 'change') throw new RequestError(405, 'Dots 委派任务尚未接入代码浏览。');
|
|
527
|
+
try {
|
|
528
|
+
if ((operation === 'image' || operation === 'binary') && !request.fileTransfer) throw new RequestError(400, '请通过文件通道读取预览文件。');
|
|
529
|
+
const result = await browseCode((method, params) => execution.request(method, params), operation, url.searchParams);
|
|
530
|
+
if (operation === 'image' || operation === 'binary') {
|
|
531
|
+
const { data, ...metadata } = result;
|
|
532
|
+
response.filePart(metadata, data);
|
|
533
|
+
} else sendJson(response, 200, result);
|
|
534
|
+
} catch (error) { throw new RequestError(error.statusCode || 502, error.message); }
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
if (request.method === 'GET' && url.pathname === '/api/models') {
|
|
539
|
+
sendJson(response, 200, await execution.models());
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
if (request.method === 'GET' && url.pathname === '/api/archived-threads') {
|
|
544
|
+
sendJson(response, 200, await archivedThreadsPage(execution, sharedServer, hostId, url.searchParams.get('cursor')));
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
if (request.method === 'GET' && url.pathname === '/api/threads') {
|
|
549
|
+
const limit = boundedInteger(url.searchParams.get('limit'), 20, 1, 200);
|
|
550
|
+
const archived = url.searchParams.get('archived') === 'true';
|
|
551
|
+
const scope = url.searchParams.get('scope') || 'all';
|
|
552
|
+
if (!['all', 'local', 'durable'].includes(scope)) { sendJson(response, 400, { error: '无效的会话列表范围' }); return; }
|
|
553
|
+
const catalog = await sharedCatalog.threads(limit, archived, scope, url.searchParams.get('refresh') === '1');
|
|
554
|
+
const creations = await messageReceipts.creationBindings();
|
|
555
|
+
for (const thread of [...(catalog.threads || []), ...(catalog.pinnedThreads || [])]) {
|
|
556
|
+
const clientId = creations.get(thread.id);
|
|
557
|
+
if (clientId && (thread.hostId || 'local') === 'local') thread.creationClientId = clientId;
|
|
558
|
+
}
|
|
559
|
+
sendJson(response, 200, catalog);
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
if (request.method === 'GET' && url.pathname === '/api/file-local-copy') {
|
|
564
|
+
const value = url.searchParams.get('source') || '';
|
|
565
|
+
const match = /^([a-f0-9]{64})(?:\?recovery=([A-Za-z0-9_-]{1,4096}))?$/.exec(value);
|
|
566
|
+
if (!match) throw new RequestError(400, '无效的文件标识。');
|
|
567
|
+
const asset = attachmentCache.get(match[1])
|
|
568
|
+
|| dotsImages.restore(match[1], match[2] || url.searchParams.get('recovery') || '');
|
|
569
|
+
// A missing process cache does not make a local image an external file.
|
|
570
|
+
// The actual image endpoint owns recovery and download authorization.
|
|
571
|
+
if (!asset?.dotsFile) {
|
|
572
|
+
sendJson(response, 200, { external: false, localCopy: null }); return;
|
|
573
|
+
}
|
|
574
|
+
await dotsImages.authorization(asset.identity);
|
|
575
|
+
const copy = await workstationDownloads.copy(asset.id);
|
|
576
|
+
sendJson(response, 200, { external: true, localCopy: copy ? workstationCopyReference(copy, asset) : null,
|
|
577
|
+
cachedContent: asset.buffer ? { remotePath: asset.id, name: asset.name, size: asset.buffer.length, mimeType: asset.mimeType } : null });
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (request.method === 'POST' && url.pathname === '/api/workstation-file-attachments') {
|
|
355
582
|
await requireExecutionWritable();
|
|
356
|
-
await
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
583
|
+
const body = await readJsonBody(request);
|
|
584
|
+
const source = body.source;
|
|
585
|
+
const file = typeof source === 'string' && /^[a-z]:[\\/]/i.test(source) ? describeLocalFile(source)
|
|
586
|
+
: typeof source === 'string' && /^[a-f0-9]{64}$/.test(source) ? fileCache.get(source) : null;
|
|
587
|
+
if (!file) throw new RequestError(404, '电脑文件不可用,请从原文件入口重新添加。');
|
|
588
|
+
if (file.externalIdentity) await dotsImages.authorization(file.externalIdentity);
|
|
589
|
+
sendJson(response, 201, { file: await stageWorkstationMessageFile(file, uploadsRoot) });
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (request.method === 'GET' && url.pathname === '/api/file-save-locations') {
|
|
594
|
+
await requireExecutionWritable();
|
|
595
|
+
const locations = await projectLocations();
|
|
596
|
+
const projects = (await sharedCatalog.projects()).projects.filter(project => project.hostId === 'local' && project.roots?.length);
|
|
597
|
+
sendJson(response, 200, { projects, downloads: locations.downloads });
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
if (request.method === 'GET' && url.pathname === '/api/file-save-folders') {
|
|
602
|
+
await requireExecutionWritable();
|
|
603
|
+
sendJson(response, 200, await workstationDownloads.browse((method, params) => sharedServer.request(method, params),
|
|
604
|
+
await projectLocations(), Object.fromEntries(url.searchParams)));
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
if (request.method === 'POST' && url.pathname === '/api/file-saves') {
|
|
609
|
+
await requireExecutionWritable();
|
|
610
|
+
const body = await readJsonBody(request);
|
|
611
|
+
const asset = await externalDownloadAsset(body.source, body.recovery);
|
|
612
|
+
const controller = new AbortController(), cancel = () => controller.abort();
|
|
613
|
+
response.once('close', cancel);
|
|
614
|
+
try {
|
|
615
|
+
const result = await workstationDownloads.save((method, params) => sharedServer.request(method, params),
|
|
616
|
+
await projectLocations(), body, asset, (file, query) => dotsImages.readPart(file, query), controller.signal);
|
|
617
|
+
sendJson(response, 201, { localCopy: workstationCopyReference(result, asset), warning: result.warning || '' });
|
|
618
|
+
} finally { response.off('close', cancel); }
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
if (request.method === 'GET' && url.pathname === '/api/projects') {
|
|
623
|
+
sendJson(response, 200, { projects: (await sharedCatalog.projects()).projects });
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
if (url.pathname === '/api/project-folders' && ['GET', 'POST'].includes(request.method)) {
|
|
628
|
+
await requireExecutionWritable();
|
|
629
|
+
try {
|
|
630
|
+
const rpc = (method, params) => sharedServer.request(method, params);
|
|
631
|
+
const result = request.method === 'GET'
|
|
632
|
+
? await browseProjectFolders(rpc, !url.searchParams.get('path') || url.searchParams.get('locations') === '1' ? await projectLocations() : null, url.searchParams.get('path'))
|
|
633
|
+
: await createProjectFolder(rpc, await readJsonBody(request));
|
|
634
|
+
sendJson(response, request.method === 'GET' ? 200 : 201, result);
|
|
635
|
+
} catch (error) { throw new RequestError(error.statusCode || 502, error.message); }
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
const projectActionMatch = /^\/api\/projects\/([^/]+)\/(remove|move)$/.exec(url.pathname);
|
|
640
|
+
if (projectActionMatch) {
|
|
641
|
+
await requireExecutionWritable();
|
|
642
|
+
const projectId = decodeURIComponent(projectActionMatch[1]);
|
|
643
|
+
if (request.method === 'POST' && projectActionMatch[2] === 'move') {
|
|
644
|
+
const { beforeProjectId } = await readJsonBody(request);
|
|
645
|
+
if (beforeProjectId !== null && (typeof beforeProjectId !== 'string' || !beforeProjectId.trim()) || beforeProjectId === projectId) {
|
|
646
|
+
throw new RequestError(400, '排序目标无效。');
|
|
647
|
+
}
|
|
648
|
+
await sharedServer.request('project/move', { projectId, beforeProjectId });
|
|
649
|
+
sendJson(response, 200, await sharedCatalog.projects().then(({ projects }) => ({ projects })));
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
if (request.method === 'POST' && projectActionMatch[2] === 'remove') {
|
|
653
|
+
const result = await removeWorkstationProject(sharedServer, stateRoot, codexDataRoot, projectId, await readJsonBody(request));
|
|
654
|
+
sendJson(response, 200, result);
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
throw new RequestError(405, '不支持的项目操作。');
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
const updateProjectMatch = /^\/api\/projects\/([^/]+)$/.exec(url.pathname);
|
|
661
|
+
if (request.method === 'POST' && (url.pathname === '/api/projects' || updateProjectMatch)) {
|
|
662
|
+
await requireExecutionWritable();
|
|
663
|
+
const body = await readJsonBody(request);
|
|
664
|
+
try {
|
|
665
|
+
const result = !updateProjectMatch ? await createWorkstationProject(sharedServer, stateRoot, codexDataRoot, body)
|
|
666
|
+
: await updateWorkstationProject(sharedServer, stateRoot, codexDataRoot, decodeURIComponent(updateProjectMatch[1]), body);
|
|
667
|
+
sendJson(response, updateProjectMatch ? 200 : 201, result);
|
|
668
|
+
} catch (error) { throw new RequestError(error.statusCode || 502, error.message, error.details); }
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
if (request.method === 'GET' && url.pathname === '/api/plan-pricing') {
|
|
673
|
+
sendJson(response, 200, await readPlanPricing(sharedServer));
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
if (request.method === 'GET' && url.pathname === '/api/usage-limits') {
|
|
678
|
+
sendJson(response, 200, await sharedServer.usage());
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
if (request.method === 'POST' && url.pathname === '/api/usage-reset') {
|
|
363
683
|
await requireExecutionWritable();
|
|
364
|
-
const
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
684
|
+
const body = await readJsonBody(request);
|
|
685
|
+
try { sendJson(response, 200, await consumeUsageReset(sharedServer, body)); }
|
|
686
|
+
catch (error) { throw new RequestError(error.statusCode || 502, error.message,
|
|
687
|
+
error.code === 'usage_reset_not_submitted' ? { code: error.code, deliveryUnknown: false } : undefined); }
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
if (request.method === 'GET' && url.pathname === '/api/usage-events') {
|
|
692
|
+
const execution = sharedServer;
|
|
693
|
+
response.startEvents();
|
|
694
|
+
const emit = value => { if (!response.destroyed) response.event('usage', value); };
|
|
695
|
+
const failed = error => { if (!response.destroyed) response.event('usage-error', { error: error.message }); };
|
|
696
|
+
const disconnected = () => response.end();
|
|
697
|
+
execution.on('usage', emit); execution.on('usage-error', failed); execution.on('disconnected', disconnected);
|
|
698
|
+
response.once('close', () => { execution.off('usage', emit); execution.off('usage-error', failed); execution.off('disconnected', disconnected); });
|
|
699
|
+
try { emit(await execution.usage()); } catch (error) { failed(error); }
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (request.method === 'GET' && url.pathname === '/api/thread-events') {
|
|
704
|
+
await sharedServer.connect();
|
|
705
|
+
const clients = [sharedServer, dotsServer, dotsChat];
|
|
706
|
+
response.startEvents();
|
|
707
|
+
const listener = ({ method, params }) => {
|
|
708
|
+
const questionChange = questionAttention.fromNotification(method, params);
|
|
709
|
+
if ((!threadListNotificationMethods.has(method) && !questionChange) || response.destroyed) return;
|
|
710
|
+
response.event('thread-list-changed', { method, threadId: params.threadId || params.thread?.id || '',
|
|
711
|
+
...(questionChange ? { questionChange } : {}),
|
|
712
|
+
...(params.hostId ? { hostId: params.hostId } : {}),
|
|
713
|
+
...(params.chatRevision !== undefined ? { chatRevision: params.chatRevision } : {}),
|
|
714
|
+
...(params.updatedAt !== undefined ? { updatedAt: params.updatedAt } : {}),
|
|
715
|
+
...(params.chatMessageRevision !== undefined ? { chatMessageRevision: params.chatMessageRevision } : {}),
|
|
716
|
+
...(params.status ? { status: typeof params.status === 'string' ? params.status : params.status.type } : {}) });
|
|
717
|
+
};
|
|
718
|
+
const disconnected = () => response.end();
|
|
719
|
+
for (const client of clients) {
|
|
720
|
+
client.on('notification', listener);
|
|
721
|
+
client.on('disconnected', disconnected);
|
|
722
|
+
}
|
|
723
|
+
response.once('close', () => {
|
|
724
|
+
for (const client of clients) {
|
|
725
|
+
client.off('notification', listener);
|
|
726
|
+
client.off('disconnected', disconnected);
|
|
727
|
+
}
|
|
728
|
+
});
|
|
729
|
+
response.event('ready', {});
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
if (request.method === 'GET' && url.pathname === '/api/turn-events') {
|
|
734
|
+
const clients = [sharedServer, dotsServer, dotsChat];
|
|
735
|
+
response.startEvents();
|
|
736
|
+
const listener = ({ method, params }) => {
|
|
737
|
+
if (!['turn/started', 'turn/completed'].includes(method)) return;
|
|
738
|
+
const threadId = params?.threadId, turnId = params?.turn?.id;
|
|
739
|
+
if (typeof threadId === 'string' && typeof turnId === 'string' && !response.destroyed) {
|
|
740
|
+
response.event('turn', { method, threadId, turnId });
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
const disconnected = () => response.end();
|
|
744
|
+
for (const client of clients) {
|
|
745
|
+
client.on('notification', listener);
|
|
746
|
+
client.on('disconnected', disconnected);
|
|
747
|
+
}
|
|
748
|
+
response.once('close', () => {
|
|
749
|
+
for (const client of clients) {
|
|
750
|
+
client.off('notification', listener);
|
|
751
|
+
client.off('disconnected', disconnected);
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
const activeTurnMatch = /^\/api\/threads\/([^/]+)\/active-turn$/.exec(url.pathname);
|
|
758
|
+
if (request.method === 'GET' && activeTurnMatch) {
|
|
759
|
+
if (rootChat) { sendJson(response, 200, { turnId: null }); return; }
|
|
760
|
+
const threadId = decodeURIComponent(activeTurnMatch[1]);
|
|
761
|
+
await execution.connect();
|
|
762
|
+
const { thread } = await execution.request('thread/read', { threadId, includeTurns: false });
|
|
763
|
+
const status = typeof thread.status === 'string' ? thread.status : thread.status?.type;
|
|
764
|
+
let turnId = null;
|
|
765
|
+
if (status === 'active') {
|
|
766
|
+
const page = await execution.request('thread/turns/list', {
|
|
767
|
+
threadId, limit: 1, sortDirection: 'desc', itemsView: 'summary',
|
|
768
|
+
});
|
|
769
|
+
const latest = page.data?.[0];
|
|
770
|
+
if (latest?.status === 'inProgress') turnId = latest.id;
|
|
771
|
+
}
|
|
772
|
+
sendJson(response, 200, { turnId });
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const createStatusMatch = /^\/api\/projects\/([^/]+)\/threads\/([a-f0-9]{32})\/status$/.exec(url.pathname);
|
|
777
|
+
if (request.method === 'GET' && createStatusMatch) {
|
|
778
|
+
const creationScope = ['project', decodeURIComponent(createStatusMatch[1])], clientId = createStatusMatch[2];
|
|
779
|
+
let status = messageReceipts.status(creationScope, clientId);
|
|
780
|
+
if (status.state === 'unknown' && status.createdThreadId) {
|
|
781
|
+
const threadId = status.createdThreadId;
|
|
782
|
+
status = await messageReceipts.reconcile(creationScope, clientId, async () => {
|
|
783
|
+
const found = await sharedServer.findSentMessage(threadId, clientId);
|
|
784
|
+
return found ? { threadId, hostId: 'local', turnId: found.data?.turnId } : null;
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
sendJson(response, 200, status); return;
|
|
788
|
+
}
|
|
789
|
+
const createThreadMatch = /^\/api\/projects\/([^/]+)\/threads$/.exec(url.pathname);
|
|
790
|
+
if (request.method === 'POST' && createThreadMatch) {
|
|
791
|
+
const projectId = decodeURIComponent(createThreadMatch[1]);
|
|
792
|
+
const body = await readJsonBody(request);
|
|
793
|
+
const result = await messageReceipts.submit(['project', projectId], body.clientUserMessageId, async () => {
|
|
794
|
+
const bindCreation = messageReceipts.beginCreation(['project', projectId], body.clientUserMessageId);
|
|
795
|
+
try {
|
|
796
|
+
await requireExecutionWritable();
|
|
797
|
+
if (body.transport === 'app-server' || (body.hostId && body.hostId !== 'local')) {
|
|
798
|
+
throw new RequestError(410, '此连接方式已停用,请检查 Codex 内核状态。', { code: 'unsupported_control' });
|
|
799
|
+
}
|
|
800
|
+
const projects = (await sharedCatalog.projects()).projects;
|
|
801
|
+
const project = projects.find(item => item.projectId === projectId);
|
|
802
|
+
if (projectId !== '__unassigned__' && !project) throw new RequestError(404, '没有找到对应项目。');
|
|
803
|
+
const execution = sharedServer;
|
|
804
|
+
await execution.connect();
|
|
805
|
+
const rpc = (method, params) => execution.request(method, params);
|
|
806
|
+
let target = appServerEvents.projectlessThreadTarget(projectRoot);
|
|
807
|
+
if (project) {
|
|
808
|
+
const nativeProjects = await appServerEvents.readProjects(rpc);
|
|
809
|
+
const nativeProject = nativeProjects.find(item => item.id === project.projectId);
|
|
810
|
+
if (!nativeProject) throw new RequestError(404, 'Codex 内核中没有找到对应项目,请刷新项目列表。');
|
|
811
|
+
target = appServerEvents.projectThreadTarget(nativeProject);
|
|
812
|
+
}
|
|
813
|
+
const { input } = appServerTurnArguments('', body);
|
|
814
|
+
const preference = await execution.globalPermissions(undefined, { cwd: target.cwd });
|
|
815
|
+
messageSubmissionStarted = true;
|
|
816
|
+
const createRpc = (method, params) => method === 'thread/start'
|
|
817
|
+
? execution.startThread(params) : rpc(method, params);
|
|
818
|
+
const created = await appServerEvents.createThread(createRpc, target, input,
|
|
819
|
+
{ ...body, desktopPermissionMode: preference.globalPermissionMode }, undefined, bindCreation);
|
|
820
|
+
const prompt = input.filter(part => part.type === 'text').map(part => part.text).join('\n');
|
|
821
|
+
void generateAndSetThreadTitle({
|
|
822
|
+
request: rpc,
|
|
823
|
+
subscribe: listener => {
|
|
824
|
+
execution.on('notification', listener);
|
|
825
|
+
return () => execution.off('notification', listener);
|
|
826
|
+
},
|
|
827
|
+
threadId: created.threadId,
|
|
828
|
+
prompt,
|
|
829
|
+
cwd: target.cwd || null,
|
|
830
|
+
}).catch(error => console.error(`生成对话标题失败:${error.message}`));
|
|
831
|
+
return { ...created, hostId:'local' };
|
|
832
|
+
} catch (error) {
|
|
833
|
+
error.deliveryUnknown = Boolean(messageReceipts.status(['project', projectId], body.clientUserMessageId).createdThreadId)
|
|
834
|
+
|| messageSubmissionStarted && !messageDelivery.rejectedBeforeSubmission(error);
|
|
835
|
+
if (error.deliveryResult) error.deliveryResult = error.deliveryResult.then(created => ({ ...created, hostId: 'local' })).finally(() => bindCreation());
|
|
836
|
+
else bindCreation();
|
|
837
|
+
throw error;
|
|
838
|
+
}
|
|
839
|
+
});
|
|
840
|
+
sendJson(response, 201, result);
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
const timelineMatch = /^\/api\/threads\/([^/]+)\/timeline$/.exec(url.pathname);
|
|
427
845
|
if (request.method === 'GET' && timelineMatch) {
|
|
428
846
|
const threadId = decodeURIComponent(timelineMatch[1]);
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
: timeline;
|
|
446
|
-
sendJson(response, 200, unchanged ? { ...timeline, turns: [], notModified: true } : partial);
|
|
447
|
-
return;
|
|
847
|
+
const knownSeq = url.searchParams.get('knownSeq');
|
|
848
|
+
const knownSync = { id: url.searchParams.get('knownSyncId'),
|
|
849
|
+
epoch: url.searchParams.get('knownEpoch'), seq: knownSeq === null ? undefined : Number(knownSeq),
|
|
850
|
+
updatedAt: Number(url.searchParams.get('knownUpdatedAt')), chatRevision: url.searchParams.get('knownChatRevision') };
|
|
851
|
+
const pageOptions = sharedHistoryPageOptions();
|
|
852
|
+
pageOptions.reconcileObserved = url.searchParams.get('refresh') === '1';
|
|
853
|
+
if (request.socketRequest) {
|
|
854
|
+
pageOptions.onWindow = async window => {
|
|
855
|
+
if (response.writableEnded) return;
|
|
856
|
+
await response.historyPage(await prepareSharedTimeline(window));
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
const timeline = await prepareSharedTimeline(await execution.timeline(threadId, pageOptions, knownSync));
|
|
860
|
+
if (request.socketRequest) {
|
|
861
|
+
response.on('progress', () => execution.keepSnapshotAlive(threadId, timeline.sync));
|
|
862
|
+
response.once('close', () => execution.keepSnapshotAlive(threadId, timeline.sync));
|
|
448
863
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
const timeline = normalizeTimeline(result.data);
|
|
461
|
-
enrichTimelineWithLocalActivity(timeline, threadId);
|
|
462
|
-
sendJson(response, 200, timeline);
|
|
463
|
-
} else {
|
|
464
|
-
sendJson(response, 502, { error: 'Codex Desktop 工具返回失败。', details: result.data });
|
|
465
|
-
}
|
|
466
|
-
return;
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
const approvalMatch = /^\/api\/threads\/([^/]+)\/approvals$/.exec(url.pathname);
|
|
864
|
+
sendJson(response, 200, timeline);
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
const approvalMatch = /^\/api\/threads\/([^/]+)\/approvals$/.exec(url.pathname);
|
|
869
|
+
if (request.method === 'GET' && approvalMatch && rootChat) {
|
|
870
|
+
const threadId = decodeURIComponent(approvalMatch[1]);
|
|
871
|
+
sendJson(response, 200, await execution.inspectApproval(threadId, {
|
|
872
|
+
id: url.searchParams.get('requestId'), roomMessageId: url.searchParams.get('roomMessageId'),
|
|
873
|
+
})); return;
|
|
874
|
+
}
|
|
470
875
|
if (request.method === 'POST' && approvalMatch) {
|
|
471
876
|
const threadId = decodeURIComponent(approvalMatch[1]);
|
|
472
|
-
await requireExecutionWritable(threadId);
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
}
|
|
500
|
-
await
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
const contextMatch = /^\/api\/threads\/([^/]+)\/context$/.exec(url.pathname);
|
|
510
|
-
if (request.method === 'GET' && contextMatch) {
|
|
511
|
-
const threadId = decodeURIComponent(contextMatch[1]);
|
|
512
|
-
const current = readContextUsage(threadId);
|
|
513
|
-
const native = usesSharedTask({ hostId: url.searchParams.get('hostId') }) ? await sharedServer.readContext(threadId) : {};
|
|
514
|
-
sendJson(response, 200, { ...current, ...(native.model ? { model: native.model, thinking: native.thinking, serviceTier: native.serviceTier,
|
|
515
|
-
permissionMode: native.permissionMode, permissionModes: native.permissionModes } : {}), ...(native.available ? native : {}) });
|
|
516
|
-
return;
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
const sharedAction = /^\/api\/threads\/([^/]+)\/(history|settings|permissions)$/.exec(url.pathname);
|
|
877
|
+
await requireExecutionWritable(threadId, execution);
|
|
878
|
+
const body = await readJsonBody(request);
|
|
879
|
+
sendJson(response, 200, await execution.respondApproval(threadId, body)); return;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
const eventsMatch = /^\/api\/threads\/([^/]+)\/events$/.exec(url.pathname);
|
|
883
|
+
if (request.method === 'GET' && eventsMatch) {
|
|
884
|
+
const threadId = decodeURIComponent(eventsMatch[1]);
|
|
885
|
+
const after = Number(url.searchParams.get('afterSeq'));
|
|
886
|
+
const requestedSync = { id: url.searchParams.get('syncId'), epoch: url.searchParams.get('syncEpoch'),
|
|
887
|
+
after: Number.isSafeInteger(after) && after >= 0 ? after : undefined,
|
|
888
|
+
updatedAt: Number(url.searchParams.get('knownUpdatedAt')), chatRevision: url.searchParams.get('knownChatRevision') };
|
|
889
|
+
await streamSharedThread(response, threadId, execution,
|
|
890
|
+
prepareSharedTimeline, requestedSync);
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
const modelChangesMatch = /^\/api\/threads\/([^/]+)\/model-changes$/.exec(url.pathname);
|
|
895
|
+
if (request.method === 'GET' && modelChangesMatch) {
|
|
896
|
+
const threadId = decodeURIComponent(modelChangesMatch[1]);
|
|
897
|
+
if (!/^[0-9a-f]{8}-[0-9a-f-]{20,55}$/i.test(threadId)) throw new RequestError(400, '对话 ID 无效。');
|
|
898
|
+
sendJson(response, 200, hostId === 'durable' ? [] : await turnModelHistory.read(findSessionPath(threadId), (url.searchParams.get('turnIds') || '').split(',').filter(Boolean)));
|
|
899
|
+
return;
|
|
900
|
+
}
|
|
901
|
+
const contextMatch = /^\/api\/threads\/([^/]+)\/context$/.exec(url.pathname);
|
|
902
|
+
if (request.method === 'GET' && contextMatch) {
|
|
903
|
+
const threadId = decodeURIComponent(contextMatch[1]);
|
|
904
|
+
const current = hostId === 'durable' ? { available: false } : readContextUsage(threadId);
|
|
905
|
+
const native = await execution.readContext(threadId, url.searchParams.get('refreshSettings') === 'true');
|
|
906
|
+
sendJson(response, 200, { ...current, ...(native.model ? { model: native.model, thinking: native.thinking, serviceTier: native.serviceTier,
|
|
907
|
+
permissionMode: native.permissionMode, permissionModes: native.permissionModes, globalPermissionMode: native.globalPermissionMode } : {}), ...(native.available ? native : {}) });
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
const sharedAction = /^\/api\/threads\/([^/]+)\/(history|settings|permissions)$/.exec(url.pathname);
|
|
520
912
|
if (sharedAction) {
|
|
521
|
-
const id = decodeURIComponent(sharedAction[1]);
|
|
522
|
-
if (
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
913
|
+
const id = decodeURIComponent(sharedAction[1]);
|
|
914
|
+
if (request.method === 'GET' && sharedAction[2] === 'history') {
|
|
915
|
+
const pageOptions = sharedHistoryPageOptions();
|
|
916
|
+
if (url.searchParams.has('itemLimit')) {
|
|
917
|
+
const itemLimit = Number(url.searchParams.get('itemLimit'));
|
|
918
|
+
if (!Number.isInteger(itemLimit) || itemLimit < 1 || itemLimit > 100) throw new RequestError(400, '历史条目数量无效。');
|
|
919
|
+
pageOptions.itemLimit = itemLimit;
|
|
920
|
+
}
|
|
921
|
+
const history = await execution.history(id, url.searchParams.get('cursor'), pageOptions);
|
|
922
|
+
sendJson(response, 200, await prepareSharedTimeline(history, hostId));
|
|
923
|
+
return;
|
|
924
|
+
}
|
|
527
925
|
if (request.method === 'POST' && sharedAction[2] === 'settings') {
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
926
|
+
if (rootChat) throw new RequestError(405, 'Dots 主对话不提供 Codex 模型设置。');
|
|
927
|
+
await requireExecutionWritable(id, execution);
|
|
928
|
+
const body = await readJsonBody(request);
|
|
929
|
+
sendJson(response, 200, await execution.settings(id, body.model, body.thinking, body.serviceTier));
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
533
932
|
if (request.method === 'POST' && sharedAction[2] === 'permissions') {
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
933
|
+
if (rootChat) throw new RequestError(405, 'Dots 主对话不提供 Codex 权限设置。');
|
|
934
|
+
await requireExecutionWritable(id, execution);
|
|
935
|
+
const body = await readJsonBody(request);
|
|
936
|
+
sendJson(response, 200, await execution.permissions(id, body.mode));
|
|
937
|
+
return;
|
|
538
938
|
}
|
|
539
939
|
}
|
|
540
940
|
|
|
541
|
-
const
|
|
542
|
-
if (request.method === '
|
|
543
|
-
|
|
544
|
-
const
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
sendJson(response, 200, {
|
|
551
|
-
entries: page.items.map(normalizeItem).filter(Boolean), nextOffset: page.nextOffset, total: page.total });
|
|
941
|
+
const renameMatch = /^\/api\/threads\/([^/]+)\/name$/.exec(url.pathname);
|
|
942
|
+
if (request.method === 'POST' && renameMatch) {
|
|
943
|
+
if (rootChat) throw new RequestError(405, '点点主聊天名称由点点资料管理。');
|
|
944
|
+
const threadId = decodeURIComponent(renameMatch[1]);
|
|
945
|
+
await requireExecutionWritable(threadId, execution);
|
|
946
|
+
const body = await readJsonBody(request);
|
|
947
|
+
const name = typeof body.name === 'string' ? body.name.trim() : '';
|
|
948
|
+
if (!name || /[\r\n]/.test(name)) throw new RequestError(400, '请输入单行对话名称。');
|
|
949
|
+
await execution.request('thread/name/set', { threadId, name });
|
|
950
|
+
sendJson(response, 200, { threadId, name });
|
|
552
951
|
return;
|
|
553
952
|
}
|
|
554
953
|
|
|
555
954
|
const archiveMatch = /^\/api\/threads\/([^/]+)\/(archive|unarchive)$/.exec(url.pathname);
|
|
556
955
|
if (request.method === 'POST' && archiveMatch) {
|
|
956
|
+
if (rootChat) throw new RequestError(405, 'Dots 主对话不提供任务归档。');
|
|
557
957
|
const threadId = decodeURIComponent(archiveMatch[1]);
|
|
558
|
-
await requireExecutionWritable(threadId);
|
|
559
|
-
if (
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
if (
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
sendJson(response, 200, { deleted: true, threadId, transport: 'app-server' });
|
|
577
|
-
return;
|
|
578
|
-
}
|
|
579
|
-
if (request.method === 'GET' && readMatch) {
|
|
580
|
-
const threadId = decodeURIComponent(readMatch[1]);
|
|
581
|
-
if (appServerTasks.owns(threadId)) {
|
|
582
|
-
sendJson(response, 200, { thread: await appServerTasks.readTask(threadId, {
|
|
583
|
-
includeTurns: true,
|
|
584
|
-
turnLimit: boundedInteger(url.searchParams.get('turnLimit'), 10, 1, 10),
|
|
585
|
-
}) });
|
|
586
|
-
return;
|
|
587
|
-
}
|
|
588
|
-
const argumentsValue = readThreadArguments(url, threadId, 10, 12_000);
|
|
589
|
-
sendToolResult(response, await callTool('read_thread', argumentsValue));
|
|
590
|
-
return;
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
const queueMatch = /^\/api\/threads\/([^/]+)\/queue$/.exec(url.pathname);
|
|
594
|
-
if (queueMatch) {
|
|
595
|
-
const threadId = decodeURIComponent(queueMatch[1]);
|
|
596
|
-
if (!appServerTasks.owns(threadId) && usesSharedTask({ hostId: url.searchParams.get('hostId') })) {
|
|
597
|
-
await sharedServer.connect();
|
|
598
|
-
const rpc = (method, params) => sharedServer.request(method, params);
|
|
599
|
-
if (request.method === 'GET') { sendJson(response, 200, await appServerEvents.readQueue(rpc, threadId)); return; }
|
|
600
|
-
if (request.method === 'POST') {
|
|
601
|
-
await requireExecutionWritable(threadId);
|
|
602
|
-
const args = appServerTurnArguments(threadId, await readJsonBody(request));
|
|
603
|
-
sendJson(response, 202, await appServerEvents.addQueue(rpc, threadId, args.input, crypto.randomUUID())); return;
|
|
604
|
-
}
|
|
605
|
-
}
|
|
606
|
-
if (request.method === 'GET') {
|
|
607
|
-
sendJson(response, 200, { items: publicQueue(threadId) });
|
|
608
|
-
return;
|
|
609
|
-
}
|
|
958
|
+
await requireExecutionWritable(threadId, execution);
|
|
959
|
+
if (archiveMatch[2] === 'archive') {
|
|
960
|
+
const { thread } = await execution.request('thread/read', { threadId, includeTurns: false });
|
|
961
|
+
const status = typeof thread.status === 'string' ? thread.status : thread.status?.type;
|
|
962
|
+
if (['active', 'inProgress'].includes(status)) throw new RequestError(409, '对话正在运行,请先停止任务。');
|
|
963
|
+
}
|
|
964
|
+
await execution.request(`thread/${archiveMatch[2]}`, { threadId });
|
|
965
|
+
sendJson(response, 200, { threadId, archived: archiveMatch[2] === 'archive' });
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
const queueMatch = /^\/api\/threads\/([^/]+)\/queue$/.exec(url.pathname);
|
|
970
|
+
if (queueMatch) {
|
|
971
|
+
if (hostId === 'durable') throw new RequestError(405, '当前托管连接不提供排队消息。');
|
|
972
|
+
const threadId = decodeURIComponent(queueMatch[1]);
|
|
973
|
+
await sharedServer.connect();
|
|
974
|
+
const rpc = (method, params) => sharedServer.request(method, params);
|
|
975
|
+
if (request.method === 'GET') { sendJson(response, 200, await appServerEvents.readQueue(rpc, threadId)); return; }
|
|
610
976
|
if (request.method === 'POST') {
|
|
611
|
-
await
|
|
612
|
-
const
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
const queueItemMatch = /^\/api\/threads\/([^/]+)\/queue\/([a-f0-9-]+)(?:\/(steer))?$/.exec(url.pathname);
|
|
636
|
-
if (queueItemMatch) {
|
|
637
|
-
const threadId = decodeURIComponent(queueItemMatch[1]);
|
|
638
|
-
const itemId = queueItemMatch[2];
|
|
639
|
-
if (!appServerTasks.owns(threadId) && usesSharedTask({ hostId: url.searchParams.get('hostId') })) {
|
|
640
|
-
await sharedServer.connect();
|
|
641
|
-
const action = request.method === 'DELETE' ? 'delete' : queueItemMatch[3] === 'steer' ? 'steer' : null;
|
|
642
|
-
if (!action) throw new RequestError(405, '不支持的队列操作');
|
|
643
|
-
await requireExecutionWritable(threadId);
|
|
644
|
-
sendJson(response, 200, await appServerEvents.changeQueue((method, params) => sharedServer.request(method, params), threadId, itemId, action)); return;
|
|
645
|
-
}
|
|
646
|
-
const queue = messageQueues.get(threadId) || [];
|
|
647
|
-
const index = queue.findIndex(item => item.id === itemId);
|
|
648
|
-
if (index < 0) {
|
|
649
|
-
sendJson(response, 404, { error: '没有找到该排队消息。' });
|
|
650
|
-
return;
|
|
651
|
-
}
|
|
652
|
-
if (request.method === 'DELETE' && !queueItemMatch[3]) {
|
|
653
|
-
await requireExecutionWritable(threadId);
|
|
654
|
-
queue.splice(index, 1);
|
|
655
|
-
sendJson(response, 200, { items: publicQueue(threadId) });
|
|
656
|
-
return;
|
|
657
|
-
}
|
|
658
|
-
if (request.method === 'POST' && queueItemMatch[3] === 'steer') {
|
|
659
|
-
await requireExecutionWritable(threadId);
|
|
660
|
-
const [item] = queue.splice(index, 1);
|
|
661
|
-
const result = await steerQueuedItem(threadId, item);
|
|
662
|
-
if (!result.success) {
|
|
663
|
-
queue.splice(index, 0, item);
|
|
664
|
-
sendJson(response, 502, { error: '插队发送失败。', details: result.data });
|
|
665
|
-
return;
|
|
666
|
-
}
|
|
667
|
-
sendJson(response, 200, { items: publicQueue(threadId) });
|
|
668
|
-
return;
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
const takeoverMatch = /^\/api\/threads\/([^/]+)\/takeover$/.exec(url.pathname);
|
|
673
|
-
if (request.method === 'POST' && takeoverMatch) {
|
|
674
|
-
const threadId = decodeURIComponent(takeoverMatch[1]);
|
|
977
|
+
const body = await readJsonBody(request);
|
|
978
|
+
const result = await messageReceipts.submit([hostId, threadId], body.clientUserMessageId, async () => {
|
|
979
|
+
let args;
|
|
980
|
+
try { await requireExecutionWritable(threadId); args = appServerTurnArguments(threadId, body); }
|
|
981
|
+
catch (error) { error.deliveryUnknown = false; throw error; }
|
|
982
|
+
messageSubmissionStarted = true;
|
|
983
|
+
try { return await appServerEvents.addQueue(rpc, threadId, args.input, body.clientUserMessageId, body.containsVoiceInput); }
|
|
984
|
+
catch (error) { if (messageDelivery.rejectedBeforeSubmission(error)) error.deliveryUnknown = false; throw error; }
|
|
985
|
+
});
|
|
986
|
+
sendJson(response, 202, result); return;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
const queueItemMatch = /^\/api\/threads\/([^/]+)\/queue\/([a-f0-9-]+)(?:\/(steer))?$/.exec(url.pathname);
|
|
991
|
+
if (queueItemMatch) {
|
|
992
|
+
if (hostId === 'durable') throw new RequestError(405, '当前托管连接不提供排队消息。');
|
|
993
|
+
const threadId = decodeURIComponent(queueItemMatch[1]);
|
|
994
|
+
const itemId = queueItemMatch[2];
|
|
995
|
+
await sharedServer.connect();
|
|
996
|
+
const action = request.method === 'DELETE' ? 'delete' : queueItemMatch[3] === 'steer' ? 'steer' : null;
|
|
997
|
+
if (!action) throw new RequestError(405, '不支持的队列操作');
|
|
675
998
|
await requireExecutionWritable(threadId);
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
if (messageQueues.get(threadId)?.length || queueWorkers.has(threadId)) throw new RequestError(409, '请先处理此聊天的排队消息。');
|
|
681
|
-
const result = await callTool('read_thread', { threadId, turnLimit: 1, includeOutputs: false });
|
|
682
|
-
if (!result.success) throw new RequestError(502, '无法确认 Desktop 聊天状态。');
|
|
683
|
-
const timeline = normalizeTimeline(result.data);
|
|
684
|
-
const thread = timeline.thread;
|
|
685
|
-
if (thread.hostId && thread.hostId !== 'local') throw new RequestError(400, '只支持本机聊天。');
|
|
686
|
-
if (!['idle', 'notLoaded'].includes(thread.status) || timeline.turns.some(t => t.status === 'inProgress')) throw new RequestError(409, '只允许接管已空闲的聊天,请等当前轮次结束。');
|
|
687
|
-
if (!findSessionPath(threadId)) throw new RequestError(400, '未找到此聊天的本机历史。');
|
|
688
|
-
sendJson(response, 200, { thread: await appServerTasks.adoptTask({ ...thread, id: threadId }) });
|
|
689
|
-
return;
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
const interruptMatch = /^\/api\/threads\/([^/]+)\/interrupt$/.exec(url.pathname);
|
|
999
|
+
sendJson(response, 200, await appServerEvents.changeQueue((method, params) => sharedServer.request(method, params), threadId, itemId, action)); return;
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
const interruptMatch = /^\/api\/threads\/([^/]+)\/interrupt$/.exec(url.pathname);
|
|
693
1003
|
if (request.method === 'POST' && interruptMatch) {
|
|
1004
|
+
if (rootChat) throw new RequestError(405, 'Dots 主对话不提供停止 Codex 任务的操作。');
|
|
694
1005
|
const threadId = decodeURIComponent(interruptMatch[1]);
|
|
695
|
-
await requireExecutionWritable(threadId);
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
1006
|
+
await requireExecutionWritable(threadId, execution);
|
|
1007
|
+
const body = await readJsonBody(request);
|
|
1008
|
+
if (!body.turnId) throw new RequestError(400, '缺少活动轮次 ID。');
|
|
1009
|
+
await execution.interrupt(threadId, body.turnId);
|
|
1010
|
+
sendJson(response, 200, { requested: true });
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
const roomReadMatch = /^\/api\/threads\/([^/]+)\/read$/.exec(url.pathname);
|
|
1015
|
+
if (request.method === 'POST' && roomReadMatch) {
|
|
1016
|
+
if (!rootChat) throw new RequestError(405, '此对话不提供消息房间已读操作。');
|
|
1017
|
+
await dotsChat.markRead(decodeURIComponent(roomReadMatch[1]), await readJsonBody(request));
|
|
1018
|
+
sendJson(response, 200, { success: true });
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
const messageStatusMatch = /^\/api\/threads\/([^/]+)\/messages\/([a-f0-9]{32})\/status$/.exec(url.pathname);
|
|
1023
|
+
if (request.method === 'GET' && messageStatusMatch) {
|
|
1024
|
+
const threadId = decodeURIComponent(messageStatusMatch[1]), clientId = messageStatusMatch[2];
|
|
1025
|
+
const result = await messageReceipts.reconcile([hostId, threadId], clientId, async () => {
|
|
1026
|
+
if (hostId !== 'durable') {
|
|
1027
|
+
await sharedServer.connect();
|
|
1028
|
+
const queue = await appServerEvents.readQueue((method, params) => sharedServer.request(method, params), threadId);
|
|
1029
|
+
if (queue.items.some(item => messageDelivery.normalizeId(item.clientUserMessageId) === clientId)) return queue;
|
|
1030
|
+
}
|
|
1031
|
+
return execution.findSentMessage(threadId, clientId, url.searchParams.get('anchorItemId') || '');
|
|
1032
|
+
});
|
|
1033
|
+
sendJson(response, 200, result);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
const messageMatch = /^\/api\/threads\/([^/]+)\/messages$/.exec(url.pathname);
|
|
716
1037
|
if (request.method === 'POST' && messageMatch) {
|
|
717
1038
|
const threadId = decodeURIComponent(messageMatch[1]);
|
|
718
|
-
await
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
const
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
return;
|
|
746
|
-
}
|
|
747
|
-
const status = error instanceof RequestError || error instanceof ThreadWriterConflictError ? (error.statusCode || 409) : 502;
|
|
1039
|
+
const body = await readJsonBody(request);
|
|
1040
|
+
if (body.hostId && body.hostId !== hostId) throw new RequestError(400, '请求中的对话主机不一致。');
|
|
1041
|
+
const result = await messageReceipts.submit([hostId, threadId], body.clientUserMessageId, async () => {
|
|
1042
|
+
let args;
|
|
1043
|
+
try { await requireExecutionWritable(threadId, execution); args = execution === dotsChat ? { ...body, threadId } : appServerTurnArguments(threadId, { ...body, hostId }); }
|
|
1044
|
+
catch (error) { error.deliveryUnknown = false; throw error; }
|
|
1045
|
+
messageSubmissionStarted = true;
|
|
1046
|
+
const responseFor = submitted => ({ success: true, data: submitted.result, usage: submitted.usage });
|
|
1047
|
+
try { return responseFor(await execution.send(args)); }
|
|
1048
|
+
catch (error) {
|
|
1049
|
+
if (error.deliveryResult) error.deliveryResult = error.deliveryResult.then(responseFor);
|
|
1050
|
+
throw error;
|
|
1051
|
+
}
|
|
1052
|
+
});
|
|
1053
|
+
sendJson(response, 200, result);
|
|
1054
|
+
return;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
sendJson(response, 404, { error: '未找到请求的资源。' });
|
|
1058
|
+
} catch (error) {
|
|
1059
|
+
if (response.headersSent) {
|
|
1060
|
+
if (!response.writableEnded) response.end();
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
if (!messageSubmissionStarted && error.deliveryUnknown === undefined && request.method === 'POST'
|
|
1064
|
+
&& /^\/api\/threads\/[^/]+\/(?:messages|queue)(?:\?|$)/.test(request.url || '')) error.deliveryUnknown = false;
|
|
1065
|
+
const status = error instanceof RequestError || error instanceof ThreadWriterConflictError || error instanceof FileRangeError ? (error.statusCode || 409) : 502;
|
|
748
1066
|
sendJson(response, status, {
|
|
749
1067
|
error: error instanceof Error ? error.message : String(error),
|
|
750
1068
|
code: error?.code,
|
|
751
1069
|
threadId: error?.threadId,
|
|
752
1070
|
readOnly: error?.readOnly,
|
|
753
|
-
details: error?.details,
|
|
754
|
-
});
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
const server = http.createServer(handleRequest);
|
|
759
|
-
const lanSocket = attachLanSocket(server, { token: options.token, dispatch: handleRequest,
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
console.error(
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
1071
|
+
details: error?.deliveryUnknown === undefined ? error?.details : { ...error?.details, deliveryUnknown: error.deliveryUnknown },
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
const server = http.createServer(handleRequest);
|
|
1077
|
+
const lanSocket = attachLanSocket(server, { token: options.token, dispatch: handleRequest,
|
|
1078
|
+
uploadsRoot,
|
|
1079
|
+
authorizeDevice: (clientId, credential) => authorizeLanDevice(stateRoot, clientId, credential),
|
|
1080
|
+
onDeviceAuthorizationsChanged: listener => onLanAuthorizationsChanged(stateRoot, listener),
|
|
1081
|
+
onPhoneConnected: (...args) => connectionReporting(stateRoot).connected(...args),
|
|
1082
|
+
onPhoneDisconnected: id => connectionReporting(stateRoot).disconnected(id),
|
|
1083
|
+
onDeviceConnected: (clientId, info) => {
|
|
1084
|
+
try { recordLanConnection(stateRoot, clientId, info); }
|
|
1085
|
+
catch (error) { console.error('记录局域网设备连接失败:', error.message); }
|
|
1086
|
+
},
|
|
1087
|
+
});
|
|
1088
|
+
|
|
772
1089
|
let control;
|
|
773
|
-
|
|
1090
|
+
const powerManager = createPowerManager(stateRoot);
|
|
1091
|
+
runtimeDiagnostic('service.starting', { platform: process.platform, nodeVersion: process.version });
|
|
774
1092
|
void managedAppServer.start();
|
|
775
1093
|
executionHealth.start();
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
1094
|
+
runtimeDiscovery.start();
|
|
1095
|
+
server.on('error', error => {
|
|
1096
|
+
console.error('桌面服务监听失败:', error.message);
|
|
1097
|
+
process.exit(1);
|
|
1098
|
+
});
|
|
1099
|
+
server.listen(options.port, options.lan ? '0.0.0.0' : '127.0.0.1', async () => {
|
|
1100
|
+
try {
|
|
1101
|
+
await powerManager.start();
|
|
1102
|
+
if (process.env.CODEX_REMOTE_INSTANCE && process.env.CODEX_REMOTE_CONTROL_SECRET && process.env.CODEX_REMOTE_READY_PATH) {
|
|
783
1103
|
control = await openControl({ instanceId: process.env.CODEX_REMOTE_INSTANCE,
|
|
784
1104
|
secret: process.env.CODEX_REMOTE_CONTROL_SECRET, shutdown: shutDown, actions: {
|
|
785
1105
|
'refresh-execution': refreshExecution,
|
|
1106
|
+
'keep-awake-status': () => powerManager.snapshot(),
|
|
1107
|
+
'keep-awake-enable': () => powerManager.setEnabled(true),
|
|
1108
|
+
'keep-awake-disable': () => powerManager.setEnabled(false),
|
|
1109
|
+
'relay-start': () => relayManager.run('relay-start'),
|
|
1110
|
+
'relay-status': () => relayManager.run('relay-status'),
|
|
1111
|
+
'relay-stop': () => relayManager.run('relay-stop'),
|
|
1112
|
+
'relay-pair': () => relayManager.run('relay-pair'),
|
|
1113
|
+
'relay-revoke': () => relayManager.run('relay-revoke'),
|
|
1114
|
+
'invite-create': details => relayManager.run('invite-create', details),
|
|
1115
|
+
'invite-list': () => relayManager.run('invite-list'),
|
|
1116
|
+
'invite-revoke': details => relayManager.run('invite-revoke', details),
|
|
1117
|
+
'devices-list': () => relayManager.run('devices-list'),
|
|
1118
|
+
'device-revoke': details => relayManager.run('device-revoke', details),
|
|
786
1119
|
'restart-managed-app-server': () => {
|
|
787
1120
|
const state = managedAppServer.snapshot();
|
|
788
1121
|
return state.launcherRestartRequired ? managedAppServer.restart(crypto.randomUUID()) : state;
|
|
789
1122
|
},
|
|
1123
|
+
'restart-managed-app-server-confirmed': () => managedAppServer.restart(crypto.randomUUID()),
|
|
790
1124
|
} });
|
|
791
|
-
writeRecord(process.env.CODEX_REMOTE_READY_PATH, { instanceId: process.env.CODEX_REMOTE_INSTANCE,
|
|
792
|
-
pid: process.pid, controlPort: control.port });
|
|
793
|
-
}
|
|
794
|
-
} catch (error) {
|
|
795
|
-
console.error('
|
|
796
|
-
process.exit(1);
|
|
797
|
-
}
|
|
798
|
-
console.log(`Code Relax
|
|
799
|
-
if (options.lan) {
|
|
800
|
-
console.log('LAN 模式使用鉴权 WebSocket,仅适合受信任局域网测试,不要暴露到公网。');
|
|
801
|
-
}
|
|
802
|
-
});
|
|
803
|
-
|
|
804
|
-
let shuttingDown = false;
|
|
805
|
-
async function shutDown() {
|
|
806
|
-
if (shuttingDown) return;
|
|
807
|
-
shuttingDown = true;
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
1125
|
+
writeRecord(process.env.CODEX_REMOTE_READY_PATH, { instanceId: process.env.CODEX_REMOTE_INSTANCE,
|
|
1126
|
+
pid: process.pid, controlPort: control.port });
|
|
1127
|
+
}
|
|
1128
|
+
} catch (error) {
|
|
1129
|
+
console.error('桌面服务管理通道启动失败:', error.message);
|
|
1130
|
+
process.exit(1);
|
|
1131
|
+
}
|
|
1132
|
+
console.log(`Code Relax 桌面服务已启动:http://127.0.0.1:${options.port}/`);
|
|
1133
|
+
if (options.lan) {
|
|
1134
|
+
console.log('LAN 模式使用鉴权 WebSocket,仅适合受信任局域网测试,不要暴露到公网。');
|
|
1135
|
+
}
|
|
1136
|
+
});
|
|
1137
|
+
|
|
1138
|
+
let shuttingDown = false;
|
|
1139
|
+
async function shutDown() {
|
|
1140
|
+
if (shuttingDown) return;
|
|
1141
|
+
shuttingDown = true;
|
|
1142
|
+
await powerManager.close();
|
|
1143
|
+
desktopHelper?.release();
|
|
1144
|
+
lanSocket.close();
|
|
1145
|
+
server.close();
|
|
811
1146
|
executionHealth?.stop();
|
|
1147
|
+
runtimeDiscovery.stop();
|
|
1148
|
+
await relayManager.close();
|
|
1149
|
+
dotsServer.close();
|
|
1150
|
+
dotsChat.close();
|
|
812
1151
|
managedAppServer.close();
|
|
813
|
-
await
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
process.on('
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
if (!ALLOWED_TOOLS.has(tool)) {
|
|
823
|
-
throw new RequestError(403, `工具 ${tool} 不在 Bridge 允许列表中。`);
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
const invocationId = crypto.randomUUID();
|
|
827
|
-
const rpc = await callDesktop('tools/call', {
|
|
828
|
-
arguments: argumentsValue,
|
|
829
|
-
callId: `codex-remote-${invocationId}`,
|
|
830
|
-
namespace: 'codex_app',
|
|
831
|
-
threadId: sourceThreadId,
|
|
832
|
-
tool,
|
|
833
|
-
turnId: `codex-remote-turn-${invocationId}`,
|
|
834
|
-
}, timeoutMs, targetPipe);
|
|
835
|
-
|
|
836
|
-
const result = rpc.result;
|
|
837
|
-
if (!result || typeof result.success !== 'boolean') {
|
|
838
|
-
throw new BridgeError('Codex Desktop 没有返回有效的工具结果。', rpc);
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
const items = Array.isArray(result.contentItems) ? result.contentItems : [];
|
|
842
|
-
let data = items;
|
|
843
|
-
if (items.length === 1 && items[0]?.type === 'inputText' && typeof items[0].text === 'string') {
|
|
844
|
-
try {
|
|
845
|
-
data = JSON.parse(items[0].text);
|
|
846
|
-
} catch {
|
|
847
|
-
data = items[0].text;
|
|
848
|
-
}
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
return { success: result.success, data };
|
|
852
|
-
}
|
|
853
|
-
|
|
854
|
-
function callDesktop(method, params, timeoutMs, targetPipe = desktopMonitor?.pipe || pipePath) {
|
|
855
|
-
if (!targetPipe) return Promise.reject(new RequestError(503, 'Desktop 工具通道尚未就绪。'));
|
|
856
|
-
return new Promise((resolve, reject) => {
|
|
857
|
-
const socket = net.createConnection(targetPipe);
|
|
858
|
-
const requestId = ++nextRequestId;
|
|
859
|
-
const payload = Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: requestId, method, params }), 'utf8');
|
|
860
|
-
const header = Buffer.allocUnsafe(4);
|
|
861
|
-
header.writeUInt32LE(payload.length, 0);
|
|
862
|
-
let pending = Buffer.alloc(0);
|
|
863
|
-
let expectedLength = null;
|
|
864
|
-
let settled = false;
|
|
865
|
-
|
|
866
|
-
const finish = (callback, value) => {
|
|
867
|
-
if (settled) return;
|
|
868
|
-
settled = true;
|
|
869
|
-
clearTimeout(timer);
|
|
870
|
-
socket.destroy();
|
|
871
|
-
callback(value);
|
|
872
|
-
};
|
|
873
|
-
|
|
874
|
-
const timer = setTimeout(() => {
|
|
875
|
-
finish(reject, new BridgeError('等待 Codex Desktop 响应超时。'));
|
|
876
|
-
}, timeoutMs);
|
|
877
|
-
|
|
878
|
-
socket.once('connect', () => socket.write(Buffer.concat([header, payload])));
|
|
879
|
-
socket.on('data', chunk => {
|
|
880
|
-
pending = Buffer.concat([pending, chunk]);
|
|
881
|
-
if (expectedLength === null && pending.length >= 4) {
|
|
882
|
-
expectedLength = pending.readUInt32LE(0);
|
|
883
|
-
pending = pending.subarray(4);
|
|
884
|
-
if (expectedLength <= 0 || expectedLength > MAX_FRAME_BYTES) {
|
|
885
|
-
finish(reject, new BridgeError(`Codex Desktop 返回了无效帧长度:${expectedLength}。`));
|
|
886
|
-
return;
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
if (expectedLength !== null && pending.length >= expectedLength) {
|
|
891
|
-
try {
|
|
892
|
-
const responseValue = JSON.parse(pending.subarray(0, expectedLength).toString('utf8'));
|
|
893
|
-
if (responseValue.error) {
|
|
894
|
-
finish(reject, new BridgeError('Codex Desktop 工具调用失败。', responseValue.error));
|
|
895
|
-
} else if (responseValue.id !== requestId) {
|
|
896
|
-
finish(reject, new BridgeError('Codex Desktop 返回了不匹配的请求 ID。'));
|
|
897
|
-
} else {
|
|
898
|
-
finish(resolve, responseValue);
|
|
899
|
-
}
|
|
900
|
-
} catch (error) {
|
|
901
|
-
finish(reject, new BridgeError('无法解析 Codex Desktop 响应。', undefined, error));
|
|
902
|
-
}
|
|
903
|
-
}
|
|
904
|
-
});
|
|
905
|
-
socket.once('error', error => finish(reject, new BridgeError(
|
|
906
|
-
'无法连接 Codex Desktop Pipe。桌面版可能已重启,请重新启动 Bridge。',
|
|
907
|
-
undefined,
|
|
908
|
-
error,
|
|
909
|
-
)));
|
|
910
|
-
socket.once('close', () => {
|
|
911
|
-
if (!settled) finish(reject, new BridgeError('Codex Desktop Pipe 在返回结果前关闭。'));
|
|
912
|
-
});
|
|
913
|
-
});
|
|
914
|
-
}
|
|
915
|
-
|
|
916
|
-
function sendToolResult(response, result) {
|
|
917
|
-
if (result.success) {
|
|
918
|
-
sendJson(response, 200, result.data);
|
|
919
|
-
} else {
|
|
920
|
-
sendJson(response, 502, { error: 'Codex Desktop 工具返回失败。', details: result.data });
|
|
921
|
-
}
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
function appServerBridgeStatus() {
|
|
925
|
-
return {
|
|
926
|
-
...appServer.snapshot(),
|
|
927
|
-
platformFamily: appServer.initializeResult?.platformFamily || null,
|
|
928
|
-
platformOs: appServer.initializeResult?.platformOs || null,
|
|
929
|
-
taskCount: appServerTasks.store.list().length,
|
|
930
|
-
ownershipError: appServerTasks.store.loadError?.message || null,
|
|
931
|
-
};
|
|
932
|
-
}
|
|
933
|
-
|
|
934
|
-
function readThreadArguments(url, threadId, defaultTurnLimit, defaultOutputLimit = 4_000) {
|
|
935
|
-
const argumentsValue = {
|
|
936
|
-
threadId,
|
|
937
|
-
turnLimit: boundedInteger(url.searchParams.get('turnLimit'), defaultTurnLimit, 1, 10),
|
|
938
|
-
includeOutputs: booleanValue(url.searchParams.get('includeOutputs'), true),
|
|
939
|
-
maxOutputCharsPerItem: boundedInteger(
|
|
940
|
-
url.searchParams.get('maxOutputCharsPerItem'),
|
|
941
|
-
defaultOutputLimit,
|
|
942
|
-
500,
|
|
943
|
-
100_000,
|
|
944
|
-
),
|
|
945
|
-
};
|
|
946
|
-
const hostId = url.searchParams.get('hostId')?.trim();
|
|
947
|
-
if (hostId) argumentsValue.hostId = hostId;
|
|
948
|
-
return argumentsValue;
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
function readContextUsage(threadId) {
|
|
952
|
-
if (!/^[0-9a-f]{8}-[0-9a-f-]{20,55}$/i.test(threadId)) {
|
|
953
|
-
return { available: false };
|
|
954
|
-
}
|
|
955
|
-
const sessionPath = findSessionPath(threadId);
|
|
956
|
-
if (!sessionPath) return { available: false };
|
|
957
|
-
|
|
958
|
-
let handle;
|
|
959
|
-
try {
|
|
960
|
-
const stat = fs.statSync(sessionPath);
|
|
961
|
-
const readLength = Math.min(stat.size, MAX_CONTEXT_TAIL_BYTES);
|
|
962
|
-
const buffer = Buffer.allocUnsafe(readLength);
|
|
963
|
-
handle = fs.openSync(sessionPath, 'r');
|
|
964
|
-
fs.readSync(handle, buffer, 0, readLength, stat.size - readLength);
|
|
965
|
-
const lines = buffer.toString('utf8').split(/\r?\n/);
|
|
966
|
-
let usage = null;
|
|
967
|
-
let settings = null;
|
|
968
|
-
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
969
|
-
let event;
|
|
970
|
-
if (!usage && lines[index].includes('"token_count"')) {
|
|
971
|
-
try { event = JSON.parse(lines[index]); } catch { event = null; }
|
|
972
|
-
if (event?.type === 'event_msg' && event?.payload?.type === 'token_count') {
|
|
973
|
-
const usedTokens = Number(event.payload.info?.last_token_usage?.total_tokens);
|
|
974
|
-
const contextWindow = Number(event.payload.info?.model_context_window);
|
|
975
|
-
if (Number.isFinite(usedTokens) && Number.isFinite(contextWindow) && contextWindow > 0) {
|
|
976
|
-
usage = {
|
|
977
|
-
available: true,
|
|
978
|
-
usedTokens,
|
|
979
|
-
contextWindow,
|
|
980
|
-
remainingTokens: Math.max(0, contextWindow - usedTokens),
|
|
981
|
-
usedPercent: Math.min(100, Math.max(0, usedTokens / contextWindow * 100)),
|
|
982
|
-
updatedAt: event.timestamp || null,
|
|
983
|
-
};
|
|
984
|
-
}
|
|
985
|
-
}
|
|
986
|
-
}
|
|
987
|
-
if (!settings && lines[index].includes('"type":"turn_context"')) {
|
|
988
|
-
try { event = JSON.parse(lines[index]); } catch { event = null; }
|
|
989
|
-
settings = turnSettings(event);
|
|
990
|
-
}
|
|
991
|
-
if (usage && settings) break;
|
|
992
|
-
}
|
|
993
|
-
settings ||= sessionSettingsCache.get(sessionPath) || readLatestTurnSettings(sessionPath);
|
|
994
|
-
if (settings) sessionSettingsCache.set(sessionPath, settings);
|
|
995
|
-
if (usage) return { ...usage, ...settings };
|
|
996
|
-
if (settings) return { available: false, ...settings };
|
|
997
|
-
} catch {
|
|
998
|
-
sessionPathCache.delete(threadId);
|
|
999
|
-
} finally {
|
|
1000
|
-
if (handle !== undefined) fs.closeSync(handle);
|
|
1001
|
-
}
|
|
1002
|
-
return { available: false };
|
|
1003
|
-
}
|
|
1004
|
-
|
|
1005
|
-
function readLatestTurnSettings(sessionPath) {
|
|
1006
|
-
let handle;
|
|
1007
|
-
try {
|
|
1008
|
-
const stat = fs.statSync(sessionPath);
|
|
1009
|
-
const readLength = Math.min(stat.size, MAX_SETTINGS_SCAN_BYTES);
|
|
1010
|
-
const buffer = Buffer.allocUnsafe(readLength);
|
|
1011
|
-
handle = fs.openSync(sessionPath, 'r');
|
|
1012
|
-
fs.readSync(handle, buffer, 0, readLength, stat.size - readLength);
|
|
1013
|
-
const text = buffer.toString('utf8');
|
|
1014
|
-
let searchFrom = text.length;
|
|
1015
|
-
while (searchFrom > 0) {
|
|
1016
|
-
const marker = text.lastIndexOf('"type":"turn_context"', searchFrom);
|
|
1017
|
-
if (marker < 0) break;
|
|
1018
|
-
const lineStart = text.lastIndexOf('\n', marker) + 1;
|
|
1019
|
-
const nextLine = text.indexOf('\n', marker);
|
|
1020
|
-
const lineEnd = nextLine < 0 ? text.length : nextLine;
|
|
1021
|
-
let event;
|
|
1022
|
-
try { event = JSON.parse(text.slice(lineStart, lineEnd)); } catch { event = null; }
|
|
1023
|
-
const settings = turnSettings(event);
|
|
1024
|
-
if (settings) return settings;
|
|
1025
|
-
searchFrom = Math.max(0, lineStart - 1);
|
|
1026
|
-
}
|
|
1027
|
-
} catch {
|
|
1028
|
-
return null;
|
|
1029
|
-
} finally {
|
|
1030
|
-
if (handle !== undefined) fs.closeSync(handle);
|
|
1031
|
-
}
|
|
1032
|
-
return null;
|
|
1033
|
-
}
|
|
1034
|
-
|
|
1035
|
-
function turnSettings(event) {
|
|
1036
|
-
if (event?.type !== 'turn_context') return null;
|
|
1037
|
-
const model = typeof event.payload?.model === 'string' && /^[a-z0-9.-]{1,80}$/i.test(event.payload.model)
|
|
1038
|
-
? event.payload.model
|
|
1039
|
-
: '';
|
|
1040
|
-
const thinking = typeof event.payload?.effort === 'string' && /^[a-z0-9_-]{1,32}$/i.test(event.payload.effort)
|
|
1041
|
-
? event.payload.effort
|
|
1042
|
-
: '';
|
|
1043
|
-
return model || thinking ? { model, thinking } : null;
|
|
1044
|
-
}
|
|
1045
|
-
|
|
1046
|
-
function findSessionPath(threadId) {
|
|
1047
|
-
const cached = sessionPathCache.get(threadId);
|
|
1048
|
-
if (cached && fs.existsSync(cached)) return cached;
|
|
1049
|
-
if (!fs.existsSync(sessionsRoot)) return null;
|
|
1050
|
-
|
|
1051
|
-
const suffix = `-${threadId}.jsonl`.toLowerCase();
|
|
1052
|
-
const directories = [sessionsRoot];
|
|
1053
|
-
while (directories.length) {
|
|
1054
|
-
const directory = directories.pop();
|
|
1055
|
-
let entries;
|
|
1056
|
-
try {
|
|
1057
|
-
entries = fs.readdirSync(directory, { withFileTypes: true });
|
|
1058
|
-
} catch {
|
|
1059
|
-
continue;
|
|
1060
|
-
}
|
|
1061
|
-
for (const entry of entries) {
|
|
1062
|
-
const fullPath = path.join(directory, entry.name);
|
|
1063
|
-
if (entry.isDirectory()) directories.push(fullPath);
|
|
1064
|
-
if (entry.isFile() && entry.name.toLowerCase().endsWith(suffix)) {
|
|
1065
|
-
sessionPathCache.set(threadId, fullPath);
|
|
1066
|
-
return fullPath;
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
1069
|
-
}
|
|
1070
|
-
return null;
|
|
1071
|
-
}
|
|
1072
|
-
|
|
1073
|
-
function enrichTimelineWithLocalActivity(timeline, threadId) {
|
|
1074
|
-
const turn = timeline.turns.at(-1);
|
|
1075
|
-
if (!turn || turn.status !== 'inProgress') return;
|
|
1076
|
-
if (turn.entries.some(entry => entry?.type === 'activity' && entry.status === 'inProgress')) return;
|
|
1077
|
-
const pending = readPendingLocalActivity(threadId);
|
|
1078
|
-
if (!pending || (pending.turnId && pending.turnId !== turn.id)) return;
|
|
1079
|
-
turn.entries.push(pending.entry);
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
function readPendingLocalActivity(threadId) {
|
|
1083
|
-
const sessionPath = findSessionPath(threadId);
|
|
1084
|
-
if (!sessionPath) return null;
|
|
1085
|
-
let handle;
|
|
1086
|
-
try {
|
|
1087
|
-
const stat = fs.statSync(sessionPath);
|
|
1088
|
-
const cacheKey = `${stat.size}:${stat.mtimeMs}`;
|
|
1089
|
-
const cached = liveActivityCache.get(sessionPath);
|
|
1090
|
-
if (cached?.key === cacheKey) return cached.value;
|
|
1091
|
-
const readLength = Math.min(stat.size, MAX_LIVE_ACTIVITY_TAIL_BYTES);
|
|
1092
|
-
const buffer = Buffer.allocUnsafe(readLength);
|
|
1093
|
-
handle = fs.openSync(sessionPath, 'r');
|
|
1094
|
-
fs.readSync(handle, buffer, 0, readLength, stat.size - readLength);
|
|
1095
|
-
const lines = buffer.toString('utf8').split(/\r?\n/);
|
|
1096
|
-
if (readLength < stat.size) lines.shift();
|
|
1097
|
-
const pending = new Map();
|
|
1098
|
-
for (const line of lines) {
|
|
1099
|
-
if (!line.includes('"custom_tool_call')) continue;
|
|
1100
|
-
let event;
|
|
1101
|
-
try { event = JSON.parse(line); } catch { continue; }
|
|
1102
|
-
if (event?.type !== 'response_item') continue;
|
|
1103
|
-
const payload = event.payload;
|
|
1104
|
-
const callId = payload?.call_id;
|
|
1105
|
-
if (!callId) continue;
|
|
1106
|
-
if (payload.type === 'custom_tool_call') pending.set(callId, payload);
|
|
1107
|
-
if (payload.type === 'custom_tool_call_output') pending.delete(callId);
|
|
1108
|
-
}
|
|
1109
|
-
const payload = [...pending.values()].at(-1);
|
|
1110
|
-
const value = payload ? pendingActivity(payload) : null;
|
|
1111
|
-
liveActivityCache.set(sessionPath, { key: cacheKey, value });
|
|
1112
|
-
return value;
|
|
1113
|
-
} catch {
|
|
1114
|
-
liveActivityCache.delete(sessionPath);
|
|
1115
|
-
return null;
|
|
1116
|
-
} finally {
|
|
1117
|
-
if (handle !== undefined) fs.closeSync(handle);
|
|
1118
|
-
}
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
function pendingActivity(payload) {
|
|
1122
|
-
const input = typeof payload.input === 'string' ? payload.input : '';
|
|
1123
|
-
const nestedTool = input.match(/tools\.([A-Za-z0-9_]+)\s*\(/)?.[1] || payload.name || 'tool';
|
|
1124
|
-
const id = `live:${payload.call_id}`;
|
|
1125
|
-
const common = { type: 'activity', id, status: 'inProgress', transient: true };
|
|
1126
|
-
const turnId = payload.internal_chat_message_metadata_passthrough?.turn_id || '';
|
|
1127
|
-
if (nestedTool === 'exec_command') {
|
|
1128
|
-
return {
|
|
1129
|
-
turnId,
|
|
1130
|
-
entry: {
|
|
1131
|
-
...common,
|
|
1132
|
-
kind: 'command',
|
|
1133
|
-
title: '命令',
|
|
1134
|
-
command: jsonStringField(input, 'cmd'),
|
|
1135
|
-
cwd: jsonStringField(input, 'workdir'),
|
|
1136
|
-
},
|
|
1137
|
-
};
|
|
1138
|
-
}
|
|
1139
|
-
if (nestedTool === 'apply_patch') {
|
|
1140
|
-
return { turnId, entry: { ...common, kind: 'fileChange', title: '文件修改', changes: [] } };
|
|
1141
|
-
}
|
|
1142
|
-
if (nestedTool === 'web__run') {
|
|
1143
|
-
return {
|
|
1144
|
-
turnId,
|
|
1145
|
-
entry: { ...common, kind: 'webSearch', title: '网页搜索', query: jsonStringField(input, 'q') },
|
|
1146
|
-
};
|
|
1147
|
-
}
|
|
1148
|
-
if (nestedTool === 'view_image') {
|
|
1149
|
-
return {
|
|
1150
|
-
turnId,
|
|
1151
|
-
entry: { ...common, kind: 'imageView', title: '查看图片', path: jsonStringField(input, 'path') },
|
|
1152
|
-
};
|
|
1153
|
-
}
|
|
1154
|
-
const parts = nestedTool.replace(/^mcp__/, '').split('__');
|
|
1155
|
-
return {
|
|
1156
|
-
turnId,
|
|
1157
|
-
entry: {
|
|
1158
|
-
...common,
|
|
1159
|
-
kind: 'tool',
|
|
1160
|
-
title: '工具',
|
|
1161
|
-
server: parts.length > 1 ? parts.shift() : 'functions',
|
|
1162
|
-
tool: parts.join('/') || nestedTool,
|
|
1163
|
-
arguments: {},
|
|
1164
|
-
},
|
|
1165
|
-
};
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
function jsonStringField(source, field) {
|
|
1169
|
-
const pattern = new RegExp(`(?:["']${field}["']|${field})\\s*:\\s*("(?:\\\\.|[^"\\\\])*")`);
|
|
1170
|
-
const match = pattern.exec(source);
|
|
1171
|
-
if (!match) return '';
|
|
1172
|
-
try { return JSON.parse(match[1]); } catch { return ''; }
|
|
1173
|
-
}
|
|
1174
|
-
|
|
1175
|
-
function messagePayload(body) {
|
|
1176
|
-
const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
|
|
1177
|
-
if (body.images !== undefined && (!Array.isArray(body.images) || body.images.length > 4)) {
|
|
1178
|
-
throw new RequestError(400, '每条消息最多 4 张图片。');
|
|
1179
|
-
}
|
|
1180
|
-
const images = (body.images || []).map(id => {
|
|
1181
|
-
if (typeof id === 'string' && id.startsWith('data:')) return validateInlineImage(id);
|
|
1182
|
-
if (typeof id !== 'string' || !/^[a-f0-9]{64}$/.test(id)) throw new RequestError(400, '无效的图片标识。');
|
|
1183
|
-
const webpFile = path.join(uploadsRoot, `${id}.webp`);
|
|
1184
|
-
const file = fs.existsSync(webpFile) ? webpFile : path.join(uploadsRoot, `${id}.png`);
|
|
1185
|
-
if (!fs.existsSync(file)) throw new RequestError(400, '图片不存在,请重新添加。');
|
|
1186
|
-
return file;
|
|
1187
|
-
});
|
|
1188
|
-
if (images.filter(image => image.startsWith('data:')).reduce((size, image) => size + Buffer.byteLength(image.slice(image.indexOf(',') + 1), 'base64'), 0) > 8 * 1024 * 1024) throw new RequestError(413, '本条消息图片合计不能超过 8 MiB。');
|
|
1189
|
-
if (!prompt && !images.length) throw new RequestError(400, 'prompt 不能为空。');
|
|
1190
|
-
if (prompt.length > 32_000) throw new RequestError(400, 'prompt 不能超过 32000 个字符。');
|
|
1191
|
-
|
|
1192
|
-
const payload = { prompt, images };
|
|
1193
|
-
if (typeof body.hostId === 'string' && body.hostId.trim()) payload.hostId = body.hostId.trim();
|
|
1194
|
-
if (typeof body.model === 'string' && body.model.trim()) {
|
|
1195
|
-
const model = body.model.trim();
|
|
1196
|
-
if (!ALLOWED_MODELS.has(model)) throw new RequestError(400, '不支持的模型。');
|
|
1197
|
-
payload.model = model;
|
|
1198
|
-
}
|
|
1199
|
-
if (typeof body.thinking === 'string' && body.thinking.trim()) {
|
|
1200
|
-
const thinking = body.thinking.trim();
|
|
1201
|
-
if (!ALLOWED_THINKING.has(thinking)) throw new RequestError(400, '不支持的推理强度。');
|
|
1202
|
-
if ((payload.model === 'gpt-5.5' || payload.model === 'gpt-5.3-codex-spark')
|
|
1203
|
-
&& (thinking === 'max' || thinking === 'ultra')) {
|
|
1204
|
-
throw new RequestError(400, '所选模型不支持该推理强度。');
|
|
1205
|
-
}
|
|
1206
|
-
payload.thinking = thinking;
|
|
1207
|
-
}
|
|
1208
|
-
return payload;
|
|
1209
|
-
}
|
|
1210
|
-
|
|
1211
|
-
async function messageArguments(threadId, body) {
|
|
1212
|
-
const payload = messagePayload(body);
|
|
1213
|
-
payload.images = await Promise.all(payload.images.map(image => image.startsWith('data:') ? persistLegacyImage(image, uploadsRoot) : image));
|
|
1214
|
-
let prompt = payload.prompt;
|
|
1215
|
-
if (payload.images.length) {
|
|
1216
|
-
prompt += (prompt ? '\n\n' : '') + payload.images
|
|
1217
|
-
.map((file, index) => `})`)
|
|
1218
|
-
.join('\n\n');
|
|
1219
|
-
}
|
|
1220
|
-
const argumentsValue = { threadId, prompt };
|
|
1221
|
-
if (payload.hostId) argumentsValue.hostId = payload.hostId;
|
|
1222
|
-
if (payload.model) argumentsValue.model = payload.model;
|
|
1223
|
-
if (payload.thinking) argumentsValue.thinking = payload.thinking;
|
|
1224
|
-
return argumentsValue;
|
|
1225
|
-
}
|
|
1226
|
-
|
|
1227
|
-
function usesSharedTask(body) {
|
|
1228
|
-
return Boolean(sharedServer && (!body.hostId || body.hostId === 'local'));
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
|
-
function appServerTurnArguments(threadId, body) {
|
|
1232
|
-
const payload = messagePayload(body);
|
|
1233
|
-
const input = [];
|
|
1234
|
-
if (payload.prompt) input.push({ type: 'text', text: payload.prompt });
|
|
1235
|
-
for (const image of payload.images) input.push(image.startsWith('data:') ? { type: 'image', url: image } : { type: 'localImage', path: image });
|
|
1236
|
-
const value = { threadId, input };
|
|
1237
|
-
if (typeof body.clientUserMessageId === 'string' && /^[a-f0-9]{32}$/.test(body.clientUserMessageId)) value.clientUserMessageId = body.clientUserMessageId;
|
|
1238
|
-
if (payload.model) value.model = payload.model;
|
|
1239
|
-
if (payload.thinking) value.effort = payload.thinking;
|
|
1240
|
-
return value;
|
|
1241
|
-
}
|
|
1242
|
-
|
|
1243
|
-
function messageDisplayText(body) {
|
|
1244
|
-
const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
|
|
1245
|
-
const imageCount = Array.isArray(body.images) ? body.images.length : 0;
|
|
1246
|
-
return prompt || (imageCount ? `[${imageCount} 张图片]` : '');
|
|
1247
|
-
}
|
|
1248
|
-
|
|
1249
|
-
function createThreadBody(body) {
|
|
1250
|
-
const payload = messagePayload(body);
|
|
1251
|
-
return { ...body, prompt: payload.prompt, transport: body.transport === 'app-server' ? 'app-server' : 'desktop-tools' };
|
|
1252
|
-
}
|
|
1253
|
-
|
|
1254
|
-
function appServerProjectTarget(projectId, projects) {
|
|
1255
|
-
if (projectId === '__unassigned__') return appServerEvents.projectlessThreadTarget(projectRoot);
|
|
1256
|
-
const project = projects.find(item => item?.projectId === projectId);
|
|
1257
|
-
if (!project) throw new RequestError(404, '没有找到对应项目。');
|
|
1258
|
-
if (project.hostId && project.hostId !== 'local') {
|
|
1259
|
-
throw new RequestError(400, '独立 app-server 当前只支持本机项目。');
|
|
1260
|
-
}
|
|
1261
|
-
if (typeof project.path !== 'string' || !path.isAbsolute(project.path)) {
|
|
1262
|
-
throw new RequestError(400, '项目没有可用的本机路径。');
|
|
1263
|
-
}
|
|
1264
|
-
return { projectId, cwd: project.path };
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
function mergeThreadCatalog(catalog, appThreads, limit, sharedSnapshot = Boolean(sharedServer)) {
|
|
1268
|
-
const owned = new Map(appThreads.map(thread => [thread.id, thread]));
|
|
1269
|
-
const pinnedThreads = (catalog.pinnedThreads || []).map(thread => owned.get(thread.id) || thread);
|
|
1270
|
-
const pinnedIds = new Set(pinnedThreads.map(thread => thread.id));
|
|
1271
|
-
if (sharedSnapshot) {
|
|
1272
|
-
const listed = new Set([...pinnedIds, ...(catalog.threads || []).map(thread => thread.id)]);
|
|
1273
|
-
const threads = (catalog.threads || []).map(thread => owned.get(thread.id) || thread);
|
|
1274
|
-
threads.push(...appThreads.filter(thread => !listed.has(thread.id)));
|
|
1275
|
-
threads.sort((left, right) => threadRecency(right) - threadRecency(left));
|
|
1276
|
-
return { ...catalog, pinnedThreads: [], threads: threads.slice(0, limit) };
|
|
1152
|
+
await control?.close();
|
|
1153
|
+
process.exit(0);
|
|
1154
|
+
}
|
|
1155
|
+
process.on('SIGTERM', shutDown);
|
|
1156
|
+
process.on('SIGINT', shutDown);
|
|
1157
|
+
|
|
1158
|
+
function readContextUsage(threadId) {
|
|
1159
|
+
if (!/^[0-9a-f]{8}-[0-9a-f-]{20,55}$/i.test(threadId)) {
|
|
1160
|
+
return { available: false };
|
|
1277
1161
|
}
|
|
1278
|
-
const
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
}
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
const
|
|
1347
|
-
if (
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
if (
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
}
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
if (
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
}
|
|
1480
|
-
if (timeline.thread.status === 'active' || update.turn?.status === 'inProgress') {
|
|
1481
|
-
intervalMs = 1_000;
|
|
1482
|
-
}
|
|
1483
|
-
} catch (error) {
|
|
1484
|
-
sendEvent(response, 'bridge-error', {
|
|
1485
|
-
error: error instanceof Error ? error.message : String(error),
|
|
1486
|
-
});
|
|
1487
|
-
intervalMs = 3_000;
|
|
1488
|
-
}
|
|
1489
|
-
|
|
1490
|
-
await delay(intervalMs);
|
|
1491
|
-
}
|
|
1492
|
-
|
|
1493
|
-
if (!response.writableEnded) response.end();
|
|
1494
|
-
}
|
|
1495
|
-
|
|
1496
|
-
function sendEvent(response, eventName, value) {
|
|
1497
|
-
if (response.destroyed || response.writableEnded) return;
|
|
1498
|
-
response.event(eventName, value);
|
|
1499
|
-
}
|
|
1500
|
-
|
|
1501
|
-
function normalizeTimeline(data, reverseTurns = true) {
|
|
1502
|
-
const source = data && typeof data === 'object' ? data : {};
|
|
1503
|
-
const sourceTurns = Array.isArray(source.turns) ? source.turns : source.thread?.turns;
|
|
1504
|
-
const turns = Array.isArray(sourceTurns) ? sourceTurns.map(normalizeTurn) : [];
|
|
1505
|
-
if (reverseTurns) turns.reverse();
|
|
1506
|
-
if (reverseTurns) restoreEmptyTurnMessages(source.thread?.id, turns);
|
|
1507
|
-
return {
|
|
1508
|
-
schemaVersion: 1,
|
|
1509
|
-
thread: normalizeThread(source.thread),
|
|
1510
|
-
turns,
|
|
1511
|
-
};
|
|
1512
|
-
}
|
|
1513
|
-
|
|
1514
|
-
function normalizeAppServerTimeline(thread) {
|
|
1515
|
-
const record = appServerTasks.store.get(thread?.id);
|
|
1516
|
-
return normalizeTimeline({
|
|
1517
|
-
thread: {
|
|
1518
|
-
...thread,
|
|
1519
|
-
title: thread?.name || thread?.title || record?.title || '',
|
|
1520
|
-
projectId: record?.projectId || '',
|
|
1521
|
-
hostId: 'app-server',
|
|
1522
|
-
transport: 'app-server',
|
|
1523
|
-
},
|
|
1524
|
-
}, false);
|
|
1525
|
-
}
|
|
1526
|
-
|
|
1527
|
-
function normalizeSharedTimeline({ thread, nextCursor, sync }) {
|
|
1528
|
-
return { ...normalizeTimeline({ thread: { ...thread, title: thread.name || thread.title || '', hostId: 'local', transport: 'shared-app-server' } }, false),
|
|
1529
|
-
historyView: 'grouped-lazy-skeleton-v11',
|
|
1162
|
+
const sessionPath = findSessionPath(threadId);
|
|
1163
|
+
if (!sessionPath) return { available: false };
|
|
1164
|
+
|
|
1165
|
+
let handle;
|
|
1166
|
+
try {
|
|
1167
|
+
const stat = fs.statSync(sessionPath);
|
|
1168
|
+
const readLength = Math.min(stat.size, MAX_CONTEXT_TAIL_BYTES);
|
|
1169
|
+
const buffer = Buffer.allocUnsafe(readLength);
|
|
1170
|
+
handle = fs.openSync(sessionPath, 'r');
|
|
1171
|
+
fs.readSync(handle, buffer, 0, readLength, stat.size - readLength);
|
|
1172
|
+
const lines = buffer.toString('utf8').split(/\r?\n/);
|
|
1173
|
+
let usage = null;
|
|
1174
|
+
let settings = null;
|
|
1175
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
1176
|
+
let event;
|
|
1177
|
+
if (!usage && lines[index].includes('"token_count"')) {
|
|
1178
|
+
try { event = JSON.parse(lines[index]); } catch { event = null; }
|
|
1179
|
+
if (event?.type === 'event_msg' && event?.payload?.type === 'token_count') {
|
|
1180
|
+
const usedTokens = Number(event.payload.info?.last_token_usage?.total_tokens);
|
|
1181
|
+
const contextWindow = Number(event.payload.info?.model_context_window);
|
|
1182
|
+
if (Number.isFinite(usedTokens) && Number.isFinite(contextWindow) && contextWindow > 0) {
|
|
1183
|
+
usage = {
|
|
1184
|
+
available: true,
|
|
1185
|
+
usedTokens,
|
|
1186
|
+
contextWindow,
|
|
1187
|
+
remainingTokens: Math.max(0, contextWindow - usedTokens),
|
|
1188
|
+
usedPercent: Math.min(100, Math.max(0, usedTokens / contextWindow * 100)),
|
|
1189
|
+
updatedAt: event.timestamp || null,
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
if (!settings && lines[index].includes('"type":"turn_context"')) {
|
|
1195
|
+
try { event = JSON.parse(lines[index]); } catch { event = null; }
|
|
1196
|
+
settings = turnSettings(event);
|
|
1197
|
+
}
|
|
1198
|
+
if (usage && settings) break;
|
|
1199
|
+
}
|
|
1200
|
+
settings ||= sessionSettingsCache.get(sessionPath) || readLatestTurnSettings(sessionPath);
|
|
1201
|
+
if (settings) sessionSettingsCache.set(sessionPath, settings);
|
|
1202
|
+
if (usage) return { ...usage, ...settings };
|
|
1203
|
+
if (settings) return { available: false, ...settings };
|
|
1204
|
+
} catch {
|
|
1205
|
+
sessionPathCache.delete(threadId);
|
|
1206
|
+
} finally {
|
|
1207
|
+
if (handle !== undefined) fs.closeSync(handle);
|
|
1208
|
+
}
|
|
1209
|
+
return { available: false };
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
function readLatestTurnSettings(sessionPath) {
|
|
1213
|
+
let handle;
|
|
1214
|
+
try {
|
|
1215
|
+
const stat = fs.statSync(sessionPath);
|
|
1216
|
+
const readLength = Math.min(stat.size, MAX_SETTINGS_SCAN_BYTES);
|
|
1217
|
+
const buffer = Buffer.allocUnsafe(readLength);
|
|
1218
|
+
handle = fs.openSync(sessionPath, 'r');
|
|
1219
|
+
fs.readSync(handle, buffer, 0, readLength, stat.size - readLength);
|
|
1220
|
+
const text = buffer.toString('utf8');
|
|
1221
|
+
let searchFrom = text.length;
|
|
1222
|
+
while (searchFrom > 0) {
|
|
1223
|
+
const marker = text.lastIndexOf('"type":"turn_context"', searchFrom);
|
|
1224
|
+
if (marker < 0) break;
|
|
1225
|
+
const lineStart = text.lastIndexOf('\n', marker) + 1;
|
|
1226
|
+
const nextLine = text.indexOf('\n', marker);
|
|
1227
|
+
const lineEnd = nextLine < 0 ? text.length : nextLine;
|
|
1228
|
+
let event;
|
|
1229
|
+
try { event = JSON.parse(text.slice(lineStart, lineEnd)); } catch { event = null; }
|
|
1230
|
+
const settings = turnSettings(event);
|
|
1231
|
+
if (settings) return settings;
|
|
1232
|
+
searchFrom = Math.max(0, lineStart - 1);
|
|
1233
|
+
}
|
|
1234
|
+
} catch {
|
|
1235
|
+
return null;
|
|
1236
|
+
} finally {
|
|
1237
|
+
if (handle !== undefined) fs.closeSync(handle);
|
|
1238
|
+
}
|
|
1239
|
+
return null;
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
function turnSettings(event) {
|
|
1243
|
+
if (event?.type !== 'turn_context') return null;
|
|
1244
|
+
const model = typeof event.payload?.model === 'string' && /^[a-z0-9.-]{1,80}$/i.test(event.payload.model)
|
|
1245
|
+
? event.payload.model
|
|
1246
|
+
: '';
|
|
1247
|
+
const thinking = typeof event.payload?.effort === 'string' && /^[a-z0-9_-]{1,32}$/i.test(event.payload.effort)
|
|
1248
|
+
? event.payload.effort
|
|
1249
|
+
: '';
|
|
1250
|
+
return model || thinking ? { model, thinking } : null;
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
function findSessionPath(threadId) {
|
|
1254
|
+
const cached = sessionPathCache.get(threadId);
|
|
1255
|
+
if (cached && fs.existsSync(cached)) return cached;
|
|
1256
|
+
if (!fs.existsSync(sessionsRoot)) return null;
|
|
1257
|
+
|
|
1258
|
+
const suffix = `-${threadId}.jsonl`.toLowerCase();
|
|
1259
|
+
const directories = [sessionsRoot];
|
|
1260
|
+
while (directories.length) {
|
|
1261
|
+
const directory = directories.pop();
|
|
1262
|
+
let entries;
|
|
1263
|
+
try {
|
|
1264
|
+
entries = fs.readdirSync(directory, { withFileTypes: true });
|
|
1265
|
+
} catch {
|
|
1266
|
+
continue;
|
|
1267
|
+
}
|
|
1268
|
+
for (const entry of entries) {
|
|
1269
|
+
const fullPath = path.join(directory, entry.name);
|
|
1270
|
+
if (entry.isDirectory()) directories.push(fullPath);
|
|
1271
|
+
if (entry.isFile() && entry.name.toLowerCase().endsWith(suffix)) {
|
|
1272
|
+
sessionPathCache.set(threadId, fullPath);
|
|
1273
|
+
return fullPath;
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
return null;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
function messagePayload(body) {
|
|
1281
|
+
const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
|
|
1282
|
+
if (body.images !== undefined && (!Array.isArray(body.images) || body.images.length > 4)) {
|
|
1283
|
+
throw new RequestError(400, '每条消息最多 4 张图片。');
|
|
1284
|
+
}
|
|
1285
|
+
const images = (body.images || []).map(id => {
|
|
1286
|
+
if (typeof id === 'string' && id.startsWith('data:')) return validateInlineImage(id);
|
|
1287
|
+
if (typeof id !== 'string' || !/^[a-f0-9]{64}$/.test(id)) throw new RequestError(400, '无效的图片标识。');
|
|
1288
|
+
const webpFile = path.join(uploadsRoot, `${id}.webp`);
|
|
1289
|
+
const file = fs.existsSync(webpFile) ? webpFile : path.join(uploadsRoot, `${id}.png`);
|
|
1290
|
+
if (!fs.existsSync(file)) throw new RequestError(400, '图片不存在,请重新添加。');
|
|
1291
|
+
return file;
|
|
1292
|
+
});
|
|
1293
|
+
for (const input of fileMentions.originalInputs(body)) {
|
|
1294
|
+
const incoming = fs.realpathSync(path.join(uploadsRoot, 'incoming'));
|
|
1295
|
+
const imagePath = fs.realpathSync(input.path);
|
|
1296
|
+
if (path.dirname(imagePath).toLowerCase() !== incoming.toLowerCase()) throw new RequestError(400, '原图必须来自上传目录。');
|
|
1297
|
+
const stat = fs.statSync(imagePath);
|
|
1298
|
+
if (!stat.isFile() || stat.size <= 0) throw new RequestError(400, '原图为空。');
|
|
1299
|
+
images.push(imagePath);
|
|
1300
|
+
}
|
|
1301
|
+
if (images.filter(image => image.startsWith('data:')).reduce((size, image) => size + Buffer.byteLength(image.slice(image.indexOf(',') + 1), 'base64'), 0) > 8 * 1024 * 1024) throw new RequestError(413, '本条消息图片合计不能超过 8 MiB。');
|
|
1302
|
+
if (!prompt && !images.length) throw new RequestError(400, 'prompt 不能为空。');
|
|
1303
|
+
if (prompt.length > 32_000) throw new RequestError(400, 'prompt 不能超过 32000 个字符。');
|
|
1304
|
+
|
|
1305
|
+
const payload = { prompt, images };
|
|
1306
|
+
if (typeof body.hostId === 'string' && body.hostId.trim()) payload.hostId = body.hostId.trim();
|
|
1307
|
+
if (typeof body.model === 'string' && body.model.trim()) {
|
|
1308
|
+
payload.model = body.model.trim();
|
|
1309
|
+
}
|
|
1310
|
+
if (typeof body.thinking === 'string' && body.thinking.trim()) {
|
|
1311
|
+
const thinking = body.thinking.trim();
|
|
1312
|
+
if (!ALLOWED_THINKING.has(thinking)) throw new RequestError(400, '不支持的推理强度。');
|
|
1313
|
+
if ((payload.model === 'gpt-5.5' || payload.model === 'gpt-5.3-codex-spark')
|
|
1314
|
+
&& (thinking === 'max' || thinking === 'ultra')) {
|
|
1315
|
+
throw new RequestError(400, '所选模型不支持该推理强度。');
|
|
1316
|
+
}
|
|
1317
|
+
payload.thinking = thinking;
|
|
1318
|
+
}
|
|
1319
|
+
return payload;
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
function appServerTurnArguments(threadId, body) {
|
|
1323
|
+
const payload = messagePayload(body);
|
|
1324
|
+
const mentioned = payload.hostId === 'durable' ? fileMentions.parse(payload.prompt) : null;
|
|
1325
|
+
if (mentioned?.files.length) payload.prompt = mentioned.text;
|
|
1326
|
+
const input = [];
|
|
1327
|
+
if (payload.prompt) input.push({ type: 'text', text: payload.prompt });
|
|
1328
|
+
for (const image of payload.images) {
|
|
1329
|
+
if (image.startsWith('data:')) input.push({ type: 'image', url: image });
|
|
1330
|
+
else if (payload.hostId === 'durable') {
|
|
1331
|
+
const mimeType = imageMimeType(image);
|
|
1332
|
+
if (!mimeType) throw new RequestError(400, '云端图片格式无效。');
|
|
1333
|
+
input.push({ type: 'image', url: `data:${mimeType};base64,${fs.readFileSync(image).toString('base64')}` });
|
|
1334
|
+
} else input.push({ type: 'localImage', path: image });
|
|
1335
|
+
}
|
|
1336
|
+
const value = { threadId, input, ...appServerEvents.mobileTurnSource(body.clientUserMessageId, body.containsVoiceInput) };
|
|
1337
|
+
if (mentioned?.files.length) value.uploadFiles = mentioned.files;
|
|
1338
|
+
if (typeof body.clientUserMessageId === 'string' && /^[a-f0-9]{32}$/.test(body.clientUserMessageId)) value.clientUserMessageId = body.clientUserMessageId;
|
|
1339
|
+
if (payload.model) value.model = payload.model;
|
|
1340
|
+
if (payload.thinking) value.effort = payload.thinking;
|
|
1341
|
+
return value;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
function normalizeTimeline(data) {
|
|
1345
|
+
const source = data && typeof data === 'object' ? data : {};
|
|
1346
|
+
const sourceTurns = Array.isArray(source.turns) ? source.turns : source.thread?.turns;
|
|
1347
|
+
const turns = Array.isArray(sourceTurns) ? sourceTurns.map(normalizeTurn) : [];
|
|
1348
|
+
return {
|
|
1349
|
+
schemaVersion: 1,
|
|
1350
|
+
thread: normalizeThread(source.thread),
|
|
1351
|
+
turns,
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
function normalizeSharedTimeline({ thread, nextCursor, sync, notModified, incremental }, hostId = thread?.hostId || 'local') {
|
|
1356
|
+
const timeline = normalizeTimeline({ thread: { ...thread, title: thread.name || thread.title || '', hostId,
|
|
1357
|
+
transport: 'shared-app-server' } });
|
|
1358
|
+
return { ...timeline,
|
|
1359
|
+
historyItemCount: (thread.turns || []).reduce((count, turn) => count + (turn.roomMessage ? 1 : turn.items?.length || 0), 0),
|
|
1360
|
+
historyView: thread?.threadSource === 'aeon' ? 'chat-items-v1' : 'item-pages-v1',
|
|
1361
|
+
...(notModified ? { notModified: true } : {}),
|
|
1362
|
+
...(incremental ? { incremental: true } : {}),
|
|
1530
1363
|
...(nextCursor !== undefined ? { nextCursor } : {}), ...(sync ? { sync } : {}) };
|
|
1531
1364
|
}
|
|
1532
|
-
|
|
1533
|
-
function
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
const
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
const
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
if (event.type === 'event_msg' && item?.type === 'task_started') turnId = item.turn_id;
|
|
1553
|
-
if (event.type === 'turn_context') turnId = item?.turn_id;
|
|
1554
|
-
const turn = missing.get(turnId);
|
|
1555
|
-
if (!turn || event.type !== 'response_item') continue;
|
|
1556
|
-
let entry;
|
|
1557
|
-
if (item.type === 'function_call_output' && item.namespace === 'codex_app' && ['create_thread', 'send_message_to_thread'].includes(item.name)) {
|
|
1558
|
-
const text = extractDelegatedInput(item.output);
|
|
1559
|
-
if (text) entry = { type: 'message', id: item.id, role: 'user', source: 'remote', ...splitUploadedImages(text) };
|
|
1560
|
-
} else if (item.type === 'message' && ['user', 'assistant'].includes(item.role) && item.channel !== 'analysis') {
|
|
1561
|
-
const text = (item.content || []).filter(part => ['input_text', 'output_text'].includes(part.type)).map(part => part.text || '').join('\n');
|
|
1562
|
-
if (text) entry = item.role === 'user'
|
|
1563
|
-
? normalizeItem({ type: 'userMessage', id: item.id, content: item.content.map(part => ({ ...part, type: part.type === 'input_text' ? 'text' : part.type })) })
|
|
1564
|
-
: normalizeItem({ type: 'agentMessage', id: item.id, phase: item.phase || item.channel, text });
|
|
1565
|
-
}
|
|
1566
|
-
if (entry) turn.entries.push(entry);
|
|
1567
|
-
}
|
|
1568
|
-
} finally { fs.closeSync(handle); }
|
|
1569
|
-
}
|
|
1570
|
-
|
|
1365
|
+
|
|
1366
|
+
async function prepareSharedTimeline(value, hostId) {
|
|
1367
|
+
if (value.thread?.threadSource !== 'aeon') return normalizeSharedTimeline(value, hostId);
|
|
1368
|
+
const epoch = dotsChat.epoch, threadId = value.thread.id;
|
|
1369
|
+
const current = () => {
|
|
1370
|
+
if (epoch !== dotsChat.epoch) throw new Error('点点连接已变化,请重新同步。');
|
|
1371
|
+
};
|
|
1372
|
+
if (value.notModified) {
|
|
1373
|
+
const record = dotsChat.threads.get(threadId);
|
|
1374
|
+
if (await dotsImages.prepareTimeline(record?.thread)) {
|
|
1375
|
+
current();
|
|
1376
|
+
value = dotsChat.snapshot(threadId, record);
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
const snapshot = structuredClone(value);
|
|
1380
|
+
await dotsImages.prepareTimeline(snapshot.thread);
|
|
1381
|
+
current();
|
|
1382
|
+
return normalizeSharedTimeline(snapshot, hostId);
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1571
1385
|
function normalizeThread(thread) {
|
|
1572
|
-
const source = thread && typeof thread === 'object' ? thread : {};
|
|
1573
|
-
return {
|
|
1386
|
+
const source = thread && typeof thread === 'object' ? thread : {};
|
|
1387
|
+
return {
|
|
1574
1388
|
id: source.id || '',
|
|
1575
1389
|
title: source.name || source.title || source.preview || '',
|
|
1576
1390
|
status: statusText(source.status),
|
|
1577
1391
|
updatedAt: Number(source.updatedAt) || 0,
|
|
1578
1392
|
recencyAt: Number(source.recencyAt ?? source.updatedAt) || 0,
|
|
1579
1393
|
projectId: source.projectId || '',
|
|
1580
|
-
cwd: source.cwd || '',
|
|
1581
|
-
hostId: source.hostId || '',
|
|
1582
|
-
|
|
1394
|
+
cwd: source.cwd || '',
|
|
1395
|
+
hostId: source.hostId || '',
|
|
1396
|
+
threadSource: source.threadSource || '',
|
|
1397
|
+
...(['aeon', 'aeon_child'].includes(source.threadSource) ? { chatRevision: source.chatRevision || '' } : {}),
|
|
1398
|
+
...(source.threadSource === 'aeon' ? { avatar: source.avatar || '', color: source.color || '',
|
|
1399
|
+
chatMessageRevision: source.chatMessageRevision, messagingRoomId: source.messagingRoomId, lastMessageAt: source.lastMessageAt } : {}),
|
|
1400
|
+
transport: source.transport || 'shared-app-server',
|
|
1583
1401
|
readOnly: source.readOnly === true,
|
|
1584
1402
|
readOnlyReason: source.readOnlyReason || '',
|
|
1585
|
-
};
|
|
1586
|
-
}
|
|
1587
|
-
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1588
1406
|
function normalizeTurn(turn) {
|
|
1589
1407
|
const source = turn && typeof turn === 'object' ? turn : {};
|
|
1590
1408
|
const turnId = source.id || '';
|
|
@@ -1596,10 +1414,16 @@ function normalizeTurn(turn) {
|
|
|
1596
1414
|
return {
|
|
1597
1415
|
id: turnId,
|
|
1598
1416
|
status: statusText(source.status),
|
|
1599
|
-
startedAt: source.startedAt || null,
|
|
1600
|
-
completedAt: source.completedAt || null,
|
|
1601
|
-
durationMs: source.durationMs ?? null,
|
|
1417
|
+
startedAt: source.startedAt || null,
|
|
1418
|
+
completedAt: source.completedAt || null,
|
|
1419
|
+
durationMs: source.durationMs ?? null,
|
|
1602
1420
|
error: source.error ?? null,
|
|
1421
|
+
runtimeNotice: source.runtimeNotice ?? null,
|
|
1422
|
+
...(source.itemPage ? { itemPage: source.itemPage } : {}),
|
|
1423
|
+
...(source.roomMessage ? { roomMessage: true } : {}),
|
|
1424
|
+
...(source.deleted ? { deleted: true } : {}),
|
|
1425
|
+
...(source.historyOnly ? { historyOnly: true } : {}),
|
|
1426
|
+
...(source.cacheStub ? { cacheStub: true } : {}),
|
|
1603
1427
|
entries,
|
|
1604
1428
|
};
|
|
1605
1429
|
}
|
|
@@ -1607,70 +1431,61 @@ function normalizeTurn(turn) {
|
|
|
1607
1431
|
function normalizeItem(item) {
|
|
1608
1432
|
if (!item || typeof item !== 'object') return null;
|
|
1609
1433
|
|
|
1610
|
-
if (item.type === '
|
|
1434
|
+
if (item.type === 'approval') {
|
|
1435
|
+
return { ...item, type: 'activity', kind: 'approval', title: item.params?.message || '需要你的批准' };
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
if (item.type === 'contextCompaction') {
|
|
1611
1439
|
return {
|
|
1612
1440
|
type: 'activity',
|
|
1613
1441
|
id: item.id || '',
|
|
1614
|
-
kind: '
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1442
|
+
kind: 'contextCompaction',
|
|
1443
|
+
title: '已自动压缩上下文',
|
|
1444
|
+
};
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
const delegated = appServerEvents.toolDelegation(item);
|
|
1448
|
+
if (delegated) {
|
|
1449
|
+
return {
|
|
1450
|
+
type: 'message', id: item.id || '', role: 'user', source: 'remote',
|
|
1451
|
+
delegation: delegationSource(delegated), ...splitUploadedImages(delegated.input),
|
|
1619
1452
|
};
|
|
1620
1453
|
}
|
|
1621
|
-
|
|
1622
|
-
if (item.type === '
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
};
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
attachments,
|
|
1657
|
-
};
|
|
1658
|
-
}
|
|
1659
|
-
|
|
1660
|
-
if (item.type === 'agentMessage') {
|
|
1661
|
-
return {
|
|
1662
|
-
type: 'message',
|
|
1663
|
-
id: item.id || '',
|
|
1664
|
-
role: 'assistant',
|
|
1665
|
-
phase: item.phase || '',
|
|
1666
|
-
delivery: item.delivery,
|
|
1667
|
-
questions: item.questions,
|
|
1668
|
-
text: item.text || '',
|
|
1669
|
-
imageAssets: markdownImageAssets(item.text || ''),
|
|
1670
|
-
fileAssets: markdownFileAssets(item.text || ''),
|
|
1671
|
-
};
|
|
1672
|
-
}
|
|
1673
|
-
|
|
1454
|
+
|
|
1455
|
+
if (item.type === 'userMessage') {
|
|
1456
|
+
const { text, files, delegation } = extractUserText(item.content);
|
|
1457
|
+
const attachments = [...normalizeAttachments(item.content), ...files.map(file => file.fileId ? normalizeAttachment(file) : ({
|
|
1458
|
+
...file,
|
|
1459
|
+
remotePath: file.path,
|
|
1460
|
+
previewRemotePath: file.previewPath || '',
|
|
1461
|
+
}))];
|
|
1462
|
+
if (!text && !attachments.length) return null;
|
|
1463
|
+
return {
|
|
1464
|
+
clientId: item.clientId,
|
|
1465
|
+
type: 'message',
|
|
1466
|
+
id: item.id || '',
|
|
1467
|
+
role: 'user',
|
|
1468
|
+
text,
|
|
1469
|
+
attachments,
|
|
1470
|
+
...(delegation ? { delegation: delegationSource(delegation) } : {}),
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
if (item.type === 'agentMessage') {
|
|
1475
|
+
return {
|
|
1476
|
+
type: 'message',
|
|
1477
|
+
id: item.id || '',
|
|
1478
|
+
role: 'assistant',
|
|
1479
|
+
phase: item.phase || '',
|
|
1480
|
+
delivery: item.delivery,
|
|
1481
|
+
questions: item.questions,
|
|
1482
|
+
text: item.text || '',
|
|
1483
|
+
attachments: normalizeAttachments(item.attachments),
|
|
1484
|
+
imageAssets: markdownImageAssets(item.text || ''),
|
|
1485
|
+
fileAssets: markdownFileAssets(item.text || ''),
|
|
1486
|
+
};
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1674
1489
|
if (item.type === 'reasoning') {
|
|
1675
1490
|
const detail = Array.isArray(item.summary)
|
|
1676
1491
|
? item.summary.map(summaryText).filter(Boolean).join('\n')
|
|
@@ -1683,7 +1498,7 @@ function normalizeItem(item) {
|
|
|
1683
1498
|
detail,
|
|
1684
1499
|
};
|
|
1685
1500
|
}
|
|
1686
|
-
|
|
1501
|
+
|
|
1687
1502
|
if (item.type === 'commandExecution') {
|
|
1688
1503
|
return {
|
|
1689
1504
|
type: 'activity',
|
|
@@ -1739,10 +1554,10 @@ function normalizeItem(item) {
|
|
|
1739
1554
|
title: '文件修改',
|
|
1740
1555
|
titleOnly: true,
|
|
1741
1556
|
status: statusText(item.status),
|
|
1742
|
-
changes:
|
|
1557
|
+
changes: fileChanges.summarize(item.changes),
|
|
1743
1558
|
};
|
|
1744
1559
|
}
|
|
1745
|
-
|
|
1560
|
+
|
|
1746
1561
|
if (item.type === 'webSearch') {
|
|
1747
1562
|
return {
|
|
1748
1563
|
type: 'activity',
|
|
@@ -1756,6 +1571,9 @@ function normalizeItem(item) {
|
|
|
1756
1571
|
}
|
|
1757
1572
|
|
|
1758
1573
|
if (item.type === 'imageView') {
|
|
1574
|
+
const image = typeof item.path === 'string' && item.path
|
|
1575
|
+
? normalizeAttachment({ type: 'localImage', path: item.path })
|
|
1576
|
+
: null;
|
|
1759
1577
|
return {
|
|
1760
1578
|
type: 'activity',
|
|
1761
1579
|
id: item.id || '',
|
|
@@ -1763,16 +1581,16 @@ function normalizeItem(item) {
|
|
|
1763
1581
|
title: '查看图片',
|
|
1764
1582
|
titleOnly: true,
|
|
1765
1583
|
path: item.path || '',
|
|
1766
|
-
image
|
|
1767
|
-
? normalizeAttachment({ type: 'localImage', path: item.path })
|
|
1768
|
-
: null,
|
|
1584
|
+
image,
|
|
1769
1585
|
};
|
|
1770
1586
|
}
|
|
1771
1587
|
|
|
1772
1588
|
if (item.type === 'imageGeneration') {
|
|
1589
|
+
const result = typeof item.result === 'string' ? item.result.trim() : '';
|
|
1773
1590
|
const image = typeof item.savedPath === 'string' && item.savedPath
|
|
1774
1591
|
? normalizeAttachment({ type: 'localImage', path: item.savedPath, name: '生成的图片' })
|
|
1775
|
-
:
|
|
1592
|
+
: result ? normalizeAttachment({ type: 'image', name: '生成的图片',
|
|
1593
|
+
url: result.startsWith('data:image/') ? result : `data:image/png;base64,${result}` }) : null;
|
|
1776
1594
|
return {
|
|
1777
1595
|
type: 'activity',
|
|
1778
1596
|
id: item.id || '',
|
|
@@ -1809,17 +1627,21 @@ function normalizeItem(item) {
|
|
|
1809
1627
|
status: statusText(item.status),
|
|
1810
1628
|
tool: item.tool || '',
|
|
1811
1629
|
prompt: item.prompt || '',
|
|
1630
|
+
senderThreadId: item.senderThreadId || '',
|
|
1812
1631
|
receiverThreadIds: Array.isArray(item.receiverThreadIds) ? item.receiverThreadIds : [],
|
|
1632
|
+
model: item.model || '',
|
|
1633
|
+
reasoningEffort: item.reasoningEffort || '',
|
|
1634
|
+
agentsStates: item.agentsStates && typeof item.agentsStates === 'object' ? item.agentsStates : {},
|
|
1813
1635
|
};
|
|
1814
1636
|
}
|
|
1815
|
-
|
|
1637
|
+
|
|
1816
1638
|
return {
|
|
1817
|
-
type: 'activity',
|
|
1818
|
-
id: item.id || '',
|
|
1819
|
-
kind: item.type || 'event',
|
|
1820
|
-
title: item.type || '事件',
|
|
1821
|
-
status: statusText(item.status),
|
|
1822
|
-
detail: JSON.stringify(item, null, 2),
|
|
1639
|
+
type: 'activity',
|
|
1640
|
+
id: item.id || '',
|
|
1641
|
+
kind: item.type || 'event',
|
|
1642
|
+
title: item.type || '事件',
|
|
1643
|
+
status: statusText(item.status),
|
|
1644
|
+
detail: JSON.stringify(item, null, 2),
|
|
1823
1645
|
};
|
|
1824
1646
|
}
|
|
1825
1647
|
|
|
@@ -1831,174 +1653,180 @@ function sharedHistoryPageOptions() {
|
|
|
1831
1653
|
};
|
|
1832
1654
|
}
|
|
1833
1655
|
|
|
1834
|
-
function
|
|
1835
|
-
|
|
1656
|
+
function normalizeAttachments(content) {
|
|
1657
|
+
if (!Array.isArray(content)) return [];
|
|
1658
|
+
const items = content.filter(item => item && !['text', 'input_text'].includes(item.type)).map(item => ({ ...item }));
|
|
1659
|
+
const text = content.filter(item => ['text', 'input_text'].includes(item?.type)).map(item => item.text || '').join('\n');
|
|
1660
|
+
const paths = [...new Set([...text.matchAll(/<image\b[^>]*\bpath="([^"]+)"[^>]*>/g)].map(match => match[1]))];
|
|
1661
|
+
const images = items.filter(item => ['image', 'input_image', 'localImage'].includes(item.type));
|
|
1662
|
+
for (const [index, imagePath] of paths.entries()) {
|
|
1663
|
+
if (images.some(item => item.path === imagePath)) continue;
|
|
1664
|
+
if (images[index] && !images[index].path) images[index].path = imagePath;
|
|
1665
|
+
else items.push({ type: 'localImage', path: imagePath });
|
|
1666
|
+
}
|
|
1667
|
+
const seen = new Set();
|
|
1668
|
+
return items.map(item => normalizeAttachment(item)).filter(item => {
|
|
1669
|
+
if (!item.url) return true;
|
|
1670
|
+
if (seen.has(item.url)) return false;
|
|
1671
|
+
seen.add(item.url); return true;
|
|
1672
|
+
});
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
function markdownImageAssets(text) {
|
|
1676
|
+
const assets = Object.create(null);
|
|
1677
|
+
function visit(tokens) {
|
|
1678
|
+
for (const token of tokens) {
|
|
1679
|
+
const value = token.type === 'image' ? token.attrGet('src')
|
|
1680
|
+
: token.type === 'link_open' && !token.meta?.fileCitation ? token.attrGet('href') : null;
|
|
1681
|
+
if (value && !Object.hasOwn(assets, value)) {
|
|
1682
|
+
const localPath = fileCitations.localReference(value)?.path;
|
|
1683
|
+
// Only paths actually referenced by Desktop messages become accessible.
|
|
1684
|
+
// Do not expose a client-supplied filesystem path endpoint or UNC shares.
|
|
1685
|
+
if (localPath && /^[a-z]:[\\/]/i.test(localPath)) {
|
|
1686
|
+
const asset = normalizeAttachment({ type: 'localImage', path: localPath });
|
|
1687
|
+
if (asset.available) assets[value] = asset;
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
if (token.children && token.type !== 'image') visit(token.children);
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
visit(imageMarkdown.parse(text, { allowFileCitations: true }));
|
|
1694
|
+
return assets;
|
|
1836
1695
|
}
|
|
1837
1696
|
|
|
1838
|
-
function normalizeAttachments(content) {
|
|
1839
|
-
if (!Array.isArray(content)) return [];
|
|
1840
|
-
const items = content.filter(item => item && !['text', 'input_text'].includes(item.type)).map(item => ({ ...item }));
|
|
1841
|
-
const text = content.filter(item => ['text', 'input_text'].includes(item?.type)).map(item => item.text || '').join('\n');
|
|
1842
|
-
const paths = [...new Set([...text.matchAll(/<image\b[^>]*\bpath="([^"]+)"[^>]*>/g)].map(match => match[1]))];
|
|
1843
|
-
const images = items.filter(item => ['image', 'input_image', 'localImage'].includes(item.type));
|
|
1844
|
-
for (const [index, imagePath] of paths.entries()) {
|
|
1845
|
-
if (images.some(item => item.path === imagePath)) continue;
|
|
1846
|
-
if (images[index] && !images[index].path) images[index].path = imagePath;
|
|
1847
|
-
else items.push({ type: 'localImage', path: imagePath });
|
|
1848
|
-
}
|
|
1849
|
-
const seen = new Set();
|
|
1850
|
-
return items.map(normalizeAttachment).filter(item => {
|
|
1851
|
-
if (!item.url) return true;
|
|
1852
|
-
if (seen.has(item.url)) return false;
|
|
1853
|
-
seen.add(item.url); return true;
|
|
1854
|
-
});
|
|
1855
|
-
}
|
|
1856
|
-
|
|
1857
|
-
function markdownImageAssets(text) {
|
|
1858
|
-
const assets = Object.create(null);
|
|
1859
|
-
function visit(tokens) {
|
|
1860
|
-
for (const token of tokens) {
|
|
1861
|
-
const value = token.type === 'image' ? token.attrGet('src')
|
|
1862
|
-
: token.type === 'link_open' ? token.attrGet('href') : null;
|
|
1863
|
-
if (value && !Object.hasOwn(assets, value)) {
|
|
1864
|
-
let localPath;
|
|
1865
|
-
try { localPath = decodeURIComponent(value); } catch { continue; }
|
|
1866
|
-
// Only paths actually referenced by Desktop messages become accessible.
|
|
1867
|
-
// Do not expose a client-supplied filesystem path endpoint or UNC shares.
|
|
1868
|
-
if (/^\/?[a-z]:[\\/]/i.test(localPath)) {
|
|
1869
|
-
localPath = localPath.replace(/^\/(?=[a-z]:)/i, '');
|
|
1870
|
-
const asset = normalizeAttachment({ type: 'localImage', path: localPath });
|
|
1871
|
-
if (asset.available) assets[value] = asset;
|
|
1872
|
-
}
|
|
1873
|
-
}
|
|
1874
|
-
if (token.children) visit(token.children);
|
|
1875
|
-
}
|
|
1876
|
-
}
|
|
1877
|
-
visit(imageMarkdown.parse(text, {}));
|
|
1878
|
-
return assets;
|
|
1879
|
-
}
|
|
1880
|
-
|
|
1881
1697
|
function markdownFileAssets(text) {
|
|
1882
|
-
const assets = Object.create(null);
|
|
1883
|
-
function visit(tokens) {
|
|
1884
|
-
for (const token of tokens) {
|
|
1885
|
-
if (token.type === 'link_open') {
|
|
1886
|
-
const value = token.attrGet('href');
|
|
1887
|
-
if (value && !Object.hasOwn(assets, value)) {
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
const
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
const
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
const
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
}
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
name
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1698
|
+
const assets = Object.create(null);
|
|
1699
|
+
function visit(tokens) {
|
|
1700
|
+
for (const token of tokens) {
|
|
1701
|
+
if (token.type === 'link_open') {
|
|
1702
|
+
const value = token.attrGet('href');
|
|
1703
|
+
if (value && !Object.hasOwn(assets, value)) {
|
|
1704
|
+
const localPath = fileCitations.localReference(value)?.path;
|
|
1705
|
+
if (localPath && /^[a-z]:[\\/]/i.test(localPath)) {
|
|
1706
|
+
assets[value] = { remotePath: localPath, name: path.basename(localPath) };
|
|
1707
|
+
// Link rendering must not depend on file existence or transient backend state.
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
if (token.children && token.type !== 'image') visit(token.children);
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
visit(imageMarkdown.parse(text, { allowFileCitations: true }));
|
|
1715
|
+
return assets;
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
function describeLocalFile(filePath) {
|
|
1719
|
+
const resolved = path.resolve(filePath);
|
|
1720
|
+
let stat;
|
|
1721
|
+
try { stat = fs.statSync(resolved); }
|
|
1722
|
+
catch (error) {
|
|
1723
|
+
if (error.code === 'ENOENT') throw new RequestError(404, '电脑上的文件已不存在。');
|
|
1724
|
+
if (error.code === 'EACCES' || error.code === 'EPERM') throw new RequestError(403, '电脑系统无法读取此文件:' + error.code);
|
|
1725
|
+
throw error;
|
|
1726
|
+
}
|
|
1727
|
+
if (!stat.isFile()) throw new RequestError(400, '此路径不是文件。');
|
|
1728
|
+
return { path: resolved, name: path.basename(resolved), size: stat.size, revision: fileRevision(stat) };
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
function splitUploadedImages(text) {
|
|
1732
|
+
const tokens = imageMarkdown.parse(text, {});
|
|
1733
|
+
const lines = text.split('\n');
|
|
1734
|
+
const removed = new Set();
|
|
1735
|
+
const attachments = [];
|
|
1736
|
+
for (let index = 0; index < tokens.length - 1; index++) {
|
|
1737
|
+
const block = tokens[index];
|
|
1738
|
+
const inline = tokens[index + 1];
|
|
1739
|
+
if (block.type !== 'paragraph_open' || !block.map || inline.type !== 'inline') continue;
|
|
1740
|
+
const children = (inline.children || []).filter(token => token.type !== 'softbreak');
|
|
1741
|
+
if (!children.length || children.some(token => token.type !== 'image')) continue;
|
|
1742
|
+
const paths = children.map(token => {
|
|
1743
|
+
try { return path.resolve(decodeURIComponent(token.attrGet('src') || '')); } catch { return ''; }
|
|
1744
|
+
});
|
|
1745
|
+
if (paths.some(file => path.dirname(file).toLowerCase() !== uploadsRoot.toLowerCase()
|
|
1746
|
+
|| !/^[a-f0-9]{64}\.(png|webp)$/.test(path.basename(file)))) continue;
|
|
1747
|
+
for (const file of paths) attachments.push(normalizeAttachment({ type: 'localImage', path: file, name: '移动端图片' }));
|
|
1748
|
+
for (let line = block.map[0]; line < block.map[1]; line++) removed.add(line);
|
|
1749
|
+
}
|
|
1750
|
+
const visibleText = lines.filter((line, index) => !removed.has(index)).join('\n').trim();
|
|
1751
|
+
return { text: visibleText, attachments, imageAssets: markdownImageAssets(visibleText) };
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
async function externalDownloadAsset(value, recovery = '') {
|
|
1755
|
+
const match = /^([a-f0-9]{64})(?:\?recovery=([A-Za-z0-9_-]{1,4096}))?$/.exec(value || '');
|
|
1756
|
+
if (!match) throw new RequestError(400, '无效的外部文件标识。');
|
|
1757
|
+
const asset = attachmentCache.get(match[1]) || dotsImages.restore(match[1], match[2] || recovery || '');
|
|
1758
|
+
if (!asset?.dotsFile) throw new RequestError(404, '外部文件授权已失效,请重新读取对话。');
|
|
1759
|
+
await dotsImages.authorization(asset.identity);
|
|
1760
|
+
return asset;
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
function workstationCopyReference(copy, asset) {
|
|
1764
|
+
const id = crypto.createHmac('sha256', fileCapabilitySecret).update(JSON.stringify([asset.id, copy.path, copy.revision])).digest('hex');
|
|
1765
|
+
fileCache.set(id, { ...copy, id, externalIdentity: asset.identity });
|
|
1766
|
+
while (fileCache.size > MAX_CACHED_FILES) fileCache.delete(fileCache.keys().next().value);
|
|
1767
|
+
return { remotePath: id, path: copy.path, name: copy.name, size: copy.size, mimeType: copy.mimeType };
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
function normalizeAttachment(item, identity) {
|
|
1771
|
+
const name = item.name || item.fileName || (typeof item.path === 'string' ? path.basename(item.path) : '');
|
|
1772
|
+
let cached = null;
|
|
1773
|
+
const isImage = ['image', 'input_image', 'localImage'].includes(item.type);
|
|
1774
|
+
if (isImage || item.type === 'file') cached = dotsImages.remember(item, identity);
|
|
1775
|
+
if (isImage && typeof item.path === 'string') {
|
|
1776
|
+
cached = cacheLocalImage(item.path, name) || cached;
|
|
1777
|
+
}
|
|
1778
|
+
if (!cached) {
|
|
1779
|
+
const dataUrl = typeof item.url === 'string' && item.url.startsWith('data:image/')
|
|
1780
|
+
? item.url
|
|
1781
|
+
: (typeof item.image_url === 'string' && item.image_url.startsWith('data:image/') ? item.image_url : '');
|
|
1782
|
+
if (dataUrl) cached = cacheDataImage(dataUrl, name);
|
|
1783
|
+
}
|
|
1784
|
+
return {
|
|
1785
|
+
type: isImage ? 'image' : item.type || 'attachment',
|
|
1786
|
+
name: cached?.name || name,
|
|
1787
|
+
mimeType: cached?.mimeType || item.mimeType || '',
|
|
1788
|
+
...(cached?.size ? { size: cached.size } : {}),
|
|
1789
|
+
...(cached?.dotsFile ? { networkFile: true } : {}),
|
|
1790
|
+
available: Boolean(cached),
|
|
1791
|
+
remotePath: cached ? (isImage ? cached.id : `${cached.id}?recovery=${cached.recoveryToken}`) : '',
|
|
1964
1792
|
recoveryToken: cached?.recoveryToken || '',
|
|
1965
|
-
url: '',
|
|
1966
|
-
thumbnailUrl: '',
|
|
1967
|
-
};
|
|
1968
|
-
}
|
|
1969
|
-
|
|
1793
|
+
url: '',
|
|
1794
|
+
thumbnailUrl: '',
|
|
1795
|
+
};
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1970
1798
|
function cacheLocalImage(filePath, name) {
|
|
1971
1799
|
try {
|
|
1972
1800
|
const resolved = path.resolve(filePath);
|
|
1973
1801
|
const stat = fs.statSync(resolved);
|
|
1974
1802
|
const mimeType = imageMimeType(resolved);
|
|
1975
|
-
if (!stat.isFile() || !mimeType || stat.size >
|
|
1803
|
+
if (!stat.isFile() || !mimeType || stat.size > MAX_IMAGE_PREVIEW_BYTES) return null;
|
|
1976
1804
|
const cached = rememberAttachment(fs.readFileSync(resolved), mimeType, name,
|
|
1977
1805
|
localImageRecoveryToken(resolved, stat));
|
|
1978
1806
|
void attachmentThumbnail(cached).catch(() => {});
|
|
1979
1807
|
return cached;
|
|
1980
|
-
} catch {
|
|
1981
|
-
return null;
|
|
1982
|
-
}
|
|
1983
|
-
}
|
|
1984
|
-
|
|
1985
|
-
function cacheDataImage(dataUrl, name) {
|
|
1986
|
-
const match = /^data:(image\/(?:png|jpeg|gif|webp|bmp));base64,([a-z0-9+/=\r\n]+)$/i.exec(dataUrl);
|
|
1987
|
-
if (!match) return null;
|
|
1988
|
-
try {
|
|
1989
|
-
const buffer = Buffer.from(match[2], 'base64');
|
|
1990
|
-
if (!buffer.length || buffer.length >
|
|
1991
|
-
return rememberAttachment(buffer, match[1].toLowerCase(), name);
|
|
1992
|
-
} catch {
|
|
1993
|
-
return null;
|
|
1994
|
-
}
|
|
1995
|
-
}
|
|
1996
|
-
|
|
1808
|
+
} catch {
|
|
1809
|
+
return null;
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
function cacheDataImage(dataUrl, name) {
|
|
1814
|
+
const match = /^data:(image\/(?:png|jpeg|gif|webp|bmp));base64,([a-z0-9+/=\r\n]+)$/i.exec(dataUrl);
|
|
1815
|
+
if (!match) return null;
|
|
1816
|
+
try {
|
|
1817
|
+
const buffer = Buffer.from(match[2], 'base64');
|
|
1818
|
+
if (!buffer.length || buffer.length > MAX_IMAGE_PREVIEW_BYTES) return null;
|
|
1819
|
+
return rememberAttachment(buffer, match[1].toLowerCase(), name);
|
|
1820
|
+
} catch {
|
|
1821
|
+
return null;
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1997
1825
|
function rememberAttachment(buffer, mimeType, name, recoveryToken = '') {
|
|
1998
1826
|
const id = crypto.createHash('sha256').update(buffer).digest('hex');
|
|
1999
1827
|
if (!attachmentCache.has(id)) {
|
|
2000
|
-
while (attachmentCache.size >= MAX_CACHED_ATTACHMENTS) {
|
|
2001
|
-
attachmentCache.delete(attachmentCache.keys().next().value);
|
|
1828
|
+
while (attachmentCache.size >= MAX_CACHED_ATTACHMENTS) {
|
|
1829
|
+
attachmentCache.delete(attachmentCache.keys().next().value);
|
|
2002
1830
|
}
|
|
2003
1831
|
attachmentCache.set(id, { id, buffer, mimeType, name, recoveryToken });
|
|
2004
1832
|
} else if (recoveryToken && !attachmentCache.get(id).recoveryToken) {
|
|
@@ -2026,7 +1854,7 @@ function recoverLocalImage(id, token) {
|
|
|
2026
1854
|
decipher.update(value.subarray(28)), decipher.final(),
|
|
2027
1855
|
]).toString('utf8'));
|
|
2028
1856
|
if (typeof filePath !== 'string' || !path.isAbsolute(filePath)
|
|
2029
|
-
|| !Number.isSafeInteger(size) || size <= 0 || size >
|
|
1857
|
+
|| !Number.isSafeInteger(size) || size <= 0 || size > MAX_IMAGE_PREVIEW_BYTES
|
|
2030
1858
|
|| typeof mtimeMs !== 'number' || !Number.isFinite(mtimeMs)) return null;
|
|
2031
1859
|
const stat = fs.statSync(filePath);
|
|
2032
1860
|
const mimeType = imageMimeType(filePath);
|
|
@@ -2053,55 +1881,47 @@ async function attachmentThumbnail(image) {
|
|
|
2053
1881
|
}
|
|
2054
1882
|
return image.thumbnail;
|
|
2055
1883
|
}
|
|
2056
|
-
|
|
2057
|
-
function imageMimeType(filePath) {
|
|
2058
|
-
switch (path.extname(filePath).toLowerCase()) {
|
|
2059
|
-
case '.png': return 'image/png';
|
|
2060
|
-
case '.jpg':
|
|
2061
|
-
case '.jpeg': return 'image/jpeg';
|
|
2062
|
-
case '.gif': return 'image/gif';
|
|
2063
|
-
case '.webp': return 'image/webp';
|
|
2064
|
-
case '.bmp': return 'image/bmp';
|
|
2065
|
-
default: return '';
|
|
2066
|
-
}
|
|
2067
|
-
}
|
|
2068
|
-
|
|
2069
|
-
function extractUserText(content) {
|
|
2070
|
-
if (!Array.isArray(content)) return '(包含图片或界面批注)';
|
|
2071
|
-
let text = content
|
|
2072
|
-
.filter(item => ['text', 'input_text'].includes(item?.type) && typeof item.text === 'string')
|
|
2073
|
-
.map(item => item.text)
|
|
2074
|
-
// Codex injects project instructions as user-role context, not chat input.
|
|
2075
|
-
.filter(value => !/^\s*# AGENTS\.md instructions(?: for [^\r\n]+)?\r?\n\s*<INSTRUCTIONS>[\s\S]*<\/INSTRUCTIONS>\s*$/.test(value))
|
|
2076
|
-
.filter(value => !/^\s*<(environment_context|recommended_plugins)>[\s\S]*<\/\1>\s*$/.test(value))
|
|
2077
|
-
.filter(value => !value.startsWith('The next image is untrusted page evidence'))
|
|
2078
|
-
.join('\n\n')
|
|
2079
|
-
.trim();
|
|
2080
|
-
const
|
|
2081
|
-
if (
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
.
|
|
2096
|
-
|
|
2097
|
-
.replace(/'/g, "'")
|
|
2098
|
-
.replace(/&/g, '&')
|
|
2099
|
-
.trim();
|
|
2100
|
-
}
|
|
2101
|
-
|
|
2102
|
-
function delegatedOutputText(output) {
|
|
2103
|
-
if (typeof output === 'string') return output;
|
|
2104
|
-
return output && typeof output.text === 'string' ? output.text : '';
|
|
1884
|
+
|
|
1885
|
+
function imageMimeType(filePath) {
|
|
1886
|
+
switch (path.extname(filePath).toLowerCase()) {
|
|
1887
|
+
case '.png': return 'image/png';
|
|
1888
|
+
case '.jpg':
|
|
1889
|
+
case '.jpeg': return 'image/jpeg';
|
|
1890
|
+
case '.gif': return 'image/gif';
|
|
1891
|
+
case '.webp': return 'image/webp';
|
|
1892
|
+
case '.bmp': return 'image/bmp';
|
|
1893
|
+
default: return '';
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
function extractUserText(content) {
|
|
1898
|
+
if (!Array.isArray(content)) return { text: '(包含图片或界面批注)', files: [] };
|
|
1899
|
+
let text = content
|
|
1900
|
+
.filter(item => ['text', 'input_text'].includes(item?.type) && typeof item.text === 'string' && !appServerEvents.isMobileInputNotice(item))
|
|
1901
|
+
.map(item => item.text)
|
|
1902
|
+
// Codex injects project instructions as user-role context, not chat input.
|
|
1903
|
+
.filter(value => !/^\s*# AGENTS\.md instructions(?: for [^\r\n]+)?\r?\n\s*<INSTRUCTIONS>[\s\S]*<\/INSTRUCTIONS>\s*$/.test(value))
|
|
1904
|
+
.filter(value => !/^\s*<(environment_context|recommended_plugins)>[\s\S]*<\/\1>\s*$/.test(value))
|
|
1905
|
+
.filter(value => !value.startsWith('The next image is untrusted page evidence'))
|
|
1906
|
+
.join('\n\n')
|
|
1907
|
+
.trim();
|
|
1908
|
+
const delegation = appServerEvents.parseCodexDelegation(text);
|
|
1909
|
+
if (delegation) text = delegation.input;
|
|
1910
|
+
const mentioned = fileMentions.parse(text);
|
|
1911
|
+
const imagePaths = new Set([
|
|
1912
|
+
...content.filter(item => ['image', 'input_image', 'localImage'].includes(item?.type) && item.path).map(item => item.path),
|
|
1913
|
+
...[...mentioned.text.matchAll(/<image\b[^>]*\bpath="([^"]+)"[^>]*>/g)].map(match => match[1]),
|
|
1914
|
+
].map(value => path.resolve(value).toLowerCase()));
|
|
1915
|
+
text = mentioned.text;
|
|
1916
|
+
text = text.replace(/<image\b[^>]*\bpath="[^"]+"[^>]*>/g, '').replace(/<\/image>/g, '').trim();
|
|
1917
|
+
return { text, files: mentioned.files.filter(file => file.fileId || !imagePaths.has(path.resolve(file.path).toLowerCase())), delegation };
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
function delegationSource(delegation) {
|
|
1921
|
+
const dots = dotsServer.threadSources.get(delegation.sourceThreadId) === 'aeon';
|
|
1922
|
+
return { sourceThreadId: delegation.sourceThreadId, sourceKind: dots ? 'dots' : 'codex',
|
|
1923
|
+
...(dots ? { sourceName: dotsServer.profileName(delegation.sourceThreadId),
|
|
1924
|
+
sourceAvatar: dotsServer.profileAvatar(delegation.sourceThreadId) } : {}) };
|
|
2105
1925
|
}
|
|
2106
1926
|
|
|
2107
1927
|
function summaryText(value) {
|
|
@@ -2111,76 +1931,51 @@ function summaryText(value) {
|
|
|
2111
1931
|
}
|
|
2112
1932
|
|
|
2113
1933
|
function statusText(value) {
|
|
2114
|
-
if (typeof value === 'string') return value;
|
|
2115
|
-
if (value && typeof value === 'object') return value.type || value.status || 'unknown';
|
|
2116
|
-
return value == null ? 'unknown' : String(value);
|
|
2117
|
-
}
|
|
2118
|
-
|
|
2119
|
-
function
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
'Content-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
}
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
let
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
if (args[i] === '--token' && args[i + 1]) token = args[++i];
|
|
2153
|
-
}
|
|
2154
|
-
if (!Number.isInteger(port) || port < 1024 || port > 65535) {
|
|
2155
|
-
throw new Error('端口必须位于 1024 到 65535 之间。');
|
|
2156
|
-
}
|
|
2157
|
-
if (lan && !token) token = crypto.randomBytes(32).toString('base64url');
|
|
2158
|
-
return { port, lan, token, appServer };
|
|
2159
|
-
}
|
|
2160
|
-
|
|
2161
|
-
function boundedInteger(value, fallback, minimum, maximum) {
|
|
2162
|
-
const parsed = Number.parseInt(value || '', 10);
|
|
2163
|
-
return Number.isFinite(parsed) ? Math.min(maximum, Math.max(minimum, parsed)) : fallback;
|
|
2164
|
-
}
|
|
2165
|
-
|
|
2166
|
-
function booleanValue(value, fallback) {
|
|
2167
|
-
if (value === 'true') return true;
|
|
2168
|
-
if (value === 'false') return false;
|
|
2169
|
-
return fallback;
|
|
2170
|
-
}
|
|
2171
|
-
|
|
2172
|
-
class BridgeError extends Error {
|
|
2173
|
-
constructor(message, details, options) {
|
|
2174
|
-
super(message, options ? { cause: options } : undefined);
|
|
2175
|
-
this.details = details;
|
|
2176
|
-
}
|
|
2177
|
-
}
|
|
2178
|
-
|
|
2179
|
-
class RequestError extends Error {
|
|
2180
|
-
constructor(statusCode, message, details) {
|
|
2181
|
-
super(message);
|
|
2182
|
-
this.statusCode = statusCode;
|
|
2183
|
-
this.details = details;
|
|
2184
|
-
this.code = details?.code;
|
|
1934
|
+
if (typeof value === 'string') return value;
|
|
1935
|
+
if (value && typeof value === 'object') return value.type || value.status || 'unknown';
|
|
1936
|
+
return value == null ? 'unknown' : String(value);
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
function sendJson(response, statusCode, value) {
|
|
1940
|
+
if (response.json) { response.json(statusCode, value); return; }
|
|
1941
|
+
sendBuffer(response, statusCode, 'application/json; charset=utf-8', Buffer.from(JSON.stringify(value)));
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
function sendBuffer(response, statusCode, contentType, value) {
|
|
1945
|
+
response.writeHead(statusCode, {
|
|
1946
|
+
'Content-Type': contentType,
|
|
1947
|
+
'Content-Length': value.length,
|
|
1948
|
+
'Cache-Control': 'no-store',
|
|
1949
|
+
'X-Content-Type-Options': 'nosniff',
|
|
1950
|
+
'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; media-src blob:",
|
|
1951
|
+
});
|
|
1952
|
+
response.end(value);
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
async function readJsonBody(request) {
|
|
1956
|
+
return request.body;
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
function parseOptions(args) {
|
|
1960
|
+
let port = Number.parseInt(process.env.CODEX_REMOTE_BRIDGE_PORT || '45831', 10);
|
|
1961
|
+
let lan = process.env.CODEX_REMOTE_BRIDGE_LAN === 'true';
|
|
1962
|
+
let token = process.env.CODEX_REMOTE_BRIDGE_TOKEN?.trim() || '';
|
|
1963
|
+
if (process.env.CODEX_REMOTE_APP_SERVER === 'true') throw new Error('此连接方式已停用。');
|
|
1964
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
1965
|
+
if (args[i] === '--lan') lan = true;
|
|
1966
|
+
if (args[i] === '--app-server') throw new Error('此连接方式已停用。');
|
|
1967
|
+
if (args[i] === '--port' && args[i + 1]) port = Number.parseInt(args[++i], 10);
|
|
1968
|
+
if (args[i] === '--token' && args[i + 1]) token = args[++i];
|
|
1969
|
+
}
|
|
1970
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535) {
|
|
1971
|
+
throw new Error('端口必须位于 1024 到 65535 之间。');
|
|
2185
1972
|
}
|
|
1973
|
+
if (lan && !token) token = crypto.randomBytes(32).toString('base64url');
|
|
1974
|
+
return { port, lan, token };
|
|
2186
1975
|
}
|
|
1976
|
+
|
|
1977
|
+
function boundedInteger(value, fallback, minimum, maximum) {
|
|
1978
|
+
const parsed = Number.parseInt(value || '', 10);
|
|
1979
|
+
return Number.isFinite(parsed) ? Math.min(maximum, Math.max(minimum, parsed)) : fallback;
|
|
1980
|
+
}
|
|
1981
|
+
|