mindwire 0.1.25 → 0.1.26
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/binary-cache-VM7VHCEU.js +4 -0
- package/dist/{binary-cache-CG52TXCZ.js.map → binary-cache-VM7VHCEU.js.map} +1 -1
- package/dist/{chunk-PFYKJ6LX.js → chunk-3FR7BFAW.js} +4 -56
- package/dist/chunk-3FR7BFAW.js.map +1 -0
- package/dist/chunk-L3USUTZZ.js +2021 -0
- package/dist/chunk-L3USUTZZ.js.map +1 -0
- package/dist/cli.js +447 -2178
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts +12 -2
- package/dist/computer/controller.d.ts +3 -0
- package/dist/computer/lifecycle.d.ts +13 -3
- package/dist/computer/lock.d.ts +11 -0
- package/dist/computer/pairing-display.d.ts +23 -0
- package/dist/computer/process.d.ts +26 -0
- package/dist/computer/relay.d.ts +5 -1
- package/dist/computer/startup.d.ts +38 -0
- package/dist/computer.d.ts +4 -0
- package/dist/controller-CGSJZZZD.js +496 -0
- package/dist/controller-CGSJZZZD.js.map +1 -0
- package/dist/index.cjs +17 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +17 -10
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/workspace.d.ts +16 -2
- package/package.json +1 -1
- package/dist/binary-cache-CG52TXCZ.js +0 -3
- package/dist/chunk-PFYKJ6LX.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/computer.ts","../src/version.ts","../src/daemon-binary.ts","../src/computer/process.ts","../src/http.ts","../src/sse.ts","../src/run.ts","../src/workspace.ts","../src/surfaces.ts","../src/service.ts","../src/execution.ts","../src/embedded.ts","../src/target/index.ts","../src/client.ts","../src/computer/lock.ts","../src/computer/lifecycle.ts"],"names":["path","stat","delay","payload","spawn","fs","fs2","randomUUID","controller"],"mappings":";;;;;;;;;;;AA0BO,IAAM,cAAN,MAAkB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MAAMJ,aAAM,GAAG,CAAA;AAAA,EAAG;AACrH,EAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;AACnE","file":"chunk-L3USUTZZ.js","sourcesContent":["import type { Mindwire } from \"./client.js\";\n\nexport type ComputerRoute = { kind: \"ssh\"; host: string; port: number } | { kind: \"websocket\"; url: string };\nexport interface ComputerInvitation {\n version: 1; computerId: string; name: string; fingerprint: string; routes: ComputerRoute[];\n pairingId: string; secret: string; expiresAt: string;\n}\nexport interface ComputerDevice { id: string; name: string; publicKey: string; createdAt: string; revoked: boolean }\nexport interface ComputerPairRequest { id: string; name: string; publicKey: string }\nexport interface ComputerPairing {\n id: string; expiresAt: string; status: \"waiting\" | \"pending\" | \"approved\" | \"rejected\";\n request?: ComputerPairRequest;\n completed?: boolean;\n}\nexport interface ComputerUpdate {\n id: string; version: string; updatedAt: string; error?: string;\n status: \"idle\" | \"queued\" | \"downloading\" | \"waiting\" | \"restarting\" | \"complete\" | \"failed\";\n}\nexport interface ComputerInfo {\n version: number; computerId: string; registryId: string; fingerprint: string; routes: ComputerRoute[];\n pid: number; apiAddress: string; sshPort: number; websocketPort: number;\n portForwardingVersion?: number;\n}\nexport interface ComputerForwardRequest { id: string; deviceId: string; port: number }\nexport interface ComputerForward extends ComputerForwardRequest { expiresAt: string }\n/** Available only in computer mode. All calls use the existing authenticated transport. */\nexport class ComputerApi {\n constructor(private readonly client: Mindwire) {}\n info(): Promise<ComputerInfo> { return this.client.http.request(\"GET\", \"/computer\"); }\n setRoutes(routes: ComputerRoute[]): Promise<ComputerInfo> {\n return this.client.http.request(\"PUT\", \"/computer/routes\", { body: { routes } });\n }\n updateStatus(): Promise<ComputerUpdate> { return this.client.http.request(\"GET\", \"/computer/update\"); }\n requestUpdate(version: string): Promise<ComputerUpdate> {\n return this.client.http.request(\"POST\", \"/computer/update\", { body: { version } });\n }\n invite(routes: ComputerRoute[]): Promise<ComputerInvitation> {\n return this.client.http.request(\"POST\", \"/computer/pairings\", { body: { routes } });\n }\n pairing(id: string): Promise<ComputerPairing> { return this.client.http.request(\"GET\", `/computer/pairings/${encodeURIComponent(id)}`); }\n completePairing(id: string, requestId: string): Promise<{ ok: boolean }> {\n return this.client.http.request(\"POST\", `/computer/pairings/${encodeURIComponent(id)}/complete`, { body: { requestId } });\n }\n decide(id: string, requestId: string, approve: boolean): Promise<{ ok: boolean; device: ComputerDevice }> {\n return this.client.http.request(\"POST\", `/computer/pairings/${encodeURIComponent(id)}/decision`, { body: { requestId, approve } });\n }\n devices(): Promise<ComputerDevice[]> { return this.client.http.request(\"GET\", \"/computer/devices\"); }\n revoke(id: string): Promise<{ ok: boolean }> { return this.client.http.request(\"DELETE\", `/computer/devices/${encodeURIComponent(id)}`); }\n forwards(): Promise<ComputerForward[]> { return this.client.http.request(\"GET\", \"/computer/forwards\"); }\n /** Authorize a loopback port for this paired device. Renew the same ID every 30s;\n * grants expire after two minutes. Carry traffic using SSH direct-tcpip. */\n forward(request: ComputerForwardRequest): Promise<ComputerForward> {\n return this.client.http.request(\"POST\", \"/computer/forwards\", { body: request });\n }\n closeForward(id: string): Promise<{ ok: boolean }> {\n return this.client.http.request(\"DELETE\", `/computer/forwards/${encodeURIComponent(id)}`);\n }\n}\n\n/** The mobile scanner accepts raw JSON. Avoid base64 overhead in QR codes without\n * dropping routes, shortening the host pin or changing the pairing protocol.\n * This includes a short-lived secret; never log it to shared service logs. */\nexport function computerPairingQRData(invitation: ComputerInvitation): string {\n return JSON.stringify(invitation);\n}\n\n/** A URI carries an invitation, not permanent credentials. Never log it to shared service logs. */\nexport function computerPairingURI(invitation: ComputerInvitation): string {\n // UTF-8/base64url works in browsers too; no Node-only dependency in the protocol layer.\n const bytes = new TextEncoder().encode(computerPairingQRData(invitation));\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n const encoded = btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n return `mindwire://pair?v=1#${encoded}`;\n}\n","// The SDK's own version, replaced at build time by tsup's `define` (see tsup.config.ts) with the\n// literal from package.json. This is also the version of the bundled Linux daemon binary\n// (build-daemon.mjs stamps the per-arch daemon packages to the same version), so a sandbox adapter\n// can compare it against a running daemon's `/healthz` version to decide whether to (re)deploy.\n//\n// The `typeof` guard keeps this importable in dev/test where the define isn't applied (raw `tsc`,\n// `bun test`) — it falls back to a sentinel instead of throwing on an undefined identifier.\ndeclare const __MINDWIRE_VERSION__: string;\n\nexport const SDK_VERSION: string =\n typeof __MINDWIRE_VERSION__ !== \"undefined\" ? __MINDWIRE_VERSION__ : \"0.0.0-dev\";\n","// Version-pinned daemon acquisition. The npm package stays TypeScript-only: when a server-side target\n// needs a daemon, it downloads the binary matching this SDK's version from the GitHub Release, verifies\n// the published SHA-256, and caches it outside node_modules for later offline use.\nimport { MindwireError } from \"./errors.js\";\nimport { SDK_VERSION } from \"./version.js\";\n\nexport type DaemonPlatform = \"darwin\" | \"linux\" | \"win32\";\nexport type DaemonArch = \"x64\" | \"arm64\";\n\nexport interface EnsureDaemonBinaryOptions {\n version?: string;\n platform?: DaemonPlatform;\n arch?: DaemonArch;\n cacheDir?: string;\n /** Override for tests or a private GitHub Releases mirror. */\n releaseBaseUrl?: string;\n fetch?: typeof fetch;\n}\n\nfunction supported(platform: string, arch: string): asserts platform is DaemonPlatform & string {\n if (!([\"darwin\", \"linux\", \"win32\"] as string[]).includes(platform) || !([\"x64\", \"arm64\"] as string[]).includes(arch)) {\n throw new MindwireError(`mindwire: no daemon release for ${platform}-${arch}`);\n }\n}\n\nfunction assetName(version: string, platform: DaemonPlatform, arch: DaemonArch): string {\n const releasePlatform = platform === \"win32\" ? \"windows\" : platform;\n const releaseArch = arch === \"x64\" ? \"amd64\" : arch;\n return `mindwired-v${version}-${releasePlatform}-${releaseArch}${platform === \"win32\" ? \".exe\" : \"\"}`;\n}\n\nfunction checksumFor(text: string, asset: string): string | undefined {\n const line = text.split(\"\\n\").find((l) => l.trim().endsWith(` ${asset}`) || l.trim().endsWith(` ${asset}`));\n const hash = line?.trim().split(/\\s+/)[0];\n return hash && /^[a-f0-9]{64}$/i.test(hash) ? hash.toLowerCase() : undefined;\n}\n\n/** Ensure the SDK-matched daemon binary is present locally and return its executable path. */\nexport async function ensureDaemonBinary(opts: EnsureDaemonBinaryOptions = {}): Promise<string> {\n const proc = globalThis as typeof globalThis & { process?: { platform?: string; arch?: string; env?: Record<string, string | undefined> } };\n const platform = opts.platform ?? proc.process?.platform;\n const arch = opts.arch ?? proc.process?.arch;\n supported(platform ?? \"unknown\", arch ?? \"unknown\");\n const daemonPlatform = platform as DaemonPlatform;\n const daemonArch = arch as DaemonArch;\n const version = opts.version ?? SDK_VERSION;\n if (!/^[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {\n throw new MindwireError(`mindwire: cannot download daemon for non-release SDK version ${version}`);\n }\n\n const path = await import(\"node:path\");\n const { binaryCacheDirectory, cachedExecutable, cacheExecutable } = await import(\"./binary-cache.js\");\n const dir = path.join(opts.cacheDir ?? await binaryCacheDirectory(daemonPlatform), version, `${daemonPlatform}-${daemonArch}`);\n const asset = assetName(version, daemonPlatform, daemonArch);\n const bin = path.join(dir, asset);\n const cached = await cachedExecutable(bin);\n if (cached) return cached;\n\n const base = (opts.releaseBaseUrl ?? proc.process?.env?.MINDWIRE_RELEASE_BASE_URL ?? \"https://github.com/oblien/mindwire/releases/download\").replace(/\\/$/, \"\");\n const release = `${base}/v${version}`;\n const request = opts.fetch ?? globalThis.fetch;\n if (!request) throw new MindwireError(\"mindwire: fetch is unavailable; set daemonBin or MINDWIRE_DAEMON\");\n const [checksums, binary] = await Promise.all([request(`${release}/checksums.txt`), request(`${release}/${asset}`)]);\n if (!checksums.ok || !binary.ok) {\n // A just-published SDK can briefly precede its matching Release asset. For the public release\n // endpoint only, recover to GitHub's latest stable release; mirrors must be explicit and exact.\n if (!opts.releaseBaseUrl && !proc.process?.env?.MINDWIRE_RELEASE_BASE_URL) {\n const latest = await request(\"https://api.github.com/repos/oblien/mindwire/releases/latest\");\n if (latest.ok) {\n const tag = (await latest.json() as { tag_name?: unknown }).tag_name;\n const fallback = typeof tag === \"string\" ? tag.replace(/^v/, \"\") : \"\";\n if (/^[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/.test(fallback) && fallback !== version) {\n return ensureDaemonBinary({ ...opts, version: fallback });\n }\n }\n }\n throw new MindwireError(`mindwire: failed to download daemon v${version} for ${daemonPlatform}-${daemonArch}`);\n }\n const expected = checksumFor(await checksums.text(), asset);\n if (!expected) throw new MindwireError(`mindwire: release v${version} has no checksum for ${asset}`);\n const bytes = new Uint8Array(await binary.arrayBuffer());\n return cacheExecutable(bin, bytes, expected);\n}\n","import { execFile, type ChildProcess } from \"node:child_process\";\nimport { readFile } from \"node:fs/promises\";\nimport { promisify } from \"node:util\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nconst execute = promisify(execFile);\nexport interface ProcessIdentity { pid: number; start: string }\nexport interface ProcessState { pid: number; start?: string }\nexport interface OwnedProcess {\n readonly pid: number;\n readonly identity?: ProcessIdentity;\n alive(): boolean;\n close(): Promise<void>;\n}\n\nexport function processAlive(pid: number | undefined): boolean {\n if (!pid || !Number.isSafeInteger(pid) || pid < 1) return false;\n try { process.kill(pid, 0); return true; } catch { return false; }\n}\n\n/** Include process birth, not just its reusable PID, when adopting an orphan. */\nexport async function processIdentity(pid: number): Promise<ProcessIdentity | undefined> {\n if (!processAlive(pid)) return undefined;\n try {\n let start: string;\n if (process.platform === \"linux\") {\n const stat = await readFile(`/proc/${pid}/stat`, \"utf8\");\n const fields = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \");\n const boot = (await readFile(\"/proc/sys/kernel/random/boot_id\", \"utf8\")).trim();\n start = `${boot}:${fields[19]}`;\n } else if (process.platform === \"win32\") {\n const result = await execute(\"powershell.exe\", [\"-NoProfile\", \"-NonInteractive\", \"-Command\",\n `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`], { timeout: 5000, windowsHide: true });\n start = result.stdout.trim();\n } else {\n // ps is native on macOS; no flock or other Unix package is required.\n const result = await execute(\"/bin/ps\", [\"-p\", String(pid), \"-o\", \"lstart=\", \"-o\", \"comm=\"], {\n timeout: 3000, env: { ...process.env, LC_ALL: \"C\", TZ: \"UTC\" },\n });\n start = result.stdout.trim();\n }\n return start ? { pid, start } : undefined;\n } catch { return undefined; }\n}\n\nexport async function currentProcessIdentity(): Promise<ProcessIdentity> {\n const identity = await processIdentity(process.pid);\n if (!identity) throw new Error(\"Couldn't verify the Mindwire process identity. Retry the command.\");\n return identity;\n}\n\n/** Old CLI records contain only a PID. New records also survive PID reuse after\n * reboot, so an unrelated process cannot block recovery or receive Stop. */\nexport async function processStateAlive(state: ProcessState | undefined): Promise<boolean> {\n if (!state || !processAlive(state.pid)) return false;\n if (state.start === undefined) return true;\n const current = await processIdentity(state.pid);\n if (!current && processAlive(state.pid)) throw new Error(\"Couldn't verify the running Mindwire process. Retry the command.\");\n return !!state.start && current?.start === state.start;\n}\n\n/** Launch/startup locks used plain numeric PIDs before process identities. */\nexport async function readProcessState(file: string): Promise<ProcessState | undefined> {\n try {\n const state = JSON.parse(await readFile(file, \"utf8\"));\n if (typeof state === \"number\") return { pid: state };\n return state && typeof state.pid === \"number\" ? state : undefined;\n } catch (error) {\n if (error instanceof SyntaxError || (error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw error;\n }\n}\n\nexport async function ownChild(child: ChildProcess): Promise<OwnedProcess> {\n if (!child.pid) throw new Error(\"The background process could not start.\");\n const pid = child.pid;\n const identity = await processIdentity(pid);\n const alive = () => child.exitCode === null && child.signalCode === null;\n return { pid, identity, alive, async close() {\n if (!alive()) return;\n const exited = new Promise<void>(resolve => child.once(\"exit\", () => resolve()));\n child.kill(\"SIGTERM\");\n const timer = setTimeout(() => { if (alive()) child.kill(\"SIGKILL\"); }, 15_000);\n try { await exited; } finally { clearTimeout(timer); }\n } };\n}\n\nexport async function adoptProcess(identity: ProcessIdentity): Promise<OwnedProcess | undefined> {\n const matches = async () => (await processIdentity(identity.pid))?.start === identity.start;\n if (!await matches()) return undefined;\n return { pid: identity.pid, identity, alive: () => processAlive(identity.pid), async close() {\n if (!await matches()) return;\n process.kill(identity.pid, \"SIGTERM\");\n for (let attempt = 0; attempt < 60; attempt++) {\n if (!processAlive(identity.pid)) return;\n await delay(250);\n }\n // Never signal a new process that inherited the old PID.\n if (await matches()) process.kill(identity.pid, \"SIGKILL\");\n } };\n}\n","import { ApiError, MindwireError, TimeoutError } from \"./errors.js\";\n\n/** A `fetch` implementation. Defaults to the global `fetch` (Node 18+, Bun, Deno, browsers). */\nexport type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\n/** Default deadline for a single unary request. Long enough to cover a cold daemon, short enough\n * that a wedged connection surfaces as an error instead of an indefinite hang. */\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\n/** True for a fetch rejection caused by an `AbortSignal` firing (user cancel or our own timeout). */\nfunction isAbortError(e: unknown): boolean {\n return typeof e === \"object\" && e !== null && (e as { name?: unknown }).name === \"AbortError\";\n}\n\n/**\n * Fetches the current bearer token for a transport whose credential rotates (e.g. the Oblien\n * gateway JWT). Called per request — implementations should cache and only mint on `{force:true}`\n * or expiry. `request()`/`open()` call it with `{force:true}` once on a `401`, then retry.\n */\nexport type TokenGetter = (opts?: { force?: boolean }) => Promise<string | undefined>;\n\n/**\n * Resolves the daemon's base URL, plus an optional static token, an optional dynamic `getToken`\n * (for rotating credentials), and optional per-transport `headers` merged into every request\n * (e.g. the Oblien proxy target). Called once, lazily, and memoized.\n */\nexport type BaseResolver = () => Promise<{\n baseUrl: string;\n token?: string;\n getToken?: TokenGetter;\n headers?: Record<string, string>;\n /**\n * A transport-specific `fetch` for this base — used for both unary requests and SSE streams. A\n * sandbox adapter supplies it to route every call through its runtime (e.g. Oblien's `rt.proxy`);\n * when omitted the client's default fetch is used, so embedded/remote transports are unchanged.\n */\n fetch?: FetchLike;\n}>;\n\nexport interface HttpOptions {\n /** Base URL of a running daemon, e.g. `http://127.0.0.1:8790`. */\n baseUrl?: string;\n /** Per-sandbox bearer token. */\n token?: string;\n /** Lazily resolve the base URL (used by the embedded transport to spawn on first call). */\n resolveBase?: BaseResolver;\n /** Custom fetch. Defaults to global `fetch`. */\n fetch?: FetchLike;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /**\n * Deadline in milliseconds for a single unary request. Does NOT apply to SSE streams (`open()`),\n * which are long-lived by design. Defaults to {@link DEFAULT_TIMEOUT_MS}; pass `0` to disable.\n */\n timeoutMs?: number;\n}\n\nexport interface RequestInitLike {\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n signal?: AbortSignal;\n headers?: Record<string, string>;\n}\n\ninterface Base {\n baseUrl: string;\n token?: string;\n getToken?: TokenGetter;\n headers?: Record<string, string>;\n fetch?: FetchLike;\n}\n\n/**\n * The low-level transport: URL/auth/JSON/error plumbing shared by every high-level method.\n * The base URL is resolved lazily and memoized — a fixed `baseUrl` resolves instantly; the\n * embedded transport spawns the daemon on the first request.\n */\nexport class Http {\n private readonly fetchImpl: FetchLike;\n private readonly baseHeaders: Record<string, string>;\n private readonly resolver: BaseResolver;\n private readonly timeoutMs: number;\n private cached: Base | null = null;\n private pending: Promise<Base> | null = null;\n\n constructor(opts: HttpOptions) {\n const f = opts.fetch ?? (globalThis.fetch as FetchLike | undefined);\n if (!f) {\n throw new MindwireError(\n \"mindwire: no global fetch found — pass a `fetch` implementation in the client options\",\n );\n }\n this.fetchImpl = f;\n this.baseHeaders = { ...opts.headers };\n this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n if (opts.baseUrl) {\n const base: Base = { baseUrl: opts.baseUrl.replace(/\\/+$/, \"\"), token: opts.token };\n this.resolver = async () => base;\n } else if (opts.resolveBase) {\n const rb = opts.resolveBase;\n this.resolver = async () => {\n const r = await rb();\n return {\n baseUrl: r.baseUrl.replace(/\\/+$/, \"\"),\n token: r.token ?? opts.token,\n getToken: r.getToken,\n headers: r.headers,\n fetch: r.fetch,\n };\n };\n } else {\n throw new MindwireError(\"mindwire: Http requires a baseUrl or a resolveBase\");\n }\n }\n\n /**\n * One fetch, with raw network failures wrapped as {@link MindwireError} so callers see a typed\n * SDK error instead of a bare `TypeError: fetch failed`. An abort (the request's own signal, or\n * our timeout controller) is re-thrown untouched — `fetchWithTimeout` classifies it.\n */\n private async fetchOnce(\n f: FetchLike,\n url: string,\n init: RequestInit,\n method: string,\n path: string,\n ): Promise<Response> {\n try {\n return await f(url, init);\n } catch (e) {\n const aborted = init.signal?.aborted ?? false;\n if (aborted || isAbortError(e)) throw e; // an abort, not a network fault — leave it for the caller\n throw new MindwireError(`mindwire: ${method} ${path} — network request failed`, { cause: e });\n }\n }\n\n /**\n * `fetchOnce` plus a timeout that composes with the caller's `signal`. A hand-rolled controller\n * (not `AbortSignal.timeout`/`AbortSignal.any`, which need Node 20.3+/18.17+) fires after\n * `timeoutMs`; whichever aborts first wins. Timeout → {@link TimeoutError}; the caller's own abort\n * propagates as-is (its `reason`). `timeoutMs<=0` disables the deadline entirely.\n */\n private async fetchWithTimeout(\n f: FetchLike,\n url: string,\n init: RequestInit,\n userSignal: AbortSignal | undefined,\n method: string,\n path: string,\n ): Promise<Response> {\n if (!this.timeoutMs || this.timeoutMs <= 0) {\n return this.fetchOnce(f, url, { ...init, ...(userSignal ? { signal: userSignal } : {}) }, method, path);\n }\n const ctrl = new AbortController();\n const onAbort = () => ctrl.abort(userSignal?.reason);\n if (userSignal) {\n if (userSignal.aborted) ctrl.abort(userSignal.reason);\n else userSignal.addEventListener(\"abort\", onAbort, { once: true });\n }\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n ctrl.abort();\n }, this.timeoutMs);\n try {\n return await this.fetchOnce(f, url, { ...init, signal: ctrl.signal }, method, path);\n } catch (e) {\n if (timedOut) throw new TimeoutError(method, path, this.timeoutMs);\n if (userSignal?.aborted) throw userSignal.reason ?? e; // caller cancelled — surface their reason\n throw e;\n } finally {\n clearTimeout(timer);\n if (userSignal) userSignal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n /**\n * The bearer token for the next request. Prefers the transport's dynamic `getToken` (which\n * caches and mints on demand); falls back to the static token resolved at base time. `force`\n * asks the getter to re-mint — used once on a 401 before retrying.\n */\n private async authToken(base: Base, force: boolean): Promise<string | undefined> {\n if (base.getToken) {\n const t = await base.getToken(force ? { force: true } : undefined);\n return t ?? base.token;\n }\n return base.token;\n }\n\n private base(): Promise<Base> {\n if (this.cached) return Promise.resolve(this.cached);\n if (!this.pending) {\n // Memoize the in-flight provision, but drop it on failure so a cold-start error (e.g. a fresh\n // SSH box that wasn't ready) can be retried by the next `ensure()`/request instead of latching.\n this.pending = this.resolver()\n .then((b) => (this.cached = b))\n .catch((err) => {\n this.pending = null;\n throw err;\n });\n }\n return this.pending;\n }\n\n /**\n * Resolve the base eagerly and memoize it — provisions the transport (spawns the embedded daemon,\n * connects the sandbox/SSH/Docker target, …) now instead of on the first request. Idempotent: this\n * awaits the *same* memoized promise the first `request()`/`open()` awaits, so the target's\n * `connect()` fires exactly once. Backs {@link import(\"./client.js\").Mindwire.ensure}.\n */\n async ready(): Promise<void> {\n await this.base();\n }\n\n private url(baseUrl: string, path: string, query?: RequestInitLike[\"query\"]): string {\n const u = new URL(baseUrl + (path.startsWith(\"/\") ? path : `/${path}`));\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined) u.searchParams.set(k, String(v));\n }\n }\n return u.toString();\n }\n\n private headers(token: string | undefined, extra?: Record<string, string>, hasBody = false): Record<string, string> {\n const h: Record<string, string> = { Accept: \"application/json\", ...this.baseHeaders, ...extra };\n if (token) h[\"Authorization\"] = `Bearer ${token}`;\n if (hasBody) h[\"Content-Type\"] = \"application/json\";\n return h;\n }\n\n async request<T>(method: string, path: string, init: RequestInitLike = {}): Promise<T> {\n const base = await this.base();\n const hasBody = init.body !== undefined;\n const url = this.url(base.baseUrl, path, init.query);\n const extra = { ...base.headers, ...init.headers };\n const f = base.fetch ?? this.fetchImpl;\n const send = async (force: boolean) =>\n this.fetchWithTimeout(\n f,\n url,\n {\n method,\n headers: this.headers(await this.authToken(base, force), extra, hasBody),\n body: hasBody ? JSON.stringify(init.body) : undefined,\n },\n init.signal,\n method,\n path,\n );\n\n let res = await send(false);\n // One-shot re-mint + retry for rotating credentials (e.g. an expired gateway JWT).\n if (res.status === 401 && base.getToken) res = await send(true);\n\n if (!res.ok) throw await this.toApiError(method, res);\n if (res.status === 204) return undefined as T;\n\n const text = await res.text();\n if (text === \"\") return undefined as T;\n try {\n return JSON.parse(text) as T;\n } catch (e) {\n throw new MindwireError(`mindwire: ${method} ${path} returned a non-JSON body`, { cause: e });\n }\n }\n\n /** Open a streaming response (SSE). Caller owns the body. */\n async open(method: string, path: string, init: RequestInitLike = {}): Promise<Response> {\n const base = await this.base();\n const url = this.url(base.baseUrl, path, init.query);\n const extra = { Accept: \"text/event-stream\", ...base.headers, ...init.headers };\n const f = base.fetch ?? this.fetchImpl;\n // No timeout: SSE streams are long-lived. We still wrap network faults (via fetchOnce) so a\n // connection refused surfaces as a MindwireError rather than a bare `TypeError: fetch failed`.\n const send = async (force: boolean) =>\n this.fetchOnce(\n f,\n url,\n {\n method,\n headers: this.headers(await this.authToken(base, force), extra, init.body !== undefined),\n ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),\n ...(init.signal ? { signal: init.signal } : {}),\n },\n method,\n path,\n );\n\n let res = await send(false);\n if (res.status === 401 && base.getToken) res = await send(true);\n\n if (!res.ok) throw await this.toApiError(method, res);\n if (!res.body)\n throw new MindwireError(`mindwire: ${method} ${path} returned no response body to stream`);\n return res;\n }\n\n private async toApiError(method: string, res: Response): Promise<ApiError> {\n let body: unknown = \"\";\n try {\n const text = await res.text();\n try {\n body = text ? JSON.parse(text) : \"\";\n } catch {\n body = text;\n }\n } catch {\n /* ignore body read failures */\n }\n return new ApiError({ status: res.status, url: res.url, method, body });\n }\n}\n","/**\n * A minimal, dependency-free Server-Sent Events reader.\n *\n * The daemon streams `data: <json>\\n\\n` frames (one JSON object per event) plus `: ping`\n * comment keepalives and an initial `{ \"type\": \"status\", \"meta\": { \"stream\": \"open\" } }`\n * sentinel. This parser handles multi-line `data:` fields and `\\r\\n`/`\\n` line endings, and\n * yields the JSON-parsed payload of each event.\n *\n * We read via `ReadableStream.getReader()` rather than `for await` so it works on every\n * runtime with WHATWG streams (Node 18+ undici, Deno, Bun, browsers), not only those that\n * made the stream async-iterable.\n */\nexport async function* readSSE<T>(\n body: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncGenerator<T, void, unknown> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const onAbort = () => void reader.cancel().catch(() => {});\n if (signal) {\n if (signal.aborted) {\n await reader.cancel().catch(() => {});\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n // Events are separated by a blank line. Normalize CRLF first.\n let sep: number;\n while ((sep = indexOfBlankLine(buffer)) !== -1) {\n const rawEvent = buffer.slice(0, sep);\n buffer = buffer.slice(sepEnd(buffer, sep));\n const payload = parseEvent(rawEvent);\n if (payload !== undefined) yield JSON.parse(payload) as T;\n }\n }\n // Flush any trailing event that wasn't terminated by a blank line.\n const payload = parseEvent(buffer);\n if (payload !== undefined) yield JSON.parse(payload) as T;\n } finally {\n if (signal) signal.removeEventListener(\"abort\", onAbort);\n // Breaking a consumer loop must release the HTTP stream as well as its reader.\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n}\n\n/** Index of the start of the blank-line separator (`\\n\\n` or `\\r\\n\\r\\n`), or -1. */\nfunction indexOfBlankLine(s: string): number {\n const a = s.indexOf(\"\\n\\n\");\n const b = s.indexOf(\"\\r\\n\\r\\n\");\n if (a === -1) return b;\n if (b === -1) return a;\n return Math.min(a, b);\n}\n\n/** Length of the separator that starts at `idx`, so the next event begins after it. */\nfunction sepEnd(s: string, idx: number): number {\n return s.startsWith(\"\\r\\n\\r\\n\", idx) ? idx + 4 : idx + 2;\n}\n\n/**\n * Extract the concatenated `data:` payload of one raw SSE event block. Comment lines\n * (starting with `:`) and non-data fields are ignored. Returns `undefined` for an event\n * with no data lines (e.g. a lone keepalive comment).\n */\nfunction parseEvent(block: string): string | undefined {\n const lines = block.split(/\\r\\n|\\n/);\n const data: string[] = [];\n for (const line of lines) {\n if (line === \"\" || line.startsWith(\":\")) continue;\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n if (field !== \"data\") continue;\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1); // SSE strips one leading space\n data.push(value);\n }\n if (data.length === 0) return undefined;\n return data.join(\"\\n\");\n}\n","import type { Http } from \"./http.js\";\nimport { readSSE } from \"./sse.js\";\nimport { RunFailedError } from \"./errors.js\";\nimport type { Event, ResultInfo, RespondInput, RunSnapshot, Run as RunData } from \"./types.js\";\n\nexport interface StreamOptions {\n signal?: AbortSignal;\n /** Resume after a snapshot/event cursor without replaying earlier output. */\n after?: number;\n /**\n * Include the daemon's `{ type: \"status\", meta: { stream: \"open\" } }` sentinel that is\n * flushed the instant the stream opens (used to detect a live vs. buffered transport).\n * Off by default — most consumers only care about model output.\n */\n includeOpenSentinel?: boolean;\n}\n\nexport interface WaitResult {\n run: RunData;\n result?: ResultInfo;\n}\n\nconst TERMINAL = new Set([\"done\", \"error\", \"cancelled\"]);\n\n/**\n * A handle to one turn's run. Wraps the durable `Run` record returned by `POST /turns` and\n * exposes the unified event stream, cancellation, and status polling.\n *\n * Stream it directly:\n *\n * ```ts\n * const run = await mw.turn({ chatId, message: \"refactor foo\" });\n * for await (const ev of run) {\n * if (ev.type === \"text\") process.stdout.write(ev.text ?? \"\");\n * }\n * ```\n */\nexport class Run {\n private data: RunData;\n private readonly http: Http;\n\n constructor(http: Http, data: RunData) {\n this.http = http;\n this.data = data;\n }\n\n get id(): string {\n return this.data.id;\n }\n get chatId(): string {\n return this.data.chatId;\n }\n get agent(): string | undefined {\n return this.data.agent;\n }\n get status(): RunData[\"status\"] {\n return this.data.status;\n }\n /** `\"resolve\"` on the parent of a global-resolve run; `undefined` for an ordinary turn. */\n get kind(): RunData[\"kind\"] {\n return this.data.kind;\n }\n /** On a child iteration of a resolve run, the id of its parent resolve run; else `undefined`. */\n get parentId(): string | undefined {\n return this.data.parentId;\n }\n /** Parent of a resolve run only: why the loop ended (`\"done\"` | `\"capped\"` | `\"error\"` | …). */\n get stopReason(): RunData[\"stopReason\"] {\n return this.data.stopReason;\n }\n /** Parent of a resolve run only: how many child turns the loop ran. */\n get iterations(): number | undefined {\n return this.data.iterations;\n }\n /** The latest known run record. */\n get value(): RunData {\n return this.data;\n }\n\n /** Unified SSE event stream: replay buffer, then live events, then close. */\n async *stream(opts: StreamOptions = {}): AsyncGenerator<Event, void, unknown> {\n const cursor = opts.after === undefined ? \"\" : `?after=${encodeURIComponent(opts.after)}`;\n const res = await this.http.open(\"GET\", `/runs/${encodeURIComponent(this.id)}/stream${cursor}`, {\n ...(opts.signal ? { signal: opts.signal } : {}),\n });\n for await (const ev of readSSE<Event>(res.body!, opts.signal)) {\n if (!opts.includeOpenSentinel && ev.type === \"status\" && ev.meta?.[\"stream\"] === \"open\") {\n continue;\n }\n yield ev;\n }\n }\n\n /** `for await (const ev of run)` — sugar for `run.stream()`. */\n [Symbol.asyncIterator](): AsyncGenerator<Event, void, unknown> {\n return this.stream();\n }\n\n /** Cancel the in-flight turn (kills the underlying agent process). */\n async cancel(): Promise<void> {\n await this.http.request<void>(\"POST\", `/runs/${encodeURIComponent(this.id)}/cancel`);\n }\n\n /**\n * Answer a pending permission, question or plan. Message-mode questions remain answerable\n * after completion; the daemon steers or resumes the conversation. Read the chat's latest\n * run after replying to a completed run. Requires the agent's `respond` capability.\n */\n async respond(input: RespondInput & { gitAuth?: import(\"./workspace.js\").ProjectAuth } = {}): Promise<void> {\n await this.http.request<void>(\"POST\", `/runs/${encodeURIComponent(this.id)}/respond`, { body: input });\n }\n\n /**\n * Steer a follow-up message into the running turn without cancelling it. Requires the agent's\n * `input` capability.\n */\n async sendInput(text: string): Promise<void> {\n await this.http.request<void>(\"POST\", `/runs/${encodeURIComponent(this.id)}/input`, { body: { text } });\n }\n\n /**\n * Soft-stop the running turn (ask the agent to halt current work) without the hard process kill\n * {@link Run.cancel} does — the turn stays open for a follow-up via {@link Run.sendInput}.\n * Requires the agent's `interrupt` capability.\n */\n async interrupt(): Promise<void> {\n await this.http.request<void>(\"POST\", `/runs/${encodeURIComponent(this.id)}/interrupt`);\n }\n\n /**\n * Switch the model of the live turn. An empty/omitted `model` resets the turn to the agent/CLI\n * default. Only meaningful on a persistent (non-bypass) turn; on a one-shot turn it is a\n * best-effort no-op. Requires the agent's `setModel` capability.\n */\n async setModel(model?: string): Promise<void> {\n await this.http.request<void>(\"POST\", `/runs/${encodeURIComponent(this.id)}/set-model`, {\n body: { model: model ?? \"\" },\n });\n }\n\n /**\n * Switch the live permission mode using a value from the agent's settings schema.\n * Resolves after the harness acknowledges the change; rejects if it cannot apply it.\n * Requires `setPermissionMode`. Codex settings apply on the next turn instead.\n */\n async setPermissionMode(mode: string): Promise<void> {\n await this.http.request<void>(\"POST\", `/runs/${encodeURIComponent(this.id)}/set-permission-mode`, {\n body: { mode },\n });\n }\n\n /**\n * `GET /runs/{id}/children` — the child iterations of a global-resolve run, oldest→newest, each as\n * its own {@link Run} handle. An ordinary turn (or a resolve that ran a single iteration) returns an\n * empty array. Use it to inspect the run tree a {@link Mindwire.resolve} produced.\n */\n async children(): Promise<Run[]> {\n const data = await this.http.request<RunData[]>(\n \"GET\",\n `/runs/${encodeURIComponent(this.id)}/children`,\n );\n return data.map((d) => new Run(this.http, d));\n }\n\n /** Re-fetch the run record from the daemon and update this handle. */\n async refresh(): Promise<RunData> {\n this.data = await this.http.request<RunData>(\"GET\", `/runs/${encodeURIComponent(this.id)}`);\n return this.data;\n }\n\n /** Restore current output once, then follow with `stream({ after: snapshot.sequence })`. */\n async snapshot(): Promise<RunSnapshot> {\n const snapshot = await this.http.request<RunSnapshot>(\"GET\", `/runs/${encodeURIComponent(this.id)}/snapshot`);\n this.data = snapshot.run;\n return snapshot;\n }\n\n /**\n * Consume the event stream to completion. Returns the final run record and the `result`\n * event's summary (if any). Throws {@link RunFailedError} on an `error`/`cancelled` outcome\n * unless `throwOnError` is set to `false`.\n */\n async wait(opts: StreamOptions & { throwOnError?: boolean } = {}): Promise<WaitResult> {\n let result: ResultInfo | undefined;\n let streamError: string | undefined;\n for await (const ev of this.stream(opts)) {\n if (ev.type === \"result\") result = ev.result;\n else if (ev.type === \"error\") streamError = ev.error;\n }\n const run = await this.refresh();\n if (opts.throwOnError !== false) {\n if (TERMINAL.has(run.status)) {\n if (run.status !== \"done\") {\n throw new RunFailedError(run.id, run.status, run.error ?? streamError);\n }\n } else {\n // The stream ended but the run never reached a terminal state — the transport dropped\n // mid-run (the daemon keeps a replay buffer, but this client does not yet reconnect).\n // Report it rather than returning a success-shaped result on a truncated stream.\n throw new RunFailedError(\n run.id,\n run.status,\n streamError ?? \"event stream ended before the run reached a terminal state\",\n );\n }\n }\n return result !== undefined ? { run, result } : { run };\n }\n}\n","import type { Mindwire } from \"./client.js\";\nimport { readSSE } from \"./sse.js\";\n\n/** Write-only credentials. Never persisted in operation snapshots or conversation state. */\nexport type ProjectAuth = (\n | { kind: \"token\"; token: string; username?: string }\n | { kind: \"ssh\"; privateKey: string }\n | { kind: \"gh\" }\n) & { connectionId?: string; expiresAt?: string; readOnly?: boolean };\n\nexport interface GitConnection {\n id: string;\n login: string;\n mode: \"token\" | \"oblienApp\" | \"sshKey\" | \"ghCli\" | \"native\";\n lifetime: \"run\" | \"workspace\";\n}\n\nexport interface GitAccessState {\n default?: GitConnection;\n storedConnectionIds: string[];\n storedConnections: GitConnection[];\n activeOperations: number;\n}\n\nexport interface ProjectGitState {\n connection?: GitConnection;\n inherited: boolean;\n stored: boolean;\n repoUrl?: string;\n}\n\nexport type GitAction = \"stage\" | \"unstage\" | \"discard\" | \"commit\" | \"fetch\" | \"pull\" | \"push\"\n | \"switch_branch\" | \"create_branch\" | \"restore_commit\";\n\nexport interface GitIdentity { name: string; email: string }\n\nexport type GitIdentityScope = \"repository\" | \"workspace\" | \"all_workspaces\";\n\nexport interface GitIdentitySettings {\n effective: GitIdentity;\n repository: GitIdentity | null;\n workspace: GitIdentity | null;\n allWorkspaces: GitIdentity | null;\n defaultRevision: string;\n}\n\nexport interface GitIdentityUpdate {\n scope: GitIdentityScope;\n /** null removes this override, allowing a broader default to apply. */\n identity: GitIdentity | null;\n /** Required for all_workspaces; keep this ID and expectedRevision until acknowledged. */\n requestId?: string;\n expectedRevision?: string;\n}\n\nexport interface GitOperationRequest {\n /** Stable ID. Reuse this exact intent after a lost acknowledgement. */\n id: string;\n action: GitAction;\n /** Literal repository-relative paths, required for stage/unstage/discard. */\n paths?: string[];\n /** Required for commit. Uses the existing author unless identity is explicitly supplied. */\n message?: string;\n /** Literal branch name for switch_branch/create_branch; requires gitOperationsVersion >= 2. */\n branch?: string;\n /** switch_branch only: branch is a remote tracking name, e.g. origin/feature. */\n remote?: boolean;\n /** Commit only; requires gitOperationsVersion >= 3. Saves attribution in this repository,\n * then commits under the same durable lock. Never changes global Git configuration. */\n identity?: GitIdentity;\n /** restore_commit only; requires gitOperationsVersion >= 4. Full source commit object ID. */\n commitId?: string;\n /** restore_commit only: full HEAD object ID observed before confirmation. */\n expectedHead?: string;\n /** restore_commit only: observed local branch name; omit for detached HEAD. */\n expectedBranch?: string;\n /** Write-only, for network operations only. Never part of an operation snapshot. */\n auth?: ProjectAuth;\n}\n\nexport interface GitOperation extends Omit<GitOperationRequest, \"auth\"> {\n projectId: string;\n /** Canonical repository root resolved by the daemon. */\n path: string;\n status: \"queued\" | \"running\" | \"cancelling\" | \"succeeded\" | \"failed\" | \"cancelled\" | \"interrupted\";\n output?: string;\n error?: string;\n /** git_identity_required asks the client to collect a name/email before a new commit intent. */\n errorCode?: \"git_identity_required\" | \"git_restore_dirty\" | \"git_restore_changed\"\n | \"git_restore_in_progress\" | \"git_restore_commit_unavailable\" | \"git_restore_local_files\" | (string & {});\n createdAt: string;\n updatedAt: string;\n sequence: number;\n}\n\nexport interface ProjectRequest {\n /** Stable idempotency key. Keep the same ID if the acknowledgement is lost. */\n id: string;\n source: \"folder\" | \"create\" | \"clone\";\n name: string;\n /** Absolute directory, or ~/... on the workspace. Clone/create require an absent destination. */\n path: string;\n repoUrl?: string;\n branch?: string;\n auth?: ProjectAuth;\n gitConnection?: GitConnection;\n}\n\nexport interface ProjectRemoveRequest {\n /** Stable idempotency key for this confirmed removal. */\n operationId: string;\n expectedRevision: number;\n}\n\nexport interface ProjectOperation extends Omit<ProjectRequest, \"auth\" | \"source\"> {\n source: ProjectRequest[\"source\"] | \"delete\";\n expectedRevision?: number;\n authKind?: ProjectAuth[\"kind\"];\n status: \"queued\" | \"running\" | \"cancelling\" | \"succeeded\" | \"failed\" | \"cancelled\" | \"interrupted\";\n phase: string;\n progress?: number;\n /** Bounded, redacted output tail. */\n log?: string;\n error?: string;\n projectId?: string;\n createdAt: string;\n updatedAt: string;\n sequence: number;\n attempt: number;\n}\n\nexport class ProjectOperationsApi {\n constructor(private readonly mw: Mindwire) {}\n async list(activeOnly = false): Promise<ProjectOperation[]> {\n const response = await this.mw.http.request<{ operations: ProjectOperation[] }>(\"GET\", \"/workspace/operations\", {\n query: { active: activeOnly },\n });\n return response.operations;\n }\n get(id: string): Promise<ProjectOperation> {\n return this.mw.http.request(\"GET\", `/workspace/operations/${encodeURIComponent(id)}`);\n }\n cancel(id: string): Promise<ProjectOperation> {\n return this.mw.http.request(\"POST\", `/workspace/operations/${encodeURIComponent(id)}/cancel`);\n }\n retry(id: string, auth?: ProjectAuth): Promise<ProjectOperation> {\n return this.mw.http.request(\"POST\", `/workspace/operations/${encodeURIComponent(id)}/retry`, { body: { auth } });\n }\n /** The first event is the current snapshot, then live changes. Reconnecting never replays old\n * progress. Breaking the loop/aborting detaches the observer; cancel(id) explicitly stops work.\n */\n async *watch(id: string, opts: { signal?: AbortSignal } = {}): AsyncGenerator<ProjectOperation> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n opts.signal?.addEventListener(\"abort\", abort, { once: true });\n if (opts.signal?.aborted) controller.abort();\n try {\n const response = await this.mw.http.open(\"GET\", `/workspace/operations/${encodeURIComponent(id)}/stream`, {\n signal: controller.signal,\n });\n let sequence = -1;\n for await (const operation of readSSE<ProjectOperation>(response.body!, controller.signal)) {\n if (operation.sequence > sequence) { sequence = operation.sequence; yield operation; }\n }\n } finally {\n controller.abort();\n opts.signal?.removeEventListener(\"abort\", abort);\n }\n }\n}\n\n/** Stable identity and version of a record in one workspace's SQLite registry. */\nexport interface WorkspaceRecord {\n id: string;\n /** Registry identity, independent of the cloud provider's workspace ID. */\n workspaceId: string;\n createdAt: string;\n revision: number;\n}\n\n/** A saved agent profile. Profiles using one harness share that workspace's native configuration. */\nexport interface WorkspaceAgent extends WorkspaceRecord {\n name: string;\n agentType: string;\n agentTypeName?: string;\n /** Mutes this profile's current and future chats across notification channels. Omit to preserve; false to clear. */\n notificationsMuted?: boolean;\n}\n\nexport interface WorkspaceProject extends WorkspaceRecord {\n name: string;\n path: string;\n repoUrl?: string;\n /** Omit on edits to preserve; explicitly null restores the workspace default. */\n gitConnection?: GitConnection | null;\n}\n\n/** Chat membership; transcript content continues to come from /chats/:id/messages. */\nexport interface WorkspaceChat extends WorkspaceRecord {\n agentId: string;\n projectId: string;\n title: string;\n /** Cached native title beneath an optional user rename. Owned by the daemon. */\n nativeTitle?: string;\n titleIsUserSet?: boolean;\n sessionId?: string;\n /** Native harness activity, retained across app restarts. Not the last app-open time. */\n updatedAt?: string;\n /** Mutes this chat. False clears its own mute but never overrides a muted parent profile. Omit to preserve. */\n notificationsMuted?: boolean;\n}\n\nexport type WorkspaceKind = \"agents\" | \"projects\" | \"chats\";\nexport type WorkspaceInput<T extends WorkspaceRecord> = Omit<T, \"id\" | \"workspaceId\" | \"revision\" | \"createdAt\"> & {\n createdAt?: string;\n};\n\n/** Additive migration. Existing records and deletion tombstones always win over these values. */\nexport interface WorkspaceImport {\n agents?: (WorkspaceInput<WorkspaceAgent> & { id: string })[];\n projects?: (WorkspaceInput<WorkspaceProject> & { id: string })[];\n chats?: (WorkspaceInput<WorkspaceChat> & { id: string })[];\n}\n\nexport interface WorkspaceSnapshot {\n version: number;\n workspaceId: string;\n revision: number;\n /** true replaces the cache for this workspace; false applies changed rows and deletions. */\n full: boolean;\n agents: WorkspaceAgent[];\n projects: WorkspaceProject[];\n chats: WorkspaceChat[];\n deleted: { kind: WorkspaceKind; id: string; revision: number }[];\n /** Cached chats are retained when a harness's native list could not be refreshed. */\n sessionDiscoveryIssues?: { projectId: string; agent: string; message: string }[];\n}\n\nexport class WorkspaceCollection<T extends WorkspaceRecord> {\n constructor(private readonly mw: Mindwire, private readonly kind: WorkspaceKind) {}\n\n /** Create with a stable client-generated ID. For updates, supply the record's last revision. */\n put(id: string, record: WorkspaceInput<T>, expectedRevision?: number): Promise<WorkspaceSnapshot> {\n return this.mw.http.request(\"PUT\", `/workspace/${this.kind}/${encodeURIComponent(id)}`, {\n body: { record, expectedRevision },\n });\n }\n\n /** Remove membership and dependent chat links. Files and native transcripts are retained.\n * Use deleteChat() for an explicit transcript purge. Running chats reject removal with 409.\n */\n delete(id: string, revision: number): Promise<WorkspaceSnapshot> {\n return this.mw.http.request(\"DELETE\", `/workspace/${this.kind}/${encodeURIComponent(id)}`, {\n query: { revision },\n });\n }\n}\n\n/** Workspace metadata is shared by all harnesses; withAgent() never scopes these requests. */\nexport class WorkspaceApi {\n readonly git: GitAccessApi;\n readonly operations: ProjectOperationsApi;\n readonly agents: WorkspaceCollection<WorkspaceAgent>;\n readonly projects: WorkspaceCollection<WorkspaceProject>;\n readonly chats: WorkspaceCollection<WorkspaceChat>;\n\n constructor(private readonly mw: Mindwire) {\n this.git = new GitAccessApi(mw);\n this.operations = new ProjectOperationsApi(mw);\n this.agents = new WorkspaceCollection(mw, \"agents\");\n this.projects = new WorkspaceCollection(mw, \"projects\");\n this.chats = new WorkspaceCollection(mw, \"chats\");\n }\n\n snapshot(options: { refresh?: boolean } = {}): Promise<WorkspaceSnapshot> {\n return this.mw.http.request(\"GET\", \"/workspace\", { query: options });\n }\n\n /** Start an operation owned by the daemon. The same ID/payload returns the existing operation. */\n createProject(request: ProjectRequest): Promise<ProjectOperation> {\n return this.mw.http.request(\"POST\", \"/workspace/projects\", { body: request });\n }\n\n /** Permanently remove the confirmed project's directory and membership.\n * projects.delete() retains files. Native harness transcripts are not purged.\n */\n removeProjectFiles(id: string, request: ProjectRemoveRequest): Promise<ProjectOperation> {\n return this.mw.http.request(\"POST\", `/workspace/projects/${encodeURIComponent(id)}/remove`, { body: request });\n }\n\n /** Incremental reconciliation. Pass the previous identity to detect a replaced/restored workspace.\n * A 409 requires fetching snapshot() again; never apply a delta to a different registry.\n */\n changes(since: number, workspaceId: string, options: { refresh?: boolean } = {}): Promise<WorkspaceSnapshot> {\n return this.mw.http.request(\"GET\", \"/workspace/changes\", { query: { since, workspaceId, ...options } });\n }\n\n /** Import legacy metadata before replacing a local cache. Safe to repeat after interruption. */\n import(records: WorkspaceImport): Promise<WorkspaceSnapshot> {\n return this.mw.http.request(\"POST\", \"/workspace/import\", { body: records });\n }\n}\n\n/** Account preferences and authenticated Git on the daemon hosting each repository. */\nexport class GitAccessApi {\n constructor(private readonly mw: Mindwire) {}\n /** Reads attribution independently of GitHub authentication. Requires gitIdentityVersion >= 1. */\n identity(context: { projectId?: string; path?: string } = {}): Promise<GitIdentitySettings> {\n return this.mw.http.request(\"GET\", \"/workspace/git/identity\", { query: context });\n }\n /** Saves settings only; never stages or commits. all_workspaces installs this\n * workspace's copy of a client-managed default; the client handles fan-out. */\n setIdentity(update: GitIdentityUpdate, context: { projectId?: string; path?: string } = {}): Promise<GitIdentitySettings> {\n return this.mw.http.request(\"PUT\", \"/workspace/git/identity\", { query: context, body: update });\n }\n state(): Promise<GitAccessState> {\n return this.mw.http.request(\"GET\", \"/workspace/git\");\n }\n setDefault(connection: GitConnection | null, auth?: ProjectAuth): Promise<GitAccessState> {\n return this.mw.http.request(\"PUT\", \"/workspace/git\", { body: { connection, auth } });\n }\n forget(connectionId: string): Promise<GitAccessState> {\n return this.mw.http.request(\"DELETE\", `/workspace/git/connections/${encodeURIComponent(connectionId)}`);\n }\n project(projectId: string): Promise<ProjectGitState> {\n return this.mw.http.request(\"GET\", `/workspace/projects/${encodeURIComponent(projectId)}/git`);\n }\n setProject(projectId: string, connection: GitConnection | null, expectedRevision: number, auth?: ProjectAuth): Promise<WorkspaceSnapshot> {\n return this.mw.http.request(\"PUT\", `/workspace/projects/${encodeURIComponent(projectId)}/git`, {\n body: { connection, expectedRevision, auth },\n });\n }\n /** Compatibility call. Prefer start() and operation()/watch() for reconnectable writes. */\n run(projectId: string, operation: \"fetch\" | \"pull\" | \"push\", auth?: ProjectAuth): Promise<{ output: string }> {\n return this.mw.http.request(\"POST\", `/workspace/projects/${encodeURIComponent(projectId)}/git/${operation}`, { body: { auth } });\n }\n\n /** Requires health.gitOperationsVersion >= 1 (>= 2 for branches, >= 4 for restore_commit). Acceptance persists before Git runs;\n * disconnecting only detaches the client. The same ID/intent never runs twice.\n */\n start(projectId: string, request: GitOperationRequest): Promise<GitOperation> {\n return this.mw.http.request(\"POST\", `/workspace/projects/${encodeURIComponent(projectId)}/git/operations`, { body: request });\n }\n async operations(projectId: string, activeOnly = false): Promise<GitOperation[]> {\n const result = await this.mw.http.request<{ operations: GitOperation[] }>(\"GET\",\n `/workspace/projects/${encodeURIComponent(projectId)}/git/operations`, { query: { active: activeOnly, actionsVersion: 4 } });\n return result.operations;\n }\n operation(id: string): Promise<GitOperation> {\n return this.mw.http.request(\"GET\", `/workspace/git/operations/${encodeURIComponent(id)}`);\n }\n cancel(id: string): Promise<GitOperation> {\n return this.mw.http.request(\"POST\", `/workspace/git/operations/${encodeURIComponent(id)}/cancel`);\n }\n /** Current snapshot followed by state changes. Aborting observation never cancels the operation. */\n async *watch(id: string, opts: { signal?: AbortSignal } = {}): AsyncGenerator<GitOperation> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n opts.signal?.addEventListener(\"abort\", abort, { once: true });\n if (opts.signal?.aborted) controller.abort();\n try {\n const response = await this.mw.http.open(\"GET\", `/workspace/git/operations/${encodeURIComponent(id)}/stream`, {\n signal: controller.signal,\n });\n let sequence = -1;\n for await (const operation of readSSE<GitOperation>(response.body!, controller.signal)) {\n if (operation.sequence > sequence) { sequence = operation.sequence; yield operation; }\n }\n } finally {\n controller.abort();\n opts.signal?.removeEventListener(\"abort\", abort);\n }\n }\n}\n","import type { Mindwire } from \"./client.js\";\nimport { readSSE } from \"./sse.js\";\n\nexport interface SurfaceGeometry { width: number; height: number; revision: number }\nexport interface SurfaceProblem { code: string; message: string }\nexport interface SurfaceCapabilities {\n view: boolean; capture: boolean; pointer: boolean; keyboard: boolean; text: boolean;\n clipboardRead: boolean; clipboardWrite: boolean;\n keyboardText?: boolean; extendedKeys?: boolean;\n}\nexport interface SurfaceController {\n sessionId: string; actor: \"user\" | \"agent\"; name: string; runId?: string; chatId?: string;\n generation: number; expiresAt: string;\n}\nexport interface SurfaceSnapshot {\n id: string; workspaceId: string; kind: \"desktop\"; provider: \"oblien\";\n version: number; revision: number; instanceId: string;\n state: string; observedAt?: string; supported: boolean; enabled: boolean; available: boolean;\n credentials: boolean; os?: string; capabilities: SurfaceCapabilities;\n geometry?: SurfaceGeometry; controller?: SurfaceController;\n authorizationExpiresAt?: string; error?: SurfaceProblem;\n}\n/** Write-only, desktop-only, expiring provider grant. Never pass a user's session JWT. */\nexport interface SurfaceBinding {\n registryId: string; workspaceId: string; gatewayToken?: string;\n connection: {\n expires_at: string;\n ssh: { host: string; port: number; username: string; password: string; host_key_fingerprint: string };\n vnc: { host: string; port: number; authentication: \"none\" };\n };\n}\nexport interface SurfaceSession {\n id: string; surfaceId: string; actor: \"user\" | \"agent\"; name: string;\n chatId?: string; runId?: string; mode: \"view\" | \"control\"; createdAt: string;\n controller?: SurfaceController;\n}\nexport interface SurfaceOpenRequest { requestId: string; name?: string; mode: \"view\" | \"control\" }\nexport interface SurfaceControlRequest { action: \"acquire\" | \"takeover\" | \"release\" | \"renew\"; generation?: number }\nexport interface SurfaceAction {\n kind: \"pointer\" | \"click\" | \"drag\" | \"scroll\" | \"key\" | \"text\" | \"clipboard_read\" | \"clipboard_write\" | \"release\";\n x?: number; y?: number; toX?: number; toY?: number; buttons?: number;\n button?: \"left\" | \"middle\" | \"right\"; count?: number; deltaX?: number; deltaY?: number;\n keys?: string[]; text?: string;\n /** Physical US keyboard text (printable ASCII, up to 4096 bytes), preserving the clipboard. */\n textMode?: \"keyboard\";\n}\nexport interface SurfaceActionRequest {\n /** Reuse this ID to inspect/recover an uncertain acknowledgement. Do not replay with a new ID. */\n requestId: string; sessionId: string; controlGeneration: number; frameId?: string;\n geometryRevision?: number; action: SurfaceAction;\n}\nexport interface SurfaceReceipt {\n id: string; sessionId: string; surfaceId: string; kind: string;\n status: \"dispatching\" | \"dispatched\" | \"outcome_unknown\"; createdAt: string; error?: SurfaceProblem;\n /** Transient clipboard output, not stored in the receipt. */\n text?: string;\n}\nexport interface SurfaceCapture {\n id: string; surfaceId: string; artifactId: string; mime: string; geometry: SurfaceGeometry; createdAt: string;\n}\nexport interface ArtifactContent {\n id: string; chatId?: string; mime: string; bytes: number; width: number; height: number; createdAt: string;\n /** Base64 bytes, compatible with every existing daemon transport. */\n data: string;\n}\nexport interface SurfaceToolAction {\n surfaceId: string; operation: string; sessionId?: string; receiptId?: string; status?: string;\n capture?: { id: string; artifactId: string; width: number; height: number };\n}\n\n/** Workspace-scoped API. One controller is shared by every harness and app client. */\nexport class SurfacesApi {\n constructor(private readonly mw: Mindwire) {}\n list(): Promise<SurfaceSnapshot[]> { return this.mw.http.request(\"GET\", \"/surfaces\"); }\n status(refresh = false): Promise<SurfaceSnapshot> {\n return this.mw.http.request(\"GET\", \"/surfaces/desktop\", { query: { refresh } });\n }\n bind(binding: SurfaceBinding): Promise<SurfaceSnapshot> {\n return this.mw.http.request(\"PUT\", \"/surfaces/desktop/binding\", { body: binding });\n }\n open(request: SurfaceOpenRequest): Promise<SurfaceSession> {\n return this.mw.http.request(\"POST\", \"/surfaces/desktop/sessions\", { body: request });\n }\n control(id: string, request: SurfaceControlRequest): Promise<SurfaceSession> {\n return this.mw.http.request(\"POST\", `/surfaces/desktop/sessions/${encodeURIComponent(id)}/control`, { body: request });\n }\n close(id: string): Promise<{ closed: boolean }> {\n return this.mw.http.request(\"DELETE\", `/surfaces/desktop/sessions/${encodeURIComponent(id)}`);\n }\n capture(id: string): Promise<SurfaceCapture> {\n return this.mw.http.request(\"POST\", `/surfaces/desktop/sessions/${encodeURIComponent(id)}/captures`);\n }\n action(request: SurfaceActionRequest): Promise<SurfaceReceipt> {\n return this.mw.http.request(\"POST\", \"/surfaces/desktop/actions\", { body: request });\n }\n receipt(id: string): Promise<SurfaceReceipt> {\n return this.mw.http.request(\"GET\", `/surfaces/desktop/actions/${encodeURIComponent(id)}`);\n }\n artifact(id: string): Promise<ArtifactContent> {\n return this.mw.http.request(\"GET\", `/artifacts/${encodeURIComponent(id)}`);\n }\n /** Every connection starts with the current snapshot, then revisions. Never replays input. */\n async *watch(opts: { signal?: AbortSignal } = {}): AsyncGenerator<SurfaceSnapshot> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n opts.signal?.addEventListener(\"abort\", abort, { once: true });\n if (opts.signal?.aborted) controller.abort();\n try {\n const response = await this.mw.http.open(\"GET\", \"/surfaces/desktop/events\", { signal: controller.signal });\n let instance: string | undefined;\n let revision = -1;\n for await (const snapshot of readSSE<SurfaceSnapshot>(response.body!, controller.signal)) {\n if (instance !== snapshot.instanceId || snapshot.revision > revision) {\n instance = snapshot.instanceId; revision = snapshot.revision; yield snapshot;\n }\n }\n } finally {\n controller.abort(); opts.signal?.removeEventListener(\"abort\", abort);\n }\n }\n}\n","import type { Mindwire } from \"./client.js\";\n\nexport interface ServiceUpdateState {\n idle: boolean;\n updating: boolean;\n activeOperations: number;\n}\n\nexport interface ServiceUpdateLease {\n id: string;\n /** Terminate only this leased process, not every mindwired process on the host. */\n pid: number;\n expiresAt: string;\n}\n\n/** Installer coordination; requires health.serviceUpdateVersion >= 1. */\nexport class ServiceApi {\n constructor(private readonly client: Mindwire) {}\n\n updateStatus(): Promise<ServiceUpdateState> {\n return this.client.http.request(\"GET\", \"/service/update\");\n }\n\n /** Download first. Acquire immediately before replacement; busy work returns 409.\n * Admission stays closed until release, process exit, or the one-minute expiry. */\n acquireUpdate(): Promise<ServiceUpdateLease> {\n return this.client.http.request(\"POST\", \"/service/update\");\n }\n\n releaseUpdate(id: string): Promise<{ ok: boolean }> {\n return this.client.http.request(\"DELETE\", `/service/update/${encodeURIComponent(id)}`);\n }\n}\n","import type { Mindwire } from \"./client.js\";\nimport { readSSE } from \"./sse.js\";\n\n/** Native workspace execution; the same contract on macOS, Linux and Windows. */\nexport interface WorkspaceHost {\n hostname: string; os: \"darwin\" | \"linux\" | \"windows\" | string; arch: string;\n home: string; directory: string; pid: number;\n}\nexport interface HostResources { cpus: number; memoryMb: number; diskMb: number }\nexport interface WorkspaceFile {\n name: string; path: string; type: \"file\" | \"dir\"; size: number; modifiedAt: string; isIgnored: boolean;\n}\nexport interface WorkspaceFileContent { path: string; content: string; size: number }\nexport interface WorkspaceExecRequest { argv: string[]; directory?: string; input?: string; timeoutMs?: number }\nexport interface WorkspaceExecResult { stdout: string; stderr: string; exitCode: number; truncated?: boolean }\nexport type WorkspaceExecEvent =\n | { kind: \"output\"; channel: \"stdout\" | \"stderr\"; data: string }\n | { kind: \"exit\"; exitCode: number }\n | { kind: \"error\"; error: string };\nexport interface TerminalRequest { id: string; directory?: string; columns: number; rows: number }\nexport interface TerminalState extends TerminalRequest { title: string; running: boolean; exitCode?: number; createdAt: string }\nexport interface TerminalEvent { sequence: number; kind: \"output\" | \"reset\" | \"exit\"; data?: string; state?: TerminalState }\n/** Retry the exact same writer/sequence/data after a lost acknowledgement, never a new sequence. */\nexport interface TerminalInput { writer: string; sequence: number; data: string }\n\nexport class ExecutionApi {\n readonly terminals: TerminalsApi;\n constructor(private readonly client: Mindwire) { this.terminals = new TerminalsApi(client); }\n host(): Promise<WorkspaceHost> { return this.client.http.request(\"GET\", \"/workspace/host\"); }\n resources(): Promise<HostResources> { return this.client.http.request(\"GET\", \"/workspace/resources\"); }\n files(path = \"\", query?: string): Promise<WorkspaceFile[]> {\n return this.client.http.request(\"GET\", \"/workspace/files\", { query: { path, query } });\n }\n read(path: string): Promise<WorkspaceFileContent> { return this.client.http.request(\"GET\", \"/workspace/file\", { query: { path } }); }\n write(path: string, content: string): Promise<{ ok: boolean }> {\n return this.client.http.request(\"PUT\", \"/workspace/file\", { body: { path, content } });\n }\n remove(path: string): Promise<{ ok: boolean }> { return this.client.http.request(\"DELETE\", \"/workspace/file\", { query: { path } }); }\n exec(command: WorkspaceExecRequest, signal?: AbortSignal): Promise<WorkspaceExecResult> {\n return this.client.http.request(\"POST\", \"/workspace/exec\", { body: command, signal });\n }\n /** Output data is base64, preserving partial UTF-8 chunks. Cancelling stops this command. */\n async *stream(command: WorkspaceExecRequest, signal?: AbortSignal): AsyncGenerator<WorkspaceExecEvent> {\n const response = await this.client.http.open(\"POST\", \"/workspace/exec/stream\", { body: command, signal });\n yield* readSSE<WorkspaceExecEvent>(response.body!, signal);\n }\n}\nexport class TerminalsApi {\n constructor(private readonly client: Mindwire) {}\n list(directory?: string): Promise<TerminalState[]> { return this.client.http.request(\"GET\", \"/workspace/terminals\", { query: { directory } }); }\n open(request: TerminalRequest): Promise<TerminalState> { return this.client.http.request(\"POST\", \"/workspace/terminals\", { body: request }); }\n get(id: string): Promise<TerminalState> { return this.client.http.request(\"GET\", this.path(id)); }\n close(id: string): Promise<{ ok: boolean }> { return this.client.http.request(\"DELETE\", this.path(id)); }\n input(id: string, input: TerminalInput): Promise<{ ok: boolean; sequence: number }> {\n return this.client.http.request(\"POST\", `${this.path(id)}/input`, { body: input });\n }\n resize(id: string, columns: number, rows: number): Promise<TerminalState> {\n return this.client.http.request(\"PUT\", `${this.path(id)}/size`, { body: { columns, rows } });\n }\n /** Detaching only closes the subscription. Resume from the last sequence; reset replaces the screen. */\n async *events(id: string, after = 0, signal?: AbortSignal): AsyncGenerator<TerminalEvent> {\n const response = await this.client.http.open(\"GET\", `${this.path(id)}/events`, { query: { after }, signal });\n yield* readSSE<TerminalEvent>(response.body!, signal);\n }\n private path(id: string): string { return `/workspace/terminals/${encodeURIComponent(id)}`; }\n}\n","// Embedded daemon: the default transport. On a server runtime (Node/Bun/Deno) it auto-spawns\n// the bundled `mindwired` binary on a loopback port and hands the SDK its base URL — so\n// `new Mindwire({ agent })` \"just works\" with no server to run. Browsers/edge can't spawn a\n// process, so they must pass `{ baseUrl }` to reach a daemon over HTTP.\nimport { MindwireError } from \"./errors.js\";\nimport { ensureDaemonBinary } from \"./daemon-binary.js\";\n\nexport interface EmbeddedOptions {\n /** Working directory the daemon runs agents in. Defaults to the process cwd. */\n cwd?: string;\n /** Local state file for the embedded daemon. */\n statePath?: string;\n /** Explicit path to the `mindwired` binary (overrides discovery). */\n bin?: string;\n}\n\nexport interface EmbeddedDaemon {\n baseUrl: string;\n token?: string;\n stop(): void;\n}\n\n// Embedded daemons, memoized by config so distinct environments get distinct daemons while identical\n// configs share one. Two zero-config `local()` clients collapse to a single loopback daemon (avoids a\n// double-spawn and a `statePath` collision); a client with its own `cwd`/`statePath`/`bin` gets its\n// own daemon — the mechanism behind \"one instance = one environment; isolate → a new target\".\nconst shared = new Map<string, Promise<EmbeddedDaemon>>();\n\n/** Distinct config ⇒ distinct daemon. `cwd`/`statePath` are the state-affecting knobs; `bin` too. */\nfunction configKey(opts: EmbeddedOptions): string {\n return JSON.stringify([opts.cwd ?? \"\", opts.statePath ?? \"\", opts.bin ?? \"\"]);\n}\n\nexport function startEmbedded(opts: EmbeddedOptions = {}): Promise<EmbeddedDaemon> {\n const key = configKey(opts);\n let daemon = shared.get(key);\n if (!daemon) {\n daemon = spawnDaemon(opts).catch((err) => {\n shared.delete(key); // allow a retry on next call\n throw err;\n });\n shared.set(key, daemon);\n }\n return daemon;\n}\n\nfunction serverRuntime(): typeof globalThis & { process?: any; Bun?: any; Deno?: any } {\n return globalThis as never;\n}\n\nfunction isServerRuntime(): boolean {\n const g = serverRuntime();\n return (\n (typeof g.process !== \"undefined\" && !!g.process.versions?.node) ||\n typeof g.Bun !== \"undefined\" ||\n typeof g.Deno !== \"undefined\"\n );\n}\n\nasync function spawnDaemon(opts: EmbeddedOptions): Promise<EmbeddedDaemon> {\n if (!isServerRuntime()) {\n throw new MindwireError(\n \"MindWire embedded mode needs a server runtime (Node/Bun/Deno). In the browser or an edge runtime, pass { baseUrl } to connect to a running daemon.\",\n );\n }\n\n const { spawn } = await import(\"node:child_process\");\n const net = await import(\"node:net\");\n const proc = serverRuntime().process;\n const { randomBytes } = await import(\"node:crypto\");\n\n const resolved = await resolveBinary(opts.bin);\n const bin = resolved.bin;\n const port = await freePort(net);\n const baseUrl = `http://127.0.0.1:${port}`;\n const token = randomBytes(32).toString(\"hex\");\n\n const child = spawn(bin, [], {\n env: {\n ...proc.env,\n ADDR: `127.0.0.1:${port}`,\n AGENT_CWD: opts.cwd ?? proc.cwd(),\n STATE_PATH: opts.statePath ?? \".mindwire-state.json\",\n DAEMON_TOKEN: token,\n },\n stdio: \"ignore\",\n });\n\n let spawnError: Error | null = null;\n child.on(\"error\", (e: Error) => {\n spawnError = e;\n });\n\n const stop = () => {\n try {\n child.kill();\n } catch {}\n };\n // Best-effort: don't leave the daemon running after the host exits.\n proc.once?.(\"exit\", stop);\n proc.once?.(\"SIGINT\", () => {\n stop();\n proc.exit?.(130);\n });\n\n await waitHealthy(baseUrl, token, () => spawnError, resolved);\n return { baseUrl, token, stop };\n}\n\ninterface ResolvedBinary {\n /** The path (or bare name) we'll hand to spawn(). */\n bin: string;\n /** True if we found the binary on disk; false means we fell back to a bare PATH lookup. */\n found: boolean;\n /** Human-readable list of every location we checked, for a useful not-found error. */\n checked: string[];\n}\n\nasync function resolveBinary(explicit?: string): Promise<ResolvedBinary> {\n const fs = await import(\"node:fs\");\n const path = await import(\"node:path\");\n const proc = serverRuntime().process;\n const ext = proc.platform === \"win32\" ? \".exe\" : \"\";\n const binName = `mindwired${ext}`;\n\n const candidates: string[] = [];\n if (explicit) candidates.push(explicit);\n if (proc.env?.MINDWIRE_DAEMON) candidates.push(proc.env.MINDWIRE_DAEMON);\n\n // Dev / direct bundling: a binary dropped next to the SDK at bin/mindwired-<platform>[.exe].\n try {\n const url = await import(\"node:url\");\n const here = path.dirname(url.fileURLToPath(import.meta.url));\n const named = `mindwired-${proc.platform}-${proc.arch}${ext}`;\n candidates.push(path.join(here, \"bin\", named), path.join(here, \"..\", \"bin\", named));\n } catch {\n // import.meta.url unavailable (e.g. CJS) — skip bundled discovery.\n }\n\n for (const c of candidates) {\n try {\n if (fs.existsSync(c)) return { bin: c, found: true, checked: candidates };\n } catch {}\n }\n const downloaded = await ensureDaemonBinary({ platform: proc.platform, arch: proc.arch });\n return { bin: downloaded, found: true, checked: [...candidates, downloaded] };\n}\n\n// Build the daemon-couldn't-start error. When the binary was never found on disk, enumerate every\n// remedy, including an explicit locally built binary for monorepo development.\nfunction daemonStartError(resolved: ResolvedBinary, cause: Error): string {\n if (!resolved.found) {\n return [\n \"Couldn't start the mindwire daemon: the `mindwired` binary was not found.\",\n `Looked in: ${resolved.checked.join(\", \")}.`,\n \"Fixes:\",\n \" • check GitHub Release access so the SDK can download its matching daemon binary; or\",\n \" • set MINDWIRE_DAEMON to a `mindwired` binary; or\",\n \" • pass { baseUrl } to connect to a daemon you run yourself.\",\n \" • Working inside the mindwire monorepo? Run `go build -o /tmp/mindwired ./daemon/cmd/daemon` and set MINDWIRE_DAEMON.\",\n `(underlying error: ${cause.message})`,\n ].join(\"\\n\");\n }\n return (\n `Couldn't start the mindwire daemon (${resolved.bin}): ${cause.message}. ` +\n \"Set MINDWIRE_DAEMON to the binary path, or pass { baseUrl } to use a running daemon.\"\n );\n}\n\nfunction freePort(net: typeof import(\"node:net\")): Promise<number> {\n return new Promise((resolve, reject) => {\n const srv = net.createServer();\n srv.on(\"error\", reject);\n srv.listen(0, \"127.0.0.1\", () => {\n const addr = srv.address();\n const port = addr && typeof addr === \"object\" ? addr.port : 0;\n srv.close(() => resolve(port));\n });\n });\n}\n\nasync function waitHealthy(\n baseUrl: string,\n token: string,\n getError: () => Error | null,\n resolved: ResolvedBinary,\n timeoutMs = 15000,\n): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const err = getError();\n if (err) {\n throw new MindwireError(daemonStartError(resolved, err), { cause: err });\n }\n try {\n const res = await fetch(`${baseUrl}/healthz`, { headers: { Authorization: `Bearer ${token}` } });\n if (res.ok) return;\n } catch {\n // not up yet\n }\n await new Promise((r) => setTimeout(r, 150));\n }\n throw new MindwireError(\"mindwire embedded daemon did not become healthy in time.\");\n}\n","// The unified destination seam. A **target** is *where the mindwire daemon runs and how the SDK\n// reaches it* — the single axis that used to be three unrelated constructor branches (embedded /\n// remote / sandbox). Every destination is a {@link Target} factory: `local()` (the zero-config\n// default), `remote()`, `ssh()`, `docker()`, `oblien()`, or your own object implementing {@link Target}.\n//\n// A `Target`'s `connect()` does two things: **ensure the daemon** at the destination and return\n// **how to contact it** as a {@link TargetHandle}. The `Http` layer consumes exactly that: a resolved\n// base that may carry a transport-specific `fetch` (used for both unary and SSE), a rotating\n// `getToken`, and per-request `headers` (see http.ts). Nothing in `http.ts` changes to add a backend.\nimport type { FetchLike, TokenGetter } from \"../http.js\";\nimport { startEmbedded, type EmbeddedOptions } from \"../embedded.js\";\nimport type { EnsureEvent } from \"./host.js\";\n\n/**\n * What `connect()` is told about the turn's context. Provisioning knobs (image, port, credentials, …)\n * live on each factory's own config — this is only the client-level context every target shares.\n */\nexport interface ConnectSpec {\n /** The client's default agent, used as the in-daemon `AGENT_TYPE` when the target provisions one. */\n agent?: string;\n /** Receives an {@link EnsureEvent} at each provisioning phase (wired from the client `logger`). */\n onLog?: (e: EnsureEvent) => void;\n}\n\n/**\n * A live transport descriptor a target returns from {@link Target.connect} — everything the SDK's\n * `Http` layer needs to reach the daemon at this destination.\n */\nexport interface TargetHandle {\n /** Stable id of the destination this handle drives (for logging / reuse). */\n id: string;\n /** Base URL for the daemon. With a custom `fetch`, this may be a sentinel the fetch strips. */\n baseUrl: string;\n /**\n * A transport-specific `fetch` for this destination — used for both unary requests and SSE streams.\n * A target supplies it to route every call through its runtime (e.g. Oblien's `rt.proxy`); a\n * direct-HTTP destination (loopback, a published Docker port, an SSH tunnel) omits it and the\n * client's default fetch is used.\n */\n fetch?: FetchLike;\n /** Per-request headers this transport must send (e.g. a proxy-target port). */\n headers?: Record<string, string>;\n /** A static bearer token, if the destination uses one. */\n token?: string;\n /** Fetch the current bearer for a rotating credential; re-mints on `{force:true}`. */\n getToken?: TokenGetter;\n /** Release destination-owned resources (per the factory's `stopOnExit`). Idempotent. */\n stop(): Promise<void>;\n}\n\n/**\n * A destination for the mindwire daemon. Given a {@link ConnectSpec}, provision (or reuse) the\n * environment, ensure a reachable daemon, and return a {@link TargetHandle}. The built-ins are\n * {@link local} / {@link remote} (here) and {@link import(\"./ssh.js\").ssh} /\n * {@link import(\"./docker.js\").docker} / {@link import(\"./oblien.js\").oblien}; a custom backend is\n * just another object with this shape.\n */\nexport interface Target {\n /** Destination id, e.g. `\"local\"` / `\"remote\"` / `\"ssh\"` / `\"docker\"` / `\"oblien\"`. */\n readonly name: string;\n connect(spec: ConnectSpec): Promise<TargetHandle>;\n}\n\n/** Emit one {@link EnsureEvent}, tolerating a throwing logger (see host.ts Risk 8). */\nfunction emit(spec: ConnectSpec, e: EnsureEvent): void {\n if (!spec.onLog) return;\n try {\n spec.onLog(e);\n } catch {\n // A user logger must not be able to break connect().\n }\n}\n\n/**\n * The default destination: an **embedded** daemon on loopback. On a server runtime (Node/Bun/Deno)\n * `connect()` auto-spawns the bundled `mindwired` on a free `127.0.0.1` port and points the SDK at it,\n * so `new Mindwire()` \"just works\" with nothing to deploy.\n *\n * Embedded daemons are memoized by config (see embedded.ts): two zero-config `local()` clients share\n * one loopback daemon (one environment), while `local({ cwd })` / `local({ statePath })` isolate into\n * their own. `stop()` is a **no-op** — the shared daemon is reaped on process exit (Risk 5).\n */\nexport function local(opts: EmbeddedOptions = {}): Target {\n return {\n name: \"local\",\n async connect(spec) {\n const d = await startEmbedded(opts);\n emit(spec, { target: \"local\", phase: \"ready\", message: `embedded daemon on ${d.baseUrl}` });\n return {\n id: d.baseUrl,\n baseUrl: d.baseUrl,\n ...(d.token !== undefined ? { token: d.token } : {}),\n // No-op: the embedded daemon is shared (keyed memoization) and reaped on process exit.\n stop: async () => {},\n };\n },\n };\n}\n\n/** Options for {@link remote}. */\nexport interface RemoteOptions {\n /** Bearer token for the daemon, if it requires one. */\n token?: string;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Custom fetch for this destination (else the client default / global fetch). */\n fetch?: FetchLike;\n}\n\n/**\n * A **remote** daemon you already run, reached over plain HTTP at `baseUrl`. `connect()` returns the\n * transport immediately without a network round-trip — there is no ensure/probe here; `mw.health()`\n * is the real liveness check (Risk 6). Required in the browser / edge runtimes, where a daemon can't\n * be spawned. `stop()` is a no-op (mindwire doesn't own a daemon it didn't start).\n */\nexport function remote(baseUrl: string, opts: RemoteOptions = {}): Target {\n return {\n name: \"remote\",\n async connect(spec) {\n emit(spec, { target: \"remote\", phase: \"skip\", message: `using remote daemon at ${baseUrl}` });\n return {\n id: baseUrl,\n baseUrl,\n ...(opts.token !== undefined ? { token: opts.token } : {}),\n ...(opts.headers !== undefined ? { headers: opts.headers } : {}),\n ...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}),\n stop: async () => {},\n };\n },\n };\n}\n","import { Http, type FetchLike } from \"./http.js\";\nimport { readSSE } from \"./sse.js\";\nimport { Run } from \"./run.js\";\nimport { WorkspaceApi, type ProjectAuth } from \"./workspace.js\";\nimport { SurfacesApi } from \"./surfaces.js\";\nimport { ServiceApi } from \"./service.js\";\nimport { ExecutionApi } from \"./execution.js\";\nimport { ComputerApi } from \"./computer.js\";\nimport { local, type Target, type TargetHandle, type ConnectSpec } from \"./target/index.js\";\nimport type { EnsureEvent } from \"./target/host.js\";\nimport type {\n AgentInfo,\n AuthMethod,\n AuthState,\n AuthStatus,\n Catalog,\n ChatSummary,\n CustomProvider,\n DeleteResult,\n DoctorReport,\n Health,\n MCPServer,\n MemoryDoc,\n MemoryScope,\n Message,\n ModelInfo,\n Notification,\n NotifyChannel,\n NotifyChannelInput,\n NotifyChannelTestResult,\n NotifyConfigInput,\n NotifyConfigStatus,\n NotifyRule,\n NotifyRuleInput,\n ProcessFrame,\n PromptTemplate,\n ResolveOptions,\n Run as RunData,\n SetupStatus,\n HarnessSoftware,\n Stats,\n Subagent,\n TurnOptions,\n} from \"./types.js\";\n\nexport interface MindwireOptions {\n /**\n * Default agent type for agent-scoped calls (e.g. `\"claude-code\"`). When omitted, the daemon\n * uses its own default. Override per call with the `agent` option, or scope a whole client\n * with {@link Mindwire.withAgent}.\n */\n agent?: string;\n /**\n * **Where the daemon runs and how the SDK reaches it.** A {@link Target} factory: {@link local}\n * (the default — an embedded loopback daemon, auto-spawned on a server runtime), {@link remote}\n * (a daemon you already run, required in the browser), or {@link import(\"./target/ssh.js\").ssh} /\n * {@link import(\"./target/docker.js\").docker} / {@link import(\"./target/oblien.js\").oblien} — or any\n * object implementing `Target`. One `new Mindwire` = one target = one daemon = one environment; to\n * isolate agents, create another `Mindwire` with its own target. Omit for the zero-config default.\n */\n target?: Target;\n /**\n * Receives a step {@link EnsureEvent} while a target provisions (connect → probe → upload → launch →\n * ready, or skip). Handy to surface the seconds-long \"upload the daemon + launch + health-poll\" of a\n * fresh SSH/Docker/Oblien box. A throwing callback can't abort provisioning.\n */\n logger?: (e: EnsureEvent) => void;\n /** Custom fetch. Defaults to the global `fetch` (Node 18+, Bun, Deno, browsers). */\n fetch?: FetchLike;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /**\n * Deadline in milliseconds for a single unary request (health, config, `turn` creation, memory,\n * …). Guards against a hung daemon or a dead tunnel blocking a call forever — on expiry the call\n * rejects with {@link import(\"./errors.js\").TimeoutError}. Does **not** apply to the event stream,\n * which is long-lived. Defaults to 120000; pass `0` to disable.\n */\n requestTimeoutMs?: number;\n}\n\n// Reaps the destination behind a transport exactly once, keyed by the shared Http so any\n// `withAgent()` clone can `close()` it. `local`/`remote` handles have no-op `stop()`.\nconst handleByTransport = new WeakMap<Http, Promise<TargetHandle>>();\n\n/** Options accepted by any agent-scoped method to override the client's default agent. */\nexport interface AgentScoped {\n agent?: string;\n}\n\n/**\n * The mindwire client — one typed surface over the daemon, regardless of which coding-agent\n * harness runs behind `?agent=<type>`.\n *\n * **Where** it runs is one option — `target`. By default it's an **embedded** daemon\n * ({@link local}): on a server runtime it auto-spawns the bundled `mindwired` on loopback, so there's\n * nothing to deploy. Point elsewhere with {@link remote} (a daemon you run; also required in the\n * browser), {@link import(\"./target/ssh.js\").ssh}, {@link import(\"./target/docker.js\").docker}, or\n * {@link import(\"./target/oblien.js\").oblien}. One client = one target = one daemon = one environment.\n *\n * ```ts\n * // Local embedded (default) — Node/Bun/Deno:\n * const mw = new Mindwire({ agent: \"claude-code\" });\n *\n * // Remote — or in the browser:\n * const mw = new Mindwire({ target: remote(\"https://mindwire.yourco.com\", { token }) });\n *\n * // A fresh box over SSH, watching it provision:\n * const mw = new Mindwire({ target: ssh({ host, username: \"root\" }), logger: (e) => console.log(e.phase, e.message) });\n * await mw.ensure();\n *\n * const run = await mw.turn({ chatId: \"c1\", message: \"add a health check\" });\n * for await (const ev of run) console.log(ev.type, ev.text ?? \"\");\n * ```\n */\nexport class Mindwire {\n /** Workspace registry: saved agent profiles, projects and chat relationships. */\n readonly workspace: WorkspaceApi;\n readonly surfaces: SurfacesApi;\n readonly service: ServiceApi;\n readonly execution: ExecutionApi;\n readonly computer: ComputerApi;\n readonly http: Http;\n /** The default agent type applied to agent-scoped calls, if set. */\n readonly defaultAgent: string | undefined;\n /** Step-flow auth, scoped to this client's default agent (override per call). */\n readonly auth: AuthApi;\n /** Persistent memory files + saved prompt templates, scoped to this client's default agent. */\n readonly prompts: PromptsApi;\n /** Persistent MCP-server config (the config an agent loads every run), scoped to this client's default agent. */\n readonly mcp: McpApi;\n /** Custom LLM-provider registration (opencode/Codex native config), scoped to this client's default agent. */\n readonly providers: ProvidersApi;\n /** Daemon-driven notification channels + routing rules (webhook/slack/discord/telegram; per-agent/session/global). */\n readonly notify: NotifyApi;\n\n constructor(opts: MindwireOptions = {}) {\n // One path for every destination. The target's `connect()` — called once, memoized by `Http` —\n // provisions the daemon (spawn embedded / connect SSH+Docker+Oblien / nothing for remote) and\n // returns how to reach it: a base URL plus an optional transport `fetch`, rotating `getToken`, and\n // per-request `headers`. The handle is stashed so `close()` can reap it once across `withAgent()`.\n const target = opts.target ?? local();\n const spec: ConnectSpec = { agent: opts.agent, onLog: opts.logger };\n this.http = new Http({\n fetch: opts.fetch,\n headers: opts.headers,\n timeoutMs: opts.requestTimeoutMs,\n resolveBase: () => {\n const h = target.connect(spec);\n handleByTransport.set(this.http, h);\n return h.then((x) => ({\n baseUrl: x.baseUrl,\n token: x.token,\n getToken: x.getToken,\n headers: x.headers,\n fetch: x.fetch,\n }));\n },\n });\n this.defaultAgent = opts.agent;\n this.workspace = new WorkspaceApi(this);\n this.surfaces = new SurfacesApi(this);\n this.service = new ServiceApi(this);\n this.execution = new ExecutionApi(this);\n this.computer = new ComputerApi(this);\n this.auth = new AuthApi(this);\n this.prompts = new PromptsApi(this);\n this.mcp = new McpApi(this);\n this.providers = new ProvidersApi(this);\n this.notify = new NotifyApi(this);\n }\n\n /**\n * Provision the destination and await readiness **now**, rather than lazily on the first request —\n * useful to front-load a fresh SSH/Docker/Oblien box (and to stream its {@link EnsureEvent}s to the\n * `logger`) before the first `turn()`. Idempotent and memoized: repeated `ensure()` calls, and the\n * first real request, all await the same provisioning, so the target connects exactly once.\n */\n async ensure(): Promise<void> {\n await this.http.ready();\n }\n\n /** Return a new client bound to a different default agent (shares the same transport config). */\n withAgent(agent: string): Mindwire {\n const clone = Object.create(Mindwire.prototype) as Mutable<Mindwire>;\n clone.http = this.http;\n clone.defaultAgent = agent;\n clone.workspace = new WorkspaceApi(clone as Mindwire);\n clone.surfaces = new SurfacesApi(clone as Mindwire);\n clone.service = new ServiceApi(clone as Mindwire);\n clone.execution = new ExecutionApi(clone as Mindwire);\n clone.computer = new ComputerApi(clone as Mindwire);\n clone.auth = new AuthApi(clone as Mindwire);\n clone.prompts = new PromptsApi(clone as Mindwire);\n clone.mcp = new McpApi(clone as Mindwire);\n clone.providers = new ProvidersApi(clone as Mindwire);\n clone.notify = new NotifyApi(clone as Mindwire);\n return clone as Mindwire;\n }\n\n /** The `?agent=` value to send for a scoped call: explicit override → client default → none. */\n agentParam(scoped?: AgentScoped): { agent: string } | undefined {\n const a = scoped?.agent ?? this.defaultAgent;\n return a ? { agent: a } : undefined;\n }\n\n /**\n * Release target-owned resources by calling the {@link TargetHandle}'s `stop()` — once, even across\n * {@link withAgent} clones that share the transport. For an `ssh`/`docker`/`oblien` target this reaps\n * the box (tear down the tunnel, stop or delete the container/workspace, per `stopOnExit`); a no-op\n * for `local`/`remote` (embedded self-cleans on process exit; remote is not ours to stop). Safe to\n * call before the target has connected (nothing to reap yet).\n */\n async close(): Promise<void> {\n const handle = handleByTransport.get(this.http);\n if (!handle) return;\n handleByTransport.delete(this.http);\n const h = await handle.catch(() => null);\n if (h) await h.stop();\n }\n\n // ---- health & catalog ----------------------------------------------------\n\n /** `GET /healthz` — authenticated liveness check. Resolves with the daemon's health payload when it is up. */\n health(): Promise<Health> {\n return this.http.request<Health>(\"GET\", \"/healthz\");\n }\n\n /**\n * `GET /stats` — the daemon **process's** resource snapshot (heap in use, memory reserved from the\n * OS, goroutines, GC cycles, cores, platform, uptime). Cheap enough to call on demand — the daemon\n * reads its own Go runtime, not the machine — so a UI can fetch it when a user opens a daemon's page\n * without any background polling. See {@link Stats} for what each field means and doesn't.\n */\n stats(): Promise<Stats> {\n return this.http.request<Stats>(\"GET\", \"/stats\");\n }\n\n /** `GET /catalog` — every agent this daemon binary supports. */\n catalog(): Promise<Catalog> {\n return this.http.request<Catalog>(\"GET\", \"/catalog\");\n }\n\n /** `GET /agent` — capabilities + settings schema + auth methods/status for the selected agent. */\n agent(scoped?: AgentScoped): Promise<AgentInfo> {\n return this.http.request<AgentInfo>(\"GET\", \"/agent\", { query: this.agentParam(scoped) });\n }\n\n /** `GET /agent/software` — installed version, compatibility and approved update target. */\n software(opts: AgentScoped & { refresh?: boolean } = {}): Promise<HarnessSoftware> {\n return this.http.request<HarnessSoftware>(\"GET\", \"/agent/software\", {\n query: { ...this.agentParam(opts), ...(opts.refresh ? { refresh: \"true\" } : {}) },\n });\n }\n\n /**\n * `GET /models` — the models the selected agent can run for the configured account. An empty array\n * is valid (no credentials yet / offline). Throws a 400 {@link ApiError} for an agent whose model is\n * free text (check `capabilities.models` first).\n */\n models(scoped?: AgentScoped): Promise<ModelInfo[]> {\n return this.http.request<ModelInfo[]>(\"GET\", \"/models\", { query: this.agentParam(scoped) });\n }\n\n /** `GET /doctor` — daemon-level health plus the selected agent's own checks. */\n doctor(scoped?: AgentScoped): Promise<DoctorReport> {\n return this.http.request<DoctorReport>(\"GET\", \"/doctor\", { query: this.agentParam(scoped) });\n }\n\n // ---- toolchain setup -----------------------------------------------------\n\n /** `POST /setup` — start the agent's install toolchain (background; poll {@link setupStatus}). */\n setup(scoped?: AgentScoped): Promise<SetupStatus> {\n return this.http.request<SetupStatus>(\"POST\", \"/setup\", { query: this.agentParam(scoped) });\n }\n\n /** `POST /update` — install the catalog's newest tested version compatible with this daemon. */\n update(scoped?: AgentScoped): Promise<SetupStatus> {\n return this.http.request<SetupStatus>(\"POST\", \"/update\", { query: this.agentParam(scoped) });\n }\n\n /** `GET /setup` — current toolchain install progress. */\n setupStatus(scoped?: AgentScoped): Promise<SetupStatus> {\n return this.http.request<SetupStatus>(\"GET\", \"/setup\", { query: this.agentParam(scoped) });\n }\n\n // ---- config --------------------------------------------------------------\n\n /** `GET /config` — the declared, non-secret settings for the agent. */\n getConfig(scoped?: AgentScoped): Promise<Record<string, string>> {\n return this.http.request<Record<string, string>>(\"GET\", \"/config\", {\n query: this.agentParam(scoped),\n });\n }\n\n /** `PUT /config` — merge recognized (non-secret) setting keys. Unknown keys are ignored server-side. */\n async setConfig(values: Record<string, string>, scoped?: AgentScoped): Promise<void> {\n await this.http.request<void>(\"PUT\", \"/config\", {\n query: this.agentParam(scoped),\n body: values,\n });\n }\n\n // ---- chats & history -----------------------------------------------------\n\n /** Native project conversations and drafts, newest first, shared across agents.\n * `cwd` matches an exact directory; `projectId` selects saved membership.\n * `refresh` bypasses the daemon's short native metadata cache.\n */\n chats(options: { cwd?: string; projectId?: string; refresh?: boolean } = {}): Promise<ChatSummary[]> {\n return this.http.request<ChatSummary[]>(\"GET\", \"/chats\", { query: options });\n }\n\n /**\n * `PUT /chats/{id}` — rename a chat. The user title wins over the agent's native auto-title in\n * every listing; an empty title clears the rename (reverting to the native/derived title).\n * Returns the updated summary.\n */\n renameChat(chatId: string, title: string): Promise<ChatSummary> {\n return this.http.request<ChatSummary>(\"PUT\", `/chats/${encodeURIComponent(chatId)}`, {\n body: { title },\n });\n }\n\n /**\n * `DELETE /chats/{id}` — a true, irreversible delete: purges ALL of the chat's mindwire\n * bookkeeping and, for every session the chat mapped to, removes that agent's native transcript\n * (the source of truth). Rejects with a 409 error if a turn is live. Native deletion is\n * best-effort per agent; the result reports what was purged vs. failed.\n */\n deleteChat(chatId: string): Promise<DeleteResult> {\n return this.http.request<DeleteResult>(\"DELETE\", `/chats/${encodeURIComponent(chatId)}`);\n }\n\n /**\n * `POST /chats/{id}/fork` — clone a chat into a new id (generated when `newChatId` is omitted).\n * The fork shares the source's native session until its first turn, which branches it (natively\n * on Claude via `--fork-session`; a fresh session on agents without native fork). Rejects with a\n * 409 if the source has a live turn, 404 if the source is unknown, 400 if the target id is in\n * use. Returns the new chat's summary.\n */\n forkChat(chatId: string, opts: { newChatId?: string } = {}): Promise<ChatSummary> {\n return this.http.request<ChatSummary>(\"POST\", `/chats/${encodeURIComponent(chatId)}/fork`, {\n body: opts.newChatId ? { newChatId: opts.newChatId } : {},\n });\n }\n\n /**\n * `GET /chats/{id}/messages` — a chat's transcript (native when the agent supports it, else\n * the recorded fallback). `limit` caps to the newest N; `before` pages older history.\n */\n messages(\n chatId: string,\n opts: AgentScoped & { limit?: number; before?: string } = {},\n ): Promise<Message[]> {\n const query: Record<string, string | number | undefined> = { ...this.agentParam(opts) };\n if (opts.limit !== undefined) query[\"limit\"] = opts.limit;\n if (opts.before !== undefined) query[\"before\"] = opts.before;\n return this.http.request<Message[]>(\"GET\", `/chats/${encodeURIComponent(chatId)}/messages`, {\n query,\n });\n }\n\n /** `GET /chats/{id}/run` — the latest run for a chat (reattach anchor), or `null` if none yet. */\n async latestRun(chatId: string): Promise<Run | null> {\n const data = await this.http.request<RunData | undefined>(\n \"GET\",\n `/chats/${encodeURIComponent(chatId)}/run`,\n );\n return data ? new Run(this.http, data) : null;\n }\n\n // ---- turns & runs --------------------------------------------------------\n\n /**\n * `POST /turns` — start a turn. Returns a {@link Run} handle you can stream, cancel, or await.\n * Rejects with an {@link ApiError} (409) if a turn is already running for the chat.\n *\n * `mode` defaults to `\"turn\"` — one agent turn that ends when the CLI settles. Pass\n * `mode: \"resolve\"` (with optional {@link ResolveOptions} `resolve` caps) for a global-resolve run\n * that auto-continues the agent's multi-step work until it's done; {@link Mindwire.resolve} is the\n * clearer entry point for that. The returned {@link Run} is then the parent of the run tree.\n */\n async turn(\n input: {\n /** Keep this ID when retrying an unacknowledged turn. Requires turnRequestVersion >= 1. */\n requestId?: string;\n chatId: string;\n message: string;\n cwd?: string;\n options?: TurnOptions;\n mode?: \"turn\" | \"resolve\";\n resolve?: ResolveOptions;\n gitAuth?: ProjectAuth;\n } & AgentScoped,\n ): Promise<Run> {\n const body: {\n requestId?: string;\n chatId: string;\n message: string;\n cwd?: string;\n options?: TurnOptions;\n mode?: \"turn\" | \"resolve\";\n resolve?: ResolveOptions;\n gitAuth?: ProjectAuth;\n } = {\n chatId: input.chatId,\n message: input.message,\n };\n if (input.requestId !== undefined) body.requestId = input.requestId;\n if (input.cwd !== undefined) body.cwd = input.cwd;\n if (input.options !== undefined) body.options = input.options;\n if (input.mode !== undefined) body.mode = input.mode;\n if (input.resolve !== undefined) body.resolve = input.resolve;\n if (input.gitAuth !== undefined) body.gitAuth = input.gitAuth;\n const data = await this.http.request<RunData>(\"POST\", \"/turns\", {\n query: this.agentParam(input),\n body,\n });\n return new Run(this.http, data);\n }\n\n /**\n * `POST /turns {mode:\"resolve\"}` — start a **global-resolve** run: instead of returning after one\n * turn, the daemon holds the task open and auto-continues the agent (resuming on continuable stops\n * and probing for completion) until the work is globally resolved, then aggregates one final result.\n *\n * The returned {@link Run} is the **parent** of a run tree: each auto-continued iteration is a child\n * turn ({@link Run.children}) whose events stream onto the parent's topic, delimited by `continuation`\n * boundary events. `run.wait()` resolves once with the aggregated result; `run.stopReason` /\n * `run.iterations` report how the loop ended. Resolve turns run unattended (no mid-turn approvals)\n * and are bounded by {@link ResolveOptions} caps — see the resolve guide. Rejects with an\n * {@link ApiError} (409) if a turn is already running for the chat.\n */\n async resolve(\n input: {\n requestId?: string;\n chatId: string;\n message: string;\n cwd?: string;\n options?: TurnOptions;\n resolve?: ResolveOptions;\n gitAuth?: ProjectAuth;\n } & AgentScoped,\n ): Promise<Run> {\n return this.turn({ ...input, mode: \"resolve\" });\n }\n\n /** `GET /runs/{id}` — fetch an existing run as a {@link Run} handle. */\n async run(id: string): Promise<Run> {\n const data = await this.http.request<RunData>(\"GET\", `/runs/${encodeURIComponent(id)}`);\n return new Run(this.http, data);\n }\n\n /**\n * `POST /chats/{id}/compact` — run an on-demand conversation compaction as a first-class {@link Run}\n * you can stream or await. The agent folds prior context into a summary it carries forward, emitting\n * a `compaction` event on the stream and recording the boundary in history exactly like an\n * auto-compaction. Optional `instructions` focus the continuation summary (Claude's\n * `/compact <instructions>`; agents that don't honor focus still compact). Rejects with an\n * {@link ApiError}: 400 if the agent doesn't support compaction (`capabilities.compactNow`) or the\n * chat has no conversation yet, 409 if a turn is already running for the chat.\n */\n async compact(chatId: string, opts: { instructions?: string } & AgentScoped = {}): Promise<Run> {\n const data = await this.http.request<RunData>(\n \"POST\",\n `/chats/${encodeURIComponent(chatId)}/compact`,\n {\n query: this.agentParam(opts),\n body: opts.instructions ? { instructions: opts.instructions } : {},\n },\n );\n return new Run(this.http, data);\n }\n\n // ---- notifications -------------------------------------------------------\n\n /** `GET /notify/config` — whether a notification channel is wired (token never returned). */\n getNotifyConfig(): Promise<NotifyConfigStatus> {\n return this.http.request<NotifyConfigStatus>(\"GET\", \"/notify/config\");\n }\n\n /** `PUT /notify/config` — store the provisioned notification channel (daemon-wide). */\n async setNotifyConfig(input: NotifyConfigInput): Promise<void> {\n await this.http.request<void>(\"PUT\", \"/notify/config\", { body: input });\n }\n\n /** `GET /notify/stream` — SSE feed of the daemon's notifications (replay, then live). */\n async *notifications(opts: { signal?: AbortSignal } = {}): AsyncGenerator<Notification> {\n const res = await this.http.open(\"GET\", \"/notify/stream\", {\n ...(opts.signal ? { signal: opts.signal } : {}),\n });\n yield* readSSE<Notification>(res.body!, opts.signal);\n }\n\n // ---- live resources ------------------------------------------------------\n\n /**\n * `GET /processes/stream` — SSE feed of live per-turn CPU/memory, one {@link ProcessFrame} per tick.\n * Sampling is **on demand**: the daemon starts measuring only while a client is connected and stops\n * the instant the last one disconnects, so aborting the `signal` (or ending the loop) tells the\n * daemon to stop — no background work, no leak. Pass `agent` to filter each frame's samples to one\n * agent type. Frames are live snapshots (no replay); an empty `samples` array is a valid keep-alive.\n */\n async *processes(\n opts: { agent?: string; signal?: AbortSignal } = {},\n ): AsyncGenerator<ProcessFrame> {\n const path =\n \"/processes/stream\" +\n (opts.agent ? `?agent=${encodeURIComponent(opts.agent)}` : \"\");\n const res = await this.http.open(\"GET\", path, {\n ...(opts.signal ? { signal: opts.signal } : {}),\n });\n yield* readSSE<ProcessFrame>(res.body!, opts.signal);\n }\n}\n\n/** Step-flow auth (`methods → begin → step → status`) for a scoped agent. */\nexport class AuthApi {\n constructor(private readonly mw: Mindwire) {}\n\n /** `GET /auth/methods` — the options list to present. */\n methods(scoped?: AgentScoped): Promise<AuthMethod[]> {\n return this.mw.http.request<AuthMethod[]>(\"GET\", \"/auth/methods\", {\n query: this.mw.agentParam(scoped),\n });\n }\n\n /** `POST /auth/begin` — start one method (may return `{ url, code, fields, pending }`). */\n begin(method: string, scoped?: AgentScoped): Promise<AuthState> {\n return this.mw.http.request<AuthState>(\"POST\", \"/auth/begin\", {\n query: this.mw.agentParam(scoped),\n body: { method },\n });\n }\n\n /** `POST /auth/step` — submit fields, or poll an interactive login to completion. */\n step(input: Record<string, string>, scoped?: AgentScoped): Promise<AuthState> {\n return this.mw.http.request<AuthState>(\"POST\", \"/auth/step\", {\n query: this.mw.agentParam(scoped),\n body: input,\n });\n }\n\n /** Read one interactive attempt, scoped by the returned AuthState.flowId. */\n poll(flowId: string, scoped?: AgentScoped): Promise<AuthState> {\n return this.step({ _flowId: flowId }, scoped);\n }\n\n /** Cancel this native login without affecting a newer sign-in attempt. */\n cancel(flowId: string, scoped?: AgentScoped): Promise<AuthState> {\n return this.step({ _flowId: flowId, _action: \"cancel\" }, scoped);\n }\n\n /** `GET /auth/status` — is the agent authenticated, and via which method. */\n status(scoped?: AgentScoped): Promise<AuthStatus> {\n return this.mw.http.request<AuthStatus>(\"GET\", \"/auth/status\", {\n query: this.mw.agentParam(scoped),\n });\n }\n\n /** `POST /auth/logout` — disconnect this harness once its running chats finish. */\n logout(scoped?: AgentScoped): Promise<AuthStatus> {\n return this.mw.http.request<AuthStatus>(\"POST\", \"/auth/logout\", {\n query: this.mw.agentParam(scoped),\n });\n }\n}\n\n/**\n * The persistent prompt/memory surface for a scoped agent — the three layers beneath a turn's\n * per-turn `systemPrompt`: the agent's **memory file** (`CLAUDE.md` / `AGENTS.md`) and its saved\n * **prompt templates** (slash-commands / saved prompts). One shape regardless of which agent runs;\n * a call 400s if the selected agent doesn't support the layer.\n *\n * `dir` selects the project-scope working directory (defaults to the daemon cwd); `scope` picks\n * `project` vs `user` (the agent's home config dir). Only agents whose `Capabilities.memory` /\n * `Capabilities.promptTemplates` is set expose these — read that first to decide what to render.\n */\nexport class PromptsApi {\n constructor(private readonly mw: Mindwire) {}\n\n private query(scoped: AgentScoped | undefined, extra?: Record<string, string | undefined>) {\n return { ...this.mw.agentParam(scoped), ...extra };\n }\n\n /**\n * `GET /memory` — the agent's memory file at every supported scope (project + user for both\n * Claude and Codex). Each entry carries the resolved `path` and `exists`; `content` is `\"\"` for\n * an absent file.\n */\n memory(opts: AgentScoped & { dir?: string } = {}): Promise<MemoryDoc[]> {\n return this.mw.http.request<MemoryDoc[]>(\"GET\", \"/memory\", {\n query: this.query(opts, { dir: opts.dir }),\n });\n }\n\n /** `PUT /memory` — write the memory file at `scope`. Returns the resulting {@link MemoryDoc}. */\n setMemory(\n input: { scope: MemoryScope; content: string },\n opts: AgentScoped & { dir?: string } = {},\n ): Promise<MemoryDoc> {\n return this.mw.http.request<MemoryDoc>(\"PUT\", \"/memory\", {\n query: this.query(opts, { dir: opts.dir }),\n body: input,\n });\n }\n\n /**\n * `DELETE /memory` — remove the memory file at `scope` (defaults to `user`). Returns the resulting\n * {@link MemoryDoc} (`exists: false` at the resolved path). Idempotent: deleting an absent file still\n * succeeds.\n */\n deleteMemory(opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {}): Promise<MemoryDoc> {\n return this.mw.http.request<MemoryDoc>(\"DELETE\", \"/memory\", {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n });\n }\n\n /**\n * `GET /prompts` — saved prompt templates across every supported scope (Claude: project + user;\n * Codex: user only). `content` is omitted here; fetch it with {@link get}. A missing project\n * directory yields an empty list for that scope rather than an error.\n */\n list(opts: AgentScoped & { dir?: string } = {}): Promise<PromptTemplate[]> {\n return this.mw.http.request<PromptTemplate[]>(\"GET\", \"/prompts\", {\n query: this.query(opts, { dir: opts.dir }),\n });\n }\n\n /** `GET /prompts/{name}` — one template's full body. Rejects with a 404 `ApiError` if absent. */\n get(name: string, opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {}): Promise<PromptTemplate> {\n return this.mw.http.request<PromptTemplate>(\"GET\", `/prompts/${encodeURIComponent(name)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n });\n }\n\n /** `PUT /prompts/{name}` — create or overwrite a template. Returns the resulting {@link PromptTemplate}. */\n set(\n name: string,\n content: string,\n opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {},\n ): Promise<PromptTemplate> {\n return this.mw.http.request<PromptTemplate>(\"PUT\", `/prompts/${encodeURIComponent(name)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n body: { content },\n });\n }\n\n /**\n * `DELETE /prompts/{name}` — remove one template at `scope` (defaults to `user`). Idempotent:\n * deleting an absent template still succeeds. A traversal name rejects with a 400 `ApiError`.\n */\n async delete(name: string, opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {}): Promise<void> {\n await this.mw.http.request<{ deleted: boolean }>(\"DELETE\", `/prompts/${encodeURIComponent(name)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n });\n }\n\n /**\n * `GET /subagents` — persistent subagent definitions (Claude `.claude/agents/*.md`) across every\n * supported scope. `content` is omitted here (fetch it with {@link subagent}); `meta` is the parsed\n * frontmatter view. Rejects with a 400 `ApiError` on an agent without the subagent-definition module.\n * Distinct from a turn's per-turn `subagents` passthrough — this is the on-disk definition store.\n */\n subagents(opts: AgentScoped & { dir?: string } = {}): Promise<Subagent[]> {\n return this.mw.http.request<Subagent[]>(\"GET\", \"/subagents\", {\n query: this.query(opts, { dir: opts.dir }),\n });\n }\n\n /** `GET /subagents/{name}` — one definition's raw body + parsed meta. 404 `ApiError` if absent. */\n subagent(name: string, opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {}): Promise<Subagent> {\n return this.mw.http.request<Subagent>(\"GET\", `/subagents/${encodeURIComponent(name)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n });\n }\n\n /** `PUT /subagents/{name}` — create or overwrite a definition (raw content is canonical). Returns it. */\n setSubagent(\n name: string,\n content: string,\n opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {},\n ): Promise<Subagent> {\n return this.mw.http.request<Subagent>(\"PUT\", `/subagents/${encodeURIComponent(name)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n body: { content },\n });\n }\n\n /**\n * `DELETE /subagents/{name}` — remove one definition at `scope` (defaults to `user`). Idempotent:\n * deleting an absent definition still succeeds. A traversal name rejects with a 400 `ApiError`.\n */\n async deleteSubagent(\n name: string,\n opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {},\n ): Promise<void> {\n await this.mw.http.request<{ deleted: boolean }>(\"DELETE\", `/subagents/${encodeURIComponent(name)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n });\n }\n}\n\n/**\n * The persistent MCP-server surface for a scoped agent — the servers an agent loads on **every run**\n * from its own on-disk config (Claude's project `.mcp.json` + user `.claude.json`, Codex's\n * `config.toml`), as opposed to a turn's per-turn {@link TurnOptions.mcpServers} overlay. One shape\n * regardless of which agent runs; a call 400s if the selected agent doesn't expose the config\n * (check `capabilities.mcpConfig` first).\n *\n * `scope` picks `project` vs `user` (defaults to `user` — the scope every supporting agent has;\n * Codex is user-only); `dir` selects the project-scope working directory (defaults to the daemon cwd).\n * No secret ever crosses this surface — HTTP auth travels as `bearerTokenEnvVar` (an env-var name).\n */\nexport class McpApi {\n constructor(private readonly mw: Mindwire) {}\n\n private query(scoped: AgentScoped | undefined, extra?: Record<string, string | undefined>) {\n return { ...this.mw.agentParam(scoped), ...extra };\n }\n\n /**\n * `GET /mcp` — every persistent MCP server across the agent's supported scopes, keyed\n * `scope → name → server` (Claude: project + user; Codex: user only). A missing config file yields\n * an empty object for that scope rather than an error.\n */\n list(\n opts: AgentScoped & { dir?: string } = {},\n ): Promise<Partial<Record<MemoryScope, Record<string, MCPServer>>>> {\n return this.mw.http.request<Partial<Record<MemoryScope, Record<string, MCPServer>>>>(\"GET\", \"/mcp\", {\n query: this.query(opts, { dir: opts.dir }),\n });\n }\n\n /** `GET /mcp/{name}` — one server's definition. Rejects with a 404 `ApiError` if it isn't configured. */\n get(name: string, opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {}): Promise<MCPServer> {\n return this.mw.http.request<MCPServer>(\"GET\", `/mcp/${encodeURIComponent(name)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n });\n }\n\n /** `PUT /mcp/{name}` — create or overwrite one server. Returns the stored definition. */\n set(\n name: string,\n server: MCPServer,\n opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {},\n ): Promise<MCPServer> {\n return this.mw.http.request<MCPServer>(\"PUT\", `/mcp/${encodeURIComponent(name)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n body: server,\n });\n }\n\n /** `DELETE /mcp/{name}` — remove one server. Idempotent: deleting an absent server still succeeds. */\n async delete(name: string, opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {}): Promise<void> {\n await this.mw.http.request<{ deleted: boolean }>(\"DELETE\", `/mcp/${encodeURIComponent(name)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n });\n }\n}\n\n/**\n * The custom LLM-provider surface for a scoped agent — the OpenAI-compatible endpoints an agent loads on\n * **every run** from its own native config (opencode's `opencode.json` `provider.<id>`, Codex's\n * `config.toml` `[model_providers.<id>]`). One shape regardless of agent; a call 400s if the selected\n * agent can't materialize one (check `capabilities.customProviders` — Claude uses its gateway auth lane\n * instead). Registered models then appear in {@link Mindwire.models} with `custom:true`.\n *\n * `scope` picks `project` vs `user` (defaults to `user`; opencode/Codex are user-only); `dir` selects the\n * project-scope working directory (defaults to the daemon cwd).\n *\n * SECURITY: secrets are passed write-only via {@link set}'s `apiKey` / `secrets` options and reported only\n * as `hasKey` (plus the stored `envVars` NAMES). They never cross this surface on the way back and are never\n * written literally into any config file — the harness references them through env-var placeholders and the\n * daemon exports them at run time.\n */\nexport class ProvidersApi {\n constructor(private readonly mw: Mindwire) {}\n\n private query(scoped: AgentScoped | undefined, extra?: Record<string, string | undefined>) {\n return { ...this.mw.agentParam(scoped), ...extra };\n }\n\n /**\n * `GET /providers` — every registered custom provider across the agent's supported scopes, keyed\n * `scope → id → provider` (opencode/Codex: user only). A missing config file yields an empty object for\n * that scope rather than an error. `hasKey` reports whether a secret is stored; the key is never returned.\n */\n list(\n opts: AgentScoped & { dir?: string } = {},\n ): Promise<Partial<Record<MemoryScope, Record<string, CustomProvider>>>> {\n return this.mw.http.request<Partial<Record<MemoryScope, Record<string, CustomProvider>>>>(\"GET\", \"/providers\", {\n query: this.query(opts, { dir: opts.dir }),\n });\n }\n\n /** `GET /providers/{id}` — one provider's definition. Rejects with a 404 `ApiError` if it isn't configured. */\n get(id: string, opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {}): Promise<CustomProvider> {\n return this.mw.http.request<CustomProvider>(\"GET\", `/providers/${encodeURIComponent(id)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n });\n }\n\n /**\n * `PUT /providers/{id}` — create or overwrite one provider, returning the stored definition (with\n * `hasKey` and the stored `envVars`). Two write-only secret channels, both optional: `opts.apiKey` is a\n * single key (custom endpoints, single-key catalog brands); `opts.secrets` is a NAME→VALUE map for a\n * catalog provider whose entry declares MULTIPLE env vars (e.g. AWS Bedrock). Omitting both leaves any\n * previously stored secret intact. The path `id` wins over any `id` on the provider value.\n */\n set(\n id: string,\n provider: Omit<CustomProvider, \"id\" | \"hasKey\"> & Partial<Pick<CustomProvider, \"hasKey\">>,\n opts: AgentScoped & { scope?: MemoryScope; dir?: string; apiKey?: string; secrets?: Record<string, string> } = {},\n ): Promise<CustomProvider> {\n return this.mw.http.request<CustomProvider>(\"PUT\", `/providers/${encodeURIComponent(id)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n body: { ...provider, id, apiKey: opts.apiKey, secrets: opts.secrets },\n });\n }\n\n /** `DELETE /providers/{id}` — remove one provider and clear its stored key. Idempotent. */\n async delete(id: string, opts: AgentScoped & { scope?: MemoryScope; dir?: string } = {}): Promise<void> {\n await this.mw.http.request<{ deleted: boolean }>(\"DELETE\", `/providers/${encodeURIComponent(id)}`, {\n query: this.query(opts, { scope: opts.scope, dir: opts.dir }),\n });\n }\n}\n\n/**\n * Daemon-driven notification fan-out: named **channels** (a webhook URL shaped for\n * webhook/Slack/Discord/Telegram, with optional headers, a bearer token, and — for the raw webhook\n * type — an HMAC signing secret) and the **rules** that route matching notifications to them\n * (`global` / per-`agent` / per-`session`, with optional event selection). This is daemon-wide\n * config (NOT agent-scoped): the daemon evaluates every rule against each notification it emits and\n * POSTs to the union of the matched channels — additive over the single {@link Mindwire.setNotifyConfig}\n * webhook.\n *\n * Secrets are **write-only**: a channel read back via {@link channels} never carries the URL, token,\n * secret, or header values — only their presence (and the URL host). On {@link setChannel}, omitting\n * `url`/`token`/`secret` preserves the stored value; send a new value to rotate it.\n */\nexport class NotifyApi {\n constructor(private readonly mw: Mindwire) {}\n\n /** `GET /notify/channels` — every channel, masked (no secrets). */\n channels(): Promise<NotifyChannel[]> {\n return this.mw.http.request<NotifyChannel[]>(\"GET\", \"/notify/channels\");\n }\n\n /** `POST /notify/channels` — create a channel (server-assigns the id). Returns it masked. */\n createChannel(input: NotifyChannelInput): Promise<NotifyChannel> {\n return this.mw.http.request<NotifyChannel>(\"POST\", \"/notify/channels\", { body: input });\n }\n\n /**\n * `PUT /notify/channels/{id}` — update a channel, merge-preserving any omitted secret\n * (`url`/`token`/`secret`). Returns the updated masked channel. 404 `ApiError` if unknown.\n */\n setChannel(id: string, input: NotifyChannelInput): Promise<NotifyChannel> {\n return this.mw.http.request<NotifyChannel>(\"PUT\", `/notify/channels/${encodeURIComponent(id)}`, {\n body: input,\n });\n }\n\n /** `DELETE /notify/channels/{id}` — remove a channel. Idempotent. */\n async deleteChannel(id: string): Promise<void> {\n await this.mw.http.request<{ deleted: boolean }>(\"DELETE\", `/notify/channels/${encodeURIComponent(id)}`);\n }\n\n /**\n * `POST /notify/channels/{id}/test` — deliver a synthetic notification to a channel. A failed\n * delivery is DATA (`{ ok: false, error }`), not a thrown error; only an unknown id rejects (404).\n */\n testChannel(id: string): Promise<NotifyChannelTestResult> {\n return this.mw.http.request<NotifyChannelTestResult>(\n \"POST\",\n `/notify/channels/${encodeURIComponent(id)}/test`,\n );\n }\n\n /** `GET /notify/rules` — every routing rule. */\n rules(): Promise<NotifyRule[]> {\n return this.mw.http.request<NotifyRule[]>(\"GET\", \"/notify/rules\");\n }\n\n /** `POST /notify/rules` — create a rule (server-assigns the id). Returns it. */\n createRule(input: NotifyRuleInput): Promise<NotifyRule> {\n return this.mw.http.request<NotifyRule>(\"POST\", \"/notify/rules\", { body: input });\n }\n\n /** `PUT /notify/rules/{id}` — replace a rule. Returns it. 404 `ApiError` if unknown. */\n setRule(id: string, input: NotifyRuleInput): Promise<NotifyRule> {\n return this.mw.http.request<NotifyRule>(\"PUT\", `/notify/rules/${encodeURIComponent(id)}`, {\n body: input,\n });\n }\n\n /** `DELETE /notify/rules/{id}` — remove a rule. Idempotent. */\n async deleteRule(id: string): Promise<void> {\n await this.mw.http.request<{ deleted: boolean }>(\"DELETE\", `/notify/rules/${encodeURIComponent(id)}`);\n }\n}\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n","import { randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { currentProcessIdentity, processStateAlive, readProcessState, type ProcessIdentity } from \"./process.js\";\n\ninterface Claim { owner: ProcessIdentity; ticket: number | null }\nexport interface ProcessLock { close(): Promise<void> }\n\n/** Serialize lock-file acquisition and stale recovery with a bakery queue. Each\n * waiter owns a unique, atomically published ticket; it never removes another\n * live waiter's ticket. That prevents two stale-lock cleaners deleting a newly\n * acquired lock. Process birth also makes abandoned tickets safe after reboot. */\nexport async function acquireProcessLock(file: string, options: {\n signal?: AbortSignal; onWait?: () => Promise<boolean>;\n} = {}): Promise<ProcessLock | undefined> {\n const owner = await currentProcessIdentity();\n const queue = file + \".queue\", id = randomUUID() + \".json\", claimPath = queue + \"/\" + id;\n await fs.mkdir(queue, { recursive: true, mode: 0o700 });\n let lock: fs.FileHandle | undefined;\n const release = async () => {\n try {\n if (lock) {\n const held = lock; lock = undefined;\n const owned = await held.stat();\n await held.close();\n const current = await fs.stat(file).catch(() => undefined);\n if (current?.ino === owned.ino && current.dev === owned.dev) await fs.rm(file, { force: true });\n }\n } finally { await fs.rm(claimPath, { force: true }); }\n };\n const publish = async (claim: Claim) => {\n const temporary = claimPath + \".tmp\";\n try {\n await fs.writeFile(temporary, JSON.stringify(claim), { mode: 0o600 });\n await fs.rename(temporary, claimPath);\n } finally { await fs.rm(temporary, { force: true }); }\n };\n const claims = async () => {\n const entries: { id: string; claim: Claim }[] = [];\n for (const candidate of await fs.readdir(queue)) {\n if (!candidate.endsWith(\".json\")) continue;\n const content = await fs.readFile(queue + \"/\" + candidate, \"utf8\").catch(error => {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw error;\n });\n if (content === undefined) continue;\n const claim = JSON.parse(content) as Claim;\n if (!claim.owner || claim.ticket !== null && (!Number.isSafeInteger(claim.ticket) || claim.ticket < 1)) {\n throw new Error(\"Invalid Mindwire lock ticket.\");\n }\n if (await processStateAlive(claim.owner)) entries.push({ id: candidate, claim });\n else await fs.rm(queue + \"/\" + candidate, { force: true });\n }\n return entries;\n };\n try {\n options.signal?.throwIfAborted();\n await publish({ owner, ticket: null });\n const ticket = Math.max(0, ...(await claims()).map(entry => entry.claim.ticket ?? 0)) + 1;\n if (!Number.isSafeInteger(ticket)) throw new Error(\"Mindwire's connection queue is full. Retry shortly.\");\n await publish({ owner, ticket });\n const deadline = Date.now() + 30_000;\n while (Date.now() < deadline) {\n options.signal?.throwIfAborted();\n if (await options.onWait?.()) { await release(); return undefined; }\n const ahead = (await claims()).some(entry => entry.id !== id && (entry.claim.ticket === null\n || entry.claim.ticket < ticket || entry.claim.ticket === ticket && entry.id < id));\n if (!ahead) {\n try {\n lock = await fs.open(file, \"wx\", 0o600);\n await lock.writeFile(JSON.stringify(owner));\n return { close: release };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n const holder = await readProcessState(file);\n const age = Date.now() - (await fs.stat(file).catch(() => ({ mtimeMs: Date.now() }))).mtimeMs;\n if (age > 5000 && !await processStateAlive(holder)) { await fs.rm(file, { force: true }); continue; }\n }\n }\n await delay(250, undefined, { signal: options.signal });\n }\n throw new Error(\"Another Mindwire operation is in progress. Try again shortly.\");\n } catch (error) { await release(); throw error; }\n}\n","import { spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport { homedir, networkInterfaces } from \"node:os\";\nimport * as path from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { Mindwire } from \"../client.js\";\nimport { remote } from \"../target/index.js\";\nimport type { ComputerInfo, ComputerRoute } from \"../computer.js\";\nimport type { RelayOptions } from \"./relay.js\";\nimport { processStateAlive, type ProcessState } from \"./process.js\";\nimport { acquireProcessLock } from \"./lock.js\";\n\nexport interface ComputerConfig {\n daemonBin?: string;\n version?: string;\n directory: string;\n host?: string;\n bind: string;\n sshPort: number;\n websocketPort: number;\n relay: RelayOptions;\n}\nexport interface ControllerState extends ProcessState { ready: boolean; phase?: string; error?: string; recovering?: boolean; routes?: ComputerRoute[] }\n\nexport const defaultStateDirectory = () => path.join(homedir(), \".mindwire\", \"computer\");\nexport const defaultComputerConfig = (): ComputerConfig => ({ directory: homedir(), bind: \"0.0.0.0\", sshPort: 8791, websocketPort: 8792, relay: { kind: \"cloudflare\" } });\n\nexport async function readJSON<T>(file: string): Promise<T | undefined> {\n try { return JSON.parse(await fs.readFile(file, \"utf8\")) as T; }\n catch (error) { if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined; throw error; }\n}\nexport async function writeJSON(file: string, value: unknown): Promise<void> {\n const temp = `${file}.${randomUUID()}.tmp`;\n try { await fs.writeFile(temp, JSON.stringify(value) + \"\\n\", { mode: 0o600 }); await fs.rename(temp, file); }\n finally { await fs.rm(temp, { force: true }); }\n}\n\nexport async function computerClient(directory: string): Promise<Mindwire> {\n const runtime = await readJSON<ComputerInfo>(path.join(directory, \"computer-runtime.json\"));\n if (!runtime) throw new Error(\"Mindwire is not running. Run mindwire connect on the computer.\");\n const url = new URL(`http://${runtime.apiAddress}`);\n if (![\"127.0.0.1\", \"[::1]\"].includes(url.hostname) || url.username || url.password) throw new Error(\"Invalid local Mindwire address.\");\n const token = (await fs.readFile(path.join(directory, \"daemon.token\"), \"utf8\")).trim();\n const client = new Mindwire({ target: remote(url.origin, { token }), requestTimeoutMs: 3000 });\n const info = await client.computer.info();\n if (info.computerId !== runtime.computerId || info.pid !== runtime.pid) throw new Error(\"The local Mindwire process changed. Retry the command.\");\n return client;\n}\n\nexport function directRoutes(config: ComputerConfig, port: number): ComputerRoute[] {\n if (config.host) return [{ kind: \"ssh\", host: config.host, port }];\n if (![\"0.0.0.0\", \"::\"].includes(config.bind)) return [{ kind: \"ssh\", host: config.bind, port }];\n const addresses = new Set<string>();\n for (const entries of Object.values(networkInterfaces())) {\n for (const address of entries ?? []) if (address.family === \"IPv4\" && !address.internal) addresses.add(address.address);\n }\n // A wired/LAN address and an existing VPN can coexist. Limit QR size.\n return [...addresses].slice(0, 6).map(host => ({ kind: \"ssh\", host, port }));\n}\n\n/** Launch once; the daemon additionally owns an OS file lock over its identity/state. */\nexport async function ensureComputer(directory: string, cliPath: string, patch: Partial<ComputerConfig> = {},\n onProgress?: (message: string) => void, options: { resume?: boolean; signal?: AbortSignal } = {}): Promise<Mindwire> {\n const resume = options.resume !== false;\n options.signal?.throwIfAborted();\n await fs.mkdir(directory, { recursive: true, mode: 0o700 });\n const stoppedPath = path.join(directory, \"computer-stopped.json\");\n if (resume) await fs.rm(stoppedPath, { force: true });\n else if ((await readJSON<{ stopped: boolean }>(stoppedPath))?.stopped) throw new Error(\"Mindwire was stopped by its owner.\");\n let current: Mindwire | undefined;\n try { current = await computerClient(directory); } catch { /* Cold start or a stale runtime file. */ }\n const configPath = path.join(directory, \"computer-config.json\");\n const previous = await readJSON<ComputerConfig>(configPath);\n const config = { ...defaultComputerConfig(), ...previous, ...patch };\n let launchedPID: number | undefined;\n let launchFailure: Error | undefined;\n const waitUntilReady = async (): Promise<Mindwire> => {\n let phase: string | undefined;\n for (let attempt = 0; attempt < 1200; attempt++) {\n options.signal?.throwIfAborted();\n const controller = await readJSON<ControllerState>(path.join(directory, \"computer-controller.json\"));\n if (launchFailure) throw launchFailure;\n if (launchedPID && controller?.pid !== launchedPID) { await delay(250); continue; }\n if (controller?.error && !controller.recovering) throw new Error(controller.error);\n if (controller?.ready && await processStateAlive(controller)) return computerClient(directory);\n if (controller?.phase && controller.phase !== phase) { phase = controller.phase; onProgress?.(phase); }\n await delay(250);\n }\n throw new Error(`Mindwire did not finish starting. Inspect ${path.join(directory, \"computer.log\")}.`);\n };\n if (current) {\n if (Object.keys(patch).some(key => JSON.stringify(config[key as keyof ComputerConfig]) !== JSON.stringify(previous?.[key as keyof ComputerConfig]))) {\n throw new Error(\"Mindwire is running with different connection settings. Run mindwire stop when idle, then retry with the new settings.\");\n }\n // The API may be healthy while the internet helper is still downloading.\n // Pairing must wait for its routes, not expose a partly prepared computer.\n const controller = await readJSON<ControllerState>(path.join(directory, \"computer-controller.json\"));\n if (await processStateAlive(controller)) return waitUntilReady();\n // The controller can crash while its daemon and tunnel remain healthy.\n // Start a new owner below; it adopts those processes without restarting them.\n }\n const lockPath = path.join(directory, \"launch.lock\");\n const lock = await acquireProcessLock(lockPath, {\n signal: options.signal,\n onWait: async () => {\n const controller = await readJSON<ControllerState>(path.join(directory, \"computer-controller.json\"));\n if (await processStateAlive(controller)) {\n const saved = await readJSON<ComputerConfig>(configPath);\n if (Object.keys(patch).some(key => JSON.stringify(patch[key as keyof ComputerConfig]) !== JSON.stringify(saved?.[key as keyof ComputerConfig]))) {\n throw new Error(\"Another start used different connection settings. Stop Mindwire when idle before changing them.\");\n }\n return true;\n }\n return false;\n },\n });\n if (!lock) return waitUntilReady();\n try {\n if (!resume && (await readJSON<{ stopped: boolean }>(stoppedPath))?.stopped) throw new Error(\"Mindwire was stopped by its owner.\");\n let existing: Mindwire | undefined;\n try { existing = await computerClient(directory); } catch { /* The other launch may still be booting. */ }\n if (existing) {\n const saved = await readJSON<ComputerConfig>(configPath);\n if (Object.keys(patch).some(key => JSON.stringify(patch[key as keyof ComputerConfig]) !== JSON.stringify(saved?.[key as keyof ComputerConfig]))) {\n throw new Error(\"Another start used different connection settings. Stop Mindwire when idle before changing them.\");\n }\n const controller = await readJSON<ControllerState>(path.join(directory, \"computer-controller.json\"));\n if (await processStateAlive(controller)) return waitUntilReady();\n }\n const controller = await readJSON<ControllerState>(path.join(directory, \"computer-controller.json\"));\n if (await processStateAlive(controller)) {\n if (controller?.error && !controller.recovering) throw new Error(controller.error);\n } else {\n await writeJSON(configPath, config);\n const log = await fs.open(path.join(directory, \"computer.log\"), \"a\", 0o600);\n try {\n const child = spawn(process.execPath, [cliPath, \"_serve\", \"--state-dir\", directory], {\n detached: true, stdio: [\"ignore\", log.fd, log.fd], windowsHide: true,\n });\n await new Promise<void>((resolve, reject) => { child.once(\"spawn\", resolve); child.once(\"error\", reject); });\n launchedPID = child.pid;\n child.on(\"exit\", () => { launchFailure = new Error(`The computer controller stopped. Inspect ${path.join(directory, \"computer.log\")}.`); });\n child.unref();\n } finally { await log.close(); }\n }\n return await waitUntilReady();\n } finally { await lock.close(); }\n}\n\nexport async function superviseComputer(directory: string): Promise<void> {\n const controller = await import(\"./controller.js\");\n await controller.superviseComputer(directory);\n}\n\nexport async function stopComputer(directory: string, force = false): Promise<void> {\n const client = await computerClient(directory);\n const controller = await readJSON<ControllerState>(path.join(directory, \"computer-controller.json\"));\n if (!await processStateAlive(controller)) throw new Error(\"The Mindwire controller is not running.\");\n const lease = force ? undefined : await client.service.acquireUpdate();\n try {\n await writeJSON(path.join(directory, \"computer-stopped.json\"), { stopped: true });\n if (!await processStateAlive(controller)) throw new Error(\"The Mindwire controller changed. Retry the command.\");\n process.kill(controller!.pid, \"SIGTERM\");\n } catch (error) {\n await fs.rm(path.join(directory, \"computer-stopped.json\"), { force: true });\n if (lease) await client.service.releaseUpdate(lease.id);\n throw error;\n }\n for (let attempt = 0; attempt < 80; attempt++) { if (!await processStateAlive(controller)) return; await delay(250); }\n throw new Error(\"Mindwire is still stopping. Check computer.log.\");\n}\n"]}
|