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