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