@yanzc/claude-pro 0.6.0 → 0.7.1

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/src/remote.js CHANGED
@@ -13,7 +13,7 @@ import fs from 'node:fs';
13
13
  import os from 'node:os';
14
14
  import crypto from 'node:crypto';
15
15
  import { stripAnsi } from './ui/ansi.js';
16
- import { toolHeader, renderToolResult } from './ui/render.js';
16
+ import { toolHeader, renderToolResult, bashModeLines } from './ui/render.js';
17
17
  import { uploadFile, downloadFile } from './transfer.js';
18
18
 
19
19
  export const REMOTE_WIDTH = 100; // columns that tool headers and results are laid out for on the page
@@ -120,6 +120,8 @@ export function transcriptItems(messages, { tools = [], ctx, cwd, width = REMOTE
120
120
  if (b.type === 'text') {
121
121
  const raw = String(b.text || '');
122
122
  if (raw.startsWith('This session is being continued')) { items.push({ k: 'summary', text: raw }); continue; }
123
+ const bash = bashModeLines(raw); // `!command`: as it was shown when it ran
124
+ if (bash) { items.push({ k: 'output', lines: [...bash, ''] }); continue; }
123
125
  const text = raw.startsWith('<system-reminder>') ? '' : shownUserText(raw);
124
126
  if (text) items.push({ k: 'user', text });
125
127
  } else if (b.type === 'image') {
@@ -192,7 +194,8 @@ export const onlineEnabled = (env = process.env) => !/^(0|false|no|off)$/i.test(
192
194
 
193
195
  export class RemoteControl {
194
196
  // gateway: {url, apiKey}. handlers: info() -> {name, title, cwd, model}, seed() -> items, status() -> object,
195
- // send(text), interrupt(), answer(body) (each returns an object or throws), changed() (online or viewers changed).
197
+ // send(text, images), interrupt(), answer(body), options(body), suggest(body), list(body) (each returns an object
198
+ // or a promise of one, or throws), changed() (online or viewers changed).
196
199
  constructor({ gateway, id, handlers, fetchImpl = globalThis.fetch }) {
197
200
  this.base = String(gateway.url).replace(/\/+$/, '');
198
201
  this.apiKey = gateway.apiKey;
@@ -218,6 +221,7 @@ export class RemoteControl {
218
221
  this.registered = false;
219
222
  this.seenPeer = new Set(); // ids of the messages from other sessions already handled (the gateway sends again what was not acknowledged)
220
223
  this.peerPending = new Set(); // messages being handled now, acknowledged when done
224
+ this.replying = new Set(); // answers to the page's commands on their way
221
225
  }
222
226
 
223
227
  get viewing() { return this.viewers !== 0; } // nobody watching: events are not uploaded (a snapshot follows when someone comes)
@@ -335,20 +339,33 @@ export class RemoteControl {
335
339
  if (cmd.type === 'snapshot') { this.needSnapshot = true; this.scheduleFlush(0); return; }
336
340
  if (!cmd.cid) return;
337
341
  if (cmd.type === 'peer') { this.peerMessage(cmd); return; }
338
- let result;
342
+ // close() waits for it: a /cd from the page restarts the session before its answer goes out
343
+ const reply = (result) => {
344
+ const sent = this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
345
+ this.replying.add(sent);
346
+ sent.finally(() => this.replying.delete(sent));
347
+ this.scheduleFlush(30);
348
+ };
349
+ const failed = (e) => reply({ cid: cmd.cid, ok: false, error: e?.message || String(e) });
350
+ let r;
339
351
  try {
340
- const body = cmd.body || {};
341
- let r;
342
- if (cmd.type === 'send') r = this.handlers.send(String(body.text ?? ''));
352
+ const body = cmd.body && typeof cmd.body === 'object' ? cmd.body : {};
353
+ // send, interrupt and dialog act; options, suggest and list only look (and are answered while it works)
354
+ if (cmd.type === 'send') r = this.handlers.send(String(body.text ?? ''), body.images);
343
355
  else if (cmd.type === 'interrupt') r = this.handlers.interrupt();
344
356
  else if (cmd.type === 'dialog') r = this.handlers.answer(body);
357
+ else if (cmd.type === 'options' && this.handlers.options) r = this.handlers.options(body);
358
+ else if (cmd.type === 'suggest' && this.handlers.suggest) r = this.handlers.suggest(body);
359
+ else if (cmd.type === 'list' && this.handlers.list) r = this.handlers.list(body);
360
+ else if (cmd.type === 'output' && this.handlers.output) r = this.handlers.output(body);
345
361
  else throw new Error(`Unknown command: ${cmd.type}`);
346
- result = { cid: cmd.cid, ok: true, ...(r || {}) };
347
362
  } catch (e) {
348
- result = { cid: cmd.cid, ok: false, error: e.message };
363
+ failed(e);
364
+ return;
349
365
  }
350
- this.request('POST', `/v1/remote/sessions/${encodeURIComponent(this.id)}/results`, result).catch(() => { /* the page times out */ });
351
- this.scheduleFlush(30);
366
+ // an answer that takes a while (a list of models from the gateway, a directory) is sent when it is there
367
+ if (typeof r?.then === 'function') r.then((v) => reply({ cid: cmd.cid, ok: true, ...(v || {}) }), failed);
368
+ else reply({ cid: cmd.cid, ok: true, ...(r || {}) });
352
369
  }
353
370
 
354
371
  // ------------------------------------------------------------ messages of the account's other sessions
@@ -475,12 +492,17 @@ export class RemoteControl {
475
492
 
476
493
  // What decides whether the status is sent again: all of it while a page watches; while none does, only what
477
494
  // the gateway's session list shows (the token count of a busy session would otherwise go out every few seconds).
495
+ // `asking` (a question waits) is in it too: the gateway tells the user about it even with no page open.
478
496
  statusKey(status) {
479
497
  if (this.viewing) return JSON.stringify({ ...status, elapsed: 0 });
480
- const { busy, title, model, cwd, name } = status;
481
- return JSON.stringify({ busy, title, model, cwd, name });
498
+ const { busy, asking, title, model, cwd, name } = status;
499
+ return JSON.stringify({ busy, asking, title, model, cwd, name });
482
500
  }
483
501
 
502
+ // What is sent at once, without the wait between statuses of an unwatched session: a task that started or ended,
503
+ // a question that came or was answered.
504
+ urgentKey(status) { return `${Boolean(status.busy)}|${Boolean(status.asking)}`; }
505
+
484
506
  // What has changed goes into the next upload: a snapshot when one is due, else the events; and the status.
485
507
  flush() {
486
508
  if (this.closed || !this.registered) return;
@@ -491,6 +513,7 @@ export class RemoteControl {
491
513
  this.events = [];
492
514
  this.sinceSnapshot = 0;
493
515
  this.lastStatus = this.statusKey(status);
516
+ this.lastUrgent = this.urgentKey(status);
494
517
  this.lastStatusAt = Date.now();
495
518
  this.outbox.push({ t: 'snapshot', seq: this.seq, items: snapshotItems(this.state.items), status });
496
519
  } else if (this.events.length) {
@@ -499,8 +522,10 @@ export class RemoteControl {
499
522
  this.events = [];
500
523
  }
501
524
  const key = this.statusKey(status);
502
- if (key !== this.lastStatus && Date.now() - this.lastStatusAt >= (this.viewing ? 0 : IDLE_STATUS_MS)) {
525
+ const urgent = this.urgentKey(status);
526
+ if (key !== this.lastStatus && (urgent !== this.lastUrgent || Date.now() - this.lastStatusAt >= (this.viewing ? 0 : IDLE_STATUS_MS))) {
503
527
  this.lastStatus = key;
528
+ this.lastUrgent = urgent;
504
529
  this.lastStatusAt = Date.now();
505
530
  this.outbox.push({ t: 'status', status });
506
531
  }
@@ -527,8 +552,18 @@ export class RemoteControl {
527
552
 
528
553
  // Ends the connection; resolves once the gateway was told (or gave up waiting). `restarting`: the session comes
529
554
  // back at once with the same id, and the pages wait for it.
530
- async close({ restarting = false } = {}) {
531
- if (this.closed) return;
555
+ close({ restarting = false } = {}) {
556
+ this.closeDone ??= this.shutdown(restarting);
557
+ return this.closeDone;
558
+ }
559
+
560
+ async shutdown(restarting) {
561
+ // First the answers on their way, while the command stream is still open (the gateway fails what is still
562
+ // waiting once it closes). Among them the answer to the command that ends the session: a /cd or /exit from the
563
+ // page closes it from inside that command, and its answer is sent when the command returns, hence the wait for
564
+ // the current call to finish first.
565
+ await null;
566
+ if (this.replying.size) await Promise.race([Promise.allSettled([...this.replying]), new Promise((r) => setTimeout(r, 1500).unref?.())]);
532
567
  this.closing = true; // what flush() collects now goes out with the last message, not on its own
533
568
  this.flush();
534
569
  this.closed = true;
package/src/runtime.js CHANGED
@@ -3,7 +3,6 @@
3
3
  import path from 'node:path';
4
4
  import crypto from 'node:crypto';
5
5
  import { loadConfig, applyRememberedChoices, SOURCE_CHECKOUT } from './config.js';
6
- import { ModeManager } from './modes.js';
7
6
  import { CheckpointStore } from './checkpoints.js';
8
7
  import { loadAgents, loadSkills } from './agents.js';
9
8
  import { buildTools, toolsForSubagent } from './tools/index.js';
@@ -25,8 +24,7 @@ export async function createRuntime({ cwd, flags = {}, io }) {
25
24
  pruneToolResults(cwd);
26
25
  pruneCheckpoints(cwd);
27
26
  pruneStaleShellFiles();
28
- // Full access: nothing is ever asked. The only mode switch is the read-only plan mode (--plan).
29
- const modes = new ModeManager(flags.plan ? 'plan' : 'full');
27
+ // Full access: nothing is ever asked.
30
28
  const checkpoints = new CheckpointStore(path.join(projectDir(cwd), 'checkpoints', `${Date.now()}-${crypto.randomBytes(3).toString('hex')}`));
31
29
 
32
30
  const agents = loadAgents(cwd);
@@ -37,7 +35,7 @@ export async function createRuntime({ cwd, flags = {}, io }) {
37
35
  const hooks = new HookRunner(config);
38
36
  const tasks = new BackgroundTasks();
39
37
  const memoryDir = autoMemoryDir(cwd);
40
- const runtime = { config, modes, checkpoints, agents, mcp, shell, io, cwd, hooks, tasks, memoryDir };
38
+ const runtime = { config, checkpoints, agents, mcp, shell, io, cwd, hooks, tasks, memoryDir };
41
39
  runtime.skills = loadSkills(cwd);
42
40
  // The self-check builds the Restart tool too, so that a mistake in it is found before a restart relies on it.
43
41
  const restartable = canRestart() || process.env.CLAUDE_PRO_SELF_CHECK === '1';
@@ -116,7 +114,6 @@ export async function createRuntime({ cwd, flags = {}, io }) {
116
114
  const depth = (ctx.depth ?? ctx.agent?.depth ?? 0) + 1;
117
115
  const sub = new Agent({
118
116
  config,
119
- modes,
120
117
  checkpoints,
121
118
  depth,
122
119
  spawnSubagent: runtime.spawnSubagent,
@@ -148,7 +145,6 @@ export async function createRuntime({ cwd, flags = {}, io }) {
148
145
 
149
146
  runtime.agent = new Agent({
150
147
  config,
151
- modes,
152
148
  checkpoints,
153
149
  tools: runtime.tools,
154
150
  systemPrompt: runtime.systemPrompt,
package/src/session.js CHANGED
@@ -52,6 +52,30 @@ export function autoMemoryDir(cwd) {
52
52
  return path.join(projectDir(cwd), 'memory');
53
53
  }
54
54
 
55
+ // /cd: the conversation in `file` goes on in another working directory, so its file goes to that directory's project
56
+ // (where /resume there finds it, and where a SessionStore(cwd, id) appends), with the new directory in its first
57
+ // line. The copy is written now; commit() removes the old file, undo() the copy. {file, commit, undo}.
58
+ export function moveSession(file, id, cwd) {
59
+ const target = path.join(projectDir(cwd), `${id}.jsonl`);
60
+ const none = { file: target, commit() {}, undo() {} };
61
+ if (path.resolve(target) === path.resolve(file)) return none;
62
+ let text;
63
+ try { text = fs.readFileSync(file, 'utf8'); } catch (e) { if (e.code === 'ENOENT') return none; throw e; } // nothing written yet
64
+ const nl = text.indexOf('\n');
65
+ let first = nl >= 0 ? text.slice(0, nl) : text;
66
+ try {
67
+ const meta = JSON.parse(first);
68
+ if (meta?.type === 'meta') first = JSON.stringify({ ...meta, cwd });
69
+ } catch { /* not a meta line: kept as it is */ }
70
+ fs.mkdirSync(path.dirname(target), { recursive: true });
71
+ fs.writeFileSync(target, first + (nl >= 0 ? text.slice(nl) : '\n'));
72
+ return {
73
+ file: target,
74
+ commit() { try { fs.rmSync(file, { force: true }); } catch { /* two copies: /resume shows it in both places */ } },
75
+ undo() { try { fs.rmSync(target, { force: true }); } catch { /* left behind */ } },
76
+ };
77
+ }
78
+
55
79
  export class SessionStore {
56
80
  constructor(cwd, id = crypto.randomUUID()) {
57
81
  this.cwd = cwd;
package/src/supervisor.js CHANGED
@@ -39,16 +39,18 @@ export function sessionEntry(entry, platform = process.platform) {
39
39
  }
40
40
 
41
41
  // Whether this invocation is an interactive session that should run under the supervisor.
42
+ // A background session (--headless, started by the computer service) has no terminal and is one all the same.
42
43
  export function shouldSupervise(argv, env = process.env, isTty = (fd) => tty.isatty(fd)) {
43
44
  if (env[ENV_SUPERVISED] || /^(1|true|yes)$/i.test(env.CLAUDE_PRO_NO_SUPERVISOR || '')) return false;
44
- if (!isTty(0) || !isTty(1)) return false;
45
- if (argv[0] === 'config' || argv[0] === 'host') return false;
45
+ if (['config', 'host', 'attach', 'connect'].includes(argv[0])) return false;
46
+ if ((!isTty(0) || !isTty(1)) && !argv.includes('--headless')) return false;
46
47
  return !argv.some((a) => NOT_INTERACTIVE.has(a));
47
48
  }
48
49
 
49
50
  function putTerminalRight() {
50
51
  // The child may have died with the terminal in the mode it had set for itself.
51
52
  // (the fullscreen renderer's alternate screen and mouse reporting included)
53
+ if (!tty.isatty(1)) return; // a background session's log
52
54
  try { process.stdout.write('\x1b[?1000l\x1b[?1002l\x1b[?1006l\x1b[?1049l\x1b[?2004l\x1b[?25h'); } catch { /* nothing to do */ }
53
55
  try { if (tty.isatty(0)) process.stdin.setRawMode(false); } catch { /* nothing to do */ }
54
56
  }
@@ -84,7 +86,8 @@ export function supervise(argv, { entry, env = process.env, execPath = process.e
84
86
  const childEnv = { ...env, [ENV_SUPERVISED]: '1', [ENV_RESTART_FILE]: stateFile };
85
87
  if (restarted) childEnv[ENV_RESTARTED] = '1'; else delete childEnv[ENV_RESTARTED];
86
88
  const startedAt = Date.now();
87
- child = spawn(execPath, [sessionEntry(entry), ...argv], { stdio: 'inherit', env: childEnv });
89
+ // a background session has no console: without windowsHide Windows would give its child a window of its own
90
+ child = spawn(execPath, [sessionEntry(entry), ...argv], { stdio: 'inherit', env: childEnv, windowsHide: argv.includes('--headless') });
88
91
  child.on('error', (e) => {
89
92
  child = null;
90
93
  err.write(`claude-pro: could not start (${e.message})\n`);
package/src/tools/bash.js CHANGED
@@ -57,7 +57,7 @@ export function shutdownBackgroundShells() {
57
57
  }
58
58
 
59
59
  export function listBackgroundShells() {
60
- return [...background.entries()].map(([id, bg]) => ({ id, command: bg.command, status: bg.status, exitCode: bg.exitCode }));
60
+ return [...background.entries()].map(([id, bg]) => ({ id, command: bg.command, description: bg.description || '', status: bg.status, exitCode: bg.exitCode, startedAt: bg.startedAt }));
61
61
  }
62
62
 
63
63
  export function makeBashTool(config) {
@@ -104,7 +104,7 @@ When you commit (the system prompt says when): run git status, git diff and git
104
104
  if (input.run_in_background) {
105
105
  const child = spawnShell(shell, command, { cwd, env: childEnv(), stdin: stdinText });
106
106
  const id = `bash_${++bgCounter}`;
107
- const bg = { child, command, output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
107
+ const bg = { child, command, description: String(input.description || ''), output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
108
108
  background.set(id, bg);
109
109
  // Decode as a stream: a multi-byte character (CJK text) can be split between two chunks.
110
110
  child.stdout.setEncoding('utf8');
@@ -2,7 +2,7 @@ import { ReadTool, WriteTool, EditTool } from './files.js';
2
2
  import { makeBashTool, BashOutputTool, KillShellTool } from './bash.js';
3
3
  import { GlobTool, GrepTool } from './search.js';
4
4
  import { makeWebFetchTool, WebSearchTool } from './web.js';
5
- import { TodoWriteTool, ExitPlanModeTool, AskUserQuestionTool } from './interaction.js';
5
+ import { TodoWriteTool, AskUserQuestionTool } from './interaction.js';
6
6
  import { makeTaskTool, TaskOutputTool, TaskStopTool } from './task.js';
7
7
  import { NotebookEditTool } from './notebook.js';
8
8
  import { makeSkillTool } from './skill.js';
@@ -31,7 +31,6 @@ export function buildTools(config, { agents, skills, mcpTools = [], restart = fa
31
31
  TodoWriteTool,
32
32
  BashOutputTool,
33
33
  KillShellTool,
34
- ExitPlanModeTool,
35
34
  AskUserQuestionTool,
36
35
  makeEffortTool(config),
37
36
  ...(restart ? [RestartTool] : []),
@@ -41,7 +40,7 @@ export function buildTools(config, { agents, skills, mcpTools = [], restart = fa
41
40
  }
42
41
 
43
42
  // Effort: a sub-agent shares the main agent's settings, so it must not change them.
44
- const NEVER_FOR_SUBAGENTS = new Set(['TaskOutput', 'TaskStop', 'TodoWrite', 'ExitPlanMode', 'AskUserQuestion', 'Restart', 'Effort', 'ListPeers', 'MessagePeer']);
43
+ const NEVER_FOR_SUBAGENTS = new Set(['TaskOutput', 'TaskStop', 'TodoWrite', 'AskUserQuestion', 'Restart', 'Effort', 'ListPeers', 'MessagePeer']);
45
44
 
46
45
  // Tools for a sub-agent. `allowTask`: it is below the nesting limit, so it may start sub-agents of its own.
47
46
  export function toolsForSubagent(allTools, def, { allowTask = false } = {}) {
@@ -1,5 +1,4 @@
1
- // Tools that interact with the session rather than the machine: TodoWrite,
2
- // ExitPlanMode and AskUserQuestion.
1
+ // Tools that interact with the session rather than the machine: TodoWrite and AskUserQuestion.
3
2
 
4
3
  export const TodoWriteTool = {
5
4
  name: 'TodoWrite',
@@ -36,6 +35,7 @@ How:
36
35
  async call(input, ctx) {
37
36
  const todos = Array.isArray(input.todos) ? input.todos.filter((t) => t && t.content) : [];
38
37
  ctx.agent.todos = todos.every((t) => t.status === 'completed') ? [] : todos;
38
+ ctx.agent.todosTurn = ctx.agent.userTurns; // see Agent.noteUserTurn
39
39
  return {
40
40
  content: 'The todo list is updated.',
41
41
  display: { todos },
@@ -43,34 +43,6 @@ How:
43
43
  },
44
44
  };
45
45
 
46
- export const ExitPlanModeTool = {
47
- name: 'ExitPlanMode',
48
- readOnly: true,
49
- description: `Use this tool when you are in plan mode and have finished planning the implementation steps of a task that requires writing code, and are ready to code. This will prompt the user to approve your plan.
50
- Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.`,
51
- input_schema: {
52
- type: 'object',
53
- properties: {
54
- plan: { type: 'string', description: 'The plan you came up with, that you want to run by the user for approval. Supports markdown. The plan should be pretty concise.' },
55
- },
56
- required: ['plan'],
57
- },
58
- summarize() { return ''; },
59
- async call(input, ctx) {
60
- if (ctx.modes.mode !== 'plan') return { isError: true, content: 'You are not in plan mode. Proceed with the task.' };
61
- const choice = await ctx.io.approvePlan(input.plan);
62
- if (choice === 'full') {
63
- ctx.modes.setMode('full');
64
- return { content: 'User has approved your plan. You can now start coding. Start with updating your todo list if applicable.', display: { plan: input.plan, approved: true } };
65
- }
66
- return {
67
- content: 'The user wants to keep planning. Do not start implementation. Wait for the user to explain what should change in the plan.',
68
- display: { plan: input.plan, approved: false },
69
- stopTurn: true,
70
- };
71
- },
72
- };
73
-
74
46
  export const AskUserQuestionTool = {
75
47
  name: 'AskUserQuestion',
76
48
  readOnly: true,
package/src/tools/task.js CHANGED
@@ -96,7 +96,7 @@ Usage notes:
96
96
  if (input.run_in_background) {
97
97
  if (!ctx.tasks) return { isError: true, content: 'Background agents are not available here; run the task in the foreground.' };
98
98
  // The task outlives this turn, so it gets its own signal and no live progress display.
99
- const base = { cwd: ctx.cwd, projectRoot: ctx.projectRoot, config: ctx.config, modes: ctx.modes, checkpoints: ctx.checkpoints, io: ctx.io, depth: ctx.agent?.depth ?? 0 };
99
+ const base = { cwd: ctx.cwd, projectRoot: ctx.projectRoot, config: ctx.config, checkpoints: ctx.checkpoints, io: ctx.io, depth: ctx.agent?.depth ?? 0 };
100
100
  const task = ctx.tasks.start({
101
101
  description: input.description || def.name,
102
102
  subagentType: def.name,
package/src/ui/ansi.js CHANGED
@@ -48,7 +48,6 @@ export const c = {
48
48
  white: hex('#ffffff'),
49
49
  claude: hex('#d77757'), // the orange brand accent
50
50
  permission: hex('#b1b9f9'),
51
- plan: hex('#48968c'),
52
51
  edits: hex('#af87ff'),
53
52
  code: hex('#b1b9f9'),
54
53
  userBg: hex('#373737', true), // the band behind the user's messages (see renderUserMessage)
package/src/ui/dialogs.js CHANGED
@@ -17,6 +17,54 @@ function box(lines, width, color) {
17
17
  return out;
18
18
  }
19
19
 
20
+ // A question answered with typed text: Enter submits, Esc cancels (shift/alt+Enter starts a new line when
21
+ // `multiline`). On the remote page it is a text box ({input: {placeholder, value, multiline}}, see App.remoteDialog).
22
+ export class TextDialog {
23
+ constructor({ title, body = [], question, placeholder = '', value = '', multiline = false, color = c.blue, onResolve, cancelValue = null }) {
24
+ this.title = title;
25
+ this.body = body;
26
+ this.question = question;
27
+ this.color = color;
28
+ this.onResolve = onResolve;
29
+ this.cancelValue = cancelValue;
30
+ this.input = { placeholder, multiline };
31
+ this.editor = new Editor();
32
+ if (value) this.editor.set(value, value.length);
33
+ }
34
+
35
+ get value() { return this.editor.text; }
36
+
37
+ resolve(value) {
38
+ const cb = this.onResolve;
39
+ this.onResolve = null;
40
+ cb?.(value);
41
+ }
42
+
43
+ handleKey(str, key = {}) {
44
+ if (key.name === 'escape') { this.resolve(this.cancelValue); return true; }
45
+ if (key.name === 'return' && !key.meta && !key.shift) { this.resolve(this.editor.text); return true; }
46
+ if (key.name === 'return' && !this.input.multiline) return true;
47
+ this.editor.handleKey(str, key);
48
+ return true; // modal: everything else is the editor's
49
+ }
50
+
51
+ render(width) {
52
+ const lines = [];
53
+ if (this.title) lines.push(c.bold(this.color(this.title)), '');
54
+ lines.push(...this.body);
55
+ if (this.body.length) lines.push('');
56
+ if (this.question) lines.push(this.question, '');
57
+ const inner = Math.max(20, width - 1) - 4;
58
+ const r = this.editor.render(width - 4, { placeholder: this.input.placeholder || 'Type the answer' });
59
+ const top = lines.length + 1; // +1 for the box's top border
60
+ lines.push(...r.lines.map((l) => truncate(l, inner)));
61
+ const cursor = r.cursor ? { row: top + r.cursor.row, col: 2 + r.cursor.col } : null;
62
+ const out = box(lines, width, this.color);
63
+ out.push(c.dim(` Enter to submit${this.input.multiline ? ' · shift+Enter for a new line' : ''} · Esc to cancel`));
64
+ return { lines: out, cursor };
65
+ }
66
+ }
67
+
20
68
  export class SelectDialog {
21
69
  // options: [{label, value, description?}]
22
70
  // selected: the option highlighted at first.
package/src/ui/render.js CHANGED
@@ -27,6 +27,16 @@ export function resultLines(lines) {
27
27
  return lines.map((l, i) => (i === 0 ? c.gray(RESULT_PREFIX) : RESULT_INDENT) + l);
28
28
  }
29
29
 
30
+ // A message of bash mode (`!command`, see App.runBashMode) as it was shown when it ran: the command, then its output
31
+ // (at most 40 lines, the middle left out). null for any other message.
32
+ export function bashModeLines(text) {
33
+ const m = /^<bash-input>([\s\S]*?)<\/bash-input>\n?(?:<bash-stdout>([\s\S]*?)<\/bash-stdout>)?\n?(?:<bash-stderr>([\s\S]*?)<\/bash-stderr>)?/.exec(String(text ?? ''));
34
+ if (!m) return null;
35
+ let lines = [m[2], m[3]].filter((s) => s != null && s !== '').join('\n').split('\n');
36
+ if (lines.length > 40) lines = [...lines.slice(0, 20), c.dim(`… +${lines.length - 40} lines`), ...lines.slice(-20)];
37
+ return [c.magenta('! ') + m[1], ...resultLines(lines.map((l) => c.dim(l)))];
38
+ }
39
+
30
40
  function numberWidth(hunks) {
31
41
  let max = 1;
32
42
  for (const h of hunks) for (const l of h.lines) max = Math.max(max, l.oldNo || 0, l.newNo || 0);
@@ -89,10 +99,6 @@ export function renderToolResult(entry, { verbose = false, width = 100, cwd }) {
89
99
  return resultLines([...partial.map((l) => c.dim(truncate(l, w))), c.red('Interrupted by user')]);
90
100
  }
91
101
  if (d.todos) return renderTodos(d.todos);
92
- if (d.plan !== undefined) {
93
- const md = renderMarkdown(d.plan, { width: w });
94
- return resultLines([d.approved ? c.green('User approved the plan') : c.yellow('User asked to keep planning'), ...(verbose ? md : [])]);
95
- }
96
102
  if (d.preview && !r.isError) {
97
103
  const lines = [d.summary ? `${d.summary}` : ''];
98
104
  if (d.preview.kind === 'create' && !verbose) return resultLines([d.summary || `Created ${displayPath(d.preview.path, cwd)}`]);