wizards 0.20.3 → 0.20.5

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 (3) hide show
  1. package/README.md +1 -1
  2. package/bin/bot.mjs +690 -107
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -234,7 +234,7 @@ The wizard format, the runner and four libraries are MIT. The rest of the code i
234
234
  |---|---|
235
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)) |
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` and `@engenty/plugins` on npm, in `packages/decision-model`, `packages/search-index`, `packages/search-libsql`, `packages/goose`, `packages/vault` and `packages/plugins` | MIT (the `LICENSE` in each folder) |
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) |
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)) |
package/bin/bot.mjs CHANGED
@@ -13,6 +13,17 @@
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
+ //
16
27
  // For tests: WIZARDS_BOT_TARBALL (a path or an address of a tarball instead of the release's),
17
28
  // ENGENTY_HOME, WIZARDS_BOT_DATA.
18
29
  import { spawn, spawnSync } from "node:child_process";
@@ -35,15 +46,20 @@ import {
35
46
  writeFileSync,
36
47
  } from "node:fs";
37
48
  import { request } from "node:http";
38
- import { createServer } from "node:net";
49
+ import { connect, createServer } from "node:net";
39
50
  import { homedir } from "node:os";
40
- import { delimiter, dirname, join, resolve, sep } from "node:path";
51
+ import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
41
52
  import { createInterface } from "node:readline";
42
53
 
43
54
  /** The Node install.sh brings; the home gets the same where it needs one. */
44
55
  export const NODE_VERSION = "26.12.0";
45
56
  const REPO = "engenty/wizards-bot";
46
- export const PORT = 4747;
57
+ /** The port of the Bot Server of the wizards.bot Mac app: never taken by a home of this command. */
58
+ export const MAC_APP_PORT = 4747;
59
+ /** The first port a new home tries. */
60
+ export const PORT = 4748;
61
+ /** The ports Tailscale Funnel serves on. */
62
+ export const FUNNEL_PORTS = [443, 8443, 10000];
47
63
  export const LABEL = "com.engenty.wizards.bot";
48
64
  export const LINK_LABEL = "com.engenty.wizards.bot.link";
49
65
  export const UNIT = "wizards-bot.service";
@@ -62,39 +78,103 @@ const bold = paint(1);
62
78
  /** Something went wrong in a way the person can act on: its message is all they see. */
63
79
  class Refusal extends Error {}
64
80
 
65
- /** Where everything goes; ENGENTY_HOME and WIZARDS_BOT_DATA move it, as for the home itself. */
66
- export function layout(env = process.env) {
81
+ /**
82
+ * Where everything goes; ENGENTY_HOME and WIZARDS_BOT_DATA move it, as for the home itself. With
83
+ * a folder, everything of that home goes into the folder (WIZARDS_BOT_DATA doesn't count there),
84
+ * and its services are named after it, so homes in different folders don't replace each other.
85
+ */
86
+ export function layout(env = process.env, folder = null) {
67
87
  const user = homedir();
68
88
  const home = join(resolve((env.ENGENTY_HOME || "").trim() || join(user, ".engenty")), "wizards");
69
- const bot = join(home, "bot");
70
89
  const config = env.XDG_CONFIG_HOME || join(user, ".config");
71
- return {
90
+ const shared = {
72
91
  user,
73
92
  home,
93
+ tools: join(home, "tools"),
94
+ wizards: join(home, "bin", "wizards"),
95
+ launchAgents: join(user, "Library", "LaunchAgents"),
96
+ units: join(config, "systemd", "user"),
97
+ };
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
+ });
108
+ if (folder) {
109
+ const dir = resolve(folder);
110
+ const id = folderId(dir);
111
+ const logs = join(dir, "logs");
112
+ return {
113
+ ...shared,
114
+ folder: dir,
115
+ bot: join(dir, "program"),
116
+ current: join(dir, "program", "current"),
117
+ settings: join(dir, "wizards-bot.json"),
118
+ command: join(dir, "wizards-bot"),
119
+ pathLink: null,
120
+ logs,
121
+ log: join(logs, "bot.log"),
122
+ linkLog: join(logs, "bot-link.log"),
123
+ installLog: join(logs, "bot-install.log"),
124
+ data: join(dir, "data"),
125
+ ...services(
126
+ `${LABEL}.${id}`,
127
+ `${LABEL}.${id}.link`,
128
+ `wizards-bot-${id}.service`,
129
+ `wizards-bot-${id}-link.service`,
130
+ ),
131
+ };
132
+ }
133
+ const bot = join(home, "bot");
134
+ return {
135
+ ...shared,
136
+ folder: null,
74
137
  bot,
75
138
  current: join(bot, "current"),
76
139
  settings: join(bot, "bot.json"),
77
140
  command: join(home, "bin", "wizards-bot"),
78
- wizards: join(home, "bin", "wizards"),
79
141
  pathLink: join(user, ".local", "bin", "wizards-bot"),
80
- tools: join(home, "tools"),
81
142
  logs: join(home, "logs"),
82
143
  log: join(home, "logs", "bot.log"),
83
144
  linkLog: join(home, "logs", "bot-link.log"),
84
145
  installLog: join(home, "logs", "bot-install.log"),
85
146
  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),
147
+ ...services(LABEL, LINK_LABEL, UNIT, LINK_UNIT),
90
148
  };
91
149
  }
92
150
 
151
+ /** A folder's name in its services: its own name, made safe, and a hash of its whole path. */
152
+ export function folderId(dir) {
153
+ const slug =
154
+ basename(dir)
155
+ .toLowerCase()
156
+ .replace(/[^a-z0-9]+/g, "-")
157
+ .replace(/^-+|-+$/g, "")
158
+ .slice(0, 24) || "folder";
159
+ return `${slug}-${createHash("sha256").update(dir).digest("hex").slice(0, 6)}`;
160
+ }
161
+
162
+ /** The Bot Server of the wizards.bot Mac app keeps its data here. */
163
+ const macAppData = (paths) => join(paths.user, ".engenty", "wizards-bot");
164
+
93
165
  const tilde = (path) =>
94
166
  path === homedir() || path.startsWith(homedir() + sep)
95
167
  ? `~${path.slice(homedir().length)}`
96
168
  : path;
97
169
 
170
+ /** A folder as you'd type it in a terminal. */
171
+ const shellArg = (path) =>
172
+ /^~?[\w./@+-]+$/.test(tilde(path)) ? tilde(path) : `'${path.replaceAll("'", "'\\''")}'`;
173
+
174
+ /** `wizards bot <command>` for this home: with its folder when it has one. */
175
+ const hint = (paths, command) =>
176
+ cyan(`wizards bot ${command}${paths.folder ? ` ${shellArg(paths.folder)}` : ""}`);
177
+
98
178
  function readJson(file) {
99
179
  try {
100
180
  return JSON.parse(readFileSync(file, "utf8"));
@@ -417,6 +497,9 @@ export function commandText(paths, settings) {
417
497
  "# wizards.bot, written by `wizards bot install`; `wizards bot update` writes it again.",
418
498
  `export WIZARDS_BOT_PORT="\${WIZARDS_BOT_PORT:-${settings.port}}"`,
419
499
  `export WIZARDS_BOT_DATA="\${WIZARDS_BOT_DATA:-${settings.data.replaceAll('"', '\\"')}}"`,
500
+ ...(settings.url
501
+ ? [`export WIZARDS_BOT_URL="\${WIZARDS_BOT_URL:-${settings.url.replaceAll('"', '\\"')}}"`]
502
+ : []),
420
503
  `exec ${quote(settings.node)} ${quote(join(paths.current, settings.bin))} "$@"`,
421
504
  "",
422
505
  ].join("\n");
@@ -426,6 +509,11 @@ function writeCommand(paths, settings) {
426
509
  mkdirSync(dirname(paths.command), { recursive: true });
427
510
  writeFileSync(paths.command, commandText(paths, settings));
428
511
  chmodSync(paths.command, 0o755);
512
+ // A home in a folder keeps its command there: ~/.local/bin/wizards-bot is the other one's.
513
+ if (!paths.pathLink) {
514
+ step("Command", tilde(paths.command));
515
+ return;
516
+ }
429
517
  mkdirSync(dirname(paths.pathLink), { recursive: true });
430
518
  let there = null;
431
519
  try {
@@ -525,28 +613,99 @@ function systemdHere() {
525
613
 
526
614
  /** The two services: the home, and the link to a home elsewhere. */
527
615
  function services(paths) {
616
+ const where = paths.folder ? ` in ${tilde(paths.folder)}` : "";
528
617
  return {
529
618
  home: {
530
- label: LABEL,
531
- unit: UNIT,
619
+ label: paths.label,
620
+ unit: paths.unitName,
532
621
  agent: paths.agent,
533
622
  unitFile: paths.unit,
534
623
  args: ["start"],
535
624
  log: paths.log,
536
- description: "wizards.bot, your home",
625
+ description: `wizards.bot, your home${where}`,
537
626
  },
538
627
  link: {
539
- label: LINK_LABEL,
540
- unit: LINK_UNIT,
628
+ label: paths.linkLabel,
629
+ unit: paths.linkUnitName,
541
630
  agent: paths.linkAgent,
542
631
  unitFile: paths.linkUnit,
543
632
  args: ["link"],
544
633
  log: paths.linkLog,
545
- description: "wizards.bot, this computer’s models for your home",
634
+ description: `wizards.bot, this computer’s models for your home${where}`,
546
635
  },
547
636
  };
548
637
  }
549
638
 
639
+ const unxml = (text) =>
640
+ text.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
641
+
642
+ function listDir(dir) {
643
+ try {
644
+ return readdirSync(dir);
645
+ } catch {
646
+ return [];
647
+ }
648
+ }
649
+
650
+ /**
651
+ * The folders with a home of `wizards bot install <folder>` on this computer, read from their
652
+ * services: a LaunchAgent or a systemd unit names the folder's command.
653
+ */
654
+ export function folderInstalls(paths) {
655
+ const found = [];
656
+ if (process.platform === "darwin") {
657
+ for (const name of listDir(paths.launchAgents)) {
658
+ const id = /^com\.engenty\.wizards\.bot\.(.+)\.plist$/.exec(name)?.[1];
659
+ if (!id || id === "link" || id.endsWith(".link")) {
660
+ continue;
661
+ }
662
+ const text = readFileSync(join(paths.launchAgents, name), "utf8");
663
+ const command = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(
664
+ text,
665
+ )?.[1];
666
+ if (command) {
667
+ found.push(dirname(unxml(command)));
668
+ }
669
+ }
670
+ } else {
671
+ for (const name of listDir(paths.units)) {
672
+ if (!/^wizards-bot-.+\.service$/.test(name) || name.endsWith("-link.service")) {
673
+ continue;
674
+ }
675
+ const text = readFileSync(join(paths.units, name), "utf8");
676
+ const command = /^ExecStart="((?:[^"\\]|\\.)*)"/m.exec(text)?.[1];
677
+ if (command) {
678
+ found.push(dirname(command.replace(/\\(.)/g, "$1")));
679
+ }
680
+ }
681
+ }
682
+ return found.filter((dir) => dir !== paths.folder).sort();
683
+ }
684
+
685
+ /**
686
+ * The ports other homes of this command keep, running or not, and whose they are: the one in
687
+ * ~/.engenty/wizards and those in folders. A home that is stopped gets its port back when it starts.
688
+ */
689
+ export function claimedPorts(paths, env = process.env) {
690
+ const claimed = new Map();
691
+ const others = folderInstalls(paths).map((dir) => layout(env, dir));
692
+ if (paths.folder) {
693
+ others.unshift(layout(env));
694
+ }
695
+ for (const other of others) {
696
+ const port = readJson(other.settings)?.port;
697
+ if (port) {
698
+ claimed.set(
699
+ port,
700
+ other.folder
701
+ ? `the Bot Server in ${tilde(other.folder)}`
702
+ : "the Bot Server of `wizards bot install`",
703
+ );
704
+ }
705
+ }
706
+ return claimed;
707
+ }
708
+
550
709
  /** Takes a LaunchAgent out of launchd and waits until it is gone. */
551
710
  async function bootout(service) {
552
711
  const target = `gui/${uid()}/${service.label}`;
@@ -642,24 +801,143 @@ function serviceRuns(service) {
642
801
 
643
802
  // --- the port and the home's answer ----------------------------------------------------------
644
803
 
645
- function portFree(port) {
804
+ /** Whether something takes connections on 127.0.0.1 at a port. */
805
+ function answers(port) {
646
806
  return new Promise((done) => {
807
+ const socket = connect({ port, host: "127.0.0.1" });
808
+ socket.setTimeout(1000);
809
+ socket.once("connect", () => {
810
+ socket.destroy();
811
+ done(true);
812
+ });
813
+ socket.once("timeout", () => {
814
+ socket.destroy();
815
+ done(false);
816
+ });
817
+ socket.once("error", () => done(false));
818
+ });
819
+ }
820
+
821
+ /**
822
+ * Whether a port is free: nothing listens on it, for the whole network or only on 127.0.0.1
823
+ * (binding to 0.0.0.0 alone wouldn't tell the second on a Mac).
824
+ */
825
+ export async function portFree(port) {
826
+ const bindable = await new Promise((done) => {
647
827
  const server = createServer();
648
828
  server.once("error", () => done(false));
649
829
  server.listen({ port, host: "0.0.0.0" }, () => server.close(() => done(true)));
650
830
  });
831
+ return bindable && !(await answers(port));
651
832
  }
652
833
 
653
- /** The first free port from `start` on. */
654
- export async function freePort(start) {
834
+ /** Who holds a port, as "<program> (pid <n>)", from lsof or ss; null when neither says. */
835
+ export function portHolder(port) {
836
+ let pid = null;
837
+ const lsof = spawnSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fp"], {
838
+ encoding: "utf8",
839
+ });
840
+ pid = /^p(\d+)/m.exec(lsof.stdout || "")?.[1] || null;
841
+ if (!pid && process.platform === "linux") {
842
+ const ss = spawnSync("ss", ["-ltnpH", `sport = :${port}`], { encoding: "utf8" });
843
+ pid = /pid=(\d+)/.exec(ss.stdout || "")?.[1] || null;
844
+ }
845
+ if (!pid) {
846
+ return null;
847
+ }
848
+ const command = spawnSync("ps", ["-o", "command=", "-p", pid], {
849
+ encoding: "utf8",
850
+ }).stdout?.trim();
851
+ return `${programName(command || "")} (pid ${pid})`;
852
+ }
853
+
854
+ /** A process's command line as a short name: an app by its name, else the program and its script. */
855
+ export function programName(command) {
856
+ const app = /\/([^/]+\.app)\/Contents\//.exec(command)?.[1];
857
+ if (app) {
858
+ return app;
859
+ }
860
+ const [program = "a program", script] = command.split(/\s+/);
861
+ const name = program.split("/").pop();
862
+ return script?.startsWith("/") ? `${name} ${tilde(script)}` : name;
863
+ }
864
+
865
+ /** Why a port can't be had: whose it is, or what holds it. */
866
+ function takenBy(port, claimed) {
867
+ if (claimed.has(port)) {
868
+ return `kept for ${claimed.get(port)}`;
869
+ }
870
+ const holder = portHolder(port);
871
+ const mac = port === MAC_APP_PORT ? " (the port of the wizards.bot Mac app)" : "";
872
+ return holder ? `taken by ${holder}${mac}` : `taken${mac}`;
873
+ }
874
+
875
+ /** The first free port from `start` on, past those other homes keep and past the Mac app's. */
876
+ export async function freePort(start, claimed = new Map(), skipped = []) {
655
877
  for (let port = start; port < start + 100; port++) {
656
- if (await portFree(port)) {
878
+ if (port === MAC_APP_PORT) {
879
+ continue;
880
+ }
881
+ if (!claimed.has(port) && (await portFree(port))) {
657
882
  return port;
658
883
  }
884
+ skipped.push(port);
659
885
  }
660
886
  throw new Refusal(`No port from ${start} to ${start + 99} is free.`);
661
887
  }
662
888
 
889
+ /**
890
+ * Refuses a --port that can't be had, before anything is downloaded: 4747, a port another home
891
+ * keeps, or one something holds now. The home's own port is let through: it holds it itself.
892
+ */
893
+ export async function checkPort(paths, options) {
894
+ const saved = readJson(paths.settings) || {};
895
+ const port = options.port;
896
+ if (!port || port === saved.port) {
897
+ return;
898
+ }
899
+ if (port === MAC_APP_PORT) {
900
+ throw new Refusal(
901
+ `${MAC_APP_PORT} is the port of the wizards.bot Mac app’s Bot Server. Pick another with --port, or leave it out.`,
902
+ );
903
+ }
904
+ const claimed = claimedPorts(paths);
905
+ if (claimed.has(port) || !(await portFree(port))) {
906
+ throw new Refusal(
907
+ `Port ${port} is ${takenBy(port, claimed)}. Pick another with --port, or leave it out to take the next free one.`,
908
+ );
909
+ }
910
+ }
911
+
912
+ /**
913
+ * The port a home starts on: the one it had, the one asked for with --port, or the first free one
914
+ * from 4748 on. A taken port is said with what holds it.
915
+ */
916
+ async function choosePort(paths, options, saved) {
917
+ const claimed = claimedPorts(paths);
918
+ const wanted = options.port || saved.port || null;
919
+ if (wanted) {
920
+ // The home that ran there a moment ago may still be letting go of it.
921
+ for (let tries = 0; tries < 20 && wanted === saved.port && !(await portFree(wanted)); tries++) {
922
+ await pause(250);
923
+ }
924
+ if (!claimed.has(wanted) && (await portFree(wanted))) {
925
+ return wanted;
926
+ }
927
+ if (options.port) {
928
+ throw new Refusal(
929
+ `Port ${wanted} is ${takenBy(wanted, claimed)}. Pick another with --port, or leave it out to take the next free one.`,
930
+ );
931
+ }
932
+ }
933
+ const skipped = [];
934
+ const port = await freePort(wanted ? wanted + 1 : PORT, claimed, skipped);
935
+ for (const taken of [wanted, ...skipped].filter(Boolean).slice(0, 4)) {
936
+ note(`Port ${taken} is ${takenBy(taken, claimed)}`);
937
+ }
938
+ return port;
939
+ }
940
+
663
941
  /** Whether the home answers on /health with 200. */
664
942
  export function healthy(port) {
665
943
  return new Promise((done) => {
@@ -712,12 +990,23 @@ function windowsRefusal() {
712
990
  }
713
991
  }
714
992
 
715
- function notInstalled() {
993
+ function notInstalled(paths) {
716
994
  return new Refusal(
717
- `wizards.bot isn’t installed on this computer. To install it: ${cyan("wizards bot install")}`,
995
+ paths.folder
996
+ ? `No wizards.bot is installed in ${tilde(paths.folder)}. To install it there: ${hint(paths, "install")}`
997
+ : `wizards.bot isn’t installed on this computer. To install it: ${cyan("wizards bot install")}`,
718
998
  );
719
999
  }
720
1000
 
1001
+ /** The settings of an installed home, or a refusal that says how to install it. */
1002
+ function installed(paths) {
1003
+ const settings = readJson(paths.settings);
1004
+ if (!settings || !installedVersion(paths)) {
1005
+ throw notInstalled(paths);
1006
+ }
1007
+ return settings;
1008
+ }
1009
+
721
1010
  /** What to install: the tarball WIZARDS_BOT_TARBALL names, or a release. */
722
1011
  function source(version) {
723
1012
  const tarball = (process.env.WIZARDS_BOT_TARBALL || "").trim();
@@ -735,7 +1024,7 @@ function source(version) {
735
1024
 
736
1025
  /**
737
1026
  * 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.
1027
+ * `--port`, or the first free one from 4748 on (4747 is the Mac app's).
739
1028
  */
740
1029
  async function put(paths, options, from) {
741
1030
  const saved = readJson(paths.settings) || {};
@@ -744,42 +1033,81 @@ async function put(paths, options, from) {
744
1033
  const { version, bin } = installProgram(paths, from, node);
745
1034
  // The home that runs gives its port free first.
746
1035
  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);
1036
+ const port = await choosePort(paths, options, saved);
752
1037
  const settings = {
753
1038
  version,
754
1039
  bin,
755
1040
  port,
756
1041
  node,
757
1042
  data: paths.data,
758
- // A Node this command downloaded goes with the home, unless engenty wizards uses it too.
1043
+ // A Node this command downloaded goes with the home, unless engenty wizards or a home in a
1044
+ // folder uses it too. Homes in folders never take it away.
759
1045
  nodeBrought:
760
- Boolean(saved.nodeBrought || brought) && node === join(paths.tools, "node", "bin", "node"),
1046
+ !paths.folder &&
1047
+ Boolean(saved.nodeBrought || brought) &&
1048
+ node === join(paths.tools, "node", "bin", "node"),
1049
+ ...(saved.url ? { url: saved.url } : {}),
1050
+ ...(saved.tunnel ? { tunnel: saved.tunnel } : {}),
761
1051
  };
762
1052
  saveSettings(paths, settings);
763
1053
  writeCommand(paths, settings);
1054
+ return { settings, running: await startHome(paths, settings) };
1055
+ }
1056
+
1057
+ /** Starts the home's service again and waits for its answer; false where nothing can run it. */
1058
+ async function startHome(paths, settings) {
1059
+ const home = services(paths).home;
764
1060
  if (!(await startService(paths, home))) {
765
1061
  console.log(
766
- `\nThe home doesn’t start by itself here: systemd --user isn’t available. Start it with ${cyan("wizards-bot start")}.`,
1062
+ `\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
1063
  );
768
- return { settings, running: false };
1064
+ return false;
1065
+ }
1066
+ note(`Starting the home on port ${settings.port}`);
1067
+ await waitForHealth(paths, settings.port);
1068
+ step("Home", `http://localhost:${settings.port}, ${serviceThere(home)}`);
1069
+ return true;
1070
+ }
1071
+
1072
+ /**
1073
+ * Whether a folder may hold a home: not your home folder itself, and not inside the folders the
1074
+ * other homes keep their program or data in.
1075
+ */
1076
+ export function folderRefusal(paths) {
1077
+ const dir = paths.folder;
1078
+ const inside = (parent) => dir === parent || dir.startsWith(parent + sep);
1079
+ if (dir === paths.user || dir === sep) {
1080
+ 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"))}`)}`;
1081
+ }
1082
+ for (const [parent, whose] of [
1083
+ [macAppData(paths), "the data of the wizards.bot Mac app"],
1084
+ [layout().data, "the data of the home of `wizards bot install`"],
1085
+ [paths.home, "engenty wizards and the home of `wizards bot install`"],
1086
+ ]) {
1087
+ if (inside(parent)) {
1088
+ return `${tilde(parent)} holds ${whose}: pick a folder outside it.`;
1089
+ }
769
1090
  }
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 };
1091
+ return null;
774
1092
  }
775
1093
 
776
1094
  async function install(paths, options) {
777
1095
  windowsRefusal();
778
- const installed = installedVersion(paths);
779
- console.log(`${bold("wizards.bot")} ${dim(`into ${tilde(paths.bot)}`)}`);
1096
+ if (paths.folder) {
1097
+ const refusal = folderRefusal(paths);
1098
+ if (refusal) {
1099
+ throw new Refusal(refusal);
1100
+ }
1101
+ }
1102
+ await checkPort(paths, options);
1103
+ if (paths.folder) {
1104
+ mkdirSync(paths.folder, { recursive: true });
1105
+ }
1106
+ const before = installedVersion(paths);
1107
+ console.log(`${bold("wizards.bot")} ${dim(`into ${tilde(paths.folder || paths.bot)}`)}`);
780
1108
  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`);
1109
+ if (before && from.version && before === from.version && !options.version) {
1110
+ note(`wizards.bot ${before} is installed already: installing it again`);
783
1111
  }
784
1112
  const { running } = await put(paths, options, from);
785
1113
  if (running) {
@@ -790,16 +1118,13 @@ async function install(paths, options) {
790
1118
  /** Prints the output of `wizards-bot pair` (the QR, the code) and opens the pairing link. */
791
1119
  async function setup(paths, options) {
792
1120
  windowsRefusal();
793
- const settings = readJson(paths.settings);
794
- if (!settings || !installedVersion(paths)) {
795
- throw notInstalled();
796
- }
1121
+ const settings = installed(paths);
797
1122
  if (options.link) {
798
1123
  return link(paths, settings, options);
799
1124
  }
800
1125
  if (!(await healthy(settings.port))) {
801
1126
  throw new Refusal(
802
- `The home doesn’t run. ${cyan("wizards bot status")} says more, its log is ${tilde(paths.log)}.`,
1127
+ `The home doesn’t run. ${hint(paths, "status")} says more, its log is ${tilde(paths.log)}.`,
803
1128
  );
804
1129
  }
805
1130
  const result = spawnSync(paths.command, ["pair"], { encoding: "utf8" });
@@ -816,11 +1141,6 @@ async function setup(paths, options) {
816
1141
  console.log(`\nOpened the home’s setup in your browser: ${url}`);
817
1142
  }
818
1143
  }
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
1144
  async function link(paths, settings, options) {
825
1145
  const [where, code] = options.link;
826
1146
  if (!where || !code) {
@@ -873,22 +1193,18 @@ async function link(paths, settings, options) {
873
1193
  console.log(`\nYour home at ${address} uses this computer’s models while this computer is on.`);
874
1194
  }
875
1195
 
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
- }
1196
+ /** One home's lines: its version, whether it runs, its address, its data, its tunnel. */
1197
+ async function describe(paths, settings, version) {
885
1198
  const { home, link: linked } = services(paths);
886
1199
  const answers = await healthy(settings.port);
887
1200
  const how = serviceThere(home);
888
- console.log(`wizards.bot ${version} ${dim(tilde(join(paths.bot, version)))}`);
1201
+ console.log(`wizards.bot ${version} ${dim(tilde(paths.folder || join(paths.bot, version)))}`);
889
1202
  console.log(
890
1203
  ` ${answers ? green("running") : red("not running")} http://localhost:${settings.port}${how ? dim(` (${how})`) : ""}`,
891
1204
  );
1205
+ if (settings.url) {
1206
+ console.log(` internet ${settings.url} ${dim("(Tailscale Funnel)")}`);
1207
+ }
892
1208
  console.log(` data ${tilde(settings.data)}`);
893
1209
  console.log(` command ${tilde(paths.command)}`);
894
1210
  const linkFile = readJson(join(settings.data, "link.json"));
@@ -898,19 +1214,86 @@ async function status(paths) {
898
1214
  );
899
1215
  }
900
1216
  if (!answers) {
901
- console.log(`\nIts log: ${tilde(paths.log)}`);
1217
+ console.log(` its log ${tilde(paths.log)}`);
1218
+ }
1219
+ }
1220
+
1221
+ /**
1222
+ * `status`: the home in ~/.engenty/wizards and a line for each home in a folder; `status <folder>`:
1223
+ * that folder's home.
1224
+ */
1225
+ async function status(paths, _options, env) {
1226
+ const version = installedVersion(paths);
1227
+ const settings = readJson(paths.settings);
1228
+ if (paths.folder) {
1229
+ if (!version || !settings) {
1230
+ console.log(`No wizards.bot is installed in ${tilde(paths.folder)}.`);
1231
+ return;
1232
+ }
1233
+ await describe(paths, settings, version);
1234
+ return;
1235
+ }
1236
+ const folders = folderInstalls(paths);
1237
+ if (version && settings) {
1238
+ await describe(paths, settings, version);
1239
+ } else if (!folders.length) {
1240
+ console.log(
1241
+ `wizards.bot isn’t installed on this computer. To install it: ${cyan("wizards bot install")}`,
1242
+ );
1243
+ return;
1244
+ }
1245
+ if (folders.length) {
1246
+ console.log(
1247
+ `${version && settings ? "\n" : ""}In folders ${dim("(wizards bot status <folder> says more)")}`,
1248
+ );
1249
+ }
1250
+ for (const dir of folders) {
1251
+ const there = layout(env, dir);
1252
+ const theirs = readJson(there.settings);
1253
+ const runs = theirs?.port ? await healthy(theirs.port) : false;
1254
+ console.log(
1255
+ ` ${tilde(dir)} ${!theirs ? red("missing") : runs ? green("running") : red("not running")}${theirs?.port ? ` http://localhost:${theirs.port}` : ""}${theirs?.url ? ` ${theirs.url}` : ""}`,
1256
+ );
1257
+ }
1258
+ }
1259
+
1260
+ /** `stop`: the home and its link stop until you log in again or start them. Nothing is removed. */
1261
+ async function stop(paths) {
1262
+ installed(paths);
1263
+ const { home, link: linked } = services(paths);
1264
+ for (const service of [linked, home]) {
1265
+ const how = serviceThere(service);
1266
+ if (how) {
1267
+ await stopService(service);
1268
+ step("Stopped", how);
1269
+ }
1270
+ }
1271
+ console.log(
1272
+ `\nIt starts again when you log in, or with ${hint(paths, "start")}. Its data and port are kept.`,
1273
+ );
1274
+ }
1275
+
1276
+ /** `start`: starts a stopped home and its link again. */
1277
+ async function start(paths) {
1278
+ windowsRefusal();
1279
+ const settings = installed(paths);
1280
+ const linked = services(paths).link;
1281
+ await startHome(paths, settings);
1282
+ if (serviceThere(linked)) {
1283
+ await startService(paths, linked);
902
1284
  }
903
1285
  }
904
1286
 
905
1287
  async function update(paths, options) {
906
1288
  windowsRefusal();
907
- const installed = installedVersion(paths);
908
- if (!installed) {
909
- throw notInstalled();
1289
+ const before = installedVersion(paths);
1290
+ if (!before) {
1291
+ throw notInstalled(paths);
910
1292
  }
1293
+ await checkPort(paths, options);
911
1294
  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.`);
1295
+ if (from.version && !options.version && !older(before, from.version)) {
1296
+ console.log(`wizards.bot ${before} is the newest version.`);
914
1297
  return;
915
1298
  }
916
1299
  const { settings, running } = await put(paths, options, from);
@@ -920,7 +1303,7 @@ async function update(paths, options) {
920
1303
  await startService(paths, linked);
921
1304
  }
922
1305
  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" : ""}.`,
1306
+ `\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
1307
  );
925
1308
  }
926
1309
 
@@ -943,6 +1326,10 @@ function dropEmpty(dir) {
943
1326
  }
944
1327
  }
945
1328
 
1329
+ /**
1330
+ * `uninstall`: takes the home in ~/.engenty/wizards away; `uninstall <folder>` the one in that
1331
+ * folder, and the folder too once nothing else is in it. The data stays unless --purge.
1332
+ */
946
1333
  async function uninstall(paths, options) {
947
1334
  const settings = readJson(paths.settings) || {};
948
1335
  const { home, link: linked } = services(paths);
@@ -952,8 +1339,13 @@ async function uninstall(paths, options) {
952
1339
  serviceThere(home) ||
953
1340
  serviceThere(linked);
954
1341
  const data = settings.data || paths.data;
1342
+ const where = paths.folder ? `${tilde(paths.folder)}` : "this computer";
955
1343
  if (!there && !options.purge) {
956
- console.log("wizards.bot isn’t installed on this computer.");
1344
+ console.log(
1345
+ paths.folder
1346
+ ? `No wizards.bot is installed in ${where}.`
1347
+ : "wizards.bot isn’t installed on this computer.",
1348
+ );
957
1349
  return;
958
1350
  }
959
1351
  let purge = false;
@@ -968,6 +1360,10 @@ async function uninstall(paths, options) {
968
1360
  throw new Refusal("--purge asks first. Run it in a terminal, or add --yes.");
969
1361
  }
970
1362
  }
1363
+ if (settings.tunnel) {
1364
+ closeTunnel(settings);
1365
+ step("Closed the tunnel", settings.url);
1366
+ }
971
1367
  for (const service of [linked, home]) {
972
1368
  const how = serviceThere(service);
973
1369
  if (how) {
@@ -975,70 +1371,251 @@ async function uninstall(paths, options) {
975
1371
  step("Stopped and removed", how);
976
1372
  }
977
1373
  }
978
- try {
979
- if (
980
- lstatSync(paths.pathLink).isSymbolicLink() &&
981
- readlinkSync(paths.pathLink) === paths.command
982
- ) {
983
- rmSync(paths.pathLink);
1374
+ if (paths.pathLink) {
1375
+ try {
1376
+ if (
1377
+ lstatSync(paths.pathLink).isSymbolicLink() &&
1378
+ readlinkSync(paths.pathLink) === paths.command
1379
+ ) {
1380
+ rmSync(paths.pathLink);
1381
+ }
1382
+ } catch {
1383
+ // no link
984
1384
  }
985
- } catch {
986
- // no link
987
1385
  }
988
1386
  rmSync(paths.command, { force: true });
989
1387
  rmSync(paths.bot, { recursive: true, force: true });
990
1388
  for (const log of [paths.log, paths.linkLog, paths.installLog]) {
991
1389
  rmSync(log, { force: true });
992
1390
  }
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 });
1391
+ step("Removed the program", tilde(paths.bot));
1392
+ if (paths.folder) {
1393
+ rmSync(paths.settings, { force: true });
1394
+ dropEmpty(paths.logs);
1395
+ } else {
1396
+ // A Node this command brought goes too, unless engenty wizards or a home in a folder uses it.
1397
+ if (settings.nodeBrought && !existsSync(paths.wizards) && !folderInstalls(paths).length) {
1398
+ for (const name of listDir(paths.tools)) {
1399
+ if (name === "node" || name.startsWith("node-v")) {
1400
+ rmSync(join(paths.tools, name), { recursive: true, force: true });
1401
+ }
998
1402
  }
999
1403
  }
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);
1404
+ for (const dir of [
1405
+ paths.tools,
1406
+ paths.logs,
1407
+ dirname(paths.command),
1408
+ paths.home,
1409
+ dirname(paths.home),
1410
+ ]) {
1411
+ dropEmpty(dir);
1412
+ }
1010
1413
  }
1011
1414
  if (purge) {
1012
1415
  rmSync(data, { recursive: true, force: true });
1013
- console.log(`\nwizards.bot is off this computer, and its data in ${tilde(data)} is deleted.`);
1416
+ }
1417
+ if (paths.folder) {
1418
+ dropEmpty(paths.folder);
1419
+ }
1420
+ if (purge) {
1421
+ console.log(`\nwizards.bot is off ${where}, and its data in ${tilde(data)} is deleted.`);
1014
1422
  } else if (existsSync(data)) {
1015
1423
  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.`,
1424
+ `\nwizards.bot is off ${where}. Your home’s data stays in ${tilde(data)}: ${hint(paths, "install")} picks it up again.`,
1017
1425
  );
1018
1426
  } else {
1019
- console.log("\nwizards.bot is off this computer.");
1427
+ console.log(`\nwizards.bot is off ${where}.`);
1020
1428
  }
1021
1429
  }
1022
1430
 
1431
+ // --- the tunnel ------------------------------------------------------------------------------
1432
+
1433
+ /** The tailscale command: on PATH, or inside the Mac app. */
1434
+ function tailscale() {
1435
+ const app = "/Applications/Tailscale.app/Contents/MacOS/Tailscale";
1436
+ return onPath("tailscale") || (process.platform === "darwin" && existsSync(app) ? app : null);
1437
+ }
1438
+
1439
+ function tailscaleJson(command, args) {
1440
+ const result = spawnSync(command, args, { encoding: "utf8", timeout: 15_000 });
1441
+ try {
1442
+ return result.status === 0 ? JSON.parse(result.stdout) : null;
1443
+ } catch {
1444
+ return null;
1445
+ }
1446
+ }
1447
+
1448
+ /** How many devices are paired with a home, from `wizards-bot status`; null when it can't say. */
1449
+ export function devicesIn(text) {
1450
+ const list = /^Devices\n((?: {2}.*\n?)*)/m.exec(text)?.[1];
1451
+ if (list === undefined) {
1452
+ return null;
1453
+ }
1454
+ const lines = list.split("\n").filter((line) => line.trim());
1455
+ return lines.length === 1 && lines[0].trim() === "none" ? 0 : lines.length;
1456
+ }
1457
+
1458
+ /**
1459
+ * The Funnel port for a home: the one that already serves it, else the first of 443, 8443 and
1460
+ * 10000 that serves nothing. `serving` is `tailscale funnel status --json`.
1461
+ */
1462
+ export function funnelPort(serving, host, port) {
1463
+ const target = new RegExp(`^(https?://)?(127\\.0\\.0\\.1|localhost):${port}/?$`);
1464
+ const web = serving?.Web || {};
1465
+ const tcp = serving?.TCP || {};
1466
+ const ours = FUNNEL_PORTS.find((https) =>
1467
+ target.test(web[`${host}:${https}`]?.Handlers?.["/"]?.Proxy || ""),
1468
+ );
1469
+ return ours || FUNNEL_PORTS.find((https) => !web[`${host}:${https}`] && !tcp[https]) || null;
1470
+ }
1471
+
1472
+ /** Whether an address answers on /health from the internet's side, by curl. */
1473
+ function reachable(url) {
1474
+ return (
1475
+ spawnSync("curl", ["-fsS", "--max-time", "10", "-o", "/dev/null", `${url}/health`]).status === 0
1476
+ );
1477
+ }
1478
+
1479
+ /** `tailscale funnel …` for a home's port, in the background (it stays after a restart). */
1480
+ const funnelArgs = (https, port) => [
1481
+ "funnel",
1482
+ "--bg",
1483
+ `--https=${https}`,
1484
+ `http://127.0.0.1:${port}`,
1485
+ ];
1486
+
1487
+ function closeTunnel(settings) {
1488
+ const command = tailscale();
1489
+ if (command && settings.tunnel?.https) {
1490
+ // Tailscale takes it off with the command that put it on, and `off` after it.
1491
+ spawnSync(command, [...funnelArgs(settings.tunnel.https, settings.port), "off"], {
1492
+ encoding: "utf8",
1493
+ timeout: 15_000,
1494
+ });
1495
+ }
1496
+ }
1497
+
1498
+ /**
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.
1503
+ */
1504
+ async function tunnel(paths, options) {
1505
+ windowsRefusal();
1506
+ const settings = installed(paths);
1507
+ if (options.off) {
1508
+ if (!settings.tunnel) {
1509
+ console.log("This home isn’t on the internet: there’s no tunnel to close.");
1510
+ return;
1511
+ }
1512
+ closeTunnel(settings);
1513
+ const { url: _url, tunnel: _tunnel, ...rest } = settings;
1514
+ saveSettings(paths, rest);
1515
+ writeCommand(paths, rest);
1516
+ await startHome(paths, rest);
1517
+ step("Closed the tunnel", settings.url);
1518
+ console.log(
1519
+ `\nThe home is off the internet. Your devices reach it on this network again, at its local address.`,
1520
+ );
1521
+ return;
1522
+ }
1523
+ if (!(await healthy(settings.port))) {
1524
+ throw new Refusal(`The home doesn’t run. Start it first: ${hint(paths, "start")}`);
1525
+ }
1526
+ const said = spawnSync(paths.command, ["status"], { encoding: "utf8", timeout: 60_000 });
1527
+ const devices = devicesIn(said.stdout || "");
1528
+ if (!devices) {
1529
+ 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.`,
1533
+ );
1534
+ }
1535
+ const command = tailscale();
1536
+ if (!command) {
1537
+ throw new Refusal(
1538
+ "The tunnel goes through Tailscale Funnel. Install Tailscale (https://tailscale.com/download), sign in, then run this again.",
1539
+ );
1540
+ }
1541
+ const state = tailscaleJson(command, ["status", "--json"]);
1542
+ const host = String(state?.Self?.DNSName || "").replace(/\.$/, "");
1543
+ if (state?.BackendState !== "Running" || !host) {
1544
+ throw new Refusal(
1545
+ `Tailscale isn’t signed in, or isn’t running. Sign in (${cyan("tailscale up")}), then run this again.`,
1546
+ );
1547
+ }
1548
+ const https = funnelPort(
1549
+ tailscaleJson(command, ["funnel", "status", "--json"]),
1550
+ host,
1551
+ settings.port,
1552
+ );
1553
+ if (!https) {
1554
+ throw new Refusal(
1555
+ `Tailscale Funnel serves on 443, 8443 and 10000 only, and all three serve something else here. ${cyan("tailscale funnel status")} shows what.`,
1556
+ );
1557
+ }
1558
+ const url = `https://${host}${https === 443 ? "" : `:${https}`}`;
1559
+ note(`Opening ${url} with Tailscale Funnel`);
1560
+ // Tailscale may ask to turn Funnel on for this computer first, with a link: that goes to you.
1561
+ const opened = spawnSync(command, funnelArgs(https, settings.port), { stdio: "inherit" });
1562
+ if (opened.status !== 0) {
1563
+ throw new Refusal(
1564
+ `tailscale funnel didn’t open ${url}. ${cyan("tailscale funnel status")} says what it serves.`,
1565
+ );
1566
+ }
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);
1576
+ }
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
+ );
1584
+ }
1585
+
1023
1586
  // --- the command line ------------------------------------------------------------------------
1024
1587
 
1025
1588
  const HELP = `${bold("wizards bot")}: wizards.bot, your own agent in a home of your own, on this computer
1026
1589
 
1027
1590
  Commands
1028
- ${cyan("wizards bot install")} install the home, start it with your computer and open its setup
1591
+ ${cyan("wizards bot install [folder]")}
1592
+ install the home, start it with your computer and open its setup
1029
1593
  ${cyan("wizards bot setup")} open the home’s setup and show a code to pair your phone
1030
1594
  ${cyan("wizards bot setup --link <address> <code>")}
1031
1595
  link this computer to your home on wizards.bot: it uses this
1032
1596
  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
1597
+ ${cyan("wizards bot status")} show the installed version, whether it runs and its address,
1598
+ and a line for each home in a folder
1599
+ ${cyan("wizards bot stop")} stop the home until you log in again or start it
1600
+ ${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)
1034
1603
  ${cyan("wizards bot update")} install the newest version and restart the home, your data is kept
1035
1604
  ${cyan("wizards bot uninstall")} take the home off this computer, your data in ~/.wizards-bot is kept
1036
1605
  (--purge deletes it too, after asking)
1037
1606
 
1607
+ A folder
1608
+ ${cyan("wizards bot install .")} or ${cyan("wizards bot install ./test01")} puts a home of its own into that
1609
+ folder: program, data, port and service, beside the other homes. Every command takes the
1610
+ folder after it (${cyan("wizards bot status ./test01")}); without one, a command means the home in
1611
+ ~/.engenty/wizards.
1612
+
1038
1613
  Options
1039
1614
  --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)
1615
+ --port <n> the port for a new home (default 4748, or the next free one; 4747 is the
1616
+ Mac app’s)
1041
1617
  --no-open don’t open the browser
1618
+ --off with tunnel: close it
1042
1619
  --yes, -y don’t ask
1043
1620
 
1044
1621
  The program goes into ~/.engenty/wizards/bot (ENGENTY_HOME moves it), the command
@@ -1046,13 +1623,15 @@ wizards-bot into ~/.local/bin. On a Mac the home runs as a LaunchAgent, on Linux
1046
1623
  systemd user service.
1047
1624
  `;
1048
1625
 
1049
- /** Reads `wizards bot <command> [options]`. */
1626
+ /** Reads `wizards bot <command> [folder] [options]`. */
1050
1627
  export function parse(argv) {
1051
1628
  const options = {
1052
1629
  command: "",
1630
+ folder: null,
1053
1631
  open: true,
1054
1632
  yes: false,
1055
1633
  purge: false,
1634
+ off: false,
1056
1635
  link: null,
1057
1636
  version: null,
1058
1637
  port: null,
@@ -1068,6 +1647,8 @@ export function parse(argv) {
1068
1647
  options.yes = true;
1069
1648
  } else if (arg === "--purge") {
1070
1649
  options.purge = true;
1650
+ } else if (arg === "--off") {
1651
+ options.off = true;
1071
1652
  } else if (arg === "--link") {
1072
1653
  options.link = [argv[i + 1], argv[i + 2]];
1073
1654
  i += 2;
@@ -1079,20 +1660,22 @@ export function parse(argv) {
1079
1660
  } else if (arg === "--port") {
1080
1661
  options.port = Number(argv[++i]);
1081
1662
  if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65535) {
1082
- throw new Refusal("--port needs a port, e.g. --port 4747");
1663
+ throw new Refusal("--port needs a port, e.g. --port 4748");
1083
1664
  }
1084
1665
  } else if (arg.startsWith("-")) {
1085
1666
  throw new Refusal(`Unknown option ${arg}. ${cyan("wizards bot --help")} lists them.`);
1086
1667
  } else if (!options.command) {
1087
1668
  options.command = arg;
1669
+ } else if (options.folder === null) {
1670
+ options.folder = arg;
1088
1671
  } else {
1089
- throw new Refusal(`One command at a time: ${options.command} or ${arg}.`);
1672
+ throw new Refusal(`One folder at a time: ${options.folder} or ${arg}.`);
1090
1673
  }
1091
1674
  }
1092
1675
  return options;
1093
1676
  }
1094
1677
 
1095
- const COMMANDS = { install, setup, status, update, uninstall };
1678
+ const COMMANDS = { install, setup, status, stop, start, tunnel, update, uninstall };
1096
1679
 
1097
1680
  /** `wizards bot …`; its exit code. */
1098
1681
  export async function main(argv, env = process.env) {
@@ -1102,13 +1685,13 @@ export async function main(argv, env = process.env) {
1102
1685
  console.log(HELP);
1103
1686
  return 0;
1104
1687
  }
1105
- const run = COMMANDS[options.command];
1106
- if (!run) {
1688
+ const command = COMMANDS[options.command];
1689
+ if (!command) {
1107
1690
  throw new Refusal(
1108
1691
  `wizards bot has no command ${options.command}. ${cyan("wizards bot --help")} lists them.`,
1109
1692
  );
1110
1693
  }
1111
- await run(layout(env), options);
1694
+ await command(layout(env, options.folder), options, env);
1112
1695
  return 0;
1113
1696
  } catch (error) {
1114
1697
  if (!(error instanceof Refusal)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wizards",
3
- "version": "0.20.3",
3
+ "version": "0.20.5",
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",