@engenty/wizards-runtime 0.20.4 → 0.20.6

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.
Files changed (87) hide show
  1. package/README.md +1 -1
  2. package/apps/runtime/dist/agents/subscription.js +19 -11
  3. package/apps/runtime/dist/cli/ollama.js +7 -76
  4. package/apps/runtime/dist/cli/setup.js +5 -4
  5. package/apps/runtime/dist/decision-model.js +1 -4
  6. package/apps/runtime/dist/docs/dev/licensing.md +7 -2
  7. package/apps/runtime/dist/docs/user-guide/command-line.md +2 -2
  8. package/apps/runtime/dist/engine/device.js +3 -2
  9. package/apps/runtime/dist/harness/antigravity.js +11 -7
  10. package/apps/runtime/dist/harness/apple.js +4 -3
  11. package/apps/runtime/dist/harness/clients.js +108 -0
  12. package/apps/runtime/dist/harness/index.js +29 -30
  13. package/apps/runtime/dist/harness/model.js +32 -270
  14. package/apps/runtime/dist/harness/prompt.js +6 -120
  15. package/apps/runtime/dist/harness/types.js +3 -2
  16. package/apps/runtime/dist/local-models.js +17 -37
  17. package/apps/runtime/dist/models.js +8 -5
  18. package/apps/runtime/dist/motion-graphics/step.js +2 -2
  19. package/apps/runtime/dist/routes/studio.js +1 -1
  20. package/apps/runtime/dist/services/work-ai.js +2 -2
  21. package/apps/web/dist/assets/{AboutDialog-CQvfeGqA.js → AboutDialog-BRUwrfQH.js} +1 -1
  22. package/apps/web/dist/assets/{CapabilitiesPage-DJRpCw2_.js → CapabilitiesPage-C30knXsS.js} +1 -1
  23. package/apps/web/dist/assets/{ChangelogDialog-F7gj0WCW.js → ChangelogDialog-BkZQOAdl.js} +1 -1
  24. package/apps/web/dist/assets/{ConnectorsSection-dXmTJOrm.js → ConnectorsSection-CmXQD7zu.js} +1 -1
  25. package/apps/web/dist/assets/{EditorPage-DNox0Po-.js → EditorPage-LEbyNWmG.js} +1 -1
  26. package/apps/web/dist/assets/{NewWizardChannels-BugegWm1.js → NewWizardChannels-CSn-9zHr.js} +1 -1
  27. package/apps/web/dist/assets/{NewWizardPage-Df359wgE.js → NewWizardPage-B4wPfClS.js} +1 -1
  28. package/apps/web/dist/assets/{ProtocolSection-B1tcJgJl.js → ProtocolSection-s4mEL_pu.js} +1 -1
  29. package/apps/web/dist/assets/{ReadOnly-DxC8kALr.js → ReadOnly-CO3ndR23.js} +1 -1
  30. package/apps/web/dist/assets/{Results-D6ecFiSB.js → Results-CC1-mElv.js} +1 -1
  31. package/apps/web/dist/assets/{RunDrawer-oPFk8yHt.js → RunDrawer-DkmSXhad.js} +1 -1
  32. package/apps/web/dist/assets/{SettingsPage-DueaPjW3.js → SettingsPage-DKs_fkNL.js} +2 -2
  33. package/apps/web/dist/assets/{SetupPage-k61GmbIs.js → SetupPage-RvmKCzF2.js} +1 -1
  34. package/apps/web/dist/assets/{SpacePage-z66Mza2y.js → SpacePage-aZqYFttF.js} +1 -1
  35. package/apps/web/dist/assets/{StudioHome-q1f_vqAI.js → StudioHome-Doua9Lyl.js} +1 -1
  36. package/apps/web/dist/assets/{TableEditor-Dfu5Qa-O.js → TableEditor-Dbq3HZZS.js} +1 -1
  37. package/apps/web/dist/assets/{UpdateCheck-y1StF2CW.js → UpdateCheck-B7etUbUf.js} +2 -2
  38. package/apps/web/dist/assets/changelog-BW79cVbx.js +1 -0
  39. package/apps/web/dist/assets/{host-Bh_WJbQv.js → host-BXSxBoOH.js} +3 -3
  40. package/apps/web/dist/assets/{index-CgSUfzBq.js → index-kDKA6ddy.js} +3 -3
  41. package/apps/web/dist/assets/{oss-credits-C4SGbRkz.js → oss-credits-B3PXhamW.js} +1 -1
  42. package/apps/web/dist/index.html +4 -4
  43. package/bin/bot-tunnel.mjs +375 -0
  44. package/bin/bot.mjs +1133 -125
  45. package/node_modules/@engenty/local-models/dist/clients/chat.d.ts +89 -0
  46. package/node_modules/@engenty/local-models/dist/clients/chat.js +22 -0
  47. package/node_modules/@engenty/local-models/dist/clients/claude.d.ts +32 -0
  48. package/node_modules/@engenty/local-models/dist/clients/claude.js +238 -0
  49. package/node_modules/@engenty/local-models/dist/clients/client.d.ts +29 -0
  50. package/node_modules/@engenty/local-models/dist/clients/client.js +2 -0
  51. package/node_modules/@engenty/local-models/dist/clients/codex.d.ts +35 -0
  52. package/node_modules/@engenty/local-models/dist/clients/codex.js +253 -0
  53. package/node_modules/@engenty/local-models/dist/clients/cursor.d.ts +33 -0
  54. package/node_modules/@engenty/local-models/dist/clients/cursor.js +180 -0
  55. package/node_modules/@engenty/local-models/dist/clients/detect.d.ts +18 -0
  56. package/node_modules/@engenty/local-models/dist/clients/detect.js +34 -0
  57. package/node_modules/@engenty/local-models/dist/clients/env.d.ts +66 -0
  58. package/{apps/runtime/dist/harness → node_modules/@engenty/local-models/dist/clients}/env.js +62 -31
  59. package/node_modules/@engenty/local-models/dist/clients/failure.d.ts +26 -0
  60. package/node_modules/@engenty/local-models/dist/clients/failure.js +35 -0
  61. package/node_modules/@engenty/local-models/dist/clients/index.d.ts +14 -0
  62. package/node_modules/@engenty/local-models/dist/clients/index.js +16 -0
  63. package/node_modules/@engenty/local-models/dist/clients/model.d.ts +126 -0
  64. package/node_modules/@engenty/local-models/dist/clients/model.js +225 -0
  65. package/node_modules/@engenty/local-models/dist/clients/prompt.d.ts +36 -0
  66. package/node_modules/@engenty/local-models/dist/clients/prompt.js +123 -0
  67. package/node_modules/@engenty/local-models/dist/clients/run.d.ts +15 -0
  68. package/node_modules/@engenty/local-models/dist/clients/run.js +41 -0
  69. package/node_modules/@engenty/local-models/dist/index.d.ts +3 -0
  70. package/node_modules/@engenty/local-models/dist/index.js +3 -0
  71. package/node_modules/@engenty/local-models/dist/ollama/api.d.ts +70 -0
  72. package/node_modules/@engenty/local-models/dist/ollama/api.js +164 -0
  73. package/node_modules/@engenty/local-models/dist/ollama/index.d.ts +2 -0
  74. package/node_modules/@engenty/local-models/dist/ollama/index.js +2 -0
  75. package/node_modules/@engenty/local-models/dist/ollama/model.d.ts +52 -0
  76. package/node_modules/@engenty/local-models/dist/ollama/model.js +302 -0
  77. package/node_modules/@engenty/local-models/dist/probe.d.ts +54 -0
  78. package/node_modules/@engenty/local-models/dist/probe.js +190 -0
  79. package/node_modules/@engenty/local-models/package.json +12 -0
  80. package/package.json +3 -1
  81. package/plugin/.claude-plugin/plugin.json +1 -1
  82. package/plugin/plugin.json +1 -1
  83. package/apps/runtime/dist/agents/chat-clients.js +0 -344
  84. package/apps/runtime/dist/harness/claude.js +0 -141
  85. package/apps/runtime/dist/harness/codex.js +0 -222
  86. package/apps/runtime/dist/harness/cursor.js +0 -89
  87. package/apps/web/dist/assets/changelog-DoEmFdnI.js +0 -1
package/bin/bot.mjs CHANGED
@@ -13,10 +13,26 @@
13
13
  // ~/.engenty/wizards/bin/wizards-bot the command, linked into ~/.local/bin
14
14
  // ~/.wizards-bot/ the home's data (WIZARDS_BOT_DATA moves it)
15
15
  //
16
+ // `wizards bot install <folder>` puts a home of its own into a folder, beside the one above and
17
+ // beside other folders: its own program, data, port and service, named after the folder.
18
+ //
19
+ // <folder>/program/<version>/, current the release
20
+ // <folder>/wizards-bot.json the port, the Node, the tunnel
21
+ // <folder>/wizards-bot the command (not linked into ~/.local/bin)
22
+ // <folder>/data/ the home's data
23
+ // <folder>/logs/
24
+ //
25
+ // The Node in ~/.engenty/wizards/tools is shared by all of them.
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
+ //
16
31
  // For tests: WIZARDS_BOT_TARBALL (a path or an address of a tarball instead of the release's),
17
- // 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).
18
34
  import { spawn, spawnSync } from "node:child_process";
19
- import { createHash } from "node:crypto";
35
+ import { createHash, randomBytes } from "node:crypto";
20
36
  import {
21
37
  chmodSync,
22
38
  copyFileSync,
@@ -35,19 +51,46 @@ import {
35
51
  writeFileSync,
36
52
  } from "node:fs";
37
53
  import { request } from "node:http";
38
- import { createServer } from "node:net";
39
- import { homedir } from "node:os";
40
- import { delimiter, dirname, join, resolve, sep } from "node:path";
54
+ import { connect, createServer } from "node:net";
55
+ import { homedir, hostname } from "node:os";
56
+ import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
41
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";
42
70
 
43
71
  /** The Node install.sh brings; the home gets the same where it needs one. */
44
72
  export const NODE_VERSION = "26.12.0";
45
73
  const REPO = "engenty/wizards-bot";
46
- export const PORT = 4747;
74
+ /** The port of the Bot Server of the wizards.bot Mac app: never taken by a home of this command. */
75
+ export const MAC_APP_PORT = 4747;
76
+ /** The first port a new home tries. */
77
+ export const PORT = 4748;
78
+ /** The ports Tailscale Funnel serves on. */
79
+ export const FUNNEL_PORTS = [443, 8443, 10000];
47
80
  export const LABEL = "com.engenty.wizards.bot";
48
81
  export const LINK_LABEL = "com.engenty.wizards.bot.link";
49
82
  export const UNIT = "wizards-bot.service";
50
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
+ };
51
94
  /** How long the home may take to answer on /health after it starts. */
52
95
  const HEALTH_WAIT = 90_000;
53
96
 
@@ -62,39 +105,115 @@ const bold = paint(1);
62
105
  /** Something went wrong in a way the person can act on: its message is all they see. */
63
106
  class Refusal extends Error {}
64
107
 
65
- /** Where everything goes; ENGENTY_HOME and WIZARDS_BOT_DATA move it, as for the home itself. */
66
- export function layout(env = process.env) {
108
+ /**
109
+ * Where everything goes; ENGENTY_HOME and WIZARDS_BOT_DATA move it, as for the home itself. With
110
+ * a folder, everything of that home goes into the folder (WIZARDS_BOT_DATA doesn't count there),
111
+ * and its services are named after it, so homes in different folders don't replace each other.
112
+ */
113
+ export function layout(env = process.env, folder = null) {
67
114
  const user = homedir();
68
115
  const home = join(resolve((env.ENGENTY_HOME || "").trim() || join(user, ".engenty")), "wizards");
69
- const bot = join(home, "bot");
70
116
  const config = env.XDG_CONFIG_HOME || join(user, ".config");
71
- return {
117
+ const shared = {
72
118
  user,
73
119
  home,
120
+ tools: join(home, "tools"),
121
+ wizards: join(home, "bin", "wizards"),
122
+ launchAgents: join(user, "Library", "LaunchAgents"),
123
+ units: join(config, "systemd", "user"),
124
+ };
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
+ };
142
+ if (folder) {
143
+ const dir = resolve(folder);
144
+ const id = folderId(dir);
145
+ const logs = join(dir, "logs");
146
+ return {
147
+ ...shared,
148
+ folder: dir,
149
+ bot: join(dir, "program"),
150
+ current: join(dir, "program", "current"),
151
+ settings: join(dir, "wizards-bot.json"),
152
+ command: join(dir, "wizards-bot"),
153
+ pathLink: null,
154
+ logs,
155
+ log: join(logs, "bot.log"),
156
+ linkLog: join(logs, "bot-link.log"),
157
+ tunnelLog: join(logs, "bot-tunnel.log"),
158
+ installLog: join(logs, "bot-install.log"),
159
+ data: join(dir, "data"),
160
+ tunnel: join(dir, "tunnel"),
161
+ ...services(
162
+ `${LABEL}.${id}`,
163
+ `${LABEL}.${id}.link`,
164
+ `wizards-bot-${id}.service`,
165
+ `wizards-bot-${id}-link.service`,
166
+ ),
167
+ };
168
+ }
169
+ const bot = join(home, "bot");
170
+ const data = (env.WIZARDS_BOT_DATA || "").trim() || join(user, ".wizards-bot");
171
+ return {
172
+ ...shared,
173
+ folder: null,
74
174
  bot,
75
175
  current: join(bot, "current"),
76
176
  settings: join(bot, "bot.json"),
77
177
  command: join(home, "bin", "wizards-bot"),
78
- wizards: join(home, "bin", "wizards"),
79
178
  pathLink: join(user, ".local", "bin", "wizards-bot"),
80
- tools: join(home, "tools"),
81
179
  logs: join(home, "logs"),
82
180
  log: join(home, "logs", "bot.log"),
83
181
  linkLog: join(home, "logs", "bot-link.log"),
182
+ tunnelLog: join(home, "logs", "bot-tunnel.log"),
84
183
  installLog: join(home, "logs", "bot-install.log"),
85
- data: (env.WIZARDS_BOT_DATA || "").trim() || join(user, ".wizards-bot"),
86
- agent: join(user, "Library", "LaunchAgents", `${LABEL}.plist`),
87
- linkAgent: join(user, "Library", "LaunchAgents", `${LINK_LABEL}.plist`),
88
- unit: join(config, "systemd", "user", UNIT),
89
- linkUnit: join(config, "systemd", "user", LINK_UNIT),
184
+ data,
185
+ tunnel: join(data, "tunnel"),
186
+ ...services(LABEL, LINK_LABEL, UNIT, LINK_UNIT),
90
187
  };
91
188
  }
92
189
 
190
+ /** A folder's name in its services: its own name, made safe, and a hash of its whole path. */
191
+ export function folderId(dir) {
192
+ const slug =
193
+ basename(dir)
194
+ .toLowerCase()
195
+ .replace(/[^a-z0-9]+/g, "-")
196
+ .replace(/^-+|-+$/g, "")
197
+ .slice(0, 24) || "folder";
198
+ return `${slug}-${createHash("sha256").update(dir).digest("hex").slice(0, 6)}`;
199
+ }
200
+
201
+ /** The Bot Server of the wizards.bot Mac app keeps its data here. */
202
+ const macAppData = (paths) => join(paths.user, ".engenty", "wizards-bot");
203
+
93
204
  const tilde = (path) =>
94
205
  path === homedir() || path.startsWith(homedir() + sep)
95
206
  ? `~${path.slice(homedir().length)}`
96
207
  : path;
97
208
 
209
+ /** A folder as you'd type it in a terminal. */
210
+ const shellArg = (path) =>
211
+ /^~?[\w./@+-]+$/.test(tilde(path)) ? tilde(path) : `'${path.replaceAll("'", "'\\''")}'`;
212
+
213
+ /** `wizards bot <command>` for this home: with its folder when it has one. */
214
+ const hint = (paths, command) =>
215
+ cyan(`wizards bot ${command}${paths.folder ? ` ${shellArg(paths.folder)}` : ""}`);
216
+
98
217
  function readJson(file) {
99
218
  try {
100
219
  return JSON.parse(readFileSync(file, "utf8"));
@@ -142,7 +261,7 @@ export function homeAddress(text) {
142
261
  }
143
262
 
144
263
  /** The PATH without what npm put in for running this command. */
145
- function cleanPath(env = process.env) {
264
+ export function cleanPath(env = process.env) {
146
265
  return (env.PATH || "")
147
266
  .split(delimiter)
148
267
  .filter((dir) => dir && !/[\\/](node_modules[\\/]\.bin|node-gyp-bin)$/.test(dir))
@@ -417,6 +536,9 @@ export function commandText(paths, settings) {
417
536
  "# wizards.bot, written by `wizards bot install`; `wizards bot update` writes it again.",
418
537
  `export WIZARDS_BOT_PORT="\${WIZARDS_BOT_PORT:-${settings.port}}"`,
419
538
  `export WIZARDS_BOT_DATA="\${WIZARDS_BOT_DATA:-${settings.data.replaceAll('"', '\\"')}}"`,
539
+ ...(settings.url
540
+ ? [`export WIZARDS_BOT_URL="\${WIZARDS_BOT_URL:-${settings.url.replaceAll('"', '\\"')}}"`]
541
+ : []),
420
542
  `exec ${quote(settings.node)} ${quote(join(paths.current, settings.bin))} "$@"`,
421
543
  "",
422
544
  ].join("\n");
@@ -426,6 +548,11 @@ function writeCommand(paths, settings) {
426
548
  mkdirSync(dirname(paths.command), { recursive: true });
427
549
  writeFileSync(paths.command, commandText(paths, settings));
428
550
  chmodSync(paths.command, 0o755);
551
+ // A home in a folder keeps its command there: ~/.local/bin/wizards-bot is the other one's.
552
+ if (!paths.pathLink) {
553
+ step("Command", tilde(paths.command));
554
+ return;
555
+ }
429
556
  mkdirSync(dirname(paths.pathLink), { recursive: true });
430
557
  let there = null;
431
558
  try {
@@ -454,13 +581,72 @@ function saveSettings(paths, settings) {
454
581
  const xml = (text) =>
455
582
  String(text).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
456
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
+
457
640
  /** The environment a service gets: your PATH (for Ollama, Claude and Codex) and your home folder. */
458
641
  function serviceEnv(paths) {
459
- 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
+ };
460
646
  }
461
647
 
462
648
  /** The LaunchAgent: `wizards-bot <args>`, started at login and again when it fails. */
463
- export function agentText(paths, label, args, log) {
649
+ export function agentText(paths, label, args, log, program = paths.command) {
464
650
  const env = serviceEnv(paths);
465
651
  return `<?xml version="1.0" encoding="UTF-8"?>
466
652
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -470,7 +656,7 @@ export function agentText(paths, label, args, log) {
470
656
  <string>${xml(label)}</string>
471
657
  <key>ProgramArguments</key>
472
658
  <array>
473
- ${[paths.command, ...args].map((arg) => ` <string>${xml(arg)}</string>\n`).join("")} </array>
659
+ ${[program, ...args].map((arg) => ` <string>${xml(arg)}</string>\n`).join("")} </array>
474
660
  <key>EnvironmentVariables</key>
475
661
  <dict>
476
662
  ${Object.entries(env)
@@ -493,7 +679,7 @@ ${Object.entries(env)
493
679
  }
494
680
 
495
681
  /** The systemd user service: `wizards-bot <args>`, started at login and again when it fails. */
496
- export function unitText(paths, description, args) {
682
+ export function unitText(paths, description, args, program = paths.command) {
497
683
  const quoted = (text) => `"${String(text).replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
498
684
  const env = serviceEnv(paths);
499
685
  return [
@@ -502,7 +688,7 @@ export function unitText(paths, description, args) {
502
688
  `Documentation=https://github.com/${REPO}`,
503
689
  "",
504
690
  "[Service]",
505
- `ExecStart=${[paths.command, ...args].map(quoted).join(" ")}`,
691
+ `ExecStart=${[program, ...args].map(quoted).join(" ")}`,
506
692
  ...Object.entries(env).map(([key, value]) => `Environment=${quoted(`${key}=${value}`)}`),
507
693
  "Restart=on-failure",
508
694
  "RestartSec=5",
@@ -523,30 +709,117 @@ function systemdHere() {
523
709
  return Boolean(onPath("systemctl")) && systemctl(["show-environment"]).status === 0;
524
710
  }
525
711
 
526
- /** 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. */
527
713
  function services(paths) {
714
+ const where = paths.folder ? ` in ${tilde(paths.folder)}` : "";
528
715
  return {
529
716
  home: {
530
- label: LABEL,
531
- unit: UNIT,
717
+ label: paths.label,
718
+ unit: paths.unitName,
532
719
  agent: paths.agent,
533
720
  unitFile: paths.unit,
534
721
  args: ["start"],
535
722
  log: paths.log,
536
- description: "wizards.bot, your home",
723
+ description: `wizards.bot, your home${where}`,
537
724
  },
538
725
  link: {
539
- label: LINK_LABEL,
540
- unit: LINK_UNIT,
726
+ label: paths.linkLabel,
727
+ unit: paths.linkUnitName,
541
728
  agent: paths.linkAgent,
542
729
  unitFile: paths.linkUnit,
543
730
  args: ["link"],
544
731
  log: paths.linkLog,
545
- description: "wizards.bot, this computer’s models for your home",
732
+ description: `wizards.bot, this computer’s models for your home${where}`,
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}`,
546
744
  },
547
745
  };
548
746
  }
549
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
+
753
+ const unxml = (text) =>
754
+ text.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
755
+
756
+ function listDir(dir) {
757
+ try {
758
+ return readdirSync(dir);
759
+ } catch {
760
+ return [];
761
+ }
762
+ }
763
+
764
+ /**
765
+ * The folders with a home of `wizards bot install <folder>` on this computer, read from their
766
+ * services: a LaunchAgent or a systemd unit names the folder's command.
767
+ */
768
+ export function folderInstalls(paths) {
769
+ const found = [];
770
+ if (process.platform === "darwin") {
771
+ for (const name of listDir(paths.launchAgents)) {
772
+ const id = /^com\.engenty\.wizards\.bot\.(.+)\.plist$/.exec(name)?.[1];
773
+ if (!id || ["link", "tunnel"].includes(id) || /\.(link|tunnel)$/.test(id)) {
774
+ continue;
775
+ }
776
+ const text = readFileSync(join(paths.launchAgents, name), "utf8");
777
+ const command = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(
778
+ text,
779
+ )?.[1];
780
+ if (command) {
781
+ found.push(dirname(unxml(command)));
782
+ }
783
+ }
784
+ } else {
785
+ for (const name of listDir(paths.units)) {
786
+ if (!/^wizards-bot-.+\.service$/.test(name) || /-(link|tunnel)\.service$/.test(name)) {
787
+ continue;
788
+ }
789
+ const text = readFileSync(join(paths.units, name), "utf8");
790
+ const command = /^ExecStart="((?:[^"\\]|\\.)*)"/m.exec(text)?.[1];
791
+ if (command) {
792
+ found.push(dirname(command.replace(/\\(.)/g, "$1")));
793
+ }
794
+ }
795
+ }
796
+ return found.filter((dir) => dir !== paths.folder).sort();
797
+ }
798
+
799
+ /**
800
+ * The ports other homes of this command keep, running or not, and whose they are: the one in
801
+ * ~/.engenty/wizards and those in folders. A home that is stopped gets its port back when it starts.
802
+ */
803
+ export function claimedPorts(paths, env = process.env) {
804
+ const claimed = new Map();
805
+ const others = folderInstalls(paths).map((dir) => layout(env, dir));
806
+ if (paths.folder) {
807
+ others.unshift(layout(env));
808
+ }
809
+ for (const other of others) {
810
+ const port = readJson(other.settings)?.port;
811
+ if (port) {
812
+ claimed.set(
813
+ port,
814
+ other.folder
815
+ ? `the Bot Server in ${tilde(other.folder)}`
816
+ : "the Bot Server of `wizards bot install`",
817
+ );
818
+ }
819
+ }
820
+ return claimed;
821
+ }
822
+
550
823
  /** Takes a LaunchAgent out of launchd and waits until it is gone. */
551
824
  async function bootout(service) {
552
825
  const target = `gui/${uid()}/${service.label}`;
@@ -564,7 +837,10 @@ async function startService(paths, service) {
564
837
  mkdirSync(paths.logs, { recursive: true });
565
838
  if (process.platform === "darwin") {
566
839
  mkdirSync(dirname(service.agent), { recursive: true });
567
- 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
+ );
568
844
  await bootout(service);
569
845
  // launchd may still be letting the old one go: it refuses with error 5 meanwhile.
570
846
  let result = null;
@@ -586,7 +862,10 @@ async function startService(paths, service) {
586
862
  return false;
587
863
  }
588
864
  mkdirSync(dirname(service.unitFile), { recursive: true });
589
- 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
+ );
590
869
  systemctl(["daemon-reload"]);
591
870
  const result = systemctl(["enable", service.unit]);
592
871
  const restart = systemctl(["restart", service.unit]);
@@ -642,24 +921,143 @@ function serviceRuns(service) {
642
921
 
643
922
  // --- the port and the home's answer ----------------------------------------------------------
644
923
 
645
- function portFree(port) {
924
+ /** Whether something takes connections on 127.0.0.1 at a port. */
925
+ function answers(port) {
646
926
  return new Promise((done) => {
927
+ const socket = connect({ port, host: "127.0.0.1" });
928
+ socket.setTimeout(1000);
929
+ socket.once("connect", () => {
930
+ socket.destroy();
931
+ done(true);
932
+ });
933
+ socket.once("timeout", () => {
934
+ socket.destroy();
935
+ done(false);
936
+ });
937
+ socket.once("error", () => done(false));
938
+ });
939
+ }
940
+
941
+ /**
942
+ * Whether a port is free: nothing listens on it, for the whole network or only on 127.0.0.1
943
+ * (binding to 0.0.0.0 alone wouldn't tell the second on a Mac).
944
+ */
945
+ export async function portFree(port) {
946
+ const bindable = await new Promise((done) => {
647
947
  const server = createServer();
648
948
  server.once("error", () => done(false));
649
949
  server.listen({ port, host: "0.0.0.0" }, () => server.close(() => done(true)));
650
950
  });
951
+ return bindable && !(await answers(port));
952
+ }
953
+
954
+ /** Who holds a port, as "<program> (pid <n>)", from lsof or ss; null when neither says. */
955
+ export function portHolder(port) {
956
+ let pid = null;
957
+ const lsof = spawnSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fp"], {
958
+ encoding: "utf8",
959
+ });
960
+ pid = /^p(\d+)/m.exec(lsof.stdout || "")?.[1] || null;
961
+ if (!pid && process.platform === "linux") {
962
+ const ss = spawnSync("ss", ["-ltnpH", `sport = :${port}`], { encoding: "utf8" });
963
+ pid = /pid=(\d+)/.exec(ss.stdout || "")?.[1] || null;
964
+ }
965
+ if (!pid) {
966
+ return null;
967
+ }
968
+ const command = spawnSync("ps", ["-o", "command=", "-p", pid], {
969
+ encoding: "utf8",
970
+ }).stdout?.trim();
971
+ return `${programName(command || "")} (pid ${pid})`;
972
+ }
973
+
974
+ /** A process's command line as a short name: an app by its name, else the program and its script. */
975
+ export function programName(command) {
976
+ const app = /\/([^/]+\.app)\/Contents\//.exec(command)?.[1];
977
+ if (app) {
978
+ return app;
979
+ }
980
+ const [program = "a program", script] = command.split(/\s+/);
981
+ const name = program.split("/").pop();
982
+ return script?.startsWith("/") ? `${name} ${tilde(script)}` : name;
983
+ }
984
+
985
+ /** Why a port can't be had: whose it is, or what holds it. */
986
+ function takenBy(port, claimed) {
987
+ if (claimed.has(port)) {
988
+ return `kept for ${claimed.get(port)}`;
989
+ }
990
+ const holder = portHolder(port);
991
+ const mac = port === MAC_APP_PORT ? " (the port of the wizards.bot Mac app)" : "";
992
+ return holder ? `taken by ${holder}${mac}` : `taken${mac}`;
651
993
  }
652
994
 
653
- /** The first free port from `start` on. */
654
- export async function freePort(start) {
995
+ /** The first free port from `start` on, past those other homes keep and past the Mac app's. */
996
+ export async function freePort(start, claimed = new Map(), skipped = []) {
655
997
  for (let port = start; port < start + 100; port++) {
656
- if (await portFree(port)) {
998
+ if (port === MAC_APP_PORT) {
999
+ continue;
1000
+ }
1001
+ if (!claimed.has(port) && (await portFree(port))) {
657
1002
  return port;
658
1003
  }
1004
+ skipped.push(port);
659
1005
  }
660
1006
  throw new Refusal(`No port from ${start} to ${start + 99} is free.`);
661
1007
  }
662
1008
 
1009
+ /**
1010
+ * Refuses a --port that can't be had, before anything is downloaded: 4747, a port another home
1011
+ * keeps, or one something holds now. The home's own port is let through: it holds it itself.
1012
+ */
1013
+ export async function checkPort(paths, options) {
1014
+ const saved = readJson(paths.settings) || {};
1015
+ const port = options.port;
1016
+ if (!port || port === saved.port) {
1017
+ return;
1018
+ }
1019
+ if (port === MAC_APP_PORT) {
1020
+ throw new Refusal(
1021
+ `${MAC_APP_PORT} is the port of the wizards.bot Mac app’s Bot Server. Pick another with --port, or leave it out.`,
1022
+ );
1023
+ }
1024
+ const claimed = claimedPorts(paths);
1025
+ if (claimed.has(port) || !(await portFree(port))) {
1026
+ throw new Refusal(
1027
+ `Port ${port} is ${takenBy(port, claimed)}. Pick another with --port, or leave it out to take the next free one.`,
1028
+ );
1029
+ }
1030
+ }
1031
+
1032
+ /**
1033
+ * The port a home starts on: the one it had, the one asked for with --port, or the first free one
1034
+ * from 4748 on. A taken port is said with what holds it.
1035
+ */
1036
+ async function choosePort(paths, options, saved) {
1037
+ const claimed = claimedPorts(paths);
1038
+ const wanted = options.port || saved.port || null;
1039
+ if (wanted) {
1040
+ // The home that ran there a moment ago may still be letting go of it.
1041
+ for (let tries = 0; tries < 20 && wanted === saved.port && !(await portFree(wanted)); tries++) {
1042
+ await pause(250);
1043
+ }
1044
+ if (!claimed.has(wanted) && (await portFree(wanted))) {
1045
+ return wanted;
1046
+ }
1047
+ if (options.port) {
1048
+ throw new Refusal(
1049
+ `Port ${wanted} is ${takenBy(wanted, claimed)}. Pick another with --port, or leave it out to take the next free one.`,
1050
+ );
1051
+ }
1052
+ }
1053
+ const skipped = [];
1054
+ const port = await freePort(wanted ? wanted + 1 : PORT, claimed, skipped);
1055
+ for (const taken of [wanted, ...skipped].filter(Boolean).slice(0, 4)) {
1056
+ note(`Port ${taken} is ${takenBy(taken, claimed)}`);
1057
+ }
1058
+ return port;
1059
+ }
1060
+
663
1061
  /** Whether the home answers on /health with 200. */
664
1062
  export function healthy(port) {
665
1063
  return new Promise((done) => {
@@ -712,12 +1110,23 @@ function windowsRefusal() {
712
1110
  }
713
1111
  }
714
1112
 
715
- function notInstalled() {
1113
+ function notInstalled(paths) {
716
1114
  return new Refusal(
717
- `wizards.bot isn’t installed on this computer. To install it: ${cyan("wizards bot install")}`,
1115
+ paths.folder
1116
+ ? `No wizards.bot is installed in ${tilde(paths.folder)}. To install it there: ${hint(paths, "install")}`
1117
+ : `wizards.bot isn’t installed on this computer. To install it: ${cyan("wizards bot install")}`,
718
1118
  );
719
1119
  }
720
1120
 
1121
+ /** The settings of an installed home, or a refusal that says how to install it. */
1122
+ function installed(paths) {
1123
+ const settings = readJson(paths.settings);
1124
+ if (!settings || !installedVersion(paths)) {
1125
+ throw notInstalled(paths);
1126
+ }
1127
+ return settings;
1128
+ }
1129
+
721
1130
  /** What to install: the tarball WIZARDS_BOT_TARBALL names, or a release. */
722
1131
  function source(version) {
723
1132
  const tarball = (process.env.WIZARDS_BOT_TARBALL || "").trim();
@@ -735,7 +1144,7 @@ function source(version) {
735
1144
 
736
1145
  /**
737
1146
  * Installs a version and (re)starts the home with it. The home keeps its port; a new home gets
738
- * 4747 (or `--port`), or the next free one from there.
1147
+ * `--port`, or the first free one from 4748 on (4747 is the Mac app's).
739
1148
  */
740
1149
  async function put(paths, options, from) {
741
1150
  const saved = readJson(paths.settings) || {};
@@ -744,42 +1153,84 @@ async function put(paths, options, from) {
744
1153
  const { version, bin } = installProgram(paths, from, node);
745
1154
  // The home that runs gives its port free first.
746
1155
  await stopService(home);
747
- const wanted = options.port || saved.port || PORT;
748
- for (let tries = 0; tries < 20 && wanted === saved.port && !(await portFree(wanted)); tries++) {
749
- await pause(250);
750
- }
751
- const port = await freePort(wanted);
1156
+ const port = await choosePort(paths, options, saved);
752
1157
  const settings = {
753
1158
  version,
754
1159
  bin,
755
1160
  port,
756
1161
  node,
757
1162
  data: paths.data,
758
- // A Node this command downloaded goes with the home, unless engenty wizards uses it too.
1163
+ // A Node this command downloaded goes with the home, unless engenty wizards or a home in a
1164
+ // folder uses it too. Homes in folders never take it away.
759
1165
  nodeBrought:
760
- Boolean(saved.nodeBrought || brought) && node === join(paths.tools, "node", "bin", "node"),
1166
+ !paths.folder &&
1167
+ Boolean(saved.nodeBrought || brought) &&
1168
+ node === join(paths.tools, "node", "bin", "node"),
1169
+ ...(saved.url ? { url: saved.url } : {}),
1170
+ ...(saved.tunnel ? { tunnel: saved.tunnel } : {}),
761
1171
  };
762
1172
  saveSettings(paths, settings);
763
1173
  writeCommand(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 };
1178
+ }
1179
+
1180
+ /** Starts the home's service again and waits for its answer; false where nothing can run it. */
1181
+ async function startHome(paths, settings) {
1182
+ const home = services(paths).home;
764
1183
  if (!(await startService(paths, home))) {
765
1184
  console.log(
766
- `\nThe home doesn’t start by itself here: systemd --user isn’t available. Start it with ${cyan("wizards-bot start")}.`,
1185
+ `\nThe home doesn’t start by itself here: systemd --user isn’t available. Start it with ${cyan(`${paths.folder ? shellArg(paths.command) : "wizards-bot"} start`)}.`,
767
1186
  );
768
- return { settings, running: false };
1187
+ return false;
769
1188
  }
770
- note(`Starting the home on port ${port}`);
771
- await waitForHealth(paths, port);
772
- step("Home", `http://localhost:${port}, ${serviceThere(home)}`);
773
- return { settings, running: true };
1189
+ note(`Starting the home on port ${settings.port}`);
1190
+ await waitForHealth(paths, settings.port);
1191
+ step("Home", `http://localhost:${settings.port}, ${serviceThere(home)}`);
1192
+ return true;
1193
+ }
1194
+
1195
+ /**
1196
+ * Whether a folder may hold a home: not your home folder itself, and not inside the folders the
1197
+ * other homes keep their program or data in.
1198
+ */
1199
+ export function folderRefusal(paths) {
1200
+ const dir = paths.folder;
1201
+ const inside = (parent) => dir === parent || dir.startsWith(parent + sep);
1202
+ if (dir === paths.user || dir === sep) {
1203
+ return `${tilde(dir)} is too wide for a home: give it a folder of its own, e.g. ${cyan(`wizards bot install ${shellArg(join(dir, "wizards-bot"))}`)}`;
1204
+ }
1205
+ for (const [parent, whose] of [
1206
+ [macAppData(paths), "the data of the wizards.bot Mac app"],
1207
+ [layout().data, "the data of the home of `wizards bot install`"],
1208
+ [paths.home, "engenty wizards and the home of `wizards bot install`"],
1209
+ ]) {
1210
+ if (inside(parent)) {
1211
+ return `${tilde(parent)} holds ${whose}: pick a folder outside it.`;
1212
+ }
1213
+ }
1214
+ return null;
774
1215
  }
775
1216
 
776
1217
  async function install(paths, options) {
777
1218
  windowsRefusal();
778
- const installed = installedVersion(paths);
779
- console.log(`${bold("wizards.bot")} ${dim(`into ${tilde(paths.bot)}`)}`);
1219
+ if (paths.folder) {
1220
+ const refusal = folderRefusal(paths);
1221
+ if (refusal) {
1222
+ throw new Refusal(refusal);
1223
+ }
1224
+ }
1225
+ await checkPort(paths, options);
1226
+ if (paths.folder) {
1227
+ mkdirSync(paths.folder, { recursive: true });
1228
+ }
1229
+ const before = installedVersion(paths);
1230
+ console.log(`${bold("wizards.bot")} ${dim(`into ${tilde(paths.folder || paths.bot)}`)}`);
780
1231
  const from = source(options.version);
781
- if (installed && from.version && installed === from.version && !options.version) {
782
- note(`wizards.bot ${installed} is installed already: installing it again`);
1232
+ if (before && from.version && before === from.version && !options.version) {
1233
+ note(`wizards.bot ${before} is installed already: installing it again`);
783
1234
  }
784
1235
  const { running } = await put(paths, options, from);
785
1236
  if (running) {
@@ -790,16 +1241,13 @@ async function install(paths, options) {
790
1241
  /** Prints the output of `wizards-bot pair` (the QR, the code) and opens the pairing link. */
791
1242
  async function setup(paths, options) {
792
1243
  windowsRefusal();
793
- const settings = readJson(paths.settings);
794
- if (!settings || !installedVersion(paths)) {
795
- throw notInstalled();
796
- }
1244
+ const settings = installed(paths);
797
1245
  if (options.link) {
798
1246
  return link(paths, settings, options);
799
1247
  }
800
1248
  if (!(await healthy(settings.port))) {
801
1249
  throw new Refusal(
802
- `The home doesn’t run. ${cyan("wizards bot status")} says more, its log is ${tilde(paths.log)}.`,
1250
+ `The home doesn’t run. ${hint(paths, "status")} says more, its log is ${tilde(paths.log)}.`,
803
1251
  );
804
1252
  }
805
1253
  const result = spawnSync(paths.command, ["pair"], { encoding: "utf8" });
@@ -816,11 +1264,6 @@ async function setup(paths, options) {
816
1264
  console.log(`\nOpened the home’s setup in your browser: ${url}`);
817
1265
  }
818
1266
  }
819
-
820
- /**
821
- * `setup --link <address> <code>`: pairs this computer with a home elsewhere, then keeps
822
- * `wizards-bot link` running as a service, so that home uses this computer's models while it is on.
823
- */
824
1267
  async function link(paths, settings, options) {
825
1268
  const [where, code] = options.link;
826
1269
  if (!where || !code) {
@@ -873,22 +1316,22 @@ async function link(paths, settings, options) {
873
1316
  console.log(`\nYour home at ${address} uses this computer’s models while this computer is on.`);
874
1317
  }
875
1318
 
876
- async function status(paths) {
877
- const version = installedVersion(paths);
878
- const settings = readJson(paths.settings);
879
- if (!version || !settings) {
880
- console.log(
881
- `wizards.bot isn’t installed on this computer. To install it: ${cyan("wizards bot install")}`,
882
- );
883
- return;
884
- }
885
- const { home, link: linked } = services(paths);
1319
+ /** One home's lines: its version, whether it runs, its address, its data, its tunnel. */
1320
+ async function describe(paths, settings, version) {
1321
+ const { home, link: linked, tunnel: tunneled } = services(paths);
886
1322
  const answers = await healthy(settings.port);
887
1323
  const how = serviceThere(home);
888
- console.log(`wizards.bot ${version} ${dim(tilde(join(paths.bot, version)))}`);
1324
+ console.log(`wizards.bot ${version} ${dim(tilde(paths.folder || join(paths.bot, version)))}`);
889
1325
  console.log(
890
1326
  ` ${answers ? green("running") : red("not running")} http://localhost:${settings.port}${how ? dim(` (${how})`) : ""}`,
891
1327
  );
1328
+ if (settings.url) {
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}`);
1334
+ }
892
1335
  console.log(` data ${tilde(settings.data)}`);
893
1336
  console.log(` command ${tilde(paths.command)}`);
894
1337
  const linkFile = readJson(join(settings.data, "link.json"));
@@ -898,19 +1341,89 @@ async function status(paths) {
898
1341
  );
899
1342
  }
900
1343
  if (!answers) {
901
- console.log(`\nIts log: ${tilde(paths.log)}`);
1344
+ console.log(` its log ${tilde(paths.log)}`);
1345
+ }
1346
+ }
1347
+
1348
+ /**
1349
+ * `status`: the home in ~/.engenty/wizards and a line for each home in a folder; `status <folder>`:
1350
+ * that folder's home.
1351
+ */
1352
+ async function status(paths, _options, env) {
1353
+ const version = installedVersion(paths);
1354
+ const settings = readJson(paths.settings);
1355
+ if (paths.folder) {
1356
+ if (!version || !settings) {
1357
+ console.log(`No wizards.bot is installed in ${tilde(paths.folder)}.`);
1358
+ return;
1359
+ }
1360
+ await describe(paths, settings, version);
1361
+ return;
1362
+ }
1363
+ const folders = folderInstalls(paths);
1364
+ if (version && settings) {
1365
+ await describe(paths, settings, version);
1366
+ } else if (!folders.length) {
1367
+ console.log(
1368
+ `wizards.bot isn’t installed on this computer. To install it: ${cyan("wizards bot install")}`,
1369
+ );
1370
+ return;
1371
+ }
1372
+ if (folders.length) {
1373
+ console.log(
1374
+ `${version && settings ? "\n" : ""}In folders ${dim("(wizards bot status <folder> says more)")}`,
1375
+ );
1376
+ }
1377
+ for (const dir of folders) {
1378
+ const there = layout(env, dir);
1379
+ const theirs = readJson(there.settings);
1380
+ const runs = theirs?.port ? await healthy(theirs.port) : false;
1381
+ console.log(
1382
+ ` ${tilde(dir)} ${!theirs ? red("missing") : runs ? green("running") : red("not running")}${theirs?.port ? ` http://localhost:${theirs.port}` : ""}${theirs?.url ? ` ${theirs.url}` : ""}`,
1383
+ );
1384
+ }
1385
+ }
1386
+
1387
+ /** `stop`: the home and its link stop until you log in again or start them. Nothing is removed. */
1388
+ async function stop(paths) {
1389
+ installed(paths);
1390
+ const { home, link: linked, tunnel: tunneled } = services(paths);
1391
+ for (const service of [tunneled, linked, home]) {
1392
+ const how = serviceThere(service);
1393
+ if (how) {
1394
+ await stopService(service);
1395
+ step("Stopped", how);
1396
+ }
1397
+ }
1398
+ console.log(
1399
+ `\nIt starts again when you log in, or with ${hint(paths, "start")}. Its data and port are kept.`,
1400
+ );
1401
+ }
1402
+
1403
+ /** `start`: starts a stopped home and its link again. */
1404
+ async function start(paths) {
1405
+ windowsRefusal();
1406
+ const settings = installed(paths);
1407
+ const linked = services(paths).link;
1408
+ await startHome(paths, settings);
1409
+ if (serviceThere(linked)) {
1410
+ await startService(paths, linked);
1411
+ }
1412
+ if (settings.tunnel?.by === "relay" && serviceThere(services(paths).tunnel)) {
1413
+ await startService(paths, tunnelService(paths, settings));
902
1414
  }
903
1415
  }
904
1416
 
905
1417
  async function update(paths, options) {
906
1418
  windowsRefusal();
907
- const installed = installedVersion(paths);
908
- if (!installed) {
909
- throw notInstalled();
1419
+ const before = installedVersion(paths);
1420
+ if (!before) {
1421
+ throw notInstalled(paths);
910
1422
  }
1423
+ await checkPort(paths, options);
911
1424
  const from = source(options.version);
912
- if (from.version && !options.version && !older(installed, from.version)) {
913
- console.log(`wizards.bot ${installed} is the newest version.`);
1425
+ if (from.version && !options.version && !older(before, from.version)) {
1426
+ console.log(`wizards.bot ${before} is the newest version.`);
914
1427
  return;
915
1428
  }
916
1429
  const { settings, running } = await put(paths, options, from);
@@ -920,7 +1433,7 @@ async function update(paths, options) {
920
1433
  await startService(paths, linked);
921
1434
  }
922
1435
  console.log(
923
- `\nwizards.bot ${installed === settings.version ? `${installed} is installed again` : `went from ${installed} to ${settings.version}`}. Your data is kept${running ? ", and the home runs" : ""}.`,
1436
+ `\nwizards.bot ${before === settings.version ? `${before} is installed again` : `went from ${before} to ${settings.version}`}. Your data is kept${running ? ", and the home runs" : ""}.`,
924
1437
  );
925
1438
  }
926
1439
 
@@ -943,17 +1456,27 @@ function dropEmpty(dir) {
943
1456
  }
944
1457
  }
945
1458
 
1459
+ /**
1460
+ * `uninstall`: takes the home in ~/.engenty/wizards away; `uninstall <folder>` the one in that
1461
+ * folder, and the folder too once nothing else is in it. The data stays unless --purge.
1462
+ */
946
1463
  async function uninstall(paths, options) {
947
1464
  const settings = readJson(paths.settings) || {};
948
- const { home, link: linked } = services(paths);
1465
+ const { home, link: linked, tunnel: tunneled } = services(paths);
949
1466
  const there =
950
1467
  existsSync(paths.bot) ||
951
1468
  existsSync(paths.command) ||
952
1469
  serviceThere(home) ||
953
- serviceThere(linked);
1470
+ serviceThere(linked) ||
1471
+ serviceThere(tunneled);
954
1472
  const data = settings.data || paths.data;
1473
+ const where = paths.folder ? `${tilde(paths.folder)}` : "this computer";
955
1474
  if (!there && !options.purge) {
956
- console.log("wizards.bot isn’t installed on this computer.");
1475
+ console.log(
1476
+ paths.folder
1477
+ ? `No wizards.bot is installed in ${where}.`
1478
+ : "wizards.bot isn’t installed on this computer.",
1479
+ );
957
1480
  return;
958
1481
  }
959
1482
  let purge = false;
@@ -968,77 +1491,544 @@ async function uninstall(paths, options) {
968
1491
  throw new Refusal("--purge asks first. Run it in a terminal, or add --yes.");
969
1492
  }
970
1493
  }
971
- for (const service of [linked, home]) {
1494
+ if (settings.tunnel) {
1495
+ await closeTunnel(paths, settings);
1496
+ step("Closed the tunnel", settings.url);
1497
+ }
1498
+ for (const service of [tunneled, linked, home]) {
972
1499
  const how = serviceThere(service);
973
1500
  if (how) {
974
1501
  await removeService(service);
975
1502
  step("Stopped and removed", how);
976
1503
  }
977
1504
  }
978
- try {
979
- if (
980
- lstatSync(paths.pathLink).isSymbolicLink() &&
981
- readlinkSync(paths.pathLink) === paths.command
982
- ) {
983
- rmSync(paths.pathLink);
1505
+ if (paths.pathLink) {
1506
+ try {
1507
+ if (
1508
+ lstatSync(paths.pathLink).isSymbolicLink() &&
1509
+ readlinkSync(paths.pathLink) === paths.command
1510
+ ) {
1511
+ rmSync(paths.pathLink);
1512
+ }
1513
+ } catch {
1514
+ // no link
984
1515
  }
985
- } catch {
986
- // no link
987
1516
  }
988
1517
  rmSync(paths.command, { force: true });
989
1518
  rmSync(paths.bot, { recursive: true, force: true });
990
- for (const log of [paths.log, paths.linkLog, paths.installLog]) {
1519
+ for (const log of [paths.log, paths.linkLog, paths.tunnelLog, paths.installLog]) {
991
1520
  rmSync(log, { force: true });
992
1521
  }
993
- // A Node this command brought goes too, unless engenty wizards is installed and uses it.
994
- if (settings.nodeBrought && !existsSync(paths.wizards)) {
995
- for (const name of existsSync(paths.tools) ? readdirSync(paths.tools) : []) {
996
- if (name === "node" || name.startsWith("node-v")) {
997
- rmSync(join(paths.tools, name), { recursive: true, force: true });
1522
+ step("Removed the program", tilde(paths.bot));
1523
+ if (paths.folder) {
1524
+ rmSync(paths.settings, { force: true });
1525
+ dropEmpty(paths.logs);
1526
+ } else {
1527
+ // A Node this command brought goes too, unless engenty wizards or a home in a folder uses it.
1528
+ if (settings.nodeBrought && !existsSync(paths.wizards) && !folderInstalls(paths).length) {
1529
+ for (const name of listDir(paths.tools)) {
1530
+ if (name === "node" || name.startsWith("node-v")) {
1531
+ rmSync(join(paths.tools, name), { recursive: true, force: true });
1532
+ }
998
1533
  }
999
1534
  }
1000
- }
1001
- step("Removed the program", tilde(paths.bot));
1002
- for (const dir of [
1003
- paths.tools,
1004
- paths.logs,
1005
- dirname(paths.command),
1006
- paths.home,
1007
- dirname(paths.home),
1008
- ]) {
1009
- dropEmpty(dir);
1535
+ for (const dir of [
1536
+ paths.tools,
1537
+ paths.logs,
1538
+ dirname(paths.command),
1539
+ paths.home,
1540
+ dirname(paths.home),
1541
+ ]) {
1542
+ dropEmpty(dir);
1543
+ }
1010
1544
  }
1011
1545
  if (purge) {
1012
1546
  rmSync(data, { recursive: true, force: true });
1013
- console.log(`\nwizards.bot is off this computer, and its data in ${tilde(data)} is deleted.`);
1547
+ // The tunnel's own key goes with the data: its name is given up.
1548
+ rmSync(paths.tunnel, { recursive: true, force: true });
1549
+ }
1550
+ if (paths.folder) {
1551
+ dropEmpty(paths.folder);
1552
+ }
1553
+ if (purge) {
1554
+ console.log(`\nwizards.bot is off ${where}, and its data in ${tilde(data)} is deleted.`);
1014
1555
  } else if (existsSync(data)) {
1015
1556
  console.log(
1016
- `\nwizards.bot is off this computer. Your home’s data stays in ${tilde(data)}: ${cyan("wizards bot install")} picks it up again.`,
1557
+ `\nwizards.bot is off ${where}. Your home’s data stays in ${tilde(data)}: ${hint(paths, "install")} picks it up again.`,
1017
1558
  );
1018
1559
  } else {
1019
- console.log("\nwizards.bot is off this computer.");
1560
+ console.log(`\nwizards.bot is off ${where}.`);
1020
1561
  }
1021
1562
  }
1022
1563
 
1564
+ // --- the tunnel ------------------------------------------------------------------------------
1565
+
1566
+ /** The tailscale command: on PATH, or inside the Mac app. */
1567
+ function tailscale() {
1568
+ const app = "/Applications/Tailscale.app/Contents/MacOS/Tailscale";
1569
+ return onPath("tailscale") || (process.platform === "darwin" && existsSync(app) ? app : null);
1570
+ }
1571
+
1572
+ function tailscaleJson(command, args) {
1573
+ const result = spawnSync(command, args, { encoding: "utf8", timeout: 15_000 });
1574
+ try {
1575
+ return result.status === 0 ? JSON.parse(result.stdout) : null;
1576
+ } catch {
1577
+ return null;
1578
+ }
1579
+ }
1580
+
1581
+ /** How many devices are paired with a home, from `wizards-bot status`; null when it can't say. */
1582
+ export function devicesIn(text) {
1583
+ const list = /^Devices\n((?: {2}.*\n?)*)/m.exec(text)?.[1];
1584
+ if (list === undefined) {
1585
+ return null;
1586
+ }
1587
+ const lines = list.split("\n").filter((line) => line.trim());
1588
+ return lines.length === 1 && lines[0].trim() === "none" ? 0 : lines.length;
1589
+ }
1590
+
1591
+ /**
1592
+ * The Funnel port for a home: the one that already serves it, else the first of 443, 8443 and
1593
+ * 10000 that serves nothing. `serving` is `tailscale funnel status --json`.
1594
+ */
1595
+ export function funnelPort(serving, host, port) {
1596
+ const target = new RegExp(`^(https?://)?(127\\.0\\.0\\.1|localhost):${port}/?$`);
1597
+ const web = serving?.Web || {};
1598
+ const tcp = serving?.TCP || {};
1599
+ const ours = FUNNEL_PORTS.find((https) =>
1600
+ target.test(web[`${host}:${https}`]?.Handlers?.["/"]?.Proxy || ""),
1601
+ );
1602
+ return ours || FUNNEL_PORTS.find((https) => !web[`${host}:${https}`] && !tcp[https]) || null;
1603
+ }
1604
+
1605
+ /** Whether an address answers on /health from the internet's side, by curl. */
1606
+ function reachable(url) {
1607
+ return (
1608
+ spawnSync("curl", ["-fsS", "--max-time", "10", "-o", "/dev/null", `${url}/health`]).status === 0
1609
+ );
1610
+ }
1611
+
1612
+ /** `tailscale funnel …` for a home's port, in the background (it stays after a restart). */
1613
+ const funnelArgs = (https, port) => [
1614
+ "funnel",
1615
+ "--bg",
1616
+ `--https=${https}`,
1617
+ `http://127.0.0.1:${port}`,
1618
+ ];
1619
+
1620
+ /** Takes a home's Funnel off, with the command that put it on and `off` after it. */
1621
+ function closeFunnel(settings) {
1622
+ const command = tailscale();
1623
+ if (command && settings.tunnel?.https) {
1624
+ spawnSync(command, [...funnelArgs(settings.tunnel.https, settings.port), "off"], {
1625
+ encoding: "utf8",
1626
+ timeout: 15_000,
1627
+ });
1628
+ }
1629
+ }
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
+
1819
+ /**
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.
1826
+ */
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
+ }
1833
+ windowsRefusal();
1834
+ const settings = installed(paths);
1835
+ if (options.off) {
1836
+ if (!settings.tunnel) {
1837
+ console.log("This home isn’t on the internet: there’s no tunnel to close.");
1838
+ return;
1839
+ }
1840
+ await closeTunnel(paths, settings);
1841
+ const { url: _url, tunnel: _tunnel, ...rest } = settings;
1842
+ saveSettings(paths, rest);
1843
+ writeCommand(paths, rest);
1844
+ await startHome(paths, rest);
1845
+ step("Closed the tunnel", settings.url);
1846
+ console.log(
1847
+ `\nThe home is off the internet. Your devices reach it on this network again, at its local address.`,
1848
+ );
1849
+ return;
1850
+ }
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
+ );
1855
+ }
1856
+ const by = options.tailscale ? "tailscale-funnel" : "relay";
1857
+ if (settings.tunnel && settings.tunnel.by !== by) {
1858
+ throw new Refusal(
1859
+ `This home is on the internet already, at ${settings.url}. Close that first: ${hint(paths, "tunnel --off")}`,
1860
+ );
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) {
1949
+ const command = tailscale();
1950
+ if (!command) {
1951
+ throw new Refusal(
1952
+ "The tunnel goes through Tailscale Funnel. Install Tailscale (https://tailscale.com/download), sign in, then run this again.",
1953
+ );
1954
+ }
1955
+ const state = tailscaleJson(command, ["status", "--json"]);
1956
+ const host = String(state?.Self?.DNSName || "").replace(/\.$/, "");
1957
+ if (state?.BackendState !== "Running" || !host) {
1958
+ throw new Refusal(
1959
+ `Tailscale isn’t signed in, or isn’t running. Sign in (${cyan("tailscale up")}), then run this again.`,
1960
+ );
1961
+ }
1962
+ const https = funnelPort(
1963
+ tailscaleJson(command, ["funnel", "status", "--json"]),
1964
+ host,
1965
+ settings.port,
1966
+ );
1967
+ if (!https) {
1968
+ throw new Refusal(
1969
+ `Tailscale Funnel serves on 443, 8443 and 10000 only, and all three serve something else here. ${cyan("tailscale funnel status")} shows what.`,
1970
+ );
1971
+ }
1972
+ const url = `https://${host}${https === 443 ? "" : `:${https}`}`;
1973
+ note(`Opening ${url} with Tailscale Funnel`);
1974
+ // Tailscale may ask to turn Funnel on for this computer first, with a link: that goes to you.
1975
+ const opened = spawnSync(command, funnelArgs(https, settings.port), { stdio: "inherit" });
1976
+ if (opened.status !== 0) {
1977
+ throw new Refusal(
1978
+ `tailscale funnel didn’t open ${url}. ${cyan("tailscale funnel status")} says what it serves.`,
1979
+ );
1980
+ }
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;
1989
+ }
1990
+ writeTunnel(paths.tunnel, { ...saved, port: settings.port });
1991
+ await startService(paths, tunnelService(paths, settings));
1992
+ }
1993
+
1023
1994
  // --- the command line ------------------------------------------------------------------------
1024
1995
 
1025
1996
  const HELP = `${bold("wizards bot")}: wizards.bot, your own agent in a home of your own, on this computer
1026
1997
 
1027
1998
  Commands
1028
- ${cyan("wizards bot install")} install the home, start it with your computer and open its setup
1999
+ ${cyan("wizards bot install [folder]")}
2000
+ install the home, start it with your computer and open its setup
1029
2001
  ${cyan("wizards bot setup")} open the home’s setup and show a code to pair your phone
1030
2002
  ${cyan("wizards bot setup --link <address> <code>")}
1031
2003
  link this computer to your home on wizards.bot: it uses this
1032
2004
  computer’s models while it’s on (e.g. --link ada K7QM-2RXD)
1033
- ${cyan("wizards bot status")} show the installed version, whether it runs and its address
2005
+ ${cyan("wizards bot status")} show the installed version, whether it runs and its address,
2006
+ and a line for each home in a folder
2007
+ ${cyan("wizards bot stop")} stop the home until you log in again or start it
2008
+ ${cyan("wizards bot start")} start it again
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)
1034
2014
  ${cyan("wizards bot update")} install the newest version and restart the home, your data is kept
1035
2015
  ${cyan("wizards bot uninstall")} take the home off this computer, your data in ~/.wizards-bot is kept
1036
2016
  (--purge deletes it too, after asking)
1037
2017
 
2018
+ A folder
2019
+ ${cyan("wizards bot install .")} or ${cyan("wizards bot install ./test01")} puts a home of its own into that
2020
+ folder: program, data, port and service, beside the other homes. Every command takes the
2021
+ folder after it (${cyan("wizards bot status ./test01")}); without one, a command means the home in
2022
+ ~/.engenty/wizards.
2023
+
1038
2024
  Options
1039
2025
  --version <v> install this version instead of the newest
1040
- --port <n> the port for a new home (default 4747, or the next free one)
2026
+ --port <n> the port for a new home (default 4748, or the next free one; 4747 is the
2027
+ Mac app’s)
1041
2028
  --no-open don’t open the browser
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
1042
2032
  --yes, -y don’t ask
1043
2033
 
1044
2034
  The program goes into ~/.engenty/wizards/bot (ENGENTY_HOME moves it), the command
@@ -1046,13 +2036,18 @@ wizards-bot into ~/.local/bin. On a Mac the home runs as a LaunchAgent, on Linux
1046
2036
  systemd user service.
1047
2037
  `;
1048
2038
 
1049
- /** Reads `wizards bot <command> [options]`. */
2039
+ /** Reads `wizards bot <command> [folder] [options]`. */
1050
2040
  export function parse(argv) {
1051
2041
  const options = {
1052
2042
  command: "",
2043
+ folder: null,
1053
2044
  open: true,
1054
2045
  yes: false,
1055
2046
  purge: false,
2047
+ off: false,
2048
+ tailscale: false,
2049
+ account: false,
2050
+ name: null,
1056
2051
  link: null,
1057
2052
  version: null,
1058
2053
  port: null,
@@ -1068,6 +2063,17 @@ export function parse(argv) {
1068
2063
  options.yes = true;
1069
2064
  } else if (arg === "--purge") {
1070
2065
  options.purge = true;
2066
+ } else if (arg === "--off") {
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
+ }
1071
2077
  } else if (arg === "--link") {
1072
2078
  options.link = [argv[i + 1], argv[i + 2]];
1073
2079
  i += 2;
@@ -1079,20 +2085,22 @@ export function parse(argv) {
1079
2085
  } else if (arg === "--port") {
1080
2086
  options.port = Number(argv[++i]);
1081
2087
  if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65535) {
1082
- throw new Refusal("--port needs a port, e.g. --port 4747");
2088
+ throw new Refusal("--port needs a port, e.g. --port 4748");
1083
2089
  }
1084
2090
  } else if (arg.startsWith("-")) {
1085
2091
  throw new Refusal(`Unknown option ${arg}. ${cyan("wizards bot --help")} lists them.`);
1086
2092
  } else if (!options.command) {
1087
2093
  options.command = arg;
2094
+ } else if (options.folder === null) {
2095
+ options.folder = arg;
1088
2096
  } else {
1089
- throw new Refusal(`One command at a time: ${options.command} or ${arg}.`);
2097
+ throw new Refusal(`One folder at a time: ${options.folder} or ${arg}.`);
1090
2098
  }
1091
2099
  }
1092
2100
  return options;
1093
2101
  }
1094
2102
 
1095
- const COMMANDS = { install, setup, status, update, uninstall };
2103
+ const COMMANDS = { install, setup, status, stop, start, tunnel, update, uninstall };
1096
2104
 
1097
2105
  /** `wizards bot …`; its exit code. */
1098
2106
  export async function main(argv, env = process.env) {
@@ -1102,13 +2110,13 @@ export async function main(argv, env = process.env) {
1102
2110
  console.log(HELP);
1103
2111
  return 0;
1104
2112
  }
1105
- const run = COMMANDS[options.command];
1106
- if (!run) {
2113
+ const command = COMMANDS[options.command];
2114
+ if (!command) {
1107
2115
  throw new Refusal(
1108
2116
  `wizards bot has no command ${options.command}. ${cyan("wizards bot --help")} lists them.`,
1109
2117
  );
1110
2118
  }
1111
- await run(layout(env), options);
2119
+ await command(layout(env, options.folder), options, env);
1112
2120
  return 0;
1113
2121
  } catch (error) {
1114
2122
  if (!(error instanceof Refusal)) {