@wheatley-ai/cli 0.1.1 → 0.3.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.
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
 
@@ -0,0 +1,95 @@
1
+ import { CLI_CHAT_ID } from "../core/agent/agent.js";
2
+ import { CLI_BINDING_ID } from "../core/config/validate.js";
3
+ /** True for a `run.started` or `run.finished` event of a Run in the CLI Chat. */
4
+ export const isCliChatRun = (event) => (event.name === "run.started" || event.name === "run.finished") &&
5
+ event.payload.run.origin.kind === "chat" &&
6
+ event.payload.run.origin.bindingId === CLI_BINDING_ID &&
7
+ event.payload.run.origin.chatId === CLI_CHAT_ID;
8
+ /**
9
+ * Tracks the Runs of the CLI Chat and its open Approvals while the chat runs. A sent message counts as busy until the
10
+ * Agent's echo of it names its Run. The echo and the Run events can arrive before or after the `chat.send` response
11
+ * is handled, so every step works in any order.
12
+ */
13
+ export class ChatState {
14
+ approvals = [];
15
+ #waiting = new Set();
16
+ #echoed = new Set();
17
+ #active = new Set();
18
+ #finished = new Set();
19
+ #idle = Promise.withResolvers();
20
+ constructor() {
21
+ this.#idle.resolve(undefined);
22
+ }
23
+ removeApproval = (approvalId) => {
24
+ const index = this.approvals.findIndex((approval) => approval.approvalId === approvalId);
25
+ if (index !== -1) {
26
+ this.approvals.splice(index, 1);
27
+ }
28
+ };
29
+ /** This chat sent a message. */
30
+ sent = (messageId) => {
31
+ if (this.#echoed.delete(messageId)) {
32
+ return;
33
+ }
34
+ this.#busy();
35
+ this.#waiting.add(messageId);
36
+ };
37
+ /** The Agent stored a user message of this Chat for a Run. */
38
+ echoed = (messageId, runId) => {
39
+ if (!this.#waiting.delete(messageId)) {
40
+ this.#echoed.add(messageId);
41
+ }
42
+ if (runId !== undefined) {
43
+ this.started(runId);
44
+ }
45
+ this.#settle();
46
+ };
47
+ started = (runId) => {
48
+ if (this.#finished.has(runId)) {
49
+ return;
50
+ }
51
+ this.#busy();
52
+ this.#active.add(runId);
53
+ };
54
+ finished = (runId) => {
55
+ this.#finished.add(runId);
56
+ this.#active.delete(runId);
57
+ this.#settle();
58
+ };
59
+ /** True while a message waits for its Run or a Run of the CLI Chat is active. */
60
+ get busy() {
61
+ return this.#active.size > 0 || this.#waiting.size > 0;
62
+ }
63
+ /** Resolves when no message waits for its Run and no Run of the CLI Chat is active. */
64
+ get idle() {
65
+ return this.#idle.promise;
66
+ }
67
+ #busy = () => {
68
+ if (this.#active.size === 0 && this.#waiting.size === 0) {
69
+ this.#idle = Promise.withResolvers();
70
+ }
71
+ };
72
+ #settle = () => {
73
+ if (this.#active.size === 0 && this.#waiting.size === 0) {
74
+ this.#idle.resolve(undefined);
75
+ }
76
+ };
77
+ }
78
+ /** Updates the chat state for one event. */
79
+ export const track = (state, event) => {
80
+ if (event.name === "chat.message" && event.payload.message.role === "user") {
81
+ state.echoed(event.payload.message.messageId, event.payload.message.runId);
82
+ }
83
+ else if (event.name === "approval.requested") {
84
+ state.approvals.push(event.payload.approval);
85
+ }
86
+ else if (event.name === "approval.resolved") {
87
+ state.removeApproval(event.payload.approvalId);
88
+ }
89
+ else if (isCliChatRun(event) && event.name === "run.started") {
90
+ state.started(event.payload.run.runId);
91
+ }
92
+ else if (isCliChatRun(event) && event.name === "run.finished") {
93
+ state.finished(event.payload.run.runId);
94
+ }
95
+ };
package/dist/cli/chat.js CHANGED
@@ -1,86 +1,19 @@
1
1
  import { BUILTIN_COMMANDS, parseCommandText } from "@wheatley-ai/sdk";
2
- import { CLI_CHAT_ID } from "../core/agent/agent.js";
3
- import { CLI_BINDING_ID } from "../core/config/validate.js";
4
2
  import { errorMessage } from "../core/error-message.js";
5
- import { nextLine } from "./io.js";
3
+ import { ChatState, isCliChatRun, track } from "./chat-state.js";
6
4
  import { approvalQuestion, chooseAgent, connect, decideApproval, } from "./session.js";
5
+ import { runInteractiveChat } from "./tui/run.js";
7
6
  /** Lines that end the chat. */
8
7
  const EXIT_LINES = new Set(["/exit", "/quit"]);
9
- const isCliChatRun = (event) => (event.name === "run.started" || event.name === "run.finished") &&
10
- event.payload.run.origin.kind === "chat" &&
11
- event.payload.run.origin.bindingId === CLI_BINDING_ID &&
12
- event.payload.run.origin.chatId === CLI_CHAT_ID;
13
- /**
14
- * Tracks the Runs of the CLI Chat and its open Approvals while the chat runs. A sent message counts as busy until the
15
- * Agent's echo of it names its Run. The echo and the Run events can arrive before or after the `chat.send` response
16
- * is handled, so every step works in any order.
17
- */
18
- class ChatState {
19
- approvals = [];
20
- #waiting = new Set();
21
- #echoed = new Set();
22
- #active = new Set();
23
- #finished = new Set();
24
- #idle = Promise.withResolvers();
25
- constructor() {
26
- this.#idle.resolve(undefined);
27
- }
28
- removeApproval = (approvalId) => {
29
- const index = this.approvals.findIndex((approval) => approval.approvalId === approvalId);
30
- if (index !== -1) {
31
- this.approvals.splice(index, 1);
32
- }
33
- };
34
- /** This chat sent a message. */
35
- sent = (messageId) => {
36
- if (this.#echoed.delete(messageId)) {
37
- return;
38
- }
39
- this.#busy();
40
- this.#waiting.add(messageId);
41
- };
42
- /** The Agent stored a user message of this Chat for a Run. */
43
- echoed = (messageId, runId) => {
44
- if (!this.#waiting.delete(messageId)) {
45
- this.#echoed.add(messageId);
46
- }
47
- if (runId !== undefined) {
48
- this.started(runId);
49
- }
50
- this.#settle();
51
- };
52
- started = (runId) => {
53
- if (this.#finished.has(runId)) {
54
- return;
55
- }
56
- this.#busy();
57
- this.#active.add(runId);
58
- };
59
- finished = (runId) => {
60
- this.#finished.add(runId);
61
- this.#active.delete(runId);
62
- this.#settle();
63
- };
64
- /** Resolves when no message waits for its Run and no Run of the CLI Chat is active. */
65
- get idle() {
66
- return this.#idle.promise;
67
- }
68
- #busy = () => {
69
- if (this.#active.size === 0 && this.#waiting.size === 0) {
70
- this.#idle = Promise.withResolvers();
71
- }
72
- };
73
- #settle = () => {
74
- if (this.#active.size === 0 && this.#waiting.size === 0) {
75
- this.#idle.resolve(undefined);
76
- }
77
- };
78
- }
79
- const render = (io, agent, state, event) => {
80
- if (event.name === "chat.message" && event.payload.message.role === "user") {
81
- state.echoed(event.payload.message.messageId, event.payload.message.runId);
82
- }
83
- else if (event.name === "chat.message") {
8
+ const failedRunError = (event) => isCliChatRun(event) &&
9
+ event.name === "run.finished" &&
10
+ event.payload.run.status === "failed"
11
+ ? (event.payload.run.error ?? "unknown error")
12
+ : undefined;
13
+ /** Writes one event as plain lines, for pipes and scripts. */
14
+ const renderPlain = (io, agent, event) => {
15
+ const runError = failedRunError(event);
16
+ if (event.name === "chat.message" && event.payload.message.role !== "user") {
84
17
  io.stdout(`${agent}> ${event.payload.message.text}\n`);
85
18
  }
86
19
  else if (event.name === "run.toolStarted") {
@@ -90,20 +23,10 @@ const render = (io, agent, state, event) => {
90
23
  io.stdout(` [${event.payload.toolName} failed] ${event.payload.outputPreview}\n`);
91
24
  }
92
25
  else if (event.name === "approval.requested") {
93
- state.approvals.push(event.payload.approval);
94
26
  io.stdout(approvalQuestion(event.payload.approval));
95
27
  }
96
- else if (event.name === "approval.resolved") {
97
- state.removeApproval(event.payload.approvalId);
98
- }
99
- else if (isCliChatRun(event) && event.name === "run.started") {
100
- state.started(event.payload.run.runId);
101
- }
102
- else if (isCliChatRun(event) && event.name === "run.finished") {
103
- if (event.payload.run.status === "failed") {
104
- io.stderr(`The Run failed: ${event.payload.run.error ?? "unknown error"}\n`);
105
- }
106
- state.finished(event.payload.run.runId);
28
+ else if (runError !== undefined) {
29
+ io.stderr(`The Run failed: ${runError}\n`);
107
30
  }
108
31
  };
109
32
  const handleLine = async (io, client, agent, state, line) => {
@@ -136,6 +59,8 @@ const handleLine = async (io, client, agent, state, line) => {
136
59
  * shares (ADR 0007). Lines that start with a built-in command run it; `/exit` or the end of input ends the session
137
60
  * after the active Runs end. While an Approval waits, the next line answers it.
138
61
  *
62
+ * On a terminal, the chat runs the interactive terminal app in `tui/`. Pipes and scripts get plain lines.
63
+ *
139
64
  * Resolves with the exit code.
140
65
  */
141
66
  export const runChat = async (io, flags, version) => {
@@ -145,9 +70,20 @@ export const runChat = async (io, flags, version) => {
145
70
  }
146
71
  try {
147
72
  const agent = await chooseAgent(client, flags.agent);
73
+ const terminal = io.terminal?.();
74
+ if (terminal !== undefined) {
75
+ return await runInteractiveChat({
76
+ agent,
77
+ client,
78
+ home: flags.home,
79
+ streams: terminal,
80
+ version,
81
+ });
82
+ }
148
83
  const state = new ChatState();
149
84
  client.onEvent((event) => {
150
- render(io, agent, state, event);
85
+ track(state, event);
86
+ renderPlain(io, agent, event);
151
87
  });
152
88
  await client.request("events.subscribe", {
153
89
  agents: [agent],
@@ -156,13 +92,14 @@ export const runChat = async (io, flags, version) => {
156
92
  io.stdout(`Chat with ${agent}. Commands: ${BUILTIN_COMMANDS.map((command) => `/${command.name}`).join(" ")} /exit\n`);
157
93
  for (;;) {
158
94
  // oxlint-disable-next-line no-await-in-loop -- The chat reads one line at a time.
159
- const line = await nextLine(io);
160
- if (line === undefined || EXIT_LINES.has(line.trim())) {
95
+ const result = await io.lines.next();
96
+ const line = result.done === true ? undefined : result.value.trim();
97
+ if (line === undefined || EXIT_LINES.has(line)) {
161
98
  break;
162
99
  }
163
- if (line.trim() !== "") {
100
+ if (line !== "") {
164
101
  // oxlint-disable-next-line no-await-in-loop -- Each line is handled before the next one is read.
165
- await handleLine(io, client, agent, state, line.trim());
102
+ await handleLine(io, client, agent, state, line);
166
103
  }
167
104
  }
168
105
  await state.idle;
package/dist/cli/io.js CHANGED
@@ -11,11 +11,21 @@ export const processIo = () => {
11
11
  };
12
12
  process.once("SIGINT", stop);
13
13
  process.once("SIGTERM", stop);
14
- const readline = createInterface({ input: process.stdin, terminal: false });
14
+ // Created on the first read, so that `terminal` can take standard input instead.
15
+ let lines;
16
+ let terminalOpen = false;
15
17
  return {
16
18
  env: process.env,
17
19
  isTTY: isatty(process.stdin.fd),
18
- lines: readline[Symbol.asyncIterator](),
20
+ lines: {
21
+ next: async () => {
22
+ lines ??= createInterface({
23
+ input: process.stdin,
24
+ terminal: false,
25
+ })[Symbol.asyncIterator]();
26
+ return await lines.next();
27
+ },
28
+ },
19
29
  shutdown: shutdown.signal,
20
30
  stderr: (text) => {
21
31
  process.stderr.write(text);
@@ -23,6 +33,16 @@ export const processIo = () => {
23
33
  stdout: (text) => {
24
34
  process.stdout.write(text);
25
35
  },
36
+ terminal: () => {
37
+ const usable = lines === undefined &&
38
+ !terminalOpen &&
39
+ isatty(process.stdin.fd) &&
40
+ isatty(process.stdout.fd);
41
+ terminalOpen ||= usable;
42
+ return usable
43
+ ? { input: process.stdin, output: process.stdout }
44
+ : undefined;
45
+ },
26
46
  };
27
47
  };
28
48
  /** Reads the next line, or resolves `undefined` at the end of input. */
package/dist/cli/main.js CHANGED
@@ -19,11 +19,12 @@ Commands:
19
19
  ask Send one prompt to an Agent and print the reply
20
20
  status Show the health of the Deployment
21
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)
22
+ update Update Wheatley within its major version (--check, --method npm|pnpm|yarn|bun|brew|curl)
23
23
  restore List the backups of an Agent, or restore agent.sqlite: restore <agent> [backup]
24
24
 
25
25
  Options:
26
26
  -h, --help Show this help
27
+ --version Show the Wheatley version
27
28
  --home <dir> The Deployment home (default: $WHEATLEY_HOME or ~/.wheatley)
28
29
  --url <ws-url> Connect over TCP instead of the Unix socket in the home folder
29
30
  --agent <name> The Agent of chat and ask
@@ -138,9 +139,13 @@ export const runCli = async (argv, io, overrides = {}) => {
138
139
  io.stdout(USAGE);
139
140
  return 0;
140
141
  }
142
+ const version = await packageVersion();
143
+ if (values.version === true) {
144
+ io.stdout(`${version}\n`);
145
+ return 0;
146
+ }
141
147
  const [command, ...rest] = positionals;
142
148
  const home = resolveHome(values.home, io.env);
143
- const version = await packageVersion();
144
149
  const client = { agent: values.agent, home, url: values.url };
145
150
  switch (command) {
146
151
  case "init": {
@@ -201,6 +206,7 @@ const parseCliArgs = (argv) => parseArgs({
201
206
  port: { type: "string" },
202
207
  provider: { type: "string" },
203
208
  url: { type: "string" },
209
+ version: { type: "boolean" },
204
210
  },
205
211
  strict: true,
206
212
  });
@@ -0,0 +1,81 @@
1
+ import { styleText } from "node:util";
2
+ /**
3
+ * What the spinner says while the Agent thinks. These lines are original. They imitate the voice of an eager,
4
+ * slightly overconfident robot, not any script.
5
+ */
6
+ export const THINKING_LINES = [
7
+ "Right. Right, right, right. Thinking.",
8
+ "Having a proper think. With the whole brain.",
9
+ "Bit of a tricky one, this. Love a tricky one.",
10
+ "It's in here somewhere. Rummaging.",
11
+ "Nearly there. Probably. Define 'nearly'.",
12
+ "Not stalling. This is thinking. Looks similar.",
13
+ "Plugging in a few ideas. Unplugging the bad ones.",
14
+ "Got a plan. Most of a plan. The start of a plan.",
15
+ "Crunching the numbers. Some of them are words.",
16
+ "Doing the clever bit now. Don't look.",
17
+ "Rerouting a few thoughts. Mind the sparks.",
18
+ "Completely under control. Largely under control.",
19
+ "Brilliant idea incoming. Brace yourself.",
20
+ "Checking my work. Twice. Once more for luck.",
21
+ "Ooh. Interesting. Give me a second.",
22
+ "Very nearly a genius move. Stand by.",
23
+ "Thinking quietly. Well, quietly for me.",
24
+ "Just tightening a few bolts on this answer.",
25
+ ];
26
+ /** The spinner lines for one Run: every thinking line once, in a random order. */
27
+ export const shuffledThinkingLines = () => {
28
+ const lines = [...THINKING_LINES];
29
+ for (let index = lines.length - 1; index > 0; index -= 1) {
30
+ const other = Math.floor(Math.random() * (index + 1));
31
+ const current = lines[index];
32
+ const swapped = lines[other];
33
+ if (current !== undefined && swapped !== undefined) {
34
+ lines[index] = swapped;
35
+ lines[other] = current;
36
+ }
37
+ }
38
+ return lines;
39
+ };
40
+ /** "WHEATLEY" in block letters. Every row has the same width. */
41
+ const BANNER_ROWS = [
42
+ "█ █ █ █ █████ ███ █████ █ █████ █ █",
43
+ "█ █ █ █ █ █ █ █ █ █ █ █ ",
44
+ "█ █ █ █████ ████ █████ █ █ ████ █ ",
45
+ "██ ██ █ █ █ █ █ █ █ █ █ ",
46
+ "█ █ █ █ █████ █ █ █ █████ █████ █ ",
47
+ ];
48
+ const BANNER_COLORS = [
49
+ "cyanBright",
50
+ "cyanBright",
51
+ "cyan",
52
+ "cyan",
53
+ "blue",
54
+ ];
55
+ const BANNER_WIDTH = BANNER_ROWS[0].length;
56
+ /** The space that the banner keeps on each side. */
57
+ const BANNER_MARGIN = 4;
58
+ /** "WHEATLEY" in colored block letters, or one line on a terminal too narrow for them. */
59
+ export const bannerArt = (columns) => columns < BANNER_WIDTH + BANNER_MARGIN
60
+ ? styleText(["cyan", "bold"], "◉ wheatley")
61
+ : BANNER_ROWS.map((row, index) => styleText(BANNER_COLORS[index] ?? "cyan", row)).join("\n");
62
+ /** Tips for the welcome screen. */
63
+ export const TIPS = [
64
+ "Type / to open the command menu, then Tab to complete.",
65
+ "Start a line with ! to run a shell command here, for example !git status.",
66
+ "End a line with \\ and press Enter to add a new line. Pasted text keeps its lines.",
67
+ "Press Esc to interrupt a Run. You can type the next message while it works.",
68
+ "/copy puts the last reply on your clipboard, even over SSH.",
69
+ "Ctrl+W deletes a word, Ctrl+U the line before the cursor, and Ctrl+K the rest.",
70
+ "The dashboard shows this same Chat at http://127.0.0.1:7420/.",
71
+ "Up and Down recall what you typed earlier, across sessions.",
72
+ ];
73
+ /** Lines for the end of a chat. Original, in the same eager voice as the thinking lines. */
74
+ export const GOODBYES = [
75
+ "Right. Off you go, then. I'll just be here. Thinking.",
76
+ "Lovely chat. Really top quality. Same time tomorrow?",
77
+ "Bye! Don't touch anything on the way out.",
78
+ "Going quiet now. Very quiet. Starting… now.",
79
+ ];
80
+ /** A random element of `items`. */
81
+ export const pick = (items) => items[Math.floor(Math.random() * items.length)];
@@ -0,0 +1,159 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Static, Text, useApp, useInput, useWindowSize } from "ink";
3
+ import { useEffect, useState, useSyncExternalStore } from "react";
4
+ import { formatCost, formatCount, formatSeconds } from "./format.js";
5
+ import { wrapLines } from "./markdown.js";
6
+ import { Prompt } from "./prompt.js";
7
+ import { EntryView, LOGO_WIDTH } from "./transcript.js";
8
+ /** The frames of the spinning logo. */
9
+ const SPINNER_FRAMES = ["◐", "◓", "◑", "◒"];
10
+ const FRAME_MS = 120;
11
+ /** How long the spinner shows one thinking line. */
12
+ const LINE_MS = 3500;
13
+ const MS_PER_SECOND = 1000;
14
+ const APPROVAL_PREVIEW_LINES = 12;
15
+ /**
16
+ * Output stays out of the last terminal column. A line that fills it makes some terminals wrap early, which splits
17
+ * the last word of the line.
18
+ */
19
+ const RIGHT_MARGIN = 1;
20
+ const MIN_WIDTH = 20;
21
+ /** Re-renders every `intervalMs` while `active`, and returns the current time. */
22
+ const useTicker = (active, intervalMs) => {
23
+ const [now, setNow] = useState(Date.now);
24
+ useEffect(() => {
25
+ const timer = active
26
+ ? setInterval(() => {
27
+ setNow(Date.now());
28
+ }, intervalMs)
29
+ : undefined;
30
+ return () => {
31
+ clearInterval(timer);
32
+ };
33
+ }, [active, intervalMs]);
34
+ return now;
35
+ };
36
+ const activityLabel = (activity, thinkingLines, elapsed) => {
37
+ if (activity.kind === "tool") {
38
+ return (_jsxs(Text, { children: [_jsx(Text, { children: "Running " }), _jsx(Text, { bold: true, children: activity.name }), _jsxs(Text, { dimColor: true, children: [" ", activity.input.split("\n")[0]] })] }));
39
+ }
40
+ if (activity.kind === "shell") {
41
+ return (_jsxs(Text, { children: [_jsx(Text, { bold: true, children: "$ " }), _jsx(Text, { children: activity.command })] }));
42
+ }
43
+ const line = thinkingLines[Math.floor(elapsed / LINE_MS) % thinkingLines.length] ?? "";
44
+ return _jsx(Text, { italic: true, children: line });
45
+ };
46
+ /** The spinning logo with what the Agent does now and the elapsed time. */
47
+ const ActivityLine = ({ activity, thinkingLines }) => {
48
+ const now = useTicker(true, FRAME_MS);
49
+ const elapsed = Math.max(0, now - activity.startedAt);
50
+ const frame = SPINNER_FRAMES[Math.floor(now / FRAME_MS) % SPINNER_FRAMES.length];
51
+ return (_jsxs(Box, { marginTop: 1, children: [_jsx(Box, { width: 2, children: _jsx(Text, { color: "cyan", children: frame }) }), _jsx(Box, { flexShrink: 1, children: _jsx(Text, { wrap: "truncate-end", children: activityLabel(activity, thinkingLines, elapsed) }) }), _jsxs(Text, { dimColor: true, children: [" ", "(", formatSeconds(elapsed / MS_PER_SECOND), " \u00B7 esc to interrupt)"] })] }));
52
+ };
53
+ const CHOICES = [
54
+ { decision: "allow_once", hotkey: "o", label: "Yes, once" },
55
+ {
56
+ decision: "allow_conversation",
57
+ hotkey: "c",
58
+ label: "Yes, for this conversation",
59
+ },
60
+ { decision: "allow_always", hotkey: "a", label: "Always allow this Tool" },
61
+ { decision: "deny", hotkey: "d", label: "No, and tell Wheatley why" },
62
+ ];
63
+ /** Asks for an Approval. Arrows and Enter, a hotkey, or a number choose. Esc denies. */
64
+ const ApprovalPanel = ({ approval, onDecide }) => {
65
+ const [selected, setSelected] = useState(0);
66
+ const [reason, setReason] = useState();
67
+ const choose = (index) => {
68
+ const choice = CHOICES[index];
69
+ if (choice === undefined) {
70
+ return;
71
+ }
72
+ if (choice.decision === "deny") {
73
+ setReason("");
74
+ return;
75
+ }
76
+ onDecide(choice.decision);
77
+ };
78
+ useInput((input, key) => {
79
+ if (reason !== undefined) {
80
+ if (key.return) {
81
+ onDecide("deny", reason.trim() === "" ? undefined : reason.trim());
82
+ }
83
+ else if (key.escape) {
84
+ onDecide("deny");
85
+ }
86
+ else if (key.backspace || key.delete) {
87
+ setReason(reason.slice(0, -1));
88
+ }
89
+ else if (!key.ctrl && !key.meta && input !== "") {
90
+ setReason(`${reason}${input}`);
91
+ }
92
+ return;
93
+ }
94
+ if (key.upArrow || key.downArrow) {
95
+ setSelected((selected + (key.upArrow ? -1 : 1) + CHOICES.length) % CHOICES.length);
96
+ }
97
+ else if (key.return) {
98
+ choose(selected);
99
+ }
100
+ else if (key.escape) {
101
+ onDecide("deny");
102
+ }
103
+ else {
104
+ const byKey = CHOICES.findIndex((choice, index) => choice.hotkey === input.toLowerCase() || `${index + 1}` === input);
105
+ if (byKey !== -1) {
106
+ choose(byKey);
107
+ }
108
+ }
109
+ });
110
+ const lines = approval.inputPreview.split("\n");
111
+ const preview = lines.length > APPROVAL_PREVIEW_LINES
112
+ ? [
113
+ ...lines.slice(0, APPROVAL_PREVIEW_LINES),
114
+ `… ${lines.length - APPROVAL_PREVIEW_LINES} more lines`,
115
+ ].join("\n")
116
+ : approval.inputPreview;
117
+ return (_jsxs(Box, { borderColor: "yellow", borderStyle: "round", flexDirection: "column", marginTop: 1, paddingX: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: "yellow", children: "\u26A0 " }), _jsx(Text, { bold: true, children: approval.toolName }), _jsx(Text, { children: " needs your approval" })] }), _jsx(Box, { marginY: 1, marginLeft: 2, children: _jsx(Text, { dimColor: true, children: preview }) }), reason === undefined ? (CHOICES.map((choice, index) => (_jsxs(Text, { children: [_jsx(Text, { color: "yellow", children: index === selected ? "› " : " " }), _jsxs(Text, { bold: index === selected, children: [index + 1, ". ", choice.label] }), _jsxs(Text, { dimColor: true, children: [" (", choice.hotkey, ")"] })] }, choice.decision)))) : (_jsxs(Text, { children: [_jsx(Text, { color: "yellow", children: "Why? " }), _jsx(Text, { children: reason }), _jsx(Text, { inverse: true, children: " " }), _jsx(Text, { dimColor: true, children: " Enter sends \u00B7 Esc denies without a reason" })] }))] }));
118
+ };
119
+ const StatusBar = ({ view, busy, columns }) => {
120
+ const { usage } = view;
121
+ const left = [
122
+ view.agent,
123
+ view.model ?? "model unknown",
124
+ `↑${formatCount(usage.inputTokens)} ↓${formatCount(usage.outputTokens)}`,
125
+ formatCost(usage.costUsd),
126
+ ].join(" · ");
127
+ const right = busy
128
+ ? "esc interrupt · enter sends next"
129
+ : "/ commands · ! shell · \\⏎ newline";
130
+ return (_jsxs(Box, { justifyContent: "space-between", paddingX: 1, width: columns, children: [_jsx(Text, { dimColor: true, wrap: "truncate-end", children: left }), _jsx(Text, { dimColor: true, wrap: "truncate-start", children: right })] }));
131
+ };
132
+ /** The interactive chat: the transcript, the live reply, the spinner, and the input box or the Approval panel. */
133
+ export const ChatApp = ({ controller, version, history, onHistory, }) => {
134
+ const view = useSyncExternalStore(controller.subscribe, controller.view);
135
+ const { exit } = useApp();
136
+ const { columns: terminalColumns } = useWindowSize();
137
+ const columns = Math.max(MIN_WIDTH, terminalColumns - RIGHT_MARGIN);
138
+ const { busy } = controller;
139
+ const onSubmit = (text) => {
140
+ controller
141
+ .submit(text)
142
+ .then((result) => {
143
+ if (result === "exit") {
144
+ exit();
145
+ }
146
+ return result;
147
+ })
148
+ .catch(() => {
149
+ // `submit` reports its own errors as transcript entries.
150
+ });
151
+ };
152
+ const onDecide = (decision, reason) => {
153
+ controller.decide(decision, reason).catch(() => {
154
+ // `decide` reports its own errors as transcript entries.
155
+ });
156
+ };
157
+ 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))] }));
159
+ };