@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
package/README.md CHANGED
@@ -8,13 +8,45 @@ This package installs the `wheatley` command. The daemon, the CLI, and the dashb
8
8
 
9
9
  ## Install
10
10
 
11
- You need Node.js 26.13.1 or newer.
11
+ ### Install script (macOS and Linux)
12
+
13
+ Works on macOS (`arm64`, `x64`) and glibc Linux (`x64`, `arm64`):
14
+
15
+ ```sh
16
+ curl -fsSL https://raw.githubusercontent.com/SphericalKat/wheatley/main/scripts/install.sh | sh
17
+ ```
18
+
19
+ Files go under `${XDG_DATA_HOME:-~/.local/share}/wheatley/` and the binary goes in `${XDG_BIN_HOME:-~/.local/bin}/wheatley`, keeping `~/.wheatley` for config and data. If your machine does not have Node.js `26.13.1` or newer, the script downloads Node.js automatically into `wheatley/runtime` (Linux requires `libatomic1`). Pass `--version <version>` to pin a release or `--no-modify-path` to skip shell profile edits.
20
+
21
+ ### npm, pnpm, yarn, or bun
22
+
23
+ Requires Node.js `26.13.1` or newer:
12
24
 
13
25
  ```sh
14
26
  npm install -g @wheatley-ai/cli
27
+ # or
28
+ pnpm add -g @wheatley-ai/cli
29
+ # or
30
+ yarn global add @wheatley-ai/cli
31
+ # or
32
+ bun install -g @wheatley-ai/cli
33
+ ```
34
+
35
+ ### Homebrew
36
+
37
+ ```sh
38
+ brew install sphericalkat/tap/wheatley
15
39
  ```
16
40
 
17
- pnpm works too: `pnpm add -g @wheatley-ai/cli`.
41
+ Homebrew installs Node.js as a dependency.
42
+
43
+ ### Arch Linux (AUR)
44
+
45
+ ```sh
46
+ paru -S wheatley-cli
47
+ # or
48
+ yay -S wheatley-cli
49
+ ```
18
50
 
19
51
  ## Quick start
20
52
 
@@ -181,7 +213,9 @@ wheatley update --check
181
213
  wheatley update
182
214
  ```
183
215
 
184
- `wheatley update` stays inside your current major version. To move to a new major version, run `npm install -g @wheatley-ai/cli@latest`. Then restart the daemon, for example with `wheatley service restart`.
216
+ `wheatley update` detects how you installed Wheatley (`npm`, `pnpm`, `yarn`, `bun`, Homebrew, or the `curl` script) and upgrades within your current major version. Pass `--method <name>` to override detection. For Volta, mise, AUR, and Docker installs, it prints the native update command without touching files.
217
+
218
+ Major version upgrades are never installed automatically. Run the command `wheatley update` prints for your install method, then restart the daemon (for example `wheatley service restart`).
185
219
 
186
220
  ## Security
187
221
 
package/dist/cli/ask.js CHANGED
@@ -7,11 +7,15 @@ import { approvalQuestion, chooseAgent, connect, decideApproval, } from "./sessi
7
7
  *
8
8
  * Resolves with the exit code: 0 for a completed Run, 1 otherwise.
9
9
  */
10
- export const runAsk = async (io, flags, prompt, version) => {
11
- const client = await connect(io, flags, version);
12
- if (client === undefined) {
10
+ export const runAsk = async (io, flags, prompt, version, daemonOverrides) => {
11
+ const session = await connect(io, flags, version, {
12
+ autoStart: true,
13
+ daemonOverrides,
14
+ });
15
+ if (session === undefined) {
13
16
  return 1;
14
17
  }
18
+ const { client } = session;
15
19
  try {
16
20
  const agent = await chooseAgent(client, flags.agent);
17
21
  const queue = [];
@@ -89,6 +93,6 @@ export const runAsk = async (io, flags, prompt, version) => {
89
93
  return 1;
90
94
  }
91
95
  finally {
92
- await client.close();
96
+ await session.close();
93
97
  }
94
98
  };
package/dist/cli/chat.js CHANGED
@@ -63,11 +63,15 @@ const handleLine = async (io, client, agent, state, line) => {
63
63
  *
64
64
  * Resolves with the exit code.
65
65
  */
66
- export const runChat = async (io, flags, version) => {
67
- const client = await connect(io, flags, version);
68
- if (client === undefined) {
66
+ export const runChat = async (io, flags, version, daemonOverrides) => {
67
+ const session = await connect(io, flags, version, {
68
+ autoStart: true,
69
+ daemonOverrides,
70
+ });
71
+ if (session === undefined) {
69
72
  return 1;
70
73
  }
74
+ const { client } = session;
71
75
  try {
72
76
  const agent = await chooseAgent(client, flags.agent);
73
77
  const terminal = io.terminal?.();
@@ -110,6 +114,6 @@ export const runChat = async (io, flags, version) => {
110
114
  return 1;
111
115
  }
112
116
  finally {
113
- await client.close();
117
+ await session.close();
114
118
  }
115
119
  };
@@ -1,6 +1,47 @@
1
1
  import { once } from "node:events";
2
+ import { readFile } from "node:fs/promises";
3
+ import { ConfigIssueSchema, decode } from "@wheatley-ai/protocol";
4
+ import { Type } from "typebox";
5
+ import { SeamError } from "../contracts/errors.js";
6
+ import { renderConfigDiagnostics } from "../core/config/diagnostics.js";
2
7
  import { errorMessage } from "../core/error-message.js";
3
8
  import { startWheatley } from "../wiring/daemon.js";
9
+ /** The `details` of a `config_invalid` error for a file on disk. */
10
+ const FileIssuesSchema = Type.Object({
11
+ file: Type.String(),
12
+ issues: Type.Array(ConfigIssueSchema),
13
+ });
14
+ /** True if stderr is a terminal and `NO_COLOR` is not set to a non-empty value (https://no-color.org). */
15
+ const useColor = (io) => io.stderrIsTTY === true && (io.env.NO_COLOR ?? "") === "";
16
+ /**
17
+ * Renders the source diagnostics of a `config_invalid` error, or returns `undefined` for any other error or if the file
18
+ * cannot be read.
19
+ */
20
+ const configDiagnostics = async (io,
21
+ // oxlint-disable-next-line anti-slop/no-unknown-parameters -- A caught value has no type.
22
+ error) => {
23
+ if (!(error instanceof SeamError) || error.code !== "config_invalid") {
24
+ return undefined;
25
+ }
26
+ const details = decode(FileIssuesSchema, error.details ?? null);
27
+ if (!details.ok) {
28
+ return undefined;
29
+ }
30
+ const { file, issues } = details.value;
31
+ try {
32
+ const source = await readFile(file, "utf-8");
33
+ return renderConfigDiagnostics({
34
+ color: useColor(io),
35
+ file,
36
+ issues,
37
+ source,
38
+ });
39
+ }
40
+ catch {
41
+ // The file changed or vanished after the failed read: report the error without a snippet.
42
+ return undefined;
43
+ }
44
+ };
4
45
  /**
5
46
  * `wheatley daemon`: runs the Deployment with every module, the Webhook Ingress, and the Control Server in the
6
47
  * foreground until `SIGINT` or `SIGTERM`, then drains and stops. Log records go to stderr as JSON lines. Resolves with
@@ -22,6 +63,10 @@ export const runDaemon = async (io, options) => {
22
63
  });
23
64
  }
24
65
  catch (error) {
66
+ const diagnostics = await configDiagnostics(io, error);
67
+ if (diagnostics !== undefined) {
68
+ io.stderr(`${diagnostics}\n`);
69
+ }
25
70
  io.stderr(`Cannot start the daemon: ${errorMessage(error)}\n`);
26
71
  return 1;
27
72
  }
package/dist/cli/io.js CHANGED
@@ -27,6 +27,7 @@ export const processIo = () => {
27
27
  },
28
28
  },
29
29
  shutdown: shutdown.signal,
30
+ stderrIsTTY: isatty(process.stderr.fd),
30
31
  stderr: (text) => {
31
32
  process.stderr.write(text);
32
33
  },
package/dist/cli/main.js CHANGED
@@ -1,37 +1,13 @@
1
1
  import { createConnection } from "node:net";
2
- import { parseArgs } from "node:util";
2
+ import { Command, CommanderError, InvalidArgumentError } from "commander";
3
3
  import { daemonSocket } from "../core/daemon-socket.js";
4
- import { errorMessage } from "../core/error-message.js";
5
- import { createOpsCommands, hostCliDeps } from "../ops/cli.js";
4
+ import { addOpsCommands, hostCliDeps } from "../ops/cli.js";
6
5
  import { runAsk } from "./ask.js";
7
6
  import { runChat } from "./chat.js";
8
7
  import { runDaemon } from "./daemon.js";
9
8
  import { runInit } from "./init.js";
10
9
  import { nextLine, packageVersion, resolveHome } from "./io.js";
11
10
  import { runStatus } from "./status.js";
12
- /** The usage text of the CLI. */
13
- export const USAGE = `Usage: wheatley <command> [options]
14
-
15
- Commands:
16
- init Create config.yaml and secrets.yaml in the Deployment home
17
- daemon Run the Deployment and its Control Server in the foreground
18
- chat Chat with an Agent in its CLI Chat
19
- ask Send one prompt to an Agent and print the reply
20
- status Show the health of the Deployment
21
- service Install or control the Wheatley service: install, start, stop, restart, status
22
- update Update Wheatley within its major version (--check, --manager npm|pnpm)
23
- restore List the backups of an Agent, or restore agent.sqlite: restore <agent> [backup]
24
-
25
- Options:
26
- -h, --help Show this help
27
- --home <dir> The Deployment home (default: $WHEATLEY_HOME or ~/.wheatley)
28
- --url <ws-url> Connect over TCP instead of the Unix socket in the home folder
29
- --agent <name> The Agent of chat and ask
30
- --provider <name> init: the model provider of the first Agent
31
- --model <id> init: the model of the first Agent
32
- --host <host> daemon: the TCP host
33
- --port <port> daemon: the TCP port
34
- `;
35
11
  /**
36
12
  * Resolves `true` if a daemon accepts connections on the Unix socket of `home` (see `daemonSocket`). Resolves `false`
37
13
  * if the connection fails for any reason, for example a missing socket file. It does not reject.
@@ -48,51 +24,24 @@ export const isDaemonRunning = async (home) => {
48
24
  });
49
25
  return await promise;
50
26
  };
51
- const OPS_COMMANDS = ["service", "update", "restore"];
52
- const isOpsCommand = (command) => OPS_COMMANDS.some((name) => name === command);
53
- /** Runs `service`, `update`, or `restore` with the ops line-based output. */
54
- const runOpsCommand = async (command, argv, io, home, overrides) => {
55
- const commands = createOpsCommands({
56
- ...hostCliDeps(async () => await isDaemonRunning(home)),
57
- homeDir: home,
58
- ...overrides,
59
- });
60
- return await commands[command](argv, {
61
- err: (line) => {
62
- io.stderr(`${line}\n`);
63
- },
64
- out: (line) => {
65
- io.stdout(`${line}\n`);
66
- },
67
- });
68
- };
69
- const HOME_FLAG = "--home";
70
- /**
71
- * Takes `--home <dir>` and `--home=<dir>` out of ops arguments, which the ops commands do not parse themselves.
72
- *
73
- * Errors: throws if `--home` has no value.
74
- */
75
- const takeHomeOption = (argv) => {
76
- const rest = [];
77
- let home;
78
- for (let index = 0; index < argv.length; index += 1) {
79
- const arg = argv[index] ?? "";
80
- if (arg.startsWith(`${HOME_FLAG}=`)) {
81
- home = arg.slice(HOME_FLAG.length + 1);
82
- }
83
- else if (arg === HOME_FLAG) {
84
- home = argv[index + 1];
85
- index += 1;
86
- if (home === undefined || home.startsWith("-")) {
87
- throw new Error(`Option '${HOME_FLAG} <dir>' argument missing`);
88
- }
89
- }
90
- else {
91
- rest.push(arg);
92
- }
27
+ const EXIT_OK = 0;
28
+ const EXIT_USAGE = 2;
29
+ /** Commander error codes after `--help`, `--version`, or a missing command, which print help or the version. */
30
+ const OUTPUT_CODES = new Set([
31
+ "commander.help",
32
+ "commander.helpDisplayed",
33
+ "commander.version",
34
+ ]);
35
+ const parsePort = (value) => {
36
+ const port = Number(value);
37
+ if (!Number.isInteger(port)) {
38
+ throw new InvalidArgumentError(`Invalid port: ${value}`);
93
39
  }
94
- return { home, rest };
40
+ return port;
95
41
  };
42
+ const addClientOptions = (command) => command
43
+ .option("--agent <name>", "The Agent")
44
+ .option("--url <ws-url>", "Connect over TCP instead of the Unix socket in the home folder");
96
45
  const readPrompt = async (io, positionals) => {
97
46
  if (positionals.length > 0) {
98
47
  return positionals.join(" ");
@@ -107,100 +56,139 @@ const readPrompt = async (io, positionals) => {
107
56
  lines.push(line);
108
57
  }
109
58
  };
59
+ const CHAT_VALUE_OPTIONS = new Set(["--home", "--agent", "--url"]);
60
+ const CHAT_OPTION_PREFIXES = ["--home=", "--agent=", "--url="];
110
61
  /**
111
- * Runs one CLI command and resolves with its exit code. `argv` excludes the program name, for example
112
- * `["ask", "--agent", "home", "What", "now?"]`.
62
+ * Routes bare `wheatley` (and `wheatley` with only chat or global options) to `chat`.
63
+ * Leaves `--help`, `--version`, explicit subcommands, and unknown options untouched.
113
64
  */
114
- export const runCli = async (argv, io, overrides = {}) => {
115
- let ops;
116
- try {
117
- ops = takeHomeOption(argv);
118
- }
119
- catch (error) {
120
- io.stderr(`${errorMessage(error)}\n${USAGE}`);
121
- return 2;
122
- }
123
- const [first, ...opsArgs] = ops.rest;
124
- // The ops commands parse their own flags, so they skip the root parser.
125
- if (isOpsCommand(first)) {
126
- return await runOpsCommand(first, opsArgs, io, resolveHome(ops.home, io.env), overrides.ops);
127
- }
128
- let parsed;
129
- try {
130
- parsed = parseCliArgs(argv);
131
- }
132
- catch (error) {
133
- io.stderr(`${errorMessage(error)}\n${USAGE}`);
134
- return 2;
135
- }
136
- const { values, positionals } = parsed;
137
- if (values.help === true) {
138
- io.stdout(USAGE);
139
- return 0;
140
- }
141
- const [command, ...rest] = positionals;
142
- const home = resolveHome(values.home, io.env);
143
- const version = await packageVersion();
144
- const client = { agent: values.agent, home, url: values.url };
145
- switch (command) {
146
- case "init": {
147
- return await runInit(io, {
148
- agent: values.agent,
149
- home,
150
- model: values.model,
151
- provider: values.provider,
152
- });
153
- }
154
- case "daemon": {
155
- const port = values.port === undefined ? undefined : Number(values.port);
156
- if (port !== undefined && !Number.isInteger(port)) {
157
- io.stderr(`Invalid port: ${values.port}\n`);
158
- return 2;
159
- }
160
- return await runDaemon(io, {
161
- home,
162
- host: values.host,
163
- overrides: overrides.daemon,
164
- port,
165
- version,
166
- });
65
+ const defaultToChat = (argv) => {
66
+ let expectValue = false;
67
+ for (const arg of argv) {
68
+ if (expectValue) {
69
+ expectValue = false;
70
+ continue;
167
71
  }
168
- case "chat": {
169
- return await runChat(io, client, version);
72
+ if (CHAT_VALUE_OPTIONS.has(arg)) {
73
+ expectValue = true;
74
+ continue;
170
75
  }
171
- case "ask": {
172
- const prompt = await readPrompt(io, rest);
173
- if (prompt.trim() === "") {
174
- io.stderr("ask needs a prompt as arguments or on standard input.\n");
175
- return 2;
176
- }
177
- return await runAsk(io, client, prompt, version);
76
+ if (CHAT_OPTION_PREFIXES.some((prefix) => arg.startsWith(prefix))) {
77
+ continue;
178
78
  }
179
- case "status": {
180
- return await runStatus(io, client, version);
181
- }
182
- case undefined: {
183
- io.stderr(USAGE);
184
- return 0;
79
+ return argv;
80
+ }
81
+ return ["chat", ...argv];
82
+ };
83
+ /**
84
+ * Creates the command tree of one `runCli` call. Its actions pass their exit code to `exit`. Commander writes help,
85
+ * version, and usage errors to `io` and throws a `CommanderError` in place of `process.exit()`.
86
+ */
87
+ const createProgram = (io, version, overrides, exit) => {
88
+ const program = new Command("wheatley")
89
+ .usage("[command] [options]")
90
+ .helpOption("-h, --help", "Show this help")
91
+ // The CLI has no `help` command. Commander adds one by default.
92
+ .helpCommand(false)
93
+ .version(version, "--version", "Show the Wheatley version")
94
+ .option("--home <dir>", "The Deployment home (default: $WHEATLEY_HOME or ~/.wheatley)")
95
+ .configureHelp({ showGlobalOptions: true })
96
+ .configureOutput({ writeErr: io.stderr, writeOut: io.stdout })
97
+ .showHelpAfterError()
98
+ .exitOverride();
99
+ const homeOf = (command) => resolveHome(command.optsWithGlobals().home, io.env);
100
+ const clientOf = (command, options) => ({
101
+ agent: options.agent,
102
+ home: homeOf(command),
103
+ url: options.url,
104
+ });
105
+ program
106
+ .command("init")
107
+ .description("Create config.yaml and secrets.yaml in the Deployment home")
108
+ .option("--agent <name>", "The name of the first Agent")
109
+ .option("--provider <name>", "The model provider of the first Agent")
110
+ .option("--model <id>", "The model of the first Agent")
111
+ .action(async (options, command) => {
112
+ exit(await runInit(io, {
113
+ agent: options.agent,
114
+ home: homeOf(command),
115
+ model: options.model,
116
+ provider: options.provider,
117
+ }));
118
+ });
119
+ program
120
+ .command("daemon")
121
+ .description("Run the Deployment and its Control Server in the foreground")
122
+ .option("--host <host>", "The TCP host")
123
+ .option("--port <port>", "The TCP port", parsePort)
124
+ .action(async (options, command) => {
125
+ exit(await runDaemon(io, {
126
+ home: homeOf(command),
127
+ host: options.host,
128
+ overrides: overrides.daemon,
129
+ port: options.port,
130
+ version,
131
+ }));
132
+ });
133
+ addClientOptions(program
134
+ .command("chat")
135
+ .description("Chat with an Agent in its CLI Chat (default)")).action(async (options, command) => {
136
+ exit(await runChat(io, clientOf(command, options), version, overrides.daemon));
137
+ });
138
+ addClientOptions(program
139
+ .command("ask")
140
+ .description("Send one prompt to an Agent and print the reply")
141
+ .argument("[prompt...]", "The prompt. Without it, ask reads the prompt from standard input")).action(async (words, options, command) => {
142
+ const prompt = await readPrompt(io, words);
143
+ if (prompt.trim() === "") {
144
+ io.stderr("ask needs a prompt as arguments or on standard input.\n");
145
+ exit(EXIT_USAGE);
146
+ return;
185
147
  }
186
- default: {
187
- io.stderr(`Unknown command: ${command}\n${USAGE}`);
188
- return 2;
148
+ exit(await runAsk(io, clientOf(command, options), prompt, version, overrides.daemon));
149
+ });
150
+ addClientOptions(program.command("status").description("Show the health of the Deployment")).action(async (options, command) => {
151
+ exit(await runStatus(io, clientOf(command, options), version));
152
+ });
153
+ addOpsCommands(program, {
154
+ deps: (command) => {
155
+ const home = homeOf(command);
156
+ return {
157
+ ...hostCliDeps(async () => await isDaemonRunning(home)),
158
+ homeDir: home,
159
+ ...overrides.ops,
160
+ };
161
+ },
162
+ exit,
163
+ io: {
164
+ err: (line) => {
165
+ io.stderr(`${line}\n`);
166
+ },
167
+ out: (line) => {
168
+ io.stdout(`${line}\n`);
169
+ },
170
+ },
171
+ });
172
+ return program;
173
+ };
174
+ /**
175
+ * Runs one CLI command and resolves with its exit code: 0 for success, `--help`, and `--version`, 1 for a runtime
176
+ * failure, and 2 for a usage error. `argv` excludes the program name, for example
177
+ * `["ask", "--agent", "home", "What", "now?"]`. `--home` can come before or after the command.
178
+ */
179
+ export const runCli = async (argv, io, overrides = {}) => {
180
+ let exitCode = EXIT_OK;
181
+ const program = createProgram(io, await packageVersion(), overrides, (code) => {
182
+ exitCode = code;
183
+ });
184
+ try {
185
+ await program.parseAsync([...defaultToChat(argv)], { from: "user" });
186
+ }
187
+ catch (error) {
188
+ if (!(error instanceof CommanderError)) {
189
+ throw error;
189
190
  }
191
+ return OUTPUT_CODES.has(error.code) ? EXIT_OK : EXIT_USAGE;
190
192
  }
193
+ return exitCode;
191
194
  };
192
- const parseCliArgs = (argv) => parseArgs({
193
- allowPositionals: true,
194
- args: [...argv],
195
- options: {
196
- agent: { type: "string" },
197
- help: { short: "h", type: "boolean" },
198
- home: { type: "string" },
199
- host: { type: "string" },
200
- model: { type: "string" },
201
- port: { type: "string" },
202
- provider: { type: "string" },
203
- url: { type: "string" },
204
- },
205
- strict: true,
206
- });
@@ -1,5 +1,7 @@
1
+ import { RpcError } from "@wheatley-ai/protocol";
1
2
  import { daemonSocket } from "../core/daemon-socket.js";
2
3
  import { errorMessage } from "../core/error-message.js";
4
+ import { startWheatley } from "../wiring/daemon.js";
3
5
  import { DaemonClient } from "./client.js";
4
6
  /** The daemon address of the flags. */
5
7
  export const targetOf = (flags) => flags.url === undefined
@@ -74,12 +76,66 @@ export const decideApproval = async (io, client, agent, approval, answer) => {
74
76
  }
75
77
  return true;
76
78
  };
77
- /** Connects to the daemon, or explains how to start it. */
78
- export const connect = async (io, flags, version) => {
79
+ const ignoreLog = () => {
80
+ // Ephemeral in-process daemons keep stdout and stderr clean for interactive chat and piped ask output.
81
+ };
82
+ const startEphemeralSession = async (io, flags, version, daemonOverrides) => {
83
+ let daemon;
79
84
  try {
80
- return await DaemonClient.connect(targetOf(flags), version);
85
+ daemon = await startWheatley({
86
+ env: io.env,
87
+ homeDir: flags.home,
88
+ port: 0,
89
+ version,
90
+ writeLog: ignoreLog,
91
+ ...daemonOverrides,
92
+ });
93
+ }
94
+ catch (error) {
95
+ io.stderr(`Cannot start the Wheatley daemon: ${errorMessage(error)}\n`);
96
+ return undefined;
97
+ }
98
+ try {
99
+ const client = await DaemonClient.connect({ url: daemon.server.url }, version);
100
+ return {
101
+ client,
102
+ close: async () => {
103
+ try {
104
+ await client.close();
105
+ }
106
+ finally {
107
+ await daemon.close();
108
+ }
109
+ },
110
+ };
111
+ }
112
+ catch (error) {
113
+ await daemon.close();
114
+ io.stderr(`Cannot reach the Wheatley daemon (${errorMessage(error)}).\n`);
115
+ return undefined;
116
+ }
117
+ };
118
+ /**
119
+ * Connects to the daemon. With `autoStart` and no `--url`, starts an in-process daemon for this session when no local
120
+ * daemon listens, and stops it when `close` runs. Otherwise reports how to start the daemon.
121
+ */
122
+ export const connect = async (io, flags, version, options = {}) => {
123
+ try {
124
+ const client = await DaemonClient.connect(targetOf(flags), version);
125
+ return {
126
+ client,
127
+ close: async () => {
128
+ await client.close();
129
+ },
130
+ };
81
131
  }
82
132
  catch (error) {
133
+ const canAutoStart = options.autoStart === true &&
134
+ flags.url === undefined &&
135
+ !(error instanceof RpcError);
136
+ if (canAutoStart) {
137
+ return await startEphemeralSession(io, flags, version, options.daemonOverrides);
138
+ }
83
139
  io.stderr(`Cannot reach the Wheatley daemon (${errorMessage(error)}). Start it with "wheatley daemon".\n`);
84
140
  return undefined;
85
141
  }
@@ -28,12 +28,12 @@ export const formatStatus = (status) => {
28
28
  };
29
29
  /** `wheatley status`: prints Deployment health. Resolves with the exit code. */
30
30
  export const runStatus = async (io, flags, version) => {
31
- const client = await connect(io, flags, version);
32
- if (client === undefined) {
31
+ const session = await connect(io, flags, version);
32
+ if (session === undefined) {
33
33
  return 1;
34
34
  }
35
35
  try {
36
- io.stdout(formatStatus(await client.request("system.status", {})));
36
+ io.stdout(formatStatus(await session.client.request("system.status", {})));
37
37
  return 0;
38
38
  }
39
39
  catch (error) {
@@ -41,6 +41,6 @@ export const runStatus = async (io, flags, version) => {
41
41
  return 1;
42
42
  }
43
43
  finally {
44
- await client.close();
44
+ await session.close();
45
45
  }
46
46
  };
@@ -3,6 +3,7 @@ import { Box, Static, Text, useApp, useInput, useWindowSize } from "ink";
3
3
  import { useEffect, useState, useSyncExternalStore } from "react";
4
4
  import { formatCost, formatCount, formatSeconds } from "./format.js";
5
5
  import { wrapLines } from "./markdown.js";
6
+ import { PickerPanel } from "./picker-panel.js";
6
7
  import { Prompt } from "./prompt.js";
7
8
  import { EntryView, LOGO_WIDTH } from "./transcript.js";
8
9
  /** The frames of the spinning logo. */
@@ -133,9 +134,15 @@ const StatusBar = ({ view, busy, columns }) => {
133
134
  export const ChatApp = ({ controller, version, history, onHistory, }) => {
134
135
  const view = useSyncExternalStore(controller.subscribe, controller.view);
135
136
  const { exit } = useApp();
136
- const { columns: terminalColumns } = useWindowSize();
137
+ const { columns: terminalColumns, rows } = useWindowSize();
137
138
  const columns = Math.max(MIN_WIDTH, terminalColumns - RIGHT_MARGIN);
138
139
  const { busy } = controller;
140
+ // The Prompt unmounts while a panel replaces it. It reads this history again when it mounts.
141
+ const [latestHistory, setLatestHistory] = useState(history);
142
+ const onPromptHistory = (next) => {
143
+ setLatestHistory(next);
144
+ onHistory(next);
145
+ };
139
146
  const onSubmit = (text) => {
140
147
  controller
141
148
  .submit(text)
@@ -154,6 +161,11 @@ export const ChatApp = ({ controller, version, history, onHistory, }) => {
154
161
  // `decide` reports its own errors as transcript entries.
155
162
  });
156
163
  };
164
+ const onChoose = () => {
165
+ controller.choosePicker().catch(() => {
166
+ // `choosePicker` reports its own errors as transcript entries.
167
+ });
168
+ };
157
169
  return (_jsxs(_Fragment, { children: [_jsx(Static, { items: [...view.entries], children: (entry) => (_jsx(Box, { width: columns, children: _jsx(EntryView, { columns: columns, entry: entry, version: version, view: view }) }, entry.id)) }), view.live.length === 0 ? undefined : (_jsx(Box, { marginLeft: LOGO_WIDTH, width: columns - LOGO_WIDTH, children: _jsx(Text, { children: wrapLines(view.live, columns - LOGO_WIDTH) }) })), view.activity === undefined ||
158
- view.approval !== undefined ? undefined : (_jsx(ActivityLine, { activity: view.activity, thinkingLines: view.thinkingLines })), view.approval === undefined ? (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsx(Prompt, { busy: busy, columns: columns, history: history, onExit: exit, onHistory: onHistory, onInterrupt: controller.interrupt, onSubmit: onSubmit }), _jsx(StatusBar, { busy: busy, columns: columns, view: view })] })) : (_jsx(ApprovalPanel, { approval: view.approval, onDecide: onDecide }, view.approval.approvalId))] }));
170
+ view.approval !== undefined ? undefined : (_jsx(ActivityLine, { activity: view.activity, thinkingLines: view.thinkingLines })), view.approval === undefined ? (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [view.picker === undefined ? (_jsx(Prompt, { busy: busy, columns: columns, history: latestHistory, onExit: exit, onHistory: onPromptHistory, onInterrupt: controller.interrupt, onSubmit: onSubmit })) : (_jsx(PickerPanel, { columns: columns, onCancel: controller.cancelPicker, onChoose: onChoose, onEdit: controller.editPicker, picker: view.picker, rows: rows })), _jsx(StatusBar, { busy: busy, columns: columns, view: view })] })) : (_jsx(ApprovalPanel, { approval: view.approval, onDecide: onDecide }, view.approval.approvalId))] }));
159
171
  };