zidane 9.0.2 → 9.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{auto-update-restart-B1ukz5-_.js → auto-update-restart-Z2v5vltT.js} +2 -2
- package/dist/{auto-update-restart-B1ukz5-_.js.map → auto-update-restart-Z2v5vltT.js.map} +1 -1
- package/dist/chat.js +3 -3
- package/dist/daemon-cli.js +2 -2
- package/dist/{engine-C_v7ggaM.js → engine-BmHe3jKd.js} +2 -2
- package/dist/{engine-C_v7ggaM.js.map → engine-BmHe3jKd.js.map} +1 -1
- package/dist/{executor-Bopn2Uvo.js → executor-CZFiV2LN.js} +2 -2
- package/dist/{executor-Bopn2Uvo.js.map → executor-CZFiV2LN.js.map} +1 -1
- package/dist/{extensions-4D_tk7i-.js → extensions-Bb_-1vbS.js} +2 -2
- package/dist/{extensions-4D_tk7i-.js.map → extensions-Bb_-1vbS.js.map} +1 -1
- package/dist/extensions.js +1 -1
- package/dist/{host-signals-DN6nZ4zd.js → host-signals-DnZhcbMy.js} +5 -5
- package/dist/{host-signals-DN6nZ4zd.js.map → host-signals-DnZhcbMy.js.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/ipc/remote.js +3 -3
- package/dist/{ipc-BdazyU1h.js → ipc-DTeKfnHc.js} +4 -4
- package/dist/{ipc-BdazyU1h.js.map → ipc-DTeKfnHc.js.map} +1 -1
- package/dist/ipc.js +4 -4
- package/dist/{links-Mt4r43nD.js → links-DUeZy_2e.js} +6 -6
- package/dist/{links-Mt4r43nD.js.map → links-DUeZy_2e.js.map} +1 -1
- package/dist/{memory-Dj9Eeybi.js → memory-T-sU3COB.js} +7 -7
- package/dist/{memory-Dj9Eeybi.js.map → memory-T-sU3COB.js.map} +1 -1
- package/dist/{path-display-BKAU3XtR.js → path-display-vzEF03NO.js} +3 -3
- package/dist/{path-display-BKAU3XtR.js.map → path-display-vzEF03NO.js.map} +1 -1
- package/dist/{remote-hosts-Ep4bgs3F.js → remote-hosts-RbuohEaP.js} +4 -4
- package/dist/{remote-hosts-Ep4bgs3F.js.map → remote-hosts-RbuohEaP.js.map} +1 -1
- package/dist/{settings-keys-CEmlwy2H.js → settings-keys-BP0tJDVS.js} +2 -2
- package/dist/{settings-keys-CEmlwy2H.js.map → settings-keys-BP0tJDVS.js.map} +1 -1
- package/dist/tui.js +8 -8
- package/dist/{version-DzI0HMrv.js → version-_Yunc9lZ.js} +2 -2
- package/dist/{version-DzI0HMrv.js.map → version-_Yunc9lZ.js.map} +1 -1
- package/dist/{ws-client-BWiyy8Op.js → ws-client-CsAtVY0b.js} +2 -2
- package/dist/{ws-client-BWiyy8Op.js.map → ws-client-CsAtVY0b.js.map} +1 -1
- package/dist/{ws-Bv6QGsEr.js → ws-ks0slKdL.js} +3 -3
- package/dist/{ws-Bv6QGsEr.js.map → ws-ks0slKdL.js.map} +1 -1
- package/docs/SERVER.md +12 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-keys-CEmlwy2H.js","names":[],"sources":["../src/ipc/daemon/lifecycle.ts","../src/ipc/transports/client-core.ts","../src/chat/sync/hash.ts","../src/chat/sync/settings-keys.ts"],"sourcesContent":["/**\n * Daemon lifecycle: socket-path resolution, liveness probing, stale-socket\n * cleanup, and spawn-on-demand.\n *\n * The socket lives in a dedicated daemon subdir of the resolved state dir\n * (`~/.zidane/daemon/daemon.sock` by default, honoring the same\n * `ZIDANE_STORAGE_DIR` / `ZIDANE_PREFIX` env knobs every other surface\n * uses), overridable via `ZIDANE_DAEMON_SOCKET` for parallel installs and\n * tests.\n */\nimport { spawn } from 'node:child_process'\nimport { existsSync, readdirSync, statSync } from 'node:fs'\nimport { connect } from 'node:net'\nimport { basename, dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { resolveStorageDirs } from '../../chat/xdg'\n\n/**\n * Build fingerprint for the handshake. Running from source it is the newest\n * mtime under the `src/` tree at import time. Bundled, it is the mtime of this\n * module's own file. Client and daemon load the same files from disk, so a\n * daemon spawned before a rebuild (or a source edit in dev) reports a\n * different id than a freshly-started client, and the client drains +\n * respawns it. This closes the \"same protocol version, different code\"\n * gap that a hand-bumped version constant can't: during development the\n * daemon process is frozen at spawn while the tree keeps moving.\n *\n * Compiled binaries (`/$bunfs/…` virtual paths) can't be stat'ed and\n * report `'unknown'`; the check is skipped when EITHER side is unknown,\n * so released builds rely on `IPC_PROTOCOL_VERSION` alone — correct,\n * since their code only changes when the version does.\n */\nexport const IPC_BUILD_ID: string = (() => {\n try {\n const selfPath = fileURLToPath(import.meta.url)\n /*\n * Dev (running from source): fingerprint the whole source tree, not\n * just this file — a change to server.ts / engine.ts / runtime code\n * with no edit to lifecycle.ts must still retire an old daemon. Walk\n * `src/` and take the newest mtime. When the tree isn't present\n * (bundled dist, compiled binary) we fall back to this module's own\n * file mtime; in a bundle every ipc source collapses into one chunk, so\n * that single mtime already moves on any ipc change.\n */\n /*\n * Root validation is load-bearing: from a built bundle this module\n * lives flat in `dist/`, so the two-levels-up guess would be the\n * PACKAGE root — walking it would synchronously stat the whole repo\n * (node_modules, .git) at import time and fingerprint unrelated\n * churn. Only walk when the candidate directory demonstrably IS the\n * ipc source tree; a bundle falls back to this chunk's own mtime,\n * which already moves on every rebuild.\n */\n const ipcRoot = dirname(dirname(selfPath))\n if (!existsSync(join(ipcRoot, 'protocol.ts')))\n return String(Math.floor(statSync(selfPath).mtimeMs))\n\n /*\n * Dev scope: walk the whole `src/` tree, not just `src/ipc` — daemon\n * behavior also lives in agent.ts, loop.ts, and chat/** (store,\n * replay, discovery), and an edit there must retire a running dev\n * daemon just as surely as an ipc edit (the spawn-marker incident\n * lived in chat/store.ts). A few hundred stats — milliseconds.\n */\n const srcRoot = dirname(ipcRoot)\n let newest = 0\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = join(dir, entry.name)\n if (entry.isDirectory())\n walk(full)\n else\n newest = Math.max(newest, statSync(full).mtimeMs)\n }\n }\n try {\n walk(srcRoot)\n }\n catch {\n newest = statSync(selfPath).mtimeMs\n }\n return String(Math.floor(newest))\n }\n catch {\n return 'unknown'\n }\n})()\n\n/**\n * Socket file name. Dev builds (`ZIDANE_DEV=1`, set by every `dev` script\n * in the repo) get their OWN socket so a checkout's TUI, GUI and `zidane\n * daemon` pair up among themselves and never attach to — or get refused by\n * — the installed daemon. Without this, a protocol bump in the working\n * tree turned the dev GUI's dot red against the stable daemon, and a dev\n * daemon could drain the one the installed TUI relies on.\n * @param env - Environment to read `ZIDANE_DEV` from.\n * @returns `dev.sock` for a dev build, else `daemon.sock`.\n */\nexport function daemonSocketName(env: NodeJS.ProcessEnv = process.env): 'daemon.sock' | 'dev.sock' {\n return env.ZIDANE_DEV && env.ZIDANE_DEV !== '0' ? 'dev.sock' : 'daemon.sock'\n}\n\n/**\n * Path of the daemon socket this process uses.\n * The `ZIDANE_DAEMON_SOCKET` environment variable wins. Otherwise it is `<stateDir>/daemon/<socket name>`, see {@link daemonSocketName}.\n * @returns The socket path.\n */\nexport function defaultSocketPath(): string {\n const explicit = process.env.ZIDANE_DAEMON_SOCKET\n if (explicit)\n return explicit\n /*\n * The socket is transient runtime state, so it lands under the resolved\n * state dir — XDG-aware on XDG installs, `<storageDir>/<prefix>` in\n * legacy mode. Uses the same resolver every other surface reads through,\n * honoring `ZIDANE_STORAGE_DIR` / `ZIDANE_PREFIX`.\n *\n * DEDICATED `daemon/` subdir: the state dir is shared with\n * `state.json` / logs, so the daemon can't chmod it 0700 without\n * affecting unrelated files. The server hardens this subdir instead;\n * client and server must agree on this path.\n */\n const dirs = resolveStorageDirs({\n ...(process.env.ZIDANE_PREFIX !== undefined ? { prefix: process.env.ZIDANE_PREFIX } : {}),\n })\n return join(dirs.stateDir, 'daemon', daemonSocketName())\n}\n\n/**\n * Legacy socket location (`<stateDir>/daemon.sock`) for the given socket path,\n * or null when the path isn't the default `<stateDir>/daemon/daemon.sock`\n * layout (explicit `ZIDANE_DAEMON_SOCKET` users never had a migration to run).\n * A daemon still serving the old path would be ORPHANED by the move — new clients\n * never probe it, and a service-style `--idle-exit 0` daemon would hold\n * agents and run-guard markers against the same sessions.db forever —\n * so daemon startup probes this path and drains any survivor.\n */\nexport function legacySocketPath(socketPath: string): string | null {\n const dir = dirname(socketPath)\n if (basename(socketPath) !== 'daemon.sock' || basename(dir) !== 'daemon')\n return null\n return join(dirname(dir), 'daemon.sock')\n}\n\n/**\n * Spawn command that re-enters the CURRENT zidane program as `… daemon`.\n *\n * Three launch shapes:\n * - compiled Bun binary — `Bun.main` is the virtual `/$bunfs/…` entry the\n * binary self-inserts as argv[1], so the spawn must NOT repeat it\n * (verified: repeating it makes the child parse the junk path as its\n * subcommand and boot the full TUI instead of the daemon).\n * - dev (`bun run cli.ts`) — the script path must ride along.\n * - Node hosts (no `Bun` global) — fall back to the published bin.\n */\nexport function selfDaemonSpawnCommand(): string[] {\n const bunMain = (globalThis as { Bun?: { main?: string } }).Bun?.main\n // Compiled binary: the virtual entry parses its own `daemon` subcommand.\n if (bunMain?.startsWith('/$bunfs'))\n return [process.execPath, 'daemon']\n // Dev-from-source: only re-execute `Bun.main` when it's actually a\n // zidane CLI entry (`cli.ts`/`cli.js`). For any other embedder (library\n // consumer, script) re-running their entry with a `daemon` argv would\n // launch an arbitrary program — fall back to the published bin instead.\n if (bunMain && /(?:^|[/\\\\])cli\\.[cm]?[jt]s$/.test(bunMain))\n return [process.execPath, bunMain, 'daemon']\n return ['zidane-daemon']\n}\n\n/**\n * True when something accepts connections on `socketPath`. Distinguishes a\n * live daemon from a stale socket file left by a crashed one.\n * @param socketPath - Path of the socket to try.\n * @param timeoutMs - How long to wait for the connection, in milliseconds.\n */\nexport function probeSocket(socketPath: string, timeoutMs = 1000): Promise<boolean> {\n return new Promise((resolve) => {\n /*\n * Skip the connect entirely unless the path is an actual socket file.\n * A stale REGULAR file (crashed daemon) or a missing path both mean\n * \"nothing listening\" — and connecting to them can surface a noisy\n * async ENOENT/ENOTSOCK that some runtimes treat as uncaught.\n */\n try {\n if (!existsSync(socketPath) || !statSync(socketPath).isSocket()) {\n resolve(false)\n return\n }\n }\n catch {\n resolve(false)\n return\n }\n\n let socket: ReturnType<typeof connect>\n try {\n socket = connect(socketPath)\n }\n catch {\n resolve(false)\n return\n }\n const done = (alive: boolean): void => {\n socket.destroy()\n resolve(alive)\n }\n socket.once('connect', () => done(true))\n socket.once('error', () => done(false))\n socket.setTimeout(timeoutMs, () => done(false))\n })\n}\n\n/** Options for {@link ensureDaemonRunning}. */\nexport interface EnsureDaemonOptions {\n /**\n * Socket the daemon listens on.\n * @default defaultSocketPath()\n */\n socketPath?: string\n /**\n * Command used to spawn the daemon when nothing is listening. Defaults to\n * `['zidane-daemon']` (the published bin). The child is detached and\n * unref'd — it outlives the spawning client by design.\n */\n spawnCommand?: string[]\n /** Total time to wait for the daemon to accept connections. Default 8000 ms. */\n timeoutMs?: number\n}\n\n/** Daemon starts in flight, by socket path, so concurrent callers share one. */\nconst pendingStarts = new Map<string, Promise<string>>()\n\n/**\n * Makes sure a daemon is listening on the socket, spawning one when nothing is. Concurrent calls for the same socket share one start.\n * Rejects when the spawn fails or the daemon does not accept connections within `timeoutMs`.\n * @param options - Socket, spawn command and timeout.\n * @returns The socket path once a connection succeeds.\n */\nexport function ensureDaemonRunning(options: EnsureDaemonOptions = {}): Promise<string> {\n const socketPath = options.socketPath ?? defaultSocketPath()\n const pending = pendingStarts.get(socketPath)\n if (pending)\n return pending\n const start = startDaemon({ ...options, socketPath }).finally(() => pendingStarts.delete(socketPath))\n pendingStarts.set(socketPath, start)\n return start\n}\n\nasync function startDaemon(options: EnsureDaemonOptions & { socketPath: string }): Promise<string> {\n const socketPath = options.socketPath\n if (await probeSocket(socketPath))\n return socketPath\n\n const [cmd, ...args] = options.spawnCommand ?? ['zidane-daemon']\n const child = spawn(cmd!, args, {\n detached: true,\n stdio: 'ignore',\n env: { ...process.env, ZIDANE_DAEMON_SOCKET: socketPath },\n })\n /*\n * A missing binary (e.g. `zidane-daemon` not on PATH) emits an async\n * `error` event; without a listener Node rethrows it as an uncaught\n * exception and crashes the caller. Capture it and surface a clean\n * rejection through the poll loop below.\n */\n let spawnError: Error | undefined\n child.once('error', (err: Error) => {\n spawnError = err\n })\n child.unref()\n\n const deadline = Date.now() + (options.timeoutMs ?? 8000)\n for (;;) {\n if (spawnError !== undefined)\n throw new Error(`Failed to spawn zidane daemon (${cmd}): ${spawnError.message}`)\n if (await probeSocket(socketPath))\n return socketPath\n if (Date.now() > deadline)\n throw new Error(`zidane daemon did not come up on ${socketPath} within ${options.timeoutMs ?? 8000}ms.`)\n await new Promise(r => setTimeout(r, 150))\n }\n}\n","/**\n * The client side every wire transport shares (the unix socket in\n * `../client.ts`, the WebSocket in `./ws-client.ts`): the `ipc.hello`\n * handshake with its version fences, typed requests with deadlines,\n * notifications, and signal fan-out. A transport supplies a connected\n * JSON-RPC {@link ClientChannel}; this turns it into an {@link IpcClient}.\n */\nimport type { AcpPeer, JsonRpcMessage } from '../../acp/types'\nimport type { HelloResult, HostSignal, IpcMethodName, IpcParams, IpcResult, SignalMeta } from '../protocol'\nimport { JsonRpcConnectionClosedError, JsonRpcRemoteError } from '../../acp/json-rpc'\nimport { compareVersions, ZIDANE_VERSION } from '../../version'\nimport { IPC_BUILD_ID } from '../daemon/lifecycle'\nimport { IPC_MIN_PROTOCOL_VERSION, IPC_PROTOCOL_VERSION, IpcErrorCode, PING_METHOD, SIGNAL_SEQ_FIELD } from '../protocol'\n\n/** A connected host client, shared by every transport. Requests are checked against {@link IpcMethods}. */\nexport interface IpcClient {\n /** The host's answer to the `ipc.hello` handshake. */\n hello: HelloResult\n /**\n * Calls a host method and resolves with its result. Rejects with a `JsonRpcRemoteError` when the host answers with an error, or with `JsonRpcConnectionClosedError` when the connection closes first.\n * A request not answered within its deadline (30 s, longer for slow methods) rejects and drops the connection. `machine.call` has no deadline.\n */\n request: <M extends IpcMethodName>(method: M, params: IpcParams<M>) => Promise<IpcResult<M>>\n /**\n * Fire-and-forget notification — same method table as `request`, but no\n * id, no response, no pending-promise bookkeeping. The hot path for\n * high-frequency writes (per-keystroke draft sync). Daemons that don't\n * know the method ignore it silently.\n */\n notify: <M extends IpcMethodName>(method: M, params: IpcParams<M>) => void\n /** Host signals, with their number in their session when they have one (`SignalMeta`). */\n onSignal: (cb: SignalListener) => () => void\n /** Closes the connection. Pending requests reject. */\n close: () => void\n}\n\nexport type SignalListener = (signal: HostSignal, meta?: SignalMeta) => void\n\n/** Thrown when the host refuses the handshake because its protocol, build or code version does not match the client's. */\nexport class IpcVersionMismatchError extends Error {\n /**\n * @param message - Description of the mismatch.\n * @param daemon - The host's handshake data, when it sent any.\n */\n constructor(message: string, readonly daemon?: HelloResult) {\n super(message)\n this.name = 'IpcVersionMismatchError'\n }\n}\n\n/** A connected JSON-RPC link to a host, as a transport hands it over. */\nexport interface ClientChannel {\n rpc: Pick<AcpPeer, 'sendRequest' | 'sendNotification'>\n /** The caller's `close()`: quiet (no `onClose`), fails what is in flight. Idempotent. */\n close: () => void\n /** Drop a wedged connection: like the host going away, so the transport's `onClose` fires. */\n abort: () => void\n /** Where the host is, for error messages (a socket path, a URL). */\n where: string\n}\n\nexport interface ClientCoreOptions {\n appVersion?: string\n /**\n * When the host refuses the handshake on a version / build mismatch:\n * `always` asks it to drain so a matching one can be spawned (session\n * controllers on the local daemon); `stale-only` only when the host is\n * provably older (passive local clients); `never` leaves it running (a\n * remote server's lifetime is not the client's to end).\n */\n drain: 'always' | 'stale-only' | 'never'\n /**\n * Send this build's fingerprint, so a host from an older build of the same\n * protocol refuses us. Off sends the `'unknown'` sentinel: clients that\n * can't act on a build mismatch (no drain, no respawn) opt out of that fence.\n */\n buildFence: boolean\n /**\n * Ping the host (`$/ping`) this often once attached; two pings in a row\n * left unanswered at the next tick abort the connection (the transport's\n * `onClose` fires, its owner reconnects). Off when absent or `0`: a\n * local socket learns of a dead host from the kernel.\n */\n heartbeatMs?: number\n}\n\n/** Missed heartbeats after which the host is considered gone. */\nexport const HEARTBEAT_MISSES = 2\n\n/** Starts the client heartbeat on `channel`; returns its stop. Stops itself once the channel closes. */\nfunction startHeartbeat(channel: ClientChannel, intervalMs: number): () => void {\n let awaiting = false\n let missed = 0\n const timer = setInterval(() => {\n if (awaiting && ++missed >= HEARTBEAT_MISSES) {\n clearInterval(timer)\n channel.abort()\n return\n }\n awaiting = true\n channel.rpc.sendRequest(PING_METHOD, {}).then(\n () => {\n awaiting = false\n missed = 0\n },\n (err: unknown) => {\n if (err instanceof JsonRpcConnectionClosedError) {\n clearInterval(timer)\n return\n }\n // Any answer, an error included (a host predating `$/ping`), proves it alive.\n awaiting = false\n missed = 0\n },\n )\n }, intervalMs)\n timer.unref?.()\n return () => clearInterval(timer)\n}\n\n/** The signal listeners of one client, and the JSON-RPC notification handler that feeds them. */\nexport function createSignalListeners() {\n const listeners = new Set<SignalListener>()\n return {\n listeners,\n onNotification(message: JsonRpcMessage & { method: string }): void {\n if (message.method !== 'ipc.signal')\n return\n const params = (message as { params?: HostSignal & { [SIGNAL_SEQ_FIELD]?: unknown } }).params\n if (!params)\n return\n const { [SIGNAL_SEQ_FIELD]: seq, ...signal } = params\n const meta = typeof seq === 'number' ? { seq } : undefined\n for (const cb of listeners)\n cb(signal as HostSignal, meta)\n },\n }\n}\n\nfunction hostRelease(hello: HelloResult): string | undefined {\n for (const value of [hello.codeVersion, hello.appVersion]) {\n if (typeof value !== 'string')\n continue\n const match = /^(?:zidane-gui\\/)?(v?\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?)$/.exec(value.trim())\n if (match)\n return match[1]\n }\n return undefined\n}\n\nconst HELLO_TIMEOUT_MS = 5000\nconst LONG_REQUEST_TIMEOUT_MS = 10 * 60 * 1000\n/** RPCs that legitimately run long: full compaction, index-backed cross-session search, a clone, a folder search. */\nconst LONG_REQUEST_METHODS = new Set<string>(['sessions.compact', 'history.searchAll', 'history.searchSession', 'git.clone', 'fs.searchDirs'])\n\n/**\n * A refused handshake. Asks the host to drain when `drain` allows it, closes\n * the channel, and returns the error to throw.\n */\nasync function refusedHello(channel: ClientChannel, err: JsonRpcRemoteError, drain: ClientCoreOptions['drain']): Promise<IpcVersionMismatchError> {\n /*\n * Ask the stale daemon to drain so the caller can respawn a matching\n * one. AWAIT the reply (bounded) before tearing the connection down —\n * closing discards unflushed writes, so a fire-and-forget\n * `daemon.shutdown` could be dropped, leaving the stale daemon alive\n * and defeating `connectOrSpawnDaemon`'s retry.\n */\n const daemon = (err.data as { daemon?: HelloResult } | undefined)?.daemon\n // A network server's lifetime is never a client's to end, whatever `drain` says.\n if (daemon?.hostKind === 'server') {\n channel.close()\n return new IpcVersionMismatchError(serverMismatchMessage(daemon, channel.where) ?? err.message, daemon)\n }\n /*\n * Passive clients (`stale-only`) never retire a daemon on a protocol /\n * build mismatch — it may be NEWER than them. A daemon that is provably\n * OLDER — an older release, or the same release speaking an older\n * protocol (a dev build from before a protocol bump) — is the case where\n * draining is always safe: nothing newer can be running on it, and\n * whoever attaches next spawns a current one. Without this a passive\n * client (the GUI) would sit in-process forever behind a stale daemon\n * nobody restarts: every retry is refused.\n */\n const daemonIsOlderRelease\n = typeof daemon?.codeVersion === 'string' && compareVersions(daemon.codeVersion, ZIDANE_VERSION) < 0\n const release = daemon && hostRelease(daemon)\n const daemonIsNewerRelease = release !== undefined && compareVersions(release, ZIDANE_VERSION) > 0\n const daemonSpeaksOlderProtocol = typeof daemon?.protocolVersion === 'number' && daemon.protocolVersion < IPC_PROTOCOL_VERSION\n const daemonIsStale = daemonIsOlderRelease || daemonSpeaksOlderProtocol\n if (drain !== 'never' && !daemonIsNewerRelease && (drain === 'always' || daemonIsStale)) {\n // `whenIdle`: a daemon with live runs defers its exit instead of\n // aborting them (older daemons ignore the flag and drain now).\n await Promise.race([\n channel.rpc.sendRequest('daemon.shutdown', { whenIdle: true }).catch(() => undefined),\n new Promise(resolve => setTimeout(resolve, 1500)),\n ])\n }\n channel.close()\n return new IpcVersionMismatchError(err.message, daemon)\n}\n\n/**\n * A server's protocol refusal, from this client's side: both versions and which side to upgrade.\n * `null` when the server's range (`minProtocolVersion`…`protocolVersion`) overlaps this client's.\n */\nfunction serverMismatchMessage(server: HelloResult, where: string): string | null {\n if (typeof server.protocolVersion !== 'number')\n return null\n const serverMin = typeof server.minProtocolVersion === 'number' ? server.minProtocolVersion : server.protocolVersion\n if (serverMin <= IPC_PROTOCOL_VERSION && server.protocolVersion >= IPC_MIN_PROTOCOL_VERSION)\n return null\n const upgrade = server.protocolVersion < IPC_PROTOCOL_VERSION ? 'server' : 'client'\n return `Protocol version mismatch with ${where}: the server speaks v${server.protocolVersion}, this client v${IPC_PROTOCOL_VERSION}. Upgrade the ${upgrade}.`\n}\n\nasync function handshake(channel: ClientChannel, options: ClientCoreOptions): Promise<HelloResult> {\n /*\n * Bound the handshake: a wedged daemon (accepting connections but never\n * reading — e.g. SIGSTOP'd) would otherwise hang this promise forever.\n * On timeout the channel is closed and the connect rejects.\n * `Promise.race` keeps the losing request promise handled, so the\n * connection-closed rejection that follows `close()` can't surface as an\n * unhandled rejection.\n */\n let helloTimer: ReturnType<typeof setTimeout> | undefined\n try {\n return (await Promise.race([\n channel.rpc.sendRequest('ipc.hello', {\n protocolVersion: IPC_PROTOCOL_VERSION,\n minProtocolVersion: IPC_MIN_PROTOCOL_VERSION,\n appVersion: options.appVersion ?? 'dev',\n pid: process.pid,\n // Build fingerprint: a daemon started from an OLDER build of this\n // same protocol version rejects us, gets drained, and respawns —\n // dev daemons cannot run stale code silently. Clients that\n // cannot act on a build mismatch send the 'unknown' sentinel\n // instead (see `buildFence`): fencing them would just lock them\n // out until someone else retires the host. They stay fenced by\n // protocol version and degrade via `optional()` like any client of\n // an older daemon.\n buildId: options.buildFence ? IPC_BUILD_ID : 'unknown',\n // Always sent, passive clients included: a stale-RELEASE daemon is\n // safe for anyone to retire (see `refusedHello`).\n codeVersion: ZIDANE_VERSION,\n }),\n new Promise<never>((_, reject) => {\n helloTimer = setTimeout(\n () => reject(new Error(`Daemon handshake timed out after ${HELLO_TIMEOUT_MS}ms on ${channel.where}.`)),\n HELLO_TIMEOUT_MS,\n )\n }),\n ])) as HelloResult\n }\n catch (err) {\n if (err instanceof JsonRpcRemoteError && err.code === IpcErrorCode.VersionMismatch)\n throw await refusedHello(channel, err, options.drain)\n channel.close()\n throw err\n }\n finally {\n clearTimeout(helloTimer)\n }\n}\n\n/** Handshake over `channel`, then the typed client around it. On failure the channel is closed. */\nexport async function openIpcClient(\n channel: ClientChannel,\n listeners: Set<SignalListener>,\n options: ClientCoreOptions,\n): Promise<IpcClient> {\n const hello = await handshake(channel, options)\n\n const release = hostRelease(hello)\n // A `retiring` daemon is fence-aware and already exits once idle; staying\n // attached until then keeps its live runs reachable from this window. A\n // network server is never retired for a client: an older one is attached\n // to, and this client degrades (`optional()`) like an older client does.\n if (!hello.retiring && hello.hostKind !== 'server' && release !== undefined && compareVersions(release, ZIDANE_VERSION) < 0) {\n // Pre-fence daemons accept hello without checking codeVersion. Disconnect\n // only: shutting down a successfully attached daemon can abort active runs.\n channel.close()\n throw new IpcVersionMismatchError(\n `Daemon release ${release} is older than client ${ZIDANE_VERSION}. Restart the daemon when active runs have finished.`,\n hello,\n )\n }\n\n // Env override is a test seam (process-level e2e exercises the real\n // deadline without waiting 30 s); undocumented, not a user setting.\n const requestTimeoutMs = Number(process.env.ZIDANE_IPC_REQUEST_TIMEOUT_MS) || 30_000\n\n const stopHeartbeat = options.heartbeatMs ? startHeartbeat(channel, options.heartbeatMs) : () => undefined\n\n return {\n hello,\n notify: (method, params) => {\n try {\n channel.rpc.sendNotification(method, params)\n }\n catch {\n // fire-and-forget by contract — a dying connection surfaces via onClose\n }\n },\n request: async (method, params) => {\n /*\n * Per-request deadline: close rejection covers a DEAD host, but a\n * wedged one (alive, not reading — the same class the server-side\n * backpressure bound handles for peers) would hang callers forever.\n * On timeout the connection is aborted (NOT `close()` — the `onClose`\n * path must fire so reconnect logic takes over) and every pending\n * request rejects via the close sweep. Known long-running RPCs get a\n * generous budget; tearing the connection down mid-`sessions.compact`\n * would abort real work, so those bounds are deliberately loose.\n */\n // A machine call lasts as long as its command (`docs/MACHINES.md`); a dead host is the heartbeat's to catch.\n if (method === 'machine.call')\n return channel.rpc.sendRequest(method, params) as Promise<IpcResult<typeof method>>\n const timeoutMs = LONG_REQUEST_METHODS.has(method) ? LONG_REQUEST_TIMEOUT_MS : requestTimeoutMs\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return (await Promise.race([\n channel.rpc.sendRequest(method, params),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`Daemon request ${method} timed out after ${timeoutMs}ms, closing the connection.`))\n channel.abort()\n }, timeoutMs)\n timer.unref?.()\n }),\n ])) as IpcResult<typeof method>\n }\n finally {\n clearTimeout(timer)\n }\n },\n onSignal: (cb) => {\n listeners.add(cb)\n return () => listeners.delete(cb)\n },\n close: () => {\n stopHeartbeat()\n channel.close()\n },\n }\n}\n","/** Stable hashes of sync values: equal values (whatever their key order) hash the same, on both sides. */\nimport { createHash } from 'node:crypto'\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** JSON with sorted keys (undefined members dropped). */\nexport function stableStringify(value: unknown): string {\n if (Array.isArray(value))\n return `[${value.map(stableStringify).join(',')}]`\n if (isRecord(value))\n return `{${Object.keys(value).sort().filter(k => value[k] !== undefined).map(k => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`\n return JSON.stringify(value) ?? 'undefined'\n}\n\nexport function hashValue(value: unknown): string {\n return createHash('sha256').update(stableStringify(value)).digest('hex')\n}\n","/** Which settings the `settings` sync category carries (`./types`). */\nimport type { Settings } from '../types'\nimport { HOST_ENABLED_LISTS, isWindowOnlySetting } from '../host-scoped-settings'\n\n/**\n * Host-scoped settings that still don't sync: they describe this computer\n * (its environments, its daemon, remote hosts on it) or would turn off what\n * the server has that this computer doesn't (the enabled allowlists, its OS\n * sandbox). Every `sandbox*` key, present and future, is the server's own:\n * a client turning it off there would be a sandbox escape.\n */\nconst NOT_SYNCED_SETTINGS: ReadonlySet<string> = new Set<string>(['environments', 'useDaemon', 'remoteHosts', ...HOST_ENABLED_LISTS])\n\n// The same legacy `safeMode` mapping as the live settings wire (`settings.get` / `settings.set`).\nexport { settingsFromWire, settingsToWire } from '../host-scoped-settings'\n\n/** A setting the `settings` category carries: host-scoped (never window-only) and not machine-specific. */\nexport function isSyncableSetting(key: keyof Settings | string): boolean {\n return !isWindowOnlySetting(key) && !NOT_SYNCED_SETTINGS.has(key) && !key.startsWith('sandbox')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,sBAA8B;CACzC,IAAI;EACF,MAAM,WAAW,cAAc,YAAY,GAAG;EAmB9C,MAAM,UAAU,QAAQ,QAAQ,QAAQ,CAAC;EACzC,IAAI,CAAC,WAAW,KAAK,SAAS,aAAa,CAAC,GAC1C,OAAO,OAAO,KAAK,MAAM,SAAS,QAAQ,CAAC,CAAC,OAAO,CAAC;EAStD,MAAM,UAAU,QAAQ,OAAO;EAC/B,IAAI,SAAS;EACb,MAAM,QAAQ,QAAsB;GAClC,KAAK,MAAM,SAAS,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC,GAAG;IAC7D,MAAM,OAAO,KAAK,KAAK,MAAM,IAAI;IACjC,IAAI,MAAM,YAAY,GACpB,KAAK,IAAI;SAET,SAAS,KAAK,IAAI,QAAQ,SAAS,IAAI,CAAC,CAAC,OAAO;GACpD;EACF;EACA,IAAI;GACF,KAAK,OAAO;EACd,QACM;GACJ,SAAS,SAAS,QAAQ,CAAC,CAAC;EAC9B;EACA,OAAO,OAAO,KAAK,MAAM,MAAM,CAAC;CAClC,QACM;EACJ,OAAO;CACT;AACF,EAAA,CAA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c/transports/client-core.ts","../src/chat/sync/hash.ts","../src/chat/sync/settings-keys.ts"],"sourcesContent":["/**\n * Daemon lifecycle: socket-path resolution, liveness probing, stale-socket\n * cleanup, and spawn-on-demand.\n *\n * The socket lives in a dedicated daemon subdir of the resolved state dir\n * (`~/.zidane/daemon/daemon.sock` by default, honoring the same\n * `ZIDANE_STORAGE_DIR` / `ZIDANE_PREFIX` env knobs every other surface\n * uses), overridable via `ZIDANE_DAEMON_SOCKET` for parallel installs and\n * tests.\n */\nimport { spawn } from 'node:child_process'\nimport { existsSync, readdirSync, statSync } from 'node:fs'\nimport { connect } from 'node:net'\nimport { basename, dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { resolveStorageDirs } from '../../chat/xdg'\n\n/**\n * Build fingerprint for the handshake. Running from source it is the newest\n * mtime under the `src/` tree at import time. Bundled, it is the mtime of this\n * module's own file. Client and daemon load the same files from disk, so a\n * daemon spawned before a rebuild (or a source edit in dev) reports a\n * different id than a freshly-started client, and the client drains +\n * respawns it. This closes the \"same protocol version, different code\"\n * gap that a hand-bumped version constant can't: during development the\n * daemon process is frozen at spawn while the tree keeps moving.\n *\n * Compiled binaries (`/$bunfs/…` virtual paths) can't be stat'ed and\n * report `'unknown'`; the check is skipped when EITHER side is unknown,\n * so released builds rely on `IPC_PROTOCOL_VERSION` alone — correct,\n * since their code only changes when the version does.\n */\nexport const IPC_BUILD_ID: string = (() => {\n try {\n const selfPath = fileURLToPath(import.meta.url)\n /*\n * Dev (running from source): fingerprint the whole source tree, not\n * just this file — a change to server.ts / engine.ts / runtime code\n * with no edit to lifecycle.ts must still retire an old daemon. Walk\n * `src/` and take the newest mtime. When the tree isn't present\n * (bundled dist, compiled binary) we fall back to this module's own\n * file mtime; in a bundle every ipc source collapses into one chunk, so\n * that single mtime already moves on any ipc change.\n */\n /*\n * Root validation is load-bearing: from a built bundle this module\n * lives flat in `dist/`, so the two-levels-up guess would be the\n * PACKAGE root — walking it would synchronously stat the whole repo\n * (node_modules, .git) at import time and fingerprint unrelated\n * churn. Only walk when the candidate directory demonstrably IS the\n * ipc source tree; a bundle falls back to this chunk's own mtime,\n * which already moves on every rebuild.\n */\n const ipcRoot = dirname(dirname(selfPath))\n if (!existsSync(join(ipcRoot, 'protocol.ts')))\n return String(Math.floor(statSync(selfPath).mtimeMs))\n\n /*\n * Dev scope: walk the whole `src/` tree, not just `src/ipc` — daemon\n * behavior also lives in agent.ts, loop.ts, and chat/** (store,\n * replay, discovery), and an edit there must retire a running dev\n * daemon just as surely as an ipc edit (the spawn-marker incident\n * lived in chat/store.ts). A few hundred stats — milliseconds.\n */\n const srcRoot = dirname(ipcRoot)\n let newest = 0\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = join(dir, entry.name)\n if (entry.isDirectory())\n walk(full)\n else\n newest = Math.max(newest, statSync(full).mtimeMs)\n }\n }\n try {\n walk(srcRoot)\n }\n catch {\n newest = statSync(selfPath).mtimeMs\n }\n return String(Math.floor(newest))\n }\n catch {\n return 'unknown'\n }\n})()\n\n/**\n * Socket file name. Dev builds (`ZIDANE_DEV=1`, set by every `dev` script\n * in the repo) get their OWN socket so a checkout's TUI, GUI and `zidane\n * daemon` pair up among themselves and never attach to — or get refused by\n * — the installed daemon. Without this, a protocol bump in the working\n * tree turned the dev GUI's dot red against the stable daemon, and a dev\n * daemon could drain the one the installed TUI relies on.\n * @param env - Environment to read `ZIDANE_DEV` from.\n * @returns `dev.sock` for a dev build, else `daemon.sock`.\n */\nexport function daemonSocketName(env: NodeJS.ProcessEnv = process.env): 'daemon.sock' | 'dev.sock' {\n return env.ZIDANE_DEV && env.ZIDANE_DEV !== '0' ? 'dev.sock' : 'daemon.sock'\n}\n\n/**\n * Path of the daemon socket this process uses.\n * The `ZIDANE_DAEMON_SOCKET` environment variable wins. Otherwise it is `<stateDir>/daemon/<socket name>`, see {@link daemonSocketName}.\n * @returns The socket path.\n */\nexport function defaultSocketPath(): string {\n const explicit = process.env.ZIDANE_DAEMON_SOCKET\n if (explicit)\n return explicit\n /*\n * The socket is transient runtime state, so it lands under the resolved\n * state dir — XDG-aware on XDG installs, `<storageDir>/<prefix>` in\n * legacy mode. Uses the same resolver every other surface reads through,\n * honoring `ZIDANE_STORAGE_DIR` / `ZIDANE_PREFIX`.\n *\n * DEDICATED `daemon/` subdir: the state dir is shared with\n * `state.json` / logs, so the daemon can't chmod it 0700 without\n * affecting unrelated files. The server hardens this subdir instead;\n * client and server must agree on this path.\n */\n const dirs = resolveStorageDirs({\n ...(process.env.ZIDANE_PREFIX !== undefined ? { prefix: process.env.ZIDANE_PREFIX } : {}),\n })\n return join(dirs.stateDir, 'daemon', daemonSocketName())\n}\n\n/**\n * Legacy socket location (`<stateDir>/daemon.sock`) for the given socket path,\n * or null when the path isn't the default `<stateDir>/daemon/daemon.sock`\n * layout (explicit `ZIDANE_DAEMON_SOCKET` users never had a migration to run).\n * A daemon still serving the old path would be ORPHANED by the move — new clients\n * never probe it, and a service-style `--idle-exit 0` daemon would hold\n * agents and run-guard markers against the same sessions.db forever —\n * so daemon startup probes this path and drains any survivor.\n */\nexport function legacySocketPath(socketPath: string): string | null {\n const dir = dirname(socketPath)\n if (basename(socketPath) !== 'daemon.sock' || basename(dir) !== 'daemon')\n return null\n return join(dirname(dir), 'daemon.sock')\n}\n\n/**\n * Spawn command that re-enters the CURRENT zidane program as `… daemon`.\n *\n * Three launch shapes:\n * - compiled Bun binary — `Bun.main` is the virtual `/$bunfs/…` entry the\n * binary self-inserts as argv[1], so the spawn must NOT repeat it\n * (verified: repeating it makes the child parse the junk path as its\n * subcommand and boot the full TUI instead of the daemon).\n * - dev (`bun run cli.ts`) — the script path must ride along.\n * - Node hosts (no `Bun` global) — fall back to the published bin.\n */\nexport function selfDaemonSpawnCommand(): string[] {\n const bunMain = (globalThis as { Bun?: { main?: string } }).Bun?.main\n // Compiled binary: the virtual entry parses its own `daemon` subcommand.\n if (bunMain?.startsWith('/$bunfs'))\n return [process.execPath, 'daemon']\n // Dev-from-source: only re-execute `Bun.main` when it's actually a\n // zidane CLI entry (`cli.ts`/`cli.js`). For any other embedder (library\n // consumer, script) re-running their entry with a `daemon` argv would\n // launch an arbitrary program — fall back to the published bin instead.\n if (bunMain && /(?:^|[/\\\\])cli\\.[cm]?[jt]s$/.test(bunMain))\n return [process.execPath, bunMain, 'daemon']\n return ['zidane-daemon']\n}\n\n/**\n * True when something accepts connections on `socketPath`. Distinguishes a\n * live daemon from a stale socket file left by a crashed one.\n * @param socketPath - Path of the socket to try.\n * @param timeoutMs - How long to wait for the connection, in milliseconds.\n */\nexport function probeSocket(socketPath: string, timeoutMs = 1000): Promise<boolean> {\n return new Promise((resolve) => {\n /*\n * Skip the connect entirely unless the path is an actual socket file.\n * A stale REGULAR file (crashed daemon) or a missing path both mean\n * \"nothing listening\" — and connecting to them can surface a noisy\n * async ENOENT/ENOTSOCK that some runtimes treat as uncaught.\n */\n try {\n if (!existsSync(socketPath) || !statSync(socketPath).isSocket()) {\n resolve(false)\n return\n }\n }\n catch {\n resolve(false)\n return\n }\n\n let socket: ReturnType<typeof connect>\n try {\n socket = connect(socketPath)\n }\n catch {\n resolve(false)\n return\n }\n const done = (alive: boolean): void => {\n socket.destroy()\n resolve(alive)\n }\n socket.once('connect', () => done(true))\n socket.once('error', () => done(false))\n socket.setTimeout(timeoutMs, () => done(false))\n })\n}\n\n/** Options for {@link ensureDaemonRunning}. */\nexport interface EnsureDaemonOptions {\n /**\n * Socket the daemon listens on.\n * @default defaultSocketPath()\n */\n socketPath?: string\n /**\n * Command used to spawn the daemon when nothing is listening. Defaults to\n * `['zidane-daemon']` (the published bin). The child is detached and\n * unref'd — it outlives the spawning client by design.\n */\n spawnCommand?: string[]\n /** Total time to wait for the daemon to accept connections. Default 8000 ms. */\n timeoutMs?: number\n}\n\n/** Daemon starts in flight, by socket path, so concurrent callers share one. */\nconst pendingStarts = new Map<string, Promise<string>>()\n\n/**\n * Makes sure a daemon is listening on the socket, spawning one when nothing is. Concurrent calls for the same socket share one start.\n * Rejects when the spawn fails or the daemon does not accept connections within `timeoutMs`.\n * @param options - Socket, spawn command and timeout.\n * @returns The socket path once a connection succeeds.\n */\nexport function ensureDaemonRunning(options: EnsureDaemonOptions = {}): Promise<string> {\n const socketPath = options.socketPath ?? defaultSocketPath()\n const pending = pendingStarts.get(socketPath)\n if (pending)\n return pending\n const start = startDaemon({ ...options, socketPath }).finally(() => pendingStarts.delete(socketPath))\n pendingStarts.set(socketPath, start)\n return start\n}\n\nasync function startDaemon(options: EnsureDaemonOptions & { socketPath: string }): Promise<string> {\n const socketPath = options.socketPath\n if (await probeSocket(socketPath))\n return socketPath\n\n const [cmd, ...args] = options.spawnCommand ?? ['zidane-daemon']\n const child = spawn(cmd!, args, {\n detached: true,\n stdio: 'ignore',\n env: { ...process.env, ZIDANE_DAEMON_SOCKET: socketPath },\n })\n /*\n * A missing binary (e.g. `zidane-daemon` not on PATH) emits an async\n * `error` event; without a listener Node rethrows it as an uncaught\n * exception and crashes the caller. Capture it and surface a clean\n * rejection through the poll loop below.\n */\n let spawnError: Error | undefined\n child.once('error', (err: Error) => {\n spawnError = err\n })\n child.unref()\n\n const deadline = Date.now() + (options.timeoutMs ?? 8000)\n for (;;) {\n if (spawnError !== undefined)\n throw new Error(`Failed to spawn zidane daemon (${cmd}): ${spawnError.message}`)\n if (await probeSocket(socketPath))\n return socketPath\n if (Date.now() > deadline)\n throw new Error(`zidane daemon did not come up on ${socketPath} within ${options.timeoutMs ?? 8000}ms.`)\n await new Promise(r => setTimeout(r, 150))\n }\n}\n","/**\n * The client side every wire transport shares (the unix socket in\n * `../client.ts`, the WebSocket in `./ws-client.ts`): the `ipc.hello`\n * handshake with its version fences, typed requests with deadlines,\n * notifications, and signal fan-out. A transport supplies a connected\n * JSON-RPC {@link ClientChannel}; this turns it into an {@link IpcClient}.\n */\nimport type { AcpPeer, JsonRpcMessage } from '../../acp/types'\nimport type { HelloResult, HostSignal, IpcMethodName, IpcParams, IpcResult, SignalMeta } from '../protocol'\nimport { JsonRpcConnectionClosedError, JsonRpcRemoteError } from '../../acp/json-rpc'\nimport { compareVersions, ZIDANE_VERSION } from '../../version'\nimport { IPC_BUILD_ID } from '../daemon/lifecycle'\nimport { IPC_MIN_PROTOCOL_VERSION, IPC_PROTOCOL_VERSION, IpcErrorCode, PING_METHOD, SIGNAL_SEQ_FIELD } from '../protocol'\n\n/** A connected host client, shared by every transport. Requests are checked against {@link IpcMethods}. */\nexport interface IpcClient {\n /** The host's answer to the `ipc.hello` handshake. */\n hello: HelloResult\n /**\n * Calls a host method and resolves with its result. Rejects with a `JsonRpcRemoteError` when the host answers with an error, or with `JsonRpcConnectionClosedError` when the connection closes first.\n * A request not answered within its deadline (30 s, longer for slow methods) rejects and drops the connection. `machine.call` has no deadline.\n */\n request: <M extends IpcMethodName>(method: M, params: IpcParams<M>) => Promise<IpcResult<M>>\n /**\n * Fire-and-forget notification — same method table as `request`, but no\n * id, no response, no pending-promise bookkeeping. The hot path for\n * high-frequency writes (per-keystroke draft sync). Daemons that don't\n * know the method ignore it silently.\n */\n notify: <M extends IpcMethodName>(method: M, params: IpcParams<M>) => void\n /** Host signals, with their number in their session when they have one (`SignalMeta`). */\n onSignal: (cb: SignalListener) => () => void\n /** Closes the connection. Pending requests reject. */\n close: () => void\n}\n\nexport type SignalListener = (signal: HostSignal, meta?: SignalMeta) => void\n\n/** Thrown when the host refuses the handshake because its protocol, build or code version does not match the client's. */\nexport class IpcVersionMismatchError extends Error {\n /**\n * @param message - Description of the mismatch.\n * @param daemon - The host's handshake data, when it sent any.\n */\n constructor(message: string, readonly daemon?: HelloResult) {\n super(message)\n this.name = 'IpcVersionMismatchError'\n }\n}\n\n/** A connected JSON-RPC link to a host, as a transport hands it over. */\nexport interface ClientChannel {\n rpc: Pick<AcpPeer, 'sendRequest' | 'sendNotification'>\n /** The caller's `close()`: quiet (no `onClose`), fails what is in flight. Idempotent. */\n close: () => void\n /** Drop a wedged connection: like the host going away, so the transport's `onClose` fires. */\n abort: () => void\n /** Where the host is, for error messages (a socket path, a URL). */\n where: string\n}\n\nexport interface ClientCoreOptions {\n appVersion?: string\n /**\n * When the host refuses the handshake on a version / build mismatch:\n * `always` asks it to drain so a matching one can be spawned (session\n * controllers on the local daemon); `stale-only` only when the host is\n * provably older (passive local clients); `never` leaves it running (a\n * remote server's lifetime is not the client's to end).\n */\n drain: 'always' | 'stale-only' | 'never'\n /**\n * Send this build's fingerprint, so a host from an older build of the same\n * protocol refuses us. Off sends the `'unknown'` sentinel: clients that\n * can't act on a build mismatch (no drain, no respawn) opt out of that fence.\n */\n buildFence: boolean\n /**\n * Ping the host (`$/ping`) this often once attached; two pings in a row\n * left unanswered at the next tick abort the connection (the transport's\n * `onClose` fires, its owner reconnects). Off when absent or `0`: a\n * local socket learns of a dead host from the kernel.\n */\n heartbeatMs?: number\n}\n\n/** Missed heartbeats after which the host is considered gone. */\nexport const HEARTBEAT_MISSES = 2\n\n/** Starts the client heartbeat on `channel`; returns its stop. Stops itself once the channel closes. */\nfunction startHeartbeat(channel: ClientChannel, intervalMs: number): () => void {\n let awaiting = false\n let missed = 0\n const timer = setInterval(() => {\n if (awaiting && ++missed >= HEARTBEAT_MISSES) {\n clearInterval(timer)\n channel.abort()\n return\n }\n awaiting = true\n channel.rpc.sendRequest(PING_METHOD, {}).then(\n () => {\n awaiting = false\n missed = 0\n },\n (err: unknown) => {\n if (err instanceof JsonRpcConnectionClosedError) {\n clearInterval(timer)\n return\n }\n // Any answer, an error included (a host predating `$/ping`), proves it alive.\n awaiting = false\n missed = 0\n },\n )\n }, intervalMs)\n timer.unref?.()\n return () => clearInterval(timer)\n}\n\n/** The signal listeners of one client, and the JSON-RPC notification handler that feeds them. */\nexport function createSignalListeners() {\n const listeners = new Set<SignalListener>()\n return {\n listeners,\n onNotification(message: JsonRpcMessage & { method: string }): void {\n if (message.method !== 'ipc.signal')\n return\n const params = (message as { params?: HostSignal & { [SIGNAL_SEQ_FIELD]?: unknown } }).params\n if (!params)\n return\n const { [SIGNAL_SEQ_FIELD]: seq, ...signal } = params\n const meta = typeof seq === 'number' ? { seq } : undefined\n for (const cb of listeners)\n cb(signal as HostSignal, meta)\n },\n }\n}\n\nfunction hostRelease(hello: HelloResult): string | undefined {\n for (const value of [hello.codeVersion, hello.appVersion]) {\n if (typeof value !== 'string')\n continue\n const match = /^(?:zidane-gui\\/)?(v?\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?)$/.exec(value.trim())\n if (match)\n return match[1]\n }\n return undefined\n}\n\nconst HELLO_TIMEOUT_MS = 5000\nconst LONG_REQUEST_TIMEOUT_MS = 10 * 60 * 1000\n/** RPCs that legitimately run long: full compaction, index-backed cross-session search, a clone, a folder search. */\nconst LONG_REQUEST_METHODS = new Set<string>(['sessions.compact', 'history.searchAll', 'history.searchSession', 'git.clone', 'fs.searchDirs'])\n\n/**\n * A refused handshake. Asks the host to drain when `drain` allows it, closes\n * the channel, and returns the error to throw.\n */\nasync function refusedHello(channel: ClientChannel, err: JsonRpcRemoteError, drain: ClientCoreOptions['drain']): Promise<IpcVersionMismatchError> {\n /*\n * Ask the stale daemon to drain so the caller can respawn a matching\n * one. AWAIT the reply (bounded) before tearing the connection down —\n * closing discards unflushed writes, so a fire-and-forget\n * `daemon.shutdown` could be dropped, leaving the stale daemon alive\n * and defeating `connectOrSpawnDaemon`'s retry.\n */\n const daemon = (err.data as { daemon?: HelloResult } | undefined)?.daemon\n // A network server's lifetime is never a client's to end, whatever `drain` says.\n if (daemon?.hostKind === 'server') {\n channel.close()\n return new IpcVersionMismatchError(serverMismatchMessage(daemon, channel.where) ?? err.message, daemon)\n }\n /*\n * Passive clients (`stale-only`) never retire a daemon on a protocol /\n * build mismatch — it may be NEWER than them. A daemon that is provably\n * OLDER — an older release, or the same release speaking an older\n * protocol (a dev build from before a protocol bump) — is the case where\n * draining is always safe: nothing newer can be running on it, and\n * whoever attaches next spawns a current one. Without this a passive\n * client (the GUI) would sit in-process forever behind a stale daemon\n * nobody restarts: every retry is refused.\n */\n const daemonIsOlderRelease\n = typeof daemon?.codeVersion === 'string' && compareVersions(daemon.codeVersion, ZIDANE_VERSION) < 0\n const release = daemon && hostRelease(daemon)\n const daemonIsNewerRelease = release !== undefined && compareVersions(release, ZIDANE_VERSION) > 0\n const daemonSpeaksOlderProtocol = typeof daemon?.protocolVersion === 'number' && daemon.protocolVersion < IPC_PROTOCOL_VERSION\n const daemonIsStale = daemonIsOlderRelease || daemonSpeaksOlderProtocol\n if (drain !== 'never' && !daemonIsNewerRelease && (drain === 'always' || daemonIsStale)) {\n // `whenIdle`: a daemon with live runs defers its exit instead of\n // aborting them (older daemons ignore the flag and drain now).\n await Promise.race([\n channel.rpc.sendRequest('daemon.shutdown', { whenIdle: true }).catch(() => undefined),\n new Promise(resolve => setTimeout(resolve, 1500)),\n ])\n }\n channel.close()\n return new IpcVersionMismatchError(err.message, daemon)\n}\n\n/**\n * A server's protocol refusal, from this client's side: both versions and which side to upgrade.\n * `null` when the server's range (`minProtocolVersion`…`protocolVersion`) overlaps this client's.\n */\nfunction serverMismatchMessage(server: HelloResult, where: string): string | null {\n if (typeof server.protocolVersion !== 'number')\n return null\n const serverMin = typeof server.minProtocolVersion === 'number' ? server.minProtocolVersion : server.protocolVersion\n if (serverMin <= IPC_PROTOCOL_VERSION && server.protocolVersion >= IPC_MIN_PROTOCOL_VERSION)\n return null\n const upgrade = server.protocolVersion < IPC_PROTOCOL_VERSION ? 'server' : 'client'\n return `Protocol version mismatch with ${where}: the server speaks v${server.protocolVersion}, this client v${IPC_PROTOCOL_VERSION}. Upgrade the ${upgrade}.`\n}\n\nasync function handshake(channel: ClientChannel, options: ClientCoreOptions): Promise<HelloResult> {\n /*\n * Bound the handshake: a wedged daemon (accepting connections but never\n * reading — e.g. SIGSTOP'd) would otherwise hang this promise forever.\n * On timeout the channel is closed and the connect rejects.\n * `Promise.race` keeps the losing request promise handled, so the\n * connection-closed rejection that follows `close()` can't surface as an\n * unhandled rejection.\n */\n let helloTimer: ReturnType<typeof setTimeout> | undefined\n try {\n return (await Promise.race([\n channel.rpc.sendRequest('ipc.hello', {\n protocolVersion: IPC_PROTOCOL_VERSION,\n minProtocolVersion: IPC_MIN_PROTOCOL_VERSION,\n appVersion: options.appVersion ?? 'dev',\n pid: process.pid,\n // Build fingerprint: a daemon started from an OLDER build of this\n // same protocol version rejects us, gets drained, and respawns —\n // dev daemons cannot run stale code silently. Clients that\n // cannot act on a build mismatch send the 'unknown' sentinel\n // instead (see `buildFence`): fencing them would just lock them\n // out until someone else retires the host. They stay fenced by\n // protocol version and degrade via `optional()` like any client of\n // an older daemon.\n buildId: options.buildFence ? IPC_BUILD_ID : 'unknown',\n // Always sent, passive clients included: a stale-RELEASE daemon is\n // safe for anyone to retire (see `refusedHello`).\n codeVersion: ZIDANE_VERSION,\n }),\n new Promise<never>((_, reject) => {\n helloTimer = setTimeout(\n () => reject(new Error(`Daemon handshake timed out after ${HELLO_TIMEOUT_MS}ms on ${channel.where}.`)),\n HELLO_TIMEOUT_MS,\n )\n }),\n ])) as HelloResult\n }\n catch (err) {\n if (err instanceof JsonRpcRemoteError && err.code === IpcErrorCode.VersionMismatch)\n throw await refusedHello(channel, err, options.drain)\n channel.close()\n throw err\n }\n finally {\n clearTimeout(helloTimer)\n }\n}\n\n/** Handshake over `channel`, then the typed client around it. On failure the channel is closed. */\nexport async function openIpcClient(\n channel: ClientChannel,\n listeners: Set<SignalListener>,\n options: ClientCoreOptions,\n): Promise<IpcClient> {\n const hello = await handshake(channel, options)\n\n const release = hostRelease(hello)\n // A `retiring` daemon is fence-aware and already exits once idle; staying\n // attached until then keeps its live runs reachable from this window. A\n // network server is never retired for a client: an older one is attached\n // to, and this client degrades (`optional()`) like an older client does.\n if (!hello.retiring && hello.hostKind !== 'server' && release !== undefined && compareVersions(release, ZIDANE_VERSION) < 0) {\n // Pre-fence daemons accept hello without checking codeVersion. Disconnect\n // only: shutting down a successfully attached daemon can abort active runs.\n channel.close()\n throw new IpcVersionMismatchError(\n `Daemon release ${release} is older than client ${ZIDANE_VERSION}. Restart the daemon when active runs have finished.`,\n hello,\n )\n }\n\n // Env override is a test seam (process-level e2e exercises the real\n // deadline without waiting 30 s); undocumented, not a user setting.\n const requestTimeoutMs = Number(process.env.ZIDANE_IPC_REQUEST_TIMEOUT_MS) || 30_000\n\n const stopHeartbeat = options.heartbeatMs ? startHeartbeat(channel, options.heartbeatMs) : () => undefined\n\n return {\n hello,\n notify: (method, params) => {\n try {\n channel.rpc.sendNotification(method, params)\n }\n catch {\n // fire-and-forget by contract — a dying connection surfaces via onClose\n }\n },\n request: async (method, params) => {\n /*\n * Per-request deadline: close rejection covers a DEAD host, but a\n * wedged one (alive, not reading — the same class the server-side\n * backpressure bound handles for peers) would hang callers forever.\n * On timeout the connection is aborted (NOT `close()` — the `onClose`\n * path must fire so reconnect logic takes over) and every pending\n * request rejects via the close sweep. Known long-running RPCs get a\n * generous budget; tearing the connection down mid-`sessions.compact`\n * would abort real work, so those bounds are deliberately loose.\n */\n // A machine call lasts as long as its command (`docs/MACHINES.md`); a dead host is the heartbeat's to catch.\n if (method === 'machine.call')\n return channel.rpc.sendRequest(method, params) as Promise<IpcResult<typeof method>>\n const timeoutMs = LONG_REQUEST_METHODS.has(method) ? LONG_REQUEST_TIMEOUT_MS : requestTimeoutMs\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return (await Promise.race([\n channel.rpc.sendRequest(method, params),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`Daemon request ${method} timed out after ${timeoutMs}ms, closing the connection.`))\n channel.abort()\n }, timeoutMs)\n timer.unref?.()\n }),\n ])) as IpcResult<typeof method>\n }\n finally {\n clearTimeout(timer)\n }\n },\n onSignal: (cb) => {\n listeners.add(cb)\n return () => listeners.delete(cb)\n },\n close: () => {\n stopHeartbeat()\n channel.close()\n },\n }\n}\n","/** Stable hashes of sync values: equal values (whatever their key order) hash the same, on both sides. */\nimport { createHash } from 'node:crypto'\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** JSON with sorted keys (undefined members dropped). */\nexport function stableStringify(value: unknown): string {\n if (Array.isArray(value))\n return `[${value.map(stableStringify).join(',')}]`\n if (isRecord(value))\n return `{${Object.keys(value).sort().filter(k => value[k] !== undefined).map(k => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`\n return JSON.stringify(value) ?? 'undefined'\n}\n\nexport function hashValue(value: unknown): string {\n return createHash('sha256').update(stableStringify(value)).digest('hex')\n}\n","/** Which settings the `settings` sync category carries (`./types`). */\nimport type { Settings } from '../types'\nimport { HOST_ENABLED_LISTS, isWindowOnlySetting } from '../host-scoped-settings'\n\n/**\n * Host-scoped settings that still don't sync: they describe this computer\n * (its environments, its daemon, remote hosts on it) or would turn off what\n * the server has that this computer doesn't (the enabled allowlists, its OS\n * sandbox). Every `sandbox*` key, present and future, is the server's own:\n * a client turning it off there would be a sandbox escape.\n */\nconst NOT_SYNCED_SETTINGS: ReadonlySet<string> = new Set<string>(['environments', 'useDaemon', 'remoteHosts', ...HOST_ENABLED_LISTS])\n\n// The same legacy `safeMode` mapping as the live settings wire (`settings.get` / `settings.set`).\nexport { settingsFromWire, settingsToWire } from '../host-scoped-settings'\n\n/** A setting the `settings` category carries: host-scoped (never window-only) and not machine-specific. */\nexport function isSyncableSetting(key: keyof Settings | string): boolean {\n return !isWindowOnlySetting(key) && !NOT_SYNCED_SETTINGS.has(key) && !key.startsWith('sandbox')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,sBAA8B;CACzC,IAAI;EACF,MAAM,WAAW,cAAc,YAAY,GAAG;EAmB9C,MAAM,UAAU,QAAQ,QAAQ,QAAQ,CAAC;EACzC,IAAI,CAAC,WAAW,KAAK,SAAS,aAAa,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AE,GAAG,gBAAgB,MAAM,EAAE,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE;CACnJ,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC;AAEA,SAAgB,UAAU,OAAwB;CAChD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,gBAAgB,KAAK,CAAC,CAAC,CAAC,OAAO,KAAK;AACzE;;;;;;;;;;ACLA,MAAM,sCAA2C,IAAI,IAAY;CAAC;CAAgB;CAAa;CAAe,GAAG;AAAkB,CAAC;;AAMpI,SAAgB,kBAAkB,KAAuC;CACvE,OAAO,CAAC,oBAAoB,GAAG,KAAK,CAAC,oBAAoB,IAAI,GAAG,KAAK,CAAC,IAAI,WAAW,SAAS;AAChG"}
|
package/dist/tui.js
CHANGED
|
@@ -28,11 +28,11 @@ import { r as browseSkillSource, s as installSkillFromSpec } from "./skills-Cx8i
|
|
|
28
28
|
import { a as skillCategory, i as groupSkillPicks, o as skillPickKey, s as skillPickOf, t as RECOMMENDED_SKILL_SOURCES } from "./sources-h464u_hH.js";
|
|
29
29
|
import { _ as extensionScaffold, d as ZIDANE_SKILL_EDIT_SKILL_NAME, u as ZIDANE_EXTENSION_SKILL_NAME } from "./system-freeze-BbYXyZuF.js";
|
|
30
30
|
import { A as badgeMenu, R as runBadgeAction, _ as panelBadgeText, d as pushPaletteRecent, f as rankPaletteItems, h as normalizePanelContent, k as artifactBadgeTarget, s as groupPaletteRows, z as sessionBadgeTarget } from "./palette-CGiUyXqF.js";
|
|
31
|
-
import { $ as scanExtensionDirectories, A as createExtensionHostRuntimeBridge, B as matchesBinding, C as filterRegistryPlugins, F as KEYBINDING_KEY_COL_WIDTH, G as resolveExtensionKeybindings, I as ensureKeybindingsFile, L as formatBindingForDisplay, N as KEYBINDING_DEFS, O as createExtensionHud, Q as parseExtensionScanPathEnv, R as groupBindings, S as filterExtensionRegistry, T as partitionExtensionCatalog, X as inlineLoadedExtension, _ as removeInstalledExtension, at as coerceExtensionConfigInput, bt as createExtensionBus, d as ExtensionInstallError, lt as resolveExtensionConfigValue, n as createExtensionPromptBridge, p as installExtensionFromSpec, ut as sanitizeExtensionConfigActionPatch, v as updateInstalledExtension, x as disposeExtensionRegistry, y as discoverAndBuildExtensionRegistry, z as keybindingsPath } from "./extensions-
|
|
31
|
+
import { $ as scanExtensionDirectories, A as createExtensionHostRuntimeBridge, B as matchesBinding, C as filterRegistryPlugins, F as KEYBINDING_KEY_COL_WIDTH, G as resolveExtensionKeybindings, I as ensureKeybindingsFile, L as formatBindingForDisplay, N as KEYBINDING_DEFS, O as createExtensionHud, Q as parseExtensionScanPathEnv, R as groupBindings, S as filterExtensionRegistry, T as partitionExtensionCatalog, X as inlineLoadedExtension, _ as removeInstalledExtension, at as coerceExtensionConfigInput, bt as createExtensionBus, d as ExtensionInstallError, lt as resolveExtensionConfigValue, n as createExtensionPromptBridge, p as installExtensionFromSpec, ut as sanitizeExtensionConfigActionPatch, v as updateInstalledExtension, x as disposeExtensionRegistry, y as discoverAndBuildExtensionRegistry, z as keybindingsPath } from "./extensions-Bb_-1vbS.js";
|
|
32
32
|
import { i as nextLogLevel, n as filterLogRecords, r as formatLogLine } from "./logs-view-DF7ArI6t.js";
|
|
33
33
|
import { a as createRingBufferSink, c as logFileTimestamp, i as createLoggingHooks, n as createFileSink, o as fanoutSink, r as createLogger } from "./logger-BQj8QCJp.js";
|
|
34
34
|
import { t as registerExtensionHostModules } from "./host-modules-D5apgL1F.js";
|
|
35
|
-
import { t as ZIDANE_VERSION } from "./version-
|
|
35
|
+
import { t as ZIDANE_VERSION } from "./version-_Yunc9lZ.js";
|
|
36
36
|
import { a as DEFAULT_OAUTH_ACCOUNT_LABEL, p as oauthAccountLabel } from "./cred-keys-C0KaSRp7.js";
|
|
37
37
|
import { t as JsonRpcConnectionClosedError } from "./json-rpc-G0rBfEar.js";
|
|
38
38
|
import { d as buildBuildSystem, f as buildPlanSystem } from "./agent-prompt-BXVwL89Y.js";
|
|
@@ -42,7 +42,7 @@ import { _ as verifyEnvironment, f as readSessionEnvironment, i as assertEnviron
|
|
|
42
42
|
import { E as restoreChainFallbacks, O as toggleChainEntry, T as reorderKeyed, b as pickChainPrimary, g as chainsEqual, h as chainPositionOf, m as chainEntryKey, p as chainAccountConflict, r as editableTurnText, s as turnAsText, u as readSessionAccount, v as filterChainFallbacks, w as rememberableChain } from "./turn-operations-CWoCTC_L.js";
|
|
43
43
|
import { $ as formatTokenCount, E as SESSION_EVENT_STATUS_STYLE, H as shortSessionId, J as fitRunReceiptCells, M as isMainSession, R as sessionDirLabel, S as parseModelSetting, V as sessionEventMeta, W as truncateTitle, Y as formatCostUsd, Z as formatRunReceiptCells, a as defaultSessionAgent, b as spacesEnabled, d as normalizeSpaces, f as readSessionSpaceId, h as spaceIdForNewSession, i as activeSpaceOf, it as modelDisplayName, m as sessionSpaceFilter, nt as nameFromModelId, o as defaultSessionKnobs, p as resolveSessionSpace, r as SPACE_METADATA_KEY, s as defaultSessionModel, t as DEFAULT_SPACE_ID, v as spaceOfSwitchItem, x as formatModelSetting, y as spaceSwitchItems, z as sessionEventExcerpt } from "./spaces-Bgq_mIe_.js";
|
|
44
44
|
import { N as suggestSafelistEntries, a as renderSystemMdSeed, d as discoverProjectMcps, i as discoverSystemMd, o as userScopeOverridesLoad, s as userSystemMdPath, t as createFileEnvironmentSecrets } from "./environment-credentials-DEETiFGr.js";
|
|
45
|
-
import { $ as tryRevealPath, $t as readPinnedSkills, A as aggregateUsage, Bt as resolveStoragePaths, C as fetchAllProviderUsage, D as usageChecksOptedOut, E as providerUsageSupported, F as connectorGithubToken, Fn as loadMcpToolsCache, Ft as removeMcpServer, G as hasClaudeCodeSetup, Gt as createFileMcpCredentialStore, I as detectOnboardingEnvironment, In as mcpToolsCachePath, It as upsertMcpServer, J as oauthUsesManualCodePaste, Jt as provisionSessionEnvironment, K as importFromClaudeCode, Kn as testDecisionModel, Ln as refreshMcpToolsCatalog, Mn as discoverProjectPlugins, Mt as listProjectFiles, Nn as parsePluginScanPathEnv, P as writeSessionExport, Pt as mcpsWritePath, Q as tryOpenBrowser, R as onboardingInstallSignals, Rt as createExtensionMcpHost, S as clearProviderUsageCache, Sn as readRemoteSandboxRef, U as claudeImportHostNote, Un as listDecisionModels, V as onboardingProviders, W as countClaudeSessionFiles, Wn as parseDecisionModel, X as runOAuthLogin, Y as pickOAuthSelectOption, Z as supportsOAuth, Zt as PINNED_SKILLS_META_KEY, an as discoverProjectSkills, dn as discoverAgentsMd, en as storeHasDurability, gn as builtinEnvironmentProviders, jn as buildPluginContributions, k as fetchGithubUsage, kn as resolveSessionCwd, on as createBuiltinCommands, q as previewClaudeImport, rn as createSkillNameProbe, sn as applyThinkingBindingSetting, un as installProviderDiagnosticHook, w as fetchProviderUsage, zn as subscribeMcpToolsCache, zt as resolveConfig } from "./auto-update-restart-
|
|
45
|
+
import { $ as tryRevealPath, $t as readPinnedSkills, A as aggregateUsage, Bt as resolveStoragePaths, C as fetchAllProviderUsage, D as usageChecksOptedOut, E as providerUsageSupported, F as connectorGithubToken, Fn as loadMcpToolsCache, Ft as removeMcpServer, G as hasClaudeCodeSetup, Gt as createFileMcpCredentialStore, I as detectOnboardingEnvironment, In as mcpToolsCachePath, It as upsertMcpServer, J as oauthUsesManualCodePaste, Jt as provisionSessionEnvironment, K as importFromClaudeCode, Kn as testDecisionModel, Ln as refreshMcpToolsCatalog, Mn as discoverProjectPlugins, Mt as listProjectFiles, Nn as parsePluginScanPathEnv, P as writeSessionExport, Pt as mcpsWritePath, Q as tryOpenBrowser, R as onboardingInstallSignals, Rt as createExtensionMcpHost, S as clearProviderUsageCache, Sn as readRemoteSandboxRef, U as claudeImportHostNote, Un as listDecisionModels, V as onboardingProviders, W as countClaudeSessionFiles, Wn as parseDecisionModel, X as runOAuthLogin, Y as pickOAuthSelectOption, Z as supportsOAuth, Zt as PINNED_SKILLS_META_KEY, an as discoverProjectSkills, dn as discoverAgentsMd, en as storeHasDurability, gn as builtinEnvironmentProviders, jn as buildPluginContributions, k as fetchGithubUsage, kn as resolveSessionCwd, on as createBuiltinCommands, q as previewClaudeImport, rn as createSkillNameProbe, sn as applyThinkingBindingSetting, un as installProviderDiagnosticHook, w as fetchProviderUsage, zn as subscribeMcpToolsCache, zt as resolveConfig } from "./auto-update-restart-Z2v5vltT.js";
|
|
46
46
|
import { a as commandNoteText, c as noteDisplay, i as commandHeaderBlock, s as gatherCommandNotes } from "./nested-call-events-BYk8XvGX.js";
|
|
47
47
|
import { A as summarizeOutcomes, _ as extractEditPayload, f as buildContextualDiff, l as promptSegmentLines, m as clipDiffForRender, p as buildUnifiedDiff, t as oneLineTitle, u as splitPromptSegments, v as filetypeFromPath, x as summarizeEditPayload, y as previewEditPayload } from "./session-title-text-CQvgo3yS.js";
|
|
48
48
|
import { D as usageByModel, S as sumRunCosts, a as eventsFromTurns, b as sessionEnvironmentSummary, c as headerFromData, d as loadState, f as marginTopFor, i as deriveSessionTitle, l as lastContextSizeFromTurns, o as getSessionHeader, p as noticeTurnContent, s as getSessionMeta, u as listSessionMeta, w as toolCallPreview } from "./store-dJ1jDLZW.js";
|
|
@@ -58,18 +58,18 @@ import { $ as machineWaiting, At as HostRemovedError, B as validateMcpForm, Ct a
|
|
|
58
58
|
import { a as settingsFromWire, c as applyEnvironmentSettingsChange, i as overlayHostSettings, n as WINDOW_LOCAL_SETTINGS, o as settingsToWire, p as resolveProviderConfig, r as isWindowOnlySetting, s as splitHostSettingsPatch, u as describeEnvironments } from "./host-scoped-settings-CLPvpPwd.js";
|
|
59
59
|
import { a as isMethodNotFound, n as LOCAL_HOST_KEY, r as LOCAL_HOST_NAME } from "./connection-BaHd3T-D.js";
|
|
60
60
|
import { d as hostRefOf, f as loadAllEvents, h as loadSessionDocument, m as loadEventsTail, p as loadEventsPage, r as IpcErrorCode } from "./protocol-DxbYJdHT.js";
|
|
61
|
-
import { n as startInProcessHost, y as createHostEnvironment } from "./memory-
|
|
62
|
-
import { n as runRemoteOAuth, t as runWorkspaceExecStream } from "./ipc-
|
|
61
|
+
import { n as startInProcessHost, y as createHostEnvironment } from "./memory-T-sU3COB.js";
|
|
62
|
+
import { n as runRemoteOAuth, t as runWorkspaceExecStream } from "./ipc-DTeKfnHc.js";
|
|
63
63
|
import { a as SYNC_MODES, f as syncAgo, i as SYNC_CATEGORY_INFO, o as SYNC_MODE_LABEL, p as syncMarkerOf, r as SYNC_CATEGORIES, u as settingField } from "./types-Skz6Z48Z.js";
|
|
64
64
|
import { c as formatJoinString } from "./browser-dFkKWxr-.js";
|
|
65
65
|
import { t as keepHostConnected } from "./connection-loop-DSCehV3W.js";
|
|
66
66
|
import { r as parseRemoteHostUrl, t as RemoteHostError } from "./url-znC3tmKE.js";
|
|
67
67
|
import { createTuiStore } from "./session/sqlite.js";
|
|
68
|
-
import { a as buildUpdateHint, c as useUpdateCheck, i as buildRestartHint, n as buildHints, o as useAutoInstallUpdate, s as useRestartRequired, t as formatPathForCwd, w as groupArtifacts } from "./path-display-
|
|
68
|
+
import { a as buildUpdateHint, c as useUpdateCheck, i as buildRestartHint, n as buildHints, o as useAutoInstallUpdate, s as useRestartRequired, t as formatPathForCwd, w as groupArtifacts } from "./path-display-vzEF03NO.js";
|
|
69
69
|
import { A as clipHintsToWidth, B as createDiscoverySlot, C as McpAuthProvider, D as useInteractionsActions, E as InteractionsProvider, F as SettingsOverride, G as ConfigProvider, H as useDiscovery, I as SettingsProvider, J as createArtifactsCompletionProvider, K as useConfig, L as useSettings, M as hintsLength, N as truncateTrailing, O as useInteractionsQueue, P as useEnabledToggleSet, Q as bootTick, R as parseEditorCommand, S as parentServerName, T as useMcpAuthState, U as useDiscoveryOptional, V as DiscoveryProvider, W as ConfigContext, X as useCompletion, a as useSurfaces, b as buildVisibleMcpRows, c as useStreamBuffer, d as useSafeModeQueue, g as redirectUriFromAuthUrl, i as useSelectStyle, k as EMPTY_HINTS, l as SafeModeProvider, m as fetchOAuthRedirect, n as ThemeProvider, o as useSyntaxStyles, p as withRunningCallStarts, r as useColors, s as useTheme, t as computeTurnAnchors, u as useSafeModeActions, v as useMcpToolToggleMap, w as useMcpAuthDispatch, x as indexOfServerRow, z as quoteForShell } from "./transcript-anchors-De74UqEg.js";
|
|
70
70
|
import { $ as ONBOARDING_WORDS, A as stepTranscriptCap, B as RUN_WAITING_LABEL, C as isEarlierHiddenMarker, Ct as getMcpAuthStatus, D as revealEarlierTranscriptEvents, Dt as chunkMarkdownForRender, E as replaceTranscriptTurnEvents, G as APPROVAL_MODE_TRADEOFFS, Gt as blendHsl, H as runRetryingLabel, It as DAEMON_HEALTH_STYLE, J as createOnboardingRun, Jt as cacheHintText, K as SETTING_TRADEOFFS, Kt as buildLinearRamp, L as spawnParents, N as turnContextSize, Nt as splitMarkdownCodeBlocks, Ot as closeDanglingCodeFence, P as withEarlierHidden, Pt as stripHtmlCommentsOutsideCode, Q as ONBOARDING_AGENT_NAMES, Rt as createSkillsCompletionProvider, S as hiddenEarlierTranscriptCount, St as MCP_STATUS_LABEL, U as runStatusKey, V as runFoldStatus, Vt as createFilesCompletionProvider, W as runTailActivity, Wt as createCommandsCompletionProvider, X as onboardingSwitchedFeatures, Y as onboardingImportParts, _ as capTranscriptEvents, _t as buildModelCatalog, a as displayNameFor, b as finalizeStreamingMarkdown, ct as ONBOARDING_PREVIEW_EVENTS, dt as CONNECTORS, et as connectorAuthText, ft as CONNECTOR_CATEGORIES, gt as connectorServerConfig, ht as connectorInstalled, j as streamTailRoot, jt as normalizeMarkdownCodeFences, kt as codeTokenHasClosingFence, lt as defaultImportSelection, mt as connectorInputError, n as reconcileEvents, nt as joinNames, o as formatToolCall, pt as connectorById, q as connectorsFromImport, r as TOOL_DISPLAY, rt as nativeExtensionNeedText, s as toolInputCode, t as convergeTranscript, v as coversTranscriptCap, vt as customModelTargets, wt as mcpFailureEvent, x as finalizeStreamingMarkdownForOwner, y as discardThinking, yt as filterModelCatalog, zt as uniqueSkillNamesFromReferences } from "./transcript-reconcile-CenPVKFz.js";
|
|
71
71
|
import { A as Well, B as HintRow, C as ListHeader, D as Switch, E as Segmented, F as Modal, G as parseHintKeySpec, H as dispatchHintKey, I as ModalRoot, L as useModal, M as badgeWidth, N as badgesWidth, O as SwitchSpan, P as cellWidth, R as useModalAwareFocus, S as CursorMarkSpan, T as PickerRow, U as hintSpans, V as ModalHints, W as inCheckboxZone, _ as BADGE_GAP, a as HostPickerModal, b as Check, c as hostStatusLook, d as EnvironmentPickerModal, f as hostUnavailableReason, g as waitForHostSettled, h as sessionHostGroups, i as pickMachineFolder, j as badgeColor$1, k as TitleBadges, l as orderRowsByHost, m as listAcrossHosts, n as localMachineKinds, o as ServerFolderPickerModal, p as isHostReachable, r as machineOfPick, s as SessionHostHeader, t as CwdPickerModal, u as placeHostHeaders, v as Badge, w as Note, x as CursorMark, y as Badges, z as useModalState } from "./cwd-picker-B6xJrv2-.js";
|
|
72
|
-
import { i as wsTransport, n as lazyInProcessTransport, r as socketTransport, t as hostSignalHandlers } from "./host-signals-
|
|
72
|
+
import { i as wsTransport, n as lazyInProcessTransport, r as socketTransport, t as hostSignalHandlers } from "./host-signals-DnZhcbMy.js";
|
|
73
73
|
import { Buffer } from "node:buffer";
|
|
74
74
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
75
75
|
import * as fs from "node:fs";
|
|
@@ -11175,7 +11175,7 @@ function useRemoteHosts(deps) {
|
|
|
11175
11175
|
let cancelled = false;
|
|
11176
11176
|
let started = null;
|
|
11177
11177
|
remoteHostsLoads++;
|
|
11178
|
-
import("./remote-hosts-
|
|
11178
|
+
import("./remote-hosts-RbuohEaP.js").then(({ startRemoteHosts }) => {
|
|
11179
11179
|
if (cancelled) return;
|
|
11180
11180
|
started = startRemoteHosts({
|
|
11181
11181
|
dataDir,
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* retires it, so an upgrade can never leave windows silently executing on a
|
|
12
12
|
* process started from the previous release.
|
|
13
13
|
*/
|
|
14
|
-
const ZIDANE_VERSION = "9.0.
|
|
14
|
+
const ZIDANE_VERSION = "9.0.4";
|
|
15
15
|
/**
|
|
16
16
|
* Compare two dotted versions (`7.0.19`, `7.1.0-beta.1`): negative when `a`
|
|
17
17
|
* is older, positive when newer, 0 when equal. Pre-release tags are ignored
|
|
@@ -39,4 +39,4 @@ function parse(v) {
|
|
|
39
39
|
//#endregion
|
|
40
40
|
export { compareVersions as n, ZIDANE_VERSION as t };
|
|
41
41
|
|
|
42
|
-
//# sourceMappingURL=version-
|
|
42
|
+
//# sourceMappingURL=version-_Yunc9lZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version-
|
|
1
|
+
{"version":3,"file":"version-_Yunc9lZ.js","names":["(pkg as { version?: string }).version"],"sources":["../package.json","../src/version.ts"],"sourcesContent":["","/**\n * The version of the zidane code this process is running — `package.json`\n * inlined at build time (Bun `--compile`, tsdown for `dist/`, and Vite for\n * the GUI main all fold JSON imports into the bundle, so this never reads\n * the filesystem at runtime and cannot report a NEIGHBOUR package's version\n * the way a `require('../package.json')` from a bundled chunk can).\n *\n * Used by the daemon handshake: a client running newer code than the daemon\n * retires it, so an upgrade can never leave windows silently executing on a\n * process started from the previous release.\n */\nimport pkg from '../package.json' with { type: 'json' }\n\nexport const ZIDANE_VERSION: string = (pkg as { version?: string }).version ?? '0.0.0'\n\n/**\n * Compare two dotted versions (`7.0.19`, `7.1.0-beta.1`): negative when `a`\n * is older, positive when newer, 0 when equal. Pre-release tags are ignored\n * — same release train, same code as far as the daemon fence is concerned.\n * Unparseable input compares equal (never fences on garbage).\n */\nexport function compareVersions(a: string, b: string): number {\n const pa = parse(a)\n const pb = parse(b)\n if (!pa || !pb)\n return 0\n for (let i = 0; i < 3; i++) {\n const d = (pa[i] ?? 0) - (pb[i] ?? 0)\n if (d !== 0)\n return d\n }\n return 0\n}\n\nfunction parse(v: string): number[] | null {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(v.trim())\n return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null\n}\n"],"mappings":";;;;;;;;;;;;;ACaA,MAAa,iBAAyBA;;;;;;;AAQtC,SAAgB,gBAAgB,GAAW,GAAmB;CAC5D,MAAM,KAAK,MAAM,CAAC;CAClB,MAAM,KAAK,MAAM,CAAC;CAClB,IAAI,CAAC,MAAM,CAAC,IACV,OAAO;CACT,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK;EAC1B,MAAM,KAAK,GAAG,MAAM,MAAM,GAAG,MAAM;EACnC,IAAI,MAAM,GACR,OAAO;CACX;CACA,OAAO;AACT;AAEA,SAAS,MAAM,GAA4B;CACzC,MAAM,IAAI,yBAAyB,KAAK,EAAE,KAAK,CAAC;CAChD,OAAO,IAAI;EAAC,OAAO,EAAE,EAAE;EAAG,OAAO,EAAE,EAAE;EAAG,OAAO,EAAE,EAAE;CAAC,IAAI;AAC1D"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.js";
|
|
2
2
|
import { a as errorResponse, i as createJsonRpcEndpoint, o as successResponse } from "./json-rpc-G0rBfEar.js";
|
|
3
3
|
import { i as METHOD_NOT_FOUND, t as HostIdentityError } from "./connection-BaHd3T-D.js";
|
|
4
|
-
import { a as createSignalListeners, o as openIpcClient } from "./settings-keys-
|
|
4
|
+
import { a as createSignalListeners, o as openIpcClient } from "./settings-keys-BP0tJDVS.js";
|
|
5
5
|
import { d as hostRefOf } from "./protocol-DxbYJdHT.js";
|
|
6
6
|
import { n as displayHostUrl } from "./url-znC3tmKE.js";
|
|
7
7
|
import tls from "node:tls";
|
|
@@ -313,4 +313,4 @@ async function connectWsClient(options) {
|
|
|
313
313
|
//#endregion
|
|
314
314
|
export { hostCaBundle as a, ws_client_exports as i, HostBusyError as n, trustSystemCertificates as o, connectWsClient as r, HostAuthError as t };
|
|
315
315
|
|
|
316
|
-
//# sourceMappingURL=ws-client-
|
|
316
|
+
//# sourceMappingURL=ws-client-CsAtVY0b.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ws-client-BWiyy8Op.js","names":["BunWebSocket"],"sources":["../src/ipc/transports/tls-trust.ts","../src/ipc/transports/ws-auth.ts","../src/ipc/transports/ws-client.ts"],"sourcesContent":["/**\n * Which certificate authorities a client trusts for a remote zidane-server:\n * the runtime's own roots plus the operating system's store (the macOS\n * keychain, the Linux CA bundle). A server behind a private CA, an mkcert\n * certificate or a self-signed one the user trusted in the OS then works\n * like a public one. `NODE_EXTRA_CA_CERTS` adds certificates at launch, in\n * both runtimes.\n *\n * Bun's WebSocket and fetch ignore `tls.setDefaultCACertificates`, so Bun\n * clients (the TUI, `zidane machine share`) pass the bundle with each\n * connection (`hostCaBundle`). Node honors it, so the desktop app's main\n * process trusts the store once, when it turns remote hosts on\n * (`trustSystemCertificates`).\n */\nimport tls from 'node:tls'\n\ntype CaKind = 'default' | 'system' | 'extra'\nconst api = tls as unknown as {\n getCACertificates?: (kind: CaKind) => string[]\n setDefaultCACertificates?: (certs: readonly string[]) => void\n}\n\nfunction certificates(kind: CaKind): string[] {\n try {\n return api.getCACertificates?.(kind) ?? []\n }\n catch {\n return []\n }\n}\n\nlet bundle: string[] | null | undefined\n\n/**\n * The runtime's roots, the OS store's and `NODE_EXTRA_CA_CERTS`'s, read once.\n * `null` when the OS store adds nothing (or can't be read): the runtime's\n * default then applies as it is.\n */\nexport function hostCaBundle(): string[] | null {\n if (bundle === undefined) {\n const system = certificates('system')\n bundle = system.length === 0 ? null : [...new Set([...certificates('default'), ...system, ...certificates('extra')])]\n }\n return bundle\n}\n\n/**\n * Node: every TLS client of this process trusts {@link hostCaBundle} from now\n * on (the desktop app's main process). Whether it applied.\n */\nexport function trustSystemCertificates(): boolean {\n const ca = hostCaBundle()\n if (!ca || !api.setDefaultCACertificates || typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined')\n return false\n api.setDefaultCACertificates(ca)\n return true\n}\n","/**\n * How a WebSocket client's token reaches the server, shared by both ends.\n *\n * Preferred: `Authorization: Bearer <token>` (Bun's WebSocket can set it).\n * Fallback for clients that can't set handshake headers (Node's and the\n * browser's WebSocket): a `zidane.bearer.<token>` entry in\n * `Sec-WebSocket-Protocol`, offered next to `zidane`, the subprotocol the\n * server selects. A token sent this way must be a valid subprotocol token\n * (base64url is).\n */\n\nimport type { ClientScope } from '../scopes'\n\n/** The subprotocol clients offer and the server selects. */\nexport const WS_SUBPROTOCOL = 'zidane'\n/** Prefix of the subprotocol entry carrying the bearer token. */\nexport const WS_BEARER_PREFIX = 'zidane.bearer.'\n\nexport type WsTokenCarrier = 'header' | 'subprotocol'\n\n/**\n * What an accepted connection is: a `client` (a window: the whole method\n * table, signals) or a `machine` lending its execution (`docs/MACHINES.md`:\n * only `ipc.hello`, `$/ping`, `machine.register`, never a peer). Default `client`.\n */\nexport type WsConnectionScope = 'client' | 'machine'\n\n/**\n * A server's answer to an upgrade's token. Accepted: `principal` names what\n * authenticated (a token id), so connections can be dropped by it later, and\n * `grant` is a client connection's reach (`../scopes`; absent: everything).\n * Refused: the HTTP status, sent before any JSON-RPC (401 no valid\n * credential, 403 a credential not allowed here).\n */\nexport type WsAuthVerdict\n = | { ok: true, principal?: string, scope?: WsConnectionScope, grant?: ClientScope }\n | { ok: false, status: 401 | 403, reason?: WsRefusalReason }\n\n/**\n * Why a server refused an upgrade with a 403, as a machine-readable code in\n * {@link WS_REFUSAL_HEADER}. Clients show a fixed text per code (never the\n * response body, which a proxy may fill with anything, the request's own\n * headers included) and ignore codes they don't know.\n */\nexport const WS_REFUSAL_HEADER = 'X-Zidane-Refusal'\nconst WS_REFUSAL_REASONS = ['origin', 'insecure-transport', 'untrusted-proxy', 'scope'] as const\nexport type WsRefusalReason = typeof WS_REFUSAL_REASONS[number]\n\nexport function isWsRefusalReason(value: unknown): value is WsRefusalReason {\n return typeof value === 'string' && (WS_REFUSAL_REASONS as readonly string[]).includes(value)\n}\n\n/** Subprotocols offered in `Sec-WebSocket-Protocol`. */\nexport function offeredSubprotocols(request: Request): string[] {\n return (request.headers.get('sec-websocket-protocol') ?? '').split(',').map(p => p.trim()).filter(Boolean)\n}\n\n/** The client's token: `Authorization: Bearer`, else the subprotocol entry. */\nexport function requestToken(request: Request): string | undefined {\n const auth = request.headers.get('authorization')\n const bearer = auth && /^Bearer\\s+(\\S+)$/i.exec(auth.trim())\n if (bearer)\n return bearer[1]\n const entry = offeredSubprotocols(request).find(p => p.startsWith(WS_BEARER_PREFIX))\n return entry ? entry.slice(WS_BEARER_PREFIX.length) : undefined\n}\n","/**\n * `IpcClient` over a WebSocket (a remote `zidane-server`, `./ws-server`):\n * one JSON-RPC message per text frame, the same handshake, deadlines and\n * signal delivery as the unix-socket client (`./client-core`).\n *\n * Uses the runtime's global `WebSocket` (Bun; Node >= 22), so it is safe in\n * the Node-imported `zidane/ipc` barrel. Unlike a local daemon client it\n * never asks the host to drain on a version mismatch (a remote server's\n * lifetime is not a client's to end) and opts out of the dev build fence.\n *\n * Opening is bounded (`openTimeoutMs`) and abortable (`signal`, up to the\n * end of the handshake). A refused upgrade is opaque to a WebSocket (no\n * status, just \"expected 101\", close 1002), so on failure the client asks\n * the same URL over plain HTTP, with the same token, why: a 401 or 403\n * becomes a {@link HostAuthError}, a 429 a {@link HostBusyError}, each with a\n * fixed message (the response body\n * is never read: a proxy may echo the request's headers, the token\n * included, and the message reaches a GUI renderer). That request never\n * follows a redirect: a 3xx is reported as a misconfigured URL, and the\n * token goes nowhere but the URL's own origin.\n *\n * Messages name the URL by scheme, host and path only (`displayHostUrl`).\n *\n * Certificates: the runtime's roots and the OS store (`./tls-trust`). Under\n * Bun the bundle goes with each socket and refusal probe; under Node the\n * process default applies (the desktop app sets it).\n */\nimport type { IpcClient } from './client-core'\nimport type { WsRefusalReason, WsTokenCarrier } from './ws-auth'\nimport { createJsonRpcEndpoint, errorResponse, successResponse } from '../../acp/json-rpc'\nimport { HostIdentityError, METHOD_NOT_FOUND } from '../../chat/hosts/connection'\nimport { displayHostUrl } from '../../chat/hosts/url'\nimport { hostRefOf } from '../protocol'\nimport { createSignalListeners, openIpcClient } from './client-core'\nimport { hostCaBundle } from './tls-trust'\nimport { isWsRefusalReason, WS_BEARER_PREFIX, WS_REFUSAL_HEADER, WS_SUBPROTOCOL } from './ws-auth'\n\n/** Options for {@link connectWsClient}. */\nexport interface WsClientOptions {\n /** `ws://` or `wss://` URL of the server. */\n url: string\n /** Bearer token for the server, see `./ws-auth`. */\n token?: string\n /**\n * How the token travels. Default: the `Authorization` header where the\n * runtime's WebSocket can set one (Bun), else the subprotocol fallback.\n */\n tokenCarrier?: WsTokenCarrier\n /** Client zidane version, surfaced in the host's diagnostics. */\n appVersion?: string\n /**\n * Certificate authorities (PEM) a `wss://` server's certificate may chain\n * to. Default: the runtime's roots and the OS store (`hostCaBundle`). Bun\n * only: under Node the process default applies.\n */\n ca?: readonly string[]\n /** The connection dropped (server exit, network error, a missed deadline or heartbeat). Not called for `close()`. */\n onClose?: () => void\n /** `$/ping` interval (`./client-core`). Default {@link WS_HEARTBEAT_MS}; `0` disables. */\n heartbeatMs?: number\n /** Bound on the upgrade (not the handshake, which has its own). Default {@link WS_OPEN_TIMEOUT_MS}. */\n openTimeoutMs?: number\n /** Abandon the connect (upgrade and handshake): it rejects with the signal's reason. */\n signal?: AbortSignal\n /**\n * The host id a saved host answered with when it was added: a hello with\n * any other id closes the connection and rejects with a\n * {@link HostIdentityError} (nothing is read from that host).\n */\n expectHostId?: string\n /**\n * Answer the host's requests and notifications on this connection: a\n * machine serving its host (`docs/MACHINES.md`). A throw becomes a\n * JSON-RPC error (its `code` when it carries one). Default: a client\n * refuses requests and reads only `ipc.signal`.\n */\n serve?: {\n request: (method: string, params: unknown) => Promise<unknown>\n notification?: (method: string, params: unknown) => void\n }\n}\n\n/** Heartbeat interval on both ends of a WebSocket by default. */\nexport const WS_HEARTBEAT_MS = 20_000\n/** How long an upgrade may take by default. */\nconst WS_OPEN_TIMEOUT_MS = 15_000\n\nconst FORBIDDEN: Record<WsRefusalReason, string> = {\n 'origin': 'this client\\'s origin is not allowed by the server (allowedOrigins)',\n 'insecure-transport': 'the server only accepts connections through its HTTPS proxy',\n 'untrusted-proxy': 'the server only accepts connections from its trusted proxies',\n 'scope': 'this token\\'s scope cannot open a client connection',\n}\n\n/**\n * The server refused this client's credential: 401 (no valid token) or 403\n * (not allowed here). `reason` only when the server sent a code clients know.\n */\nexport class HostAuthError extends Error {\n /** The server URL, scheme, host and path only. */\n readonly url: string\n /**\n * @param url - The server URL.\n * @param status - HTTP status of the refusal.\n * @param reason - Refusal code the server sent, when any.\n */\n constructor(url: string, readonly status: 401 | 403, readonly reason?: WsRefusalReason) {\n const shown = displayHostUrl(url)\n super(`WebSocket connection to ${shown} failed: ${status === 401\n ? 'token refused (401): the server does not know this token, or it was revoked. Create a new one on the server (zidane server token create --name <device>) and use it here'\n : `forbidden (403): ${reason ? FORBIDDEN[reason] : 'refused by the server or a proxy in front of it (origin, token scope or proxy rules)'}`}.`)\n this.name = 'HostAuthError'\n this.url = shown\n }\n}\n\n/** The server turned the upgrade down with a 429: too many open connections (per token, per address) or upgrades (per address). Transient. */\nexport class HostBusyError extends Error {\n /** @param url - The server URL. */\n constructor(url: string) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: too many connections or connection attempts (429). The server caps open connections per token and per address: close other windows that use this token, or wait a few seconds.`)\n this.name = 'HostBusyError'\n }\n}\n\n/** The URL answered with a redirect: not followed (the token would go along). */\nexport class HostRedirectError extends Error {\n constructor(url: string, status: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: the server redirects (${status}); not following it with the token. Check the URL (scheme, host, path) or the proxy in front of the server.`)\n this.name = 'HostRedirectError'\n }\n}\n\n/** Bun's WebSocket and fetch take handshake headers and TLS options; the WHATWG ones (Node, browsers) do not. */\nconst isBun = (): boolean => typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n\n/** Under Bun, the CAs to pass along for a `wss:` / `https:` URL; `null`: the runtime's default. */\nfunction bunCa(options: WsClientOptions): readonly string[] | null {\n return isBun() && /^(?:wss|https):/i.test(options.url) ? options.ca ?? hostCaBundle() : null\n}\n\nfunction createSocket(options: WsClientOptions): WebSocket {\n const protocols = [WS_SUBPROTOCOL]\n const carrier = options.tokenCarrier ?? (isBun() ? 'header' : 'subprotocol')\n if (options.token && carrier === 'subprotocol')\n protocols.push(`${WS_BEARER_PREFIX}${options.token}`)\n const headers = options.token && carrier === 'header' ? { Authorization: `Bearer ${options.token}` } : null\n const ca = bunCa(options)\n if (headers || ca) {\n // Bun's constructor extension: `{ headers, protocols, tls }` in place of the protocol list.\n const BunWebSocket = WebSocket as unknown as new (url: string, init: { headers?: Record<string, string>, protocols: string[], tls?: { ca: readonly string[] } }) => WebSocket\n return new BunWebSocket(options.url, { ...(headers ? { headers } : {}), protocols, ...(ca ? { tls: { ca } } : {}) })\n }\n return new WebSocket(options.url, protocols)\n}\n\n/** The upgrade took longer than `openTimeoutMs`: nothing answered, so there is no refusal to ask about. */\nclass WsOpenTimeoutError extends Error {\n constructor(url: string, timeoutMs: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} timed out after ${timeoutMs} ms.`)\n this.name = 'WsOpenTimeoutError'\n }\n}\n\nfunction abortError(signal: AbortSignal): Error {\n return signal.reason instanceof Error ? signal.reason : new DOMException('The connect was aborted.', 'AbortError')\n}\n\n/** Resolves on `open`; rejects on failure, timeout or abort (closing the socket). */\nfunction opened(ws: WebSocket, url: string, timeoutMs: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n const done = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const settle = (err?: Error): void => {\n if (done.signal.aborted)\n return\n done.abort()\n clearTimeout(timer)\n if (!err)\n return resolve()\n ws.close()\n reject(err)\n }\n const fail = (detail: string) => () => settle(new Error(`WebSocket connection to ${displayHostUrl(url)} failed${detail}.`))\n ws.addEventListener('open', () => settle(), { signal: done.signal })\n ws.addEventListener('error', fail(''), { signal: done.signal })\n ws.addEventListener('close', event => fail(` (close ${event.code}${event.reason ? `: ${event.reason}` : ''})`)(), { signal: done.signal })\n signal?.addEventListener('abort', () => settle(abortError(signal)), { signal: done.signal })\n timer = setTimeout(() => settle(new WsOpenTimeoutError(url, timeoutMs)), timeoutMs)\n })\n}\n\n/** Why an upgrade failed, asked over plain HTTP: a {@link HostAuthError} for 401 / 403, a {@link HostBusyError} for 429, a {@link HostRedirectError} for 3xx, else `null`. */\nasync function refusal(options: WsClientOptions): Promise<Error | null> {\n try {\n const url = new URL(options.url)\n url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'\n const timeout = AbortSignal.timeout(5000)\n const ca = bunCa(options)\n const response = await fetch(url, {\n headers: options.token ? { Authorization: `Bearer ${options.token}` } : {},\n redirect: 'manual',\n signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,\n // Bun's fetch extension, as for the socket.\n ...(ca ? { tls: { ca } } : {}),\n } as RequestInit)\n void response.body?.cancel().catch(() => {})\n if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400))\n return new HostRedirectError(options.url, response.status)\n if (response.status === 429)\n return new HostBusyError(options.url)\n if (response.status !== 401 && response.status !== 403)\n return null\n const reason = response.headers.get(WS_REFUSAL_HEADER)\n return new HostAuthError(options.url, response.status, response.status === 403 && isWsRefusalReason(reason) ? reason : undefined)\n }\n catch {\n return null\n }\n}\n\n/** Close a connection whose host is not the one expected, and say so. */\nfunction checkIdentity(client: IpcClient, options: WsClientOptions): IpcClient {\n if (options.expectHostId === undefined)\n return client\n const ref = hostRefOf(client.hello)\n if (ref?.id === options.expectHostId)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(options.url), ref?.name)\n}\n\n/**\n * Connects to a remote zidane server over WebSocket and completes the `ipc.hello` handshake.\n * A refused upgrade rejects with {@link HostAuthError} for a 401 or 403, and {@link HostBusyError} for a 429. A hello from another host than `expectHostId` rejects with `HostIdentityError`. A version mismatch rejects with {@link IpcVersionMismatchError} and leaves the server running.\n * @param options - Server URL, token and connection settings.\n * @returns A typed client.\n * @example\n * ```ts\n * import { connectWsClient } from 'zidane/ipc/remote'\n *\n * const client = await connectWsClient({\n * url: 'wss://zidane.example.com/',\n * token: process.env.ZIDANE_HOST_TOKEN,\n * })\n * const sessions = await client.request('sessions.list', {})\n * console.log(sessions.length)\n * client.close()\n * ```\n */\nexport async function connectWsClient(options: WsClientOptions): Promise<IpcClient> {\n const { signal } = options\n signal?.throwIfAborted()\n const ws = createSocket(options)\n ws.binaryType = 'arraybuffer'\n try {\n await opened(ws, options.url, options.openTimeoutMs ?? WS_OPEN_TIMEOUT_MS, signal)\n }\n catch (err) {\n if (signal?.aborted || err instanceof WsOpenTimeoutError)\n throw err\n throw (await refusal(options)) ?? err\n }\n\n const signals = createSignalListeners()\n let closed = false\n\n const rpc = createJsonRpcEndpoint({\n send: (json) => {\n try {\n ws.send(json)\n }\n catch {\n // A closing socket: the close handler fails what is pending.\n }\n },\n // The host never sends requests to clients, only notifications; a machine serves them.\n onRequest: async (message) => {\n const serve = options.serve\n if (!serve)\n return errorResponse(message.id, METHOD_NOT_FOUND, 'Clients do not accept requests.')\n try {\n return successResponse(message.id, (await serve.request(message.method, message.params)) ?? null)\n }\n catch (err) {\n const code = (err as { code?: unknown }).code\n return errorResponse(message.id, typeof code === 'number' ? code : -32000, err instanceof Error ? err.message : String(err))\n }\n },\n onNotification: (message) => {\n if (message.method === 'ipc.signal' || !options.serve?.notification)\n return signals.onNotification(message)\n options.serve.notification(message.method, (message as { params?: unknown }).params)\n },\n })\n\n const decoder = new TextDecoder()\n ws.addEventListener('message', (event: MessageEvent) => {\n if (closed)\n return\n rpc.receive(typeof event.data === 'string' ? event.data : decoder.decode(event.data as ArrayBuffer))\n })\n\n /** The host went away (or the connection was given up): fail what is pending, tell the owner. */\n const lost = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n options.onClose?.()\n }\n ws.addEventListener('close', lost)\n ws.addEventListener('error', () => {\n // 'close' follows.\n })\n\n const close = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n ws.close(1000)\n }\n\n // Aborted mid-handshake: the close fails the pending hello, and the connect rejects with the signal's reason.\n const onAbort = (): void => close()\n signal?.addEventListener('abort', onAbort, { once: true })\n try {\n return checkIdentity(await openIpcClient(\n {\n rpc,\n close,\n abort: () => {\n lost()\n ws.close(1000)\n },\n where: displayHostUrl(options.url),\n },\n signals.listeners,\n {\n ...(options.appVersion ? { appVersion: options.appVersion } : {}),\n drain: 'never',\n buildFence: false,\n heartbeatMs: options.heartbeatMs ?? WS_HEARTBEAT_MS,\n },\n ), options)\n }\n catch (err) {\n throw signal?.aborted ? abortError(signal) : err\n }\n finally {\n signal?.removeEventListener('abort', onAbort)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,MAAM;AAKZ,SAAS,aAAa,MAAwB;CAC5C,IAAI;EACF,OAAO,IAAI,oBAAoB,IAAI,KAAK,CAAC;CAC3C,QACM;EACJ,OAAO,CAAC;CACV;AACF;AAEA,IAAI;;;;;;AAOJ,SAAgB,eAAgC;CAC9C,IAAI,WAAW,KAAA,GAAW;EACxB,MAAM,SAAS,aAAa,QAAQ;EACpC,SAAS,OAAO,WAAW,IAAI,OAAO,CAAC,mBAAG,IAAI,IAAI;GAAC,GAAG,aAAa,SAAS;GAAG,GAAG;GAAQ,GAAG,aAAa,OAAO;EAAC,CAAC,CAAC;CACtH;CACA,OAAO;AACT;;;;;AAMA,SAAgB,0BAAmC;CACjD,MAAM,KAAK,aAAa;CACxB,IAAI,CAAC,MAAM,CAAC,IAAI,4BAA4B,OAAQ,WAAiC,QAAQ,aAC3F,OAAO;CACT,IAAI,yBAAyB,EAAE;CAC/B,OAAO;AACT;;;;AC1CA,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;;;;;;AA4BhC,MAAa,oBAAoB;AACjC,MAAM,qBAAqB;CAAC;CAAU;CAAsB;CAAmB;AAAO;AAGtF,SAAgB,kBAAkB,OAA0C;CAC1E,OAAO,OAAO,UAAU,YAAa,mBAAyC,SA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,aAAmB;EACvB,IAAI,QACF;EACF,SAAS;EACT,IAAI,MAAM;EACV,QAAQ,UAAU;CACpB;CACA,GAAG,iBAAiB,SAAS,IAAI;CACjC,GAAG,iBAAiB,eAAe,CAEnC,CAAC;CAED,MAAM,cAAoB;EACxB,IAAI,QACF;EACF,SAAS;EACT,IAAI,MAAM;EACV,GAAG,MAAM,GAAI;CACf;CAGA,MAAM,gBAAsB,MAAM;CAClC,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CACzD,IAAI;EACF,OAAO,cAAc,MAAM,cACzB;GACE;GACA;GACA,aAAa;IACX,KAAK;IACL,GAAG,MAAM,GAAI;GACf;GACA,OAAO,eAAe,QAAQ,GAAG;EACnC,GACA,QAAQ,WACR;GACE,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;GAC/D,OAAO;GACP,YAAY;GACZ,aAAa,QAAQ,eAAA;EACvB,CACF,GAAG,OAAO;CACZ,SACO,KAAK;EACV,MAAM,QAAQ,UAAU,WAAW,MAAM,IAAI;CAC/C,UACQ;EACN,QAAQ,oBAAoB,SAAS,OAAO;CAC9C;AACF"}
|
|
1
|
+
{"version":3,"file":"ws-client-CsAtVY0b.js","names":["BunWebSocket"],"sources":["../src/ipc/transports/tls-trust.ts","../src/ipc/transports/ws-auth.ts","../src/ipc/transports/ws-client.ts"],"sourcesContent":["/**\n * Which certificate authorities a client trusts for a remote zidane-server:\n * the runtime's own roots plus the operating system's store (the macOS\n * keychain, the Linux CA bundle). A server behind a private CA, an mkcert\n * certificate or a self-signed one the user trusted in the OS then works\n * like a public one. `NODE_EXTRA_CA_CERTS` adds certificates at launch, in\n * both runtimes.\n *\n * Bun's WebSocket and fetch ignore `tls.setDefaultCACertificates`, so Bun\n * clients (the TUI, `zidane machine share`) pass the bundle with each\n * connection (`hostCaBundle`). Node honors it, so the desktop app's main\n * process trusts the store once, when it turns remote hosts on\n * (`trustSystemCertificates`).\n */\nimport tls from 'node:tls'\n\ntype CaKind = 'default' | 'system' | 'extra'\nconst api = tls as unknown as {\n getCACertificates?: (kind: CaKind) => string[]\n setDefaultCACertificates?: (certs: readonly string[]) => void\n}\n\nfunction certificates(kind: CaKind): string[] {\n try {\n return api.getCACertificates?.(kind) ?? []\n }\n catch {\n return []\n }\n}\n\nlet bundle: string[] | null | undefined\n\n/**\n * The runtime's roots, the OS store's and `NODE_EXTRA_CA_CERTS`'s, read once.\n * `null` when the OS store adds nothing (or can't be read): the runtime's\n * default then applies as it is.\n */\nexport function hostCaBundle(): string[] | null {\n if (bundle === undefined) {\n const system = certificates('system')\n bundle = system.length === 0 ? null : [...new Set([...certificates('default'), ...system, ...certificates('extra')])]\n }\n return bundle\n}\n\n/**\n * Node: every TLS client of this process trusts {@link hostCaBundle} from now\n * on (the desktop app's main process). Whether it applied.\n */\nexport function trustSystemCertificates(): boolean {\n const ca = hostCaBundle()\n if (!ca || !api.setDefaultCACertificates || typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined')\n return false\n api.setDefaultCACertificates(ca)\n return true\n}\n","/**\n * How a WebSocket client's token reaches the server, shared by both ends.\n *\n * Preferred: `Authorization: Bearer <token>` (Bun's WebSocket can set it).\n * Fallback for clients that can't set handshake headers (Node's and the\n * browser's WebSocket): a `zidane.bearer.<token>` entry in\n * `Sec-WebSocket-Protocol`, offered next to `zidane`, the subprotocol the\n * server selects. A token sent this way must be a valid subprotocol token\n * (base64url is).\n */\n\nimport type { ClientScope } from '../scopes'\n\n/** The subprotocol clients offer and the server selects. */\nexport const WS_SUBPROTOCOL = 'zidane'\n/** Prefix of the subprotocol entry carrying the bearer token. */\nexport const WS_BEARER_PREFIX = 'zidane.bearer.'\n\nexport type WsTokenCarrier = 'header' | 'subprotocol'\n\n/**\n * What an accepted connection is: a `client` (a window: the whole method\n * table, signals) or a `machine` lending its execution (`docs/MACHINES.md`:\n * only `ipc.hello`, `$/ping`, `machine.register`, never a peer). Default `client`.\n */\nexport type WsConnectionScope = 'client' | 'machine'\n\n/**\n * A server's answer to an upgrade's token. Accepted: `principal` names what\n * authenticated (a token id), so connections can be dropped by it later, and\n * `grant` is a client connection's reach (`../scopes`; absent: everything).\n * Refused: the HTTP status, sent before any JSON-RPC (401 no valid\n * credential, 403 a credential not allowed here).\n */\nexport type WsAuthVerdict\n = | { ok: true, principal?: string, scope?: WsConnectionScope, grant?: ClientScope }\n | { ok: false, status: 401 | 403, reason?: WsRefusalReason }\n\n/**\n * Why a server refused an upgrade with a 403, as a machine-readable code in\n * {@link WS_REFUSAL_HEADER}. Clients show a fixed text per code (never the\n * response body, which a proxy may fill with anything, the request's own\n * headers included) and ignore codes they don't know.\n */\nexport const WS_REFUSAL_HEADER = 'X-Zidane-Refusal'\nconst WS_REFUSAL_REASONS = ['origin', 'insecure-transport', 'untrusted-proxy', 'scope'] as const\nexport type WsRefusalReason = typeof WS_REFUSAL_REASONS[number]\n\nexport function isWsRefusalReason(value: unknown): value is WsRefusalReason {\n return typeof value === 'string' && (WS_REFUSAL_REASONS as readonly string[]).includes(value)\n}\n\n/** Subprotocols offered in `Sec-WebSocket-Protocol`. */\nexport function offeredSubprotocols(request: Request): string[] {\n return (request.headers.get('sec-websocket-protocol') ?? '').split(',').map(p => p.trim()).filter(Boolean)\n}\n\n/** The client's token: `Authorization: Bearer`, else the subprotocol entry. */\nexport function requestToken(request: Request): string | undefined {\n const auth = request.headers.get('authorization')\n const bearer = auth && /^Bearer\\s+(\\S+)$/i.exec(auth.trim())\n if (bearer)\n return bearer[1]\n const entry = offeredSubprotocols(request).find(p => p.startsWith(WS_BEARER_PREFIX))\n return entry ? entry.slice(WS_BEARER_PREFIX.length) : undefined\n}\n","/**\n * `IpcClient` over a WebSocket (a remote `zidane-server`, `./ws-server`):\n * one JSON-RPC message per text frame, the same handshake, deadlines and\n * signal delivery as the unix-socket client (`./client-core`).\n *\n * Uses the runtime's global `WebSocket` (Bun; Node >= 22), so it is safe in\n * the Node-imported `zidane/ipc` barrel. Unlike a local daemon client it\n * never asks the host to drain on a version mismatch (a remote server's\n * lifetime is not a client's to end) and opts out of the dev build fence.\n *\n * Opening is bounded (`openTimeoutMs`) and abortable (`signal`, up to the\n * end of the handshake). A refused upgrade is opaque to a WebSocket (no\n * status, just \"expected 101\", close 1002), so on failure the client asks\n * the same URL over plain HTTP, with the same token, why: a 401 or 403\n * becomes a {@link HostAuthError}, a 429 a {@link HostBusyError}, each with a\n * fixed message (the response body\n * is never read: a proxy may echo the request's headers, the token\n * included, and the message reaches a GUI renderer). That request never\n * follows a redirect: a 3xx is reported as a misconfigured URL, and the\n * token goes nowhere but the URL's own origin.\n *\n * Messages name the URL by scheme, host and path only (`displayHostUrl`).\n *\n * Certificates: the runtime's roots and the OS store (`./tls-trust`). Under\n * Bun the bundle goes with each socket and refusal probe; under Node the\n * process default applies (the desktop app sets it).\n */\nimport type { IpcClient } from './client-core'\nimport type { WsRefusalReason, WsTokenCarrier } from './ws-auth'\nimport { createJsonRpcEndpoint, errorResponse, successResponse } from '../../acp/json-rpc'\nimport { HostIdentityError, METHOD_NOT_FOUND } from '../../chat/hosts/connection'\nimport { displayHostUrl } from '../../chat/hosts/url'\nimport { hostRefOf } from '../protocol'\nimport { createSignalListeners, openIpcClient } from './client-core'\nimport { hostCaBundle } from './tls-trust'\nimport { isWsRefusalReason, WS_BEARER_PREFIX, WS_REFUSAL_HEADER, WS_SUBPROTOCOL } from './ws-auth'\n\n/** Options for {@link connectWsClient}. */\nexport interface WsClientOptions {\n /** `ws://` or `wss://` URL of the server. */\n url: string\n /** Bearer token for the server, see `./ws-auth`. */\n token?: string\n /**\n * How the token travels. Default: the `Authorization` header where the\n * runtime's WebSocket can set one (Bun), else the subprotocol fallback.\n */\n tokenCarrier?: WsTokenCarrier\n /** Client zidane version, surfaced in the host's diagnostics. */\n appVersion?: string\n /**\n * Certificate authorities (PEM) a `wss://` server's certificate may chain\n * to. Default: the runtime's roots and the OS store (`hostCaBundle`). Bun\n * only: under Node the process default applies.\n */\n ca?: readonly string[]\n /** The connection dropped (server exit, network error, a missed deadline or heartbeat). Not called for `close()`. */\n onClose?: () => void\n /** `$/ping` interval (`./client-core`). Default {@link WS_HEARTBEAT_MS}; `0` disables. */\n heartbeatMs?: number\n /** Bound on the upgrade (not the handshake, which has its own). Default {@link WS_OPEN_TIMEOUT_MS}. */\n openTimeoutMs?: number\n /** Abandon the connect (upgrade and handshake): it rejects with the signal's reason. */\n signal?: AbortSignal\n /**\n * The host id a saved host answered with when it was added: a hello with\n * any other id closes the connection and rejects with a\n * {@link HostIdentityError} (nothing is read from that host).\n */\n expectHostId?: string\n /**\n * Answer the host's requests and notifications on this connection: a\n * machine serving its host (`docs/MACHINES.md`). A throw becomes a\n * JSON-RPC error (its `code` when it carries one). Default: a client\n * refuses requests and reads only `ipc.signal`.\n */\n serve?: {\n request: (method: string, params: unknown) => Promise<unknown>\n notification?: (method: string, params: unknown) => void\n }\n}\n\n/** Heartbeat interval on both ends of a WebSocket by default. */\nexport const WS_HEARTBEAT_MS = 20_000\n/** How long an upgrade may take by default. */\nconst WS_OPEN_TIMEOUT_MS = 15_000\n\nconst FORBIDDEN: Record<WsRefusalReason, string> = {\n 'origin': 'this client\\'s origin is not allowed by the server (allowedOrigins)',\n 'insecure-transport': 'the server only accepts connections through its HTTPS proxy',\n 'untrusted-proxy': 'the server only accepts connections from its trusted proxies',\n 'scope': 'this token\\'s scope cannot open a client connection',\n}\n\n/**\n * The server refused this client's credential: 401 (no valid token) or 403\n * (not allowed here). `reason` only when the server sent a code clients know.\n */\nexport class HostAuthError extends Error {\n /** The server URL, scheme, host and path only. */\n readonly url: string\n /**\n * @param url - The server URL.\n * @param status - HTTP status of the refusal.\n * @param reason - Refusal code the server sent, when any.\n */\n constructor(url: string, readonly status: 401 | 403, readonly reason?: WsRefusalReason) {\n const shown = displayHostUrl(url)\n super(`WebSocket connection to ${shown} failed: ${status === 401\n ? 'token refused (401): the server does not know this token, or it was revoked. Create a new one on the server (zidane server token create --name <device>) and use it here'\n : `forbidden (403): ${reason ? FORBIDDEN[reason] : 'refused by the server or a proxy in front of it (origin, token scope or proxy rules)'}`}.`)\n this.name = 'HostAuthError'\n this.url = shown\n }\n}\n\n/** The server turned the upgrade down with a 429: too many open connections (per token, per address) or upgrades (per address). Transient. */\nexport class HostBusyError extends Error {\n /** @param url - The server URL. */\n constructor(url: string) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: too many connections or connection attempts (429). The server caps open connections per token and per address: close other windows that use this token, or wait a few seconds.`)\n this.name = 'HostBusyError'\n }\n}\n\n/** The URL answered with a redirect: not followed (the token would go along). */\nexport class HostRedirectError extends Error {\n constructor(url: string, status: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: the server redirects (${status}); not following it with the token. Check the URL (scheme, host, path) or the proxy in front of the server.`)\n this.name = 'HostRedirectError'\n }\n}\n\n/** Bun's WebSocket and fetch take handshake headers and TLS options; the WHATWG ones (Node, browsers) do not. */\nconst isBun = (): boolean => typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n\n/** Under Bun, the CAs to pass along for a `wss:` / `https:` URL; `null`: the runtime's default. */\nfunction bunCa(options: WsClientOptions): readonly string[] | null {\n return isBun() && /^(?:wss|https):/i.test(options.url) ? options.ca ?? hostCaBundle() : null\n}\n\nfunction createSocket(options: WsClientOptions): WebSocket {\n const protocols = [WS_SUBPROTOCOL]\n const carrier = options.tokenCarrier ?? (isBun() ? 'header' : 'subprotocol')\n if (options.token && carrier === 'subprotocol')\n protocols.push(`${WS_BEARER_PREFIX}${options.token}`)\n const headers = options.token && carrier === 'header' ? { Authorization: `Bearer ${options.token}` } : null\n const ca = bunCa(options)\n if (headers || ca) {\n // Bun's constructor extension: `{ headers, protocols, tls }` in place of the protocol list.\n const BunWebSocket = WebSocket as unknown as new (url: string, init: { headers?: Record<string, string>, protocols: string[], tls?: { ca: readonly string[] } }) => WebSocket\n return new BunWebSocket(options.url, { ...(headers ? { headers } : {}), protocols, ...(ca ? { tls: { ca } } : {}) })\n }\n return new WebSocket(options.url, protocols)\n}\n\n/** The upgrade took longer than `openTimeoutMs`: nothing answered, so there is no refusal to ask about. */\nclass WsOpenTimeoutError extends Error {\n constructor(url: string, timeoutMs: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} timed out after ${timeoutMs} ms.`)\n this.name = 'WsOpenTimeoutError'\n }\n}\n\nfunction abortError(signal: AbortSignal): Error {\n return signal.reason instanceof Error ? signal.reason : new DOMException('The connect was aborted.', 'AbortError')\n}\n\n/** Resolves on `open`; rejects on failure, timeout or abort (closing the socket). */\nfunction opened(ws: WebSocket, url: string, timeoutMs: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n const done = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const settle = (err?: Error): void => {\n if (done.signal.aborted)\n return\n done.abort()\n clearTimeout(timer)\n if (!err)\n return resolve()\n ws.close()\n reject(err)\n }\n const fail = (detail: string) => () => settle(new Error(`WebSocket connection to ${displayHostUrl(url)} failed${detail}.`))\n ws.addEventListener('open', () => settle(), { signal: done.signal })\n ws.addEventListener('error', fail(''), { signal: done.signal })\n ws.addEventListener('close', event => fail(` (close ${event.code}${event.reason ? `: ${event.reason}` : ''})`)(), { signal: done.signal })\n signal?.addEventListener('abort', () => settle(abortError(signal)), { signal: done.signal })\n timer = setTimeout(() => settle(new WsOpenTimeoutError(url, timeoutMs)), timeoutMs)\n })\n}\n\n/** Why an upgrade failed, asked over plain HTTP: a {@link HostAuthError} for 401 / 403, a {@link HostBusyError} for 429, a {@link HostRedirectError} for 3xx, else `null`. */\nasync function refusal(options: WsClientOptions): Promise<Error | null> {\n try {\n const url = new URL(options.url)\n url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'\n const timeout = AbortSignal.timeout(5000)\n const ca = bunCa(options)\n const response = await fetch(url, {\n headers: options.token ? { Authorization: `Bearer ${options.token}` } : {},\n redirect: 'manual',\n signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,\n // Bun's fetch extension, as for the socket.\n ...(ca ? { tls: { ca } } : {}),\n } as RequestInit)\n void response.body?.cancel().catch(() => {})\n if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400))\n return new HostRedirectError(options.url, response.status)\n if (response.status === 429)\n return new HostBusyError(options.url)\n if (response.status !== 401 && response.status !== 403)\n return null\n const reason = response.headers.get(WS_REFUSAL_HEADER)\n return new HostAuthError(options.url, response.status, response.status === 403 && isWsRefusalReason(reason) ? reason : undefined)\n }\n catch {\n return null\n }\n}\n\n/** Close a connection whose host is not the one expected, and say so. */\nfunction checkIdentity(client: IpcClient, options: WsClientOptions): IpcClient {\n if (options.expectHostId === undefined)\n return client\n const ref = hostRefOf(client.hello)\n if (ref?.id === options.expectHostId)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(options.url), ref?.name)\n}\n\n/**\n * Connects to a remote zidane server over WebSocket and completes the `ipc.hello` handshake.\n * A refused upgrade rejects with {@link HostAuthError} for a 401 or 403, and {@link HostBusyError} for a 429. A hello from another host than `expectHostId` rejects with `HostIdentityError`. A version mismatch rejects with {@link IpcVersionMismatchError} and leaves the server running.\n * @param options - Server URL, token and connection settings.\n * @returns A typed client.\n * @example\n * ```ts\n * import { connectWsClient } from 'zidane/ipc/remote'\n *\n * const client = await connectWsClient({\n * url: 'wss://zidane.example.com/',\n * token: process.env.ZIDANE_HOST_TOKEN,\n * })\n * const sessions = await client.request('sessions.list', {})\n * console.log(sessions.length)\n * client.close()\n * ```\n */\nexport async function connectWsClient(options: WsClientOptions): Promise<IpcClient> {\n const { signal } = options\n signal?.throwIfAborted()\n const ws = createSocket(options)\n ws.binaryType = 'arraybuffer'\n try {\n await opened(ws, options.url, options.openTimeoutMs ?? WS_OPEN_TIMEOUT_MS, signal)\n }\n catch (err) {\n if (signal?.aborted || err instanceof WsOpenTimeoutError)\n throw err\n throw (await refusal(options)) ?? err\n }\n\n const signals = createSignalListeners()\n let closed = false\n\n const rpc = createJsonRpcEndpoint({\n send: (json) => {\n try {\n ws.send(json)\n }\n catch {\n // A closing socket: the close handler fails what is pending.\n }\n },\n // The host never sends requests to clients, only notifications; a machine serves them.\n onRequest: async (message) => {\n const serve = options.serve\n if (!serve)\n return errorResponse(message.id, METHOD_NOT_FOUND, 'Clients do not accept requests.')\n try {\n return successResponse(message.id, (await serve.request(message.method, message.params)) ?? null)\n }\n catch (err) {\n const code = (err as { code?: unknown }).code\n return errorResponse(message.id, typeof code === 'number' ? code : -32000, err instanceof Error ? err.message : String(err))\n }\n },\n onNotification: (message) => {\n if (message.method === 'ipc.signal' || !options.serve?.notification)\n return signals.onNotification(message)\n options.serve.notification(message.method, (message as { params?: unknown }).params)\n },\n })\n\n const decoder = new TextDecoder()\n ws.addEventListener('message', (event: MessageEvent) => {\n if (closed)\n return\n rpc.receive(typeof event.data === 'string' ? event.data : decoder.decode(event.data as ArrayBuffer))\n })\n\n /** The host went away (or the connection was given up): fail what is pending, tell the owner. */\n const lost = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n options.onClose?.()\n }\n ws.addEventListener('close', lost)\n ws.addEventListener('error', () => {\n // 'close' follows.\n })\n\n const close = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n ws.close(1000)\n }\n\n // Aborted mid-handshake: the close fails the pending hello, and the connect rejects with the signal's reason.\n const onAbort = (): void => close()\n signal?.addEventListener('abort', onAbort, { once: true })\n try {\n return checkIdentity(await openIpcClient(\n {\n rpc,\n close,\n abort: () => {\n lost()\n ws.close(1000)\n },\n where: displayHostUrl(options.url),\n },\n signals.listeners,\n {\n ...(options.appVersion ? { appVersion: options.appVersion } : {}),\n drain: 'never',\n buildFence: false,\n heartbeatMs: options.heartbeatMs ?? WS_HEARTBEAT_MS,\n },\n ), options)\n }\n catch (err) {\n throw signal?.aborted ? abortError(signal) : err\n }\n finally {\n signal?.removeEventListener('abort', onAbort)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,MAAM;AAKZ,SAAS,aAAa,MAA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,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;GAC/D,OAAO;GACP,YAAY;GACZ,aAAa,QAAQ,eAAA;EACvB,CACF,GAAG,OAAO;CACZ,SACO,KAAK;EACV,MAAM,QAAQ,UAAU,WAAW,MAAM,IAAI;CAC/C,UACQ;EACN,QAAQ,oBAAoB,SAAS,OAAO;CAC9C;AACF"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.js";
|
|
2
2
|
import { t as HostIdentityError } from "./connection-BaHd3T-D.js";
|
|
3
|
-
import { i as IpcVersionMismatchError } from "./settings-keys-
|
|
3
|
+
import { i as IpcVersionMismatchError } from "./settings-keys-BP0tJDVS.js";
|
|
4
4
|
import { d as hostRefOf } from "./protocol-DxbYJdHT.js";
|
|
5
5
|
import { t as keepHostConnected } from "./connection-loop-DSCehV3W.js";
|
|
6
6
|
import { n as displayHostUrl } from "./url-znC3tmKE.js";
|
|
7
7
|
import { i as probeUnsavedHost, t as createHostRegistry } from "./registry-DUp97g6d.js";
|
|
8
|
-
import { a as hostCaBundle, r as connectWsClient, t as HostAuthError } from "./ws-client-
|
|
8
|
+
import { a as hostCaBundle, r as connectWsClient, t as HostAuthError } from "./ws-client-CsAtVY0b.js";
|
|
9
9
|
//#region src/ipc/hosts/probe.ts
|
|
10
10
|
/** Bound on one probe: the upgrade, the handshake and `daemon.info`. */
|
|
11
11
|
const HOST_PROBE_TIMEOUT_MS = 1e4;
|
|
@@ -288,4 +288,4 @@ function startWsSavedHosts(options) {
|
|
|
288
288
|
//#endregion
|
|
289
289
|
export { MissingHostTokenError as a, createWsHostRegistry as c, ws_exports as i, probeWsHost as l, probeUnsavedWsHost as n, startSavedHosts as o, startWsSavedHosts as r, HOST_PROBE_TIMEOUT_MS as s, classifyWsFailure as t };
|
|
290
290
|
|
|
291
|
-
//# sourceMappingURL=ws-
|
|
291
|
+
//# sourceMappingURL=ws-ks0slKdL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ws-Bv6QGsEr.js","names":[],"sources":["../src/ipc/hosts/probe.ts","../src/ipc/hosts/saved-hosts.ts","../src/ipc/hosts/ws.ts"],"sourcesContent":["/**\n * The host registry's connection (`src/chat/hosts`): a WebSocket probe that\n * says who answers at a URL with a token, and the registry wired to it.\n */\nimport type { HostErrorCode, HostProbeResult, HostRegistry } from '../../chat/hosts'\nimport { createHostRegistry, displayHostUrl } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { hostCaBundle } from '../transports/tls-trust'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\n\n/** Bound on one probe: the upgrade, the handshake and `daemon.info`. */\nexport const HOST_PROBE_TIMEOUT_MS = 10_000\n\nconst TLS_FAILURE = /certificate|self[- ]signed|\\btls\\b|\\bssl\\b|UNABLE_TO_VERIFY|CERT_|ERR_TLS/i\n\nfunction classify(err: unknown): { error: HostErrorCode, message: string } {\n if (err instanceof HostAuthError) {\n return err.status === 401\n ? { error: 'auth', message: 'The host refused the token (401). Create a new one on the server: zidane server token create --name <device>.' }\n : { error: 'auth', message: err.message }\n }\n if (err instanceof IpcVersionMismatchError)\n return { error: 'protocol', message: err.message }\n const message = err instanceof Error ? err.message : String(err)\n if (TLS_FAILURE.test(message))\n return { error: 'tls', message: `TLS failed: ${message}` }\n return { error: 'unreachable', message }\n}\n\n/**\n * A failed WebSocket says nothing about why. For `wss://`, ask the same\n * address over HTTPS: a certificate or handshake failure there is a TLS\n * problem, anything else stays \"unreachable\".\n */\nasync function tlsFailure(url: string, signal: AbortSignal): Promise<string | null> {\n if (!url.startsWith('wss:'))\n return null\n try {\n // No token, and no redirect followed: only the TLS handshake with this origin matters.\n // The same CAs as the socket (Bun takes them per request; Node uses its process default).\n const ca = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' ? hostCaBundle() : null\n const response = await fetch(`https:${url.slice('wss:'.length)}`, { redirect: 'manual', signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]), ...(ca ? { tls: { ca } } : {}) } as RequestInit)\n void response.body?.cancel().catch(() => {})\n return null\n }\n catch (err) {\n const e = err as { code?: unknown, message?: unknown }\n const detail = `${typeof e.code === 'string' ? e.code : ''} ${typeof e.message === 'string' ? e.message : ''}`\n return TLS_FAILURE.test(detail) ? `TLS failed: ${String(e.message ?? e.code)}` : null\n }\n}\n\n/**\n * Connect, read the host's identity and `daemon.info`, disconnect. Never throws.\n * @param target - URL, token and an optional timeout in milliseconds. The timeout defaults to {@link HOST_PROBE_TIMEOUT_MS}.\n * @returns Who answered and how fast, or a classified failure.\n */\nexport async function probeWsHost(target: { url: string, token: string, timeoutMs?: number }): Promise<HostProbeResult> {\n // The OS certificate store is read once per process, synchronously (seconds on a loaded\n // machine): read it before the deadline starts, or that cost is misread as a host with no answer.\n if (typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' && /^wss:/i.test(target.url))\n hostCaBundle()\n const started = performance.now()\n const signal = AbortSignal.timeout(target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS)\n let client: Awaited<ReturnType<typeof connectWsClient>> | undefined\n try {\n client = await connectWsClient({ url: target.url, token: target.token, heartbeatMs: 0, signal })\n const hostRef = hostRefOf(client.hello)\n if (!hostRef)\n return { ok: false, error: 'protocol', message: `${displayHostUrl(target.url)} runs a zidane too old to say which host it is. Upgrade the server.` }\n const info = await client.request('daemon.info', {})\n const serverVersion = info.codeVersion ?? info.appVersion\n return { ok: true, hostRef, ...(serverVersion ? { serverVersion } : {}), latencyMs: Math.round(performance.now() - started) }\n }\n catch (err) {\n if (signal.aborted && !(err instanceof HostAuthError))\n return { ok: false, error: 'unreachable', message: `No answer from ${displayHostUrl(target.url)} within ${target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS} ms.` }\n const classified = classify(err)\n if (classified.error === 'unreachable') {\n const tls = await tlsFailure(target.url, signal).catch(() => null)\n if (tls)\n return { ok: false, error: 'tls', message: tls }\n }\n return { ok: false, ...classified }\n }\n finally {\n client?.close()\n }\n}\n\n/**\n * The registry in `dataDir`, connecting over WebSocket.\n * @param options - Where the registry keeps its data.\n * @returns The host registry.\n */\nexport function createWsHostRegistry(options: { dataDir: string }): HostRegistry {\n return createHostRegistry({ dataDir: options.dataDir, probe: probeWsHost })\n}\n","/**\n * A client's saved servers, kept in its host directory: one directory entry\n * and one app-lifetime connection (`connection-loop`) per server in the\n * registry, in step with it. Shared by the TUI and the GUI main process,\n * which each supply their directory (`SavedHostsDirectory`) and how to dial.\n *\n * Saving a server that is already saved (same host id: a new token, a new\n * URL) reconfigures its entry IN PLACE and reconnects: the entry is never\n * removed, so the sessions routed to it stay routed. Only a server leaving\n * the registry (removed here or by another window) or `stop()` removes an\n * entry, and the directory decides what that means for an open session.\n *\n * Every connection is checked against the saved entry's id (the server's\n * `hostId` when it was added): another host answering at the URL is closed\n * at once, reported as `identity` and not retried, so nothing it says is\n * recorded under the saved id. Dialers may check first (`expectHostId`).\n *\n * No WebSocket import: the WebSocket wiring is `./ws.ts`.\n */\nimport type { HostEntry, HostProbeResult, HostRegistry, HostTestResult } from '../../chat/hosts'\nimport type { HostSignal } from '../protocol'\nimport type { IpcClient } from '../transports/client-core'\nimport type { HostConnectionLoop, HostConnectionPatch, HostFailureKind } from './connection-loop'\nimport { displayHostUrl, HostIdentityError } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { keepHostConnected } from './connection-loop'\n\n/** The client's host directory, as the saved servers see it. Keys are host ids. */\nexport interface SavedHostsDirectory {\n /** The saved servers it holds now, with their URL (a `--host` server excluded). */\n saved: () => { key: string, url: string }[]\n /** Add the entry, or reconfigure the one under its key in place (status `connecting`). */\n upsert: (entry: HostEntry, token: string | undefined) => void\n /** Applies a connection patch, a new name or a server version to the entry. */\n update: (key: string, patch: HostConnectionPatch & { name?: string, serverVersion?: string }) => void\n /** The server left the registry, or the saved servers stopped. */\n remove: (key: string) => void\n}\n\n/** No token is saved for this server (removed by hand, or another window removed it). */\nexport class MissingHostTokenError extends Error {\n constructor() {\n super('No token saved for this server: add it again.')\n this.name = 'MissingHostTokenError'\n }\n}\n\n/** Options for {@link startSavedHosts}: the registry, the host directory, the connect function and callbacks. */\nexport interface SavedHostsOptions {\n /** The registry of saved servers. */\n registry: HostRegistry\n /** The client's host directory the entries are kept in. */\n directory: SavedHostsDirectory\n /** One connect attempt to a saved server, with its token read fresh. */\n connect: (entry: HostEntry, token: string, options: { signal: AbortSignal, onClose: () => void }) => Promise<IpcClient>\n /** `auth`: refused for good. A missing token is always `auth`, another host answering always `identity`. */\n classify?: (err: unknown) => HostFailureKind\n /** The add form's test of an unsaved URL + token (`probeUnsavedHost`). */\n probeUnsaved?: (target: { url: string, token: string }) => Promise<HostProbeResult>\n /** Saved entries the directory already reaches another way (the TUI's `--host` server). */\n skip?: (entry: HostEntry) => boolean\n /** Called with every signal of a connected saved server. */\n onSignal?: (key: string, signal: HostSignal) => void\n /** Called when a saved server connects, also after a reconnect. */\n onConnected?: (key: string, client: IpcClient) => void\n /** Called when a saved server's connection drops. */\n onDisconnected?: (key: string) => void\n /**\n * Lower backoff bound in milliseconds.\n * @default 1000\n */\n minDelayMs?: number\n /**\n * Upper backoff bound in milliseconds.\n * @default 30000\n */\n maxDelayMs?: number\n}\n\n/** Handle returned by {@link startSavedHosts} to list, add, remove, rename, test and retry saved servers. */\nexport interface SavedHostsController {\n /** The saved hosts, read fresh (other windows share the file). */\n list: () => HostEntry[]\n /** Verify, save, connect (in place when already saved). Throws a `HostRegistryError`. */\n add: (input: { url: string, token: string, name?: string }) => Promise<HostEntry>\n /** Removes a server from the registry and its entry from the directory. Returns whether it existed. */\n remove: (id: string) => boolean\n /** Renames a saved server and returns the updated entry. */\n rename: (id: string, name: string) => HostEntry\n /** Move a saved server to a new URL (its saved token; the same server must answer), then reconnect it in place. Throws a `HostRegistryError`. */\n setUrl: (id: string, url: string) => Promise<HostEntry>\n /** A saved server (by id), or an unsaved URL + token (the add form's test). */\n test: (target: string | { id: string } | { url: string, token: string }) => Promise<HostTestResult>\n /** Reconnect now (after an outage or a token fix). */\n retry: (id: string) => void\n /** Reconnect every saved server that is not connected now, its backoff reset (the computer woke up). */\n retryAll: () => void\n /** Disconnects every saved server and removes their directory entries. The registry is not changed. */\n stop: () => void\n}\n\n/**\n * Starts the connections of a client's saved servers and keeps the directory in step with the registry.\n * Each saved server gets a directory entry and a connection loop. A connection whose host id differs from the saved one is closed and reported as `identity`.\n * @param options - Registry, directory and how to dial.\n * @returns A controller over the saved servers.\n */\nexport function startSavedHosts(options: SavedHostsOptions): SavedHostsController {\n const { registry, directory, skip = () => false } = options\n const classify = (err: unknown): HostFailureKind => err instanceof MissingHostTokenError ? 'auth' : err instanceof HostIdentityError ? 'identity' : (options.classify?.(err) ?? 'retry')\n\n /** The saved server, or nobody: a connection from another host is closed before anyone sees it. */\n const dial = async (entry: HostEntry, token: string, attempt: { signal: AbortSignal, onClose: () => void }): Promise<IpcClient> => {\n const client = await options.connect(entry, token, attempt)\n const ref = hostRefOf(client.hello)\n if (ref?.id === entry.id)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(entry.url), ref?.name)\n }\n const loops = new Map<string, HostConnectionLoop>()\n\n const disconnect = (key: string): void => {\n loops.get(key)?.stop()\n loops.delete(key)\n }\n\n /** (Re)connect `entry` with the token saved now, its directory entry kept or created in place. */\n const connect = (entry: HostEntry): void => {\n const key = entry.id\n disconnect(key)\n directory.upsert(entry, registry.token(key))\n loops.set(key, keepHostConnected({\n connect: (attempt) => {\n const token = registry.token(key)\n return token ? dial(entry, token, attempt) : Promise.reject(new MissingHostTokenError())\n },\n update: patch => directory.update(key, patch),\n classify,\n ...(options.onSignal ? { onSignal: (signal: HostSignal) => options.onSignal!(key, signal) } : {}),\n ...(options.onConnected ? { onConnected: (client: IpcClient) => options.onConnected!(key, client) } : {}),\n ...(options.onDisconnected ? { onDisconnected: () => options.onDisconnected!(key) } : {}),\n ...(options.minDelayMs !== undefined ? { minDelayMs: options.minDelayMs } : {}),\n ...(options.maxDelayMs !== undefined ? { maxDelayMs: options.maxDelayMs } : {}),\n }))\n }\n\n /** Bring the directory in line with the saved hosts. */\n const sync = (): void => {\n const entries = registry.list().filter(entry => !skip(entry))\n const saved = new Set(entries.map(entry => entry.id))\n const known = new Map(directory.saved().map(host => [host.key, host.url]))\n for (const key of known.keys()) {\n if (!saved.has(key)) {\n disconnect(key)\n directory.remove(key)\n }\n }\n for (const entry of entries) {\n if (known.get(entry.id) !== entry.url)\n connect(entry)\n else\n directory.update(entry.id, { name: entry.name, ...(entry.serverVersion ? { serverVersion: entry.serverVersion } : {}) })\n }\n }\n\n sync()\n return {\n list: () => registry.list(),\n add: async (input) => {\n const entry = await registry.add(input)\n // Saved again (a new token or URL): reconnect with them, the entry kept.\n if (!skip(entry))\n connect(entry)\n sync()\n return entry\n },\n remove: (id) => {\n const removed = registry.remove(id)\n sync()\n return removed\n },\n rename: (id, name) => {\n const entry = registry.rename(id, name)\n sync()\n return entry\n },\n setUrl: async (id, url) => {\n const entry = await registry.setUrl(id, url)\n if (!skip(entry))\n connect(entry)\n sync()\n return entry\n },\n test: async (target) => {\n if (typeof target === 'object' && !('id' in target)) {\n if (!options.probeUnsaved)\n throw new Error('Testing an unsaved host is not available here.')\n return options.probeUnsaved(target)\n }\n const id = typeof target === 'string' ? target : target.id\n const result = await registry.test(id)\n if (result.ok) {\n directory.update(id, { serverName: result.hostRef.name, ...(result.serverVersion ? { serverVersion: result.serverVersion } : {}) })\n loops.get(id)?.retry()\n }\n return result\n },\n retry: id => loops.get(id)?.retry(),\n retryAll: () => {\n for (const loop of loops.values())\n loop.retry()\n },\n stop: () => {\n for (const key of [...loops.keys()]) {\n disconnect(key)\n directory.remove(key)\n }\n },\n }\n}\n","/**\n * Saved servers over WebSocket: the registry in `dataDir`, the add form's\n * unsaved test, the refusal classification and (by default) the dial, wired\n * for `startSavedHosts`. Loaded behind each client's remote-hosts gate.\n */\nimport type { HostProbeResult } from '../../chat/hosts'\nimport type { HostFailureKind } from './connection-loop'\nimport type { SavedHostsController, SavedHostsOptions } from './saved-hosts'\nimport { HostIdentityError, probeUnsavedHost } from '../../chat/hosts'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\nimport { createWsHostRegistry, probeWsHost } from './probe'\nimport { startSavedHosts } from './saved-hosts'\n\n/**\n * A refused token stays refused until the user changes something: no retry\n * loop. Another protocol version stays until one side is upgraded: a slow re-check.\n * @param err - The error a connect attempt failed with.\n * @returns `auth` for a refused token, `identity` for another host answering, `protocol` for a version mismatch, `retry` otherwise.\n */\nexport function classifyWsFailure(err: unknown): HostFailureKind {\n if (err instanceof HostAuthError)\n return 'auth'\n if (err instanceof HostIdentityError)\n return 'identity'\n return err instanceof IpcVersionMismatchError ? 'protocol' : 'retry'\n}\n\n/**\n * The add form's \"test\": the registry's own checks and probe over WebSocket, saving nothing.\n * @param target - URL and token to try.\n * @returns The probe result.\n */\nexport function probeUnsavedWsHost(target: { url: string, token: string }): Promise<HostProbeResult> {\n return probeUnsavedHost(probeWsHost, target)\n}\n\n/**\n * Options for {@link startWsSavedHosts}: {@link SavedHostsOptions} with the registry, dialer and classifier filled in.\n * `dataDir` holds the saved-hosts registry file.\n */\nexport type WsSavedHostsOptions = Omit<SavedHostsOptions, 'registry' | 'connect' | 'classify' | 'probeUnsaved'> & {\n dataDir: string\n /** Client version in the server's diagnostics (default dial only). */\n appVersion?: string\n /** Dial another way (the TUI goes through its directory entry's transport). Default: `connectWsClient`. */\n connect?: SavedHostsOptions['connect']\n registry?: SavedHostsOptions['registry']\n}\n\n/**\n * Keeps the saved servers of a client connected over WebSocket.\n * Uses the registry in `dataDir` unless `registry` is given, and dials with {@link connectWsClient} unless `connect` is given.\n * @param options - Data directory, host directory and callbacks.\n * @returns A controller to list, add, remove, test and retry hosts, and to stop them all.\n */\nexport function startWsSavedHosts(options: WsSavedHostsOptions): SavedHostsController {\n const { dataDir, appVersion, connect, registry, ...rest } = options\n return startSavedHosts({\n ...rest,\n registry: registry ?? createWsHostRegistry({ dataDir }),\n classify: classifyWsFailure,\n probeUnsaved: probeUnsavedWsHost,\n connect: connect ?? ((entry, token, attempt) => connectWsClient({\n url: entry.url,\n token,\n expectHostId: entry.id,\n ...(appVersion ? { appVersion } : {}),\n signal: attempt.signal,\n onClose: attempt.onClose,\n })),\n })\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAa,wBAAwB;AAErC,MAAM,cAAc;AAEpB,SAAS,SAAS,KAAyD;CACzE,IAAI,eAAe,eACjB,OAAO,IAAI,WAAW,MAClB;EAAE,OAAO;EAAQ,SAAS;CAAgH,IAC1I;EAAE,OAAO;EAAQ,SAAS,IAAI;CAAQ;CAE5C,IAAI,eAAe,yBACjB,OAAO;EAAE,OAAO;EAAY,SAAS,IAAI;CAAQ;CACnD,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;CAC/D,IAAI,YAAY,KAAK,OAAO,GAC1B,OAAO;EAAE,OAAO;EAAO,SAAS,eAAe;CAAU;CAC3D,OAAO;EAAE,OAAO;EAAe;CAAQ;AACzC;;;;;;AAOA,eAAe,WAAW,KAAa,QAA6C;CAClF,IAAI,CAAC,IAAI,WAAW,MAAM,GACxB,OAAO;CACT,IAAI;EAGF,MAAM,KAAK,OAAQ,WAAiC,QAAQ,cAAc,aAAa,IAAI;EAE3F,CAAK,MADkB,MAAM,SAAS,IAAI,MAAM,CAAa,KAAK;GAAE,UAAU;GAAU,QAAQ,YAAY,IAAI,CAAC,QAAQ,YAAY,QAAQ,GAAI,CAAC,CAAC;GAAG,GAAI,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC;EAAG,CAAgB,EAAA,CACvL,MAAM,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C,OAAO;CACT,SACO,KAAK;EACV,MAAM,IAAI;EACV,MAAM,SAAS,GAAG,OAAO,EAAE,SAAS,WA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AAqBA,SAAgB,kBAAkB,SAAoD;CACpF,MAAM,EAAE,SAAS,YAAY,SAAS,UAAU,GAAG,SAAS;CAC5D,OAAO,gBAAgB;EACrB,GAAG;EACH,UAAU,YAAY,qBAAqB,EAAE,QAAQ,CAAC;EACtD,UAAU;EACV,cAAc;EACd,SAAS,aAAa,OAAO,OAAO,YAAY,gBAAgB;GAC9D,KAAK,MAAM;GACX;GACA,cAAc,MAAM;GACpB,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;GACnC,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB,CAAC;CACH,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"ws-ks0slKdL.js","names":[],"sources":["../src/ipc/hosts/probe.ts","../src/ipc/hosts/saved-hosts.ts","../src/ipc/hosts/ws.ts"],"sourcesContent":["/**\n * The host registry's connection (`src/chat/hosts`): a WebSocket probe that\n * says who answers at a URL with a token, and the registry wired to it.\n */\nimport type { HostErrorCode, HostProbeResult, HostRegistry } from '../../chat/hosts'\nimport { createHostRegistry, displayHostUrl } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { hostCaBundle } from '../transports/tls-trust'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\n\n/** Bound on one probe: the upgrade, the handshake and `daemon.info`. */\nexport const HOST_PROBE_TIMEOUT_MS = 10_000\n\nconst TLS_FAILURE = /certificate|self[- ]signed|\\btls\\b|\\bssl\\b|UNABLE_TO_VERIFY|CERT_|ERR_TLS/i\n\nfunction classify(err: unknown): { error: HostErrorCode, message: string } {\n if (err instanceof HostAuthError) {\n return err.status === 401\n ? { error: 'auth', message: 'The host refused the token (401). Create a new one on the server: zidane server token create --name <device>.' }\n : { error: 'auth', message: err.message }\n }\n if (err instanceof IpcVersionMismatchError)\n return { error: 'protocol', message: err.message }\n const message = err instanceof Error ? err.message : String(err)\n if (TLS_FAILURE.test(message))\n return { error: 'tls', message: `TLS failed: ${message}` }\n return { error: 'unreachable', message }\n}\n\n/**\n * A failed WebSocket says nothing about why. For `wss://`, ask the same\n * address over HTTPS: a certificate or handshake failure there is a TLS\n * problem, anything else stays \"unreachable\".\n */\nasync function tlsFailure(url: string, signal: AbortSignal): Promise<string | null> {\n if (!url.startsWith('wss:'))\n return null\n try {\n // No token, and no redirect followed: only the TLS handshake with this origin matters.\n // The same CAs as the socket (Bun takes them per request; Node uses its process default).\n const ca = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' ? hostCaBundle() : null\n const response = await fetch(`https:${url.slice('wss:'.length)}`, { redirect: 'manual', signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]), ...(ca ? { tls: { ca } } : {}) } as RequestInit)\n void response.body?.cancel().catch(() => {})\n return null\n }\n catch (err) {\n const e = err as { code?: unknown, message?: unknown }\n const detail = `${typeof e.code === 'string' ? e.code : ''} ${typeof e.message === 'string' ? e.message : ''}`\n return TLS_FAILURE.test(detail) ? `TLS failed: ${String(e.message ?? e.code)}` : null\n }\n}\n\n/**\n * Connect, read the host's identity and `daemon.info`, disconnect. Never throws.\n * @param target - URL, token and an optional timeout in milliseconds. The timeout defaults to {@link HOST_PROBE_TIMEOUT_MS}.\n * @returns Who answered and how fast, or a classified failure.\n */\nexport async function probeWsHost(target: { url: string, token: string, timeoutMs?: number }): Promise<HostProbeResult> {\n // The OS certificate store is read once per process, synchronously (seconds on a loaded\n // machine): read it before the deadline starts, or that cost is misread as a host with no answer.\n if (typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' && /^wss:/i.test(target.url))\n hostCaBundle()\n const started = performance.now()\n const signal = AbortSignal.timeout(target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS)\n let client: Awaited<ReturnType<typeof connectWsClient>> | undefined\n try {\n client = await connectWsClient({ url: target.url, token: target.token, heartbeatMs: 0, signal })\n const hostRef = hostRefOf(client.hello)\n if (!hostRef)\n return { ok: false, error: 'protocol', message: `${displayHostUrl(target.url)} runs a zidane too old to say which host it is. Upgrade the server.` }\n const info = await client.request('daemon.info', {})\n const serverVersion = info.codeVersion ?? info.appVersion\n return { ok: true, hostRef, ...(serverVersion ? { serverVersion } : {}), latencyMs: Math.round(performance.now() - started) }\n }\n catch (err) {\n if (signal.aborted && !(err instanceof HostAuthError))\n return { ok: false, error: 'unreachable', message: `No answer from ${displayHostUrl(target.url)} within ${target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS} ms.` }\n const classified = classify(err)\n if (classified.error === 'unreachable') {\n const tls = await tlsFailure(target.url, signal).catch(() => null)\n if (tls)\n return { ok: false, error: 'tls', message: tls }\n }\n return { ok: false, ...classified }\n }\n finally {\n client?.close()\n }\n}\n\n/**\n * The registry in `dataDir`, connecting over WebSocket.\n * @param options - Where the registry keeps its data.\n * @returns The host registry.\n */\nexport function createWsHostRegistry(options: { dataDir: string }): HostRegistry {\n return createHostRegistry({ dataDir: options.dataDir, probe: probeWsHost })\n}\n","/**\n * A client's saved servers, kept in its host directory: one directory entry\n * and one app-lifetime connection (`connection-loop`) per server in the\n * registry, in step with it. Shared by the TUI and the GUI main process,\n * which each supply their directory (`SavedHostsDirectory`) and how to dial.\n *\n * Saving a server that is already saved (same host id: a new token, a new\n * URL) reconfigures its entry IN PLACE and reconnects: the entry is never\n * removed, so the sessions routed to it stay routed. Only a server leaving\n * the registry (removed here or by another window) or `stop()` removes an\n * entry, and the directory decides what that means for an open session.\n *\n * Every connection is checked against the saved entry's id (the server's\n * `hostId` when it was added): another host answering at the URL is closed\n * at once, reported as `identity` and not retried, so nothing it says is\n * recorded under the saved id. Dialers may check first (`expectHostId`).\n *\n * No WebSocket import: the WebSocket wiring is `./ws.ts`.\n */\nimport type { HostEntry, HostProbeResult, HostRegistry, HostTestResult } from '../../chat/hosts'\nimport type { HostSignal } from '../protocol'\nimport type { IpcClient } from '../transports/client-core'\nimport type { HostConnectionLoop, HostConnectionPatch, HostFailureKind } from './connection-loop'\nimport { displayHostUrl, HostIdentityError } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { keepHostConnected } from './connection-loop'\n\n/** The client's host directory, as the saved servers see it. Keys are host ids. */\nexport interface SavedHostsDirectory {\n /** The saved servers it holds now, with their URL (a `--host` server excluded). */\n saved: () => { key: string, url: string }[]\n /** Add the entry, or reconfigure the one under its key in place (status `connecting`). */\n upsert: (entry: HostEntry, token: string | undefined) => void\n /** Applies a connection patch, a new name or a server version to the entry. */\n update: (key: string, patch: HostConnectionPatch & { name?: string, serverVersion?: string }) => void\n /** The server left the registry, or the saved servers stopped. */\n remove: (key: string) => void\n}\n\n/** No token is saved for this server (removed by hand, or another window removed it). */\nexport class MissingHostTokenError extends Error {\n constructor() {\n super('No token saved for this server: add it again.')\n this.name = 'MissingHostTokenError'\n }\n}\n\n/** Options for {@link startSavedHosts}: the registry, the host directory, the connect function and callbacks. */\nexport interface SavedHostsOptions {\n /** The registry of saved servers. */\n registry: HostRegistry\n /** The client's host directory the entries are kept in. */\n directory: SavedHostsDirectory\n /** One connect attempt to a saved server, with its token read fresh. */\n connect: (entry: HostEntry, token: string, options: { signal: AbortSignal, onClose: () => void }) => Promise<IpcClient>\n /** `auth`: refused for good. A missing token is always `auth`, another host answering always `identity`. */\n classify?: (err: unknown) => HostFailureKind\n /** The add form's test of an unsaved URL + token (`probeUnsavedHost`). */\n probeUnsaved?: (target: { url: string, token: string }) => Promise<HostProbeResult>\n /** Saved entries the directory already reaches another way (the TUI's `--host` server). */\n skip?: (entry: HostEntry) => boolean\n /** Called with every signal of a connected saved server. */\n onSignal?: (key: string, signal: HostSignal) => void\n /** Called when a saved server connects, also after a reconnect. */\n onConnected?: (key: string, client: IpcClient) => void\n /** Called when a saved server's connection drops. */\n onDisconnected?: (key: string) => void\n /**\n * Lower backoff bound in milliseconds.\n * @default 1000\n */\n minDelayMs?: number\n /**\n * Upper backoff bound in milliseconds.\n * @default 30000\n */\n maxDelayMs?: number\n}\n\n/** Handle returned by {@link startSavedHosts} to list, add, remove, rename, test and retry saved servers. */\nexport interface SavedHostsController {\n /** The saved hosts, read fresh (other windows share the file). */\n list: () => HostEntry[]\n /** Verify, save, connect (in place when already saved). Throws a `HostRegistryError`. */\n add: (input: { url: string, token: string, name?: string }) => Promise<HostEntry>\n /** Removes a server from the registry and its entry from the directory. Returns whether it existed. */\n remove: (id: string) => boolean\n /** Renames a saved server and returns the updated entry. */\n rename: (id: string, name: string) => HostEntry\n /** Move a saved server to a new URL (its saved token; the same server must answer), then reconnect it in place. Throws a `HostRegistryError`. */\n setUrl: (id: string, url: string) => Promise<HostEntry>\n /** A saved server (by id), or an unsaved URL + token (the add form's test). */\n test: (target: string | { id: string } | { url: string, token: string }) => Promise<HostTestResult>\n /** Reconnect now (after an outage or a token fix). */\n retry: (id: string) => void\n /** Reconnect every saved server that is not connected now, its backoff reset (the computer woke up). */\n retryAll: () => void\n /** Disconnects every saved server and removes their directory entries. The registry is not changed. */\n stop: () => void\n}\n\n/**\n * Starts the connections of a client's saved servers and keeps the directory in step with the registry.\n * Each saved server gets a directory entry and a connection loop. A connection whose host id differs from the saved one is closed and reported as `identity`.\n * @param options - Registry, directory and how to dial.\n * @returns A controller over the saved servers.\n */\nexport function startSavedHosts(options: SavedHostsOptions): SavedHostsController {\n const { registry, directory, skip = () => false } = options\n const classify = (err: unknown): HostFailureKind => err instanceof MissingHostTokenError ? 'auth' : err instanceof HostIdentityError ? 'identity' : (options.classify?.(err) ?? 'retry')\n\n /** The saved server, or nobody: a connection from another host is closed before anyone sees it. */\n const dial = async (entry: HostEntry, token: string, attempt: { signal: AbortSignal, onClose: () => void }): Promise<IpcClient> => {\n const client = await options.connect(entry, token, attempt)\n const ref = hostRefOf(client.hello)\n if (ref?.id === entry.id)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(entry.url), ref?.name)\n }\n const loops = new Map<string, HostConnectionLoop>()\n\n const disconnect = (key: string): void => {\n loops.get(key)?.stop()\n loops.delete(key)\n }\n\n /** (Re)connect `entry` with the token saved now, its directory entry kept or created in place. */\n const connect = (entry: HostEntry): void => {\n const key = entry.id\n disconnect(key)\n directory.upsert(entry, registry.token(key))\n loops.set(key, keepHostConnected({\n connect: (attempt) => {\n const token = registry.token(key)\n return token ? dial(entry, token, attempt) : Promise.reject(new MissingHostTokenError())\n },\n update: patch => directory.update(key, patch),\n classify,\n ...(options.onSignal ? { onSignal: (signal: HostSignal) => options.onSignal!(key, signal) } : {}),\n ...(options.onConnected ? { onConnected: (client: IpcClient) => options.onConnected!(key, client) } : {}),\n ...(options.onDisconnected ? { onDisconnected: () => options.onDisconnected!(key) } : {}),\n ...(options.minDelayMs !== undefined ? { minDelayMs: options.minDelayMs } : {}),\n ...(options.maxDelayMs !== undefined ? { maxDelayMs: options.maxDelayMs } : {}),\n }))\n }\n\n /** Bring the directory in line with the saved hosts. */\n const sync = (): void => {\n const entries = registry.list().filter(entry => !skip(entry))\n const saved = new Set(entries.map(entry => entry.id))\n const known = new Map(directory.saved().map(host => [host.key, host.url]))\n for (const key of known.keys()) {\n if (!saved.has(key)) {\n disconnect(key)\n directory.remove(key)\n }\n }\n for (const entry of entries) {\n if (known.get(entry.id) !== entry.url)\n connect(entry)\n else\n directory.update(entry.id, { name: entry.name, ...(entry.serverVersion ? { serverVersion: entry.serverVersion } : {}) })\n }\n }\n\n sync()\n return {\n list: () => registry.list(),\n add: async (input) => {\n const entry = await registry.add(input)\n // Saved again (a new token or URL): reconnect with them, the entry kept.\n if (!skip(entry))\n connect(entry)\n sync()\n return entry\n },\n remove: (id) => {\n const removed = registry.remove(id)\n sync()\n return removed\n },\n rename: (id, name) => {\n const entry = registry.rename(id, name)\n sync()\n return entry\n },\n setUrl: async (id, url) => {\n const entry = await registry.setUrl(id, url)\n if (!skip(entry))\n connect(entry)\n sync()\n return entry\n },\n test: async (target) => {\n if (typeof target === 'object' && !('id' in target)) {\n if (!options.probeUnsaved)\n throw new Error('Testing an unsaved host is not available here.')\n return options.probeUnsaved(target)\n }\n const id = typeof target === 'string' ? target : target.id\n const result = await registry.test(id)\n if (result.ok) {\n directory.update(id, { serverName: result.hostRef.name, ...(result.serverVersion ? { serverVersion: result.serverVersion } : {}) })\n loops.get(id)?.retry()\n }\n return result\n },\n retry: id => loops.get(id)?.retry(),\n retryAll: () => {\n for (const loop of loops.values())\n loop.retry()\n },\n stop: () => {\n for (const key of [...loops.keys()]) {\n disconnect(key)\n directory.remove(key)\n }\n },\n }\n}\n","/**\n * Saved servers over WebSocket: the registry in `dataDir`, the add form's\n * unsaved test, the refusal classification and (by default) the dial, wired\n * for `startSavedHosts`. Loaded behind each client's remote-hosts gate.\n */\nimport type { HostProbeResult } from '../../chat/hosts'\nimport type { HostFailureKind } from './connection-loop'\nimport type { SavedHostsController, SavedHostsOptions } from './saved-hosts'\nimport { HostIdentityError, probeUnsavedHost } from '../../chat/hosts'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\nimport { createWsHostRegistry, probeWsHost } from './probe'\nimport { startSavedHosts } from './saved-hosts'\n\n/**\n * A refused token stays refused until the user changes something: no retry\n * loop. Another protocol version stays until one side is upgraded: a slow re-check.\n * @param err - The error a connect attempt failed with.\n * @returns `auth` for a refused token, `identity` for another host answering, `protocol` for a version mismatch, `retry` otherwise.\n */\nexport function classifyWsFailure(err: unknown): HostFailureKind {\n if (err instanceof HostAuthError)\n return 'auth'\n if (err instanceof HostIdentityError)\n return 'identity'\n return err instanceof IpcVersionMismatchError ? 'protocol' : 'retry'\n}\n\n/**\n * The add form's \"test\": the registry's own checks and probe over WebSocket, saving nothing.\n * @param target - URL and token to try.\n * @returns The probe result.\n */\nexport function probeUnsavedWsHost(target: { url: string, token: string }): Promise<HostProbeResult> {\n return probeUnsavedHost(probeWsHost, target)\n}\n\n/**\n * Options for {@link startWsSavedHosts}: {@link SavedHostsOptions} with the registry, dialer and classifier filled in.\n * `dataDir` holds the saved-hosts registry file.\n */\nexport type WsSavedHostsOptions = Omit<SavedHostsOptions, 'registry' | 'connect' | 'classify' | 'probeUnsaved'> & {\n dataDir: string\n /** Client version in the server's diagnostics (default dial only). */\n appVersion?: string\n /** Dial another way (the TUI goes through its directory entry's transport). Default: `connectWsClient`. */\n connect?: SavedHostsOptions['connect']\n registry?: SavedHostsOptions['registry']\n}\n\n/**\n * Keeps the saved servers of a client connected over WebSocket.\n * Uses the registry in `dataDir` unless `registry` is given, and dials with {@link connectWsClient} unless `connect` is given.\n * @param options - Data directory, host directory and callbacks.\n * @returns A controller to list, add, remove, test and retry hosts, and to stop them all.\n */\nexport function startWsSavedHosts(options: WsSavedHostsOptions): SavedHostsController {\n const { dataDir, appVersion, connect, registry, ...rest } = options\n return startSavedHosts({\n ...rest,\n registry: registry ?? createWsHostRegistry({ dataDir }),\n classify: classifyWsFailure,\n probeUnsaved: probeUnsavedWsHost,\n connect: connect ?? ((entry, token, attempt) => connectWsClient({\n url: entry.url,\n token,\n expectHostId: entry.id,\n ...(appVersion ? { appVersion } : {}),\n signal: attempt.signal,\n onClose: attempt.onClose,\n })),\n })\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAa,wBAAwB;AAErC,MAAM,cAAc;AAEpB,SAAS,SAAS,KAAyD;CACzE,IAAI,eAAe,eACjB,OAAO,IAAI,WAAW,MAClB;EAAE,OAAO;EAAQ,SAAS;CAAgH,IAC1I;EAAE,OAAO;EAAQ,SAAS,IAAI;CAAQ;CAE5C,IAAI,eAAe,yBACjB,OAAO;EAAE,OAAO;EAAY,SAAS,IAAI;CAAQ;CACnD,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;CAC/D,IAAI,YAAY,KAAK,OAAO,GAC1B,OAAO;EAAE,OAAO;EAAO,SAAS,eAAe;CAAU;CAC3D,OAAO;EAAE,OAAO;EAAe;CAAQ;AACzC;;;;;;AAOA,eAAe,WAAW,KAAa,QAA6C;CAClF,IAAI,CAAC,IAAI,WAAW,MAAM,GACxB,OAAO;CACT,IAAI;EAGF,MAAM,KAAK,OAAQ,WAAiC,QAAQ,cAAc,aAA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