@wheatley-ai/cli 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +37 -3
  2. package/dist/cli/ask.js +8 -4
  3. package/dist/cli/chat.js +8 -4
  4. package/dist/cli/daemon.js +45 -0
  5. package/dist/cli/io.js +1 -0
  6. package/dist/cli/main.js +145 -157
  7. package/dist/cli/session.js +59 -3
  8. package/dist/cli/status.js +4 -4
  9. package/dist/cli/tui/app.js +14 -2
  10. package/dist/cli/tui/controller.js +80 -19
  11. package/dist/cli/tui/markdown.js +229 -104
  12. package/dist/cli/tui/model-picker.js +76 -0
  13. package/dist/cli/tui/picker-panel.js +39 -0
  14. package/dist/core/agent/agent.js +23 -12
  15. package/dist/core/config/config-store.js +11 -6
  16. package/dist/core/config/diagnostics.js +116 -0
  17. package/dist/core/config/secret-store.js +13 -9
  18. package/dist/core/deployment.js +19 -1
  19. package/dist/core/markdown-tokens.js +60 -0
  20. package/dist/core/model-catalog.js +54 -0
  21. package/dist/core/rpc/deployment-handlers.js +2 -1
  22. package/dist/core/server/control-server.js +19 -21
  23. package/dist/core/server/http-server.js +17 -0
  24. package/dist/core/server/static-files.js +40 -66
  25. package/dist/dashboard/assets/index-DGa2Ps9u.js +12 -0
  26. package/dist/dashboard/assets/index-DeERxJOJ.css +2 -0
  27. package/dist/dashboard/assets/{sheet-presentation-DMljN0LW.js → sheet-presentation-CZ1dO2kr.js} +1 -1
  28. package/dist/dashboard/index.html +2 -2
  29. package/dist/frontends/discord/approvals.js +8 -43
  30. package/dist/frontends/discord/binding.js +81 -8
  31. package/dist/frontends/discord/json-file.js +57 -0
  32. package/dist/frontends/discord/model-picker.js +276 -0
  33. package/dist/frontends/slack/binding.js +33 -3
  34. package/dist/frontends/slack/inbound.js +21 -12
  35. package/dist/frontends/slack/model-picker-blocks.js +147 -0
  36. package/dist/frontends/slack/outbound.js +27 -2
  37. package/dist/frontends/slack/schemas.js +9 -2
  38. package/dist/frontends/telegram/approvals.js +13 -48
  39. package/dist/frontends/telegram/binding.js +5 -0
  40. package/dist/frontends/telegram/client.js +7 -0
  41. package/dist/frontends/telegram/delivery.js +19 -6
  42. package/dist/frontends/telegram/inbound.js +64 -8
  43. package/dist/frontends/telegram/markdown.js +120 -83
  44. package/dist/frontends/telegram/model-picker.js +160 -0
  45. package/dist/frontends/telegram/token-store.js +73 -0
  46. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +13 -0
  47. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +11 -0
  48. package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +1 -1
  49. package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +1 -1
  50. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +20 -0
  51. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +9 -1
  52. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +2 -2
  53. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +2 -2
  54. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +23 -0
  55. package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +1 -1
  56. package/dist/node_modules/@wheatley-ai/sdk/package.json +1 -1
  57. package/dist/ops/cli.js +127 -114
  58. package/dist/ops/command-runner.js +1 -0
  59. package/dist/ops/install-method.js +189 -0
  60. package/dist/ops/registry.js +35 -0
  61. package/dist/ops/service.js +6 -1
  62. package/dist/ops/update.js +109 -88
  63. package/dist/triggers/delivery-codec.js +13 -0
  64. package/dist/triggers/webhook-ingress.js +89 -82
  65. package/package.json +11 -4
  66. package/dist/dashboard/assets/index-C9Rul5vE.css +0 -2
  67. package/dist/dashboard/assets/index-DXzGGAxQ.js +0 -11
@@ -7,5 +7,5 @@
7
7
  },
8
8
  "name": "@wheatley-ai/sdk",
9
9
  "type": "module",
10
- "version": "0.2.0"
10
+ "version": "0.4.0"
11
11
  }
package/dist/ops/cli.js CHANGED
@@ -1,18 +1,21 @@
1
1
  import { homedir } from "node:os";
2
- import { parseArgs } from "node:util";
2
+ import { Argument, Option } from "commander";
3
3
  import { systemClock } from "../contracts/module.js";
4
4
  import { listBackups, restoreAgentBackup } from "./backup.js";
5
5
  import { processRunner } from "./command-runner.js";
6
+ import { resolveInstallation, UPDATE_METHODS } from "./install-method.js";
6
7
  import { agentDirFor, resolveHomeDir } from "./paths.js";
7
8
  import { createServiceManager, packageBinScript, resolveServiceSpec, } from "./service.js";
8
- import { applyUpdate, detectInstallMethod, installCommand, packageDir, planUpdate, readPackageVersion, } from "./update.js";
9
+ import { applyUpgrade, packageDir, planUpdate, readPackageVersion, } from "./update.js";
9
10
  /** The ops CLI dependencies of this process. */
10
11
  export const hostCliDeps = (isDaemonRunning, drainTimeoutMs) => ({
11
12
  clock: systemClock,
12
13
  env: process.env,
13
14
  execPath: process.execPath,
15
+ fetch: globalThis.fetch,
14
16
  homeDir: resolveHomeDir(),
15
17
  isDaemonRunning,
18
+ packageDir: packageDir(),
16
19
  platform: process.platform,
17
20
  runner: processRunner,
18
21
  uid: process.getuid?.() ?? 0,
@@ -21,104 +24,84 @@ export const hostCliDeps = (isDaemonRunning, drainTimeoutMs) => ({
21
24
  });
22
25
  const EXIT_OK = 0;
23
26
  const EXIT_FAILURE = 1;
24
- const EXIT_USAGE = 2;
25
- const SERVICE_USAGE = "Usage: wheatley service <install|start|stop|restart|status>";
26
- const UPDATE_USAGE = "Usage: wheatley update [--check] [--manager npm|pnpm]";
27
- const RESTORE_USAGE = "Usage: wheatley restore <agent> [backup]";
28
- class UsageError extends Error {
29
- name = "UsageError";
30
- }
31
- const isUsageError = (error) => error instanceof UsageError ||
32
- ("code" in error && String(error.code).startsWith("ERR_PARSE_ARGS"));
33
- /** Turns thrown errors into exit codes, so that a command never rejects. */
34
- const guarded = (usage, body) => async (args, io) => {
27
+ const SERVICE_ACTIONS = [
28
+ "install",
29
+ "start",
30
+ "stop",
31
+ "restart",
32
+ "status",
33
+ ];
34
+ /** Runs `body` and turns a thrown error into exit code 1 and a line on `io.err`, so that a command never rejects. */
35
+ const guarded = async (io, body) => {
35
36
  try {
36
- return await body(args, io);
37
+ return await body();
37
38
  }
38
39
  catch (error) {
39
- const failure = error instanceof Error ? error : new Error(String(error));
40
- io.err(failure.message);
41
- if (isUsageError(failure)) {
42
- io.err(usage);
43
- return EXIT_USAGE;
44
- }
40
+ io.err(error instanceof Error ? error.message : String(error));
45
41
  return EXIT_FAILURE;
46
42
  }
47
43
  };
48
- const serviceCommand = (deps) => async (args, io) => {
49
- const { positionals } = parseArgs({
50
- allowPositionals: true,
51
- args: [...args],
52
- });
53
- const [action, ...extra] = positionals;
54
- if (action === undefined || extra.length > 0) {
55
- throw new UsageError("Pass exactly one service action.");
56
- }
57
- const manager = createServiceManager(deps);
58
- switch (action) {
59
- case "install": {
60
- const spec = await resolveServiceSpec({
61
- binScript: packageBinScript(),
62
- env: deps.env,
63
- execPath: deps.execPath,
64
- homeDir: deps.homeDir,
65
- drainTimeoutMs: deps.drainTimeoutMs,
66
- });
67
- const result = await manager.install(spec);
68
- io.out(`Installed the ${manager.kind} unit: ${result.unitPath}`);
69
- for (const note of result.notes) {
70
- io.out(note);
71
- }
72
- return EXIT_OK;
73
- }
74
- case "start": {
75
- await manager.start();
76
- io.out("Started the Wheatley service.");
77
- return EXIT_OK;
78
- }
79
- case "stop": {
80
- await manager.stop();
81
- io.out("Stopped the Wheatley service.");
82
- return EXIT_OK;
83
- }
84
- case "restart": {
85
- await manager.restart();
86
- io.out("Restarted the Wheatley service.");
87
- return EXIT_OK;
44
+ /** The steps of each `wheatley service` action. */
45
+ const SERVICE_STEPS = {
46
+ install: async (manager, deps, io) => {
47
+ const spec = await resolveServiceSpec({
48
+ binScript: packageBinScript(),
49
+ env: deps.env,
50
+ execPath: deps.execPath,
51
+ homeDir: deps.homeDir,
52
+ drainTimeoutMs: deps.drainTimeoutMs,
53
+ });
54
+ const result = await manager.install(spec);
55
+ io.out(`Installed the ${manager.kind} unit: ${result.unitPath}`);
56
+ for (const note of result.notes) {
57
+ io.out(note);
88
58
  }
89
- case "status": {
90
- const status = await manager.status();
91
- io.out(`Manager: ${status.manager}`);
92
- io.out(`Unit: ${status.unitPath}`);
93
- io.out(`State: ${status.state}`);
94
- io.out(`PID: ${status.pid ?? "-"}`);
95
- return EXIT_OK;
96
- }
97
- default: {
98
- throw new UsageError(`Unknown service action: ${action}`);
99
- }
100
- }
59
+ },
60
+ restart: async (manager, _deps, io) => {
61
+ await manager.restart();
62
+ io.out("Restarted the Wheatley service.");
63
+ },
64
+ start: async (manager, _deps, io) => {
65
+ await manager.start();
66
+ io.out("Started the Wheatley service.");
67
+ },
68
+ status: async (manager, _deps, io) => {
69
+ const status = await manager.status();
70
+ io.out(`Manager: ${status.manager}`);
71
+ io.out(`Unit: ${status.unitPath}`);
72
+ io.out(`State: ${status.state}`);
73
+ io.out(`PID: ${status.pid ?? "-"}`);
74
+ },
75
+ stop: async (manager, _deps, io) => {
76
+ await manager.stop();
77
+ io.out("Stopped the Wheatley service.");
78
+ },
79
+ };
80
+ const serviceCommand = async (deps, io, action) => {
81
+ await SERVICE_STEPS[action](createServiceManager(deps), deps, io);
82
+ return EXIT_OK;
83
+ };
84
+ const newerMajorLines = (major) => {
85
+ const intro = `Wheatley ${major.version} is a new major version. wheatley update stays within the current major version. Read the release notes, then`;
86
+ return major.action.kind === "command"
87
+ ? [`${intro} run: ${major.action.command.join(" ")}`]
88
+ : [`${intro}:`, ...major.action.lines];
101
89
  };
102
- const isPackageManager = (value) => value === "npm" || value === "pnpm";
103
- const newerMajorNote = (version, manager) => `Wheatley ${version} is a new major version. wheatley update stays within the current major version. Read the release notes, then run: ${installCommand(manager, version).join(" ")}`;
104
- const updateCommand = (deps) => async (args, io) => {
105
- const { values } = parseArgs({
106
- args: [...args],
107
- options: {
108
- check: { type: "boolean" },
109
- manager: { type: "string" },
110
- },
90
+ const updateCommand = async (deps, io, values) => {
91
+ const installation = await resolveInstallation({
92
+ env: deps.env,
93
+ execPath: deps.execPath,
94
+ method: values.method,
95
+ packageDir: deps.packageDir,
96
+ platform: deps.platform,
97
+ runner: deps.runner,
98
+ userHome: deps.userHome,
111
99
  });
112
- if (values.manager !== undefined && !isPackageManager(values.manager)) {
113
- throw new UsageError(`Unknown package manager: ${values.manager}`);
114
- }
115
- const dir = packageDir();
116
- const method = detectInstallMethod(deps.env, dir);
117
100
  const plan = await planUpdate({
118
- current: await readPackageVersion(dir),
119
- method,
120
- runner: deps.runner,
121
- manager: values.manager,
101
+ current: await readPackageVersion(installation.packageDir),
102
+ env: deps.env,
103
+ fetch: deps.fetch,
104
+ installation,
122
105
  });
123
106
  if (plan.kind === "docker") {
124
107
  io.out("This Wheatley runs in Docker. In the folder of docker-compose.yml, run:");
@@ -127,23 +110,27 @@ const updateCommand = (deps) => async (args, io) => {
127
110
  }
128
111
  return EXIT_OK;
129
112
  }
130
- const manager = values.manager ?? (method === "pnpm" ? "pnpm" : "npm");
131
- const newerMajor = plan.newerMajor === undefined
132
- ? []
133
- : [newerMajorNote(plan.newerMajor, manager)];
113
+ const newerMajor = plan.newerMajor === undefined ? [] : newerMajorLines(plan.newerMajor);
134
114
  if (plan.kind === "up_to_date") {
135
115
  io.out(`Wheatley ${plan.current} is the newest release of its major version.`);
136
- for (const line of newerMajor) {
116
+ }
117
+ else if (plan.action.kind === "notice") {
118
+ io.out(`Wheatley ${plan.target} is available. This Wheatley runs ${plan.current}.`);
119
+ for (const line of plan.action.lines) {
137
120
  io.out(line);
138
121
  }
139
- return EXIT_OK;
140
122
  }
141
- if (values.check === true) {
123
+ else if (values.check === true) {
142
124
  io.out(`Update available: ${plan.current} -> ${plan.target}. Run: wheatley update`);
143
125
  }
144
126
  else {
145
- io.out(`Updating Wheatley ${plan.current} -> ${plan.target}: ${plan.command.join(" ")}`);
146
- await applyUpdate(plan, deps.runner);
127
+ io.out(`Updating Wheatley ${plan.current} -> ${plan.target}: ${plan.action.command.join(" ")}`);
128
+ await applyUpgrade(plan.action, {
129
+ packageDir: installation.packageDir,
130
+ runner: deps.runner,
131
+ target: plan.target,
132
+ workDir: deps.userHome,
133
+ });
147
134
  io.out(`Updated Wheatley to ${plan.target}. If the daemon runs as a service, run: wheatley service restart`);
148
135
  }
149
136
  for (const line of newerMajor) {
@@ -151,15 +138,7 @@ const updateCommand = (deps) => async (args, io) => {
151
138
  }
152
139
  return EXIT_OK;
153
140
  };
154
- const restoreCommand = (deps) => async (args, io) => {
155
- const { positionals } = parseArgs({
156
- allowPositionals: true,
157
- args: [...args],
158
- });
159
- const [agent, backup, ...extra] = positionals;
160
- if (agent === undefined || extra.length > 0) {
161
- throw new UsageError("Pass an Agent name and at most one backup.");
162
- }
141
+ const restoreCommand = async (deps, io, agent, backup) => {
163
142
  const agentDir = agentDirFor(deps.homeDir, agent);
164
143
  if (backup === undefined) {
165
144
  const backups = await listBackups(agentDir);
@@ -186,9 +165,43 @@ const restoreCommand = (deps) => async (args, io) => {
186
165
  }
187
166
  return EXIT_OK;
188
167
  };
189
- /** Creates the ops subcommand handlers. */
190
- export const createOpsCommands = (deps) => ({
191
- restore: guarded(RESTORE_USAGE, restoreCommand(deps)),
192
- service: guarded(SERVICE_USAGE, serviceCommand(deps)),
193
- update: guarded(UPDATE_USAGE, updateCommand(deps)),
194
- });
168
+ /**
169
+ * Adds `service`, `update`, and `restore` to `program`. Call it after the root options and the output, help, and
170
+ * exit settings of `program`, because subcommands copy those settings when they are created.
171
+ *
172
+ * - `wheatley service <install|start|stop|restart|status>`
173
+ * - `wheatley update [--check] [--method npm|pnpm|yarn|bun|brew|curl]`
174
+ * - `wheatley restore <agent> [backup]`: without `backup`, it lists the Agent's backups on stdout. With `backup`, it
175
+ * restores that backup. A running daemon, an invalid Agent name, or a failed restore prints the error on stderr and
176
+ * exits 1.
177
+ *
178
+ * Commander reports usage errors, for example a missing Agent name or an unknown option, before an action runs.
179
+ */
180
+ export const addOpsCommands = (program, host) => {
181
+ const run = async (command, body) => {
182
+ host.exit(await guarded(host.io, async () => await body(host.deps(command))));
183
+ };
184
+ program
185
+ .command("service")
186
+ .description("Install or control the Wheatley service: install, start, stop, restart, status")
187
+ .addArgument(new Argument("<action>", "The service action").choices(SERVICE_ACTIONS))
188
+ .action(async (action, _options, command) => {
189
+ await run(command, async (deps) => await serviceCommand(deps, host.io, action));
190
+ });
191
+ program
192
+ .command("update")
193
+ .description("Update Wheatley within its major version")
194
+ .option("--check", "Report an available update and install nothing")
195
+ .addOption(new Option("--method <method>", "The install method of this Wheatley").choices(UPDATE_METHODS))
196
+ .action(async (options, command) => {
197
+ await run(command, async (deps) => await updateCommand(deps, host.io, options));
198
+ });
199
+ program
200
+ .command("restore")
201
+ .description("List the backups of an Agent, or restore its agent.sqlite")
202
+ .argument("<agent>", "The Agent name")
203
+ .argument("[backup]", "The backup file to restore")
204
+ .action(async (agent, backup, _options, command) => {
205
+ await run(command, async (deps) => await restoreCommand(deps, host.io, agent, backup));
206
+ });
207
+ };
@@ -4,6 +4,7 @@ import { once } from "node:events";
4
4
  export const processRunner = {
5
5
  run: async (command, args, options) => {
6
6
  const child = spawn(command, args, {
7
+ cwd: options?.cwd,
7
8
  stdio: options?.inheritStdio === true ? "inherit" : ["ignore", "pipe", "pipe"],
8
9
  });
9
10
  let stdout = "";
@@ -0,0 +1,189 @@
1
+ import { readFile, realpath } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { Type } from "typebox";
4
+ import { Value } from "typebox/value";
5
+ import { envValue, isDocker, pathExists } from "./paths.js";
6
+ import { PACKAGE_NAME } from "./registry.js";
7
+ /** The Node.js package managers that can own a global install of Wheatley. */
8
+ export const NODE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
9
+ /** The install methods that `wheatley update` updates itself. `wheatley update --method` takes these values. */
10
+ export const UPDATE_METHODS = [...NODE_MANAGERS, "brew", "curl"];
11
+ const TAP_FORMULA = "sphericalkat/tap/wheatley";
12
+ const CORE_TAP = "homebrew/core";
13
+ const segment = (...names) => `${path.sep}${names.join(path.sep)}${path.sep}`;
14
+ const PACKAGE_SUFFIX = segment("lib", "node_modules", ...PACKAGE_NAME.split("/"));
15
+ const ReceiptSchema = Type.Object({
16
+ source: Type.Object({ tap: Type.String() }),
17
+ });
18
+ /** Returns `true` if `dir` is `parent` or inside it. Both paths must be real paths. */
19
+ const isInside = (dir, parent) => `${dir}${path.sep}`.startsWith(`${parent}${path.sep}`);
20
+ /** Returns the real path of `target`, or `target` itself if it does not exist. */
21
+ const realOrSelf = async (target) => {
22
+ try {
23
+ return await realpath(target);
24
+ }
25
+ catch {
26
+ return target;
27
+ }
28
+ };
29
+ const curlAppDirs = (env, userHome) => {
30
+ const fallback = path.join(userHome, ".local", "share");
31
+ const xdg = envValue(env, "XDG_DATA_HOME");
32
+ return [...new Set([xdg ?? fallback, fallback])].map((dataHome) => path.join(dataHome, "wheatley", "app"));
33
+ };
34
+ const isCurlInstall = async (dir, input) => {
35
+ const appDirs = await Promise.all(curlAppDirs(input.env, input.userHome).map(realOrSelf));
36
+ return appDirs.some((appDir) => isInside(dir, appDir));
37
+ };
38
+ /** The npm prefix of `<prefix>/lib/node_modules/@wheatley-ai/cli`, which npm uses on POSIX systems. */
39
+ const npmPrefix = (dir, platform) => platform !== "win32" && `${dir}${path.sep}`.endsWith(PACKAGE_SUFFIX)
40
+ ? dir.slice(0, -(PACKAGE_SUFFIX.length - 1))
41
+ : undefined;
42
+ /** Reads the tap of the Homebrew keg that holds `dir`, from its `INSTALL_RECEIPT.json`. */
43
+ const brewFormula = async (dir) => {
44
+ const cellar = segment("Cellar", "wheatley");
45
+ const start = dir.indexOf(cellar) + cellar.length;
46
+ const keg = dir.slice(0, dir.indexOf(path.sep, start));
47
+ try {
48
+ const receipt = JSON.parse(await readFile(path.join(keg, "INSTALL_RECEIPT.json"), "utf-8"));
49
+ return Value.Check(ReceiptSchema, receipt) &&
50
+ receipt.source.tap === CORE_TAP
51
+ ? "wheatley"
52
+ : TAP_FORMULA;
53
+ }
54
+ catch {
55
+ return TAP_FORMULA;
56
+ }
57
+ };
58
+ /** Returns `true` if `pacman` reports an owner package for `dir`. */
59
+ const isPacmanPackage = async (dir, runner) => {
60
+ try {
61
+ const result = await runner.run("pacman", ["-Qqo", dir]);
62
+ return result.exitCode === 0;
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ };
68
+ const AUR_DIR = segment("usr", "lib", "node_modules", ...PACKAGE_NAME.split("/"));
69
+ /** Detects the installs that a dedicated tool or another package system owns, from the real package path. */
70
+ const detectManaged = async (dir, input) => {
71
+ if (await isCurlInstall(dir, input)) {
72
+ return "curl";
73
+ }
74
+ const hints = [
75
+ ["brew", segment("Cellar", "wheatley")],
76
+ ["volta", segment("tools", "image", "packages")],
77
+ ["mise", `${path.sep}installs${path.sep}npm-`],
78
+ ];
79
+ const marked = `${dir}${path.sep}`;
80
+ const hinted = hints.find(([, hint]) => marked.includes(hint))?.[0];
81
+ if (hinted !== undefined) {
82
+ return hinted;
83
+ }
84
+ const isSystemPackage = input.platform === "linux" &&
85
+ marked.endsWith(AUR_DIR) &&
86
+ (await isPacmanPackage(dir, input.runner));
87
+ if (isSystemPackage) {
88
+ return "aur";
89
+ }
90
+ return marked.includes(segment("node_modules")) ? undefined : "source";
91
+ };
92
+ /** The global package folders of each manager, as path fragments. */
93
+ const MANAGER_HINTS = {
94
+ bun: [segment(".bun", "install", "global")],
95
+ npm: [PACKAGE_SUFFIX],
96
+ pnpm: [segment("pnpm", "global"), segment(".pnpm")],
97
+ yarn: [segment("yarn", "global"), segment("Yarn", "Data", "global")],
98
+ };
99
+ const PROBES = {
100
+ bun: ["pm", "ls", "-g"],
101
+ npm: ["list", "-g", "--depth=0", PACKAGE_NAME],
102
+ pnpm: ["list", "-g", "--depth=0", PACKAGE_NAME],
103
+ yarn: ["global", "list"],
104
+ };
105
+ /** Resolves `true` if the global package list of `manager` contains Wheatley. A missing manager counts as `false`. */
106
+ const listsWheatley = async (manager, { runner, userHome }) => {
107
+ try {
108
+ // Corepack shims of pnpm and yarn refuse to run inside a project whose `packageManager` names another manager.
109
+ const result = await runner.run(manager, PROBES[manager], {
110
+ cwd: userHome,
111
+ });
112
+ return result.exitCode === 0 && result.stdout.includes(PACKAGE_NAME);
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ };
118
+ /**
119
+ * Picks the Node.js package manager that owns the install. It ranks the managers by the path of the package, then
120
+ * confirms the ranking with their global package lists, which it queries in parallel. A path hint wins over a list
121
+ * that only another manager confirms, because that list can belong to a second copy of Wheatley.
122
+ */
123
+ const detectNodeManager = async (dir, input) => {
124
+ const marked = `${dir}${path.sep}`;
125
+ const pnpmHome = envValue(input.env, "PNPM_HOME");
126
+ const hinted = NODE_MANAGERS.filter((manager) => MANAGER_HINTS[manager].some((hint) => marked.includes(hint)) ||
127
+ (manager === "pnpm" &&
128
+ pnpmHome !== undefined &&
129
+ isInside(dir, path.resolve(pnpmHome))));
130
+ const confirmed = await Promise.all(NODE_MANAGERS.map(async (manager) => (await listsWheatley(manager, input)) ? manager : []));
131
+ const owners = confirmed.flat();
132
+ return (hinted.find((manager) => owners.includes(manager)) ??
133
+ hinted[0] ??
134
+ owners[0] ??
135
+ "npm");
136
+ };
137
+ /** The npm that belongs to `prefix`, started with the Node.js of the prefix or else the running Node.js. */
138
+ const npmFor = async (prefix, execPath) => {
139
+ if (prefix === undefined) {
140
+ return ["npm"];
141
+ }
142
+ const npm = path.join(prefix, "bin", "npm");
143
+ if (!(await pathExists(npm))) {
144
+ return ["npm"];
145
+ }
146
+ const node = path.join(prefix, "bin", "node");
147
+ return [(await pathExists(node)) ? node : await realOrSelf(execPath), npm];
148
+ };
149
+ const installationFor = async (method, dir, input) => {
150
+ if (method === "npm") {
151
+ const prefix = npmPrefix(dir, input.platform);
152
+ return {
153
+ method,
154
+ npm: await npmFor(prefix, input.execPath),
155
+ packageDir: dir,
156
+ prefix,
157
+ };
158
+ }
159
+ if (method === "brew") {
160
+ return { formula: await brewFormula(dir), method, packageDir: dir };
161
+ }
162
+ return { method, packageDir: dir };
163
+ };
164
+ /**
165
+ * Finds out how this Wheatley was installed and what updates it.
166
+ *
167
+ * It resolves the real package path first, so that a symlink such as `/opt/homebrew/opt/wheatley` or a `pnpm` link
168
+ * cannot hide the owner. It checks in this order:
169
+ *
170
+ * 1. Docker, from `WHEATLEY_DOCKER`.
171
+ * 2. The `curl` installer app folder, `${XDG_DATA_HOME:-~/.local/share}/wheatley/app`.
172
+ * 3. Homebrew, Volta, and mise, from their folders.
173
+ * 4. An AUR package, if `pacman` owns `/usr/lib/node_modules/@wheatley-ai/cli`.
174
+ * 5. A source checkout, if the package is outside `node_modules`.
175
+ * 6. npm, pnpm, yarn, or bun, from the package path and their global package lists.
176
+ *
177
+ * Errors: does not reject. A failed or missing `pacman` or package manager counts as "does not own Wheatley".
178
+ */
179
+ export const resolveInstallation = async (input) => {
180
+ const dir = await realOrSelf(input.packageDir);
181
+ if (input.method !== undefined) {
182
+ return await installationFor(input.method, dir, input);
183
+ }
184
+ if (isDocker(input.env)) {
185
+ return { method: "docker", packageDir: dir };
186
+ }
187
+ const method = (await detectManaged(dir, input)) ?? (await detectNodeManager(dir, input));
188
+ return await installationFor(method, dir, input);
189
+ };
@@ -0,0 +1,35 @@
1
+ import { Type } from "typebox";
2
+ import { Value } from "typebox/value";
3
+ import { envValue } from "./paths.js";
4
+ /** The npm package name of the daemon and CLI. */
5
+ export const PACKAGE_NAME = "@wheatley-ai/cli";
6
+ const DEFAULT_REGISTRY = "https://registry.npmjs.org";
7
+ /** The abbreviated packument has only the fields that installs need, which keeps the response small. */
8
+ const ABBREVIATED_PACKUMENT = "application/vnd.npm.install-v1+json";
9
+ const REGISTRY_TIMEOUT_MS = 10_000;
10
+ const TRAILING_SLASHES = /\/+$/u;
11
+ const PackumentSchema = Type.Object({
12
+ versions: Type.Record(Type.String(), Type.Unknown()),
13
+ });
14
+ /**
15
+ * Lists the published versions of `@wheatley-ai/cli` with one HTTP request to the npm registry. It does not start a
16
+ * package manager, so the `devEngines` field of a `package.json` in the working folder cannot make it fail.
17
+ *
18
+ * Errors: rejects on a network error, a timeout after 10 seconds, an HTTP error status, or an unexpected response.
19
+ */
20
+ export const fetchPublishedVersions = async (options) => {
21
+ const registry = (envValue(options.env, "npm_config_registry") ?? DEFAULT_REGISTRY).replace(TRAILING_SLASHES, "");
22
+ const url = `${registry}/${PACKAGE_NAME.replace("/", "%2F")}`;
23
+ const response = await options.fetch(url, {
24
+ headers: { Accept: ABBREVIATED_PACKUMENT },
25
+ signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),
26
+ });
27
+ if (!response.ok) {
28
+ throw new Error(`GET ${url} failed with HTTP ${response.status}`);
29
+ }
30
+ const parsed = await response.json();
31
+ if (!Value.Check(PackumentSchema, parsed)) {
32
+ throw new Error(`GET ${url} returned an unexpected response`);
33
+ }
34
+ return Object.keys(parsed.versions);
35
+ };
@@ -45,6 +45,11 @@ const systemdArg = (value) => {
45
45
  const escaped = value.replaceAll(PERCENT, "%%").replaceAll(DOLLAR, "$$$$");
46
46
  return SYSTEMD_BARE_WORD.test(escaped) ? escaped : quoteSystemd(escaped);
47
47
  };
48
+ /** Escapes a systemd path directive such as `WorkingDirectory=`, which does not strip quotes. */
49
+ const systemdPath = (value) => {
50
+ assertSingleLine(value);
51
+ return value.replaceAll(PERCENT, "%%");
52
+ };
48
53
  const systemdValue = (value) => {
49
54
  assertSingleLine(value);
50
55
  return quoteSystemd(value.replaceAll(PERCENT, "%%"));
@@ -64,7 +69,7 @@ export const renderSystemdUnit = (spec) => {
64
69
  "[Service]",
65
70
  "Type=exec",
66
71
  `ExecStart=${spec.command.map(systemdArg).join(" ")}`,
67
- `WorkingDirectory=${systemdValue(spec.workingDirectory)}`,
72
+ `WorkingDirectory=${systemdPath(spec.workingDirectory)}`,
68
73
  ...environment,
69
74
  "Restart=on-failure",
70
75
  `RestartSec=${RESTART_DELAY_SECONDS}`,