mindwire 0.1.0 → 0.1.1

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/index.cjs ADDED
@@ -0,0 +1,2297 @@
1
+ 'use strict';
2
+
3
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
4
+ // src/errors.ts
5
+ var MindwireError = class extends Error {
6
+ constructor(message, options) {
7
+ super(message, options);
8
+ this.name = "MindwireError";
9
+ }
10
+ };
11
+ var ApiError = class _ApiError extends MindwireError {
12
+ status;
13
+ url;
14
+ method;
15
+ body;
16
+ constructor(args) {
17
+ super(_ApiError.messageFor(args));
18
+ this.name = "ApiError";
19
+ this.status = args.status;
20
+ this.url = args.url;
21
+ this.method = args.method;
22
+ this.body = args.body;
23
+ }
24
+ static messageFor({
25
+ status,
26
+ method,
27
+ url,
28
+ body
29
+ }) {
30
+ const detail = body && typeof body === "object" && "error" in body && typeof body.error === "string" ? body.error : typeof body === "string" && body.trim() !== "" ? body.trim() : "";
31
+ const base = `${method} ${url} failed with ${status}`;
32
+ return detail ? `${base}: ${detail}` : base;
33
+ }
34
+ };
35
+ var RunFailedError = class extends MindwireError {
36
+ status;
37
+ runId;
38
+ constructor(runId, status, detail) {
39
+ super(detail ? `run ${runId} ${status}: ${detail}` : `run ${runId} ${status}`);
40
+ this.name = "RunFailedError";
41
+ this.runId = runId;
42
+ this.status = status;
43
+ }
44
+ };
45
+ var TimeoutError = class extends MindwireError {
46
+ method;
47
+ path;
48
+ timeoutMs;
49
+ constructor(method, path, timeoutMs) {
50
+ super(`mindwire: ${method} ${path} timed out after ${timeoutMs}ms`);
51
+ this.name = "TimeoutError";
52
+ this.method = method;
53
+ this.path = path;
54
+ this.timeoutMs = timeoutMs;
55
+ }
56
+ };
57
+
58
+ // src/http.ts
59
+ var DEFAULT_TIMEOUT_MS = 12e4;
60
+ function isAbortError(e) {
61
+ return typeof e === "object" && e !== null && e.name === "AbortError";
62
+ }
63
+ var Http = class {
64
+ fetchImpl;
65
+ baseHeaders;
66
+ resolver;
67
+ timeoutMs;
68
+ cached = null;
69
+ pending = null;
70
+ constructor(opts) {
71
+ const f = opts.fetch ?? globalThis.fetch;
72
+ if (!f) {
73
+ throw new MindwireError(
74
+ "mindwire: no global fetch found \u2014 pass a `fetch` implementation in the client options"
75
+ );
76
+ }
77
+ this.fetchImpl = f;
78
+ this.baseHeaders = { ...opts.headers };
79
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
80
+ if (opts.baseUrl) {
81
+ const base = { baseUrl: opts.baseUrl.replace(/\/+$/, ""), token: opts.token };
82
+ this.resolver = async () => base;
83
+ } else if (opts.resolveBase) {
84
+ const rb = opts.resolveBase;
85
+ this.resolver = async () => {
86
+ const r = await rb();
87
+ return {
88
+ baseUrl: r.baseUrl.replace(/\/+$/, ""),
89
+ token: r.token ?? opts.token,
90
+ getToken: r.getToken,
91
+ headers: r.headers,
92
+ fetch: r.fetch
93
+ };
94
+ };
95
+ } else {
96
+ throw new MindwireError("mindwire: Http requires a baseUrl or a resolveBase");
97
+ }
98
+ }
99
+ /**
100
+ * One fetch, with raw network failures wrapped as {@link MindwireError} so callers see a typed
101
+ * SDK error instead of a bare `TypeError: fetch failed`. An abort (the request's own signal, or
102
+ * our timeout controller) is re-thrown untouched — `fetchWithTimeout` classifies it.
103
+ */
104
+ async fetchOnce(f, url, init, method, path) {
105
+ try {
106
+ return await f(url, init);
107
+ } catch (e) {
108
+ const aborted = init.signal?.aborted ?? false;
109
+ if (aborted || isAbortError(e)) throw e;
110
+ throw new MindwireError(`mindwire: ${method} ${path} \u2014 network request failed`, { cause: e });
111
+ }
112
+ }
113
+ /**
114
+ * `fetchOnce` plus a timeout that composes with the caller's `signal`. A hand-rolled controller
115
+ * (not `AbortSignal.timeout`/`AbortSignal.any`, which need Node 20.3+/18.17+) fires after
116
+ * `timeoutMs`; whichever aborts first wins. Timeout → {@link TimeoutError}; the caller's own abort
117
+ * propagates as-is (its `reason`). `timeoutMs<=0` disables the deadline entirely.
118
+ */
119
+ async fetchWithTimeout(f, url, init, userSignal, method, path) {
120
+ if (!this.timeoutMs || this.timeoutMs <= 0) {
121
+ return this.fetchOnce(f, url, { ...init, ...userSignal ? { signal: userSignal } : {} }, method, path);
122
+ }
123
+ const ctrl = new AbortController();
124
+ const onAbort = () => ctrl.abort(userSignal?.reason);
125
+ if (userSignal) {
126
+ if (userSignal.aborted) ctrl.abort(userSignal.reason);
127
+ else userSignal.addEventListener("abort", onAbort, { once: true });
128
+ }
129
+ let timedOut = false;
130
+ const timer = setTimeout(() => {
131
+ timedOut = true;
132
+ ctrl.abort();
133
+ }, this.timeoutMs);
134
+ try {
135
+ return await this.fetchOnce(f, url, { ...init, signal: ctrl.signal }, method, path);
136
+ } catch (e) {
137
+ if (timedOut) throw new TimeoutError(method, path, this.timeoutMs);
138
+ if (userSignal?.aborted) throw userSignal.reason ?? e;
139
+ throw e;
140
+ } finally {
141
+ clearTimeout(timer);
142
+ if (userSignal) userSignal.removeEventListener("abort", onAbort);
143
+ }
144
+ }
145
+ /**
146
+ * The bearer token for the next request. Prefers the transport's dynamic `getToken` (which
147
+ * caches and mints on demand); falls back to the static token resolved at base time. `force`
148
+ * asks the getter to re-mint — used once on a 401 before retrying.
149
+ */
150
+ async authToken(base, force) {
151
+ if (base.getToken) {
152
+ const t = await base.getToken(force ? { force: true } : void 0);
153
+ return t ?? base.token;
154
+ }
155
+ return base.token;
156
+ }
157
+ base() {
158
+ if (this.cached) return Promise.resolve(this.cached);
159
+ if (!this.pending) {
160
+ this.pending = this.resolver().then((b) => this.cached = b).catch((err) => {
161
+ this.pending = null;
162
+ throw err;
163
+ });
164
+ }
165
+ return this.pending;
166
+ }
167
+ /**
168
+ * Resolve the base eagerly and memoize it — provisions the transport (spawns the embedded daemon,
169
+ * connects the sandbox/SSH/Docker target, …) now instead of on the first request. Idempotent: this
170
+ * awaits the *same* memoized promise the first `request()`/`open()` awaits, so the target's
171
+ * `connect()` fires exactly once. Backs {@link import("./client.js").Mindwire.ensure}.
172
+ */
173
+ async ready() {
174
+ await this.base();
175
+ }
176
+ url(baseUrl, path, query) {
177
+ const u = new URL(baseUrl + (path.startsWith("/") ? path : `/${path}`));
178
+ if (query) {
179
+ for (const [k, v] of Object.entries(query)) {
180
+ if (v !== void 0) u.searchParams.set(k, String(v));
181
+ }
182
+ }
183
+ return u.toString();
184
+ }
185
+ headers(token, extra, hasBody = false) {
186
+ const h = { Accept: "application/json", ...this.baseHeaders, ...extra };
187
+ if (token) h["Authorization"] = `Bearer ${token}`;
188
+ if (hasBody) h["Content-Type"] = "application/json";
189
+ return h;
190
+ }
191
+ async request(method, path, init = {}) {
192
+ const base = await this.base();
193
+ const hasBody = init.body !== void 0;
194
+ const url = this.url(base.baseUrl, path, init.query);
195
+ const extra = { ...base.headers, ...init.headers };
196
+ const f = base.fetch ?? this.fetchImpl;
197
+ const send = async (force) => this.fetchWithTimeout(
198
+ f,
199
+ url,
200
+ {
201
+ method,
202
+ headers: this.headers(await this.authToken(base, force), extra, hasBody),
203
+ body: hasBody ? JSON.stringify(init.body) : void 0
204
+ },
205
+ init.signal,
206
+ method,
207
+ path
208
+ );
209
+ let res = await send(false);
210
+ if (res.status === 401 && base.getToken) res = await send(true);
211
+ if (!res.ok) throw await this.toApiError(method, res);
212
+ if (res.status === 204) return void 0;
213
+ const text = await res.text();
214
+ if (text === "") return void 0;
215
+ try {
216
+ return JSON.parse(text);
217
+ } catch (e) {
218
+ throw new MindwireError(`mindwire: ${method} ${path} returned a non-JSON body`, { cause: e });
219
+ }
220
+ }
221
+ /** Open a streaming response (SSE). Caller owns the body. */
222
+ async open(method, path, init = {}) {
223
+ const base = await this.base();
224
+ const url = this.url(base.baseUrl, path, init.query);
225
+ const extra = { Accept: "text/event-stream", ...base.headers, ...init.headers };
226
+ const f = base.fetch ?? this.fetchImpl;
227
+ const send = async (force) => this.fetchOnce(
228
+ f,
229
+ url,
230
+ {
231
+ method,
232
+ headers: this.headers(await this.authToken(base, force), extra),
233
+ ...init.signal ? { signal: init.signal } : {}
234
+ },
235
+ method,
236
+ path
237
+ );
238
+ let res = await send(false);
239
+ if (res.status === 401 && base.getToken) res = await send(true);
240
+ if (!res.ok) throw await this.toApiError(method, res);
241
+ if (!res.body)
242
+ throw new MindwireError(`mindwire: ${method} ${path} returned no response body to stream`);
243
+ return res;
244
+ }
245
+ async toApiError(method, res) {
246
+ let body = "";
247
+ try {
248
+ const text = await res.text();
249
+ try {
250
+ body = text ? JSON.parse(text) : "";
251
+ } catch {
252
+ body = text;
253
+ }
254
+ } catch {
255
+ }
256
+ return new ApiError({ status: res.status, url: res.url, method, body });
257
+ }
258
+ };
259
+
260
+ // src/sse.ts
261
+ async function* readSSE(body, signal) {
262
+ const reader = body.getReader();
263
+ const decoder = new TextDecoder();
264
+ let buffer = "";
265
+ const onAbort = () => void reader.cancel().catch(() => {
266
+ });
267
+ if (signal) {
268
+ if (signal.aborted) {
269
+ await reader.cancel().catch(() => {
270
+ });
271
+ return;
272
+ }
273
+ signal.addEventListener("abort", onAbort, { once: true });
274
+ }
275
+ try {
276
+ for (; ; ) {
277
+ const { done, value } = await reader.read();
278
+ if (done) break;
279
+ buffer += decoder.decode(value, { stream: true });
280
+ let sep;
281
+ while ((sep = indexOfBlankLine(buffer)) !== -1) {
282
+ const rawEvent = buffer.slice(0, sep);
283
+ buffer = buffer.slice(sepEnd(buffer, sep));
284
+ const payload2 = parseEvent(rawEvent);
285
+ if (payload2 !== void 0) yield JSON.parse(payload2);
286
+ }
287
+ }
288
+ const payload = parseEvent(buffer);
289
+ if (payload !== void 0) yield JSON.parse(payload);
290
+ } finally {
291
+ if (signal) signal.removeEventListener("abort", onAbort);
292
+ reader.releaseLock();
293
+ }
294
+ }
295
+ function indexOfBlankLine(s) {
296
+ const a = s.indexOf("\n\n");
297
+ const b = s.indexOf("\r\n\r\n");
298
+ if (a === -1) return b;
299
+ if (b === -1) return a;
300
+ return Math.min(a, b);
301
+ }
302
+ function sepEnd(s, idx) {
303
+ return s.startsWith("\r\n\r\n", idx) ? idx + 4 : idx + 2;
304
+ }
305
+ function parseEvent(block) {
306
+ const lines = block.split(/\r\n|\n/);
307
+ const data = [];
308
+ for (const line of lines) {
309
+ if (line === "" || line.startsWith(":")) continue;
310
+ const colon = line.indexOf(":");
311
+ const field = colon === -1 ? line : line.slice(0, colon);
312
+ if (field !== "data") continue;
313
+ let value = colon === -1 ? "" : line.slice(colon + 1);
314
+ if (value.startsWith(" ")) value = value.slice(1);
315
+ data.push(value);
316
+ }
317
+ if (data.length === 0) return void 0;
318
+ return data.join("\n");
319
+ }
320
+
321
+ // src/run.ts
322
+ var TERMINAL = /* @__PURE__ */ new Set(["done", "error", "cancelled"]);
323
+ var Run = class _Run {
324
+ data;
325
+ http;
326
+ constructor(http, data) {
327
+ this.http = http;
328
+ this.data = data;
329
+ }
330
+ get id() {
331
+ return this.data.id;
332
+ }
333
+ get chatId() {
334
+ return this.data.chatId;
335
+ }
336
+ get agent() {
337
+ return this.data.agent;
338
+ }
339
+ get status() {
340
+ return this.data.status;
341
+ }
342
+ /** `"resolve"` on the parent of a global-resolve run; `undefined` for an ordinary turn. */
343
+ get kind() {
344
+ return this.data.kind;
345
+ }
346
+ /** On a child iteration of a resolve run, the id of its parent resolve run; else `undefined`. */
347
+ get parentId() {
348
+ return this.data.parentId;
349
+ }
350
+ /** Parent of a resolve run only: why the loop ended (`"done"` | `"capped"` | `"error"` | …). */
351
+ get stopReason() {
352
+ return this.data.stopReason;
353
+ }
354
+ /** Parent of a resolve run only: how many child turns the loop ran. */
355
+ get iterations() {
356
+ return this.data.iterations;
357
+ }
358
+ /** The latest known run record. */
359
+ get value() {
360
+ return this.data;
361
+ }
362
+ /** Unified SSE event stream: replay buffer, then live events, then close. */
363
+ async *stream(opts = {}) {
364
+ const res = await this.http.open("GET", `/runs/${encodeURIComponent(this.id)}/stream`, {
365
+ ...opts.signal ? { signal: opts.signal } : {}
366
+ });
367
+ for await (const ev of readSSE(res.body, opts.signal)) {
368
+ if (!opts.includeOpenSentinel && ev.type === "status" && ev.meta?.["stream"] === "open") {
369
+ continue;
370
+ }
371
+ yield ev;
372
+ }
373
+ }
374
+ /** `for await (const ev of run)` — sugar for `run.stream()`. */
375
+ [Symbol.asyncIterator]() {
376
+ return this.stream();
377
+ }
378
+ /** Cancel the in-flight turn (kills the underlying agent process). */
379
+ async cancel() {
380
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/cancel`);
381
+ }
382
+ /**
383
+ * Answer a mid-turn interaction the turn is waiting on — a permission approval, or an
384
+ * AskUserQuestion / ExitPlanMode reply. Requires the agent's `respond` capability.
385
+ */
386
+ async respond(input = {}) {
387
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/respond`, { body: input });
388
+ }
389
+ /**
390
+ * Steer a follow-up message into the running turn without cancelling it. Requires the agent's
391
+ * `input` capability.
392
+ */
393
+ async sendInput(text) {
394
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/input`, { body: { text } });
395
+ }
396
+ /**
397
+ * Soft-stop the running turn (ask the agent to halt current work) without the hard process kill
398
+ * {@link Run.cancel} does — the turn stays open for a follow-up via {@link Run.sendInput}.
399
+ * Requires the agent's `interrupt` capability.
400
+ */
401
+ async interrupt() {
402
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/interrupt`);
403
+ }
404
+ /**
405
+ * Switch the model of the live turn. An empty/omitted `model` resets the turn to the agent/CLI
406
+ * default. Only meaningful on a persistent (non-bypass) turn; on a one-shot turn it is a
407
+ * best-effort no-op. Requires the agent's `setModel` capability.
408
+ */
409
+ async setModel(model) {
410
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/set-model`, {
411
+ body: { model: model ?? "" }
412
+ });
413
+ }
414
+ /**
415
+ * Switch the permission mode of the live turn (e.g. `default`, `acceptEdits`, `plan`,
416
+ * `bypassPermissions`). Only meaningful on a persistent (non-bypass) turn; on a one-shot turn it
417
+ * is a best-effort no-op. Requires the agent's `setPermissionMode` capability.
418
+ */
419
+ async setPermissionMode(mode) {
420
+ await this.http.request("POST", `/runs/${encodeURIComponent(this.id)}/set-permission-mode`, {
421
+ body: { mode }
422
+ });
423
+ }
424
+ /**
425
+ * `GET /runs/{id}/children` — the child iterations of a global-resolve run, oldest→newest, each as
426
+ * its own {@link Run} handle. An ordinary turn (or a resolve that ran a single iteration) returns an
427
+ * empty array. Use it to inspect the run tree a {@link Mindwire.resolve} produced.
428
+ */
429
+ async children() {
430
+ const data = await this.http.request(
431
+ "GET",
432
+ `/runs/${encodeURIComponent(this.id)}/children`
433
+ );
434
+ return data.map((d) => new _Run(this.http, d));
435
+ }
436
+ /** Re-fetch the run record from the daemon and update this handle. */
437
+ async refresh() {
438
+ this.data = await this.http.request("GET", `/runs/${encodeURIComponent(this.id)}`);
439
+ return this.data;
440
+ }
441
+ /**
442
+ * Consume the event stream to completion. Returns the final run record and the `result`
443
+ * event's summary (if any). Throws {@link RunFailedError} on an `error`/`cancelled` outcome
444
+ * unless `throwOnError` is set to `false`.
445
+ */
446
+ async wait(opts = {}) {
447
+ let result;
448
+ let streamError;
449
+ for await (const ev of this.stream(opts)) {
450
+ if (ev.type === "result") result = ev.result;
451
+ else if (ev.type === "error") streamError = ev.error;
452
+ }
453
+ const run = await this.refresh();
454
+ if (opts.throwOnError !== false) {
455
+ if (TERMINAL.has(run.status)) {
456
+ if (run.status !== "done") {
457
+ throw new RunFailedError(run.id, run.status, run.error ?? streamError);
458
+ }
459
+ } else {
460
+ throw new RunFailedError(
461
+ run.id,
462
+ run.status,
463
+ streamError ?? "event stream ended before the run reached a terminal state"
464
+ );
465
+ }
466
+ }
467
+ return result !== void 0 ? { run, result } : { run };
468
+ }
469
+ };
470
+
471
+ // src/version.ts
472
+ var SDK_VERSION = "0.1.1" ;
473
+
474
+ // src/daemon-binary.ts
475
+ function supported(platform, arch) {
476
+ if (!["darwin", "linux", "win32"].includes(platform) || !["x64", "arm64"].includes(arch)) {
477
+ throw new MindwireError(`mindwire: no daemon release for ${platform}-${arch}`);
478
+ }
479
+ }
480
+ function assetName(version, platform, arch) {
481
+ const releasePlatform = platform === "win32" ? "windows" : platform;
482
+ const releaseArch = arch === "x64" ? "amd64" : arch;
483
+ return `mindwired-v${version}-${releasePlatform}-${releaseArch}${platform === "win32" ? ".exe" : ""}`;
484
+ }
485
+ function checksumFor(text, asset) {
486
+ const line = text.split("\n").find((l) => l.trim().endsWith(` ${asset}`) || l.trim().endsWith(` ${asset}`));
487
+ const hash = line?.trim().split(/\s+/)[0];
488
+ return hash && /^[a-f0-9]{64}$/i.test(hash) ? hash.toLowerCase() : void 0;
489
+ }
490
+ async function ensureDaemonBinary(opts = {}) {
491
+ const proc = globalThis;
492
+ const platform = opts.platform ?? proc.process?.platform;
493
+ const arch = opts.arch ?? proc.process?.arch;
494
+ supported(platform ?? "unknown", arch ?? "unknown");
495
+ const daemonPlatform = platform;
496
+ const daemonArch = arch;
497
+ const version = opts.version ?? SDK_VERSION;
498
+ if (!/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {
499
+ throw new MindwireError(`mindwire: cannot download daemon for non-release SDK version ${version}`);
500
+ }
501
+ const fs = await import('fs/promises');
502
+ const path = await import('path');
503
+ const os = await import('os');
504
+ const crypto = await import('crypto');
505
+ const home = os.homedir();
506
+ const defaultCache = daemonPlatform === "darwin" ? path.join(home, "Library", "Caches", "mindwire") : daemonPlatform === "win32" ? path.join(proc.process?.env?.LOCALAPPDATA ?? home, "mindwire", "Cache") : path.join(proc.process?.env?.XDG_CACHE_HOME ?? path.join(home, ".cache"), "mindwire");
507
+ const dir = path.join(opts.cacheDir ?? defaultCache, version, `${daemonPlatform}-${daemonArch}`);
508
+ const asset = assetName(version, daemonPlatform, daemonArch);
509
+ const bin = path.join(dir, asset);
510
+ const shaFile = `${bin}.sha256`;
511
+ try {
512
+ const [bytes2, expected2] = await Promise.all([fs.readFile(bin), fs.readFile(shaFile, "utf8")]);
513
+ if (crypto.createHash("sha256").update(bytes2).digest("hex") === expected2.trim()) return bin;
514
+ } catch {
515
+ }
516
+ const base = (opts.releaseBaseUrl ?? proc.process?.env?.MINDWIRE_RELEASE_BASE_URL ?? "https://github.com/oblien/mindwire/releases/download").replace(/\/$/, "");
517
+ const release = `${base}/v${version}`;
518
+ const request = opts.fetch ?? globalThis.fetch;
519
+ if (!request) throw new MindwireError("mindwire: fetch is unavailable; set daemonBin or MINDWIRE_DAEMON");
520
+ const [checksums, binary] = await Promise.all([request(`${release}/checksums.txt`), request(`${release}/${asset}`)]);
521
+ if (!checksums.ok || !binary.ok) {
522
+ if (!opts.releaseBaseUrl && !proc.process?.env?.MINDWIRE_RELEASE_BASE_URL) {
523
+ const latest = await request("https://api.github.com/repos/oblien/mindwire/releases/latest");
524
+ if (latest.ok) {
525
+ const tag = (await latest.json()).tag_name;
526
+ const fallback = typeof tag === "string" ? tag.replace(/^v/, "") : "";
527
+ if (/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/.test(fallback) && fallback !== version) {
528
+ return ensureDaemonBinary({ ...opts, version: fallback });
529
+ }
530
+ }
531
+ }
532
+ throw new MindwireError(`mindwire: failed to download daemon v${version} for ${daemonPlatform}-${daemonArch}`);
533
+ }
534
+ const expected = checksumFor(await checksums.text(), asset);
535
+ if (!expected) throw new MindwireError(`mindwire: release v${version} has no checksum for ${asset}`);
536
+ const bytes = new Uint8Array(await binary.arrayBuffer());
537
+ const actual = crypto.createHash("sha256").update(bytes).digest("hex");
538
+ if (actual !== expected) throw new MindwireError(`mindwire: checksum verification failed for ${asset}`);
539
+ await fs.mkdir(dir, { recursive: true });
540
+ const temp = `${bin}.${process.pid}.tmp`;
541
+ await fs.writeFile(temp, bytes, { mode: 493 });
542
+ await fs.writeFile(`${shaFile}.${process.pid}.tmp`, `${expected}
543
+ `);
544
+ await fs.rename(temp, bin);
545
+ await fs.rename(`${shaFile}.${process.pid}.tmp`, shaFile);
546
+ if (daemonPlatform !== "win32") await fs.chmod(bin, 493);
547
+ return bin;
548
+ }
549
+
550
+ // src/embedded.ts
551
+ var shared = /* @__PURE__ */ new Map();
552
+ function configKey(opts) {
553
+ return JSON.stringify([opts.cwd ?? "", opts.statePath ?? "", opts.bin ?? ""]);
554
+ }
555
+ function startEmbedded(opts = {}) {
556
+ const key = configKey(opts);
557
+ let daemon = shared.get(key);
558
+ if (!daemon) {
559
+ daemon = spawnDaemon(opts).catch((err) => {
560
+ shared.delete(key);
561
+ throw err;
562
+ });
563
+ shared.set(key, daemon);
564
+ }
565
+ return daemon;
566
+ }
567
+ function serverRuntime() {
568
+ return globalThis;
569
+ }
570
+ function isServerRuntime() {
571
+ const g = serverRuntime();
572
+ return typeof g.process !== "undefined" && !!g.process.versions?.node || typeof g.Bun !== "undefined" || typeof g.Deno !== "undefined";
573
+ }
574
+ async function spawnDaemon(opts) {
575
+ if (!isServerRuntime()) {
576
+ throw new MindwireError(
577
+ "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."
578
+ );
579
+ }
580
+ const { spawn } = await import('child_process');
581
+ const net = await import('net');
582
+ const proc = serverRuntime().process;
583
+ const resolved = await resolveBinary(opts.bin);
584
+ const bin = resolved.bin;
585
+ const port = await freePort(net);
586
+ const baseUrl = `http://127.0.0.1:${port}`;
587
+ const child = spawn(bin, [], {
588
+ env: {
589
+ ...proc.env,
590
+ ADDR: `127.0.0.1:${port}`,
591
+ AGENT_CWD: opts.cwd ?? proc.cwd(),
592
+ STATE_PATH: opts.statePath ?? ".mindwire-state.json",
593
+ DAEMON_TOKEN: ""
594
+ },
595
+ stdio: "ignore"
596
+ });
597
+ let spawnError = null;
598
+ child.on("error", (e) => {
599
+ spawnError = e;
600
+ });
601
+ const stop = () => {
602
+ try {
603
+ child.kill();
604
+ } catch {
605
+ }
606
+ };
607
+ proc.once?.("exit", stop);
608
+ proc.once?.("SIGINT", () => {
609
+ stop();
610
+ proc.exit?.(130);
611
+ });
612
+ await waitHealthy(baseUrl, () => spawnError, resolved);
613
+ return { baseUrl, stop };
614
+ }
615
+ async function resolveBinary(explicit) {
616
+ const fs = await import('fs');
617
+ const path = await import('path');
618
+ const proc = serverRuntime().process;
619
+ const ext = proc.platform === "win32" ? ".exe" : "";
620
+ const candidates = [];
621
+ if (explicit) candidates.push(explicit);
622
+ if (proc.env?.MINDWIRE_DAEMON) candidates.push(proc.env.MINDWIRE_DAEMON);
623
+ try {
624
+ const url = await import('url');
625
+ const here = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
626
+ const named = `mindwired-${proc.platform}-${proc.arch}${ext}`;
627
+ candidates.push(path.join(here, "bin", named), path.join(here, "..", "bin", named));
628
+ } catch {
629
+ }
630
+ for (const c of candidates) {
631
+ try {
632
+ if (fs.existsSync(c)) return { bin: c, found: true, checked: candidates };
633
+ } catch {
634
+ }
635
+ }
636
+ const downloaded = await ensureDaemonBinary({ platform: proc.platform, arch: proc.arch });
637
+ return { bin: downloaded, found: true, checked: [...candidates, downloaded] };
638
+ }
639
+ function daemonStartError(resolved, cause) {
640
+ if (!resolved.found) {
641
+ return [
642
+ "Couldn't start the mindwire daemon: the `mindwired` binary was not found.",
643
+ `Looked in: ${resolved.checked.join(", ")}.`,
644
+ "Fixes:",
645
+ " \u2022 check GitHub Release access so the SDK can download its matching daemon binary; or",
646
+ " \u2022 set MINDWIRE_DAEMON to a `mindwired` binary; or",
647
+ " \u2022 pass { baseUrl } to connect to a daemon you run yourself.",
648
+ " \u2022 Working inside the mindwire monorepo? Run `bun run build:daemon` from the repo root to build it.",
649
+ `(underlying error: ${cause.message})`
650
+ ].join("\n");
651
+ }
652
+ 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.`;
653
+ }
654
+ function freePort(net) {
655
+ return new Promise((resolve, reject) => {
656
+ const srv = net.createServer();
657
+ srv.on("error", reject);
658
+ srv.listen(0, "127.0.0.1", () => {
659
+ const addr = srv.address();
660
+ const port = addr && typeof addr === "object" ? addr.port : 0;
661
+ srv.close(() => resolve(port));
662
+ });
663
+ });
664
+ }
665
+ async function waitHealthy(baseUrl, getError, resolved, timeoutMs = 15e3) {
666
+ const deadline = Date.now() + timeoutMs;
667
+ while (Date.now() < deadline) {
668
+ const err = getError();
669
+ if (err) {
670
+ throw new MindwireError(daemonStartError(resolved, err), { cause: err });
671
+ }
672
+ try {
673
+ const res = await fetch(`${baseUrl}/healthz`);
674
+ if (res.ok) return;
675
+ } catch {
676
+ }
677
+ await new Promise((r) => setTimeout(r, 150));
678
+ }
679
+ throw new MindwireError("mindwire embedded daemon did not become healthy in time.");
680
+ }
681
+
682
+ // src/target/index.ts
683
+ function emit(spec, e) {
684
+ if (!spec.onLog) return;
685
+ try {
686
+ spec.onLog(e);
687
+ } catch {
688
+ }
689
+ }
690
+ function local(opts = {}) {
691
+ return {
692
+ name: "local",
693
+ async connect(spec) {
694
+ const d = await startEmbedded(opts);
695
+ emit(spec, { target: "local", phase: "ready", message: `embedded daemon on ${d.baseUrl}` });
696
+ return {
697
+ id: d.baseUrl,
698
+ baseUrl: d.baseUrl,
699
+ ...d.token !== void 0 ? { token: d.token } : {},
700
+ // No-op: the embedded daemon is shared (keyed memoization) and reaped on process exit.
701
+ stop: async () => {
702
+ }
703
+ };
704
+ }
705
+ };
706
+ }
707
+ function remote(baseUrl, opts = {}) {
708
+ return {
709
+ name: "remote",
710
+ async connect(spec) {
711
+ emit(spec, { target: "remote", phase: "skip", message: `using remote daemon at ${baseUrl}` });
712
+ return {
713
+ id: baseUrl,
714
+ baseUrl,
715
+ ...opts.token !== void 0 ? { token: opts.token } : {},
716
+ ...opts.headers !== void 0 ? { headers: opts.headers } : {},
717
+ ...opts.fetch !== void 0 ? { fetch: opts.fetch } : {},
718
+ stop: async () => {
719
+ }
720
+ };
721
+ }
722
+ };
723
+ }
724
+
725
+ // src/client.ts
726
+ var handleByTransport = /* @__PURE__ */ new WeakMap();
727
+ var Mindwire = class _Mindwire {
728
+ http;
729
+ /** The default agent type applied to agent-scoped calls, if set. */
730
+ defaultAgent;
731
+ /** Step-flow auth, scoped to this client's default agent (override per call). */
732
+ auth;
733
+ /** Persistent memory files + saved prompt templates, scoped to this client's default agent. */
734
+ prompts;
735
+ /** Persistent MCP-server config (the config an agent loads every run), scoped to this client's default agent. */
736
+ mcp;
737
+ /** Custom LLM-provider registration (opencode/Codex native config), scoped to this client's default agent. */
738
+ providers;
739
+ /** Daemon-driven notification channels + routing rules (webhook/slack/discord/telegram; per-agent/session/global). */
740
+ notify;
741
+ constructor(opts = {}) {
742
+ const target = opts.target ?? local();
743
+ const spec = { agent: opts.agent, onLog: opts.logger };
744
+ this.http = new Http({
745
+ fetch: opts.fetch,
746
+ headers: opts.headers,
747
+ timeoutMs: opts.requestTimeoutMs,
748
+ resolveBase: () => {
749
+ const h = target.connect(spec);
750
+ handleByTransport.set(this.http, h);
751
+ return h.then((x) => ({
752
+ baseUrl: x.baseUrl,
753
+ token: x.token,
754
+ getToken: x.getToken,
755
+ headers: x.headers,
756
+ fetch: x.fetch
757
+ }));
758
+ }
759
+ });
760
+ this.defaultAgent = opts.agent;
761
+ this.auth = new AuthApi(this);
762
+ this.prompts = new PromptsApi(this);
763
+ this.mcp = new McpApi(this);
764
+ this.providers = new ProvidersApi(this);
765
+ this.notify = new NotifyApi(this);
766
+ }
767
+ /**
768
+ * Provision the destination and await readiness **now**, rather than lazily on the first request —
769
+ * useful to front-load a fresh SSH/Docker/Oblien box (and to stream its {@link EnsureEvent}s to the
770
+ * `logger`) before the first `turn()`. Idempotent and memoized: repeated `ensure()` calls, and the
771
+ * first real request, all await the same provisioning, so the target connects exactly once.
772
+ */
773
+ async ensure() {
774
+ await this.http.ready();
775
+ }
776
+ /** Return a new client bound to a different default agent (shares the same transport config). */
777
+ withAgent(agent) {
778
+ const clone = Object.create(_Mindwire.prototype);
779
+ clone.http = this.http;
780
+ clone.defaultAgent = agent;
781
+ clone.auth = new AuthApi(clone);
782
+ clone.prompts = new PromptsApi(clone);
783
+ clone.mcp = new McpApi(clone);
784
+ clone.providers = new ProvidersApi(clone);
785
+ clone.notify = new NotifyApi(clone);
786
+ return clone;
787
+ }
788
+ /** The `?agent=` value to send for a scoped call: explicit override → client default → none. */
789
+ agentParam(scoped) {
790
+ const a = scoped?.agent ?? this.defaultAgent;
791
+ return a ? { agent: a } : void 0;
792
+ }
793
+ /**
794
+ * Release target-owned resources by calling the {@link TargetHandle}'s `stop()` — once, even across
795
+ * {@link withAgent} clones that share the transport. For an `ssh`/`docker`/`oblien` target this reaps
796
+ * the box (tear down the tunnel, stop or delete the container/workspace, per `stopOnExit`); a no-op
797
+ * for `local`/`remote` (embedded self-cleans on process exit; remote is not ours to stop). Safe to
798
+ * call before the target has connected (nothing to reap yet).
799
+ */
800
+ async close() {
801
+ const handle = handleByTransport.get(this.http);
802
+ if (!handle) return;
803
+ handleByTransport.delete(this.http);
804
+ const h = await handle.catch(() => null);
805
+ if (h) await h.stop();
806
+ }
807
+ // ---- health & catalog ----------------------------------------------------
808
+ /** `GET /healthz` — public liveness check. Resolves with the daemon's health payload when it is up. */
809
+ health() {
810
+ return this.http.request("GET", "/healthz");
811
+ }
812
+ /**
813
+ * `GET /stats` — the daemon **process's** resource snapshot (heap in use, memory reserved from the
814
+ * OS, goroutines, GC cycles, cores, platform, uptime). Cheap enough to call on demand — the daemon
815
+ * reads its own Go runtime, not the machine — so a UI can fetch it when a user opens a daemon's page
816
+ * without any background polling. See {@link Stats} for what each field means and doesn't.
817
+ */
818
+ stats() {
819
+ return this.http.request("GET", "/stats");
820
+ }
821
+ /** `GET /catalog` — every agent this daemon binary supports. */
822
+ catalog() {
823
+ return this.http.request("GET", "/catalog");
824
+ }
825
+ /** `GET /agent` — capabilities + settings schema + auth methods/status for the selected agent. */
826
+ agent(scoped) {
827
+ return this.http.request("GET", "/agent", { query: this.agentParam(scoped) });
828
+ }
829
+ /**
830
+ * `GET /models` — the models the selected agent can run for the configured account. An empty array
831
+ * is valid (no credentials yet / offline). Throws a 400 {@link ApiError} for an agent whose model is
832
+ * free text (check `capabilities.models` first).
833
+ */
834
+ models(scoped) {
835
+ return this.http.request("GET", "/models", { query: this.agentParam(scoped) });
836
+ }
837
+ /** `GET /doctor` — daemon-level health plus the selected agent's own checks. */
838
+ doctor(scoped) {
839
+ return this.http.request("GET", "/doctor", { query: this.agentParam(scoped) });
840
+ }
841
+ // ---- toolchain setup -----------------------------------------------------
842
+ /** `POST /setup` — start the agent's install toolchain (background; poll {@link setupStatus}). */
843
+ setup(scoped) {
844
+ return this.http.request("POST", "/setup", { query: this.agentParam(scoped) });
845
+ }
846
+ /** `POST /update` — re-run the toolchain, forcing reinstall of installable steps. */
847
+ update(scoped) {
848
+ return this.http.request("POST", "/update", { query: this.agentParam(scoped) });
849
+ }
850
+ /** `GET /setup` — current toolchain install progress. */
851
+ setupStatus(scoped) {
852
+ return this.http.request("GET", "/setup", { query: this.agentParam(scoped) });
853
+ }
854
+ // ---- config --------------------------------------------------------------
855
+ /** `GET /config` — the declared, non-secret settings for the agent. */
856
+ getConfig(scoped) {
857
+ return this.http.request("GET", "/config", {
858
+ query: this.agentParam(scoped)
859
+ });
860
+ }
861
+ /** `PUT /config` — merge recognized (non-secret) setting keys. Unknown keys are ignored server-side. */
862
+ async setConfig(values, scoped) {
863
+ await this.http.request("PUT", "/config", {
864
+ query: this.agentParam(scoped),
865
+ body: values
866
+ });
867
+ }
868
+ // ---- chats & history -----------------------------------------------------
869
+ /** `GET /chats` — recorded chats (newest first), shared across agents. */
870
+ chats() {
871
+ return this.http.request("GET", "/chats");
872
+ }
873
+ /**
874
+ * `PUT /chats/{id}` — rename a chat. The user title wins over the agent's native auto-title in
875
+ * every listing; an empty title clears the rename (reverting to the native/derived title).
876
+ * Returns the updated summary.
877
+ */
878
+ renameChat(chatId, title) {
879
+ return this.http.request("PUT", `/chats/${encodeURIComponent(chatId)}`, {
880
+ body: { title }
881
+ });
882
+ }
883
+ /**
884
+ * `DELETE /chats/{id}` — a true, irreversible delete: purges ALL of the chat's mindwire
885
+ * bookkeeping and, for every session the chat mapped to, removes that agent's native transcript
886
+ * (the source of truth). Rejects with a 409 error if a turn is live. Native deletion is
887
+ * best-effort per agent; the result reports what was purged vs. failed.
888
+ */
889
+ deleteChat(chatId) {
890
+ return this.http.request("DELETE", `/chats/${encodeURIComponent(chatId)}`);
891
+ }
892
+ /**
893
+ * `POST /chats/{id}/fork` — clone a chat into a new id (generated when `newChatId` is omitted).
894
+ * The fork shares the source's native session until its first turn, which branches it (natively
895
+ * on Claude via `--fork-session`; a fresh session on agents without native fork). Rejects with a
896
+ * 409 if the source has a live turn, 404 if the source is unknown, 400 if the target id is in
897
+ * use. Returns the new chat's summary.
898
+ */
899
+ forkChat(chatId, opts = {}) {
900
+ return this.http.request("POST", `/chats/${encodeURIComponent(chatId)}/fork`, {
901
+ body: opts.newChatId ? { newChatId: opts.newChatId } : {}
902
+ });
903
+ }
904
+ /**
905
+ * `GET /chats/{id}/messages` — a chat's transcript (native when the agent supports it, else
906
+ * the recorded fallback). `limit` caps to the newest N; `before` pages older history.
907
+ */
908
+ messages(chatId, opts = {}) {
909
+ const query = { ...this.agentParam(opts) };
910
+ if (opts.limit !== void 0) query["limit"] = opts.limit;
911
+ if (opts.before !== void 0) query["before"] = opts.before;
912
+ return this.http.request("GET", `/chats/${encodeURIComponent(chatId)}/messages`, {
913
+ query
914
+ });
915
+ }
916
+ /** `GET /chats/{id}/run` — the latest run for a chat (reattach anchor), or `null` if none yet. */
917
+ async latestRun(chatId) {
918
+ const data = await this.http.request(
919
+ "GET",
920
+ `/chats/${encodeURIComponent(chatId)}/run`
921
+ );
922
+ return data ? new Run(this.http, data) : null;
923
+ }
924
+ // ---- turns & runs --------------------------------------------------------
925
+ /**
926
+ * `POST /turns` — start a turn. Returns a {@link Run} handle you can stream, cancel, or await.
927
+ * Rejects with an {@link ApiError} (409) if a turn is already running for the chat.
928
+ *
929
+ * `mode` defaults to `"turn"` — one agent turn that ends when the CLI settles. Pass
930
+ * `mode: "resolve"` (with optional {@link ResolveOptions} `resolve` caps) for a global-resolve run
931
+ * that auto-continues the agent's multi-step work until it's done; {@link Mindwire.resolve} is the
932
+ * clearer entry point for that. The returned {@link Run} is then the parent of the run tree.
933
+ */
934
+ async turn(input) {
935
+ const body = {
936
+ chatId: input.chatId,
937
+ message: input.message
938
+ };
939
+ if (input.cwd !== void 0) body.cwd = input.cwd;
940
+ if (input.options !== void 0) body.options = input.options;
941
+ if (input.mode !== void 0) body.mode = input.mode;
942
+ if (input.resolve !== void 0) body.resolve = input.resolve;
943
+ const data = await this.http.request("POST", "/turns", {
944
+ query: this.agentParam(input),
945
+ body
946
+ });
947
+ return new Run(this.http, data);
948
+ }
949
+ /**
950
+ * `POST /turns {mode:"resolve"}` — start a **global-resolve** run: instead of returning after one
951
+ * turn, the daemon holds the task open and auto-continues the agent (resuming on continuable stops
952
+ * and probing for completion) until the work is globally resolved, then aggregates one final result.
953
+ *
954
+ * The returned {@link Run} is the **parent** of a run tree: each auto-continued iteration is a child
955
+ * turn ({@link Run.children}) whose events stream onto the parent's topic, delimited by `continuation`
956
+ * boundary events. `run.wait()` resolves once with the aggregated result; `run.stopReason` /
957
+ * `run.iterations` report how the loop ended. Resolve turns run unattended (no mid-turn approvals)
958
+ * and are bounded by {@link ResolveOptions} caps — see the resolve guide. Rejects with an
959
+ * {@link ApiError} (409) if a turn is already running for the chat.
960
+ */
961
+ async resolve(input) {
962
+ return this.turn({ ...input, mode: "resolve" });
963
+ }
964
+ /** `GET /runs/{id}` — fetch an existing run as a {@link Run} handle. */
965
+ async run(id) {
966
+ const data = await this.http.request("GET", `/runs/${encodeURIComponent(id)}`);
967
+ return new Run(this.http, data);
968
+ }
969
+ /**
970
+ * `POST /chats/{id}/compact` — run an on-demand conversation compaction as a first-class {@link Run}
971
+ * you can stream or await. The agent folds prior context into a summary it carries forward, emitting
972
+ * a `compaction` event on the stream and recording the boundary in history exactly like an
973
+ * auto-compaction. Optional `instructions` focus the continuation summary (Claude's
974
+ * `/compact <instructions>`; agents that don't honor focus still compact). Rejects with an
975
+ * {@link ApiError}: 400 if the agent doesn't support compaction (`capabilities.compactNow`) or the
976
+ * chat has no conversation yet, 409 if a turn is already running for the chat.
977
+ */
978
+ async compact(chatId, opts = {}) {
979
+ const data = await this.http.request(
980
+ "POST",
981
+ `/chats/${encodeURIComponent(chatId)}/compact`,
982
+ {
983
+ query: this.agentParam(opts),
984
+ body: opts.instructions ? { instructions: opts.instructions } : {}
985
+ }
986
+ );
987
+ return new Run(this.http, data);
988
+ }
989
+ // ---- notifications -------------------------------------------------------
990
+ /** `GET /notify/config` — whether a notification channel is wired (token never returned). */
991
+ getNotifyConfig() {
992
+ return this.http.request("GET", "/notify/config");
993
+ }
994
+ /** `PUT /notify/config` — store the provisioned notification channel (daemon-wide). */
995
+ async setNotifyConfig(input) {
996
+ await this.http.request("PUT", "/notify/config", { body: input });
997
+ }
998
+ /** `GET /notify/stream` — SSE feed of the daemon's notifications (replay, then live). */
999
+ async *notifications(opts = {}) {
1000
+ const res = await this.http.open("GET", "/notify/stream", {
1001
+ ...opts.signal ? { signal: opts.signal } : {}
1002
+ });
1003
+ yield* readSSE(res.body, opts.signal);
1004
+ }
1005
+ // ---- live resources ------------------------------------------------------
1006
+ /**
1007
+ * `GET /processes/stream` — SSE feed of live per-turn CPU/memory, one {@link ProcessFrame} per tick.
1008
+ * Sampling is **on demand**: the daemon starts measuring only while a client is connected and stops
1009
+ * the instant the last one disconnects, so aborting the `signal` (or ending the loop) tells the
1010
+ * daemon to stop — no background work, no leak. Pass `agent` to filter each frame's samples to one
1011
+ * agent type. Frames are live snapshots (no replay); an empty `samples` array is a valid keep-alive.
1012
+ */
1013
+ async *processes(opts = {}) {
1014
+ const path = "/processes/stream" + (opts.agent ? `?agent=${encodeURIComponent(opts.agent)}` : "");
1015
+ const res = await this.http.open("GET", path, {
1016
+ ...opts.signal ? { signal: opts.signal } : {}
1017
+ });
1018
+ yield* readSSE(res.body, opts.signal);
1019
+ }
1020
+ };
1021
+ var AuthApi = class {
1022
+ constructor(mw) {
1023
+ this.mw = mw;
1024
+ }
1025
+ mw;
1026
+ /** `GET /auth/methods` — the options list to present. */
1027
+ methods(scoped) {
1028
+ return this.mw.http.request("GET", "/auth/methods", {
1029
+ query: this.mw.agentParam(scoped)
1030
+ });
1031
+ }
1032
+ /** `POST /auth/begin` — start one method (may return `{ url, code, fields, pending }`). */
1033
+ begin(method, scoped) {
1034
+ return this.mw.http.request("POST", "/auth/begin", {
1035
+ query: this.mw.agentParam(scoped),
1036
+ body: { method }
1037
+ });
1038
+ }
1039
+ /** `POST /auth/step` — submit fields, or poll an interactive login to completion. */
1040
+ step(input, scoped) {
1041
+ return this.mw.http.request("POST", "/auth/step", {
1042
+ query: this.mw.agentParam(scoped),
1043
+ body: input
1044
+ });
1045
+ }
1046
+ /** `GET /auth/status` — is the agent authenticated, and via which method. */
1047
+ status(scoped) {
1048
+ return this.mw.http.request("GET", "/auth/status", {
1049
+ query: this.mw.agentParam(scoped)
1050
+ });
1051
+ }
1052
+ };
1053
+ var PromptsApi = class {
1054
+ constructor(mw) {
1055
+ this.mw = mw;
1056
+ }
1057
+ mw;
1058
+ query(scoped, extra) {
1059
+ return { ...this.mw.agentParam(scoped), ...extra };
1060
+ }
1061
+ /**
1062
+ * `GET /memory` — the agent's memory file at every supported scope (project + user for both
1063
+ * Claude and Codex). Each entry carries the resolved `path` and `exists`; `content` is `""` for
1064
+ * an absent file.
1065
+ */
1066
+ memory(opts = {}) {
1067
+ return this.mw.http.request("GET", "/memory", {
1068
+ query: this.query(opts, { dir: opts.dir })
1069
+ });
1070
+ }
1071
+ /** `PUT /memory` — write the memory file at `scope`. Returns the resulting {@link MemoryDoc}. */
1072
+ setMemory(input, opts = {}) {
1073
+ return this.mw.http.request("PUT", "/memory", {
1074
+ query: this.query(opts, { dir: opts.dir }),
1075
+ body: input
1076
+ });
1077
+ }
1078
+ /**
1079
+ * `DELETE /memory` — remove the memory file at `scope` (defaults to `user`). Returns the resulting
1080
+ * {@link MemoryDoc} (`exists: false` at the resolved path). Idempotent: deleting an absent file still
1081
+ * succeeds.
1082
+ */
1083
+ deleteMemory(opts = {}) {
1084
+ return this.mw.http.request("DELETE", "/memory", {
1085
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1086
+ });
1087
+ }
1088
+ /**
1089
+ * `GET /prompts` — saved prompt templates across every supported scope (Claude: project + user;
1090
+ * Codex: user only). `content` is omitted here; fetch it with {@link get}. A missing project
1091
+ * directory yields an empty list for that scope rather than an error.
1092
+ */
1093
+ list(opts = {}) {
1094
+ return this.mw.http.request("GET", "/prompts", {
1095
+ query: this.query(opts, { dir: opts.dir })
1096
+ });
1097
+ }
1098
+ /** `GET /prompts/{name}` — one template's full body. Rejects with a 404 `ApiError` if absent. */
1099
+ get(name, opts = {}) {
1100
+ return this.mw.http.request("GET", `/prompts/${encodeURIComponent(name)}`, {
1101
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1102
+ });
1103
+ }
1104
+ /** `PUT /prompts/{name}` — create or overwrite a template. Returns the resulting {@link PromptTemplate}. */
1105
+ set(name, content, opts = {}) {
1106
+ return this.mw.http.request("PUT", `/prompts/${encodeURIComponent(name)}`, {
1107
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir }),
1108
+ body: { content }
1109
+ });
1110
+ }
1111
+ /**
1112
+ * `DELETE /prompts/{name}` — remove one template at `scope` (defaults to `user`). Idempotent:
1113
+ * deleting an absent template still succeeds. A traversal name rejects with a 400 `ApiError`.
1114
+ */
1115
+ async delete(name, opts = {}) {
1116
+ await this.mw.http.request("DELETE", `/prompts/${encodeURIComponent(name)}`, {
1117
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1118
+ });
1119
+ }
1120
+ /**
1121
+ * `GET /subagents` — persistent subagent definitions (Claude `.claude/agents/*.md`) across every
1122
+ * supported scope. `content` is omitted here (fetch it with {@link subagent}); `meta` is the parsed
1123
+ * frontmatter view. Rejects with a 400 `ApiError` on an agent without the subagent-definition module.
1124
+ * Distinct from a turn's per-turn `subagents` passthrough — this is the on-disk definition store.
1125
+ */
1126
+ subagents(opts = {}) {
1127
+ return this.mw.http.request("GET", "/subagents", {
1128
+ query: this.query(opts, { dir: opts.dir })
1129
+ });
1130
+ }
1131
+ /** `GET /subagents/{name}` — one definition's raw body + parsed meta. 404 `ApiError` if absent. */
1132
+ subagent(name, opts = {}) {
1133
+ return this.mw.http.request("GET", `/subagents/${encodeURIComponent(name)}`, {
1134
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1135
+ });
1136
+ }
1137
+ /** `PUT /subagents/{name}` — create or overwrite a definition (raw content is canonical). Returns it. */
1138
+ setSubagent(name, content, opts = {}) {
1139
+ return this.mw.http.request("PUT", `/subagents/${encodeURIComponent(name)}`, {
1140
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir }),
1141
+ body: { content }
1142
+ });
1143
+ }
1144
+ /**
1145
+ * `DELETE /subagents/{name}` — remove one definition at `scope` (defaults to `user`). Idempotent:
1146
+ * deleting an absent definition still succeeds. A traversal name rejects with a 400 `ApiError`.
1147
+ */
1148
+ async deleteSubagent(name, opts = {}) {
1149
+ await this.mw.http.request("DELETE", `/subagents/${encodeURIComponent(name)}`, {
1150
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1151
+ });
1152
+ }
1153
+ };
1154
+ var McpApi = class {
1155
+ constructor(mw) {
1156
+ this.mw = mw;
1157
+ }
1158
+ mw;
1159
+ query(scoped, extra) {
1160
+ return { ...this.mw.agentParam(scoped), ...extra };
1161
+ }
1162
+ /**
1163
+ * `GET /mcp` — every persistent MCP server across the agent's supported scopes, keyed
1164
+ * `scope → name → server` (Claude: project + user; Codex: user only). A missing config file yields
1165
+ * an empty object for that scope rather than an error.
1166
+ */
1167
+ list(opts = {}) {
1168
+ return this.mw.http.request("GET", "/mcp", {
1169
+ query: this.query(opts, { dir: opts.dir })
1170
+ });
1171
+ }
1172
+ /** `GET /mcp/{name}` — one server's definition. Rejects with a 404 `ApiError` if it isn't configured. */
1173
+ get(name, opts = {}) {
1174
+ return this.mw.http.request("GET", `/mcp/${encodeURIComponent(name)}`, {
1175
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1176
+ });
1177
+ }
1178
+ /** `PUT /mcp/{name}` — create or overwrite one server. Returns the stored definition. */
1179
+ set(name, server, opts = {}) {
1180
+ return this.mw.http.request("PUT", `/mcp/${encodeURIComponent(name)}`, {
1181
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir }),
1182
+ body: server
1183
+ });
1184
+ }
1185
+ /** `DELETE /mcp/{name}` — remove one server. Idempotent: deleting an absent server still succeeds. */
1186
+ async delete(name, opts = {}) {
1187
+ await this.mw.http.request("DELETE", `/mcp/${encodeURIComponent(name)}`, {
1188
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1189
+ });
1190
+ }
1191
+ };
1192
+ var ProvidersApi = class {
1193
+ constructor(mw) {
1194
+ this.mw = mw;
1195
+ }
1196
+ mw;
1197
+ query(scoped, extra) {
1198
+ return { ...this.mw.agentParam(scoped), ...extra };
1199
+ }
1200
+ /**
1201
+ * `GET /providers` — every registered custom provider across the agent's supported scopes, keyed
1202
+ * `scope → id → provider` (opencode/Codex: user only). A missing config file yields an empty object for
1203
+ * that scope rather than an error. `hasKey` reports whether a secret is stored; the key is never returned.
1204
+ */
1205
+ list(opts = {}) {
1206
+ return this.mw.http.request("GET", "/providers", {
1207
+ query: this.query(opts, { dir: opts.dir })
1208
+ });
1209
+ }
1210
+ /** `GET /providers/{id}` — one provider's definition. Rejects with a 404 `ApiError` if it isn't configured. */
1211
+ get(id, opts = {}) {
1212
+ return this.mw.http.request("GET", `/providers/${encodeURIComponent(id)}`, {
1213
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1214
+ });
1215
+ }
1216
+ /**
1217
+ * `PUT /providers/{id}` — create or overwrite one provider, returning the stored definition (with
1218
+ * `hasKey` and the stored `envVars`). Two write-only secret channels, both optional: `opts.apiKey` is a
1219
+ * single key (custom endpoints, single-key catalog brands); `opts.secrets` is a NAME→VALUE map for a
1220
+ * catalog provider whose entry declares MULTIPLE env vars (e.g. AWS Bedrock). Omitting both leaves any
1221
+ * previously stored secret intact. The path `id` wins over any `id` on the provider value.
1222
+ */
1223
+ set(id, provider, opts = {}) {
1224
+ return this.mw.http.request("PUT", `/providers/${encodeURIComponent(id)}`, {
1225
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir }),
1226
+ body: { ...provider, id, apiKey: opts.apiKey, secrets: opts.secrets }
1227
+ });
1228
+ }
1229
+ /** `DELETE /providers/{id}` — remove one provider and clear its stored key. Idempotent. */
1230
+ async delete(id, opts = {}) {
1231
+ await this.mw.http.request("DELETE", `/providers/${encodeURIComponent(id)}`, {
1232
+ query: this.query(opts, { scope: opts.scope, dir: opts.dir })
1233
+ });
1234
+ }
1235
+ };
1236
+ var NotifyApi = class {
1237
+ constructor(mw) {
1238
+ this.mw = mw;
1239
+ }
1240
+ mw;
1241
+ /** `GET /notify/channels` — every channel, masked (no secrets). */
1242
+ channels() {
1243
+ return this.mw.http.request("GET", "/notify/channels");
1244
+ }
1245
+ /** `POST /notify/channels` — create a channel (server-assigns the id). Returns it masked. */
1246
+ createChannel(input) {
1247
+ return this.mw.http.request("POST", "/notify/channels", { body: input });
1248
+ }
1249
+ /**
1250
+ * `PUT /notify/channels/{id}` — update a channel, merge-preserving any omitted secret
1251
+ * (`url`/`token`/`secret`). Returns the updated masked channel. 404 `ApiError` if unknown.
1252
+ */
1253
+ setChannel(id, input) {
1254
+ return this.mw.http.request("PUT", `/notify/channels/${encodeURIComponent(id)}`, {
1255
+ body: input
1256
+ });
1257
+ }
1258
+ /** `DELETE /notify/channels/{id}` — remove a channel. Idempotent. */
1259
+ async deleteChannel(id) {
1260
+ await this.mw.http.request("DELETE", `/notify/channels/${encodeURIComponent(id)}`);
1261
+ }
1262
+ /**
1263
+ * `POST /notify/channels/{id}/test` — deliver a synthetic notification to a channel. A failed
1264
+ * delivery is DATA (`{ ok: false, error }`), not a thrown error; only an unknown id rejects (404).
1265
+ */
1266
+ testChannel(id) {
1267
+ return this.mw.http.request(
1268
+ "POST",
1269
+ `/notify/channels/${encodeURIComponent(id)}/test`
1270
+ );
1271
+ }
1272
+ /** `GET /notify/rules` — every routing rule. */
1273
+ rules() {
1274
+ return this.mw.http.request("GET", "/notify/rules");
1275
+ }
1276
+ /** `POST /notify/rules` — create a rule (server-assigns the id). Returns it. */
1277
+ createRule(input) {
1278
+ return this.mw.http.request("POST", "/notify/rules", { body: input });
1279
+ }
1280
+ /** `PUT /notify/rules/{id}` — replace a rule. Returns it. 404 `ApiError` if unknown. */
1281
+ setRule(id, input) {
1282
+ return this.mw.http.request("PUT", `/notify/rules/${encodeURIComponent(id)}`, {
1283
+ body: input
1284
+ });
1285
+ }
1286
+ /** `DELETE /notify/rules/{id}` — remove a rule. Idempotent. */
1287
+ async deleteRule(id) {
1288
+ await this.mw.http.request("DELETE", `/notify/rules/${encodeURIComponent(id)}`);
1289
+ }
1290
+ };
1291
+
1292
+ // src/target/host.ts
1293
+ function makeEmit(cfg) {
1294
+ const target = cfg.target ?? "sandbox";
1295
+ return (e) => {
1296
+ if (!cfg.onLog) return;
1297
+ try {
1298
+ cfg.onLog({ target, ...e });
1299
+ } catch {
1300
+ }
1301
+ };
1302
+ }
1303
+ var DAEMON_DIR = "/root/.mindwire";
1304
+ var BIN = `${DAEMON_DIR}/mindwired`;
1305
+ var BIN_NEW = `${BIN}.new`;
1306
+ var STATE = `${DAEMON_DIR}/agent-state.json`;
1307
+ var LOG = `${DAEMON_DIR}/daemon.log`;
1308
+ async function ensureDaemon(host, cfg) {
1309
+ const emit2 = makeEmit(cfg);
1310
+ try {
1311
+ await waitHostReady(host);
1312
+ emit2({ phase: "connect", message: "runtime ready" });
1313
+ const desired = cfg.desiredVersion ?? SDK_VERSION;
1314
+ const health = await probeHealth(host, cfg.port);
1315
+ if (health.reachable) {
1316
+ emit2({
1317
+ phase: "probe",
1318
+ message: health.version ? `daemon reachable (v${health.version})` : "daemon reachable (version unknown)",
1319
+ version: health.version
1320
+ });
1321
+ const upToDate = health.version !== void 0 && health.version === desired;
1322
+ if (upToDate || !cfg.autoUpdate) {
1323
+ emit2({
1324
+ phase: "skip",
1325
+ message: upToDate ? `daemon already at v${desired}` : "keeping the running daemon",
1326
+ version: health.version
1327
+ });
1328
+ return;
1329
+ }
1330
+ } else {
1331
+ emit2({ phase: "probe", message: "no daemon reachable; deploying" });
1332
+ }
1333
+ await deploy(host, cfg, emit2);
1334
+ } catch (err) {
1335
+ emit2({ phase: "error", message: "ensure failed", error: err instanceof Error ? err.message : String(err) });
1336
+ throw err;
1337
+ }
1338
+ }
1339
+ async function deploy(host, cfg, emit2) {
1340
+ const arch = await probeArch(host);
1341
+ const desired = cfg.desiredVersion ?? SDK_VERSION;
1342
+ let acquire = "";
1343
+ if (cfg.daemonBin) {
1344
+ const binPath = await resolveLinuxDaemon(cfg.daemonBin, arch);
1345
+ const bytes = await readBytes(binPath);
1346
+ emit2({ phase: "upload", message: `uploading daemon (${arch}, ${bytes.length} bytes)`, arch, bytes: bytes.length });
1347
+ await host.putFile(BIN_NEW, bytes, { mode: "0755" });
1348
+ } else {
1349
+ if (!/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/.test(desired)) {
1350
+ throw new MindwireError(`mindwire: cannot download daemon for non-release SDK version ${desired}`);
1351
+ }
1352
+ const asset = `mindwired-v${desired}-linux-${arch === "arm64" ? "arm64" : "amd64"}`;
1353
+ const release = `https://github.com/oblien/mindwire/releases/download/v${desired}`;
1354
+ emit2({ phase: "download", message: `downloading daemon v${desired} on the destination (${arch})`, arch });
1355
+ acquire = [
1356
+ `release=${shellQuote(release)}`,
1357
+ `asset=${shellQuote(asset)}`,
1358
+ "download() {",
1359
+ ` expected=$(curl -fsSL "$release/checksums.txt" | awk -v asset="$asset" '$2 == asset { print $1; exit }') || return 1`,
1360
+ ' [ -n "$expected" ] || return 1',
1361
+ ` curl -fsSL "$release/$asset" -o ${BIN_NEW} || return 1`,
1362
+ ` actual=$(sha256sum ${BIN_NEW} | awk '{print $1}')`,
1363
+ ' [ "$actual" = "$expected" ] || return 2',
1364
+ "}",
1365
+ "if download; then :; else",
1366
+ ' status=$?; [ "$status" -ne 2 ] || { echo "MINDWIRE_FAIL checksum mismatch for $asset"; exit 1; }',
1367
+ ` latest=$(curl -fsSL https://api.github.com/repos/oblien/mindwire/releases/latest | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/p')`,
1368
+ ' case "$latest" in v[0-9]*.[0-9]*.[0-9]*) ;; *) echo "MINDWIRE_FAIL no matching or latest release"; exit 1 ;; esac',
1369
+ ' release="https://github.com/oblien/mindwire/releases/download/$latest"',
1370
+ ` asset="mindwired-$latest-linux-${arch === "arm64" ? "arm64" : "amd64"}"`,
1371
+ ' download || { echo "MINDWIRE_FAIL latest release download failed"; exit 1; }',
1372
+ "fi",
1373
+ `chmod +x ${BIN_NEW}`
1374
+ ].join("\n");
1375
+ }
1376
+ const script = [
1377
+ "set -e",
1378
+ `mkdir -p ${DAEMON_DIR}`,
1379
+ acquire,
1380
+ // Stop a prior daemon by exact process NAME, never `pkill -f <path>`: this whole script (which
1381
+ // contains `${BIN}` several times) is the argv of the `bash -lc` shell running it, so a full-cmdline
1382
+ // match would SIGTERM our own deploying shell before the daemon ever launches. `-x mindwired` matches
1383
+ // only the daemon's comm (`bash`/`pkill` never match), leaving this shell alive.
1384
+ `pkill -x mindwired 2>/dev/null || true`,
1385
+ "sleep 0.3",
1386
+ `mv -f ${BIN_NEW} ${BIN}`,
1387
+ `chmod +x ${BIN}`,
1388
+ // Detach so the daemon survives this exec's shell exiting. ADDR=":<port>" binds 0.0.0.0.
1389
+ `setsid nohup env ADDR=":${cfg.port}" AGENT_TYPE="${cfg.agent}" AGENT_CWD="${cfg.agentCwd}" STATE_PATH="${STATE}" DAEMON_TOKEN="" ${BIN} > ${LOG} 2>&1 < /dev/null &`,
1390
+ // Health-poll from inside the VM (loopback) and emit a marker — exit codes are unreliable here.
1391
+ `for i in $(seq 1 60); do curl -fsS --max-time 2 http://127.0.0.1:${cfg.port}/healthz >/dev/null 2>&1 && { echo MINDWIRE_READY; exit 0; }; sleep 0.25; done`,
1392
+ "echo MINDWIRE_FAIL",
1393
+ `tail -n 40 ${LOG} 2>/dev/null || true`
1394
+ ].join("\n");
1395
+ emit2({ phase: "launch", message: "launching daemon" });
1396
+ const res = await host.exec(["bash", "-lc", script], { timeoutSeconds: 45 });
1397
+ const out = res.stdout ?? "";
1398
+ if (!out.includes("MINDWIRE_READY")) {
1399
+ throw new MindwireError(
1400
+ "mindwire: the in-sandbox daemon did not become healthy after deploy.\n" + (out || res.stderr || res.error || "(no output)").trim()
1401
+ );
1402
+ }
1403
+ emit2({ phase: "ready", message: "daemon deployed and healthy" });
1404
+ }
1405
+ async function probeHealth(host, port) {
1406
+ const script = `out=$(curl -fsS --max-time 3 http://127.0.0.1:${port}/healthz 2>/dev/null) && printf '<<MW_H>>%s<<MW_H>>' "$out" || printf '<<MW_H>><<MW_H>>'`;
1407
+ const res = await host.exec(["bash", "-lc", script], { timeoutSeconds: 15 });
1408
+ const body = ((res.stdout ?? "").match(/<<MW_H>>([\s\S]*?)<<MW_H>>/)?.[1] ?? "").trim();
1409
+ if (!body) return { reachable: false };
1410
+ try {
1411
+ const j = JSON.parse(body);
1412
+ return { reachable: true, version: typeof j.version === "string" ? j.version : void 0 };
1413
+ } catch {
1414
+ return { reachable: true };
1415
+ }
1416
+ }
1417
+ async function probeArch(host) {
1418
+ const res = await host.exec(["bash", "-lc", `printf '<<ARCH:%s>>' "$(uname -m)"`], { timeoutSeconds: 15 });
1419
+ const raw = ((res.stdout ?? "").match(/<<ARCH:([^>]*)>>/)?.[1] ?? "").trim();
1420
+ return raw === "aarch64" || raw === "arm64" ? "arm64" : "amd64";
1421
+ }
1422
+ async function waitHostReady(host, timeoutMs = 6e4) {
1423
+ const deadline = Date.now() + timeoutMs;
1424
+ let lastErr = null;
1425
+ while (Date.now() < deadline) {
1426
+ try {
1427
+ const r = await host.exec(["bash", "-lc", "echo mw_ready"], { timeoutSeconds: 10 });
1428
+ if ((r.stdout ?? "").includes("mw_ready")) return;
1429
+ } catch (e) {
1430
+ lastErr = e;
1431
+ }
1432
+ await sleep(1e3);
1433
+ }
1434
+ throw new MindwireError(
1435
+ "mindwire: the sandbox runtime did not become ready in time.",
1436
+ lastErr ? { cause: lastErr } : void 0
1437
+ );
1438
+ }
1439
+ async function resolveLinuxDaemon(explicit, arch) {
1440
+ const fs = await import('fs');
1441
+ if (explicit) {
1442
+ if (!fs.existsSync(explicit)) {
1443
+ throw new MindwireError(`mindwire: sandbox daemonBin not found at ${explicit}`);
1444
+ }
1445
+ return explicit;
1446
+ }
1447
+ return ensureDaemonBinary({ platform: "linux", arch: arch === "arm64" ? "arm64" : "x64" });
1448
+ }
1449
+ async function readBytes(p) {
1450
+ const fs = await import('fs/promises');
1451
+ return fs.readFile(p);
1452
+ }
1453
+ function sleep(ms) {
1454
+ return new Promise((r) => setTimeout(r, ms));
1455
+ }
1456
+ function shellQuote(value) {
1457
+ return `'${value.replace(/'/g, "'\\''")}'`;
1458
+ }
1459
+
1460
+ // src/target/container.ts
1461
+ async function provisionContainer(host, cfg, onLog) {
1462
+ const target = cfg.target ?? "container";
1463
+ const emit2 = (e) => {
1464
+ if (!onLog) return;
1465
+ try {
1466
+ onLog({ target, ...e });
1467
+ } catch {
1468
+ }
1469
+ };
1470
+ await ensureDockerReady(host, cfg.install ?? "never", emit2);
1471
+ const { containerId, hostPort, created } = await runContainer(host, cfg, emit2);
1472
+ await ensureDaemon(new ContainerHost(host, containerId), {
1473
+ port: cfg.daemonPort,
1474
+ agent: cfg.agent,
1475
+ agentCwd: cfg.agentCwd,
1476
+ daemonBin: cfg.daemonBin,
1477
+ autoUpdate: cfg.autoUpdate,
1478
+ target,
1479
+ onLog
1480
+ });
1481
+ let stopped = false;
1482
+ const stop = async () => {
1483
+ if (stopped) return;
1484
+ stopped = true;
1485
+ if (!created || !(cfg.stopOnExit ?? true)) return;
1486
+ try {
1487
+ await host.exec(["docker", "rm", "-f", containerId]);
1488
+ } catch {
1489
+ }
1490
+ };
1491
+ return { containerId, hostPort, stop };
1492
+ }
1493
+ var ContainerHost = class {
1494
+ constructor(base, containerId) {
1495
+ this.base = base;
1496
+ this.containerId = containerId;
1497
+ }
1498
+ base;
1499
+ containerId;
1500
+ exec(argv, opts) {
1501
+ return this.base.exec(["docker", "exec", this.containerId, ...argv], opts);
1502
+ }
1503
+ async putFile(path, data, opts) {
1504
+ const slash = path.lastIndexOf("/");
1505
+ const dir = slash > 0 ? path.slice(0, slash) : "/";
1506
+ const base = path.slice(slash + 1);
1507
+ const mode = opts?.mode ?? "0644";
1508
+ const tmp = `/tmp/.mw-${this.containerId.slice(0, 12)}-${base}`;
1509
+ await this.base.exec(["docker", "exec", this.containerId, "mkdir", "-p", dir]);
1510
+ await this.base.putFile(tmp, data, opts);
1511
+ await this.base.exec(["docker", "cp", tmp, `${this.containerId}:${path}`]);
1512
+ await this.base.exec(["docker", "exec", this.containerId, "chmod", mode, path]);
1513
+ await this.base.exec(["rm", "-f", tmp]);
1514
+ }
1515
+ };
1516
+ async function ensureDockerReady(host, install, emit2) {
1517
+ let state = await detectDocker(host);
1518
+ if (state.status === "running") {
1519
+ emit2({ phase: "install", message: `docker present (v${state.version ?? "?"})`, version: state.version });
1520
+ return;
1521
+ }
1522
+ if (state.status === "denied") {
1523
+ throw new MindwireError(
1524
+ "mindwire: connected to the host, but this user can't reach the Docker daemon socket (permission denied). Connect as root, or add the SSH user to the `docker` group."
1525
+ );
1526
+ }
1527
+ if (state.status === "stopped") {
1528
+ emit2({ phase: "install", message: "docker installed but not running; starting it" });
1529
+ await startDocker(host);
1530
+ state = await detectDocker(host);
1531
+ if (state.status === "running") {
1532
+ emit2({ phase: "install", message: `docker started (v${state.version ?? "?"})`, version: state.version });
1533
+ return;
1534
+ }
1535
+ throw new MindwireError("mindwire: Docker is installed on the host but could not be started.");
1536
+ }
1537
+ if (install !== "ifMissing") {
1538
+ throw new MindwireError(
1539
+ 'mindwire: Docker is not installed on the remote host, and mindwire won\'t install system packages unless you opt in. Pass docker: { install: "ifMissing" } to have it run the official get.docker.com script (`curl -fsSL https://get.docker.com | sh`) and enable the service \u2014 or install Docker on the host yourself.'
1540
+ );
1541
+ }
1542
+ emit2({ phase: "install", message: "docker not found; installing via get.docker.com" });
1543
+ await installDocker(host);
1544
+ await startDocker(host);
1545
+ state = await detectDocker(host);
1546
+ if (state.status !== "running") {
1547
+ throw new MindwireError(
1548
+ "mindwire: ran the get.docker.com install script, but the Docker daemon did not come up."
1549
+ );
1550
+ }
1551
+ emit2({ phase: "install", message: `docker installed and started (v${state.version ?? "?"})`, version: state.version });
1552
+ }
1553
+ async function detectDocker(host) {
1554
+ const script = [
1555
+ 'if ! command -v docker >/dev/null 2>&1; then echo "MW_DOCKER=absent"; exit 0; fi',
1556
+ 'if v=$(docker info --format "{{.ServerVersion}}" 2>/dev/null); then echo "MW_DOCKER=running:$v"; exit 0; fi',
1557
+ "err=$(docker info 2>&1 >/dev/null || true)",
1558
+ 'case "$err" in',
1559
+ ' *ermission*denied*) echo "MW_DOCKER=denied" ;;',
1560
+ ' *) echo "MW_DOCKER=stopped" ;;',
1561
+ "esac"
1562
+ ].join("\n");
1563
+ const res = await host.exec(["bash", "-lc", script], { timeoutSeconds: 30 });
1564
+ const m = (res.stdout ?? "").match(/MW_DOCKER=([a-z]+)(?::([^\n]*))?/);
1565
+ const status = m?.[1] ?? "absent";
1566
+ const version = m?.[2]?.trim() || void 0;
1567
+ return { status, version };
1568
+ }
1569
+ async function installDocker(host) {
1570
+ const res = await host.exec(["bash", "-lc", "curl -fsSL https://get.docker.com | sh"], {
1571
+ timeoutSeconds: 600
1572
+ });
1573
+ if ((res.exitCode ?? 0) !== 0) {
1574
+ throw new MindwireError(
1575
+ "mindwire: the Docker install script (get.docker.com) failed.\n" + (res.stderr || res.stdout || "(no output)").trim()
1576
+ );
1577
+ }
1578
+ }
1579
+ async function startDocker(host) {
1580
+ await host.exec(
1581
+ ["bash", "-lc", "systemctl enable --now docker 2>/dev/null || service docker start 2>/dev/null || true"],
1582
+ { timeoutSeconds: 60 }
1583
+ );
1584
+ }
1585
+ async function runContainer(host, cfg, emit2) {
1586
+ const port = cfg.daemonPort;
1587
+ if (cfg.container !== void 0) {
1588
+ await host.exec(["docker", "start", cfg.container]);
1589
+ const hostPort2 = await resolveHostPort(host, cfg.container, port);
1590
+ emit2({
1591
+ phase: "provision",
1592
+ message: `attached to container ${cfg.container}; daemon published on host port ${hostPort2}`
1593
+ });
1594
+ return { containerId: cfg.container, hostPort: hostPort2, created: false };
1595
+ }
1596
+ if (!cfg.image) {
1597
+ throw new MindwireError(
1598
+ "mindwire: running the daemon in a container needs an image (docker.image) to create one, or an existing container (docker.container) to attach to."
1599
+ );
1600
+ }
1601
+ const runArgs = ["docker", "run", "-d"];
1602
+ if (cfg.name) runArgs.push("--name", cfg.name);
1603
+ runArgs.push("-p", `127.0.0.1:0:${port}`);
1604
+ if (cfg.createArgs?.length) runArgs.push(...cfg.createArgs);
1605
+ runArgs.push(cfg.image, "sleep", "infinity");
1606
+ const res = await host.exec(runArgs, { timeoutSeconds: 120 });
1607
+ const containerId = (res.stdout ?? "").trim().split(/\s+/).pop() ?? "";
1608
+ if (!containerId || (res.exitCode ?? 0) !== 0) {
1609
+ throw new MindwireError(
1610
+ "mindwire: `docker run` did not start a container.\n" + (res.stderr || res.stdout || "(no output)").trim()
1611
+ );
1612
+ }
1613
+ const hostPort = await resolveHostPort(host, containerId, port);
1614
+ emit2({
1615
+ phase: "provision",
1616
+ message: `container ${containerId.slice(0, 12)} up; daemon published on host port ${hostPort}`
1617
+ });
1618
+ return { containerId, hostPort, created: true };
1619
+ }
1620
+ async function resolveHostPort(host, containerId, port) {
1621
+ const res = await host.exec(["docker", "port", containerId, `${port}/tcp`]);
1622
+ const line = (res.stdout ?? "").split("\n").map((s) => s.trim()).find(Boolean);
1623
+ const hostPort = line ? Number.parseInt(line.match(/:(\d+)\s*$/)?.[1] ?? "", 10) : NaN;
1624
+ if (!Number.isFinite(hostPort) || hostPort <= 0) {
1625
+ throw new MindwireError(
1626
+ `mindwire: could not resolve the published host port for ${port}/tcp on container ${containerId.slice(0, 12)}. ` + cfgHint(res) + `docker port output: ${JSON.stringify((res.stdout ?? "").trim())}`
1627
+ );
1628
+ }
1629
+ return hostPort;
1630
+ }
1631
+ function cfgHint(res) {
1632
+ return (res.stdout ?? "").trim() === "" ? "Attach to a container started with that port published (e.g. `-p 127.0.0.1:0:<port>`). " : "";
1633
+ }
1634
+
1635
+ // src/target/ssh.ts
1636
+ function ssh(opts) {
1637
+ return { name: "ssh", connect: (spec) => connectSsh(opts, spec) };
1638
+ }
1639
+ var DEFAULT_PORT = 8790;
1640
+ var DEFAULT_AGENT = "claude-code";
1641
+ var DEFAULT_AGENT_CWD = "/root";
1642
+ var SshHost = class {
1643
+ constructor(client) {
1644
+ this.client = client;
1645
+ }
1646
+ client;
1647
+ exec(argv) {
1648
+ const command = toCommandLine(argv);
1649
+ return new Promise((resolve, reject) => {
1650
+ this.client.exec(command, (err, channel) => {
1651
+ if (err) {
1652
+ reject(err);
1653
+ return;
1654
+ }
1655
+ const out = [];
1656
+ const errb = [];
1657
+ let code;
1658
+ channel.on("data", (chunk) => out.push(Buffer.from(chunk)));
1659
+ channel.stderr?.on("data", (chunk) => errb.push(Buffer.from(chunk)));
1660
+ channel.on("close", (c) => {
1661
+ code = typeof c === "number" ? c : void 0;
1662
+ resolve({
1663
+ exitCode: code,
1664
+ stdout: Buffer.concat(out).toString("utf8"),
1665
+ stderr: Buffer.concat(errb).toString("utf8")
1666
+ });
1667
+ });
1668
+ channel.on("error", (e) => reject(e));
1669
+ });
1670
+ });
1671
+ }
1672
+ async putFile(path, data, opts) {
1673
+ const slash = path.lastIndexOf("/");
1674
+ const dir = slash > 0 ? path.slice(0, slash) : "/";
1675
+ await this.exec(["mkdir", "-p", dir]);
1676
+ const sftp = await this.sftp();
1677
+ const mode = parseInt(opts?.mode ?? "0644", 8) || 420;
1678
+ await new Promise((resolve, reject) => {
1679
+ const ws = sftp.createWriteStream(path, { mode });
1680
+ let done = false;
1681
+ const finish = () => {
1682
+ if (!done) {
1683
+ done = true;
1684
+ resolve();
1685
+ }
1686
+ };
1687
+ ws.on("error", (e) => reject(e));
1688
+ ws.on("close", finish);
1689
+ ws.on("finish", finish);
1690
+ ws.end?.(Buffer.from(data));
1691
+ });
1692
+ }
1693
+ sftp() {
1694
+ return new Promise((resolve, reject) => {
1695
+ this.client.sftp((err, sftp) => err ? reject(err) : resolve(sftp));
1696
+ });
1697
+ }
1698
+ };
1699
+ async function connectSsh(opts, spec) {
1700
+ const mod = await importSsh2();
1701
+ const net = await import('net');
1702
+ const client = await openConnection(mod, opts);
1703
+ const daemonPort = opts.daemonPort ?? DEFAULT_PORT;
1704
+ const makeTunnel = (c, port) => createTunnel(net, c, port);
1705
+ const shared2 = {
1706
+ daemonPort,
1707
+ agent: opts.agentType ?? spec.agent ?? DEFAULT_AGENT,
1708
+ agentCwd: opts.agentCwd ?? DEFAULT_AGENT_CWD,
1709
+ daemonBin: opts.daemonBin,
1710
+ autoUpdate: opts.autoUpdate,
1711
+ stopOnExit: opts.stopOnExit ?? true,
1712
+ onLog: spec.onLog
1713
+ };
1714
+ if (opts.docker) {
1715
+ return provisionSshContainer(client, makeTunnel, {
1716
+ ...shared2,
1717
+ id: `${opts.username}@${opts.host}/docker`,
1718
+ docker: opts.docker
1719
+ });
1720
+ }
1721
+ return provisionSsh(client, makeTunnel, {
1722
+ ...shared2,
1723
+ id: `${opts.username}@${opts.host}:${daemonPort}`
1724
+ });
1725
+ }
1726
+ async function provisionSsh(client, makeTunnel, cfg) {
1727
+ await ensureDaemon(new SshHost(client), {
1728
+ port: cfg.daemonPort,
1729
+ agent: cfg.agent,
1730
+ agentCwd: cfg.agentCwd,
1731
+ daemonBin: cfg.daemonBin,
1732
+ autoUpdate: cfg.autoUpdate,
1733
+ target: "ssh",
1734
+ onLog: cfg.onLog
1735
+ });
1736
+ const tunnel = await makeTunnel(client, cfg.daemonPort);
1737
+ let stopped = false;
1738
+ const stop = async () => {
1739
+ if (stopped) return;
1740
+ stopped = true;
1741
+ await tunnel.close().catch(() => {
1742
+ });
1743
+ if (cfg.stopOnExit ?? true) {
1744
+ try {
1745
+ client.end();
1746
+ } catch {
1747
+ }
1748
+ }
1749
+ };
1750
+ return { id: cfg.id, baseUrl: tunnel.baseUrl, stop };
1751
+ }
1752
+ async function provisionSshContainer(client, makeTunnel, cfg) {
1753
+ const container = await provisionContainer(
1754
+ new SshHost(client),
1755
+ {
1756
+ image: cfg.docker.image,
1757
+ container: cfg.docker.container,
1758
+ name: cfg.docker.name,
1759
+ install: cfg.docker.install,
1760
+ createArgs: cfg.docker.createArgs,
1761
+ daemonPort: cfg.daemonPort,
1762
+ agent: cfg.agent,
1763
+ agentCwd: cfg.agentCwd,
1764
+ daemonBin: cfg.daemonBin,
1765
+ autoUpdate: cfg.autoUpdate,
1766
+ stopOnExit: cfg.stopOnExit ?? true,
1767
+ target: "ssh"
1768
+ },
1769
+ cfg.onLog
1770
+ );
1771
+ const tunnel = await makeTunnel(client, container.hostPort);
1772
+ let stopped = false;
1773
+ const stop = async () => {
1774
+ if (stopped) return;
1775
+ stopped = true;
1776
+ await tunnel.close().catch(() => {
1777
+ });
1778
+ await container.stop().catch(() => {
1779
+ });
1780
+ if (cfg.stopOnExit ?? true) {
1781
+ try {
1782
+ client.end();
1783
+ } catch {
1784
+ }
1785
+ }
1786
+ };
1787
+ return { id: cfg.id, baseUrl: tunnel.baseUrl, stop };
1788
+ }
1789
+ async function openConnection(mod, opts) {
1790
+ const auth = await buildAuth(opts);
1791
+ return new Promise((resolve, reject) => {
1792
+ const client = new mod.Client();
1793
+ let settled = false;
1794
+ client.on("ready", () => {
1795
+ if (settled) return;
1796
+ settled = true;
1797
+ resolve(client);
1798
+ });
1799
+ client.on("error", (err) => {
1800
+ if (settled) return;
1801
+ settled = true;
1802
+ reject(
1803
+ new MindwireError(
1804
+ `mindwire: SSH connection to ${opts.username}@${opts.host}:${opts.port ?? 22} failed: ${err.message}`,
1805
+ { cause: err }
1806
+ )
1807
+ );
1808
+ });
1809
+ client.connect({
1810
+ host: opts.host,
1811
+ port: opts.port ?? 22,
1812
+ username: opts.username,
1813
+ readyTimeout: opts.readyTimeoutMs ?? 2e4,
1814
+ ...auth
1815
+ });
1816
+ });
1817
+ }
1818
+ async function buildAuth(opts) {
1819
+ if (opts.privateKey !== void 0) {
1820
+ return { privateKey: opts.privateKey, ...opts.passphrase ? { passphrase: opts.passphrase } : {} };
1821
+ }
1822
+ if (opts.privateKeyPath !== void 0) {
1823
+ const fs = await import('fs/promises');
1824
+ const key = await fs.readFile(opts.privateKeyPath);
1825
+ return { privateKey: key, ...opts.passphrase ? { passphrase: opts.passphrase } : {} };
1826
+ }
1827
+ if (opts.password !== void 0) {
1828
+ return { password: opts.password };
1829
+ }
1830
+ const sock = opts.agent ?? env("SSH_AUTH_SOCK");
1831
+ return sock ? { agent: sock } : {};
1832
+ }
1833
+ async function createTunnel(net, client, daemonPort) {
1834
+ await new Promise((resolve, reject) => {
1835
+ client.forwardOut("127.0.0.1", 0, "127.0.0.1", daemonPort, (err, stream) => {
1836
+ if (err) {
1837
+ reject(
1838
+ new MindwireError(
1839
+ `mindwire: the SSH server refused a port-forward to 127.0.0.1:${daemonPort} (direct-tcpip). Enable \`AllowTcpForwarding yes\` in the remote sshd_config \u2014 mindwire tunnels the daemon's HTTP/SSE over the SSH connection.`,
1840
+ { cause: err }
1841
+ )
1842
+ );
1843
+ return;
1844
+ }
1845
+ try {
1846
+ (stream.destroy ?? stream.end)?.call(stream);
1847
+ } catch {
1848
+ }
1849
+ resolve();
1850
+ });
1851
+ });
1852
+ const sockets = /* @__PURE__ */ new Set();
1853
+ const server = net.createServer((socket) => {
1854
+ sockets.add(socket);
1855
+ socket.on("close", () => sockets.delete(socket));
1856
+ socket.on("error", () => {
1857
+ });
1858
+ client.forwardOut("127.0.0.1", 0, "127.0.0.1", daemonPort, (err, stream) => {
1859
+ if (err) {
1860
+ socket.destroy();
1861
+ return;
1862
+ }
1863
+ stream.on("error", () => socket.destroy());
1864
+ const duplex = stream;
1865
+ socket.pipe(duplex).pipe(socket);
1866
+ });
1867
+ });
1868
+ const localPort = await new Promise((resolve, reject) => {
1869
+ server.on("error", reject);
1870
+ server.listen(0, "127.0.0.1", () => {
1871
+ const addr = server.address();
1872
+ resolve(addr && typeof addr === "object" ? addr.port : 0);
1873
+ });
1874
+ });
1875
+ const close = async () => {
1876
+ for (const s of sockets) {
1877
+ try {
1878
+ s.destroy();
1879
+ } catch {
1880
+ }
1881
+ }
1882
+ sockets.clear();
1883
+ await new Promise((resolve) => server.close(() => resolve()));
1884
+ };
1885
+ return { baseUrl: `http://127.0.0.1:${localPort}`, close };
1886
+ }
1887
+ function shQuote(s) {
1888
+ return `'${s.replace(/'/g, `'\\''`)}'`;
1889
+ }
1890
+ function toCommandLine(argv) {
1891
+ return argv.map(shQuote).join(" ");
1892
+ }
1893
+ async function importSsh2() {
1894
+ const spec = "ssh2";
1895
+ try {
1896
+ const mod = await import(
1897
+ /* @vite-ignore */
1898
+ spec
1899
+ );
1900
+ return mod.default && mod.default.Client ? mod.default : mod;
1901
+ } catch (err) {
1902
+ throw new MindwireError(
1903
+ "mindwire: the SSH target needs the optional `ssh2` package. Install it (`npm i ssh2`). It's an optional peer dependency, so the core SDK stays dependency-free.",
1904
+ { cause: err }
1905
+ );
1906
+ }
1907
+ }
1908
+ function env(key) {
1909
+ const proc = globalThis.process;
1910
+ return proc?.env?.[key];
1911
+ }
1912
+
1913
+ // src/target/docker.ts
1914
+ function docker(config = {}) {
1915
+ return { name: "docker", connect: (spec) => connectDocker(config, spec) };
1916
+ }
1917
+ var DEFAULT_PORT2 = 8790;
1918
+ var DEFAULT_AGENT2 = "claude-code";
1919
+ var DEFAULT_AGENT_CWD2 = "/root";
1920
+ var DockerHost = class {
1921
+ constructor(container) {
1922
+ this.container = container;
1923
+ }
1924
+ container;
1925
+ async exec(argv) {
1926
+ const { Writable } = await import('stream');
1927
+ const exec = await this.container.exec({ Cmd: argv, AttachStdout: true, AttachStderr: true });
1928
+ const stream = await exec.start({ hijack: true, stdin: false });
1929
+ const out = [];
1930
+ const err = [];
1931
+ const sink = (arr) => new Writable({
1932
+ write(chunk, _enc, cb) {
1933
+ arr.push(Buffer.from(chunk));
1934
+ cb();
1935
+ }
1936
+ });
1937
+ this.container.modem.demuxStream(stream, sink(out), sink(err));
1938
+ await new Promise((resolve, reject) => {
1939
+ stream.on("end", () => resolve());
1940
+ stream.on("close", () => resolve());
1941
+ stream.on("error", (e) => reject(e instanceof Error ? e : new Error(String(e))));
1942
+ });
1943
+ const info = await exec.inspect();
1944
+ return {
1945
+ exitCode: info.ExitCode,
1946
+ stdout: Buffer.concat(out).toString("utf8"),
1947
+ stderr: Buffer.concat(err).toString("utf8")
1948
+ };
1949
+ }
1950
+ async putFile(path, data, opts) {
1951
+ const slash = path.lastIndexOf("/");
1952
+ const dir = slash > 0 ? path.slice(0, slash) : "/";
1953
+ const base = path.slice(slash + 1);
1954
+ await this.exec(["mkdir", "-p", dir]);
1955
+ const tar = tarSingleFile(base, data, opts?.mode ?? "0644");
1956
+ await this.container.putArchive(tar, { path: dir });
1957
+ }
1958
+ };
1959
+ async function connectDocker(config, spec) {
1960
+ const Docker = await importDockerode();
1961
+ const instance = config.docker ?? new Docker(config.engine);
1962
+ const merged = { ...config, agent: config.agent ?? spec.agent };
1963
+ return provisionDocker(instance, merged, spec.onLog);
1964
+ }
1965
+ async function provisionDocker(docker2, config = {}, onLog) {
1966
+ const port = config.port ?? DEFAULT_PORT2;
1967
+ const agent = config.agent ?? DEFAULT_AGENT2;
1968
+ const agentCwd = config.agentCwd ?? DEFAULT_AGENT_CWD2;
1969
+ const created = config.container === void 0;
1970
+ let container;
1971
+ if (config.container !== void 0) {
1972
+ container = docker2.getContainer(config.container);
1973
+ } else {
1974
+ if (!config.image) {
1975
+ throw new MindwireError(
1976
+ "mindwire: the Docker adapter needs an image or a container \u2014 pass docker({ image }) to create one, or docker({ container }) to attach to an existing one."
1977
+ );
1978
+ }
1979
+ const portKey = `${port}/tcp`;
1980
+ container = await docker2.createContainer({
1981
+ Image: config.image,
1982
+ Cmd: ["sleep", "infinity"],
1983
+ Tty: false,
1984
+ ExposedPorts: { [portKey]: {} },
1985
+ HostConfig: { PortBindings: { [portKey]: [{ HostPort: "0" }] } },
1986
+ ...config.createOptions ?? {}
1987
+ });
1988
+ }
1989
+ await container.start().catch(() => {
1990
+ });
1991
+ const info = await container.inspect();
1992
+ const binding = info.NetworkSettings?.Ports?.[`${port}/tcp`];
1993
+ const hostPort = binding?.[0]?.HostPort;
1994
+ if (!hostPort) {
1995
+ throw new MindwireError(
1996
+ `mindwire: the Docker container does not publish a host port for ${port}/tcp. ` + (created ? "This is unexpected for a container mindwire created." : "Attach to a container started with that port published (e.g. `-p 0:" + port + "`).")
1997
+ );
1998
+ }
1999
+ await ensureDaemon(new DockerHost(container), {
2000
+ port,
2001
+ agent,
2002
+ agentCwd,
2003
+ daemonBin: config.daemonBin,
2004
+ autoUpdate: config.autoUpdate,
2005
+ target: "docker",
2006
+ onLog
2007
+ });
2008
+ const stop = async () => {
2009
+ if (!config.stopOnExit) return;
2010
+ if (!created) return;
2011
+ try {
2012
+ await container.stop().catch(() => {
2013
+ });
2014
+ await container.remove({ force: true });
2015
+ } catch {
2016
+ }
2017
+ };
2018
+ return { id: container.id, baseUrl: `http://127.0.0.1:${hostPort}`, stop };
2019
+ }
2020
+ function tarSingleFile(name, data, mode) {
2021
+ const header = Buffer.alloc(512, 0);
2022
+ header.write(name.slice(0, 100), 0, "utf8");
2023
+ header.write(octal(parseInt(mode, 8) || 420, 8), 100, "utf8");
2024
+ header.write(octal(0, 8), 108, "utf8");
2025
+ header.write(octal(0, 8), 116, "utf8");
2026
+ header.write(octal(data.length, 12), 124, "utf8");
2027
+ header.write(octal(0, 12), 136, "utf8");
2028
+ header.write(" ", 148, "utf8");
2029
+ header.write("0", 156, "utf8");
2030
+ header.write("ustar\0", 257, "latin1");
2031
+ header.write("00", 263, "utf8");
2032
+ let sum = 0;
2033
+ for (const b of header) sum += b;
2034
+ header.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, "latin1");
2035
+ const body = Buffer.from(data);
2036
+ const pad = (512 - body.length % 512) % 512;
2037
+ return Buffer.concat([header, body, Buffer.alloc(pad), Buffer.alloc(1024)]);
2038
+ }
2039
+ function octal(n, len) {
2040
+ return n.toString(8).padStart(len - 1, "0").slice(-(len - 1)) + "\0";
2041
+ }
2042
+ async function importDockerode() {
2043
+ const spec = "dockerode";
2044
+ try {
2045
+ const mod = await import(
2046
+ /* @vite-ignore */
2047
+ spec
2048
+ );
2049
+ return mod.default ?? mod;
2050
+ } catch (err) {
2051
+ throw new MindwireError(
2052
+ "mindwire: the Docker sandbox adapter needs the optional `dockerode` package. Install it (`npm i dockerode`). It's an optional peer dependency, so the core SDK stays dependency-free.",
2053
+ { cause: err }
2054
+ );
2055
+ }
2056
+ }
2057
+
2058
+ // src/target/oblien.ts
2059
+ function oblien(config = {}) {
2060
+ return { name: "oblien", connect: (spec) => connectOblien(config, spec) };
2061
+ }
2062
+ var DEFAULT_PORT3 = 8790;
2063
+ var DEFAULT_IMAGE = "node-22";
2064
+ var DEFAULT_AGENT3 = "claude-code";
2065
+ var DEFAULT_AGENT_CWD3 = "/root";
2066
+ var SENTINEL_BASE = "http://mindwire-sandbox.local";
2067
+ var OblienHost = class {
2068
+ constructor(rt) {
2069
+ this.rt = rt;
2070
+ }
2071
+ rt;
2072
+ async exec(argv, opts) {
2073
+ const r = await this.rt.exec.run(argv, {
2074
+ execMode: "direct",
2075
+ timeoutSeconds: opts?.timeoutSeconds,
2076
+ keepLogs: true
2077
+ });
2078
+ return { exitCode: r.exit_code, stdout: r.stdout, stderr: r.stderr, error: r.error };
2079
+ }
2080
+ async putFile(path, data, opts) {
2081
+ const b64 = Buffer.from(data).toString("base64");
2082
+ const b64Path = `${path}.b64`;
2083
+ await this.rt.files.write({ fullPath: b64Path, content: b64, createDirs: true });
2084
+ const mode = opts?.mode ?? "0644";
2085
+ await this.rt.exec.run(
2086
+ ["bash", "-lc", `base64 -d ${b64Path} > ${path} && chmod ${mode} ${path} && rm -f ${b64Path}`],
2087
+ { execMode: "direct", timeoutSeconds: 30, keepLogs: true }
2088
+ );
2089
+ }
2090
+ };
2091
+ async function connectOblien(config, spec) {
2092
+ const clientId = config.clientId ?? env2("MINDWIRE_SANDBOX_CLIENT_ID") ?? env2("OBLIEN_CLIENT_ID");
2093
+ const clientSecret = config.clientSecret ?? env2("MINDWIRE_SANDBOX_CLIENT_SECRET") ?? env2("OBLIEN_CLIENT_SECRET");
2094
+ if (!clientId || !clientSecret) {
2095
+ throw new MindwireError(
2096
+ "mindwire: the Oblien target needs credentials \u2014 pass oblien({ clientId, clientSecret }) or set MINDWIRE_SANDBOX_CLIENT_ID / MINDWIRE_SANDBOX_CLIENT_SECRET (OBLIEN_CLIENT_ID / OBLIEN_CLIENT_SECRET are also accepted)."
2097
+ );
2098
+ }
2099
+ const mod = await importOblien();
2100
+ const client = new mod.default({
2101
+ clientId,
2102
+ clientSecret,
2103
+ ...config.baseUrl ? { baseUrl: config.baseUrl } : {}
2104
+ });
2105
+ return provisionOblien(client, { ...config, agent: config.agent ?? spec.agent }, spec.onLog);
2106
+ }
2107
+ async function provisionOblien(client, config = {}, onLog) {
2108
+ const port = config.port ?? DEFAULT_PORT3;
2109
+ const agent = config.agent ?? DEFAULT_AGENT3;
2110
+ const agentCwd = config.agentCwd ?? DEFAULT_AGENT_CWD3;
2111
+ const created = config.workspaceId === void 0;
2112
+ let workspaceId = config.workspaceId;
2113
+ if (workspaceId === void 0) {
2114
+ const params = {
2115
+ image: config.image ?? DEFAULT_IMAGE,
2116
+ mode: config.mode ?? "temporary"
2117
+ };
2118
+ if (config.name !== void 0) params["name"] = config.name;
2119
+ if (config.cpus !== void 0) params["cpus"] = config.cpus;
2120
+ if (config.memoryMb !== void 0) params["memory_mb"] = config.memoryMb;
2121
+ if (config.diskMb !== void 0) params["disk_size_mb"] = config.diskMb;
2122
+ const ws = await client.workspaces.create(params);
2123
+ workspaceId = ws.id;
2124
+ }
2125
+ const handle = client.workspace(workspaceId);
2126
+ await handle.start().catch(() => {
2127
+ });
2128
+ let rt = await handle.runtime();
2129
+ await ensureDaemon(new OblienHost(rt), {
2130
+ port,
2131
+ agent,
2132
+ agentCwd,
2133
+ daemonBin: config.daemonBin,
2134
+ autoUpdate: config.autoUpdate,
2135
+ target: "oblien",
2136
+ onLog
2137
+ });
2138
+ const fetchImpl = async (url, init) => {
2139
+ const { pathname, search } = new URL(url);
2140
+ const path = pathname + search;
2141
+ let res = await rt.proxy(port).fetch(path, init);
2142
+ if (res.status === 401) {
2143
+ rt = await handle.runtime({ force: true });
2144
+ res = await rt.proxy(port).fetch(path, init);
2145
+ }
2146
+ return res;
2147
+ };
2148
+ const stop = async () => {
2149
+ if (!config.stopOnExit) return;
2150
+ try {
2151
+ await (created ? handle.delete() : handle.stop());
2152
+ } catch {
2153
+ }
2154
+ };
2155
+ return { id: workspaceId, workspaceId, baseUrl: SENTINEL_BASE, fetch: fetchImpl, stop };
2156
+ }
2157
+ async function importOblien() {
2158
+ const spec = "oblien";
2159
+ try {
2160
+ return await import(
2161
+ /* @vite-ignore */
2162
+ spec
2163
+ );
2164
+ } catch (err) {
2165
+ throw new MindwireError(
2166
+ "mindwire: sandbox mode with the default (Oblien) adapter needs the optional `oblien` package. Install it (`npm i oblien`). It's an optional peer dependency, so the core SDK stays dependency-free.",
2167
+ { cause: err }
2168
+ );
2169
+ }
2170
+ }
2171
+ function env2(key) {
2172
+ const proc = globalThis.process;
2173
+ return proc?.env?.[key];
2174
+ }
2175
+
2176
+ // src/catalog/index.ts
2177
+ var MODELS_DEV_URL = "https://models.dev/api.json";
2178
+ var TTL_MS = 6 * 60 * 60 * 1e3;
2179
+ function toCost(c) {
2180
+ if (!c) return void 0;
2181
+ const cost = {};
2182
+ if (typeof c.input === "number") cost.input = c.input;
2183
+ if (typeof c.output === "number") cost.output = c.output;
2184
+ if (typeof c.cache_read === "number") cost.cacheRead = c.cache_read;
2185
+ if (typeof c.cache_write === "number") cost.cacheWrite = c.cache_write;
2186
+ return Object.keys(cost).length ? cost : void 0;
2187
+ }
2188
+ function toModel(providerId, id, m) {
2189
+ const info = { id: m.id ?? id, label: m.name || (m.id ?? id), provider: providerId };
2190
+ if (m.limit?.context) info.contextWindow = m.limit.context;
2191
+ if (m.limit?.output) info.maxOutput = m.limit.output;
2192
+ if (m.modalities?.input?.length) info.inputModalities = m.modalities.input;
2193
+ if (m.modalities?.output?.length) info.outputModalities = m.modalities.output;
2194
+ if (m.reasoning) info.reasoning = true;
2195
+ if (m.tool_call) info.toolCall = true;
2196
+ if (m.attachment) info.attachment = true;
2197
+ const cost = toCost(m.cost);
2198
+ if (cost) info.cost = cost;
2199
+ return info;
2200
+ }
2201
+ function project(feed) {
2202
+ const providers = [];
2203
+ for (const [pid, prov] of Object.entries(feed ?? {})) {
2204
+ if (!prov || typeof prov !== "object") continue;
2205
+ const id = prov.id ?? pid;
2206
+ const models = Object.entries(prov.models ?? {}).map(([mid, m]) => toModel(id, mid, m)).sort((a, b) => a.label.localeCompare(b.label) || a.id.localeCompare(b.id));
2207
+ providers.push({
2208
+ id,
2209
+ name: prov.name || id,
2210
+ env: Array.isArray(prov.env) ? prov.env.filter((v) => typeof v === "string" && !!v) : [],
2211
+ ...prov.npm ? { npm: prov.npm } : {},
2212
+ ...prov.api ? { api: prov.api } : {},
2213
+ ...prov.doc ? { doc: prov.doc } : {},
2214
+ models
2215
+ });
2216
+ }
2217
+ return providers.sort((a, b) => a.name.localeCompare(b.name));
2218
+ }
2219
+ var cache = null;
2220
+ var inflight = null;
2221
+ async function loadCatalog(opts = {}) {
2222
+ const url = opts.url ?? MODELS_DEV_URL;
2223
+ if (cache && cache.url === url && Date.now() - cache.at < TTL_MS) return cache.data;
2224
+ if (inflight) return inflight;
2225
+ const doFetch = opts.fetch ?? globalThis.fetch;
2226
+ if (typeof doFetch !== "function") {
2227
+ throw new Error("no fetch implementation available \u2014 pass CatalogOptions.fetch");
2228
+ }
2229
+ inflight = (async () => {
2230
+ const res = await doFetch(url, { headers: { accept: "application/json" }, signal: opts.signal });
2231
+ if (!res.ok) throw new Error(`models.dev catalog fetch failed: ${res.status} ${res.statusText}`);
2232
+ const data = project(await res.json());
2233
+ cache = { url, at: Date.now(), data };
2234
+ return data;
2235
+ })();
2236
+ try {
2237
+ return await inflight;
2238
+ } finally {
2239
+ inflight = null;
2240
+ }
2241
+ }
2242
+ function catalogProviders(opts) {
2243
+ return loadCatalog(opts);
2244
+ }
2245
+ async function catalogProvider(id, opts) {
2246
+ return (await loadCatalog(opts)).find((p) => p.id === id);
2247
+ }
2248
+ async function catalogModels(provider, opts) {
2249
+ const providers = await loadCatalog(opts);
2250
+ if (provider) return providers.find((p) => p.id === provider)?.models ?? [];
2251
+ return providers.flatMap((p) => p.models);
2252
+ }
2253
+ async function lookupModel(provider, id, opts) {
2254
+ return (await catalogProvider(provider, opts))?.models.find((m) => m.id === id);
2255
+ }
2256
+ function clearCatalogCache() {
2257
+ cache = null;
2258
+ inflight = null;
2259
+ }
2260
+
2261
+ exports.ApiError = ApiError;
2262
+ exports.AuthApi = AuthApi;
2263
+ exports.ContainerHost = ContainerHost;
2264
+ exports.Http = Http;
2265
+ exports.MODELS_DEV_URL = MODELS_DEV_URL;
2266
+ exports.McpApi = McpApi;
2267
+ exports.Mindwire = Mindwire;
2268
+ exports.MindwireError = MindwireError;
2269
+ exports.NotifyApi = NotifyApi;
2270
+ exports.PromptsApi = PromptsApi;
2271
+ exports.ProvidersApi = ProvidersApi;
2272
+ exports.Run = Run;
2273
+ exports.RunFailedError = RunFailedError;
2274
+ exports.SDK_VERSION = SDK_VERSION;
2275
+ exports.TimeoutError = TimeoutError;
2276
+ exports.catalogModels = catalogModels;
2277
+ exports.catalogProvider = catalogProvider;
2278
+ exports.catalogProviders = catalogProviders;
2279
+ exports.clearCatalogCache = clearCatalogCache;
2280
+ exports.docker = docker;
2281
+ exports.ensureDaemon = ensureDaemon;
2282
+ exports.ensureDaemonBinary = ensureDaemonBinary;
2283
+ exports.loadCatalog = loadCatalog;
2284
+ exports.local = local;
2285
+ exports.lookupModel = lookupModel;
2286
+ exports.oblien = oblien;
2287
+ exports.provisionContainer = provisionContainer;
2288
+ exports.provisionDocker = provisionDocker;
2289
+ exports.provisionOblien = provisionOblien;
2290
+ exports.provisionSsh = provisionSsh;
2291
+ exports.provisionSshContainer = provisionSshContainer;
2292
+ exports.remote = remote;
2293
+ exports.resolveLinuxDaemon = resolveLinuxDaemon;
2294
+ exports.ssh = ssh;
2295
+ exports.startEmbedded = startEmbedded;
2296
+ //# sourceMappingURL=index.cjs.map
2297
+ //# sourceMappingURL=index.cjs.map