From 55a42b0d5d92028d5636ceb40a3fb1eae7b15472 Mon Sep 17 00:00:00 2001 From: QQ Date: Tue, 17 Nov 2026 08:43:35 +0800 Subject: [PATCH] Import packages/plugin/dist/index.js --- packages/plugin/dist/index.js | 6789 +++++++++++++++++++++------------ 1 file changed, 4454 insertions(+), 2335 deletions(-) diff --git a/packages/plugin/dist/index.js b/packages/plugin/dist/index.js index cfe61ab..162f223 100644 --- a/packages/plugin/dist/index.js +++ b/packages/plugin/dist/index.js @@ -2278,7 +2278,7 @@ var require_websocket = __commonJS({ var http = __require("http"); var net2 = __require("net"); var tls3 = __require("tls"); - var { randomBytes: randomBytes14, createHash: createHash8 } = __require("crypto"); + var { randomBytes: randomBytes15, createHash: createHash8 } = __require("crypto"); var { Duplex, Readable } = __require("stream"); var { URL: URL2 } = __require("url"); var PerMessageDeflate2 = require_permessage_deflate(); @@ -2816,7 +2816,7 @@ var require_websocket = __commonJS({ } } const defaultPort2 = isSecure ? 443 : 80; - const key = randomBytes14(16).toString("base64"); + const key = randomBytes15(16).toString("base64"); const request = isSecure ? https.request : http.request; const protocolSet = /* @__PURE__ */ new Set(); let perMessageDeflate; @@ -3227,7 +3227,7 @@ var require_stream = __commonJS({ }; duplex._final = function(callback) { if (ws.readyState === ws.CONNECTING) { - ws.once("open", function open6() { + ws.once("open", function open7() { duplex._final(callback); }); return; @@ -3248,7 +3248,7 @@ var require_stream = __commonJS({ }; duplex._write = function(chunk, encoding, callback) { if (ws.readyState === ws.CONNECTING) { - ws.once("open", function open6() { + ws.once("open", function open7() { duplex._write(chunk, encoding, callback); }); return; @@ -9169,10 +9169,10 @@ function generateCodecStatsId(transportId, payloadType, scopeId) { function getStatsTimestamp() { return performance.timeOrigin + performance.now(); } -function getReferencedStatsIds(stat10) { +function getReferencedStatsIds(stat11) { const references = []; for (const [key, value] of Object.entries( - stat10 + stat11 )) { if (key === "id") { continue; @@ -9195,8 +9195,8 @@ function getReferencedStatsIds(stat10) { } function buildStatsReport(stats, rootIds) { const index = /* @__PURE__ */ new Map(); - for (const stat10 of stats) { - index.set(stat10.id, stat10); + for (const stat11 of stats) { + index.set(stat11.id, stat11); } if (!rootIds) { return new RTCStatsReport([...index.values()]); @@ -9208,15 +9208,15 @@ function buildStatsReport(stats, rootIds) { if (!id6 || includedIds.has(id6)) { continue; } - const stat10 = index.get(id6); - if (!stat10) { + const stat11 = index.get(id6); + if (!stat11) { continue; } includedIds.add(id6); - queue.push(...getReferencedStatsIds(stat10)); + queue.push(...getReferencedStatsIds(stat11)); } return new RTCStatsReport( - [...includedIds].map((id6) => index.get(id6)).filter((stat10) => !!stat10) + [...includedIds].map((id6) => index.get(id6)).filter((stat11) => !!stat11) ); } function getApplicationStopRevision(transceiver) { @@ -14641,8 +14641,8 @@ var init_lib = __esm({ const id6 = setTimeout(...args); return () => clearTimeout(id6); }, - setInterval: (callback, delay) => { - const id6 = setInterval(callback, delay); + setInterval: (callback, delay2) => { + const id6 = setInterval(callback, delay2); return () => clearInterval(id6); } }; @@ -15742,8 +15742,8 @@ var init_lib = __esm({ handleAbort = () => { this.stop(); }; - schedule(delay) { - const handle = this.scheduler.setTimeout(this.handleTimer, delay); + schedule(delay2) { + const handle = this.scheduler.setTimeout(this.handleTimer, delay2); if (this.unref) { handle?.unref?.(); } @@ -15928,8 +15928,8 @@ var init_lib = __esm({ return; } this.anchor ??= { time: now + this.latencyMs, dts: next.dts }; - const delay = Math.max(0, this.deadline(next.dts) - now); - const handle = this.scheduler.setTimeout(this.handleTimer, delay); + const delay2 = Math.max(0, this.deadline(next.dts) - now); + const handle = this.scheduler.setTimeout(this.handleTimer, delay2); if (this.unref) { handle?.unref?.(); } @@ -19768,10 +19768,10 @@ var init_lib = __esm({ abort.abort(); }); while (!abort.signal.aborted) { - const delay = 5 / 6 * exp * 1e3; - log23("refresh delay", delay, { exp }); + const delay2 = 5 / 6 * exp * 1e3; + log23("refresh delay", delay2, { exp }); try { - await setTimeout42(delay, void 0, { signal: abort.signal }); + await setTimeout42(delay2, void 0, { signal: abort.signal }); } catch (error62) { if (abort.signal.aborted) { return; @@ -24138,8 +24138,8 @@ var init_lib = __esm({ constructor(stats) { super(); if (stats) { - for (const stat10 of stats) { - this.set(stat10.id, stat10); + for (const stat11 of stats) { + this.set(stat11.id, stat11); } } } @@ -41443,11 +41443,11 @@ var require_dijkstra = __commonJS({ var predecessors = {}; var costs = {}; costs[s] = 0; - var open6 = dijkstra.PriorityQueue.make(); - open6.push(s, 0); + var open7 = dijkstra.PriorityQueue.make(); + open7.push(s, 0); var closest, u, v, cost_of_s_to_u, adjacent_nodes, cost_of_e, cost_of_s_to_u_plus_cost_of_e, cost_of_s_to_v, first_visit; - while (!open6.empty()) { - closest = open6.pop(); + while (!open7.empty()) { + closest = open7.pop(); u = closest.value; cost_of_s_to_u = closest.cost; adjacent_nodes = graph[u] || {}; @@ -41459,7 +41459,7 @@ var require_dijkstra = __commonJS({ first_visit = typeof costs[v] === "undefined"; if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) { costs[v] = cost_of_s_to_u_plus_cost_of_e; - open6.push(v, cost_of_s_to_u_plus_cost_of_e); + open7.push(v, cost_of_s_to_u_plus_cost_of_e); predecessors[v] = u; } } @@ -44701,6 +44701,75 @@ var require_lib = __commonJS({ // packages/plugin/src/index.ts import * as DshConnection from "@deepseek-ai/dsh-client-connection"; +// packages/plugin/src/local-mention-upload.ts +import { lstat, readFile } from "node:fs/promises"; +import { posix, win32 } from "node:path"; +var MAX_MENTION_BYTES = 192 * 1024 * 1024; +var LOCAL_MENTION = /(^|\s)@(?:"([^"\r\n]+)"|([^\s]+))/gu; +async function uploadLocalMentions(payload, remote, signal, platform3 = process.platform, fileIO = { lstat, readFile }) { + if (!isMentionRecord(payload) || !isMentionRecord(payload.args) || !isMentionRecord(payload.args.request)) return payload; + const request = payload.args.request; + if (typeof request.sessionId !== "string" || !Array.isArray(request.content)) return payload; + const content = []; + let uploaded = 0; + let seen = 0; + let staged = 0; + for (const block of request.content) { + if (!isMentionRecord(block) || block.type !== "text" || typeof block.text !== "string") { + content.push(block); + continue; + } + const matches = [...block.text.matchAll(LOCAL_MENTION)].filter((match) => (platform3 === "win32" ? win32 : posix).isAbsolute(match[2] ?? match[3])); + if (matches.length === 0) { + content.push(block); + continue; + } + let cursor3 = 0; + for (const match of matches) { + signal.throwIfAborted(); + const start = match.index + (match[1]?.length ?? 0); + if (start > cursor3) content.push({ ...block, text: block.text.slice(cursor3, start) }); + const path = match[2] ?? match[3]; + const candidates = await remote.dispatch("fileReferences/list", { args: { + agentId: request.sessionId, + query: path + } }, signal); + if (candidates.ok && Array.isArray(candidates.value) && candidates.value.some((candidate) => isMentionRecord(candidate) && candidate.kind === "file" && candidate.path === path)) continue; + if (++seen > 4) throw new Error("Remote supports at most four absolute local file mentions per message."); + let file2; + try { + file2 = await fileIO.lstat(path); + } catch (error62) { + if (isMissingFile(error62)) continue; + throw error62; + } + if (!file2.isFile() || file2.isSymbolicLink() || uploaded + file2.size > MAX_MENTION_BYTES) { + throw new Error("The selected local file is unavailable or exceeds the Remote transfer limit."); + } + uploaded += file2.size; + const data2 = (await fileIO.readFile(path, { signal })).toString("base64"); + const result = await remote.dispatch("fileUploads/upload", { args: { + agentId: request.sessionId, + request: { data: data2, name: (platform3 === "win32" ? win32 : posix).basename(path) } + } }, signal); + if (!result.ok) throw new Error(result.error.message); + const value = result.value; + if (typeof value?.receiptId !== "string" || value.receiptId.length === 0) throw new Error("The Remote Host did not return a file receipt."); + content.push({ type: "file", receiptId: value.receiptId }); + staged++; + cursor3 = match.index + match[0].length; + } + if (cursor3 < block.text.length) content.push({ ...block, text: block.text.slice(cursor3) }); + } + return staged === 0 ? payload : { ...payload, args: { ...payload.args, request: { ...request, content } } }; +} +function isMentionRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function isMissingFile(error62) { + return isMentionRecord(error62) && (error62.code === "ENOENT" || error62.code === "ENOTDIR"); +} + // node_modules/zod/v4/classic/external.js var external_exports = {}; __export(external_exports, { @@ -64418,6 +64487,234 @@ function date4(params) { return _coercedDate(ZodDate, params); } +// packages/protocol/dist/lan-upload.js +var LAN_UPLOAD_CAPABILITY = "workspace.upload.lan.v1"; +var LAN_UPLOAD_MIN_BYTES = 1024 * 1024; +var LAN_UPLOAD_TICKET_MS = 1e4; +var lanUploadScopeSchema = external_exports.object({ + sessionId: external_exports.string().min(1).max(512), + uploadId: external_exports.string().uuid() +}).strict(); +var lanUploadRequestSchema = lanUploadScopeSchema.extend({ address: external_exports.string().max(64) }).strict(); +var lanUploadOfferSchema = lanUploadScopeSchema.extend({ + connectionId: external_exports.string().min(1).max(512), + url: external_exports.string().max(512), + expiresInMs: external_exports.number().int().positive().max(LAN_UPLOAD_TICKET_MS) +}).strict(); +function isLanUploadAddress(address2) { + const parts = address2.split("."); + if (parts.length !== 4 || parts.some((p) => !/^\d{1,3}$/.test(p) || Number(p) > 255 || String(Number(p)) !== p)) + return false; + const [a, b] = parts.map(Number); + return a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168; +} +function createLanUploadPrologue(offer) { + const ticket = new URL(offer.url).pathname.split("/").at(-1); + return new TextEncoder().encode(JSON.stringify(["ds-harness-remote/lan-upload/v1", offer.connectionId, offer.sessionId, offer.uploadId, ticket])); +} + +// packages/protocol/dist/transport-upgrade.js +var TRANSPORT_UPGRADE_CAPABILITY = "remote.transport.upgrade.v1"; +var UPGRADE_SEQUENCE_HEADER_BYTES = 12; +var MAX_REORDER_BUFFERED_FRAMES = 256; +var MAX_REORDER_BUFFERED_BYTES = 4 * 1024 * 1024; +var DEFAULT_REORDER_GAP_TIMEOUT_MS = 5e3; +var DEFAULT_PREVIOUS_LEG_DRAIN_MS = 3e3; +var UPGRADE_SEQ_MAGIC = [68, 83, 72, 85]; +var transportUpgradeCandidateSchema = external_exports.object({ + candidate: external_exports.string().max(4096).optional(), + sdpMid: external_exports.string().max(128).nullable().optional(), + sdpMLineIndex: external_exports.number().int().min(0).max(64).nullable().optional(), + usernameFragment: external_exports.string().max(256).nullable().optional() +}).strict(); +var transportUpgradeOfferSchema = external_exports.object({ + attemptId: external_exports.string().min(1).max(64), + sdp: external_exports.string().min(1).max(128 * 1024) +}).strict(); +var transportUpgradeIceSchema = external_exports.object({ + attemptId: external_exports.string().min(1).max(64), + candidate: transportUpgradeCandidateSchema +}).strict(); +var transportUpgradeActivateSchema = external_exports.object({ + attemptId: external_exports.string().min(1).max(64), + transport: external_exports.enum(["lan", "p2p", "turn"]).optional(), + previousLegEndCounter: external_exports.number().int().min(0).optional() +}).strict(); +var transportUpgradeDrainSchema = external_exports.object({ + attemptId: external_exports.string().min(1).max(64), + previousLegEndCounter: external_exports.number().int().min(0) +}).strict(); +var transportUpgradeAbortSchema = external_exports.object({ + attemptId: external_exports.string().min(1).max(64).optional() +}).strict(); +function transportTierRank(mode2) { + switch (mode2) { + case "LAN": + return 3; + case "P2P": + return 2; + case "TURN": + return 1; + default: + return 0; + } +} +function wireFromTransportTier(mode2) { + return mode2 === "LAN" ? "lan" : mode2 === "P2P" ? "p2p" : "turn"; +} +function wrapUpgradedTransportFrame(counter, ciphertext) { + if (!Number.isSafeInteger(counter) || counter < 0) { + throw new Error("Upgraded transport counter must be a non-negative safe integer."); + } + const out = new Uint8Array(UPGRADE_SEQUENCE_HEADER_BYTES + ciphertext.byteLength); + out.set(UPGRADE_SEQ_MAGIC, 0); + const view = new DataView(out.buffer, out.byteOffset, UPGRADE_SEQUENCE_HEADER_BYTES); + view.setBigUint64(4, BigInt(counter), false); + out.set(ciphertext, UPGRADE_SEQUENCE_HEADER_BYTES); + return out; +} +function unwrapUpgradedTransportFrame(frame) { + if (frame.byteLength < UPGRADE_SEQUENCE_HEADER_BYTES || frame[0] !== UPGRADE_SEQ_MAGIC[0] || frame[1] !== UPGRADE_SEQ_MAGIC[1] || frame[2] !== UPGRADE_SEQ_MAGIC[2] || frame[3] !== UPGRADE_SEQ_MAGIC[3]) { + throw new Error("Invalid upgraded transport frame header."); + } + const view = new DataView(frame.buffer, frame.byteOffset, UPGRADE_SEQUENCE_HEADER_BYTES); + const rawCounter = view.getBigUint64(4, false); + if (rawCounter > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error("Upgraded transport frame counter overflowed."); + } + return { + counter: Number(rawCounter), + ciphertext: frame.subarray(UPGRADE_SEQUENCE_HEADER_BYTES) + }; +} +var SequencedCiphertextReorderBuffer = class { + options; + pending = /* @__PURE__ */ new Map(); + bufferedBytes = 0; + gapTimer; + gapCounter; + constructor(options) { + this.options = options; + } + get size() { + return this.pending.size; + } + get bytes() { + return this.bufferedBytes; + } + push(counter, expectedCounter, ciphertext) { + if (!Number.isSafeInteger(counter) || counter <= expectedCounter) { + throw new Error("Ciphertext counter is duplicated or out of order."); + } + if (this.pending.has(counter)) { + throw new Error("Duplicate buffered ciphertext counter."); + } + const maxFrames = this.options.maxFrames ?? MAX_REORDER_BUFFERED_FRAMES; + const maxBytes = this.options.maxBytes ?? MAX_REORDER_BUFFERED_BYTES; + if (this.pending.size >= maxFrames || this.bufferedBytes + ciphertext.byteLength > maxBytes) { + throw new Error("Cross-transport reorder buffer exceeded its limit."); + } + const copy = new Uint8Array(ciphertext); + this.pending.set(counter, copy); + this.bufferedBytes += copy.byteLength; + this.armGapTimer(expectedCounter); + } + takeNext(expectedCounter) { + const hit = this.pending.get(expectedCounter); + if (hit === void 0) { + if (this.pending.size === 0) + this.clearGapTimer(); + else + this.armGapTimer(expectedCounter); + return void 0; + } + this.pending.delete(expectedCounter); + this.bufferedBytes -= hit.byteLength; + if (this.pending.size === 0) + this.clearGapTimer(); + else + this.armGapTimer(expectedCounter + 1); + return hit; + } + onExpectedAdvanced(nextExpectedCounter) { + if (this.pending.size === 0) { + this.clearGapTimer(); + return; + } + this.armGapTimer(nextExpectedCounter); + } + clear() { + this.clearGapTimer(); + this.pending.clear(); + this.bufferedBytes = 0; + } + armGapTimer(expectedCounter) { + if (this.gapCounter === expectedCounter && this.gapTimer !== void 0) + return; + this.clearGapTimer(); + this.gapCounter = expectedCounter; + const timeoutMs = this.options.gapTimeoutMs ?? DEFAULT_REORDER_GAP_TIMEOUT_MS; + this.gapTimer = setTimeout(() => { + this.gapTimer = void 0; + if (this.pending.size > 0) { + this.options.onGapTimeout(expectedCounter); + } + }, timeoutMs); + this.gapTimer.unref?.(); + } + clearGapTimer() { + if (this.gapTimer !== void 0) { + clearTimeout(this.gapTimer); + this.gapTimer = void 0; + } + this.gapCounter = void 0; + } +}; + +// packages/protocol/dist/binary-upload.js +var BINARY_UPLOAD_CAPABILITY = "workspace.upload.binary.v1"; +var BINARY_UPLOAD_CHUNK_BYTES = 256 * 1024; +var BINARY_UPLOAD_MAGIC = new Uint8Array([68, 83, 72, 85, 80, 1, 0, 0]); +var BINARY_UPLOAD_PREFIX_BYTES = 12; +var BINARY_UPLOAD_MAX_HEADER_BYTES = 4096; +var BINARY_UPLOAD_METHOD = "workspace.upload.chunk.binary"; +function encodeBinaryUpload(message) { + if (message.type !== "rpc.request" || !isBinaryUploadRecord(message.payload) || message.payload.method !== BINARY_UPLOAD_METHOD) + return void 0; + const params = message.payload.params; + if (!isBinaryUploadRecord(params) || !(params.data instanceof Uint8Array)) + throw new Error("Binary upload requires bytes"); + const { data: data2, ...metadata } = params; + if (!data2.byteLength || data2.byteLength > BINARY_UPLOAD_CHUNK_BYTES) + throw new Error("Binary upload chunk exceeds limit"); + const header = new TextEncoder().encode(JSON.stringify({ ...message, payload: { method: BINARY_UPLOAD_METHOD, params: metadata } })); + if (header.byteLength > BINARY_UPLOAD_MAX_HEADER_BYTES) + throw new Error("Binary upload header exceeds limit"); + const frame = new Uint8Array(BINARY_UPLOAD_PREFIX_BYTES + header.byteLength + data2.byteLength); + frame.set(BINARY_UPLOAD_MAGIC); + new DataView(frame.buffer).setUint32(8, header.byteLength, false); + frame.set(header, BINARY_UPLOAD_PREFIX_BYTES); + frame.set(data2, BINARY_UPLOAD_PREFIX_BYTES + header.byteLength); + return frame; +} +function decodeBinaryUpload(data2) { + if (typeof data2 === "string" || data2[0] !== BINARY_UPLOAD_MAGIC[0] || data2[1] !== BINARY_UPLOAD_MAGIC[1] || data2[2] !== BINARY_UPLOAD_MAGIC[2] || data2[3] !== BINARY_UPLOAD_MAGIC[3]) + return void 0; + if (data2.byteLength < BINARY_UPLOAD_PREFIX_BYTES || !BINARY_UPLOAD_MAGIC.every((byte, index) => data2[index] === byte)) + throw new Error("Invalid binary upload prefix"); + const headerBytes = new DataView(data2.buffer, data2.byteOffset, data2.byteLength).getUint32(8, false); + const chunkBytes = data2.byteLength - BINARY_UPLOAD_PREFIX_BYTES - headerBytes; + if (!headerBytes || headerBytes > BINARY_UPLOAD_MAX_HEADER_BYTES || chunkBytes < 1 || chunkBytes > BINARY_UPLOAD_CHUNK_BYTES) + throw new Error("Invalid binary upload bounds"); + const message = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(data2.subarray(BINARY_UPLOAD_PREFIX_BYTES, BINARY_UPLOAD_PREFIX_BYTES + headerBytes))); + if (!isBinaryUploadRecord(message) || message.type !== "rpc.request" || !isBinaryUploadRecord(message.payload) || message.payload.method !== BINARY_UPLOAD_METHOD || !isBinaryUploadRecord(message.payload.params) || "data" in message.payload.params) + throw new Error("Invalid binary upload header"); + return { ...message, payload: { ...message.payload, params: { ...message.payload.params, data: data2.subarray(BINARY_UPLOAD_PREFIX_BYTES + headerBytes) } } }; +} +function isBinaryUploadRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + // packages/protocol/dist/loopback.js var LOOPBACK_CHUNK_BYTES = 64 * 1024; var LOOPBACK_MAX_BODY_BYTES = 1024 * 1024; @@ -64586,8 +64883,10 @@ var controlFrameTypes = [ "error" ]; var rpcMethods = [ + "workspace.upload.lan.open", "workspace.upload.open", "workspace.upload.chunk", + "workspace.upload.chunk.binary", "workspace.upload.commit", "workspace.upload.abort", "harness.transport.describe", @@ -64609,6 +64908,9 @@ var rpcMethods = [ "harness.remote.transfer.close", "harness.remote.stream.open", "harness.remote.stream.close", + "harness.remote.compaction.submit", + "harness.remote.compaction.status", + "harness.remote.compaction.cancel", "loopback.call", "fileviewer.call", "codex.app.call", @@ -64705,6 +65007,8 @@ function acceptNegotiatedCapabilities(offered, negotiated) { } return [...accepted]; } +var REMOTE_COMPACTION_CAPABILITY = "remote.compaction.async.v1"; +var REMOTE_SESSION_EVENTS_CAPABILITY = "remote.session.events.v1"; var rpcMethodSchema = external_exports.enum(rpcMethods); var messageTypeSchema = external_exports.enum(messageTypes); var controlFrameTypeSchema = external_exports.enum(controlFrameTypes); @@ -65070,10 +65374,10 @@ function parseRelayDataFrame(input4) { return frame; } function encodeMessage(message) { - return new TextEncoder().encode(JSON.stringify(message)); + return encodeBinaryUpload(message) ?? new TextEncoder().encode(JSON.stringify(message)); } function decodeMessage(data2) { - return parseRemoteMessage(parseWireJson(data2)); + return parseRemoteMessage(decodeBinaryUpload(data2) ?? parseWireJson(data2)); } var SecureMessageCodec = class { nextMessageId = 1; @@ -66074,6 +66378,2014 @@ function canonicalBase64ToBytes(value) { return bytes; } +// packages/webrtc/dist/websocket-backpressure.js +async function waitForRelayCapacity(socket) { + const started = Date.now(); + while ((socket.bufferedAmount ?? 0) > 512 * 1024) { + if (socket.readyState !== 1 || Date.now() - started > 1e4) + throw new Error("Relay consumer is too slow or disconnected"); + await new Promise((resolve10) => setTimeout(resolve10, 10)); + } + if (socket.readyState !== 1) + throw new Error("Relay transport closed"); +} + +// packages/webrtc/dist/transport.js +var BaseTransport = class { + handlers = /* @__PURE__ */ new Set(); + closeHandlers = /* @__PURE__ */ new Set(); + onMessage(cb) { + this.handlers.add(cb); + return () => this.handlers.delete(cb); + } + onClose(cb) { + this.closeHandlers.add(cb); + return () => this.closeHandlers.delete(cb); + } + emit(data2) { + for (const handler of this.handlers) + handler(data2); + } + emitClose(error62) { + for (const handler of this.closeHandlers) + handler(error62); + } +}; + +// packages/webrtc/dist/util.js +function toBase64Url(bytes) { + const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""); + const base643 = typeof btoa === "function" ? btoa(binary) : Buffer.from(bytes).toString("base64"); + return base643.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +} +function fromBase64Url(value) { + const normalized = value.replaceAll("-", "+").replaceAll("_", "/"); + const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "="); + if (typeof atob === "function") + return Uint8Array.from(atob(padded), (char) => char.charCodeAt(0)); + return new Uint8Array(Buffer.from(padded, "base64")); +} + +// packages/webrtc/dist/rtc-adapter.js +var RTC_DATA_CHANNEL_LABEL = "dsh"; +var RTC_DATA_CHANNEL_OPTIONS = { ordered: true }; +function browserRtcFactory(options = {}) { + const binarySender = options.sendBinary; + return { + create(configuration) { + const raw = new RTCPeerConnection({ + iceServers: configuration.iceServers, + iceTransportPolicy: configuration.iceTransportPolicy + }); + return { + get connectionState() { + return raw.connectionState; + }, + get iceConnectionState() { + return raw.iceConnectionState; + }, + get iceGatheringState() { + return raw.iceGatheringState; + }, + get signalingState() { + return raw.signalingState; + }, + set onconnectionstatechange(value) { + raw.onconnectionstatechange = value; + }, + get onconnectionstatechange() { + return raw.onconnectionstatechange; + }, + set oniceconnectionstatechange(value) { + raw.oniceconnectionstatechange = value; + }, + get oniceconnectionstatechange() { + return raw.oniceconnectionstatechange; + }, + set onicegatheringstatechange(value) { + raw.onicegatheringstatechange = value; + }, + get onicegatheringstatechange() { + return raw.onicegatheringstatechange; + }, + set onicecandidate(value) { + raw.onicecandidate = value; + }, + get onicecandidate() { + return raw.onicecandidate; + }, + set ondatachannel(value) { + raw.ondatachannel = value; + }, + get ondatachannel() { + return raw.ondatachannel; + }, + createDataChannel(label, options2) { + return adaptDataChannel(raw.createDataChannel(label, options2), binarySender); + }, + createOffer() { + return raw.createOffer(); + }, + createAnswer() { + return raw.createAnswer(); + }, + setLocalDescription(description) { + return raw.setLocalDescription(description); + }, + setRemoteDescription(description) { + return raw.setRemoteDescription(description); + }, + addIceCandidate(candidate) { + return raw.addIceCandidate(candidate); + }, + async getStats() { + return await raw.getStats(); + }, + close() { + raw.close(); + } + }; + } + }; +} +function summarizeIceCandidate(candidate) { + const value = candidate?.candidate?.trim(); + if (value === void 0 || value.length === 0) + return emptyCandidateSummary(); + const parts = value.replace(/^candidate:/, "").split(/\s+/); + const typeIndex = parts.indexOf("typ"); + const relatedAddressIndex = parts.indexOf("raddr"); + return { + candidateType: parseCandidateType(parts[typeIndex + 1]), + protocol: normalizeProtocol(parts[2]), + ...summarizeAddress(parts[4]), + ...relatedAddressIndex < 0 ? {} : relatedAddressSummary(parts[relatedAddressIndex + 1]) + }; +} +function summarizeAddress(address2) { + if (address2 === void 0 || address2.length === 0) + return { addressFamily: "unknown", addressScope: "unknown" }; + if (address2.includes(":")) + return { addressFamily: "ipv6", addressScope: summarizeIpv6Scope(address2) }; + const parts = address2.split(".").map(Number); + if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) { + return { addressFamily: "unknown", addressScope: "unknown" }; + } + return { addressFamily: "ipv4", addressScope: summarizeIpv4Scope(parts) }; +} +function stunOnlyIceServers(iceServers) { + const direct = []; + for (const server of iceServers) { + const sourceUrls = Array.isArray(server.urls) ? server.urls : [server.urls]; + const urls = sourceUrls.filter(isStunUrl); + if (urls.length === 0) + continue; + direct.push({ urls: Array.isArray(server.urls) ? urls : urls[0] }); + } + return direct; +} +function isStunUrl(url2) { + const value = url2.trim().toLowerCase(); + return value.startsWith("stun:") || value.startsWith("stuns:"); +} +function emptyCandidateSummary() { + return { candidateType: "unknown", addressFamily: "unknown", addressScope: "unknown" }; +} +function parseCandidateType(value) { + if (value === "host" || value === "srflx" || value === "prflx" || value === "relay") + return value; + return "unknown"; +} +function normalizeProtocol(value) { + if (value === void 0 || value.length === 0) + return void 0; + return value.toLowerCase(); +} +function relatedAddressSummary(address2) { + const summary3 = summarizeAddress(address2); + return { + relatedAddressFamily: summary3.addressFamily, + relatedAddressScope: summary3.addressScope + }; +} +function summarizeIpv4Scope(parts) { + if (parts[0] === 0 || parts[0] >= 240) + return "reserved"; + if (parts[0] === 127) + return "loopback"; + if (parts[0] === 169 && parts[1] === 254) + return "link-local"; + if (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) + return "cgnat"; + if (parts[0] >= 224) + return "reserved"; + if (parts[0] === 10) + return "private"; + if (parts[0] === 192 && parts[1] === 168) + return "private"; + if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) + return "private"; + return "public"; +} +function summarizeIpv6Scope(address2) { + const value = address2.toLowerCase(); + if (value === "::1") + return "loopback"; + if (value.startsWith("fe80:")) + return "link-local"; + if (value.startsWith("fd7a:115c:a1e0:")) + return "cgnat"; + if (value.startsWith("fc") || value.startsWith("fd")) + return "private"; + if (value.startsWith("ff")) + return "reserved"; + return "public"; +} +function adaptDataChannel(raw, sendBinary) { + return { + get label() { + return raw.label; + }, + get ordered() { + return raw.ordered; + }, + get readyState() { + return raw.readyState; + }, + get bufferedAmount() { + return raw.bufferedAmount; + }, + get binaryType() { + return raw.binaryType; + }, + set binaryType(value) { + raw.binaryType = value; + }, + set onopen(value) { + raw.onopen = value; + }, + get onopen() { + return raw.onopen; + }, + set onmessage(value) { + raw.onmessage = value; + }, + get onmessage() { + return raw.onmessage; + }, + set onclose(value) { + raw.onclose = value; + }, + get onclose() { + return raw.onclose; + }, + set onerror(value) { + raw.onerror = value; + }, + get onerror() { + return raw.onerror; + }, + set onbufferedamountlow(value) { + raw.onbufferedamountlow = value; + }, + get onbufferedamountlow() { + return raw.onbufferedamountlow; + }, + send(data2) { + if (data2 instanceof ArrayBuffer && sendBinary?.(raw, data2)) + return; + raw.send(data2); + }, + close() { + raw.close(); + } + }; +} + +// packages/webrtc/dist/rtc-chunking.js +var RTC_CHUNK_MAGIC = new Uint8Array([82, 84, 67, 72]); +var RTC_CHUNK_HEADER_BYTES = 12; +var RTC_CHUNK_PAYLOAD_BYTES = 8 * 1024; +var RTC_CHUNK_MAX_MESSAGE_BYTES = 4 * 1024 * 1024; +var RTC_CHUNK_MAX_TOTAL = Math.ceil(RTC_CHUNK_MAX_MESSAGE_BYTES / RTC_CHUNK_PAYLOAD_BYTES); +var MAX_IN_FLIGHT_MESSAGES = 8; +var MAX_ASSEMBLY_AGE_MS = 3e4; +var RtcChunkCodec = class { + nextMessageId = 1; + assemblies = /* @__PURE__ */ new Map(); + encode(data2) { + if (data2.byteLength <= RTC_CHUNK_PAYLOAD_BYTES) + return [data2]; + if (data2.byteLength > RTC_CHUNK_MAX_MESSAGE_BYTES) { + throw new Error("WebRTC transport message exceeds the reassembly limit."); + } + const messageId = this.nextMessageId; + this.nextMessageId = messageId === 4294967295 ? 1 : messageId + 1; + const total = Math.ceil(data2.byteLength / RTC_CHUNK_PAYLOAD_BYTES); + const frames = []; + for (let index = 0; index < total; index += 1) { + const start = index * RTC_CHUNK_PAYLOAD_BYTES; + const chunk = data2.subarray(start, Math.min(data2.byteLength, start + RTC_CHUNK_PAYLOAD_BYTES)); + const frame = new Uint8Array(RTC_CHUNK_HEADER_BYTES + chunk.byteLength); + frame.set(RTC_CHUNK_MAGIC); + const view = new DataView(frame.buffer); + view.setUint32(4, messageId); + view.setUint16(8, index); + view.setUint16(10, total); + frame.set(chunk, RTC_CHUNK_HEADER_BYTES); + frames.push(frame); + } + return frames; + } + decode(frame) { + if (!isChunk(frame)) { + if (frame.byteLength > RTC_CHUNK_MAX_MESSAGE_BYTES) { + throw new Error("WebRTC transport message exceeds the reassembly limit."); + } + return frame; + } + if (frame.byteLength < RTC_CHUNK_HEADER_BYTES) + throw new Error("WebRTC transport chunk header is invalid."); + const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength); + const messageId = view.getUint32(4); + const index = view.getUint16(8); + const total = view.getUint16(10); + if (messageId === 0 || total < 2 || total > RTC_CHUNK_MAX_TOTAL || index >= total) { + throw new Error("WebRTC transport chunk metadata is invalid."); + } + const chunk = frame.subarray(RTC_CHUNK_HEADER_BYTES); + if (chunk.byteLength > RTC_CHUNK_PAYLOAD_BYTES || index < total - 1 && chunk.byteLength !== RTC_CHUNK_PAYLOAD_BYTES || index === total - 1 && chunk.byteLength === 0) { + throw new Error("WebRTC transport chunk length is invalid."); + } + this.pruneStale(); + let assembly = this.assemblies.get(messageId); + if (assembly === void 0) { + if (index !== 0 || this.assemblies.size >= MAX_IN_FLIGHT_MESSAGES) { + throw new Error("WebRTC transport chunk sequence is invalid."); + } + assembly = { messageId, total, receivedBytes: 0, chunks: [], updatedAt: Date.now() }; + this.assemblies.set(messageId, assembly); + } + if (assembly.total !== total || index !== assembly.chunks.length) { + this.assemblies.delete(messageId); + throw new Error("WebRTC transport chunk sequence is invalid."); + } + const receivedBytes = assembly.receivedBytes + chunk.byteLength; + if (receivedBytes > RTC_CHUNK_MAX_MESSAGE_BYTES) { + this.assemblies.delete(messageId); + throw new Error("WebRTC transport message exceeds the reassembly limit."); + } + assembly.chunks.push(Uint8Array.from(chunk)); + assembly.receivedBytes = receivedBytes; + assembly.updatedAt = Date.now(); + if (assembly.chunks.length < total) + return void 0; + this.assemblies.delete(messageId); + const message = new Uint8Array(assembly.receivedBytes); + let offset = 0; + for (const part of assembly.chunks) { + message.set(part, offset); + offset += part.byteLength; + } + return message; + } + reset() { + this.nextMessageId = 1; + this.assemblies.clear(); + } + pruneStale() { + const now = Date.now(); + for (const [messageId, assembly] of this.assemblies) { + if (now - assembly.updatedAt > MAX_ASSEMBLY_AGE_MS) + this.assemblies.delete(messageId); + } + } +}; +function isChunk(frame) { + if (frame.byteLength < RTC_CHUNK_MAGIC.byteLength) + return false; + for (let index = 0; index < RTC_CHUNK_MAGIC.byteLength; index += 1) { + if (frame[index] !== RTC_CHUNK_MAGIC[index]) + return false; + } + return true; +} + +// packages/webrtc/dist/rtc-data-channel.js +var DEFAULT_NEGOTIATE_TIMEOUT_MS = 8e3; +var SELECTED_PATH_RETRY_COUNT = 5; +var SELECTED_PATH_RETRY_DELAY_MS = 50; +var RtcDataChannelTransport = class { + pc; + role; + onSignal; + negotiateTimeoutMs; + channelLabel; + sendTimeoutMs; + label; + onDiagnostic; + channel; + remoteCandidates = []; + remoteDescriptionSet = false; + opened = false; + closed = false; + messageHandlers = /* @__PURE__ */ new Set(); + closeHandlers = /* @__PURE__ */ new Set(); + errorHandlers = /* @__PURE__ */ new Set(); + connectPromise; + openResolve; + openReject; + negotiateTimer; + removeAbort; + watchdogTimer; + outgoing = new RtcChunkCodec(); + incoming = new RtcChunkCodec(); + bytesSent = 0; + bytesReceived = 0; + selected; + selectedMode; + selectedRelayUrlValue; + selectedPathTelemetry; + localCandidateTelemetry = emptyCandidateTelemetry(); + remoteCandidateTelemetry = emptyCandidateTelemetry(); + candidatePairTelemetry = emptyCandidatePairTelemetry(); + filteredLocalCandidateTelemetry = emptyCandidateTelemetry(); + filteredCandidatePairTelemetry = emptyCandidateTelemetry(); + lastBufferedAmount = 0; + constructor(options) { + this.role = options.role; + this.onSignal = options.onSignal; + this.negotiateTimeoutMs = options.negotiateTimeoutMs ?? DEFAULT_NEGOTIATE_TIMEOUT_MS; + this.channelLabel = options.channelLabel ?? RTC_DATA_CHANNEL_LABEL; + this.sendTimeoutMs = options.sendTimeoutMs; + this.label = options.label; + this.onDiagnostic = options.onDiagnostic; + this.pc = options.factory.create({ + iceServers: options.iceServers, + iceTransportPolicy: options.iceTransportPolicy, + onDiagnostic: (event) => this.handlePeerDiagnostic(event) + }); + this.pc.ondatachannel = (event) => this.adoptChannel(event.channel); + this.pc.onicecandidate = (event) => { + if (event.candidate !== null && !this.closed) { + const candidate = summarizeIceCandidate(event.candidate); + recordCandidate(this.localCandidateTelemetry, candidate); + this.emitDiagnostic({ type: "local-candidate", candidate, diagnostics: this.diagnostics() }); + this.onSignal({ type: "ice", candidate: event.candidate }); + } + }; + this.pc.onconnectionstatechange = () => { + this.emitStateChange(); + this.checkConnectionState(); + }; + this.pc.oniceconnectionstatechange = () => { + this.emitStateChange(); + this.checkConnectionState(); + }; + this.pc.onicegatheringstatechange = () => this.emitStateChange(); + } + /** Begin negotiation; resolves when the DataChannel is open. */ + connect(signal) { + if (this.closed) + return Promise.reject(new RtcConnectError("RTC_CLOSED", "WebRTC transport closed.")); + if (signal?.aborted) + return Promise.reject(new RtcConnectError("RTC_ABORTED", "WebRTC negotiation was aborted.")); + if (this.opened) + return Promise.resolve(); + if (this.connectPromise !== void 0) + return this.connectPromise; + this.armAbort(signal); + this.connectPromise = new Promise((resolve10, reject) => { + this.openResolve = resolve10; + this.openReject = reject; + this.negotiateTimer = setTimeout(() => { + void this.failOpenAfterStats(new RtcConnectError("RTC_CONNECT_TIMEOUT", `WebRTC negotiation timed out after ${this.negotiateTimeoutMs}ms.`)); + }, this.negotiateTimeoutMs); + if (this.role === "initiator") { + void this.startInitiator().catch((error62) => this.failOpen(asError(error62))); + } + }); + return this.connectPromise; + } + handleSignal(signal) { + if (this.closed) + return; + if (signal.type === "offer") + void this.handleOffer(signal.sdp); + else if (signal.type === "answer") + void this.handleAnswer(signal.sdp); + else + void this.handleIce(signal.candidate); + } + async send(data2) { + const channel = this.requireOpenChannel(); + if (channel.readyState !== "open") + throw new Error("WebRTC data channel is not open."); + for (const frame of this.outgoing.encode(data2)) { + try { + channel.send(toArrayBuffer(frame)); + } catch (error62) { + console.error("[rtc-send-error] bytes=" + frame.byteLength, error62 instanceof Error ? error62.message : error62); + throw error62; + } + } + this.bytesSent += data2.byteLength; + this.armWatchdog(channel); + } + onMessage(handler) { + this.messageHandlers.add(handler); + return () => this.messageHandlers.delete(handler); + } + onClose(handler) { + this.closeHandlers.add(handler); + return () => this.closeHandlers.delete(handler); + } + onError(handler) { + this.errorHandlers.add(handler); + return () => this.errorHandlers.delete(handler); + } + selectedTransport() { + return this.selected; + } + selectedRelayUrl() { + return this.selectedRelayUrlValue; + } + selectedPathMode() { + return this.selectedMode; + } + diagnostics() { + return { + role: this.role, + ...this.label === void 0 ? {} : { label: this.label }, + connectionState: this.pc.connectionState, + iceConnectionState: this.pc.iceConnectionState, + iceGatheringState: this.pc.iceGatheringState, + localCandidates: cloneCandidateTelemetry(this.localCandidateTelemetry), + remoteCandidates: cloneCandidateTelemetry(this.remoteCandidateTelemetry), + candidatePairs: cloneCandidatePairTelemetry(this.candidatePairTelemetry), + filteredLocalCandidates: cloneCandidateTelemetry(this.filteredLocalCandidateTelemetry), + filteredCandidatePairs: cloneCandidateTelemetry(this.filteredCandidatePairTelemetry), + ...this.selectedPathTelemetry === void 0 ? {} : { selectedPath: { ...this.selectedPathTelemetry } } + }; + } + async connectionDetails() { + let statsDetails = {}; + try { + statsDetails = await this.refreshStatsDiagnostics(); + } catch { + } + return { + ...statsDetails, + mode: statsDetails.mode ?? this.selectedMode, + connectionState: this.pc.connectionState, + iceConnectionState: this.pc.iceConnectionState, + dataChannelState: this.channel?.readyState, + diagnostics: this.diagnostics() + }; + } + getStats() { + const connected = this.channel?.readyState === "open"; + return { + mode: !connected ? "Disconnected" : this.selectedMode ?? (this.selected === "turn" ? "TURN" : this.selected === "lan" ? "LAN" : "P2P"), + connected, + bytesSent: this.bytesSent, + bytesReceived: this.bytesReceived + }; + } + /** Idempotent close: releases PeerConnection, DataChannel, timers and listeners. */ + async close() { + if (this.closed) + return; + this.closed = true; + this.clearNegotiation(); + this.openReject?.(new RtcConnectError("RTC_CLOSED", "WebRTC transport closed during negotiation.")); + this.openResolve = void 0; + this.openReject = void 0; + this.clearWatchdog(); + const channel = this.channel; + this.channel = void 0; + if (channel !== void 0) { + channel.onopen = null; + channel.onmessage = null; + channel.onclose = null; + channel.onerror = null; + channel.onbufferedamountlow = null; + try { + channel.close(); + } catch { + } + } + this.pc.onicecandidate = null; + this.pc.ondatachannel = null; + this.pc.onconnectionstatechange = null; + this.pc.oniceconnectionstatechange = null; + try { + this.pc.close(); + } catch { + } + if (this.opened) { + this.opened = false; + for (const handler of this.closeHandlers) + handler(); + } + } + armAbort(signal) { + this.removeAbort?.(); + this.removeAbort = void 0; + if (signal === void 0) + return; + const onAbort = () => { + this.failOpen(new RtcConnectError("RTC_ABORTED", "WebRTC negotiation was aborted.")); + }; + signal.addEventListener("abort", onAbort, { once: true }); + this.removeAbort = () => signal.removeEventListener("abort", onAbort); + if (signal.aborted) + onAbort(); + } + async startInitiator() { + const channel = this.pc.createDataChannel(this.channelLabel, RTC_DATA_CHANNEL_OPTIONS); + this.adoptChannel(channel); + const offer = await this.pc.createOffer(); + if (this.closed) + return; + await this.pc.setLocalDescription(offer); + if (this.closed) + return; + this.onSignal({ type: "offer", sdp: requireSdp(offer) }); + } + async handleOffer(sdp) { + if (this.role !== "responder" || this.remoteDescriptionSet) { + this.failOpen(new RtcConnectError("RTC_INVALID_STATE", "Received an unexpected WebRTC offer.")); + return; + } + try { + await this.pc.setRemoteDescription({ type: "offer", sdp }); + this.remoteDescriptionSet = true; + await this.flushRemoteCandidates(); + const answer = await this.pc.createAnswer(); + await this.pc.setLocalDescription(answer); + this.onSignal({ type: "answer", sdp: requireSdp(answer) }); + } catch (error62) { + this.failOpen(asError(error62)); + } + } + async handleAnswer(sdp) { + if (this.role !== "initiator" || this.remoteDescriptionSet) { + this.failOpen(new RtcConnectError("RTC_INVALID_STATE", "Received an unexpected WebRTC answer.")); + return; + } + try { + await this.pc.setRemoteDescription({ type: "answer", sdp }); + this.remoteDescriptionSet = true; + await this.flushRemoteCandidates(); + } catch (error62) { + this.failOpen(asError(error62)); + } + } + async handleIce(candidate) { + const summary3 = summarizeIceCandidate(candidate); + if (!this.remoteDescriptionSet) { + recordCandidate(this.remoteCandidateTelemetry, summary3); + this.emitDiagnostic({ type: "remote-candidate", candidate: summary3, action: "buffered", diagnostics: this.diagnostics() }); + this.remoteCandidates.push(candidate); + return; + } + try { + await this.pc.addIceCandidate(candidate); + recordCandidate(this.remoteCandidateTelemetry, summary3); + this.emitDiagnostic({ type: "remote-candidate", candidate: summary3, action: "added", diagnostics: this.diagnostics() }); + } catch { + this.emitDiagnostic({ type: "remote-candidate", candidate: summary3, action: "ignored", diagnostics: this.diagnostics() }); + } + } + async flushRemoteCandidates() { + const buffered = this.remoteCandidates.splice(0, this.remoteCandidates.length); + for (const candidate of buffered) { + try { + await this.pc.addIceCandidate(candidate); + } catch { + } + } + } + adoptChannel(channel) { + if (this.channel !== void 0 && this.channel !== channel) { + try { + channel.close(); + } catch { + } + return; + } + this.channel = channel; + channel.binaryType = "arraybuffer"; + channel.onopen = () => { + if (this.closed || this.opened) + return; + this.opened = true; + const resolve10 = this.openResolve; + this.clearNegotiation(); + void this.resolveSelectedTransport().then(() => { + if (this.closed) + return; + this.openResolve = void 0; + this.openReject = void 0; + resolve10?.(); + }); + }; + channel.onmessage = (event) => { + if (this.closed || !this.opened) + return; + const data2 = event.data; + const frame = typeof data2 === "string" ? new TextEncoder().encode(data2) : new Uint8Array(data2); + this.bytesReceived += frame.byteLength; + try { + const message = this.incoming.decode(frame); + if (message === void 0) + return; + for (const handler of this.messageHandlers) + handler(message); + } catch { + void this.close(); + } + }; + channel.onclose = () => { + if (this.closed) + return; + this.failOpen(new RtcConnectError("RTC_CLOSED", "WebRTC data channel closed.")); + if (this.opened) { + this.opened = false; + for (const handler of this.closeHandlers) + handler(); + } + }; + channel.onerror = () => { + const error62 = new RtcConnectError("RTC_FAILED", "WebRTC data channel reported an error."); + this.failOpen(error62); + for (const handler of this.errorHandlers) + handler(error62); + }; + } + async resolveSelectedTransport() { + try { + let selected = await this.refreshStatsDiagnostics(); + for (let attempt = 0; attempt < SELECTED_PATH_RETRY_COUNT && !this.closed && (selected.transport === void 0 || selected.mode === void 0 || selected.mode === "P2P"); attempt += 1) { + await sleep(SELECTED_PATH_RETRY_DELAY_MS); + selected = await this.refreshStatsDiagnostics(); + } + this.selected = selected?.transport; + this.selectedMode = selected?.mode; + this.selectedRelayUrlValue = selected?.relayUrl; + this.selectedPathTelemetry = selectedPathTelemetry(selected); + this.emitDiagnostic({ + type: "selected-path", + selectedPath: this.selectedPathTelemetry, + diagnostics: this.diagnostics() + }); + } catch { + this.selected = void 0; + this.selectedMode = void 0; + } + } + checkConnectionState() { + if (this.closed || this.opened) + return; + if (this.pc.connectionState === "failed" || this.pc.iceConnectionState === "failed" || this.pc.connectionState === "closed" || this.pc.iceConnectionState === "closed") { + void this.failOpenAfterStats(new RtcConnectError("RTC_FAILED", "WebRTC peer connection failed before the data channel opened.")); + } + } + async failOpenAfterStats(error62) { + await this.refreshStatsDiagnostics().catch(() => void 0); + this.failOpen(error62); + } + failOpen(error62) { + if (this.closed || this.opened || this.openReject === void 0) + return; + const reject = this.openReject; + this.clearNegotiation(); + this.openResolve = void 0; + this.openReject = void 0; + reject(error62); + void this.close(); + } + clearNegotiation() { + if (this.negotiateTimer !== void 0) + clearTimeout(this.negotiateTimer); + this.negotiateTimer = void 0; + this.removeAbort?.(); + this.removeAbort = void 0; + } + requireOpenChannel() { + const channel = this.channel; + if (channel === void 0 || channel.readyState !== "open" || this.closed || !this.opened) { + throw new Error("WebRTC data channel is not open."); + } + return channel; + } + armWatchdog(channel) { + if (this.closed || this.sendTimeoutMs === void 0 || this.sendTimeoutMs <= 0) + return; + if (this.watchdogTimer !== void 0) + clearTimeout(this.watchdogTimer); + this.watchdogTimer = void 0; + const baseline = channel.bufferedAmount; + if (baseline <= 0) { + this.lastBufferedAmount = 0; + return; + } + this.lastBufferedAmount = baseline; + this.watchdogTimer = setTimeout(() => { + this.watchdogTimer = void 0; + if (this.closed || this.channel !== channel || channel.readyState !== "open") + return; + const current = channel.bufferedAmount; + if (current > 0 && current >= this.lastBufferedAmount) { + const error62 = new RtcConnectError("RTC_SEND_TIMEOUT", "DataChannel send stalled."); + for (const handler of this.errorHandlers) + handler(error62); + void this.close(); + return; + } + this.lastBufferedAmount = current; + if (current > 0) + this.armWatchdog(channel); + }, this.sendTimeoutMs); + } + clearWatchdog() { + if (this.watchdogTimer !== void 0) + clearTimeout(this.watchdogTimer); + this.watchdogTimer = void 0; + this.lastBufferedAmount = 0; + } + async refreshStatsDiagnostics() { + const stats = [...await new Promise((resolve10, reject) => { + const timer2 = setTimeout(() => reject(new Error("WebRTC statistics timed out.")), 250); + Promise.resolve().then(() => this.pc.getStats()).then(resolve10, reject).finally(() => clearTimeout(timer2)); + })]; + if (this.closed) + return {}; + this.candidatePairTelemetry = inspectCandidatePairs(stats); + return inspectSelectedPath(stats); + } + handlePeerDiagnostic(event) { + if (event.type === "local-candidate-filtered") { + recordCandidate(this.filteredLocalCandidateTelemetry, event.candidate); + this.emitDiagnostic({ + type: event.type, + candidate: event.candidate, + reason: event.reason, + diagnostics: this.diagnostics() + }); + return; + } + if (event.localCandidate !== void 0) + recordCandidate(this.filteredCandidatePairTelemetry, event.localCandidate); + this.emitDiagnostic({ + type: event.type, + localCandidate: event.localCandidate, + reason: event.reason, + diagnostics: this.diagnostics() + }); + } + emitStateChange() { + this.emitDiagnostic({ + type: "state-change", + connectionState: this.pc.connectionState, + iceConnectionState: this.pc.iceConnectionState, + iceGatheringState: this.pc.iceGatheringState, + diagnostics: this.diagnostics() + }); + } + emitDiagnostic(event) { + try { + this.onDiagnostic?.(event); + } catch { + } + } +}; +var RtcConnectError = class extends Error { + code; + constructor(code, message) { + super(message); + this.code = code; + } +}; +function inspectSelectedPath(stats) { + const candidates = /* @__PURE__ */ new Map(); + const candidatePairs = /* @__PURE__ */ new Map(); + const selectedPairs = []; + const selectedPairIds = /* @__PURE__ */ new Set(); + for (const [reportId, entry] of stats) { + if (entry.type === "local-candidate" || entry.type === "remote-candidate") { + if (typeof entry.candidateType === "string" && entry.id !== void 0) { + candidates.set(String(entry.id), entry); + } + } else if (entry.type === "candidate-pair") { + candidatePairs.set(String(entry.id ?? reportId), entry); + if (entry.selected === true || entry.nominated === true) + selectedPairs.push(entry); + } else if (entry.type === "transport" && typeof entry.selectedCandidatePairId === "string") { + selectedPairIds.add(entry.selectedCandidatePairId); + } + } + const pairs = [ + ...[...selectedPairIds].map((id6) => candidatePairs.get(id6)).filter((pair) => pair !== void 0), + ...selectedPairs + ]; + for (const pair of pairs) { + const local = candidates.get(String(pair.localCandidateId)); + const remote = candidates.get(String(pair.remoteCandidateId)); + const localType = local?.candidateType; + const remoteType = remote?.candidateType; + const localAddressScope = summarizeAddress(candidateAddressValue(local)).addressScope; + const remoteAddressScope = summarizeAddress(candidateAddressValue(remote)).addressScope; + let selected; + if (localType === "relay" || remoteType === "relay") + selected = { transport: "turn", mode: "TURN" }; + const relayUrl = localType === "relay" ? stringStat(local, "url") : void 0; + if (local === void 0 && remote === void 0) + continue; + const lan = isLanCandidatePair(localType, remoteType, localAddressScope, remoteAddressScope); + selected ??= { transport: lan ? "lan" : "p2p", mode: lan ? "LAN" : "P2P" }; + const currentRoundTripTime = numberStat(pair, "currentRoundTripTime"); + return { + ...selected, + ...relayUrl === void 0 ? {} : { relayUrl }, + localCandidateType: stringStat(local, "candidateType"), + remoteCandidateType: stringStat(remote, "candidateType"), + localAddressScope, + remoteAddressScope, + localAddress: candidateAddress(local), + remoteAddress: candidateAddress(remote), + protocol: stringStat(local, "protocol") ?? stringStat(remote, "protocol"), + relayProtocol: stringStat(local, "relayProtocol") ?? stringStat(remote, "relayProtocol"), + currentRoundTripTimeMs: currentRoundTripTime === void 0 ? void 0 : Math.round(currentRoundTripTime * 1e3), + availableOutgoingBitrate: numberStat(pair, "availableOutgoingBitrate"), + bytesSent: numberStat(pair, "bytesSent"), + bytesReceived: numberStat(pair, "bytesReceived") + }; + } + return {}; +} +function inspectCandidatePairs(stats) { + const candidates = /* @__PURE__ */ new Map(); + const telemetry = emptyCandidatePairTelemetry(); + const pairs = []; + for (const [reportId, entry] of stats) { + if (entry.type === "local-candidate" || entry.type === "remote-candidate") { + if (typeof entry.candidateType === "string" && entry.id !== void 0) { + candidates.set(String(entry.id), entry); + } + } else if (entry.type === "candidate-pair") { + pairs.push({ ...entry, id: entry.id ?? reportId }); + } + } + for (const pair of pairs) { + telemetry.total += 1; + if (pair.nominated === true) + telemetry.nominated += 1; + if (pair.selected === true) + telemetry.selected += 1; + increment(telemetry.byState, stringStat(pair, "state") ?? (pair.selected === true ? "selected" : "unknown")); + const local = candidates.get(String(pair.localCandidateId)); + const remote = candidates.get(String(pair.remoteCandidateId)); + recordCandidateStats(telemetry.byLocalType, telemetry.byLocalFamily, telemetry.byLocalScope, local); + recordCandidateStats(telemetry.byRemoteType, telemetry.byRemoteFamily, telemetry.byRemoteScope, remote); + } + return telemetry; +} +function candidateAddress(candidate) { + const address2 = stringStat(candidate, "address") ?? stringStat(candidate, "ip"); + if (address2 === void 0) + return void 0; + const port = numberStat(candidate, "port"); + return port === void 0 ? address2 : `${address2}:${port}`; +} +function stringStat(entry, key) { + const value = entry?.[key]; + return typeof value === "string" && value.length > 0 ? value : void 0; +} +function numberStat(entry, key) { + const value = entry?.[key]; + return typeof value === "number" && Number.isFinite(value) ? value : void 0; +} +function emptyCandidateTelemetry() { + return { + total: 0, + byType: {}, + byFamily: {}, + byScope: {}, + byProtocol: {} + }; +} +function cloneCandidateTelemetry(value) { + return { + total: value.total, + byType: { ...value.byType }, + byFamily: { ...value.byFamily }, + byScope: { ...value.byScope }, + byProtocol: { ...value.byProtocol } + }; +} +function emptyCandidatePairTelemetry() { + return { + total: 0, + nominated: 0, + selected: 0, + byState: {}, + byLocalType: {}, + byRemoteType: {}, + byLocalFamily: {}, + byRemoteFamily: {}, + byLocalScope: {}, + byRemoteScope: {} + }; +} +function cloneCandidatePairTelemetry(value) { + return { + total: value.total, + nominated: value.nominated, + selected: value.selected, + byState: { ...value.byState }, + byLocalType: { ...value.byLocalType }, + byRemoteType: { ...value.byRemoteType }, + byLocalFamily: { ...value.byLocalFamily }, + byRemoteFamily: { ...value.byRemoteFamily }, + byLocalScope: { ...value.byLocalScope }, + byRemoteScope: { ...value.byRemoteScope } + }; +} +function recordCandidate(telemetry, candidate) { + telemetry.total += 1; + increment(telemetry.byType, candidate.candidateType); + increment(telemetry.byFamily, candidate.addressFamily); + increment(telemetry.byScope, candidate.addressScope); + if (candidate.protocol !== void 0) + increment(telemetry.byProtocol, candidate.protocol); +} +function recordCandidateStats(byType, byFamily, byScope, candidate) { + const candidateType = candidateTypeStat(candidate); + const address2 = summarizeAddress(candidateAddressValue(candidate)); + increment(byType, candidateType); + increment(byFamily, address2.addressFamily); + increment(byScope, address2.addressScope); +} +function candidateTypeStat(candidate) { + const value = stringStat(candidate, "candidateType"); + if (value === "host" || value === "srflx" || value === "prflx" || value === "relay") + return value; + return "unknown"; +} +function candidateAddressValue(candidate) { + return stringStat(candidate, "address") ?? stringStat(candidate, "ip"); +} +function isLanCandidatePair(localType, remoteType, localScope, remoteScope) { + if (localType === "host" && remoteType === "host") { + return !isExplicitlyNonLanScope(localScope) && !isExplicitlyNonLanScope(remoteScope); + } + const directTypes = /* @__PURE__ */ new Set(["host", "prflx"]); + if (!directTypes.has(String(localType)) || !directTypes.has(String(remoteType))) + return false; + if (isLocalNetworkScope(localScope) && isLocalNetworkScope(remoteScope)) + return true; + return localType === "host" && isLocalNetworkScope(localScope) && remoteType === "prflx" && remoteScope === "unknown" || remoteType === "host" && isLocalNetworkScope(remoteScope) && localType === "prflx" && localScope === "unknown"; +} +function isLocalNetworkScope(scope2) { + return scope2 === "private" || scope2 === "link-local" || scope2 === "loopback"; +} +function isExplicitlyNonLanScope(scope2) { + return scope2 === "public" || scope2 === "cgnat" || scope2 === "reserved"; +} +function increment(map2, key) { + map2[key] = (map2[key] ?? 0) + 1; +} +function selectedPathTelemetry(details2) { + return { + ...details2.transport === void 0 ? {} : { transport: details2.transport }, + ...details2.mode === void 0 ? {} : { mode: details2.mode }, + ...details2.relayUrl === void 0 ? {} : { relayUrl: details2.relayUrl }, + ...details2.localCandidateType === void 0 ? {} : { localCandidateType: details2.localCandidateType }, + ...details2.remoteCandidateType === void 0 ? {} : { remoteCandidateType: details2.remoteCandidateType }, + ...details2.localAddressScope === void 0 ? {} : { localAddressScope: details2.localAddressScope }, + ...details2.remoteAddressScope === void 0 ? {} : { remoteAddressScope: details2.remoteAddressScope }, + ...details2.protocol === void 0 ? {} : { protocol: details2.protocol }, + ...details2.relayProtocol === void 0 ? {} : { relayProtocol: details2.relayProtocol }, + ...details2.currentRoundTripTimeMs === void 0 ? {} : { currentRoundTripTimeMs: details2.currentRoundTripTimeMs }, + ...details2.availableOutgoingBitrate === void 0 ? {} : { availableOutgoingBitrate: details2.availableOutgoingBitrate } + }; +} +function requireSdp(description) { + if (typeof description.sdp !== "string" || description.sdp.length === 0) { + throw new RtcConnectError("RTC_FAILED", "The RTC backend produced an empty session description."); + } + return description.sdp; +} +function toArrayBuffer(data2) { + if (data2.byteOffset === 0 && data2.byteLength === data2.buffer.byteLength) + return data2.buffer; + return data2.slice().buffer; +} +function asError(error62) { + return error62 instanceof Error ? error62 : new RtcConnectError("RTC_FAILED", "WebRTC negotiation failed."); +} +function sleep(ms) { + return new Promise((resolve10) => setTimeout(resolve10, ms)); +} + +// packages/webrtc/dist/control-lease.js +var WEBRTC_LEASE_MS2 = 3e5; +var ControlLease = class { + connectionId; + ticket; + request; + expired; + confirmed = false; + stopped = false; + sent; + deadline; + sequence = 0; + timer; + lastRequest = -Infinity; + constructor(connectionId, ticket, request, expired) { + this.connectionId = connectionId; + this.ticket = ticket; + this.request = request; + this.expired = expired; + } + start() { + this.timer = setInterval(() => this.tick(), 1e3); + this.deadline = { mono: performance.now() + WEBRTC_LEASE_MS2, wall: Date.now() + WEBRTC_LEASE_MS2 }; + this.tick(true); + } + valid() { + if (this.stopped) + return false; + const d = this.deadline; + if (d && (performance.now() >= d.mono || Date.now() >= d.wall)) { + this.stop(); + this.expired(); + return false; + } + return true; + } + remainingMs() { + if (!this.confirmed || this.stopped || !this.deadline) + return void 0; + return Math.max(0, Math.min(this.deadline.mono - performance.now(), this.deadline.wall - Date.now())); + } + canDetach() { + return this.confirmed && this.valid(); + } + recoveryTicket() { + return this.canDetach() ? this.ticket : void 0; + } + tick(force = false) { + if (!this.valid()) + return; + const mono = performance.now(); + if (!force && mono - this.lastRequest < 25e3) + return; + const sent = { id: String(++this.sequence), mono, wall: Date.now() }; + this.lastRequest = mono; + try { + this.request({ connectionId: this.connectionId, requestId: sent.id, ticket: this.ticket }); + this.sent = sent; + } catch { + } + } + acknowledge(ack) { + if (!this.valid() || ack.connectionId !== this.connectionId || ack.leaseMs !== WEBRTC_LEASE_MS2) + return; + const sent = this.sent; + if (!sent || sent.id !== ack.requestId) + return; + if (performance.now() - sent.mono >= 3e4 || Date.now() - sent.wall >= 3e4) + return; + this.sent = void 0; + this.ticket = ack.ticket; + this.confirmed = true; + this.deadline = { mono: sent.mono + WEBRTC_LEASE_MS2, wall: sent.wall + WEBRTC_LEASE_MS2 }; + } + stop() { + this.stopped = true; + clearInterval(this.timer); + this.timer = void 0; + this.sent = void 0; + } +}; + +// packages/webrtc/dist/adaptive-transport.js +var DEFAULT_CAPABILITIES = [WEBRTC_RESUME_CAPABILITY, RELAY_RESUME_CAPABILITY, "transport.lan", "transport.p2p", "transport.turn", "transport.relay", "transport.relay.attach", "harness.api.v1"]; +var DEFAULT_PREFERRED_TRANSPORTS = ["lan", "p2p", "turn", "relay"]; +var AdaptiveTransport = class extends BaseTransport { + url; + options; + handshakeHandlers = /* @__PURE__ */ new Set(); + sequencedHandlers = /* @__PURE__ */ new Set(); + socket; + dataSocket; + connectionId; + relayCounter = 0; + bytesSent = 0; + bytesReceived = 0; + dataMode = "relay"; + selected; + rtc; + readyResolve; + readyReject; + handshakeTimer; + lifetime; + removeAbort; + webrtcEnabled = true; + serverNegotiateTimeoutMs; + negotiatedCapabilities = ["transport.relay"]; + controlFrameLimits = {}; + connectedAt; + heartbeatIntervalMs; + lastControlReceivedAt; + lastControlSentAt; + lastRtcDiagnostics; + relayAssignment; + dataReady = false; + recoveryTicket; + relayRecoveryTicket; + lease; + recoveryTimer; + recoveryOpeningTimer; + recoveryAttempt = 0; + controlReady = false; + constructor(url2, options) { + super(); + this.url = url2; + this.options = options; + } + async connect() { + if (this.socket !== void 0 || this.connectedAt !== void 0) + return; + throwIfAborted(this.options.signal); + const lifetime = new AbortController(); + this.lifetime = lifetime; + this.webrtcEnabled = true; + this.serverNegotiateTimeoutMs = void 0; + this.dataMode = "relay"; + this.selected = void 0; + this.connectedAt = void 0; + this.relayCounter = 0; + this.socket = new WebSocket(this.url); + this.controlFrameLimits = {}; + this.socket.binaryType = "arraybuffer"; + await new Promise((resolve10, reject) => { + this.readyResolve = resolve10; + this.readyReject = reject; + const onAbort = () => this.failConnection(new Error("Adaptive connection was aborted")); + this.options.signal?.addEventListener("abort", onAbort, { once: true }); + this.removeAbort = () => this.options.signal?.removeEventListener("abort", onAbort); + this.handshakeTimer = setTimeout(() => this.failConnection(new Error("Adaptive control handshake timed out")), this.options.handshakeTimeoutMs ?? 15e3); + const socket = this.socket; + socket.onmessage = (event) => { + if (this.socket === socket) + void this.handleSocketMessage(event.data, lifetime); + }; + socket.onopen = () => { + if (this.lifetime !== lifetime) + return; + this.sendControl("hello", { + role: this.options.role, + deviceId: this.options.deviceId, + accessToken: this.options.accessToken, + protocols: [PROTOCOL_VERSION], + capabilities: this.options.capabilities ?? DEFAULT_CAPABILITIES + }); + }; + socket.onerror = () => { + if (this.lifetime === lifetime && this.socket === socket) + this.controlLost(new Error("Control socket failed"), { reason: "control-error" }); + }; + socket.onclose = (event) => { + if (this.lifetime === lifetime && this.socket === socket) + this.controlLost(adaptiveControlCloseError(event), { reason: "control-closed", closeCode: event.code, closeReason: event.reason }); + }; + }); + } + async send(data2) { + if (this.lease && !this.lease.valid()) + throw new Error("Control lease expired"); + if (this.connectionId === void 0) + throw new Error("adaptive transport has not been authorized"); + if (this.dataMode === "webrtc") { + const rtc = this.rtc; + if (rtc === void 0) + throw new Error("webrtc data channel is not available"); + this.bytesSent += data2.byteLength; + await rtc.send(data2); + return; + } + const socket = this.dataSocket ?? this.socket; + if (socket?.readyState !== WebSocket.OPEN) + throw new Error("adaptive transport is not connected"); + await waitForRelayCapacity(socket); + const payload = { + connectionId: this.connectionId, + targetDeviceId: this.options.targetDeviceId, + counter: this.relayCounter, + ciphertext: toBase64Url(data2) + }; + if (this.dataSocket !== void 0) { + this.dataSocket.send(encodeRelayDataFrame(createRelayDataFrame("relay", payload), this.controlFrameLimits)); + } else + this.sendControl("relay", payload); + this.bytesSent += data2.byteLength; + this.relayCounter += 1; + } + connectionInfo() { + if (this.connectionId === void 0) + throw new Error("adaptive transport has not been authorized"); + return { + connectionId: this.connectionId, + localDeviceId: this.options.deviceId, + remoteDeviceId: this.options.targetDeviceId + }; + } + async connectionDetails() { + const remainingMs = this.lease?.remainingMs(); + return { + ...this.connectionId === void 0 ? {} : { connectionId: this.connectionId }, + ...this.connectedAt === void 0 ? {} : { connectedAt: this.connectedAt }, + ...this.heartbeatIntervalMs === void 0 ? {} : { heartbeatIntervalMs: this.heartbeatIntervalMs }, + ...this.lastControlReceivedAt === void 0 ? {} : { lastControlReceivedAt: this.lastControlReceivedAt }, + ...this.lastControlSentAt === void 0 ? {} : { lastControlSentAt: this.lastControlSentAt }, + recoveryExpiresAt: remainingMs === void 0 ? void 0 : Date.now() + remainingMs, + controlChannelUrl: this.url, + controlChannelState: socketState(this.socket?.readyState), + preferredTransports: this.options.forceRelay === true ? ["relay"] : [...this.options.preferredTransports ?? DEFAULT_PREFERRED_TRANSPORTS], + negotiatedCapabilities: [...this.negotiatedCapabilities], + webRtcEnabled: this.webrtcEnabled, + ...this.rtc === void 0 ? {} : { webRtc: await this.rtc.connectionDetails() } + }; + } + async sendHandshake(step, data2) { + if (this.socket?.readyState !== WebSocket.OPEN || this.connectionId === void 0) { + throw new Error("adaptive transport has not been authorized"); + } + this.sendControl("secure.handshake", { + connectionId: this.connectionId, + targetDeviceId: this.options.targetDeviceId, + step, + data: toBase64Url(data2) + }); + } + onHandshake(cb) { + this.handshakeHandlers.add(cb); + return () => this.handshakeHandlers.delete(cb); + } + onSequencedMessage(cb) { + this.sequencedHandlers.add(cb); + return () => this.sequencedHandlers.delete(cb); + } + async close() { + this.failConnection(new Error("Adaptive transport closed")); + } + getStats() { + const webrtcConnected = this.dataMode === "webrtc" && this.rtc?.getStats().connected === true; + const relayConnected = this.dataMode === "relay" && (this.dataSocket?.readyState === WebSocket.OPEN && this.dataReady || this.socket?.readyState === WebSocket.OPEN) && this.connectionId !== void 0; + const connected = webrtcConnected || relayConnected; + let mode2 = "Disconnected"; + if (this.selected === "relay") + mode2 = relayConnected ? "Relay" : "Disconnected"; + else if (this.selected === "lan" || this.selected === "turn" || this.selected === "p2p") { + mode2 = webrtcConnected ? this.rtc.getStats().mode : "Disconnected"; + } + return { mode: mode2, connected, bytesSent: this.bytesSent, bytesReceived: this.bytesReceived }; + } + async handleSocketMessage(raw, lifetime) { + if (this.lifetime !== lifetime) + return; + try { + if (typeof raw !== "string") + throw new Error("Adaptive control frames must be text JSON"); + const frame = decodeControlFrame(raw, this.controlFrameLimits); + this.lastControlReceivedAt = Date.now(); + if (frame.type === "hello.ack") { + this.controlReady = true; + const payload = frame.payload; + if (payload.protocol !== PROTOCOL_VERSION) + throw new Error("Server selected an unsupported protocol version"); + this.heartbeatIntervalMs = payload.heartbeatIntervalMs; + const offered = this.options.capabilities ?? DEFAULT_CAPABILITIES; + this.negotiatedCapabilities = acceptNegotiatedCapabilities(offered, payload.capabilities); + this.controlFrameLimits = { + maxControlFrameBytes: payload.maxControlFrameBytes, + maxRelayFrameBytes: payload.maxRelayFrameBytes + }; + const preferredTransports = this.negotiatedTransports(); + if (preferredTransports.length === 0) { + throw new Error("Server did not negotiate a supported transport capability"); + } + if (payload.webrtcEnabled === false) + this.webrtcEnabled = false; + if (typeof payload.webrtcFallbackTimeoutMs === "number" && Number.isSafeInteger(payload.webrtcFallbackTimeoutMs) && payload.webrtcFallbackTimeoutMs > 0) { + this.serverNegotiateTimeoutMs = payload.webrtcFallbackTimeoutMs; + } + if (this.lease) { + if (!this.negotiatedCapabilities.includes(this.dataMode === "webrtc" ? WEBRTC_RESUME_CAPABILITY : RELAY_RESUME_CAPABILITY)) + throw new Error("Server no longer supports control recovery"); + clearTimeout(this.recoveryOpeningTimer); + this.recoveryAttempt = 0; + this.lease.tick(true); + return; + } + this.sendControl("connect.request", { + hostDeviceId: this.options.targetDeviceId, + preferredTransports + }); + return; + } + if (frame.type === "connect.accepted") { + if (this.connectionId !== void 0) + throw new Error("Duplicate connect.accepted"); + const payload = frame.payload; + if (typeof payload.connectionId !== "string" || payload.connectionId.length === 0) { + throw new Error("connect.accepted did not include a connectionId"); + } + this.connectionId = payload.connectionId; + if (this.negotiatedCapabilities.includes(WEBRTC_RESUME_CAPABILITY)) + this.recoveryTicket = payload.recoveryTicket; + if (this.negotiatedCapabilities.includes(RELAY_RESUME_CAPABILITY)) + this.relayRecoveryTicket = payload.relayRecoveryTicket; + const assignment = payload; + if (typeof assignment.relayEndpoint === "string" && typeof assignment.relayTicket === "string") { + this.relayAssignment = assignment; + } + this.clearHandshake(); + void this.negotiate(lifetime.signal).catch((error62) => { + if (this.lifetime === lifetime) + this.failConnection(error62 instanceof Error ? error62 : new Error("Adaptive transport negotiation failed")); + }); + return; + } + if (frame.type === "connection.lease.ack") { + if (!this.lease) + throw new Error("Unexpected connection lease"); + this.lease.acknowledge(frame.payload); + return; + } + if (frame.type === "connect.rejected" || frame.type === "error") { + const payload = frame.payload; + const message = typeof payload.message === "string" ? payload.message : "Server rejected the connection"; + const failure5 = Object.assign(new Error(message), { code: payload.code, retryable: payload.retryable }); + const code = errorCodeSchema.safeParse(payload.code); + this.failConnection(failure5, { + reason: payload.retryable === true ? "control-error" : "invalid-control-frame", + ...code.success ? { errorCode: code.data } : {} + }); + return; + } + if (frame.type === "relay") { + if (this.dataSocket !== void 0) + return; + if (this.dataMode !== "relay") + return; + this.handleRelay(frame.payload); + return; + } + if (frame.type === "secure.handshake") { + const payload = frame.payload; + if (payload.connectionId !== this.connectionId || payload.targetDeviceId !== this.options.deviceId || !Number.isSafeInteger(payload.step) || typeof payload.data !== "string") { + throw new Error("Received a secure handshake frame for an unknown connection"); + } + const data2 = fromBase64Url(payload.data); + for (const handler of this.handshakeHandlers) + handler(payload.step, data2); + return; + } + if (frame.type === "signal.answer") { + const payload = frame.payload; + if (payload.connectionId === this.connectionId && typeof payload.sdp === "string") { + this.rtc?.handleSignal({ type: "answer", sdp: payload.sdp }); + } + return; + } + if (frame.type === "signal.ice") { + const payload = frame.payload; + if (payload.connectionId === this.connectionId && isObject2(payload.candidate)) { + this.rtc?.handleSignal({ type: "ice", candidate: payload.candidate }); + } + return; + } + if (frame.type === "signal.offer" || frame.type === "transport.selected") + return; + if (frame.type === "ping") + this.sendControl("pong", frame.payload); + } catch (error62) { + const failure5 = error62 instanceof Error ? error62 : new Error("Invalid adaptive control frame"); + if (!("code" in failure5)) + Object.assign(failure5, { code: "INVALID_MESSAGE" }); + const code = errorCodeSchema.safeParse(failure5.code); + this.failConnection(failure5, { reason: "invalid-control-frame", ...code.success ? { errorCode: code.data } : {} }); + } + } + handleRelay(payload) { + if (payload.connectionId !== this.connectionId || payload.targetDeviceId !== this.options.deviceId || !Number.isSafeInteger(payload.counter) || typeof payload.ciphertext !== "string") { + throw new Error("Received a relay frame for an unknown connection"); + } + const data2 = fromBase64Url(payload.ciphertext); + this.bytesReceived += data2.byteLength; + for (const handler of this.sequencedHandlers) + handler(payload.counter, data2); + this.emit(data2); + } + async negotiate(signal) { + if (this.connectionId === void 0) + return; + const preferred = this.negotiatedTransports(); + const wantWebRtc = !this.options.forceRelay && !this.options.relayFirst && this.webrtcEnabled && (preferred.includes("lan") || preferred.includes("p2p") || preferred.includes("turn")); + let selected = "relay"; + this.lastRtcDiagnostics = void 0; + if (wantWebRtc) { + try { + const rtcSelected = (await this.tryWebRtc(signal)).transport; + throwIfAborted(signal); + const wireSelected = rtcSelected === "lan" && !preferred.includes("lan") && preferred.includes("p2p") ? "p2p" : rtcSelected; + if (!preferred.includes(wireSelected)) { + await this.rtc?.close(); + throwIfAborted(signal); + this.rtc = void 0; + if (!preferred.includes("relay")) { + throw new Error(`WebRTC selected unnegotiated transport: ${rtcSelected}`); + } + this.dataMode = "relay"; + selected = "relay"; + } else { + this.dataMode = "webrtc"; + selected = wireSelected; + } + } catch (error62) { + throwIfAborted(signal); + const reason = error62 instanceof Error ? error62 : new Error("WebRTC negotiation failed."); + try { + this.options.onWebRtcFallback?.(reason, this.lastRtcDiagnostics); + } catch { + } + await this.rtc?.close(); + throwIfAborted(signal); + this.rtc = void 0; + if (!preferred.includes("relay")) + throw reason; + this.dataMode = "relay"; + selected = "relay"; + } + } else { + if (!preferred.includes("relay")) + throw new Error("No negotiated transport is available"); + this.dataMode = "relay"; + selected = "relay"; + } + this.selected = selected; + if (selected === "relay" && this.relayAssignment !== void 0) { + await this.openDataSocket(this.relayAssignment); + } + const turnNode = selected === "turn" ? this.rtc?.selectedRelayUrl() : void 0; + this.sendControl("transport.selected", { + connectionId: this.connectionId, + targetDeviceId: this.options.targetDeviceId, + transport: selected, + ...turnNode === void 0 ? {} : { turnNode } + }); + this.finishConnection(); + } + negotiatedTransports() { + const preferred = this.options.forceRelay === true ? ["relay"] : this.options.preferredTransports ?? DEFAULT_PREFERRED_TRANSPORTS; + return preferred.filter((transport) => { + if (transport === "lan") + return this.negotiatedCapabilities.includes("transport.lan"); + if (transport === "p2p") + return this.negotiatedCapabilities.includes("transport.p2p"); + return this.negotiatedCapabilities.includes(`transport.${transport}`); + }); + } + async tryWebRtc(signal) { + const connectionId = this.connectionId; + if (connectionId === void 0) + throw new RtcConnectError("RTC_UNAVAILABLE", "No connection id for WebRTC negotiation."); + const factory = this.options.rtcFactory ?? (typeof RTCPeerConnection === "undefined" ? void 0 : browserRtcFactory()); + if (factory === void 0) { + throw new RtcConnectError("RTC_UNAVAILABLE", "No RTC backend is available in this environment."); + } + let iceServers = []; + try { + iceServers = await this.fetchIceServers(connectionId, signal); + } catch { + iceServers = []; + } + throwIfAborted(signal); + const negotiatedMs = negotiateTimeout(this.serverNegotiateTimeoutMs, this.options.negotiateTimeoutMs); + const effectiveNegotiateTimeoutMs = iceServers.length === 0 ? Math.min(negotiatedMs ?? DEFAULT_EMPTY_ICE_NEGOTIATE_TIMEOUT_MS, DEFAULT_EMPTY_ICE_NEGOTIATE_TIMEOUT_MS) : negotiatedMs; + const rtc = new RtcDataChannelTransport({ + role: "initiator", + factory, + iceServers, + // A TURN-only attempt must constrain ICE itself. Otherwise a faster + // direct pair wins, then gets rejected as an unnegotiated transport. + iceTransportPolicy: this.negotiatedTransports().includes("turn") && !this.negotiatedTransports().some((transport) => transport === "lan" || transport === "p2p") ? "relay" : "all", + onSignal: (signal2) => this.sendRtcSignal(signal2), + negotiateTimeoutMs: effectiveNegotiateTimeoutMs, + label: `client->${this.options.targetDeviceId}`, + onDiagnostic: (event) => { + this.lastRtcDiagnostics = event.diagnostics; + try { + this.options.onWebRtcDiagnostic?.(event); + } catch { + } + } + }); + this.rtc = rtc; + rtc.onMessage((data2) => { + if (this.lease && !this.lease.valid()) + return; + this.bytesReceived += data2.byteLength; + for (const handler of this.sequencedHandlers) + handler(void 0, data2); + this.emit(data2); + }); + rtc.onClose(() => { + if (this.rtc === rtc && this.dataMode === "webrtc") { + const transport = this.selected; + this.failConnection(new Error("Active WebRTC channel closed"), { + reason: "webrtc-closed", + ...transport === "lan" || transport === "p2p" || transport === "turn" ? { transport } : {} + }); + } + }); + try { + await rtc.connect(signal); + } catch (error62) { + throwIfAborted(signal); + this.lastRtcDiagnostics = rtc.diagnostics(); + await rtc.close(); + if (this.rtc === rtc) + this.rtc = void 0; + throwIfAborted(signal); + throw error62; + } + throwIfAborted(signal); + this.lastRtcDiagnostics = rtc.diagnostics(); + return { transport: rtc.selectedTransport() ?? "p2p", relayUrl: rtc.selectedRelayUrl() }; + } + markSecureReady() { + const ticket = this.dataMode === "webrtc" ? this.recoveryTicket : this.dataReady && this.dataSocket?.readyState === WebSocket.OPEN ? this.relayRecoveryTicket : void 0; + if (!ticket || !this.connectionId || this.lease) + return; + this.lease = new ControlLease(this.connectionId, ticket, (payload) => { + if (this.controlReady && this.lastControlReceivedAt !== void 0 && Date.now() - this.lastControlReceivedAt >= 75e3) { + this.controlLost(new Error("Control heartbeat timed out"), { reason: "control-error" }); + throw new Error("Control heartbeat timed out"); + } + this.sendControl("connection.lease.request", payload); + }, () => this.failConnection(Object.assign(new Error("Control authorization lease expired"), { code: "TRANSPORT_CLOSED", retryable: true }))); + this.lease.start(); + } + controlLost(error62, diagnostic) { + if (error62.retryable === false || !this.lease?.canDetach() || !(this.dataMode === "webrtc" ? this.rtc?.getStats().connected : this.dataReady && this.dataSocket?.readyState === WebSocket.OPEN)) { + this.failConnection(error62, diagnostic); + return; + } + const socket = this.socket; + this.controlReady = false; + this.socket = void 0; + clearTimeout(this.recoveryOpeningTimer); + socket?.close(); + if (this.recoveryTimer !== void 0) + return; + const delay2 = recoveryDelayMs(this.recoveryAttempt, diagnostic); + this.recoveryAttempt++; + this.recoveryTimer = setTimeout(() => { + this.recoveryTimer = void 0; + void this.reopenControl(); + }, delay2); + } + async reopenControl() { + const lifetime = this.lifetime; + if (!lifetime || !this.lease?.canDetach()) + return; + try { + const token = this.options.refreshAccessToken ? await this.options.refreshAccessToken() : this.options.accessToken; + if (this.lifetime !== lifetime || !this.lease?.canDetach()) + return; + const socket = new WebSocket(this.url); + this.socket = socket; + socket.binaryType = "arraybuffer"; + this.recoveryOpeningTimer = setTimeout(() => { + if (this.socket === socket) + this.controlLost(new Error("Control recovery handshake timed out"), { reason: "control-error" }); + }, 15e3); + socket.onopen = () => { + if (this.socket !== socket || this.lifetime !== lifetime) + return; + this.sendControl("hello", { + role: this.options.role, + deviceId: this.options.deviceId, + accessToken: token, + protocols: [PROTOCOL_VERSION], + capabilities: this.options.capabilities ?? DEFAULT_CAPABILITIES + }); + }; + socket.onmessage = (event) => { + if (this.socket === socket && this.lifetime === lifetime) + void this.handleSocketMessage(event.data, lifetime); + }; + socket.onerror = () => { + if (this.socket === socket) + this.controlLost(new Error("Control recovery failed"), { reason: "control-error" }); + }; + socket.onclose = (event) => { + if (this.socket === socket) + this.controlLost(adaptiveControlCloseError(event), { reason: "control-closed", closeCode: event.code, closeReason: event.reason }); + }; + } catch (error62) { + if (this.lifetime !== lifetime) + return; + if (typeof error62 === "object" && error62 && ("retryable" in error62 && error62.retryable === false || "code" in error62 && ["AUTH_INVALID", "DEVICE_REVOKED", "MEMBERSHIP_REQUIRED", "PEER_IDENTITY_MISMATCH", "DEVICE_NOT_FOUND", "TOKEN_REUSED"].includes(String(error62.code)))) { + this.failConnection(error62 instanceof Error ? error62 : new Error("Control recovery authorization failed")); + } else + this.controlLost(new Error("Control recovery unavailable"), { reason: "control-error" }); + } + } + async fetchIceServers(connectionId, signal) { + if (this.options.fetchIceServers === void 0) + return []; + return new Promise((resolve10, reject) => { + const request = new AbortController(); + let settled = false; + const finish = (error62, servers = []) => { + if (settled) + return; + settled = true; + clearTimeout(timer2); + signal.removeEventListener("abort", onAbort); + if (error62) + reject(error62); + else + resolve10(servers); + }; + const onAbort = () => { + finish(new Error("ICE configuration request was aborted")); + request.abort(); + }; + const timer2 = setTimeout(() => { + finish(new Error("ICE configuration request timed out")); + request.abort(); + }, this.options.iceServersTimeoutMs ?? 1e4); + signal.addEventListener("abort", onAbort, { once: true }); + if (signal.aborted) { + onAbort(); + return; + } + Promise.resolve().then(() => { + throwIfAborted(request.signal); + return this.options.fetchIceServers(connectionId, request.signal); + }).then((servers) => finish(void 0, servers), (error62) => finish(error62 instanceof Error ? error62 : new Error("ICE configuration request failed"))); + }); + } + sendRtcSignal(signal) { + if (this.connectionId === void 0) + return; + if (signal.type === "offer") { + this.sendControl("signal.offer", { + connectionId: this.connectionId, + targetDeviceId: this.options.targetDeviceId, + sdp: signal.sdp + }); + } else if (signal.type === "answer") { + this.sendControl("signal.answer", { + connectionId: this.connectionId, + targetDeviceId: this.options.targetDeviceId, + sdp: signal.sdp + }); + } else { + this.sendControl("signal.ice", { + connectionId: this.connectionId, + targetDeviceId: this.options.targetDeviceId, + candidate: signal.candidate + }); + } + } + async openDataSocket(assignment) { + if (this.connectionId === void 0 || this.dataSocket !== void 0) + return; + const socket = new WebSocket(assignment.relayEndpoint); + socket.binaryType = "arraybuffer"; + this.dataSocket = socket; + await new Promise((resolve10, reject) => { + const timer2 = setTimeout(() => { + reject(new Error("Relay data attach timed out")); + socket.close(); + }, this.options.handshakeTimeoutMs ?? 15e3); + socket.onopen = () => socket.send(encodeRelayDataFrame(createRelayDataFrame("relay.attach", { + connectionId: this.connectionId, + deviceId: this.options.deviceId, + peerDeviceId: this.options.targetDeviceId, + ticket: assignment.relayTicket + }), this.controlFrameLimits)); + socket.onmessage = (event) => { + try { + if (typeof event.data !== "string") + throw new Error("Relay data frames must be text JSON"); + const data2 = decodeRelayDataFrame(event.data, this.controlFrameLimits); + if (data2.type === "relay.ready") { + if (data2.payload.connectionId !== this.connectionId || assignment.relayEpoch !== void 0 && data2.payload.epoch !== assignment.relayEpoch) { + throw new Error("Relay data attach assignment mismatch"); + } + clearTimeout(timer2); + this.dataReady = true; + resolve10(); + return; + } + void this.handleDataSocketFrame(data2.type, data2.payload).catch((error62) => { + this.failConnection(error62 instanceof Error ? error62 : new Error("Invalid Relay data frame")); + }); + } catch (error62) { + clearTimeout(timer2); + reject(error62 instanceof Error ? error62 : new Error("Invalid Relay data frame")); + this.failConnection(error62 instanceof Error ? error62 : new Error("Invalid Relay data frame")); + } + }; + socket.onerror = () => { + clearTimeout(timer2); + reject(new Error("Relay data socket failed")); + }; + socket.onclose = () => { + clearTimeout(timer2); + if (!this.dataReady) + reject(new Error("Relay data socket closed before attach")); + else + this.failConnection(new Error("Relay data socket closed")); + }; + }); + } + async handleDataSocketFrame(type, payload) { + if (type === "relay.detach") { + this.failConnection(new Error("Relay peer detached")); + return; + } + if (type === "ping") { + if (this.dataSocket?.readyState === WebSocket.OPEN) { + this.dataSocket.send(encodeRelayDataFrame(createRelayDataFrame("pong", payload), this.controlFrameLimits)); + } + return; + } + if (type === "relay") { + if (payload.connectionId !== this.connectionId || payload.targetDeviceId !== this.options.deviceId || !Number.isSafeInteger(payload.counter) || typeof payload.ciphertext !== "string") { + throw new Error("Received a relay frame for an unknown connection"); + } + const data2 = fromBase64Url(payload.ciphertext); + this.bytesReceived += data2.byteLength; + for (const handler of this.sequencedHandlers) + handler(payload.counter, data2); + this.emit(data2); + return; + } + if (type === "secure.handshake") { + if (payload.connectionId !== this.connectionId || payload.targetDeviceId !== this.options.deviceId || !Number.isSafeInteger(payload.step) || typeof payload.data !== "string") { + throw new Error("Received a secure handshake frame for an unknown connection"); + } + const data2 = fromBase64Url(payload.data); + for (const handler of this.handshakeHandlers) + handler(payload.step, data2); + } + } + sendControl(type, payload) { + if (this.socket?.readyState !== WebSocket.OPEN) + throw Object.assign(new Error("adaptive control socket is not open"), { code: "TRANSPORT_CLOSED" }); + this.socket.send(encodeControlFrame(createControlFrame(type, payload), this.controlFrameLimits)); + this.lastControlSentAt = Date.now(); + } + finishConnection() { + this.clearHandshake(); + this.removeAbort?.(); + this.removeAbort = void 0; + this.connectedAt ??= Date.now(); + this.readyResolve?.(); + this.readyResolve = void 0; + this.readyReject = void 0; + } + failConnection(error62, diagnostic) { + if (this.lease && this.connectionId && this.socket?.readyState === WebSocket.OPEN) { + try { + this.sendControl("connection.lease.close", { connectionId: this.connectionId }); + } catch { + } + } + const established = this.connectedAt !== void 0; + this.controlReady = false; + this.recoveryAttempt = 0; + this.lease?.stop(); + this.lease = void 0; + this.recoveryTicket = void 0; + this.relayRecoveryTicket = void 0; + clearTimeout(this.recoveryTimer); + clearTimeout(this.recoveryOpeningTimer); + this.recoveryTimer = void 0; + this.clearHandshake(); + const reject = this.readyReject; + this.readyResolve = void 0; + this.readyReject = void 0; + this.removeAbort?.(); + this.removeAbort = void 0; + const lifetime = this.lifetime; + this.lifetime = void 0; + const rtc = this.rtc; + const socket = this.socket; + const dataSocket = this.dataSocket; + this.rtc = void 0; + this.socket = void 0; + this.dataSocket = void 0; + this.dataReady = false; + this.relayAssignment = void 0; + this.connectionId = void 0; + this.connectedAt = void 0; + lifetime?.abort(); + reject?.(error62); + void rtc?.close(); + dataSocket?.close(); + socket?.close(); + if (established && diagnostic !== void 0) { + try { + this.options.onDisconnect?.(diagnostic); + } catch { + } + } + if (socket !== void 0 || established) + this.emitClose(error62); + } + clearHandshake() { + if (this.handshakeTimer !== void 0) + clearTimeout(this.handshakeTimer); + this.handshakeTimer = void 0; + } +}; +function adaptiveControlCloseError(event) { + const serverShutdown = isServerShutdownClose(event.code, event.reason); + const heartbeatTimeout = isHeartbeatTimeoutClose(event.code, event.reason); + const reason = event.reason.trim().slice(0, 300); + const detail = reason.length > 0 ? `${reason} (WebSocket ${event.code})` : `WebSocket closed with code ${event.code}`; + return Object.assign(new Error(`Adaptive control channel closed: ${detail}`), { + // Preserve the specific self-hosted authorization reasons so the Client + // runtime can surface a terminal reauthorization state instead of a generic + // transport loss (PR #285). Every other close keeps the shared semantics. + code: event.code === 4003 ? "CONNECTION_REPLACED" : event.code === 4001 && ["AUTH_INVALID", "TOKEN_EXPIRED", "DEVICE_REVOKED"].includes(reason) ? reason : "TRANSPORT_CLOSED", + retryable: serverShutdown || heartbeatTimeout || [1e3, 1001, 1006, 1011, 1012, 1013].includes(event.code) + }); +} +var CONTROL_RECOVERY_MAX_DELAY_MS = 15e3; +function recoveryDelayMs(_attempt, _diagnostic) { + return Math.random() * CONTROL_RECOVERY_MAX_DELAY_MS; +} +function isObject2(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function socketState(readyState) { + if (readyState === 0) + return "connecting"; + if (readyState === 1) + return "open"; + if (readyState === 2) + return "closing"; + return "closed"; +} +function negotiateTimeout(serverMs, localMs) { + if (localMs !== void 0) + return localMs; + if (serverMs === void 0) + return void 0; + return Math.min(SERVER_NEGOTIATE_TIMEOUT_MAX_MS, Math.max(SERVER_NEGOTIATE_TIMEOUT_MIN_MS, serverMs)); +} +var DEFAULT_EMPTY_ICE_NEGOTIATE_TIMEOUT_MS = 4e3; +var SERVER_NEGOTIATE_TIMEOUT_MIN_MS = 6e3; +var SERVER_NEGOTIATE_TIMEOUT_MAX_MS = 12e3; +function throwIfAborted(signal) { + if (signal?.aborted) + throw new Error("Adaptive connection was aborted"); +} + +// packages/webrtc/dist/serial-send.js +var SerialSend = class { + tail = Promise.resolve(); + bytes = 0; + count = 0; + async run(bytes, send) { + if (this.bytes + bytes > 8 * 1024 * 1024 || this.count >= 256) + throw new Error("Encrypted send queue exceeds its limit"); + this.bytes += bytes; + this.count += 1; + const task = this.tail.then(send); + this.tail = task.catch(() => void 0); + try { + await task; + } finally { + this.bytes -= bytes; + this.count -= 1; + } + } +}; + // packages/client-core/dist/index.js var RemoteClientError = class extends Error { code; @@ -67780,8 +70092,8 @@ var AcpSessionTitles = class { this.pending.set(session2.sessionId, controller); const deadline = this.backend === "opencode" ? setTimeout(() => controller.abort(), 2e4) : void 0; try { - for (const delay of this.backend === "opencode" ? [0, 1e3, 3e3, 6e3, 9e3] : [0]) { - if (delay) await waitForTitle(delay, signal); + for (const delay2 of this.backend === "opencode" ? [0, 1e3, 3e3, 6e3, 9e3] : [0]) { + if (delay2) await waitForTitle(delay2, signal); if (signal.aborted || this.closed || session2.titleOverridden) return; const previous = session2.title; try { @@ -67806,14 +70118,14 @@ var AcpSessionTitles = class { this.pending.clear(); } }; -function waitForTitle(delay, signal) { +function waitForTitle(delay2, signal) { return new Promise((resolve10) => { const finish = () => { clearTimeout(timer2); signal.removeEventListener("abort", finish); resolve10(); }; - const timer2 = setTimeout(finish, delay); + const timer2 = setTimeout(finish, delay2); signal.addEventListener("abort", finish, { once: true }); if (signal.aborted) finish(); }); @@ -68798,2000 +71110,6 @@ var AcpVirtualHarness = class _AcpVirtualHarness { } }; -// packages/webrtc/dist/websocket-backpressure.js -async function waitForRelayCapacity(socket) { - const started = Date.now(); - while ((socket.bufferedAmount ?? 0) > 512 * 1024) { - if (socket.readyState !== 1 || Date.now() - started > 1e4) - throw new Error("Relay consumer is too slow or disconnected"); - await new Promise((resolve10) => setTimeout(resolve10, 10)); - } - if (socket.readyState !== 1) - throw new Error("Relay transport closed"); -} - -// packages/webrtc/dist/transport.js -var BaseTransport = class { - handlers = /* @__PURE__ */ new Set(); - closeHandlers = /* @__PURE__ */ new Set(); - onMessage(cb) { - this.handlers.add(cb); - return () => this.handlers.delete(cb); - } - onClose(cb) { - this.closeHandlers.add(cb); - return () => this.closeHandlers.delete(cb); - } - emit(data2) { - for (const handler of this.handlers) - handler(data2); - } - emitClose(error62) { - for (const handler of this.closeHandlers) - handler(error62); - } -}; - -// packages/webrtc/dist/util.js -function toBase64Url(bytes) { - const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""); - const base643 = typeof btoa === "function" ? btoa(binary) : Buffer.from(bytes).toString("base64"); - return base643.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); -} -function fromBase64Url(value) { - const normalized = value.replaceAll("-", "+").replaceAll("_", "/"); - const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "="); - if (typeof atob === "function") - return Uint8Array.from(atob(padded), (char) => char.charCodeAt(0)); - return new Uint8Array(Buffer.from(padded, "base64")); -} - -// packages/webrtc/dist/rtc-adapter.js -var RTC_DATA_CHANNEL_LABEL = "dsh"; -var RTC_DATA_CHANNEL_OPTIONS = { ordered: true }; -function browserRtcFactory() { - return { - create(configuration) { - const raw = new RTCPeerConnection({ - iceServers: configuration.iceServers, - iceTransportPolicy: configuration.iceTransportPolicy - }); - return { - get connectionState() { - return raw.connectionState; - }, - get iceConnectionState() { - return raw.iceConnectionState; - }, - get iceGatheringState() { - return raw.iceGatheringState; - }, - get signalingState() { - return raw.signalingState; - }, - set onconnectionstatechange(value) { - raw.onconnectionstatechange = value; - }, - get onconnectionstatechange() { - return raw.onconnectionstatechange; - }, - set oniceconnectionstatechange(value) { - raw.oniceconnectionstatechange = value; - }, - get oniceconnectionstatechange() { - return raw.oniceconnectionstatechange; - }, - set onicegatheringstatechange(value) { - raw.onicegatheringstatechange = value; - }, - get onicegatheringstatechange() { - return raw.onicegatheringstatechange; - }, - set onicecandidate(value) { - raw.onicecandidate = value; - }, - get onicecandidate() { - return raw.onicecandidate; - }, - set ondatachannel(value) { - raw.ondatachannel = value; - }, - get ondatachannel() { - return raw.ondatachannel; - }, - createDataChannel(label, options) { - return adaptDataChannel(raw.createDataChannel(label, options)); - }, - createOffer() { - return raw.createOffer(); - }, - createAnswer() { - return raw.createAnswer(); - }, - setLocalDescription(description) { - return raw.setLocalDescription(description); - }, - setRemoteDescription(description) { - return raw.setRemoteDescription(description); - }, - addIceCandidate(candidate) { - return raw.addIceCandidate(candidate); - }, - async getStats() { - return await raw.getStats(); - }, - close() { - raw.close(); - } - }; - } - }; -} -function summarizeIceCandidate(candidate) { - const value = candidate?.candidate?.trim(); - if (value === void 0 || value.length === 0) - return emptyCandidateSummary(); - const parts = value.replace(/^candidate:/, "").split(/\s+/); - const typeIndex = parts.indexOf("typ"); - const relatedAddressIndex = parts.indexOf("raddr"); - return { - candidateType: parseCandidateType(parts[typeIndex + 1]), - protocol: normalizeProtocol(parts[2]), - ...summarizeAddress(parts[4]), - ...relatedAddressIndex < 0 ? {} : relatedAddressSummary(parts[relatedAddressIndex + 1]) - }; -} -function summarizeAddress(address2) { - if (address2 === void 0 || address2.length === 0) - return { addressFamily: "unknown", addressScope: "unknown" }; - if (address2.includes(":")) - return { addressFamily: "ipv6", addressScope: summarizeIpv6Scope(address2) }; - const parts = address2.split(".").map(Number); - if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) { - return { addressFamily: "unknown", addressScope: "unknown" }; - } - return { addressFamily: "ipv4", addressScope: summarizeIpv4Scope(parts) }; -} -function stunOnlyIceServers(iceServers) { - const direct = []; - for (const server of iceServers) { - const sourceUrls = Array.isArray(server.urls) ? server.urls : [server.urls]; - const urls = sourceUrls.filter(isStunUrl); - if (urls.length === 0) - continue; - direct.push({ urls: Array.isArray(server.urls) ? urls : urls[0] }); - } - return direct; -} -function isStunUrl(url2) { - const value = url2.trim().toLowerCase(); - return value.startsWith("stun:") || value.startsWith("stuns:"); -} -function emptyCandidateSummary() { - return { candidateType: "unknown", addressFamily: "unknown", addressScope: "unknown" }; -} -function parseCandidateType(value) { - if (value === "host" || value === "srflx" || value === "prflx" || value === "relay") - return value; - return "unknown"; -} -function normalizeProtocol(value) { - if (value === void 0 || value.length === 0) - return void 0; - return value.toLowerCase(); -} -function relatedAddressSummary(address2) { - const summary3 = summarizeAddress(address2); - return { - relatedAddressFamily: summary3.addressFamily, - relatedAddressScope: summary3.addressScope - }; -} -function summarizeIpv4Scope(parts) { - if (parts[0] === 0 || parts[0] >= 240) - return "reserved"; - if (parts[0] === 127) - return "loopback"; - if (parts[0] === 169 && parts[1] === 254) - return "link-local"; - if (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) - return "cgnat"; - if (parts[0] >= 224) - return "reserved"; - if (parts[0] === 10) - return "private"; - if (parts[0] === 192 && parts[1] === 168) - return "private"; - if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) - return "private"; - return "public"; -} -function summarizeIpv6Scope(address2) { - const value = address2.toLowerCase(); - if (value === "::1") - return "loopback"; - if (value.startsWith("fe80:")) - return "link-local"; - if (value.startsWith("fd7a:115c:a1e0:")) - return "cgnat"; - if (value.startsWith("fc") || value.startsWith("fd")) - return "private"; - if (value.startsWith("ff")) - return "reserved"; - return "public"; -} -function adaptDataChannel(raw) { - return { - get label() { - return raw.label; - }, - get ordered() { - return raw.ordered; - }, - get readyState() { - return raw.readyState; - }, - get bufferedAmount() { - return raw.bufferedAmount; - }, - get binaryType() { - return raw.binaryType; - }, - set binaryType(value) { - raw.binaryType = value; - }, - set onopen(value) { - raw.onopen = value; - }, - get onopen() { - return raw.onopen; - }, - set onmessage(value) { - raw.onmessage = value; - }, - get onmessage() { - return raw.onmessage; - }, - set onclose(value) { - raw.onclose = value; - }, - get onclose() { - return raw.onclose; - }, - set onerror(value) { - raw.onerror = value; - }, - get onerror() { - return raw.onerror; - }, - set onbufferedamountlow(value) { - raw.onbufferedamountlow = value; - }, - get onbufferedamountlow() { - return raw.onbufferedamountlow; - }, - send(data2) { - raw.send(data2); - }, - close() { - raw.close(); - } - }; -} - -// packages/webrtc/dist/rtc-chunking.js -var RTC_CHUNK_MAGIC = new Uint8Array([82, 84, 67, 72]); -var RTC_CHUNK_HEADER_BYTES = 12; -var RTC_CHUNK_PAYLOAD_BYTES = 8 * 1024; -var RTC_CHUNK_MAX_MESSAGE_BYTES = 4 * 1024 * 1024; -var RTC_CHUNK_MAX_TOTAL = Math.ceil(RTC_CHUNK_MAX_MESSAGE_BYTES / RTC_CHUNK_PAYLOAD_BYTES); -var MAX_IN_FLIGHT_MESSAGES = 8; -var MAX_ASSEMBLY_AGE_MS = 3e4; -var RtcChunkCodec = class { - nextMessageId = 1; - assemblies = /* @__PURE__ */ new Map(); - encode(data2) { - if (data2.byteLength <= RTC_CHUNK_PAYLOAD_BYTES) - return [data2]; - if (data2.byteLength > RTC_CHUNK_MAX_MESSAGE_BYTES) { - throw new Error("WebRTC transport message exceeds the reassembly limit."); - } - const messageId = this.nextMessageId; - this.nextMessageId = messageId === 4294967295 ? 1 : messageId + 1; - const total = Math.ceil(data2.byteLength / RTC_CHUNK_PAYLOAD_BYTES); - const frames = []; - for (let index = 0; index < total; index += 1) { - const start = index * RTC_CHUNK_PAYLOAD_BYTES; - const chunk = data2.subarray(start, Math.min(data2.byteLength, start + RTC_CHUNK_PAYLOAD_BYTES)); - const frame = new Uint8Array(RTC_CHUNK_HEADER_BYTES + chunk.byteLength); - frame.set(RTC_CHUNK_MAGIC); - const view = new DataView(frame.buffer); - view.setUint32(4, messageId); - view.setUint16(8, index); - view.setUint16(10, total); - frame.set(chunk, RTC_CHUNK_HEADER_BYTES); - frames.push(frame); - } - return frames; - } - decode(frame) { - if (!isChunk(frame)) { - if (frame.byteLength > RTC_CHUNK_MAX_MESSAGE_BYTES) { - throw new Error("WebRTC transport message exceeds the reassembly limit."); - } - return frame; - } - if (frame.byteLength < RTC_CHUNK_HEADER_BYTES) - throw new Error("WebRTC transport chunk header is invalid."); - const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength); - const messageId = view.getUint32(4); - const index = view.getUint16(8); - const total = view.getUint16(10); - if (messageId === 0 || total < 2 || total > RTC_CHUNK_MAX_TOTAL || index >= total) { - throw new Error("WebRTC transport chunk metadata is invalid."); - } - const chunk = frame.subarray(RTC_CHUNK_HEADER_BYTES); - if (chunk.byteLength > RTC_CHUNK_PAYLOAD_BYTES || index < total - 1 && chunk.byteLength !== RTC_CHUNK_PAYLOAD_BYTES || index === total - 1 && chunk.byteLength === 0) { - throw new Error("WebRTC transport chunk length is invalid."); - } - this.pruneStale(); - let assembly = this.assemblies.get(messageId); - if (assembly === void 0) { - if (index !== 0 || this.assemblies.size >= MAX_IN_FLIGHT_MESSAGES) { - throw new Error("WebRTC transport chunk sequence is invalid."); - } - assembly = { messageId, total, receivedBytes: 0, chunks: [], updatedAt: Date.now() }; - this.assemblies.set(messageId, assembly); - } - if (assembly.total !== total || index !== assembly.chunks.length) { - this.assemblies.delete(messageId); - throw new Error("WebRTC transport chunk sequence is invalid."); - } - const receivedBytes = assembly.receivedBytes + chunk.byteLength; - if (receivedBytes > RTC_CHUNK_MAX_MESSAGE_BYTES) { - this.assemblies.delete(messageId); - throw new Error("WebRTC transport message exceeds the reassembly limit."); - } - assembly.chunks.push(Uint8Array.from(chunk)); - assembly.receivedBytes = receivedBytes; - assembly.updatedAt = Date.now(); - if (assembly.chunks.length < total) - return void 0; - this.assemblies.delete(messageId); - const message = new Uint8Array(assembly.receivedBytes); - let offset = 0; - for (const part of assembly.chunks) { - message.set(part, offset); - offset += part.byteLength; - } - return message; - } - reset() { - this.nextMessageId = 1; - this.assemblies.clear(); - } - pruneStale() { - const now = Date.now(); - for (const [messageId, assembly] of this.assemblies) { - if (now - assembly.updatedAt > MAX_ASSEMBLY_AGE_MS) - this.assemblies.delete(messageId); - } - } -}; -function isChunk(frame) { - if (frame.byteLength < RTC_CHUNK_MAGIC.byteLength) - return false; - for (let index = 0; index < RTC_CHUNK_MAGIC.byteLength; index += 1) { - if (frame[index] !== RTC_CHUNK_MAGIC[index]) - return false; - } - return true; -} - -// packages/webrtc/dist/rtc-data-channel.js -var DEFAULT_NEGOTIATE_TIMEOUT_MS = 8e3; -var SELECTED_PATH_RETRY_COUNT = 5; -var SELECTED_PATH_RETRY_DELAY_MS = 50; -var RtcDataChannelTransport = class { - pc; - role; - onSignal; - negotiateTimeoutMs; - channelLabel; - sendTimeoutMs; - label; - onDiagnostic; - channel; - remoteCandidates = []; - remoteDescriptionSet = false; - opened = false; - closed = false; - messageHandlers = /* @__PURE__ */ new Set(); - closeHandlers = /* @__PURE__ */ new Set(); - errorHandlers = /* @__PURE__ */ new Set(); - connectPromise; - openResolve; - openReject; - negotiateTimer; - removeAbort; - watchdogTimer; - outgoing = new RtcChunkCodec(); - incoming = new RtcChunkCodec(); - bytesSent = 0; - bytesReceived = 0; - selected; - selectedMode; - selectedRelayUrlValue; - selectedPathTelemetry; - localCandidateTelemetry = emptyCandidateTelemetry(); - remoteCandidateTelemetry = emptyCandidateTelemetry(); - candidatePairTelemetry = emptyCandidatePairTelemetry(); - filteredLocalCandidateTelemetry = emptyCandidateTelemetry(); - filteredCandidatePairTelemetry = emptyCandidateTelemetry(); - lastBufferedAmount = 0; - constructor(options) { - this.role = options.role; - this.onSignal = options.onSignal; - this.negotiateTimeoutMs = options.negotiateTimeoutMs ?? DEFAULT_NEGOTIATE_TIMEOUT_MS; - this.channelLabel = options.channelLabel ?? RTC_DATA_CHANNEL_LABEL; - this.sendTimeoutMs = options.sendTimeoutMs; - this.label = options.label; - this.onDiagnostic = options.onDiagnostic; - this.pc = options.factory.create({ - iceServers: options.iceServers, - iceTransportPolicy: options.iceTransportPolicy, - onDiagnostic: (event) => this.handlePeerDiagnostic(event) - }); - this.pc.ondatachannel = (event) => this.adoptChannel(event.channel); - this.pc.onicecandidate = (event) => { - if (event.candidate !== null && !this.closed) { - const candidate = summarizeIceCandidate(event.candidate); - recordCandidate(this.localCandidateTelemetry, candidate); - this.emitDiagnostic({ type: "local-candidate", candidate, diagnostics: this.diagnostics() }); - this.onSignal({ type: "ice", candidate: event.candidate }); - } - }; - this.pc.onconnectionstatechange = () => { - this.emitStateChange(); - this.checkConnectionState(); - }; - this.pc.oniceconnectionstatechange = () => { - this.emitStateChange(); - this.checkConnectionState(); - }; - this.pc.onicegatheringstatechange = () => this.emitStateChange(); - } - /** Begin negotiation; resolves when the DataChannel is open. */ - connect(signal) { - if (this.closed) - return Promise.reject(new RtcConnectError("RTC_CLOSED", "WebRTC transport closed.")); - if (signal?.aborted) - return Promise.reject(new RtcConnectError("RTC_ABORTED", "WebRTC negotiation was aborted.")); - if (this.opened) - return Promise.resolve(); - if (this.connectPromise !== void 0) - return this.connectPromise; - this.armAbort(signal); - this.connectPromise = new Promise((resolve10, reject) => { - this.openResolve = resolve10; - this.openReject = reject; - this.negotiateTimer = setTimeout(() => { - void this.failOpenAfterStats(new RtcConnectError("RTC_CONNECT_TIMEOUT", `WebRTC negotiation timed out after ${this.negotiateTimeoutMs}ms.`)); - }, this.negotiateTimeoutMs); - if (this.role === "initiator") { - void this.startInitiator().catch((error62) => this.failOpen(asError(error62))); - } - }); - return this.connectPromise; - } - handleSignal(signal) { - if (this.closed) - return; - if (signal.type === "offer") - void this.handleOffer(signal.sdp); - else if (signal.type === "answer") - void this.handleAnswer(signal.sdp); - else - void this.handleIce(signal.candidate); - } - async send(data2) { - const channel = this.requireOpenChannel(); - if (channel.readyState !== "open") - throw new Error("WebRTC data channel is not open."); - for (const frame of this.outgoing.encode(data2)) { - try { - channel.send(toArrayBuffer(frame)); - } catch (error62) { - console.error("[rtc-send-error] bytes=" + frame.byteLength, error62 instanceof Error ? error62.message : error62); - throw error62; - } - } - this.bytesSent += data2.byteLength; - this.armWatchdog(channel); - } - onMessage(handler) { - this.messageHandlers.add(handler); - return () => this.messageHandlers.delete(handler); - } - onClose(handler) { - this.closeHandlers.add(handler); - return () => this.closeHandlers.delete(handler); - } - onError(handler) { - this.errorHandlers.add(handler); - return () => this.errorHandlers.delete(handler); - } - selectedTransport() { - return this.selected; - } - selectedRelayUrl() { - return this.selectedRelayUrlValue; - } - selectedPathMode() { - return this.selectedMode; - } - diagnostics() { - return { - role: this.role, - ...this.label === void 0 ? {} : { label: this.label }, - connectionState: this.pc.connectionState, - iceConnectionState: this.pc.iceConnectionState, - iceGatheringState: this.pc.iceGatheringState, - localCandidates: cloneCandidateTelemetry(this.localCandidateTelemetry), - remoteCandidates: cloneCandidateTelemetry(this.remoteCandidateTelemetry), - candidatePairs: cloneCandidatePairTelemetry(this.candidatePairTelemetry), - filteredLocalCandidates: cloneCandidateTelemetry(this.filteredLocalCandidateTelemetry), - filteredCandidatePairs: cloneCandidateTelemetry(this.filteredCandidatePairTelemetry), - ...this.selectedPathTelemetry === void 0 ? {} : { selectedPath: { ...this.selectedPathTelemetry } } - }; - } - async connectionDetails() { - let statsDetails = {}; - try { - statsDetails = await this.refreshStatsDiagnostics(); - } catch { - } - return { - ...statsDetails, - mode: statsDetails.mode ?? this.selectedMode, - connectionState: this.pc.connectionState, - iceConnectionState: this.pc.iceConnectionState, - dataChannelState: this.channel?.readyState, - diagnostics: this.diagnostics() - }; - } - getStats() { - const connected = this.channel?.readyState === "open"; - return { - mode: !connected ? "Disconnected" : this.selectedMode ?? (this.selected === "turn" ? "TURN" : this.selected === "lan" ? "LAN" : "P2P"), - connected, - bytesSent: this.bytesSent, - bytesReceived: this.bytesReceived - }; - } - /** Idempotent close: releases PeerConnection, DataChannel, timers and listeners. */ - async close() { - if (this.closed) - return; - this.closed = true; - this.clearNegotiation(); - this.openReject?.(new RtcConnectError("RTC_CLOSED", "WebRTC transport closed during negotiation.")); - this.openResolve = void 0; - this.openReject = void 0; - this.clearWatchdog(); - const channel = this.channel; - this.channel = void 0; - if (channel !== void 0) { - channel.onopen = null; - channel.onmessage = null; - channel.onclose = null; - channel.onerror = null; - channel.onbufferedamountlow = null; - try { - channel.close(); - } catch { - } - } - this.pc.onicecandidate = null; - this.pc.ondatachannel = null; - this.pc.onconnectionstatechange = null; - this.pc.oniceconnectionstatechange = null; - try { - this.pc.close(); - } catch { - } - if (this.opened) { - this.opened = false; - for (const handler of this.closeHandlers) - handler(); - } - } - armAbort(signal) { - this.removeAbort?.(); - this.removeAbort = void 0; - if (signal === void 0) - return; - const onAbort = () => { - this.failOpen(new RtcConnectError("RTC_ABORTED", "WebRTC negotiation was aborted.")); - }; - signal.addEventListener("abort", onAbort, { once: true }); - this.removeAbort = () => signal.removeEventListener("abort", onAbort); - if (signal.aborted) - onAbort(); - } - async startInitiator() { - const channel = this.pc.createDataChannel(this.channelLabel, RTC_DATA_CHANNEL_OPTIONS); - this.adoptChannel(channel); - const offer = await this.pc.createOffer(); - if (this.closed) - return; - await this.pc.setLocalDescription(offer); - if (this.closed) - return; - this.onSignal({ type: "offer", sdp: requireSdp(offer) }); - } - async handleOffer(sdp) { - if (this.role !== "responder" || this.remoteDescriptionSet) { - this.failOpen(new RtcConnectError("RTC_INVALID_STATE", "Received an unexpected WebRTC offer.")); - return; - } - try { - await this.pc.setRemoteDescription({ type: "offer", sdp }); - this.remoteDescriptionSet = true; - await this.flushRemoteCandidates(); - const answer = await this.pc.createAnswer(); - await this.pc.setLocalDescription(answer); - this.onSignal({ type: "answer", sdp: requireSdp(answer) }); - } catch (error62) { - this.failOpen(asError(error62)); - } - } - async handleAnswer(sdp) { - if (this.role !== "initiator" || this.remoteDescriptionSet) { - this.failOpen(new RtcConnectError("RTC_INVALID_STATE", "Received an unexpected WebRTC answer.")); - return; - } - try { - await this.pc.setRemoteDescription({ type: "answer", sdp }); - this.remoteDescriptionSet = true; - await this.flushRemoteCandidates(); - } catch (error62) { - this.failOpen(asError(error62)); - } - } - async handleIce(candidate) { - const summary3 = summarizeIceCandidate(candidate); - if (!this.remoteDescriptionSet) { - recordCandidate(this.remoteCandidateTelemetry, summary3); - this.emitDiagnostic({ type: "remote-candidate", candidate: summary3, action: "buffered", diagnostics: this.diagnostics() }); - this.remoteCandidates.push(candidate); - return; - } - try { - await this.pc.addIceCandidate(candidate); - recordCandidate(this.remoteCandidateTelemetry, summary3); - this.emitDiagnostic({ type: "remote-candidate", candidate: summary3, action: "added", diagnostics: this.diagnostics() }); - } catch { - this.emitDiagnostic({ type: "remote-candidate", candidate: summary3, action: "ignored", diagnostics: this.diagnostics() }); - } - } - async flushRemoteCandidates() { - const buffered = this.remoteCandidates.splice(0, this.remoteCandidates.length); - for (const candidate of buffered) { - try { - await this.pc.addIceCandidate(candidate); - } catch { - } - } - } - adoptChannel(channel) { - if (this.channel !== void 0 && this.channel !== channel) { - try { - channel.close(); - } catch { - } - return; - } - this.channel = channel; - channel.binaryType = "arraybuffer"; - channel.onopen = () => { - if (this.closed || this.opened) - return; - this.opened = true; - const resolve10 = this.openResolve; - this.clearNegotiation(); - void this.resolveSelectedTransport().then(() => { - if (this.closed) - return; - this.openResolve = void 0; - this.openReject = void 0; - resolve10?.(); - }); - }; - channel.onmessage = (event) => { - if (this.closed || !this.opened) - return; - const data2 = event.data; - const frame = typeof data2 === "string" ? new TextEncoder().encode(data2) : new Uint8Array(data2); - this.bytesReceived += frame.byteLength; - try { - const message = this.incoming.decode(frame); - if (message === void 0) - return; - for (const handler of this.messageHandlers) - handler(message); - } catch { - void this.close(); - } - }; - channel.onclose = () => { - if (this.closed) - return; - this.failOpen(new RtcConnectError("RTC_CLOSED", "WebRTC data channel closed.")); - if (this.opened) { - this.opened = false; - for (const handler of this.closeHandlers) - handler(); - } - }; - channel.onerror = () => { - const error62 = new RtcConnectError("RTC_FAILED", "WebRTC data channel reported an error."); - this.failOpen(error62); - for (const handler of this.errorHandlers) - handler(error62); - }; - } - async resolveSelectedTransport() { - try { - let selected = await this.refreshStatsDiagnostics(); - for (let attempt = 0; attempt < SELECTED_PATH_RETRY_COUNT && !this.closed && (selected.transport === void 0 || selected.mode === void 0 || selected.mode === "P2P"); attempt += 1) { - await sleep(SELECTED_PATH_RETRY_DELAY_MS); - selected = await this.refreshStatsDiagnostics(); - } - this.selected = selected?.transport; - this.selectedMode = selected?.mode; - this.selectedRelayUrlValue = selected?.relayUrl; - this.selectedPathTelemetry = selectedPathTelemetry(selected); - this.emitDiagnostic({ - type: "selected-path", - selectedPath: this.selectedPathTelemetry, - diagnostics: this.diagnostics() - }); - } catch { - this.selected = void 0; - this.selectedMode = void 0; - } - } - checkConnectionState() { - if (this.closed || this.opened) - return; - if (this.pc.connectionState === "failed" || this.pc.iceConnectionState === "failed" || this.pc.connectionState === "closed" || this.pc.iceConnectionState === "closed") { - void this.failOpenAfterStats(new RtcConnectError("RTC_FAILED", "WebRTC peer connection failed before the data channel opened.")); - } - } - async failOpenAfterStats(error62) { - await this.refreshStatsDiagnostics().catch(() => void 0); - this.failOpen(error62); - } - failOpen(error62) { - if (this.closed || this.opened || this.openReject === void 0) - return; - const reject = this.openReject; - this.clearNegotiation(); - this.openResolve = void 0; - this.openReject = void 0; - reject(error62); - void this.close(); - } - clearNegotiation() { - if (this.negotiateTimer !== void 0) - clearTimeout(this.negotiateTimer); - this.negotiateTimer = void 0; - this.removeAbort?.(); - this.removeAbort = void 0; - } - requireOpenChannel() { - const channel = this.channel; - if (channel === void 0 || channel.readyState !== "open" || this.closed || !this.opened) { - throw new Error("WebRTC data channel is not open."); - } - return channel; - } - armWatchdog(channel) { - if (this.closed || this.sendTimeoutMs === void 0 || this.sendTimeoutMs <= 0) - return; - if (this.watchdogTimer !== void 0) - clearTimeout(this.watchdogTimer); - this.watchdogTimer = void 0; - const baseline = channel.bufferedAmount; - if (baseline <= 0) { - this.lastBufferedAmount = 0; - return; - } - this.lastBufferedAmount = baseline; - this.watchdogTimer = setTimeout(() => { - this.watchdogTimer = void 0; - if (this.closed || this.channel !== channel || channel.readyState !== "open") - return; - const current = channel.bufferedAmount; - if (current > 0 && current >= this.lastBufferedAmount) { - const error62 = new RtcConnectError("RTC_SEND_TIMEOUT", "DataChannel send stalled."); - for (const handler of this.errorHandlers) - handler(error62); - void this.close(); - return; - } - this.lastBufferedAmount = current; - if (current > 0) - this.armWatchdog(channel); - }, this.sendTimeoutMs); - } - clearWatchdog() { - if (this.watchdogTimer !== void 0) - clearTimeout(this.watchdogTimer); - this.watchdogTimer = void 0; - this.lastBufferedAmount = 0; - } - async refreshStatsDiagnostics() { - const stats = [...await new Promise((resolve10, reject) => { - const timer2 = setTimeout(() => reject(new Error("WebRTC statistics timed out.")), 250); - Promise.resolve().then(() => this.pc.getStats()).then(resolve10, reject).finally(() => clearTimeout(timer2)); - })]; - if (this.closed) - return {}; - this.candidatePairTelemetry = inspectCandidatePairs(stats); - return inspectSelectedPath(stats); - } - handlePeerDiagnostic(event) { - if (event.type === "local-candidate-filtered") { - recordCandidate(this.filteredLocalCandidateTelemetry, event.candidate); - this.emitDiagnostic({ - type: event.type, - candidate: event.candidate, - reason: event.reason, - diagnostics: this.diagnostics() - }); - return; - } - if (event.localCandidate !== void 0) - recordCandidate(this.filteredCandidatePairTelemetry, event.localCandidate); - this.emitDiagnostic({ - type: event.type, - localCandidate: event.localCandidate, - reason: event.reason, - diagnostics: this.diagnostics() - }); - } - emitStateChange() { - this.emitDiagnostic({ - type: "state-change", - connectionState: this.pc.connectionState, - iceConnectionState: this.pc.iceConnectionState, - iceGatheringState: this.pc.iceGatheringState, - diagnostics: this.diagnostics() - }); - } - emitDiagnostic(event) { - try { - this.onDiagnostic?.(event); - } catch { - } - } -}; -var RtcConnectError = class extends Error { - code; - constructor(code, message) { - super(message); - this.code = code; - } -}; -function inspectSelectedPath(stats) { - const candidates = /* @__PURE__ */ new Map(); - const candidatePairs = /* @__PURE__ */ new Map(); - const selectedPairs = []; - const selectedPairIds = /* @__PURE__ */ new Set(); - for (const [reportId, entry] of stats) { - if (entry.type === "local-candidate" || entry.type === "remote-candidate") { - if (typeof entry.candidateType === "string" && entry.id !== void 0) { - candidates.set(String(entry.id), entry); - } - } else if (entry.type === "candidate-pair") { - candidatePairs.set(String(entry.id ?? reportId), entry); - if (entry.selected === true || entry.nominated === true) - selectedPairs.push(entry); - } else if (entry.type === "transport" && typeof entry.selectedCandidatePairId === "string") { - selectedPairIds.add(entry.selectedCandidatePairId); - } - } - const pairs = [ - ...[...selectedPairIds].map((id6) => candidatePairs.get(id6)).filter((pair) => pair !== void 0), - ...selectedPairs - ]; - for (const pair of pairs) { - const local = candidates.get(String(pair.localCandidateId)); - const remote = candidates.get(String(pair.remoteCandidateId)); - const localType = local?.candidateType; - const remoteType = remote?.candidateType; - const localAddressScope = summarizeAddress(candidateAddressValue(local)).addressScope; - const remoteAddressScope = summarizeAddress(candidateAddressValue(remote)).addressScope; - let selected; - if (localType === "relay" || remoteType === "relay") - selected = { transport: "turn", mode: "TURN" }; - const relayUrl = localType === "relay" ? stringStat(local, "url") : void 0; - if (local === void 0 && remote === void 0) - continue; - const lan = isLanCandidatePair(localType, remoteType, localAddressScope, remoteAddressScope); - selected ??= { transport: lan ? "lan" : "p2p", mode: lan ? "LAN" : "P2P" }; - const currentRoundTripTime = numberStat(pair, "currentRoundTripTime"); - return { - ...selected, - ...relayUrl === void 0 ? {} : { relayUrl }, - localCandidateType: stringStat(local, "candidateType"), - remoteCandidateType: stringStat(remote, "candidateType"), - localAddressScope, - remoteAddressScope, - localAddress: candidateAddress(local), - remoteAddress: candidateAddress(remote), - protocol: stringStat(local, "protocol") ?? stringStat(remote, "protocol"), - relayProtocol: stringStat(local, "relayProtocol") ?? stringStat(remote, "relayProtocol"), - currentRoundTripTimeMs: currentRoundTripTime === void 0 ? void 0 : Math.round(currentRoundTripTime * 1e3), - availableOutgoingBitrate: numberStat(pair, "availableOutgoingBitrate"), - bytesSent: numberStat(pair, "bytesSent"), - bytesReceived: numberStat(pair, "bytesReceived") - }; - } - return {}; -} -function inspectCandidatePairs(stats) { - const candidates = /* @__PURE__ */ new Map(); - const telemetry = emptyCandidatePairTelemetry(); - const pairs = []; - for (const [reportId, entry] of stats) { - if (entry.type === "local-candidate" || entry.type === "remote-candidate") { - if (typeof entry.candidateType === "string" && entry.id !== void 0) { - candidates.set(String(entry.id), entry); - } - } else if (entry.type === "candidate-pair") { - pairs.push({ ...entry, id: entry.id ?? reportId }); - } - } - for (const pair of pairs) { - telemetry.total += 1; - if (pair.nominated === true) - telemetry.nominated += 1; - if (pair.selected === true) - telemetry.selected += 1; - increment(telemetry.byState, stringStat(pair, "state") ?? (pair.selected === true ? "selected" : "unknown")); - const local = candidates.get(String(pair.localCandidateId)); - const remote = candidates.get(String(pair.remoteCandidateId)); - recordCandidateStats(telemetry.byLocalType, telemetry.byLocalFamily, telemetry.byLocalScope, local); - recordCandidateStats(telemetry.byRemoteType, telemetry.byRemoteFamily, telemetry.byRemoteScope, remote); - } - return telemetry; -} -function candidateAddress(candidate) { - const address2 = stringStat(candidate, "address") ?? stringStat(candidate, "ip"); - if (address2 === void 0) - return void 0; - const port = numberStat(candidate, "port"); - return port === void 0 ? address2 : `${address2}:${port}`; -} -function stringStat(entry, key) { - const value = entry?.[key]; - return typeof value === "string" && value.length > 0 ? value : void 0; -} -function numberStat(entry, key) { - const value = entry?.[key]; - return typeof value === "number" && Number.isFinite(value) ? value : void 0; -} -function emptyCandidateTelemetry() { - return { - total: 0, - byType: {}, - byFamily: {}, - byScope: {}, - byProtocol: {} - }; -} -function cloneCandidateTelemetry(value) { - return { - total: value.total, - byType: { ...value.byType }, - byFamily: { ...value.byFamily }, - byScope: { ...value.byScope }, - byProtocol: { ...value.byProtocol } - }; -} -function emptyCandidatePairTelemetry() { - return { - total: 0, - nominated: 0, - selected: 0, - byState: {}, - byLocalType: {}, - byRemoteType: {}, - byLocalFamily: {}, - byRemoteFamily: {}, - byLocalScope: {}, - byRemoteScope: {} - }; -} -function cloneCandidatePairTelemetry(value) { - return { - total: value.total, - nominated: value.nominated, - selected: value.selected, - byState: { ...value.byState }, - byLocalType: { ...value.byLocalType }, - byRemoteType: { ...value.byRemoteType }, - byLocalFamily: { ...value.byLocalFamily }, - byRemoteFamily: { ...value.byRemoteFamily }, - byLocalScope: { ...value.byLocalScope }, - byRemoteScope: { ...value.byRemoteScope } - }; -} -function recordCandidate(telemetry, candidate) { - telemetry.total += 1; - increment(telemetry.byType, candidate.candidateType); - increment(telemetry.byFamily, candidate.addressFamily); - increment(telemetry.byScope, candidate.addressScope); - if (candidate.protocol !== void 0) - increment(telemetry.byProtocol, candidate.protocol); -} -function recordCandidateStats(byType, byFamily, byScope, candidate) { - const candidateType = candidateTypeStat(candidate); - const address2 = summarizeAddress(candidateAddressValue(candidate)); - increment(byType, candidateType); - increment(byFamily, address2.addressFamily); - increment(byScope, address2.addressScope); -} -function candidateTypeStat(candidate) { - const value = stringStat(candidate, "candidateType"); - if (value === "host" || value === "srflx" || value === "prflx" || value === "relay") - return value; - return "unknown"; -} -function candidateAddressValue(candidate) { - return stringStat(candidate, "address") ?? stringStat(candidate, "ip"); -} -function isLanCandidatePair(localType, remoteType, localScope, remoteScope) { - if (localType === "host" && remoteType === "host") { - return !isExplicitlyNonLanScope(localScope) && !isExplicitlyNonLanScope(remoteScope); - } - const directTypes = /* @__PURE__ */ new Set(["host", "prflx"]); - if (!directTypes.has(String(localType)) || !directTypes.has(String(remoteType))) - return false; - if (isLocalNetworkScope(localScope) && isLocalNetworkScope(remoteScope)) - return true; - return localType === "host" && isLocalNetworkScope(localScope) && remoteType === "prflx" && remoteScope === "unknown" || remoteType === "host" && isLocalNetworkScope(remoteScope) && localType === "prflx" && localScope === "unknown"; -} -function isLocalNetworkScope(scope2) { - return scope2 === "private" || scope2 === "link-local" || scope2 === "loopback"; -} -function isExplicitlyNonLanScope(scope2) { - return scope2 === "public" || scope2 === "cgnat" || scope2 === "reserved"; -} -function increment(map2, key) { - map2[key] = (map2[key] ?? 0) + 1; -} -function selectedPathTelemetry(details2) { - return { - ...details2.transport === void 0 ? {} : { transport: details2.transport }, - ...details2.mode === void 0 ? {} : { mode: details2.mode }, - ...details2.relayUrl === void 0 ? {} : { relayUrl: details2.relayUrl }, - ...details2.localCandidateType === void 0 ? {} : { localCandidateType: details2.localCandidateType }, - ...details2.remoteCandidateType === void 0 ? {} : { remoteCandidateType: details2.remoteCandidateType }, - ...details2.localAddressScope === void 0 ? {} : { localAddressScope: details2.localAddressScope }, - ...details2.remoteAddressScope === void 0 ? {} : { remoteAddressScope: details2.remoteAddressScope }, - ...details2.protocol === void 0 ? {} : { protocol: details2.protocol }, - ...details2.relayProtocol === void 0 ? {} : { relayProtocol: details2.relayProtocol }, - ...details2.currentRoundTripTimeMs === void 0 ? {} : { currentRoundTripTimeMs: details2.currentRoundTripTimeMs }, - ...details2.availableOutgoingBitrate === void 0 ? {} : { availableOutgoingBitrate: details2.availableOutgoingBitrate } - }; -} -function requireSdp(description) { - if (typeof description.sdp !== "string" || description.sdp.length === 0) { - throw new RtcConnectError("RTC_FAILED", "The RTC backend produced an empty session description."); - } - return description.sdp; -} -function toArrayBuffer(data2) { - if (data2.byteOffset === 0 && data2.byteLength === data2.buffer.byteLength) - return data2.buffer; - return data2.slice().buffer; -} -function asError(error62) { - return error62 instanceof Error ? error62 : new RtcConnectError("RTC_FAILED", "WebRTC negotiation failed."); -} -function sleep(ms) { - return new Promise((resolve10) => setTimeout(resolve10, ms)); -} - -// packages/webrtc/dist/control-lease.js -var WEBRTC_LEASE_MS2 = 3e5; -var ControlLease = class { - connectionId; - ticket; - request; - expired; - confirmed = false; - stopped = false; - sent; - deadline; - sequence = 0; - timer; - lastRequest = -Infinity; - constructor(connectionId, ticket, request, expired) { - this.connectionId = connectionId; - this.ticket = ticket; - this.request = request; - this.expired = expired; - } - start() { - this.timer = setInterval(() => this.tick(), 1e3); - this.deadline = { mono: performance.now() + WEBRTC_LEASE_MS2, wall: Date.now() + WEBRTC_LEASE_MS2 }; - this.tick(true); - } - valid() { - if (this.stopped) - return false; - const d = this.deadline; - if (d && (performance.now() >= d.mono || Date.now() >= d.wall)) { - this.stop(); - this.expired(); - return false; - } - return true; - } - remainingMs() { - if (!this.confirmed || this.stopped || !this.deadline) - return void 0; - return Math.max(0, Math.min(this.deadline.mono - performance.now(), this.deadline.wall - Date.now())); - } - canDetach() { - return this.confirmed && this.valid(); - } - recoveryTicket() { - return this.canDetach() ? this.ticket : void 0; - } - tick(force = false) { - if (!this.valid()) - return; - const mono = performance.now(); - if (!force && mono - this.lastRequest < 25e3) - return; - const sent = { id: String(++this.sequence), mono, wall: Date.now() }; - this.lastRequest = mono; - try { - this.request({ connectionId: this.connectionId, requestId: sent.id, ticket: this.ticket }); - this.sent = sent; - } catch { - } - } - acknowledge(ack) { - if (!this.valid() || ack.connectionId !== this.connectionId || ack.leaseMs !== WEBRTC_LEASE_MS2) - return; - const sent = this.sent; - if (!sent || sent.id !== ack.requestId) - return; - if (performance.now() - sent.mono >= 3e4 || Date.now() - sent.wall >= 3e4) - return; - this.sent = void 0; - this.ticket = ack.ticket; - this.confirmed = true; - this.deadline = { mono: sent.mono + WEBRTC_LEASE_MS2, wall: sent.wall + WEBRTC_LEASE_MS2 }; - } - stop() { - this.stopped = true; - clearInterval(this.timer); - this.timer = void 0; - this.sent = void 0; - } -}; - -// packages/webrtc/dist/adaptive-transport.js -var DEFAULT_CAPABILITIES = [WEBRTC_RESUME_CAPABILITY, RELAY_RESUME_CAPABILITY, "transport.lan", "transport.p2p", "transport.turn", "transport.relay", "transport.relay.attach", "harness.api.v1"]; -var DEFAULT_PREFERRED_TRANSPORTS = ["lan", "p2p", "turn", "relay"]; -var AdaptiveTransport = class extends BaseTransport { - url; - options; - handshakeHandlers = /* @__PURE__ */ new Set(); - socket; - dataSocket; - connectionId; - relayCounter = 0; - bytesSent = 0; - bytesReceived = 0; - dataMode = "relay"; - selected; - rtc; - readyResolve; - readyReject; - handshakeTimer; - lifetime; - removeAbort; - webrtcEnabled = true; - serverNegotiateTimeoutMs; - negotiatedCapabilities = ["transport.relay"]; - controlFrameLimits = {}; - connectedAt; - heartbeatIntervalMs; - lastControlReceivedAt; - lastControlSentAt; - lastRtcDiagnostics; - relayAssignment; - dataReady = false; - recoveryTicket; - relayRecoveryTicket; - lease; - recoveryTimer; - recoveryOpeningTimer; - recoveryAttempt = 0; - controlReady = false; - constructor(url2, options) { - super(); - this.url = url2; - this.options = options; - } - async connect() { - if (this.socket !== void 0 || this.connectedAt !== void 0) - return; - throwIfAborted(this.options.signal); - const lifetime = new AbortController(); - this.lifetime = lifetime; - this.webrtcEnabled = true; - this.serverNegotiateTimeoutMs = void 0; - this.dataMode = "relay"; - this.selected = void 0; - this.connectedAt = void 0; - this.relayCounter = 0; - this.socket = new WebSocket(this.url); - this.controlFrameLimits = {}; - this.socket.binaryType = "arraybuffer"; - await new Promise((resolve10, reject) => { - this.readyResolve = resolve10; - this.readyReject = reject; - const onAbort = () => this.failConnection(new Error("Adaptive connection was aborted")); - this.options.signal?.addEventListener("abort", onAbort, { once: true }); - this.removeAbort = () => this.options.signal?.removeEventListener("abort", onAbort); - this.handshakeTimer = setTimeout(() => this.failConnection(new Error("Adaptive control handshake timed out")), this.options.handshakeTimeoutMs ?? 15e3); - const socket = this.socket; - socket.onmessage = (event) => { - if (this.socket === socket) - void this.handleSocketMessage(event.data, lifetime); - }; - socket.onopen = () => { - if (this.lifetime !== lifetime) - return; - this.sendControl("hello", { - role: this.options.role, - deviceId: this.options.deviceId, - accessToken: this.options.accessToken, - protocols: [PROTOCOL_VERSION], - capabilities: this.options.capabilities ?? DEFAULT_CAPABILITIES - }); - }; - socket.onerror = () => { - if (this.lifetime === lifetime && this.socket === socket) - this.controlLost(new Error("Control socket failed"), { reason: "control-error" }); - }; - socket.onclose = (event) => { - if (this.lifetime === lifetime && this.socket === socket) - this.controlLost(adaptiveControlCloseError(event), { reason: "control-closed", closeCode: event.code, closeReason: event.reason }); - }; - }); - } - async send(data2) { - if (this.lease && !this.lease.valid()) - throw new Error("Control lease expired"); - if (this.connectionId === void 0) - throw new Error("adaptive transport has not been authorized"); - if (this.dataMode === "webrtc") { - const rtc = this.rtc; - if (rtc === void 0) - throw new Error("webrtc data channel is not available"); - this.bytesSent += data2.byteLength; - await rtc.send(data2); - return; - } - const socket = this.dataSocket ?? this.socket; - if (socket?.readyState !== WebSocket.OPEN) - throw new Error("adaptive transport is not connected"); - await waitForRelayCapacity(socket); - const payload = { - connectionId: this.connectionId, - targetDeviceId: this.options.targetDeviceId, - counter: this.relayCounter, - ciphertext: toBase64Url(data2) - }; - if (this.dataSocket !== void 0) { - this.dataSocket.send(encodeRelayDataFrame(createRelayDataFrame("relay", payload), this.controlFrameLimits)); - } else - this.sendControl("relay", payload); - this.bytesSent += data2.byteLength; - this.relayCounter += 1; - } - connectionInfo() { - if (this.connectionId === void 0) - throw new Error("adaptive transport has not been authorized"); - return { - connectionId: this.connectionId, - localDeviceId: this.options.deviceId, - remoteDeviceId: this.options.targetDeviceId - }; - } - async connectionDetails() { - const remainingMs = this.lease?.remainingMs(); - return { - ...this.connectionId === void 0 ? {} : { connectionId: this.connectionId }, - ...this.connectedAt === void 0 ? {} : { connectedAt: this.connectedAt }, - ...this.heartbeatIntervalMs === void 0 ? {} : { heartbeatIntervalMs: this.heartbeatIntervalMs }, - ...this.lastControlReceivedAt === void 0 ? {} : { lastControlReceivedAt: this.lastControlReceivedAt }, - ...this.lastControlSentAt === void 0 ? {} : { lastControlSentAt: this.lastControlSentAt }, - recoveryExpiresAt: remainingMs === void 0 ? void 0 : Date.now() + remainingMs, - controlChannelUrl: this.url, - controlChannelState: socketState(this.socket?.readyState), - preferredTransports: this.options.forceRelay === true ? ["relay"] : [...this.options.preferredTransports ?? DEFAULT_PREFERRED_TRANSPORTS], - negotiatedCapabilities: [...this.negotiatedCapabilities], - webRtcEnabled: this.webrtcEnabled, - ...this.rtc === void 0 ? {} : { webRtc: await this.rtc.connectionDetails() } - }; - } - async sendHandshake(step, data2) { - if (this.socket?.readyState !== WebSocket.OPEN || this.connectionId === void 0) { - throw new Error("adaptive transport has not been authorized"); - } - this.sendControl("secure.handshake", { - connectionId: this.connectionId, - targetDeviceId: this.options.targetDeviceId, - step, - data: toBase64Url(data2) - }); - } - onHandshake(cb) { - this.handshakeHandlers.add(cb); - return () => this.handshakeHandlers.delete(cb); - } - async close() { - this.failConnection(new Error("Adaptive transport closed")); - } - getStats() { - const webrtcConnected = this.dataMode === "webrtc" && this.rtc?.getStats().connected === true; - const relayConnected = this.dataMode === "relay" && (this.dataSocket?.readyState === WebSocket.OPEN && this.dataReady || this.socket?.readyState === WebSocket.OPEN) && this.connectionId !== void 0; - const connected = webrtcConnected || relayConnected; - let mode2 = "Disconnected"; - if (this.selected === "relay") - mode2 = relayConnected ? "Relay" : "Disconnected"; - else if (this.selected === "lan" || this.selected === "turn" || this.selected === "p2p") { - mode2 = webrtcConnected ? this.rtc.getStats().mode : "Disconnected"; - } - return { mode: mode2, connected, bytesSent: this.bytesSent, bytesReceived: this.bytesReceived }; - } - async handleSocketMessage(raw, lifetime) { - if (this.lifetime !== lifetime) - return; - try { - if (typeof raw !== "string") - throw new Error("Adaptive control frames must be text JSON"); - const frame = decodeControlFrame(raw, this.controlFrameLimits); - this.lastControlReceivedAt = Date.now(); - if (frame.type === "hello.ack") { - this.controlReady = true; - const payload = frame.payload; - if (payload.protocol !== PROTOCOL_VERSION) - throw new Error("Server selected an unsupported protocol version"); - this.heartbeatIntervalMs = payload.heartbeatIntervalMs; - const offered = this.options.capabilities ?? DEFAULT_CAPABILITIES; - this.negotiatedCapabilities = acceptNegotiatedCapabilities(offered, payload.capabilities); - this.controlFrameLimits = { - maxControlFrameBytes: payload.maxControlFrameBytes, - maxRelayFrameBytes: payload.maxRelayFrameBytes - }; - const preferredTransports = this.negotiatedTransports(); - if (preferredTransports.length === 0) { - throw new Error("Server did not negotiate a supported transport capability"); - } - if (payload.webrtcEnabled === false) - this.webrtcEnabled = false; - if (typeof payload.webrtcFallbackTimeoutMs === "number" && Number.isSafeInteger(payload.webrtcFallbackTimeoutMs) && payload.webrtcFallbackTimeoutMs > 0) { - this.serverNegotiateTimeoutMs = payload.webrtcFallbackTimeoutMs; - } - if (this.lease) { - if (!this.negotiatedCapabilities.includes(this.dataMode === "webrtc" ? WEBRTC_RESUME_CAPABILITY : RELAY_RESUME_CAPABILITY)) - throw new Error("Server no longer supports control recovery"); - clearTimeout(this.recoveryOpeningTimer); - this.recoveryAttempt = 0; - this.lease.tick(true); - return; - } - this.sendControl("connect.request", { - hostDeviceId: this.options.targetDeviceId, - preferredTransports - }); - return; - } - if (frame.type === "connect.accepted") { - if (this.connectionId !== void 0) - throw new Error("Duplicate connect.accepted"); - const payload = frame.payload; - if (typeof payload.connectionId !== "string" || payload.connectionId.length === 0) { - throw new Error("connect.accepted did not include a connectionId"); - } - this.connectionId = payload.connectionId; - if (this.negotiatedCapabilities.includes(WEBRTC_RESUME_CAPABILITY)) - this.recoveryTicket = payload.recoveryTicket; - if (this.negotiatedCapabilities.includes(RELAY_RESUME_CAPABILITY)) - this.relayRecoveryTicket = payload.relayRecoveryTicket; - const assignment = payload; - if (typeof assignment.relayEndpoint === "string" && typeof assignment.relayTicket === "string") { - this.relayAssignment = assignment; - } - this.clearHandshake(); - void this.negotiate(lifetime.signal).catch((error62) => { - if (this.lifetime === lifetime) - this.failConnection(error62 instanceof Error ? error62 : new Error("Adaptive transport negotiation failed")); - }); - return; - } - if (frame.type === "connection.lease.ack") { - if (!this.lease) - throw new Error("Unexpected connection lease"); - this.lease.acknowledge(frame.payload); - return; - } - if (frame.type === "connect.rejected" || frame.type === "error") { - const payload = frame.payload; - const message = typeof payload.message === "string" ? payload.message : "Server rejected the connection"; - const failure5 = Object.assign(new Error(message), { code: payload.code, retryable: payload.retryable }); - const code = errorCodeSchema.safeParse(payload.code); - this.failConnection(failure5, { - reason: payload.retryable === true ? "control-error" : "invalid-control-frame", - ...code.success ? { errorCode: code.data } : {} - }); - return; - } - if (frame.type === "relay") { - if (this.dataSocket !== void 0) - return; - if (this.dataMode !== "relay") - return; - this.handleRelay(frame.payload); - return; - } - if (frame.type === "secure.handshake") { - const payload = frame.payload; - if (payload.connectionId !== this.connectionId || payload.targetDeviceId !== this.options.deviceId || !Number.isSafeInteger(payload.step) || typeof payload.data !== "string") { - throw new Error("Received a secure handshake frame for an unknown connection"); - } - const data2 = fromBase64Url(payload.data); - for (const handler of this.handshakeHandlers) - handler(payload.step, data2); - return; - } - if (frame.type === "signal.answer") { - const payload = frame.payload; - if (payload.connectionId === this.connectionId && typeof payload.sdp === "string") { - this.rtc?.handleSignal({ type: "answer", sdp: payload.sdp }); - } - return; - } - if (frame.type === "signal.ice") { - const payload = frame.payload; - if (payload.connectionId === this.connectionId && isObject2(payload.candidate)) { - this.rtc?.handleSignal({ type: "ice", candidate: payload.candidate }); - } - return; - } - if (frame.type === "signal.offer" || frame.type === "transport.selected") - return; - if (frame.type === "ping") - this.sendControl("pong", frame.payload); - } catch (error62) { - const failure5 = error62 instanceof Error ? error62 : new Error("Invalid adaptive control frame"); - if (!("code" in failure5)) - Object.assign(failure5, { code: "INVALID_MESSAGE" }); - const code = errorCodeSchema.safeParse(failure5.code); - this.failConnection(failure5, { reason: "invalid-control-frame", ...code.success ? { errorCode: code.data } : {} }); - } - } - handleRelay(payload) { - if (payload.connectionId !== this.connectionId || payload.targetDeviceId !== this.options.deviceId || !Number.isSafeInteger(payload.counter) || typeof payload.ciphertext !== "string") { - throw new Error("Received a relay frame for an unknown connection"); - } - const data2 = fromBase64Url(payload.ciphertext); - this.bytesReceived += data2.byteLength; - this.emit(data2); - } - async negotiate(signal) { - if (this.connectionId === void 0) - return; - const preferred = this.negotiatedTransports(); - const wantWebRtc = !this.options.forceRelay && this.webrtcEnabled && (preferred.includes("lan") || preferred.includes("p2p") || preferred.includes("turn")); - let selected = "relay"; - this.lastRtcDiagnostics = void 0; - if (wantWebRtc) { - try { - const rtcSelected = (await this.tryWebRtc(signal)).transport; - throwIfAborted(signal); - const wireSelected = rtcSelected === "lan" && !preferred.includes("lan") && preferred.includes("p2p") ? "p2p" : rtcSelected; - if (!preferred.includes(wireSelected)) { - await this.rtc?.close(); - throwIfAborted(signal); - this.rtc = void 0; - if (!preferred.includes("relay")) { - throw new Error(`WebRTC selected unnegotiated transport: ${rtcSelected}`); - } - this.dataMode = "relay"; - selected = "relay"; - } else { - this.dataMode = "webrtc"; - selected = wireSelected; - } - } catch (error62) { - throwIfAborted(signal); - const reason = error62 instanceof Error ? error62 : new Error("WebRTC negotiation failed."); - try { - this.options.onWebRtcFallback?.(reason, this.lastRtcDiagnostics); - } catch { - } - await this.rtc?.close(); - throwIfAborted(signal); - this.rtc = void 0; - if (!preferred.includes("relay")) - throw reason; - this.dataMode = "relay"; - selected = "relay"; - } - } else { - if (!preferred.includes("relay")) - throw new Error("No negotiated transport is available"); - this.dataMode = "relay"; - selected = "relay"; - } - this.selected = selected; - if (selected === "relay" && this.relayAssignment !== void 0) { - await this.openDataSocket(this.relayAssignment); - } - const turnNode = selected === "turn" ? this.rtc?.selectedRelayUrl() : void 0; - this.sendControl("transport.selected", { - connectionId: this.connectionId, - targetDeviceId: this.options.targetDeviceId, - transport: selected, - ...turnNode === void 0 ? {} : { turnNode } - }); - this.finishConnection(); - } - negotiatedTransports() { - const preferred = this.options.forceRelay === true ? ["relay"] : this.options.preferredTransports ?? DEFAULT_PREFERRED_TRANSPORTS; - return preferred.filter((transport) => { - if (transport === "lan") - return this.negotiatedCapabilities.includes("transport.lan"); - if (transport === "p2p") - return this.negotiatedCapabilities.includes("transport.p2p"); - return this.negotiatedCapabilities.includes(`transport.${transport}`); - }); - } - async tryWebRtc(signal) { - const connectionId = this.connectionId; - if (connectionId === void 0) - throw new RtcConnectError("RTC_UNAVAILABLE", "No connection id for WebRTC negotiation."); - const factory = this.options.rtcFactory ?? (typeof RTCPeerConnection === "undefined" ? void 0 : browserRtcFactory()); - if (factory === void 0) { - throw new RtcConnectError("RTC_UNAVAILABLE", "No RTC backend is available in this environment."); - } - let iceServers = []; - try { - iceServers = await this.fetchIceServers(connectionId, signal); - } catch { - iceServers = []; - } - throwIfAborted(signal); - const negotiatedMs = negotiateTimeout(this.serverNegotiateTimeoutMs, this.options.negotiateTimeoutMs); - const effectiveNegotiateTimeoutMs = iceServers.length === 0 ? Math.min(negotiatedMs ?? DEFAULT_EMPTY_ICE_NEGOTIATE_TIMEOUT_MS, DEFAULT_EMPTY_ICE_NEGOTIATE_TIMEOUT_MS) : negotiatedMs; - const rtc = new RtcDataChannelTransport({ - role: "initiator", - factory, - iceServers, - // A TURN-only attempt must constrain ICE itself. Otherwise a faster - // direct pair wins, then gets rejected as an unnegotiated transport. - iceTransportPolicy: this.negotiatedTransports().includes("turn") && !this.negotiatedTransports().some((transport) => transport === "lan" || transport === "p2p") ? "relay" : "all", - onSignal: (signal2) => this.sendRtcSignal(signal2), - negotiateTimeoutMs: effectiveNegotiateTimeoutMs, - label: `client->${this.options.targetDeviceId}`, - onDiagnostic: (event) => { - this.lastRtcDiagnostics = event.diagnostics; - try { - this.options.onWebRtcDiagnostic?.(event); - } catch { - } - } - }); - this.rtc = rtc; - rtc.onMessage((data2) => { - if (this.lease && !this.lease.valid()) - return; - this.bytesReceived += data2.byteLength; - this.emit(data2); - }); - rtc.onClose(() => { - if (this.rtc === rtc && this.dataMode === "webrtc") { - const transport = this.selected; - this.failConnection(new Error("Active WebRTC channel closed"), { - reason: "webrtc-closed", - ...transport === "lan" || transport === "p2p" || transport === "turn" ? { transport } : {} - }); - } - }); - try { - await rtc.connect(signal); - } catch (error62) { - throwIfAborted(signal); - this.lastRtcDiagnostics = rtc.diagnostics(); - await rtc.close(); - if (this.rtc === rtc) - this.rtc = void 0; - throwIfAborted(signal); - throw error62; - } - throwIfAborted(signal); - this.lastRtcDiagnostics = rtc.diagnostics(); - return { transport: rtc.selectedTransport() ?? "p2p", relayUrl: rtc.selectedRelayUrl() }; - } - markSecureReady() { - const ticket = this.dataMode === "webrtc" ? this.recoveryTicket : this.dataReady && this.dataSocket?.readyState === WebSocket.OPEN ? this.relayRecoveryTicket : void 0; - if (!ticket || !this.connectionId || this.lease) - return; - this.lease = new ControlLease(this.connectionId, ticket, (payload) => { - if (this.controlReady && this.lastControlReceivedAt !== void 0 && Date.now() - this.lastControlReceivedAt >= 75e3) { - this.controlLost(new Error("Control heartbeat timed out"), { reason: "control-error" }); - throw new Error("Control heartbeat timed out"); - } - this.sendControl("connection.lease.request", payload); - }, () => this.failConnection(Object.assign(new Error("Control authorization lease expired"), { code: "TRANSPORT_CLOSED", retryable: true }))); - this.lease.start(); - } - controlLost(error62, diagnostic) { - if (error62.retryable === false || !this.lease?.canDetach() || !(this.dataMode === "webrtc" ? this.rtc?.getStats().connected : this.dataReady && this.dataSocket?.readyState === WebSocket.OPEN)) { - this.failConnection(error62, diagnostic); - return; - } - const socket = this.socket; - this.controlReady = false; - this.socket = void 0; - clearTimeout(this.recoveryOpeningTimer); - socket?.close(); - if (this.recoveryTimer !== void 0) - return; - const delay = recoveryDelayMs(this.recoveryAttempt, diagnostic); - this.recoveryAttempt++; - this.recoveryTimer = setTimeout(() => { - this.recoveryTimer = void 0; - void this.reopenControl(); - }, delay); - } - async reopenControl() { - const lifetime = this.lifetime; - if (!lifetime || !this.lease?.canDetach()) - return; - try { - const token = this.options.refreshAccessToken ? await this.options.refreshAccessToken() : this.options.accessToken; - if (this.lifetime !== lifetime || !this.lease?.canDetach()) - return; - const socket = new WebSocket(this.url); - this.socket = socket; - socket.binaryType = "arraybuffer"; - this.recoveryOpeningTimer = setTimeout(() => { - if (this.socket === socket) - this.controlLost(new Error("Control recovery handshake timed out"), { reason: "control-error" }); - }, 15e3); - socket.onopen = () => { - if (this.socket !== socket || this.lifetime !== lifetime) - return; - this.sendControl("hello", { - role: this.options.role, - deviceId: this.options.deviceId, - accessToken: token, - protocols: [PROTOCOL_VERSION], - capabilities: this.options.capabilities ?? DEFAULT_CAPABILITIES - }); - }; - socket.onmessage = (event) => { - if (this.socket === socket && this.lifetime === lifetime) - void this.handleSocketMessage(event.data, lifetime); - }; - socket.onerror = () => { - if (this.socket === socket) - this.controlLost(new Error("Control recovery failed"), { reason: "control-error" }); - }; - socket.onclose = (event) => { - if (this.socket === socket) - this.controlLost(adaptiveControlCloseError(event), { reason: "control-closed", closeCode: event.code, closeReason: event.reason }); - }; - } catch (error62) { - if (this.lifetime !== lifetime) - return; - if (typeof error62 === "object" && error62 && ("retryable" in error62 && error62.retryable === false || "code" in error62 && ["AUTH_INVALID", "DEVICE_REVOKED", "MEMBERSHIP_REQUIRED", "PEER_IDENTITY_MISMATCH", "DEVICE_NOT_FOUND", "TOKEN_REUSED"].includes(String(error62.code)))) { - this.failConnection(error62 instanceof Error ? error62 : new Error("Control recovery authorization failed")); - } else - this.controlLost(new Error("Control recovery unavailable"), { reason: "control-error" }); - } - } - async fetchIceServers(connectionId, signal) { - if (this.options.fetchIceServers === void 0) - return []; - return new Promise((resolve10, reject) => { - const request = new AbortController(); - let settled = false; - const finish = (error62, servers = []) => { - if (settled) - return; - settled = true; - clearTimeout(timer2); - signal.removeEventListener("abort", onAbort); - if (error62) - reject(error62); - else - resolve10(servers); - }; - const onAbort = () => { - finish(new Error("ICE configuration request was aborted")); - request.abort(); - }; - const timer2 = setTimeout(() => { - finish(new Error("ICE configuration request timed out")); - request.abort(); - }, this.options.iceServersTimeoutMs ?? 1e4); - signal.addEventListener("abort", onAbort, { once: true }); - if (signal.aborted) { - onAbort(); - return; - } - Promise.resolve().then(() => { - throwIfAborted(request.signal); - return this.options.fetchIceServers(connectionId, request.signal); - }).then((servers) => finish(void 0, servers), (error62) => finish(error62 instanceof Error ? error62 : new Error("ICE configuration request failed"))); - }); - } - sendRtcSignal(signal) { - if (this.connectionId === void 0) - return; - if (signal.type === "offer") { - this.sendControl("signal.offer", { - connectionId: this.connectionId, - targetDeviceId: this.options.targetDeviceId, - sdp: signal.sdp - }); - } else if (signal.type === "answer") { - this.sendControl("signal.answer", { - connectionId: this.connectionId, - targetDeviceId: this.options.targetDeviceId, - sdp: signal.sdp - }); - } else { - this.sendControl("signal.ice", { - connectionId: this.connectionId, - targetDeviceId: this.options.targetDeviceId, - candidate: signal.candidate - }); - } - } - async openDataSocket(assignment) { - if (this.connectionId === void 0 || this.dataSocket !== void 0) - return; - const socket = new WebSocket(assignment.relayEndpoint); - socket.binaryType = "arraybuffer"; - this.dataSocket = socket; - await new Promise((resolve10, reject) => { - const timer2 = setTimeout(() => { - reject(new Error("Relay data attach timed out")); - socket.close(); - }, this.options.handshakeTimeoutMs ?? 15e3); - socket.onopen = () => socket.send(encodeRelayDataFrame(createRelayDataFrame("relay.attach", { - connectionId: this.connectionId, - deviceId: this.options.deviceId, - peerDeviceId: this.options.targetDeviceId, - ticket: assignment.relayTicket - }), this.controlFrameLimits)); - socket.onmessage = (event) => { - try { - if (typeof event.data !== "string") - throw new Error("Relay data frames must be text JSON"); - const data2 = decodeRelayDataFrame(event.data, this.controlFrameLimits); - if (data2.type === "relay.ready") { - if (data2.payload.connectionId !== this.connectionId || assignment.relayEpoch !== void 0 && data2.payload.epoch !== assignment.relayEpoch) { - throw new Error("Relay data attach assignment mismatch"); - } - clearTimeout(timer2); - this.dataReady = true; - resolve10(); - return; - } - void this.handleDataSocketFrame(data2.type, data2.payload).catch((error62) => { - this.failConnection(error62 instanceof Error ? error62 : new Error("Invalid Relay data frame")); - }); - } catch (error62) { - clearTimeout(timer2); - reject(error62 instanceof Error ? error62 : new Error("Invalid Relay data frame")); - this.failConnection(error62 instanceof Error ? error62 : new Error("Invalid Relay data frame")); - } - }; - socket.onerror = () => { - clearTimeout(timer2); - reject(new Error("Relay data socket failed")); - }; - socket.onclose = () => { - clearTimeout(timer2); - if (!this.dataReady) - reject(new Error("Relay data socket closed before attach")); - else - this.failConnection(new Error("Relay data socket closed")); - }; - }); - } - async handleDataSocketFrame(type, payload) { - if (type === "relay.detach") { - this.failConnection(new Error("Relay peer detached")); - return; - } - if (type === "ping") { - if (this.dataSocket?.readyState === WebSocket.OPEN) { - this.dataSocket.send(encodeRelayDataFrame(createRelayDataFrame("pong", payload), this.controlFrameLimits)); - } - return; - } - if (type === "relay") { - if (payload.connectionId !== this.connectionId || payload.targetDeviceId !== this.options.deviceId || !Number.isSafeInteger(payload.counter) || typeof payload.ciphertext !== "string") { - throw new Error("Received a relay frame for an unknown connection"); - } - const data2 = fromBase64Url(payload.ciphertext); - this.bytesReceived += data2.byteLength; - this.emit(data2); - return; - } - if (type === "secure.handshake") { - if (payload.connectionId !== this.connectionId || payload.targetDeviceId !== this.options.deviceId || !Number.isSafeInteger(payload.step) || typeof payload.data !== "string") { - throw new Error("Received a secure handshake frame for an unknown connection"); - } - const data2 = fromBase64Url(payload.data); - for (const handler of this.handshakeHandlers) - handler(payload.step, data2); - } - } - sendControl(type, payload) { - if (this.socket?.readyState !== WebSocket.OPEN) - throw Object.assign(new Error("adaptive control socket is not open"), { code: "TRANSPORT_CLOSED" }); - this.socket.send(encodeControlFrame(createControlFrame(type, payload), this.controlFrameLimits)); - this.lastControlSentAt = Date.now(); - } - finishConnection() { - this.clearHandshake(); - this.removeAbort?.(); - this.removeAbort = void 0; - this.connectedAt ??= Date.now(); - this.readyResolve?.(); - this.readyResolve = void 0; - this.readyReject = void 0; - } - failConnection(error62, diagnostic) { - if (this.lease && this.connectionId && this.socket?.readyState === WebSocket.OPEN) { - try { - this.sendControl("connection.lease.close", { connectionId: this.connectionId }); - } catch { - } - } - const established = this.connectedAt !== void 0; - this.controlReady = false; - this.recoveryAttempt = 0; - this.lease?.stop(); - this.lease = void 0; - this.recoveryTicket = void 0; - this.relayRecoveryTicket = void 0; - clearTimeout(this.recoveryTimer); - clearTimeout(this.recoveryOpeningTimer); - this.recoveryTimer = void 0; - this.clearHandshake(); - const reject = this.readyReject; - this.readyResolve = void 0; - this.readyReject = void 0; - this.removeAbort?.(); - this.removeAbort = void 0; - const lifetime = this.lifetime; - this.lifetime = void 0; - const rtc = this.rtc; - const socket = this.socket; - const dataSocket = this.dataSocket; - this.rtc = void 0; - this.socket = void 0; - this.dataSocket = void 0; - this.dataReady = false; - this.relayAssignment = void 0; - this.connectionId = void 0; - this.connectedAt = void 0; - lifetime?.abort(); - reject?.(error62); - void rtc?.close(); - dataSocket?.close(); - socket?.close(); - if (established && diagnostic !== void 0) { - try { - this.options.onDisconnect?.(diagnostic); - } catch { - } - } - if (socket !== void 0 || established) - this.emitClose(error62); - } - clearHandshake() { - if (this.handshakeTimer !== void 0) - clearTimeout(this.handshakeTimer); - this.handshakeTimer = void 0; - } -}; -function adaptiveControlCloseError(event) { - const serverShutdown = isServerShutdownClose(event.code, event.reason); - const heartbeatTimeout = isHeartbeatTimeoutClose(event.code, event.reason); - const reason = event.reason.trim().slice(0, 300); - const detail = reason.length > 0 ? `${reason} (WebSocket ${event.code})` : `WebSocket closed with code ${event.code}`; - return Object.assign(new Error(`Adaptive control channel closed: ${detail}`), { - // Preserve the specific self-hosted authorization reasons so the Client - // runtime can surface a terminal reauthorization state instead of a generic - // transport loss (PR #285). Every other close keeps the shared semantics. - code: event.code === 4003 ? "CONNECTION_REPLACED" : event.code === 4001 && ["AUTH_INVALID", "TOKEN_EXPIRED", "DEVICE_REVOKED"].includes(reason) ? reason : "TRANSPORT_CLOSED", - retryable: serverShutdown || heartbeatTimeout || [1e3, 1001, 1006, 1011, 1012, 1013].includes(event.code) - }); -} -var CONTROL_RECOVERY_MAX_DELAY_MS = 15e3; -function recoveryDelayMs(_attempt, _diagnostic) { - return Math.random() * CONTROL_RECOVERY_MAX_DELAY_MS; -} -function isObject2(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function socketState(readyState) { - if (readyState === 0) - return "connecting"; - if (readyState === 1) - return "open"; - if (readyState === 2) - return "closing"; - return "closed"; -} -function negotiateTimeout(serverMs, localMs) { - if (localMs !== void 0) - return localMs; - if (serverMs === void 0) - return void 0; - return Math.min(SERVER_NEGOTIATE_TIMEOUT_MAX_MS, Math.max(SERVER_NEGOTIATE_TIMEOUT_MIN_MS, serverMs)); -} -var DEFAULT_EMPTY_ICE_NEGOTIATE_TIMEOUT_MS = 4e3; -var SERVER_NEGOTIATE_TIMEOUT_MIN_MS = 6e3; -var SERVER_NEGOTIATE_TIMEOUT_MAX_MS = 12e3; -function throwIfAborted(signal) { - if (signal?.aborted) - throw new Error("Adaptive connection was aborted"); -} - -// packages/webrtc/dist/serial-send.js -var SerialSend = class { - tail = Promise.resolve(); - bytes = 0; - count = 0; - async run(bytes, send) { - if (this.bytes + bytes > 8 * 1024 * 1024 || this.count >= 256) - throw new Error("Encrypted send queue exceeds its limit"); - this.bytes += bytes; - this.count += 1; - const task = this.tail.then(send); - this.tail = task.catch(() => void 0); - try { - await task; - } finally { - this.bytes -= bytes; - this.count -= 1; - } - } -}; - // packages/plugin/src/client-runtime-contract.ts var DIRECT_WEBRTC_NEGOTIATE_TIMEOUT_MS = 12e3; var DIRECT_LAN_PROGRESS_DISPLAY_MS = 1400; @@ -72683,7 +73001,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) { }); const { prehash } = eddsaOpts; const { BASE, Fp: Fp2, Fn: Fn2 } = Point; - const randomBytes14 = eddsaOpts.randomBytes || randomBytes2; + const randomBytes15 = eddsaOpts.randomBytes || randomBytes2; const adjustScalarBytes3 = eddsaOpts.adjustScalarBytes || ((bytes) => bytes); const domain2 = eddsaOpts.domain || ((data2, ctx, phflag) => { _abool2(phflag, "phflag"); @@ -72765,7 +73083,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) { signature: 2 * _size2, seed: _size2 }; - function randomSecretKey(seed = randomBytes14(lengths.seed)) { + function randomSecretKey(seed = randomBytes15(lengths.seed)) { return _abytes2(seed, lengths.seed, "seed"); } function keygen(seed) { @@ -75089,18 +75407,18 @@ function validateTableBytes(numPoints, fpBytes) { if (bytes > TABLE_BYTES_MAX) throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB"); } -function probeRandomBytes(randomBytes14, length) { - if (randomBytes14 === void 0) +function probeRandomBytes(randomBytes15, length) { + if (randomBytes15 === void 0) return void 0; - afunction(randomBytes14, "randomBytes"); + afunction(randomBytes15, "randomBytes"); try { - const probe = randomBytes14(length); + const probe = randomBytes15(length); if (!isBytes3(probe) || probe.length !== length) return void 0; } catch { return void 0; } - return randomBytes14; + return randomBytes15; } function validateMSMPoints2(points, c) { aarray(points, "points"); @@ -75193,9 +75511,9 @@ var ScalarMultiplier = class { baseCanBeBlinded; bits; // Parametrized with a given Point class (not individual point) - constructor(Point, randomBytes14) { + constructor(Point, randomBytes15) { validatePointCons(Point); - this.randomBytes = probeRandomBytes(randomBytes14, BLIND_BYTES); + this.randomBytes = probeRandomBytes(randomBytes15, BLIND_BYTES); this.Point = Point; this.BASE = Point.BASE; this.ZERO = Point.ZERO; @@ -75466,7 +75784,7 @@ function edwards2(params, extraOpts = {}) { if (FpLegendre2(Fp2, CURVE.d) !== -1) throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas"); validateObject2(opts, {}, { uvRatio: "function", randomBytes: "function" }); - const randomBytes14 = opts.randomBytes === void 0 ? randomBytes4 : opts.randomBytes; + const randomBytes15 = opts.randomBytes === void 0 ? randomBytes4 : opts.randomBytes; const MASK = _2n6 << BigInt(Fp2.BYTES * 8) - _1n10; function isOdd(n) { if (!Fp2.isOdd) @@ -75727,7 +76045,7 @@ function edwards2(params, extraOpts = {}) { } } const normalize = (points) => normalizeZ2(Point, points); - const wnaf = new ScalarMultiplier(Point, randomBytes14); + const wnaf = new ScalarMultiplier(Point, randomBytes15); if (wnaf.bits >= 6) Point.BASE.precompute(6); Object.freeze(Point.prototype); @@ -77975,7 +78293,18 @@ var NoiseIkSession = class { initiator, s: { secretKey: localPrivate, publicKey: localPublic }, ...initiator ? { rs: Uint8Array.from(this.expectedRemoteStatic) } : {}, - cipher: chachaPoly, + cipher: options.encryptChaChaPoly ? { + ...chachaPoly, + encrypt(key, nonce, ad, plaintext, out) { + const encrypted = options.encryptChaChaPoly(key, nonce, ad, plaintext); + if (encrypted === void 0) + return chachaPoly.encrypt(key, nonce, ad, plaintext, out); + if (encrypted.byteLength !== plaintext.byteLength + chachaPoly.tagLen) { + throw new NoiseSessionError("INVALID_ENCRYPTION_OUTPUT", "ChaChaPoly accelerator returned an invalid length."); + } + out.set(encrypted); + } + } : chachaPoly, hash: sha256H, rng: options.random ?? randomBytes }); @@ -78497,14 +78826,14 @@ var ClientReconnect = class { } async run(connect4, pending) { while (!pending.signal.aborted) { - const delay = Math.random() * this.config.maxDelayMs; + const delay2 = Math.random() * this.config.maxDelayMs; await new Promise((resolve10) => { const finish = () => { clearTimeout(timer2); pending.signal.removeEventListener("abort", finish); resolve10(); }; - const timer2 = setTimeout(finish, delay); + const timer2 = setTimeout(finish, delay2); pending.signal.addEventListener("abort", finish, { once: true }); }); if (pending.signal.aborted) return; @@ -78549,6 +78878,7 @@ var import_sender = __toESM(require_sender(), 1); var import_subprotocol = __toESM(require_subprotocol(), 1); var import_websocket = __toESM(require_websocket(), 1); var import_websocket_server = __toESM(require_websocket_server(), 1); +var wrapper_default = import_websocket.default; // packages/plugin/src/loopback-host.ts import { request as httpRequest } from "node:http"; @@ -79130,74 +79460,173 @@ var LoopbackPreview = class { }; // packages/plugin/src/plugin-route-bridge.ts -var PLUGIN_ROUTE_ALLOWLIST = ["api/bot"]; +var PLUGIN_ROUTE_ALLOWLIST = ["api/bot", "api/session/uploadFileBinary"]; var BOT_REMOTE_OPERATIONS = [ - "state", - "models", - "efforts", - "providers", - "local-agents", - "exchange", - "exchange-text", - "file-text", - "earlier", - "chat", - "run-stats", - "thinking", - "usage", - "room-progress", - "group-rows", - "schedules", - "schedule-create", - "schedule-delete", - "memory-view", - "memory-history", - "memory-ask", - "memory-forget", - "memory-restore", - "folders", - "folder-list", - "team-workspace", - "set-prefs", - "browser-takeover", - "browser-give-back", - "browser-stop", - "create-bot", - "duplicate-bot", - "update-bot", - "delete-bot", - "set-main", - "set-flags", - "resume", - "bot-new-part", - "bot-open-part", - "create-room", - "update-room", - "delete-room", - "stop-room-work", - "goal-draft", - "goal-control", + "abandon-work", "add-agent", - "agent-session", "agent-adopt", "agent-archive", "agent-rename", - "remove-agent", - "send", - "btw", - "btw-cancel", + "agent-session", + "answer-question", + "approval-answer", + "avatar", + "avatar-delete", + "avatar-import", + "avatar-library", + "bot-capability", + "bot-new-part", + "bot-open-part", + "browser-frame", + "browser-give-back", + "browser-result", + "browser-stop", + "browser-takeover", + "browser-wait", "btw-delete", - "side-new", + "capability-approve", + "capability-delete", + "capability-save", + "chat", + "computer-allow-foreground", + "computer-app-answer", + "computer-cursor-wait", + "computer-handback", + "computer-hold-answer", + "computer-open-settings", + "computer-permission", + "computer-provider-retry", + "computer-revoke-app", + "computer-set-enabled", + "computer-set-level", + "computer-shot", + "computer-stop", + "computer-system-status", + "computer-takeover", + "computer-user-active", + "connector-add", + "connector-cancel", + "connector-client", + "connector-connect", + "connector-disconnect", + "connector-import", + "connector-import-scan", + "connector-remove", + "connector-request-cancel", + "connector-retry", + "connector-set", + "connector-sign-in-code", + "create-bot", + "create-room", + "delete-bot", + "delete-room", + "diagnostics", + "diagnostics-clear", + "diagnostics-log", + "dismiss-question", + "dismiss-view", + "dsh-update-install", + "duplicate-bot", + "earlier", + "efforts", + "exchange", + "exchange-text", + "file-text", + "folder-list", + "folder-pick", + "folders", + "goal-control", + "goal-draft", + "group-rows", + "hello", + "im-add", + "im-chat", + "im-login-start", + "im-login-wait", + "im-pair", + "im-remove", + "im-retry", + "im-unpair", + "im-update", + "image", + "learning-answer", + "local-agent-add", + "local-agent-models", + "local-agent-refresh", + "local-agent-remove", + "local-agent-update", + "local-agents", + "mail-account-add", + "mail-account-remove", + "mail-rule-set", + "mail-send-answer", + "mail-sign-in-code", + "memory-add", + "memory-ask", + "memory-edit", + "memory-forget", + "memory-history", + "memory-layer", + "memory-move", + "memory-pin", + "memory-restore", + "memory-tidy-undo", + "memory-view", + "models", + "notices", + "phone-pair", + "phone-pair-cancel", + "phone-remove", + "phone-set", + "private-release", + "provider-add", + "provider-key", + "provider-models", + "provider-remove", + "providers", + "remove-agent", + "repo-stars", + "resume", + "room-chat", + "room-progress", + "run-stats", + "schedule-create", + "schedule-delete", + "schedules", + "secret-allow", + "secret-cancel", + "secret-delete", + "secret-set", + "secret-update", + "section-delete", + "section-order", + "section-save", + "send", + "set-flags", + "set-main", + "set-prefs", "side-ask", "side-cancel", "side-close", - "room-continue", - "answer-question", - "dismiss-question", - "dismiss-view", + "side-new", + "stage-image", + "state", + "stop-chat", + "stop-member-work", + "stop-room-work", + "team-workspace", + "thinking", + "update-bot", + "update-check", + "update-install", + "update-room", + "usage", + "usage-summary", "view-reply", - "approval-answer", - "stop-member-work" + // Older DS-Bot Hosts still implement these operations. + "btw", + "btw-cancel", + "room-continue" ]; function isAllowedPluginRoute(route) { return PLUGIN_ROUTE_ALLOWLIST.some((allowed) => allowed === route); @@ -79207,11 +79636,22 @@ var callSchema = external_exports.object({ body: external_exports.object({ endpoint: external_exports.enum(BOT_REMOTE_OPERATIONS), payload: external_exports.record(external_exports.string(), external_exports.unknown()).nullable().optional() - }).strict().superRefine((body, ctx) => { - if (body.endpoint === "approval-answer" && body.payload?.choice !== "allow" && body.payload?.choice !== "reject") { - ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Only one-time approval or rejection is supported." }); - } - }) + }).strict() +}).strict(); +var uploadFields = { + sessionId: external_exports.string().min(1).max(512), + name: external_exports.string().max(512).optional(), + data: external_exports.string().max(256 * 1024 * 1024).regex(/^[A-Za-z0-9+/]*={0,2}$/).refine((value) => value.length % 4 === 0) +}; +var imageUploadCallSchema = external_exports.object({ + route: external_exports.literal("api/session/uploadFileBinary"), + body: external_exports.discriminatedUnion("endpoint", [ + external_exports.object({ endpoint: external_exports.literal("image"), payload: external_exports.object({ + ...uploadFields, + mediaType: external_exports.enum(["image/png", "image/jpeg", "image/webp", "image/gif"]) + }).strict() }).strict(), + external_exports.object({ endpoint: external_exports.literal("file"), payload: external_exports.object(uploadFields).strict() }).strict() + ]) }).strict(); var PLUGIN_ROUTE_TIMEOUT_MS = 3e4; var PluginRouteBridge = class { @@ -79219,17 +79659,17 @@ var PluginRouteBridge = class { this.dispatch = dispatch; this.logger = logger2; } - async call(input4) { + async call(input4, transferred = false) { let params; try { - params = callSchema.parse(input4); + params = typeof input4 === "object" && input4 !== null && "route" in input4 && input4.route === "api/session/uploadFileBinary" ? imageUploadCallSchema.parse(input4) : callSchema.parse(input4); } catch (error62) { if (error62 instanceof external_exports.ZodError) { throw new RpcError("INVALID_MESSAGE", "The plugin route call is invalid for the remote channel."); } throw error62; } - if (serializedBytes(params) > MAX_SECURE_MESSAGE_BYTES) { + if (serializedBytes(params) > (transferred && params.route === "api/session/uploadFileBinary" ? MAX_HARNESS_API_TRANSFER_BYTES : MAX_SECURE_MESSAGE_BYTES)) { throw new RpcError("INVALID_MESSAGE", `The plugin route call exceeds the ${MAX_SECURE_MESSAGE_BYTES}-byte remote limit.`); } const startedAt = performance.now(); @@ -79505,6 +79945,9 @@ var ClientControl = class { if (typeof value.route !== "string" || !isAllowedPluginRoute(value.route)) { throw new ClientModeError("INVALID_MESSAGE", "A valid plugin route is required."); } + if (value.route === "api/session/uploadFileBinary" && (typeof value.targetDeviceId !== "string" || this.context.activeRemote()?.target.deviceId !== value.targetDeviceId)) { + throw new ClientModeError("REMOTE_NOT_CONNECTED", "The selected upload Host changed. Select the file again."); + } if (!isRecord5(value.body)) throw new ClientModeError("INVALID_MESSAGE", "A plugin route body object is required."); return ok(await this.context.pluginRoute(value.route, value.body, signal)); } @@ -82443,7 +82886,7 @@ function writeText(res, status2, body) { } // packages/plugin/src/harness-version.ts -import { readFile, realpath as realpathEntrypoint } from "node:fs/promises"; +import { readFile as readFile2, realpath as realpathEntrypoint } from "node:fs/promises"; import { createRequire } from "node:module"; import { dirname, isAbsolute, join, resolve } from "node:path"; var HARNESS_PACKAGE_NAME = "@deepseek-ai/dsh"; @@ -82462,9 +82905,17 @@ function harnessSessionGeneration(version2) { const patch = Number(match[3]); return major === 0 && (minor === 1 && patch >= 5 || minor === 2) ? "v3" : "legacy"; } +function isLiveSessionEventsHarnessVersion(version2) { + if (version2 === void 0) return false; + const match = /^(?:dsh-)?v?(\d+)\.(\d+)\.(\d+)(?:-|$)/u.exec(version2.trim()); + if (match === null) return false; + const major = Number(match[1]); + const minor = Number(match[2]); + return major > 0 || major === 0 && minor >= 2; +} async function readHarnessManifestVersion(manifestPath) { try { - const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + const manifest = JSON.parse(await readFile2(manifestPath, "utf8")); if (manifest.name !== HARNESS_PACKAGE_NAME) return void 0; return normalizeHarnessVersion(manifest.version); } catch { @@ -83924,7 +84375,7 @@ var ObservedState = class { import { platform } from "node:os"; // packages/plugin/src/server-credentials.ts -import { chmod, link, mkdir as mkdir2, readFile as readFile2, readdir, rename, rm as rm2, stat, writeFile } from "node:fs/promises"; +import { chmod, link, mkdir as mkdir2, readFile as readFile3, readdir, rename, rm as rm2, stat, writeFile } from "node:fs/promises"; import { basename as basename3, dirname as dirname2, join as join3, sep } from "node:path"; var credentialSchema = external_exports.object({ schemaVersion: external_exports.literal(1), @@ -83965,7 +84416,7 @@ var ServerCredentialStore = class { await assertPrivateMode(this.path); let parsed; try { - parsed = credentialSchema.parse(JSON.parse(await readFile2(this.path, "utf8"))); + parsed = credentialSchema.parse(JSON.parse(await readFile3(this.path, "utf8"))); } catch (error62) { throw new ServerCredentialsInvalidError(`server credentials are invalid: ${safeMessage(error62)}`); } @@ -84113,7 +84564,7 @@ async function isLockContention(error62, path) { } async function readLockRecord(path) { try { - return await readFile2(path, "utf8"); + return await readFile3(path, "utf8"); } catch (error62) { if (error62 instanceof Error && "code" in error62 && error62.code === "ENOENT") return void 0; throw error62; @@ -84164,7 +84615,7 @@ function safeMessage(error62) { async function readPrivateJson(path) { if (!await exists(path)) return void 0; await assertPrivateMode(path); - return JSON.parse(await readFile2(path, "utf8")); + return JSON.parse(await readFile3(path, "utf8")); } // packages/plugin/src/config.ts @@ -85295,7 +85746,7 @@ function parseIpv6(value) { } // packages/plugin/src/version.ts -var PLUGIN_VERSION = "0.6.4-fast.5"; +var PLUGIN_VERSION = "0.6.5-fast.1"; // packages/plugin/src/server-api.ts var TERMINAL_CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/u; @@ -86202,7 +86653,7 @@ var TypertGatewaySwitch = class { return { ok: false, error: this.failure(error62) }; } }) : (endpoint, payload, signal) => this.localDispatch(endpoint, payload, signal, peer); - const open6 = this.localOpen === void 0 ? (async (endpoint, payload, signal) => { + const open7 = this.localOpen === void 0 ? (async (endpoint, payload, signal) => { if (this.localStream === void 0) throw new Error("The local Harness Gateway does not support Remote streams."); return this.localStream({ ...requestFromCarrier(endpoint, payload, signal), ...peer === void 0 ? {} : { peer } }); }) : (endpoint, payload, signal, uplink) => this.localOpen(endpoint, payload, signal, uplink, peer); @@ -86211,7 +86662,7 @@ var TypertGatewaySwitch = class { peer, ...this.localStream === void 0 ? {} : { stream: (request) => this.localStream({ ...request, ...peer === void 0 ? {} : { peer } }) }, dispatch, - open: open6, + open: open7, failure: (error62) => this.failure(error62), supportsCarrier: this.localDispatch !== void 0 && this.localOpen !== void 0 }; @@ -86238,12 +86689,12 @@ var TypertGatewaySwitch = class { }; } if (this.originalOpen !== void 0) { - const open6 = this.originalOpen; - const rc1 = usesRc1Arity(open6); + const open7 = this.originalOpen; + const rc1 = usesRc1Arity(open7); this.runtime.openWireStream = (...callArgs) => { const endpoint = callArgs[0]; if (this.remoteTarget === void 0 || isLocalOnlyEndpoint(endpoint)) { - return rc1 ? Reflect.apply(open6, this.runtime, callArgs) : open6.call(this.runtime, endpoint, callArgs[1], callArgs[2]); + return rc1 ? Reflect.apply(open7, this.runtime, callArgs) : open7.call(this.runtime, endpoint, callArgs[1], callArgs[2]); } const signal = rc1 ? callArgs[4] : callArgs[2]; return this.openRemote(endpoint, callArgs[1], signal ?? new AbortController().signal, rc1 ? callArgs[2] : void 0); @@ -86327,8 +86778,8 @@ function workspaceConnectionResult(endpoint, result) { ] }; } -function usesRc1Arity(open6) { - return open6.length >= 5; +function usesRc1Arity(open7) { + return open7.length >= 5; } function endedUplink() { return { @@ -86347,9 +86798,9 @@ function linkControl(signal) { return control; } function createLocalOpen(gateway, runtime) { - const open6 = runtime.openWireStream; - if (open6 !== void 0) { - return usesRc1Arity(open6) ? (endpoint, payload, signal, uplink, peer) => peer === void 0 ? Promise.reject(missingPeerError(endpoint)) : open6.call(runtime, endpoint, payload, uplink ?? endedUplink(), peer, signal, linkControl(signal)) : (endpoint, payload, signal) => open6.call(runtime, endpoint, payload, signal); + const open7 = runtime.openWireStream; + if (open7 !== void 0) { + return usesRc1Arity(open7) ? (endpoint, payload, signal, uplink, peer) => peer === void 0 ? Promise.reject(missingPeerError(endpoint)) : open7.call(runtime, endpoint, payload, uplink ?? endedUplink(), peer, signal, linkControl(signal)) : (endpoint, payload, signal) => open7.call(runtime, endpoint, payload, signal); } const wire = gateway.wireStream; if (wire === void 0) return void 0; @@ -86502,10 +86953,10 @@ function isUsableExternalNode(candidate, requireFrom) { } function isExecutableFile(candidate) { try { - const stat10 = statSync(candidate); - if (!stat10.isFile()) return false; + const stat11 = statSync(candidate); + if (!stat11.isFile()) return false; if (process.platform === "win32") return true; - return (stat10.mode & 73) !== 0; + return (stat11.mode & 73) !== 0; } catch { return false; } @@ -87899,7 +88350,7 @@ var ClientModeRuntime = class { async discoverToolWorkspaces(targetDeviceId, signal) { return this.withToolRemote(targetDeviceId, signal, async (remote, activeSignal) => { const workspaces = []; - const unavailable3 = []; + const unavailable4 = []; const read = async (backend, query) => { activeSignal.throwIfAborted(); try { @@ -87908,7 +88359,7 @@ var ClientModeRuntime = class { } } catch { activeSignal.throwIfAborted(); - unavailable3.push({ backend, code: "BACKEND_UNAVAILABLE" }); + unavailable4.push({ backend, code: "BACKEND_UNAVAILABLE" }); } }; if (remote.features.remoteGateway) { @@ -87930,7 +88381,7 @@ var ClientModeRuntime = class { }); }); } - return { workspaces, unavailable: unavailable3 }; + return { workspaces, unavailable: unavailable4 }; }); } async withToolRemote(targetDeviceId, signal, query) { @@ -88230,6 +88681,11 @@ var ClientModeRuntime = class { if (!remote.features.pluginRoute) { throw new ClientModeError("FEATURE_NOT_SUPPORTED", "The connected Host cannot forward plugin routes."); } + if (route === "api/session/uploadFileBinary") { + const result = await this.remoteTypertGateway(remote).dispatch("remoteUploads/upload", { args: body }, signal); + if (!result.ok) throw new ClientModeError(result.error.code, result.error.message); + return result.value; + } return remote.client.rpc("plugin.route.call", { route, body }, signal); } activeRemote() { @@ -88239,7 +88695,21 @@ var ClientModeRuntime = class { this.assertRemoteCompatible(remote); this.clientAuthRequired = false; const target3 = { deviceId: remote.target.deviceId, name: remote.target.name }; - this.gatewaySwitch.selectRemote(this.remoteTypertGateway(remote), void 0, target3); + const gateway = this.remoteTypertGateway(remote); + const selected = { + invoke: async (request) => { + if (`${request.namespace}/${request.method}` !== "session/prompt") return gateway.invoke(request); + const payload = await uploadLocalMentions({ args: request.args }, gateway, request.signal ?? new AbortController().signal); + return gateway.invoke({ ...request, args: payload.args }); + }, + dispatch: async (endpoint, payload, signal) => gateway.dispatch( + endpoint, + endpoint === "session/prompt" ? await uploadLocalMentions(payload, gateway, signal) : payload, + signal + ), + open: (endpoint, payload, signal) => gateway.open(endpoint, payload, signal) + }; + this.gatewaySwitch.selectRemote(selected, void 0, target3); this.recoverable = remote; } remoteTypertGateway(remote) { @@ -88632,7 +89102,7 @@ var savedPairingSchema = external_exports.object({ // packages/plugin/src/identity-store.ts import { createHash as createHash5 } from "node:crypto"; -import { chmod as chmod2, lstat, mkdir as mkdir3, readFile as readFile3, readdir as readdir2, rename as rename2, rm as rm3, stat as stat2, unlink, writeFile as writeFile2 } from "node:fs/promises"; +import { chmod as chmod2, lstat as lstat2, mkdir as mkdir3, readFile as readFile4, readdir as readdir2, rename as rename2, rm as rm3, stat as stat2, unlink, writeFile as writeFile2 } from "node:fs/promises"; import { homedir as homedir2 } from "node:os"; import { basename as basename4, dirname as dirname4, join as join5 } from "node:path"; var identitySchema = external_exports.object({ @@ -88701,8 +89171,8 @@ var IdentityStore = class { } await assertPrivateMode2(keyPath); try { - const record11 = identitySchema.parse(JSON.parse(await readFile3(devicePath, "utf8"))); - const privateKey = (await readFile3(keyPath, "utf8")).trim(); + const record11 = identitySchema.parse(JSON.parse(await readFile4(devicePath, "utf8"))); + const privateKey = (await readFile4(keyPath, "utf8")).trim(); const regenerated = generateKeyPair(fromBase64Url2(privateKey)); if (regenerated.publicKey !== record11.publicKey) { throw new IdentityInvalidError("device public and private keys do not match"); @@ -88756,8 +89226,8 @@ var IdentityStore = class { async readIdentity(devicePath, keyPath, deviceName) { await assertPrivateMode2(keyPath); try { - let record11 = identitySchema.parse(JSON.parse(await readFile3(devicePath, "utf8"))); - const privateKey = (await readFile3(keyPath, "utf8")).trim(); + let record11 = identitySchema.parse(JSON.parse(await readFile4(devicePath, "utf8"))); + const privateKey = (await readFile4(keyPath, "utf8")).trim(); const regenerated = generateKeyPair(fromBase64Url2(privateKey)); if (regenerated.publicKey !== record11.publicKey) { throw new IdentityInvalidError("device public and private keys do not match"); @@ -88826,7 +89296,7 @@ var IdentityStore = class { if (!await exists2(path)) { await atomicJsonWrite(path, { schemaVersion: 1, peers: [] }, 384); } - const parsed = trustedPeersSchema.parse(JSON.parse(await readFile3(path, "utf8"))); + const parsed = trustedPeersSchema.parse(JSON.parse(await readFile4(path, "utf8"))); const peers = /* @__PURE__ */ new Map(); for (const peer of parsed.peers) { if (peer.fingerprint !== fingerprint2(peer.publicKey)) { @@ -88882,7 +89352,7 @@ async function prepareDefaultIdentityDirectoryLocked({ source, target: target3, const old = await storageDirectoryStat(source); const current = await storageDirectoryStat(target3); const pinPath = join5(lockDirectory, "legacy-root.json"); - const pinMetadata = await lstat(pinPath).catch((error62) => { + const pinMetadata = await lstat2(pinPath).catch((error62) => { if (isNodeError(error62) && error62.code === "ENOENT") return void 0; throw error62; }); @@ -88893,7 +89363,7 @@ async function prepareDefaultIdentityDirectoryLocked({ source, target: target3, } await assertPrivateMode2(pinPath); try { - pin = legacyRootPinSchema.parse(JSON.parse(await readFile3(pinPath, "utf8"))); + pin = legacyRootPinSchema.parse(JSON.parse(await readFile4(pinPath, "utf8"))); } catch { throw new IdentityInvalidError("Remote storage fallback record is invalid; no credentials were changed.", "STORAGE_CONFLICT"); } @@ -88997,7 +89467,7 @@ async function assertOwnedRemoteStorage(root2) { } if (isLockArtifact(entry.name)) { const lockPath = join5(directory, entry.name); - const metadata2 = await lstat(lockPath); + const metadata2 = await lstat2(lockPath); if (!entry.isFile() || !metadata2.isFile() || metadata2.isSymbolicLink() || metadata2.nlink !== 1 || metadata2.size > 16 * 1024 * 1024) { throw rejected("STORAGE_CONFLICT"); } @@ -89011,13 +89481,13 @@ async function assertOwnedRemoteStorage(root2) { } const allowedFile = identityFiles.has(entry.name) || isOwnedTempArtifact(entry.name) || isRefreshQueueArtifact(entry.name) || isBackupArtifact(entry.name) || canAutoHeal && isIdentityTempArtifact(entry.name); if (!entry.isFile() || !allowedFile) throw rejected("STORAGE_CONFLICT", entry.name); - const metadata = await lstat(join5(directory, entry.name)); + const metadata = await lstat2(join5(directory, entry.name)); if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 16 * 1024 * 1024 || metadata.nlink !== 1 && !await isVerifiedRefreshHardlink(directory, entry.name, entries.map((item) => item.name))) { throw rejected("STORAGE_CONFLICT", entry.name); } } const names = new Set(entries.map((entry) => entry.name).filter((name2) => !isLockArtifact(name2))); - if (names.has("server-credentials.json.refresh-lock") && await readFile3(join5(directory, "server-credentials.json.refresh-lock"), "utf8") !== SERVER_CREDENTIALS_QUEUE_MARKER) { + if (names.has("server-credentials.json.refresh-lock") && await readFile4(join5(directory, "server-credentials.json.refresh-lock"), "utf8") !== SERVER_CREDENTIALS_QUEUE_MARKER) { throw rejected("STORAGE_CONFLICT"); } if (!names.has("device.json") && !names.has("device.key")) { @@ -89038,8 +89508,8 @@ async function assertOwnedRemoteStorage(root2) { await assertPrivateMode2(join5(directory, "device.key")); let record11; try { - record11 = identitySchema.parse(JSON.parse(await readFile3(join5(directory, "device.json"), "utf8"))); - const key = (await readFile3(join5(directory, "device.key"), "utf8")).trim(); + record11 = identitySchema.parse(JSON.parse(await readFile4(join5(directory, "device.json"), "utf8"))); + const key = (await readFile4(join5(directory, "device.key"), "utf8")).trim(); if (generateKeyPair(fromBase64Url2(key)).publicKey !== record11.publicKey) { throw new IdentityInvalidError("device public and private keys do not match"); } @@ -89051,7 +89521,7 @@ async function assertOwnedRemoteStorage(root2) { throw rejected("IDENTITY_INVALID"); } if (names.has("trusted-peers.json")) { - const peers = trustedPeersSchema.parse(JSON.parse(await readFile3(join5(directory, "trusted-peers.json"), "utf8"))).peers; + const peers = trustedPeersSchema.parse(JSON.parse(await readFile4(join5(directory, "trusted-peers.json"), "utf8"))).peers; const ids = /* @__PURE__ */ new Set(); for (const peer of peers) { if (peer.fingerprint !== fingerprint2(peer.publicKey) || ids.has(peer.deviceId)) throw rejected("IDENTITY_INVALID"); @@ -89059,7 +89529,7 @@ async function assertOwnedRemoteStorage(root2) { } } if (names.has("server-credentials.json")) { - const raw = JSON.parse(await readFile3(join5(directory, "server-credentials.json"), "utf8")); + const raw = JSON.parse(await readFile4(join5(directory, "server-credentials.json"), "utf8")); if (typeof raw.serverUrl !== "string") throw rejected("IDENTITY_INVALID"); const expectedDeviceId = role2 === "client" && typeof raw.deviceId === "string" && external_exports.string().uuid().safeParse(raw.deviceId).success ? raw.deviceId : record11.deviceId; const credentials = await new ServerCredentialStore(directory).load(raw.serverUrl, expectedDeviceId); @@ -89072,11 +89542,11 @@ async function assertOwnedRemoteStorage(root2) { } if (names.has("pairing-host-only.json")) { await assertPrivateMode2(join5(directory, "pairing-host-only.json")); - external_exports.object({ hostOnly: external_exports.literal(true) }).strict().parse(JSON.parse(await readFile3(join5(directory, "pairing-host-only.json"), "utf8"))); + external_exports.object({ hostOnly: external_exports.literal(true) }).strict().parse(JSON.parse(await readFile4(join5(directory, "pairing-host-only.json"), "utf8"))); } if (names.has("host-pairing.json")) { await assertPrivateMode2(join5(directory, "host-pairing.json")); - const pairing = savedPairingSchema.parse(JSON.parse(await readFile3(join5(directory, "host-pairing.json"), "utf8"))); + const pairing = savedPairingSchema.parse(JSON.parse(await readFile4(join5(directory, "host-pairing.json"), "utf8"))); if (pairing.deviceId !== record11.deviceId || pairing.session.host.deviceId !== record11.deviceId || pairing.session.host.identityKey !== record11.publicKey || pairing.session.host.role !== "host") throw rejected("IDENTITY_INVALID"); const origin = new URL(pairing.serverUrl); if (!["http:", "https:"].includes(origin.protocol) || origin.origin !== pairing.serverUrl) throw rejected("IDENTITY_INVALID"); @@ -89125,7 +89595,7 @@ async function isRepairableLegacyClientDirectory(directory, names) { } } if (names.has("trusted-peers.json")) { - const peers = trustedPeersSchema.parse(JSON.parse(await readFile3(join5(directory, "trusted-peers.json"), "utf8"))).peers; + const peers = trustedPeersSchema.parse(JSON.parse(await readFile4(join5(directory, "trusted-peers.json"), "utf8"))).peers; if (peers.length > 0) return false; } if (names.has("device.key")) { @@ -89135,7 +89605,7 @@ async function isRepairableLegacyClientDirectory(directory, names) { } async function storageDirectoryStat(path) { try { - const entry = await lstat(path, { bigint: true }); + const entry = await lstat2(path, { bigint: true }); if (!entry.isDirectory() || entry.isSymbolicLink()) { throw new IdentityInvalidError("Remote storage must be a real directory; symbolic links are not migrated.", "STORAGE_CONFLICT"); } @@ -89154,7 +89624,7 @@ async function assertStorageIdle(directory) { const linkedTemps = []; for (const entry of before) { if (!isRefreshQueueTemp(entry.name)) continue; - const metadata = await lstat(join5(currentDirectory, entry.name)); + const metadata = await lstat2(join5(currentDirectory, entry.name)); if (metadata.nlink === 2 && await isVerifiedRefreshHardlink(currentDirectory, entry.name, names)) { linkedTemps.push(join5(currentDirectory, entry.name)); } @@ -89168,7 +89638,7 @@ async function assertStorageIdle(directory) { for (const temporary of linkedTemps) await unlink(temporary); for (const entry of await readdir2(currentDirectory, { withFileTypes: true })) { const entryPath = join5(currentDirectory, entry.name); - if (entry.name === "server-credentials.json.refresh-lock" && entry.isFile() && await readFile3(entryPath, "utf8") === SERVER_CREDENTIALS_QUEUE_MARKER) continue; + if (entry.name === "server-credentials.json.refresh-lock" && entry.isFile() && await readFile4(entryPath, "utf8") === SERVER_CREDENTIALS_QUEUE_MARKER) continue; if (entry.isFile() && isRefreshQueueArtifact(entry.name)) continue; if (entry.isSymbolicLink()) { throw new IdentityInvalidError( @@ -89242,8 +89712,8 @@ async function isVerifiedRefreshHardlink(directory, name2, names) { if (match === null || !names.includes(match[1]) || !ownerExited2(`${match[2]} `)) return false; const [source, published] = await Promise.all([ - lstat(join5(directory, temporary[0]), { bigint: true }), - lstat(join5(directory, match[1]), { bigint: true }) + lstat2(join5(directory, temporary[0]), { bigint: true }), + lstat2(join5(directory, match[1]), { bigint: true }) ]); return source.isFile() && published.isFile() && source.nlink === 2n && published.nlink === 2n && source.dev === published.dev && source.ino === published.ino; } @@ -89300,7 +89770,7 @@ var LOCK_RETRY_MAX_MS = 200; async function withIdentityLock(directory, operation) { const lockPath = join5(directory, LOCK_FILE_NAME); const deadline = Date.now() + LOCK_TIMEOUT_MS; - let delay = LOCK_RETRY_INITIAL_MS; + let delay2 = LOCK_RETRY_INITIAL_MS; for (; ; ) { try { await writeFile2(lockPath, `${process.pid} @@ -89316,8 +89786,8 @@ async function withIdentityLock(directory, operation) { "IDENTITY_LOCKED" ); } - await new Promise((resolve10) => setTimeout(resolve10, delay)); - delay = Math.min(delay * 2, LOCK_RETRY_MAX_MS); + await new Promise((resolve10) => setTimeout(resolve10, delay2)); + delay2 = Math.min(delay2 * 2, LOCK_RETRY_MAX_MS); } try { return await operation(); @@ -89369,7 +89839,7 @@ async function acquireTakeoverClaim(claimPath, depth, reclaimed) { } async function readLockRecord2(lockPath) { try { - return await readFile3(lockPath, "utf8"); + return await readFile4(lockPath, "utf8"); } catch { return void 0; } @@ -89392,7 +89862,7 @@ function isScopedClientDirectory(directory) { async function hasVerifiedScopedIdentity(directory) { try { const serversPath = join5(directory, "servers"); - const metadata = await lstat(serversPath); + const metadata = await lstat2(serversPath); if (!metadata.isDirectory() || metadata.isSymbolicLink()) return false; for (const scope2 of await readdir2(serversPath, { withFileTypes: true })) { if (!scope2.isDirectory() || scope2.isSymbolicLink() || !/^[a-f0-9]{24}$/.test(scope2.name)) continue; @@ -89401,14 +89871,14 @@ async function hasVerifiedScopedIdentity(directory) { const roleDir = join5(serversPath, scope2.name, role2.name); try { for (const fileName of ["device.json", "device.key"]) { - const fileStat = await lstat(join5(roleDir, fileName)); + const fileStat = await lstat2(join5(roleDir, fileName)); if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.nlink !== 1 || fileStat.size > 16 * 1024 * 1024) { throw new Error("invalid identity file metadata"); } } await assertPrivateMode2(join5(roleDir, "device.key")); - const record11 = identitySchema.parse(JSON.parse(await readFile3(join5(roleDir, "device.json"), "utf8"))); - const key = (await readFile3(join5(roleDir, "device.key"), "utf8")).trim(); + const record11 = identitySchema.parse(JSON.parse(await readFile4(join5(roleDir, "device.json"), "utf8"))); + const key = (await readFile4(join5(roleDir, "device.key"), "utf8")).trim(); if (generateKeyPair(fromBase64Url2(key)).publicKey === record11.publicKey) return true; } catch { continue; @@ -89426,7 +89896,7 @@ async function canAutoHealClientIdentity(directory, allowServersDirectory = fals for (const entry of entries) { if (isLockArtifact(entry.name)) continue; const entryPath = join5(directory, entry.name); - const metadata = await lstat(entryPath); + const metadata = await lstat2(entryPath); if (metadata.isSymbolicLink()) return false; if (allowServersDirectory && entry.name === "servers" && metadata.isDirectory()) continue; if (!metadata.isFile()) return false; @@ -89434,7 +89904,7 @@ async function canAutoHealClientIdentity(directory, allowServersDirectory = fals continue; } if (entry.name === "trusted-peers.json") { - const parsed = trustedPeersSchema.parse(JSON.parse(await readFile3(entryPath, "utf8"))); + const parsed = trustedPeersSchema.parse(JSON.parse(await readFile4(entryPath, "utf8"))); if (parsed.peers.length > 0) return false; continue; } @@ -89480,7 +89950,7 @@ async function readStorageEntries(directory) { const result = []; for (const entry of entries) { if (isStorageMetadataArtifact(entry.name) && entry.isFile()) { - const metadata = await lstat(join5(directory, entry.name)); + const metadata = await lstat2(join5(directory, entry.name)); if (metadata.isFile() && metadata.nlink === 1 && metadata.size <= 16 * 1024 * 1024) continue; } result.push(entry); @@ -90120,6 +90590,7 @@ function compactBotRound(text) { var LIMIT = 512; var MARKER = "\n[Compact history: output omitted]"; var ROUND_BUDGET = 128 * 1024; +var UI_TOOL_NAMES = /* @__PURE__ */ new Set(["ui_render", "ui_patch", "ui_render_widget", "ui_compose"]); var object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value); function preservedRound(text, budget) { if (budget.remaining < LIMIT) return void 0; @@ -90133,13 +90604,18 @@ function summary2(value, budget) { if (text.length <= LIMIT) return text; return preservedRound(text, budget) ?? text.slice(0, LIMIT) + MARKER; } -function toolValue(value, budget) { - if (Array.isArray(value)) return value.map((item) => toolValue(item, budget)); +function toolValue(value, budget, keepUiPayload = false) { + if (Array.isArray(value)) return value.map((item) => toolValue(item, budget, keepUiPayload)); if (!object3(value)) return value; const result = { ...value }; + const toolName = typeof value.name === "string" ? value.name : typeof value.toolName === "string" ? value.toolName : void 0; + const keepUi = keepUiPayload || toolName !== void 0 && UI_TOOL_NAMES.has(toolName); for (const [key, child] of Object.entries(value)) { - if (["input", "arguments", "output", "result", "rawInput", "rawOutput", "uiResultMeta", "meta", "argumentsDelta"].includes(key)) { - result[key] = typeof child === "string" ? summary2(child, budget) : { summary: summary2(child, budget) }; + if (key === "meta" || key === "uiResultMeta") { + result[key] = child; + } else if (["input", "arguments", "output", "result", "rawInput", "rawOutput", "argumentsDelta"].includes(key)) { + if (keepUi && (key === "arguments" || key === "argumentsDelta" || key === "input")) result[key] = child; + else result[key] = typeof child === "string" ? summary2(child, budget) : { summary: summary2(child, budget) }; } else if (key === "content" && Array.isArray(child)) { let previews = 0; const blocks = child.flatMap((block) => { @@ -91988,6 +92464,12 @@ var ACP_PROMPT_TIMEOUT_MS = 10 * 6e4; var ACP_START_TIMEOUT_MS = 2e4; var MAX_ACP_LINE_BYTES = 288 * 1024 * 1024; var MAX_STDERR_CAPTURE_BYTES2 = 4 * 1024; +var ADAPTER_LABELS = Object.freeze({ + cursor: "Cursor", + pi: "Pi", + claude: "Claude", + hermes: "Hermes" +}); var CursorAcpError = class extends Error { constructor(code, message, options) { super(message, options); @@ -92020,8 +92502,18 @@ var CursorAcpClient = class { startPromise; modelStates = /* @__PURE__ */ new Map(); modelBusy = /* @__PURE__ */ new Set(); + /** Backend that owns this process: failure codes and log lines must name it. */ + get backend() { + return this.options.backend ?? "cursor"; + } + get adapterLabel() { + return ADAPTER_LABELS[this.backend]; + } + code(suffix) { + return `${this.backend.toUpperCase()}_${suffix}`; + } start() { - if (this.closed) return Promise.reject(new CursorAcpError("CURSOR_CLOSED", "The Cursor domain is closed.")); + if (this.closed) return Promise.reject(new CursorAcpError(this.code("CLOSED"), `The ${this.adapterLabel} domain is closed.`)); if (this.ready) return Promise.resolve(); this.startPromise ??= this.startOnce().finally(() => { this.startPromise = void 0; @@ -92032,7 +92524,7 @@ var CursorAcpClient = class { return this.ready; } async call(method, params, timeoutMs) { - if (!this.ready) throw new CursorAcpError("CURSOR_UNAVAILABLE", "Cursor ACP is not ready."); + if (!this.ready) throw new CursorAcpError(this.code("UNAVAILABLE"), `${this.adapterLabel} ACP is not ready.`); const backend = this.options.modelBackend ?? (this.options.authenticationMethod === null ? void 0 : "cursor"); const id6 = isRecord16(params) && typeof params.sessionId === "string" ? params.sessionId : void 0; if (backend && (method === "dsh/sessionModels" || method === "dsh/selectModel")) { @@ -92103,7 +92595,7 @@ var CursorAcpClient = class { this.closed = true; this.ready = false; this.modelStates.clear(); - this.failPending(new CursorAcpError("CURSOR_CLOSED", "Cursor ACP was closed.")); + this.failPending(new CursorAcpError(this.code("CLOSED"), `${this.adapterLabel} ACP was closed.`)); const child = this.process; this.process = void 0; if (child === void 0 || child.exitCode !== null || child.killed) return; @@ -92122,7 +92614,7 @@ var CursorAcpClient = class { } async startOnce() { if (this.process !== void 0) { - throw new CursorAcpError("CURSOR_STARTING", "Cursor ACP is already starting."); + throw new CursorAcpError(this.code("STARTING"), `${this.adapterLabel} ACP is already starting.`); } const child = this.spawnAcp(this.binary); this.process = child; @@ -92137,21 +92629,21 @@ var CursorAcpClient = class { this.stderrBytes = Math.min(MAX_STDERR_CAPTURE_BYTES2, this.stderrBytes + Buffer4.byteLength(chunk)); }); child.on("error", (error62) => { - if (this.process === child) this.handleProcessFailure("CURSOR_BINARY_UNAVAILABLE", error62); + if (this.process === child) this.handleProcessFailure(this.code("BINARY_UNAVAILABLE"), error62); }); child.on("exit", (code, signal) => { if (this.process !== child) return; this.process = void 0; this.ready = false; this.modelStates.clear(); - this.failPending(new CursorAcpError("CURSOR_ACP_EXITED", "Cursor ACP exited unexpectedly.")); + this.failPending(new CursorAcpError(this.code("ACP_EXITED"), `${this.adapterLabel} ACP exited unexpectedly.`)); if (!this.closed) { - this.logger?.warn("Cursor ACP exited", { + this.logger?.warn(`${this.adapterLabel} ACP exited`, { code: code ?? "none", signal: signal ?? "none", stderrBytes: this.stderrBytes }); - this.notifyUnavailable("CURSOR_ACP_EXITED"); + this.notifyUnavailable(this.code("ACP_EXITED")); } }); try { @@ -92172,20 +92664,20 @@ var CursorAcpClient = class { } this.assertStarting(child); this.ready = true; - this.logger?.info("Cursor ACP ready"); + this.logger?.info(`${this.adapterLabel} ACP ready`); } catch (error62) { this.ready = false; this.modelStates.clear(); if (this.process === child) this.process = void 0; child.kill("SIGTERM"); if (error62 instanceof CursorAcpError) throw error62; - throw new CursorAcpError("CURSOR_INITIALIZE_FAILED", "Cursor ACP initialization failed.", { cause: error62 }); + throw new CursorAcpError(this.code("INITIALIZE_FAILED"), `${this.adapterLabel} ACP initialization failed.`, { cause: error62 }); } } assertStarting(child) { - if (this.closed) throw new CursorAcpError("CURSOR_CLOSED", "Cursor ACP was closed."); + if (this.closed) throw new CursorAcpError(this.code("CLOSED"), `${this.adapterLabel} ACP was closed.`); if (this.process !== child || child.exitCode !== null || child.killed) { - throw new CursorAcpError("CURSOR_UNAVAILABLE", "Cursor ACP is not available."); + throw new CursorAcpError(this.code("UNAVAILABLE"), `${this.adapterLabel} ACP is not available.`); } } request(method, params, timeoutMs) { @@ -92193,7 +92685,7 @@ var CursorAcpClient = class { const result = new Promise((resolve10, reject) => { const timer2 = setTimeout(() => { this.pending.delete(id6); - reject(new CursorAcpError("CURSOR_REQUEST_TIMEOUT", "Cursor ACP request timed out.")); + reject(new CursorAcpError(this.code("REQUEST_TIMEOUT"), `${this.adapterLabel} ACP request timed out.`)); }, timeoutMs); timer2.unref?.(); this.pending.set(id6, { resolve: resolve10, reject, timer: timer2 }); @@ -92209,7 +92701,7 @@ var CursorAcpClient = class { write(message) { const child = this.process; if (child === void 0 || child.stdin.destroyed || !child.stdin.writable) { - throw new CursorAcpError("CURSOR_UNAVAILABLE", "Cursor ACP is not available."); + throw new CursorAcpError(this.code("UNAVAILABLE"), `${this.adapterLabel} ACP is not available.`); } child.stdin.write(`${JSON.stringify(message)} `); @@ -92218,8 +92710,8 @@ var CursorAcpClient = class { this.stdoutBuffer = this.stdoutBuffer.length === 0 ? chunk : Buffer4.concat([this.stdoutBuffer, chunk]); if (this.stdoutBuffer.length > MAX_ACP_LINE_BYTES) { this.handleProcessFailure( - "CURSOR_RESPONSE_TOO_LARGE", - new Error("Cursor ACP emitted an oversized JSONL message.") + this.code("RESPONSE_TOO_LARGE"), + new Error(`${this.adapterLabel} ACP emitted an oversized JSONL message.`) ); return; } @@ -92236,18 +92728,18 @@ var CursorAcpClient = class { try { value = JSON.parse(line.toString("utf8")); } catch { - this.handleProcessFailure("CURSOR_INVALID_RESPONSE", new Error("Cursor ACP emitted invalid JSON.")); + this.handleProcessFailure(this.code("INVALID_RESPONSE"), new Error(`${this.adapterLabel} ACP emitted invalid JSON.`)); return; } if (!isRecord16(value)) { - this.handleProcessFailure("CURSOR_INVALID_RESPONSE", new Error("Cursor ACP emitted an invalid message.")); + this.handleProcessFailure(this.code("INVALID_RESPONSE"), new Error(`${this.adapterLabel} ACP emitted an invalid message.`)); return; } if ((typeof value.id === "number" || typeof value.id === "string") && ("result" in value || "error" in value)) { const pending = this.takePending(value.id); if (pending === void 0) return; if ("error" in value && value.error !== void 0) { - pending.reject(new CursorAcpError("CURSOR_UPSTREAM_ERROR", safeUpstreamError2(value.error))); + pending.reject(new CursorAcpError(this.code("UPSTREAM_ERROR"), safeUpstreamError2(value.error, this.adapterLabel))); } else { pending.resolve(value.result); } @@ -92264,11 +92756,11 @@ var CursorAcpClient = class { handleProcessFailure(code, cause) { this.ready = false; this.modelStates.clear(); - this.failPending(new CursorAcpError(code, "Cursor ACP communication failed.", { cause })); + this.failPending(new CursorAcpError(code, `${this.adapterLabel} ACP communication failed.`, { cause })); const child = this.process; this.process = void 0; child?.kill("SIGTERM"); - this.logger?.warn("Cursor ACP communication failed", { code }); + this.logger?.warn(`${this.adapterLabel} ACP communication failed`, { code }); if (!this.closed) this.notifyUnavailable(code); } notifyUnavailable(code) { @@ -92287,14 +92779,14 @@ var CursorAcpClient = class { for (const id6 of [...this.pending.keys()]) this.takePending(id6)?.reject(error62); } }; -function safeUpstreamError2(value) { - if (!isRecord16(value) || typeof value.message !== "string") return "Cursor ACP rejected the request."; +function safeUpstreamError2(value, label = "Cursor") { + if (!isRecord16(value) || typeof value.message !== "string") return `${label} ACP rejected the request.`; const message = value.message.toLowerCase(); if (message.includes("auth") || message.includes("login") || message.includes("api key")) { - return "Cursor ACP authentication failed."; + return `${label} ACP authentication failed.`; } - if (message.includes("not initialized")) return "Cursor ACP is not initialized."; - return "Cursor ACP rejected the request."; + if (message.includes("not initialized")) return `${label} ACP is not initialized.`; + return `${label} ACP rejected the request.`; } function isRecord16(value) { return typeof value === "object" && value !== null && !Array.isArray(value); @@ -92424,7 +92916,7 @@ var IsolatedAcpClient = class { binary, logger2, void 0, - { ...options, args: options.args ?? (options.backend === "cursor" ? ["acp"] : []), authenticationMethod: options.backend === "cursor" ? "cursor_login" : null } + { ...options, backend: options.backend ?? "pi", args: options.args ?? (options.backend === "cursor" ? ["acp"] : []), authenticationMethod: options.backend === "cursor" ? "cursor_login" : null } )) { this.binary = binary; this.logger = logger2; @@ -92698,7 +93190,7 @@ var IsolatedAcpClient = class { }; // packages/plugin/src/workspace-bridge.ts -import { realpath as realpath2, lstat as lstat2, readdir as readdir4, open as open4, stat as stat4, watch } from "node:fs/promises"; +import { realpath as realpath2, lstat as lstat3, readdir as readdir4, open as open4, stat as stat4, watch } from "node:fs/promises"; import { isAbsolute as isAbsolute5, join as join8, relative as relative2, resolve as resolve4 } from "node:path"; // packages/plugin/src/remote-terminal-controller.ts @@ -93381,7 +93873,7 @@ var WorkspaceBridge = class { const result = []; for (const entry of entries.slice(0, 500)) { const item = join8(target3, entry.name); - const info2 = await lstat2(item); + const info2 = await lstat3(item); if (info2.isSymbolicLink()) continue; result.push({ name: entry.name, type: info2.isDirectory() ? "directory" : info2.isFile() ? "file" : "other", ...info2.isFile() ? { size: info2.size } : {} }); } @@ -93480,7 +93972,7 @@ var WorkspaceBridge = class { const rel = relative2(root2, candidate); if (rel.startsWith("..") || isAbsolute5(rel)) throw this.scopeError("WORKSPACE_PATH_DENIED", "The requested workspace path is outside the CodeX workspace."); try { - const info = await lstat2(candidate); + const info = await lstat3(candidate); if (info.isSymbolicLink()) throw new Error(); const canonical = await realpath2(candidate); const canonicalRel = relative2(root2, canonical); @@ -93788,7 +94280,7 @@ var ClaudeAcpClient = class extends CursorAcpClient { shuttingDown = false; makeClient; constructor(binary = "claude-agent-acp", logger2, spawnAcp, options = {}, backend = "claude") { - const config2 = { ...options, args: options.args ?? [], authenticationMethod: null, modelBackend: backend }; + const config2 = { ...options, args: options.args ?? [], authenticationMethod: null, modelBackend: backend, backend }; super(binary, logger2, spawnAcp, config2); this.makeClient = () => new CursorAcpClient(binary, logger2, spawnAcp, config2); this.modelLabel = backend; @@ -94136,16 +94628,16 @@ var TranscriptWatcher = class extends EventEmitter2 { await this.readNewLines(); } async readNewLines() { - let stat10; + let stat11; try { - stat10 = await fs2.stat(this.transcriptPath); + stat11 = await fs2.stat(this.transcriptPath); } catch { return; } - if (stat10.size <= this.offset) return; + if (stat11.size <= this.offset) return; const handle = await fs2.open(this.transcriptPath, "r"); try { - const bytesToRead = stat10.size - this.offset; + const bytesToRead = stat11.size - this.offset; const buffer3 = Buffer.alloc(bytesToRead); const { bytesRead } = await handle.read(buffer3, 0, bytesToRead, this.offset); this.offset += bytesRead; @@ -95674,7 +96166,7 @@ async function readTranscriptSummary(baseDir, conversationId) { try { const path = await transcriptPath(baseDir, conversationId); if (path === void 0) return void 0; - const stat10 = await fs3.stat(path); + const stat11 = await fs3.stat(path); const handle = await fs3.open(path, "r"); try { const buffer3 = Buffer.alloc(4096); @@ -95685,7 +96177,7 @@ async function readTranscriptSummary(baseDir, conversationId) { if (record11.type !== "USER_INPUT") return void 0; const title = cleanUserPrompt(record11.content).split("\n")[0]?.trim().slice(0, 40) || (agyImageReferences(record11.content ?? "").length > 0 ? "Image" : void 0); if (!title) return void 0; - return { conversationId, title, createdAt: record11.created_at ? new Date(record11.created_at).getTime() : stat10.mtimeMs, updatedAt: stat10.mtimeMs }; + return { conversationId, title, createdAt: record11.created_at ? new Date(record11.created_at).getTime() : stat11.mtimeMs, updatedAt: stat11.mtimeMs }; } finally { await handle.close(); } @@ -97239,7 +97731,14 @@ var AcpRemoteGateway = class { this.approvalExpiryTimer.unref?.(); } requireAcp(backend) { - if (!this.config.enabled || backend !== void 0 && (!this.enabledBackends().includes(backend) || this.pendingReconfiguration.has(backend)) || !this.isAvailable()) { + if (!this.config.enabled) { + throw new RpcError("CURSOR_UNAVAILABLE", "Cursor ACP is disabled or unavailable on this Host."); + } + const configured = backend === void 0 ? void 0 : this.config.backends.find((item) => item.id === backend); + if (configured !== void 0 && !configured.enabled) { + throw new RpcError("ACP_BACKEND_DISABLED", `The ${backend} ACP backend is disabled by configuration.`); + } + if (backend !== void 0 && (!this.enabledBackends().includes(backend) || this.pendingReconfiguration.has(backend)) || !this.isAvailable()) { throw new RpcError("CURSOR_UNAVAILABLE", "Cursor ACP is disabled or unavailable on this Host."); } if (backend !== void 0) { @@ -97528,7 +98027,7 @@ function isRecord20(value) { import { execFile as execFile3, execFileSync } from "node:child_process"; import { existsSync as existsSync4, constants as constants5, accessSync as accessSync2, statSync as statSync3 } from "node:fs"; import { homedir as homedir7 } from "node:os"; -import { dirname as dirname5, join as join13, posix, win32 } from "node:path"; +import { dirname as dirname5, join as join13, posix as posix2, win32 as win322 } from "node:path"; import { promisify as promisify4 } from "node:util"; var execFileAsync2 = promisify4(execFile3); var BUILTIN_ACP_SPECS = Object.freeze({ @@ -97585,8 +98084,8 @@ function isBuiltinAcpBackend(id6) { function defaultCheckExecutable(candidate, platform3 = process.platform) { try { if (!existsSync4(candidate)) return false; - const stat10 = statSync3(candidate); - if (!stat10.isFile()) return false; + const stat11 = statSync3(candidate); + if (!stat11.isFile()) return false; if (platform3 === "win32") return true; accessSync2(candidate, constants5.X_OK); return true; @@ -97619,7 +98118,7 @@ function discoverSystemNpmPrefix(platform3 = process.platform) { } function candidateBinaryPaths(id6, options = {}) { const platform3 = options.platform ?? process.platform; - const pJoin = platform3 === "win32" ? win32.join : posix.join; + const pJoin = platform3 === "win32" ? win322.join : posix2.join; const env = options.env ?? process.env; const home = options.homedir ?? homedir7(); const localAppData = env.LOCALAPPDATA ?? (platform3 === "win32" ? pJoin(home, "AppData", "Local") : ""); @@ -97767,7 +98266,7 @@ function lookupSystemPath(command, platform3 = process.platform) { }); const firstLine = output2.split(/\r?\n/).find((line) => line.trim().length > 0); if (firstLine && defaultCheckExecutable(firstLine.trim(), platform3)) { - return platform3 === "win32" ? win32.resolve(firstLine.trim()) : posix.resolve(firstLine.trim()); + return platform3 === "win32" ? win322.resolve(firstLine.trim()) : posix2.resolve(firstLine.trim()); } return void 0; } catch { @@ -97780,7 +98279,7 @@ function findExistingBinary(id6, options = {}) { const candidates = candidateBinaryPaths(id6, options); for (const candidate of candidates) { if (check2(candidate)) { - return platform3 === "win32" ? win32.resolve(candidate) : posix.resolve(candidate); + return platform3 === "win32" ? win322.resolve(candidate) : posix2.resolve(candidate); } } const defaultCommands = { @@ -97865,7 +98364,7 @@ async function installOrConfigureBackend(backendId, options = {}) { // packages/plugin/src/control-runtime.ts var execFileAsync3 = promisify5(execFile4); var PluginControlRuntime = class { - constructor(config2, identityDirectory, settings, client, host, switchServer, updates, useDefaultStorage = false) { + constructor(config2, identityDirectory, settings, client, host, switchServer, updates, useDefaultStorage = false, logStore) { this.config = config2; this.identityDirectory = identityDirectory; this.settings = settings; @@ -97874,6 +98373,7 @@ var PluginControlRuntime = class { this.switchServer = switchServer; this.updates = updates; this.useDefaultStorage = useDefaultStorage; + this.logStore = logStore; } logoutFlight; serverSwitchFlight; @@ -97945,6 +98445,8 @@ var PluginControlRuntime = class { if (endpoint === "settings.acp.installOrConfigure") return ok3(await this.installOrConfigureAcp(payload)); if (endpoint === "settings.logout") return ok3(await this.logout()); if (endpoint === "settings.identity.reset") return ok3(await this.resetIdentity(payload)); + if (endpoint === "settings.logs.get") return ok3(await this.getLogs(payload)); + if (endpoint === "settings.logs.clear") return ok3(await this.clearLogs()); if (endpoint === "host.authorization.set" && this.client !== void 0) { const value = record9(payload); if (typeof value.enabled !== "boolean") throw new ClientModeError("INVALID_MESSAGE", "Host authorization state is required."); @@ -97960,6 +98462,7 @@ var PluginControlRuntime = class { this.host.reconnectHost(); return withUpdate(ok3(this.hostOnlyStatus()), this.updates?.snapshot()); } + if (endpoint === "plugin.update") return ok3(await this.updatePlugin(payload)); if (endpoint === "status") { if (this.startupFailure !== void 0) { const startupError = safeStartupError(this.startupFailure); @@ -98216,6 +98719,43 @@ var PluginControlRuntime = class { await this.settings.replace({ ...current, role: role2 }); return this.settingsView(); } + currentLogLevel() { + if (this.settings === void 0) return this.config.logLevel; + try { + const raw = this.settings.get()?.logLevel; + if (raw === "debug" || raw === "info" || raw === "warn" || raw === "error") return raw; + } catch { + } + return this.config.logLevel; + } + async getLogs(payload) { + const value = payload === void 0 ? {} : record9(payload); + const filter = value.filter; + if (filter !== void 0 && filter !== "all" && filter !== "warn") { + throw new ClientModeError("INVALID_MESSAGE", "The log filter must be all or warn."); + } + const limit = value.limit; + if (limit !== void 0 && (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 1e3)) { + throw new ClientModeError("INVALID_MESSAGE", "The log limit must be an integer between 1 and 1000."); + } + const logLevel = this.currentLogLevel(); + if (this.logStore === void 0) { + return { logLevel, entries: [], totalBuffered: 0 }; + } + const snapshot2 = await this.logStore.snapshot({ filter, limit }); + return { logLevel, ...snapshot2 }; + } + async clearLogs() { + if (this.settings === void 0) { + throw new ClientModeError("SETTINGS_UNAVAILABLE", "DSH user settings are unavailable in this profile."); + } + const logLevel = this.currentLogLevel(); + if (this.logStore === void 0) { + return { logLevel, entries: [], totalBuffered: 0 }; + } + const snapshot2 = await this.logStore.clear(); + return { logLevel, ...snapshot2 }; + } async setDevelopment(payload) { if (this.settings === void 0) throw new ClientModeError("SETTINGS_UNAVAILABLE", "DSH user settings are unavailable in this profile."); const value = record9(payload); @@ -98476,6 +99016,24 @@ var PluginControlRuntime = class { throw error62; } } + /** + * Replace this Desktop install through the official plugin manager. + * A version the registry check did not publish is refused. Installs the + * manager cannot update stay on the manual releases path. + */ + async updatePlugin(payload) { + const version2 = record9(payload).version; + if (typeof version2 !== "string" || version2.trim() === "") { + throw new ClientModeError("INVALID_MESSAGE", "A plugin version is required."); + } + if (this.updates?.start === void 0) return { status: "manual" }; + const outcome = await this.updates.start(version2); + if (outcome.status === "rejected") { + throw new ClientModeError("INVALID_MESSAGE", "That version is not the published update."); + } + if (outcome.status === "failed") return { status: "failed", message: outcome.message }; + return { status: outcome.status }; + } hostOnlyStatus() { return { mode: "local", @@ -98573,9 +99131,289 @@ function fail5(error62) { }; } +// packages/plugin/src/index.ts +import { basename as basename9, dirname as dirname9 } from "node:path"; + +// packages/plugin/src/host-log-store.ts +import { mkdir as mkdir4, open as open5, readFile as readFile5, rename as rename3, rm as rm4, stat as stat6, writeFile as writeFile3 } from "node:fs/promises"; +import { homedir as homedir8 } from "node:os"; +import { dirname as dirname6, join as join14 } from "node:path"; +var DEFAULT_MAX_ENTRIES = 1e3; +var DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024; +var DEFAULT_MAX_BACKUPS = 2; +var MAX_LINE_CHARS = 8192; +var TAIL_READ_BYTES = 512 * 1024; +function resolveHostLogPath(options = {}) { + const env = options.env ?? process.env; + const home = env.DSH_HOME || join14(options.homeDirectory ?? homedir8(), ".dsh"); + const rawProfile = options.profile ?? env.DSH_PROFILE ?? ""; + const profileSlug = rawProfile.trim().replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "host"; + return join14(home, "logs", "ds-harness-remote", `${profileSlug}.log`); +} +var HostLogStore = class { + filePath; + maxEntries; + maxFileBytes; + maxBackups; + liveEntries = []; + persistedEntries = []; + nextSeq = 1; + currentBytes = 0; + fileError; + writeChain = Promise.resolve(); + initPromise; + clearedBeforeInit = false; + sizeVerified = false; + dirEnsured = false; + pendingDiskLines = []; + diskFlushScheduled = false; + constructor(options = {}) { + this.filePath = options.filePath; + this.maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_MAX_ENTRIES); + this.maxFileBytes = Math.max(1024, options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES); + this.maxBackups = Math.max(0, options.maxBackups ?? DEFAULT_MAX_BACKUPS); + this.initPromise = this.loadInitialFile(); + this.writeChain = this.initPromise.catch(() => void 0); + } + record(level, message, now = /* @__PURE__ */ new Date()) { + const timestamp = now.toISOString(); + const clean4 = sanitizeLogMessage(message); + const line = `${timestamp} [${level.toUpperCase()}] ${clean4}`; + const entry = { + seq: this.nextSeq++, + timestamp, + level, + line + }; + this.liveEntries.push(entry); + this.trimInMemory(); + if (this.filePath !== void 0) { + this.pendingDiskLines.push(`${line} +`); + this.scheduleDiskFlush(); + } + } + async snapshot(options = {}) { + await this.initPromise.catch(() => void 0); + const filter = options.filter ?? "all"; + const limit = Math.min(this.maxEntries, Math.max(1, options.limit ?? 500)); + const combined = this.combinedEntries(); + const filtered = filter === "warn" ? combined.filter((entry) => entry.level === "warn" || entry.level === "error") : combined; + const entries = filtered.length > limit ? filtered.slice(-limit) : filtered; + return { + entries, + totalBuffered: combined.length, + ...this.filePath === void 0 ? {} : { filePath: this.filePath }, + ...this.fileError === void 0 ? {} : { fileError: this.fileError } + }; + } + async clear() { + this.clearedBeforeInit = true; + this.persistedEntries = []; + this.liveEntries = []; + this.pendingDiskLines = []; + if (this.filePath !== void 0) { + this.enqueueWrite(async () => { + await this.clearDisk(); + }); + await this.writeChain; + } + const entries = this.combinedEntries(); + return { + entries, + totalBuffered: entries.length, + ...this.filePath === void 0 ? {} : { filePath: this.filePath }, + ...this.fileError === void 0 ? {} : { fileError: this.fileError } + }; + } + async flush() { + await this.writeChain; + } + scheduleDiskFlush() { + if (this.diskFlushScheduled) return; + this.diskFlushScheduled = true; + this.enqueueWrite(async () => { + while (this.pendingDiskLines.length > 0) { + let batch = ""; + let batchBytes = 0; + while (this.pendingDiskLines.length > 0) { + const next = this.pendingDiskLines[0]; + const nextBytes = Buffer.byteLength(next, "utf8"); + if (batch.length > 0 && this.currentBytes + batchBytes + nextBytes > this.maxFileBytes) break; + this.pendingDiskLines.shift(); + batch += next; + batchBytes += nextBytes; + } + await this.appendToDisk(batch); + } + this.diskFlushScheduled = false; + }, () => { + this.diskFlushScheduled = false; + }); + } + enqueueWrite(task, onError) { + this.writeChain = this.writeChain.then(async () => { + try { + await task(); + this.fileError = void 0; + } catch (error62) { + this.dirEnsured = false; + onError?.(); + this.fileError = safeFsErrorMessage(error62); + } + }); + } + async loadInitialFile() { + if (this.filePath === void 0) return; + try { + const info = await stat6(this.filePath); + this.currentBytes = info.size; + this.sizeVerified = true; + if (this.clearedBeforeInit || info.size === 0) return; + const text = await readTailUtf8(this.filePath, info.size, TAIL_READ_BYTES); + if (this.clearedBeforeInit) return; + const lines = text.split(/\r?\n/).filter((line) => line.length > 0); + const tail = lines.slice(-this.maxEntries); + const parsed = []; + let seqBase = 1; + for (const line of tail) { + parsed.push(parsePersistedLine(line, seqBase++)); + } + this.persistedEntries = parsed; + let next = parsed.length + 1; + for (const entry of this.liveEntries) { + entry.seq = next++; + } + this.nextSeq = next; + this.trimInMemory(); + } catch (error62) { + if (isEnoent(error62)) { + this.currentBytes = 0; + this.sizeVerified = true; + return; + } + this.fileError = safeFsErrorMessage(error62); + } + } + async appendToDisk(payload) { + const target3 = this.filePath; + if (!this.dirEnsured) { + await mkdir4(dirname6(target3), { recursive: true, mode: 448 }); + this.dirEnsured = true; + } + if (!this.sizeVerified) { + const existing = await stat6(target3).catch((err5) => isEnoent(err5) ? void 0 : Promise.reject(err5)); + this.currentBytes = existing?.size ?? 0; + this.sizeVerified = true; + } + const byteLength = Buffer.byteLength(payload, "utf8"); + if (this.currentBytes > 0 && this.currentBytes + byteLength > this.maxFileBytes) { + await this.rotateFiles(target3); + } + await writeFile3(target3, payload, { encoding: "utf8", flag: "a", mode: 384 }); + this.currentBytes += byteLength; + } + async rotateFiles(target3) { + if (this.maxBackups === 0) { + await writeFile3(target3, "", { encoding: "utf8", mode: 384 }); + this.currentBytes = 0; + return; + } + for (let index = this.maxBackups; index >= 1; index--) { + const dest = `${target3}.${index}`; + const src = index === 1 ? target3 : `${target3}.${index - 1}`; + if (index === this.maxBackups) { + await rm4(dest, { force: true }).catch(() => void 0); + } + try { + await rename3(src, dest); + } catch (error62) { + if (!isEnoent(error62)) throw error62; + } + } + this.currentBytes = 0; + } + async clearDisk() { + const target3 = this.filePath; + if (!this.dirEnsured) { + await mkdir4(dirname6(target3), { recursive: true, mode: 448 }); + this.dirEnsured = true; + } + await writeFile3(target3, "", { encoding: "utf8", mode: 384 }); + this.sizeVerified = true; + for (let index = 1; index <= this.maxBackups; index++) { + await rm4(`${target3}.${index}`, { force: true }).catch(() => void 0); + } + this.currentBytes = 0; + } + combinedEntries() { + if (this.persistedEntries.length === 0) return [...this.liveEntries]; + const merged = [...this.persistedEntries, ...this.liveEntries]; + return merged.length > this.maxEntries ? merged.slice(-this.maxEntries) : merged; + } + trimInMemory() { + const total = this.persistedEntries.length + this.liveEntries.length; + if (total <= this.maxEntries) return; + const overflow = total - this.maxEntries; + if (this.persistedEntries.length >= overflow) { + this.persistedEntries.splice(0, overflow); + } else { + const remaining = overflow - this.persistedEntries.length; + this.persistedEntries = []; + this.liveEntries.splice(0, remaining); + } + } +}; +function sanitizeLogMessage(message) { + const redacted = message.replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi, "Bearer [REDACTED]").replace(/([?&](?:token|access_token|refresh_token|secret|password|authorization|cookie|code)=)[^&\s]+/gi, "$1[REDACTED]"); + const collapsed = redacted.replace(/[\r\n]+/g, " ").trimEnd(); + if (collapsed.length <= MAX_LINE_CHARS) return collapsed; + return `${collapsed.slice(0, MAX_LINE_CHARS)}...`; +} +function parsePersistedLine(line, seq) { + const match = line.match(/^(\d{4}-\d{2}-\d{2}T\S+)\s+\[(DEBUG|INFO|WARN|ERROR)\]\s+(.*)$/); + if (match === null) { + return { seq, timestamp: "", level: "info", line }; + } + const level = match[2].toLowerCase(); + return { + seq, + timestamp: match[1], + level, + line + }; +} +async function readTailUtf8(filePath, totalSize, maxBytes) { + if (totalSize <= maxBytes) { + return readFile5(filePath, "utf8"); + } + const handle = await open5(filePath, "r"); + try { + const start = totalSize - maxBytes; + const buffer3 = Buffer.allocUnsafe(maxBytes); + const { bytesRead } = await handle.read(buffer3, 0, maxBytes, start); + const raw = buffer3.subarray(0, bytesRead).toString("utf8"); + const firstNewline = raw.indexOf("\n"); + return firstNewline === -1 ? raw : raw.slice(firstNewline + 1); + } finally { + await handle.close(); + } +} +function isEnoent(error62) { + return typeof error62 === "object" && error62 !== null && error62.code === "ENOENT"; +} +function safeFsErrorMessage(error62) { + if (error62 instanceof Error && error62.message.trim().length > 0) { + const home = homedir8(); + const normalized = home.length > 0 ? error62.message.split(home).join("~") : error62.message; + return normalized.replace(/[\r\n]+/g, " ").trim(); + } + return "Failed to write log file."; +} + // packages/plugin/src/logging.ts var levels = ["debug", "info", "warn", "error"]; -var secretKey = /authorization|cookie|token|secret|private|shared|ciphertext|payload|prompt|source|workspace|output|registrationCode|deviceCode/i; +var secretKey = /authorization|cookie|token|secret|password|passphrase|credential|apiKey|private|shared|ciphertext|payload|prompt|source|workspace|output|registrationCode|deviceCode/i; var SafeLogger = class { constructor(sink, threshold = "info") { this.sink = sink; @@ -98607,10 +99445,201 @@ function redact(value, key = "") { return Object.fromEntries(Object.entries(value).map(([childKey, child]) => [childKey, redact(child, childKey)])); } +// packages/plugin/src/lan-upload.ts +import { randomBytes as randomBytes13 } from "node:crypto"; +import { createServer as createServer4 } from "node:http"; +import { networkInterfaces as networkInterfaces3 } from "node:os"; +var LanUploadHost = class { + constructor(upload, owner, localAddresses = () => Object.values(networkInterfaces3()).flatMap((list2) => list2 ?? []).filter((a) => a.family === "IPv4" && !a.internal).map((a) => a.address)) { + this.upload = upload; + this.owner = owner; + this.localAddresses = localAddresses; + } + closed = false; + entries = /* @__PURE__ */ new Set(); + async open(input4) { + const p = lanUploadRequestSchema.parse(input4); + if (!this.live() || !isLanUploadAddress(p.address) || !this.localAddresses().includes(p.address) || this.entries.size >= 2) throw unavailable2(); + if ([...this.entries].some((e) => e.uploadId === p.uploadId)) throw unavailable2(); + const server = createServer4((_request, response) => { + response.writeHead(404).end(); + }); + server.maxConnections = 4; + server.headersTimeout = 5e3; + server.requestTimeout = 5e3; + server.keepAliveTimeout = 1e3; + const wss = new import_websocket_server.default({ noServer: true, maxPayload: 65535, perMessageDeflate: false }); + const entry = { server, wss, sessionId: p.sessionId, uploadId: p.uploadId, used: false, opened: false, committed: false, disposed: false, queuedBytes: 0, requests: 0 }; + this.entries.add(entry); + try { + await new Promise((resolve10, reject) => { + entry.rejectBinding = () => reject(unavailable2()); + server.once("error", reject); + server.listen(0, p.address, () => { + server.off("error", reject); + entry.rejectBinding = void 0; + if (entry.disposed) { + server.close(); + reject(unavailable2()); + } else resolve10(); + }); + }); + if (!this.live() || entry.disposed) throw unavailable2(); + const address2 = server.address(); + if (!address2 || typeof address2 === "string") throw unavailable2(); + const token = randomBytes13(32).toString("base64url"); + const path = `/ds-harness-remote/upload/${token}`; + const offer = { + sessionId: p.sessionId, + uploadId: p.uploadId, + connectionId: this.owner.connectionId, + url: `ws://${p.address}:${address2.port}${path}`, + expiresInMs: LAN_UPLOAD_TICKET_MS + }; + entry.timer = setTimeout(() => { + void this.dispose(entry); + }, LAN_UPLOAD_TICKET_MS); + entry.timer.unref(); + server.on("error", () => { + void this.dispose(entry); + }); + server.on("upgrade", (request, socket, head) => { + if (!this.live() || entry.disposed || entry.used || request.url !== path) { + socket.destroy(); + return; + } + entry.used = true; + clearTimeout(entry.timer); + try { + wss.handleUpgrade(request, socket, head, (ws) => this.attach(entry, offer, ws)); + } catch { + socket.destroy(); + void this.dispose(entry); + } + }); + return offer; + } catch (error62) { + await this.dispose(entry); + throw error62 instanceof RpcError ? error62 : unavailable2(); + } + } + async closeAll() { + this.closed = true; + await Promise.all([...this.entries].map((entry) => this.dispose(entry))); + } + live() { + return !this.closed && this.owner.mode() === "LAN"; + } + attach(entry, offer, socket) { + if (!this.live() || entry.disposed) { + socket.terminate(); + return; + } + entry.socket = socket; + socket.on("error", () => { + void this.dispose(entry); + }); + socket.on("close", () => { + void this.dispose(entry); + }); + const identity3 = this.owner.identity(); + const noise = new NoiseIkSession({ + role: "responder", + localPrivateKey: identity3.privateKey, + localPublicKey: identity3.publicKey, + remotePublicKey: this.owner.peerIdentityKey, + prologue: createLanUploadPrologue(offer) + }); + entry.noise = noise; + const incoming = new SecureMessageCodec(), outgoing = new SecureMessageCodec(); + let tail = Promise.resolve(); + const send = async (message) => { + for (const frame of outgoing.encode(encodeMessage(message))) { + if (!this.live() || entry.disposed || socket.readyState !== import_websocket.default.OPEN) throw unavailable2(); + await new Promise((resolve10, reject) => socket.send(noise.encrypt(frame), { binary: true }, (error62) => error62 ? reject(error62) : resolve10())); + } + }; + const touch = () => { + clearTimeout(entry.timer); + entry.timer = setTimeout(() => { + void this.dispose(entry); + }, 12e4); + entry.timer.unref(); + }; + entry.handshakeTimer = setTimeout(() => { + void this.dispose(entry); + }, 5e3); + entry.handshakeTimer.unref(); + socket.on("message", (raw, binary) => { + try { + if (!binary || !this.live() || entry.disposed) throw unavailable2(); + const bytes = raw instanceof Buffer ? raw : Buffer.from(raw); + if (!noise.complete) { + noise.readHandshake(bytes); + socket.send(noise.writeHandshake(), { binary: true }); + clearTimeout(entry.handshakeTimer); + touch(); + return; + } + const data2 = incoming.decode(noise.decrypt(bytes)); + if (!data2) return; + if (data2.byteLength > BINARY_UPLOAD_CHUNK_BYTES + 8192 || entry.queuedBytes + data2.byteLength > 2 * 1024 * 1024 || entry.requests >= 8) throw unavailable2(); + const message = decodeMessage(data2); + const payload = message.payload; + const params = payload?.params; + if (message.type !== "rpc.request" || !params || params.sessionId !== entry.sessionId || params.uploadId !== entry.uploadId || !["workspace.upload.open", "workspace.upload.chunk.binary", "workspace.upload.commit", "workspace.upload.abort"].includes(String(payload.method))) throw unavailable2(); + entry.queuedBytes += data2.byteLength; + entry.requests++; + touch(); + tail = tail.then(async () => { + if (!this.live() || entry.disposed) return; + const method = payload.method; + try { + if (entry.committed || (method === "workspace.upload.open" ? entry.opened || params.encoding !== "binary-v1" : !entry.opened)) throw unavailable2(); + if (method === "workspace.upload.open") entry.opened = true; + const result = await this.upload.call(method, params); + if (method === "workspace.upload.commit") entry.committed = true; + await send(createRpcResponse(message.id, result)); + } catch (error62) { + await send(createRpcError(message.id, safeErrorCode(error62), "The LAN upload could not be completed.")).catch(() => void 0); + await this.dispose(entry); + } finally { + entry.queuedBytes -= data2.byteLength; + entry.requests--; + } + }).catch(() => { + void this.dispose(entry); + }); + } catch { + void this.dispose(entry); + } + }); + } + async dispose(entry) { + if (entry.disposed) return; + entry.disposed = true; + entry.rejectBinding?.(); + entry.rejectBinding = void 0; + this.entries.delete(entry); + clearTimeout(entry.timer); + clearTimeout(entry.handshakeTimer); + entry.socket?.terminate(); + entry.noise?.destroy(); + for (const socket of entry.wss.clients) socket.terminate(); + entry.wss.close(); + entry.server.closeAllConnections(); + entry.server.close(); + if (entry.opened && !entry.committed) await this.upload.call("workspace.upload.abort", { sessionId: entry.sessionId, uploadId: entry.uploadId }).catch(() => void 0); + } +}; +function unavailable2() { + return new RpcError("FEATURE_NOT_SUPPORTED", "LAN upload is unavailable on this connection."); +} + // packages/plugin/src/host-pairing.ts -import { createHash as createHash7, createHmac as createHmac6, createPrivateKey as createPrivateKey4, createPublicKey as createPublicKey2, diffieHellman as diffieHellman2, hkdfSync, randomBytes as randomBytes13, createCipheriv as createCipheriv5, createDecipheriv as createDecipheriv4 } from "node:crypto"; -import { join as join14 } from "node:path"; -import { rm as rm4 } from "node:fs/promises"; +import { createHash as createHash7, createHmac as createHmac6, createPrivateKey as createPrivateKey4, createPublicKey as createPublicKey2, diffieHellman as diffieHellman2, hkdfSync, randomBytes as randomBytes14, createCipheriv as createCipheriv5, createDecipheriv as createDecipheriv4 } from "node:crypto"; +import { join as join15 } from "node:path"; +import { rm as rm5 } from "node:fs/promises"; var root = "/api/v1/device-pairing/sessions"; var active = /* @__PURE__ */ new Set(["created", "claimed", "approved"]); function rawKey(text) { @@ -98641,7 +99670,7 @@ var HostPairing = class { this.adopt = adopt; this.fetcher = fetcher; this.serverUrl = normalizeServerUrl(serverUrl, httpServerAllowlist); - this.path = join14(directory, "host-pairing.json"); + this.path = join15(directory, "host-pairing.json"); } path; serverUrl; @@ -98653,7 +99682,7 @@ var HostPairing = class { async discard() { this.close(); await this.queue.catch(() => void 0); - await rm4(this.path, { force: true }); + await rm5(this.path, { force: true }); } serial(fn) { const task = this.queue.catch(() => void 0).then(fn); @@ -98717,7 +99746,7 @@ var HostPairing = class { if (s.serverUrl !== this.serverUrl || s.deviceId !== this.identity.deviceId) throw new ServerApiError("PAIRING_IDENTITY_INVALID", "Pairing belongs to another identity.", false); if (s.session.expiresAt + 3e5 <= Date.now()) { - await rm4(this.path, { force: true }); + await rm5(this.path, { force: true }); return void 0; } return s; @@ -98818,7 +99847,7 @@ var HostPairing = class { const key = createHash7("sha256").update("dsh-pairing-host-submission-v1\0").update(rawKey(this.identity.privateKey)).digest(); try { if (encrypt) { - const iv = randomBytes13(12); + const iv = randomBytes14(12); const c2 = createCipheriv5("aes-256-gcm", key, iv); c2.setAAD(Buffer.from(id6)); const data2 = Buffer.concat([c2.update(value, "utf8"), c2.final()]); @@ -98838,15 +99867,16 @@ var HostPairing = class { // packages/plugin/src/workspace-upload.ts import { randomUUID as randomUUID16 } from "node:crypto"; import { constants as constants6 } from "node:fs"; -import { link as link2, lstat as lstat3, open as open5, realpath as realpath6, stat as stat6, unlink as unlink2 } from "node:fs/promises"; -import { extname, isAbsolute as isAbsolute8, join as join15 } from "node:path"; +import { link as link2, lstat as lstat4, open as open6, realpath as realpath6, stat as stat7, unlink as unlink2 } from "node:fs/promises"; +import { extname, isAbsolute as isAbsolute8, join as join16 } from "node:path"; var WORKSPACE_UPLOAD_BYTES = 20 * 1024 * 1024; var WORKSPACE_UPLOAD_CHUNK = 64 * 1024; var WORKSPACE_UPLOAD_AUTHORITY_TTL_MS = 5e3; var WORKSPACE_UPLOAD_AUTHORITY_BYTES = 4 * 1024 * 1024; var scope = external_exports.object({ sessionId: external_exports.string().min(1).max(512), uploadId: external_exports.string().uuid() }).strict(); -var openParams = scope.extend({ name: external_exports.string().min(1), totalBytes: external_exports.number().int().min(0).max(workspaceUploadMaxBytes("LAN")) }).strict(); +var openParams = scope.extend({ name: external_exports.string().min(1), totalBytes: external_exports.number().int().min(0).max(workspaceUploadMaxBytes("LAN")), encoding: external_exports.literal("binary-v1").optional() }).strict(); var chunkParams = scope.extend({ offset: external_exports.number().int().min(0), data: external_exports.string().min(1).max(Math.ceil(WORKSPACE_UPLOAD_CHUNK / 3) * 4) }).strict(); +var binaryChunkParams = scope.extend({ offset: external_exports.number().int().min(0), data: external_exports.instanceof(Uint8Array).refine((data2) => data2.byteLength > 0 && data2.byteLength <= BINARY_UPLOAD_CHUNK_BYTES) }).strict(); var WorkspaceUploadHost = class { constructor(resolveRoot, ttlMs = 12e4, transportMode = () => void 0, now = Date.now) { this.resolveRoot = resolveRoot; @@ -98874,6 +99904,8 @@ var WorkspaceUploadHost = class { return await this.begin(input4); case "workspace.upload.chunk": return await this.append(input4); + case "workspace.upload.chunk.binary": + return await this.append(input4, true); case "workspace.upload.commit": return await this.commit(input4); case "workspace.upload.abort": { @@ -98919,10 +99951,10 @@ var WorkspaceUploadHost = class { this.assertLive(); if (!sourceRoot || !isAbsolute8(sourceRoot)) throw failure4("UPLOAD_WORKSPACE_UNAVAILABLE"); const root2 = await realpath6(sourceRoot); - const directory = await stat6(root2); + const directory = await stat7(root2); if (!directory.isDirectory()) throw failure4("UPLOAD_WORKSPACE_UNAVAILABLE"); - const temp = join15(root2, `.dsh-upload-${randomUUID16()}.part`); - const handle = await open5(temp, constants6.O_CREAT | constants6.O_EXCL | constants6.O_RDWR | (constants6.O_NOFOLLOW ?? 0), 384); + const temp = join16(root2, `.dsh-upload-${randomUUID16()}.part`); + const handle = await open6(temp, constants6.O_CREAT | constants6.O_EXCL | constants6.O_RDWR | (constants6.O_NOFOLLOW ?? 0), 384); const upload = { ...p, received: 0, @@ -98938,13 +99970,14 @@ var WorkspaceUploadHost = class { }; this.uploads.set(p.uploadId, upload); await this.validateRoot(upload); - return { uploadId: p.uploadId, chunkBytes: WORKSPACE_UPLOAD_CHUNK }; + return { uploadId: p.uploadId, chunkBytes: p.encoding ? BINARY_UPLOAD_CHUNK_BYTES : WORKSPACE_UPLOAD_CHUNK, ...p.encoding ? { encoding: p.encoding } : {} }; } - async append(input4) { - const p = chunkParams.parse(input4); + async append(input4, binary = false) { + const p = binary ? binaryChunkParams.parse(input4) : chunkParams.parse(input4); const upload = this.requireUpload(p); - const data2 = Buffer.from(p.data, "base64"); - if (!data2.length || data2.length > WORKSPACE_UPLOAD_CHUNK || data2.toString("base64") !== p.data || p.offset !== upload.received || upload.received + data2.length > upload.totalBytes) throw failure4("UPLOAD_INVALID_CHUNK"); + if (binary !== (upload.encoding === "binary-v1")) throw failure4("UPLOAD_INVALID_CHUNK"); + const data2 = typeof p.data === "string" ? Buffer.from(p.data, "base64") : Buffer.from(p.data.buffer, p.data.byteOffset, p.data.byteLength); + if (!data2.length || data2.length > (binary ? BINARY_UPLOAD_CHUNK_BYTES : WORKSPACE_UPLOAD_CHUNK) || !binary && data2.toString("base64") !== p.data || p.offset !== upload.received || upload.received + data2.length > upload.totalBytes) throw failure4("UPLOAD_INVALID_CHUNK"); await this.validateRoot(upload, this.authorityExpired(upload)); let written = 0; while (written < data2.length) { @@ -98969,7 +100002,7 @@ var WorkspaceUploadHost = class { await this.validateRoot(upload); await upload.handle.sync(); const original = await upload.handle.stat(); - const temp = await lstat3(upload.temp); + const temp = await lstat4(upload.temp); if (!temp.isFile() || temp.dev !== original.dev || temp.ino !== original.ino || temp.size !== upload.totalBytes) throw failure4("UPLOAD_WORKSPACE_CHANGED"); const extension2 = extname(upload.name); const stem = upload.name.slice(0, upload.name.length - extension2.length); @@ -98977,7 +100010,7 @@ var WorkspaceUploadHost = class { await this.validateRoot(upload); const name2 = suffix === 0 ? upload.name : `${stem} (${suffix})${extension2}`; try { - await link2(upload.temp, join15(upload.root, name2)); + await link2(upload.temp, join16(upload.root, name2)); } catch (error62) { if (error62.code === "EEXIST") continue; throw error62; @@ -99033,7 +100066,7 @@ var WorkspaceUploadHost = class { upload.authorityBytes = upload.received; } if (await realpath6(upload.root) !== upload.root) throw failure4("UPLOAD_WORKSPACE_CHANGED"); - const directory = await stat6(upload.root); + const directory = await stat7(upload.root); if (!directory.isDirectory() || directory.dev !== upload.dev || directory.ino !== upload.ino) throw failure4("UPLOAD_WORKSPACE_CHANGED"); } async discard(id6, upload) { @@ -99041,8 +100074,8 @@ var WorkspaceUploadHost = class { const original = await upload.handle.stat().catch(() => void 0); await upload.handle.close().catch(() => void 0); try { - const root2 = await lstat3(upload.root); - const temp = await lstat3(upload.temp); + const root2 = await lstat4(upload.root); + const temp = await lstat4(upload.temp); if (original && root2.isDirectory() && root2.dev === upload.dev && root2.ino === upload.ino && temp.isFile() && temp.dev === original.dev && temp.ino === original.ino) await unlink2(upload.temp); } catch { } @@ -99066,18 +100099,18 @@ function workspaceUploadRootResolver(gateway, supportsHarnessSessions, codex, ac signal.throwIfAborted(); if (sessionId.startsWith("codex:")) { const parsed = parseCodexSessionId(sessionId); - if (!parsed) throw unavailable2(); + if (!parsed) throw unavailable3(); return codex(parsed.threadId); } if (/^(acp|cursor|pi|opencode|claude|hermes):/.test(sessionId)) return acp(sessionId); - if (!gateway?.supportsCarrier || !supportsHarnessSessions()) throw unavailable2(); + if (!gateway?.supportsCarrier || !supportsHarnessSessions()) throw unavailable3(); const result = await gateway.dispatch("session/list", { args: { _request: {} } }, signal); signal.throwIfAborted(); const value = result.ok ? result.value : void 0; return value?.items?.find((item) => item.sessionId === sessionId)?.cwd; }; } -function unavailable2() { +function unavailable3() { return new RpcError("UPLOAD_WORKSPACE_UNAVAILABLE", "The session workspace is unavailable."); } @@ -99120,7 +100153,7 @@ var ConnectionController = class { } await Promise.all(replaced.map((connection2) => this.disconnect(connection2, "CONNECTION_REPLACED"))); const router = this.createRouter( - { connectionId, peerDeviceId: channel.peerDeviceId, transportMode: () => channel.mode }, + { connectionId, peerDeviceId: channel.peerDeviceId, peerIdentityKey: channel.peerIdentityKey, transportMode: () => channel.mode, createTransportUpgradeHost: channel.createTransportUpgradeHost?.bind(channel) }, (message) => this.sendTo(connectionId, channel, message) ); const connection = { @@ -99296,10 +100329,236 @@ function shortId2(value) { return value.length <= 12 ? value : `${value.slice(0, 8)}\u2026${value.slice(-4)}`; } +// packages/plugin/src/transport-upgrade.ts +var TransportUpgradeHost = class { + constructor(options) { + this.options = options; + } + candidate; + closed = false; + offerEpoch = 0; + activating = false; + async offer(rawParams) { + if (this.closed) throw new RpcError("INVALID_MESSAGE", "The connection is closed."); + const { attemptId, sdp } = transportUpgradeOfferSchema.parse(rawParams); + const current = this.options.currentMode(); + if (current === "LAN") { + throw new RpcError("REQUEST_CONFLICT", "Transport is already at LAN tier."); + } + const epoch = ++this.offerEpoch; + await this.clearCandidate(); + const factory = await this.options.loadRtcFactory(); + if (this.closed || epoch !== this.offerEpoch) { + throw new RpcError("REQUEST_CONFLICT", "Transport upgrade offer was superseded."); + } + if (factory === void 0) { + throw new RpcError("CAPABILITY_NOT_SUPPORTED", "WebRTC is unavailable on this Host."); + } + let iceServers = []; + try { + iceServers = await this.options.fetchIceServers(this.options.connectionId); + } catch { + iceServers = []; + } + if (this.closed || epoch !== this.offerEpoch) { + throw new RpcError("REQUEST_CONFLICT", "Transport upgrade offer was superseded."); + } + let answerResolve; + let answerReject; + const answerReady = new Promise((resolve10, reject) => { + answerResolve = resolve10; + answerReject = reject; + }); + const rtc = new RtcDataChannelTransport({ + role: "responder", + factory, + iceServers, + negotiateTimeoutMs: 12e3, + onSignal: (signal) => { + if (this.closed) return; + if (signal.type === "answer") { + answerResolve?.(signal.sdp); + return; + } + if (signal.type === "ice" && this.candidate?.attemptId === attemptId && !this.candidate.activated) { + void this.options.publishEvent(createEvent("remote.transport.upgrade.ice", { + attemptId, + candidate: signal.candidate + })).catch(() => void 0); + } + } + }); + const unsubscribeMessage = rtc.onMessage((frame) => { + try { + const parsed = unwrapUpgradedTransportFrame(frame); + this.options.onReceiveSequencedCiphertext(parsed.counter, parsed.ciphertext, rtc); + } catch { + void rtc.close().catch(() => void 0); + } + }); + const unsubscribeClose = rtc.onClose(() => { + if (this.candidate?.attemptId === attemptId && !this.candidate.activated) { + void this.clearCandidate(); + } + }); + const expiryTimer = setTimeout(() => { + if (this.candidate?.attemptId === attemptId && !this.candidate.activated) { + void this.clearCandidate(); + } + }, this.options.attemptTtlMs ?? 2e4); + expiryTimer.unref?.(); + const attempt = { + attemptId, + rtc, + unsubscribeMessage, + unsubscribeClose, + expiryTimer, + activated: false + }; + this.candidate = attempt; + void rtc.connect().catch((err5) => { + answerReject?.(err5 instanceof Error ? err5 : new Error(String(err5))); + }); + rtc.handleSignal({ type: "offer", sdp }); + let timer2; + try { + const answerSdp = await Promise.race([ + answerReady, + new Promise((_, reject) => { + timer2 = setTimeout(() => reject(new Error("Timed out creating WebRTC upgrade answer.")), 8e3); + timer2.unref?.(); + }) + ]); + if (this.closed || this.candidate !== attempt) { + await this.disposeAttempt(attempt, true); + throw new RpcError("REQUEST_CONFLICT", "Transport upgrade offer was superseded."); + } + return { attemptId, sdp: answerSdp }; + } catch (error62) { + if (this.candidate === attempt) await this.clearCandidate(); + else await this.disposeAttempt(attempt, true); + if (error62 instanceof RpcError) throw error62; + throw new RpcError("CONNECTION_FAILED", error62 instanceof Error ? error62.message : "Failed to negotiate WebRTC upgrade.", true); + } finally { + if (timer2 !== void 0) clearTimeout(timer2); + } + } + async addIce(rawParams) { + const { attemptId, candidate } = transportUpgradeIceSchema.parse(rawParams); + if (this.closed || this.candidate?.attemptId !== attemptId) return { ok: true }; + this.candidate.rtc.handleSignal({ type: "ice", candidate }); + return { ok: true }; + } + async activate(rawParams) { + if (this.closed) throw new RpcError("INVALID_MESSAGE", "The connection is closed."); + if (this.activating) throw new RpcError("REQUEST_CONFLICT", "Another transport activation is already in progress."); + const { attemptId } = transportUpgradeActivateSchema.parse(rawParams); + const attempt = this.candidate; + if (attempt === void 0 || attempt.attemptId !== attemptId) { + throw new RpcError("REQUEST_CONFLICT", "Transport upgrade attempt is no longer active."); + } + this.activating = true; + try { + let timer2; + try { + await Promise.race([ + attempt.rtc.connect(), + new Promise((_, reject) => { + timer2 = setTimeout(() => reject(new Error("Timed out waiting for upgraded DataChannel to open.")), 6e3); + timer2.unref?.(); + }) + ]); + } finally { + if (timer2 !== void 0) clearTimeout(timer2); + } + if (this.closed || this.candidate !== attempt) { + await this.disposeAttempt(attempt, true); + return { activated: false, mode: this.options.currentMode() ?? "Relay" }; + } + let verifiedMode; + for (let i = 0; i < 5; i += 1) { + const details2 = await attempt.rtc.connectionDetails().catch(() => void 0); + verifiedMode = details2?.mode; + if (verifiedMode !== void 0) break; + if (i < 4) await new Promise((resolve10) => setTimeout(resolve10, 40)); + } + if (this.closed || this.candidate !== attempt) { + await this.disposeAttempt(attempt, true); + return { activated: false, mode: this.options.currentMode() ?? "Relay" }; + } + const beforeMode = this.options.currentMode() ?? "Relay"; + if (verifiedMode === void 0 || transportTierRank(verifiedMode) <= transportTierRank(beforeMode)) { + await this.clearCandidate(); + return { activated: false, mode: beforeMode }; + } + clearTimeout(attempt.expiryTimer); + attempt.unsubscribeClose(); + attempt.activated = true; + this.candidate = void 0; + const hostPreviousLegEndCounter = await this.options.adoptRtc(attempt.rtc, verifiedMode, attemptId); + this.options.logger?.info("in-band transport upgraded", { + connectionId: this.options.connectionId.slice(0, 8), + from: beforeMode, + to: verifiedMode + }); + return { + activated: true, + mode: verifiedMode, + previousLegEndCounter: hostPreviousLegEndCounter + }; + } finally { + this.activating = false; + } + } + async drain(rawParams) { + const { attemptId, previousLegEndCounter } = transportUpgradeDrainSchema.parse(rawParams); + if (!this.closed) { + this.options.confirmPreviousLegDrain?.(attemptId, previousLegEndCounter); + } + return { ok: true }; + } + async abort(rawParams) { + const { attemptId } = transportUpgradeAbortSchema.parse(rawParams ?? {}); + if (attemptId === void 0 || this.candidate?.attemptId === attemptId) { + await this.clearCandidate(); + } + return { ok: true }; + } + async closeAll() { + this.closed = true; + this.offerEpoch += 1; + await this.clearCandidate(); + } + async clearCandidate() { + const current = this.candidate; + if (current === void 0) return; + this.candidate = void 0; + await this.disposeAttempt(current, !current.activated); + } + async disposeAttempt(attempt, closeRtc) { + clearTimeout(attempt.expiryTimer); + attempt.unsubscribeClose(); + if (closeRtc) { + attempt.unsubscribeMessage(); + await attempt.rtc.close().catch(() => void 0); + } + } +}; + // packages/plugin/src/rpc-router.ts var wireRequestSchema = external_exports.object({ method: external_exports.string().min(1), params: external_exports.unknown() }).strict(); var emptyParamsSchema = external_exports.object({}).strict(); var historyConfigureSchema = external_exports.object({ compact: external_exports.boolean() }).strict(); +var compactionSessionSchema = external_exports.string().min(1).max(128); +var compactionSubmitSchema = external_exports.object({ + sessionId: compactionSessionSchema, + requestId: external_exports.string().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/), + budgetMs: external_exports.number().int().min(6e4).max(72e5).optional() +}).strict(); +var compactionOperationSchema = external_exports.object({ + sessionId: compactionSessionSchema, + operationId: external_exports.string().uuid() +}).strict(); var apiMethods = /* @__PURE__ */ new Set([ "harness.transport.describe", "remote.history.configure", @@ -99311,6 +100570,9 @@ var apiMethods = /* @__PURE__ */ new Set([ "harness.remote.transfer.close", "harness.remote.stream.open", "harness.remote.stream.close", + "harness.remote.compaction.submit", + "harness.remote.compaction.status", + "harness.remote.compaction.cancel", "loopback.call", "fileviewer.call", "codex.app.call", @@ -99332,10 +100594,17 @@ var apiMethods = /* @__PURE__ */ new Set([ "agent.acp.transfer.read", "agent.acp.transfer.close", "plugin.route.call", + "workspace.upload.lan.open", "workspace.upload.open", "workspace.upload.chunk", + "workspace.upload.chunk.binary", "workspace.upload.commit", - "workspace.upload.abort" + "workspace.upload.abort", + "remote.transport.upgrade.offer", + "remote.transport.upgrade.ice", + "remote.transport.upgrade.activate", + "remote.transport.upgrade.drain", + "remote.transport.upgrade.abort" ]); var HOST_CAPABILITIES = [ "harness.remote.v1", @@ -99348,7 +100617,7 @@ var HOST_CAPABILITIES = [ "agent.acp.transfer.v1" ]; var RpcRouter = class { - constructor(maxPending = 128, logger2, fileViewer, harnessRemote, capabilities = () => HOST_CAPABILITIES, codex, acp, loopback, workspaceTypes, pluginRoute, workspaceUpload) { + constructor(maxPending = 128, logger2, fileViewer, harnessRemote, capabilities = () => HOST_CAPABILITIES, codex, acp, loopback, workspaceTypes, pluginRoute, workspaceUpload, compaction, lanUpload, transportUpgrade) { this.maxPending = maxPending; this.logger = logger2; this.fileViewer = fileViewer; @@ -99360,6 +100629,9 @@ var RpcRouter = class { this.workspaceTypes = workspaceTypes; this.pluginRoute = pluginRoute; this.workspaceUpload = workspaceUpload; + this.compaction = compaction; + this.lanUpload = lanUpload; + this.transportUpgrade = transportUpgrade; } active = 0; async closePeerStreams() { @@ -99368,7 +100640,9 @@ var RpcRouter = class { this.harnessRemote?.closeAll(), this.codex?.closeAll(), this.acp?.closeAll(), - this.workspaceUpload?.closeAll() + this.workspaceUpload?.closeAll(), + this.lanUpload?.closeAll(), + this.transportUpgrade?.closeAll() ]); } async handle(message) { @@ -99416,12 +100690,15 @@ var RpcRouter = class { switch (method) { case "harness.transport.describe": { emptyParamsSchema.parse(params); - const hostCapabilities = await this.capabilities(); + const hostCapabilities = (await this.capabilities()).filter((capability) => capability !== BINARY_UPLOAD_CAPABILITY && capability !== LAN_UPLOAD_CAPABILITY); const remoteAvailable = hostCapabilities.includes("harness.remote.v1") || hostCapabilities.includes("harness.remote.v3"); const capabilities = [.../* @__PURE__ */ new Set([ ...hostCapabilities, "remote.history.compact.v1", - ...this.harnessRemote === void 0 || !remoteAvailable ? [] : ["harness.remote.stream.transfer.v1"] + ...this.harnessRemote === void 0 || !remoteAvailable ? [] : ["harness.remote.stream.transfer.v1"], + ...this.compaction === void 0 ? [] : [REMOTE_COMPACTION_CAPABILITY], + ...this.workspaceUpload === void 0 || !hostCapabilities.includes("workspace.upload.v1") ? [] : [BINARY_UPLOAD_CAPABILITY, ...this.lanUpload ? [LAN_UPLOAD_CAPABILITY] : []], + ...this.transportUpgrade === void 0 ? [] : [TRANSPORT_UPGRADE_CAPABILITY] ])]; let workspaceTypes; if (this.workspaceTypes !== void 0) { @@ -99443,6 +100720,18 @@ var RpcRouter = class { } return { compact }; } + case "harness.remote.compaction.submit": { + const route = this.requireCompaction(); + return route.operations.submit(compactionSubmitSchema.parse(params), route.owner); + } + case "harness.remote.compaction.status": { + const route = this.requireCompaction(); + return route.operations.status(compactionOperationSchema.parse(params), route.owner); + } + case "harness.remote.compaction.cancel": { + const route = this.requireCompaction(); + return route.operations.cancel(compactionOperationSchema.parse(params), route.owner); + } case "harness.remote.call": return this.requireRemoteGateway().call(params); case "harness.remote.transfer.open": @@ -99505,8 +100794,13 @@ var RpcRouter = class { return this.requireAcp().readTransfer(params); case "agent.acp.transfer.close": return this.requireAcp().closeTransfer(params); + case "workspace.upload.lan.open": { + if (!this.lanUpload) throw new RpcError("FEATURE_NOT_SUPPORTED", "LAN upload is unavailable on this Host."); + return this.lanUpload.open(params); + } case "workspace.upload.open": case "workspace.upload.chunk": + case "workspace.upload.chunk.binary": case "workspace.upload.commit": case "workspace.upload.abort": { if (!this.workspaceUpload) throw new RpcError("FEATURE_NOT_SUPPORTED", "Workspace upload is unavailable on this Host."); @@ -99514,10 +100808,26 @@ var RpcRouter = class { } case "plugin.route.call": return this.requirePluginRoute().call(params); + case "remote.transport.upgrade.offer": + return this.requireTransportUpgrade().offer(params); + case "remote.transport.upgrade.ice": + return this.requireTransportUpgrade().addIce(params); + case "remote.transport.upgrade.activate": + return this.requireTransportUpgrade().activate(params); + case "remote.transport.upgrade.drain": + return this.requireTransportUpgrade().drain(params); + case "remote.transport.upgrade.abort": + return this.requireTransportUpgrade().abort(params); default: throw new RpcError("METHOD_NOT_FOUND", "The requested method does not exist."); } } + requireCompaction() { + if (this.compaction === void 0) { + throw new RpcError("FEATURE_NOT_SUPPORTED", "This Host does not provide asynchronous Remote compaction."); + } + return this.compaction; + } requireRemoteGateway() { if (this.harnessRemote === void 0) { throw new RpcError("FEATURE_NOT_SUPPORTED", "This Harness version does not provide the Remote Gateway transport."); @@ -99542,6 +100852,12 @@ var RpcRouter = class { } return this.pluginRoute; } + requireTransportUpgrade() { + if (this.transportUpgrade === void 0) { + throw new RpcError("CAPABILITY_NOT_SUPPORTED", "In-band transport upgrade is unavailable on this Host."); + } + return this.transportUpgrade; + } }; function errorResponse2(requestId, error62) { const code = safeErrorCode(error62); @@ -99673,13 +100989,18 @@ function isOversizedListing(value) { return typeof value === "object" && value !== null && "entries" in value && Array.isArray(value.entries) && value.entries.length > MAX_REMOTE_DIRECTORY_ENTRIES; } +// packages/plugin/src/node-websocket.ts +function createNodeWebSocket(url2) { + return new wrapper_default(url2, { perMessageDeflate: false }); +} + // packages/plugin/src/server-connection.ts var DEFAULT_WEBRTC_NEGOTIATE_TIMEOUT_MS = 12e3; function advertisedTransportCapabilities(forceRelay, rtcAvailable) { return forceRelay || !rtcAvailable ? ["transport.relay", "transport.relay.attach"] : ["transport.lan", "transport.p2p", "transport.turn", "transport.relay", "transport.relay.attach"]; } var HostServerConnection = class { - constructor(config2, identity3, identities, api, connections, logger2, createWebSocket = (url2) => new WebSocket(url2), rtcFactoryProvider, hostCapabilities = () => [], harnessVersion) { + constructor(config2, identity3, identities, api, connections, logger2, createWebSocket = (url2) => createNodeWebSocket(url2), rtcFactoryProvider, hostCapabilities = () => [], harnessVersion) { this.config = config2; this.identity = identity3; this.identities = identities; @@ -100303,6 +101624,8 @@ var HostServerConnection = class { tunnel.lease?.stop(); try { await tunnel.rtc?.close(); + for (const stale of tunnel.drainingRtcs ?? []) await stale.close().catch(() => void 0); + tunnel.drainingRtcs?.clear(); } catch (error62) { this.logger.warn("remote connection RTC cleanup failed", { connectionId: shortId3(tunnel.connectionId), @@ -100312,7 +101635,66 @@ var HostServerConnection = class { tunnel.dataSocket?.close(); tunnel.dataSocket = void 0; tunnel.dataReady = false; - }, mode2); + }, mode2, this.rtcFactoryProvider === void 0 || this.config.forceRelay ? void 0 : (publishEvent) => new TransportUpgradeHost({ + connectionId: tunnel.connectionId, + peerDeviceId: tunnel.peer.deviceId, + currentMode: () => channel.mode, + outboundCounter: () => channel.outboundCounter, + loadRtcFactory: async () => { + if (this.rtcFactory === void 0 && this.rtcFactoryProvider !== void 0) { + this.rtcFactory = await this.rtcFactoryProvider().catch(() => void 0); + } + return this.rtcFactory; + }, + fetchIceServers: async (id6) => { + const servers = await this.api.turnCredentials(id6).catch(() => []); + return tunnel.preferredTransports.includes("turn") ? servers : stunOnlyIceServers(servers); + }, + onReceiveSequencedCiphertext: (counter, ciphertext, source) => { + if (this.tunnels.get(tunnel.connectionId) !== tunnel || tunnel.channel !== channel) return; + try { + channel.receive(counter, ciphertext, source); + } catch { + void this.dropTunnel(tunnel.connectionId, "SECURE_CHANNEL_FAILED"); + } + }, + adoptRtc: async (rtc, upgradedMode, attemptId) => { + const prevRtc = tunnel.rtc; + tunnel.rtc = rtc; + tunnel.transport = wireFromTransportTier(upgradedMode); + tunnel.transportMode = upgradedMode; + rtc.onClose(() => { + if (this.tunnels.get(tunnel.connectionId) === tunnel && tunnel.rtc === rtc) { + void this.dropTunnel(tunnel.connectionId, "CONNECTION_FAILED"); + } + }); + rtc.onError(() => { + if (this.tunnels.get(tunnel.connectionId) === tunnel && tunnel.rtc === rtc) { + void this.dropTunnel(tunnel.connectionId, "CONNECTION_FAILED"); + } + }); + if (prevRtc !== void 0 && prevRtc !== rtc) { + tunnel.drainingRtcs ??= /* @__PURE__ */ new Set(); + tunnel.drainingRtcs.add(prevRtc); + } + const endCounter = await channel.upgradeTransport( + upgradedMode, + (counter, ciphertext) => rtc.send(wrapUpgradedTransportFrame(counter, ciphertext)), + prevRtc, + attemptId, + (stale) => { + tunnel.drainingRtcs?.delete(stale); + void stale.close().catch(() => void 0); + } + ); + return endCounter; + }, + confirmPreviousLegDrain: (attemptId, clientPreviousLegEndCounter) => { + channel.confirmPreviousLegDrain(attemptId, clientPreviousLegEndCounter); + }, + publishEvent, + logger: this.logger + })); tunnel.channel = channel; await this.connections.accept(channel); this.sendControl("secure.handshake", { @@ -100747,6 +102129,8 @@ var HostServerConnection = class { tunnel.lease?.stop(); try { await tunnel.rtc?.close(); + for (const stale of tunnel.drainingRtcs ?? []) await stale.close().catch(() => void 0); + tunnel.drainingRtcs?.clear(); } catch (error62) { this.logger.warn("remote connection RTC cleanup failed", { connectionId: shortId3(connectionId), @@ -100772,12 +102156,12 @@ var HostServerConnection = class { } } waitBeforeRetry() { - const delay = Math.round(Math.random() * this.config.reconnect.maxDelayMs); + const delay2 = Math.round(Math.random() * this.config.reconnect.maxDelayMs); return new Promise((resolve10) => { const timer2 = setTimeout(() => { this.retryWake = void 0; resolve10(); - }, delay); + }, delay2); this.retryWake = () => { clearTimeout(timer2); resolve10(); @@ -100794,11 +102178,18 @@ var TERMINAL_AUTH_ERRORS = /* @__PURE__ */ new Set([ "TOKEN_EXPIRED" ]); var ServerNoiseChannel = class { - constructor(tunnel, transmit, onClose, mode2) { + constructor(tunnel, transmit, onClose, mode2, createTransportUpgradeHost, reorderOptions) { this.tunnel = tunnel; this.transmit = transmit; this.onClose = onClose; this.mode = mode2; + this.createTransportUpgradeHost = createTransportUpgradeHost; + this.reorderBuffer = new SequencedCiphertextReorderBuffer({ + ...reorderOptions, + onGapTimeout: () => { + void this.close("SECURE_CHANNEL_FAILED"); + } + }); this.security = { protocol: "Noise_IK_25519_ChaChaPoly_SHA256", connectionId: tunnel.connectionId, @@ -100812,12 +102203,57 @@ var ServerNoiseChannel = class { peerDeviceId; peerIdentityKey; mode; + createTransportUpgradeHost; + transmitSequenced; + reorderBuffer; + drainingLegs = /* @__PURE__ */ new Map(); handlers = /* @__PURE__ */ new Set(); incoming = new SecureMessageCodec(); outgoing = new SecureMessageCodec(); closed = false; /** Noise + SecureMessageCodec counters are not re-entrant; serialize sends. */ sendTail = Promise.resolve(); + get outboundCounter() { + return Number(this.tunnel.noise.sendingCounter()); + } + async upgradeTransport(nextMode, nextTransmit, previousRtc, attemptId = "", disposePreviousRtc) { + this.mode = nextMode; + this.transmitSequenced = nextTransmit; + const endCounter = Number(this.tunnel.noise.sendingCounter()); + if (previousRtc !== void 0 && disposePreviousRtc !== void 0 && previousRtc !== void 0) { + const existing = this.drainingLegs.get(previousRtc); + if (existing !== void 0) clearTimeout(existing.timer); + const timer2 = setTimeout(() => { + const leg = this.drainingLegs.get(previousRtc); + if (leg !== void 0) { + this.drainingLegs.delete(previousRtc); + leg.dispose(previousRtc); + } + }, DEFAULT_PREVIOUS_LEG_DRAIN_MS); + timer2.unref?.(); + this.drainingLegs.set(previousRtc, { + rtc: previousRtc, + attemptId, + endCounter: void 0, + timer: timer2, + dispose: disposePreviousRtc + }); + } + return endCounter; + } + confirmPreviousLegDrain(attemptId, clientPreviousLegEndCounter) { + if (this.closed) return; + const received = Number(this.tunnel.noise.receivingCounter()); + for (const [rtc, leg] of this.drainingLegs) { + if (leg.attemptId !== attemptId) continue; + leg.endCounter = clientPreviousLegEndCounter; + if (received >= clientPreviousLegEndCounter) { + clearTimeout(leg.timer); + this.drainingLegs.delete(rtc); + leg.dispose(rtc); + } + } + } async send(message) { const run = this.sendTail.then(() => this.sendNow(message)); this.sendTail = run.catch(() => void 0); @@ -100832,7 +102268,13 @@ var ServerNoiseChannel = class { if (this.closed) throw new Error("Secure channel closed"); for (const plaintext of this.outgoing.encode(encoded)) { if (this.closed) throw new Error("Secure channel closed"); - await this.transmit(this.tunnel.noise.encrypt(plaintext)); + const ciphertext = this.tunnel.noise.encrypt(plaintext); + const frameCounter = Number(this.tunnel.noise.sendingCounter() - 1n); + if (this.transmitSequenced !== void 0) { + await this.transmitSequenced(frameCounter, ciphertext); + } else { + await this.transmit(ciphertext); + } } }); } catch (error62) { @@ -100844,23 +102286,55 @@ var ServerNoiseChannel = class { this.handlers.add(handler); return () => this.handlers.delete(handler); } - receive(counter, ciphertext) { - if (this.tunnel.lease && !this.tunnel.lease.valid()) return; - if (this.closed) return; - if (counter !== void 0) { - const expected = Number(this.tunnel.noise.receivingCounter()); - if (!Number.isSafeInteger(counter) || counter !== expected) { - throw new ControlConnectionError("INVALID_MESSAGE", "Relay counter is duplicated or out of order."); + deliverDecrypted(ciphertext) { + const plaintext = this.incoming.decode(this.tunnel.noise.decrypt(ciphertext)); + const currentReceiving = Number(this.tunnel.noise.receivingCounter()); + this.reorderBuffer.onExpectedAdvanced(currentReceiving); + for (const [rtc, leg] of this.drainingLegs) { + if (leg.endCounter !== void 0 && currentReceiving >= leg.endCounter) { + clearTimeout(leg.timer); + this.drainingLegs.delete(rtc); + leg.dispose(rtc); } } - const plaintext = this.incoming.decode(this.tunnel.noise.decrypt(ciphertext)); if (plaintext === void 0) return; const message = decodeMessage(plaintext); for (const handler of this.handlers) handler(message); } + receive(counter, ciphertext, _source) { + if (this.tunnel.lease && !this.tunnel.lease.valid()) return; + if (this.closed) return; + if (counter !== void 0) { + const expected = Number(this.tunnel.noise.receivingCounter()); + if (!Number.isSafeInteger(counter) || counter < expected) { + throw new ControlConnectionError("INVALID_MESSAGE", "Relay counter is duplicated or out of order."); + } + if (counter > expected) { + try { + this.reorderBuffer.push(counter, expected, ciphertext); + } catch (error62) { + throw new ControlConnectionError("INVALID_MESSAGE", error62 instanceof Error ? error62.message : "Reorder buffer overflow."); + } + return; + } + } + this.deliverDecrypted(ciphertext); + while (!this.closed) { + const nextExpected = Number(this.tunnel.noise.receivingCounter()); + const buffered = this.reorderBuffer.takeNext(nextExpected); + if (buffered === void 0) break; + this.deliverDecrypted(buffered); + } + } async close(_code) { if (this.closed) return; this.closed = true; + this.reorderBuffer.clear(); + for (const [rtc, leg] of this.drainingLegs) { + clearTimeout(leg.timer); + leg.dispose(rtc); + } + this.drainingLegs.clear(); this.handlers.clear(); this.incoming.reset(); this.outgoing.reset(); @@ -101003,24 +102477,24 @@ function closeCode(code) { // packages/plugin/src/harness-remote-bridge.ts import { randomUUID as randomUUID17 } from "node:crypto"; -import { homedir as homedir9 } from "node:os"; -import { lstat as lstat4, realpath as realpath7, stat as stat8 } from "node:fs/promises"; -import { dirname as dirname7, isAbsolute as isAbsolute10, join as join16, parse as parse4, relative as relative5, resolve as resolve9, sep as sep3 } from "node:path"; +import { homedir as homedir10 } from "node:os"; +import { lstat as lstat5, realpath as realpath7, stat as stat9 } from "node:fs/promises"; +import { dirname as dirname8, isAbsolute as isAbsolute10, join as join17, parse as parse4, relative as relative5, resolve as resolve9, sep as sep3 } from "node:path"; // packages/plugin/src/remote-directory-browser.ts -import { mkdir as mkdir4, readdir as readdir6, stat as stat7 } from "node:fs/promises"; -import { homedir as homedir8, platform as platform2 } from "node:os"; -import { basename as basename8, dirname as dirname6, isAbsolute as isAbsolute9, parse as parse3, resolve as resolve8 } from "node:path"; +import { mkdir as mkdir5, readdir as readdir6, stat as stat8 } from "node:fs/promises"; +import { homedir as homedir9, platform as platform2 } from "node:os"; +import { basename as basename8, dirname as dirname7, isAbsolute as isAbsolute9, parse as parse3, resolve as resolve8 } from "node:path"; var MAX_ENTRIES = 500; async function ensureHostWorkspaceDirectory(path) { if (typeof path !== "string" || path.trim() === "" || path.includes("\0") || !isAbsolute9(path) || resolve8(path) === parse3(path).root) { throw new RpcError("INVALID_MESSAGE", "Workspace path must be an absolute, non-root directory path."); } - await mkdir4(path, { recursive: true }); + await mkdir5(path, { recursive: true }); } async function listRemoteDirectory(path, signal) { signal?.throwIfAborted(); - const home = resolve8(homedir8()); + const home = resolve8(homedir9()); const target3 = path === void 0 || path.trim() === "" ? home : resolve8(path); if (!isAbsolute9(target3)) throw new Error("The remote directory path must be absolute."); const rows = await readdir6(target3, { withFileTypes: true }); @@ -101029,7 +102503,7 @@ async function listRemoteDirectory(path, signal) { signal?.throwIfAborted(); const child = resolve8(target3, row.name); let directory = row.isDirectory(); - if (!directory && row.isSymbolicLink()) directory = await stat7(child).then((value) => value.isDirectory()).catch(() => false); + if (!directory && row.isSymbolicLink()) directory = await stat8(child).then((value) => value.isDirectory()).catch(() => false); if (!directory) continue; directories.push({ name: row.name, path: child, hidden: platform2() !== "win32" && row.name.startsWith(".") }); } @@ -101049,7 +102523,7 @@ function crumbs(path) { let current = path; while (current !== root2) { segments.unshift(basename8(current)); - current = dirname6(current); + current = dirname7(current); } for (const segment of segments) { current = resolve8(current, segment); @@ -101072,10 +102546,10 @@ var commandExecuteArgsSchema = external_exports.object({ agentId: external_exports.string().min(1).max(128), line: external_exports.string().min(1).max(2048), // dsh-commands <= 0.1.2 calls this field `images`; dsh-commands 0.1.5 - // renamed it to `submittedAttachments`. Only empty arrays are exposed by - // the Remote bridge; command attachments are deliberately out of scope. + // renamed it to `submittedAttachments`. Current Hosts resolve opaque file + // receipts in the receiving Session; legacy image arguments stay empty. images: external_exports.array(external_exports.never()).length(0).optional(), - submittedAttachments: external_exports.array(external_exports.never()).length(0).optional() + submittedAttachments: external_exports.array(external_exports.object({ type: external_exports.literal("file"), receiptId: external_exports.string().min(1).max(512) }).strict()).max(32).optional() }).strict().superRefine((value, context) => { if (value.images !== void 0 && value.submittedAttachments !== void 0) { context.addIssue({ @@ -101154,6 +102628,7 @@ var HARNESS_REMOTE_ALLOWLIST = [ "schedule/deliveryLimits", "schedule/edit", "schedule/run", + "fileUploads/upload", "session/attachment", "session/cancel", "session/canOpenWorkspacePath", @@ -101253,7 +102728,7 @@ var PUBLIC_SCHEDULE_ERRORS = { }; var allowedEndpoints = new Set(HARNESS_REMOTE_ALLOWLIST); var HarnessRemoteBridge = class { - constructor(gateway, publish, logger2, harnessVersion, terminal = new TerminalPolicy(() => false, "", /* @__PURE__ */ new Map()), codexWorkspace, resolveWorkspaceRoot, schedule) { + constructor(gateway, publish, logger2, harnessVersion, terminal = new TerminalPolicy(() => false, "", /* @__PURE__ */ new Map()), codexWorkspace, resolveWorkspaceRoot, schedule, uploadAttachment) { this.gateway = gateway; this.publish = publish; this.logger = logger2; @@ -101262,6 +102737,7 @@ var HarnessRemoteBridge = class { this.codexWorkspace = codexWorkspace; this.resolveWorkspaceRoot = resolveWorkspaceRoot; this.schedule = schedule; + this.uploadAttachment = uploadAttachment; this.terminalCarrier = usesDuplexTerminal(harnessVersion) ? new TerminalCarrierCompat(gateway) : void 0; } compactHistoryEnabled = false; @@ -101272,6 +102748,10 @@ var HarnessRemoteBridge = class { terminalCarrier; async call(input4) { const params = callSchema3.parse(input4); + if ((params.endpoint === "remoteUploads/upload" || params.endpoint === "remoteImages/upload") && this.uploadAttachment !== void 0) { + const payload = external_exports.object({ args: external_exports.unknown() }).strict().parse(params.payload); + return { ok: true, value: await this.uploadAttachment(payload.args) }; + } this.assertAllowed(params.endpoint); if (TERMINAL_STREAMS.has(params.endpoint)) throw new RpcError("METHOD_NOT_ALLOWED", "Use a stream for this terminal endpoint."); if (["settings/update", "settings/replace", "settings/mutate"].includes(params.endpoint)) { @@ -101532,7 +103012,7 @@ var HarnessRemoteBridge = class { first2 = await iterator.next(); } catch (error62) { if (!await this.canUseIdleRemoteEvents(error62, signal)) throw error62; - yield { type: "ready", clientId: randomUUID17(), host: { home: homedir9() } }; + yield { type: "ready", clientId: randomUUID17(), host: { home: homedir10() } }; await new Promise((resolve10) => { if (signal.aborted) { resolve10(); @@ -101764,18 +103244,18 @@ var HarnessRemoteBridge = class { if (baseSegments.some((segment) => segment === "..")) { throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The requested workspace path is outside the workspace.", "outside-root"); } - const safeBaseRel = await this.verifyWorkspacePathContainment(sessionWorkspace.root, rawBaseFile, endpoint); + const safeBaseRel = await this.verifyWorkspacePathContainment(sessionWorkspace.root, rawBaseFile, endpoint, sessionWorkspace.cwd); const baseCandidate = resolve9(sessionWorkspace.root, safeBaseRel); - const baseDir = dirname7(baseCandidate); + const baseDir = dirname8(baseCandidate); const targetCandidate = resolve9(baseDir, path); - safeRel = await this.verifyWorkspacePathContainment(sessionWorkspace.root, targetCandidate, endpoint); + safeRel = await this.verifyWorkspacePathContainment(sessionWorkspace.root, targetCandidate, endpoint, sessionWorkspace.cwd); } else { const path = typeof args.path === "string" ? args.path : "."; const pathSegments = process.platform === "win32" ? path.replaceAll("\\", "/").split("/") : path.split("/"); if (pathSegments.some((segment) => segment === "..")) { throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The requested workspace path is outside the workspace.", "outside-root"); } - safeRel = await this.verifyWorkspacePathContainment(sessionWorkspace.root, path, endpoint); + safeRel = await this.verifyWorkspacePathContainment(sessionWorkspace.root, path, endpoint, sessionWorkspace.cwd); } let finalArgs = isRecord23(rootPayload.args) ? { ...rootPayload.args, path: safeRel } : { ...rootPayload, path: safeRel }; if (isRecord23(finalArgs.options)) { @@ -101816,7 +103296,7 @@ var HarnessRemoteBridge = class { } try { const root2 = await realpath7(cwd2); - const info = await stat8(root2); + const info = await stat9(root2); if (!info.isDirectory()) { throw workspaceFileFailure("WORKSPACE_UNAVAILABLE", "The workspace is unavailable.", "root-invalid"); } @@ -101832,8 +103312,10 @@ var HarnessRemoteBridge = class { * must not turn an in-root file into a denial. The boundary itself is * unchanged: the canonical target must stay inside the canonical root. */ - async verifyWorkspacePathContainment(root2, path, endpoint) { - const candidate = isAbsolute10(path) ? resolve9(path) : resolve9(root2, path); + async verifyWorkspacePathContainment(root2, path, endpoint, cwd2 = root2) { + const supplied = isAbsolute10(path) ? resolve9(path) : resolve9(root2, path); + const cwdRelative = relative5(resolve9(cwd2), supplied); + const candidate = isAbsolute10(path) && !isPathOutside(cwdRelative) ? resolve9(root2, cwdRelative) : supplied; if (process.platform === "win32") { const rootDrive = parse4(root2).root.toLowerCase(); const candDrive = parse4(candidate).root.toLowerCase(); @@ -101845,7 +103327,7 @@ var HarnessRemoteBridge = class { throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The requested workspace path is outside the workspace.", "outside-root"); } try { - const rootLstat = await lstat4(root2); + const rootLstat = await lstat5(root2); if (rootLstat.isSymbolicLink() || !rootLstat.isDirectory()) { throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The workspace root is invalid or a symlink.", "root-invalid"); } @@ -101853,11 +103335,11 @@ var HarnessRemoteBridge = class { const parts = rel.split(sep3).filter((p) => p.length > 0 && p !== "."); let currentPath = root2; for (let i = 0; i < parts.length - 1; i++) { - currentPath = join16(currentPath, parts[i]); + currentPath = join17(currentPath, parts[i]); if (isPathOutside(relative5(root2, currentPath))) { throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The requested workspace path is outside the workspace.", "outside-root"); } - const dirLstat = await lstat4(currentPath); + const dirLstat = await lstat5(currentPath); if (dirLstat.isSymbolicLink()) { throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "An ancestor directory is invalid or a symlink.", "symlink"); } @@ -101865,7 +103347,7 @@ var HarnessRemoteBridge = class { throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "An ancestor directory is invalid or a symlink.", "not-regular-file"); } } - const targetLstat = await lstat4(candidate); + const targetLstat = await lstat5(candidate); if (targetLstat.isSymbolicLink()) { throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The requested workspace path is not a regular file.", "symlink"); } @@ -101881,7 +103363,7 @@ var HarnessRemoteBridge = class { if (isPathOutside(canonicalRel)) { throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The requested workspace path is outside the workspace.", "outside-root"); } - const info = await stat8(canonical); + const info = await stat9(canonical); if (endpoint !== "workspaceFiles/stat" && !info.isFile()) { throw workspaceFileFailure("WORKSPACE_PATH_DENIED", "The requested workspace path is not a regular file.", "not-regular-file"); } @@ -102057,6 +103539,9 @@ function requiresWorkspaceChangePath(version2) { } async function dispatchCommandForHost(gateway, payload, signal, harnessVersion) { const parsed = commandExecutePayloadSchema.parse(payload); + if (harnessSessionGeneration(harnessVersion) !== "v3" && (parsed.args.submittedAttachments?.length ?? 0) > 0) { + throw new RpcError("METHOD_NOT_ALLOWED", "This Host does not support command file receipts."); + } const legacyPayload = { args: { agentId: parsed.args.agentId, @@ -102277,6 +103762,346 @@ function remoteOwnedBundleRow(row, plugin) { return !plugin && (!Array.isArray(row.rows) || row.rows.some((value) => !isRecord23(value) || remoteModule(value.moduleName)) || Array.isArray(row.overrides) && row.overrides.some((value) => remoteModule(value))); } +// packages/plugin/src/remote-compaction-operations.ts +import { randomUUID as randomUUID18 } from "node:crypto"; +var MIN_BUDGET_MS = 6e4; +var MAX_BUDGET_MS = 72e5; +var DEFAULT_BUDGET_MS = 18e5; +var RETENTION_MS = 6e5; +var CANCEL_SETTLE_MS = 15e3; +var MAX_OPERATIONS = 32; +function requestIndexKey(ownerDeviceId, sessionId, requestId) { + return `${ownerDeviceId}\0${sessionId}\0${requestId}`; +} +function isRecord24(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function commandIdOf(result) { + if (result?.ok !== true || !isRecord24(result.value)) return void 0; + return typeof result.value.commandId === "string" ? result.value.commandId : void 0; +} +var RemoteCompactionOperations = class { + constructor(runner, options = {}) { + this.runner = runner; + this.confirm = options.confirm; + this.logger = options.logger; + this.now = options.now ?? Date.now; + } + operations = /* @__PURE__ */ new Map(); + requestIndex = /* @__PURE__ */ new Map(); + confirm; + logger; + now; + closed = false; + submit(params, owner) { + if (this.closed) throw new RpcError("HARNESS_UNAVAILABLE", "The Remote Host is shutting down."); + this.prune(); + const key = requestIndexKey(owner.deviceId, params.sessionId, params.requestId); + const existing = this.requestIndex.get(key); + if (existing !== void 0) { + const operation2 = this.operations.get(existing); + if (operation2 !== void 0) return { operationId: operation2.operationId, state: operation2.state }; + this.requestIndex.delete(key); + } + for (const operation2 of this.operations.values()) { + if (operation2.sessionId === params.sessionId && operation2.finishedAt === void 0) { + throw new RpcError("AGENT_BUSY", "A compaction operation is already running for this Session."); + } + } + if (this.operations.size >= MAX_OPERATIONS) { + throw new RpcError("RATE_LIMITED", "Too many Remote compaction operations are tracked by this Host.", void 0, true); + } + const budgetMs = clampBudget(params.budgetMs); + const operation = this.createOperation(params, owner, budgetMs); + this.operations.set(operation.operationId, operation); + this.requestIndex.set(key, operation.operationId); + this.logger?.info("remote compaction accepted", { + operationId: operation.operationId, + sessionId: operation.sessionId, + budgetMs + }); + void this.run(operation); + return { operationId: operation.operationId, state: "accepted" }; + } + async status(params, owner) { + this.prune(); + const operation = this.find(params, owner); + if (operation === void 0) return this.interrupted(params); + if (operation.finishedAt === void 0 && operation.commandSettledFlag && (operation.state === "cancelling" || operation.state === "unconfirmed")) { + await this.reconcile(operation); + } + return this.view(operation); + } + async cancel(params, owner) { + this.prune(); + const operation = this.find(params, owner); + if (operation === void 0) return this.interrupted(params); + if (operation.finishedAt !== void 0) return this.view(operation); + if (!operation.cancelled) { + operation.cancelled = true; + operation.state = "cancelling"; + operation.controller.abort(new Error("Remote compaction cancelled by the client.")); + this.logger?.info("remote compaction cancellation requested", { operationId: operation.operationId }); + } + await Promise.race([operation.commandSettled, delay(CANCEL_SETTLE_MS)]); + if (operation.commandSettledFlag) await this.reconcile(operation); + return this.view(operation); + } + /** Host shutdown: stop work and report every unfinished operation as interrupted. */ + closeAll() { + this.closed = true; + for (const operation of this.operations.values()) { + if (operation.finishedAt !== void 0) continue; + this.settle(operation, "interrupted", "The Remote Host shut down before the compaction finished."); + operation.controller.abort(new Error("Remote Host shut down.")); + } + } + createOperation(params, owner, budgetMs) { + let resolveCommandSettled = () => { + }; + const commandSettled = new Promise((resolve10) => { + resolveCommandSettled = resolve10; + }); + return { + operationId: randomUUID18(), + requestId: params.requestId, + sessionId: params.sessionId, + ownerDeviceId: owner.deviceId, + budgetMs, + acceptedAt: this.now(), + controller: new AbortController(), + commandSettled, + resolveCommandSettled, + state: "accepted", + cancelled: false, + timedOut: false, + commandSettledFlag: false, + confirmation: "pending" + }; + } + async run(operation) { + operation.state = "running"; + operation.startedAt = this.now(); + operation.timer = setTimeout(() => { + operation.timedOut = true; + operation.controller.abort(new Error("Remote compaction exceeded its budget.")); + }, operation.budgetMs); + let result; + let thrown; + try { + result = await this.runner(operation.sessionId, operation.controller.signal); + } catch (error62) { + thrown = error62; + } finally { + if (operation.timer !== void 0) { + clearTimeout(operation.timer); + operation.timer = void 0; + } + operation.commandSettledFlag = true; + operation.resolveCommandSettled(); + } + operation.commandId = commandIdOf(result); + if (result?.ok === true && isCommandSuccess(result)) { + this.settle(operation, "succeeded", commandText2(result) ?? void 0); + return; + } + if (operation.cancelled || operation.timedOut) { + await this.reconcile(operation); + return; + } + this.settle(operation, "failed", this.commandFailureMessage(operation, result, thrown)); + } + /** + * Inspect the compaction lifecycle for a settled command call. A confirmed + * `compaction/end` with an error marks the run stopped; a confirmed end + * without error means it committed, but the final persistence result is no + * longer observable after the abort. + */ + async reconcile(operation) { + if (operation.finishedAt !== void 0) return; + if (!operation.commandSettledFlag) return; + if (this.confirm === void 0) { + operation.state = "unconfirmed"; + operation.message = "The Host cannot observe the compaction lifecycle for this run."; + operation.finishedAt = this.now(); + return; + } + let confirmation; + try { + confirmation = await this.confirm(operation.sessionId, operation.acceptedAt, operation.commandId); + } catch { + confirmation = { kind: "unknown" }; + } + this.logger?.info("remote compaction confirmation", { + operationId: operation.operationId, + kind: confirmation.kind, + ...confirmation.kind === "finished" ? { failed: confirmation.error !== void 0 } : {} + }); + if (confirmation.kind === "finished") { + operation.confirmation = "finished"; + operation.confirmError = confirmation.error; + if (confirmation.error !== void 0) { + this.settle( + operation, + operation.cancelled ? "cancelled" : "failed", + operation.cancelled ? "Compaction cancelled and the Host confirmed the run stopped." : sanitizeMessage(confirmation.error) + ); + return; + } + this.settle( + operation, + "unconfirmed", + "Compaction committed despite the stop request; the final persistence result could not be confirmed." + ); + return; + } + if (confirmation.kind === "not-yet" || confirmation.kind === "unknown") { + operation.confirmation = "unknown"; + operation.state = "cancelling"; + operation.message = operation.cancelled ? "Cancellation was requested; the Host is still waiting for the compaction to finish." : "The compaction budget expired; the Host is still waiting for the compaction to finish."; + return; + } + } + commandFailureMessage(operation, result, thrown) { + if (result?.ok === true) { + const text = commandText2(result); + return text === void 0 ? "The Host rejected the compaction command." : sanitizeMessage(text); + } + if (result !== void 0 && result.ok === false) return sanitizeMessage(result.error.message); + if (operation.timedOut) return `Compaction exceeded its ${operation.budgetMs}ms budget.`; + if (thrown instanceof RpcError) return sanitizeMessage(thrown.message); + this.logger?.warn("remote compaction failed", { + operationId: operation.operationId, + reason: thrown instanceof Error ? thrown.name : "unknown" + }); + return "The Host failed to run the compaction command."; + } + settle(operation, state2, message) { + if (operation.finishedAt !== void 0) return; + if (operation.timer !== void 0) { + clearTimeout(operation.timer); + operation.timer = void 0; + } + operation.state = state2; + operation.finishedAt = this.now(); + if (message !== void 0) operation.message = message; + this.logger?.info("remote compaction settled", { + operationId: operation.operationId, + state: state2, + durationMs: operation.startedAt === void 0 ? 0 : operation.finishedAt - operation.startedAt + }); + this.prune(); + } + find(params, owner) { + const operation = this.operations.get(params.operationId); + if (operation === void 0) return void 0; + if (operation.ownerDeviceId !== owner.deviceId) { + throw new RpcError("PERMISSION_DENIED", "This compaction operation belongs to another device."); + } + if (operation.sessionId !== params.sessionId) { + throw new RpcError("INVALID_MESSAGE", "The compaction operation does not belong to this Session."); + } + return operation; + } + view(operation) { + return { + operationId: operation.operationId, + sessionId: operation.sessionId, + state: operation.state, + acceptedAt: operation.acceptedAt, + ...operation.startedAt === void 0 ? {} : { startedAt: operation.startedAt }, + ...operation.finishedAt === void 0 ? {} : { finishedAt: operation.finishedAt }, + ...operation.message === void 0 ? {} : { message: operation.message } + }; + } + interrupted(params) { + return { + operationId: params.operationId, + sessionId: params.sessionId, + state: "interrupted", + message: "The Host no longer tracks this operation; it may have restarted." + }; + } + /** Drop settled operations past retention; unfinished ones are never pruned. */ + prune() { + const cutoff = this.now() - RETENTION_MS; + for (const [operationId2, operation] of this.operations) { + if (operation.finishedAt === void 0 || operation.finishedAt > cutoff) continue; + this.operations.delete(operationId2); + this.requestIndex.delete(requestIndexKey(operation.ownerDeviceId, operation.sessionId, operation.requestId)); + } + } +}; +function clampBudget(value) { + if (value === void 0) return DEFAULT_BUDGET_MS; + if (!Number.isFinite(value) || !Number.isSafeInteger(value)) { + throw new RpcError("INVALID_MESSAGE", "budgetMs must be a safe integer."); + } + return Math.min(Math.max(value, MIN_BUDGET_MS), MAX_BUDGET_MS); +} +function isCommandSuccess(result) { + if (result.ok !== true || !isRecord24(result.value)) return false; + const command = isRecord24(result.value.result) ? result.value.result : void 0; + return command?.kind === "success"; +} +function commandText2(result) { + if (result.ok !== true || !isRecord24(result.value)) return void 0; + const command = isRecord24(result.value.result) ? result.value.result : void 0; + return typeof command?.text === "string" && command.text.trim() !== "" ? command.text : void 0; +} +function sanitizeMessage(message) { + return message.length <= 2e3 ? message : `${message.slice(0, 2e3)}\u2026`; +} +function delay(ms) { + return new Promise((resolve10) => setTimeout(resolve10, ms)); +} +function readCompactionConfirmation(result, acceptedAt, commandId) { + if (result.ok !== true || !isRecord24(result.value)) return { kind: "unknown" }; + const records = Array.isArray(result.value.records) ? result.value.records : []; + const legacy = Array.isArray(result.value.events) ? result.value.events : []; + const events = []; + for (const record11 of [...records, ...legacy]) { + const event = isRecord24(record11) && isRecord24(record11.event) ? record11.event : record11; + if (isRecord24(event) && typeof event.type === "string") events.push(event); + } + if (events.length === 0) return { kind: "unknown" }; + const resolvedCommandId = commandId ?? latestCompactCommandId(events, acceptedAt); + if (resolvedCommandId === void 0) return { kind: "not-yet" }; + const end = [...events].reverse().find((event) => { + if (event.type !== "compaction/end") return false; + const data3 = isRecord24(event.data) ? event.data : void 0; + return data3?.sourceCommandId === resolvedCommandId; + }); + if (end === void 0) return { kind: "not-yet" }; + const data2 = isRecord24(end.data) ? end.data : {}; + const error62 = data2.error === void 0 ? void 0 : errorText(data2.error); + return error62 === void 0 ? { kind: "finished" } : { kind: "finished", error: error62 }; +} +function latestCompactCommandId(events, acceptedAt) { + for (const event of [...events].reverse()) { + if (event.type !== "command/run") continue; + const data2 = isRecord24(event.data) ? event.data : void 0; + if (data2?.name !== "compact" || typeof data2.commandId !== "string") continue; + const time3 = typeof event.time === "number" ? event.time : 0; + if (time3 !== 0 && time3 < acceptedAt - 5e3) continue; + return data2.commandId; + } + return void 0; +} +function errorText(error62) { + if (typeof error62 === "string") return sanitizeMessage(error62); + if (isRecord24(error62)) { + const message = error62.message ?? error62.error ?? error62.reason; + if (typeof message === "string" && message.trim() !== "") return sanitizeMessage(message); + try { + return sanitizeMessage(JSON.stringify(error62)); + } catch { + return "The compaction failed."; + } + } + return "The compaction failed."; +} + // packages/plugin/src/service.ts import { execFileSync as execFileSync2 } from "node:child_process"; import { existsSync as existsSync5 } from "node:fs"; @@ -102315,8 +104140,42 @@ var HostPluginRuntime = class { this.loopbackPorts = [...config2.loopback.ports]; this.codex = new CodexRemoteDomain(config2.codex, logger2); this.acp = new AcpRemoteGateway(config2.acp ?? { enabled: false, backends: [] }, logger2, void 0, void 0, () => this.terminalEnabled, this.terminalSpawner); + this.compactionOperations = new RemoteCompactionOperations(async (sessionId, signal) => { + const gateway = this.localGateway?.createPeer?.() ?? this.localGateway; + if (gateway === void 0) throw new RpcError("HARNESS_UNAVAILABLE", "The Host Harness gateway is unavailable."); + try { + return await dispatchCommandForHost( + gateway, + { args: { agentId: sessionId, line: "/compact" } }, + signal, + this.harnessVersion + ); + } finally { + await gateway.dispose?.(); + } + }, { + logger: logger2, + // `commands/execute` stops waiting on abort while the compaction handler + // keeps running, so lifecycle confirmation comes from the Session log. + confirm: async (sessionId, acceptedAt, commandId) => { + const gateway = this.localGateway?.createPeer?.() ?? this.localGateway; + if (gateway === void 0) return { kind: "unknown" }; + try { + const result = await gateway.dispatch("session/events", { + args: { request: { address: { kind: "session", sessionId }, maxMessages: 128 } } + }, AbortSignal.timeout(5e3)); + return readCompactionConfirmation(result, acceptedAt, commandId); + } catch { + return { kind: "unknown" }; + } finally { + await gateway.dispose?.(); + } + } + }); this.connections = new ConnectionController(this.identities, (context, send) => { const peerGateway = this.localGateway?.createPeer?.() ?? this.localGateway; + const uploadDispatcher = this.pluginRoutes?.(peerGateway?.peer); + const uploadBridge = uploadDispatcher === void 0 ? void 0 : new PluginRouteBridge(uploadDispatcher, this.logger); const harnessRemote = peerGateway?.supportsCarrier === true ? new HarnessRemoteBridge( peerGateway, (event, data2) => send(createEvent(event, data2)), @@ -102335,7 +104194,8 @@ var HostPluginRuntime = class { (threadId) => this.codex.resolveThreadWorkspace(context.connectionId, threadId), (sessionId) => this.acp.resolveUploadWorkspace(context.connectionId, sessionId) ), - this.schedule + this.schedule, + uploadBridge === void 0 ? void 0 : (body) => uploadBridge.call({ route: "api/session/uploadFileBinary", body }, true) ) : void 0; const fileViewer = new RemoteFileViewerBridge( () => this.fileViewerHost?.(), @@ -102351,6 +104211,18 @@ var HostPluginRuntime = class { ); const dispatcher = this.pluginRoutes?.(peerGateway?.peer); const pluginRoute = dispatcher === void 0 ? void 0 : new PluginRouteBridge(dispatcher, this.logger); + const workspaceUpload = new WorkspaceUploadHost(workspaceUploadRootResolver( + peerGateway, + () => harnessSessionGeneration(this.harnessVersion) === "v3", + (threadId) => this.codex.resolveThreadWorkspace(context.connectionId, threadId), + (sessionId) => this.acp.resolveUploadWorkspace(context.connectionId, sessionId) + ), void 0, context.transportMode); + const lanUpload = context.peerIdentityKey && context.transportMode ? new LanUploadHost(workspaceUpload, { + connectionId: context.connectionId, + peerIdentityKey: context.peerIdentityKey, + identity: () => this.currentIdentity(), + mode: context.transportMode + }) : void 0; return new RpcRouter( void 0, this.logger, @@ -102363,12 +104235,13 @@ var HostPluginRuntime = class { this.createLoopbackHost(), () => this.hostWorkspaceTypes(), pluginRoute, - new WorkspaceUploadHost(workspaceUploadRootResolver( - peerGateway, - () => harnessSessionGeneration(this.harnessVersion) === "v3", - (threadId) => this.codex.resolveThreadWorkspace(context.connectionId, threadId), - (sessionId) => this.acp.resolveUploadWorkspace(context.connectionId, sessionId) - ), void 0, context.transportMode) + workspaceUpload, + { + operations: this.compactionOperations, + owner: { deviceId: context.peerDeviceId, connectionId: context.connectionId } + }, + lanUpload, + context.createTransportUpgradeHost?.(send) ); }, this.logger); if (config2.serverUrl !== void 0) { @@ -102389,6 +104262,11 @@ var HostPluginRuntime = class { codex; acp; codexWorkspaceState = new WorkspaceBridgeState((key) => TerminalPolicy.releaseOwner(this.terminalOwners, key)); + /** + * Host-wide async compaction registry. It deliberately lives on the runtime, + * not on a connection: disconnecting a client must not abort a compaction. + */ + compactionOperations; localCodexPeer; localCodexPublish = async () => void 0; localAcpPeer; @@ -102667,6 +104545,7 @@ var HostPluginRuntime = class { this.pairing?.close(); this.serverApi?.close(); await this.serverConnection?.stop(); + this.compactionOperations.closeAll(); await this.connections.close(); await this.localCodexPeer?.closeAll(); this.localCodexPeer = void 0; @@ -102743,11 +104622,19 @@ var HostPluginRuntime = class { if (gateway?.supportsCarrier !== true) return capabilities; let result; try { - result = await gateway.dispatch("session/list", { args: { _request: {} } }, AbortSignal.timeout(5e3)); + result = await gateway.dispatch("session/list", { args: { __remoteCapabilityProbe: true } }, AbortSignal.timeout(5e3)); } catch { throw new RpcError("CONNECTION_FAILED", "Cannot verify the Host Session API.", void 0, true); } - if (result.ok) return capabilities; + if (!result.ok && result.error.code === "gateway/arguments-invalid") { + if (isLiveSessionEventsHarnessVersion(this.harnessVersion) && await this.probeLiveSessionEvents(gateway)) { + capabilities.push(REMOTE_SESSION_EVENTS_CAPABILITY); + } + return capabilities; + } + if (result.ok) { + throw new RpcError("CONNECTION_FAILED", "The Host Gateway did not reject the Session API probe.", void 0, true); + } if (result.error.code === "gateway/service-unavailable") { throw new RpcError("CONNECTION_FAILED", "The Host Session API is not ready.", void 0, true); } @@ -102760,6 +104647,23 @@ var HostPluginRuntime = class { } return capabilities.filter((value) => !value.startsWith("harness.remote.") && value !== "harness.terminal.v1"); } + async probeLiveSessionEvents(gateway) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 2e3); + let iterator; + try { + const stream = await gateway.open("$events", { args: {} }, controller.signal); + iterator = stream[Symbol.asyncIterator](); + const first2 = await iterator.next(); + return !first2.done && typeof first2.value === "object" && first2.value !== null && !Array.isArray(first2.value) && first2.value.type === "ready"; + } catch { + return false; + } finally { + clearTimeout(timeout); + controller.abort(); + await iterator?.return?.().catch(() => void 0); + } + } hostWorkspaceTypes() { const types22 = []; if (this.codex.isAvailable()) { @@ -102842,12 +104746,20 @@ function createPluginRouteDispatcher(readConnection, readPort, peer) { signal.throwIfAborted(); const connection = readConnection(); const handler = connection?.createSharedFetchHandler?.("/api"); + const upload = route === "api/session/uploadFileBinary" ? body.payload : void 0; + const query = upload === void 0 ? "" : `?${new URLSearchParams({ + sessionId: upload.sessionId, + ...upload.mediaType === void 0 ? {} : { mediaType: upload.mediaType }, + ...upload.name === void 0 ? {} : { name: upload.name } + })}`; + const contentType2 = upload === void 0 ? "application/json" : "application/octet-stream"; + const requestBody = upload === void 0 ? JSON.stringify(body ?? {}) : Buffer.from(upload.data, "base64"); let response; if (handler !== void 0) { - response = await withSignal(handler.fetch(new Request(`http://127.0.0.1/${route}`, { + response = await withSignal(handler.fetch(new Request(`http://127.0.0.1/${route}${query}`, { method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(body ?? {}), + headers: { "content-type": contentType2 }, + body: requestBody, signal }), peer), signal); } else { @@ -102861,10 +104773,10 @@ function createPluginRouteDispatcher(readConnection, readPort, peer) { const setCookie = typeof launch.headers.getSetCookie === "function" ? launch.headers.getSetCookie() : []; cookie = setCookie.map((item) => item.split(";", 1)[0]).join("; ") || void 0; } - response = await fetch(`${origin}/${route}`, { + response = await fetch(`${origin}/${route}${query}`, { method: "POST", - headers: { "content-type": "application/json", ...cookie === void 0 ? {} : { cookie } }, - body: JSON.stringify(body ?? {}), + headers: { "content-type": contentType2, ...cookie === void 0 ? {} : { cookie } }, + body: requestBody, signal }); if (response.status === 401) cookie = void 0; @@ -103205,6 +105117,155 @@ var PluginUpdateChecker = class { } }; +// packages/plugin/src/plugin-self-update.ts +import { randomUUID as randomUUID19 } from "node:crypto"; + +// packages/plugin/src/version-compare.ts +var VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/; +function parseVersion(value) { + const match = VERSION_PATTERN.exec(value.trim().replace(/^v/, "")); + if (match === null) return void 0; + return { + core: [Number(match[1]), Number(match[2]), Number(match[3])], + prerelease: match[4] === void 0 ? [] : match[4].split(".") + }; +} +function comparePrerelease(left, right) { + if (left.length === 0 && right.length === 0) return 0; + if (left.length === 0) return 1; + if (right.length === 0) return -1; + for (let index = 0; index < Math.max(left.length, right.length); index += 1) { + const part = left[index]; + const other = right[index]; + if (part === void 0) return -1; + if (other === void 0) return 1; + if (part === other) continue; + const partNumeric = /^\d+$/.test(part); + const otherNumeric = /^\d+$/.test(other); + if (partNumeric && otherNumeric) return Math.sign(Number(part) - Number(other)); + if (partNumeric) return -1; + if (otherNumeric) return 1; + return part < other ? -1 : 1; + } + return 0; +} +function compareVersions(left, right) { + const parsedLeft = parseVersion(left); + const parsedRight = parseVersion(right); + if (parsedLeft === void 0 || parsedRight === void 0) return 0; + for (let index = 0; index < 3; index += 1) { + if (parsedLeft.core[index] !== parsedRight.core[index]) { + return Math.sign(parsedLeft.core[index] - parsedRight.core[index]); + } + } + return comparePrerelease(parsedLeft.prerelease, parsedRight.prerelease); +} + +// packages/plugin/src/plugin-self-update.ts +var REMOTE_PLUGIN_PACKAGE = "ds-harness-remote"; +var LocalPluginUpgrade = class { + constructor(checker, manager, subscribe, requestId = randomUUID19) { + this.checker = checker; + this.manager = manager; + this.subscribe = subscribe; + this.requestId = requestId; + } + decidedVersion; + ready = false; + probeFlight; + startFlight; + /** Registry snapshot, plus `upgrade: 'ready'` once this install is confirmed updatable. */ + snapshot() { + const base = this.checker.snapshot(); + if (base === void 0) return void 0; + if (compareVersions(base.currentVersion, base.latestVersion) < 0) { + if (this.decidedVersion !== base.latestVersion) this.probe(base.latestVersion); + if (this.ready && this.decidedVersion === base.latestVersion) return { ...base, upgrade: "ready" }; + } + return base; + } + /** + * Replace this plugin with `version` when it is the checked latest and the + * official manager marks the installed bundle updatable. + */ + start(version2) { + const refused = this.refusal(version2); + if (refused !== void 0) return Promise.resolve(refused); + this.startFlight ??= this.execute(version2).finally(() => { + this.startFlight = void 0; + }); + return this.startFlight; + } + refusal(version2) { + const current = this.checker.snapshot(); + if (current === void 0 || version2 !== current.latestVersion || compareVersions(current.currentVersion, version2) >= 0) return { status: "rejected" }; + return void 0; + } + probe(version2) { + if (this.probeFlight !== void 0) return; + this.probeFlight = this.readReady().then((ready) => { + this.ready = ready; + this.decidedVersion = version2; + }).finally(() => { + this.probeFlight = void 0; + }); + } + async readReady() { + try { + const manager = this.manager(); + if (manager === void 0) return false; + return bundleUpdatable(await manager.listBundles(), REMOTE_PLUGIN_PACKAGE); + } catch { + return false; + } + } + async execute(version2) { + const manager = this.manager(); + if (manager === void 0) return { status: "manual" }; + let updatable = false; + try { + updatable = bundleUpdatable(await manager.listBundles(), REMOTE_PLUGIN_PACKAGE); + } catch { + return { status: "manual" }; + } + if (!updatable) return { status: "manual" }; + const requestId = this.requestId(); + let dispose = () => { + }; + const started = new Promise((resolve10) => { + dispose = this.subscribe((event) => { + if (event.requestId !== requestId) return; + if (event.step === "removing" || event.step === "installing") resolve10({ status: "started" }); + }); + }); + try { + const settled = manager.updateBundle(REMOTE_PLUGIN_PACKAGE, version2, { requestId }).then((result) => classifyUpdateResult(result)).catch(() => ({ status: "failed", message: "update-failed" })); + return await Promise.race([started, settled]); + } finally { + dispose(); + } + } +}; +function bundleUpdatable(listed, packageName) { + if (!Array.isArray(listed)) return false; + return listed.some((row) => isRecord25(row) && row.name === packageName && (row.update === "registry" || row.update === void 0 && row.updatable === true)); +} +function classifyUpdateResult(result) { + if (!isRecord25(result) || !isRecord25(result.result)) return { status: "failed", message: "update-failed" }; + const application = result.result.application; + if (application === "applied" || application === "restart-required") return { status: "started" }; + return { status: "failed", message: failureMessage(result.result.error) }; +} +function failureMessage(error62) { + if (!isRecord25(error62)) return "update-failed"; + const code = typeof error62.code === "string" && error62.code.length > 0 && error62.code.length <= 80 ? error62.code : "update-failed"; + const diagnostic = typeof error62.diagnostic === "string" ? error62.diagnostic.replace(/\s+/g, " ").trim().slice(0, 180) : ""; + return diagnostic === "" ? code : `${code}: ${diagnostic}`; +} +function isRecord25(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + // packages/plugin/src/tui-event-source.ts async function assertRemoteEventSource(gateway) { const peerGateway = gateway.createPeer?.(); @@ -103327,9 +105388,9 @@ function decodeBase64(value) { } // packages/plugin/src/cli.ts -import { stat as stat9 } from "node:fs/promises"; +import { stat as stat10 } from "node:fs/promises"; import { hostname as hostname5 } from "node:os"; -import { join as join17 } from "node:path"; +import { join as join18 } from "node:path"; var QR_POLL_INTERVAL_MS = 2e3; var TERMINAL_QR_MARGIN = 4; async function runCli(args = process.argv.slice(2), dependencies = {}) { @@ -103421,7 +105482,7 @@ async function status(args, runtime) { `Server: ${serverUrl}`, "Host control: enabled" ]; - if (!await exists3(join17(directory, "device.json"))) { + if (!await exists3(join18(directory, "device.json"))) { lines.push("Device: not initialized", "Authorization: logged out", "Credential: unavailable"); write2(runtime.stdout, `${lines.join("\n")} @@ -103481,9 +105542,9 @@ async function logout(args, runtime) { } const directory = serverStorageDirectory(root2, serverUrl, "host"); const [hasDevice, hasKey, hasCredentials] = await Promise.all([ - exists3(join17(directory, "device.json")), - exists3(join17(directory, "device.key")), - exists3(join17(directory, "server-credentials.json")) + exists3(join18(directory, "device.json")), + exists3(join18(directory, "device.key")), + exists3(join18(directory, "server-credentials.json")) ]); if (!hasDevice && !hasKey && !hasCredentials) { await new ServerCredentialStore(directory).clear(); @@ -103612,7 +105673,7 @@ function terminalLink(url2, target3) { } async function exists3(path) { try { - await stat9(path); + await stat10(path); return true; } catch (error62) { if (error62 instanceof Error && "code" in error62 && error62.code === "ENOENT") return false; @@ -103692,6 +105753,7 @@ function apply(ctx, entry = void 0) { } catch (error62) { storageError = error62; } + const pendingLogStore = new HostLogStore({ filePath: resolveHostLogPath({ profile: resolveLogProfileName(runtimeContext) }) }); disposePendingControl = runtimeContext.effect(() => { const control = new PluginControlRuntime( resolveConfig(readConfig()), @@ -103701,12 +105763,17 @@ function apply(ctx, entry = void 0) { void 0, void 0, void 0, - true + true, + pendingLogStore ); if (storageError !== void 0) { control.setStartupFailure(storageError, { storageAvailable: false }); } - return control.register(connection, webServer); + const dispose = control.register(connection, webServer); + return async () => { + await dispose(); + await pendingLogStore.flush(); + }; }, "ds-harness-remote pending control"); }; const startActiveRuntime = async (activeContext) => { @@ -103738,6 +105805,37 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) { const connection = ctx.get("connection"); const webServer = ctx.get("webServer"); const config2 = resolveConfig(settingsBinding?.get() ?? readConfig()); + const logStore = new HostLogStore({ filePath: resolveHostLogPath({ profile: resolveLogProfileName(ctx) }) }); + const readSafeLogLevel = () => { + try { + const raw = (settingsBinding?.get() ?? readConfig()).logLevel; + if (raw === "debug" || raw === "info" || raw === "warn" || raw === "error") return raw; + } catch { + } + return config2.logLevel; + }; + const logger2 = new SafeLogger({ + debug: (message) => { + logStore.record("debug", message); + ctx.logger.debug(message); + console.debug(message); + }, + info: (message) => { + logStore.record("info", message); + ctx.logger.info(message); + console.info(message); + }, + warn: (message) => { + logStore.record("warn", message); + ctx.logger.warn(message); + console.warn(message); + }, + error: (message) => { + logStore.record("error", message); + ctx.logger.error(message); + console.error(message); + } + }, readSafeLogLevel); let defaultIdentityDirectory = new IdentityStore().directory; let initialStorageError; try { @@ -103755,34 +105853,35 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) { void 0, void 0, void 0, - true + true, + logStore ); if (initialStorageError !== void 0) { + logger2.error("Remote plugin startup failed", safeStartupError(initialStorageError)); controlRuntime2.setStartupFailure(initialStorageError, { storageAvailable: false }); } - ctx.effect(() => controlRuntime2.register(connection, webServer), "ds-harness-remote disabled control"); + ctx.effect(() => { + const dispose = controlRuntime2.register(connection, webServer); + return async () => { + await dispose(); + await logStore.flush(); + }; + }, "ds-harness-remote disabled control"); } return; } - const logger2 = new SafeLogger({ - debug: (message) => { - ctx.logger.debug(message); - console.debug(message); - }, - info: (message) => { - ctx.logger.info(message); - console.info(message); - }, - warn: (message) => { - ctx.logger.warn(message); - console.warn(message); - }, - error: (message) => { - ctx.logger.error(message); - console.error(message); - } - }, () => resolveConfig(settingsBinding?.get() ?? readConfig()).logLevel); const updateChecker = new PluginUpdateChecker(logger2); + const pluginUpgrade = new LocalPluginUpgrade( + updateChecker, + () => readPluginManager(ctx), + (listener) => { + const buses = ctx.events === ctx.root.events ? [ctx.root.events] : [ctx.root.events, ctx.events]; + const dispose = buses.map((events) => events.on("plugin-manager/update-state", listener, { global: true })); + return () => { + for (const stop of dispose) stop(); + }; + } + ); const nativeTypertGateway = ctx.get("typertGateway"); const connectionExports = DshConnection; const connectionService = ctx.get("connection", false); @@ -103923,8 +106022,9 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) { clientRuntime, runtime, replaceServer, - updateChecker, - true + pluginUpgrade, + true, + logStore ); if (initialStorageError !== void 0) { controlRuntime?.setStartupFailure(initialStorageError, { storageAvailable: false }); @@ -103972,6 +106072,7 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) { await disposeControl?.(); await clientRuntime?.close(); await runtime?.close(); + await logStore.flush(); }; }, "ds-harness-remote lifecycle"); if (config2.remoteTools?.enabled) { @@ -103986,6 +106087,19 @@ async function activate(ctx, readConfig, entryId, requireRemoteEvents = false) { }); } } +function resolveLogProfileName(ctx) { + const envProfile = process.env.DSH_PROFILE?.trim(); + if (envProfile) return envProfile; + const baseDir = ctx.root?.baseDir; + if (typeof baseDir === "string" && baseDir.trim().length > 0) { + const trimmed = baseDir.trim(); + if (basename9(dirname9(trimmed)) === "profiles") { + const segment = basename9(trimmed); + if (segment.length > 0) return segment; + } + } + return void 0; +} function readEntryConfig(entry) { if (entry === void 0) return {}; return isEntryConfig(entry) ? entry.get() : entry; @@ -103993,6 +106107,11 @@ function readEntryConfig(entry) { function isEntryConfig(value) { return typeof value.get === "function"; } +function readPluginManager(ctx) { + const candidate = ctx.get("pluginManager", false) ?? ctx.root.get("pluginManager", false); + if (typeof candidate !== "object" || candidate === null || typeof candidate.listBundles !== "function" || typeof candidate.updateBundle !== "function") return void 0; + return candidate; +} function locateEntryId(ctx) { const loader = ctx.get("loader"); const located = loader?.locate?.(ctx.fiber);