@engenty/wizards-runtime 0.20.0 → 0.20.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/apps/runtime/dist/cli/main.js +2 -0
- package/apps/runtime/dist/docs/dev/licensing.md +5 -2
- package/apps/runtime/dist/docs/user-guide/command-line.md +2 -1
- package/apps/web/dist/assets/{AboutDialog-QWzpEK8M.js → AboutDialog-CSbCideu.js} +1 -1
- package/apps/web/dist/assets/{BlockEditor-C44bI_ih.js → BlockEditor-CgjXTWly.js} +1 -1
- package/apps/web/dist/assets/{Bundle-DZyQ1FP7.js → Bundle-C0u5HUZL.js} +1 -1
- package/apps/web/dist/assets/CapabilitiesPage-M2s68GkB.js +2 -0
- package/apps/web/dist/assets/{ChangelogDialog-CdHqJV2P.js → ChangelogDialog-BG3enhF_.js} +1 -1
- package/apps/web/dist/assets/{CodeEditor-BRufUwu0.js → CodeEditor-2LyHbSre.js} +1 -1
- package/apps/web/dist/assets/{ConnectorsSection-BO6jHrYU.js → ConnectorsSection-C2ZKAYYg.js} +1 -1
- package/apps/web/dist/assets/EditorPage-DrlMr_BY.js +3 -0
- package/apps/web/dist/assets/{FlowPreview-aj58c-gH.js → FlowPreview-BXf4EKjU.js} +1 -1
- package/apps/web/dist/assets/{LangSwitch-BNkytlus.js → LangSwitch-BLB7dDce.js} +1 -1
- package/apps/web/dist/assets/{Marketplace-D3hdvrkz.js → Marketplace-B3NoH5Va.js} +2 -2
- package/apps/web/dist/assets/{NewWizardChannels-fveQcQlY.js → NewWizardChannels-5Nz8FBfp.js} +1 -1
- package/apps/web/dist/assets/{NewWizardPage-BTX1g2t1.js → NewWizardPage-DZZx49Zp.js} +1 -1
- package/apps/web/dist/assets/{OnboardingPage-DwF6KdQy.js → OnboardingPage-RawpCO9J.js} +1 -1
- package/apps/web/dist/assets/{ProtocolSection-YnJcMN9E.js → ProtocolSection-D4pst4zv.js} +1 -1
- package/apps/web/dist/assets/{PublicRunner-Bp4DxTrD.js → PublicRunner-COatyxMi.js} +1 -1
- package/apps/web/dist/assets/{ReadOnly-C6qmTD35.js → ReadOnly-CcHDevY4.js} +1 -1
- package/apps/web/dist/assets/{Results-BNuuBiwU.js → Results-DTEHveBZ.js} +1 -1
- package/apps/web/dist/assets/{RunDrawer-CMgN-XTB.js → RunDrawer-r6eFEs5D.js} +1 -1
- package/apps/web/dist/assets/SettingsPage-DmZdkZJZ.js +2 -0
- package/apps/web/dist/assets/{SetupPage-llGzMVeH.js → SetupPage-KE6tcFO2.js} +1 -1
- package/apps/web/dist/assets/{SharePage-CgQp_PT6.js → SharePage-Drntg_oj.js} +1 -1
- package/apps/web/dist/assets/{SkillEditor-ARx8QPGp.js → SkillEditor-Ca_bzmjD.js} +1 -1
- package/apps/web/dist/assets/{Skills-frfXXEcF.js → Skills-BcgxuD15.js} +1 -1
- package/apps/web/dist/assets/SpacePage-BdB2lsHC.js +2 -0
- package/apps/web/dist/assets/StudioHome-Dc4vCVDX.js +1 -0
- package/apps/web/dist/assets/TableEditor-DjIhH4Xp.js +7 -0
- package/apps/web/dist/assets/{UpdateCheck-D3QhfI5c.js → UpdateCheck-C82R62Tc.js} +2 -2
- package/apps/web/dist/assets/brand-BIT7AumL.js +2 -0
- package/apps/web/dist/assets/changelog-BqBrvuEE.js +1 -0
- package/apps/web/dist/assets/{code-editor-BLwDuQLI.js → code-editor-CufyaUFC.js} +2 -2
- package/apps/web/dist/assets/{host-C-AAp8Bz.js → host-CA1dqZWL.js} +41 -41
- package/apps/web/dist/assets/i18n-WXeVnv7i.js +55 -0
- package/apps/web/dist/assets/index-BtEYkDXF.js +102 -0
- package/apps/web/dist/assets/index-D1iL3986.css +1 -0
- package/apps/web/dist/assets/{read-aloud-DGS8mWgC.js → read-aloud-CRFt5q6k.js} +1 -1
- package/apps/web/dist/assets/{session-EIDP3Wzc.js → session-RDdtfee2.js} +1 -1
- package/apps/web/dist/assets/{theme-B46aPLtX.js → theme-23bNrOQh.js} +2 -2
- package/apps/web/dist/assets/{ui-DSgksc1H.js → ui-DkEhb2Rt.js} +1 -1
- package/apps/web/dist/assets/{useMutation-fT44ij_b.js → useMutation-BSffqL6W.js} +1 -1
- package/apps/web/dist/assets/{viewers-DvA5VsXw.js → viewers-CmGDpBjn.js} +2 -2
- package/apps/web/dist/index.html +15 -15
- package/apps/web/dist/mcp/flow.html +25 -25
- package/bin/bot.mjs +1120 -0
- package/bin/wizards.mjs +6 -0
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/plugin.json +1 -1
- package/apps/web/dist/assets/CapabilitiesPage-DAr0-gN1.js +0 -2
- package/apps/web/dist/assets/EditorPage-Bx-fKnsY.js +0 -3
- package/apps/web/dist/assets/SettingsPage-CuUB26YJ.js +0 -2
- package/apps/web/dist/assets/SpacePage-Dv6ocsc_.js +0 -2
- package/apps/web/dist/assets/StudioHome-B0bZRm1L.js +0 -1
- package/apps/web/dist/assets/TableEditor-CfzTLmJF.js +0 -7
- package/apps/web/dist/assets/brand-DKuVyYhH.js +0 -2
- package/apps/web/dist/assets/changelog-Db3nvWao.js +0 -1
- package/apps/web/dist/assets/i18n-Dyi0kvaA.js +0 -55
- package/apps/web/dist/assets/index-CduFlFCp.css +0 -1
- package/apps/web/dist/assets/index-CtE0rJEL.js +0 -102
package/bin/bot.mjs
ADDED
|
@@ -0,0 +1,1120 @@
|
|
|
1
|
+
// `wizards bot`: wizards.bot, a home for your own agent, on this computer. The home is the program
|
|
2
|
+
// of github.com/engenty/wizards-bot; this installs a release of it, runs it as a service of yours
|
|
3
|
+
// and pairs your devices with it (docs/hosted.md of that repo, "Contract", points 2 and 9).
|
|
4
|
+
//
|
|
5
|
+
// It lives beside the launcher, not in the runtime: `npx wizards bot install` works without
|
|
6
|
+
// engenty wizards, and the runtime carries the same file, so its `wizards bot` is this one too.
|
|
7
|
+
// Like bin/wizards.mjs it needs nothing but Node, curl and tar, and runs on an older Node: the
|
|
8
|
+
// home gets a Node of its own when this one is too old.
|
|
9
|
+
//
|
|
10
|
+
// ~/.engenty/wizards/bot/<version>/ the release, unpacked and installed with npm
|
|
11
|
+
// ~/.engenty/wizards/bot/current names the version that runs; the one before stays
|
|
12
|
+
// ~/.engenty/wizards/bot/bot.json the port and the Node it runs with
|
|
13
|
+
// ~/.engenty/wizards/bin/wizards-bot the command, linked into ~/.local/bin
|
|
14
|
+
// ~/.wizards-bot/ the home's data (WIZARDS_BOT_DATA moves it)
|
|
15
|
+
//
|
|
16
|
+
// For tests: WIZARDS_BOT_TARBALL (a path or an address of a tarball instead of the release's),
|
|
17
|
+
// ENGENTY_HOME, WIZARDS_BOT_DATA.
|
|
18
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
19
|
+
import { createHash } from "node:crypto";
|
|
20
|
+
import {
|
|
21
|
+
chmodSync,
|
|
22
|
+
copyFileSync,
|
|
23
|
+
existsSync,
|
|
24
|
+
lstatSync,
|
|
25
|
+
mkdirSync,
|
|
26
|
+
mkdtempSync,
|
|
27
|
+
readdirSync,
|
|
28
|
+
readFileSync,
|
|
29
|
+
readlinkSync,
|
|
30
|
+
renameSync,
|
|
31
|
+
rmdirSync,
|
|
32
|
+
rmSync,
|
|
33
|
+
statSync,
|
|
34
|
+
symlinkSync,
|
|
35
|
+
writeFileSync,
|
|
36
|
+
} from "node:fs";
|
|
37
|
+
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";
|
|
41
|
+
import { createInterface } from "node:readline";
|
|
42
|
+
|
|
43
|
+
/** The Node install.sh brings; the home gets the same where it needs one. */
|
|
44
|
+
export const NODE_VERSION = "26.12.0";
|
|
45
|
+
const REPO = "engenty/wizards-bot";
|
|
46
|
+
export const PORT = 4747;
|
|
47
|
+
export const LABEL = "com.engenty.wizards.bot";
|
|
48
|
+
export const LINK_LABEL = "com.engenty.wizards.bot.link";
|
|
49
|
+
export const UNIT = "wizards-bot.service";
|
|
50
|
+
export const LINK_UNIT = "wizards-bot-link.service";
|
|
51
|
+
/** How long the home may take to answer on /health after it starts. */
|
|
52
|
+
const HEALTH_WAIT = 90_000;
|
|
53
|
+
|
|
54
|
+
const tty = process.stdout.isTTY && !process.env.NO_COLOR && process.env.TERM !== "dumb";
|
|
55
|
+
const paint = (code) => (text) => (tty ? `\u001b[${code}m${text}\u001b[0m` : text);
|
|
56
|
+
const cyan = paint(36);
|
|
57
|
+
const dim = paint(2);
|
|
58
|
+
const green = paint(32);
|
|
59
|
+
const red = paint(31);
|
|
60
|
+
const bold = paint(1);
|
|
61
|
+
|
|
62
|
+
/** Something went wrong in a way the person can act on: its message is all they see. */
|
|
63
|
+
class Refusal extends Error {}
|
|
64
|
+
|
|
65
|
+
/** Where everything goes; ENGENTY_HOME and WIZARDS_BOT_DATA move it, as for the home itself. */
|
|
66
|
+
export function layout(env = process.env) {
|
|
67
|
+
const user = homedir();
|
|
68
|
+
const home = join(resolve((env.ENGENTY_HOME || "").trim() || join(user, ".engenty")), "wizards");
|
|
69
|
+
const bot = join(home, "bot");
|
|
70
|
+
const config = env.XDG_CONFIG_HOME || join(user, ".config");
|
|
71
|
+
return {
|
|
72
|
+
user,
|
|
73
|
+
home,
|
|
74
|
+
bot,
|
|
75
|
+
current: join(bot, "current"),
|
|
76
|
+
settings: join(bot, "bot.json"),
|
|
77
|
+
command: join(home, "bin", "wizards-bot"),
|
|
78
|
+
wizards: join(home, "bin", "wizards"),
|
|
79
|
+
pathLink: join(user, ".local", "bin", "wizards-bot"),
|
|
80
|
+
tools: join(home, "tools"),
|
|
81
|
+
logs: join(home, "logs"),
|
|
82
|
+
log: join(home, "logs", "bot.log"),
|
|
83
|
+
linkLog: join(home, "logs", "bot-link.log"),
|
|
84
|
+
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),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const tilde = (path) =>
|
|
94
|
+
path === homedir() || path.startsWith(homedir() + sep)
|
|
95
|
+
? `~${path.slice(homedir().length)}`
|
|
96
|
+
: path;
|
|
97
|
+
|
|
98
|
+
function readJson(file) {
|
|
99
|
+
try {
|
|
100
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The installed version: the one `current` names, or null. */
|
|
107
|
+
export function installedVersion(paths) {
|
|
108
|
+
try {
|
|
109
|
+
return readJson(join(paths.bot, readlinkSync(paths.current), "package.json"))?.version || null;
|
|
110
|
+
} catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Whether a Node version runs the home: 24.11 or newer. */
|
|
116
|
+
export function newEnough(version) {
|
|
117
|
+
const [major, minor] = String(version).replace(/^v/, "").split(".").map(Number);
|
|
118
|
+
return major > 24 || (major === 24 && minor >= 11);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Whether version a is older than b, by major, minor and patch. */
|
|
122
|
+
export function older(a, b) {
|
|
123
|
+
const pa = a.split(/[.+-]/).map(Number);
|
|
124
|
+
const pb = b.split(/[.+-]/).map(Number);
|
|
125
|
+
for (let i = 0; i < 3; i++) {
|
|
126
|
+
if ((pa[i] || 0) !== (pb[i] || 0)) {
|
|
127
|
+
return (pa[i] || 0) < (pb[i] || 0);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** `ada`, `ada.wizards.bot` or a whole address, as the address of a home. */
|
|
134
|
+
export function homeAddress(text) {
|
|
135
|
+
const address = String(text).trim().replace(/\/+$/, "");
|
|
136
|
+
if (/^https?:\/\//.test(address)) {
|
|
137
|
+
return address;
|
|
138
|
+
}
|
|
139
|
+
return address.includes(".") || address.includes(":")
|
|
140
|
+
? `https://${address}`
|
|
141
|
+
: `https://${address}.wizards.bot`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The PATH without what npm put in for running this command. */
|
|
145
|
+
function cleanPath(env = process.env) {
|
|
146
|
+
return (env.PATH || "")
|
|
147
|
+
.split(delimiter)
|
|
148
|
+
.filter((dir) => dir && !/[\\/](node_modules[\\/]\.bin|node-gyp-bin)$/.test(dir))
|
|
149
|
+
.join(delimiter);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function onPath(name) {
|
|
153
|
+
for (const dir of cleanPath().split(delimiter)) {
|
|
154
|
+
const file = join(dir, name);
|
|
155
|
+
if (existsSync(file)) {
|
|
156
|
+
return file;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Runs a command; its output goes to the install log. Throws with the log's end when it fails. */
|
|
163
|
+
function logged(paths, file, args, options = {}) {
|
|
164
|
+
mkdirSync(paths.logs, { recursive: true });
|
|
165
|
+
writeFileSync(paths.installLog, `\n$ ${file} ${args.join(" ")}\n`, { flag: "a" });
|
|
166
|
+
const result = spawnSync(file, args, { encoding: "utf8", ...options });
|
|
167
|
+
writeFileSync(paths.installLog, `${result.stdout || ""}${result.stderr || ""}`, { flag: "a" });
|
|
168
|
+
if (result.status !== 0) {
|
|
169
|
+
const tail = `${result.stdout || ""}${result.stderr || ""}${result.error?.message || ""}`
|
|
170
|
+
.trim()
|
|
171
|
+
.split("\n")
|
|
172
|
+
.slice(-12)
|
|
173
|
+
.map((line) => ` ${line}`)
|
|
174
|
+
.join("\n");
|
|
175
|
+
throw new Refusal(
|
|
176
|
+
`${tail ? `${dim(tail)}\n` : ""}${file.split(sep).pop()} ${args[0]} failed. The whole log: ${tilde(paths.installLog)}`,
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
return result.stdout || "";
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function step(text, detail) {
|
|
183
|
+
console.log(`${green("◇")} ${text}${detail ? ` ${dim(detail)}` : ""}`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function note(text) {
|
|
187
|
+
console.log(`${dim("…")} ${text}`);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// --- the release -----------------------------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
/** The release to install: its version, the tarball's address and its checksum, if GitHub has one. */
|
|
193
|
+
export function findRelease(version) {
|
|
194
|
+
const tag = version ? `tags/v${version.replace(/^v/, "")}` : "latest";
|
|
195
|
+
const url = `https://api.github.com/repos/${REPO}/releases/${tag}`;
|
|
196
|
+
const result = spawnSync(
|
|
197
|
+
"curl",
|
|
198
|
+
["-fsSL", "-H", "Accept: application/vnd.github+json", "-H", "User-Agent: wizards", url],
|
|
199
|
+
{ encoding: "utf8" },
|
|
200
|
+
);
|
|
201
|
+
const release = result.status === 0 ? JSON.parse(result.stdout) : null;
|
|
202
|
+
if (!release?.tag_name) {
|
|
203
|
+
throw new Refusal(
|
|
204
|
+
version
|
|
205
|
+
? `wizards.bot ${version} wasn’t found at https://github.com/${REPO}/releases.`
|
|
206
|
+
: `No release of wizards.bot was found at https://github.com/${REPO}/releases.`,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
const found = release.tag_name.replace(/^v/, "");
|
|
210
|
+
const name = `wizards-bot-${found}.tgz`;
|
|
211
|
+
const asset = (release.assets || []).find((item) => item.name === name);
|
|
212
|
+
if (!asset) {
|
|
213
|
+
throw new Refusal(`The release ${found} of wizards.bot has no ${name} yet.`);
|
|
214
|
+
}
|
|
215
|
+
const digest = typeof asset.digest === "string" ? asset.digest : "";
|
|
216
|
+
return {
|
|
217
|
+
version: found,
|
|
218
|
+
url: asset.browser_download_url,
|
|
219
|
+
sha256: digest.startsWith("sha256:") ? digest.slice(7) : null,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function sha256(file) {
|
|
224
|
+
return createHash("sha256").update(readFileSync(file)).digest("hex");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Copies or downloads a tarball to `to`, checking its checksum where there is one. */
|
|
228
|
+
function fetchFile(paths, from, to, checksum) {
|
|
229
|
+
if (/^https?:\/\//.test(from)) {
|
|
230
|
+
logged(paths, "curl", ["-fsSL", "-o", to, from]);
|
|
231
|
+
} else {
|
|
232
|
+
copyFileSync(resolve(from), to);
|
|
233
|
+
}
|
|
234
|
+
if (checksum && sha256(to) !== checksum) {
|
|
235
|
+
throw new Refusal(`The download of ${from} doesn’t match its checksum.`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// --- Node ------------------------------------------------------------------------------------
|
|
240
|
+
|
|
241
|
+
function nodeVersion(file) {
|
|
242
|
+
const result = spawnSync(file, ["--version"], { encoding: "utf8" });
|
|
243
|
+
return result.status === 0 ? result.stdout.trim() : null;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* The Node the home runs with: the one the wizards installer brought, yours if it is 24.11 or
|
|
248
|
+
* newer, or else one of its own, as the installer gets it (into the same place, so the two share
|
|
249
|
+
* it). `brought` says this command downloaded it.
|
|
250
|
+
*/
|
|
251
|
+
function findNode(paths) {
|
|
252
|
+
const ours = join(paths.tools, "node", "bin", "node");
|
|
253
|
+
for (const file of [ours, onPath("node")]) {
|
|
254
|
+
const version = file && existsSync(file) ? nodeVersion(file) : null;
|
|
255
|
+
if (version && newEnough(version)) {
|
|
256
|
+
return { node: file, brought: false };
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
downloadNode(paths);
|
|
260
|
+
return { node: ours, brought: true };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function machine() {
|
|
264
|
+
if (process.platform !== "darwin" && process.platform !== "linux") {
|
|
265
|
+
throw new Refusal(`${process.platform} isn’t supported: macOS and Linux are.`);
|
|
266
|
+
}
|
|
267
|
+
let arch = process.arch;
|
|
268
|
+
// A terminal under Rosetta says x64 on a Mac with Apple silicon.
|
|
269
|
+
if (
|
|
270
|
+
process.platform === "darwin" &&
|
|
271
|
+
spawnSync("sysctl", ["-n", "sysctl.proc_translated"], { encoding: "utf8" }).stdout?.trim() ===
|
|
272
|
+
"1"
|
|
273
|
+
) {
|
|
274
|
+
arch = "arm64";
|
|
275
|
+
}
|
|
276
|
+
if (arch !== "arm64" && arch !== "x64") {
|
|
277
|
+
throw new Refusal(`${arch} isn’t supported: arm64 and x64 are.`);
|
|
278
|
+
}
|
|
279
|
+
return `${process.platform}-${arch}`;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function downloadNode(paths) {
|
|
283
|
+
const name = `node-v${NODE_VERSION}-${machine()}`;
|
|
284
|
+
const dist = `https://nodejs.org/dist/v${NODE_VERSION}`;
|
|
285
|
+
note(`Downloading Node ${NODE_VERSION} for the home`);
|
|
286
|
+
mkdirSync(paths.tools, { recursive: true });
|
|
287
|
+
const tmp = mkdtempSync(join(paths.tools, ".node."));
|
|
288
|
+
try {
|
|
289
|
+
const tarball = join(tmp, "node.tar.gz");
|
|
290
|
+
logged(paths, "curl", ["-fsSL", "-o", tarball, `${dist}/${name}.tar.gz`]);
|
|
291
|
+
const sums = logged(paths, "curl", ["-fsSL", `${dist}/SHASUMS256.txt`]);
|
|
292
|
+
const expected = sums
|
|
293
|
+
.split("\n")
|
|
294
|
+
.map((line) => line.trim().split(/\s+/))
|
|
295
|
+
.find(([, file]) => file === `${name}.tar.gz`)?.[0];
|
|
296
|
+
if (!expected || expected !== sha256(tarball)) {
|
|
297
|
+
throw new Refusal("The Node download doesn’t match its checksum from nodejs.org.");
|
|
298
|
+
}
|
|
299
|
+
mkdirSync(join(tmp, "node"));
|
|
300
|
+
logged(paths, "tar", ["-xzf", tarball, "-C", join(tmp, "node"), "--strip-components", "1"]);
|
|
301
|
+
// The headers are for compiling addons, which nothing here does.
|
|
302
|
+
rmSync(join(tmp, "node", "include"), { recursive: true, force: true });
|
|
303
|
+
const dir = join(paths.tools, `node-v${NODE_VERSION}`);
|
|
304
|
+
rmSync(dir, { recursive: true, force: true });
|
|
305
|
+
renameSync(join(tmp, "node"), dir);
|
|
306
|
+
pointTo(join(paths.tools, "node"), `node-v${NODE_VERSION}`);
|
|
307
|
+
} finally {
|
|
308
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
309
|
+
}
|
|
310
|
+
step(
|
|
311
|
+
`Node ${NODE_VERSION}`,
|
|
312
|
+
`${tilde(join(paths.tools, "node"))}, checksum from nodejs.org matches`,
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** A symlink at `link` to `target`, replaced in one move. */
|
|
317
|
+
function pointTo(link, target) {
|
|
318
|
+
const next = `${link}.next`;
|
|
319
|
+
rmSync(next, { force: true });
|
|
320
|
+
symlinkSync(target, next);
|
|
321
|
+
renameSync(next, link);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// --- the program -----------------------------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
/** The folder in an unpacked tarball that holds package.json: its top, or `package/` (npm pack). */
|
|
327
|
+
function packageRoot(dir) {
|
|
328
|
+
if (existsSync(join(dir, "package.json"))) {
|
|
329
|
+
return dir;
|
|
330
|
+
}
|
|
331
|
+
const entries = readdirSync(dir);
|
|
332
|
+
const only = entries.length === 1 ? join(dir, entries[0]) : null;
|
|
333
|
+
if (only && existsSync(join(only, "package.json"))) {
|
|
334
|
+
return only;
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** The home's command in its package.json, relative to it. */
|
|
340
|
+
function binOf(manifest) {
|
|
341
|
+
const bin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.["wizards-bot"];
|
|
342
|
+
if (!bin) {
|
|
343
|
+
throw new Refusal("The tarball’s package.json names no wizards-bot command.");
|
|
344
|
+
}
|
|
345
|
+
return bin;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Unpacks a tarball into bot/<version> and installs what it depends on with npm. A version is
|
|
350
|
+
* either all there or not at all: it is put together in a staging folder first. `current` names
|
|
351
|
+
* it afterwards; this version and the one before stay, older ones go.
|
|
352
|
+
*/
|
|
353
|
+
function installProgram(paths, source, node) {
|
|
354
|
+
mkdirSync(paths.bot, { recursive: true });
|
|
355
|
+
// What an install that was stopped halfway left behind.
|
|
356
|
+
for (const name of readdirSync(paths.bot)) {
|
|
357
|
+
if (name.startsWith(".staging-")) {
|
|
358
|
+
rmSync(join(paths.bot, name), { recursive: true, force: true });
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
const stage = mkdtempSync(join(paths.bot, ".staging-"));
|
|
362
|
+
try {
|
|
363
|
+
const tarball = join(stage, "wizards-bot.tgz");
|
|
364
|
+
note(`${/^https?:\/\//.test(source.from) ? "Downloading" : "Copying"} ${source.label}`);
|
|
365
|
+
fetchFile(paths, source.from, tarball, source.sha256);
|
|
366
|
+
mkdirSync(join(stage, "unpacked"));
|
|
367
|
+
logged(paths, "tar", ["-xzf", tarball, "-C", join(stage, "unpacked")]);
|
|
368
|
+
const root = packageRoot(join(stage, "unpacked"));
|
|
369
|
+
if (!root) {
|
|
370
|
+
throw new Refusal(`${source.label} holds no package.json.`);
|
|
371
|
+
}
|
|
372
|
+
const manifest = readJson(join(root, "package.json"));
|
|
373
|
+
const version = manifest?.version;
|
|
374
|
+
if (!version) {
|
|
375
|
+
throw new Refusal(`${source.label} has no version in its package.json.`);
|
|
376
|
+
}
|
|
377
|
+
const bin = binOf(manifest);
|
|
378
|
+
const npm = join(dirname(node), "npm");
|
|
379
|
+
if (!existsSync(npm)) {
|
|
380
|
+
throw new Refusal(`npm wasn’t found next to ${tilde(node)}.`);
|
|
381
|
+
}
|
|
382
|
+
note(`Installing wizards.bot ${version} with npm (about a minute)`);
|
|
383
|
+
logged(paths, npm, ["install", "--omit=dev", "--no-audit", "--no-fund", "--loglevel=error"], {
|
|
384
|
+
cwd: root,
|
|
385
|
+
env: { ...process.env, PATH: `${dirname(node)}${delimiter}${cleanPath()}` },
|
|
386
|
+
});
|
|
387
|
+
if (!existsSync(join(root, bin))) {
|
|
388
|
+
throw new Refusal(`${source.label} has no ${bin}, the command its package.json names.`);
|
|
389
|
+
}
|
|
390
|
+
const dir = join(paths.bot, version);
|
|
391
|
+
const previous = installedVersion(paths);
|
|
392
|
+
// The version that is there already steps aside in one move and goes once the new one is in.
|
|
393
|
+
const aside = existsSync(dir) ? join(stage, "aside") : null;
|
|
394
|
+
if (aside) {
|
|
395
|
+
renameSync(dir, aside);
|
|
396
|
+
}
|
|
397
|
+
renameSync(root, dir);
|
|
398
|
+
pointTo(paths.current, version);
|
|
399
|
+
for (const name of readdirSync(paths.bot)) {
|
|
400
|
+
if (/^\d/.test(name) && name !== version && name !== previous) {
|
|
401
|
+
rmSync(join(paths.bot, name), { recursive: true, force: true });
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
step(`wizards.bot ${version}`, tilde(dir));
|
|
405
|
+
return { version, bin };
|
|
406
|
+
} finally {
|
|
407
|
+
rmSync(stage, { recursive: true, force: true });
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const quote = (text) => `'${String(text).replaceAll("'", "'\\''")}'`;
|
|
412
|
+
|
|
413
|
+
/** The command `wizards-bot`: the home's own CLI with its Node, its port and its data folder. */
|
|
414
|
+
export function commandText(paths, settings) {
|
|
415
|
+
return [
|
|
416
|
+
"#!/bin/sh",
|
|
417
|
+
"# wizards.bot, written by `wizards bot install`; `wizards bot update` writes it again.",
|
|
418
|
+
`export WIZARDS_BOT_PORT="\${WIZARDS_BOT_PORT:-${settings.port}}"`,
|
|
419
|
+
`export WIZARDS_BOT_DATA="\${WIZARDS_BOT_DATA:-${settings.data.replaceAll('"', '\\"')}}"`,
|
|
420
|
+
`exec ${quote(settings.node)} ${quote(join(paths.current, settings.bin))} "$@"`,
|
|
421
|
+
"",
|
|
422
|
+
].join("\n");
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function writeCommand(paths, settings) {
|
|
426
|
+
mkdirSync(dirname(paths.command), { recursive: true });
|
|
427
|
+
writeFileSync(paths.command, commandText(paths, settings));
|
|
428
|
+
chmodSync(paths.command, 0o755);
|
|
429
|
+
mkdirSync(dirname(paths.pathLink), { recursive: true });
|
|
430
|
+
let there = null;
|
|
431
|
+
try {
|
|
432
|
+
there = lstatSync(paths.pathLink);
|
|
433
|
+
} catch {
|
|
434
|
+
// nothing of that name yet
|
|
435
|
+
}
|
|
436
|
+
// Something else of that name is not ours to replace.
|
|
437
|
+
if (there && !there.isSymbolicLink()) {
|
|
438
|
+
step(
|
|
439
|
+
"Command",
|
|
440
|
+
`${tilde(paths.command)} (${tilde(paths.pathLink)} exists and was left as it is)`,
|
|
441
|
+
);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
pointTo(paths.pathLink, paths.command);
|
|
445
|
+
step("Command", tilde(paths.pathLink));
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function saveSettings(paths, settings) {
|
|
449
|
+
writeFileSync(paths.settings, `${JSON.stringify(settings, null, 2)}\n`);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// --- the service -----------------------------------------------------------------------------
|
|
453
|
+
|
|
454
|
+
const xml = (text) =>
|
|
455
|
+
String(text).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
456
|
+
|
|
457
|
+
/** The environment a service gets: your PATH (for Ollama, Claude and Codex) and your home folder. */
|
|
458
|
+
function serviceEnv(paths) {
|
|
459
|
+
return { PATH: cleanPath(), HOME: paths.user };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** The LaunchAgent: `wizards-bot <args>`, started at login and again when it fails. */
|
|
463
|
+
export function agentText(paths, label, args, log) {
|
|
464
|
+
const env = serviceEnv(paths);
|
|
465
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
466
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
467
|
+
<plist version="1.0">
|
|
468
|
+
<dict>
|
|
469
|
+
<key>Label</key>
|
|
470
|
+
<string>${xml(label)}</string>
|
|
471
|
+
<key>ProgramArguments</key>
|
|
472
|
+
<array>
|
|
473
|
+
${[paths.command, ...args].map((arg) => ` <string>${xml(arg)}</string>\n`).join("")} </array>
|
|
474
|
+
<key>EnvironmentVariables</key>
|
|
475
|
+
<dict>
|
|
476
|
+
${Object.entries(env)
|
|
477
|
+
.map(([key, value]) => ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>\n`)
|
|
478
|
+
.join("")} </dict>
|
|
479
|
+
<key>RunAtLoad</key>
|
|
480
|
+
<true/>
|
|
481
|
+
<key>KeepAlive</key>
|
|
482
|
+
<dict>
|
|
483
|
+
<key>SuccessfulExit</key>
|
|
484
|
+
<false/>
|
|
485
|
+
</dict>
|
|
486
|
+
<key>StandardOutPath</key>
|
|
487
|
+
<string>${xml(log)}</string>
|
|
488
|
+
<key>StandardErrorPath</key>
|
|
489
|
+
<string>${xml(log)}</string>
|
|
490
|
+
</dict>
|
|
491
|
+
</plist>
|
|
492
|
+
`;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/** The systemd user service: `wizards-bot <args>`, started at login and again when it fails. */
|
|
496
|
+
export function unitText(paths, description, args) {
|
|
497
|
+
const quoted = (text) => `"${String(text).replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
|
|
498
|
+
const env = serviceEnv(paths);
|
|
499
|
+
return [
|
|
500
|
+
"[Unit]",
|
|
501
|
+
`Description=${description}`,
|
|
502
|
+
`Documentation=https://github.com/${REPO}`,
|
|
503
|
+
"",
|
|
504
|
+
"[Service]",
|
|
505
|
+
`ExecStart=${[paths.command, ...args].map(quoted).join(" ")}`,
|
|
506
|
+
...Object.entries(env).map(([key, value]) => `Environment=${quoted(`${key}=${value}`)}`),
|
|
507
|
+
"Restart=on-failure",
|
|
508
|
+
"RestartSec=5",
|
|
509
|
+
"",
|
|
510
|
+
"[Install]",
|
|
511
|
+
"WantedBy=default.target",
|
|
512
|
+
"",
|
|
513
|
+
].join("\n");
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const uid = () => (process.getuid ? process.getuid() : 0);
|
|
517
|
+
|
|
518
|
+
function systemctl(args) {
|
|
519
|
+
return spawnSync("systemctl", ["--user", ...args], { encoding: "utf8" });
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function systemdHere() {
|
|
523
|
+
return Boolean(onPath("systemctl")) && systemctl(["show-environment"]).status === 0;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** The two services: the home, and the link to a home elsewhere. */
|
|
527
|
+
function services(paths) {
|
|
528
|
+
return {
|
|
529
|
+
home: {
|
|
530
|
+
label: LABEL,
|
|
531
|
+
unit: UNIT,
|
|
532
|
+
agent: paths.agent,
|
|
533
|
+
unitFile: paths.unit,
|
|
534
|
+
args: ["start"],
|
|
535
|
+
log: paths.log,
|
|
536
|
+
description: "wizards.bot, your home",
|
|
537
|
+
},
|
|
538
|
+
link: {
|
|
539
|
+
label: LINK_LABEL,
|
|
540
|
+
unit: LINK_UNIT,
|
|
541
|
+
agent: paths.linkAgent,
|
|
542
|
+
unitFile: paths.linkUnit,
|
|
543
|
+
args: ["link"],
|
|
544
|
+
log: paths.linkLog,
|
|
545
|
+
description: "wizards.bot, this computer’s models for your home",
|
|
546
|
+
},
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** Takes a LaunchAgent out of launchd and waits until it is gone. */
|
|
551
|
+
async function bootout(service) {
|
|
552
|
+
const target = `gui/${uid()}/${service.label}`;
|
|
553
|
+
spawnSync("launchctl", ["bootout", target], { encoding: "utf8" });
|
|
554
|
+
for (let tries = 0; tries < 50; tries++) {
|
|
555
|
+
if (spawnSync("launchctl", ["print", target], { encoding: "utf8" }).status !== 0) {
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
await pause(100);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** Writes a service and starts it, or starts it again. False where nothing can run it here. */
|
|
563
|
+
async function startService(paths, service) {
|
|
564
|
+
mkdirSync(paths.logs, { recursive: true });
|
|
565
|
+
if (process.platform === "darwin") {
|
|
566
|
+
mkdirSync(dirname(service.agent), { recursive: true });
|
|
567
|
+
writeFileSync(service.agent, agentText(paths, service.label, service.args, service.log));
|
|
568
|
+
await bootout(service);
|
|
569
|
+
// launchd may still be letting the old one go: it refuses with error 5 meanwhile.
|
|
570
|
+
let result = null;
|
|
571
|
+
for (let tries = 0; tries < 10; tries++) {
|
|
572
|
+
result = spawnSync("launchctl", ["bootstrap", `gui/${uid()}`, service.agent], {
|
|
573
|
+
encoding: "utf8",
|
|
574
|
+
});
|
|
575
|
+
if (result.status === 0) {
|
|
576
|
+
break;
|
|
577
|
+
}
|
|
578
|
+
await pause(500);
|
|
579
|
+
}
|
|
580
|
+
if (result.status !== 0) {
|
|
581
|
+
throw new Refusal(`launchctl couldn’t start ${service.label}: ${result.stderr.trim()}`);
|
|
582
|
+
}
|
|
583
|
+
return true;
|
|
584
|
+
}
|
|
585
|
+
if (!systemdHere()) {
|
|
586
|
+
return false;
|
|
587
|
+
}
|
|
588
|
+
mkdirSync(dirname(service.unitFile), { recursive: true });
|
|
589
|
+
writeFileSync(service.unitFile, unitText(paths, service.description, service.args));
|
|
590
|
+
systemctl(["daemon-reload"]);
|
|
591
|
+
const result = systemctl(["enable", service.unit]);
|
|
592
|
+
const restart = systemctl(["restart", service.unit]);
|
|
593
|
+
if (result.status !== 0 || restart.status !== 0) {
|
|
594
|
+
throw new Refusal(
|
|
595
|
+
`systemctl couldn’t start ${service.unit}: ${`${result.stderr}${restart.stderr}`.trim()}`,
|
|
596
|
+
);
|
|
597
|
+
}
|
|
598
|
+
return true;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** Stops a service and takes it away. */
|
|
602
|
+
async function removeService(service) {
|
|
603
|
+
if (process.platform === "darwin") {
|
|
604
|
+
await bootout(service);
|
|
605
|
+
rmSync(service.agent, { force: true });
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
if (existsSync(service.unitFile)) {
|
|
609
|
+
systemctl(["disable", "--now", service.unit]);
|
|
610
|
+
rmSync(service.unitFile, { force: true });
|
|
611
|
+
systemctl(["daemon-reload"]);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/** Stops a service and leaves it there. */
|
|
616
|
+
async function stopService(service) {
|
|
617
|
+
if (process.platform === "darwin") {
|
|
618
|
+
await bootout(service);
|
|
619
|
+
} else if (existsSync(service.unitFile)) {
|
|
620
|
+
systemctl(["stop", service.unit]);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** Whether a service is there, and how it is called. */
|
|
625
|
+
function serviceThere(service) {
|
|
626
|
+
if (process.platform === "darwin") {
|
|
627
|
+
return existsSync(service.agent) ? `a LaunchAgent, ${service.label}` : null;
|
|
628
|
+
}
|
|
629
|
+
return existsSync(service.unitFile) ? `a systemd user service, ${service.unit}` : null;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/** Whether the service runs now. */
|
|
633
|
+
function serviceRuns(service) {
|
|
634
|
+
if (process.platform === "darwin") {
|
|
635
|
+
const result = spawnSync("launchctl", ["print", `gui/${uid()}/${service.label}`], {
|
|
636
|
+
encoding: "utf8",
|
|
637
|
+
});
|
|
638
|
+
return result.status === 0 && /\bstate = running\b/.test(result.stdout);
|
|
639
|
+
}
|
|
640
|
+
return systemctl(["is-active", service.unit]).stdout?.trim() === "active";
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// --- the port and the home's answer ----------------------------------------------------------
|
|
644
|
+
|
|
645
|
+
function portFree(port) {
|
|
646
|
+
return new Promise((done) => {
|
|
647
|
+
const server = createServer();
|
|
648
|
+
server.once("error", () => done(false));
|
|
649
|
+
server.listen({ port, host: "0.0.0.0" }, () => server.close(() => done(true)));
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** The first free port from `start` on. */
|
|
654
|
+
export async function freePort(start) {
|
|
655
|
+
for (let port = start; port < start + 100; port++) {
|
|
656
|
+
if (await portFree(port)) {
|
|
657
|
+
return port;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
throw new Refusal(`No port from ${start} to ${start + 99} is free.`);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/** Whether the home answers on /health with 200. */
|
|
664
|
+
export function healthy(port) {
|
|
665
|
+
return new Promise((done) => {
|
|
666
|
+
const req = request({ host: "127.0.0.1", port, path: "/health", timeout: 2000 }, (res) => {
|
|
667
|
+
res.resume();
|
|
668
|
+
done(res.statusCode === 200);
|
|
669
|
+
});
|
|
670
|
+
req.on("error", () => done(false));
|
|
671
|
+
req.on("timeout", () => {
|
|
672
|
+
req.destroy();
|
|
673
|
+
done(false);
|
|
674
|
+
});
|
|
675
|
+
req.end();
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
const pause = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
680
|
+
|
|
681
|
+
async function waitForHealth(paths, port) {
|
|
682
|
+
const until = Date.now() + HEALTH_WAIT;
|
|
683
|
+
while (Date.now() < until) {
|
|
684
|
+
if (await healthy(port)) {
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
await pause(500);
|
|
688
|
+
}
|
|
689
|
+
throw new Refusal(
|
|
690
|
+
`The home didn’t answer at http://localhost:${port}/health within ${HEALTH_WAIT / 1000} seconds. Its log: ${tilde(paths.log)}`,
|
|
691
|
+
);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
function openBrowser(url) {
|
|
695
|
+
const opener = process.platform === "darwin" ? "open" : "xdg-open";
|
|
696
|
+
if (!onPath(opener)) {
|
|
697
|
+
return false;
|
|
698
|
+
}
|
|
699
|
+
const child = spawn(opener, [url], { stdio: "ignore", detached: true });
|
|
700
|
+
child.on("error", () => undefined);
|
|
701
|
+
child.unref();
|
|
702
|
+
return true;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// --- the commands ----------------------------------------------------------------------------
|
|
706
|
+
|
|
707
|
+
function windowsRefusal() {
|
|
708
|
+
if (process.platform === "win32") {
|
|
709
|
+
throw new Refusal(
|
|
710
|
+
"wizards.bot doesn’t install on Windows yet. It runs on macOS and Linux, and on Windows in WSL.",
|
|
711
|
+
);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function notInstalled() {
|
|
716
|
+
return new Refusal(
|
|
717
|
+
`wizards.bot isn’t installed on this computer. To install it: ${cyan("wizards bot install")}`,
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** What to install: the tarball WIZARDS_BOT_TARBALL names, or a release. */
|
|
722
|
+
function source(version) {
|
|
723
|
+
const tarball = (process.env.WIZARDS_BOT_TARBALL || "").trim();
|
|
724
|
+
if (tarball) {
|
|
725
|
+
return { from: tarball, label: /^https?:/.test(tarball) ? tarball : tilde(resolve(tarball)) };
|
|
726
|
+
}
|
|
727
|
+
const release = findRelease(version);
|
|
728
|
+
return {
|
|
729
|
+
from: release.url,
|
|
730
|
+
label: `wizards.bot ${release.version}`,
|
|
731
|
+
version: release.version,
|
|
732
|
+
sha256: release.sha256,
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* 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.
|
|
739
|
+
*/
|
|
740
|
+
async function put(paths, options, from) {
|
|
741
|
+
const saved = readJson(paths.settings) || {};
|
|
742
|
+
const home = services(paths).home;
|
|
743
|
+
const { node, brought } = findNode(paths);
|
|
744
|
+
const { version, bin } = installProgram(paths, from, node);
|
|
745
|
+
// The home that runs gives its port free first.
|
|
746
|
+
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);
|
|
752
|
+
const settings = {
|
|
753
|
+
version,
|
|
754
|
+
bin,
|
|
755
|
+
port,
|
|
756
|
+
node,
|
|
757
|
+
data: paths.data,
|
|
758
|
+
// A Node this command downloaded goes with the home, unless engenty wizards uses it too.
|
|
759
|
+
nodeBrought:
|
|
760
|
+
Boolean(saved.nodeBrought || brought) && node === join(paths.tools, "node", "bin", "node"),
|
|
761
|
+
};
|
|
762
|
+
saveSettings(paths, settings);
|
|
763
|
+
writeCommand(paths, settings);
|
|
764
|
+
if (!(await startService(paths, home))) {
|
|
765
|
+
console.log(
|
|
766
|
+
`\nThe home doesn’t start by itself here: systemd --user isn’t available. Start it with ${cyan("wizards-bot start")}.`,
|
|
767
|
+
);
|
|
768
|
+
return { settings, running: false };
|
|
769
|
+
}
|
|
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 };
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
async function install(paths, options) {
|
|
777
|
+
windowsRefusal();
|
|
778
|
+
const installed = installedVersion(paths);
|
|
779
|
+
console.log(`${bold("wizards.bot")} ${dim(`into ${tilde(paths.bot)}`)}`);
|
|
780
|
+
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`);
|
|
783
|
+
}
|
|
784
|
+
const { running } = await put(paths, options, from);
|
|
785
|
+
if (running) {
|
|
786
|
+
await setup(paths, options);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/** Prints the output of `wizards-bot pair` (the QR, the code) and opens the pairing link. */
|
|
791
|
+
async function setup(paths, options) {
|
|
792
|
+
windowsRefusal();
|
|
793
|
+
const settings = readJson(paths.settings);
|
|
794
|
+
if (!settings || !installedVersion(paths)) {
|
|
795
|
+
throw notInstalled();
|
|
796
|
+
}
|
|
797
|
+
if (options.link) {
|
|
798
|
+
return link(paths, settings, options);
|
|
799
|
+
}
|
|
800
|
+
if (!(await healthy(settings.port))) {
|
|
801
|
+
throw new Refusal(
|
|
802
|
+
`The home doesn’t run. ${cyan("wizards bot status")} says more, its log is ${tilde(paths.log)}.`,
|
|
803
|
+
);
|
|
804
|
+
}
|
|
805
|
+
const result = spawnSync(paths.command, ["pair"], { encoding: "utf8" });
|
|
806
|
+
if (result.status !== 0) {
|
|
807
|
+
throw new Refusal(`wizards-bot pair failed: ${(result.stderr || result.stdout).trim()}`);
|
|
808
|
+
}
|
|
809
|
+
const code = /^Code:\s+(\S+)/m.exec(result.stdout)?.[1];
|
|
810
|
+
// The QR and the address for your phone; the browser on this computer uses localhost.
|
|
811
|
+
process.stdout.write(`\n${result.stdout.replace(/^Browser:.*\n/m, "")}`);
|
|
812
|
+
const url = `http://localhost:${settings.port}/${code ? `#code=${code}` : ""}`;
|
|
813
|
+
if (!options.open || !openBrowser(url)) {
|
|
814
|
+
console.log(`\nThe home’s setup: ${url}`);
|
|
815
|
+
} else {
|
|
816
|
+
console.log(`\nOpened the home’s setup in your browser: ${url}`);
|
|
817
|
+
}
|
|
818
|
+
}
|
|
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
|
+
async function link(paths, settings, options) {
|
|
825
|
+
const [where, code] = options.link;
|
|
826
|
+
if (!where || !code) {
|
|
827
|
+
throw new Refusal(
|
|
828
|
+
`Give your home’s address and a code from it: ${cyan("wizards bot setup --link ada K7QM-2RXD")}`,
|
|
829
|
+
);
|
|
830
|
+
}
|
|
831
|
+
const address = homeAddress(where);
|
|
832
|
+
const file = join(settings.data, "link.json");
|
|
833
|
+
const before = existsSync(file) ? statSync(file).mtimeMs : 0;
|
|
834
|
+
note(`Pairing this computer with ${address}`);
|
|
835
|
+
const child = spawn(paths.command, ["link", address, code], {
|
|
836
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
837
|
+
});
|
|
838
|
+
let said = "";
|
|
839
|
+
child.stdout.on("data", (chunk) => {
|
|
840
|
+
said += chunk;
|
|
841
|
+
});
|
|
842
|
+
child.stderr.on("data", (chunk) => {
|
|
843
|
+
said += chunk;
|
|
844
|
+
});
|
|
845
|
+
let exited = null;
|
|
846
|
+
child.on("exit", (status) => {
|
|
847
|
+
exited = status ?? 1;
|
|
848
|
+
});
|
|
849
|
+
const until = Date.now() + 30_000;
|
|
850
|
+
while (exited === null && Date.now() < until) {
|
|
851
|
+
if (existsSync(file) && statSync(file).mtimeMs > before) {
|
|
852
|
+
break;
|
|
853
|
+
}
|
|
854
|
+
await pause(200);
|
|
855
|
+
}
|
|
856
|
+
const paired = existsSync(file) && statSync(file).mtimeMs > before;
|
|
857
|
+
if (exited === null) {
|
|
858
|
+
child.kill("SIGTERM");
|
|
859
|
+
}
|
|
860
|
+
if (!paired) {
|
|
861
|
+
throw new Refusal(
|
|
862
|
+
`This computer couldn’t pair with ${address}${said.trim() ? `: ${said.trim().split("\n").pop()}` : "."}`,
|
|
863
|
+
);
|
|
864
|
+
}
|
|
865
|
+
const service = services(paths).link;
|
|
866
|
+
if (!(await startService(paths, service))) {
|
|
867
|
+
console.log(
|
|
868
|
+
`\nPaired with ${address}. systemd --user isn’t available here: keep ${cyan("wizards-bot link")} running yourself.`,
|
|
869
|
+
);
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
step(`Linked to ${address}`, serviceThere(service));
|
|
873
|
+
console.log(`\nYour home at ${address} uses this computer’s models while this computer is on.`);
|
|
874
|
+
}
|
|
875
|
+
|
|
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);
|
|
886
|
+
const answers = await healthy(settings.port);
|
|
887
|
+
const how = serviceThere(home);
|
|
888
|
+
console.log(`wizards.bot ${version} ${dim(tilde(join(paths.bot, version)))}`);
|
|
889
|
+
console.log(
|
|
890
|
+
` ${answers ? green("running") : red("not running")} http://localhost:${settings.port}${how ? dim(` (${how})`) : ""}`,
|
|
891
|
+
);
|
|
892
|
+
console.log(` data ${tilde(settings.data)}`);
|
|
893
|
+
console.log(` command ${tilde(paths.command)}`);
|
|
894
|
+
const linkFile = readJson(join(settings.data, "link.json"));
|
|
895
|
+
if (linkFile?.home && serviceThere(linked)) {
|
|
896
|
+
console.log(
|
|
897
|
+
` linked ${linkFile.home} ${serviceRuns(linked) ? green("running") : red("not running")}`,
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
if (!answers) {
|
|
901
|
+
console.log(`\nIts log: ${tilde(paths.log)}`);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
async function update(paths, options) {
|
|
906
|
+
windowsRefusal();
|
|
907
|
+
const installed = installedVersion(paths);
|
|
908
|
+
if (!installed) {
|
|
909
|
+
throw notInstalled();
|
|
910
|
+
}
|
|
911
|
+
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.`);
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
const { settings, running } = await put(paths, options, from);
|
|
917
|
+
// A link that runs starts again with the new version.
|
|
918
|
+
const linked = services(paths).link;
|
|
919
|
+
if (serviceThere(linked)) {
|
|
920
|
+
await startService(paths, linked);
|
|
921
|
+
}
|
|
922
|
+
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" : ""}.`,
|
|
924
|
+
);
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
function ask(question) {
|
|
928
|
+
return new Promise((done) => {
|
|
929
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
930
|
+
rl.question(question, (answer) => {
|
|
931
|
+
rl.close();
|
|
932
|
+
done(/^y(es)?$/i.test(answer.trim()));
|
|
933
|
+
});
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/** Removes a folder if nothing is left in it. */
|
|
938
|
+
function dropEmpty(dir) {
|
|
939
|
+
try {
|
|
940
|
+
rmdirSync(dir);
|
|
941
|
+
} catch {
|
|
942
|
+
// not empty, or not there
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
async function uninstall(paths, options) {
|
|
947
|
+
const settings = readJson(paths.settings) || {};
|
|
948
|
+
const { home, link: linked } = services(paths);
|
|
949
|
+
const there =
|
|
950
|
+
existsSync(paths.bot) ||
|
|
951
|
+
existsSync(paths.command) ||
|
|
952
|
+
serviceThere(home) ||
|
|
953
|
+
serviceThere(linked);
|
|
954
|
+
const data = settings.data || paths.data;
|
|
955
|
+
if (!there && !options.purge) {
|
|
956
|
+
console.log("wizards.bot isn’t installed on this computer.");
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
let purge = false;
|
|
960
|
+
if (options.purge && existsSync(data)) {
|
|
961
|
+
if (options.yes) {
|
|
962
|
+
purge = true;
|
|
963
|
+
} else if (process.stdin.isTTY) {
|
|
964
|
+
purge = await ask(
|
|
965
|
+
`Also delete your home’s data in ${tilde(data)}: its agents, conversations, devices and keys? This can’t be undone. [y/N] `,
|
|
966
|
+
);
|
|
967
|
+
} else {
|
|
968
|
+
throw new Refusal("--purge asks first. Run it in a terminal, or add --yes.");
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
for (const service of [linked, home]) {
|
|
972
|
+
const how = serviceThere(service);
|
|
973
|
+
if (how) {
|
|
974
|
+
await removeService(service);
|
|
975
|
+
step("Stopped and removed", how);
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
try {
|
|
979
|
+
if (
|
|
980
|
+
lstatSync(paths.pathLink).isSymbolicLink() &&
|
|
981
|
+
readlinkSync(paths.pathLink) === paths.command
|
|
982
|
+
) {
|
|
983
|
+
rmSync(paths.pathLink);
|
|
984
|
+
}
|
|
985
|
+
} catch {
|
|
986
|
+
// no link
|
|
987
|
+
}
|
|
988
|
+
rmSync(paths.command, { force: true });
|
|
989
|
+
rmSync(paths.bot, { recursive: true, force: true });
|
|
990
|
+
for (const log of [paths.log, paths.linkLog, paths.installLog]) {
|
|
991
|
+
rmSync(log, { force: true });
|
|
992
|
+
}
|
|
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 });
|
|
998
|
+
}
|
|
999
|
+
}
|
|
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);
|
|
1010
|
+
}
|
|
1011
|
+
if (purge) {
|
|
1012
|
+
rmSync(data, { recursive: true, force: true });
|
|
1013
|
+
console.log(`\nwizards.bot is off this computer, and its data in ${tilde(data)} is deleted.`);
|
|
1014
|
+
} else if (existsSync(data)) {
|
|
1015
|
+
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.`,
|
|
1017
|
+
);
|
|
1018
|
+
} else {
|
|
1019
|
+
console.log("\nwizards.bot is off this computer.");
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
// --- the command line ------------------------------------------------------------------------
|
|
1024
|
+
|
|
1025
|
+
const HELP = `${bold("wizards bot")}: wizards.bot, your own agent in a home of your own, on this computer
|
|
1026
|
+
|
|
1027
|
+
Commands
|
|
1028
|
+
${cyan("wizards bot install")} install the home, start it with your computer and open its setup
|
|
1029
|
+
${cyan("wizards bot setup")} open the home’s setup and show a code to pair your phone
|
|
1030
|
+
${cyan("wizards bot setup --link <address> <code>")}
|
|
1031
|
+
link this computer to your home on wizards.bot: it uses this
|
|
1032
|
+
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
|
|
1034
|
+
${cyan("wizards bot update")} install the newest version and restart the home, your data is kept
|
|
1035
|
+
${cyan("wizards bot uninstall")} take the home off this computer, your data in ~/.wizards-bot is kept
|
|
1036
|
+
(--purge deletes it too, after asking)
|
|
1037
|
+
|
|
1038
|
+
Options
|
|
1039
|
+
--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)
|
|
1041
|
+
--no-open don’t open the browser
|
|
1042
|
+
--yes, -y don’t ask
|
|
1043
|
+
|
|
1044
|
+
The program goes into ~/.engenty/wizards/bot (ENGENTY_HOME moves it), the command
|
|
1045
|
+
wizards-bot into ~/.local/bin. On a Mac the home runs as a LaunchAgent, on Linux as a
|
|
1046
|
+
systemd user service.
|
|
1047
|
+
`;
|
|
1048
|
+
|
|
1049
|
+
/** Reads `wizards bot <command> [options]`. */
|
|
1050
|
+
export function parse(argv) {
|
|
1051
|
+
const options = {
|
|
1052
|
+
command: "",
|
|
1053
|
+
open: true,
|
|
1054
|
+
yes: false,
|
|
1055
|
+
purge: false,
|
|
1056
|
+
link: null,
|
|
1057
|
+
version: null,
|
|
1058
|
+
port: null,
|
|
1059
|
+
};
|
|
1060
|
+
for (let i = 0; i < argv.length; i++) {
|
|
1061
|
+
const arg = argv[i];
|
|
1062
|
+
if (arg === "--help" || arg === "-h") {
|
|
1063
|
+
options.command = "help";
|
|
1064
|
+
return options;
|
|
1065
|
+
} else if (arg === "--no-open") {
|
|
1066
|
+
options.open = false;
|
|
1067
|
+
} else if (arg === "--yes" || arg === "-y") {
|
|
1068
|
+
options.yes = true;
|
|
1069
|
+
} else if (arg === "--purge") {
|
|
1070
|
+
options.purge = true;
|
|
1071
|
+
} else if (arg === "--link") {
|
|
1072
|
+
options.link = [argv[i + 1], argv[i + 2]];
|
|
1073
|
+
i += 2;
|
|
1074
|
+
} else if (arg === "--version") {
|
|
1075
|
+
options.version = (argv[++i] || "").replace(/^v/, "");
|
|
1076
|
+
if (!options.version) {
|
|
1077
|
+
throw new Refusal("--version needs a version, e.g. --version 0.1.0");
|
|
1078
|
+
}
|
|
1079
|
+
} else if (arg === "--port") {
|
|
1080
|
+
options.port = Number(argv[++i]);
|
|
1081
|
+
if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65535) {
|
|
1082
|
+
throw new Refusal("--port needs a port, e.g. --port 4747");
|
|
1083
|
+
}
|
|
1084
|
+
} else if (arg.startsWith("-")) {
|
|
1085
|
+
throw new Refusal(`Unknown option ${arg}. ${cyan("wizards bot --help")} lists them.`);
|
|
1086
|
+
} else if (!options.command) {
|
|
1087
|
+
options.command = arg;
|
|
1088
|
+
} else {
|
|
1089
|
+
throw new Refusal(`One command at a time: ${options.command} or ${arg}.`);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
return options;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
const COMMANDS = { install, setup, status, update, uninstall };
|
|
1096
|
+
|
|
1097
|
+
/** `wizards bot …`; its exit code. */
|
|
1098
|
+
export async function main(argv, env = process.env) {
|
|
1099
|
+
try {
|
|
1100
|
+
const options = parse(argv);
|
|
1101
|
+
if (!options.command || options.command === "help") {
|
|
1102
|
+
console.log(HELP);
|
|
1103
|
+
return 0;
|
|
1104
|
+
}
|
|
1105
|
+
const run = COMMANDS[options.command];
|
|
1106
|
+
if (!run) {
|
|
1107
|
+
throw new Refusal(
|
|
1108
|
+
`wizards bot has no command ${options.command}. ${cyan("wizards bot --help")} lists them.`,
|
|
1109
|
+
);
|
|
1110
|
+
}
|
|
1111
|
+
await run(layout(env), options);
|
|
1112
|
+
return 0;
|
|
1113
|
+
} catch (error) {
|
|
1114
|
+
if (!(error instanceof Refusal)) {
|
|
1115
|
+
throw error;
|
|
1116
|
+
}
|
|
1117
|
+
console.error(`${red("■")} ${error.message}`);
|
|
1118
|
+
return 1;
|
|
1119
|
+
}
|
|
1120
|
+
}
|