mindwire 0.1.19 → 0.1.22

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/cli.js ADDED
@@ -0,0 +1,2395 @@
1
+ #!/usr/bin/env node
2
+ import { MindwireError, TimeoutError, ApiError, RunFailedError, binaryCacheDirectory, cachedExecutable, verifyReleaseBytes, cacheExecutable, executableChecksum } from './chunk-PFYKJ6LX.js';
3
+ import { promisify, parseArgs } from 'util';
4
+ import { pathToFileURL, fileURLToPath } from 'url';
5
+ import * as path2 from 'path';
6
+ import { createHash, randomBytes, randomUUID } from 'crypto';
7
+ import { createInterface } from 'readline/promises';
8
+ import { setTimeout as setTimeout$1 } from 'timers/promises';
9
+ import { execFile, execFileSync, spawn } from 'child_process';
10
+ import * as fs from 'fs/promises';
11
+ import { readFile, mkdtemp, writeFile, rm } from 'fs/promises';
12
+ import { homedir, networkInterfaces, tmpdir } from 'os';
13
+
14
+ // src/computer.ts
15
+ var ComputerApi = class {
16
+ constructor(client) {
17
+ this.client = client;
18
+ }
19
+ client;
20
+ info() {
21
+ return this.client.http.request("GET", "/computer");
22
+ }
23
+ setRoutes(routes) {
24
+ return this.client.http.request("PUT", "/computer/routes", { body: { routes } });
25
+ }
26
+ updateStatus() {
27
+ return this.client.http.request("GET", "/computer/update");
28
+ }
29
+ requestUpdate(version) {
30
+ return this.client.http.request("POST", "/computer/update", { body: { version } });
31
+ }
32
+ invite(routes) {
33
+ return this.client.http.request("POST", "/computer/pairings", { body: { routes } });
34
+ }
35
+ pairing(id) {
36
+ return this.client.http.request("GET", `/computer/pairings/${encodeURIComponent(id)}`);
37
+ }
38
+ completePairing(id, requestId) {
39
+ return this.client.http.request("POST", `/computer/pairings/${encodeURIComponent(id)}/complete`, { body: { requestId } });
40
+ }
41
+ decide(id, requestId, approve) {
42
+ return this.client.http.request("POST", `/computer/pairings/${encodeURIComponent(id)}/decision`, { body: { requestId, approve } });
43
+ }
44
+ devices() {
45
+ return this.client.http.request("GET", "/computer/devices");
46
+ }
47
+ revoke(id) {
48
+ return this.client.http.request("DELETE", `/computer/devices/${encodeURIComponent(id)}`);
49
+ }
50
+ };
51
+ function computerPairingURI(invitation) {
52
+ const bytes = new TextEncoder().encode(JSON.stringify(invitation));
53
+ let binary = "";
54
+ for (const byte of bytes) binary += String.fromCharCode(byte);
55
+ const encoded = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
56
+ return `mindwire://pair?v=1#${encoded}`;
57
+ }
58
+
59
+ // src/version.ts
60
+ var SDK_VERSION = "0.1.22" ;
61
+
62
+ // src/http.ts
63
+ var DEFAULT_TIMEOUT_MS = 12e4;
64
+ function isAbortError(e) {
65
+ return typeof e === "object" && e !== null && e.name === "AbortError";
66
+ }
67
+ var Http = class {
68
+ fetchImpl;
69
+ baseHeaders;
70
+ resolver;
71
+ timeoutMs;
72
+ cached = null;
73
+ pending = null;
74
+ constructor(opts) {
75
+ const f = opts.fetch ?? globalThis.fetch;
76
+ if (!f) {
77
+ throw new MindwireError(
78
+ "mindwire: no global fetch found \u2014 pass a `fetch` implementation in the client options"
79
+ );
80
+ }
81
+ this.fetchImpl = f;
82
+ this.baseHeaders = { ...opts.headers };
83
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
84
+ if (opts.baseUrl) {
85
+ const base = { baseUrl: opts.baseUrl.replace(/\/+$/, ""), token: opts.token };
86
+ this.resolver = async () => base;
87
+ } else if (opts.resolveBase) {
88
+ const rb = opts.resolveBase;
89
+ this.resolver = async () => {
90
+ const r = await rb();
91
+ return {
92
+ baseUrl: r.baseUrl.replace(/\/+$/, ""),
93
+ token: r.token ?? opts.token,
94
+ getToken: r.getToken,
95
+ headers: r.headers,
96
+ fetch: r.fetch
97
+ };
98
+ };
99
+ } else {
100
+ throw new MindwireError("mindwire: Http requires a baseUrl or a resolveBase");
101
+ }
102
+ }
103
+ /**
104
+ * One fetch, with raw network failures wrapped as {@link MindwireError} so callers see a typed
105
+ * SDK error instead of a bare `TypeError: fetch failed`. An abort (the request's own signal, or
106
+ * our timeout controller) is re-thrown untouched — `fetchWithTimeout` classifies it.
107
+ */
108
+ async fetchOnce(f, url, init, method, path4) {
109
+ try {
110
+ return await f(url, init);
111
+ } catch (e) {
112
+ const aborted = init.signal?.aborted ?? false;
113
+ if (aborted || isAbortError(e)) throw e;
114
+ throw new MindwireError(`mindwire: ${method} ${path4} \u2014 network request failed`, { cause: e });
115
+ }
116
+ }
117
+ /**
118
+ * `fetchOnce` plus a timeout that composes with the caller's `signal`. A hand-rolled controller
119
+ * (not `AbortSignal.timeout`/`AbortSignal.any`, which need Node 20.3+/18.17+) fires after
120
+ * `timeoutMs`; whichever aborts first wins. Timeout → {@link TimeoutError}; the caller's own abort
121
+ * propagates as-is (its `reason`). `timeoutMs<=0` disables the deadline entirely.
122
+ */
123
+ async fetchWithTimeout(f, url, init, userSignal, method, path4) {
124
+ if (!this.timeoutMs || this.timeoutMs <= 0) {
125
+ return this.fetchOnce(f, url, { ...init, ...userSignal ? { signal: userSignal } : {} }, method, path4);
126
+ }
127
+ const ctrl = new AbortController();
128
+ const onAbort = () => ctrl.abort(userSignal?.reason);
129
+ if (userSignal) {
130
+ if (userSignal.aborted) ctrl.abort(userSignal.reason);
131
+ else userSignal.addEventListener("abort", onAbort, { once: true });
132
+ }
133
+ let timedOut = false;
134
+ const timer = setTimeout(() => {
135
+ timedOut = true;
136
+ ctrl.abort();
137
+ }, this.timeoutMs);
138
+ try {
139
+ return await this.fetchOnce(f, url, { ...init, signal: ctrl.signal }, method, path4);
140
+ } catch (e) {
141
+ if (timedOut) throw new TimeoutError(method, path4, this.timeoutMs);
142
+ if (userSignal?.aborted) throw userSignal.reason ?? e;
143
+ throw e;
144
+ } finally {
145
+ clearTimeout(timer);
146
+ if (userSignal) userSignal.removeEventListener("abort", onAbort);
147
+ }
148
+ }
149
+ /**
150
+ * The bearer token for the next request. Prefers the transport's dynamic `getToken` (which
151
+ * caches and mints on demand); falls back to the static token resolved at base time. `force`
152
+ * asks the getter to re-mint — used once on a 401 before retrying.
153
+ */
154
+ async authToken(base, force) {
155
+ if (base.getToken) {
156
+ const t = await base.getToken(force ? { force: true } : void 0);
157
+ return t ?? base.token;
158
+ }
159
+ return base.token;
160
+ }
161
+ base() {
162
+ if (this.cached) return Promise.resolve(this.cached);
163
+ if (!this.pending) {
164
+ this.pending = this.resolver().then((b) => this.cached = b).catch((err) => {
165
+ this.pending = null;
166
+ throw err;
167
+ });
168
+ }
169
+ return this.pending;
170
+ }
171
+ /**
172
+ * Resolve the base eagerly and memoize it — provisions the transport (spawns the embedded daemon,
173
+ * connects the sandbox/SSH/Docker target, …) now instead of on the first request. Idempotent: this
174
+ * awaits the *same* memoized promise the first `request()`/`open()` awaits, so the target's
175
+ * `connect()` fires exactly once. Backs {@link import("./client.js").Mindwire.ensure}.
176
+ */
177
+ async ready() {
178
+ await this.base();
179
+ }
180
+ url(baseUrl, path4, query) {
181
+ const u = new URL(baseUrl + (path4.startsWith("/") ? path4 : `/${path4}`));
182
+ if (query) {
183
+ for (const [k, v] of Object.entries(query)) {
184
+ if (v !== void 0) u.searchParams.set(k, String(v));
185
+ }
186
+ }
187
+ return u.toString();
188
+ }
189
+ headers(token, extra, hasBody = false) {
190
+ const h = { Accept: "application/json", ...this.baseHeaders, ...extra };
191
+ if (token) h["Authorization"] = `Bearer ${token}`;
192
+ if (hasBody) h["Content-Type"] = "application/json";
193
+ return h;
194
+ }
195
+ async request(method, path4, init = {}) {
196
+ const base = await this.base();
197
+ const hasBody = init.body !== void 0;
198
+ const url = this.url(base.baseUrl, path4, init.query);
199
+ const extra = { ...base.headers, ...init.headers };
200
+ const f = base.fetch ?? this.fetchImpl;
201
+ const send = async (force) => this.fetchWithTimeout(
202
+ f,
203
+ url,
204
+ {
205
+ method,
206
+ headers: this.headers(await this.authToken(base, force), extra, hasBody),
207
+ body: hasBody ? JSON.stringify(init.body) : void 0
208
+ },
209
+ init.signal,
210
+ method,
211
+ path4
212
+ );
213
+ let res = await send(false);
214
+ if (res.status === 401 && base.getToken) res = await send(true);
215
+ if (!res.ok) throw await this.toApiError(method, res);
216
+ if (res.status === 204) return void 0;
217
+ const text = await res.text();
218
+ if (text === "") return void 0;
219
+ try {
220
+ return JSON.parse(text);
221
+ } catch (e) {
222
+ throw new MindwireError(`mindwire: ${method} ${path4} returned a non-JSON body`, { cause: e });
223
+ }
224
+ }
225
+ /** Open a streaming response (SSE). Caller owns the body. */
226
+ async open(method, path4, init = {}) {
227
+ const base = await this.base();
228
+ const url = this.url(base.baseUrl, path4, init.query);
229
+ const extra = { Accept: "text/event-stream", ...base.headers, ...init.headers };
230
+ const f = base.fetch ?? this.fetchImpl;
231
+ const send = async (force) => this.fetchOnce(
232
+ f,
233
+ url,
234
+ {
235
+ method,
236
+ headers: this.headers(await this.authToken(base, force), extra, init.body !== void 0),
237
+ ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
238
+ ...init.signal ? { signal: init.signal } : {}
239
+ },
240
+ method,
241
+ path4
242
+ );
243
+ let res = await send(false);
244
+ if (res.status === 401 && base.getToken) res = await send(true);
245
+ if (!res.ok) throw await this.toApiError(method, res);
246
+ if (!res.body)
247
+ throw new MindwireError(`mindwire: ${method} ${path4} returned no response body to stream`);
248
+ return res;
249
+ }
250
+ async toApiError(method, res) {
251
+ let body = "";
252
+ try {
253
+ const text = await res.text();
254
+ try {
255
+ body = text ? JSON.parse(text) : "";
256
+ } catch {
257
+ body = text;
258
+ }
259
+ } catch {
260
+ }
261
+ return new ApiError({ status: res.status, url: res.url, method, body });
262
+ }
263
+ };
264
+
265
+ // src/sse.ts
266
+ async function* readSSE(body, signal) {
267
+ const reader = body.getReader();
268
+ const decoder = new TextDecoder();
269
+ let buffer = "";
270
+ const onAbort = () => void reader.cancel().catch(() => {
271
+ });
272
+ if (signal) {
273
+ if (signal.aborted) {
274
+ await reader.cancel().catch(() => {
275
+ });
276
+ return;
277
+ }
278
+ signal.addEventListener("abort", onAbort, { once: true });
279
+ }
280
+ try {
281
+ for (; ; ) {
282
+ const { done, value } = await reader.read();
283
+ if (done) break;
284
+ buffer += decoder.decode(value, { stream: true });
285
+ let sep;
286
+ while ((sep = indexOfBlankLine(buffer)) !== -1) {
287
+ const rawEvent = buffer.slice(0, sep);
288
+ buffer = buffer.slice(sepEnd(buffer, sep));
289
+ const payload2 = parseEvent(rawEvent);
290
+ if (payload2 !== void 0) yield JSON.parse(payload2);
291
+ }
292
+ }
293
+ const payload = parseEvent(buffer);
294
+ if (payload !== void 0) yield JSON.parse(payload);
295
+ } finally {
296
+ if (signal) signal.removeEventListener("abort", onAbort);
297
+ await reader.cancel().catch(() => {
298
+ });
299
+ reader.releaseLock();
300
+ }
301
+ }
302
+ function indexOfBlankLine(s) {
303
+ const a = s.indexOf("\n\n");
304
+ const b = s.indexOf("\r\n\r\n");
305
+ if (a === -1) return b;
306
+ if (b === -1) return a;
307
+ return Math.min(a, b);
308
+ }
309
+ function sepEnd(s, idx) {
310
+ return s.startsWith("\r\n\r\n", idx) ? idx + 4 : idx + 2;
311
+ }
312
+ function parseEvent(block) {
313
+ const lines = block.split(/\r\n|\n/);
314
+ const data = [];
315
+ for (const line of lines) {
316
+ if (line === "" || line.startsWith(":")) continue;
317
+ const colon = line.indexOf(":");
318
+ const field = colon === -1 ? line : line.slice(0, colon);
319
+ if (field !== "data") continue;
320
+ let value = colon === -1 ? "" : line.slice(colon + 1);
321
+ if (value.startsWith(" ")) value = value.slice(1);
322
+ data.push(value);
323
+ }
324
+ if (data.length === 0) return void 0;
325
+ return data.join("\n");
326
+ }
327
+
328
+ // src/run.ts
329
+ var TERMINAL = /* @__PURE__ */ new Set(["done", "error", "cancelled"]);
330
+ var Run = class _Run {
331
+ data;
332
+ http;
333
+ constructor(http, data) {
334
+ this.http = http;
335
+ this.data = data;
336
+ }
337
+ get id() {
338
+ return this.data.id;
339
+ }
340
+ get chatId() {
341
+ return this.data.chatId;
342
+ }
343
+ get agent() {
344
+ return this.data.agent;
345
+ }
346
+ get status() {
347
+ return this.data.status;
348
+ }
349
+ /** `"resolve"` on the parent of a global-resolve run; `undefined` for an ordinary turn. */
350
+ get kind() {
351
+ return this.data.kind;
352
+ }
353
+ /** On a child iteration of a resolve run, the id of its parent resolve run; else `undefined`. */
354
+ get parentId() {
355
+ return this.data.parentId;
356
+ }
357
+ /** Parent of a resolve run only: why the loop ended (`"done"` | `"capped"` | `"error"` | …). */
358
+ get stopReason() {
359
+ return this.data.stopReason;
360
+ }
361
+ /** Parent of a resolve run only: how many child turns the loop ran. */
362
+ get iterations() {
363
+ return this.data.iterations;
364
+ }
365
+ /** The latest known run record. */
366
+ get value() {
367
+ return this.data;
368
+ }
369
+ /** Unified SSE event stream: replay buffer, then live events, then close. */
370
+ async *stream(opts = {}) {
371
+ const cursor = opts.after === void 0 ? "" : `?after=${encodeURIComponent(opts.after)}`;
372
+ const res = await this.http.open("GET", `/runs/${encodeURIComponent(this.id)}/stream${cursor}`, {
373
+ ...opts.signal ? { signal: opts.signal } : {}
374
+ });
375
+ for await (const ev of readSSE(res.body, opts.signal)) {
376
+ if (!opts.includeOpenSentinel && ev.type === "status" && ev.meta?.["stream"] === "open") {
377
+ continue;
378
+ }
379
+ yield ev;
380
+ }
381
+ }
382
+ /** `for await (const ev of run)` — sugar for `run.stream()`. */
383
+ [Symbol.asyncIterator]() {
384
+ return this.stream();
385
+ }
386
+ /** Cancel the in-flight turn (kills the underlying agent process). */
387
+ async cancel() {
388
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/cancel`);
389
+ }
390
+ /**
391
+ * Answer a pending permission, question or plan. Message-mode questions remain answerable
392
+ * after completion; the daemon steers or resumes the conversation. Read the chat's latest
393
+ * run after replying to a completed run. Requires the agent's `respond` capability.
394
+ */
395
+ async respond(input = {}) {
396
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/respond`, { body: input });
397
+ }
398
+ /**
399
+ * Steer a follow-up message into the running turn without cancelling it. Requires the agent's
400
+ * `input` capability.
401
+ */
402
+ async sendInput(text) {
403
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/input`, { body: { text } });
404
+ }
405
+ /**
406
+ * Soft-stop the running turn (ask the agent to halt current work) without the hard process kill
407
+ * {@link Run.cancel} does — the turn stays open for a follow-up via {@link Run.sendInput}.
408
+ * Requires the agent's `interrupt` capability.
409
+ */
410
+ async interrupt() {
411
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/interrupt`);
412
+ }
413
+ /**
414
+ * Switch the model of the live turn. An empty/omitted `model` resets the turn to the agent/CLI
415
+ * default. Only meaningful on a persistent (non-bypass) turn; on a one-shot turn it is a
416
+ * best-effort no-op. Requires the agent's `setModel` capability.
417
+ */
418
+ async setModel(model) {
419
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/set-model`, {
420
+ body: { model: model ?? "" }
421
+ });
422
+ }
423
+ /**
424
+ * Switch the live permission mode using a value from the agent's settings schema.
425
+ * Resolves after the harness acknowledges the change; rejects if it cannot apply it.
426
+ * Requires `setPermissionMode`. Codex settings apply on the next turn instead.
427
+ */
428
+ async setPermissionMode(mode) {
429
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/set-permission-mode`, {
430
+ body: { mode }
431
+ });
432
+ }
433
+ /**
434
+ * `GET /runs/{id}/children` — the child iterations of a global-resolve run, oldest→newest, each as
435
+ * its own {@link Run} handle. An ordinary turn (or a resolve that ran a single iteration) returns an
436
+ * empty array. Use it to inspect the run tree a {@link Mindwire.resolve} produced.
437
+ */
438
+ async children() {
439
+ const data = await this.http.request(
440
+ "GET",
441
+ `/runs/${encodeURIComponent(this.id)}/children`
442
+ );
443
+ return data.map((d) => new _Run(this.http, d));
444
+ }
445
+ /** Re-fetch the run record from the daemon and update this handle. */
446
+ async refresh() {
447
+ this.data = await this.http.request("GET", `/runs/${encodeURIComponent(this.id)}`);
448
+ return this.data;
449
+ }
450
+ /** Restore current output once, then follow with `stream({ after: snapshot.sequence })`. */
451
+ async snapshot() {
452
+ const snapshot = await this.http.request("GET", `/runs/${encodeURIComponent(this.id)}/snapshot`);
453
+ this.data = snapshot.run;
454
+ return snapshot;
455
+ }
456
+ /**
457
+ * Consume the event stream to completion. Returns the final run record and the `result`
458
+ * event's summary (if any). Throws {@link RunFailedError} on an `error`/`cancelled` outcome
459
+ * unless `throwOnError` is set to `false`.
460
+ */
461
+ async wait(opts = {}) {
462
+ let result;
463
+ let streamError;
464
+ for await (const ev of this.stream(opts)) {
465
+ if (ev.type === "result") result = ev.result;
466
+ else if (ev.type === "error") streamError = ev.error;
467
+ }
468
+ const run = await this.refresh();
469
+ if (opts.throwOnError !== false) {
470
+ if (TERMINAL.has(run.status)) {
471
+ if (run.status !== "done") {
472
+ throw new RunFailedError(run.id, run.status, run.error ?? streamError);
473
+ }
474
+ } else {
475
+ throw new RunFailedError(
476
+ run.id,
477
+ run.status,
478
+ streamError ?? "event stream ended before the run reached a terminal state"
479
+ );
480
+ }
481
+ }
482
+ return result !== void 0 ? { run, result } : { run };
483
+ }
484
+ };
485
+
486
+ // src/workspace.ts
487
+ var ProjectOperationsApi = class {
488
+ constructor(mw) {
489
+ this.mw = mw;
490
+ }
491
+ mw;
492
+ async list(activeOnly = false) {
493
+ const response = await this.mw.http.request("GET", "/workspace/operations", {
494
+ query: { active: activeOnly }
495
+ });
496
+ return response.operations;
497
+ }
498
+ get(id) {
499
+ return this.mw.http.request("GET", `/workspace/operations/${encodeURIComponent(id)}`);
500
+ }
501
+ cancel(id) {
502
+ return this.mw.http.request("POST", `/workspace/operations/${encodeURIComponent(id)}/cancel`);
503
+ }
504
+ retry(id, auth) {
505
+ return this.mw.http.request("POST", `/workspace/operations/${encodeURIComponent(id)}/retry`, { body: { auth } });
506
+ }
507
+ /** The first event is the current snapshot, then live changes. Reconnecting never replays old
508
+ * progress. Breaking the loop/aborting detaches the observer; cancel(id) explicitly stops work.
509
+ */
510
+ async *watch(id, opts = {}) {
511
+ const controller = new AbortController();
512
+ const abort = () => controller.abort();
513
+ opts.signal?.addEventListener("abort", abort, { once: true });
514
+ if (opts.signal?.aborted) controller.abort();
515
+ try {
516
+ const response = await this.mw.http.open("GET", `/workspace/operations/${encodeURIComponent(id)}/stream`, {
517
+ signal: controller.signal
518
+ });
519
+ let sequence = -1;
520
+ for await (const operation of readSSE(response.body, controller.signal)) {
521
+ if (operation.sequence > sequence) {
522
+ sequence = operation.sequence;
523
+ yield operation;
524
+ }
525
+ }
526
+ } finally {
527
+ controller.abort();
528
+ opts.signal?.removeEventListener("abort", abort);
529
+ }
530
+ }
531
+ };
532
+ var WorkspaceCollection = class {
533
+ constructor(mw, kind) {
534
+ this.mw = mw;
535
+ this.kind = kind;
536
+ }
537
+ mw;
538
+ kind;
539
+ /** Create with a stable client-generated ID. For updates, supply the record's last revision. */
540
+ put(id, record, expectedRevision) {
541
+ return this.mw.http.request("PUT", `/workspace/${this.kind}/${encodeURIComponent(id)}`, {
542
+ body: { record, expectedRevision }
543
+ });
544
+ }
545
+ /** Remove membership and dependent chat links. Files and native transcripts are retained.
546
+ * Use deleteChat() for an explicit transcript purge. Running chats reject removal with 409.
547
+ */
548
+ delete(id, revision) {
549
+ return this.mw.http.request("DELETE", `/workspace/${this.kind}/${encodeURIComponent(id)}`, {
550
+ query: { revision }
551
+ });
552
+ }
553
+ };
554
+ var WorkspaceApi = class {
555
+ constructor(mw) {
556
+ this.mw = mw;
557
+ this.git = new GitAccessApi(mw);
558
+ this.operations = new ProjectOperationsApi(mw);
559
+ this.agents = new WorkspaceCollection(mw, "agents");
560
+ this.projects = new WorkspaceCollection(mw, "projects");
561
+ this.chats = new WorkspaceCollection(mw, "chats");
562
+ }
563
+ mw;
564
+ git;
565
+ operations;
566
+ agents;
567
+ projects;
568
+ chats;
569
+ snapshot() {
570
+ return this.mw.http.request("GET", "/workspace");
571
+ }
572
+ /** Start an operation owned by the daemon. The same ID/payload returns the existing operation. */
573
+ createProject(request) {
574
+ return this.mw.http.request("POST", "/workspace/projects", { body: request });
575
+ }
576
+ /** Permanently remove the confirmed project's directory and membership.
577
+ * projects.delete() retains files. Native harness transcripts are not purged.
578
+ */
579
+ removeProjectFiles(id, request) {
580
+ return this.mw.http.request("POST", `/workspace/projects/${encodeURIComponent(id)}/remove`, { body: request });
581
+ }
582
+ /** Incremental reconciliation. Pass the previous identity to detect a replaced/restored workspace.
583
+ * A 409 requires fetching snapshot() again; never apply a delta to a different registry.
584
+ */
585
+ changes(since, workspaceId) {
586
+ return this.mw.http.request("GET", "/workspace/changes", { query: { since, workspaceId } });
587
+ }
588
+ /** Import legacy metadata before replacing a local cache. Safe to repeat after interruption. */
589
+ import(records) {
590
+ return this.mw.http.request("POST", "/workspace/import", { body: records });
591
+ }
592
+ };
593
+ var GitAccessApi = class {
594
+ constructor(mw) {
595
+ this.mw = mw;
596
+ }
597
+ mw;
598
+ /** Reads attribution independently of GitHub authentication. Requires gitIdentityVersion >= 1. */
599
+ identity(context = {}) {
600
+ return this.mw.http.request("GET", "/workspace/git/identity", { query: context });
601
+ }
602
+ /** Saves settings only; never stages or commits. all_workspaces installs this
603
+ * workspace's copy of a client-managed default; the client handles fan-out. */
604
+ setIdentity(update, context = {}) {
605
+ return this.mw.http.request("PUT", "/workspace/git/identity", { query: context, body: update });
606
+ }
607
+ state() {
608
+ return this.mw.http.request("GET", "/workspace/git");
609
+ }
610
+ setDefault(connection, auth) {
611
+ return this.mw.http.request("PUT", "/workspace/git", { body: { connection, auth } });
612
+ }
613
+ forget(connectionId) {
614
+ return this.mw.http.request("DELETE", `/workspace/git/connections/${encodeURIComponent(connectionId)}`);
615
+ }
616
+ project(projectId) {
617
+ return this.mw.http.request("GET", `/workspace/projects/${encodeURIComponent(projectId)}/git`);
618
+ }
619
+ setProject(projectId, connection, expectedRevision, auth) {
620
+ return this.mw.http.request("PUT", `/workspace/projects/${encodeURIComponent(projectId)}/git`, {
621
+ body: { connection, expectedRevision, auth }
622
+ });
623
+ }
624
+ /** Compatibility call. Prefer start() and operation()/watch() for reconnectable writes. */
625
+ run(projectId, operation, auth) {
626
+ return this.mw.http.request("POST", `/workspace/projects/${encodeURIComponent(projectId)}/git/${operation}`, { body: { auth } });
627
+ }
628
+ /** Requires health.gitOperationsVersion >= 1 (>= 2 for branch changes). Acceptance persists before Git runs;
629
+ * disconnecting only detaches the client. The same ID/intent never runs twice.
630
+ */
631
+ start(projectId, request) {
632
+ return this.mw.http.request("POST", `/workspace/projects/${encodeURIComponent(projectId)}/git/operations`, { body: request });
633
+ }
634
+ async operations(projectId, activeOnly = false) {
635
+ const result = await this.mw.http.request(
636
+ "GET",
637
+ `/workspace/projects/${encodeURIComponent(projectId)}/git/operations`,
638
+ { query: { active: activeOnly, actionsVersion: 2 } }
639
+ );
640
+ return result.operations;
641
+ }
642
+ operation(id) {
643
+ return this.mw.http.request("GET", `/workspace/git/operations/${encodeURIComponent(id)}`);
644
+ }
645
+ cancel(id) {
646
+ return this.mw.http.request("POST", `/workspace/git/operations/${encodeURIComponent(id)}/cancel`);
647
+ }
648
+ /** Current snapshot followed by state changes. Aborting observation never cancels the operation. */
649
+ async *watch(id, opts = {}) {
650
+ const controller = new AbortController();
651
+ const abort = () => controller.abort();
652
+ opts.signal?.addEventListener("abort", abort, { once: true });
653
+ if (opts.signal?.aborted) controller.abort();
654
+ try {
655
+ const response = await this.mw.http.open("GET", `/workspace/git/operations/${encodeURIComponent(id)}/stream`, {
656
+ signal: controller.signal
657
+ });
658
+ let sequence = -1;
659
+ for await (const operation of readSSE(response.body, controller.signal)) {
660
+ if (operation.sequence > sequence) {
661
+ sequence = operation.sequence;
662
+ yield operation;
663
+ }
664
+ }
665
+ } finally {
666
+ controller.abort();
667
+ opts.signal?.removeEventListener("abort", abort);
668
+ }
669
+ }
670
+ };
671
+
672
+ // src/surfaces.ts
673
+ var SurfacesApi = class {
674
+ constructor(mw) {
675
+ this.mw = mw;
676
+ }
677
+ mw;
678
+ list() {
679
+ return this.mw.http.request("GET", "/surfaces");
680
+ }
681
+ status(refresh = false) {
682
+ return this.mw.http.request("GET", "/surfaces/desktop", { query: { refresh } });
683
+ }
684
+ bind(binding) {
685
+ return this.mw.http.request("PUT", "/surfaces/desktop/binding", { body: binding });
686
+ }
687
+ open(request) {
688
+ return this.mw.http.request("POST", "/surfaces/desktop/sessions", { body: request });
689
+ }
690
+ control(id, request) {
691
+ return this.mw.http.request("POST", `/surfaces/desktop/sessions/${encodeURIComponent(id)}/control`, { body: request });
692
+ }
693
+ close(id) {
694
+ return this.mw.http.request("DELETE", `/surfaces/desktop/sessions/${encodeURIComponent(id)}`);
695
+ }
696
+ capture(id) {
697
+ return this.mw.http.request("POST", `/surfaces/desktop/sessions/${encodeURIComponent(id)}/captures`);
698
+ }
699
+ action(request) {
700
+ return this.mw.http.request("POST", "/surfaces/desktop/actions", { body: request });
701
+ }
702
+ receipt(id) {
703
+ return this.mw.http.request("GET", `/surfaces/desktop/actions/${encodeURIComponent(id)}`);
704
+ }
705
+ artifact(id) {
706
+ return this.mw.http.request("GET", `/artifacts/${encodeURIComponent(id)}`);
707
+ }
708
+ /** Every connection starts with the current snapshot, then revisions. Never replays input. */
709
+ async *watch(opts = {}) {
710
+ const controller = new AbortController();
711
+ const abort = () => controller.abort();
712
+ opts.signal?.addEventListener("abort", abort, { once: true });
713
+ if (opts.signal?.aborted) controller.abort();
714
+ try {
715
+ const response = await this.mw.http.open("GET", "/surfaces/desktop/events", { signal: controller.signal });
716
+ let instance;
717
+ let revision = -1;
718
+ for await (const snapshot of readSSE(response.body, controller.signal)) {
719
+ if (instance !== snapshot.instanceId || snapshot.revision > revision) {
720
+ instance = snapshot.instanceId;
721
+ revision = snapshot.revision;
722
+ yield snapshot;
723
+ }
724
+ }
725
+ } finally {
726
+ controller.abort();
727
+ opts.signal?.removeEventListener("abort", abort);
728
+ }
729
+ }
730
+ };
731
+
732
+ // src/service.ts
733
+ var ServiceApi = class {
734
+ constructor(client) {
735
+ this.client = client;
736
+ }
737
+ client;
738
+ updateStatus() {
739
+ return this.client.http.request("GET", "/service/update");
740
+ }
741
+ /** Download first. Acquire immediately before replacement; busy work returns 409.
742
+ * Admission stays closed until release, process exit, or the one-minute expiry. */
743
+ acquireUpdate() {
744
+ return this.client.http.request("POST", "/service/update");
745
+ }
746
+ releaseUpdate(id) {
747
+ return this.client.http.request("DELETE", `/service/update/${encodeURIComponent(id)}`);
748
+ }
749
+ };
750
+
751
+ // src/execution.ts
752
+ var ExecutionApi = class {
753
+ constructor(client) {
754
+ this.client = client;
755
+ this.terminals = new TerminalsApi(client);
756
+ }
757
+ client;
758
+ terminals;
759
+ host() {
760
+ return this.client.http.request("GET", "/workspace/host");
761
+ }
762
+ resources() {
763
+ return this.client.http.request("GET", "/workspace/resources");
764
+ }
765
+ files(path4 = "", query) {
766
+ return this.client.http.request("GET", "/workspace/files", { query: { path: path4, query } });
767
+ }
768
+ read(path4) {
769
+ return this.client.http.request("GET", "/workspace/file", { query: { path: path4 } });
770
+ }
771
+ write(path4, content) {
772
+ return this.client.http.request("PUT", "/workspace/file", { body: { path: path4, content } });
773
+ }
774
+ remove(path4) {
775
+ return this.client.http.request("DELETE", "/workspace/file", { query: { path: path4 } });
776
+ }
777
+ exec(command, signal) {
778
+ return this.client.http.request("POST", "/workspace/exec", { body: command, signal });
779
+ }
780
+ /** Output data is base64, preserving partial UTF-8 chunks. Cancelling stops this command. */
781
+ async *stream(command, signal) {
782
+ const response = await this.client.http.open("POST", "/workspace/exec/stream", { body: command, signal });
783
+ yield* readSSE(response.body, signal);
784
+ }
785
+ };
786
+ var TerminalsApi = class {
787
+ constructor(client) {
788
+ this.client = client;
789
+ }
790
+ client;
791
+ list(directory) {
792
+ return this.client.http.request("GET", "/workspace/terminals", { query: { directory } });
793
+ }
794
+ open(request) {
795
+ return this.client.http.request("POST", "/workspace/terminals", { body: request });
796
+ }
797
+ get(id) {
798
+ return this.client.http.request("GET", this.path(id));
799
+ }
800
+ close(id) {
801
+ return this.client.http.request("DELETE", this.path(id));
802
+ }
803
+ input(id, input) {
804
+ return this.client.http.request("POST", `${this.path(id)}/input`, { body: input });
805
+ }
806
+ resize(id, columns, rows) {
807
+ return this.client.http.request("PUT", `${this.path(id)}/size`, { body: { columns, rows } });
808
+ }
809
+ /** Detaching only closes the subscription. Resume from the last sequence; reset replaces the screen. */
810
+ async *events(id, after = 0, signal) {
811
+ const response = await this.client.http.open("GET", `${this.path(id)}/events`, { query: { after }, signal });
812
+ yield* readSSE(response.body, signal);
813
+ }
814
+ path(id) {
815
+ return `/workspace/terminals/${encodeURIComponent(id)}`;
816
+ }
817
+ };
818
+
819
+ // src/daemon-binary.ts
820
+ function supported(platform, arch) {
821
+ if (!["darwin", "linux", "win32"].includes(platform) || !["x64", "arm64"].includes(arch)) {
822
+ throw new MindwireError(`mindwire: no daemon release for ${platform}-${arch}`);
823
+ }
824
+ }
825
+ function assetName(version, platform, arch) {
826
+ const releasePlatform = platform === "win32" ? "windows" : platform;
827
+ const releaseArch = arch === "x64" ? "amd64" : arch;
828
+ return `mindwired-v${version}-${releasePlatform}-${releaseArch}${platform === "win32" ? ".exe" : ""}`;
829
+ }
830
+ function checksumFor(text, asset) {
831
+ const line = text.split("\n").find((l) => l.trim().endsWith(` ${asset}`) || l.trim().endsWith(` ${asset}`));
832
+ const hash = line?.trim().split(/\s+/)[0];
833
+ return hash && /^[a-f0-9]{64}$/i.test(hash) ? hash.toLowerCase() : void 0;
834
+ }
835
+ async function ensureDaemonBinary(opts = {}) {
836
+ const proc = globalThis;
837
+ const platform = opts.platform ?? proc.process?.platform;
838
+ const arch = opts.arch ?? proc.process?.arch;
839
+ supported(platform ?? "unknown", arch ?? "unknown");
840
+ const daemonPlatform = platform;
841
+ const daemonArch = arch;
842
+ const version = opts.version ?? SDK_VERSION;
843
+ if (!/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {
844
+ throw new MindwireError(`mindwire: cannot download daemon for non-release SDK version ${version}`);
845
+ }
846
+ const path4 = await import('path');
847
+ const { binaryCacheDirectory: binaryCacheDirectory2, cachedExecutable: cachedExecutable2, cacheExecutable: cacheExecutable2 } = await import('./binary-cache-CG52TXCZ.js');
848
+ const dir = path4.join(opts.cacheDir ?? await binaryCacheDirectory2(daemonPlatform), version, `${daemonPlatform}-${daemonArch}`);
849
+ const asset = assetName(version, daemonPlatform, daemonArch);
850
+ const bin = path4.join(dir, asset);
851
+ const cached = await cachedExecutable2(bin);
852
+ if (cached) return cached;
853
+ const base = (opts.releaseBaseUrl ?? proc.process?.env?.MINDWIRE_RELEASE_BASE_URL ?? "https://github.com/oblien/mindwire/releases/download").replace(/\/$/, "");
854
+ const release = `${base}/v${version}`;
855
+ const request = opts.fetch ?? globalThis.fetch;
856
+ if (!request) throw new MindwireError("mindwire: fetch is unavailable; set daemonBin or MINDWIRE_DAEMON");
857
+ const [checksums, binary] = await Promise.all([request(`${release}/checksums.txt`), request(`${release}/${asset}`)]);
858
+ if (!checksums.ok || !binary.ok) {
859
+ if (!opts.releaseBaseUrl && !proc.process?.env?.MINDWIRE_RELEASE_BASE_URL) {
860
+ const latest = await request("https://api.github.com/repos/oblien/mindwire/releases/latest");
861
+ if (latest.ok) {
862
+ const tag = (await latest.json()).tag_name;
863
+ const fallback = typeof tag === "string" ? tag.replace(/^v/, "") : "";
864
+ if (/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/.test(fallback) && fallback !== version) {
865
+ return ensureDaemonBinary({ ...opts, version: fallback });
866
+ }
867
+ }
868
+ }
869
+ throw new MindwireError(`mindwire: failed to download daemon v${version} for ${daemonPlatform}-${daemonArch}`);
870
+ }
871
+ const expected = checksumFor(await checksums.text(), asset);
872
+ if (!expected) throw new MindwireError(`mindwire: release v${version} has no checksum for ${asset}`);
873
+ const bytes = new Uint8Array(await binary.arrayBuffer());
874
+ return cacheExecutable2(bin, bytes, expected);
875
+ }
876
+
877
+ // src/embedded.ts
878
+ var shared = /* @__PURE__ */ new Map();
879
+ function configKey(opts) {
880
+ return JSON.stringify([opts.cwd ?? "", opts.statePath ?? "", opts.bin ?? ""]);
881
+ }
882
+ function startEmbedded(opts = {}) {
883
+ const key = configKey(opts);
884
+ let daemon = shared.get(key);
885
+ if (!daemon) {
886
+ daemon = spawnDaemon(opts).catch((err) => {
887
+ shared.delete(key);
888
+ throw err;
889
+ });
890
+ shared.set(key, daemon);
891
+ }
892
+ return daemon;
893
+ }
894
+ function serverRuntime() {
895
+ return globalThis;
896
+ }
897
+ function isServerRuntime() {
898
+ const g = serverRuntime();
899
+ return typeof g.process !== "undefined" && !!g.process.versions?.node || typeof g.Bun !== "undefined" || typeof g.Deno !== "undefined";
900
+ }
901
+ async function spawnDaemon(opts) {
902
+ if (!isServerRuntime()) {
903
+ throw new MindwireError(
904
+ "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."
905
+ );
906
+ }
907
+ const { spawn: spawn3 } = await import('child_process');
908
+ const net = await import('net');
909
+ const proc = serverRuntime().process;
910
+ const { randomBytes: randomBytes2 } = await import('crypto');
911
+ const resolved = await resolveBinary(opts.bin);
912
+ const bin = resolved.bin;
913
+ const port = await freePort(net);
914
+ const baseUrl = `http://127.0.0.1:${port}`;
915
+ const token = randomBytes2(32).toString("hex");
916
+ const child = spawn3(bin, [], {
917
+ env: {
918
+ ...proc.env,
919
+ ADDR: `127.0.0.1:${port}`,
920
+ AGENT_CWD: opts.cwd ?? proc.cwd(),
921
+ STATE_PATH: opts.statePath ?? ".mindwire-state.json",
922
+ DAEMON_TOKEN: token
923
+ },
924
+ stdio: "ignore"
925
+ });
926
+ let spawnError = null;
927
+ child.on("error", (e) => {
928
+ spawnError = e;
929
+ });
930
+ const stop = () => {
931
+ try {
932
+ child.kill();
933
+ } catch {
934
+ }
935
+ };
936
+ proc.once?.("exit", stop);
937
+ proc.once?.("SIGINT", () => {
938
+ stop();
939
+ proc.exit?.(130);
940
+ });
941
+ await waitHealthy(baseUrl, token, () => spawnError, resolved);
942
+ return { baseUrl, token, stop };
943
+ }
944
+ async function resolveBinary(explicit) {
945
+ const fs2 = await import('fs');
946
+ const path4 = await import('path');
947
+ const proc = serverRuntime().process;
948
+ const ext = proc.platform === "win32" ? ".exe" : "";
949
+ const candidates = [];
950
+ if (explicit) candidates.push(explicit);
951
+ if (proc.env?.MINDWIRE_DAEMON) candidates.push(proc.env.MINDWIRE_DAEMON);
952
+ try {
953
+ const url = await import('url');
954
+ const here = path4.dirname(url.fileURLToPath(import.meta.url));
955
+ const named = `mindwired-${proc.platform}-${proc.arch}${ext}`;
956
+ candidates.push(path4.join(here, "bin", named), path4.join(here, "..", "bin", named));
957
+ } catch {
958
+ }
959
+ for (const c of candidates) {
960
+ try {
961
+ if (fs2.existsSync(c)) return { bin: c, found: true, checked: candidates };
962
+ } catch {
963
+ }
964
+ }
965
+ const downloaded = await ensureDaemonBinary({ platform: proc.platform, arch: proc.arch });
966
+ return { bin: downloaded, found: true, checked: [...candidates, downloaded] };
967
+ }
968
+ function daemonStartError(resolved, cause) {
969
+ if (!resolved.found) {
970
+ return [
971
+ "Couldn't start the mindwire daemon: the `mindwired` binary was not found.",
972
+ `Looked in: ${resolved.checked.join(", ")}.`,
973
+ "Fixes:",
974
+ " \u2022 check GitHub Release access so the SDK can download its matching daemon binary; or",
975
+ " \u2022 set MINDWIRE_DAEMON to a `mindwired` binary; or",
976
+ " \u2022 pass { baseUrl } to connect to a daemon you run yourself.",
977
+ " \u2022 Working inside the mindwire monorepo? Run `go build -o /tmp/mindwired ./daemon/cmd/daemon` and set MINDWIRE_DAEMON.",
978
+ `(underlying error: ${cause.message})`
979
+ ].join("\n");
980
+ }
981
+ return `Couldn't start the mindwire daemon (${resolved.bin}): ${cause.message}. Set MINDWIRE_DAEMON to the binary path, or pass { baseUrl } to use a running daemon.`;
982
+ }
983
+ function freePort(net) {
984
+ return new Promise((resolve3, reject) => {
985
+ const srv = net.createServer();
986
+ srv.on("error", reject);
987
+ srv.listen(0, "127.0.0.1", () => {
988
+ const addr = srv.address();
989
+ const port = addr && typeof addr === "object" ? addr.port : 0;
990
+ srv.close(() => resolve3(port));
991
+ });
992
+ });
993
+ }
994
+ async function waitHealthy(baseUrl, token, getError, resolved, timeoutMs = 15e3) {
995
+ const deadline = Date.now() + timeoutMs;
996
+ while (Date.now() < deadline) {
997
+ const err = getError();
998
+ if (err) {
999
+ throw new MindwireError(daemonStartError(resolved, err), { cause: err });
1000
+ }
1001
+ try {
1002
+ const res = await fetch(`${baseUrl}/healthz`, { headers: { Authorization: `Bearer ${token}` } });
1003
+ if (res.ok) return;
1004
+ } catch {
1005
+ }
1006
+ await new Promise((r) => setTimeout(r, 150));
1007
+ }
1008
+ throw new MindwireError("mindwire embedded daemon did not become healthy in time.");
1009
+ }
1010
+
1011
+ // src/target/index.ts
1012
+ function emit(spec, e) {
1013
+ if (!spec.onLog) return;
1014
+ try {
1015
+ spec.onLog(e);
1016
+ } catch {
1017
+ }
1018
+ }
1019
+ function local(opts = {}) {
1020
+ return {
1021
+ name: "local",
1022
+ async connect(spec) {
1023
+ const d = await startEmbedded(opts);
1024
+ emit(spec, { target: "local", phase: "ready", message: `embedded daemon on ${d.baseUrl}` });
1025
+ return {
1026
+ id: d.baseUrl,
1027
+ baseUrl: d.baseUrl,
1028
+ ...d.token !== void 0 ? { token: d.token } : {},
1029
+ // No-op: the embedded daemon is shared (keyed memoization) and reaped on process exit.
1030
+ stop: async () => {
1031
+ }
1032
+ };
1033
+ }
1034
+ };
1035
+ }
1036
+ function remote(baseUrl, opts = {}) {
1037
+ return {
1038
+ name: "remote",
1039
+ async connect(spec) {
1040
+ emit(spec, { target: "remote", phase: "skip", message: `using remote daemon at ${baseUrl}` });
1041
+ return {
1042
+ id: baseUrl,
1043
+ baseUrl,
1044
+ ...opts.token !== void 0 ? { token: opts.token } : {},
1045
+ ...opts.headers !== void 0 ? { headers: opts.headers } : {},
1046
+ ...opts.fetch !== void 0 ? { fetch: opts.fetch } : {},
1047
+ stop: async () => {
1048
+ }
1049
+ };
1050
+ }
1051
+ };
1052
+ }
1053
+
1054
+ // src/client.ts
1055
+ var handleByTransport = /* @__PURE__ */ new WeakMap();
1056
+ var Mindwire = class _Mindwire {
1057
+ /** Workspace registry: saved agent profiles, projects and chat relationships. */
1058
+ workspace;
1059
+ surfaces;
1060
+ service;
1061
+ execution;
1062
+ computer;
1063
+ http;
1064
+ /** The default agent type applied to agent-scoped calls, if set. */
1065
+ defaultAgent;
1066
+ /** Step-flow auth, scoped to this client's default agent (override per call). */
1067
+ auth;
1068
+ /** Persistent memory files + saved prompt templates, scoped to this client's default agent. */
1069
+ prompts;
1070
+ /** Persistent MCP-server config (the config an agent loads every run), scoped to this client's default agent. */
1071
+ mcp;
1072
+ /** Custom LLM-provider registration (opencode/Codex native config), scoped to this client's default agent. */
1073
+ providers;
1074
+ /** Daemon-driven notification channels + routing rules (webhook/slack/discord/telegram; per-agent/session/global). */
1075
+ notify;
1076
+ constructor(opts = {}) {
1077
+ const target = opts.target ?? local();
1078
+ const spec = { agent: opts.agent, onLog: opts.logger };
1079
+ this.http = new Http({
1080
+ fetch: opts.fetch,
1081
+ headers: opts.headers,
1082
+ timeoutMs: opts.requestTimeoutMs,
1083
+ resolveBase: () => {
1084
+ const h = target.connect(spec);
1085
+ handleByTransport.set(this.http, h);
1086
+ return h.then((x) => ({
1087
+ baseUrl: x.baseUrl,
1088
+ token: x.token,
1089
+ getToken: x.getToken,
1090
+ headers: x.headers,
1091
+ fetch: x.fetch
1092
+ }));
1093
+ }
1094
+ });
1095
+ this.defaultAgent = opts.agent;
1096
+ this.workspace = new WorkspaceApi(this);
1097
+ this.surfaces = new SurfacesApi(this);
1098
+ this.service = new ServiceApi(this);
1099
+ this.execution = new ExecutionApi(this);
1100
+ this.computer = new ComputerApi(this);
1101
+ this.auth = new AuthApi(this);
1102
+ this.prompts = new PromptsApi(this);
1103
+ this.mcp = new McpApi(this);
1104
+ this.providers = new ProvidersApi(this);
1105
+ this.notify = new NotifyApi(this);
1106
+ }
1107
+ /**
1108
+ * Provision the destination and await readiness **now**, rather than lazily on the first request —
1109
+ * useful to front-load a fresh SSH/Docker/Oblien box (and to stream its {@link EnsureEvent}s to the
1110
+ * `logger`) before the first `turn()`. Idempotent and memoized: repeated `ensure()` calls, and the
1111
+ * first real request, all await the same provisioning, so the target connects exactly once.
1112
+ */
1113
+ async ensure() {
1114
+ await this.http.ready();
1115
+ }
1116
+ /** Return a new client bound to a different default agent (shares the same transport config). */
1117
+ withAgent(agent) {
1118
+ const clone = Object.create(_Mindwire.prototype);
1119
+ clone.http = this.http;
1120
+ clone.defaultAgent = agent;
1121
+ clone.workspace = new WorkspaceApi(clone);
1122
+ clone.surfaces = new SurfacesApi(clone);
1123
+ clone.service = new ServiceApi(clone);
1124
+ clone.execution = new ExecutionApi(clone);
1125
+ clone.computer = new ComputerApi(clone);
1126
+ clone.auth = new AuthApi(clone);
1127
+ clone.prompts = new PromptsApi(clone);
1128
+ clone.mcp = new McpApi(clone);
1129
+ clone.providers = new ProvidersApi(clone);
1130
+ clone.notify = new NotifyApi(clone);
1131
+ return clone;
1132
+ }
1133
+ /** The `?agent=` value to send for a scoped call: explicit override → client default → none. */
1134
+ agentParam(scoped) {
1135
+ const a = scoped?.agent ?? this.defaultAgent;
1136
+ return a ? { agent: a } : void 0;
1137
+ }
1138
+ /**
1139
+ * Release target-owned resources by calling the {@link TargetHandle}'s `stop()` — once, even across
1140
+ * {@link withAgent} clones that share the transport. For an `ssh`/`docker`/`oblien` target this reaps
1141
+ * the box (tear down the tunnel, stop or delete the container/workspace, per `stopOnExit`); a no-op
1142
+ * for `local`/`remote` (embedded self-cleans on process exit; remote is not ours to stop). Safe to
1143
+ * call before the target has connected (nothing to reap yet).
1144
+ */
1145
+ async close() {
1146
+ const handle = handleByTransport.get(this.http);
1147
+ if (!handle) return;
1148
+ handleByTransport.delete(this.http);
1149
+ const h = await handle.catch(() => null);
1150
+ if (h) await h.stop();
1151
+ }
1152
+ // ---- health & catalog ----------------------------------------------------
1153
+ /** `GET /healthz` — authenticated liveness check. Resolves with the daemon's health payload when it is up. */
1154
+ health() {
1155
+ return this.http.request("GET", "/healthz");
1156
+ }
1157
+ /**
1158
+ * `GET /stats` — the daemon **process's** resource snapshot (heap in use, memory reserved from the
1159
+ * OS, goroutines, GC cycles, cores, platform, uptime). Cheap enough to call on demand — the daemon
1160
+ * reads its own Go runtime, not the machine — so a UI can fetch it when a user opens a daemon's page
1161
+ * without any background polling. See {@link Stats} for what each field means and doesn't.
1162
+ */
1163
+ stats() {
1164
+ return this.http.request("GET", "/stats");
1165
+ }
1166
+ /** `GET /catalog` — every agent this daemon binary supports. */
1167
+ catalog() {
1168
+ return this.http.request("GET", "/catalog");
1169
+ }
1170
+ /** `GET /agent` — capabilities + settings schema + auth methods/status for the selected agent. */
1171
+ agent(scoped) {
1172
+ return this.http.request("GET", "/agent", { query: this.agentParam(scoped) });
1173
+ }
1174
+ /** `GET /agent/software` — installed version, compatibility and approved update target. */
1175
+ software(opts = {}) {
1176
+ return this.http.request("GET", "/agent/software", {
1177
+ query: { ...this.agentParam(opts), ...opts.refresh ? { refresh: "true" } : {} }
1178
+ });
1179
+ }
1180
+ /**
1181
+ * `GET /models` — the models the selected agent can run for the configured account. An empty array
1182
+ * is valid (no credentials yet / offline). Throws a 400 {@link ApiError} for an agent whose model is
1183
+ * free text (check `capabilities.models` first).
1184
+ */
1185
+ models(scoped) {
1186
+ return this.http.request("GET", "/models", { query: this.agentParam(scoped) });
1187
+ }
1188
+ /** `GET /doctor` — daemon-level health plus the selected agent's own checks. */
1189
+ doctor(scoped) {
1190
+ return this.http.request("GET", "/doctor", { query: this.agentParam(scoped) });
1191
+ }
1192
+ // ---- toolchain setup -----------------------------------------------------
1193
+ /** `POST /setup` — start the agent's install toolchain (background; poll {@link setupStatus}). */
1194
+ setup(scoped) {
1195
+ return this.http.request("POST", "/setup", { query: this.agentParam(scoped) });
1196
+ }
1197
+ /** `POST /update` — install the catalog's newest tested version compatible with this daemon. */
1198
+ update(scoped) {
1199
+ return this.http.request("POST", "/update", { query: this.agentParam(scoped) });
1200
+ }
1201
+ /** `GET /setup` — current toolchain install progress. */
1202
+ setupStatus(scoped) {
1203
+ return this.http.request("GET", "/setup", { query: this.agentParam(scoped) });
1204
+ }
1205
+ // ---- config --------------------------------------------------------------
1206
+ /** `GET /config` — the declared, non-secret settings for the agent. */
1207
+ getConfig(scoped) {
1208
+ return this.http.request("GET", "/config", {
1209
+ query: this.agentParam(scoped)
1210
+ });
1211
+ }
1212
+ /** `PUT /config` — merge recognized (non-secret) setting keys. Unknown keys are ignored server-side. */
1213
+ async setConfig(values, scoped) {
1214
+ await this.http.request("PUT", "/config", {
1215
+ query: this.agentParam(scoped),
1216
+ body: values
1217
+ });
1218
+ }
1219
+ // ---- chats & history -----------------------------------------------------
1220
+ /** `GET /chats` — recorded chats (newest first), shared across agents. */
1221
+ chats() {
1222
+ return this.http.request("GET", "/chats");
1223
+ }
1224
+ /**
1225
+ * `PUT /chats/{id}` — rename a chat. The user title wins over the agent's native auto-title in
1226
+ * every listing; an empty title clears the rename (reverting to the native/derived title).
1227
+ * Returns the updated summary.
1228
+ */
1229
+ renameChat(chatId, title) {
1230
+ return this.http.request("PUT", `/chats/${encodeURIComponent(chatId)}`, {
1231
+ body: { title }
1232
+ });
1233
+ }
1234
+ /**
1235
+ * `DELETE /chats/{id}` — a true, irreversible delete: purges ALL of the chat's mindwire
1236
+ * bookkeeping and, for every session the chat mapped to, removes that agent's native transcript
1237
+ * (the source of truth). Rejects with a 409 error if a turn is live. Native deletion is
1238
+ * best-effort per agent; the result reports what was purged vs. failed.
1239
+ */
1240
+ deleteChat(chatId) {
1241
+ return this.http.request("DELETE", `/chats/${encodeURIComponent(chatId)}`);
1242
+ }
1243
+ /**
1244
+ * `POST /chats/{id}/fork` — clone a chat into a new id (generated when `newChatId` is omitted).
1245
+ * The fork shares the source's native session until its first turn, which branches it (natively
1246
+ * on Claude via `--fork-session`; a fresh session on agents without native fork). Rejects with a
1247
+ * 409 if the source has a live turn, 404 if the source is unknown, 400 if the target id is in
1248
+ * use. Returns the new chat's summary.
1249
+ */
1250
+ forkChat(chatId, opts = {}) {
1251
+ return this.http.request("POST", `/chats/${encodeURIComponent(chatId)}/fork`, {
1252
+ body: opts.newChatId ? { newChatId: opts.newChatId } : {}
1253
+ });
1254
+ }
1255
+ /**
1256
+ * `GET /chats/{id}/messages` — a chat's transcript (native when the agent supports it, else
1257
+ * the recorded fallback). `limit` caps to the newest N; `before` pages older history.
1258
+ */
1259
+ messages(chatId, opts = {}) {
1260
+ const query = { ...this.agentParam(opts) };
1261
+ if (opts.limit !== void 0) query["limit"] = opts.limit;
1262
+ if (opts.before !== void 0) query["before"] = opts.before;
1263
+ return this.http.request("GET", `/chats/${encodeURIComponent(chatId)}/messages`, {
1264
+ query
1265
+ });
1266
+ }
1267
+ /** `GET /chats/{id}/run` — the latest run for a chat (reattach anchor), or `null` if none yet. */
1268
+ async latestRun(chatId) {
1269
+ const data = await this.http.request(
1270
+ "GET",
1271
+ `/chats/${encodeURIComponent(chatId)}/run`
1272
+ );
1273
+ return data ? new Run(this.http, data) : null;
1274
+ }
1275
+ // ---- turns & runs --------------------------------------------------------
1276
+ /**
1277
+ * `POST /turns` — start a turn. Returns a {@link Run} handle you can stream, cancel, or await.
1278
+ * Rejects with an {@link ApiError} (409) if a turn is already running for the chat.
1279
+ *
1280
+ * `mode` defaults to `"turn"` — one agent turn that ends when the CLI settles. Pass
1281
+ * `mode: "resolve"` (with optional {@link ResolveOptions} `resolve` caps) for a global-resolve run
1282
+ * that auto-continues the agent's multi-step work until it's done; {@link Mindwire.resolve} is the
1283
+ * clearer entry point for that. The returned {@link Run} is then the parent of the run tree.
1284
+ */
1285
+ async turn(input) {
1286
+ const body = {
1287
+ chatId: input.chatId,
1288
+ message: input.message
1289
+ };
1290
+ if (input.cwd !== void 0) body.cwd = input.cwd;
1291
+ if (input.options !== void 0) body.options = input.options;
1292
+ if (input.mode !== void 0) body.mode = input.mode;
1293
+ if (input.resolve !== void 0) body.resolve = input.resolve;
1294
+ if (input.gitAuth !== void 0) body.gitAuth = input.gitAuth;
1295
+ const data = await this.http.request("POST", "/turns", {
1296
+ query: this.agentParam(input),
1297
+ body
1298
+ });
1299
+ return new Run(this.http, data);
1300
+ }
1301
+ /**
1302
+ * `POST /turns {mode:"resolve"}` — start a **global-resolve** run: instead of returning after one
1303
+ * turn, the daemon holds the task open and auto-continues the agent (resuming on continuable stops
1304
+ * and probing for completion) until the work is globally resolved, then aggregates one final result.
1305
+ *
1306
+ * The returned {@link Run} is the **parent** of a run tree: each auto-continued iteration is a child
1307
+ * turn ({@link Run.children}) whose events stream onto the parent's topic, delimited by `continuation`
1308
+ * boundary events. `run.wait()` resolves once with the aggregated result; `run.stopReason` /
1309
+ * `run.iterations` report how the loop ended. Resolve turns run unattended (no mid-turn approvals)
1310
+ * and are bounded by {@link ResolveOptions} caps — see the resolve guide. Rejects with an
1311
+ * {@link ApiError} (409) if a turn is already running for the chat.
1312
+ */
1313
+ async resolve(input) {
1314
+ return this.turn({ ...input, mode: "resolve" });
1315
+ }
1316
+ /** `GET /runs/{id}` — fetch an existing run as a {@link Run} handle. */
1317
+ async run(id) {
1318
+ const data = await this.http.request("GET", `/runs/${encodeURIComponent(id)}`);
1319
+ return new Run(this.http, data);
1320
+ }
1321
+ /**
1322
+ * `POST /chats/{id}/compact` — run an on-demand conversation compaction as a first-class {@link Run}
1323
+ * you can stream or await. The agent folds prior context into a summary it carries forward, emitting
1324
+ * a `compaction` event on the stream and recording the boundary in history exactly like an
1325
+ * auto-compaction. Optional `instructions` focus the continuation summary (Claude's
1326
+ * `/compact <instructions>`; agents that don't honor focus still compact). Rejects with an
1327
+ * {@link ApiError}: 400 if the agent doesn't support compaction (`capabilities.compactNow`) or the
1328
+ * chat has no conversation yet, 409 if a turn is already running for the chat.
1329
+ */
1330
+ async compact(chatId, opts = {}) {
1331
+ const data = await this.http.request(
1332
+ "POST",
1333
+ `/chats/${encodeURIComponent(chatId)}/compact`,
1334
+ {
1335
+ query: this.agentParam(opts),
1336
+ body: opts.instructions ? { instructions: opts.instructions } : {}
1337
+ }
1338
+ );
1339
+ return new Run(this.http, data);
1340
+ }
1341
+ // ---- notifications -------------------------------------------------------
1342
+ /** `GET /notify/config` — whether a notification channel is wired (token never returned). */
1343
+ getNotifyConfig() {
1344
+ return this.http.request("GET", "/notify/config");
1345
+ }
1346
+ /** `PUT /notify/config` — store the provisioned notification channel (daemon-wide). */
1347
+ async setNotifyConfig(input) {
1348
+ await this.http.request("PUT", "/notify/config", { body: input });
1349
+ }
1350
+ /** `GET /notify/stream` — SSE feed of the daemon's notifications (replay, then live). */
1351
+ async *notifications(opts = {}) {
1352
+ const res = await this.http.open("GET", "/notify/stream", {
1353
+ ...opts.signal ? { signal: opts.signal } : {}
1354
+ });
1355
+ yield* readSSE(res.body, opts.signal);
1356
+ }
1357
+ // ---- live resources ------------------------------------------------------
1358
+ /**
1359
+ * `GET /processes/stream` — SSE feed of live per-turn CPU/memory, one {@link ProcessFrame} per tick.
1360
+ * Sampling is **on demand**: the daemon starts measuring only while a client is connected and stops
1361
+ * the instant the last one disconnects, so aborting the `signal` (or ending the loop) tells the
1362
+ * daemon to stop — no background work, no leak. Pass `agent` to filter each frame's samples to one
1363
+ * agent type. Frames are live snapshots (no replay); an empty `samples` array is a valid keep-alive.
1364
+ */
1365
+ async *processes(opts = {}) {
1366
+ const path4 = "/processes/stream" + (opts.agent ? `?agent=${encodeURIComponent(opts.agent)}` : "");
1367
+ const res = await this.http.open("GET", path4, {
1368
+ ...opts.signal ? { signal: opts.signal } : {}
1369
+ });
1370
+ yield* readSSE(res.body, opts.signal);
1371
+ }
1372
+ };
1373
+ var AuthApi = class {
1374
+ constructor(mw) {
1375
+ this.mw = mw;
1376
+ }
1377
+ mw;
1378
+ /** `GET /auth/methods` — the options list to present. */
1379
+ methods(scoped) {
1380
+ return this.mw.http.request("GET", "/auth/methods", {
1381
+ query: this.mw.agentParam(scoped)
1382
+ });
1383
+ }
1384
+ /** `POST /auth/begin` — start one method (may return `{ url, code, fields, pending }`). */
1385
+ begin(method, scoped) {
1386
+ return this.mw.http.request("POST", "/auth/begin", {
1387
+ query: this.mw.agentParam(scoped),
1388
+ body: { method }
1389
+ });
1390
+ }
1391
+ /** `POST /auth/step` — submit fields, or poll an interactive login to completion. */
1392
+ step(input, scoped) {
1393
+ return this.mw.http.request("POST", "/auth/step", {
1394
+ query: this.mw.agentParam(scoped),
1395
+ body: input
1396
+ });
1397
+ }
1398
+ /** Read one interactive attempt, scoped by the returned AuthState.flowId. */
1399
+ poll(flowId, scoped) {
1400
+ return this.step({ _flowId: flowId }, scoped);
1401
+ }
1402
+ /** Cancel this native login without affecting a newer sign-in attempt. */
1403
+ cancel(flowId, scoped) {
1404
+ return this.step({ _flowId: flowId, _action: "cancel" }, scoped);
1405
+ }
1406
+ /** `GET /auth/status` — is the agent authenticated, and via which method. */
1407
+ status(scoped) {
1408
+ return this.mw.http.request("GET", "/auth/status", {
1409
+ query: this.mw.agentParam(scoped)
1410
+ });
1411
+ }
1412
+ /** `POST /auth/logout` — disconnect this harness once its running chats finish. */
1413
+ logout(scoped) {
1414
+ return this.mw.http.request("POST", "/auth/logout", {
1415
+ query: this.mw.agentParam(scoped)
1416
+ });
1417
+ }
1418
+ };
1419
+ var PromptsApi = class {
1420
+ constructor(mw) {
1421
+ this.mw = mw;
1422
+ }
1423
+ mw;
1424
+ query(scoped, extra) {
1425
+ return { ...this.mw.agentParam(scoped), ...extra };
1426
+ }
1427
+ /**
1428
+ * `GET /memory` — the agent's memory file at every supported scope (project + user for both
1429
+ * Claude and Codex). Each entry carries the resolved `path` and `exists`; `content` is `""` for
1430
+ * an absent file.
1431
+ */
1432
+ memory(opts = {}) {
1433
+ return this.mw.http.request("GET", "/memory", {
1434
+ query: this.query(opts, { dir: opts.dir })
1435
+ });
1436
+ }
1437
+ /** `PUT /memory` — write the memory file at `scope`. Returns the resulting {@link MemoryDoc}. */
1438
+ setMemory(input, opts = {}) {
1439
+ return this.mw.http.request("PUT", "/memory", {
1440
+ query: this.query(opts, { dir: opts.dir }),
1441
+ body: input
1442
+ });
1443
+ }
1444
+ /**
1445
+ * `DELETE /memory` — remove the memory file at `scope` (defaults to `user`). Returns the resulting
1446
+ * {@link MemoryDoc} (`exists: false` at the resolved path). Idempotent: deleting an absent file still
1447
+ * succeeds.
1448
+ */
1449
+ deleteMemory(opts = {}) {
1450
+ return this.mw.http.request("DELETE", "/memory", {
1451
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1452
+ });
1453
+ }
1454
+ /**
1455
+ * `GET /prompts` — saved prompt templates across every supported scope (Claude: project + user;
1456
+ * Codex: user only). `content` is omitted here; fetch it with {@link get}. A missing project
1457
+ * directory yields an empty list for that scope rather than an error.
1458
+ */
1459
+ list(opts = {}) {
1460
+ return this.mw.http.request("GET", "/prompts", {
1461
+ query: this.query(opts, { dir: opts.dir })
1462
+ });
1463
+ }
1464
+ /** `GET /prompts/{name}` — one template's full body. Rejects with a 404 `ApiError` if absent. */
1465
+ get(name, opts = {}) {
1466
+ return this.mw.http.request("GET", `/prompts/${encodeURIComponent(name)}`, {
1467
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1468
+ });
1469
+ }
1470
+ /** `PUT /prompts/{name}` — create or overwrite a template. Returns the resulting {@link PromptTemplate}. */
1471
+ set(name, content, opts = {}) {
1472
+ return this.mw.http.request("PUT", `/prompts/${encodeURIComponent(name)}`, {
1473
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir }),
1474
+ body: { content }
1475
+ });
1476
+ }
1477
+ /**
1478
+ * `DELETE /prompts/{name}` — remove one template at `scope` (defaults to `user`). Idempotent:
1479
+ * deleting an absent template still succeeds. A traversal name rejects with a 400 `ApiError`.
1480
+ */
1481
+ async delete(name, opts = {}) {
1482
+ await this.mw.http.request("DELETE", `/prompts/${encodeURIComponent(name)}`, {
1483
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1484
+ });
1485
+ }
1486
+ /**
1487
+ * `GET /subagents` — persistent subagent definitions (Claude `.claude/agents/*.md`) across every
1488
+ * supported scope. `content` is omitted here (fetch it with {@link subagent}); `meta` is the parsed
1489
+ * frontmatter view. Rejects with a 400 `ApiError` on an agent without the subagent-definition module.
1490
+ * Distinct from a turn's per-turn `subagents` passthrough — this is the on-disk definition store.
1491
+ */
1492
+ subagents(opts = {}) {
1493
+ return this.mw.http.request("GET", "/subagents", {
1494
+ query: this.query(opts, { dir: opts.dir })
1495
+ });
1496
+ }
1497
+ /** `GET /subagents/{name}` — one definition's raw body + parsed meta. 404 `ApiError` if absent. */
1498
+ subagent(name, opts = {}) {
1499
+ return this.mw.http.request("GET", `/subagents/${encodeURIComponent(name)}`, {
1500
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1501
+ });
1502
+ }
1503
+ /** `PUT /subagents/{name}` — create or overwrite a definition (raw content is canonical). Returns it. */
1504
+ setSubagent(name, content, opts = {}) {
1505
+ return this.mw.http.request("PUT", `/subagents/${encodeURIComponent(name)}`, {
1506
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir }),
1507
+ body: { content }
1508
+ });
1509
+ }
1510
+ /**
1511
+ * `DELETE /subagents/{name}` — remove one definition at `scope` (defaults to `user`). Idempotent:
1512
+ * deleting an absent definition still succeeds. A traversal name rejects with a 400 `ApiError`.
1513
+ */
1514
+ async deleteSubagent(name, opts = {}) {
1515
+ await this.mw.http.request("DELETE", `/subagents/${encodeURIComponent(name)}`, {
1516
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1517
+ });
1518
+ }
1519
+ };
1520
+ var McpApi = class {
1521
+ constructor(mw) {
1522
+ this.mw = mw;
1523
+ }
1524
+ mw;
1525
+ query(scoped, extra) {
1526
+ return { ...this.mw.agentParam(scoped), ...extra };
1527
+ }
1528
+ /**
1529
+ * `GET /mcp` — every persistent MCP server across the agent's supported scopes, keyed
1530
+ * `scope → name → server` (Claude: project + user; Codex: user only). A missing config file yields
1531
+ * an empty object for that scope rather than an error.
1532
+ */
1533
+ list(opts = {}) {
1534
+ return this.mw.http.request("GET", "/mcp", {
1535
+ query: this.query(opts, { dir: opts.dir })
1536
+ });
1537
+ }
1538
+ /** `GET /mcp/{name}` — one server's definition. Rejects with a 404 `ApiError` if it isn't configured. */
1539
+ get(name, opts = {}) {
1540
+ return this.mw.http.request("GET", `/mcp/${encodeURIComponent(name)}`, {
1541
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1542
+ });
1543
+ }
1544
+ /** `PUT /mcp/{name}` — create or overwrite one server. Returns the stored definition. */
1545
+ set(name, server, opts = {}) {
1546
+ return this.mw.http.request("PUT", `/mcp/${encodeURIComponent(name)}`, {
1547
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir }),
1548
+ body: server
1549
+ });
1550
+ }
1551
+ /** `DELETE /mcp/{name}` — remove one server. Idempotent: deleting an absent server still succeeds. */
1552
+ async delete(name, opts = {}) {
1553
+ await this.mw.http.request("DELETE", `/mcp/${encodeURIComponent(name)}`, {
1554
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1555
+ });
1556
+ }
1557
+ };
1558
+ var ProvidersApi = class {
1559
+ constructor(mw) {
1560
+ this.mw = mw;
1561
+ }
1562
+ mw;
1563
+ query(scoped, extra) {
1564
+ return { ...this.mw.agentParam(scoped), ...extra };
1565
+ }
1566
+ /**
1567
+ * `GET /providers` — every registered custom provider across the agent's supported scopes, keyed
1568
+ * `scope → id → provider` (opencode/Codex: user only). A missing config file yields an empty object for
1569
+ * that scope rather than an error. `hasKey` reports whether a secret is stored; the key is never returned.
1570
+ */
1571
+ list(opts = {}) {
1572
+ return this.mw.http.request("GET", "/providers", {
1573
+ query: this.query(opts, { dir: opts.dir })
1574
+ });
1575
+ }
1576
+ /** `GET /providers/{id}` — one provider's definition. Rejects with a 404 `ApiError` if it isn't configured. */
1577
+ get(id, opts = {}) {
1578
+ return this.mw.http.request("GET", `/providers/${encodeURIComponent(id)}`, {
1579
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1580
+ });
1581
+ }
1582
+ /**
1583
+ * `PUT /providers/{id}` — create or overwrite one provider, returning the stored definition (with
1584
+ * `hasKey` and the stored `envVars`). Two write-only secret channels, both optional: `opts.apiKey` is a
1585
+ * single key (custom endpoints, single-key catalog brands); `opts.secrets` is a NAME→VALUE map for a
1586
+ * catalog provider whose entry declares MULTIPLE env vars (e.g. AWS Bedrock). Omitting both leaves any
1587
+ * previously stored secret intact. The path `id` wins over any `id` on the provider value.
1588
+ */
1589
+ set(id, provider, opts = {}) {
1590
+ return this.mw.http.request("PUT", `/providers/${encodeURIComponent(id)}`, {
1591
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir }),
1592
+ body: { ...provider, id, apiKey: opts.apiKey, secrets: opts.secrets }
1593
+ });
1594
+ }
1595
+ /** `DELETE /providers/{id}` — remove one provider and clear its stored key. Idempotent. */
1596
+ async delete(id, opts = {}) {
1597
+ await this.mw.http.request("DELETE", `/providers/${encodeURIComponent(id)}`, {
1598
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1599
+ });
1600
+ }
1601
+ };
1602
+ var NotifyApi = class {
1603
+ constructor(mw) {
1604
+ this.mw = mw;
1605
+ }
1606
+ mw;
1607
+ /** `GET /notify/channels` — every channel, masked (no secrets). */
1608
+ channels() {
1609
+ return this.mw.http.request("GET", "/notify/channels");
1610
+ }
1611
+ /** `POST /notify/channels` — create a channel (server-assigns the id). Returns it masked. */
1612
+ createChannel(input) {
1613
+ return this.mw.http.request("POST", "/notify/channels", { body: input });
1614
+ }
1615
+ /**
1616
+ * `PUT /notify/channels/{id}` — update a channel, merge-preserving any omitted secret
1617
+ * (`url`/`token`/`secret`). Returns the updated masked channel. 404 `ApiError` if unknown.
1618
+ */
1619
+ setChannel(id, input) {
1620
+ return this.mw.http.request("PUT", `/notify/channels/${encodeURIComponent(id)}`, {
1621
+ body: input
1622
+ });
1623
+ }
1624
+ /** `DELETE /notify/channels/{id}` — remove a channel. Idempotent. */
1625
+ async deleteChannel(id) {
1626
+ await this.mw.http.request("DELETE", `/notify/channels/${encodeURIComponent(id)}`);
1627
+ }
1628
+ /**
1629
+ * `POST /notify/channels/{id}/test` — deliver a synthetic notification to a channel. A failed
1630
+ * delivery is DATA (`{ ok: false, error }`), not a thrown error; only an unknown id rejects (404).
1631
+ */
1632
+ testChannel(id) {
1633
+ return this.mw.http.request(
1634
+ "POST",
1635
+ `/notify/channels/${encodeURIComponent(id)}/test`
1636
+ );
1637
+ }
1638
+ /** `GET /notify/rules` — every routing rule. */
1639
+ rules() {
1640
+ return this.mw.http.request("GET", "/notify/rules");
1641
+ }
1642
+ /** `POST /notify/rules` — create a rule (server-assigns the id). Returns it. */
1643
+ createRule(input) {
1644
+ return this.mw.http.request("POST", "/notify/rules", { body: input });
1645
+ }
1646
+ /** `PUT /notify/rules/{id}` — replace a rule. Returns it. 404 `ApiError` if unknown. */
1647
+ setRule(id, input) {
1648
+ return this.mw.http.request("PUT", `/notify/rules/${encodeURIComponent(id)}`, {
1649
+ body: input
1650
+ });
1651
+ }
1652
+ /** `DELETE /notify/rules/{id}` — remove a rule. Idempotent. */
1653
+ async deleteRule(id) {
1654
+ await this.mw.http.request("DELETE", `/notify/rules/${encodeURIComponent(id)}`);
1655
+ }
1656
+ };
1657
+ var CLOUDFLARED_VERSION = "2026.9.3";
1658
+ var execute = promisify(execFile);
1659
+ async function ensureCloudflareBinary(options = {}) {
1660
+ const platform = options.platform ?? process.platform, arch = options.arch ?? process.arch;
1661
+ const cpu = arch === "x64" ? "amd64" : arch === "arm64" ? "arm64" : "";
1662
+ if (!cpu || !["darwin", "linux", "win32"].includes(platform) || platform === "win32" && cpu !== "amd64") {
1663
+ throw new Error("Install cloudflared for this computer, or select another connection provider.");
1664
+ }
1665
+ const asset = `cloudflared-${platform === "win32" ? "windows" : platform}-${cpu}${platform === "darwin" ? ".tgz" : platform === "win32" ? ".exe" : ""}`;
1666
+ const bin = path2.join(
1667
+ options.cacheDir ?? await binaryCacheDirectory(),
1668
+ "cloudflared",
1669
+ CLOUDFLARED_VERSION,
1670
+ `${platform}-${arch}`,
1671
+ platform === "win32" ? "cloudflared.exe" : "cloudflared"
1672
+ );
1673
+ const cached = await cachedExecutable(bin);
1674
+ if (cached) return cached;
1675
+ await options.onProgress?.("Downloading the secure connection helper\u2026");
1676
+ const request = options.fetch ?? fetch;
1677
+ const release = await request(
1678
+ `https://api.github.com/repos/cloudflare/cloudflared/releases/tags/${CLOUDFLARED_VERSION}`,
1679
+ { headers: { Accept: "application/vnd.github+json" }, signal: AbortSignal.timeout(2e4) }
1680
+ );
1681
+ if (!release.ok) throw new Error("Couldn't download the connection helper. Retry, install cloudflared yourself, or choose another provider.");
1682
+ const metadata = await release.json();
1683
+ const item = metadata.assets?.find((value) => value.name === asset);
1684
+ const checksum = item?.digest?.match(/^sha256:([a-f0-9]{64})$/i)?.[1];
1685
+ const expectedURL = `https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}/${asset}`;
1686
+ if (!checksum || item?.browser_download_url !== expectedURL) throw new Error("The connection helper has no verified release asset for this computer.");
1687
+ const downloaded = await request(expectedURL, { signal: AbortSignal.timeout(12e4) });
1688
+ if (!downloaded.ok) throw new Error("Couldn't download the connection helper. Check your internet connection and retry.");
1689
+ const archive = new Uint8Array(await downloaded.arrayBuffer());
1690
+ await verifyReleaseBytes(archive, checksum, asset);
1691
+ let executable = archive;
1692
+ if (platform === "darwin") {
1693
+ const temporary = await mkdtemp(path2.join(tmpdir(), "mindwire-cloudflared-"));
1694
+ try {
1695
+ const archivePath = path2.join(temporary, asset);
1696
+ await writeFile(archivePath, archive, { mode: 384 });
1697
+ const result = await execute(
1698
+ "/usr/bin/tar",
1699
+ ["-xzOf", archivePath, "cloudflared"],
1700
+ { encoding: "buffer", maxBuffer: 128 * 1024 * 1024, timeout: 3e4 }
1701
+ );
1702
+ executable = new Uint8Array(result.stdout);
1703
+ } finally {
1704
+ await rm(temporary, { recursive: true, force: true });
1705
+ }
1706
+ }
1707
+ return cacheExecutable(bin, executable, await executableChecksum(executable));
1708
+ }
1709
+ async function cloudflareCommand(options) {
1710
+ try {
1711
+ await execute("cloudflared", ["--version"], { timeout: 3e3, windowsHide: true });
1712
+ return "cloudflared";
1713
+ } catch (error) {
1714
+ if (error.code !== "ENOENT") throw new Error("The installed cloudflared could not start. Repair it or choose another connection provider.");
1715
+ return ensureCloudflareBinary(options);
1716
+ }
1717
+ }
1718
+
1719
+ // src/computer/relay.ts
1720
+ function websocketURL(value) {
1721
+ const url = new URL(value);
1722
+ if (url.protocol === "https:") url.protocol = "wss:";
1723
+ if (url.protocol !== "wss:" || !url.hostname || url.username || url.password || url.hash) {
1724
+ throw new Error("Relay URLs must use wss:// with no embedded credentials or fragment.");
1725
+ }
1726
+ if (!url.pathname || url.pathname === "/") url.pathname = "/ssh";
1727
+ return url.toString();
1728
+ }
1729
+ async function startRelay(options, port, runtime = {}) {
1730
+ if (options.kind === "none") return { close() {
1731
+ } };
1732
+ if (options.kind === "custom") {
1733
+ if (!options.url) throw new Error("A custom relay needs --relay-url wss://your-host/ssh.");
1734
+ return { route: { kind: "websocket", url: websocketURL(options.url) }, close() {
1735
+ } };
1736
+ }
1737
+ const origin = `http://127.0.0.1:${port}`;
1738
+ const env = { ...process.env };
1739
+ let command, args;
1740
+ if (options.kind === "cloudflare") {
1741
+ command = await cloudflareCommand(runtime);
1742
+ await runtime.onProgress?.("Connecting through Cloudflare\u2026");
1743
+ if (options.cloudflareTokenFile) {
1744
+ if (!options.url) throw new Error("A named Cloudflare tunnel needs --relay-url for its configured hostname.");
1745
+ env.TUNNEL_TOKEN = (await readFile(options.cloudflareTokenFile, "utf8")).trim();
1746
+ args = ["tunnel", "--no-autoupdate", "run"];
1747
+ } else {
1748
+ if (options.url) throw new Error("Use --cloudflare-token-file with a named tunnel, or --relay custom for an existing tunnel.");
1749
+ args = ["tunnel", "--no-autoupdate", "--url", origin];
1750
+ }
1751
+ } else {
1752
+ command = "ngrok";
1753
+ args = ["http", origin, "--log", "stdout", "--log-format", "json"];
1754
+ if (options.url) {
1755
+ const url = new URL(websocketURL(options.url));
1756
+ args.push("--url", `https://${url.host}`);
1757
+ }
1758
+ }
1759
+ const child = spawn(command, args, { env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
1760
+ let buffer = "";
1761
+ try {
1762
+ const address = await new Promise((resolve3, reject) => {
1763
+ const timer = setTimeout(() => {
1764
+ cleanup();
1765
+ reject(new Error(`${command} did not establish its tunnel. Check its account and tunnel configuration.`));
1766
+ }, 45e3);
1767
+ const cleanup = () => {
1768
+ clearTimeout(timer);
1769
+ child.off("error", fail);
1770
+ child.off("exit", exited);
1771
+ };
1772
+ const fail = (error) => {
1773
+ cleanup();
1774
+ reject(new Error(`Could not run ${command}. Install it on the computer first.`, { cause: error }));
1775
+ };
1776
+ const exited = () => {
1777
+ cleanup();
1778
+ reject(new Error(`${command} exited before the tunnel connected. Check its account configuration.`));
1779
+ };
1780
+ let cloudflareAddress = options.url;
1781
+ let cloudflareConnected = false;
1782
+ const receive = (chunk) => {
1783
+ const received = buffer + chunk.toString();
1784
+ buffer = received.slice(-16384);
1785
+ let found;
1786
+ if (options.kind === "cloudflare") {
1787
+ cloudflareAddress ??= received.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/)?.[0];
1788
+ cloudflareConnected ||= /Registered tunnel connection/.test(received);
1789
+ if (cloudflareConnected) found = cloudflareAddress;
1790
+ } else {
1791
+ for (const line of received.split(/\r?\n/)) {
1792
+ try {
1793
+ const event = JSON.parse(line);
1794
+ if (event.msg === "started tunnel" && event.url?.startsWith("https://")) found = event.url;
1795
+ } catch {
1796
+ }
1797
+ }
1798
+ }
1799
+ if (found) {
1800
+ cleanup();
1801
+ resolve3(websocketURL(found));
1802
+ }
1803
+ };
1804
+ child.once("error", fail);
1805
+ child.once("exit", exited);
1806
+ child.stdout.on("data", receive);
1807
+ child.stderr.on("data", receive);
1808
+ });
1809
+ child.stdout.removeAllListeners("data");
1810
+ child.stderr.removeAllListeners("data");
1811
+ child.stdout.resume();
1812
+ child.stderr.resume();
1813
+ child.on("error", () => {
1814
+ });
1815
+ return { route: { kind: "websocket", url: address }, process: child, close() {
1816
+ child.kill();
1817
+ } };
1818
+ } catch (error) {
1819
+ child.kill();
1820
+ throw error;
1821
+ }
1822
+ }
1823
+
1824
+ // src/computer/lifecycle.ts
1825
+ var defaultStateDirectory = () => path2.join(homedir(), ".mindwire", "computer");
1826
+ var defaultComputerConfig = () => ({ directory: homedir(), bind: "0.0.0.0", sshPort: 8791, websocketPort: 8792, relay: { kind: "cloudflare" } });
1827
+ async function readJSON(file) {
1828
+ try {
1829
+ return JSON.parse(await fs.readFile(file, "utf8"));
1830
+ } catch (error) {
1831
+ if (error.code === "ENOENT") return void 0;
1832
+ throw error;
1833
+ }
1834
+ }
1835
+ async function writeJSON(file, value) {
1836
+ const temp = `${file}.${randomUUID()}.tmp`;
1837
+ try {
1838
+ await fs.writeFile(temp, JSON.stringify(value) + "\n", { mode: 384 });
1839
+ await fs.rename(temp, file);
1840
+ } finally {
1841
+ await fs.rm(temp, { force: true });
1842
+ }
1843
+ }
1844
+ function alive(pid) {
1845
+ if (!pid || !Number.isSafeInteger(pid) || pid < 1) return false;
1846
+ try {
1847
+ process.kill(pid, 0);
1848
+ return true;
1849
+ } catch {
1850
+ return false;
1851
+ }
1852
+ }
1853
+ async function computerClient(directory) {
1854
+ const runtime = await readJSON(path2.join(directory, "computer-runtime.json"));
1855
+ if (!runtime) throw new Error("Mindwire is not running. Run mindwire connect on the computer.");
1856
+ const url = new URL(`http://${runtime.apiAddress}`);
1857
+ if (!["127.0.0.1", "[::1]"].includes(url.hostname) || url.username || url.password) throw new Error("Invalid local Mindwire address.");
1858
+ const token = (await fs.readFile(path2.join(directory, "daemon.token"), "utf8")).trim();
1859
+ const client = new Mindwire({ target: remote(url.origin, { token }), requestTimeoutMs: 3e3 });
1860
+ const info = await client.computer.info();
1861
+ if (info.computerId !== runtime.computerId || info.pid !== runtime.pid) throw new Error("The local Mindwire process changed. Retry the command.");
1862
+ return client;
1863
+ }
1864
+ function directRoutes(config, port) {
1865
+ if (config.host) return [{ kind: "ssh", host: config.host, port }];
1866
+ if (!["0.0.0.0", "::"].includes(config.bind)) return [{ kind: "ssh", host: config.bind, port }];
1867
+ const addresses = /* @__PURE__ */ new Set();
1868
+ for (const entries of Object.values(networkInterfaces())) {
1869
+ for (const address of entries ?? []) if (address.family === "IPv4" && !address.internal) addresses.add(address.address);
1870
+ }
1871
+ return [...addresses].slice(0, 6).map((host) => ({ kind: "ssh", host, port }));
1872
+ }
1873
+ async function ensureComputer(directory, cliPath, patch = {}, onProgress) {
1874
+ await fs.mkdir(directory, { recursive: true, mode: 448 });
1875
+ let current;
1876
+ try {
1877
+ current = await computerClient(directory);
1878
+ } catch {
1879
+ }
1880
+ const configPath = path2.join(directory, "computer-config.json");
1881
+ const previous = await readJSON(configPath);
1882
+ const config = { ...defaultComputerConfig(), ...previous, ...patch };
1883
+ const waitUntilReady = async () => {
1884
+ let phase;
1885
+ for (let attempt = 0; attempt < 1200; attempt++) {
1886
+ const controller = await readJSON(path2.join(directory, "computer-controller.json"));
1887
+ if (controller?.error) throw new Error(controller.error);
1888
+ if (controller?.ready) return computerClient(directory);
1889
+ if (controller?.phase && controller.phase !== phase) {
1890
+ phase = controller.phase;
1891
+ onProgress?.(phase);
1892
+ }
1893
+ await setTimeout$1(250);
1894
+ }
1895
+ throw new Error(`Mindwire did not finish starting. Inspect ${path2.join(directory, "computer.log")}.`);
1896
+ };
1897
+ if (current) {
1898
+ if (Object.keys(patch).some((key) => JSON.stringify(config[key]) !== JSON.stringify(previous?.[key]))) {
1899
+ throw new Error("Mindwire is running with different connection settings. Run mindwire stop when idle, then retry with the new settings.");
1900
+ }
1901
+ return waitUntilReady();
1902
+ }
1903
+ const lockPath = path2.join(directory, "launch.lock");
1904
+ let lock;
1905
+ for (let attempt = 0; attempt < 120; attempt++) {
1906
+ try {
1907
+ lock = await fs.open(lockPath, "wx", 384);
1908
+ await lock.writeFile(String(process.pid));
1909
+ break;
1910
+ } catch (error) {
1911
+ if (error.code !== "EEXIST") throw error;
1912
+ const owner = Number(await fs.readFile(lockPath, "utf8").catch(() => ""));
1913
+ const age = Date.now() - (await fs.stat(lockPath).catch(() => ({ mtimeMs: Date.now() }))).mtimeMs;
1914
+ if (age > 5e3 && !alive(owner)) {
1915
+ await fs.rm(lockPath, { force: true });
1916
+ continue;
1917
+ }
1918
+ const controller = await readJSON(path2.join(directory, "computer-controller.json"));
1919
+ if (alive(controller?.pid)) {
1920
+ const saved = await readJSON(configPath);
1921
+ if (Object.keys(patch).some((key) => JSON.stringify(patch[key]) !== JSON.stringify(saved?.[key]))) {
1922
+ throw new Error("Another start used different connection settings. Stop Mindwire when idle before changing them.");
1923
+ }
1924
+ return waitUntilReady();
1925
+ }
1926
+ await setTimeout$1(250);
1927
+ }
1928
+ }
1929
+ if (!lock) throw new Error("Another Mindwire start is in progress. Try again shortly.");
1930
+ try {
1931
+ let existing;
1932
+ try {
1933
+ existing = await computerClient(directory);
1934
+ } catch {
1935
+ }
1936
+ if (existing) {
1937
+ const saved = await readJSON(configPath);
1938
+ if (Object.keys(patch).some((key) => JSON.stringify(patch[key]) !== JSON.stringify(saved?.[key]))) {
1939
+ throw new Error("Another start used different connection settings. Stop Mindwire when idle before changing them.");
1940
+ }
1941
+ return waitUntilReady();
1942
+ }
1943
+ const controller = await readJSON(path2.join(directory, "computer-controller.json"));
1944
+ if (alive(controller?.pid)) {
1945
+ if (controller?.error) throw new Error(controller.error);
1946
+ } else {
1947
+ await writeJSON(configPath, config);
1948
+ await fs.rm(path2.join(directory, "computer-controller.json"), { force: true });
1949
+ const log = await fs.open(path2.join(directory, "computer.log"), "a", 384);
1950
+ try {
1951
+ const child = spawn(process.execPath, [cliPath, "_serve", "--state-dir", directory], {
1952
+ detached: true,
1953
+ stdio: ["ignore", log.fd, log.fd],
1954
+ windowsHide: true
1955
+ });
1956
+ await new Promise((resolve3, reject) => {
1957
+ child.once("spawn", resolve3);
1958
+ child.once("error", reject);
1959
+ });
1960
+ child.unref();
1961
+ } finally {
1962
+ await log.close();
1963
+ }
1964
+ }
1965
+ return await waitUntilReady();
1966
+ } finally {
1967
+ await lock.close();
1968
+ await fs.rm(lockPath, { force: true });
1969
+ }
1970
+ }
1971
+ async function terminate(child) {
1972
+ if (child.exitCode !== null || child.signalCode !== null) return;
1973
+ const exited = new Promise((resolve3) => child.once("exit", () => resolve3()));
1974
+ child.kill("SIGTERM");
1975
+ const timer = setTimeout(() => child.kill("SIGKILL"), 15e3);
1976
+ try {
1977
+ await exited;
1978
+ } finally {
1979
+ clearTimeout(timer);
1980
+ }
1981
+ }
1982
+ async function superviseComputer(directory) {
1983
+ let config = await readJSON(path2.join(directory, "computer-config.json"));
1984
+ if (!config) throw new Error("Computer configuration is missing.");
1985
+ const controllerPath = path2.join(directory, "computer-controller.json");
1986
+ const previous = await readJSON(controllerPath);
1987
+ if (alive(previous?.pid)) throw new Error("The computer already has a service controller.");
1988
+ const phase = (message) => writeJSON(controllerPath, { pid: process.pid, ready: false, phase: message });
1989
+ await phase("Preparing Mindwire\u2026");
1990
+ let child, relay, stopping = false;
1991
+ const stop = () => {
1992
+ stopping = true;
1993
+ };
1994
+ process.on("SIGTERM", stop);
1995
+ process.on("SIGINT", stop);
1996
+ let token;
1997
+ try {
1998
+ token = (await fs.readFile(path2.join(directory, "daemon.token"), "utf8")).trim();
1999
+ } catch (error) {
2000
+ if (error.code !== "ENOENT") throw error;
2001
+ token = randomBytes(32).toString("hex");
2002
+ await fs.writeFile(path2.join(directory, "daemon.token"), token, { mode: 384, flag: "wx" });
2003
+ }
2004
+ const daemonEnv = { ...process.env };
2005
+ if (process.platform === "win32") {
2006
+ try {
2007
+ const git = execFileSync("where.exe", ["git"], { encoding: "utf8", timeout: 3e3, windowsHide: true }).split(/\r?\n/)[0];
2008
+ if (git) {
2009
+ const shellDirectory = path2.resolve(path2.dirname(git), "..", "bin");
2010
+ await fs.access(path2.join(shellDirectory, "bash.exe"));
2011
+ const pathKey = Object.keys(daemonEnv).find((key) => key.toLowerCase() === "path") ?? "PATH";
2012
+ daemonEnv[pathKey] = `${shellDirectory}${path2.delimiter}${daemonEnv[pathKey] ?? ""}`;
2013
+ }
2014
+ } catch {
2015
+ }
2016
+ }
2017
+ let sshPort = config.sshPort, websocketPort = config.websocketPort;
2018
+ const launch = async (binary) => {
2019
+ await fs.rm(path2.join(directory, "computer-runtime.json"), { force: true });
2020
+ child = spawn(binary, ["--computer"], {
2021
+ cwd: config.directory,
2022
+ stdio: ["ignore", "inherit", "inherit"],
2023
+ windowsHide: true,
2024
+ env: {
2025
+ ...daemonEnv,
2026
+ DAEMON_TOKEN: token,
2027
+ ADDR: "127.0.0.1:0",
2028
+ STATE_PATH: path2.join(directory, "agent-state.json"),
2029
+ WORKSPACE_DB_PATH: path2.join(directory, "workspace.db"),
2030
+ AGENT_CWD: config.directory,
2031
+ COMPUTER_SSH_ADDR: `${config.bind.includes(":") ? `[${config.bind}]` : config.bind}:${sshPort}`,
2032
+ COMPUTER_WS_ADDR: `127.0.0.1:${websocketPort}`,
2033
+ MINDWIRE_COMPUTER_MANAGED: "1"
2034
+ }
2035
+ });
2036
+ let failure;
2037
+ child.on("error", (error) => {
2038
+ failure = error;
2039
+ });
2040
+ for (let attempt = 0; attempt < 100; attempt++) {
2041
+ if (failure) throw failure;
2042
+ if (child.exitCode !== null || child.signalCode !== null) throw new Error("Mindwire exited during startup. Check computer.log; the downloaded release must support computer connections.");
2043
+ try {
2044
+ const client = await computerClient(directory);
2045
+ const health = await client.health();
2046
+ if (health.computerConnectionVersion !== 1) throw new Error("This daemon release does not support computer connections. Update Mindwire.");
2047
+ return client;
2048
+ } catch (error) {
2049
+ if (attempt === 99) throw error;
2050
+ }
2051
+ await setTimeout$1(100);
2052
+ }
2053
+ throw new Error("Mindwire startup timed out.");
2054
+ };
2055
+ let routes = [];
2056
+ try {
2057
+ await phase("Checking the Mindwire service\u2026");
2058
+ let binary = config.daemonBin ?? await ensureDaemonBinary({ version: config.version ?? SDK_VERSION, cacheDir: process.env.MINDWIRE_RELEASE_CACHE_DIR });
2059
+ await phase("Starting the Mindwire service\u2026");
2060
+ let client = await launch(binary);
2061
+ const info = await client.computer.info();
2062
+ sshPort = info.sshPort;
2063
+ websocketPort = info.websocketPort;
2064
+ await phase(config.relay.kind === "none" ? "Preparing direct SSH\u2026" : "Preparing your internet connection\u2026");
2065
+ relay = await startRelay(config.relay, info.websocketPort, { cacheDir: path2.join(directory, "tools"), onProgress: phase });
2066
+ routes = directRoutes(config, info.sshPort);
2067
+ if (relay.route) routes.push(relay.route);
2068
+ if (routes.length === 0) throw new Error("No network address is available. Use --host with your LAN/VPN address or choose a relay.");
2069
+ await client.computer.setRoutes(routes);
2070
+ await writeJSON(controllerPath, { pid: process.pid, ready: true, routes });
2071
+ while (!stopping) {
2072
+ await setTimeout$1(500);
2073
+ if (child.exitCode !== null || child.signalCode !== null) throw new Error("The Mindwire service stopped. Run mindwire start to reconnect.");
2074
+ if (relay.process && (relay.process.exitCode !== null || relay.process.signalCode !== null)) {
2075
+ routes = routes.filter((r) => r.kind === "ssh");
2076
+ if (routes.length > 0) await client.computer.setRoutes(routes);
2077
+ await writeJSON(controllerPath, { pid: process.pid, ready: true, routes, error: "The relay disconnected. Direct SSH still works. Restart Mindwire when idle to reconnect the relay." });
2078
+ relay = { close() {
2079
+ } };
2080
+ }
2081
+ const updatePath = path2.join(directory, "computer-update.json");
2082
+ const update = await readJSON(updatePath);
2083
+ if (!update || !["queued", "downloading", "waiting", "restarting"].includes(update.status)) continue;
2084
+ const status = async (state, error) => writeJSON(updatePath, { ...update, status: state, error, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
2085
+ try {
2086
+ await status("downloading");
2087
+ const replacement = await ensureDaemonBinary({ version: update.version, cacheDir: process.env.MINDWIRE_RELEASE_CACHE_DIR });
2088
+ await status("waiting");
2089
+ let lease;
2090
+ while (!stopping && !lease) {
2091
+ try {
2092
+ lease = await client.service.acquireUpdate();
2093
+ } catch (error) {
2094
+ if (error.status !== 409) throw error;
2095
+ await setTimeout$1(2e3);
2096
+ }
2097
+ }
2098
+ if (stopping || !lease) break;
2099
+ if (lease.pid !== child.pid) {
2100
+ await client.service.releaseUpdate(lease.id);
2101
+ throw new Error("The leased service process changed.");
2102
+ }
2103
+ await status("restarting");
2104
+ await terminate(child);
2105
+ try {
2106
+ client = await launch(replacement);
2107
+ await client.computer.setRoutes(routes);
2108
+ const health = await client.health();
2109
+ if (health.version.replace(/^v/, "") !== update.version) throw new Error("The replacement service reports a different release version.");
2110
+ } catch (error) {
2111
+ if (child) await terminate(child);
2112
+ client = await launch(binary);
2113
+ await client.computer.setRoutes(routes);
2114
+ throw error;
2115
+ }
2116
+ binary = replacement;
2117
+ config = { ...config, daemonBin: void 0, version: update.version };
2118
+ await writeJSON(path2.join(directory, "computer-config.json"), config);
2119
+ await status("complete");
2120
+ } catch (error) {
2121
+ await status("failed", error instanceof Error ? error.message : "Service update failed.");
2122
+ }
2123
+ }
2124
+ } catch (error) {
2125
+ await writeJSON(controllerPath, { pid: process.pid, ready: false, error: error instanceof Error ? error.message : "Computer service failed." });
2126
+ throw error;
2127
+ } finally {
2128
+ relay?.close();
2129
+ if (child) await terminate(child);
2130
+ process.off("SIGTERM", stop);
2131
+ process.off("SIGINT", stop);
2132
+ if (stopping) await writeJSON(controllerPath, { pid: 0, ready: false });
2133
+ }
2134
+ }
2135
+ async function stopComputer(directory, force = false) {
2136
+ const client = await computerClient(directory);
2137
+ const controller = await readJSON(path2.join(directory, "computer-controller.json"));
2138
+ if (!alive(controller?.pid)) throw new Error("The Mindwire controller is not running.");
2139
+ const lease = force ? void 0 : await client.service.acquireUpdate();
2140
+ try {
2141
+ process.kill(controller.pid, "SIGTERM");
2142
+ } catch (error) {
2143
+ if (lease) await client.service.releaseUpdate(lease.id);
2144
+ throw error;
2145
+ }
2146
+ for (let attempt = 0; attempt < 80; attempt++) {
2147
+ if (!alive(controller.pid)) return;
2148
+ await setTimeout$1(250);
2149
+ }
2150
+ throw new Error("Mindwire is still stopping. Check computer.log.");
2151
+ }
2152
+
2153
+ // src/cli.ts
2154
+ var help = `Mindwire \u2014 connect this computer to your phone
2155
+
2156
+ npm install -g mindwire
2157
+ mindwire connect Connect across networks, show QR, approve phone
2158
+ mindwire connect --relay none --host laptop.tailnet Use your existing VPN
2159
+ mindwire connect --relay none Direct SSH only (reachable network required)
2160
+ mindwire connect --relay cloudflare Cloudflare quick tunnel
2161
+ mindwire connect --relay ngrok ngrok (uses its configured account)
2162
+ mindwire connect --relay custom --relay-url wss://computer.example/ssh
2163
+
2164
+ mindwire start Start the saved connection in the background
2165
+ mindwire status Show connection and running service
2166
+ mindwire devices List paired phones
2167
+ mindwire revoke DEVICE_ID Disconnect and revoke one phone
2168
+ mindwire update [--version VERSION] Download a verified release; wait until idle
2169
+ mindwire stop Stop when no work or terminals are running
2170
+
2171
+ Options:
2172
+ --directory PATH Initial workspace directory (default: home)
2173
+ --host HOST Reachable LAN, public or VPN hostname
2174
+ --relay none|cloudflare|ngrok|custom Provider (default: Cloudflare internet tunnel)
2175
+ --relay-url URL Stable configured WebSocket hostname
2176
+ --cloudflare-token-file PATH Named Cloudflare tunnel token file
2177
+ --state-dir PATH Private state directory
2178
+ --json Structured output (QR invitation includes a secret)
2179
+ --no-qr Print only the pairing link
2180
+
2181
+ The default works across Wi-Fi and mobile networks. Mindwire privately downloads
2182
+ a verified Cloudflare helper when needed. Relays carry encrypted SSH.
2183
+ Quick tunnel addresses change on restart; use a stable hostname/VPN for regular use.
2184
+ ngrok needs its installed CLI and account. Direct SSH needs no relay when reachable.
2185
+ Nothing changes your system SSH login.
2186
+ `;
2187
+ function safeName(text) {
2188
+ return text.replace(/[\x00-\x1f\x7f-\x9f]/g, "");
2189
+ }
2190
+ async function main(args = process.argv.slice(2)) {
2191
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
2192
+ help: { type: "boolean", short: "h" },
2193
+ json: { type: "boolean" },
2194
+ "no-qr": { type: "boolean" },
2195
+ "state-dir": { type: "string" },
2196
+ directory: { type: "string" },
2197
+ host: { type: "string" },
2198
+ relay: { type: "string" },
2199
+ "relay-url": { type: "string" },
2200
+ "cloudflare-token-file": { type: "string" },
2201
+ "daemon-bin": { type: "string" },
2202
+ bind: { type: "string" },
2203
+ port: { type: "string" },
2204
+ "websocket-port": { type: "string" },
2205
+ version: { type: "string" },
2206
+ force: { type: "boolean" }
2207
+ } });
2208
+ const command = positionals[0] ?? "help";
2209
+ if (values.help || command === "help") {
2210
+ process.stdout.write(help);
2211
+ return;
2212
+ }
2213
+ const directory = path2.resolve(values["state-dir"] ?? defaultStateDirectory());
2214
+ const emit2 = (event, data = {}, text) => {
2215
+ if (values.json) process.stdout.write(JSON.stringify({ event, ...data }) + "\n");
2216
+ else if (text) process.stdout.write(text + "\n");
2217
+ };
2218
+ if (command === "_serve") {
2219
+ await superviseComputer(directory);
2220
+ return;
2221
+ }
2222
+ if (["connect", "start"].includes(command)) {
2223
+ const patch = {};
2224
+ if (values.directory) patch.directory = path2.resolve(values.directory);
2225
+ if (values.host) patch.host = values.host;
2226
+ if (values.bind) patch.bind = values.bind;
2227
+ for (const [flag, field] of [["port", "sshPort"], ["websocket-port", "websocketPort"]]) {
2228
+ if (values[flag] !== void 0) {
2229
+ const n = Number(values[flag]);
2230
+ if (!Number.isInteger(n) || n < 0 || n > 65535) throw new Error(`Invalid --${flag}.`);
2231
+ patch[field] = n;
2232
+ }
2233
+ }
2234
+ if (values["daemon-bin"] || process.env.MINDWIRE_DAEMON) patch.daemonBin = path2.resolve(values["daemon-bin"] ?? process.env.MINDWIRE_DAEMON);
2235
+ if (values.version) patch.version = values.version.replace(/^v/, "");
2236
+ if (values.relay || values["relay-url"] || values["cloudflare-token-file"]) {
2237
+ const kind = values.relay ?? "custom";
2238
+ if (!["none", "cloudflare", "ngrok", "custom"].includes(kind)) throw new Error("Choose relay none, cloudflare, ngrok or custom.");
2239
+ patch.relay = {
2240
+ kind,
2241
+ url: values["relay-url"],
2242
+ cloudflareTokenFile: values["cloudflare-token-file"] ? path2.resolve(values["cloudflare-token-file"]) : void 0
2243
+ };
2244
+ }
2245
+ emit2("starting", {}, "Starting Mindwire\u2026");
2246
+ const client2 = await ensureComputer(
2247
+ directory,
2248
+ fileURLToPath(import.meta.url),
2249
+ patch,
2250
+ (phase) => emit2("progress", { message: phase }, phase)
2251
+ );
2252
+ const info = await client2.computer.info();
2253
+ emit2("ready", { computerId: info.computerId, routes: info.routes }, "Mindwire is running in the background.");
2254
+ if (command === "start") return;
2255
+ if (info.routes.some((route) => route.kind === "websocket" && new URL(route.url).hostname.endsWith(".trycloudflare.com"))) {
2256
+ emit2("temporary_address", {}, "Internet access is ready. This quick-tunnel address changes after a restart; use a stable hostname or VPN for regular access.");
2257
+ }
2258
+ const invitation = await client2.computer.invite(info.routes);
2259
+ const uri = computerPairingURI(invitation);
2260
+ emit2("invitation", { invitation, uri }, "Open Mindwire on your phone \u2192 Add computer \u2192 Scan QR code.");
2261
+ if (!values.json) {
2262
+ if (!values["no-qr"]) {
2263
+ const QR = await import('qrcode');
2264
+ process.stdout.write(await QR.toString(uri, { type: "terminal", small: true, errorCorrectionLevel: "L" }));
2265
+ }
2266
+ process.stdout.write(`
2267
+ Pairing link (expires in 5 minutes):
2268
+ ${uri}
2269
+
2270
+ Waiting for your phone\u2026
2271
+ `);
2272
+ }
2273
+ let shownRequest;
2274
+ while (Date.now() < Date.parse(invitation.expiresAt)) {
2275
+ const pairing = await client2.computer.pairing(invitation.pairingId);
2276
+ if (pairing.status === "approved") {
2277
+ emit2("paired", {}, "Phone connected. You can close this terminal; Mindwire keeps running.");
2278
+ return;
2279
+ }
2280
+ if (pairing.status === "rejected") {
2281
+ emit2("rejected", {}, "Pairing declined.");
2282
+ return;
2283
+ }
2284
+ if (pairing.request && shownRequest !== pairing.request.id) {
2285
+ shownRequest = pairing.request.id;
2286
+ const key = Buffer.from(pairing.request.publicKey.split(" ")[1] ?? "", "base64");
2287
+ const fingerprint = "SHA256:" + createHash("sha256").update(key).digest("base64").replace(/=+$/, "");
2288
+ emit2(
2289
+ "approval_required",
2290
+ { pairingId: invitation.pairingId, request: pairing.request, fingerprint },
2291
+ `
2292
+ ${safeName(pairing.request.name)} wants to connect.
2293
+ Device key: ${fingerprint}`
2294
+ );
2295
+ if (!process.stdin.isTTY) {
2296
+ emit2(
2297
+ "approval_command",
2298
+ { command: `mindwire approve ${invitation.pairingId} ${pairing.request.id}` },
2299
+ `Review this device, then run:
2300
+ mindwire approve ${invitation.pairingId} ${pairing.request.id}`
2301
+ );
2302
+ } else {
2303
+ const input = createInterface({ input: process.stdin, output: process.stderr });
2304
+ try {
2305
+ const answer = await input.question("Allow this phone to access this workspace? [y/N] ");
2306
+ await client2.computer.decide(invitation.pairingId, pairing.request.id, /^y(es)?$/i.test(answer.trim()));
2307
+ } finally {
2308
+ input.close();
2309
+ }
2310
+ }
2311
+ }
2312
+ await setTimeout$1(750);
2313
+ }
2314
+ throw new Error("Pairing expired. Run mindwire connect to show a new QR code.");
2315
+ }
2316
+ if (command === "stop") {
2317
+ await stopComputer(directory, values.force === true);
2318
+ emit2("stopped", {}, "Mindwire stopped.");
2319
+ return;
2320
+ }
2321
+ const client = await computerClient(directory);
2322
+ switch (command) {
2323
+ case "status": {
2324
+ const [info, health, work, controller] = await Promise.all([
2325
+ client.computer.info(),
2326
+ client.health(),
2327
+ client.service.updateStatus(),
2328
+ readJSON(path2.join(directory, "computer-controller.json"))
2329
+ ]);
2330
+ emit2(
2331
+ "status",
2332
+ { ...info, daemonVersion: health.version, ...work, relayError: controller?.error },
2333
+ `Mindwire ${health.version} \xB7 ${work.idle ? "idle" : "working"}
2334
+ ${info.routes.map((route) => route.kind === "ssh" ? `SSH ${route.host}:${route.port}` : route.url).join("\n")}${controller?.error ? `
2335
+ ${controller.error}` : ""}`
2336
+ );
2337
+ break;
2338
+ }
2339
+ case "devices": {
2340
+ const devices = await client.computer.devices();
2341
+ emit2("devices", { devices }, devices.length ? devices.map((d) => `${safeName(d.name)} ${d.id}${d.revoked ? " (revoked)" : ""}`).join("\n") : "No paired phones yet. Run mindwire connect.");
2342
+ break;
2343
+ }
2344
+ case "revoke": {
2345
+ if (!positionals[1]) throw new Error("Use mindwire revoke DEVICE_ID (from mindwire devices).");
2346
+ await client.computer.revoke(positionals[1]);
2347
+ emit2("revoked", {}, "Device revoked and disconnected.");
2348
+ break;
2349
+ }
2350
+ case "approve":
2351
+ case "reject": {
2352
+ if (!positionals[1] || !positionals[2]) throw new Error(`Use mindwire ${command} PAIRING_ID REQUEST_ID.`);
2353
+ await client.computer.decide(positionals[1], positionals[2], command === "approve");
2354
+ emit2(command, {}, command === "approve" ? "Phone approved." : "Phone declined.");
2355
+ break;
2356
+ }
2357
+ case "update": {
2358
+ const version = (values.version ?? SDK_VERSION).replace(/^v/, "");
2359
+ const health = await client.health();
2360
+ if (health.version.replace(/^v/, "") === version) {
2361
+ emit2("updated", { version }, `Mindwire ${version} is already installed.`);
2362
+ return;
2363
+ }
2364
+ const requested = await client.computer.requestUpdate(version);
2365
+ emit2("update_queued", requested, "Update queued. It will wait until all work and terminals are finished.");
2366
+ let last = "";
2367
+ for (; ; ) {
2368
+ const update = await readJSON(path2.join(directory, "computer-update.json"));
2369
+ if (update?.id !== requested.id) throw new Error("The update request changed. Run mindwire status.");
2370
+ if (update.status !== last) {
2371
+ last = update.status;
2372
+ emit2("update", update, `Update: ${update.status}`);
2373
+ }
2374
+ if (update.status === "complete") return;
2375
+ if (update.status === "failed") throw new Error(update.error ?? "Update failed.");
2376
+ await setTimeout$1(750);
2377
+ }
2378
+ }
2379
+ default:
2380
+ throw new Error(`Unknown command ${command}. Run mindwire --help.`);
2381
+ }
2382
+ }
2383
+ if (process.argv[1] && import.meta.url === pathToFileURL(path2.resolve(process.argv[1])).href) {
2384
+ void main().catch((error) => {
2385
+ const message = error instanceof Error ? error.message : String(error);
2386
+ if (process.argv.includes("--json")) process.stderr.write(JSON.stringify({ event: "error", message }) + "\n");
2387
+ else process.stderr.write(`Mindwire: ${message}
2388
+ `);
2389
+ process.exitCode = 1;
2390
+ });
2391
+ }
2392
+
2393
+ export { main };
2394
+ //# sourceMappingURL=cli.js.map
2395
+ //# sourceMappingURL=cli.js.map