wizards 0.20.5 → 0.21.0

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/README.md CHANGED
@@ -228,13 +228,13 @@ and is a site of its own: `pnpm dev:docs`.
228
228
 
229
229
  ## License
230
230
 
231
- The wizard format, the runner and four libraries are MIT. The rest of the code is FSL-1.1-MIT.
231
+ The wizard format, the runner and the libraries are MIT. The rest of the code is FSL-1.1-MIT.
232
232
 
233
233
  | What | Licence |
234
234
  |---|---|
235
- | The wizard format: the eighteen files of `packages/shared` that define a wizard, read it and pack it as a `.wizard` file | MIT or FSL-1.1-MIT, your choice ([LICENSE-MIT](packages/shared/LICENSE-MIT)) |
235
+ | The wizard format: the fifteen files of `packages/shared` that define a wizard, read it and pack it as a `.wizard` file | MIT or FSL-1.1-MIT, your choice ([LICENSE-MIT](packages/shared/LICENSE-MIT)) |
236
236
  | The runner, `packages/runner` | MIT ([LICENSE](packages/runner/LICENSE)) |
237
- | The libraries `@engenty/decision-model`, `@engenty/search-index`, `@engenty/search-libsql`, `@engenty/goose`, `@engenty/vault`, `@engenty/plugins` and `@engenty/browser` on npm, in `packages/decision-model`, `packages/search-index`, `packages/search-libsql`, `packages/goose`, `packages/vault`, `packages/plugins` and `packages/browser` | MIT (the `LICENSE` in each folder) |
237
+ | The libraries `@engenty/chatviews`, `@engenty/decision-model`, `@engenty/search-index`, `@engenty/search-libsql`, `@engenty/tool-harness`, `@engenty/goose`, `@engenty/vault`, `@engenty/plugins`, `@engenty/browser`, `@engenty/local-models` and `@engenty/model-setup` on npm, in `packages/chatviews`, `packages/decision-model`, `packages/search-index`, `packages/search-libsql`, `packages/tool-harness`, `packages/goose`, `packages/vault`, `packages/plugins`, `packages/browser`, `packages/local-models` and `packages/model-setup` | MIT (the `LICENSE` in each folder) |
238
238
  | The plugin for the AI apps, `plugin/`, without the engenty figures in it | MIT ([LICENSE](plugin/LICENSE)) |
239
239
  | Everything else: the studio, the runtime, the `wizards` command, `@engenty/wizards` on npm | FSL-1.1-MIT ([LICENSE](LICENSE)) |
240
240
  | The engenty figures as artwork | CC BY 4.0 ([LICENSE-FIGURES](LICENSE-FIGURES)) |
@@ -0,0 +1,375 @@
1
+ // The tunnel of a home at <name>.wizards.host: frpc to our relay, and its certificate.
2
+ //
3
+ // `wizards bot tunnel` (bin/bot.mjs) uses what this file exports, and copies the file into the
4
+ // home as `tunnel/run.mjs`; run there by the home's tunnel service, it keeps frpc running and
5
+ // renews the certificate before it ends. Like bot.mjs it needs nothing but Node.
6
+ //
7
+ // tunnel/claim.pem the tunnel's own Ed25519 key (0600): its name is made from it, and it
8
+ // claims the name again after --off; losing it loses the name
9
+ // tunnel/tunnel.json the API, the name, the key for it, frpc and the home's port (0600)
10
+ // tunnel/frpc.toml frpc's settings (0600: it holds the key)
11
+ // tunnel/key.pem this computer's private key for the name (0600); it never leaves it
12
+ // tunnel/cert.pem the certificate for the name, from Let's Encrypt through wizards.host
13
+ //
14
+ // The relay ends no TLS: frpc's https2http plugin ends it here, with key.pem and cert.pem, and
15
+ // hands plain HTTP to the home on 127.0.0.1.
16
+ import { spawn, spawnSync } from "node:child_process";
17
+ import {
18
+ createHash,
19
+ createPrivateKey,
20
+ createPublicKey,
21
+ generateKeyPairSync,
22
+ sign,
23
+ X509Certificate,
24
+ } from "node:crypto";
25
+ import { chmodSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
26
+ import { join } from "node:path";
27
+ import { pathToFileURL } from "node:url";
28
+
29
+ /** Where tunnels get their names and certificates: WIZARDS_TUNNEL_URL changes it. */
30
+ export const TUNNEL_URL = "https://wizards.host";
31
+ /** Renew this long before a certificate ends. */
32
+ export const RENEW_BEFORE = 30 * 24 * 3600_000;
33
+ /** How often the running tunnel looks at its certificate. */
34
+ const CHECK_EVERY = 12 * 3600_000;
35
+
36
+ // --- the tunnel's own key, and the name it gets ---------------------------------------------
37
+
38
+ const BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
39
+
40
+ /** RFC 4648 base32, lower case, without padding. */
41
+ function base32(bytes) {
42
+ let bits = 0;
43
+ let value = 0;
44
+ let out = "";
45
+ for (const byte of bytes) {
46
+ value = (value << 8) | byte;
47
+ bits += 8;
48
+ while (bits >= 5) {
49
+ out += BASE32[(value >>> (bits - 5)) & 31];
50
+ bits -= 5;
51
+ }
52
+ }
53
+ if (bits > 0) {
54
+ out += BASE32[(value << (5 - bits)) & 31];
55
+ }
56
+ return out;
57
+ }
58
+
59
+ /** The name a key claims: the first 10 characters of base32(sha256(raw public key)). */
60
+ export function claimName(publicKeyRaw) {
61
+ return base32(createHash("sha256").update(publicKeyRaw).digest()).slice(0, 10);
62
+ }
63
+
64
+ /** The tunnel's Ed25519 key in `claim.pem`, made the first time; it stays for you alone. */
65
+ export function claimKey(file) {
66
+ if (!existsSync(file)) {
67
+ const { privateKey } = generateKeyPairSync("ed25519");
68
+ writeFileAtomic(file, privateKey.export({ type: "pkcs8", format: "pem" }), true);
69
+ }
70
+ return createPrivateKey(readFileSync(file, "utf8"));
71
+ }
72
+
73
+ /** A key's raw 32-byte public half, base64url. */
74
+ export function publicKeyOf(privateKey) {
75
+ return createPublicKey(privateKey).export({ format: "jwk" }).x;
76
+ }
77
+
78
+ /** What a claim signs. */
79
+ export const claimText = (publicKey, timestamp) => `wizards.host claim ${publicKey} ${timestamp}`;
80
+
81
+ /** The body of `POST /v1/tunnels/claim`: the public key, now, and the signature over both. */
82
+ export function claimBody(privateKey, now = Date.now()) {
83
+ const publicKey = publicKeyOf(privateKey);
84
+ const signature = sign(null, Buffer.from(claimText(publicKey, now)), privateKey).toString(
85
+ "base64url",
86
+ );
87
+ return { publicKey, timestamp: now, signature };
88
+ }
89
+
90
+ /**
91
+ * Claims the name of the key in `file`: no account, no browser. Every claim gives a fresh key
92
+ * for the relay; the name stays the key's.
93
+ */
94
+ export async function claim(api, file, computer) {
95
+ const { data } = await call(api, "/v1/tunnels/claim", {
96
+ method: "POST",
97
+ body: { ...claimBody(claimKey(file)), ...(computer ? { computer } : {}) },
98
+ });
99
+ return data;
100
+ }
101
+
102
+ // --- a key and a certificate request ---------------------------------------------------------
103
+
104
+ /** A new EC P-256 private key, as PEM. */
105
+ export function makeKey() {
106
+ const { privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
107
+ return privateKey.export({ type: "pkcs8", format: "pem" });
108
+ }
109
+
110
+ function length(n) {
111
+ if (n < 0x80) {
112
+ return Buffer.from([n]);
113
+ }
114
+ const bytes = [];
115
+ for (let rest = n; rest > 0; rest >>= 8) {
116
+ bytes.unshift(rest & 0xff);
117
+ }
118
+ return Buffer.from([0x80 | bytes.length, ...bytes]);
119
+ }
120
+
121
+ const tlv = (tag, ...parts) => {
122
+ const body = Buffer.concat(parts);
123
+ return Buffer.concat([Buffer.from([tag]), length(body.length), body]);
124
+ };
125
+
126
+ function oid(text) {
127
+ const [a, b, ...rest] = text.split(".").map(Number);
128
+ const bytes = [a * 40 + b];
129
+ for (const n of rest) {
130
+ const chunk = [n & 0x7f];
131
+ for (let v = n >> 7; v > 0; v >>= 7) {
132
+ chunk.unshift((v & 0x7f) | 0x80);
133
+ }
134
+ bytes.push(...chunk);
135
+ }
136
+ return tlv(0x06, Buffer.from(bytes));
137
+ }
138
+
139
+ const sequence = (...parts) => tlv(0x30, ...parts);
140
+
141
+ /**
142
+ * A PKCS#10 certificate request for one name, signed with the key: the name as the subject's
143
+ * common name and as the only DNS name. Built by hand, since Node has no API for it.
144
+ */
145
+ export function csrFor(name, keyPem) {
146
+ const key = createPrivateKey(keyPem);
147
+ const spki = createPublicKey(key).export({ type: "spki", format: "der" });
148
+ const subject = sequence(tlv(0x31, sequence(oid("2.5.4.3"), tlv(0x0c, Buffer.from(name)))));
149
+ const san = sequence(tlv(0x82, Buffer.from(name, "ascii")));
150
+ const extensions = sequence(sequence(oid("2.5.29.17"), tlv(0x04, san)));
151
+ const attributes = tlv(0xa0, sequence(oid("1.2.840.113549.1.9.14"), tlv(0x31, extensions)));
152
+ const info = sequence(tlv(0x02, Buffer.from([0])), subject, spki, attributes);
153
+ const signature = sign("sha256", info, { key, dsaEncoding: "der" });
154
+ const der = sequence(
155
+ info,
156
+ sequence(oid("1.2.840.10045.4.3.2")),
157
+ tlv(0x03, Buffer.from([0]), signature),
158
+ );
159
+ const lines = der
160
+ .toString("base64")
161
+ .match(/.{1,64}/g)
162
+ .join("\n");
163
+ return `-----BEGIN CERTIFICATE REQUEST-----\n${lines}\n-----END CERTIFICATE REQUEST-----\n`;
164
+ }
165
+
166
+ // --- the certificate -------------------------------------------------------------------------
167
+
168
+ /** When a certificate ends, or null when the text isn't one. */
169
+ export function notAfter(certPem) {
170
+ try {
171
+ return new Date(new X509Certificate(certPem).validTo);
172
+ } catch {
173
+ return null;
174
+ }
175
+ }
176
+
177
+ /** Whether a certificate is missing, unreadable, or ends within RENEW_BEFORE. */
178
+ export function needsRenewal(certPem, now = Date.now()) {
179
+ const end = certPem ? notAfter(certPem) : null;
180
+ return !end || end.getTime() - now < RENEW_BEFORE;
181
+ }
182
+
183
+ /** Something the tunnel API said no to, with its sentence for people and its code. */
184
+ export class AccountError extends Error {
185
+ constructor(message, code, status) {
186
+ super(message);
187
+ this.code = code;
188
+ this.status = status;
189
+ }
190
+ }
191
+
192
+ /** A call to the tunnel API at `api` (wizards.host): its JSON, or an AccountError. */
193
+ export async function call(api, path, { method = "GET", key, body } = {}) {
194
+ let res;
195
+ try {
196
+ res = await fetch(`${api}${path}`, {
197
+ method,
198
+ headers: {
199
+ ...(body ? { "content-type": "application/json" } : {}),
200
+ ...(key ? { authorization: `Bearer ${key}` } : {}),
201
+ "user-agent": "wizards-bot-tunnel",
202
+ },
203
+ body: body ? JSON.stringify(body) : undefined,
204
+ signal: AbortSignal.timeout(30_000),
205
+ });
206
+ } catch (error) {
207
+ throw new AccountError(`${api} didn’t answer: ${error.message}`, "unreachable", 0);
208
+ }
209
+ const data = res.status === 204 ? {} : await res.json().catch(() => ({}));
210
+ if (!res.ok) {
211
+ throw new AccountError(
212
+ data.error || `${api} answered ${res.status}.`,
213
+ data.code || "error",
214
+ res.status,
215
+ );
216
+ }
217
+ return { status: res.status, data };
218
+ }
219
+
220
+ const pause = (ms) => new Promise((done) => setTimeout(done, ms));
221
+
222
+ /**
223
+ * A certificate for the key's name: posts the request, then asks every `every` ms until the
224
+ * API has it (Let's Encrypt checks the name's DNS meanwhile). Returns the PEM chain.
225
+ */
226
+ export async function orderCertificate(api, key, csr, { every = 3000, within = 300_000 } = {}) {
227
+ const { data: order } = await call(api, "/v1/tunnels/cert", {
228
+ method: "POST",
229
+ key,
230
+ body: { csr },
231
+ });
232
+ const until = Date.now() + within;
233
+ while (Date.now() < until) {
234
+ const { data } = await call(api, `/v1/tunnels/cert/${encodeURIComponent(order.id)}`, {
235
+ key,
236
+ });
237
+ if (data.state === "ready" && data.cert) {
238
+ return data.cert;
239
+ }
240
+ if (data.state === "failed") {
241
+ throw new AccountError(data.error || "The certificate couldn’t be made.", "failed", 200);
242
+ }
243
+ await pause(every);
244
+ }
245
+ throw new AccountError("The certificate took too long. Try again in a few minutes.", "slow", 0);
246
+ }
247
+
248
+ /** Writes a file in one move, readable only by you where `secret`. */
249
+ export function writeFileAtomic(file, text, secret = false) {
250
+ const next = `${file}.next`;
251
+ writeFileSync(next, text, { mode: secret ? 0o600 : 0o644 });
252
+ if (secret) {
253
+ chmodSync(next, 0o600);
254
+ }
255
+ renameSync(next, file);
256
+ }
257
+
258
+ // --- frpc's settings -------------------------------------------------------------------------
259
+
260
+ const toml = (text) => JSON.stringify(String(text));
261
+
262
+ /**
263
+ * frpc.toml for a home: one https proxy for the name, TLS ended here by the https2http plugin,
264
+ * the control connection over wss to the relay, the key as metadata, and frpc's admin API on
265
+ * 127.0.0.1 so `frpc reload` can read a renewed certificate.
266
+ */
267
+ export function frpcConfig(tunnel) {
268
+ return [
269
+ "# Written by `wizards bot tunnel`; `wizards bot update` writes it again.",
270
+ `serverAddr = ${toml(tunnel.server)}`,
271
+ `serverPort = ${Number(tunnel.serverPort)}`,
272
+ "loginFailExit = false",
273
+ 'transport.protocol = "wss"',
274
+ "transport.tls.useSystemCa = true",
275
+ "transport.heartbeatInterval = 30",
276
+ "transport.heartbeatTimeout = 90",
277
+ `metadatas.token = ${toml(tunnel.key)}`,
278
+ 'webServer.addr = "127.0.0.1"',
279
+ `webServer.port = ${Number(tunnel.adminPort)}`,
280
+ 'webServer.user = "wizards"',
281
+ `webServer.password = ${toml(tunnel.adminPassword)}`,
282
+ "",
283
+ "[[proxies]]",
284
+ `name = ${toml(tunnel.name)}`,
285
+ 'type = "https"',
286
+ `customDomains = [${toml(tunnel.name)}]`,
287
+ "",
288
+ "[proxies.plugin]",
289
+ 'type = "https2http"',
290
+ `localAddr = ${toml(`127.0.0.1:${Number(tunnel.port)}`)}`,
291
+ `crtPath = ${toml(join(tunnel.dir, "cert.pem"))}`,
292
+ `keyPath = ${toml(join(tunnel.dir, "key.pem"))}`,
293
+ "",
294
+ ].join("\n");
295
+ }
296
+
297
+ // --- running -------------------------------------------------------------------------------
298
+
299
+ const stamp = () => new Date().toISOString();
300
+ const say = (text) => console.log(`${stamp()} ${text}`);
301
+
302
+ /** Renews the certificate when it's due; true when there's a new one. */
303
+ export async function renewIfDue(tunnel, now = Date.now()) {
304
+ const certFile = join(tunnel.dir, "cert.pem");
305
+ const current = existsSync(certFile) ? readFileSync(certFile, "utf8") : null;
306
+ if (!needsRenewal(current, now)) {
307
+ return false;
308
+ }
309
+ const keyPem = readFileSync(join(tunnel.dir, "key.pem"), "utf8");
310
+ const cert = await orderCertificate(tunnel.api, tunnel.key, csrFor(tunnel.name, keyPem));
311
+ writeFileAtomic(certFile, cert);
312
+ return true;
313
+ }
314
+
315
+ /**
316
+ * The tunnel's service: frpc, started again when it ends (after 1 s, then longer, up to a
317
+ * minute), and the certificate looked at every 12 hours.
318
+ */
319
+ export async function run(dir) {
320
+ const tunnel = { ...JSON.parse(readFileSync(join(dir, "tunnel.json"), "utf8")), dir };
321
+ const config = join(dir, "frpc.toml");
322
+ let child = null;
323
+ let wait = 1000;
324
+ let stopping = false;
325
+ const startFrpc = () => {
326
+ const started = Date.now();
327
+ say(`frpc for https://${tunnel.name}`);
328
+ child = spawn(tunnel.frpc, ["-c", config], { stdio: "inherit" });
329
+ child.on("exit", (code, signal) => {
330
+ child = null;
331
+ if (stopping) {
332
+ return;
333
+ }
334
+ wait = Date.now() - started > 300_000 ? 1000 : Math.min(wait * 2, 60_000);
335
+ say(`frpc ended (${signal || code}); again in ${Math.round(wait / 1000)} s`);
336
+ setTimeout(startFrpc, wait);
337
+ });
338
+ child.on("error", (error) => say(`frpc didn’t start: ${error.message}`));
339
+ };
340
+ const check = async () => {
341
+ try {
342
+ if (await renewIfDue(tunnel)) {
343
+ say(
344
+ `New certificate for ${tunnel.name}, until ${notAfter(readFileSync(join(dir, "cert.pem"), "utf8"))?.toISOString()}`,
345
+ );
346
+ const reload = spawnSync(tunnel.frpc, ["reload", "-c", config], { encoding: "utf8" });
347
+ if (reload.status !== 0) {
348
+ say(`frpc reload failed (${(reload.stderr || reload.stdout).trim()}); restarting frpc`);
349
+ child?.kill("SIGTERM");
350
+ }
351
+ }
352
+ } catch (error) {
353
+ say(`The certificate wasn’t renewed: ${error.message}`);
354
+ }
355
+ };
356
+ for (const signal of ["SIGTERM", "SIGINT"]) {
357
+ process.on(signal, () => {
358
+ stopping = true;
359
+ child?.kill("SIGTERM");
360
+ process.exit(0);
361
+ });
362
+ }
363
+ await check();
364
+ startFrpc();
365
+ setInterval(check, CHECK_EVERY);
366
+ }
367
+
368
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
369
+ const dir = process.argv[2];
370
+ if (!dir) {
371
+ console.error("Usage: node run.mjs <the home's tunnel folder>");
372
+ process.exit(2);
373
+ }
374
+ await run(dir);
375
+ }
package/bin/bot.mjs CHANGED
@@ -24,10 +24,15 @@
24
24
  //
25
25
  // The Node in ~/.engenty/wizards/tools is shared by all of them.
26
26
  //
27
+ // `wizards bot tunnel` puts a home on the internet at https://<name>.wizards.host, through our relay
28
+ // (frp): frpc dials out from this computer, TLS ends here (bin/bot-tunnel.mjs). Its files are in
29
+ // the home's `tunnel/` folder: <folder>/tunnel, or <data>/tunnel for the home above.
30
+ //
27
31
  // For tests: WIZARDS_BOT_TARBALL (a path or an address of a tarball instead of the release's),
28
- // ENGENTY_HOME, WIZARDS_BOT_DATA.
32
+ // ENGENTY_HOME, WIZARDS_BOT_DATA, WIZARDS_TUNNEL_URL (the tunnel API, https://wizards.host),
33
+ // WIZARDS_BOT_FRPC (an frpc to use instead of downloading one).
29
34
  import { spawn, spawnSync } from "node:child_process";
30
- import { createHash } from "node:crypto";
35
+ import { createHash, randomBytes } from "node:crypto";
31
36
  import {
32
37
  chmodSync,
33
38
  copyFileSync,
@@ -47,9 +52,21 @@ import {
47
52
  } from "node:fs";
48
53
  import { request } from "node:http";
49
54
  import { connect, createServer } from "node:net";
50
- import { homedir } from "node:os";
55
+ import { homedir, hostname } from "node:os";
51
56
  import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
52
57
  import { createInterface } from "node:readline";
58
+ import { fileURLToPath } from "node:url";
59
+ import {
60
+ AccountError,
61
+ call,
62
+ claim,
63
+ csrFor,
64
+ frpcConfig,
65
+ makeKey,
66
+ orderCertificate,
67
+ TUNNEL_URL,
68
+ writeFileAtomic,
69
+ } from "./bot-tunnel.mjs";
53
70
 
54
71
  /** The Node install.sh brings; the home gets the same where it needs one. */
55
72
  export const NODE_VERSION = "26.12.0";
@@ -64,6 +81,16 @@ export const LABEL = "com.engenty.wizards.bot";
64
81
  export const LINK_LABEL = "com.engenty.wizards.bot.link";
65
82
  export const UNIT = "wizards-bot.service";
66
83
  export const LINK_UNIT = "wizards-bot-link.service";
84
+ /** frp (github.com/fatedier/frp, Apache-2.0): the relay's frps and this computer's frpc. */
85
+ export const FRP_VERSION = "0.72.0";
86
+ /** sha256 of frp's release files, from the release's frp_sha256_checksums.txt. */
87
+ export const FRP_SHA256 = {
88
+ darwin_amd64: "60439dc6bf794c4182a1a4cac147d642f839d55201607208979eb23aecd09be9",
89
+ darwin_arm64: "6e8576c5b6b9914a86850f6ff4fb81c5a09e706f91f70f64d5f398558bdc9db8",
90
+ linux_amd64: "daf719b32ca2778770bb92955e231a07414d754378b9af328aa2642862479804",
91
+ linux_arm64: "02180b857480302fd934e9ddbd50fe2f73229f99062f88756abc6de9df5e95cf",
92
+ windows_amd64: "5197c1b69564089cdc229fc1260a0e25db1e722b1b7db45fe1542c3c43edf9ae",
93
+ };
67
94
  /** How long the home may take to answer on /health after it starts. */
68
95
  const HEALTH_WAIT = 90_000;
69
96
 
@@ -95,16 +122,23 @@ export function layout(env = process.env, folder = null) {
95
122
  launchAgents: join(user, "Library", "LaunchAgents"),
96
123
  units: join(config, "systemd", "user"),
97
124
  };
98
- const services = (label, linkLabel, unit, linkUnit) => ({
99
- label,
100
- linkLabel,
101
- unitName: unit,
102
- linkUnitName: linkUnit,
103
- agent: join(shared.launchAgents, `${label}.plist`),
104
- linkAgent: join(shared.launchAgents, `${linkLabel}.plist`),
105
- unit: join(shared.units, unit),
106
- linkUnit: join(shared.units, linkUnit),
107
- });
125
+ const services = (label, linkLabel, unit, linkUnit) => {
126
+ const tunnelUnit = unit.replace(/\.service$/, "-tunnel.service");
127
+ return {
128
+ label,
129
+ linkLabel,
130
+ tunnelLabel: `${label}.tunnel`,
131
+ unitName: unit,
132
+ linkUnitName: linkUnit,
133
+ tunnelUnitName: tunnelUnit,
134
+ agent: join(shared.launchAgents, `${label}.plist`),
135
+ linkAgent: join(shared.launchAgents, `${linkLabel}.plist`),
136
+ tunnelAgent: join(shared.launchAgents, `${label}.tunnel.plist`),
137
+ unit: join(shared.units, unit),
138
+ linkUnit: join(shared.units, linkUnit),
139
+ tunnelUnit: join(shared.units, tunnelUnit),
140
+ };
141
+ };
108
142
  if (folder) {
109
143
  const dir = resolve(folder);
110
144
  const id = folderId(dir);
@@ -120,8 +154,10 @@ export function layout(env = process.env, folder = null) {
120
154
  logs,
121
155
  log: join(logs, "bot.log"),
122
156
  linkLog: join(logs, "bot-link.log"),
157
+ tunnelLog: join(logs, "bot-tunnel.log"),
123
158
  installLog: join(logs, "bot-install.log"),
124
159
  data: join(dir, "data"),
160
+ tunnel: join(dir, "tunnel"),
125
161
  ...services(
126
162
  `${LABEL}.${id}`,
127
163
  `${LABEL}.${id}.link`,
@@ -131,6 +167,7 @@ export function layout(env = process.env, folder = null) {
131
167
  };
132
168
  }
133
169
  const bot = join(home, "bot");
170
+ const data = (env.WIZARDS_BOT_DATA || "").trim() || join(user, ".wizards-bot");
134
171
  return {
135
172
  ...shared,
136
173
  folder: null,
@@ -142,8 +179,10 @@ export function layout(env = process.env, folder = null) {
142
179
  logs: join(home, "logs"),
143
180
  log: join(home, "logs", "bot.log"),
144
181
  linkLog: join(home, "logs", "bot-link.log"),
182
+ tunnelLog: join(home, "logs", "bot-tunnel.log"),
145
183
  installLog: join(home, "logs", "bot-install.log"),
146
- data: (env.WIZARDS_BOT_DATA || "").trim() || join(user, ".wizards-bot"),
184
+ data,
185
+ tunnel: join(data, "tunnel"),
147
186
  ...services(LABEL, LINK_LABEL, UNIT, LINK_UNIT),
148
187
  };
149
188
  }
@@ -222,7 +261,7 @@ export function homeAddress(text) {
222
261
  }
223
262
 
224
263
  /** The PATH without what npm put in for running this command. */
225
- function cleanPath(env = process.env) {
264
+ export function cleanPath(env = process.env) {
226
265
  return (env.PATH || "")
227
266
  .split(delimiter)
228
267
  .filter((dir) => dir && !/[\\/](node_modules[\\/]\.bin|node-gyp-bin)$/.test(dir))
@@ -542,13 +581,72 @@ function saveSettings(paths, settings) {
542
581
  const xml = (text) =>
543
582
  String(text).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
544
583
 
584
+ /** The commands a home thinks with, which its service has to find. */
585
+ export const AGENT_COMMANDS = ["claude", "codex", "ollama", "goose"];
586
+
587
+ function runnable(file) {
588
+ try {
589
+ return statSync(file).isFile() && (statSync(file).mode & 0o111) !== 0;
590
+ } catch {
591
+ return false;
592
+ }
593
+ }
594
+
595
+ /**
596
+ * Folders where those commands are often installed without being on the PATH of the shell that
597
+ * ran this command: Node version managers (nvm's newest first), global npm and pnpm folders,
598
+ * Bun, Homebrew.
599
+ */
600
+ function commandFolders(home, system) {
601
+ const nvm = join(home, ".nvm", "versions", "node");
602
+ const versions = listDir(nvm)
603
+ .filter((name) => /^v\d+/.test(name))
604
+ .sort((a, b) => (older(a.slice(1), b.slice(1)) ? 1 : older(b.slice(1), a.slice(1)) ? -1 : 0))
605
+ .map((name) => join(nvm, name, "bin"));
606
+ return [
607
+ ...versions,
608
+ join(home, ".volta", "bin"),
609
+ join(home, ".npm-global", "bin"),
610
+ join(home, "Library", "pnpm"),
611
+ join(home, ".local", "share", "pnpm"),
612
+ join(home, ".bun", "bin"),
613
+ join(home, ".local", "bin"),
614
+ ...system,
615
+ ];
616
+ }
617
+
618
+ /** Homebrew's folders, where Ollama usually is. */
619
+ const SYSTEM_FOLDERS = ["/opt/homebrew/bin", "/usr/local/bin"];
620
+
621
+ /**
622
+ * The folders to add to a service's PATH so it finds Claude, Codex, Ollama and Goose that the
623
+ * PATH of this shell misses: a Codex installed with npm under nvm, say, when nvm wasn't loaded.
624
+ */
625
+ export function agentFolders(env = process.env, home = homedir(), system = SYSTEM_FOLDERS) {
626
+ const path = cleanPath(env).split(delimiter);
627
+ const found = [];
628
+ for (const name of AGENT_COMMANDS) {
629
+ if (path.some((dir) => runnable(join(dir, name)))) {
630
+ continue;
631
+ }
632
+ const dir = commandFolders(home, system).find((folder) => runnable(join(folder, name)));
633
+ if (dir && !found.includes(dir)) {
634
+ found.push(dir);
635
+ }
636
+ }
637
+ return found;
638
+ }
639
+
545
640
  /** The environment a service gets: your PATH (for Ollama, Claude and Codex) and your home folder. */
546
641
  function serviceEnv(paths) {
547
- return { PATH: cleanPath(), HOME: paths.user };
642
+ return {
643
+ PATH: [cleanPath(), ...agentFolders(process.env, paths.user)].filter(Boolean).join(delimiter),
644
+ HOME: paths.user,
645
+ };
548
646
  }
549
647
 
550
648
  /** The LaunchAgent: `wizards-bot <args>`, started at login and again when it fails. */
551
- export function agentText(paths, label, args, log) {
649
+ export function agentText(paths, label, args, log, program = paths.command) {
552
650
  const env = serviceEnv(paths);
553
651
  return `<?xml version="1.0" encoding="UTF-8"?>
554
652
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -558,7 +656,7 @@ export function agentText(paths, label, args, log) {
558
656
  <string>${xml(label)}</string>
559
657
  <key>ProgramArguments</key>
560
658
  <array>
561
- ${[paths.command, ...args].map((arg) => ` <string>${xml(arg)}</string>\n`).join("")} </array>
659
+ ${[program, ...args].map((arg) => ` <string>${xml(arg)}</string>\n`).join("")} </array>
562
660
  <key>EnvironmentVariables</key>
563
661
  <dict>
564
662
  ${Object.entries(env)
@@ -581,7 +679,7 @@ ${Object.entries(env)
581
679
  }
582
680
 
583
681
  /** The systemd user service: `wizards-bot <args>`, started at login and again when it fails. */
584
- export function unitText(paths, description, args) {
682
+ export function unitText(paths, description, args, program = paths.command) {
585
683
  const quoted = (text) => `"${String(text).replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
586
684
  const env = serviceEnv(paths);
587
685
  return [
@@ -590,7 +688,7 @@ export function unitText(paths, description, args) {
590
688
  `Documentation=https://github.com/${REPO}`,
591
689
  "",
592
690
  "[Service]",
593
- `ExecStart=${[paths.command, ...args].map(quoted).join(" ")}`,
691
+ `ExecStart=${[program, ...args].map(quoted).join(" ")}`,
594
692
  ...Object.entries(env).map(([key, value]) => `Environment=${quoted(`${key}=${value}`)}`),
595
693
  "Restart=on-failure",
596
694
  "RestartSec=5",
@@ -611,7 +709,7 @@ function systemdHere() {
611
709
  return Boolean(onPath("systemctl")) && systemctl(["show-environment"]).status === 0;
612
710
  }
613
711
 
614
- /** The two services: the home, and the link to a home elsewhere. */
712
+ /** The three services: the home, the link to a home elsewhere, and the tunnel. */
615
713
  function services(paths) {
616
714
  const where = paths.folder ? ` in ${tilde(paths.folder)}` : "";
617
715
  return {
@@ -633,9 +731,25 @@ function services(paths) {
633
731
  log: paths.linkLog,
634
732
  description: `wizards.bot, this computer’s models for your home${where}`,
635
733
  },
734
+ tunnel: {
735
+ label: paths.tunnelLabel,
736
+ unit: paths.tunnelUnitName,
737
+ agent: paths.tunnelAgent,
738
+ unitFile: paths.tunnelUnit,
739
+ // The Node the home runs with, set when the tunnel opens (tunnelService).
740
+ program: null,
741
+ args: [join(paths.tunnel, "run.mjs"), paths.tunnel],
742
+ log: paths.tunnelLog,
743
+ description: `wizards.bot, the tunnel of your home${where}`,
744
+ },
636
745
  };
637
746
  }
638
747
 
748
+ /** The tunnel's service, run by the home's Node. */
749
+ function tunnelService(paths, settings) {
750
+ return { ...services(paths).tunnel, program: settings.node };
751
+ }
752
+
639
753
  const unxml = (text) =>
640
754
  text.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
641
755
 
@@ -656,7 +770,7 @@ export function folderInstalls(paths) {
656
770
  if (process.platform === "darwin") {
657
771
  for (const name of listDir(paths.launchAgents)) {
658
772
  const id = /^com\.engenty\.wizards\.bot\.(.+)\.plist$/.exec(name)?.[1];
659
- if (!id || id === "link" || id.endsWith(".link")) {
773
+ if (!id || ["link", "tunnel"].includes(id) || /\.(link|tunnel)$/.test(id)) {
660
774
  continue;
661
775
  }
662
776
  const text = readFileSync(join(paths.launchAgents, name), "utf8");
@@ -669,7 +783,7 @@ export function folderInstalls(paths) {
669
783
  }
670
784
  } else {
671
785
  for (const name of listDir(paths.units)) {
672
- if (!/^wizards-bot-.+\.service$/.test(name) || name.endsWith("-link.service")) {
786
+ if (!/^wizards-bot-.+\.service$/.test(name) || /-(link|tunnel)\.service$/.test(name)) {
673
787
  continue;
674
788
  }
675
789
  const text = readFileSync(join(paths.units, name), "utf8");
@@ -723,7 +837,10 @@ async function startService(paths, service) {
723
837
  mkdirSync(paths.logs, { recursive: true });
724
838
  if (process.platform === "darwin") {
725
839
  mkdirSync(dirname(service.agent), { recursive: true });
726
- writeFileSync(service.agent, agentText(paths, service.label, service.args, service.log));
840
+ writeFileSync(
841
+ service.agent,
842
+ agentText(paths, service.label, service.args, service.log, service.program || undefined),
843
+ );
727
844
  await bootout(service);
728
845
  // launchd may still be letting the old one go: it refuses with error 5 meanwhile.
729
846
  let result = null;
@@ -745,7 +862,10 @@ async function startService(paths, service) {
745
862
  return false;
746
863
  }
747
864
  mkdirSync(dirname(service.unitFile), { recursive: true });
748
- writeFileSync(service.unitFile, unitText(paths, service.description, service.args));
865
+ writeFileSync(
866
+ service.unitFile,
867
+ unitText(paths, service.description, service.args, service.program || undefined),
868
+ );
749
869
  systemctl(["daemon-reload"]);
750
870
  const result = systemctl(["enable", service.unit]);
751
871
  const restart = systemctl(["restart", service.unit]);
@@ -1051,7 +1171,10 @@ async function put(paths, options, from) {
1051
1171
  };
1052
1172
  saveSettings(paths, settings);
1053
1173
  writeCommand(paths, settings);
1054
- return { settings, running: await startHome(paths, settings) };
1174
+ const running = await startHome(paths, settings);
1175
+ // The tunnel keeps its name, with the home's port and this run.mjs.
1176
+ await refreshRelay(paths, settings);
1177
+ return { settings, running };
1055
1178
  }
1056
1179
 
1057
1180
  /** Starts the home's service again and waits for its answer; false where nothing can run it. */
@@ -1195,7 +1318,7 @@ async function link(paths, settings, options) {
1195
1318
 
1196
1319
  /** One home's lines: its version, whether it runs, its address, its data, its tunnel. */
1197
1320
  async function describe(paths, settings, version) {
1198
- const { home, link: linked } = services(paths);
1321
+ const { home, link: linked, tunnel: tunneled } = services(paths);
1199
1322
  const answers = await healthy(settings.port);
1200
1323
  const how = serviceThere(home);
1201
1324
  console.log(`wizards.bot ${version} ${dim(tilde(paths.folder || join(paths.bot, version)))}`);
@@ -1203,7 +1326,11 @@ async function describe(paths, settings, version) {
1203
1326
  ` ${answers ? green("running") : red("not running")} http://localhost:${settings.port}${how ? dim(` (${how})`) : ""}`,
1204
1327
  );
1205
1328
  if (settings.url) {
1206
- console.log(` internet ${settings.url} ${dim("(Tailscale Funnel)")}`);
1329
+ const how =
1330
+ settings.tunnel?.by === "relay"
1331
+ ? `${dim("(our relay, ")}${serviceRuns(tunneled) ? green("running") : red("not running")}${dim(")")}`
1332
+ : dim("(Tailscale Funnel)");
1333
+ console.log(` internet ${settings.url} ${how}`);
1207
1334
  }
1208
1335
  console.log(` data ${tilde(settings.data)}`);
1209
1336
  console.log(` command ${tilde(paths.command)}`);
@@ -1260,8 +1387,8 @@ async function status(paths, _options, env) {
1260
1387
  /** `stop`: the home and its link stop until you log in again or start them. Nothing is removed. */
1261
1388
  async function stop(paths) {
1262
1389
  installed(paths);
1263
- const { home, link: linked } = services(paths);
1264
- for (const service of [linked, home]) {
1390
+ const { home, link: linked, tunnel: tunneled } = services(paths);
1391
+ for (const service of [tunneled, linked, home]) {
1265
1392
  const how = serviceThere(service);
1266
1393
  if (how) {
1267
1394
  await stopService(service);
@@ -1282,6 +1409,9 @@ async function start(paths) {
1282
1409
  if (serviceThere(linked)) {
1283
1410
  await startService(paths, linked);
1284
1411
  }
1412
+ if (settings.tunnel?.by === "relay" && serviceThere(services(paths).tunnel)) {
1413
+ await startService(paths, tunnelService(paths, settings));
1414
+ }
1285
1415
  }
1286
1416
 
1287
1417
  async function update(paths, options) {
@@ -1332,12 +1462,13 @@ function dropEmpty(dir) {
1332
1462
  */
1333
1463
  async function uninstall(paths, options) {
1334
1464
  const settings = readJson(paths.settings) || {};
1335
- const { home, link: linked } = services(paths);
1465
+ const { home, link: linked, tunnel: tunneled } = services(paths);
1336
1466
  const there =
1337
1467
  existsSync(paths.bot) ||
1338
1468
  existsSync(paths.command) ||
1339
1469
  serviceThere(home) ||
1340
- serviceThere(linked);
1470
+ serviceThere(linked) ||
1471
+ serviceThere(tunneled);
1341
1472
  const data = settings.data || paths.data;
1342
1473
  const where = paths.folder ? `${tilde(paths.folder)}` : "this computer";
1343
1474
  if (!there && !options.purge) {
@@ -1361,10 +1492,10 @@ async function uninstall(paths, options) {
1361
1492
  }
1362
1493
  }
1363
1494
  if (settings.tunnel) {
1364
- closeTunnel(settings);
1495
+ await closeTunnel(paths, settings);
1365
1496
  step("Closed the tunnel", settings.url);
1366
1497
  }
1367
- for (const service of [linked, home]) {
1498
+ for (const service of [tunneled, linked, home]) {
1368
1499
  const how = serviceThere(service);
1369
1500
  if (how) {
1370
1501
  await removeService(service);
@@ -1385,7 +1516,7 @@ async function uninstall(paths, options) {
1385
1516
  }
1386
1517
  rmSync(paths.command, { force: true });
1387
1518
  rmSync(paths.bot, { recursive: true, force: true });
1388
- for (const log of [paths.log, paths.linkLog, paths.installLog]) {
1519
+ for (const log of [paths.log, paths.linkLog, paths.tunnelLog, paths.installLog]) {
1389
1520
  rmSync(log, { force: true });
1390
1521
  }
1391
1522
  step("Removed the program", tilde(paths.bot));
@@ -1413,6 +1544,8 @@ async function uninstall(paths, options) {
1413
1544
  }
1414
1545
  if (purge) {
1415
1546
  rmSync(data, { recursive: true, force: true });
1547
+ // The tunnel's own key goes with the data: its name is given up.
1548
+ rmSync(paths.tunnel, { recursive: true, force: true });
1416
1549
  }
1417
1550
  if (paths.folder) {
1418
1551
  dropEmpty(paths.folder);
@@ -1484,10 +1617,10 @@ const funnelArgs = (https, port) => [
1484
1617
  `http://127.0.0.1:${port}`,
1485
1618
  ];
1486
1619
 
1487
- function closeTunnel(settings) {
1620
+ /** Takes a home's Funnel off, with the command that put it on and `off` after it. */
1621
+ function closeFunnel(settings) {
1488
1622
  const command = tailscale();
1489
1623
  if (command && settings.tunnel?.https) {
1490
- // Tailscale takes it off with the command that put it on, and `off` after it.
1491
1624
  spawnSync(command, [...funnelArgs(settings.tunnel.https, settings.port), "off"], {
1492
1625
  encoding: "utf8",
1493
1626
  timeout: 15_000,
@@ -1495,13 +1628,208 @@ function closeTunnel(settings) {
1495
1628
  }
1496
1629
  }
1497
1630
 
1631
+ /** Where tunnels get their names and certificates: WIZARDS_TUNNEL_URL, or wizards.host. */
1632
+ export function tunnelUrl(env = process.env) {
1633
+ return ((env.WIZARDS_TUNNEL_URL || "").trim() || TUNNEL_URL).replace(/\/+$/, "");
1634
+ }
1635
+
1636
+ /** Whether a word can go before a team's name: `test01` in test01.ada.wizards.host. */
1637
+ export function labelOk(label) {
1638
+ return /^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$/.test(label);
1639
+ }
1640
+
1641
+ /**
1642
+ * Closes a home's tunnel, whichever it is: Funnel goes off; the relay's service goes, its key
1643
+ * is given back (best effort) and the tunnel's files go, all but `claim.pem`: with it, the next
1644
+ * `tunnel` gets the same name again.
1645
+ */
1646
+ async function closeTunnel(paths, settings) {
1647
+ if (settings.tunnel?.by === "relay") {
1648
+ await removeService(services(paths).tunnel);
1649
+ const saved = readJson(join(paths.tunnel, "tunnel.json"));
1650
+ if (saved?.key && saved.api) {
1651
+ try {
1652
+ await call(saved.api, "/v1/tunnels/key", { method: "DELETE", key: saved.key });
1653
+ } catch (error) {
1654
+ note(`wizards.host didn’t take the tunnel’s key back: ${error.message}`);
1655
+ }
1656
+ }
1657
+ for (const name of listDir(paths.tunnel)) {
1658
+ if (name !== CLAIM_FILE) {
1659
+ rmSync(join(paths.tunnel, name), { recursive: true, force: true });
1660
+ }
1661
+ }
1662
+ dropEmpty(paths.tunnel);
1663
+ return;
1664
+ }
1665
+ closeFunnel(settings);
1666
+ }
1667
+
1668
+ /** The tunnel's own key, in the home's tunnel folder: its name comes from it. */
1669
+ export const CLAIM_FILE = "claim.pem";
1670
+
1671
+ /** Refuses while the home doesn't run, or while no device is paired with it. */
1672
+ async function requirePaired(paths, settings) {
1673
+ if (!(await healthy(settings.port))) {
1674
+ throw new Refusal(`The home doesn’t run. Start it first: ${hint(paths, "start")}`);
1675
+ }
1676
+ const said = spawnSync(paths.command, ["status"], { encoding: "utf8", timeout: 60_000 });
1677
+ const devices = devicesIn(said.stdout || "");
1678
+ if (!devices) {
1679
+ throw new Refusal(
1680
+ devices === 0
1681
+ ? `No device is paired with this home yet, so it stays off the internet. Pair your phone on this network first (${hint(paths, "setup")}), then run this again.`
1682
+ : `wizards-bot status didn’t say whether a device is paired, so the home stays off the internet.`,
1683
+ );
1684
+ }
1685
+ }
1686
+
1687
+ /** frp's name for this computer: `darwin_arm64`, `linux_amd64` and so on. */
1688
+ export function frpMachine(platform = process.platform, arch = machine().split("-")[1]) {
1689
+ return `${platform === "win32" ? "windows" : platform}_${arch === "x64" ? "amd64" : arch}`;
1690
+ }
1691
+
1692
+ /**
1693
+ * frpc, in ~/.engenty/wizards/tools/frp/<version>, downloaded from frp's release and checked
1694
+ * against the checksum in FRP_SHA256. WIZARDS_BOT_FRPC names one to use instead.
1695
+ */
1696
+ function findFrpc(paths, env = process.env) {
1697
+ const given = (env.WIZARDS_BOT_FRPC || "").trim();
1698
+ if (given) {
1699
+ return resolve(given);
1700
+ }
1701
+ const dir = join(paths.tools, "frp", FRP_VERSION);
1702
+ const frpc = join(dir, "frpc");
1703
+ if (existsSync(frpc)) {
1704
+ return frpc;
1705
+ }
1706
+ const name = `frp_${FRP_VERSION}_${frpMachine()}`;
1707
+ const checksum = FRP_SHA256[frpMachine()];
1708
+ if (!checksum) {
1709
+ throw new Refusal(`frp ${FRP_VERSION} has no frpc for ${frpMachine()} here.`);
1710
+ }
1711
+ note(`Downloading frpc ${FRP_VERSION} for the tunnel`);
1712
+ mkdirSync(join(paths.tools, "frp"), { recursive: true });
1713
+ const tmp = mkdtempSync(join(paths.tools, "frp", ".frp."));
1714
+ try {
1715
+ const tarball = join(tmp, "frp.tar.gz");
1716
+ fetchFile(
1717
+ paths,
1718
+ `https://github.com/fatedier/frp/releases/download/v${FRP_VERSION}/${name}.tar.gz`,
1719
+ tarball,
1720
+ checksum,
1721
+ );
1722
+ logged(paths, "tar", ["-xzf", tarball, "-C", tmp, `${name}/frpc`]);
1723
+ mkdirSync(dir, { recursive: true });
1724
+ renameSync(join(tmp, name, "frpc"), frpc);
1725
+ chmodSync(frpc, 0o755);
1726
+ } finally {
1727
+ rmSync(tmp, { recursive: true, force: true });
1728
+ }
1729
+ step(`frpc ${FRP_VERSION}`, `${tilde(frpc)}, checksum matches`);
1730
+ return frpc;
1731
+ }
1732
+
1733
+ /**
1734
+ * Signs in for a name: the account shows a code, you confirm it there, and this gets the
1735
+ * name's key. `label` asks for <label>.<team>.wizards.host.
1736
+ */
1737
+ export async function signIn(api, { label, open = true, every } = {}) {
1738
+ const { data: started } = await call(api, "/v1/tunnels/start", {
1739
+ method: "POST",
1740
+ body: { ...(label ? { label } : {}), computer: hostname().replace(/\.local$/, "") },
1741
+ });
1742
+ console.log(
1743
+ `\nTo give this home its name, open ${cyan(started.url)}\nsign in to your wizards account and confirm the code ${bold(started.userCode)}.\n`,
1744
+ );
1745
+ if (open) {
1746
+ openBrowser(started.url);
1747
+ }
1748
+ const wait = every ?? (started.interval || 3) * 1000;
1749
+ const until = Date.now() + (started.expiresIn || 900) * 1000;
1750
+ while (Date.now() < until) {
1751
+ let answer;
1752
+ try {
1753
+ answer = await call(api, "/v1/tunnels/redeem", {
1754
+ method: "POST",
1755
+ body: { deviceCode: started.deviceCode },
1756
+ });
1757
+ } catch (error) {
1758
+ if (error instanceof AccountError) {
1759
+ throw new Refusal(
1760
+ error.code === "denied"
1761
+ ? "The name wasn’t given: it was declined on the account page."
1762
+ : error.code === "expired"
1763
+ ? "The code ran out before it was confirmed. Run this again for a new one."
1764
+ : error.message,
1765
+ );
1766
+ }
1767
+ throw error;
1768
+ }
1769
+ if (answer.status === 200 && answer.data.key) {
1770
+ return answer.data;
1771
+ }
1772
+ await pause(wait);
1773
+ }
1774
+ throw new Refusal("The code ran out before it was confirmed. Run this again for a new one.");
1775
+ }
1776
+
1777
+ /** A port for frpc's admin API on 127.0.0.1, free now. */
1778
+ async function adminPort() {
1779
+ for (let tries = 0; tries < 50; tries++) {
1780
+ const port = 20000 + (randomBytes(2).readUInt16BE(0) % 40000);
1781
+ if (await portFree(port)) {
1782
+ return port;
1783
+ }
1784
+ }
1785
+ throw new Refusal("No free port was found for frpc.");
1786
+ }
1787
+
1788
+ /** Writes the tunnel's files for a home: tunnel.json, frpc.toml and run.mjs. */
1789
+ export function writeTunnel(dir, tunnel) {
1790
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
1791
+ writeFileAtomic(join(dir, "tunnel.json"), `${JSON.stringify(tunnel, null, 2)}\n`, true);
1792
+ writeFileAtomic(join(dir, "frpc.toml"), frpcConfig({ ...tunnel, dir }), true);
1793
+ copyFileSync(fileURLToPath(new URL("./bot-tunnel.mjs", import.meta.url)), join(dir, "run.mjs"));
1794
+ }
1795
+
1796
+ /** Gets the certificate for the tunnel's name into its folder. */
1797
+ async function certificate(dir, tunnel) {
1798
+ const keyFile = join(dir, "key.pem");
1799
+ if (!existsSync(keyFile)) {
1800
+ writeFileAtomic(keyFile, makeKey(), true);
1801
+ }
1802
+ note(`Getting a certificate for ${tunnel.name} (Let’s Encrypt, up to a minute)`);
1803
+ try {
1804
+ const cert = await orderCertificate(
1805
+ tunnel.api,
1806
+ tunnel.key,
1807
+ csrFor(tunnel.name, readFileSync(keyFile, "utf8")),
1808
+ );
1809
+ writeFileAtomic(join(dir, "cert.pem"), cert);
1810
+ } catch (error) {
1811
+ if (error instanceof AccountError) {
1812
+ throw new Refusal(`No certificate for ${tunnel.name}: ${error.message}`);
1813
+ }
1814
+ throw error;
1815
+ }
1816
+ step("Certificate", `${tunnel.name}, the key stays on this computer`);
1817
+ }
1818
+
1498
1819
  /**
1499
- * `tunnel`: puts a home on the internet with Tailscale Funnel, at https://<computer>.<tailnet>.ts.net.
1500
- * TLS ends on this computer, no port opens on the router, and it refuses while no device is
1501
- * paired: whoever reaches the address then still needs a pairing code or a device's token.
1502
- * `tunnel --off` closes it.
1820
+ * `tunnel`: puts a home on the internet at https://<name>.wizards.host, through our relay. The
1821
+ * name is the tunnel key's own, with no account; `--account` takes your team's name instead,
1822
+ * after you sign in. frpc dials out (no port opens on the router), and TLS ends on this computer:
1823
+ * the relay passes it on by name, unread. It refuses while no device is paired: whoever reaches
1824
+ * the address then still needs a pairing code or a device's token. `--tailscale` uses Tailscale
1825
+ * Funnel instead, and `tunnel --off` closes either.
1503
1826
  */
1504
- async function tunnel(paths, options) {
1827
+ async function tunnel(paths, options, env = process.env) {
1828
+ if (options.name && !options.account) {
1829
+ throw new Refusal(
1830
+ `--name picks a word before your team’s name, so it goes with --account: ${cyan("wizards bot tunnel --account --name test01")}`,
1831
+ );
1832
+ }
1505
1833
  windowsRefusal();
1506
1834
  const settings = installed(paths);
1507
1835
  if (options.off) {
@@ -1509,7 +1837,7 @@ async function tunnel(paths, options) {
1509
1837
  console.log("This home isn’t on the internet: there’s no tunnel to close.");
1510
1838
  return;
1511
1839
  }
1512
- closeTunnel(settings);
1840
+ await closeTunnel(paths, settings);
1513
1841
  const { url: _url, tunnel: _tunnel, ...rest } = settings;
1514
1842
  saveSettings(paths, rest);
1515
1843
  writeCommand(paths, rest);
@@ -1520,18 +1848,104 @@ async function tunnel(paths, options) {
1520
1848
  );
1521
1849
  return;
1522
1850
  }
1523
- if (!(await healthy(settings.port))) {
1524
- throw new Refusal(`The home doesn’t run. Start it first: ${hint(paths, "start")}`);
1851
+ if (options.name && !labelOk(options.name)) {
1852
+ throw new Refusal(
1853
+ `--name takes lower-case letters, digits and dashes, up to 32: e.g. ${cyan("--name test01")}`,
1854
+ );
1525
1855
  }
1526
- const said = spawnSync(paths.command, ["status"], { encoding: "utf8", timeout: 60_000 });
1527
- const devices = devicesIn(said.stdout || "");
1528
- if (!devices) {
1856
+ const by = options.tailscale ? "tailscale-funnel" : "relay";
1857
+ if (settings.tunnel && settings.tunnel.by !== by) {
1529
1858
  throw new Refusal(
1530
- devices === 0
1531
- ? `No device is paired with this home yet, so it stays off the internet. Pair your phone on this network first (${hint(paths, "setup")}), then run this again.`
1532
- : `wizards-bot status didn’t say whether a device is paired, so the home stays off the internet.`,
1859
+ `This home is on the internet already, at ${settings.url}. Close that first: ${hint(paths, "tunnel --off")}`,
1533
1860
  );
1534
1861
  }
1862
+ await requirePaired(paths, settings);
1863
+ const next = options.tailscale
1864
+ ? await openFunnel(settings)
1865
+ : await openRelay(paths, settings, options, env);
1866
+ saveSettings(paths, next);
1867
+ // The home says this address in its pairing codes from now on.
1868
+ writeCommand(paths, next);
1869
+ await startHome(paths, next);
1870
+ const url = next.url;
1871
+ let answered = reachable(url);
1872
+ for (let tries = 0; tries < 12 && !answered; tries++) {
1873
+ await pause(5000);
1874
+ answered = reachable(url);
1875
+ }
1876
+ step(
1877
+ "On the internet",
1878
+ answered ? url : `${url} (it doesn’t answer yet: a new name takes a minute or two)`,
1879
+ );
1880
+ console.log(
1881
+ `\nOnly your paired devices get in; a new one needs a code from ${hint(paths, "setup")}, which now shows this address. A phone paired on this network still uses the local address: pair it again with that code to reach the home away from home. ${hint(paths, "tunnel --off")} closes it.`,
1882
+ );
1883
+ }
1884
+
1885
+ /**
1886
+ * A name for the home's tunnel. Without --account it is the tunnel key's own, at wizards.host:
1887
+ * no sign-in. With --account the name is your team's, after you sign in to your wizards account.
1888
+ */
1889
+ export async function nameTunnel(dir, options, env = process.env) {
1890
+ const api = tunnelUrl(env);
1891
+ const computer = hostname().replace(/\.local$/, "");
1892
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
1893
+ let given;
1894
+ try {
1895
+ given = options.account
1896
+ ? await signIn(api, { label: options.name, open: options.open })
1897
+ : await claim(api, join(dir, CLAIM_FILE), computer);
1898
+ } catch (error) {
1899
+ if (error instanceof AccountError) {
1900
+ throw new Refusal(`No name at wizards.host: ${error.message}`);
1901
+ }
1902
+ throw error;
1903
+ }
1904
+ return {
1905
+ api,
1906
+ name: given.name,
1907
+ key: given.key,
1908
+ server: given.server,
1909
+ serverPort: given.serverPort,
1910
+ };
1911
+ }
1912
+
1913
+ /** The relay: a name at wizards.host, a certificate for it, frpc as a service. */
1914
+ async function openRelay(paths, settings, options, env) {
1915
+ const dir = paths.tunnel;
1916
+ const saved = readJson(join(dir, "tunnel.json"));
1917
+ const wanted = options.name;
1918
+ if (saved?.name && wanted && !saved.name.startsWith(`${wanted}.`)) {
1919
+ throw new Refusal(
1920
+ `This home’s tunnel is ${saved.name}. To take another name, close it first: ${hint(paths, "tunnel --off")}`,
1921
+ );
1922
+ }
1923
+ let tunnel = saved?.key ? saved : null;
1924
+ if (!tunnel) {
1925
+ tunnel = await nameTunnel(dir, options, env);
1926
+ step("Name", tunnel.name);
1927
+ }
1928
+ tunnel = {
1929
+ ...tunnel,
1930
+ frpc: findFrpc(paths, env),
1931
+ port: settings.port,
1932
+ adminPort: tunnel.adminPort || (await adminPort()),
1933
+ adminPassword: tunnel.adminPassword || randomBytes(18).toString("base64url"),
1934
+ };
1935
+ writeTunnel(dir, tunnel);
1936
+ await certificate(dir, tunnel);
1937
+ const service = tunnelService(paths, settings);
1938
+ if (!(await startService(paths, service))) {
1939
+ throw new Refusal(
1940
+ `systemd --user isn’t available here, so the tunnel can’t run as a service. Run it yourself: ${cyan(`${settings.node} ${join(dir, "run.mjs")} ${dir}`)}`,
1941
+ );
1942
+ }
1943
+ step("Tunnel", serviceThere(service));
1944
+ return { ...settings, url: `https://${tunnel.name}`, tunnel: { by: "relay", name: tunnel.name } };
1945
+ }
1946
+
1947
+ /** Tailscale Funnel, at https://<computer>.<tailnet>.ts.net. */
1948
+ async function openFunnel(settings) {
1535
1949
  const command = tailscale();
1536
1950
  if (!command) {
1537
1951
  throw new Refusal(
@@ -1564,23 +1978,17 @@ async function tunnel(paths, options) {
1564
1978
  `tailscale funnel didn’t open ${url}. ${cyan("tailscale funnel status")} says what it serves.`,
1565
1979
  );
1566
1980
  }
1567
- const next = { ...settings, url, tunnel: { by: "tailscale-funnel", https } };
1568
- saveSettings(paths, next);
1569
- // The home says this address in its pairing codes from now on.
1570
- writeCommand(paths, next);
1571
- await startHome(paths, next);
1572
- let answered = reachable(url);
1573
- for (let tries = 0; tries < 12 && !answered; tries++) {
1574
- await pause(5000);
1575
- answered = reachable(url);
1981
+ return { ...settings, url, tunnel: { by: "tailscale-funnel", https } };
1982
+ }
1983
+
1984
+ /** After an update: the relay's files with the home's port and this run.mjs, and frpc again. */
1985
+ async function refreshRelay(paths, settings) {
1986
+ const saved = readJson(join(paths.tunnel, "tunnel.json"));
1987
+ if (settings.tunnel?.by !== "relay" || !saved) {
1988
+ return;
1576
1989
  }
1577
- step(
1578
- "On the internet",
1579
- answered ? url : `${url} (it doesn’t answer yet: a new name takes a minute or two)`,
1580
- );
1581
- console.log(
1582
- `\nOnly your paired devices get in; a new one needs a code from ${hint(paths, "setup")}, which now shows this address. A phone paired on this network still uses the local address: pair it again with that code to reach the home away from home. ${hint(paths, "tunnel --off")} closes it.`,
1583
- );
1990
+ writeTunnel(paths.tunnel, { ...saved, port: settings.port });
1991
+ await startService(paths, tunnelService(paths, settings));
1584
1992
  }
1585
1993
 
1586
1994
  // --- the command line ------------------------------------------------------------------------
@@ -1598,8 +2006,11 @@ Commands
1598
2006
  and a line for each home in a folder
1599
2007
  ${cyan("wizards bot stop")} stop the home until you log in again or start it
1600
2008
  ${cyan("wizards bot start")} start it again
1601
- ${cyan("wizards bot tunnel")} put the home on the internet with Tailscale Funnel, once a
1602
- device is paired (--off closes it)
2009
+ ${cyan("wizards bot tunnel")} put the home on the internet at https://<name>.wizards.host, once
2010
+ a device is paired; the name is its own, no account needed
2011
+ (--account for your team’s name after you sign in, with --name test01
2012
+ for test01.<team>.wizards.host; --tailscale for Tailscale Funnel
2013
+ instead; --off closes it)
1603
2014
  ${cyan("wizards bot update")} install the newest version and restart the home, your data is kept
1604
2015
  ${cyan("wizards bot uninstall")} take the home off this computer, your data in ~/.wizards-bot is kept
1605
2016
  (--purge deletes it too, after asking)
@@ -1616,6 +2027,8 @@ Options
1616
2027
  Mac app’s)
1617
2028
  --no-open don’t open the browser
1618
2029
  --off with tunnel: close it
2030
+ --name <word> with tunnel: the word before your name, for a second home
2031
+ --tailscale with tunnel: Tailscale Funnel instead of wizards.host
1619
2032
  --yes, -y don’t ask
1620
2033
 
1621
2034
  The program goes into ~/.engenty/wizards/bot (ENGENTY_HOME moves it), the command
@@ -1632,6 +2045,9 @@ export function parse(argv) {
1632
2045
  yes: false,
1633
2046
  purge: false,
1634
2047
  off: false,
2048
+ tailscale: false,
2049
+ account: false,
2050
+ name: null,
1635
2051
  link: null,
1636
2052
  version: null,
1637
2053
  port: null,
@@ -1649,6 +2065,15 @@ export function parse(argv) {
1649
2065
  options.purge = true;
1650
2066
  } else if (arg === "--off") {
1651
2067
  options.off = true;
2068
+ } else if (arg === "--tailscale") {
2069
+ options.tailscale = true;
2070
+ } else if (arg === "--account") {
2071
+ options.account = true;
2072
+ } else if (arg === "--name") {
2073
+ options.name = (argv[++i] || "").toLowerCase();
2074
+ if (!options.name) {
2075
+ throw new Refusal("--name needs a word, e.g. --name test01");
2076
+ }
1652
2077
  } else if (arg === "--link") {
1653
2078
  options.link = [argv[i + 1], argv[i + 2]];
1654
2079
  i += 2;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wizards",
3
- "version": "0.20.5",
3
+ "version": "0.21.0",
4
4
  "description": "Make a wish. Get your wizard. It guides you step by step. Let AI do the work. Runs on your machine, on the AI subscription you already have.",
5
5
  "license": "FSL-1.1-MIT AND CC-BY-4.0",
6
6
  "homepage": "https://engenty.ai",