reasonally 0.5.0 → 0.6.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.
@@ -6,8 +6,10 @@ import { createHash, randomBytes } from "node:crypto";
6
6
  import { access, appendFile, chmod, mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile, } from "node:fs/promises";
7
7
  import { hostname } from "node:os";
8
8
  import { basename, join } from "node:path";
9
+ import { contentText } from "./compact.js";
9
10
  import { CONTINUE_PROMPT, HELPER_PLAN_ON_NOTE, INTERRUPTED_NOTE, PLAN_OFF_NOTE, PLAN_ON_NOTE, } from "./loop-constants.js";
10
11
  import { PLAN_TOOL } from "./tools/plan.js";
12
+ import { commandLabel } from "./command-template.js";
11
13
  /** A new session's id, which is also its file name: when it started, plus a few random characters. */
12
14
  export function newSessionId(now = new Date()) {
13
15
  const stamp = now.toISOString().replace(/[:.]/g, "-");
@@ -270,11 +272,69 @@ function planArgument(args) {
270
272
  }
271
273
  /** Notes the agent adds in front of a message, never shown as what the user wrote. */
272
274
  const LEADING_NOTES = [INTERRUPTED_NOTE, PLAN_ON_NOTE, HELPER_PLAN_ON_NOTE, PLAN_OFF_NOTE];
275
+ /**
276
+ * A message as it's saved: images become a placeholder, so session files stay small and their
277
+ * content stays text. The conversation in memory keeps them. Other messages are returned as is.
278
+ */
279
+ export function savedMessage(message) {
280
+ if (message.role !== "user" || typeof message.content === "string")
281
+ return message;
282
+ return { ...message, content: contentText(message.content) };
283
+ }
284
+ /**
285
+ * The record a host saves for a change to the conversation. Every kind of change has its own
286
+ * record (a change saved as the wrong kind would rewrite the conversation on the next load).
287
+ * Images become `[image]` (see `savedMessage`): files stay small and hold no screenshots, while the
288
+ * conversation in memory keeps them. A slash command goes beside its message, never in it: older
289
+ * versions read only `message`, so they never send it on.
290
+ */
291
+ export function changeRecord(change) {
292
+ switch (change.type) {
293
+ case "usage":
294
+ return {
295
+ type: "usage",
296
+ promptTokens: change.usage.promptTokens,
297
+ completionTokens: change.usage.completionTokens,
298
+ costMicros: change.costMicros.toString(),
299
+ };
300
+ case "append": {
301
+ const message = savedMessage(change.message);
302
+ if (message.role !== "user" || !message.command)
303
+ return { type: "append", message };
304
+ const { command, ...rest } = message;
305
+ return { type: "append", message: rest, command };
306
+ }
307
+ case "replace":
308
+ return {
309
+ type: "replace",
310
+ reason: change.reason,
311
+ messages: change.messages.map((m) => savedMessage(withoutCommand(m))),
312
+ };
313
+ default: {
314
+ const unknown = change;
315
+ throw new Error(`No session record for ${JSON.stringify(unknown)}`);
316
+ }
317
+ }
318
+ }
319
+ function withoutCommand(message) {
320
+ if (message.role !== "user" || !message.command)
321
+ return message;
322
+ const copy = { ...message };
323
+ delete copy.command;
324
+ return copy;
325
+ }
326
+ /** A saved `command`, if it has the right shape (a file edited by hand may not). */
327
+ function commandOf(value) {
328
+ const c = value;
329
+ return c && typeof c.name === "string" && c.name && typeof c.args === "string"
330
+ ? { name: c.name, args: c.args }
331
+ : null;
332
+ }
273
333
  /** Strips our own markers from a user message, for showing it. */
274
334
  export function userText(content) {
275
335
  if (content === CONTINUE_PROMPT)
276
336
  return null;
277
- let text = content;
337
+ let text = typeof content === "string" ? content : contentText(content);
278
338
  for (let found = true; found;) {
279
339
  const note = LEADING_NOTES.find((n) => text.startsWith(n));
280
340
  found = Boolean(note);
@@ -331,12 +391,14 @@ export async function loadSession(path) {
331
391
  display.push({ kind: "compacted" });
332
392
  break;
333
393
  case "append": {
334
- const m = r.message;
394
+ const command = r.message.role === "user" ? commandOf(r.command) : null;
395
+ const m = command && r.message.role === "user" ? { ...r.message, command } : r.message;
335
396
  messages.push(m);
336
397
  if (m.role === "user") {
337
- const shown = userText(m.content);
398
+ // A tool call's images, added by the agent: not something the user wrote.
399
+ const shown = m.synthetic ? null : userText(m.content);
338
400
  if (shown)
339
- display.push({ kind: "user", text: shown });
401
+ display.push({ kind: "user", text: shown, ...(command ? { command } : {}) });
340
402
  }
341
403
  else if (m.role === "assistant") {
342
404
  if (m.content)
@@ -396,13 +458,19 @@ export async function listSessions(dir) {
396
458
  id: s.meta.id,
397
459
  path: s.path,
398
460
  surface: s.meta.surface ?? "terminal",
399
- firstMessage: s.display.find((d) => d.kind === "user").text,
461
+ firstMessage: shownText(s.display.find((d) => d.kind === "user")),
400
462
  model: s.model,
401
463
  costMicros: s.costMicros,
402
464
  updatedAt: s.updatedAt,
403
465
  }))
404
466
  .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime() || b.id.localeCompare(a.id));
405
467
  }
468
+ /** How a user message reads in a list: what was typed (`/review auth` for a command). */
469
+ function shownText(entry) {
470
+ if (entry.kind !== "user")
471
+ return "";
472
+ return entry.command ? commandLabel(entry.command) : entry.text;
473
+ }
406
474
  /** "just now", "5m ago", "3h ago", "2d ago", or the date. */
407
475
  export function timeAgo(date, now = new Date()) {
408
476
  const s = Math.max(0, (now.getTime() - date.getTime()) / 1000);
@@ -55,6 +55,21 @@ export function isLocalHostname(hostname) {
55
55
  // A single label ("router", "nas") only resolves through local search domains.
56
56
  !host.includes("."));
57
57
  }
58
+ /**
59
+ * This computer itself, by its exact names: `localhost`, `*.localhost`, `127.0.0.1` and `[::1]`.
60
+ * Narrower than `isLocalHostname`, which also counts private networks, `.local` names and single
61
+ * labels (a router, a NAS): those aren't the app being built here.
62
+ */
63
+ export function isLoopbackHostname(hostname) {
64
+ const host = hostname.toLowerCase().replace(/\.$/, "");
65
+ if (!isLocalHostname(host))
66
+ return false;
67
+ return (host === "localhost" ||
68
+ host.endsWith(".localhost") ||
69
+ host === "127.0.0.1" ||
70
+ host === "[::1]" ||
71
+ host === "::1");
72
+ }
58
73
  const SCHEME = /^[a-z][a-z0-9+.-]*:/i;
59
74
  const HOST_PORT = /^[^/?#:@]+:\d{1,5}(?:[/?#]|$)/; // "example.com:8080/x" is a host, not a scheme
60
75
  /**
@@ -0,0 +1,61 @@
1
+ /** An error whose message is already written for the chat. */
2
+ export class UserError extends Error {
3
+ }
4
+ /** Customer-facing wording for whatever Playwright or the network threw. Never a stack trace. */
5
+ export function friendlyError(error, action) {
6
+ if (error instanceof UserError)
7
+ return error.message;
8
+ const message = String(error?.message ?? error);
9
+ const has = (pattern) => pattern.test(message);
10
+ if (has(/has been closed|Target closed|Browser closed|browser has disconnected/i)) {
11
+ return "The window was closed during the action. Try again to open a new one.";
12
+ }
13
+ if (has(/ERR_NAME_NOT_RESOLVED/))
14
+ return "Couldn't find that site. Check the address.";
15
+ if (has(/ERR_INTERNET_DISCONNECTED/))
16
+ return "This computer seems to be offline.";
17
+ if (has(/ERR_CERT_|ERR_SSL_/)) {
18
+ return "The site's security certificate isn't valid, so the page wasn't opened.";
19
+ }
20
+ if (has(/ERR_TOO_MANY_REDIRECTS/))
21
+ return "The site redirected too many times.";
22
+ if (has(/ERR_CONNECTION_|ERR_TIMED_OUT|ERR_ADDRESS_UNREACHABLE|ERR_EMPTY_RESPONSE/)) {
23
+ return "Couldn't connect to that site.";
24
+ }
25
+ if (has(/ERR_ABORTED/)) {
26
+ return "The page stopped loading (it may have started a download, which isn't supported).";
27
+ }
28
+ if (has(/Unknown key/i)) {
29
+ return "Unknown key. Use names like Enter, Tab, Escape, ArrowDown or Control+A.";
30
+ }
31
+ if (has(/not a <select> element|Element is not a <select>/i))
32
+ return "That element isn't a dropdown.";
33
+ if (has(/did not find some options/i))
34
+ return "That option isn't in the list.";
35
+ if (has(/not an <input>|not an? (input|textarea)|cannot type|Element is not editable/i)) {
36
+ return "That element can't be typed into.";
37
+ }
38
+ if (has(/Timeout \d+ms exceeded|TimeoutError/)) {
39
+ if (action === "navigate" || action === "back")
40
+ return "The page took too long to load.";
41
+ if (action === "click" || action === "type" || action === "select") {
42
+ return "That element didn't respond (it may be hidden, disabled or covered). Take a new snapshot and try again.";
43
+ }
44
+ return "The page took too long to respond.";
45
+ }
46
+ return UNKNOWN_FAILURE;
47
+ }
48
+ export const UNKNOWN_FAILURE = "The browser couldn't do that. Take a new snapshot and try again.";
49
+ /** Quoted for a message, cut to 60 characters. */
50
+ export const quote = (text) => `"${text.length > 60 ? `${text.slice(0, 57)}…` : text}"`;
51
+ const DIALOGS = {
52
+ alert: "an alert",
53
+ confirm: "a confirmation",
54
+ prompt: "a prompt",
55
+ beforeunload: "a leave-page warning",
56
+ };
57
+ export function dialogNote(type, message) {
58
+ const what = DIALOGS[type] ?? "a dialog";
59
+ const text = message.trim() ? `: ${quote(message.trim())}` : "";
60
+ return `The page showed ${what}${text} (${type === "beforeunload" ? "left the page" : "dismissed it"}).`;
61
+ }
@@ -8,7 +8,9 @@
8
8
  import { lookup } from "node:dns/promises";
9
9
  import { isIP } from "node:net";
10
10
  import { checkPressTarget, checkTypeTarget, checkUrl, isAllowedPageUrl, isNonPublicAddress, LOCAL_BLOCKED, } from "./guards.js";
11
+ import { dialogNote, friendlyError, quote, UNKNOWN_FAILURE, UserError } from "./messages.js";
11
12
  import { capSnapshot, nameForRef, STALE_REF, } from "./protocol.js";
13
+ export { dialogNote, friendlyError, UserError };
12
14
  const ACTION_TIMEOUT_MS = 10_000;
13
15
  const NAVIGATION_TIMEOUT_MS = 30_000;
14
16
  /** Lets a click start its navigation (or open its tab) before we wait for the page. */
@@ -21,9 +23,6 @@ const NO_BROWSER = "Couldn't open a browser on this computer. Ask the person to
21
23
  "(or run `npx playwright install chromium`), then try again.";
22
24
  const LOCAL_PAGE = "This window is showing an address on this computer or the local network, which the browser " +
23
25
  "companion doesn't read or control. Navigate somewhere else or go back.";
24
- /** An error whose message is already written for the chat. */
25
- export class UserError extends Error {
26
- }
27
26
  /** The page as the model sees it: Playwright's AI-mode aria snapshot, with `[ref=e12]` handles. */
28
27
  export function snapshotForAI(page) {
29
28
  return page.ariaSnapshot({ mode: "ai", timeout: ACTION_TIMEOUT_MS });
@@ -32,63 +31,6 @@ export function snapshotForAI(page) {
32
31
  export function refLocator(page, ref) {
33
32
  return page.getByRef(ref);
34
33
  }
35
- /** Customer-facing wording for whatever Playwright or the network threw. Never a stack trace. */
36
- export function friendlyError(error, action) {
37
- if (error instanceof UserError)
38
- return error.message;
39
- const message = String(error?.message ?? error);
40
- const has = (pattern) => pattern.test(message);
41
- if (has(/has been closed|Target closed|Browser closed|browser has disconnected/i)) {
42
- return "The window was closed during the action. Try again to open a new one.";
43
- }
44
- if (has(/ERR_NAME_NOT_RESOLVED/))
45
- return "Couldn't find that site. Check the address.";
46
- if (has(/ERR_INTERNET_DISCONNECTED/))
47
- return "This computer seems to be offline.";
48
- if (has(/ERR_CERT_|ERR_SSL_/)) {
49
- return "The site's security certificate isn't valid, so the page wasn't opened.";
50
- }
51
- if (has(/ERR_TOO_MANY_REDIRECTS/))
52
- return "The site redirected too many times.";
53
- if (has(/ERR_CONNECTION_|ERR_TIMED_OUT|ERR_ADDRESS_UNREACHABLE|ERR_EMPTY_RESPONSE/)) {
54
- return "Couldn't connect to that site.";
55
- }
56
- if (has(/ERR_ABORTED/)) {
57
- return "The page stopped loading (it may have started a download, which isn't supported).";
58
- }
59
- if (has(/Unknown key/i)) {
60
- return "Unknown key. Use names like Enter, Tab, Escape, ArrowDown or Control+A.";
61
- }
62
- if (has(/not a <select> element|Element is not a <select>/i))
63
- return "That element isn't a dropdown.";
64
- if (has(/did not find some options/i))
65
- return "That option isn't in the list.";
66
- if (has(/not an <input>|not an? (input|textarea)|cannot type|Element is not editable/i)) {
67
- return "That element can't be typed into.";
68
- }
69
- if (has(/Timeout \d+ms exceeded|TimeoutError/)) {
70
- if (action === "navigate" || action === "back")
71
- return "The page took too long to load.";
72
- if (action === "click" || action === "type" || action === "select") {
73
- return "That element didn't respond (it may be hidden, disabled or covered). Take a new snapshot and try again.";
74
- }
75
- return "The page took too long to respond.";
76
- }
77
- return UNKNOWN_FAILURE;
78
- }
79
- const UNKNOWN_FAILURE = "The browser couldn't do that. Take a new snapshot and try again.";
80
- const quote = (text) => `"${text.length > 60 ? `${text.slice(0, 57)}…` : text}"`;
81
- const DIALOGS = {
82
- alert: "an alert",
83
- confirm: "a confirmation",
84
- prompt: "a prompt",
85
- beforeunload: "a leave-page warning",
86
- };
87
- export function dialogNote(type, message) {
88
- const what = DIALOGS[type] ?? "a dialog";
89
- const text = message.trim() ? `: ${quote(message.trim())}` : "";
90
- return `The page showed ${what}${text} (${type === "beforeunload" ? "left the page" : "dismissed it"}).`;
91
- }
92
34
  /**
93
35
  * The focused field of every frame (cross-origin frames included). Without window focus no frame
94
36
  * "has" focus, so each frame's active element counts.
package/dist/tui/app.js CHANGED
@@ -2,6 +2,7 @@ import { CombinedAutocompleteProvider, Editor, Loader, Markdown, matchesKey, Tui
2
2
  import { formatUsd } from "../agent/cost.js";
3
3
  import { Agent, } from "../agent/loop.js";
4
4
  import { DEFAULT_WEB_POLICY, emptyAllows, MODE_LABELS, MODES, } from "../agent/permissions.js";
5
+ import { commandLabel, expandCommand, listCommands, parseSlash, } from "../agent/command-files.js";
5
6
  import { MCP_EXAMPLE } from "../agent/mcp-config.js";
6
7
  import { count } from "../agent/tools/files.js";
7
8
  import { BUILTIN_TOOLS, webTools } from "../agent/tools/index.js";
@@ -9,10 +10,10 @@ import { tildePath } from "../agent/tools/paths.js";
9
10
  import { formatTodos } from "../agent/tools/todo.js";
10
11
  import { FileTracker } from "../agent/tools/types.js";
11
12
  import { commandEnv } from "../agent/tools/bash.js";
12
- import { listSessions, loadSession, sessionHolder, SessionWriter, stepRecord, timeAgo, } from "../agent/session.js";
13
+ import { changeRecord, listSessions, loadSession, sessionHolder, SessionWriter, stepRecord, timeAgo, } from "../agent/session.js";
13
14
  import { PLAN_OUTCOME_LABELS, PLAN_TOOL } from "../agent/tools/plan.js";
14
15
  import { changedLines, editInEditor } from "./external-editor.js";
15
- import { COMMANDS, helpText, parseCommand } from "./commands.js";
16
+ import { appCommand, closeMatches, COMMANDS, helpText, SOURCE_LABELS } from "./commands.js";
16
17
  import { ApprovalBox, Clamped, PlanApprovalBox, PlanBlock, gap, Header, INDENT, Lines, markdownTheme, Picker, Reasoning, selectListTheme, ToolLine, UserMessage, } from "./components.js";
17
18
  import { compactionNote, describeError, formatTokens, modelChoice, openElsewhere, retryMessage, sortModels, modeStatus, statusLine, } from "./format.js";
18
19
  import { style, theme } from "./theme.js";
@@ -35,6 +36,7 @@ export class App {
35
36
  /** Cost of earlier conversations in this session (`/new`). */
36
37
  spentBefore = 0n;
37
38
  busy = null;
39
+ /** Sent once the current step ends: messages, and commands as typed (`/review auth`). */
38
40
  queued = [];
39
41
  queuedNote = null;
40
42
  /** What Enter on an empty input does after an error. */
@@ -53,6 +55,12 @@ export class App {
53
55
  header = null;
54
56
  /** The kind of the last transcript entry, for spacing. */
55
57
  lastKind = null;
58
+ /** The `/` menu: the app's commands, then saved ones. Updated in place (the menu reads it). */
59
+ slashItems = [];
60
+ saved = [];
61
+ commandProblems = [];
62
+ commandsAt = 0;
63
+ commandsLoading = null;
56
64
  // The reply being streamed.
57
65
  replyText = "";
58
66
  reply = null;
@@ -77,8 +85,15 @@ export class App {
77
85
  };
78
86
  this.tui = new TuiMainScreen(options.terminal);
79
87
  this.editor = new Editor(this.tui, { borderColor: theme.border, selectList: selectListTheme }, { paddingX: 1 });
80
- this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider(COMMANDS.map((c) => ({ name: c.name, description: c.description })), options.cwd, null));
88
+ this.slashItems.push(...this.menuItems());
89
+ this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider(this.slashItems, options.cwd, null));
81
90
  this.editor.onSubmit = (text) => this.submit(text);
91
+ // A command file added since: it's in the menu the next time "/" is typed.
92
+ this.editor.onChange = (text) => {
93
+ if (text === "/")
94
+ void this.refreshCommands(3000);
95
+ };
96
+ void this.refreshCommands();
82
97
  this.tui.addChild(this.transcript);
83
98
  this.tui.addChild(this.activity);
84
99
  this.tui.addChild(this.editor);
@@ -189,23 +204,22 @@ export class App {
189
204
  void this.relogin();
190
205
  return;
191
206
  }
192
- const command = text.startsWith("/") ? parseCommand(text) : null;
193
- if (text.startsWith("/")) {
194
- this.editor.addToHistory(text);
195
- if (command)
196
- this.runCommand(command.name, command.arg);
197
- else
198
- this.notice(theme.warning(`"${text}" isn't a command. Type /help for the list.`));
199
- return;
200
- }
201
207
  this.editor.addToHistory(text);
208
+ // A path ("/Users/me/app is slow") isn't a command: it goes as a message.
209
+ const slash = parseSlash(text);
210
+ if (slash)
211
+ void this.runSlash(slash);
212
+ else
213
+ this.sendMessage(text);
214
+ }
215
+ sendMessage(text) {
202
216
  if (!this.agent) {
203
217
  this.afterPick = text;
204
218
  this.openModelPicker();
205
219
  return;
206
220
  }
207
221
  if (this.busy) {
208
- this.queued.push(text);
222
+ this.queued.push({ text });
209
223
  this.showQueued();
210
224
  return;
211
225
  }
@@ -213,6 +227,113 @@ export class App {
213
227
  const agent = this.agent;
214
228
  void this.runTurn((signal) => agent.send(text, signal));
215
229
  }
230
+ // --- slash commands ---------------------------------------------------------------------------
231
+ commandRoots() {
232
+ const { cwd, home, configDir } = this.options;
233
+ return { cwd, home, configDir, env: process.env };
234
+ }
235
+ /** The menu's entries: the app's commands (with their arguments), then saved commands. */
236
+ menuItems() {
237
+ const own = COMMANDS.map((c) => ({
238
+ name: c.name,
239
+ description: c.description,
240
+ argumentHint: c.argumentHint,
241
+ ...(c.name === "model" && {
242
+ getArgumentCompletions: (prefix) => sortModels(this.options.models)
243
+ .filter((m) => m.id.toLowerCase().includes(prefix.toLowerCase()))
244
+ .slice(0, 20)
245
+ .map((m) => ({ value: m.id, label: m.id, description: modelChoice(m).description })),
246
+ }),
247
+ ...(c.name === "mode" && {
248
+ getArgumentCompletions: (prefix) => MODES.filter((m) => m.startsWith(prefix.toLowerCase())).map((m) => ({
249
+ value: m,
250
+ label: m,
251
+ description: MODE_LABELS[m],
252
+ })),
253
+ }),
254
+ }));
255
+ const saved = this.saved.map((c) => ({
256
+ name: c.name,
257
+ description: c.source === "bundled"
258
+ ? c.description
259
+ : [c.description, SOURCE_LABELS[c.source]].filter(Boolean).join(" · "),
260
+ ...(c.argumentHint && { argumentHint: c.argumentHint }),
261
+ }));
262
+ return [...own, ...saved];
263
+ }
264
+ /** Reads saved commands again, unless they were read within `maxAgeMs`. */
265
+ refreshCommands(maxAgeMs = 0) {
266
+ if (this.commandsLoading)
267
+ return this.commandsLoading;
268
+ if (maxAgeMs && Date.now() - this.commandsAt < maxAgeMs)
269
+ return Promise.resolve();
270
+ this.commandsLoading = listCommands(this.commandRoots())
271
+ .then(({ commands, problems }) => {
272
+ this.saved = commands;
273
+ this.commandProblems = problems;
274
+ this.commandsAt = Date.now();
275
+ this.slashItems.splice(0, this.slashItems.length, ...this.menuItems());
276
+ })
277
+ .catch(() => { })
278
+ .finally(() => {
279
+ this.commandsLoading = null;
280
+ });
281
+ return this.commandsLoading;
282
+ }
283
+ async runSlash(ref) {
284
+ const own = appCommand(ref.name);
285
+ if (own)
286
+ return this.runCommand(own.name, ref.args);
287
+ if (!ref.name) {
288
+ return this.notice(theme.muted("Type a command's name after the /. /help lists them."));
289
+ }
290
+ const find = () => this.saved.find((c) => c.name === ref.name);
291
+ // Not known yet: the list may still be loading, or the file was just added.
292
+ if (!find())
293
+ await this.refreshCommands();
294
+ if (!find()) {
295
+ const near = closeMatches(ref.name, [
296
+ ...COMMANDS.map((c) => c.name),
297
+ ...this.saved.map((c) => c.name),
298
+ ]);
299
+ const hint = near.length ? ` Did you mean ${near.map((n) => `/${n}`).join(", ")}?` : "";
300
+ return this.notice(theme.warning(`/${ref.name} isn't a command.${hint} Type /help for the list.`));
301
+ }
302
+ this.sendCommand(ref);
303
+ }
304
+ /** A saved command (or /review, /init) as a message: queued while a step runs, like any. */
305
+ sendCommand(ref) {
306
+ if (!this.agent) {
307
+ this.afterPick = commandLabel(ref);
308
+ this.openModelPicker();
309
+ return;
310
+ }
311
+ if (this.busy) {
312
+ this.queued.push({ text: commandLabel(ref), command: ref });
313
+ this.showQueued();
314
+ return;
315
+ }
316
+ this.runPrompt(ref);
317
+ }
318
+ /** Runs a saved command: its file is read now, and what was typed is shown (`/review auth`). */
319
+ runPrompt(ref) {
320
+ const agent = this.agent;
321
+ const roots = this.commandRoots();
322
+ const show = () => this.addUser(commandLabel(ref));
323
+ const fail = (message) => {
324
+ this.notice(theme.warning(message));
325
+ // What was typed comes back, to fix or run again.
326
+ if (!this.editor.getText())
327
+ this.editor.setText(commandLabel(ref));
328
+ };
329
+ void this.runTurn(async function* (signal) {
330
+ const result = await expandCommand(ref, roots);
331
+ if (!result.ok)
332
+ return fail(result.message);
333
+ show();
334
+ yield* agent.send(result.prompt, signal, undefined, ref);
335
+ });
336
+ }
216
337
  // --- turns ------------------------------------------------------------------------------------
217
338
  async runTurn(start) {
218
339
  const controller = new AbortController();
@@ -249,10 +370,23 @@ export class App {
249
370
  }
250
371
  if (!this.queued.length || !this.agent || this.exited)
251
372
  return;
252
- const text = this.queued.splice(0).join("\n\n");
253
- this.addUser(text);
254
- const agent = this.agent;
255
- void this.runTurn((signal) => agent.send(text, signal));
373
+ // A command goes on its own; messages before the next one go together.
374
+ const first = this.queued[0];
375
+ if (first.command) {
376
+ this.queued.shift();
377
+ this.runPrompt(first.command);
378
+ }
379
+ else {
380
+ const batch = [];
381
+ while (this.queued.length && !this.queued[0].command)
382
+ batch.push(this.queued.shift().text);
383
+ const text = batch.join("\n\n");
384
+ this.addUser(text);
385
+ const agent = this.agent;
386
+ void this.runTurn((signal) => agent.send(text, signal));
387
+ }
388
+ if (this.queued.length)
389
+ this.showQueued();
256
390
  }
257
391
  showQueued() {
258
392
  const text = theme.muted(`Queued (${this.queued.length}). Sends when this step finishes, or now with esc.`);
@@ -530,8 +664,12 @@ export class App {
530
664
  this.cycleMode();
531
665
  return;
532
666
  }
667
+ case "plan":
668
+ this.setMode("plan");
669
+ if (arg)
670
+ this.sendMessage(arg);
671
+ return;
533
672
  case "new":
534
- case "clear":
535
673
  if (this.busy)
536
674
  return this.notice(theme.muted("Stop the current task first (esc)."));
537
675
  void this.writer?.release();
@@ -544,7 +682,7 @@ export class App {
544
682
  this.notice(theme.muted("── New conversation ──"));
545
683
  this.updateStatus();
546
684
  return;
547
- case "cost": {
685
+ case "usage": {
548
686
  const context = this.agent?.contextTokens;
549
687
  this.notice([
550
688
  `This session: ~${formatUsd(this.sessionCost())} (an estimate; your usage page has exact charges)`,
@@ -563,7 +701,7 @@ export class App {
563
701
  const agent = this.agent;
564
702
  if (!agent)
565
703
  return;
566
- void this.runTurn((signal) => agent.compactNow(signal));
704
+ void this.runTurn((signal) => agent.compactNow(signal, arg || undefined));
567
705
  return;
568
706
  }
569
707
  case "resume":
@@ -580,10 +718,10 @@ export class App {
580
718
  this.notice(this.mcpReport());
581
719
  return;
582
720
  case "help":
583
- this.notice(helpText());
721
+ this.notice(helpText(this.saved, this.commandProblems, this.options.home));
722
+ void this.refreshCommands(3000);
584
723
  return;
585
724
  case "exit":
586
- case "quit":
587
725
  this.exit(0);
588
726
  return;
589
727
  default:
@@ -752,20 +890,7 @@ export class App {
752
890
  if (!this.model)
753
891
  return;
754
892
  this.writer ??= SessionWriter.create(this.options.sessionsDir, this.options.cwd, this.model.id, new Date(), "terminal");
755
- if (change.type === "usage") {
756
- this.writer.append({
757
- type: "usage",
758
- promptTokens: change.usage.promptTokens,
759
- completionTokens: change.usage.completionTokens,
760
- costMicros: change.costMicros.toString(),
761
- });
762
- }
763
- else if (change.type === "append") {
764
- this.writer.append({ type: "append", message: change.message });
765
- }
766
- else {
767
- this.writer.append({ type: "replace", reason: change.reason, messages: change.messages });
768
- }
893
+ this.writer.append(changeRecord(change));
769
894
  }
770
895
  /** Continues a saved conversation: reprints it as it looked, then carries on in the same file. */
771
896
  resumeSession(loaded) {
@@ -787,8 +912,9 @@ export class App {
787
912
  // The callers checked that nothing else has it open.
788
913
  void this.writer.claim("terminal");
789
914
  for (const entry of loaded.display) {
790
- if (entry.kind === "user")
791
- this.addUser(entry.text);
915
+ if (entry.kind === "user") {
916
+ this.addUser(entry.command ? commandLabel(entry.command) : entry.text);
917
+ }
792
918
  else if (entry.kind === "text") {
793
919
  this.add(new Markdown(entry.text, INDENT.length, 0, markdownTheme), "text");
794
920
  }