@ai-matrx/desktop-protocol 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/client/client.ts","../src/error.ts","../src/frame.ts","../src/schema/envelope.ts","../src/schema/errors.ts","../src/schema/primitives.ts","../src/schema/frame.ts","../src/schema/sysinfo.ts","../src/schema/fs.ts","../src/schema/exec.ts","../src/schema/session.ts","../src/schema/relay.ts","../src/schema/registry.ts","../src/client/wake.ts"],"sourcesContent":["/**\n * `@ai-matrx/desktop-protocol/client` — the reconnecting client every TypeScript surface uses to\n * drive a Matrx 2 device (phone console, web app, extension): typed requests by op name, byte\n * streams with credit backpressure, transparent terminal reattach (since_seq replay / gap +\n * snapshot), events, heartbeat, relay reauth. Reconnect uses `createBackoff` from\n * `@ai-matrx/realtime` — the one backoff ladder on the platform.\n */\nexport { createDesktopClient, RECONNECT_ALARM_ATTEMPTS } from \"./client/client\";\nexport { bindDesktopWake } from \"./client/wake\";\nexport type { WakeTargets } from \"./client/wake\";\nexport type {\n ClientTimers,\n DesktopClient,\n DesktopClientDiagnostic,\n DesktopClientOptions,\n DesktopClientState,\n DesktopClientStatus,\n DesktopStream,\n EventHandler,\n EventName,\n EventPayload,\n RequestOptions,\n StreamHandlers,\n StreamOpName,\n StreamOptions,\n WebSocketFactory,\n WebSocketLike,\n WakeOptions,\n} from \"./client/types\";\nexport { DesktopProtocolError, isDesktopProtocolError } from \"./error\";\nexport type { OpName, OpParams, OpResult } from \"./schema/registry\";\n","/**\n * The reconnecting desktop-protocol client: hello → requests, streams with credit-based\n * backpressure, events, transparent reattach of resource streams (terminals, watches) after a\n * drop, heartbeat, and relay reauth. One instance per device connection. All state lives in the\n * closure — no module-level state (dual ESM/CJS graphs would split it).\n */\nimport { RECONNECT_ALARM_ATTEMPTS, createBackoff } from \"@ai-matrx/realtime\";\nimport { DesktopProtocolError } from \"../error\";\nimport { FRAME_VERSION, FrameChannel, decodeFrame, encodeFrame } from \"../frame\";\nimport type { FrameHeader } from \"../frame\";\nimport { CloseCode, CoreToClientMsg, PING_TEXT, PONG_TEXT, Welcome } from \"../schema/envelope\";\nimport type { EndReason, StreamMeta } from \"../schema/envelope\";\nimport type { ProtocolErrorBody } from \"../schema/errors\";\nimport { DEFAULT_MAX_FRAME_PAYLOAD_BYTES, DEFAULT_WINDOW_BYTES } from \"../schema/frame\";\nimport { PROTOCOL_MAJOR, PROTOCOL_MINOR } from \"../schema/primitives\";\nimport { EVENTS, OPS } from \"../schema/registry\";\nimport type { OpName, OpParams, OpResult } from \"../schema/registry\";\nimport type {\n ClientTimers,\n DesktopClient,\n DesktopClientDiagnostic,\n DesktopClientOptions,\n DesktopClientState,\n DesktopStream,\n EventHandler,\n EventName,\n RequestOptions,\n StreamHandlers,\n StreamOpName,\n StreamOptions,\n WakeOptions,\n WebSocketFactory,\n WebSocketLike,\n} from \"./types\";\n\nconst WS_OPEN = 1;\n/** Close codes after which reconnecting is pointless or forbidden. */\nconst TERMINAL_CLOSE: ReadonlyMap<number, [DesktopProtocolError[\"code\"], string]> = new Map([\n [CloseCode.DEVICE_REVOKED, [\"AUTH_DEVICE_REVOKED\", \"This device was revoked\"]],\n [CloseCode.AUTH_FORBIDDEN, [\"AUTH_FORBIDDEN\", \"Not this device's owner\"]],\n [CloseCode.DEVICE_NOT_FOUND, [\"NOT_FOUND\", \"Device not found\"]],\n [CloseCode.REPLACED, [\"CONFLICT\", \"Replaced by a newer connection\"]],\n [CloseCode.UPGRADE_REQUIRED, [\"PROTOCOL_VERSION_UNSUPPORTED\", \"Protocol upgrade required\"]],\n]);\n\ntype Pending = {\n kind: \"unary\";\n op: string;\n resolve: (value: unknown) => void;\n reject: (error: DesktopProtocolError) => void;\n cleanup: () => void;\n};\n\ninterface StreamState {\n op: string;\n handlers: StreamHandlers;\n options: StreamOptions;\n id: string;\n sid: number | null;\n resourceId: string | null;\n /** Last inbound DATA seq delivered to the consumer. */\n lastSeq: number;\n /** Expected next inbound seq, or null right after a gap/snapshot (resync on next frame). */\n expectSeq: number | null;\n windowBytes: number;\n /** Consumed bytes not yet credited back. */\n consumedUncredited: number;\n /** Outbound (STDIN) credit granted by the core. */\n sendWindow: number;\n sendSeq: number;\n sendQueue: Uint8Array[];\n /** Serializes consumer callbacks so credits follow consumption order. */\n chain: Promise<void>;\n resultSettled: boolean;\n resolveResult: (value: unknown) => void;\n rejectResult: (error: DesktopProtocolError) => void;\n resolveDone: (reason: EndReason) => void;\n rejectDone: (error: DesktopProtocolError) => void;\n ended: boolean;\n /** True while a reattach request is in flight for it. */\n reattaching: boolean;\n}\n\nconst defaultTimers: ClientTimers = {\n setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),\n clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),\n now: () => Date.now(),\n};\n\nfunction defaultWebSocket(): WebSocketFactory {\n return (url, protocols) => {\n const Ctor = (globalThis as { WebSocket?: new (url: string, protocols?: string[]) => WebSocketLike }).WebSocket;\n if (!Ctor) {\n throw new DesktopProtocolError(\"PLATFORM_UNSUPPORTED\", \"No global WebSocket — pass options.webSocket\");\n }\n return new Ctor(url, protocols);\n };\n}\n\nfunction capOf(op: string): { cap: string; op: string } {\n const dot = op.indexOf(\".\");\n return { cap: op.slice(0, dot), op: op.slice(dot + 1) };\n}\n\nfunction fromBody(body: ProtocolErrorBody): DesktopProtocolError {\n return body.data === undefined\n ? new DesktopProtocolError(body.code, body.message, { retryable: body.retryable })\n : new DesktopProtocolError(body.code, body.message, { retryable: body.retryable, data: body.data });\n}\n\nfunction toBytes(data: unknown): Uint8Array | null {\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n return null;\n}\n\nexport function createDesktopClient(options: DesktopClientOptions): DesktopClient {\n const timers = options.timers ?? defaultTimers;\n const makeSocket = options.webSocket ?? defaultWebSocket();\n const heartbeatMs = options.heartbeatMs ?? 25_000;\n const requestTimeoutMs = options.requestTimeoutMs ?? 70_000;\n const protocolVersion = options.protocolVersion ?? `${PROTOCOL_MAJOR}.${PROTOCOL_MINOR}`;\n const backoff = createBackoff({ ...options.backoff, now: timers.now });\n const diagnose =\n options.onDiagnostic ??\n ((d: DesktopClientDiagnostic) => {\n console.warn(\"[desktop-protocol]\", d.kind, d);\n });\n\n let state: DesktopClientState = {\n status: \"idle\",\n welcome: null,\n attempts: 0,\n retryInMs: null,\n lastError: null,\n lastCloseCode: null,\n };\n const listeners = new Set<() => void>();\n const readyWaiters = new Set<{ resolve: (w: Welcome) => void; reject: (e: DesktopProtocolError) => void }>();\n const pending = new Map<string, Pending>();\n const streams = new Map<string, StreamState>(); // by current request id\n const bySid = new Map<number, StreamState>();\n const eventHandlers = new Map<string, Set<EventHandler<EventName>>>();\n let socket: WebSocketLike | null = null;\n let socketGeneration = 0;\n let nextId = 0;\n let helloId: string | null = null;\n let reconnectTimer: unknown = null;\n let heartbeatTimer: unknown = null;\n let probeTimer: unknown = null;\n let lastHeardAt = 0;\n /** Inbound messages on the current socket — the wake probe's \"was anything heard since?\" */\n let heardCount = 0;\n let closedByUser = false;\n\n const newId = (prefix: string) => `${prefix}${(++nextId).toString(36)}`;\n\n function setState(patch: Partial<DesktopClientState>): void {\n state = { ...state, ...patch };\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch (error) {\n diagnose({ kind: \"handler_threw\", where: \"subscribe listener\", error });\n }\n }\n }\n\n function sendJson(message: unknown): boolean {\n if (!socket || socket.readyState !== WS_OPEN) return false;\n socket.send(JSON.stringify(message));\n return true;\n }\n\n // ── connection lifecycle ────────────────────────────────────────────────────\n\n function connect(): void {\n if (state.status === \"connecting\" || state.status === \"handshaking\" || state.status === \"open\") return;\n closedByUser = false;\n if (reconnectTimer !== null) {\n timers.clearTimeout(reconnectTimer);\n reconnectTimer = null;\n }\n void openSocket();\n }\n\n async function openSocket(): Promise<void> {\n const generation = ++socketGeneration;\n setState({ status: \"connecting\", retryInMs: null });\n let ws: WebSocketLike;\n try {\n const url = typeof options.url === \"function\" ? await options.url() : options.url;\n const protocols = options.protocols ? await options.protocols() : [];\n if (generation !== socketGeneration || closedByUser) return;\n ws = makeSocket(url, protocols);\n } catch (error) {\n if (generation !== socketGeneration) return;\n const err =\n error instanceof DesktopProtocolError\n ? error\n : new DesktopProtocolError(\"INTERNAL\", \"Could not open the connection\", { retryable: true, cause: error });\n onSocketGone(generation, null, err);\n return;\n }\n socket = ws;\n ws.binaryType = \"arraybuffer\";\n ws.onopen = () => {\n if (generation !== socketGeneration) return;\n lastHeardAt = timers.now();\n helloId = newId(\"h\");\n setState({ status: \"handshaking\" });\n sendJson({ type: \"hello\", id: helloId, protocolVersion, clientType: options.clientType, clientVersion: options.clientVersion });\n scheduleHeartbeat(generation);\n };\n ws.onmessage = (event) => {\n if (generation !== socketGeneration) return;\n lastHeardAt = timers.now();\n heardCount++;\n onMessage(event.data);\n };\n ws.onerror = () => {\n // The close event that always follows carries the code; nothing to do here.\n };\n ws.onclose = (event) => {\n if (generation !== socketGeneration) return;\n onSocketGone(generation, event.code, null);\n };\n }\n\n function scheduleHeartbeat(generation: number): void {\n if (heartbeatTimer !== null) timers.clearTimeout(heartbeatTimer);\n heartbeatTimer = timers.setTimeout(() => {\n heartbeatTimer = null;\n if (generation !== socketGeneration || !socket) return;\n const silentMs = timers.now() - lastHeardAt;\n if (silentMs >= heartbeatMs * 2) {\n diagnose({ kind: \"heartbeat_timeout\", silentMs });\n const dead = socket;\n onSocketGone(generation, null, new DesktopProtocolError(\"TIMEOUT\", \"Connection went silent\", { retryable: true }));\n try {\n dead.close(CloseCode.NORMAL, \"heartbeat timeout\");\n } catch {\n // already closing\n }\n return;\n }\n if (socket.readyState === WS_OPEN) socket.send(PING_TEXT);\n scheduleHeartbeat(generation);\n }, heartbeatMs);\n }\n\n /** The socket is gone (close event, open failure or heartbeat death). */\n function onSocketGone(generation: number, code: number | null, error: DesktopProtocolError | null): void {\n if (generation !== socketGeneration) return;\n socketGeneration++; // ignore anything the dead socket still emits\n if (socket) {\n socket.onopen = socket.onmessage = socket.onclose = socket.onerror = null;\n }\n socket = null;\n helloId = null;\n if (heartbeatTimer !== null) {\n timers.clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n if (probeTimer !== null) {\n timers.clearTimeout(probeTimer);\n probeTimer = null;\n }\n const terminal = code === null ? undefined : TERMINAL_CLOSE.get(code);\n const lost =\n error ??\n (terminal\n ? new DesktopProtocolError(terminal[0], terminal[1])\n : new DesktopProtocolError(\"DEVICE_OFFLINE\", \"Connection lost\", { retryable: true }));\n\n // Unary requests cannot survive a drop: the caller decides whether to retry.\n for (const [id, p] of pending) {\n pending.delete(id);\n p.cleanup();\n p.reject(lost);\n }\n // Resource streams survive (reattach on reconnect); everything else ends now.\n bySid.clear();\n for (const [id, s] of streams) {\n if (s.resourceId !== null && terminal === undefined && !closedByUser) {\n s.sid = null;\n s.reattaching = false;\n continue;\n }\n streams.delete(id);\n endStream(s, null, lost);\n }\n\n if (closedByUser || terminal) {\n setState({ status: \"closed\", welcome: null, lastError: closedByUser ? state.lastError : lost, lastCloseCode: code, retryInMs: null });\n rejectReadyWaiters(lost);\n return;\n }\n const delay = backoff.nextDelayMs();\n if (backoff.isAlarming()) diagnose({ kind: \"reconnect_alarm\", attempts: backoff.attempts() });\n setState({ status: \"reconnecting\", welcome: null, attempts: backoff.attempts(), retryInMs: delay, lastError: lost, lastCloseCode: code });\n reconnectTimer = timers.setTimeout(() => {\n reconnectTimer = null;\n if (!closedByUser) void openSocket();\n }, delay);\n }\n\n function rejectReadyWaiters(error: DesktopProtocolError): void {\n for (const w of [...readyWaiters]) {\n readyWaiters.delete(w);\n w.reject(error);\n }\n }\n\n function close(): void {\n closedByUser = true;\n if (reconnectTimer !== null) {\n timers.clearTimeout(reconnectTimer);\n reconnectTimer = null;\n }\n const cancelled = new DesktopProtocolError(\"CANCELLED\", \"Client closed\");\n const ws = socket;\n if (ws) {\n onSocketGone(socketGeneration, CloseCode.NORMAL, cancelled);\n try {\n ws.close(CloseCode.NORMAL, \"client closed\");\n } catch {\n // already closed\n }\n } else {\n for (const [id, s] of streams) {\n streams.delete(id);\n endStream(s, null, cancelled);\n }\n setState({ status: \"closed\", retryInMs: null });\n rejectReadyWaiters(cancelled);\n }\n }\n\n // ── inbound ────────────────────────────────────────────────────────────────\n\n function onMessage(data: unknown): void {\n if (typeof data === \"string\") {\n if (data === PONG_TEXT) return;\n let json: unknown;\n try {\n json = JSON.parse(data);\n } catch {\n diagnose({ kind: \"malformed_message\", detail: \"not JSON\" });\n return;\n }\n const parsed = CoreToClientMsg.safeParse(json);\n if (!parsed.success) {\n diagnose({ kind: \"malformed_message\", detail: parsed.error.issues.map((i) => `${i.path.join(\".\")}: ${i.message}`).join(\"; \") });\n return;\n }\n onEnvelope(parsed.data);\n return;\n }\n const bytes = toBytes(data);\n if (bytes === null) {\n diagnose({ kind: \"malformed_message\", detail: \"binary message is not an ArrayBuffer/view (set binaryType)\" });\n return;\n }\n let frame: ReturnType<typeof decodeFrame>;\n try {\n frame = decodeFrame(bytes);\n } catch (error) {\n diagnose({ kind: \"malformed_message\", detail: error instanceof Error ? error.message : String(error) });\n return;\n }\n onFrame(frame.header, frame.payload);\n }\n\n function onEnvelope(msg: CoreToClientMsg): void {\n switch (msg.type) {\n case \"response\": {\n if (msg.id === helloId) return onWelcome(msg.result);\n const s = streams.get(msg.id);\n if (s) return onStreamResult(s, msg.result);\n const p = pending.get(msg.id);\n if (!p) return diagnose({ kind: \"unknown_request\", id: msg.id, type: msg.type });\n pending.delete(msg.id);\n p.cleanup();\n p.resolve(msg.result);\n return;\n }\n case \"error\": {\n const error = fromBody(msg.error);\n if (msg.id === helloId) return onHelloRefused(error);\n const s = streams.get(msg.id);\n if (s) {\n if (s.reattaching && s.resourceId !== null) diagnose({ kind: \"reattach_failed\", resourceId: s.resourceId, error });\n streams.delete(msg.id);\n if (s.sid !== null) bySid.delete(s.sid);\n return endStream(s, null, error);\n }\n const p = pending.get(msg.id);\n if (!p) return diagnose({ kind: \"unknown_request\", id: msg.id, type: msg.type });\n pending.delete(msg.id);\n p.cleanup();\n p.reject(error);\n return;\n }\n case \"stream\": {\n const s = streams.get(msg.id);\n if (!s) return diagnose({ kind: \"unknown_request\", id: msg.id, type: msg.type });\n onStreamMeta(s, msg.meta);\n return;\n }\n case \"end\": {\n const s = streams.get(msg.id);\n if (!s) return diagnose({ kind: \"unknown_request\", id: msg.id, type: msg.type });\n // Deliver everything already queued before announcing the end.\n void s.chain.then(() => {\n streams.delete(s.id);\n if (s.sid !== null) bySid.delete(s.sid);\n endStream(s, msg.reason ?? \"completed\", null);\n });\n return;\n }\n case \"credit\": {\n const s = streams.get(msg.id);\n if (!s) return diagnose({ kind: \"unknown_request\", id: msg.id, type: msg.type });\n s.sendWindow += msg.n;\n flushSend(s);\n return;\n }\n case \"event\": {\n const key = `${msg.cap}.${msg.name}`;\n const schema = (EVENTS as Record<string, (typeof EVENTS)[EventName]>)[key];\n if (!schema) return diagnose({ kind: \"malformed_message\", detail: `unknown event ${key}` });\n const payload = schema.safeParse(msg.payload);\n if (!payload.success) return diagnose({ kind: \"malformed_message\", detail: `event ${key}: invalid payload` });\n if (key === \"relay.auth_expiring\" && options.getToken) {\n options.getToken().then(reauth, (error: unknown) => diagnose({ kind: \"reauth_failed\", error }));\n }\n for (const handler of [...(eventHandlers.get(key) ?? [])]) {\n try {\n handler(payload.data as never, msg.resourceId);\n } catch (error) {\n diagnose({ kind: \"handler_threw\", where: `event ${key}`, error });\n }\n }\n return;\n }\n }\n }\n\n function onWelcome(result: unknown): void {\n const welcome = Welcome.safeParse(result);\n if (!welcome.success) {\n onHelloRefused(new DesktopProtocolError(\"PROTOCOL_ERROR\", \"Malformed welcome\"));\n return;\n }\n helloId = null;\n backoff.markConnected();\n setState({ status: \"open\", welcome: welcome.data, attempts: 0, retryInMs: null, lastError: null });\n for (const w of [...readyWaiters]) {\n readyWaiters.delete(w);\n w.resolve(welcome.data);\n }\n // Transparent reattach: every surviving resource stream continues where its consumer stopped.\n for (const s of [...streams.values()]) {\n if (s.sid === null && s.resourceId !== null && !s.ended) reattach(s, welcome.data);\n }\n }\n\n function onHelloRefused(error: DesktopProtocolError): void {\n // An unsupported version will not fix itself on retry: UPGRADE_REQUIRED is a terminal close.\n const ws = socket;\n onSocketGone(socketGeneration, error.code === \"PROTOCOL_VERSION_UNSUPPORTED\" ? CloseCode.UPGRADE_REQUIRED : null, error);\n try {\n ws?.close(CloseCode.NORMAL, \"hello refused\");\n } catch {\n // already closed\n }\n }\n\n // ── streams ────────────────────────────────────────────────────────────────\n\n function onStreamResult(s: StreamState, result: unknown): void {\n if (s.reattaching) {\n // session.attach result = ResourceInfo; the stream continues on the new id.\n s.reattaching = false;\n safeCall(\"onReattached\", () => s.handlers.onReattached?.());\n return;\n }\n const rid = (result as { resource_id?: unknown } | null)?.resource_id;\n if (typeof rid === \"string\") s.resourceId = rid;\n if (!s.resultSettled) {\n s.resultSettled = true;\n s.resolveResult(result);\n }\n }\n\n function onStreamMeta(s: StreamState, meta: StreamMeta): void {\n if (meta.kind === \"open\") {\n if (s.sid !== null) bySid.delete(s.sid);\n s.sid = meta.sid;\n s.windowBytes = meta.window_bytes;\n if (meta.resource_id !== undefined) s.resourceId = meta.resource_id;\n bySid.set(meta.sid, s);\n flushSend(s);\n } else {\n // gap or snapshot: the next DATA frame re-establishes the sequence.\n s.expectSeq = null;\n }\n safeCall(\"onMeta\", () => s.handlers.onMeta?.(meta));\n }\n\n function onFrame(header: FrameHeader, payload: Uint8Array): void {\n const s = bySid.get(header.sid);\n if (!s) {\n diagnose({ kind: \"unknown_stream\", sid: header.sid });\n return;\n }\n const isData = header.channel === FrameChannel.DATA || header.channel === FrameChannel.STDERR;\n const isSnapshot = header.channel === FrameChannel.SNAPSHOT;\n if (!isData && !isSnapshot) {\n diagnose({ kind: \"malformed_message\", detail: `channel ${header.channel} is not client-bound` });\n return;\n }\n if (isData) {\n if (s.expectSeq !== null && header.seq !== s.expectSeq) {\n diagnose({ kind: \"seq_gap\", id: s.id, expected: s.expectSeq, received: header.seq });\n }\n s.expectSeq = header.seq + 1;\n }\n // Copy: the payload is a view into a buffer the transport may reuse.\n const bytes = payload.slice();\n const handler = isData ? s.handlers.onData : s.handlers.onSnapshot;\n s.chain = s.chain.then(async () => {\n if (s.ended) return;\n try {\n await handler?.(bytes, header);\n } catch (error) {\n diagnose({ kind: \"handler_threw\", where: isData ? \"onData\" : \"onSnapshot\", error });\n }\n if (isData) s.lastSeq = header.seq;\n grantCredit(s, bytes.byteLength);\n });\n }\n\n function grantCredit(s: StreamState, consumed: number): void {\n s.consumedUncredited += consumed;\n // Batch: one credit per quarter window keeps the pipe full without a message per frame.\n if (s.consumedUncredited >= Math.max(1, Math.floor(s.windowBytes / 4))) {\n if (sendJson({ type: \"credit\", id: s.id, n: s.consumedUncredited })) s.consumedUncredited = 0;\n }\n }\n\n function flushSend(s: StreamState): void {\n if (s.sid === null || !socket || socket.readyState !== WS_OPEN) return;\n const maxPayload = state.welcome?.limits.max_frame_payload_bytes ?? DEFAULT_MAX_FRAME_PAYLOAD_BYTES;\n while (s.sendQueue.length > 0 && s.sendWindow > 0) {\n const head = s.sendQueue[0]!;\n const n = Math.min(head.byteLength, s.sendWindow, maxPayload);\n const chunk = head.subarray(0, n);\n if (n === head.byteLength) s.sendQueue.shift();\n else s.sendQueue[0] = head.subarray(n);\n s.sendWindow -= n;\n s.sendSeq += 1;\n socket.send(encodeFrame({ version: FRAME_VERSION, flags: 0, channel: FrameChannel.STDIN, cid: 0, sid: s.sid, seq: s.sendSeq }, chunk));\n }\n }\n\n function endStream(s: StreamState, reason: EndReason | null, error: DesktopProtocolError | null): void {\n if (s.ended) return;\n s.ended = true;\n s.sendQueue = [];\n if (!s.resultSettled) {\n s.resultSettled = true;\n s.rejectResult(error ?? new DesktopProtocolError(\"INTERNAL\", \"Stream ended before its result\"));\n }\n if (error) s.rejectDone(error);\n else s.resolveDone(reason ?? \"completed\");\n }\n\n function reattach(s: StreamState, welcome: Welcome): void {\n const id = newId(\"a\");\n streams.delete(s.id);\n s.id = id;\n s.reattaching = true;\n s.expectSeq = s.lastSeq > 0 ? s.lastSeq + 1 : null;\n s.consumedUncredited = 0;\n s.sendWindow = welcome.limits.default_window_bytes;\n s.sendSeq = 0;\n streams.set(id, s);\n const params: Record<string, unknown> = { resource_id: s.resourceId, mode: s.options.mode ?? \"control\" };\n if (s.lastSeq > 0) params.since_seq = s.lastSeq;\n if (s.options.windowBytes !== undefined) params.window_bytes = s.options.windowBytes;\n sendJson({ id, type: \"request\", cap: \"session\", op: \"attach\", params });\n }\n\n function safeCall(where: string, fn: () => void): void {\n try {\n fn();\n } catch (error) {\n diagnose({ kind: \"handler_threw\", where, error });\n }\n }\n\n // ── public API ─────────────────────────────────────────────────────────────\n\n function ready(opts: RequestOptions = {}): Promise<Welcome> {\n if (state.status === \"open\" && state.welcome) return Promise.resolve(state.welcome);\n if (state.status === \"closed\") {\n return Promise.reject(state.lastError ?? new DesktopProtocolError(\"CANCELLED\", \"Client is closed\"));\n }\n if (state.status === \"idle\") connect();\n return new Promise((resolve, reject) => {\n const waiter = {\n resolve: (w: Welcome) => {\n done();\n resolve(w);\n },\n reject: (e: DesktopProtocolError) => {\n done();\n reject(e);\n },\n };\n const timeoutMs = opts.timeoutMs ?? requestTimeoutMs;\n const timer = timers.setTimeout(() => waiter.reject(new DesktopProtocolError(\"DEVICE_OFFLINE\", \"Device not reachable\", { retryable: true })), timeoutMs);\n const onAbort = () => waiter.reject(new DesktopProtocolError(\"CANCELLED\", \"Aborted\"));\n opts.signal?.addEventListener(\"abort\", onAbort, { once: true });\n function done() {\n readyWaiters.delete(waiter);\n timers.clearTimeout(timer);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n }\n readyWaiters.add(waiter);\n });\n }\n\n async function request<N extends OpName>(op: N, params: OpParams<N>, opts: RequestOptions = {}): Promise<OpResult<N>> {\n if (OPS[op].kind !== \"unary\") {\n throw new DesktopProtocolError(\"INVALID_PARAMS\", `${op} is a ${OPS[op].kind} op — use stream()`);\n }\n await ready(opts);\n const id = newId(\"r\");\n return new Promise<OpResult<N>>((resolve, reject) => {\n const timeoutMs = opts.timeoutMs ?? requestTimeoutMs;\n const timer = timers.setTimeout(() => {\n pending.delete(id);\n cleanup();\n sendJson({ id, type: \"cancel\" });\n reject(new DesktopProtocolError(\"TIMEOUT\", `${op} timed out`, { retryable: true }));\n }, timeoutMs);\n const onAbort = () => {\n pending.delete(id);\n cleanup();\n sendJson({ id, type: \"cancel\" });\n reject(new DesktopProtocolError(\"CANCELLED\", \"Aborted\"));\n };\n function cleanup() {\n timers.clearTimeout(timer);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n }\n opts.signal?.addEventListener(\"abort\", onAbort, { once: true });\n pending.set(id, { kind: \"unary\", op, resolve: resolve as (v: unknown) => void, reject, cleanup });\n if (!sendJson({ id, type: \"request\", ...capOf(op), params })) {\n pending.delete(id);\n cleanup();\n reject(new DesktopProtocolError(\"DEVICE_OFFLINE\", \"Connection lost\", { retryable: true }));\n }\n });\n }\n\n function stream<N extends StreamOpName>(\n op: N,\n params: OpParams<N>,\n handlers: StreamHandlers = {},\n opts: StreamOptions = {},\n ): DesktopStream<N> {\n let resolveResult!: (v: unknown) => void;\n let rejectResult!: (e: DesktopProtocolError) => void;\n let resolveDone!: (r: EndReason) => void;\n let rejectDone!: (e: DesktopProtocolError) => void;\n const result = new Promise<OpResult<N>>((res, rej) => {\n resolveResult = res as (v: unknown) => void;\n rejectResult = rej;\n });\n const done = new Promise<EndReason>((res, rej) => {\n resolveDone = res;\n rejectDone = rej;\n });\n // Consumers often await only one of the two; never leave the other as an unhandled rejection.\n result.catch(() => undefined);\n done.catch(() => undefined);\n\n // A caller-started session.attach (a page reload reattaching by the resource id it kept in its\n // URL) is a resource stream from its first byte: it survives drops like the stream that created\n // the resource, and its sequence continues from since_seq rather than from 1.\n const attach = op === \"session.attach\" ? (params as { resource_id: string; since_seq?: number }) : null;\n const s: StreamState = {\n op,\n handlers,\n options: opts,\n id: newId(\"s\"),\n sid: null,\n resourceId: attach ? attach.resource_id : null,\n lastSeq: attach?.since_seq ?? 0,\n expectSeq: attach ? (attach.since_seq === undefined ? null : attach.since_seq + 1) : 1,\n windowBytes: opts.windowBytes ?? DEFAULT_WINDOW_BYTES,\n consumedUncredited: 0,\n sendWindow: DEFAULT_WINDOW_BYTES,\n sendSeq: 0,\n sendQueue: [],\n chain: Promise.resolve(),\n resultSettled: false,\n resolveResult,\n rejectResult,\n resolveDone,\n rejectDone,\n ended: false,\n reattaching: false,\n };\n\n const start = async () => {\n let welcome: Welcome;\n try {\n welcome = await ready(opts);\n } catch (error) {\n endStream(s, null, error as DesktopProtocolError);\n return;\n }\n if (s.ended) return;\n s.sendWindow = welcome.limits.default_window_bytes;\n if (opts.windowBytes === undefined) s.windowBytes = welcome.limits.default_window_bytes;\n streams.set(s.id, s);\n const wire: Record<string, unknown> = { ...(params as Record<string, unknown>) };\n if (opts.windowBytes !== undefined && \"window_bytes\" in OPS[op].params.shape) wire.window_bytes = opts.windowBytes;\n if (!sendJson({ id: s.id, type: \"request\", ...capOf(op), params: wire })) {\n streams.delete(s.id);\n endStream(s, null, new DesktopProtocolError(\"DEVICE_OFFLINE\", \"Connection lost\", { retryable: true }));\n }\n };\n void start();\n opts.signal?.addEventListener(\"abort\", () => handle.cancel(), { once: true });\n\n const encoder = new TextEncoder();\n const handle: DesktopStream<N> = {\n get id() {\n return s.id;\n },\n result,\n done,\n get resourceId() {\n return s.resourceId;\n },\n get lastSeq() {\n return s.lastSeq;\n },\n write(data) {\n if (s.ended) throw new DesktopProtocolError(\"RESOURCE_GONE\", \"Stream has ended\");\n const bytes = typeof data === \"string\" ? encoder.encode(data) : data;\n if (bytes.byteLength === 0) return;\n s.sendQueue.push(bytes);\n flushSend(s);\n },\n cancel() {\n if (s.ended) return;\n if (!sendJson({ id: s.id, type: \"cancel\" })) {\n streams.delete(s.id);\n endStream(s, \"cancelled\", null);\n }\n },\n async detach() {\n if (s.ended) return;\n if (s.resourceId === null) throw new DesktopProtocolError(\"INVALID_PARAMS\", \"Only resource streams can be detached\");\n const resourceId = s.resourceId;\n streams.delete(s.id);\n if (s.sid !== null) bySid.delete(s.sid);\n endStream(s, \"detached\", null);\n await request(\"session.detach\", { resource_id: resourceId });\n },\n };\n return handle;\n }\n\n function on<E extends EventName>(name: E, handler: EventHandler<E>): () => void {\n let set = eventHandlers.get(name);\n if (!set) {\n set = new Set();\n eventHandlers.set(name, set);\n }\n set.add(handler as EventHandler<EventName>);\n return () => {\n set.delete(handler as EventHandler<EventName>);\n };\n }\n\n function reauth(token: string): void {\n sendJson({ type: \"relay\", op: \"reauth\", token });\n }\n\n function wake(opts: WakeOptions = {}): void {\n if (closedByUser || state.status === \"closed\") return;\n if (state.status === \"idle\" || state.status === \"reconnecting\") {\n connect(); // dial now; connect() cancels the scheduled backoff timer\n return;\n }\n if (state.status === \"connecting\" || !socket || probeTimer !== null) return;\n const generation = socketGeneration;\n const heardBefore = heardCount;\n try {\n socket.send(PING_TEXT);\n } catch {\n // A socket that cannot even send is dead: fall through to the probe verdict.\n }\n probeTimer = timers.setTimeout(() => {\n probeTimer = null;\n if (generation !== socketGeneration || !socket) return;\n if (heardCount > heardBefore) return; // answered: the socket is alive\n const silentMs = timers.now() - lastHeardAt;\n diagnose({ kind: \"heartbeat_timeout\", silentMs });\n const dead = socket;\n onSocketGone(generation, null, new DesktopProtocolError(\"TIMEOUT\", \"Connection went silent\", { retryable: true }));\n try {\n dead.close(CloseCode.NORMAL, \"wake probe timeout\");\n } catch {\n // already closing\n }\n if (state.status === \"reconnecting\") connect(); // the person is looking: no backoff wait\n }, opts.probeMs ?? 4000);\n }\n\n return {\n connect,\n close,\n getState: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n ready,\n request,\n stream,\n on,\n reauth,\n wake,\n };\n}\n\nexport { RECONNECT_ALARM_ATTEMPTS };\n","/**\n * The one error type every package entry throws. It carries the wire ErrorCode (SPEC §5), so a\n * caller branches on `code`/`retryable`/`data.reason` and never parses a message. Zod-free on\n * purpose: `./frame` (the relay hot path) throws it without pulling the schema graph.\n */\nimport type { ErrorCodeName, ErrorData } from \"./types\";\n\nexport class DesktopProtocolError extends Error {\n readonly code: ErrorCodeName;\n readonly retryable: boolean;\n readonly data: ErrorData | undefined;\n\n constructor(code: ErrorCodeName, message: string, options: { retryable?: boolean; data?: ErrorData; cause?: unknown } = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = \"DesktopProtocolError\";\n this.code = code;\n this.retryable = options.retryable ?? false;\n this.data = options.data;\n }\n\n /** The wire body (ProtocolErrorBody) — what a core or relay sends for this error. */\n toBody(): { code: ErrorCodeName; message: string; retryable: boolean; data?: ErrorData } {\n return this.data === undefined\n ? { code: this.code, message: this.message, retryable: this.retryable }\n : { code: this.code, message: this.message, retryable: this.retryable, data: this.data };\n }\n}\n\nexport function isDesktopProtocolError(value: unknown): value is DesktopProtocolError {\n return value instanceof DesktopProtocolError || (value instanceof Error && value.name === \"DesktopProtocolError\" && \"code\" in value);\n}\n","/**\n * `@ai-matrx/desktop-protocol/frame` — the 16-byte binary frame codec. ZOD-FREE by design: the\n * relay Worker's hot path imports only this entry and must stay tiny.\n *\n * off size field notes\n * 0 u8 version = 1\n * 1 u8 flags bit0 FIN (last frame of this stream), bit1 REPLAY (from ring buffer),\n * bits2-7 reserved = 0\n * 2 u8 channel see FrameChannel\n * 3 u8 reserved = 0\n * 4 u32 cid relay connection id. 0 on every client↔relay hop; the relay stamps it on\n * the relay→device hop and strips it on the way back (rewrites 4 bytes in\n * place — the relay never parses payloads).\n * 8 u32 sid stream id, announced by the core in stream{meta:{kind:\"open\",sid}}\n * 12 u32 seq per-stream frame sequence, starts at 1, strictly +1\n *\n * Big-endian. Payload length = message length − 16 (one frame = one WS binary message).\n * Python struct format: \">BBBBIII\". The zod twin (FrameHeader in the root entry, and so the JSON\n * Schema and Pydantic model) is checked against this file by src/frame.test.ts.\n */\nimport { DesktopProtocolError } from \"./error\";\n\nexport const FRAME_HEADER_BYTES = 16 as const;\nexport const FRAME_VERSION = 1 as const;\nexport const FRAME_STRUCT_FORMAT = \">BBBBIII\" as const;\nexport const FrameFlag = { FIN: 0b01, REPLAY: 0b10 } as const;\nexport const FrameChannel = {\n /** core→client: pty output, fs.read_stream bytes */\n DATA: 0,\n /** core→client: stderr of a non-pty process (reserved for exec.spawn in v1.1) */\n STDERR: 1,\n /** client→core: keystrokes / stdin to sid */\n STDIN: 2,\n /** core→client: serialized terminal screen (attach when since_seq is outside the ring) */\n SNAPSHOT: 3,\n /** relay↔device hop only: a JSON envelope carried inside a binary frame so the relay can route\n * by cid without parsing JSON. Never seen by clients. */\n ENVELOPE: 255,\n} as const;\n\nexport type FrameChannelValue = (typeof FrameChannel)[keyof typeof FrameChannel];\n\nexport interface FrameHeader {\n version: typeof FRAME_VERSION;\n /** 0..3 — FrameFlag bits. */\n flags: number;\n channel: FrameChannelValue;\n cid: number;\n sid: number;\n seq: number;\n}\n\nexport interface DecodedFrame {\n header: FrameHeader;\n /** A VIEW into the input buffer (no copy). Copy it if you keep it past the input's lifetime. */\n payload: Uint8Array;\n}\n\nconst U32_MAX = 4_294_967_295;\nconst CHANNELS: ReadonlySet<number> = new Set(Object.values(FrameChannel));\n\nfunction frameError(message: string): DesktopProtocolError {\n return new DesktopProtocolError(\"PROTOCOL_ERROR\", message);\n}\n\nfunction checkU32(name: string, value: number): void {\n if (!Number.isInteger(value) || value < 0 || value > U32_MAX) throw frameError(`frame ${name} is not a u32: ${value}`);\n}\n\n/** Validate a header without zod. Throws DesktopProtocolError(PROTOCOL_ERROR). */\nexport function assertFrameHeader(h: FrameHeader): void {\n if (h.version !== FRAME_VERSION) throw frameError(`unsupported frame version ${String(h.version)}`);\n if (!Number.isInteger(h.flags) || h.flags < 0 || h.flags > 3) throw frameError(`reserved frame flag bits set: ${h.flags}`);\n if (!CHANNELS.has(h.channel)) throw frameError(`unknown frame channel ${String(h.channel)}`);\n checkU32(\"cid\", h.cid);\n checkU32(\"sid\", h.sid);\n checkU32(\"seq\", h.seq);\n}\n\nexport function encodeFrame(h: FrameHeader, payload: Uint8Array): Uint8Array {\n assertFrameHeader(h);\n const out = new Uint8Array(FRAME_HEADER_BYTES + payload.byteLength);\n const v = new DataView(out.buffer);\n v.setUint8(0, h.version);\n v.setUint8(1, h.flags);\n v.setUint8(2, h.channel);\n v.setUint8(3, 0);\n v.setUint32(4, h.cid);\n v.setUint32(8, h.sid);\n v.setUint32(12, h.seq);\n out.set(payload, FRAME_HEADER_BYTES);\n return out;\n}\n\nexport function decodeFrame(buf: ArrayBuffer | Uint8Array): DecodedFrame {\n const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);\n if (bytes.byteLength < FRAME_HEADER_BYTES) throw frameError(`short frame: ${bytes.byteLength} bytes`);\n const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n if (v.getUint8(3) !== 0) throw frameError(\"reserved frame byte 3 is not 0\");\n const header = {\n version: v.getUint8(0),\n flags: v.getUint8(1),\n channel: v.getUint8(2),\n cid: v.getUint32(4),\n sid: v.getUint32(8),\n seq: v.getUint32(12),\n } as FrameHeader;\n assertFrameHeader(header);\n return { header, payload: bytes.subarray(FRAME_HEADER_BYTES) };\n}\n\n/** Read only the 4-byte cid (relay routing) without decoding the rest. */\nexport function readCid(frame: Uint8Array): number {\n if (frame.byteLength < FRAME_HEADER_BYTES) throw frameError(`short frame: ${frame.byteLength} bytes`);\n return new DataView(frame.buffer, frame.byteOffset, frame.byteLength).getUint32(4);\n}\n\n/** Relay hot path: rewrite only the cid IN PLACE, never touch the payload. Returns the same array. */\nexport function stampCid(frame: Uint8Array, cid: number): Uint8Array {\n if (frame.byteLength < FRAME_HEADER_BYTES) throw frameError(`short frame: ${frame.byteLength} bytes`);\n checkU32(\"cid\", cid);\n new DataView(frame.buffer, frame.byteOffset, frame.byteLength).setUint32(4, cid);\n return frame;\n}\n\nexport function hasFlag(header: FrameHeader, flag: (typeof FrameFlag)[keyof typeof FrameFlag]): boolean {\n return (header.flags & flag) !== 0;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Relay ↔ device hop (never seen by clients). Every JSON envelope rides an ENVELOPE frame with\n// flags 0, sid 0, seq 0 and the client's cid; byte frames carry that cid too.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** cid 0 on an ENVELOPE frame from the device: the relay delivers it to every client. */\nexport const BROADCAST_CID = 0 as const;\n\n/**\n * Connection end: an ENVELOPE frame with FIN, sid 0, seq 0 and NO payload, for connection `cid`.\n * Relay → device: client `cid` is gone — cancel its streams, detach its sessions (idempotent; it\n * may arrive more than once). Device → relay: close client `cid`.\n */\nexport function connectionEndFrame(cid: number): Uint8Array {\n if (cid === BROADCAST_CID) throw frameError(\"a connection end needs a client cid, not the broadcast cid 0\");\n return encodeFrame({ version: FRAME_VERSION, flags: FrameFlag.FIN, channel: FrameChannel.ENVELOPE, cid, sid: 0, seq: 0 }, new Uint8Array(0));\n}\n\n/** True for a decoded connection-end frame (see connectionEndFrame). */\nexport function isConnectionEnd(frame: DecodedFrame): boolean {\n const h = frame.header;\n return h.channel === FrameChannel.ENVELOPE && hasFlag(h, FrameFlag.FIN) && frame.payload.byteLength === 0 && h.cid !== BROADCAST_CID;\n}\n","/** @ai-matrx/desktop-protocol — the JSON envelope (SPEC §4). Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { ProtocolErrorBody } from \"./errors\";\nimport { DeviceId, ProtocolVersion, RequestId, ResourceId, epochMs, u32 } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Client types and hello\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const ClientType = z\n .enum([\"screen\", \"web\", \"extension\", \"server\", \"test\"]);\n\nexport const Limits = z\n .strictObject({\n max_message_bytes: z.int().min(65_536),\n max_frame_payload_bytes: z.int().min(4096),\n default_window_bytes: z.int().min(4096),\n max_streams_per_client: z.int().min(1),\n max_resources_per_user: z.int().min(1),\n });\n\nexport const OpDescriptor = z\n .strictObject({ cap: z.string().max(32), op: z.string().max(64), since: ProtocolVersion });\n\nexport const Welcome = z\n .strictObject({\n protocol_version: ProtocolVersion, // negotiated = min(client, core) within the same major\n session_id: z.string().min(8).max(64),\n client_id: z.string().min(8).max(64), // this connection's identity in the Session Manager\n device_id: DeviceId,\n device_name: z.string().max(128),\n app_version: z.string().max(32),\n platform: z.enum([\"darwin\", \"win32\", \"linux\"]),\n ops: z.array(OpDescriptor),\n limits: Limits,\n server_time_ms: epochMs,\n });\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Envelope (SPEC §4). Text WS messages carry exactly one of these as JSON.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const HelloMsg = z\n .strictObject({\n type: z.literal(\"hello\"),\n id: RequestId, // answered by response{id, result: Welcome} or error{id}\n protocolVersion: ProtocolVersion,\n clientType: ClientType,\n clientVersion: z.string().min(1).max(32),\n });\n\nexport const RequestMsg = z\n .strictObject({\n id: RequestId,\n type: z.literal(\"request\"),\n cap: z.string().min(1).max(32),\n op: z.string().min(1).max(64),\n params: z.unknown(), // validated by the Router against OPS[cap.op].params — once, there\n });\n\nexport const ResponseMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"response\"), result: z.unknown() });\n\nexport const ErrorMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"error\"), error: ProtocolErrorBody });\n\nexport const StreamMeta = z\n .discriminatedUnion(\"kind\", [\n /** Binds request id → numeric sid; binary frames for this stream follow. */\n z.strictObject({\n kind: z.literal(\"open\"),\n sid: u32,\n window_bytes: z.int().min(4096),\n resource_id: ResourceId.optional(),\n }),\n /** Frames after this (channel SNAPSHOT) are a serialized screen; live DATA resumes after. */\n z.strictObject({ kind: z.literal(\"snapshot\"), cols: z.int().min(1), rows: z.int().min(1) }),\n /** Frames [from_seq, to_seq] are gone from the ring; a snapshot follows. */\n z.strictObject({ kind: z.literal(\"gap\"), from_seq: u32, to_seq: u32 }),\n ]);\n\nexport const StreamMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"stream\"), seq: u32, meta: StreamMeta });\n\nexport const EndReason = z\n .enum([\"completed\", \"cancelled\", \"detached\", \"resource_exited\", \"error\"]);\n\nexport const EndMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"end\"), seq: u32, reason: EndReason.optional() });\n\nexport const CancelMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"cancel\") });\n\n/** Grant n more payload bytes for the stream opened by request `id` (either direction). */\nexport const CreditMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"credit\"), n: z.int().min(1).max(2_147_483_647) });\n\nexport const EventMsg = z\n .strictObject({\n type: z.literal(\"event\"),\n cap: z.string().min(1).max(32),\n name: z.string().min(1).max(64),\n payload: z.unknown(), // validated against EVENTS[cap.name]\n resourceId: ResourceId.optional(),\n });\n\n/** Client↔relay only; the relay consumes these and never forwards them to the core. */\nexport const RelayMsg = z\n .discriminatedUnion(\"op\", [\n /** Fresh access token before the current one expires (relay closes 4008 at exp + 60 s). */\n z.strictObject({ type: z.literal(\"relay\"), op: z.literal(\"reauth\"), token: z.string().min(16).max(8192) }),\n ]);\n\n/**\n * Heartbeat. Sent as these EXACT bytes; the relay answers via the Durable Object\n * setWebSocketAutoResponse pair, so a heartbeat never wakes a hibernated object.\n * Interval 25 s (device and clients); 2 missed pongs = reconnect.\n */\nexport const PING_TEXT = '{\"type\":\"ping\"}' as const;\nexport const PONG_TEXT = '{\"type\":\"pong\"}' as const;\n\nexport const ClientToCoreMsg = z\n .discriminatedUnion(\"type\", [HelloMsg, RequestMsg, CancelMsg, CreditMsg]);\n\nexport const CoreToClientMsg = z\n .discriminatedUnion(\"type\", [ResponseMsg, ErrorMsg, StreamMsg, EndMsg, CreditMsg, EventMsg]);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// WebSocket close codes (relay and localhost transport alike)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const CloseCode = {\n NORMAL: 1000,\n GOING_AWAY: 1001, // app quit; relay: the device was silent for 75 s — reconnect\n /** Never sent by anyone: what a socket reports when it drops without a close frame. A relay\n * deploy (every Durable Object restarts) arrives as this — reconnect immediately. */\n ABNORMAL: 1006,\n /** Relay → clients: the device (re)connected, so the core session they spoke to is gone —\n * reconnect, hello, and reattach with since_seq. */\n DEVICE_RECONNECTED: 1012,\n TRY_AGAIN_LATER: 1013, // relay: signing keys or the device registry unreachable — retry\n AUTH_INVALID: 4001,\n AUTH_FORBIDDEN: 4003,\n DEVICE_NOT_FOUND: 4004,\n AUTH_EXPIRED: 4008, // no reauth before exp + 60 s\n REPLACED: 4009, // a newer device socket for the same device took over\n DEVICE_REVOKED: 4010, // kill switch — do NOT reconnect\n PROTOCOL_ERROR: 4400,\n UPGRADE_REQUIRED: 4426,\n} as const;\n\n/** Every close code above, as a schema (so Python sees the same table). */\nexport const CloseCodeValue = z.literal([1000, 1001, 1006, 1012, 1013, 4001, 4003, 4004, 4008, 4009, 4010, 4400, 4426]);\nexport type CloseCodeValue = z.output<typeof CloseCodeValue>;\n\n// Compile-time proof the schema lists exactly the CloseCode table.\ntype SameCodes<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\ntype AssertCodes<T extends true> = T;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype CloseCodeTableCheck = AssertCodes<SameCodes<CloseCodeValue, (typeof CloseCode)[keyof typeof CloseCode]>>;\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type ClientType = z.output<typeof ClientType>;\nexport type Limits = z.output<typeof Limits>;\nexport type OpDescriptor = z.output<typeof OpDescriptor>;\nexport type Welcome = z.output<typeof Welcome>;\nexport type HelloMsg = z.output<typeof HelloMsg>;\nexport type RequestMsg = z.output<typeof RequestMsg>;\nexport type ResponseMsg = z.output<typeof ResponseMsg>;\nexport type ErrorMsg = z.output<typeof ErrorMsg>;\nexport type StreamMeta = z.output<typeof StreamMeta>;\nexport type StreamMsg = z.output<typeof StreamMsg>;\nexport type EndReason = z.output<typeof EndReason>;\nexport type EndMsg = z.output<typeof EndMsg>;\nexport type CancelMsg = z.output<typeof CancelMsg>;\nexport type CreditMsg = z.output<typeof CreditMsg>;\nexport type EventMsg = z.output<typeof EventMsg>;\nexport type RelayMsg = z.output<typeof RelayMsg>;\nexport type ClientToCoreMsg = z.output<typeof ClientToCoreMsg>;\nexport type CoreToClientMsg = z.output<typeof CoreToClientMsg>;\n","/** @ai-matrx/desktop-protocol — error model (SPEC §5). Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport type { ErrorCodeName, ErrorData, ErrorReasonName } from \"../types\";\nimport { AbsPath, ProtocolVersion, nonNegInt } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Errors (SPEC §5, plus the five additions marked NEW)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const ErrorCode = z\n .enum([\n \"AUTH_REQUIRED\",\n \"AUTH_INVALID\",\n \"AUTH_EXPIRED\",\n \"AUTH_FORBIDDEN\", // signed in, but not this device's owner\n \"AUTH_DEVICE_REVOKED\", // kill switch\n \"PERMISSION_DENIED_OS\",\n \"NOT_FOUND\",\n \"CONFLICT\",\n \"INVALID_PARAMS\",\n \"RESOURCE_BUSY\",\n \"RESOURCE_GONE\",\n \"CANCELLED\",\n \"TIMEOUT\",\n \"PLATFORM_UNSUPPORTED\",\n \"RATE_LIMITED\",\n \"INTERNAL\",\n \"PROTOCOL_VERSION_UNSUPPORTED\", // NEW: hello refused, carries data.upgrade\n \"PROTOCOL_ERROR\", // NEW: malformed envelope/frame, credit overrun, unknown sid\n \"UNKNOWN_OPERATION\", // NEW: cap.op not served by this core version\n \"DEVICE_OFFLINE\", // NEW: relay has no live device socket (retryable)\n \"PAYLOAD_TOO_LARGE\", // NEW: message or frame above limits.max_*_bytes\n ]);\n\n/** Machine reason under a code, so clients branch without parsing messages. */\nexport const ErrorReason = z\n .enum([\n \"not_a_directory\",\n \"is_a_directory\",\n \"directory_not_empty\",\n \"already_exists\",\n \"stale_write\", // fs.write if_match_mtime_ms mismatch → CONFLICT\n \"binary_content\", // utf8 read of non-UTF-8 bytes → INVALID_PARAMS\n \"not_utf8_boundary\",\n \"patch_no_match\",\n \"patch_ambiguous\",\n \"resource_exited\",\n \"resource_expired\",\n \"control_taken\", // another client of the same user took control\n \"window_exhausted\",\n ]);\n\nexport const ProtocolErrorBody = z\n .strictObject({\n code: ErrorCode,\n message: z.string().max(300), // short, human, never a stack trace or a token\n retryable: z.boolean(),\n data: z\n .strictObject({\n reason: ErrorReason.optional(),\n cap: z.string().max(32).optional(),\n op: z.string().max(64).optional(),\n path: AbsPath.optional(),\n settings_url: z.string().max(512).optional(), // PERMISSION_DENIED_OS deep link\n retry_after_ms: nonNegInt.optional(),\n limit_bytes: nonNegInt.optional(),\n upgrade: z\n .strictObject({\n min_version: ProtocolVersion,\n max_version: ProtocolVersion,\n download_url: z.url().optional(),\n })\n .optional(),\n })\n .optional(),\n });\n\n\n// Compile-time proof the zod-free twins in ../types.ts equal these schemas.\ntype Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\ntype AssertTrue<T extends true> = T;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype ErrorTwinCheck = [\n AssertTrue<Same<z.infer<typeof ErrorCode>, ErrorCodeName>>,\n AssertTrue<Same<z.infer<typeof ErrorReason>, ErrorReasonName>>,\n AssertTrue<Same<NonNullable<z.input<typeof ProtocolErrorBody>[\"data\"]>, ErrorData>>,\n];\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type ErrorCode = z.output<typeof ErrorCode>;\nexport type ErrorReason = z.output<typeof ErrorReason>;\nexport type ProtocolErrorBody = z.output<typeof ProtocolErrorBody>;\n","/** @ai-matrx/desktop-protocol — version and primitive schemas. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Version\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const PROTOCOL_MAJOR = 1 as const;\nexport const PROTOCOL_MINOR = 0 as const;\n/** \"major.minor\". Same major = compatible (minor adds optional fields/ops only). */\nexport const ProtocolVersion = z\n .string()\n .regex(/^[1-9][0-9]{0,2}\\.[0-9]{1,3}$/);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Primitives\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Client-generated request id, unique per session. */\nexport const RequestId = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[A-Za-z0-9_-]+$/);\n\n/** Long-lived resource handle minted by the core: \"<kind>_<base62>\" (pty_…, watch_…). */\nexport const ResourceId = z\n .string()\n .regex(/^(pty|watch)_[A-Za-z0-9]{16,40}$/);\n\n/**\n * = app_instances.id. A plain pattern, NOT z.uuid(): z.uuid() emits `format: uuid` + `pattern`,\n * which datamodel-codegen renders as `Annotated[UUID, Field(pattern=...)]` — a model Pydantic can\n * never validate (\"Unable to apply constraint 'pattern' … of type 'uuid'\"). generate.ts now\n * refuses format+pattern on one node so this class cannot come back.\n */\nexport const DeviceId = z\n .string()\n .regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/);\n\n/**\n * Absolute, normalized path: forward slashes on every OS, NFC. POSIX \"/...\" or Windows \"C:/...\".\n * Normalization happens once, in the fs owner (SPEC §9); the wire never carries backslashes.\n */\nexport const AbsPath = z\n .string()\n .min(1)\n .max(4096)\n .regex(/^(\\/|[A-Za-z]:\\/)[^\\\\\\u0000]*$/);\n\n/** Internal building blocks — deliberately unnamed in $defs (inlined wherever used). */\nexport const u32 = z.int().min(0).max(4_294_967_295);\nexport const nonNegInt = z.int().min(0);\n/** Unix epoch milliseconds. */\nexport const epochMs = z.int().min(0);\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type ProtocolVersion = z.output<typeof ProtocolVersion>;\nexport type RequestId = z.output<typeof RequestId>;\nexport type ResourceId = z.output<typeof ResourceId>;\nexport type DeviceId = z.output<typeof DeviceId>;\nexport type AbsPath = z.output<typeof AbsPath>;\n","/** @ai-matrx/desktop-protocol — binary frame header and flow-control constants. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { FRAME_VERSION } from \"../frame\";\nimport type { FrameHeader as FrameHeaderShape } from \"../frame\";\nimport { u32 } from \"./primitives\";\n\n/** Zod twin of the codec's FrameHeader (layout documented in src/frame.ts) — for $defs and Pydantic. */\nexport const FrameHeader = z\n .strictObject({\n version: z.literal(FRAME_VERSION),\n flags: z.int().min(0).max(3),\n channel: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(255)]),\n cid: u32,\n sid: u32,\n seq: u32,\n });\nexport type FrameHeader = z.infer<typeof FrameHeader>;\n\n/** Relay ↔ device hop: the header of a frame carrying one JSON envelope. cid 0 = broadcast (device → relay). */\nexport const RelayHopEnvelopeHeader = z\n .strictObject({\n version: z.literal(FRAME_VERSION),\n flags: z.literal(0),\n channel: z.literal(255),\n cid: u32,\n sid: z.literal(0),\n seq: z.literal(0),\n });\nexport type RelayHopEnvelopeHeader = z.infer<typeof RelayHopEnvelopeHeader>;\n\n/** Relay ↔ device hop: the header of a connection-end frame (FIN, empty payload; see connectionEndFrame). */\nexport const RelayHopConnectionEnd = z\n .strictObject({\n version: z.literal(FRAME_VERSION),\n flags: z.literal(1),\n channel: z.literal(255),\n cid: z.int().min(1).max(4_294_967_295),\n sid: z.literal(0),\n seq: z.literal(0),\n });\nexport type RelayHopConnectionEnd = z.infer<typeof RelayHopConnectionEnd>;\n\n// Compile-time proof the zod twin and the zod-free codec type are the same shape.\ntype Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\ntype AssertTrue<T extends true> = T;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype FrameHeaderTwinCheck = AssertTrue<Same<z.infer<typeof FrameHeader>, FrameHeaderShape>>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Flow control (credits)\n//\n// The RECEIVER of a byte stream grants the SENDER a window in payload bytes. The sender may have at\n// most `window` un-credited payload bytes in flight per sid; it pauses its source (node-pty\n// pause(), file read loop) at zero and resumes on credit. Initial window = request's\n// `window_bytes` or limits.default_window_bytes. The receiver sends credit{n} after it has\n// CONSUMED n bytes (xterm write callback fired, file chunk persisted). Overrun → PROTOCOL_ERROR\n// and the stream is ended. Credits are end-to-end (client↔core), so the relay holds at most\n// sum(windows) per device and never buffers without bound. Unary JSON ops are not credited.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const DEFAULT_WINDOW_BYTES = 262_144 as const; // 256 KiB\nexport const DEFAULT_MAX_FRAME_PAYLOAD_BYTES = 65_536 as const; // 64 KiB\nexport const DEFAULT_MAX_MESSAGE_BYTES = 8_388_608 as const; // 8 MiB JSON message cap\n\n","/** @ai-matrx/desktop-protocol — cap sysinfo. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { AbsPath, DeviceId, ProtocolVersion, nonNegInt } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// sysinfo\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const OsPermissionName = z\n .enum([\n \"full_disk_access\",\n \"accessibility\",\n \"screen_recording\",\n \"microphone\",\n \"camera\",\n \"automation\",\n \"contacts\",\n \"calendars\",\n \"photos\",\n \"location\",\n \"local_network\",\n \"bluetooth\",\n \"notifications\",\n ]);\n\nexport const SysinfoGetParams = z.strictObject({});\nexport const SysinfoGetResult = z\n .strictObject({\n device_id: DeviceId,\n device_name: z.string().max(128),\n hostname: z.string().max(255),\n platform: z.enum([\"darwin\", \"win32\", \"linux\"]),\n os_version: z.string().max(64),\n arch: z.enum([\"arm64\", \"x64\"]),\n app_version: z.string().max(32),\n protocol_version: ProtocolVersion,\n user: z.strictObject({ username: z.string().max(128), shell: z.string().max(512) }),\n paths: z.strictObject({\n home: AbsPath,\n desktop: AbsPath,\n documents: AbsPath,\n downloads: AbsPath,\n app_data: AbsPath,\n temp: AbsPath,\n }),\n cpu: z.strictObject({ model: z.string().max(128), cores: z.int().min(1) }),\n memory: z.strictObject({ total_bytes: nonNegInt, free_bytes: nonNegInt }),\n uptime_seconds: nonNegInt,\n on_battery: z.boolean().nullable(),\n sleep_prevented: z.boolean(), // true while any remote session holds the power blocker\n permissions: z.array(\n z.strictObject({\n name: OsPermissionName,\n state: z.enum([\"granted\", \"denied\", \"not_determined\", \"not_applicable\"]),\n settings_url: z.string().max(512).nullable(),\n }),\n ),\n });\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type OsPermissionName = z.output<typeof OsPermissionName>;\nexport type SysinfoGetParams = z.output<typeof SysinfoGetParams>;\nexport type SysinfoGetResult = z.output<typeof SysinfoGetResult>;\n","/** @ai-matrx/desktop-protocol — cap fs. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { AbsPath, ResourceId, epochMs, nonNegInt } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// fs — mirrors matrx_agent daemon /fs/* field names (SPEC §6.1)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const FsKind = z.enum([\"file\", \"dir\", \"symlink\"]);\n\n/** = daemon get_stat_dict(), plus mtime in ms and hidden. */\nexport const FsEntry = z\n .strictObject({\n name: z.string().max(1024),\n path: AbsPath,\n kind: FsKind,\n size: nonNegInt,\n mtime: z.number().min(0), // seconds, float — daemon parity\n mtime_ms: epochMs,\n mode: z.int().min(0).max(0o7777),\n target: AbsPath.nullable(), // symlink target, never followed\n hidden: z.boolean(),\n });\n\nexport const FsListParams = z\n .strictObject({\n path: AbsPath,\n recursive: z.boolean().default(false),\n depth: z.int().min(1).max(32).default(1),\n pattern: z.string().max(256).optional(), // glob on name\n limit: z.int().min(1).max(5000).default(500),\n page_token: z.string().max(256).optional(),\n show_hidden: z.boolean().default(false),\n sort: z.enum([\"name\", \"mtime\", \"size\", \"kind\"]).default(\"kind\"),\n });\nexport const FsListResult = z\n .strictObject({\n entries: z.array(FsEntry),\n truncated: z.boolean(),\n next_page_token: z.string().max(256).nullable(),\n scanned: nonNegInt,\n });\n\nexport const FsStatParams = z.strictObject({ path: AbsPath });\nexport const FsStatResult = FsEntry;\n\nexport const FsEncoding = z.enum([\"utf8\", \"base64\"]);\n\n/** Bounded read. offset = byte offset; limit = chars (utf8) or bytes (base64), as the daemon. */\nexport const FsReadParams = z\n .strictObject({\n path: AbsPath,\n encoding: FsEncoding.default(\"utf8\"),\n offset: nonNegInt.default(0),\n limit: z.int().min(1).max(4_194_304).default(262_144),\n });\nexport const FsReadResult = z\n .strictObject({\n content: z.string(),\n encoding: FsEncoding,\n size: nonNegInt,\n offset: nonNegInt,\n next_offset: nonNegInt,\n truncated: z.boolean(),\n mime: z.string().max(128).nullable(),\n mtime_ms: epochMs, // pass back as if_match_mtime_ms to guard a later write\n });\n\n/** Whole-file or ranged download as binary frames (channel DATA, credited). */\nexport const FsReadStreamParams = z\n .strictObject({\n path: AbsPath,\n offset: nonNegInt.default(0),\n length: nonNegInt.optional(), // absent = to EOF\n window_bytes: z.int().min(4096).max(16_777_216).optional(),\n });\n/** Unary result arrives first (size/mime), then stream{open} + DATA frames + end. */\nexport const FsReadStreamResult = z\n .strictObject({ size: nonNegInt, mime: z.string().max(128).nullable(), mtime_ms: epochMs });\n\nexport const FsWriteParams = z\n .strictObject({\n path: AbsPath,\n content: z.string().max(5_592_406), // ≤ 4 MiB of bytes after base64 decode\n encoding: FsEncoding.default(\"utf8\"),\n mode: z.int().min(0).max(0o7777).optional(),\n create_parents: z.boolean().default(false),\n /** Optimistic concurrency: CONFLICT/stale_write if the file changed since this mtime. */\n if_match_mtime_ms: epochMs.optional(),\n /** Refuse to replace an existing file (CONFLICT/already_exists). */\n exclusive: z.boolean().default(false),\n });\n/** Writes are atomic: temp file in the same directory + rename (daemon parity). */\nexport const FsWriteResult = z\n .strictObject({ path: AbsPath, size: nonNegInt, mtime_ms: epochMs, created: z.boolean() });\n\nexport const FsMkdirParams = z\n .strictObject({ path: AbsPath, parents: z.boolean().default(false) });\nexport const FsMkdirResult = z\n .strictObject({ path: AbsPath, created: z.boolean() });\n\n/** = daemon RenameRequest (/fs/rename). */\nexport const FsMoveParams = z\n .strictObject({ from_path: AbsPath, to_path: AbsPath, overwrite: z.boolean().default(false) });\nexport const FsMoveResult = z\n .strictObject({ from_path: AbsPath, to_path: AbsPath });\n\n/**\n * Delete. Default goes to the OS Trash (Finder/Explorer semantics: undoable from the phone's\n * \"Undo\" toast via fs.move back). to_trash:false is a permanent delete — the daemon's behaviour,\n * used by agents through _sandbox_proxy.\n */\nexport const FsDeleteParams = z\n .strictObject({\n path: AbsPath,\n recursive: z.boolean().default(false),\n to_trash: z.boolean().default(true),\n });\nexport const FsDeleteResult = z\n .strictObject({ deleted: z.literal(true), trashed_to: AbsPath.nullable() });\n\n/** Opens a watch resource; changes arrive as event fs.changed with resourceId. */\nexport const FsWatchParams = z\n .strictObject({\n path: AbsPath,\n recursive: z.boolean().default(false),\n ignore: z.array(z.string().max(256)).max(64).default([]),\n debounce_ms: z.int().min(0).max(5000).default(50),\n });\nexport const FsWatchResult = z\n .strictObject({ resource_id: ResourceId, path: AbsPath });\n\n// — Required by lane F (SPEC §6.1 parity sequence and every existing _sandbox_proxy call) —\n\n/** = daemon EditChunk / PatchRequest (/fs/patch). */\nexport const FsPatchParams = z\n .strictObject({\n path: AbsPath,\n edits: z\n .array(\n z.strictObject({\n old_text: z.string(),\n new_text: z.string(),\n replace_all: z.boolean().default(false),\n }),\n )\n .min(1)\n .max(256),\n create_if_missing: z.boolean().default(false),\n });\nexport const FsPatchResult = z\n .strictObject({ path: AbsPath, applied: nonNegInt, size: nonNegInt, mtime_ms: epochMs });\n\n/** = daemon SearchPathRequest (/search/paths). */\nexport const FsSearchPathsParams = z\n .strictObject({\n pattern: z.string().min(1).max(512),\n cwd: AbsPath,\n hidden: z.boolean().default(false),\n max_results: z.int().min(1).max(5000).default(100),\n });\nexport const FsSearchPathsResult = z\n .strictObject({ paths: z.array(AbsPath), truncated: z.boolean() });\n\n/** = daemon SearchContentRequest (/search/content). */\nexport const FsSearchContentParams = z\n .strictObject({\n query: z.string().min(1).max(1024),\n cwd: AbsPath,\n regex: z.boolean().default(true),\n case_sensitive: z.boolean().default(false),\n include: z.array(z.string().max(256)).max(64).optional(),\n exclude: z.array(z.string().max(256)).max(64).optional(),\n max_results: z.int().min(1).max(5000).default(100),\n });\nexport const FsSearchContentResult = z\n .strictObject({\n results: z.array(\n z.strictObject({\n path: AbsPath,\n lines: z.string(),\n line_number: z.int().min(1),\n submatches: z.array(z.strictObject({ match: z.string(), start: nonNegInt, end: nonNegInt })),\n }),\n ),\n truncated: z.boolean(),\n });\n\nexport const FsChange = z\n .strictObject({\n type: z.enum([\"created\", \"modified\", \"deleted\", \"moved\"]),\n path: AbsPath,\n to_path: AbsPath.optional(),\n kind: z.enum([\"file\", \"dir\", \"symlink\", \"unknown\"]),\n });\nexport const FsChangedEvent = z\n .strictObject({ changes: z.array(FsChange).min(1).max(1000), overflow: z.boolean() }); // overflow:true = events dropped; client re-lists\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type FsKind = z.output<typeof FsKind>;\nexport type FsEntry = z.output<typeof FsEntry>;\nexport type FsListParams = z.output<typeof FsListParams>;\nexport type FsListResult = z.output<typeof FsListResult>;\nexport type FsStatParams = z.output<typeof FsStatParams>;\nexport type FsStatResult = z.output<typeof FsStatResult>;\nexport type FsEncoding = z.output<typeof FsEncoding>;\nexport type FsReadParams = z.output<typeof FsReadParams>;\nexport type FsReadResult = z.output<typeof FsReadResult>;\nexport type FsReadStreamParams = z.output<typeof FsReadStreamParams>;\nexport type FsReadStreamResult = z.output<typeof FsReadStreamResult>;\nexport type FsWriteParams = z.output<typeof FsWriteParams>;\nexport type FsWriteResult = z.output<typeof FsWriteResult>;\nexport type FsMkdirParams = z.output<typeof FsMkdirParams>;\nexport type FsMkdirResult = z.output<typeof FsMkdirResult>;\nexport type FsMoveParams = z.output<typeof FsMoveParams>;\nexport type FsMoveResult = z.output<typeof FsMoveResult>;\nexport type FsDeleteParams = z.output<typeof FsDeleteParams>;\nexport type FsDeleteResult = z.output<typeof FsDeleteResult>;\nexport type FsWatchParams = z.output<typeof FsWatchParams>;\nexport type FsWatchResult = z.output<typeof FsWatchResult>;\nexport type FsPatchParams = z.output<typeof FsPatchParams>;\nexport type FsPatchResult = z.output<typeof FsPatchResult>;\nexport type FsSearchPathsParams = z.output<typeof FsSearchPathsParams>;\nexport type FsSearchPathsResult = z.output<typeof FsSearchPathsResult>;\nexport type FsSearchContentParams = z.output<typeof FsSearchContentParams>;\nexport type FsSearchContentResult = z.output<typeof FsSearchContentResult>;\nexport type FsChange = z.output<typeof FsChange>;\nexport type FsChangedEvent = z.output<typeof FsChangedEvent>;\n","/** @ai-matrx/desktop-protocol — cap exec. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { AbsPath, ResourceId, epochMs, nonNegInt, u32 } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// exec — PTY sessions (resources) + one-shot run\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const Signal = z\n .enum([\"SIGINT\", \"SIGTERM\", \"SIGKILL\", \"SIGHUP\", \"SIGQUIT\", \"SIGTSTP\", \"SIGCONT\", \"SIGUSR1\", \"SIGUSR2\"]); // Windows: SIGINT→Ctrl-C event, SIGTERM/SIGKILL/SIGHUP→terminate, others PLATFORM_UNSUPPORTED\n\nconst cols = z.int().min(2).max(1000);\nconst rows = z.int().min(1).max(500);\n\n/**\n * Start a PTY. Response result = PtyInfo; the same request id then carries the output stream:\n * stream{meta:{kind:\"open\",sid,resource_id}} → DATA frames (credited) → end{reason}.\n * Input goes as STDIN frames on that sid (cheap per keystroke) or via exec.pty.write.\n */\nexport const ExecPtyStartParams = z\n .strictObject({\n cols,\n rows,\n cwd: AbsPath.optional(), // default: home\n shell: z.string().max(512).optional(), // default: user's login shell (PowerShell on Windows)\n args: z.array(z.string().max(4096)).max(64).optional(),\n env: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(128), z.string().max(32_768)).optional(),\n name: z.string().max(64).optional(), // tab label\n window_bytes: z.int().min(4096).max(16_777_216).optional(),\n });\n\nexport const PtyInfo = z\n .strictObject({\n resource_id: ResourceId,\n pid: z.int().min(1),\n shell: z.string().max(512),\n cwd: AbsPath, // live, from OSC 7 / process cwd\n title: z.string().max(256),\n name: z.string().max(64).nullable(),\n cols,\n rows,\n state: z.enum([\"running\", \"exited\"]),\n exit_code: z.int().nullable(),\n exit_signal: Signal.nullable(),\n last_seq: u32,\n created_at_ms: epochMs,\n controller_client_id: z.string().max(64).nullable(), // null = orphaned (in grace period)\n attached_clients: nonNegInt,\n orphan_expires_at_ms: epochMs.nullable(),\n });\n\nexport const ExecPtyStartResult = PtyInfo;\n\nexport const ExecPtyWriteParams = z\n .strictObject({ resource_id: ResourceId, data: z.string().min(1).max(65_536) });\nexport const ExecPtyWriteResult = z.strictObject({ written: nonNegInt });\n\nexport const ExecPtyResizeParams = z\n .strictObject({ resource_id: ResourceId, cols, rows });\nexport const ExecPtyResizeResult = z.strictObject({ cols, rows });\n\n/** Delivered to the PTY's foreground process group (daemon parity: tcgetpgrp + killpg). */\nexport const ExecPtySignalParams = z\n .strictObject({ resource_id: ResourceId, signal: Signal });\nexport const ExecPtySignalResult = z.strictObject({ delivered: z.boolean() });\n\n/** SIGHUP the session, SIGKILL after grace_ms, reap, free the resource. Idempotent. */\nexport const ExecPtyKillParams = z\n .strictObject({ resource_id: ResourceId, grace_ms: z.int().min(0).max(30_000).default(2000) });\nexport const ExecPtyKillResult = z\n .strictObject({ exit_code: z.int().nullable(), exit_signal: Signal.nullable() });\n\nexport const ExecListParams = z.strictObject({});\nexport const ExecListResult = z.strictObject({ sessions: z.array(PtyInfo) });\n\n/**\n * One-shot command (agents, via _sandbox_proxy → /exec). Timeout ENFORCED (exit 124, daemon\n * convention). cwd is sticky per cwd_key: a later run with the same key and no cwd starts where\n * the last one ended (SPEC §6.1: \"cd sub && pwd\" then \"pwd\").\n */\nexport const ExecRunParams = z\n .strictObject({\n command: z.string().min(1).max(131_072),\n cwd: AbsPath.optional(),\n cwd_key: z.string().max(128).optional(),\n env: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(128), z.string().max(32_768)).optional(),\n stdin: z.string().max(1_048_576).optional(),\n timeout: z.int().min(1).max(3600).default(60), // seconds, daemon parity\n max_output_bytes: z.int().min(1024).max(8_388_608).default(1_048_576),\n });\nexport const ExecRunResult = z\n .strictObject({\n exit_code: z.int(),\n stdout: z.string(),\n stderr: z.string(),\n cwd: AbsPath,\n duration_ms: nonNegInt,\n timed_out: z.boolean(),\n output_truncated: z.boolean(),\n });\n\nexport const ExecExitedEvent = z\n .strictObject({ exit_code: z.int().nullable(), exit_signal: Signal.nullable() });\nexport const ExecTitleEvent = z.strictObject({ title: z.string().max(256) });\nexport const ExecCwdEvent = z.strictObject({ cwd: AbsPath });\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type Signal = z.output<typeof Signal>;\nexport type ExecPtyStartParams = z.output<typeof ExecPtyStartParams>;\nexport type PtyInfo = z.output<typeof PtyInfo>;\nexport type ExecPtyStartResult = z.output<typeof ExecPtyStartResult>;\nexport type ExecPtyWriteParams = z.output<typeof ExecPtyWriteParams>;\nexport type ExecPtyWriteResult = z.output<typeof ExecPtyWriteResult>;\nexport type ExecPtyResizeParams = z.output<typeof ExecPtyResizeParams>;\nexport type ExecPtyResizeResult = z.output<typeof ExecPtyResizeResult>;\nexport type ExecPtySignalParams = z.output<typeof ExecPtySignalParams>;\nexport type ExecPtySignalResult = z.output<typeof ExecPtySignalResult>;\nexport type ExecPtyKillParams = z.output<typeof ExecPtyKillParams>;\nexport type ExecPtyKillResult = z.output<typeof ExecPtyKillResult>;\nexport type ExecListParams = z.output<typeof ExecListParams>;\nexport type ExecListResult = z.output<typeof ExecListResult>;\nexport type ExecRunParams = z.output<typeof ExecRunParams>;\nexport type ExecRunResult = z.output<typeof ExecRunResult>;\nexport type ExecExitedEvent = z.output<typeof ExecExitedEvent>;\nexport type ExecTitleEvent = z.output<typeof ExecTitleEvent>;\nexport type ExecCwdEvent = z.output<typeof ExecCwdEvent>;\n","/** @ai-matrx/desktop-protocol — cap session. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { PtyInfo } from \"./exec\";\nimport { AbsPath, ResourceId, epochMs, u32 } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// session — generic resource ownership (SPEC §3.3). One attach/detach for EVERY resource kind.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Reattach after a drop. mode \"control\" by the same user takes control (previous controller is\n * demoted to read_only and gets session.control_changed). since_seq = last seq the client\n * rendered: frames (since_seq, last_seq] are replayed from the ring with the REPLAY flag; if they\n * have left the ring, stream{gap} + stream{snapshot} + SNAPSHOT frames come first.\n * Response = PtyInfo|FsWatchResult-shaped ResourceInfo; then the stream continues on a new sid.\n */\nexport const SessionAttachParams = z\n .strictObject({\n resource_id: ResourceId,\n mode: z.enum([\"control\", \"read_only\"]).default(\"control\"),\n since_seq: u32.optional(),\n window_bytes: z.int().min(4096).max(16_777_216).optional(),\n });\n\nexport const ResourceInfo = z\n .discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"pty\"), pty: PtyInfo }),\n z.strictObject({\n kind: z.literal(\"watch\"),\n resource_id: ResourceId,\n path: AbsPath,\n orphan_expires_at_ms: epochMs.nullable(),\n }),\n ]);\nexport const SessionAttachResult = ResourceInfo;\n\n/** Leave the resource running (orphan grace starts if no other client controls it). */\nexport const SessionDetachParams = z.strictObject({ resource_id: ResourceId });\nexport const SessionDetachResult = z\n .strictObject({ orphan_expires_at_ms: epochMs.nullable() });\n\n/** Free a resource through its owner's cancel path (watch → unwatch; pty → exec.pty.kill). */\nexport const SessionReleaseParams = z.strictObject({ resource_id: ResourceId });\nexport const SessionReleaseResult = z.strictObject({ released: z.literal(true) });\n\nexport const SessionListParams = z.strictObject({});\nexport const SessionListResult = z.strictObject({ resources: z.array(ResourceInfo) });\n\nexport const SessionControlChangedEvent = z\n .strictObject({ controller_client_id: z.string().max(64).nullable(), your_mode: z.enum([\"control\", \"read_only\"]) });\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type SessionAttachParams = z.output<typeof SessionAttachParams>;\nexport type ResourceInfo = z.output<typeof ResourceInfo>;\nexport type SessionAttachResult = z.output<typeof SessionAttachResult>;\nexport type SessionDetachParams = z.output<typeof SessionDetachParams>;\nexport type SessionDetachResult = z.output<typeof SessionDetachResult>;\nexport type SessionReleaseParams = z.output<typeof SessionReleaseParams>;\nexport type SessionReleaseResult = z.output<typeof SessionReleaseResult>;\nexport type SessionListParams = z.output<typeof SessionListParams>;\nexport type SessionListResult = z.output<typeof SessionListResult>;\nexport type SessionControlChangedEvent = z.output<typeof SessionControlChangedEvent>;\n","/** @ai-matrx/desktop-protocol — cap relay. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { ProtocolErrorBody } from \"./errors\";\nimport { ProtocolVersion, epochMs } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// relay — events the relay itself emits to clients (cap \"relay\")\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const RelayDeviceStatusEvent = z\n .strictObject({\n online: z.boolean(),\n since_ms: epochMs,\n app_version: z.string().max(32).nullable(),\n protocol_version: ProtocolVersion.nullable(),\n });\nexport const RelayAuthExpiringEvent = z\n .strictObject({ expires_at_ms: epochMs });\n\n/** HTTP POST https://relay.matrxserver.com/v1/devices/{device_id}/call — unary ops only (lane F). */\nexport const RelayCallRequest = z\n .strictObject({\n cap: z.string().min(1).max(32),\n op: z.string().min(1).max(64),\n params: z.unknown(),\n timeout_ms: z.int().min(100).max(3_700_000).default(70_000),\n });\nexport const RelayCallResponse = z\n .discriminatedUnion(\"ok\", [\n z.strictObject({ ok: z.literal(true), result: z.unknown() }),\n z.strictObject({ ok: z.literal(false), error: ProtocolErrorBody }),\n ]);\n\n/**\n * How the relay runs one /call on the device: a fresh cid (its own connection) carrying exactly\n * RelayCallHello then RelayCallEnvelope, answered on that cid by response/error with id \"call\"\n * (an error on id \"hello\" also ends it), then a connection-end frame. A stream answer is refused.\n */\nexport const RELAY_CALL_HELLO_ID = \"hello\" as const;\nexport const RELAY_CALL_REQUEST_ID = \"call\" as const;\n\nexport const RelayCallHello = z\n .strictObject({\n type: z.literal(\"hello\"),\n id: z.literal(RELAY_CALL_HELLO_ID),\n protocolVersion: ProtocolVersion,\n clientType: z.literal(\"server\"),\n clientVersion: z.string().min(1).max(32),\n });\nexport const RelayCallEnvelope = z\n .strictObject({\n id: z.literal(RELAY_CALL_REQUEST_ID),\n type: z.literal(\"request\"),\n cap: z.string().min(1).max(32),\n op: z.string().min(1).max(64),\n params: z.unknown(),\n });\n\n/** HTTP GET /v1/devices/{device_id}/status (owner JWT). */\nexport const RelayStatusResponse = RelayDeviceStatusEvent;\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type RelayDeviceStatusEvent = z.output<typeof RelayDeviceStatusEvent>;\nexport type RelayAuthExpiringEvent = z.output<typeof RelayAuthExpiringEvent>;\nexport type RelayCallRequest = z.output<typeof RelayCallRequest>;\nexport type RelayCallResponse = z.output<typeof RelayCallResponse>;\nexport type RelayStatusResponse = z.output<typeof RelayStatusResponse>;\nexport type RelayCallHello = z.output<typeof RelayCallHello>;\nexport type RelayCallEnvelope = z.output<typeof RelayCallEnvelope>;\n","/** @ai-matrx/desktop-protocol — the op and event registries (Router, client and Python are generated from these). */\nimport { z } from \"zod\";\nimport {\n AbsPath,\n DeviceId,\n ProtocolVersion,\n RequestId,\n ResourceId,\n} from \"./primitives\";\nimport {\n ErrorCode,\n ErrorReason,\n ProtocolErrorBody,\n} from \"./errors\";\nimport {\n FrameHeader,\n RelayHopEnvelopeHeader,\n RelayHopConnectionEnd,\n} from \"./frame\";\nimport {\n CancelMsg,\n ClientToCoreMsg,\n ClientType,\n CoreToClientMsg,\n CreditMsg,\n EndMsg,\n EndReason,\n ErrorMsg,\n EventMsg,\n HelloMsg,\n Limits,\n OpDescriptor,\n RelayMsg,\n RequestMsg,\n ResponseMsg,\n StreamMeta,\n StreamMsg,\n Welcome,\n CloseCodeValue,\n} from \"./envelope\";\nimport {\n OsPermissionName,\n SysinfoGetParams,\n SysinfoGetResult,\n} from \"./sysinfo\";\nimport {\n FsChange,\n FsChangedEvent,\n FsDeleteParams,\n FsDeleteResult,\n FsEncoding,\n FsEntry,\n FsKind,\n FsListParams,\n FsListResult,\n FsMkdirParams,\n FsMkdirResult,\n FsMoveParams,\n FsMoveResult,\n FsPatchParams,\n FsPatchResult,\n FsReadParams,\n FsReadResult,\n FsReadStreamParams,\n FsReadStreamResult,\n FsSearchContentParams,\n FsSearchContentResult,\n FsSearchPathsParams,\n FsSearchPathsResult,\n FsStatParams,\n FsStatResult,\n FsWatchParams,\n FsWatchResult,\n FsWriteParams,\n FsWriteResult,\n} from \"./fs\";\nimport {\n ExecCwdEvent,\n ExecExitedEvent,\n ExecListParams,\n ExecListResult,\n ExecPtyKillParams,\n ExecPtyKillResult,\n ExecPtyResizeParams,\n ExecPtyResizeResult,\n ExecPtySignalParams,\n ExecPtySignalResult,\n ExecPtyStartParams,\n ExecPtyStartResult,\n ExecPtyWriteParams,\n ExecPtyWriteResult,\n ExecRunParams,\n ExecRunResult,\n ExecTitleEvent,\n PtyInfo,\n Signal,\n} from \"./exec\";\nimport {\n ResourceInfo,\n SessionAttachParams,\n SessionAttachResult,\n SessionControlChangedEvent,\n SessionDetachParams,\n SessionDetachResult,\n SessionListParams,\n SessionListResult,\n SessionReleaseParams,\n SessionReleaseResult,\n} from \"./session\";\nimport {\n RelayAuthExpiringEvent,\n RelayCallRequest,\n RelayCallResponse,\n RelayDeviceStatusEvent,\n RelayCallHello,\n RelayCallEnvelope,\n} from \"./relay\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Registries — the Router, the client and the Python side are all generated from these.\n// kind: unary = response only; stream = response, then stream/end on the same id;\n// resource = like stream and the result carries a resource_id the Session Manager owns.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type OpSpec = {\n readonly params: z.ZodType;\n readonly result: z.ZodType;\n readonly kind: \"unary\" | \"stream\" | \"resource\";\n readonly since: \"1.0\";\n readonly errors: readonly z.infer<typeof ErrorCode>[];\n};\n\nconst FS_ERR = [\"NOT_FOUND\", \"PERMISSION_DENIED_OS\", \"INVALID_PARAMS\", \"RESOURCE_BUSY\", \"INTERNAL\"] as const;\n\nexport const OPS = {\n \"sysinfo.get\": { params: SysinfoGetParams, result: SysinfoGetResult, kind: \"unary\", since: \"1.0\", errors: [\"INTERNAL\"] },\n\n \"fs.list\": { params: FsListParams, result: FsListResult, kind: \"unary\", since: \"1.0\", errors: FS_ERR },\n \"fs.stat\": { params: FsStatParams, result: FsStatResult, kind: \"unary\", since: \"1.0\", errors: FS_ERR },\n \"fs.read\": { params: FsReadParams, result: FsReadResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"PAYLOAD_TOO_LARGE\"] },\n \"fs.read_stream\": { params: FsReadStreamParams, result: FsReadStreamResult, kind: \"stream\", since: \"1.0\", errors: [...FS_ERR, \"CANCELLED\"] },\n \"fs.write\": { params: FsWriteParams, result: FsWriteResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"CONFLICT\", \"PAYLOAD_TOO_LARGE\"] },\n \"fs.mkdir\": { params: FsMkdirParams, result: FsMkdirResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"CONFLICT\"] },\n \"fs.move\": { params: FsMoveParams, result: FsMoveResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"CONFLICT\"] },\n \"fs.delete\": { params: FsDeleteParams, result: FsDeleteResult, kind: \"unary\", since: \"1.0\", errors: FS_ERR },\n \"fs.watch\": { params: FsWatchParams, result: FsWatchResult, kind: \"resource\", since: \"1.0\", errors: [...FS_ERR, \"RATE_LIMITED\"] },\n \"fs.patch\": { params: FsPatchParams, result: FsPatchResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"CONFLICT\"] },\n \"fs.search_paths\": { params: FsSearchPathsParams, result: FsSearchPathsResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"TIMEOUT\"] },\n \"fs.search_content\": { params: FsSearchContentParams, result: FsSearchContentResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"TIMEOUT\"] },\n\n \"exec.pty.start\": { params: ExecPtyStartParams, result: ExecPtyStartResult, kind: \"resource\", since: \"1.0\", errors: [\"INVALID_PARAMS\", \"NOT_FOUND\", \"RATE_LIMITED\", \"PLATFORM_UNSUPPORTED\", \"INTERNAL\"] },\n \"exec.pty.write\": { params: ExecPtyWriteParams, result: ExecPtyWriteResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\", \"INVALID_PARAMS\"] },\n \"exec.pty.resize\": { params: ExecPtyResizeParams, result: ExecPtyResizeResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\"] },\n \"exec.pty.signal\": { params: ExecPtySignalParams, result: ExecPtySignalResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\", \"PLATFORM_UNSUPPORTED\"] },\n \"exec.pty.kill\": { params: ExecPtyKillParams, result: ExecPtyKillResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\"] },\n \"exec.list\": { params: ExecListParams, result: ExecListResult, kind: \"unary\", since: \"1.0\", errors: [\"INTERNAL\"] },\n \"exec.run\": { params: ExecRunParams, result: ExecRunResult, kind: \"unary\", since: \"1.0\", errors: [\"INVALID_PARAMS\", \"NOT_FOUND\", \"TIMEOUT\", \"CANCELLED\", \"INTERNAL\"] },\n\n \"session.attach\": { params: SessionAttachParams, result: SessionAttachResult, kind: \"stream\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\", \"RESOURCE_BUSY\"] },\n \"session.detach\": { params: SessionDetachParams, result: SessionDetachResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\"] },\n \"session.release\": { params: SessionReleaseParams, result: SessionReleaseResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\"] },\n \"session.list\": { params: SessionListParams, result: SessionListResult, kind: \"unary\", since: \"1.0\", errors: [\"INTERNAL\"] },\n} as const satisfies Record<string, OpSpec>;\n\nexport type OpName = keyof typeof OPS;\nexport type OpParams<N extends OpName> = z.input<(typeof OPS)[N][\"params\"]>;\nexport type OpResult<N extends OpName> = z.output<(typeof OPS)[N][\"result\"]>;\n\nexport const EVENTS = {\n \"fs.changed\": FsChangedEvent,\n \"exec.exited\": ExecExitedEvent,\n \"exec.title\": ExecTitleEvent,\n \"exec.cwd\": ExecCwdEvent,\n \"session.control_changed\": SessionControlChangedEvent,\n \"relay.device_status\": RelayDeviceStatusEvent,\n \"relay.auth_expiring\": RelayAuthExpiringEvent,\n} as const satisfies Record<string, z.ZodType>;\n\nexport type EventName = keyof typeof EVENTS;\n\n/**\n * Every schema that lands in the generated JSON Schema `$defs` under a stable name (and so becomes a\n * named Pydantic model). Order is the emission order. A test asserts every exported schema of\n * src/schema/* is either listed here or is a documented alias of a listed one.\n * Registered into a PRIVATE zod registry by scripts/generate.ts — never `.meta()`/`.describe()`,\n * which write zod's process-global registry as an import side effect.\n */\nexport const NAMED_SCHEMAS = {\n ProtocolVersion,\n RequestId,\n ResourceId,\n DeviceId,\n AbsPath,\n ErrorCode,\n ErrorReason,\n ProtocolErrorBody,\n FrameHeader,\n ClientType,\n Limits,\n OpDescriptor,\n Welcome,\n HelloMsg,\n RequestMsg,\n ResponseMsg,\n ErrorMsg,\n StreamMeta,\n StreamMsg,\n EndReason,\n EndMsg,\n CancelMsg,\n CreditMsg,\n EventMsg,\n RelayMsg,\n ClientToCoreMsg,\n CoreToClientMsg,\n OsPermissionName,\n SysinfoGetParams,\n SysinfoGetResult,\n FsKind,\n FsEntry,\n FsListParams,\n FsListResult,\n FsStatParams,\n FsEncoding,\n FsReadParams,\n FsReadResult,\n FsReadStreamParams,\n FsReadStreamResult,\n FsWriteParams,\n FsWriteResult,\n FsMkdirParams,\n FsMkdirResult,\n FsMoveParams,\n FsMoveResult,\n FsDeleteParams,\n FsDeleteResult,\n FsWatchParams,\n FsWatchResult,\n FsPatchParams,\n FsPatchResult,\n FsSearchPathsParams,\n FsSearchPathsResult,\n FsSearchContentParams,\n FsSearchContentResult,\n FsChange,\n FsChangedEvent,\n Signal,\n ExecPtyStartParams,\n PtyInfo,\n ExecPtyWriteParams,\n ExecPtyWriteResult,\n ExecPtyResizeParams,\n ExecPtyResizeResult,\n ExecPtySignalParams,\n ExecPtySignalResult,\n ExecPtyKillParams,\n ExecPtyKillResult,\n ExecListParams,\n ExecListResult,\n ExecRunParams,\n ExecRunResult,\n ExecExitedEvent,\n ExecTitleEvent,\n ExecCwdEvent,\n SessionAttachParams,\n ResourceInfo,\n SessionDetachParams,\n SessionDetachResult,\n SessionReleaseParams,\n SessionReleaseResult,\n SessionListParams,\n SessionListResult,\n SessionControlChangedEvent,\n RelayDeviceStatusEvent,\n RelayAuthExpiringEvent,\n RelayCallRequest,\n RelayCallResponse,\n RelayCallHello,\n RelayCallEnvelope,\n RelayHopEnvelopeHeader,\n RelayHopConnectionEnd,\n CloseCodeValue,\n} as const satisfies Record<string, z.ZodType>;\n\nexport type NamedSchemaId = keyof typeof NAMED_SCHEMAS;\n","/**\n * Wire a client's wake() to the browser events that mean \"the person is back\": the page becomes\n * visible again (iOS Safari suspends a background tab's sockets), a back/forward-cache restore\n * (`pageshow` with persisted), and the network returning (`online`). Framework-free; the React\n * binding is `useDesktopWake` in `./react`.\n */\nimport type { DesktopClient, WakeOptions } from \"./types\";\n\n/** The subset of window/document the binding listens on — injectable for tests and non-DOM hosts. */\nexport interface WakeTargets {\n window: Pick<Window, \"addEventListener\" | \"removeEventListener\">;\n document: Pick<Document, \"addEventListener\" | \"removeEventListener\" | \"visibilityState\">;\n}\n\nexport function bindDesktopWake(client: Pick<DesktopClient, \"wake\">, options: WakeOptions & { targets?: WakeTargets } = {}): () => void {\n const targets: WakeTargets | null =\n options.targets ?? (typeof window !== \"undefined\" && typeof document !== \"undefined\" ? { window, document } : null);\n if (!targets) return () => undefined;\n const wakeOptions: WakeOptions = options.probeMs === undefined ? {} : { probeMs: options.probeMs };\n const onVisibility = () => {\n if (targets.document.visibilityState === \"visible\") client.wake(wakeOptions);\n };\n const onWake = () => client.wake(wakeOptions);\n targets.document.addEventListener(\"visibilitychange\", onVisibility);\n targets.window.addEventListener(\"pageshow\", onWake);\n targets.window.addEventListener(\"online\", onWake);\n targets.window.addEventListener(\"focus\", onWake);\n return () => {\n targets.document.removeEventListener(\"visibilitychange\", onVisibility);\n targets.window.removeEventListener(\"pageshow\", onWake);\n targets.window.removeEventListener(\"online\", onWake);\n targets.window.removeEventListener(\"focus\", onWake);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,sBAAwD;;;ACCjD,IAAM,uBAAN,cAAmC,MAAM;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAAqB,SAAiB,UAAsE,CAAC,GAAG;AAC1H,UAAM,SAAS,QAAQ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IAChB,UAAU,UAAU;AAClB,gBAAU,IAAI,QAAQ;AACtB,aAAO,MAAM;AACX,kBAAU,OAAO,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;Aa/zBO,SAAS,gBAAgB,QAAqC,UAAmD,CAAC,GAAe;AACtI,QAAM,UACJ,QAAQ,YAAY,OAAO,WAAW,eAAe,OAAO,aAAa,cAAc,EAAE,QAAQ,SAAS,IAAI;AAChH,MAAI,CAAC,QAAS,QAAO,MAAM;AAC3B,QAAM,cAA2B,QAAQ,YAAY,SAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ;AACjG,QAAM,eAAe,MAAM;AACzB,QAAI,QAAQ,SAAS,oBAAoB,UAAW,QAAO,KAAK,WAAW;AAAA,EAC7E;AACA,QAAM,SAAS,MAAM,OAAO,KAAK,WAAW;AAC5C,UAAQ,SAAS,iBAAiB,oBAAoB,YAAY;AAClE,UAAQ,OAAO,iBAAiB,YAAY,MAAM;AAClD,UAAQ,OAAO,iBAAiB,UAAU,MAAM;AAChD,UAAQ,OAAO,iBAAiB,SAAS,MAAM;AAC/C,SAAO,MAAM;AACX,YAAQ,SAAS,oBAAoB,oBAAoB,YAAY;AACrE,YAAQ,OAAO,oBAAoB,YAAY,MAAM;AACrD,YAAQ,OAAO,oBAAoB,UAAU,MAAM;AACnD,YAAQ,OAAO,oBAAoB,SAAS,MAAM;AAAA,EACpD;AACF;","names":["import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/client/client.ts","../src/error.ts","../src/frame.ts","../src/schema/envelope.ts","../src/schema/errors.ts","../src/schema/primitives.ts","../src/schema/frame.ts","../src/schema/sysinfo.ts","../src/schema/fs.ts","../src/schema/exec.ts","../src/schema/session.ts","../src/schema/relay.ts","../src/schema/registry.ts","../src/client/wake.ts"],"sourcesContent":["/**\n * `@ai-matrx/desktop-protocol/client` — the reconnecting client every TypeScript surface uses to\n * drive a Matrx 2 device (phone console, web app, extension): typed requests by op name, byte\n * streams with credit backpressure, transparent terminal reattach (since_seq replay / gap +\n * snapshot), events, heartbeat, relay reauth. Reconnect uses `createBackoff` from\n * `@ai-matrx/realtime` — the one backoff ladder on the platform.\n */\nexport { createDesktopClient, RECONNECT_ALARM_ATTEMPTS } from \"./client/client\";\nexport { bindDesktopWake } from \"./client/wake\";\nexport type { WakeTargets } from \"./client/wake\";\nexport type {\n ClientTimers,\n DesktopClient,\n DesktopClientDiagnostic,\n DesktopClientOptions,\n DesktopClientState,\n DesktopClientStatus,\n DesktopStream,\n EventHandler,\n EventName,\n EventPayload,\n RequestOptions,\n StreamHandlers,\n StreamOpName,\n StreamOptions,\n WebSocketFactory,\n WebSocketLike,\n WakeOptions,\n} from \"./client/types\";\nexport { DesktopProtocolError, isDesktopProtocolError } from \"./error\";\nexport type { OpName, OpParams, OpResult } from \"./schema/registry\";\n","/**\n * The reconnecting desktop-protocol client: hello → requests, streams with credit-based\n * backpressure, events, transparent reattach of resource streams (terminals, watches) after a\n * drop, heartbeat, and relay reauth. One instance per device connection. All state lives in the\n * closure — no module-level state (dual ESM/CJS graphs would split it).\n */\nimport { RECONNECT_ALARM_ATTEMPTS, createBackoff } from \"@ai-matrx/realtime\";\nimport { DesktopProtocolError } from \"../error\";\nimport { FRAME_VERSION, FrameChannel, decodeFrame, encodeFrame } from \"../frame\";\nimport type { FrameHeader } from \"../frame\";\nimport { CloseCode, CoreToClientMsg, PING_TEXT, PONG_TEXT, Welcome } from \"../schema/envelope\";\nimport type { EndReason, StreamMeta } from \"../schema/envelope\";\nimport type { ProtocolErrorBody } from \"../schema/errors\";\nimport { DEFAULT_MAX_FRAME_PAYLOAD_BYTES, DEFAULT_WINDOW_BYTES } from \"../schema/frame\";\nimport { PROTOCOL_MAJOR, PROTOCOL_MINOR } from \"../schema/primitives\";\nimport { EVENTS, OPS } from \"../schema/registry\";\nimport type { OpName, OpParams, OpResult } from \"../schema/registry\";\nimport type {\n ClientTimers,\n DesktopClient,\n DesktopClientDiagnostic,\n DesktopClientOptions,\n DesktopClientState,\n DesktopStream,\n EventHandler,\n EventName,\n RequestOptions,\n StreamHandlers,\n StreamOpName,\n StreamOptions,\n WakeOptions,\n WebSocketFactory,\n WebSocketLike,\n} from \"./types\";\n\nconst WS_OPEN = 1;\n/** Close codes after which reconnecting is pointless or forbidden. */\nconst TERMINAL_CLOSE: ReadonlyMap<number, [DesktopProtocolError[\"code\"], string]> = new Map([\n [CloseCode.DEVICE_REVOKED, [\"AUTH_DEVICE_REVOKED\", \"This device was revoked\"]],\n [CloseCode.AUTH_FORBIDDEN, [\"AUTH_FORBIDDEN\", \"Not this device's owner\"]],\n [CloseCode.DEVICE_NOT_FOUND, [\"NOT_FOUND\", \"Device not found\"]],\n [CloseCode.REPLACED, [\"CONFLICT\", \"Replaced by a newer connection\"]],\n [CloseCode.UPGRADE_REQUIRED, [\"PROTOCOL_VERSION_UNSUPPORTED\", \"Protocol upgrade required\"]],\n]);\n\ntype Pending = {\n kind: \"unary\";\n op: string;\n resolve: (value: unknown) => void;\n reject: (error: DesktopProtocolError) => void;\n cleanup: () => void;\n};\n\ninterface StreamState {\n op: string;\n handlers: StreamHandlers;\n options: StreamOptions;\n id: string;\n sid: number | null;\n resourceId: string | null;\n /** Last inbound DATA seq delivered to the consumer. */\n lastSeq: number;\n /** Expected next inbound seq, or null right after a gap/snapshot (resync on next frame). */\n expectSeq: number | null;\n windowBytes: number;\n /** Consumed bytes not yet credited back. */\n consumedUncredited: number;\n /** Outbound (STDIN) credit granted by the core. */\n sendWindow: number;\n sendSeq: number;\n sendQueue: Uint8Array[];\n /** Serializes consumer callbacks so credits follow consumption order. */\n chain: Promise<void>;\n resultSettled: boolean;\n resolveResult: (value: unknown) => void;\n rejectResult: (error: DesktopProtocolError) => void;\n resolveDone: (reason: EndReason) => void;\n rejectDone: (error: DesktopProtocolError) => void;\n ended: boolean;\n /** True while a reattach request is in flight for it. */\n reattaching: boolean;\n}\n\nconst defaultTimers: ClientTimers = {\n setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),\n clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),\n now: () => Date.now(),\n};\n\nfunction defaultWebSocket(): WebSocketFactory {\n return (url, protocols) => {\n const Ctor = (globalThis as { WebSocket?: new (url: string, protocols?: string[]) => WebSocketLike }).WebSocket;\n if (!Ctor) {\n throw new DesktopProtocolError(\"PLATFORM_UNSUPPORTED\", \"No global WebSocket — pass options.webSocket\");\n }\n return new Ctor(url, protocols);\n };\n}\n\nfunction capOf(op: string): { cap: string; op: string } {\n const dot = op.indexOf(\".\");\n return { cap: op.slice(0, dot), op: op.slice(dot + 1) };\n}\n\nfunction fromBody(body: ProtocolErrorBody): DesktopProtocolError {\n return body.data === undefined\n ? new DesktopProtocolError(body.code, body.message, { retryable: body.retryable })\n : new DesktopProtocolError(body.code, body.message, { retryable: body.retryable, data: body.data });\n}\n\nfunction toBytes(data: unknown): Uint8Array | null {\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n return null;\n}\n\nexport function createDesktopClient(options: DesktopClientOptions): DesktopClient {\n const timers = options.timers ?? defaultTimers;\n const makeSocket = options.webSocket ?? defaultWebSocket();\n const heartbeatMs = options.heartbeatMs ?? 25_000;\n const requestTimeoutMs = options.requestTimeoutMs ?? 70_000;\n const protocolVersion = options.protocolVersion ?? `${PROTOCOL_MAJOR}.${PROTOCOL_MINOR}`;\n const backoff = createBackoff({ ...options.backoff, now: timers.now });\n const diagnose =\n options.onDiagnostic ??\n ((d: DesktopClientDiagnostic) => {\n console.warn(\"[desktop-protocol]\", d.kind, d);\n });\n\n let state: DesktopClientState = {\n status: \"idle\",\n welcome: null,\n attempts: 0,\n retryInMs: null,\n lastError: null,\n lastCloseCode: null,\n };\n const listeners = new Set<() => void>();\n const readyWaiters = new Set<{ resolve: (w: Welcome) => void; reject: (e: DesktopProtocolError) => void }>();\n const pending = new Map<string, Pending>();\n const streams = new Map<string, StreamState>(); // by current request id\n const bySid = new Map<number, StreamState>();\n const eventHandlers = new Map<string, Set<EventHandler<EventName>>>();\n let socket: WebSocketLike | null = null;\n let socketGeneration = 0;\n let nextId = 0;\n let helloId: string | null = null;\n let reconnectTimer: unknown = null;\n let heartbeatTimer: unknown = null;\n let probeTimer: unknown = null;\n let lastHeardAt = 0;\n /** Inbound messages on the current socket — the wake probe's \"was anything heard since?\" */\n let heardCount = 0;\n let closedByUser = false;\n\n const newId = (prefix: string) => `${prefix}${(++nextId).toString(36)}`;\n\n function setState(patch: Partial<DesktopClientState>): void {\n state = { ...state, ...patch };\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch (error) {\n diagnose({ kind: \"handler_threw\", where: \"subscribe listener\", error });\n }\n }\n }\n\n function sendJson(message: unknown): boolean {\n if (!socket || socket.readyState !== WS_OPEN) return false;\n socket.send(JSON.stringify(message));\n return true;\n }\n\n // ── connection lifecycle ────────────────────────────────────────────────────\n\n function connect(): void {\n if (state.status === \"connecting\" || state.status === \"handshaking\" || state.status === \"open\") return;\n closedByUser = false;\n if (reconnectTimer !== null) {\n timers.clearTimeout(reconnectTimer);\n reconnectTimer = null;\n }\n void openSocket();\n }\n\n async function openSocket(): Promise<void> {\n const generation = ++socketGeneration;\n setState({ status: \"connecting\", retryInMs: null });\n let ws: WebSocketLike;\n try {\n const url = typeof options.url === \"function\" ? await options.url() : options.url;\n const protocols = options.protocols ? await options.protocols() : [];\n if (generation !== socketGeneration || closedByUser) return;\n ws = makeSocket(url, protocols);\n } catch (error) {\n if (generation !== socketGeneration) return;\n const err =\n error instanceof DesktopProtocolError\n ? error\n : new DesktopProtocolError(\"INTERNAL\", \"Could not open the connection\", { retryable: true, cause: error });\n onSocketGone(generation, null, err);\n return;\n }\n socket = ws;\n ws.binaryType = \"arraybuffer\";\n ws.onopen = () => {\n if (generation !== socketGeneration) return;\n lastHeardAt = timers.now();\n helloId = newId(\"h\");\n setState({ status: \"handshaking\" });\n sendJson({ type: \"hello\", id: helloId, protocolVersion, clientType: options.clientType, clientVersion: options.clientVersion });\n scheduleHeartbeat(generation);\n };\n ws.onmessage = (event) => {\n if (generation !== socketGeneration) return;\n lastHeardAt = timers.now();\n heardCount++;\n onMessage(event.data);\n };\n ws.onerror = () => {\n // The close event that always follows carries the code; nothing to do here.\n };\n ws.onclose = (event) => {\n if (generation !== socketGeneration) return;\n onSocketGone(generation, event.code, null);\n };\n }\n\n function scheduleHeartbeat(generation: number): void {\n if (heartbeatTimer !== null) timers.clearTimeout(heartbeatTimer);\n heartbeatTimer = timers.setTimeout(() => {\n heartbeatTimer = null;\n if (generation !== socketGeneration || !socket) return;\n const silentMs = timers.now() - lastHeardAt;\n if (silentMs >= heartbeatMs * 2) {\n diagnose({ kind: \"heartbeat_timeout\", silentMs });\n const dead = socket;\n onSocketGone(generation, null, new DesktopProtocolError(\"TIMEOUT\", \"Connection went silent\", { retryable: true }));\n try {\n dead.close(CloseCode.NORMAL, \"heartbeat timeout\");\n } catch {\n // already closing\n }\n return;\n }\n if (socket.readyState === WS_OPEN) socket.send(PING_TEXT);\n scheduleHeartbeat(generation);\n }, heartbeatMs);\n }\n\n /** The socket is gone (close event, open failure or heartbeat death). */\n function onSocketGone(generation: number, code: number | null, error: DesktopProtocolError | null): void {\n if (generation !== socketGeneration) return;\n socketGeneration++; // ignore anything the dead socket still emits\n if (socket) {\n socket.onopen = socket.onmessage = socket.onclose = socket.onerror = null;\n }\n socket = null;\n helloId = null;\n if (heartbeatTimer !== null) {\n timers.clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n if (probeTimer !== null) {\n timers.clearTimeout(probeTimer);\n probeTimer = null;\n }\n const terminal = code === null ? undefined : TERMINAL_CLOSE.get(code);\n const lost =\n error ??\n (terminal\n ? new DesktopProtocolError(terminal[0], terminal[1])\n : new DesktopProtocolError(\"DEVICE_OFFLINE\", \"Connection lost\", { retryable: true }));\n\n // Unary requests cannot survive a drop: the caller decides whether to retry.\n for (const [id, p] of pending) {\n pending.delete(id);\n p.cleanup();\n p.reject(lost);\n }\n // Resource streams survive (reattach on reconnect); everything else ends now.\n bySid.clear();\n for (const [id, s] of streams) {\n if (s.resourceId !== null && terminal === undefined && !closedByUser) {\n s.sid = null;\n s.reattaching = false;\n continue;\n }\n streams.delete(id);\n endStream(s, null, lost);\n }\n\n if (closedByUser || terminal) {\n setState({ status: \"closed\", welcome: null, lastError: closedByUser ? state.lastError : lost, lastCloseCode: code, retryInMs: null });\n rejectReadyWaiters(lost);\n return;\n }\n const delay = backoff.nextDelayMs();\n if (backoff.isAlarming()) diagnose({ kind: \"reconnect_alarm\", attempts: backoff.attempts() });\n setState({ status: \"reconnecting\", welcome: null, attempts: backoff.attempts(), retryInMs: delay, lastError: lost, lastCloseCode: code });\n reconnectTimer = timers.setTimeout(() => {\n reconnectTimer = null;\n if (!closedByUser) void openSocket();\n }, delay);\n }\n\n function rejectReadyWaiters(error: DesktopProtocolError): void {\n for (const w of [...readyWaiters]) {\n readyWaiters.delete(w);\n w.reject(error);\n }\n }\n\n function close(): void {\n closedByUser = true;\n if (reconnectTimer !== null) {\n timers.clearTimeout(reconnectTimer);\n reconnectTimer = null;\n }\n const cancelled = new DesktopProtocolError(\"CANCELLED\", \"Client closed\");\n const ws = socket;\n if (ws) {\n onSocketGone(socketGeneration, CloseCode.NORMAL, cancelled);\n try {\n ws.close(CloseCode.NORMAL, \"client closed\");\n } catch {\n // already closed\n }\n } else {\n for (const [id, s] of streams) {\n streams.delete(id);\n endStream(s, null, cancelled);\n }\n setState({ status: \"closed\", retryInMs: null });\n rejectReadyWaiters(cancelled);\n }\n }\n\n // ── inbound ────────────────────────────────────────────────────────────────\n\n function onMessage(data: unknown): void {\n if (typeof data === \"string\") {\n if (data === PONG_TEXT) return;\n let json: unknown;\n try {\n json = JSON.parse(data);\n } catch {\n diagnose({ kind: \"malformed_message\", detail: \"not JSON\" });\n return;\n }\n const parsed = CoreToClientMsg.safeParse(json);\n if (!parsed.success) {\n diagnose({ kind: \"malformed_message\", detail: parsed.error.issues.map((i) => `${i.path.join(\".\")}: ${i.message}`).join(\"; \") });\n return;\n }\n onEnvelope(parsed.data);\n return;\n }\n const bytes = toBytes(data);\n if (bytes === null) {\n diagnose({ kind: \"malformed_message\", detail: \"binary message is not an ArrayBuffer/view (set binaryType)\" });\n return;\n }\n let frame: ReturnType<typeof decodeFrame>;\n try {\n frame = decodeFrame(bytes);\n } catch (error) {\n diagnose({ kind: \"malformed_message\", detail: error instanceof Error ? error.message : String(error) });\n return;\n }\n onFrame(frame.header, frame.payload);\n }\n\n function onEnvelope(msg: CoreToClientMsg): void {\n switch (msg.type) {\n case \"response\": {\n if (msg.id === helloId) return onWelcome(msg.result);\n const s = streams.get(msg.id);\n if (s) return onStreamResult(s, msg.result);\n const p = pending.get(msg.id);\n if (!p) return diagnose({ kind: \"unknown_request\", id: msg.id, type: msg.type });\n pending.delete(msg.id);\n p.cleanup();\n p.resolve(msg.result);\n return;\n }\n case \"error\": {\n const error = fromBody(msg.error);\n if (msg.id === helloId) return onHelloRefused(error);\n const s = streams.get(msg.id);\n if (s) {\n if (s.reattaching && s.resourceId !== null) diagnose({ kind: \"reattach_failed\", resourceId: s.resourceId, error });\n streams.delete(msg.id);\n if (s.sid !== null) bySid.delete(s.sid);\n return endStream(s, null, error);\n }\n const p = pending.get(msg.id);\n if (!p) return diagnose({ kind: \"unknown_request\", id: msg.id, type: msg.type });\n pending.delete(msg.id);\n p.cleanup();\n p.reject(error);\n return;\n }\n case \"stream\": {\n const s = streams.get(msg.id);\n if (!s) return diagnose({ kind: \"unknown_request\", id: msg.id, type: msg.type });\n onStreamMeta(s, msg.meta);\n return;\n }\n case \"end\": {\n const s = streams.get(msg.id);\n if (!s) return diagnose({ kind: \"unknown_request\", id: msg.id, type: msg.type });\n // Deliver everything already queued before announcing the end.\n void s.chain.then(() => {\n streams.delete(s.id);\n if (s.sid !== null) bySid.delete(s.sid);\n endStream(s, msg.reason ?? \"completed\", null);\n });\n return;\n }\n case \"credit\": {\n const s = streams.get(msg.id);\n if (!s) return diagnose({ kind: \"unknown_request\", id: msg.id, type: msg.type });\n s.sendWindow += msg.n;\n flushSend(s);\n return;\n }\n case \"event\": {\n const key = `${msg.cap}.${msg.name}`;\n const schema = (EVENTS as Record<string, (typeof EVENTS)[EventName]>)[key];\n if (!schema) return diagnose({ kind: \"malformed_message\", detail: `unknown event ${key}` });\n const payload = schema.safeParse(msg.payload);\n if (!payload.success) return diagnose({ kind: \"malformed_message\", detail: `event ${key}: invalid payload` });\n if (key === \"relay.auth_expiring\" && options.getToken) {\n options.getToken().then(reauth, (error: unknown) => diagnose({ kind: \"reauth_failed\", error }));\n }\n for (const handler of [...(eventHandlers.get(key) ?? [])]) {\n try {\n handler(payload.data as never, msg.resourceId);\n } catch (error) {\n diagnose({ kind: \"handler_threw\", where: `event ${key}`, error });\n }\n }\n return;\n }\n }\n }\n\n function onWelcome(result: unknown): void {\n const welcome = Welcome.safeParse(result);\n if (!welcome.success) {\n onHelloRefused(new DesktopProtocolError(\"PROTOCOL_ERROR\", \"Malformed welcome\"));\n return;\n }\n helloId = null;\n backoff.markConnected();\n setState({ status: \"open\", welcome: welcome.data, attempts: 0, retryInMs: null, lastError: null });\n for (const w of [...readyWaiters]) {\n readyWaiters.delete(w);\n w.resolve(welcome.data);\n }\n // Transparent reattach: every surviving resource stream continues where its consumer stopped.\n for (const s of [...streams.values()]) {\n if (s.sid === null && s.resourceId !== null && !s.ended) reattach(s, welcome.data);\n }\n }\n\n function onHelloRefused(error: DesktopProtocolError): void {\n // An unsupported version will not fix itself on retry: UPGRADE_REQUIRED is a terminal close.\n const ws = socket;\n onSocketGone(socketGeneration, error.code === \"PROTOCOL_VERSION_UNSUPPORTED\" ? CloseCode.UPGRADE_REQUIRED : null, error);\n try {\n ws?.close(CloseCode.NORMAL, \"hello refused\");\n } catch {\n // already closed\n }\n }\n\n // ── streams ────────────────────────────────────────────────────────────────\n\n function onStreamResult(s: StreamState, result: unknown): void {\n if (s.reattaching) {\n // session.attach result = ResourceInfo; the stream continues on the new id.\n s.reattaching = false;\n safeCall(\"onReattached\", () => s.handlers.onReattached?.());\n return;\n }\n const rid = (result as { resource_id?: unknown } | null)?.resource_id;\n if (typeof rid === \"string\") s.resourceId = rid;\n if (!s.resultSettled) {\n s.resultSettled = true;\n s.resolveResult(result);\n }\n }\n\n function onStreamMeta(s: StreamState, meta: StreamMeta): void {\n if (meta.kind === \"open\") {\n if (s.sid !== null) bySid.delete(s.sid);\n s.sid = meta.sid;\n s.windowBytes = meta.window_bytes;\n if (meta.resource_id !== undefined) s.resourceId = meta.resource_id;\n bySid.set(meta.sid, s);\n flushSend(s);\n } else {\n // gap or snapshot: the next DATA frame re-establishes the sequence.\n s.expectSeq = null;\n }\n safeCall(\"onMeta\", () => s.handlers.onMeta?.(meta));\n }\n\n function onFrame(header: FrameHeader, payload: Uint8Array): void {\n const s = bySid.get(header.sid);\n if (!s) {\n diagnose({ kind: \"unknown_stream\", sid: header.sid });\n return;\n }\n const isData = header.channel === FrameChannel.DATA || header.channel === FrameChannel.STDERR;\n const isSnapshot = header.channel === FrameChannel.SNAPSHOT;\n if (!isData && !isSnapshot) {\n diagnose({ kind: \"malformed_message\", detail: `channel ${header.channel} is not client-bound` });\n return;\n }\n if (isData) {\n if (s.expectSeq !== null && header.seq !== s.expectSeq) {\n diagnose({ kind: \"seq_gap\", id: s.id, expected: s.expectSeq, received: header.seq });\n }\n s.expectSeq = header.seq + 1;\n }\n // Copy: the payload is a view into a buffer the transport may reuse.\n const bytes = payload.slice();\n const handler = isData ? s.handlers.onData : s.handlers.onSnapshot;\n s.chain = s.chain.then(async () => {\n if (s.ended) return;\n try {\n await handler?.(bytes, header);\n } catch (error) {\n diagnose({ kind: \"handler_threw\", where: isData ? \"onData\" : \"onSnapshot\", error });\n }\n if (isData) s.lastSeq = header.seq;\n grantCredit(s, bytes.byteLength);\n });\n }\n\n function grantCredit(s: StreamState, consumed: number): void {\n s.consumedUncredited += consumed;\n // Batch: one credit per quarter window keeps the pipe full without a message per frame.\n if (s.consumedUncredited >= Math.max(1, Math.floor(s.windowBytes / 4))) {\n if (sendJson({ type: \"credit\", id: s.id, n: s.consumedUncredited })) s.consumedUncredited = 0;\n }\n }\n\n function flushSend(s: StreamState): void {\n if (s.sid === null || !socket || socket.readyState !== WS_OPEN) return;\n const maxPayload = state.welcome?.limits.max_frame_payload_bytes ?? DEFAULT_MAX_FRAME_PAYLOAD_BYTES;\n while (s.sendQueue.length > 0 && s.sendWindow > 0) {\n const head = s.sendQueue[0]!;\n const n = Math.min(head.byteLength, s.sendWindow, maxPayload);\n const chunk = head.subarray(0, n);\n if (n === head.byteLength) s.sendQueue.shift();\n else s.sendQueue[0] = head.subarray(n);\n s.sendWindow -= n;\n s.sendSeq += 1;\n socket.send(encodeFrame({ version: FRAME_VERSION, flags: 0, channel: FrameChannel.STDIN, cid: 0, sid: s.sid, seq: s.sendSeq }, chunk));\n }\n }\n\n function endStream(s: StreamState, reason: EndReason | null, error: DesktopProtocolError | null): void {\n if (s.ended) return;\n s.ended = true;\n s.sendQueue = [];\n if (!s.resultSettled) {\n s.resultSettled = true;\n s.rejectResult(error ?? new DesktopProtocolError(\"INTERNAL\", \"Stream ended before its result\"));\n }\n if (error) s.rejectDone(error);\n else s.resolveDone(reason ?? \"completed\");\n }\n\n function reattach(s: StreamState, welcome: Welcome): void {\n const id = newId(\"a\");\n streams.delete(s.id);\n s.id = id;\n s.reattaching = true;\n s.expectSeq = s.lastSeq > 0 ? s.lastSeq + 1 : null;\n s.consumedUncredited = 0;\n s.sendWindow = welcome.limits.default_window_bytes;\n s.sendSeq = 0;\n streams.set(id, s);\n const params: Record<string, unknown> = { resource_id: s.resourceId, mode: s.options.mode ?? \"control\" };\n if (s.lastSeq > 0) params.since_seq = s.lastSeq;\n if (s.options.windowBytes !== undefined) params.window_bytes = s.options.windowBytes;\n sendJson({ id, type: \"request\", cap: \"session\", op: \"attach\", params });\n }\n\n function safeCall(where: string, fn: () => void): void {\n try {\n fn();\n } catch (error) {\n diagnose({ kind: \"handler_threw\", where, error });\n }\n }\n\n // ── public API ─────────────────────────────────────────────────────────────\n\n function ready(opts: RequestOptions = {}): Promise<Welcome> {\n if (state.status === \"open\" && state.welcome) return Promise.resolve(state.welcome);\n if (state.status === \"closed\") {\n return Promise.reject(state.lastError ?? new DesktopProtocolError(\"CANCELLED\", \"Client is closed\"));\n }\n if (state.status === \"idle\") connect();\n return new Promise((resolve, reject) => {\n const waiter = {\n resolve: (w: Welcome) => {\n done();\n resolve(w);\n },\n reject: (e: DesktopProtocolError) => {\n done();\n reject(e);\n },\n };\n const timeoutMs = opts.timeoutMs ?? requestTimeoutMs;\n const timer = timers.setTimeout(() => waiter.reject(new DesktopProtocolError(\"DEVICE_OFFLINE\", \"Device not reachable\", { retryable: true })), timeoutMs);\n const onAbort = () => waiter.reject(new DesktopProtocolError(\"CANCELLED\", \"Aborted\"));\n opts.signal?.addEventListener(\"abort\", onAbort, { once: true });\n function done() {\n readyWaiters.delete(waiter);\n timers.clearTimeout(timer);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n }\n readyWaiters.add(waiter);\n });\n }\n\n async function request<N extends OpName>(op: N, params: OpParams<N>, opts: RequestOptions = {}): Promise<OpResult<N>> {\n if (OPS[op].kind !== \"unary\") {\n throw new DesktopProtocolError(\"INVALID_PARAMS\", `${op} is a ${OPS[op].kind} op — use stream()`);\n }\n await ready(opts);\n const id = newId(\"r\");\n return new Promise<OpResult<N>>((resolve, reject) => {\n const timeoutMs = opts.timeoutMs ?? requestTimeoutMs;\n const timer = timers.setTimeout(() => {\n pending.delete(id);\n cleanup();\n sendJson({ id, type: \"cancel\" });\n reject(new DesktopProtocolError(\"TIMEOUT\", `${op} timed out`, { retryable: true }));\n }, timeoutMs);\n const onAbort = () => {\n pending.delete(id);\n cleanup();\n sendJson({ id, type: \"cancel\" });\n reject(new DesktopProtocolError(\"CANCELLED\", \"Aborted\"));\n };\n function cleanup() {\n timers.clearTimeout(timer);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n }\n opts.signal?.addEventListener(\"abort\", onAbort, { once: true });\n pending.set(id, { kind: \"unary\", op, resolve: resolve as (v: unknown) => void, reject, cleanup });\n if (!sendJson({ id, type: \"request\", ...capOf(op), params })) {\n pending.delete(id);\n cleanup();\n reject(new DesktopProtocolError(\"DEVICE_OFFLINE\", \"Connection lost\", { retryable: true }));\n }\n });\n }\n\n function stream<N extends StreamOpName>(\n op: N,\n params: OpParams<N>,\n handlers: StreamHandlers = {},\n opts: StreamOptions = {},\n ): DesktopStream<N> {\n let resolveResult!: (v: unknown) => void;\n let rejectResult!: (e: DesktopProtocolError) => void;\n let resolveDone!: (r: EndReason) => void;\n let rejectDone!: (e: DesktopProtocolError) => void;\n const result = new Promise<OpResult<N>>((res, rej) => {\n resolveResult = res as (v: unknown) => void;\n rejectResult = rej;\n });\n const done = new Promise<EndReason>((res, rej) => {\n resolveDone = res;\n rejectDone = rej;\n });\n // Consumers often await only one of the two; never leave the other as an unhandled rejection.\n result.catch(() => undefined);\n done.catch(() => undefined);\n\n // A caller-started session.attach (a page reload reattaching by the resource id it kept in its\n // URL) is a resource stream from its first byte: it survives drops like the stream that created\n // the resource, and its sequence continues from since_seq rather than from 1.\n const attach = op === \"session.attach\" ? (params as { resource_id: string; since_seq?: number }) : null;\n const s: StreamState = {\n op,\n handlers,\n options: opts,\n id: newId(\"s\"),\n sid: null,\n resourceId: attach ? attach.resource_id : null,\n lastSeq: attach?.since_seq ?? 0,\n expectSeq: attach ? (attach.since_seq === undefined ? null : attach.since_seq + 1) : 1,\n windowBytes: opts.windowBytes ?? DEFAULT_WINDOW_BYTES,\n consumedUncredited: 0,\n sendWindow: DEFAULT_WINDOW_BYTES,\n sendSeq: 0,\n sendQueue: [],\n chain: Promise.resolve(),\n resultSettled: false,\n resolveResult,\n rejectResult,\n resolveDone,\n rejectDone,\n ended: false,\n reattaching: false,\n };\n\n const start = async () => {\n let welcome: Welcome;\n try {\n welcome = await ready(opts);\n } catch (error) {\n endStream(s, null, error as DesktopProtocolError);\n return;\n }\n if (s.ended) return;\n s.sendWindow = welcome.limits.default_window_bytes;\n if (opts.windowBytes === undefined) s.windowBytes = welcome.limits.default_window_bytes;\n streams.set(s.id, s);\n const wire: Record<string, unknown> = { ...(params as Record<string, unknown>) };\n if (opts.windowBytes !== undefined && \"window_bytes\" in OPS[op].params.shape) wire.window_bytes = opts.windowBytes;\n if (!sendJson({ id: s.id, type: \"request\", ...capOf(op), params: wire })) {\n streams.delete(s.id);\n endStream(s, null, new DesktopProtocolError(\"DEVICE_OFFLINE\", \"Connection lost\", { retryable: true }));\n }\n };\n void start();\n opts.signal?.addEventListener(\"abort\", () => handle.cancel(), { once: true });\n\n const encoder = new TextEncoder();\n const handle: DesktopStream<N> = {\n get id() {\n return s.id;\n },\n result,\n done,\n get resourceId() {\n return s.resourceId;\n },\n get lastSeq() {\n return s.lastSeq;\n },\n write(data) {\n if (s.ended) throw new DesktopProtocolError(\"RESOURCE_GONE\", \"Stream has ended\");\n const bytes = typeof data === \"string\" ? encoder.encode(data) : data;\n if (bytes.byteLength === 0) return;\n s.sendQueue.push(bytes);\n flushSend(s);\n },\n cancel() {\n if (s.ended) return;\n if (!sendJson({ id: s.id, type: \"cancel\" })) {\n streams.delete(s.id);\n endStream(s, \"cancelled\", null);\n }\n },\n async detach() {\n if (s.ended) return;\n if (s.resourceId === null) throw new DesktopProtocolError(\"INVALID_PARAMS\", \"Only resource streams can be detached\");\n const resourceId = s.resourceId;\n streams.delete(s.id);\n if (s.sid !== null) bySid.delete(s.sid);\n endStream(s, \"detached\", null);\n await request(\"session.detach\", { resource_id: resourceId });\n },\n };\n return handle;\n }\n\n function on<E extends EventName>(name: E, handler: EventHandler<E>): () => void {\n let set = eventHandlers.get(name);\n if (!set) {\n set = new Set();\n eventHandlers.set(name, set);\n }\n set.add(handler as EventHandler<EventName>);\n return () => {\n set.delete(handler as EventHandler<EventName>);\n };\n }\n\n function reauth(token: string): void {\n sendJson({ type: \"relay\", op: \"reauth\", token });\n }\n\n function wake(opts: WakeOptions = {}): void {\n if (closedByUser || state.status === \"closed\") return;\n if (state.status === \"idle\" || state.status === \"reconnecting\") {\n connect(); // dial now; connect() cancels the scheduled backoff timer\n return;\n }\n if (state.status === \"connecting\" || !socket || probeTimer !== null) return;\n const generation = socketGeneration;\n const heardBefore = heardCount;\n try {\n socket.send(PING_TEXT);\n } catch {\n // A socket that cannot even send is dead: fall through to the probe verdict.\n }\n probeTimer = timers.setTimeout(() => {\n probeTimer = null;\n if (generation !== socketGeneration || !socket) return;\n if (heardCount > heardBefore) return; // answered: the socket is alive\n const silentMs = timers.now() - lastHeardAt;\n diagnose({ kind: \"heartbeat_timeout\", silentMs });\n const dead = socket;\n onSocketGone(generation, null, new DesktopProtocolError(\"TIMEOUT\", \"Connection went silent\", { retryable: true }));\n try {\n dead.close(CloseCode.NORMAL, \"wake probe timeout\");\n } catch {\n // already closing\n }\n if (state.status === \"reconnecting\") connect(); // the person is looking: no backoff wait\n }, opts.probeMs ?? 4000);\n }\n\n return {\n connect,\n close,\n getState: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n ready,\n request,\n stream,\n on,\n reauth,\n wake,\n };\n}\n\nexport { RECONNECT_ALARM_ATTEMPTS };\n","/**\n * The one error type every package entry throws. It carries the wire ErrorCode (SPEC §5), so a\n * caller branches on `code`/`retryable`/`data.reason` and never parses a message. Zod-free on\n * purpose: `./frame` (the relay hot path) throws it without pulling the schema graph.\n */\nimport type { ErrorCodeName, ErrorData } from \"./types\";\n\nexport class DesktopProtocolError extends Error {\n readonly code: ErrorCodeName;\n readonly retryable: boolean;\n readonly data: ErrorData | undefined;\n\n constructor(code: ErrorCodeName, message: string, options: { retryable?: boolean; data?: ErrorData; cause?: unknown } = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = \"DesktopProtocolError\";\n this.code = code;\n this.retryable = options.retryable ?? false;\n this.data = options.data;\n }\n\n /** The wire body (ProtocolErrorBody) — what a core or relay sends for this error. */\n toBody(): { code: ErrorCodeName; message: string; retryable: boolean; data?: ErrorData } {\n return this.data === undefined\n ? { code: this.code, message: this.message, retryable: this.retryable }\n : { code: this.code, message: this.message, retryable: this.retryable, data: this.data };\n }\n}\n\nexport function isDesktopProtocolError(value: unknown): value is DesktopProtocolError {\n return value instanceof DesktopProtocolError || (value instanceof Error && value.name === \"DesktopProtocolError\" && \"code\" in value);\n}\n","/**\n * `@ai-matrx/desktop-protocol/frame` — the 16-byte binary frame codec. ZOD-FREE by design: the\n * relay Worker's hot path imports only this entry and must stay tiny.\n *\n * off size field notes\n * 0 u8 version = 1\n * 1 u8 flags bit0 FIN (last frame of this stream), bit1 REPLAY (from ring buffer),\n * bits2-7 reserved = 0\n * 2 u8 channel see FrameChannel\n * 3 u8 reserved = 0\n * 4 u32 cid relay connection id. 0 on every client↔relay hop; the relay stamps it on\n * the relay→device hop and strips it on the way back (rewrites 4 bytes in\n * place — the relay never parses payloads).\n * 8 u32 sid stream id, announced by the core in stream{meta:{kind:\"open\",sid}}\n * 12 u32 seq per-stream frame sequence, starts at 1, strictly +1\n *\n * Big-endian. Payload length = message length − 16 (one frame = one WS binary message).\n * Python struct format: \">BBBBIII\". The zod twin (FrameHeader in the root entry, and so the JSON\n * Schema and Pydantic model) is checked against this file by src/frame.test.ts.\n */\nimport { DesktopProtocolError } from \"./error\";\n\nexport const FRAME_HEADER_BYTES = 16 as const;\nexport const FRAME_VERSION = 1 as const;\nexport const FRAME_STRUCT_FORMAT = \">BBBBIII\" as const;\nexport const FrameFlag = { FIN: 0b01, REPLAY: 0b10 } as const;\nexport const FrameChannel = {\n /** core→client: pty output, fs.read_stream bytes */\n DATA: 0,\n /** core→client: stderr of a non-pty process (reserved for exec.spawn in v1.1) */\n STDERR: 1,\n /** client→core: keystrokes / stdin to sid */\n STDIN: 2,\n /** core→client: serialized terminal screen (attach when since_seq is outside the ring) */\n SNAPSHOT: 3,\n /** relay↔device hop only: a JSON envelope carried inside a binary frame so the relay can route\n * by cid without parsing JSON. Never seen by clients. */\n ENVELOPE: 255,\n} as const;\n\nexport type FrameChannelValue = (typeof FrameChannel)[keyof typeof FrameChannel];\n\nexport interface FrameHeader {\n version: typeof FRAME_VERSION;\n /** 0..3 — FrameFlag bits. */\n flags: number;\n channel: FrameChannelValue;\n cid: number;\n sid: number;\n seq: number;\n}\n\nexport interface DecodedFrame {\n header: FrameHeader;\n /** A VIEW into the input buffer (no copy). Copy it if you keep it past the input's lifetime. */\n payload: Uint8Array;\n}\n\nconst U32_MAX = 4_294_967_295;\nconst CHANNELS: ReadonlySet<number> = new Set(Object.values(FrameChannel));\n\nfunction frameError(message: string): DesktopProtocolError {\n return new DesktopProtocolError(\"PROTOCOL_ERROR\", message);\n}\n\nfunction checkU32(name: string, value: number): void {\n if (!Number.isInteger(value) || value < 0 || value > U32_MAX) throw frameError(`frame ${name} is not a u32: ${value}`);\n}\n\n/** Validate a header without zod. Throws DesktopProtocolError(PROTOCOL_ERROR). */\nexport function assertFrameHeader(h: FrameHeader): void {\n if (h.version !== FRAME_VERSION) throw frameError(`unsupported frame version ${String(h.version)}`);\n if (!Number.isInteger(h.flags) || h.flags < 0 || h.flags > 3) throw frameError(`reserved frame flag bits set: ${h.flags}`);\n if (!CHANNELS.has(h.channel)) throw frameError(`unknown frame channel ${String(h.channel)}`);\n checkU32(\"cid\", h.cid);\n checkU32(\"sid\", h.sid);\n checkU32(\"seq\", h.seq);\n}\n\nexport function encodeFrame(h: FrameHeader, payload: Uint8Array): Uint8Array {\n assertFrameHeader(h);\n const out = new Uint8Array(FRAME_HEADER_BYTES + payload.byteLength);\n const v = new DataView(out.buffer);\n v.setUint8(0, h.version);\n v.setUint8(1, h.flags);\n v.setUint8(2, h.channel);\n v.setUint8(3, 0);\n v.setUint32(4, h.cid);\n v.setUint32(8, h.sid);\n v.setUint32(12, h.seq);\n out.set(payload, FRAME_HEADER_BYTES);\n return out;\n}\n\nexport function decodeFrame(buf: ArrayBuffer | Uint8Array): DecodedFrame {\n const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);\n if (bytes.byteLength < FRAME_HEADER_BYTES) throw frameError(`short frame: ${bytes.byteLength} bytes`);\n const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n if (v.getUint8(3) !== 0) throw frameError(\"reserved frame byte 3 is not 0\");\n const header = {\n version: v.getUint8(0),\n flags: v.getUint8(1),\n channel: v.getUint8(2),\n cid: v.getUint32(4),\n sid: v.getUint32(8),\n seq: v.getUint32(12),\n } as FrameHeader;\n assertFrameHeader(header);\n return { header, payload: bytes.subarray(FRAME_HEADER_BYTES) };\n}\n\n/** Read only the 4-byte cid (relay routing) without decoding the rest. */\nexport function readCid(frame: Uint8Array): number {\n if (frame.byteLength < FRAME_HEADER_BYTES) throw frameError(`short frame: ${frame.byteLength} bytes`);\n return new DataView(frame.buffer, frame.byteOffset, frame.byteLength).getUint32(4);\n}\n\n/** Relay hot path: rewrite only the cid IN PLACE, never touch the payload. Returns the same array. */\nexport function stampCid(frame: Uint8Array, cid: number): Uint8Array {\n if (frame.byteLength < FRAME_HEADER_BYTES) throw frameError(`short frame: ${frame.byteLength} bytes`);\n checkU32(\"cid\", cid);\n new DataView(frame.buffer, frame.byteOffset, frame.byteLength).setUint32(4, cid);\n return frame;\n}\n\nexport function hasFlag(header: FrameHeader, flag: (typeof FrameFlag)[keyof typeof FrameFlag]): boolean {\n return (header.flags & flag) !== 0;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Relay ↔ device hop (never seen by clients). Every JSON envelope rides an ENVELOPE frame with\n// flags 0, sid 0, seq 0 and the client's cid; byte frames carry that cid too.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** cid 0 on an ENVELOPE frame from the device: the relay delivers it to every client. */\nexport const BROADCAST_CID = 0 as const;\n\n/**\n * Connection end: an ENVELOPE frame with FIN, sid 0, seq 0 and NO payload, for connection `cid`.\n * Relay → device: client `cid` is gone — cancel its streams, detach its sessions (idempotent; it\n * may arrive more than once). Device → relay: close client `cid`.\n */\nexport function connectionEndFrame(cid: number): Uint8Array {\n if (cid === BROADCAST_CID) throw frameError(\"a connection end needs a client cid, not the broadcast cid 0\");\n return encodeFrame({ version: FRAME_VERSION, flags: FrameFlag.FIN, channel: FrameChannel.ENVELOPE, cid, sid: 0, seq: 0 }, new Uint8Array(0));\n}\n\n/** True for a decoded connection-end frame (see connectionEndFrame). */\nexport function isConnectionEnd(frame: DecodedFrame): boolean {\n const h = frame.header;\n return h.channel === FrameChannel.ENVELOPE && hasFlag(h, FrameFlag.FIN) && frame.payload.byteLength === 0 && h.cid !== BROADCAST_CID;\n}\n","/** @ai-matrx/desktop-protocol — the JSON envelope (SPEC §4). Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { ProtocolErrorBody } from \"./errors\";\nimport { DeviceId, ProtocolVersion, RequestId, ResourceId, epochMs, u32 } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Client types and hello\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const ClientType = z\n .enum([\"screen\", \"web\", \"extension\", \"server\", \"test\"]);\n\nexport const Limits = z\n .strictObject({\n max_message_bytes: z.int().min(65_536),\n max_frame_payload_bytes: z.int().min(4096),\n default_window_bytes: z.int().min(4096),\n max_streams_per_client: z.int().min(1),\n max_resources_per_user: z.int().min(1),\n });\n\nexport const OpDescriptor = z\n .strictObject({ cap: z.string().max(32), op: z.string().max(64), since: ProtocolVersion });\n\nexport const Welcome = z\n .strictObject({\n protocol_version: ProtocolVersion, // negotiated = min(client, core) within the same major\n session_id: z.string().min(8).max(64),\n client_id: z.string().min(8).max(64), // this connection's identity in the Session Manager\n device_id: DeviceId,\n device_name: z.string().max(128),\n app_version: z.string().max(32),\n platform: z.enum([\"darwin\", \"win32\", \"linux\"]),\n ops: z.array(OpDescriptor),\n limits: Limits,\n server_time_ms: epochMs,\n });\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Envelope (SPEC §4). Text WS messages carry exactly one of these as JSON.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const HelloMsg = z\n .strictObject({\n type: z.literal(\"hello\"),\n id: RequestId, // answered by response{id, result: Welcome} or error{id}\n protocolVersion: ProtocolVersion,\n clientType: ClientType,\n clientVersion: z.string().min(1).max(32),\n });\n\nexport const RequestMsg = z\n .strictObject({\n id: RequestId,\n type: z.literal(\"request\"),\n cap: z.string().min(1).max(32),\n op: z.string().min(1).max(64),\n params: z.unknown(), // validated by the Router against OPS[cap.op].params — once, there\n });\n\nexport const ResponseMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"response\"), result: z.unknown() });\n\nexport const ErrorMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"error\"), error: ProtocolErrorBody });\n\nexport const StreamMeta = z\n .discriminatedUnion(\"kind\", [\n /** Binds request id → numeric sid; binary frames for this stream follow. */\n z.strictObject({\n kind: z.literal(\"open\"),\n sid: u32,\n window_bytes: z.int().min(4096),\n resource_id: ResourceId.optional(),\n }),\n /** Frames after this (channel SNAPSHOT) are a serialized screen; live DATA resumes after. */\n z.strictObject({ kind: z.literal(\"snapshot\"), cols: z.int().min(1), rows: z.int().min(1) }),\n /** Frames [from_seq, to_seq] are gone from the ring; a snapshot follows. */\n z.strictObject({ kind: z.literal(\"gap\"), from_seq: u32, to_seq: u32 }),\n ]);\n\nexport const StreamMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"stream\"), seq: u32, meta: StreamMeta });\n\nexport const EndReason = z\n .enum([\"completed\", \"cancelled\", \"detached\", \"resource_exited\", \"error\"]);\n\nexport const EndMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"end\"), seq: u32, reason: EndReason.optional() });\n\nexport const CancelMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"cancel\") });\n\n/** Grant n more payload bytes for the stream opened by request `id` (either direction). */\nexport const CreditMsg = z\n .strictObject({ id: RequestId, type: z.literal(\"credit\"), n: z.int().min(1).max(2_147_483_647) });\n\nexport const EventMsg = z\n .strictObject({\n type: z.literal(\"event\"),\n cap: z.string().min(1).max(32),\n name: z.string().min(1).max(64),\n payload: z.unknown(), // validated against EVENTS[cap.name]\n resourceId: ResourceId.optional(),\n });\n\n/** Client↔relay only; the relay consumes these and never forwards them to the core. */\nexport const RelayMsg = z\n .discriminatedUnion(\"op\", [\n /** Fresh access token before the current one expires (relay closes 4008 at exp + 60 s). */\n z.strictObject({ type: z.literal(\"relay\"), op: z.literal(\"reauth\"), token: z.string().min(16).max(8192) }),\n ]);\n\n/**\n * Heartbeat. Sent as these EXACT bytes; the relay answers via the Durable Object\n * setWebSocketAutoResponse pair, so a heartbeat never wakes a hibernated object.\n * Interval 25 s (device and clients); 2 missed pongs = reconnect.\n */\nexport const PING_TEXT = '{\"type\":\"ping\"}' as const;\nexport const PONG_TEXT = '{\"type\":\"pong\"}' as const;\n\n/**\n * Every WebSocket (device, phone, browser, localhost) offers this subprotocol; the access token\n * rides beside it as `${BEARER_PREFIX}<token>`, never in the URL. The server echoes only SUBPROTOCOL.\n */\nexport const SUBPROTOCOL = \"matrx.v1\" as const;\nexport const BEARER_PREFIX = \"bearer.\" as const;\n\nexport const ClientToCoreMsg = z\n .discriminatedUnion(\"type\", [HelloMsg, RequestMsg, CancelMsg, CreditMsg]);\n\nexport const CoreToClientMsg = z\n .discriminatedUnion(\"type\", [ResponseMsg, ErrorMsg, StreamMsg, EndMsg, CreditMsg, EventMsg]);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// WebSocket close codes (relay and localhost transport alike)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const CloseCode = {\n NORMAL: 1000,\n GOING_AWAY: 1001, // app quit; relay: the device was silent for 75 s — reconnect\n /** Never sent by anyone: what a socket reports when it drops without a close frame. A relay\n * deploy (every Durable Object restarts) arrives as this — reconnect immediately. */\n ABNORMAL: 1006,\n /** Relay → clients: the device (re)connected, so the core session they spoke to is gone —\n * reconnect, hello, and reattach with since_seq. */\n DEVICE_RECONNECTED: 1012,\n TRY_AGAIN_LATER: 1013, // relay: signing keys or the device registry unreachable — retry\n AUTH_INVALID: 4001,\n AUTH_FORBIDDEN: 4003,\n DEVICE_NOT_FOUND: 4004,\n AUTH_EXPIRED: 4008, // no reauth before exp + 60 s\n REPLACED: 4009, // a newer device socket for the same device took over\n DEVICE_REVOKED: 4010, // kill switch — do NOT reconnect\n PROTOCOL_ERROR: 4400,\n UPGRADE_REQUIRED: 4426,\n} as const;\n\n/** Every close code above, as a schema (so Python sees the same table). */\nexport const CloseCodeValue = z.literal([1000, 1001, 1006, 1012, 1013, 4001, 4003, 4004, 4008, 4009, 4010, 4400, 4426]);\nexport type CloseCodeValue = z.output<typeof CloseCodeValue>;\n\n// Compile-time proof the schema lists exactly the CloseCode table.\ntype SameCodes<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\ntype AssertCodes<T extends true> = T;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype CloseCodeTableCheck = AssertCodes<SameCodes<CloseCodeValue, (typeof CloseCode)[keyof typeof CloseCode]>>;\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type ClientType = z.output<typeof ClientType>;\nexport type Limits = z.output<typeof Limits>;\nexport type OpDescriptor = z.output<typeof OpDescriptor>;\nexport type Welcome = z.output<typeof Welcome>;\nexport type HelloMsg = z.output<typeof HelloMsg>;\nexport type RequestMsg = z.output<typeof RequestMsg>;\nexport type ResponseMsg = z.output<typeof ResponseMsg>;\nexport type ErrorMsg = z.output<typeof ErrorMsg>;\nexport type StreamMeta = z.output<typeof StreamMeta>;\nexport type StreamMsg = z.output<typeof StreamMsg>;\nexport type EndReason = z.output<typeof EndReason>;\nexport type EndMsg = z.output<typeof EndMsg>;\nexport type CancelMsg = z.output<typeof CancelMsg>;\nexport type CreditMsg = z.output<typeof CreditMsg>;\nexport type EventMsg = z.output<typeof EventMsg>;\nexport type RelayMsg = z.output<typeof RelayMsg>;\nexport type ClientToCoreMsg = z.output<typeof ClientToCoreMsg>;\nexport type CoreToClientMsg = z.output<typeof CoreToClientMsg>;\n","/** @ai-matrx/desktop-protocol — error model (SPEC §5). Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport type { ErrorCodeName, ErrorData, ErrorReasonName } from \"../types\";\nimport { AbsPath, ProtocolVersion, nonNegInt } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Errors (SPEC §5, plus the five additions marked NEW)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const ErrorCode = z\n .enum([\n \"AUTH_REQUIRED\",\n \"AUTH_INVALID\",\n \"AUTH_EXPIRED\",\n \"AUTH_FORBIDDEN\", // signed in, but not this device's owner\n \"AUTH_DEVICE_REVOKED\", // kill switch\n \"PERMISSION_DENIED_OS\",\n \"NOT_FOUND\",\n \"CONFLICT\",\n \"INVALID_PARAMS\",\n \"RESOURCE_BUSY\",\n \"RESOURCE_GONE\",\n \"CANCELLED\",\n \"TIMEOUT\",\n \"PLATFORM_UNSUPPORTED\",\n \"RATE_LIMITED\",\n \"INTERNAL\",\n \"PROTOCOL_VERSION_UNSUPPORTED\", // NEW: hello refused, carries data.upgrade\n \"PROTOCOL_ERROR\", // NEW: malformed envelope/frame, credit overrun, unknown sid\n \"UNKNOWN_OPERATION\", // NEW: cap.op not served by this core version\n \"DEVICE_OFFLINE\", // NEW: relay has no live device socket (retryable)\n \"PAYLOAD_TOO_LARGE\", // NEW: message or frame above limits.max_*_bytes\n ]);\n\n/** Machine reason under a code, so clients branch without parsing messages. */\nexport const ErrorReason = z\n .enum([\n \"not_a_directory\",\n \"is_a_directory\",\n \"directory_not_empty\",\n \"already_exists\",\n \"stale_write\", // fs.write if_match_mtime_ms mismatch → CONFLICT\n \"binary_content\", // utf8 read of non-UTF-8 bytes → INVALID_PARAMS\n \"not_utf8_boundary\",\n \"patch_no_match\",\n \"patch_ambiguous\",\n \"resource_exited\",\n \"resource_expired\",\n \"control_taken\", // another client of the same user took control\n \"window_exhausted\",\n ]);\n\n/**\n * One edit fs.patch could not apply — the daemon's `edits_failed[]` entry, verbatim: the edit's\n * index and the daemon's own reason text (\"old_text not found\", or \"old_text matches N locations —\n * add context or set replace_all=True\").\n */\nexport const FsPatchEditFailure = z.strictObject({ edit_index: nonNegInt, reason: z.string().max(300) });\n\nexport const ProtocolErrorBody = z\n .strictObject({\n code: ErrorCode,\n message: z.string().max(300), // short, human, never a stack trace or a token\n retryable: z.boolean(),\n data: z\n .strictObject({\n reason: ErrorReason.optional(),\n cap: z.string().max(32).optional(),\n op: z.string().max(64).optional(),\n path: AbsPath.optional(),\n settings_url: z.string().max(512).optional(), // PERMISSION_DENIED_OS deep link\n retry_after_ms: nonNegInt.optional(),\n limit_bytes: nonNegInt.optional(),\n /** fs.patch when every edit failed (CONFLICT, patch_no_match / patch_ambiguous): the daemon's 422 `failures`. */\n edits_failed: z.array(FsPatchEditFailure).max(256).optional(),\n upgrade: z\n .strictObject({\n min_version: ProtocolVersion,\n max_version: ProtocolVersion,\n download_url: z.url().optional(),\n })\n .optional(),\n })\n .optional(),\n });\n\n\n// Compile-time proof the zod-free twins in ../types.ts equal these schemas.\ntype Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\ntype AssertTrue<T extends true> = T;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype ErrorTwinCheck = [\n AssertTrue<Same<z.infer<typeof ErrorCode>, ErrorCodeName>>,\n AssertTrue<Same<z.infer<typeof ErrorReason>, ErrorReasonName>>,\n AssertTrue<Same<NonNullable<z.input<typeof ProtocolErrorBody>[\"data\"]>, ErrorData>>,\n];\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type ErrorCode = z.output<typeof ErrorCode>;\nexport type ErrorReason = z.output<typeof ErrorReason>;\nexport type ProtocolErrorBody = z.output<typeof ProtocolErrorBody>;\nexport type FsPatchEditFailure = z.output<typeof FsPatchEditFailure>;\n","/** @ai-matrx/desktop-protocol — version and primitive schemas. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Version\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const PROTOCOL_MAJOR = 1 as const;\nexport const PROTOCOL_MINOR = 0 as const;\n/** This package's version as the wire spells it (\"major.minor\"): hello, welcome, relay status. */\nexport const PROTOCOL_VERSION = `${PROTOCOL_MAJOR}.${PROTOCOL_MINOR}` as const;\n/** \"major.minor\". Same major = compatible (minor adds optional fields/ops only). */\nexport const ProtocolVersion = z\n .string()\n .regex(/^[1-9][0-9]{0,2}\\.[0-9]{1,3}$/);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Primitives\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Client-generated request id, unique per session. */\nexport const RequestId = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[A-Za-z0-9_-]+$/);\n\n/** Long-lived resource handle minted by the core: \"<kind>_<base62>\" (pty_…, watch_…). */\nexport const ResourceId = z\n .string()\n .regex(/^(pty|watch)_[A-Za-z0-9]{16,40}$/);\n\n/**\n * = app_instances.id. A plain pattern, NOT z.uuid(): z.uuid() emits `format: uuid` + `pattern`,\n * which datamodel-codegen renders as `Annotated[UUID, Field(pattern=...)]` — a model Pydantic can\n * never validate (\"Unable to apply constraint 'pattern' … of type 'uuid'\"). generate.ts now\n * refuses format+pattern on one node so this class cannot come back.\n */\nexport const DeviceId = z\n .string()\n .regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/);\n\n/**\n * Absolute, normalized path: forward slashes on every OS, NFC. POSIX \"/...\" or Windows \"C:/...\".\n * Normalization happens once, in the fs owner (SPEC §9); the wire never carries backslashes.\n */\nexport const AbsPath = z\n .string()\n .min(1)\n .max(4096)\n .regex(/^(\\/|[A-Za-z]:\\/)[^\\\\\\u0000]*$/);\n\n/** Internal building blocks — deliberately unnamed in $defs (inlined wherever used). */\nexport const u32 = z.int().min(0).max(4_294_967_295);\nexport const nonNegInt = z.int().min(0);\n/** Unix epoch milliseconds. */\nexport const epochMs = z.int().min(0);\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type ProtocolVersion = z.output<typeof ProtocolVersion>;\nexport type RequestId = z.output<typeof RequestId>;\nexport type ResourceId = z.output<typeof ResourceId>;\nexport type DeviceId = z.output<typeof DeviceId>;\nexport type AbsPath = z.output<typeof AbsPath>;\n","/** @ai-matrx/desktop-protocol — binary frame header and flow-control constants. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { FRAME_VERSION } from \"../frame\";\nimport type { FrameHeader as FrameHeaderShape } from \"../frame\";\nimport { u32 } from \"./primitives\";\n\n/** Zod twin of the codec's FrameHeader (layout documented in src/frame.ts) — for $defs and Pydantic. */\nexport const FrameHeader = z\n .strictObject({\n version: z.literal(FRAME_VERSION),\n flags: z.int().min(0).max(3),\n channel: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(255)]),\n cid: u32,\n sid: u32,\n seq: u32,\n });\nexport type FrameHeader = z.infer<typeof FrameHeader>;\n\n/** Relay ↔ device hop: the header of a frame carrying one JSON envelope. cid 0 = broadcast (device → relay). */\nexport const RelayHopEnvelopeHeader = z\n .strictObject({\n version: z.literal(FRAME_VERSION),\n flags: z.literal(0),\n channel: z.literal(255),\n cid: u32,\n sid: z.literal(0),\n seq: z.literal(0),\n });\nexport type RelayHopEnvelopeHeader = z.infer<typeof RelayHopEnvelopeHeader>;\n\n/** Relay ↔ device hop: the header of a connection-end frame (FIN, empty payload; see connectionEndFrame). */\nexport const RelayHopConnectionEnd = z\n .strictObject({\n version: z.literal(FRAME_VERSION),\n flags: z.literal(1),\n channel: z.literal(255),\n cid: z.int().min(1).max(4_294_967_295),\n sid: z.literal(0),\n seq: z.literal(0),\n });\nexport type RelayHopConnectionEnd = z.infer<typeof RelayHopConnectionEnd>;\n\n// Compile-time proof the zod twin and the zod-free codec type are the same shape.\ntype Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\ntype AssertTrue<T extends true> = T;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ntype FrameHeaderTwinCheck = AssertTrue<Same<z.infer<typeof FrameHeader>, FrameHeaderShape>>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Flow control (credits)\n//\n// The RECEIVER of a byte stream grants the SENDER a window in payload bytes. The sender may have at\n// most `window` un-credited payload bytes in flight per sid; it pauses its source (node-pty\n// pause(), file read loop) at zero and resumes on credit. Initial window = request's\n// `window_bytes` or limits.default_window_bytes. The receiver sends credit{n} after it has\n// CONSUMED n bytes (xterm write callback fired, file chunk persisted). Overrun → PROTOCOL_ERROR\n// and the stream is ended. Credits are end-to-end (client↔core), so the relay holds at most\n// sum(windows) per device and never buffers without bound. Unary JSON ops are not credited.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const DEFAULT_WINDOW_BYTES = 262_144 as const; // 256 KiB\nexport const DEFAULT_MAX_FRAME_PAYLOAD_BYTES = 65_536 as const; // 64 KiB\nexport const DEFAULT_MAX_MESSAGE_BYTES = 8_388_608 as const; // 8 MiB JSON message cap\n\n","/** @ai-matrx/desktop-protocol — cap sysinfo. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { AbsPath, DeviceId, ProtocolVersion, nonNegInt } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// sysinfo\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const OsPermissionName = z\n .enum([\n \"full_disk_access\",\n \"accessibility\",\n \"screen_recording\",\n \"microphone\",\n \"camera\",\n \"automation\",\n \"contacts\",\n \"calendars\",\n \"photos\",\n \"location\",\n \"local_network\",\n \"bluetooth\",\n \"notifications\",\n ]);\n\nexport const SysinfoGetParams = z.strictObject({});\nexport const SysinfoGetResult = z\n .strictObject({\n device_id: DeviceId,\n device_name: z.string().max(128),\n hostname: z.string().max(255),\n platform: z.enum([\"darwin\", \"win32\", \"linux\"]),\n os_version: z.string().max(64),\n arch: z.enum([\"arm64\", \"x64\"]),\n app_version: z.string().max(32),\n protocol_version: ProtocolVersion,\n user: z.strictObject({ username: z.string().max(128), shell: z.string().max(512) }),\n paths: z.strictObject({\n home: AbsPath,\n desktop: AbsPath,\n documents: AbsPath,\n downloads: AbsPath,\n app_data: AbsPath,\n temp: AbsPath,\n }),\n cpu: z.strictObject({ model: z.string().max(128), cores: z.int().min(1) }),\n memory: z.strictObject({ total_bytes: nonNegInt, free_bytes: nonNegInt }),\n uptime_seconds: nonNegInt,\n on_battery: z.boolean().nullable(),\n sleep_prevented: z.boolean(), // true while any remote session holds the power blocker\n permissions: z.array(\n z.strictObject({\n name: OsPermissionName,\n state: z.enum([\"granted\", \"denied\", \"not_determined\", \"not_applicable\"]),\n settings_url: z.string().max(512).nullable(),\n }),\n ),\n });\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type OsPermissionName = z.output<typeof OsPermissionName>;\nexport type SysinfoGetParams = z.output<typeof SysinfoGetParams>;\nexport type SysinfoGetResult = z.output<typeof SysinfoGetResult>;\n","/** @ai-matrx/desktop-protocol — cap fs. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { FsPatchEditFailure } from \"./errors\";\nimport { AbsPath, ResourceId, epochMs, nonNegInt } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// fs — mirrors matrx_agent daemon /fs/* field names (SPEC §6.1)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const FsKind = z.enum([\"file\", \"dir\", \"symlink\"]);\n\n/**\n * = daemon get_stat_dict(), field for field (SPEC 6.1): what /fs/stat and every /fs/list entry\n * answer in the cloud sandbox. Never follows symlinks; `target` is the fully resolved target.\n */\nexport const FsEntry = z\n .strictObject({\n name: z.string().max(1024),\n path: AbsPath,\n kind: FsKind,\n size: nonNegInt,\n mtime: z.number().min(0), // seconds, float\n mode: z.int().min(0).max(0o7777),\n target: AbsPath.nullable(),\n });\n\nexport const FsListParams = z\n .strictObject({\n path: AbsPath,\n recursive: z.boolean().default(false),\n depth: z.int().min(1).max(32).default(1),\n pattern: z.string().max(256).optional(), // glob on name\n limit: z.int().min(1).max(5000).default(1000),\n page_token: z.string().max(256).optional(),\n // Desktop additions; their defaults ARE the daemon's behaviour: dotfiles listed, siblings in\n // binary (byte) order of name, depth-first.\n show_hidden: z.boolean().default(true),\n sort: z.enum([\"name\", \"mtime\", \"size\", \"kind\"]).default(\"name\"),\n });\nexport const FsListResult = z\n .strictObject({\n entries: z.array(FsEntry),\n truncated: z.boolean(),\n next_page_token: z.string().max(256).nullable(),\n scanned: nonNegInt,\n });\n\nexport const FsStatParams = z.strictObject({ path: AbsPath });\nexport const FsStatResult = FsEntry;\n\nexport const FsEncoding = z.enum([\"utf8\", \"base64\"]);\n\n/** Bounded read. offset = byte offset; limit = chars (utf8) or bytes (base64), as the daemon. */\nexport const FsReadParams = z\n .strictObject({\n path: AbsPath,\n encoding: FsEncoding.default(\"utf8\"),\n offset: nonNegInt.default(0),\n limit: z.int().min(1).max(4_194_304).default(262_144),\n });\nexport const FsReadResult = z\n .strictObject({\n content: z.string(),\n encoding: FsEncoding,\n size: nonNegInt,\n offset: nonNegInt,\n next_offset: nonNegInt,\n truncated: z.boolean(),\n mime: z.string().max(128).nullable(),\n mtime_ms: epochMs, // pass back as if_match_mtime_ms to guard a later write\n });\n\n/** Whole-file or ranged download as binary frames (channel DATA, credited). */\nexport const FsReadStreamParams = z\n .strictObject({\n path: AbsPath,\n offset: nonNegInt.default(0),\n length: nonNegInt.optional(), // absent = to EOF\n window_bytes: z.int().min(4096).max(16_777_216).optional(),\n });\n/** Unary result arrives first (size/mime), then stream{open} + DATA frames + end. */\nexport const FsReadStreamResult = z\n .strictObject({ size: nonNegInt, mime: z.string().max(128).nullable(), mtime_ms: epochMs });\n\nexport const FsWriteParams = z\n .strictObject({\n path: AbsPath,\n content: z.string().max(5_592_406), // ≤ 4 MiB of bytes after base64 decode\n encoding: FsEncoding.default(\"utf8\"),\n mode: z.int().min(0).max(0o7777).optional(),\n create_parents: z.boolean().default(false),\n /** Optimistic concurrency: CONFLICT/stale_write if the file changed since this mtime. */\n if_match_mtime_ms: epochMs.optional(),\n /** Refuse to replace an existing file (CONFLICT/already_exists). */\n exclusive: z.boolean().default(false),\n });\n/** Writes are atomic: temp file in the same directory + rename (daemon parity). */\nexport const FsWriteResult = z\n .strictObject({ path: AbsPath, size: nonNegInt, mtime_ms: epochMs, created: z.boolean() });\n\nexport const FsMkdirParams = z\n .strictObject({ path: AbsPath, parents: z.boolean().default(false) });\nexport const FsMkdirResult = z\n .strictObject({ path: AbsPath, created: z.boolean() });\n\n/** = daemon RenameRequest (/fs/rename). */\nexport const FsMoveParams = z\n .strictObject({ from_path: AbsPath, to_path: AbsPath, overwrite: z.boolean().default(false) });\nexport const FsMoveResult = z\n .strictObject({ from_path: AbsPath, to_path: AbsPath });\n\n/**\n * Delete. Default goes to the OS Trash (Finder/Explorer semantics: undoable from the phone's\n * \"Undo\" toast via fs.move back). to_trash:false is a permanent delete — the daemon's behaviour,\n * used by agents through _sandbox_proxy.\n */\nexport const FsDeleteParams = z\n .strictObject({\n path: AbsPath,\n recursive: z.boolean().default(false),\n to_trash: z.boolean().default(true),\n });\nexport const FsDeleteResult = z\n .strictObject({ deleted: z.literal(true), trashed_to: AbsPath.nullable() });\n\n/** Opens a watch resource; changes arrive as event fs.changed with resourceId. */\nexport const FsWatchParams = z\n .strictObject({\n path: AbsPath,\n recursive: z.boolean().default(false),\n ignore: z.array(z.string().max(256)).max(64).default([]),\n debounce_ms: z.int().min(0).max(5000).default(50),\n });\nexport const FsWatchResult = z\n .strictObject({ resource_id: ResourceId, path: AbsPath });\n\n// — Required by lane F (SPEC §6.1 parity sequence and every existing _sandbox_proxy call) —\n\n/** = daemon EditChunk / PatchRequest (/fs/patch). */\nexport const FsPatchParams = z\n .strictObject({\n path: AbsPath,\n edits: z\n .array(\n z.strictObject({\n old_text: z.string(),\n new_text: z.string(),\n replace_all: z.boolean().default(false),\n }),\n )\n .min(1)\n .max(256),\n create_if_missing: z.boolean().default(false),\n });\n/** One edit fs.patch applied — the daemon's `edits_applied[]` entry, verbatim. */\nexport const FsPatchEditApplied = z.strictObject({\n edit_index: nonNegInt,\n mode: z.enum([\"create\", \"replace\", \"replace_all\"]),\n /** Present for replace_all only, as the daemon sends it. */\n matches_replaced: nonNegInt.optional(),\n});\n\n/**\n * = the daemon's /fs/patch answer per edit: edits apply in order, each sees the previous result; an\n * edit whose old_text is missing, or matches more than once without replace_all, is skipped and\n * listed in edits_failed with the daemon's reason; the file is written when at least one applied.\n * (Every edit failing is a CONFLICT whose data.edits_failed lists them — the daemon's 422.)\n */\nexport const FsPatchResult = z.strictObject({\n path: AbsPath,\n applied: nonNegInt,\n size: nonNegInt,\n mtime_ms: epochMs,\n edits_applied: z.array(FsPatchEditApplied).max(256),\n edits_failed: z.array(FsPatchEditFailure).max(256),\n});\n\n/** = daemon SearchPathRequest (/search/paths). */\nexport const FsSearchPathsParams = z\n .strictObject({\n pattern: z.string().min(1).max(512),\n cwd: AbsPath,\n hidden: z.boolean().default(false),\n max_results: z.int().min(1).max(5000).default(100),\n });\n/**\n * = the daemon's /search/paths answer (fd 8.3.1 in the sandbox image): paths RELATIVE to `cwd`, each\n * prefixed \"./\", sorted, cut to max_results. No truncation flag (the daemon has none).\n */\nexport const FsSearchPathsResult = z\n .strictObject({ paths: z.array(z.string().min(3).max(4096).regex(/^\\.\\/[^\\\\\\u0000]+$/)) });\n\n/** = daemon SearchContentRequest (/search/content). */\nexport const FsSearchContentParams = z\n .strictObject({\n query: z.string().min(1).max(1024),\n cwd: AbsPath,\n regex: z.boolean().default(true),\n case_sensitive: z.boolean().default(false),\n include: z.array(z.string().max(256)).max(64).optional(),\n exclude: z.array(z.string().max(256)).max(64).optional(),\n max_results: z.int().min(1).max(5000).default(100),\n });\n/**\n * = the daemon's /search/content answer (ripgrep 13 --json run in `cwd`): `path` RELATIVE to `cwd`\n * with no \"./\"; `lines` is the matching line with its newline; submatches are ripgrep's, byte\n * offsets within the line. max_results is per FILE (rg -m), as the daemon passes it. No truncation\n * flag (the daemon has none).\n */\nexport const FsSearchContentResult = z\n .strictObject({\n results: z.array(\n z.strictObject({\n path: z.string().min(1).max(4096).regex(/^[^/\\\\\\u0000][^\\\\\\u0000]*$/),\n lines: z.string(),\n line_number: z.int().min(1),\n submatches: z.array(\n z.strictObject({ match: z.strictObject({ text: z.string() }), start: nonNegInt, end: nonNegInt }),\n ),\n }),\n ),\n });\n\nexport const FsChange = z\n .strictObject({\n type: z.enum([\"created\", \"modified\", \"deleted\", \"moved\"]),\n path: AbsPath,\n to_path: AbsPath.optional(),\n kind: z.enum([\"file\", \"dir\", \"symlink\", \"unknown\"]),\n });\nexport const FsChangedEvent = z\n .strictObject({ changes: z.array(FsChange).min(1).max(1000), overflow: z.boolean() }); // overflow:true = events dropped; client re-lists\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type FsKind = z.output<typeof FsKind>;\nexport type FsEntry = z.output<typeof FsEntry>;\nexport type FsListParams = z.output<typeof FsListParams>;\nexport type FsListResult = z.output<typeof FsListResult>;\nexport type FsStatParams = z.output<typeof FsStatParams>;\nexport type FsStatResult = z.output<typeof FsStatResult>;\nexport type FsEncoding = z.output<typeof FsEncoding>;\nexport type FsReadParams = z.output<typeof FsReadParams>;\nexport type FsReadResult = z.output<typeof FsReadResult>;\nexport type FsReadStreamParams = z.output<typeof FsReadStreamParams>;\nexport type FsReadStreamResult = z.output<typeof FsReadStreamResult>;\nexport type FsWriteParams = z.output<typeof FsWriteParams>;\nexport type FsWriteResult = z.output<typeof FsWriteResult>;\nexport type FsMkdirParams = z.output<typeof FsMkdirParams>;\nexport type FsMkdirResult = z.output<typeof FsMkdirResult>;\nexport type FsMoveParams = z.output<typeof FsMoveParams>;\nexport type FsMoveResult = z.output<typeof FsMoveResult>;\nexport type FsDeleteParams = z.output<typeof FsDeleteParams>;\nexport type FsDeleteResult = z.output<typeof FsDeleteResult>;\nexport type FsWatchParams = z.output<typeof FsWatchParams>;\nexport type FsWatchResult = z.output<typeof FsWatchResult>;\nexport type FsPatchParams = z.output<typeof FsPatchParams>;\nexport type FsPatchResult = z.output<typeof FsPatchResult>;\nexport type FsPatchEditApplied = z.output<typeof FsPatchEditApplied>;\nexport type FsSearchPathsParams = z.output<typeof FsSearchPathsParams>;\nexport type FsSearchPathsResult = z.output<typeof FsSearchPathsResult>;\nexport type FsSearchContentParams = z.output<typeof FsSearchContentParams>;\nexport type FsSearchContentResult = z.output<typeof FsSearchContentResult>;\nexport type FsChange = z.output<typeof FsChange>;\nexport type FsChangedEvent = z.output<typeof FsChangedEvent>;\n","/** @ai-matrx/desktop-protocol — cap exec. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { AbsPath, ResourceId, epochMs, nonNegInt, u32 } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// exec — PTY sessions (resources) + one-shot run\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const Signal = z\n .enum([\"SIGINT\", \"SIGTERM\", \"SIGKILL\", \"SIGHUP\", \"SIGQUIT\", \"SIGTSTP\", \"SIGCONT\", \"SIGUSR1\", \"SIGUSR2\"]); // Windows: SIGINT→Ctrl-C event, SIGTERM/SIGKILL/SIGHUP→terminate, others PLATFORM_UNSUPPORTED\n\nconst cols = z.int().min(2).max(1000);\nconst rows = z.int().min(1).max(500);\n\n/**\n * Start a PTY. Response result = PtyInfo; the same request id then carries the output stream:\n * stream{meta:{kind:\"open\",sid,resource_id}} → DATA frames (credited) → end{reason}.\n * Input goes as STDIN frames on that sid (cheap per keystroke) or via exec.pty.write.\n */\nexport const ExecPtyStartParams = z\n .strictObject({\n cols,\n rows,\n cwd: AbsPath.optional(), // default: home\n shell: z.string().max(512).optional(), // default: user's login shell (PowerShell on Windows)\n args: z.array(z.string().max(4096)).max(64).optional(),\n env: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(128), z.string().max(32_768)).optional(),\n name: z.string().max(64).optional(), // tab label\n window_bytes: z.int().min(4096).max(16_777_216).optional(),\n });\n\nexport const PtyInfo = z\n .strictObject({\n resource_id: ResourceId,\n pid: z.int().min(1),\n shell: z.string().max(512),\n cwd: AbsPath, // live, from OSC 7 / process cwd\n title: z.string().max(256),\n name: z.string().max(64).nullable(),\n cols,\n rows,\n state: z.enum([\"running\", \"exited\"]),\n exit_code: z.int().nullable(),\n exit_signal: Signal.nullable(),\n last_seq: u32,\n created_at_ms: epochMs,\n controller_client_id: z.string().max(64).nullable(), // null = orphaned (in grace period)\n attached_clients: nonNegInt,\n orphan_expires_at_ms: epochMs.nullable(),\n });\n\nexport const ExecPtyStartResult = PtyInfo;\n\nexport const ExecPtyWriteParams = z\n .strictObject({ resource_id: ResourceId, data: z.string().min(1).max(65_536) });\nexport const ExecPtyWriteResult = z.strictObject({ written: nonNegInt });\n\nexport const ExecPtyResizeParams = z\n .strictObject({ resource_id: ResourceId, cols, rows });\nexport const ExecPtyResizeResult = z.strictObject({ cols, rows });\n\n/** Delivered to the PTY's foreground process group (daemon parity: tcgetpgrp + killpg). */\nexport const ExecPtySignalParams = z\n .strictObject({ resource_id: ResourceId, signal: Signal });\nexport const ExecPtySignalResult = z.strictObject({ delivered: z.boolean() });\n\n/** SIGHUP the session, SIGKILL after grace_ms, reap, free the resource. Idempotent. */\nexport const ExecPtyKillParams = z\n .strictObject({ resource_id: ResourceId, grace_ms: z.int().min(0).max(30_000).default(2000) });\nexport const ExecPtyKillResult = z\n .strictObject({ exit_code: z.int().nullable(), exit_signal: Signal.nullable() });\n\nexport const ExecListParams = z.strictObject({});\nexport const ExecListResult = z.strictObject({ sessions: z.array(PtyInfo) });\n\n/**\n * One-shot command (agents, via _sandbox_proxy → /exec). Timeout ENFORCED (exit 124, daemon\n * convention). cwd is sticky per cwd_key: a later run with the same key and no cwd starts where\n * the last one ended (SPEC §6.1: \"cd sub && pwd\" then \"pwd\").\n */\nexport const ExecRunParams = z\n .strictObject({\n command: z.string().min(1).max(131_072),\n cwd: AbsPath.optional(),\n cwd_key: z.string().max(128).optional(),\n env: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(128), z.string().max(32_768)).optional(),\n stdin: z.string().max(1_048_576).optional(),\n timeout: z.int().min(1).max(3600).default(60), // seconds, daemon parity\n max_output_bytes: z.int().min(1024).max(8_388_608).default(1_048_576),\n });\nexport const ExecRunResult = z\n .strictObject({\n exit_code: z.int(),\n stdout: z.string(),\n stderr: z.string(),\n cwd: AbsPath,\n duration_ms: nonNegInt,\n timed_out: z.boolean(),\n output_truncated: z.boolean(),\n });\n\nexport const ExecExitedEvent = z\n .strictObject({ exit_code: z.int().nullable(), exit_signal: Signal.nullable() });\nexport const ExecTitleEvent = z.strictObject({ title: z.string().max(256) });\nexport const ExecCwdEvent = z.strictObject({ cwd: AbsPath });\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type Signal = z.output<typeof Signal>;\nexport type ExecPtyStartParams = z.output<typeof ExecPtyStartParams>;\nexport type PtyInfo = z.output<typeof PtyInfo>;\nexport type ExecPtyStartResult = z.output<typeof ExecPtyStartResult>;\nexport type ExecPtyWriteParams = z.output<typeof ExecPtyWriteParams>;\nexport type ExecPtyWriteResult = z.output<typeof ExecPtyWriteResult>;\nexport type ExecPtyResizeParams = z.output<typeof ExecPtyResizeParams>;\nexport type ExecPtyResizeResult = z.output<typeof ExecPtyResizeResult>;\nexport type ExecPtySignalParams = z.output<typeof ExecPtySignalParams>;\nexport type ExecPtySignalResult = z.output<typeof ExecPtySignalResult>;\nexport type ExecPtyKillParams = z.output<typeof ExecPtyKillParams>;\nexport type ExecPtyKillResult = z.output<typeof ExecPtyKillResult>;\nexport type ExecListParams = z.output<typeof ExecListParams>;\nexport type ExecListResult = z.output<typeof ExecListResult>;\nexport type ExecRunParams = z.output<typeof ExecRunParams>;\nexport type ExecRunResult = z.output<typeof ExecRunResult>;\nexport type ExecExitedEvent = z.output<typeof ExecExitedEvent>;\nexport type ExecTitleEvent = z.output<typeof ExecTitleEvent>;\nexport type ExecCwdEvent = z.output<typeof ExecCwdEvent>;\n","/** @ai-matrx/desktop-protocol — cap session. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { PtyInfo } from \"./exec\";\nimport { AbsPath, ResourceId, epochMs, u32 } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// session — generic resource ownership (SPEC §3.3). One attach/detach for EVERY resource kind.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Reattach after a drop. mode \"control\" by the same user takes control (previous controller is\n * demoted to read_only and gets session.control_changed). since_seq = last seq the client\n * rendered: frames (since_seq, last_seq] are replayed from the ring with the REPLAY flag; if they\n * have left the ring, stream{gap} + stream{snapshot} + SNAPSHOT frames come first.\n * Response = PtyInfo|FsWatchResult-shaped ResourceInfo; then the stream continues on a new sid.\n */\nexport const SessionAttachParams = z\n .strictObject({\n resource_id: ResourceId,\n mode: z.enum([\"control\", \"read_only\"]).default(\"control\"),\n since_seq: u32.optional(),\n window_bytes: z.int().min(4096).max(16_777_216).optional(),\n });\n\nexport const ResourceInfo = z\n .discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"pty\"), pty: PtyInfo }),\n z.strictObject({\n kind: z.literal(\"watch\"),\n resource_id: ResourceId,\n path: AbsPath,\n orphan_expires_at_ms: epochMs.nullable(),\n }),\n ]);\nexport const SessionAttachResult = ResourceInfo;\n\n/** Leave the resource running (orphan grace starts if no other client controls it). */\nexport const SessionDetachParams = z.strictObject({ resource_id: ResourceId });\nexport const SessionDetachResult = z\n .strictObject({ orphan_expires_at_ms: epochMs.nullable() });\n\n/** Free a resource through its owner's cancel path (watch → unwatch; pty → exec.pty.kill). */\nexport const SessionReleaseParams = z.strictObject({ resource_id: ResourceId });\nexport const SessionReleaseResult = z.strictObject({ released: z.literal(true) });\n\nexport const SessionListParams = z.strictObject({});\nexport const SessionListResult = z.strictObject({ resources: z.array(ResourceInfo) });\n\nexport const SessionControlChangedEvent = z\n .strictObject({ controller_client_id: z.string().max(64).nullable(), your_mode: z.enum([\"control\", \"read_only\"]) });\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type SessionAttachParams = z.output<typeof SessionAttachParams>;\nexport type ResourceInfo = z.output<typeof ResourceInfo>;\nexport type SessionAttachResult = z.output<typeof SessionAttachResult>;\nexport type SessionDetachParams = z.output<typeof SessionDetachParams>;\nexport type SessionDetachResult = z.output<typeof SessionDetachResult>;\nexport type SessionReleaseParams = z.output<typeof SessionReleaseParams>;\nexport type SessionReleaseResult = z.output<typeof SessionReleaseResult>;\nexport type SessionListParams = z.output<typeof SessionListParams>;\nexport type SessionListResult = z.output<typeof SessionListResult>;\nexport type SessionControlChangedEvent = z.output<typeof SessionControlChangedEvent>;\n","/** @ai-matrx/desktop-protocol — cap relay. Schema source: lint-enforced rules in scripts/check-schema-source.mjs. */\nimport { z } from \"zod\";\nimport { ProtocolErrorBody } from \"./errors\";\nimport { ProtocolVersion, epochMs } from \"./primitives\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// relay — events the relay itself emits to clients (cap \"relay\")\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const RelayDeviceStatusEvent = z\n .strictObject({\n online: z.boolean(),\n since_ms: epochMs,\n app_version: z.string().max(32).nullable(),\n protocol_version: ProtocolVersion.nullable(),\n });\nexport const RelayAuthExpiringEvent = z\n .strictObject({ expires_at_ms: epochMs });\n\n/** HTTP POST https://relay.matrxserver.com/v1/devices/{device_id}/call — unary ops only (lane F). */\nexport const RelayCallRequest = z\n .strictObject({\n cap: z.string().min(1).max(32),\n op: z.string().min(1).max(64),\n params: z.unknown(),\n timeout_ms: z.int().min(100).max(3_700_000).default(70_000),\n });\nexport const RelayCallResponse = z\n .discriminatedUnion(\"ok\", [\n z.strictObject({ ok: z.literal(true), result: z.unknown() }),\n z.strictObject({ ok: z.literal(false), error: ProtocolErrorBody }),\n ]);\n\n/**\n * How the relay runs one /call on the device: a fresh cid (its own connection) carrying exactly\n * RelayCallHello then RelayCallEnvelope, answered on that cid by response/error with id \"call\"\n * (an error on id \"hello\" also ends it), then a connection-end frame. A stream answer is refused.\n */\nexport const RELAY_CALL_HELLO_ID = \"hello\" as const;\nexport const RELAY_CALL_REQUEST_ID = \"call\" as const;\n\nexport const RelayCallHello = z\n .strictObject({\n type: z.literal(\"hello\"),\n id: z.literal(RELAY_CALL_HELLO_ID),\n protocolVersion: ProtocolVersion,\n clientType: z.literal(\"server\"),\n clientVersion: z.string().min(1).max(32),\n });\nexport const RelayCallEnvelope = z\n .strictObject({\n id: z.literal(RELAY_CALL_REQUEST_ID),\n type: z.literal(\"request\"),\n cap: z.string().min(1).max(32),\n op: z.string().min(1).max(64),\n params: z.unknown(),\n });\n\n/** HTTP GET /v1/devices/{device_id}/status (owner JWT). */\nexport const RelayStatusResponse = RelayDeviceStatusEvent;\n\n// Inferred (output) types — same name as the schema, so `FsEntry` is both the validator and its type.\nexport type RelayDeviceStatusEvent = z.output<typeof RelayDeviceStatusEvent>;\nexport type RelayAuthExpiringEvent = z.output<typeof RelayAuthExpiringEvent>;\nexport type RelayCallRequest = z.output<typeof RelayCallRequest>;\nexport type RelayCallResponse = z.output<typeof RelayCallResponse>;\nexport type RelayStatusResponse = z.output<typeof RelayStatusResponse>;\nexport type RelayCallHello = z.output<typeof RelayCallHello>;\nexport type RelayCallEnvelope = z.output<typeof RelayCallEnvelope>;\n","/** @ai-matrx/desktop-protocol — the op and event registries (Router, client and Python are generated from these). */\nimport { z } from \"zod\";\nimport {\n AbsPath,\n DeviceId,\n ProtocolVersion,\n RequestId,\n ResourceId,\n} from \"./primitives\";\nimport {\n ErrorCode,\n ErrorReason,\n FsPatchEditFailure,\n ProtocolErrorBody,\n} from \"./errors\";\nimport {\n FrameHeader,\n RelayHopEnvelopeHeader,\n RelayHopConnectionEnd,\n} from \"./frame\";\nimport {\n CancelMsg,\n ClientToCoreMsg,\n ClientType,\n CoreToClientMsg,\n CreditMsg,\n EndMsg,\n EndReason,\n ErrorMsg,\n EventMsg,\n HelloMsg,\n Limits,\n OpDescriptor,\n RelayMsg,\n RequestMsg,\n ResponseMsg,\n StreamMeta,\n StreamMsg,\n Welcome,\n CloseCodeValue,\n} from \"./envelope\";\nimport {\n OsPermissionName,\n SysinfoGetParams,\n SysinfoGetResult,\n} from \"./sysinfo\";\nimport {\n FsChange,\n FsChangedEvent,\n FsDeleteParams,\n FsDeleteResult,\n FsEncoding,\n FsEntry,\n FsKind,\n FsListParams,\n FsListResult,\n FsMkdirParams,\n FsMkdirResult,\n FsMoveParams,\n FsMoveResult,\n FsPatchEditApplied,\n FsPatchParams,\n FsPatchResult,\n FsReadParams,\n FsReadResult,\n FsReadStreamParams,\n FsReadStreamResult,\n FsSearchContentParams,\n FsSearchContentResult,\n FsSearchPathsParams,\n FsSearchPathsResult,\n FsStatParams,\n FsStatResult,\n FsWatchParams,\n FsWatchResult,\n FsWriteParams,\n FsWriteResult,\n} from \"./fs\";\nimport {\n ExecCwdEvent,\n ExecExitedEvent,\n ExecListParams,\n ExecListResult,\n ExecPtyKillParams,\n ExecPtyKillResult,\n ExecPtyResizeParams,\n ExecPtyResizeResult,\n ExecPtySignalParams,\n ExecPtySignalResult,\n ExecPtyStartParams,\n ExecPtyStartResult,\n ExecPtyWriteParams,\n ExecPtyWriteResult,\n ExecRunParams,\n ExecRunResult,\n ExecTitleEvent,\n PtyInfo,\n Signal,\n} from \"./exec\";\nimport {\n ResourceInfo,\n SessionAttachParams,\n SessionAttachResult,\n SessionControlChangedEvent,\n SessionDetachParams,\n SessionDetachResult,\n SessionListParams,\n SessionListResult,\n SessionReleaseParams,\n SessionReleaseResult,\n} from \"./session\";\nimport {\n RelayAuthExpiringEvent,\n RelayCallRequest,\n RelayCallResponse,\n RelayDeviceStatusEvent,\n RelayCallHello,\n RelayCallEnvelope,\n} from \"./relay\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Registries — the Router, the client and the Python side are all generated from these.\n// kind: unary = response only; stream = response, then stream/end on the same id;\n// resource = like stream and the result carries a resource_id the Session Manager owns.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type OpSpec = {\n readonly params: z.ZodType;\n readonly result: z.ZodType;\n readonly kind: \"unary\" | \"stream\" | \"resource\";\n readonly since: \"1.0\";\n readonly errors: readonly z.infer<typeof ErrorCode>[];\n};\n\nconst FS_ERR = [\"NOT_FOUND\", \"PERMISSION_DENIED_OS\", \"INVALID_PARAMS\", \"RESOURCE_BUSY\", \"INTERNAL\"] as const;\n\nexport const OPS = {\n \"sysinfo.get\": { params: SysinfoGetParams, result: SysinfoGetResult, kind: \"unary\", since: \"1.0\", errors: [\"INTERNAL\"] },\n\n \"fs.list\": { params: FsListParams, result: FsListResult, kind: \"unary\", since: \"1.0\", errors: FS_ERR },\n \"fs.stat\": { params: FsStatParams, result: FsStatResult, kind: \"unary\", since: \"1.0\", errors: FS_ERR },\n \"fs.read\": { params: FsReadParams, result: FsReadResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"PAYLOAD_TOO_LARGE\"] },\n \"fs.read_stream\": { params: FsReadStreamParams, result: FsReadStreamResult, kind: \"stream\", since: \"1.0\", errors: [...FS_ERR, \"CANCELLED\"] },\n \"fs.write\": { params: FsWriteParams, result: FsWriteResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"CONFLICT\", \"PAYLOAD_TOO_LARGE\"] },\n \"fs.mkdir\": { params: FsMkdirParams, result: FsMkdirResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"CONFLICT\"] },\n \"fs.move\": { params: FsMoveParams, result: FsMoveResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"CONFLICT\"] },\n \"fs.delete\": { params: FsDeleteParams, result: FsDeleteResult, kind: \"unary\", since: \"1.0\", errors: FS_ERR },\n \"fs.watch\": { params: FsWatchParams, result: FsWatchResult, kind: \"resource\", since: \"1.0\", errors: [...FS_ERR, \"RATE_LIMITED\"] },\n \"fs.patch\": { params: FsPatchParams, result: FsPatchResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"CONFLICT\"] },\n \"fs.search_paths\": { params: FsSearchPathsParams, result: FsSearchPathsResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"TIMEOUT\"] },\n \"fs.search_content\": { params: FsSearchContentParams, result: FsSearchContentResult, kind: \"unary\", since: \"1.0\", errors: [...FS_ERR, \"TIMEOUT\"] },\n\n \"exec.pty.start\": { params: ExecPtyStartParams, result: ExecPtyStartResult, kind: \"resource\", since: \"1.0\", errors: [\"INVALID_PARAMS\", \"NOT_FOUND\", \"RATE_LIMITED\", \"PLATFORM_UNSUPPORTED\", \"INTERNAL\"] },\n \"exec.pty.write\": { params: ExecPtyWriteParams, result: ExecPtyWriteResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\", \"INVALID_PARAMS\"] },\n \"exec.pty.resize\": { params: ExecPtyResizeParams, result: ExecPtyResizeResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\"] },\n \"exec.pty.signal\": { params: ExecPtySignalParams, result: ExecPtySignalResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\", \"PLATFORM_UNSUPPORTED\"] },\n \"exec.pty.kill\": { params: ExecPtyKillParams, result: ExecPtyKillResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\"] },\n \"exec.list\": { params: ExecListParams, result: ExecListResult, kind: \"unary\", since: \"1.0\", errors: [\"INTERNAL\"] },\n \"exec.run\": { params: ExecRunParams, result: ExecRunResult, kind: \"unary\", since: \"1.0\", errors: [\"INVALID_PARAMS\", \"NOT_FOUND\", \"TIMEOUT\", \"CANCELLED\", \"INTERNAL\"] },\n\n \"session.attach\": { params: SessionAttachParams, result: SessionAttachResult, kind: \"stream\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\", \"RESOURCE_BUSY\"] },\n \"session.detach\": { params: SessionDetachParams, result: SessionDetachResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\"] },\n \"session.release\": { params: SessionReleaseParams, result: SessionReleaseResult, kind: \"unary\", since: \"1.0\", errors: [\"RESOURCE_GONE\", \"AUTH_FORBIDDEN\"] },\n \"session.list\": { params: SessionListParams, result: SessionListResult, kind: \"unary\", since: \"1.0\", errors: [\"INTERNAL\"] },\n} as const satisfies Record<string, OpSpec>;\n\nexport type OpName = keyof typeof OPS;\nexport type OpParams<N extends OpName> = z.input<(typeof OPS)[N][\"params\"]>;\nexport type OpResult<N extends OpName> = z.output<(typeof OPS)[N][\"result\"]>;\n\nexport const EVENTS = {\n \"fs.changed\": FsChangedEvent,\n \"exec.exited\": ExecExitedEvent,\n \"exec.title\": ExecTitleEvent,\n \"exec.cwd\": ExecCwdEvent,\n \"session.control_changed\": SessionControlChangedEvent,\n \"relay.device_status\": RelayDeviceStatusEvent,\n \"relay.auth_expiring\": RelayAuthExpiringEvent,\n} as const satisfies Record<string, z.ZodType>;\n\nexport type EventName = keyof typeof EVENTS;\n\n/**\n * Every schema that lands in the generated JSON Schema `$defs` under a stable name (and so becomes a\n * named Pydantic model). Order is the emission order. A test asserts every exported schema of\n * src/schema/* is either listed here or is a documented alias of a listed one.\n * Registered into a PRIVATE zod registry by scripts/generate.ts — never `.meta()`/`.describe()`,\n * which write zod's process-global registry as an import side effect.\n */\nexport const NAMED_SCHEMAS = {\n ProtocolVersion,\n RequestId,\n ResourceId,\n DeviceId,\n AbsPath,\n ErrorCode,\n ErrorReason,\n FsPatchEditFailure,\n ProtocolErrorBody,\n FrameHeader,\n ClientType,\n Limits,\n OpDescriptor,\n Welcome,\n HelloMsg,\n RequestMsg,\n ResponseMsg,\n ErrorMsg,\n StreamMeta,\n StreamMsg,\n EndReason,\n EndMsg,\n CancelMsg,\n CreditMsg,\n EventMsg,\n RelayMsg,\n ClientToCoreMsg,\n CoreToClientMsg,\n OsPermissionName,\n SysinfoGetParams,\n SysinfoGetResult,\n FsKind,\n FsEntry,\n FsListParams,\n FsListResult,\n FsStatParams,\n FsEncoding,\n FsReadParams,\n FsReadResult,\n FsReadStreamParams,\n FsReadStreamResult,\n FsWriteParams,\n FsWriteResult,\n FsMkdirParams,\n FsMkdirResult,\n FsMoveParams,\n FsMoveResult,\n FsDeleteParams,\n FsDeleteResult,\n FsWatchParams,\n FsWatchResult,\n FsPatchEditApplied,\n FsPatchParams,\n FsPatchResult,\n FsSearchPathsParams,\n FsSearchPathsResult,\n FsSearchContentParams,\n FsSearchContentResult,\n FsChange,\n FsChangedEvent,\n Signal,\n ExecPtyStartParams,\n PtyInfo,\n ExecPtyWriteParams,\n ExecPtyWriteResult,\n ExecPtyResizeParams,\n ExecPtyResizeResult,\n ExecPtySignalParams,\n ExecPtySignalResult,\n ExecPtyKillParams,\n ExecPtyKillResult,\n ExecListParams,\n ExecListResult,\n ExecRunParams,\n ExecRunResult,\n ExecExitedEvent,\n ExecTitleEvent,\n ExecCwdEvent,\n SessionAttachParams,\n ResourceInfo,\n SessionDetachParams,\n SessionDetachResult,\n SessionReleaseParams,\n SessionReleaseResult,\n SessionListParams,\n SessionListResult,\n SessionControlChangedEvent,\n RelayDeviceStatusEvent,\n RelayAuthExpiringEvent,\n RelayCallRequest,\n RelayCallResponse,\n RelayCallHello,\n RelayCallEnvelope,\n RelayHopEnvelopeHeader,\n RelayHopConnectionEnd,\n CloseCodeValue,\n} as const satisfies Record<string, z.ZodType>;\n\nexport type NamedSchemaId = keyof typeof NAMED_SCHEMAS;\n","/**\n * Wire a client's wake() to the browser events that mean \"the person is back\": the page becomes\n * visible again (iOS Safari suspends a background tab's sockets), a back/forward-cache restore\n * (`pageshow` with persisted), and the network returning (`online`). Framework-free; the React\n * binding is `useDesktopWake` in `./react`.\n */\nimport type { DesktopClient, WakeOptions } from \"./types\";\n\n/** The subset of window/document the binding listens on — injectable for tests and non-DOM hosts. */\nexport interface WakeTargets {\n window: Pick<Window, \"addEventListener\" | \"removeEventListener\">;\n document: Pick<Document, \"addEventListener\" | \"removeEventListener\" | \"visibilityState\">;\n}\n\nexport function bindDesktopWake(client: Pick<DesktopClient, \"wake\">, options: WakeOptions & { targets?: WakeTargets } = {}): () => void {\n const targets: WakeTargets | null =\n options.targets ?? (typeof window !== \"undefined\" && typeof document !== \"undefined\" ? { window, document } : null);\n if (!targets) return () => undefined;\n const wakeOptions: WakeOptions = options.probeMs === undefined ? {} : { probeMs: options.probeMs };\n const onVisibility = () => {\n if (targets.document.visibilityState === \"visible\") client.wake(wakeOptions);\n };\n const onWake = () => client.wake(wakeOptions);\n targets.document.addEventListener(\"visibilitychange\", onVisibility);\n targets.window.addEventListener(\"pageshow\", onWake);\n targets.window.addEventListener(\"online\", onWake);\n targets.window.addEventListener(\"focus\", onWake);\n return () => {\n targets.document.removeEventListener(\"visibilitychange\", onVisibility);\n targets.window.removeEventListener(\"pageshow\", onWake);\n targets.window.removeEventListener(\"online\", onWake);\n targets.window.removeEventListener(\"focus\", onWake);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,sBAAwD;;;ACCjD,IAAM,uBAAN,cAAmC,MAAM;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAAqB,SAAiB,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