reasonally 0.3.0 → 0.5.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/dist/login.js CHANGED
@@ -13,6 +13,8 @@ export function authorizeUrl(appUrl, params) {
13
13
  state: params.state,
14
14
  device: params.device,
15
15
  });
16
+ if (params.client)
17
+ query.set("client", params.client);
16
18
  return `${appUrl}/cli/authorize?${query}`;
17
19
  }
18
20
  /** Interprets a request to the loopback server. Only `/callback` with our `state` counts. */
@@ -43,10 +45,35 @@ function openBrowser(url) {
43
45
  // same
44
46
  }
45
47
  }
48
+ /** Thrown when the caller's `signal` stops a login that was waiting for the browser. */
49
+ export class LoginCancelled extends Error {
50
+ constructor() {
51
+ super("Login was cancelled.");
52
+ }
53
+ }
54
+ /** Thrown when the user pressed Cancel on the approval page. */
55
+ export class LoginDenied extends Error {
56
+ constructor() {
57
+ super("Login was cancelled in the browser.");
58
+ }
59
+ }
60
+ /** Thrown when nobody approved in the browser in time. */
61
+ export class LoginTimedOut extends Error {
62
+ constructor() {
63
+ super("Timed out waiting for approval in the browser. Run the login again.");
64
+ }
65
+ }
46
66
  /** Waits for the browser to come back to the loopback server with a code (or a refusal). */
47
- function waitForCallback(server, state) {
67
+ function waitForCallback(server, state, { signal, returnTo = "your terminal" } = {}) {
48
68
  return new Promise((resolve, reject) => {
49
- const timer = setTimeout(() => reject(new Error("Timed out waiting for approval in the browser. Run the login again.")), LOGIN_TIMEOUT_MS);
69
+ const timer = setTimeout(() => reject(new LoginTimedOut()), LOGIN_TIMEOUT_MS);
70
+ const onAbort = () => {
71
+ clearTimeout(timer);
72
+ reject(new LoginCancelled());
73
+ };
74
+ if (signal?.aborted)
75
+ return onAbort();
76
+ signal?.addEventListener("abort", onAbort, { once: true });
50
77
  server.on("request", (req, res) => {
51
78
  const result = readCallback(req.url ?? "/", state);
52
79
  const reply = (status, title, body) => {
@@ -56,26 +83,24 @@ function waitForCallback(server, state) {
56
83
  if (result.kind === "ignore")
57
84
  return reply(404, "Not found", "Nothing to see here.");
58
85
  clearTimeout(timer);
86
+ signal?.removeEventListener("abort", onAbort);
59
87
  if (result.kind === "code") {
60
- reply(200, "You're logged in", "You can close this tab and go back to your terminal.");
88
+ reply(200, "You're logged in", `You can close this tab and go back to ${returnTo}.`);
61
89
  resolve(result.code);
62
90
  }
63
91
  else if (result.kind === "denied") {
64
92
  reply(200, "Login cancelled", "You can close this tab.");
65
- reject(new Error("Login was cancelled in the browser."));
93
+ reject(new LoginDenied());
66
94
  }
67
95
  else {
68
- reply(400, "Login failed", "This response didn't match the login in your terminal.");
96
+ reply(400, "Login failed", `This response didn't match the login in ${returnTo}.`);
69
97
  reject(new Error("The browser returned an unexpected response. Run the login again."));
70
98
  }
71
99
  });
72
100
  });
73
101
  }
74
- /**
75
- * Browser login: opens the approval page, receives the code on a one-shot loopback server and
76
- * exchanges it (with the PKCE verifier) for an API key.
77
- */
78
- export async function browserLogin(appUrl, log, { open = true } = {}) {
102
+ export async function browserLogin(appUrl, log, options = {}) {
103
+ const { open = true } = options;
79
104
  const pkce = createPkce();
80
105
  const server = createServer();
81
106
  await new Promise((resolve, reject) => {
@@ -89,21 +114,24 @@ export async function browserLogin(appUrl, log, { open = true } = {}) {
89
114
  redirectUri,
90
115
  challenge: pkce.challenge,
91
116
  state: pkce.state,
92
- device: hostname().replace(/\.local$/, ""),
117
+ device: options.device ?? hostname().replace(/\.local$/, ""),
118
+ client: options.client,
93
119
  });
120
+ options.onUrl?.(url);
94
121
  if (open) {
95
122
  log("Opening your browser to approve this computer…");
96
123
  log(`If it doesn't open, visit:\n\n ${url}\n`);
97
- openBrowser(url);
124
+ (options.openUrl ?? openBrowser)(url);
98
125
  }
99
126
  else {
100
127
  log(`Open this link in the browser where you're signed in, on this computer:\n\n ${url}\n`);
101
128
  }
102
- const code = await waitForCallback(server, pkce.state);
129
+ const code = await waitForCallback(server, pkce.state, options);
103
130
  return await exchangeCode(appUrl, {
104
131
  code,
105
132
  code_verifier: pkce.verifier,
106
133
  redirect_uri: redirectUri,
134
+ client: options.client,
107
135
  });
108
136
  }
109
137
  finally {
package/dist/tui/app.js CHANGED
@@ -1,18 +1,20 @@
1
1
  import { CombinedAutocompleteProvider, Editor, Loader, Markdown, matchesKey, TuiMainScreen, } from "@earendil-works/pi-tui";
2
2
  import { formatUsd } from "../agent/cost.js";
3
3
  import { Agent, } from "../agent/loop.js";
4
- import { emptyAllows, MODE_LABELS, MODES, } from "../agent/permissions.js";
4
+ import { DEFAULT_WEB_POLICY, emptyAllows, MODE_LABELS, MODES, } from "../agent/permissions.js";
5
5
  import { MCP_EXAMPLE } from "../agent/mcp-config.js";
6
6
  import { count } from "../agent/tools/files.js";
7
- import { BUILTIN_TOOLS } from "../agent/tools/index.js";
7
+ import { BUILTIN_TOOLS, webTools } from "../agent/tools/index.js";
8
8
  import { tildePath } from "../agent/tools/paths.js";
9
9
  import { formatTodos } from "../agent/tools/todo.js";
10
10
  import { FileTracker } from "../agent/tools/types.js";
11
11
  import { commandEnv } from "../agent/tools/bash.js";
12
- import { listSessions, loadSession, SessionWriter, timeAgo, } from "../agent/session.js";
12
+ import { listSessions, loadSession, sessionHolder, SessionWriter, stepRecord, timeAgo, } from "../agent/session.js";
13
+ import { PLAN_OUTCOME_LABELS, PLAN_TOOL } from "../agent/tools/plan.js";
14
+ import { changedLines, editInEditor } from "./external-editor.js";
13
15
  import { COMMANDS, helpText, parseCommand } from "./commands.js";
14
- import { ApprovalBox, Clamped, gap, Header, INDENT, Lines, markdownTheme, Picker, Reasoning, selectListTheme, ToolLine, UserMessage, } from "./components.js";
15
- import { compactionNote, describeError, formatTokens, modelChoice, retryMessage, sortModels, statusLine, } from "./format.js";
16
+ import { ApprovalBox, Clamped, PlanApprovalBox, PlanBlock, gap, Header, INDENT, Lines, markdownTheme, Picker, Reasoning, selectListTheme, ToolLine, UserMessage, } from "./components.js";
17
+ import { compactionNote, describeError, formatTokens, modelChoice, openElsewhere, retryMessage, sortModels, modeStatus, statusLine, } from "./format.js";
16
18
  import { style, theme } from "./theme.js";
17
19
  export class App {
18
20
  options;
@@ -56,6 +58,12 @@ export class App {
56
58
  reply = null;
57
59
  reasoning = null;
58
60
  toolLines = new Map();
61
+ /** The plan being written or waiting for an answer, in the transcript. */
62
+ planBlock = null;
63
+ /** How the last presented plan ended, for the words at the end of the turn. */
64
+ lastPlanOutcome = null;
65
+ /** The plan is open in the person's editor. */
66
+ editingPlan = false;
59
67
  constructor(options) {
60
68
  this.options = options;
61
69
  this.session = options.session;
@@ -65,6 +73,7 @@ export class App {
65
73
  mode: options.mode,
66
74
  allows: emptyAllows(),
67
75
  context: { cwd: options.cwd, home: options.home, configDir: options.configDir },
76
+ web: options.web ?? DEFAULT_WEB_POLICY,
68
77
  };
69
78
  this.tui = new TuiMainScreen(options.terminal);
70
79
  this.editor = new Editor(this.tui, { borderColor: theme.border, selectList: selectListTheme }, { paddingX: 1 });
@@ -139,7 +148,7 @@ export class App {
139
148
  return false;
140
149
  }
141
150
  if (this.picker || this.approval) {
142
- if (matchesKey(data, "ctrl+o") && this.approval) {
151
+ if (matchesKey(data, "ctrl+o") && this.approval instanceof ApprovalBox) {
143
152
  this.approval.toggleExpanded();
144
153
  this.tui.requestRender();
145
154
  return true;
@@ -283,13 +292,34 @@ export class App {
283
292
  break;
284
293
  case "tool_call_streaming":
285
294
  this.reasoning?.finish();
286
- this.setLoader(`Preparing ${event.name}…`);
295
+ this.setLoader(event.name === PLAN_TOOL ? "Writing the plan…" : `Preparing ${event.name}…`);
296
+ break;
297
+ case "plan_draft":
298
+ this.reasoning?.finish();
299
+ if (this.planBlock)
300
+ this.planBlock.setText(event.text);
301
+ else {
302
+ this.planBlock = new PlanBlock(event.text);
303
+ this.add(this.planBlock, "text");
304
+ }
305
+ this.setLoader("Writing the plan…");
306
+ break;
307
+ case "plan_draft_dropped":
308
+ if (this.planBlock)
309
+ this.transcript.removeChild(this.planBlock);
310
+ this.planBlock = null;
311
+ break;
312
+ case "mode_changed":
313
+ // The agent switched it (the plan was approved); the status line shows it below.
287
314
  break;
288
315
  case "model_done":
289
316
  this.reasoning?.finish();
290
317
  this.reply = null;
291
318
  break;
292
319
  case "tool_start": {
320
+ // A plan shows as itself (above), and its outcome as a line once answered.
321
+ if (event.name === PLAN_TOOL)
322
+ break;
293
323
  const line = new ToolLine(event.id, event.title);
294
324
  this.toolLines.set(event.id, line);
295
325
  this.add(line, "steps");
@@ -308,18 +338,17 @@ export class App {
308
338
  this.add(line, "steps");
309
339
  }
310
340
  const { result } = event;
311
- line.finish(result.isError ? "error" : "done", result.summary, result.detail);
341
+ const feedback = result.plan?.feedback;
342
+ line.finish(result.isError ? "error" : "done", feedback ? `${result.summary} · ${feedback}` : result.summary, result.detail);
343
+ if (event.name === PLAN_TOOL) {
344
+ this.planBlock = null;
345
+ this.lastPlanOutcome = result.plan?.outcome ?? null;
346
+ }
312
347
  if (event.name === "todo" && this.todos.length) {
313
348
  line.detail = formatTodos(this.todos);
314
349
  line.expanded = true;
315
350
  }
316
- this.writer?.append({
317
- type: "step",
318
- id: event.id,
319
- title: event.title,
320
- summary: result.summary,
321
- isError: Boolean(result.isError),
322
- });
351
+ this.writer?.append(stepRecord(event.id, event.title, result));
323
352
  if (line.expandable)
324
353
  this.lastExpandable = line;
325
354
  this.setLoader("Thinking…");
@@ -343,8 +372,12 @@ export class App {
343
372
  case "done":
344
373
  if (event.reason === "aborted")
345
374
  this.notice(theme.muted("Stopped. What should it do instead?"));
346
- if (event.reason === "declined")
347
- this.notice(theme.muted("Okay, I won't. What should it do instead?"));
375
+ if (event.reason === "declined") {
376
+ this.notice(theme.muted(this.lastPlanOutcome === "not-approved"
377
+ ? "Plan not approved. Say what should change, or press Shift+Tab to leave Plan mode."
378
+ : "Okay, I won't. What should it do instead?"));
379
+ }
380
+ this.lastPlanOutcome = null;
348
381
  break;
349
382
  }
350
383
  this.updateStatus();
@@ -366,6 +399,8 @@ export class App {
366
399
  return next;
367
400
  }
368
401
  showApproval(request, signal) {
402
+ if (request.tool === PLAN_TOOL)
403
+ return this.showPlanApproval(request, signal);
369
404
  return new Promise((resolve) => {
370
405
  let done = false;
371
406
  const finish = (decision) => {
@@ -396,6 +431,90 @@ export class App {
396
431
  signal.addEventListener("abort", onAbort, { once: true });
397
432
  });
398
433
  }
434
+ /**
435
+ * "Ready to build?" under the plan. Ctrl+G hands the terminal to the person's editor and comes
436
+ * back with their version, which the answer then carries.
437
+ */
438
+ showPlanApproval(request, signal) {
439
+ const original = request.preview ?? "";
440
+ // The draft becomes the plan as presented (or it appears now, if it wasn't streamed).
441
+ if (this.planBlock)
442
+ this.planBlock.setText(original);
443
+ else {
444
+ this.planBlock = new PlanBlock(original);
445
+ this.add(this.planBlock, "text");
446
+ }
447
+ return new Promise((resolve) => {
448
+ let done = false;
449
+ let edited = null;
450
+ const finish = (decision) => {
451
+ if (done)
452
+ return;
453
+ done = true;
454
+ signal.removeEventListener("abort", onAbort);
455
+ if (this.approval === box) {
456
+ this.activity.removeChild(box);
457
+ this.approval = null;
458
+ }
459
+ this.tui.setFocus(this.editor);
460
+ if (!signal.aborted) {
461
+ if (decision.kind !== "no")
462
+ this.showLoader("Starting on the plan…");
463
+ else if (decision.feedback)
464
+ this.showLoader("Revising the plan…");
465
+ }
466
+ this.tui.requestRender();
467
+ resolve(edited !== null ? { ...decision, plan: edited } : decision);
468
+ };
469
+ const onAbort = () => finish({ kind: "no" });
470
+ const edit = async () => {
471
+ if (this.editingPlan || done)
472
+ return;
473
+ this.editingPlan = true;
474
+ const before = edited ?? original;
475
+ let outcome;
476
+ this.tui.stop();
477
+ try {
478
+ outcome = await (this.options.editPlan ?? editInEditor)(before);
479
+ }
480
+ catch (error) {
481
+ outcome = { kind: "failed", message: error.message };
482
+ }
483
+ finally {
484
+ this.tui.start();
485
+ // A forced redraw: renders asked for while the editor had the screen were skipped.
486
+ this.tui.requestRender(true);
487
+ this.editingPlan = false;
488
+ }
489
+ if (done)
490
+ return;
491
+ if (outcome.kind === "failed")
492
+ this.flash("Couldn't open your editor. Set $EDITOR.");
493
+ else if (outcome.kind === "empty") {
494
+ this.notice(theme.muted("The edited plan was empty, so the plan stays as it was."));
495
+ }
496
+ else if (outcome.kind === "unchanged") {
497
+ if (outcome.quick)
498
+ this.flash("If your editor returns at once, set EDITOR='code --wait'.");
499
+ }
500
+ else {
501
+ const n = changedLines(before, outcome.text);
502
+ edited = outcome.text;
503
+ box.edited = true;
504
+ this.add(new PlanBlock(outcome.text, true), "text");
505
+ this.notice(`${theme.warning("✎")} Plan edited ${theme.muted(`· ${n} ${n === 1 ? "line" : "lines"} changed`)}`);
506
+ }
507
+ this.tui.requestRender();
508
+ };
509
+ const box = new PlanApprovalBox(finish, () => void edit(), this.options.planArmMs);
510
+ this.hideLoader();
511
+ this.approval = box;
512
+ this.activity.addChild(box);
513
+ this.tui.setFocus(box);
514
+ this.tui.requestRender();
515
+ signal.addEventListener("abort", onAbort, { once: true });
516
+ });
517
+ }
399
518
  // --- commands ---------------------------------------------------------------------------------
400
519
  runCommand(name, arg) {
401
520
  switch (name) {
@@ -415,6 +534,7 @@ export class App {
415
534
  case "clear":
416
535
  if (this.busy)
417
536
  return this.notice(theme.muted("Stop the current task first (esc)."));
537
+ void this.writer?.release();
418
538
  this.writer = null;
419
539
  if (this.agent)
420
540
  this.spentBefore += this.agent.totalCostMicros;
@@ -479,6 +599,9 @@ export class App {
479
599
  if (mode === "full") {
480
600
  this.flash("Don't ask: edits and commands run without asking. Shift+Tab to switch back.");
481
601
  }
602
+ else if (mode === "plan") {
603
+ this.flash("Plan mode: it looks around and plans. Nothing changes until you approve.");
604
+ }
482
605
  this.updateStatus();
483
606
  this.tui.requestRender();
484
607
  }
@@ -570,7 +693,11 @@ export class App {
570
693
  // --- helpers ----------------------------------------------------------------------------------
571
694
  // --- MCP ------------------------------------------------------------------------------------
572
695
  tools() {
573
- return [...BUILTIN_TOOLS, ...(this.options.mcp?.tools ?? [])];
696
+ return [
697
+ ...BUILTIN_TOOLS,
698
+ ...webTools(this.options.web ?? DEFAULT_WEB_POLICY),
699
+ ...(this.options.mcp?.tools ?? []),
700
+ ];
574
701
  }
575
702
  /** Picks up MCP tools as servers connect, and says once how the start-up went. */
576
703
  watchMcp() {
@@ -624,7 +751,7 @@ export class App {
624
751
  save(change) {
625
752
  if (!this.model)
626
753
  return;
627
- this.writer ??= SessionWriter.create(this.options.sessionsDir, this.options.cwd, this.model.id);
754
+ this.writer ??= SessionWriter.create(this.options.sessionsDir, this.options.cwd, this.model.id, new Date(), "terminal");
628
755
  if (change.type === "usage") {
629
756
  this.writer.append({
630
757
  type: "usage",
@@ -655,7 +782,10 @@ export class App {
655
782
  this.header.model = model.id;
656
783
  this.agent = this.newAgent(model);
657
784
  this.agent.restore(loaded.messages);
785
+ void this.writer?.release();
658
786
  this.writer = SessionWriter.resume(loaded.path);
787
+ // The callers checked that nothing else has it open.
788
+ void this.writer.claim("terminal");
659
789
  for (const entry of loaded.display) {
660
790
  if (entry.kind === "user")
661
791
  this.addUser(entry.text);
@@ -667,6 +797,14 @@ export class App {
667
797
  line.finish(entry.isError ? "error" : "done", entry.summary);
668
798
  this.add(line, "steps");
669
799
  }
800
+ else if (entry.kind === "plan") {
801
+ this.add(new PlanBlock(entry.text, entry.edited), "text");
802
+ const line = new ToolLine("", "Plan");
803
+ const failed = entry.outcome === "not-approved" || entry.outcome === "stopped";
804
+ const label = PLAN_OUTCOME_LABELS[entry.outcome];
805
+ line.finish(failed ? "error" : "done", entry.feedback ? `${label} · ${entry.feedback}` : label);
806
+ this.add(line, "steps");
807
+ }
670
808
  else
671
809
  this.notice(theme.muted("Summarized earlier conversation."));
672
810
  }
@@ -703,6 +841,11 @@ export class App {
703
841
  }
704
842
  async pickSession(path) {
705
843
  this.closePicker();
844
+ const holder = await sessionHolder(path);
845
+ if (holder) {
846
+ this.notice(theme.muted(`${openElsewhere(holder)} Close it there to continue it here.`));
847
+ return;
848
+ }
706
849
  const loaded = await loadSession(path);
707
850
  if (!loaded) {
708
851
  this.notice(theme.error("✗ That conversation couldn't be read."));
@@ -781,16 +924,19 @@ export class App {
781
924
  this.tui.requestRender();
782
925
  }
783
926
  updateStatus() {
784
- const text = this.hint
785
- ? theme.warning(this.hint)
786
- : theme.muted(statusLine({
787
- mode: this.permissions.mode,
788
- contextTokens: this.agent?.contextTokens ?? null,
789
- contextLength: this.model?.contextLength ?? 1,
790
- costMicros: this.sessionCost(),
791
- balance: this.balance,
792
- }));
793
- this.status.setText(text);
927
+ const mode = this.permissions.mode;
928
+ const line = statusLine({
929
+ mode,
930
+ contextTokens: this.agent?.contextTokens ?? null,
931
+ contextLength: this.model?.contextLength ?? 1,
932
+ costMicros: this.sessionCost(),
933
+ balance: this.balance,
934
+ });
935
+ // Plan mode stands out, so it's clear at a glance that nothing will change.
936
+ const shown = mode === "plan"
937
+ ? theme.accent(modeStatus(mode)) + theme.muted(line.slice(modeStatus(mode).length))
938
+ : theme.muted(line);
939
+ this.status.setText(this.hint ? theme.warning(this.hint) : shown);
794
940
  }
795
941
  showLoader(text) {
796
942
  this.loaderText = text;
@@ -854,7 +1000,7 @@ export class App {
854
1000
  const stopping = mcp
855
1001
  ? Promise.race([mcp.close(), new Promise((r) => setTimeout(r, 2000).unref())])
856
1002
  : Promise.resolve();
857
- void Promise.all([writer?.flush(), stopping]).then(() => {
1003
+ void Promise.all([writer?.release(), stopping]).then(() => {
858
1004
  const saved = writer?.started && !writer.failed
859
1005
  ? `${style.dim("Saved. Continue with:")} reasonally --continue`
860
1006
  : null;
package/dist/tui/args.js CHANGED
@@ -1,6 +1,13 @@
1
1
  /** Flags for bare `reasonally` (the agent). No terminal UI imports: `cli.ts` loads this eagerly. */
2
2
  export function parseAgentArgs(argv) {
3
- const args = { model: null, yes: false, continue: false, resume: false };
3
+ const args = {
4
+ model: null,
5
+ yes: false,
6
+ plan: false,
7
+ continue: false,
8
+ resume: false,
9
+ noWeb: false,
10
+ };
4
11
  for (let i = 0; i < argv.length; i++) {
5
12
  const arg = argv[i];
6
13
  if (arg === "--model" || arg === "-m") {
@@ -16,16 +23,24 @@ export function parseAgentArgs(argv) {
16
23
  else if (arg === "--yes" || arg === "-y") {
17
24
  args.yes = true;
18
25
  }
26
+ else if (arg === "--plan") {
27
+ args.plan = true;
28
+ }
19
29
  else if (arg === "--continue" || arg === "-c") {
20
30
  args.continue = true;
21
31
  }
22
32
  else if (arg === "--resume" || arg === "-r") {
23
33
  args.resume = true;
24
34
  }
35
+ else if (arg === "--no-web") {
36
+ args.noWeb = true;
37
+ }
25
38
  else {
26
39
  return { ok: false, error: `Unknown option "${arg}". See \`reasonally --help\`.` };
27
40
  }
28
41
  }
42
+ if (args.plan && args.yes)
43
+ return { ok: false, error: "Pick one of --plan and --yes." };
29
44
  return { ok: true, args };
30
45
  }
31
46
  /** Bare `reasonally` opens the agent only in an interactive terminal; scripts still get help. */
@@ -1,6 +1,9 @@
1
1
  export const COMMANDS = [
2
2
  { name: "model", description: "Switch model" },
3
- { name: "mode", description: "Switch between asking, auto-accepting edits, and not asking" },
3
+ {
4
+ name: "mode",
5
+ description: "Switch between asking, auto-accepting edits, planning first, and not asking",
6
+ },
4
7
  { name: "new", description: "Start a new conversation" },
5
8
  { name: "resume", description: "Continue an earlier conversation in this folder" },
6
9
  { name: "compact", description: "Summarize the conversation so far to free up context" },
@@ -22,6 +25,7 @@ export const KEYS = [
22
25
  ["Esc", "stop the current reply or command"],
23
26
  ["Shift+Tab", "switch mode"],
24
27
  ["Ctrl+O", "show the full output of the last step"],
28
+ ["Ctrl+G", "edit a waiting plan in your editor"],
25
29
  ["Ctrl+C", "clear the input · twice to quit"],
26
30
  ["@", "mention a file"],
27
31
  ["↑ ↓", "earlier messages"],
@@ -1,4 +1,4 @@
1
- import { Container, Input, matchesKey, SelectList, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
1
+ import { Container, Input, Markdown, matchesKey, SelectList, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
2
2
  import { diffLineKind } from "./format.js";
3
3
  import { style, theme } from "./theme.js";
4
4
  /** Everything the agent says or does is indented this much; the user's "›" sits in the margin. */
@@ -307,6 +307,110 @@ export class ApprovalBox {
307
307
  return lines;
308
308
  }
309
309
  }
310
+ /** A plan, as Markdown under "⏸ Plan": streamed while it's written, then left in the scrollback. */
311
+ export class PlanBlock {
312
+ edited;
313
+ markdown;
314
+ constructor(text, edited = false) {
315
+ this.edited = edited;
316
+ this.markdown = new Markdown(text, INDENT.length, 0, markdownTheme);
317
+ }
318
+ setText(text) {
319
+ this.markdown.setText(text);
320
+ }
321
+ invalidate() {
322
+ this.markdown.invalidate();
323
+ }
324
+ render(width) {
325
+ const head = theme.accent(style.bold(this.edited ? "⏸ Plan (edited)" : "⏸ Plan"));
326
+ return ["", `${INDENT}${head}`, ...this.markdown.render(width)];
327
+ }
328
+ }
329
+ /** Keys pressed this soon after the plan box appears don't count (they were meant for the input). */
330
+ export const PLAN_ARM_MS = 350;
331
+ /**
332
+ * "Ready to build?" under a presented plan: y builds asking before edits, a auto-accepts edits,
333
+ * n says what to change (empty just stops), ctrl+g edits the plan in your editor, Esc stops.
334
+ */
335
+ export class PlanApprovalBox {
336
+ resolve;
337
+ onEdit;
338
+ now;
339
+ focused = false;
340
+ /** The user edited the plan: the answer carries their version. */
341
+ edited = false;
342
+ feedback = null;
343
+ armedAt;
344
+ constructor(resolve, onEdit, armMs = PLAN_ARM_MS, now = Date.now) {
345
+ this.resolve = resolve;
346
+ this.onEdit = onEdit;
347
+ this.now = now;
348
+ this.armedAt = now() + armMs;
349
+ }
350
+ invalidate() { }
351
+ handleInput(data) {
352
+ if (this.now() < this.armedAt)
353
+ return;
354
+ if (this.feedback) {
355
+ if (matchesKey(data, "escape")) {
356
+ this.feedback = null;
357
+ return;
358
+ }
359
+ this.feedback.handleInput(data);
360
+ return;
361
+ }
362
+ if (matchesKey(data, "escape"))
363
+ return this.resolve({ kind: "no" });
364
+ if (matchesKey(data, "ctrl+g"))
365
+ return this.onEdit();
366
+ const key = data.toLowerCase();
367
+ if (key === "y")
368
+ this.resolve({ kind: "yes" });
369
+ else if (key === "a")
370
+ this.resolve({ kind: "always" });
371
+ else if (key === "n") {
372
+ const input = new Input({
373
+ prompt: "",
374
+ placeholder: "Say what to change (Enter on empty just stops)",
375
+ });
376
+ input.focused = this.focused;
377
+ input.onSubmit = (value) => this.resolve({ kind: "no", feedback: value.trim() || undefined });
378
+ this.feedback = input;
379
+ }
380
+ }
381
+ render(width) {
382
+ const heading = `${style.bold("Ready to build?")}${this.edited ? ` ${theme.warning("edited")}` : ""}`;
383
+ const body = [
384
+ theme.muted(this.edited ? "It follows your edited version." : "Nothing has changed yet."),
385
+ ];
386
+ if (this.feedback) {
387
+ this.feedback.focused = this.focused;
388
+ const input = this.feedback.render(Math.max(10, width - 4))[0] ?? "";
389
+ return [
390
+ ...boxed(heading, body, theme.accent("What should change in the plan?"), width),
391
+ `${INDENT} ${input}`,
392
+ theme.muted(`${INDENT} Enter to send · empty to just stop · esc to go back`),
393
+ ];
394
+ }
395
+ const options = [
396
+ `${style.bold("y")} yes, ask before edits`,
397
+ `${style.bold("a")} yes, auto-accept edits`,
398
+ `${style.bold("n")} no, keep planning`,
399
+ `${style.bold("ctrl+g")} edit`,
400
+ ];
401
+ const footer = `${theme.accent("Build?")} ${options.join(theme.muted(" · "))}`;
402
+ const lines = boxed(heading, body, footer, width);
403
+ // On narrow terminals the options wrap rather than vanish.
404
+ if (visibleWidth(footer) > width - 4) {
405
+ lines.pop();
406
+ lines.push(`${INDENT}${theme.border("╰")} ${theme.accent("Build?")}`);
407
+ for (const opt of options) {
408
+ lines.push(...wrapTextWithAnsi(opt, nestedWidth(width)).map((l) => NESTED + l));
409
+ }
410
+ }
411
+ return lines;
412
+ }
413
+ }
310
414
  /** A filterable list (model picker): type to filter, ↑↓ to move, Enter to pick, Esc to cancel. */
311
415
  export class Picker {
312
416
  title;