@wheatley-ai/cli 0.3.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 (63) hide show
  1. package/dist/cli/ask.js +8 -4
  2. package/dist/cli/chat.js +8 -4
  3. package/dist/cli/daemon.js +45 -0
  4. package/dist/cli/io.js +1 -0
  5. package/dist/cli/main.js +145 -163
  6. package/dist/cli/session.js +59 -3
  7. package/dist/cli/status.js +4 -4
  8. package/dist/cli/tui/app.js +14 -2
  9. package/dist/cli/tui/controller.js +80 -19
  10. package/dist/cli/tui/markdown.js +229 -104
  11. package/dist/cli/tui/model-picker.js +76 -0
  12. package/dist/cli/tui/picker-panel.js +39 -0
  13. package/dist/core/agent/agent.js +23 -12
  14. package/dist/core/config/config-store.js +11 -6
  15. package/dist/core/config/diagnostics.js +116 -0
  16. package/dist/core/config/secret-store.js +13 -9
  17. package/dist/core/deployment.js +19 -1
  18. package/dist/core/markdown-tokens.js +60 -0
  19. package/dist/core/model-catalog.js +54 -0
  20. package/dist/core/rpc/deployment-handlers.js +2 -1
  21. package/dist/core/server/control-server.js +19 -21
  22. package/dist/core/server/http-server.js +17 -0
  23. package/dist/core/server/static-files.js +40 -66
  24. package/dist/dashboard/assets/index-DGa2Ps9u.js +12 -0
  25. package/dist/dashboard/assets/index-DeERxJOJ.css +2 -0
  26. package/dist/dashboard/assets/{sheet-presentation-CkgiDsTg.js → sheet-presentation-CZ1dO2kr.js} +1 -1
  27. package/dist/dashboard/index.html +2 -2
  28. package/dist/frontends/discord/approvals.js +8 -43
  29. package/dist/frontends/discord/binding.js +81 -8
  30. package/dist/frontends/discord/json-file.js +57 -0
  31. package/dist/frontends/discord/model-picker.js +276 -0
  32. package/dist/frontends/slack/binding.js +33 -3
  33. package/dist/frontends/slack/inbound.js +21 -12
  34. package/dist/frontends/slack/model-picker-blocks.js +147 -0
  35. package/dist/frontends/slack/outbound.js +27 -2
  36. package/dist/frontends/slack/schemas.js +9 -2
  37. package/dist/frontends/telegram/approvals.js +13 -48
  38. package/dist/frontends/telegram/binding.js +5 -0
  39. package/dist/frontends/telegram/client.js +7 -0
  40. package/dist/frontends/telegram/delivery.js +19 -6
  41. package/dist/frontends/telegram/inbound.js +64 -8
  42. package/dist/frontends/telegram/markdown.js +120 -83
  43. package/dist/frontends/telegram/model-picker.js +160 -0
  44. package/dist/frontends/telegram/token-store.js +73 -0
  45. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +13 -0
  46. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +11 -0
  47. package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +1 -1
  48. package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +1 -1
  49. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +20 -0
  50. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +9 -1
  51. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +2 -2
  52. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +2 -2
  53. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +23 -0
  54. package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +1 -1
  55. package/dist/node_modules/@wheatley-ai/sdk/package.json +1 -1
  56. package/dist/ops/cli.js +92 -98
  57. package/dist/ops/service.js +6 -1
  58. package/dist/ops/update.js +14 -27
  59. package/dist/triggers/delivery-codec.js +13 -0
  60. package/dist/triggers/webhook-ingress.js +89 -82
  61. package/package.json +9 -2
  62. package/dist/dashboard/assets/index-C9Rul5vE.css +0 -2
  63. package/dist/dashboard/assets/index-DThc2x_d.js +0 -11
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,38 +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, --method npm|pnpm|yarn|bun|brew|curl)
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
- --version Show the Wheatley version
28
- --home <dir> The Deployment home (default: $WHEATLEY_HOME or ~/.wheatley)
29
- --url <ws-url> Connect over TCP instead of the Unix socket in the home folder
30
- --agent <name> The Agent of chat and ask
31
- --provider <name> init: the model provider of the first Agent
32
- --model <id> init: the model of the first Agent
33
- --host <host> daemon: the TCP host
34
- --port <port> daemon: the TCP port
35
- `;
36
11
  /**
37
12
  * Resolves `true` if a daemon accepts connections on the Unix socket of `home` (see `daemonSocket`). Resolves `false`
38
13
  * if the connection fails for any reason, for example a missing socket file. It does not reject.
@@ -49,51 +24,24 @@ export const isDaemonRunning = async (home) => {
49
24
  });
50
25
  return await promise;
51
26
  };
52
- const OPS_COMMANDS = ["service", "update", "restore"];
53
- const isOpsCommand = (command) => OPS_COMMANDS.some((name) => name === command);
54
- /** Runs `service`, `update`, or `restore` with the ops line-based output. */
55
- const runOpsCommand = async (command, argv, io, home, overrides) => {
56
- const commands = createOpsCommands({
57
- ...hostCliDeps(async () => await isDaemonRunning(home)),
58
- homeDir: home,
59
- ...overrides,
60
- });
61
- return await commands[command](argv, {
62
- err: (line) => {
63
- io.stderr(`${line}\n`);
64
- },
65
- out: (line) => {
66
- io.stdout(`${line}\n`);
67
- },
68
- });
69
- };
70
- const HOME_FLAG = "--home";
71
- /**
72
- * Takes `--home <dir>` and `--home=<dir>` out of ops arguments, which the ops commands do not parse themselves.
73
- *
74
- * Errors: throws if `--home` has no value.
75
- */
76
- const takeHomeOption = (argv) => {
77
- const rest = [];
78
- let home;
79
- for (let index = 0; index < argv.length; index += 1) {
80
- const arg = argv[index] ?? "";
81
- if (arg.startsWith(`${HOME_FLAG}=`)) {
82
- home = arg.slice(HOME_FLAG.length + 1);
83
- }
84
- else if (arg === HOME_FLAG) {
85
- home = argv[index + 1];
86
- index += 1;
87
- if (home === undefined || home.startsWith("-")) {
88
- throw new Error(`Option '${HOME_FLAG} <dir>' argument missing`);
89
- }
90
- }
91
- else {
92
- rest.push(arg);
93
- }
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}`);
94
39
  }
95
- return { home, rest };
40
+ return port;
96
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");
97
45
  const readPrompt = async (io, positionals) => {
98
46
  if (positionals.length > 0) {
99
47
  return positionals.join(" ");
@@ -108,105 +56,139 @@ const readPrompt = async (io, positionals) => {
108
56
  lines.push(line);
109
57
  }
110
58
  };
59
+ const CHAT_VALUE_OPTIONS = new Set(["--home", "--agent", "--url"]);
60
+ const CHAT_OPTION_PREFIXES = ["--home=", "--agent=", "--url="];
111
61
  /**
112
- * Runs one CLI command and resolves with its exit code. `argv` excludes the program name, for example
113
- * `["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.
114
64
  */
115
- export const runCli = async (argv, io, overrides = {}) => {
116
- let ops;
117
- try {
118
- ops = takeHomeOption(argv);
119
- }
120
- catch (error) {
121
- io.stderr(`${errorMessage(error)}\n${USAGE}`);
122
- return 2;
123
- }
124
- const [first, ...opsArgs] = ops.rest;
125
- // The ops commands parse their own flags, so they skip the root parser.
126
- if (isOpsCommand(first)) {
127
- return await runOpsCommand(first, opsArgs, io, resolveHome(ops.home, io.env), overrides.ops);
128
- }
129
- let parsed;
130
- try {
131
- parsed = parseCliArgs(argv);
132
- }
133
- catch (error) {
134
- io.stderr(`${errorMessage(error)}\n${USAGE}`);
135
- return 2;
136
- }
137
- const { values, positionals } = parsed;
138
- if (values.help === true) {
139
- io.stdout(USAGE);
140
- return 0;
141
- }
142
- const version = await packageVersion();
143
- if (values.version === true) {
144
- io.stdout(`${version}\n`);
145
- return 0;
146
- }
147
- const [command, ...rest] = positionals;
148
- const home = resolveHome(values.home, io.env);
149
- const client = { agent: values.agent, home, url: values.url };
150
- switch (command) {
151
- case "init": {
152
- return await runInit(io, {
153
- agent: values.agent,
154
- home,
155
- model: values.model,
156
- provider: values.provider,
157
- });
158
- }
159
- case "daemon": {
160
- const port = values.port === undefined ? undefined : Number(values.port);
161
- if (port !== undefined && !Number.isInteger(port)) {
162
- io.stderr(`Invalid port: ${values.port}\n`);
163
- return 2;
164
- }
165
- return await runDaemon(io, {
166
- home,
167
- host: values.host,
168
- overrides: overrides.daemon,
169
- port,
170
- version,
171
- });
65
+ const defaultToChat = (argv) => {
66
+ let expectValue = false;
67
+ for (const arg of argv) {
68
+ if (expectValue) {
69
+ expectValue = false;
70
+ continue;
172
71
  }
173
- case "chat": {
174
- return await runChat(io, client, version);
72
+ if (CHAT_VALUE_OPTIONS.has(arg)) {
73
+ expectValue = true;
74
+ continue;
175
75
  }
176
- case "ask": {
177
- const prompt = await readPrompt(io, rest);
178
- if (prompt.trim() === "") {
179
- io.stderr("ask needs a prompt as arguments or on standard input.\n");
180
- return 2;
181
- }
182
- return await runAsk(io, client, prompt, version);
76
+ if (CHAT_OPTION_PREFIXES.some((prefix) => arg.startsWith(prefix))) {
77
+ continue;
183
78
  }
184
- case "status": {
185
- return await runStatus(io, client, version);
186
- }
187
- case undefined: {
188
- io.stderr(USAGE);
189
- 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;
190
147
  }
191
- default: {
192
- io.stderr(`Unknown command: ${command}\n${USAGE}`);
193
- 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;
194
190
  }
191
+ return OUTPUT_CODES.has(error.code) ? EXIT_OK : EXIT_USAGE;
195
192
  }
193
+ return exitCode;
196
194
  };
197
- const parseCliArgs = (argv) => parseArgs({
198
- allowPositionals: true,
199
- args: [...argv],
200
- options: {
201
- agent: { type: "string" },
202
- help: { short: "h", type: "boolean" },
203
- home: { type: "string" },
204
- host: { type: "string" },
205
- model: { type: "string" },
206
- port: { type: "string" },
207
- provider: { type: "string" },
208
- url: { type: "string" },
209
- version: { type: "boolean" },
210
- },
211
- strict: true,
212
- });
@@ -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
  };