The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: implement terminal peer-to-peer data transport with WebRTC signaling and automated fallback to relay
0xken15b2afcffba96e
diff --git a/cli/package-lock.json b/cli/package-lock.jsonindex a5384684a..32586ab2b 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -7,13 +7,14 @@"": {"name": "harness","version": "0.0.1",- "license": "Apache-2.0",+ "license": "MIT","dependencies": {"@noble/ciphers": "^1.3.0","@noble/curves": "^1.9.7","@noble/hashes": "^1.8.0","chokidar": "^4.0.0","dotenv": "^17.2.3",+ "werift": "0.24.4","ws": "^8.18.0","zod": "^4.0.0"},@@ -508,6 +509,28 @@"node": ">=18"}},+ "node_modules/@fidm/asn1": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/@fidm/asn1/-/asn1-1.0.4.tgz",+ "integrity": "sha512-esd1jyNvRb2HVaQGq2Gg8Z0kbQPXzV9Tq5Z14KNIov6KfFD6PTaRIO8UpcsYiTNzOqJpmyzWgVTrUwFV3UF4TQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 8"+ }+ },+ "node_modules/@fidm/x509": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@fidm/x509/-/x509-1.2.1.tgz",+ "integrity": "sha512-nwc2iesjyc9hkuzcrMCBXQRn653XuAUKorfWM8PZyJawiy1QzLj4vahwzaI25+pfpwOLvMzbJ0uKpWLDNmo16w==",+ "license": "MIT",+ "dependencies": {+ "@fidm/asn1": "^1.0.4",+ "tweetnacl": "^1.0.1"+ },+ "engines": {+ "node": ">= 8"+ }+ },"node_modules/@jridgewell/sourcemap-codec": {"version": "1.5.5","resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",@@ -515,6 +538,12 @@"dev": true,"license": "MIT"},+ "node_modules/@leichtgewicht/ip-codec": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz",+ "integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==",+ "license": "MIT"+ },"node_modules/@napi-rs/wasm-runtime": {"version": "1.1.6","resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",@@ -583,6 +612,193 @@"url": "https://github.com/sponsors/Boshen"}},+ "node_modules/@peculiar/asn1-cms": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.9.4.tgz",+ "integrity": "sha512-cben7oxmQsUGZqotus7yt0srYdncOT6RNWcTQ77T2RFOXejYVYkXadrfePdRcrVpO9K95IRLKKglG2k38jKXuw==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.9.4",+ "@peculiar/asn1-x509": "^2.9.4",+ "@peculiar/asn1-x509-attr": "^2.9.4",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/asn1-csr": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.9.4.tgz",+ "integrity": "sha512-xd4YN4vpRjkDAQWVfZZkeu12IEND7DOpkqaHSIHxZl1uggUNa9Ju0QxY2jHvDAS9pP0zhRBytg8ifsnGo3V0jw==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.9.4",+ "@peculiar/asn1-x509": "^2.9.4",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/asn1-ecc": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.9.4.tgz",+ "integrity": "sha512-JJXefFshRAuVAjWQo/39bkg1ywc1VaiO44S8RRC+Ykvf/u2KDmYffoDb0ZBPCR5uJy4AGKQhl8mX+Q8ShcWaXQ==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.9.4",+ "@peculiar/asn1-x509": "^2.9.4",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/asn1-pfx": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.9.4.tgz",+ "integrity": "sha512-khuGzHTzNzk4GDlIBEILyIs6Lce0yn0ZBdoI9v93kmNncfZRhD+AQ5ODFqdhvoE8cMJF/JMTQ8yA+t1D14kqCw==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-cms": "^2.9.4",+ "@peculiar/asn1-pkcs8": "^2.9.4",+ "@peculiar/asn1-rsa": "^2.9.4",+ "@peculiar/asn1-schema": "^2.9.4",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/asn1-pkcs8": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.9.4.tgz",+ "integrity": "sha512-duRdotlUx9eDZe6QrQpQKl61RbWykCHBCkKayP8V8XdEFwlKHZ8qGGDMyS6Pye7OX7nLFttTTpRkJeet78ckwQ==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.9.4",+ "@peculiar/asn1-x509": "^2.9.4",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/asn1-pkcs9": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.9.4.tgz",+ "integrity": "sha512-kaL4cNxBpdQE2dKlyZBqz4ygCrwffO+8wfoxTEqM1Z8RadvCeELBRzcv0dzM8aY9azHMwODO5nxU65zXmhToOQ==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-cms": "^2.9.4",+ "@peculiar/asn1-pfx": "^2.9.4",+ "@peculiar/asn1-pkcs8": "^2.9.4",+ "@peculiar/asn1-schema": "^2.9.4",+ "@peculiar/asn1-x509": "^2.9.4",+ "@peculiar/asn1-x509-attr": "^2.9.4",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/asn1-rsa": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.9.4.tgz",+ "integrity": "sha512-pZ96eD1PptovcWQ/GSmuNFXd/7EQJNlKfDaNCyE2rx3W0v6QFelkzquVqRSRyyDXXCYD69ZXJDzZ8GhIiQzKoA==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.9.4",+ "@peculiar/asn1-x509": "^2.9.4",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/asn1-schema": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.9.4.tgz",+ "integrity": "sha512-GjzePcT9Iw8NzeOPf73iNS9xM+TBhd/FilAfP+RQGkTMQJTVWtytN3JHJACCjf/ABNau5S7mS3g+DcuxmRgYEg==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/utils": "^2.0.2",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/asn1-x509": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.9.4.tgz",+ "integrity": "sha512-CxhBo/RdEbMMob7T31ZdQjGuoyRFLVwrDzTn25bihzBasRg9kRm/0IxIPvhgQtcK/9dNcO1XQL2fuPugwELL0Q==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.9.4",+ "@peculiar/utils": "^2.0.2",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/asn1-x509-attr": {+ "version": "2.9.4",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.9.4.tgz",+ "integrity": "sha512-ehQXbpQaQYycgu8OrvigwSPTFfVRcu0ECNYCWw+yzBp02Lw5paRqzzhUpfOgO2K38+WfFZuEz/0RPtam5g0OMg==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-schema": "^2.9.4",+ "@peculiar/asn1-x509": "^2.9.4",+ "asn1js": "^3.0.10",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@peculiar/utils": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz",+ "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/x509": {+ "version": "1.14.3",+ "resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz",+ "integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==",+ "license": "MIT",+ "dependencies": {+ "@peculiar/asn1-cms": "^2.6.0",+ "@peculiar/asn1-csr": "^2.6.0",+ "@peculiar/asn1-ecc": "^2.6.0",+ "@peculiar/asn1-pkcs9": "^2.6.0",+ "@peculiar/asn1-rsa": "^2.6.0",+ "@peculiar/asn1-schema": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.0",+ "pvtsutils": "^1.3.6",+ "reflect-metadata": "^0.2.2",+ "tslib": "^2.8.1",+ "tsyringe": "^4.10.0"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/@rolldown/binding-android-arm64": {"version": "1.1.5","resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.5.tgz",@@ -847,6 +1063,19 @@"dev": true,"license": "MIT"},+ "node_modules/@shinyoshiaki/binary-data": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/@shinyoshiaki/binary-data/-/binary-data-0.6.1.tgz",+ "integrity": "sha512-7HDb/fQAop2bCmvDIzU5+69i+UJaFgIVp99h1VzK1mpg1JwSODOkjbqD7ilTYnqlnadF8C4XjpwpepxDsGY6+w==",+ "license": "MIT",+ "dependencies": {+ "generate-function": "^2.3.1",+ "is-plain-object": "^2.0.3"+ },+ "engines": {+ "node": ">=6"+ }+ },"node_modules/@standard-schema/spec": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",@@ -883,6 +1112,21 @@"dev": true,"license": "MIT"},+ "node_modules/@types/dom-mediacapture-transform": {+ "version": "0.1.12",+ "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",+ "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",+ "license": "MIT",+ "dependencies": {+ "@types/dom-webcodecs": "*"+ }+ },+ "node_modules/@types/dom-webcodecs": {+ "version": "0.1.13",+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",+ "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",+ "license": "MIT"+ },"node_modules/@types/estree": {"version": "1.0.9","resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",@@ -1023,6 +1267,20 @@"url": "https://opencollective.com/vitest"}},+ "node_modules/asn1js": {+ "version": "3.0.10",+ "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",+ "integrity": "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "pvtsutils": "^1.3.6",+ "pvutils": "^1.1.5",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },"node_modules/assertion-error": {"version": "2.0.1","resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",@@ -1033,6 +1291,50 @@"node": ">=12"}},+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/buffer": {+ "version": "6.0.3",+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",+ "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "base64-js": "^1.3.1",+ "ieee754": "^1.2.1"+ }+ },"node_modules/chai": {"version": "6.2.2","resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",@@ -1065,6 +1367,23 @@"dev": true,"license": "MIT"},+ "node_modules/debug": {+ "version": "4.4.0",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",+ "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },"node_modules/detect-libc": {"version": "2.1.2","resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",@@ -1075,6 +1394,18 @@"node": ">=8"}},+ "node_modules/dns-packet": {+ "version": "5.6.1",+ "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz",+ "integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==",+ "license": "MIT",+ "dependencies": {+ "@leichtgewicht/ip-codec": "^2.0.1"+ },+ "engines": {+ "node": ">=6"+ }+ },"node_modules/dotenv": {"version": "17.4.2","resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",@@ -1189,6 +1520,62 @@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},+ "node_modules/generate-function": {+ "version": "2.3.1",+ "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",+ "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",+ "license": "MIT",+ "dependencies": {+ "is-property": "^1.0.2"+ }+ },+ "node_modules/ieee754": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/is-plain-object": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz",+ "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==",+ "license": "MIT",+ "dependencies": {+ "isobject": "^3.0.1"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/is-property": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",+ "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",+ "license": "MIT"+ },+ "node_modules/isobject": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",+ "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/lightningcss": {"version": "1.32.0","resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",@@ -1460,6 +1847,43 @@"@jridgewell/sourcemap-codec": "^1.5.5"}},+ "node_modules/mediabunny": {+ "version": "1.55.6",+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.55.6.tgz",+ "integrity": "sha512-IuwxlL8GQ5qODxvdj0mm5bUumrwTr13ooX0UygsrT2u1uwERjV1Awv/zuFoY5iNeYic6SQU78BcGcGLnDgPQ9g==",+ "license": "MPL-2.0",+ "workspaces": [+ ".",+ "packages/*"+ ],+ "dependencies": {+ "@types/dom-mediacapture-transform": "^0.1.11",+ "@types/dom-webcodecs": "0.1.13"+ },+ "funding": {+ "type": "individual",+ "url": "https://github.com/sponsors/Vanilagy"+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },+ "node_modules/multicast-dns": {+ "version": "7.2.5",+ "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-7.2.5.tgz",+ "integrity": "sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==",+ "license": "MIT",+ "dependencies": {+ "dns-packet": "^5.2.2",+ "thunky": "^1.0.2"+ },+ "bin": {+ "multicast-dns": "cli.js"+ }+ },"node_modules/nanoid": {"version": "3.3.15","resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",@@ -1549,6 +1973,24 @@"node": "^10 || ^12 || >=14"}},+ "node_modules/pvtsutils": {+ "version": "1.3.6",+ "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",+ "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^2.8.1"+ }+ },+ "node_modules/pvutils": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",+ "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",+ "license": "MIT",+ "engines": {+ "node": ">=16.0.0"+ }+ },"node_modules/readdirp": {"version": "4.1.2","resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",@@ -1562,6 +2004,12 @@"url": "https://paulmillr.com/funding/"}},+ "node_modules/reflect-metadata": {+ "version": "0.2.2",+ "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",+ "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",+ "license": "Apache-2.0"+ },"node_modules/rolldown": {"version": "1.1.5","resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz",@@ -1627,6 +2075,12 @@"dev": true,"license": "MIT"},+ "node_modules/thunky": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz",+ "integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==",+ "license": "MIT"+ },"node_modules/tinybench": {"version": "2.9.0","resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",@@ -1675,9 +2129,7 @@"version": "2.8.1","resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz","integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",- "dev": true,- "license": "0BSD",- "optional": true+ "license": "0BSD"},"node_modules/tsx": {"version": "4.23.0",@@ -2182,6 +2634,30 @@"@esbuild/win32-x64": "0.28.1"}},+ "node_modules/tsyringe": {+ "version": "4.10.0",+ "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz",+ "integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==",+ "license": "MIT",+ "dependencies": {+ "tslib": "^1.9.3"+ },+ "engines": {+ "node": ">= 6.0.0"+ }+ },+ "node_modules/tsyringe/node_modules/tslib": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",+ "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",+ "license": "0BSD"+ },+ "node_modules/tweetnacl": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",+ "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",+ "license": "Unlicense"+ },"node_modules/typescript": {"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",@@ -2371,6 +2847,26 @@}}},+ "node_modules/werift": {+ "version": "0.24.4",+ "resolved": "https://registry.npmjs.org/werift/-/werift-0.24.4.tgz",+ "integrity": "sha512-NoROZ11L/ZqAB5ombCB4VBuVNdIZfwI493zlxlIX7BlwfWRy55eDJdtWMC2VX35yBXFaWwA8NtYbmJ8qWtVk9Q==",+ "license": "MIT",+ "dependencies": {+ "@fidm/x509": "^1.2.1",+ "@noble/curves": "^1.8.1",+ "@peculiar/x509": "^1.12.3",+ "@shinyoshiaki/binary-data": "^0.6.1",+ "buffer": "^6.0.3",+ "debug": "4.4.0",+ "mediabunny": "^1.45.2",+ "multicast-dns": "^7.2.5",+ "tweetnacl": "^1.0.3"+ },+ "engines": {+ "node": ">=16"+ }+ },"node_modules/why-is-node-running": {"version": "2.3.0","resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",diff --git a/cli/package.json b/cli/package.jsonindex d6aafe021..a899ea16c 100644--- a/cli/package.json+++ b/cli/package.json@@ -23,6 +23,7 @@"@noble/hashes": "^1.8.0","chokidar": "^4.0.0","dotenv": "^17.2.3",+ "werift": "0.24.4","ws": "^8.18.0","zod": "^4.0.0"},diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex d10ee5349..00641bfb1 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -60,6 +60,13 @@ import { shouldReplayCommander } from './lib/commanderReplay.js'import { RuntimeProfileControlError, type RuntimeProfileErrorCode } from './lib/runtimeProfileController.js'import { parseRuntimeProfile, type RuntimeModelOption } from './lib/runtimeProfile.js'import { sid, preview, logFrame } from './lib/log.js'+import {+ TerminalP2pResponderPool,+ TERMINAL_P2P_DOWN_TYPES,+ TERMINAL_P2P_SIGNAL_TYPES,+ type TerminalP2pData,+ type TerminalP2pSignal,+} from './lib/terminalP2p.js'// OpenCode has no per-session transcript file — its history is read from this SQLite store.const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')@@ -273,6 +280,9 @@ export class BackendSocket {private readonly downChains = new Map<string, Promise<void>>()private readonly localClients = new Map<string, LocalClientSink>()private terminalStreams: TerminalStreamManager | null = null+ private readonly terminalP2p: TerminalP2pResponderPool+ private readonly p2pPendingOpens = new Map<string, Set<string>>()+ private readonly p2pStreams = new Map<string, Set<string>>()private isAlive = trueprivate onStatus: (connected: boolean) => void/** Cross-instance commander (device) client count, from backend `__clients` frames. */@@ -409,6 +419,11 @@ export class BackendSocket {sendUser: (frame) => this.sendUser(frame),isConnected: () => this.isConnected(),})+ this.terminalP2p = new TerminalP2pResponderPool({+ sendSignal: (connId, type, payload) => this.sendP2pSignal(connId, type, payload),+ onData: (connId, data) => this.handleP2pData(connId, data),+ onUnavailable: (connId, reason) => this.demoteP2pConnection(connId, reason),+ })}setTerminalStreamManager(manager: TerminalStreamManager): void {@@ -525,6 +540,9 @@ export class BackendSocket {'backend disconnected',false,)+ void this.terminalP2p.stop()+ this.p2pPendingOpens.clear()+ this.p2pStreams.clear()this.replayCommanderOnNextSnapshot = truethis.onStatus(false)if (this.closed) return@@ -564,6 +582,7 @@ export class BackendSocket {if (this.heartbeat) clearInterval(this.heartbeat)if (this.appPing) clearInterval(this.appPing)await this.terminalStreams?.stop()+ await this.terminalP2p.stop()try { this.ws?.close() } catch { /* ignore */ }this.ws = null}@@ -607,6 +626,10 @@ export class BackendSocket {if (local) return local.sendFrame({ type, payload })const frame = this.e2ee.wrapTarget(connId, type, payload)if (!frame) return false+ if (this.routeTerminalOutputToP2p(connId, type, payload)) {+ if (this.terminalP2p.send(connId, JSON.stringify(frame))) return true+ this.demoteP2pConnection(connId, 'send_failed')+ }return this.sendBestEffort({t: 'up',targetConnId: connId,@@ -626,6 +649,10 @@ export class BackendSocket {}const clientFrame = this.e2ee.wrapTerminalBinary(connId, clear)if (!clientFrame) return false+ if (this.p2pStreams.get(connId)?.has(clear.streamId)) {+ if (this.terminalP2p.send(connId, Buffer.from(clientFrame))) return true+ this.demoteP2pConnection(connId, 'send_failed')+ }const packet = encodeTerminalHop(TerminalHopDirection.up, connId, clientFrame)if (!packet || !this.ws || this.ws.readyState !== WebSocket.OPEN) return falsetry { this.ws.send(packet); return true } catch { return false }@@ -703,12 +730,76 @@ export class BackendSocket {return false}- private enqueueDown(frame: Frame, connId: string): void {+ private sendP2pSignal(connId: string, type: string, payload: TerminalP2pSignal): void {+ const frame = this.e2ee.wrapTarget(connId, type, { ...payload })+ if (frame) this.sendTo(connId, frame)+ }++ private handleP2pData(connId: string, data: TerminalP2pData): void {+ if (typeof data === 'string') {+ if (Buffer.byteLength(data, 'utf8') > 512 * 1024) return+ let frame: Frame+ try { frame = JSON.parse(data) as Frame } catch { return }+ if (typeof frame.type !== 'string' || !TERMINAL_P2P_DOWN_TYPES.has(frame.type)) return+ this.enqueueDown(frame, connId, 'p2p')+ return+ }+ if (data.length > 512 * 1024) return+ this.enqueueTerminalBinary(connId, data)+ }++ private noteTerminalInputRoute(+ connId: string,+ type: string,+ payload: Record<string, unknown>,+ transport: 'relay' | 'p2p',+ ): void {+ if (type === 'terminal_open' && typeof payload.requestId === 'string') {+ let pending = this.p2pPendingOpens.get(connId)+ if (!pending) { pending = new Set(); this.p2pPendingOpens.set(connId, pending) }+ if (transport === 'p2p') pending.add(payload.requestId)+ else pending.delete(payload.requestId)+ return+ }+ const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''+ if (transport === 'relay' && streamId) this.p2pStreams.get(connId)?.delete(streamId)+ }++ private routeTerminalOutputToP2p(connId: string, type: string, payload: Record<string, unknown>): boolean {+ const requestId = typeof payload.requestId === 'string' ? payload.requestId : ''+ const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''+ const pending = this.p2pPendingOpens.get(connId)+ if ((type === 'terminal_ready' || type === 'terminal_error') && requestId && pending?.has(requestId)) {+ pending.delete(requestId)+ if (pending.size === 0) this.p2pPendingOpens.delete(connId)+ if (type === 'terminal_ready' && streamId) {+ let streams = this.p2pStreams.get(connId)+ if (!streams) { streams = new Set(); this.p2pStreams.set(connId, streams) }+ streams.add(streamId)+ }+ return true+ }+ const streams = this.p2pStreams.get(connId)+ const selected = !!streamId && streams?.has(streamId) === true+ if (selected && type === 'terminal_closed') {+ streams!.delete(streamId)+ if (streams!.size === 0) this.p2pStreams.delete(connId)+ }+ return selected+ }++ private demoteP2pConnection(connId: string, reason: string): void {+ this.p2pPendingOpens.delete(connId)+ this.p2pStreams.delete(connId)+ console.warn(`[terminal-p2p] conn=${sid(connId)} fallback=relay reason=${reason}`)+ }++ private enqueueDown(frame: Frame, connId: string, transport: 'relay' | 'p2p' = 'relay'): void {const key = connId || '__backend__'const previous = this.downChains.get(key) ?? Promise.resolve()const next = previous.catch(() => { /* prior failure is already logged */ })- .then(() => this.dispatchDown(frame, connId))+ .then(() => this.dispatchDown(frame, connId, transport)).catch((err) => {console.error('[backend] down-frame dispatch failed:', err instanceof Error ? err.message : err)})@@ -824,7 +915,7 @@ export class BackendSocket {this.send({ type: resultType, payload: { requestId, ...payload } })}- private async dispatchDown(frame: Frame, connId: string): Promise<void> {+ private async dispatchDown(frame: Frame, connId: string, transport: 'relay' | 'p2p' = 'relay'): Promise<void> {const type = frame.type as string | undefinedif (!type) returnconst local = this.localClients.has(connId)@@ -849,6 +940,10 @@ export class BackendSocket {if (!dec) returnframe = dec}+ if (!local && TERMINAL_P2P_SIGNAL_TYPES.has(type)) {+ await this.terminalP2p.handleSignal(connId, type, frame.payload)+ return+ }// Logged AFTER the unwrap above, so a down-frame reads as what the client actually asked for rather// than as an opaque __e2e envelope.// Terminal frames contain raw keystrokes, paste text and screen bytes after@@ -886,6 +981,9 @@ export class BackendSocket {// connection-scoped state immediately; otherwise a dead Desktop keeps a// terminal controller lease until the 30-second heartbeat timeout.this.e2ee.dropSession(connId)+ await this.terminalP2p.closeConnection(connId, 'client_disconnected', false)+ this.p2pPendingOpens.delete(connId)+ this.p2pStreams.delete(connId)await this.terminalStreams?.closeConnection(connId,'client connection closed',@@ -911,6 +1009,7 @@ export class BackendSocket {const requestId = payload.requestIdif (type.startsWith('terminal_')) {+ this.noteTerminalInputRoute(connId, type, payload, transport)if (this.terminalStreams) await this.terminalStreams.handleFrame(connId, type, payload)return}diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.tsindex 705389288..9add236c4 100644--- a/cli/src/lib/e2ee/core.test.ts+++ b/cli/src/lib/e2ee/core.test.ts@@ -187,6 +187,6 @@ describe('e2ee core — interop keystone', () => {it('core.ts still hashes to the pinned value shared with the other implementations', () => {const here = dirname(fileURLToPath(import.meta.url))const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')- expect(actual).toBe('7f348978c7900f3221f4e77555ed2bbf9606ff1740562587d6d908d95bbd7ac3')+ expect(actual).toBe('99737b4f286931f4b7cc9956ab069012d818b109458992a6a331ca44811dfc38')})})diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.tsindex ddbff7406..0d454ba5f 100644--- a/cli/src/lib/e2ee/core.ts+++ b/cli/src/lib/e2ee/core.ts@@ -370,6 +370,9 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>([// never see agent ids, terminal bytes, dimensions, sequence numbers, or capability metadata.'terminal_capabilities', 'terminal_open', 'terminal_alive', 'terminal_ack', 'terminal_input','terminal_resize', 'terminal_resync', 'terminal_close', 'terminal_scroll',+ // WebRTC signaling reveals both peers' network candidates. Keep it inside the already-authenticated+ // pairwise session; the backend needs only the outer type + connId to route it.+ 'p2p_offer', 'p2p_answer', 'p2p_ice_candidate', 'p2p_abort',])export function isEncryptedUpType(t: string): boolean { return ENCRYPTED_UP_TYPES.has(t) }export function isEncryptedRpcResultType(t: string): boolean { return ENCRYPTED_RPC_RESULT_TYPES.has(t) }diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.tsindex 7d7acc463..73e491167 100644--- a/cli/src/lib/e2ee/manager.ts+++ b/cli/src/lib/e2ee/manager.ts@@ -25,6 +25,7 @@ import {} from '../terminalBinary.js'import { E2eeStore } from './store.js'import { pwCpaceGenerator, pwContext } from './passwordPake.js'+import { ReplayWindow } from './replayWindow.js'type Frame = Record<string, unknown>@@ -65,11 +66,11 @@ interface Session {c2s: Uint8Array // web → adapter (down message)s2c: Uint8Array // adapter → web (welcome + targeted RPC replies)s2cCounter: number // next send counter (0 was the welcome)- c2sRecv: number // highest counter seen (replay guard)+ c2sRecv: ReplayWindow // bounded replay guard; permits cross-transport reorderingterminalC2s: Uint8ArrayterminalS2c: Uint8ArrayterminalS2cCounter: number- terminalC2sRecv: number+ terminalC2sRecv: ReplayWindow}const PAIR_TTL_MS = 60_000@@ -325,10 +326,10 @@ export class E2eeManager {const session = this.sessions.get(connId)if (!session) return nullconst envelope = parseTerminalBinaryEnvelope(raw)- if (!envelope || (session.terminalC2sRecv !== -1 && envelope.counter <= session.terminalC2sRecv)) return null+ if (!envelope || !session.terminalC2sRecv.allows(envelope.counter)) return nullconst opened = openTerminalBinary(session.terminalC2s, raw)if (!opened) return null- session.terminalC2sRecv = opened.counter+ session.terminalC2sRecv.commit(opened.counter)return opened.frame}@@ -345,10 +346,10 @@ export class E2eeManager {// (__e2e null, missing/non-string ct, non-number n) would make the deref / b64d below throw and// crash the daemon. Anything that isn't the expected shape is dropped like an undecryptable frame.if (!env || typeof env !== 'object' || typeof env.n !== 'number' || typeof env.ct !== 'string') return null- if (s.c2sRecv !== -1 && env.n <= s.c2sRecv) return null // replay / reorder — drop+ if (!s.c2sRecv.allows(env.n)) return nullconst plain = C.unwrapPayload(s.c2s, env, frame.type as string, frame.dbSessionId as string | undefined)if (plain === null) return null- s.c2sRecv = env.n+ s.c2sRecv.commit(env.n)return { ...frame, payload: plain }}@@ -714,14 +715,18 @@ export class E2eeManager {c2s: keys.c2s,s2c: keys.s2c,s2cCounter: 1,- c2sRecv: -1,+ c2sRecv: new ReplayWindow(),terminalC2s: deriveTerminalBinaryKey(keys.c2s),terminalS2c: deriveTerminalBinaryKey(keys.s2c),terminalS2cCounter: 0,- terminalC2sRecv: -1,+ terminalC2sRecv: new ReplayWindow(),})const id = this.store.getIdentity()- const enc = C.aeadSeal(keys.s2c, 0, C.utf8('e2e-welcome'), C.utf8(JSON.stringify({ groupKey: C.b64e(this.groupKey), epoch: this.epoch })))+ const enc = C.aeadSeal(keys.s2c, 0, C.utf8('e2e-welcome'), C.utf8(JSON.stringify({+ groupKey: C.b64e(this.groupKey),+ epoch: this.epoch,+ features: { terminalP2p: 1 },+ })))this.deps.sendTo(connId, {type: 'e2e_welcome',payload: {diff --git a/cli/src/lib/e2ee/relayClient.ts b/cli/src/lib/e2ee/relayClient.tsindex 49b49c8f2..60637721d 100644--- a/cli/src/lib/e2ee/relayClient.ts+++ b/cli/src/lib/e2ee/relayClient.ts@@ -13,6 +13,7 @@ import { WebSocket } from 'ws'import * as C from './core.js'import { deriveTerminalBinaryKey, openTerminalBinary, sealTerminalBinary, type TerminalBinaryClear } from '../terminalBinary.js'import { pwCpaceGenerator, pwContext, stretchPassword } from './passwordPake.js'+import { ReplayWindow } from './replayWindow.js'type Frame = Record<string, unknown>@@ -29,16 +30,18 @@ export class RelaySessionCrypto {private terminalC2s: Uint8Array | null = nullprivate terminalS2c: Uint8Array | null = nullprivate c2sCounter = 0- private s2cRecv = -1+ private readonly s2cRecv = new ReplayWindow()private terminalC2sCounter = 0- private terminalS2cRecv = -1+ private readonly terminalS2cRecv = new ReplayWindow()private groupKey: Uint8Array | null = nullprivate epoch = ''+ private p2pVersion = 0private groupRecv = new Map<string, number>() // epoch -> highest counter seenconstructor(private readonly deps: RelayCryptoDeps) {}get ready(): boolean { return this.c2s !== null && this.s2c !== null }+ get terminalP2pVersion(): number { return this.p2pVersion }helloFrame(): Frame {return {@@ -66,8 +69,8 @@ export class RelaySessionCrypto {} catch { return false }const opened = C.aeadOpen(keys.s2c, 0, C.utf8('e2e-welcome'), C.b64d(encB64))if (!opened) return false- let initial: { groupKey?: string; epoch?: string }- try { initial = JSON.parse(new TextDecoder().decode(opened)) as { groupKey?: string; epoch?: string } } catch { return false }+ let initial: { groupKey?: string; epoch?: string; features?: { terminalP2p?: unknown } }+ try { initial = JSON.parse(new TextDecoder().decode(opened)) as typeof initial } catch { return false }if (!initial.groupKey || !initial.epoch) return falsethis.c2s = keys.c2sthis.s2c = keys.s2c@@ -75,6 +78,9 @@ export class RelaySessionCrypto {this.terminalS2c = deriveTerminalBinaryKey(keys.s2c)this.groupKey = C.b64d(initial.groupKey)this.epoch = initial.epoch+ this.p2pVersion = Number.isSafeInteger(initial.features?.terminalP2p)+ ? Number(initial.features?.terminalP2p)+ : 0return true}@@ -121,10 +127,10 @@ export class RelaySessionCrypto {return { ...frame, payload: plain }}if (!this.s2c) return null- if (env.n <= this.s2cRecv) return null+ if (!this.s2cRecv.allows(env.n)) return nullconst plain = C.unwrapPayload(this.s2c, env, type, frame.dbSessionId as string | undefined)if (plain === null) return null- this.s2cRecv = env.n+ this.s2cRecv.commit(env.n)return { ...frame, payload: plain }}@@ -141,8 +147,8 @@ export class RelaySessionCrypto {decryptTerminal(raw: Uint8Array): TerminalBinaryClear | null {if (!this.terminalS2c) return nullconst opened = openTerminalBinary(this.terminalS2c, raw)- if (!opened || (this.terminalS2cRecv !== -1 && opened.counter <= this.terminalS2cRecv)) return null- this.terminalS2cRecv = opened.counter+ if (!opened || !this.terminalS2cRecv.allows(opened.counter)) return null+ this.terminalS2cRecv.commit(opened.counter)return opened.frame}}diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.tsindex ec6b68f48..482b225b7 100644--- a/cli/src/lib/e2ee/relayLink.spec.ts+++ b/cli/src/lib/e2ee/relayLink.spec.ts@@ -115,6 +115,7 @@ describe('remote-password link + relay session crypto (interop with the real E2eexpect(welcome.type).toBe('e2e_welcome')expect(crypto.handleWelcome(welcome.payload as Record<string, unknown>)).toBe(true)expect(crypto.ready).toBe(true)+ expect(crypto.terminalP2pVersion).toBe(1)// Outgoing: client encrypts a down-type frame; manager decrypts it via unwrapDown.const outgoing = crypto.wrapOutgoing({ type: 'terminal_input', payload: { requestId: 'r1', foo: 'bar' } })@@ -123,6 +124,12 @@ describe('remote-password link + relay session crypto (interop with the real E2eexpect(decrypted).not.toBeNull()expect((decrypted!.payload as Record<string, unknown>).foo).toBe('bar')+ const lowerDown = crypto.wrapOutgoing({ type: 'terminal_resize', payload: { streamId: 's', cols: 80 } })+ const higherDown = crypto.wrapOutgoing({ type: 'terminal_resize', payload: { streamId: 's', cols: 120 } })+ expect((manager.unwrapDown('session-conn', higherDown)?.payload as Record<string, unknown>).cols).toBe(120)+ expect((manager.unwrapDown('session-conn', lowerDown)?.payload as Record<string, unknown>).cols).toBe(80)+ expect(manager.unwrapDown('session-conn', lowerDown)).toBeNull()+// Incoming: manager broadcasts a group-encrypted up event; client decrypts it.const wrappedUp = manager.wrapUp({ type: 'user_message', payload: { text: 'hi' } })const plainUp = crypto.unwrapIncoming(wrappedUp)@@ -136,10 +143,30 @@ describe('remote-password link + relay session crypto (interop with the real E2econst openedByAdapter = manager.unwrapTerminalBinary('session-conn', sealedOut!)expect(openedByAdapter?.bytes).toEqual(clear.bytes)+ const lowerInput = crypto.encryptTerminal({ ...clear, seq: 2 })!+ const higherInput = crypto.encryptTerminal({ ...clear, seq: 3 })!+ expect(manager.unwrapTerminalBinary('session-conn', higherInput)?.seq).toBe(3)+ expect(manager.unwrapTerminalBinary('session-conn', lowerInput)?.seq).toBe(2)+ expect(manager.unwrapTerminalBinary('session-conn', lowerInput)).toBeNull()+const sealedIn = manager.wrapTerminalBinary('session-conn', { ...clear, kind: 2 })expect(sealedIn).not.toBeNull()const openedByClient = crypto.decryptTerminal(sealedIn!)expect(openedByClient?.bytes).toEqual(clear.bytes)++ // WebSocket RPC/control and WebRTC terminal frames share counters but can cross in flight.+ // Authentic out-of-order frames inside the replay window must both survive; duplicates must not.+ const lower = manager.wrapTarget('session-conn', 'terminal_ready', { streamId: 'lower' })!+ const higher = manager.wrapTarget('session-conn', 'terminal_ready', { streamId: 'higher' })!+ expect((crypto.unwrapIncoming(higher)?.payload as Record<string, unknown>).streamId).toBe('higher')+ expect((crypto.unwrapIncoming(lower)?.payload as Record<string, unknown>).streamId).toBe('lower')+ expect(crypto.unwrapIncoming(lower)).toBeNull()++ const lowerBinary = manager.wrapTerminalBinary('session-conn', { ...clear, kind: 2, seq: 2 })!+ const higherBinary = manager.wrapTerminalBinary('session-conn', { ...clear, kind: 2, seq: 3 })!+ expect(crypto.decryptTerminal(higherBinary)?.seq).toBe(3)+ expect(crypto.decryptTerminal(lowerBinary)?.seq).toBe(2)+ expect(crypto.decryptTerminal(lowerBinary)).toBeNull()} finally {await new Promise<void>((resolve) => wss.close(() => resolve()))}diff --git a/cli/src/lib/e2ee/replayWindow.spec.ts b/cli/src/lib/e2ee/replayWindow.spec.tsnew file mode 100644index 000000000..dcd507ca4--- /dev/null+++ b/cli/src/lib/e2ee/replayWindow.spec.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest'+import { E2EE_REPLAY_WINDOW_SIZE, ReplayWindow } from './replayWindow.js'++describe('E2EE replay window', () => {+ it('accepts authentic counters arriving out of order once, then rejects replays', () => {+ const window = new ReplayWindow()+ expect(window.allows(2)).toBe(true)+ window.commit(2)+ expect(window.allows(0)).toBe(true)+ window.commit(0)+ expect(window.allows(1)).toBe(true)+ window.commit(1)+ expect(window.allows(0)).toBe(false)+ expect(window.allows(2)).toBe(false)+ })++ it('rejects counters older than the bounded transport-reordering window', () => {+ const window = new ReplayWindow()+ window.commit(E2EE_REPLAY_WINDOW_SIZE + 7)+ expect(window.allows(7)).toBe(false)+ expect(window.allows(8)).toBe(true)+ })+})diff --git a/cli/src/lib/e2ee/replayWindow.ts b/cli/src/lib/e2ee/replayWindow.tsnew file mode 100644index 000000000..4aa140629--- /dev/null+++ b/cli/src/lib/e2ee/replayWindow.ts@@ -0,0 +1,35 @@+// P2P terminal frames and WebSocket RPC/control frames intentionally share one E2EE key/counter+// domain. They can arrive out of order across the two reliable transports, so a strict "highest+// counter wins" guard would discard authentic frames. This bounded window still rejects duplicates+// and stale counters without requiring transport-specific keys or counter resets during fallback.+export const E2EE_REPLAY_WINDOW_SIZE = 4_096++export class ReplayWindow {+ private highest = -1+ private prunedThrough = -1+ private readonly seen = new Set<number>()++ allows(counter: number): boolean {+ return Number.isSafeInteger(counter)+ && counter >= 0+ && !this.seen.has(counter)+ && (this.highest < 0 || counter > this.highest - E2EE_REPLAY_WINDOW_SIZE)+ }++ commit(counter: number): void {+ this.seen.add(counter)+ if (counter <= this.highest) return+ this.highest = counter+ const oldest = this.highest - E2EE_REPLAY_WINDOW_SIZE+ if (oldest <= this.prunedThrough) return+ // Sequential traffic deletes one integer per commit. A valid counter jumping far ahead makes the+ // entire old set stale; clear it instead of looping across a hostile-sized numeric gap.+ if (oldest - this.prunedThrough > E2EE_REPLAY_WINDOW_SIZE) {+ this.seen.clear()+ this.seen.add(counter)+ } else {+ for (let value = this.prunedThrough + 1; value <= oldest; value++) this.seen.delete(value)+ }+ this.prunedThrough = oldest+ }+}diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.tsindex 6c3f14707..18e29bd52 100644--- a/cli/src/lib/remoteRelay.ts+++ b/cli/src/lib/remoteRelay.ts@@ -18,7 +18,15 @@ import type { AuthSessionManager } from './authSession.js'import { b64d, type Identity } from './e2ee/core.js'import type { MachinePeerStore } from './e2ee/machinePeers.js'import { RelaySessionCrypto } from './e2ee/relayClient.js'-import { encodeTerminalLocal, type TerminalBinaryClear } from './terminalBinary.js'+import { encodeTerminalLocal, TerminalBinaryKind, type TerminalBinaryClear } from './terminalBinary.js'+import {+ TerminalP2pInitiator,+ TERMINAL_P2P_PROTOCOL_VERSION,+ TERMINAL_P2P_SIGNAL_TYPES,+ TERMINAL_P2P_UP_TYPES,+ type TerminalP2pData,+ type TerminalP2pPolicy,+} from './terminalP2p.js'const CONNECT_TIMEOUT_MS = 15_000const LINGER_MS = 30_000@@ -51,14 +59,37 @@ interface Entry {lingerTimer: ReturnType<typeof setTimeout> | nullalive: booleanheartbeatTimer: ReturnType<typeof setInterval> | null+ p2p: TerminalP2pInitiator | null+ p2pPolicy: TerminalP2pPolicy | null+ p2pPendingOpens: Set<string>+ p2pStreams: Set<string>}export interface RelaySession {- send: (frame: Frame) => void- sendBinary: (clear: TerminalBinaryClear) => void+ send: (frame: Frame) => Promise<void>+ sendBinary: (clear: TerminalBinaryClear) => Promise<void>detach: () => void}+function p2pPolicy(value: unknown): TerminalP2pPolicy | null {+ if (!value || typeof value !== 'object') return null+ const raw = value as Record<string, unknown>+ if (raw.enabled !== true || raw.protocolVersion !== TERMINAL_P2P_PROTOCOL_VERSION) return null+ const stunUrls = Array.isArray(raw.stunUrls)+ ? raw.stunUrls.filter((url): url is string => typeof url === 'string' && /^stuns?:/i.test(url)).slice(0, 4)+ : []+ const openWaitMs = typeof raw.openWaitMs === 'number' && Number.isSafeInteger(raw.openWaitMs)+ ? Math.max(0, Math.min(5_000, raw.openWaitMs))+ : 1_500+ return { enabled: true, protocolVersion: TERMINAL_P2P_PROTOCOL_VERSION, stunUrls, openWaitMs }+}++function framePayload(frame: Frame): Record<string, unknown> {+ return frame.payload && typeof frame.payload === 'object'+ ? frame.payload as Record<string, unknown>+ : {}+}+export class RemoteRelayPool {private entries = new Map<string, Entry>()private pending = new Map<string, Promise<Entry>>()@@ -87,6 +118,8 @@ export class RemoteRelayPool {// `ws.on('close', ...)` cleanup below doesn't turn around and close that same local socket via a// now-stale onClosed callback.entry.onClosed = null+ void entry.p2p?.stop('invalidated', false)+ entry.p2p = nulltry { entry.ws.terminate() } catch { /* already gone */ }}@@ -155,6 +188,10 @@ export class RemoteRelayPool {lingerTimer: null,alive: true,heartbeatTimer: null,+ p2p: null,+ p2pPolicy: null,+ p2pPendingOpens: new Set(),+ p2pStreams: new Set(),}// Two phases before this connection is usable: (1) machine_select ack, (2) this daemon's own// e2e_hello/e2e_welcome as the "client" role — see lib/e2ee/relayClient.ts. Only once BOTH are done@@ -173,13 +210,14 @@ export class RemoteRelayPool {if (isBinary) returnlet frame: Frametry { frame = JSON.parse(raw.toString()) as Frame } catch { return }- const payload = frame.payload as { machineId?: unknown; error?: unknown } | undefined+ const payload = frame.payload as { machineId?: unknown; error?: unknown; p2p?: unknown } | undefinedif (!selected) {// The socket's very first frame, before any select, is {type:'connected',payload:{userId}} —// pure backend bookkeeping with no machineId. Swallow it; it answers nothing this relay asked.if (frame.type === 'connected' && payload?.machineId === undefined) returnif (frame.type === 'connected' && payload?.machineId === machineId) {selected = true+ entry.p2pPolicy = p2pPolicy(payload.p2p)try { ws.send(JSON.stringify(crypto.helloFrame())) } catch { /* the close handler below rejects */ }return}@@ -195,6 +233,9 @@ export class RemoteRelayPool {if (frame.type === 'e2e_welcome') {const ok = crypto.handleWelcome((frame.payload ?? {}) as Record<string, unknown>)if (!ok) { if (!settled) { settled = true; clearTimeout(timeout); reject(new RelayConnectError('E2EE_WELCOME_INVALID')) } ; return }+ if (entry.p2pPolicy && crypto.terminalP2pVersion === TERMINAL_P2P_PROTOCOL_VERSION) {+ this.startP2p(entry)+ }if (!settled) { settled = true; clearTimeout(timeout); resolve() }return}@@ -219,6 +260,7 @@ export class RemoteRelayPool {if (isBinary) {const clear = crypto.decryptTerminal(binaryBytes(raw))if (!clear) return // undecryptable/stale — drop, never forward ciphertext or garbage to the app+ if (entry.p2pStreams.has(clear.streamId)) this.demoteP2p(entry, 'relay_binary_received')const local = encodeTerminalLocal(clear)if (local) entry.sink?.sendBinary(local)return@@ -237,7 +279,14 @@ export class RemoteRelayPool {return}const plain = crypto.unwrapIncoming(frame)- if (plain) entry.sink?.sendFrame(plain)+ if (!plain) return+ const type = typeof plain.type === 'string' ? plain.type : ''+ if (TERMINAL_P2P_SIGNAL_TYPES.has(type)) {+ void entry.p2p?.handleSignal(type, plain.payload)+ return+ }+ this.noteTerminalResponse(entry, plain, 'relay')+ entry.sink?.sendFrame(plain)})ws.once('close', (code, reasonBuf) => {if (!settled) {@@ -252,6 +301,8 @@ export class RemoteRelayPool {// Handshake done — from here on, a close is the entry's real end-of-life, not a handshake failure.ws.on('close', (code, reasonBuf) => {if (entry.heartbeatTimer) clearInterval(entry.heartbeatTimer)+ void entry.p2p?.stop('relay_closed', false)+ entry.p2p = nullthis.entries.delete(machineId)entry.onClosed?.(code, reasonBuf?.toString() ?? '')})@@ -268,19 +319,37 @@ export class RemoteRelayPool {private sessionFor(machineId: string, entry: Entry): RelaySession {return {- send: (frame) => {- try { entry.ws.send(JSON.stringify(entry.crypto.wrapOutgoing(frame))) } catch { /* closed — onClosed will fire */ }+ send: async (frame) => {+ const payload = framePayload(frame)+ let useP2p = typeof payload.streamId === 'string' && entry.p2pStreams.has(payload.streamId)+ if (frame.type === 'terminal_open' && typeof payload.requestId === 'string' && entry.p2p) {+ useP2p = entry.p2p.isReady || await entry.p2p.waitUntilReady(entry.p2pPolicy?.openWaitMs ?? 1_500)+ if (useP2p) entry.p2pPendingOpens.add(payload.requestId)+ else this.reportP2pResult(entry, 'relay', undefined, 'open_wait_elapsed')+ }+ const wrapped = entry.crypto.wrapOutgoing(frame)+ if (useP2p && entry.p2p?.send(JSON.stringify(wrapped))) {+ if (frame.type === 'terminal_close' && typeof payload.streamId === 'string') entry.p2pStreams.delete(payload.streamId)+ return+ }+ try { entry.ws.send(JSON.stringify(wrapped)) } catch { /* closed — onClosed will fire */ }+ if (useP2p) this.demoteP2p(entry, 'send_failed')},- sendBinary: (clear) => {+ sendBinary: async (clear) => {const sealed = entry.crypto.encryptTerminal(clear)if (!sealed) return+ if (entry.p2pStreams.has(clear.streamId) && entry.p2p?.send(Buffer.from(sealed))) return+ const p2pFailed = entry.p2pStreams.has(clear.streamId)try { entry.ws.send(sealed, { binary: true }) } catch { /* closed — onClosed will fire */ }+ if (p2pFailed) this.demoteP2p(entry, 'send_failed')},detach: () => {entry.sink = nullentry.onClosed = nullentry.lingerTimer = setTimeout(() => {if (!entry.sink) {+ void entry.p2p?.stop('idle', false)+ entry.p2p = nulltry { entry.ws.close(1000, 'idle') } catch { /* ignore */ }this.entries.delete(machineId)}@@ -289,4 +358,89 @@ export class RemoteRelayPool {},}}++ private startP2p(entry: Entry): void {+ const policy = entry.p2pPolicy+ if (!policy || entry.p2p) return+ let wasDirect = false+ const p2p = new TerminalP2pInitiator({+ policy,+ sendSignal: (type, payload) => {+ const wrapped = entry.crypto.wrapOutgoing({ type, payload })+ try { entry.ws.send(JSON.stringify(wrapped)) } catch { /* relay close handles cleanup */ }+ },+ onData: (data) => this.handleP2pData(entry, data),+ onState: (state, setupMs, reason) => {+ if (state === 'direct') {+ wasDirect = true+ this.reportP2pResult(entry, 'direct', setupMs)+ } else if (state === 'failed' && !wasDirect) {+ this.reportP2pResult(entry, reason === 'negotiation_timeout' ? 'timeout' : 'failed', setupMs, reason)+ }+ },+ onUnavailable: (reason) => this.demoteP2p(entry, reason),+ })+ entry.p2p = p2p+ p2p.start()+ }++ private handleP2pData(entry: Entry, data: TerminalP2pData): void {+ if (typeof data !== 'string') {+ const clear = entry.crypto.decryptTerminal(new Uint8Array(data.buffer, data.byteOffset, data.byteLength))+ if (!clear) return+ if (clear.kind !== TerminalBinaryKind.output && clear.kind !== TerminalBinaryKind.keyframe+ && clear.kind !== TerminalBinaryKind.sync) return+ const local = encodeTerminalLocal(clear)+ if (local) entry.sink?.sendBinary(local)+ return+ }+ let wrapped: Frame+ try { wrapped = JSON.parse(data) as Frame } catch { return }+ if (typeof wrapped.type !== 'string' || !TERMINAL_P2P_UP_TYPES.has(wrapped.type)) return+ const plain = entry.crypto.unwrapIncoming(wrapped)+ if (!plain) return+ this.noteTerminalResponse(entry, plain, 'p2p')+ entry.sink?.sendFrame(plain)+ }++ private noteTerminalResponse(entry: Entry, frame: Frame, transport: 'p2p' | 'relay'): void {+ const payload = framePayload(frame)+ const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''+ const requestId = typeof payload.requestId === 'string' ? payload.requestId : ''+ if (frame.type === 'terminal_ready' && requestId && streamId) {+ if (entry.p2pPendingOpens.delete(requestId) && transport === 'p2p') entry.p2pStreams.add(streamId)+ } else if (frame.type === 'terminal_error' && requestId) {+ entry.p2pPendingOpens.delete(requestId)+ } else if (frame.type === 'terminal_closed' && streamId) {+ entry.p2pStreams.delete(streamId)+ }+ if (transport === 'relay' && streamId) entry.p2pStreams.delete(streamId)+ }++ private demoteP2p(entry: Entry, reason: string): void {+ const p2p = entry.p2p+ entry.p2p = null+ const streamIds = [...entry.p2pStreams]+ entry.p2pStreams.clear()+ entry.p2pPendingOpens.clear()+ for (const streamId of streamIds) {+ const resync = entry.crypto.wrapOutgoing({ type: 'terminal_resync', payload: { streamId } })+ try { entry.ws.send(JSON.stringify(resync)) } catch { /* relay close handles cleanup */ }+ }+ if (streamIds.length > 0) this.reportP2pResult(entry, 'dropped', undefined, reason)+ void p2p?.stop(reason)+ }++ private reportP2pResult(entry: Entry, outcome: string, setupMs?: number, reason?: string): void {+ try {+ entry.ws.send(JSON.stringify({+ type: 'p2p_result',+ payload: {+ outcome,+ ...(Number.isFinite(setupMs) ? { setupMs: Math.max(0, Math.round(setupMs!)) } : {}),+ ...(reason ? { reason: reason.slice(0, 64) } : {}),+ },+ }))+ } catch { /* diagnostics must never affect terminal transport */ }+ }}diff --git a/cli/src/lib/terminalP2p.spec.ts b/cli/src/lib/terminalP2p.spec.tsnew file mode 100644index 000000000..2d39111ea--- /dev/null+++ b/cli/src/lib/terminalP2p.spec.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest'+import { TerminalP2pInitiator, TerminalP2pResponderPool } from './terminalP2p.js'++describe('terminal WebRTC data channel', () => {+ it('negotiates locally and carries ordered text and binary frames in both directions', async () => {+ let resolveResponderData!: (value: string) => void+ let resolveInitiatorData!: (value: Buffer) => void+ const responderData = new Promise<string>((resolve) => { resolveResponderData = resolve })+ const initiatorData = new Promise<Buffer>((resolve) => { resolveInitiatorData = resolve })+ let initiator!: TerminalP2pInitiator+ const responder = new TerminalP2pResponderPool({+ sendSignal: (_connId, type, payload) => { void initiator.handleSignal(type, payload) },+ onData: (_connId, data) => resolveResponderData(typeof data === 'string' ? data : data.toString()),+ })+ initiator = new TerminalP2pInitiator({+ policy: { enabled: true, protocolVersion: 1, stunUrls: [], openWaitMs: 1_500 },+ sendSignal: (type, payload) => { void responder.handleSignal('source-1', type, payload) },+ onData: (data) => resolveInitiatorData(typeof data === 'string' ? Buffer.from(data) : data),+ })++ try {+ initiator.start()+ expect(await initiator.waitUntilReady(5_000)).toBe(true)+ expect(initiator.send('terminal-input')).toBe(true)+ expect(await responderData).toBe('terminal-input')++ expect(responder.send('source-1', Buffer.from([0x48, 0x54, 0x52, 0x4d]))).toBe(true)+ expect(await initiatorData).toEqual(Buffer.from([0x48, 0x54, 0x52, 0x4d]))+ } finally {+ await initiator.stop('test_complete', false)+ await responder.stop()+ }+ }, 10_000)+})diff --git a/cli/src/lib/terminalP2p.ts b/cli/src/lib/terminalP2p.tsnew file mode 100644index 000000000..d93626dec--- /dev/null+++ b/cli/src/lib/terminalP2p.ts@@ -0,0 +1,386 @@+import { randomUUID } from 'node:crypto'+import { RTCPeerConnection, type RTCDataChannel, type RTCIceCandidateInit } from 'werift'++export const TERMINAL_P2P_PROTOCOL_VERSION = 1+export const TERMINAL_P2P_CHANNEL = 'terminal-v1'+export const TERMINAL_P2P_NEGOTIATION_TIMEOUT_MS = 10_000+export const TERMINAL_P2P_MAX_BUFFERED_BYTES = 2 * 1024 * 1024++export const TERMINAL_P2P_SIGNAL_TYPES = new Set([+ 'p2p_offer',+ 'p2p_answer',+ 'p2p_ice_candidate',+ 'p2p_abort',+])++export const TERMINAL_P2P_DOWN_TYPES = new Set([+ 'terminal_capabilities', 'terminal_open', 'terminal_alive', 'terminal_ack',+ 'terminal_input', 'terminal_resize', 'terminal_resync', 'terminal_close', 'terminal_scroll',+])++export const TERMINAL_P2P_UP_TYPES = new Set([+ 'terminal_capabilities_result', 'terminal_ready', 'terminal_keyframe',+ 'terminal_output', 'terminal_closed', 'terminal_error',+])++export type TerminalP2pState = 'connecting' | 'direct' | 'failed' | 'closed'+export type TerminalP2pData = string | Buffer++export interface TerminalP2pPolicy {+ enabled: boolean+ protocolVersion: number+ stunUrls: string[]+ openWaitMs: number+}++export interface TerminalP2pSignal {+ sessionId: string+ protocolVersion: number+ sdp?: string+ candidate?: RTCIceCandidateInit | null+ reason?: string+ stunUrls?: string[]+}++export interface TerminalP2pInitiatorDeps {+ policy: TerminalP2pPolicy+ sendSignal: (type: string, payload: TerminalP2pSignal) => void+ onData: (data: TerminalP2pData) => void+ onState?: (state: TerminalP2pState, setupMs: number, reason?: string) => void+ onUnavailable?: (reason: string) => void+ now?: () => number+}++type ReadyWaiter = (ready: boolean) => void++function validSessionId(value: unknown): value is string {+ return typeof value === 'string' && /^[0-9a-f-]{36}$/i.test(value)+}++function parseSignal(value: unknown): TerminalP2pSignal | null {+ if (!value || typeof value !== 'object') return null+ const payload = value as Record<string, unknown>+ if (!validSessionId(payload.sessionId)+ || payload.protocolVersion !== TERMINAL_P2P_PROTOCOL_VERSION) return null+ return payload as unknown as TerminalP2pSignal+}++function peerConfig(stunUrls: string[]): ConstructorParameters<typeof RTCPeerConnection>[0] {+ return {+ iceServers: stunUrls.length > 0 ? [{ urls: stunUrls }] : [],+ // Terminal keyframes can approach 480 KiB. SCTP fragments them, but advertise enough room so+ // the peer never rejects the message at the WebRTC API boundary before fragmentation happens.+ maxMessageSize: 512 * 1024,+ }+}++function channelCanSend(channel: RTCDataChannel | null): channel is RTCDataChannel {+ return channel?.readyState === 'open'+ && channel.bufferedAmount < TERMINAL_P2P_MAX_BUFFERED_BYTES+}++/** Source side: owns the offerer for one pooled remote-machine relay connection. */+export class TerminalP2pInitiator {+ readonly sessionId = randomUUID()+ private readonly startedAt: number+ private readonly now: () => number+ private pc: RTCPeerConnection | null = null+ private channel: RTCDataChannel | null = null+ private ready = false+ private finished = false+ private timeout: ReturnType<typeof setTimeout> | null = null+ private waiters: ReadyWaiter[] = []++ constructor(private readonly deps: TerminalP2pInitiatorDeps) {+ this.now = deps.now ?? (() => Date.now())+ this.startedAt = this.now()+ }++ get isReady(): boolean { return this.ready && channelCanSend(this.channel) }++ start(): void {+ if (this.pc || this.finished || !this.deps.policy.enabled) return+ const pc = new RTCPeerConnection(peerConfig(this.deps.policy.stunUrls))+ const channel = pc.createDataChannel(TERMINAL_P2P_CHANNEL, { ordered: true })+ this.pc = pc+ this.channel = channel+ this.wirePeer(pc)+ this.wireChannel(channel)+ this.timeout = setTimeout(() => this.fail('negotiation_timeout'), TERMINAL_P2P_NEGOTIATION_TIMEOUT_MS)+ this.timeout.unref?.()+ this.deps.onState?.('connecting', 0)+ void this.createOffer(pc)+ }++ private async createOffer(pc: RTCPeerConnection): Promise<void> {+ try {+ const offer = await pc.createOffer()+ await pc.setLocalDescription(offer)+ if (this.pc !== pc || this.finished) return+ const local = pc.localDescription+ if (!local) throw new Error('local_description_missing')+ this.deps.sendSignal('p2p_offer', {+ sessionId: this.sessionId,+ protocolVersion: TERMINAL_P2P_PROTOCOL_VERSION,+ sdp: local.sdp,+ stunUrls: this.deps.policy.stunUrls,+ })+ } catch {+ this.fail('offer_failed')+ }+ }++ async handleSignal(type: string, value: unknown): Promise<boolean> {+ if (!TERMINAL_P2P_SIGNAL_TYPES.has(type)) return false+ const payload = parseSignal(value)+ if (!payload || payload.sessionId !== this.sessionId || this.finished) return true+ const pc = this.pc+ if (!pc) return true+ try {+ if (type === 'p2p_answer' && typeof payload.sdp === 'string') {+ await pc.setRemoteDescription({ type: 'answer', sdp: payload.sdp })+ } else if (type === 'p2p_ice_candidate') {+ await pc.addIceCandidate(payload.candidate ?? null)+ } else if (type === 'p2p_abort') {+ this.fail(payload.reason || 'peer_aborted')+ }+ } catch {+ this.fail('signal_invalid')+ }+ return true+ }++ send(data: TerminalP2pData): boolean {+ const channel = this.channel+ if (!this.isReady || !channelCanSend(channel)) return false+ try {+ channel.send(data)+ return true+ } catch {+ // Let the caller put the already-encrypted frame on WebSocket first. Failing synchronously+ // here can emit a higher-counter resync before that fallback frame and make it look replayed.+ queueMicrotask(() => this.fail('send_failed'))+ return false+ }+ }++ waitUntilReady(timeoutMs: number): Promise<boolean> {+ if (this.isReady) return Promise.resolve(true)+ if (this.finished || timeoutMs <= 0) return Promise.resolve(false)+ return new Promise<boolean>((resolve) => {+ let settled = false+ const done = (ready: boolean): void => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ this.waiters = this.waiters.filter((waiter) => waiter !== done)+ resolve(ready)+ }+ const timer = setTimeout(() => done(false), timeoutMs)+ timer.unref?.()+ this.waiters.push(done)+ })+ }++ async stop(reason = 'closed', notifyPeer = true): Promise<void> {+ if (this.finished) return+ this.finished = true+ this.ready = false+ if (this.timeout) clearTimeout(this.timeout)+ this.timeout = null+ for (const waiter of this.waiters.splice(0)) waiter(false)+ if (notifyPeer) {+ this.deps.sendSignal('p2p_abort', {+ sessionId: this.sessionId,+ protocolVersion: TERMINAL_P2P_PROTOCOL_VERSION,+ reason,+ })+ }+ try { this.channel?.close() } catch { /* already closed */ }+ const pc = this.pc+ this.channel = null+ this.pc = null+ if (pc) await pc.close().catch(() => { /* best effort */ })+ this.deps.onState?.('closed', this.now() - this.startedAt, reason)+ }++ private wirePeer(pc: RTCPeerConnection): void {+ pc.connectionStateChange.subscribe((state) => {+ if (this.pc !== pc || this.finished) return+ if (state === 'failed' || state === 'disconnected') this.fail(`peer_${state}`)+ })+ }++ private wireChannel(channel: RTCDataChannel): void {+ channel.bufferedAmountLowThreshold = 256 * 1024+ channel.stateChanged.subscribe((state) => {+ if (this.channel !== channel || this.finished) return+ if (state === 'open') {+ this.ready = true+ if (this.timeout) clearTimeout(this.timeout)+ this.timeout = null+ for (const waiter of this.waiters.splice(0)) waiter(true)+ this.deps.onState?.('direct', this.now() - this.startedAt)+ } else if ((state === 'closed' || state === 'closing') && this.ready) {+ this.fail('channel_closed')+ }+ })+ channel.onMessage.subscribe((data) => {+ if (this.channel === channel && !this.finished) this.deps.onData(data)+ })+ channel.error.subscribe(() => this.fail('channel_error'))+ }++ private fail(reason: string): void {+ if (this.finished) return+ const wasReady = this.ready+ this.ready = false+ this.deps.onState?.('failed', this.now() - this.startedAt, reason)+ if (wasReady) this.deps.onUnavailable?.(reason)+ void this.stop(reason)+ }+}++export interface TerminalP2pResponderPoolDeps {+ sendSignal: (connId: string, type: string, payload: TerminalP2pSignal) => void+ onData: (connId: string, data: TerminalP2pData) => void+ onUnavailable?: (connId: string, reason: string) => void+}++interface ResponderEntry {+ sessionId: string+ pc: RTCPeerConnection+ channel: RTCDataChannel | null+ ready: boolean+ timeout: ReturnType<typeof setTimeout>+ closing: boolean+}++/** Target side: one responder per authenticated source connId. */+export class TerminalP2pResponderPool {+ private readonly entries = new Map<string, ResponderEntry>()++ constructor(private readonly deps: TerminalP2pResponderPoolDeps) {}++ async handleSignal(connId: string, type: string, value: unknown): Promise<boolean> {+ if (!TERMINAL_P2P_SIGNAL_TYPES.has(type)) return false+ const payload = parseSignal(value)+ if (!payload) return true+ if (type === 'p2p_offer' && typeof payload.sdp === 'string') {+ await this.acceptOffer(connId, payload)+ return true+ }+ const entry = this.entries.get(connId)+ if (!entry || entry.sessionId !== payload.sessionId) return true+ try {+ if (type === 'p2p_ice_candidate') await entry.pc.addIceCandidate(payload.candidate ?? null)+ else if (type === 'p2p_abort') await this.closeConnection(connId, payload.reason || 'peer_aborted', false)+ } catch {+ await this.closeConnection(connId, 'signal_invalid')+ }+ return true+ }++ send(connId: string, data: TerminalP2pData): boolean {+ const entry = this.entries.get(connId)+ const channel = entry?.channel ?? null+ if (!entry?.ready || !channelCanSend(channel)) return false+ try {+ channel.send(data)+ return true+ } catch {+ void this.closeConnection(connId, 'send_failed')+ return false+ }+ }++ async closeConnection(connId: string, reason = 'closed', notifyPeer = true): Promise<void> {+ const entry = this.entries.get(connId)+ if (!entry || entry.closing) return+ entry.closing = true+ this.entries.delete(connId)+ clearTimeout(entry.timeout)+ if (notifyPeer) {+ this.deps.sendSignal(connId, 'p2p_abort', {+ sessionId: entry.sessionId,+ protocolVersion: TERMINAL_P2P_PROTOCOL_VERSION,+ reason,+ })+ }+ try { entry.channel?.close() } catch { /* already closed */ }+ await entry.pc.close().catch(() => { /* best effort */ })+ }++ async stop(): Promise<void> {+ await Promise.all([...this.entries.keys()].map((connId) => this.closeConnection(connId, 'shutdown', false)))+ }++ private async acceptOffer(connId: string, payload: TerminalP2pSignal): Promise<void> {+ await this.closeConnection(connId, 'superseded', false)+ const offeredStunUrls = Array.isArray(payload.stunUrls)+ ? payload.stunUrls.filter((url): url is string => typeof url === 'string' && /^stuns?:/i.test(url)).slice(0, 4)+ : []+ const pc = new RTCPeerConnection(peerConfig(offeredStunUrls))+ const entry: ResponderEntry = {+ sessionId: payload.sessionId,+ pc,+ channel: null,+ ready: false,+ closing: false,+ timeout: setTimeout(() => {+ this.deps.onUnavailable?.(connId, 'negotiation_timeout')+ void this.closeConnection(connId, 'negotiation_timeout')+ }, TERMINAL_P2P_NEGOTIATION_TIMEOUT_MS),+ }+ entry.timeout.unref?.()+ this.entries.set(connId, entry)+ pc.connectionStateChange.subscribe((state) => {+ if (this.entries.get(connId) !== entry || entry.closing) return+ if (state === 'failed' || state === 'disconnected') {+ if (entry.ready) this.deps.onUnavailable?.(connId, `peer_${state}`)+ void this.closeConnection(connId, `peer_${state}`)+ }+ })+ pc.onDataChannel.subscribe((channel) => {+ if (this.entries.get(connId) !== entry || channel.label !== TERMINAL_P2P_CHANNEL) {+ channel.close()+ return+ }+ entry.channel = channel+ channel.bufferedAmountLowThreshold = 256 * 1024+ channel.stateChanged.subscribe((state) => {+ if (this.entries.get(connId) !== entry || entry.closing) return+ if (state === 'open') {+ entry.ready = true+ clearTimeout(entry.timeout)+ } else if ((state === 'closed' || state === 'closing') && entry.ready) {+ entry.ready = false+ this.deps.onUnavailable?.(connId, 'channel_closed')+ void this.closeConnection(connId, 'channel_closed')+ }+ })+ channel.onMessage.subscribe((data) => {+ if (this.entries.get(connId) === entry && !entry.closing) this.deps.onData(connId, data)+ })+ channel.error.subscribe(() => {+ if (entry.ready) this.deps.onUnavailable?.(connId, 'channel_error')+ void this.closeConnection(connId, 'channel_error')+ })+ })+ try {+ await pc.setRemoteDescription({ type: 'offer', sdp: payload.sdp! })+ const answer = await pc.createAnswer()+ await pc.setLocalDescription(answer)+ if (this.entries.get(connId) !== entry || entry.closing) return+ const local = pc.localDescription+ if (!local) throw new Error('local_description_missing')+ this.deps.sendSignal(connId, 'p2p_answer', {+ sessionId: payload.sessionId,+ protocolVersion: TERMINAL_P2P_PROTOCOL_VERSION,+ sdp: local.sdp,+ })+ } catch {+ await this.closeConnection(connId, 'answer_failed')+ }+ }+}diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex a650066f0..53f859921 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -216,12 +216,12 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOif (isBinary) {const clear = decodeTerminalLocal(binaryBytes(raw))if (!clear) { close(4400, 'invalid terminal frame'); return }- relay.sendBinary(clear)+ await relay.sendBinary(clear)return}const frame = jsonFrame(raw)if (!frame) { close(4400, 'invalid json frame'); return }- relay.send(frame)+ await relay.send(frame)return}