reasonally 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,417 @@
1
+ /**
2
+ * Saved conversations: one JSONL file per conversation, appended as it happens, in
3
+ * `<config>/sessions/<project>/`. Owner-only, like everything else in the config folder.
4
+ */
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ import { access, appendFile, chmod, mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile, } from "node:fs/promises";
7
+ import { hostname } from "node:os";
8
+ import { basename, join } from "node:path";
9
+ import { CONTINUE_PROMPT, HELPER_PLAN_ON_NOTE, INTERRUPTED_NOTE, PLAN_OFF_NOTE, PLAN_ON_NOTE, } from "./loop-constants.js";
10
+ import { PLAN_TOOL } from "./tools/plan.js";
11
+ /** A new session's id, which is also its file name: when it started, plus a few random characters. */
12
+ export function newSessionId(now = new Date()) {
13
+ const stamp = now.toISOString().replace(/[:.]/g, "-");
14
+ return `${stamp}-${randomBytes(3).toString("hex")}`;
15
+ }
16
+ /** The folder for one project's sessions: readable name plus a hash of the full path. */
17
+ export function sessionsDir(configDir, cwd) {
18
+ const name = basename(cwd)
19
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
20
+ .slice(0, 40) || "root";
21
+ const hash = createHash("sha256").update(cwd).digest("hex").slice(0, 10);
22
+ return join(configDir, "sessions", `${name}-${hash}`);
23
+ }
24
+ /** A holder refreshes its lock this often… */
25
+ const LOCK_BEAT_MS = 30_000;
26
+ /** …so one untouched for this long was left behind by a program that died. */
27
+ export const LOCK_STALE_MS = 2 * 60_000;
28
+ const lockPath = (sessionPath) => `${sessionPath}.lock`;
29
+ function processIsAlive(pid) {
30
+ try {
31
+ process.kill(pid, 0);
32
+ return true;
33
+ }
34
+ catch (error) {
35
+ // EPERM: it exists but belongs to someone else.
36
+ return error.code === "EPERM";
37
+ }
38
+ }
39
+ const thisProcess = () => ({ pid: process.pid, host: hostname() });
40
+ /** The other running program that has this session open, or null when it's free to use. */
41
+ export async function sessionHolder(sessionPath, { self = thisProcess(), isAlive = processIsAlive, now = Date.now() } = {}) {
42
+ try {
43
+ const file = lockPath(sessionPath);
44
+ const [text, info] = await Promise.all([readFile(file, "utf8"), stat(file)]);
45
+ const lock = JSON.parse(text);
46
+ if (!lock || typeof lock.pid !== "number" || typeof lock.host !== "string")
47
+ return null;
48
+ if (lock.pid === self.pid && lock.host === self.host)
49
+ return null;
50
+ if (now - info.mtimeMs > LOCK_STALE_MS)
51
+ return null;
52
+ if (lock.host === self.host && !isAlive(lock.pid))
53
+ return null;
54
+ return { pid: lock.pid, host: lock.host, surface: lock.surface ?? "terminal" };
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
60
+ /**
61
+ * Takes the session for this program. Returns the holder when another running program has it
62
+ * (then don't write to it), or null once it's ours. If the lock can't be written at all (a
63
+ * read-only folder), that's null too: saving matters more than the lock.
64
+ */
65
+ export async function claimSession(sessionPath, surface, options = {}) {
66
+ const self = options.self ?? thisProcess();
67
+ const file = lockPath(sessionPath);
68
+ const body = JSON.stringify({ ...self, surface });
69
+ for (let attempt = 0; attempt < 2; attempt++) {
70
+ try {
71
+ await writeFile(file, body, { flag: "wx", mode: 0o600 });
72
+ return null;
73
+ }
74
+ catch (error) {
75
+ if (error.code !== "EEXIST")
76
+ return null;
77
+ }
78
+ const holder = await sessionHolder(sessionPath, options);
79
+ if (holder)
80
+ return holder;
81
+ // Ours already, or left behind: replace it.
82
+ await rm(file, { force: true }).catch(() => { });
83
+ }
84
+ return await sessionHolder(sessionPath, options);
85
+ }
86
+ /** Lets go of a session this program holds. Someone else's lock is left alone. */
87
+ export async function releaseSession(sessionPath, options = {}) {
88
+ const self = options.self ?? thisProcess();
89
+ const file = lockPath(sessionPath);
90
+ try {
91
+ const lock = JSON.parse(await readFile(file, "utf8"));
92
+ if (lock?.pid === self.pid && lock.host === self.host)
93
+ await rm(file, { force: true });
94
+ }
95
+ catch {
96
+ // no lock, or unreadable: nothing of ours to remove
97
+ }
98
+ }
99
+ /** Appends records to a session file in order; the file is created with the first record. */
100
+ export class SessionWriter {
101
+ path;
102
+ meta;
103
+ surface;
104
+ chain = Promise.resolve();
105
+ created;
106
+ /** Set when a write failed (disk full, permissions); saving stops quietly after that. */
107
+ failed = false;
108
+ beat;
109
+ constructor(path, meta,
110
+ /** Set for a new session that takes its lock when the file is created. */
111
+ surface = null) {
112
+ this.path = path;
113
+ this.meta = meta;
114
+ this.surface = surface;
115
+ this.created = meta === null;
116
+ }
117
+ /**
118
+ * A new session; nothing is written until the first record. With `surface`, the file records
119
+ * where it was started and is locked to this program while it's open (see `release`).
120
+ */
121
+ static create(dir, cwd, model, now = new Date(), surface) {
122
+ const id = newSessionId(now);
123
+ return new SessionWriter(join(dir, `${id}.jsonl`), {
124
+ type: "meta",
125
+ version: 1,
126
+ id,
127
+ cwd,
128
+ model,
129
+ createdAt: now.toISOString(),
130
+ ...(surface ? { surface } : {}),
131
+ }, surface ?? null);
132
+ }
133
+ /** Continues an existing session file. */
134
+ static resume(path) {
135
+ return new SessionWriter(path, null);
136
+ }
137
+ get started() {
138
+ return this.created;
139
+ }
140
+ /**
141
+ * Takes an existing session for this program before continuing it. Returns the holder when
142
+ * another running program has it open: show it, but don't write to it.
143
+ */
144
+ async claim(surface) {
145
+ const holder = await claimSession(this.path, surface);
146
+ if (!holder)
147
+ this.keepLock();
148
+ return holder;
149
+ }
150
+ /** Lets go of the session (after the last write lands) so another program can continue it. */
151
+ async release() {
152
+ clearInterval(this.beat);
153
+ this.beat = undefined;
154
+ await this.chain;
155
+ await releaseSession(this.path);
156
+ }
157
+ keepLock() {
158
+ clearInterval(this.beat);
159
+ const touch = () => {
160
+ const now = new Date();
161
+ utimes(lockPath(this.path), now, now).catch(() => { });
162
+ };
163
+ this.beat = setInterval(touch, LOCK_BEAT_MS);
164
+ this.beat.unref();
165
+ }
166
+ append(record) {
167
+ if (this.failed)
168
+ return;
169
+ this.chain = this.chain.then(async () => {
170
+ try {
171
+ let text = `${JSON.stringify(record, bigintSafe)}\n`;
172
+ if (!this.created) {
173
+ await mkdir(join(this.path, ".."), { recursive: true, mode: 0o700 });
174
+ text = `${JSON.stringify(this.meta)}\n${text}`;
175
+ await appendFile(this.path, text, { mode: 0o600 });
176
+ await chmod(this.path, 0o600);
177
+ this.created = true;
178
+ if (this.surface && !(await claimSession(this.path, this.surface)))
179
+ this.keepLock();
180
+ return;
181
+ }
182
+ await appendFile(this.path, text, { mode: 0o600 });
183
+ }
184
+ catch {
185
+ this.failed = true;
186
+ }
187
+ });
188
+ }
189
+ /** Resolves once everything appended so far is on disk. */
190
+ flush() {
191
+ return this.chain;
192
+ }
193
+ }
194
+ const bigintSafe = (_key, value) => typeof value === "bigint" ? value.toString() : value;
195
+ /**
196
+ * Copies a saved conversation under a new id, to carry on separately. The original isn't touched.
197
+ * The copy starts with no cost of its own: usage records stay with the original, so nothing is
198
+ * counted twice. It appears whole or not at all (written aside, then moved into place). Returns
199
+ * the copy's id; throws if the source can't be read or isn't a conversation.
200
+ */
201
+ export async function copySession(sourcePath, dir, { now = new Date(), surface } = {}) {
202
+ const text = await readFile(sourcePath, "utf8");
203
+ let meta = null;
204
+ const kept = [];
205
+ for (const line of text.split("\n")) {
206
+ if (!line.trim())
207
+ continue;
208
+ let record;
209
+ try {
210
+ record = JSON.parse(line);
211
+ }
212
+ catch {
213
+ continue; // a torn line, as loadSession skips it
214
+ }
215
+ if (record.type === "meta")
216
+ meta ??= record;
217
+ else if (record.type !== "usage")
218
+ kept.push(line);
219
+ }
220
+ if (!meta)
221
+ throw new Error("That file isn't a conversation.");
222
+ await mkdir(dir, { recursive: true, mode: 0o700 });
223
+ let id = newSessionId(now);
224
+ // Two copies in the same millisecond: the random part differs, but never overwrite anything.
225
+ while (await access(join(dir, `${id}.jsonl`)).then(() => true, () => false)) {
226
+ id = newSessionId(now);
227
+ }
228
+ const copy = {
229
+ ...meta,
230
+ id,
231
+ createdAt: now.toISOString(),
232
+ ...(surface ? { surface } : {}),
233
+ };
234
+ const path = join(dir, `${id}.jsonl`);
235
+ // Not `.jsonl`, so a listing never picks up a half-written copy.
236
+ const temp = `${path}.${process.pid}.tmp`;
237
+ try {
238
+ await writeFile(temp, [JSON.stringify(copy), ...kept].join("\n") + "\n", {
239
+ mode: 0o600,
240
+ flag: "wx",
241
+ });
242
+ await rename(temp, path);
243
+ }
244
+ catch (error) {
245
+ await rm(temp, { force: true }).catch(() => { });
246
+ throw error;
247
+ }
248
+ return id;
249
+ }
250
+ /** The record a host saves when a step finishes (with a presented plan's outcome). */
251
+ export function stepRecord(id, title, result) {
252
+ return {
253
+ type: "step",
254
+ id,
255
+ title,
256
+ summary: result.summary,
257
+ isError: Boolean(result.isError),
258
+ ...(result.plan ? { plan: result.plan } : {}),
259
+ };
260
+ }
261
+ /** The plan in a `present_plan` call's arguments, or null when they don't parse. */
262
+ function planArgument(args) {
263
+ try {
264
+ const parsed = JSON.parse(args);
265
+ return typeof parsed?.plan === "string" && parsed.plan.trim() ? parsed.plan.trim() : null;
266
+ }
267
+ catch {
268
+ return null;
269
+ }
270
+ }
271
+ /** Notes the agent adds in front of a message, never shown as what the user wrote. */
272
+ const LEADING_NOTES = [INTERRUPTED_NOTE, PLAN_ON_NOTE, HELPER_PLAN_ON_NOTE, PLAN_OFF_NOTE];
273
+ /** Strips our own markers from a user message, for showing it. */
274
+ export function userText(content) {
275
+ if (content === CONTINUE_PROMPT)
276
+ return null;
277
+ let text = content;
278
+ for (let found = true; found;) {
279
+ const note = LEADING_NOTES.find((n) => text.startsWith(n));
280
+ found = Boolean(note);
281
+ if (note)
282
+ text = text.slice(note.length).trimStart();
283
+ }
284
+ return text || null;
285
+ }
286
+ /** Reads a session. Lines that don't parse (a crash mid-write) are skipped. */
287
+ export async function loadSession(path) {
288
+ let text;
289
+ let mtime;
290
+ try {
291
+ [text, mtime] = await Promise.all([readFile(path, "utf8"), stat(path).then((s) => s.mtime)]);
292
+ }
293
+ catch {
294
+ return null;
295
+ }
296
+ let meta = null;
297
+ let messages = [];
298
+ const display = [];
299
+ const steps = new Map();
300
+ let costMicros = 0n;
301
+ let model = "";
302
+ const records = [];
303
+ for (const line of text.split("\n")) {
304
+ if (!line.trim())
305
+ continue;
306
+ try {
307
+ records.push(JSON.parse(line));
308
+ }
309
+ catch {
310
+ // partial or corrupt line
311
+ }
312
+ }
313
+ for (const r of records)
314
+ if (r.type === "step")
315
+ steps.set(r.id, r);
316
+ for (const r of records) {
317
+ switch (r.type) {
318
+ case "meta":
319
+ meta = r;
320
+ model = r.model;
321
+ break;
322
+ case "model":
323
+ model = r.id;
324
+ break;
325
+ case "usage":
326
+ costMicros += BigInt(r.costMicros);
327
+ break;
328
+ case "replace":
329
+ messages = r.messages;
330
+ if (r.reason === "compact")
331
+ display.push({ kind: "compacted" });
332
+ break;
333
+ case "append": {
334
+ const m = r.message;
335
+ messages.push(m);
336
+ if (m.role === "user") {
337
+ const shown = userText(m.content);
338
+ if (shown)
339
+ display.push({ kind: "user", text: shown });
340
+ }
341
+ else if (m.role === "assistant") {
342
+ if (m.content)
343
+ display.push({ kind: "text", text: m.content });
344
+ for (const call of m.tool_calls ?? []) {
345
+ const step = steps.get(call.id);
346
+ if (call.function.name === PLAN_TOOL) {
347
+ // Its outcome when it finished; with no step saved, it never got an answer.
348
+ const shown = step?.plan ?? (step ? null : planArgument(call.function.arguments));
349
+ if (typeof shown === "string") {
350
+ display.push({
351
+ kind: "plan",
352
+ text: shown,
353
+ edited: false,
354
+ outcome: "stopped",
355
+ feedback: null,
356
+ });
357
+ continue;
358
+ }
359
+ if (shown) {
360
+ display.push({ kind: "plan", ...shown });
361
+ continue;
362
+ }
363
+ }
364
+ display.push({
365
+ kind: "step",
366
+ title: step?.title ?? call.function.name,
367
+ summary: step?.summary ?? call.function.name,
368
+ isError: step?.isError ?? false,
369
+ });
370
+ }
371
+ }
372
+ break;
373
+ }
374
+ case "step":
375
+ break;
376
+ }
377
+ }
378
+ if (!meta)
379
+ return null;
380
+ return { path, meta, messages, display, costMicros, model, updatedAt: mtime };
381
+ }
382
+ /** This project's sessions, newest first. Unreadable or empty ones are left out. */
383
+ export async function listSessions(dir) {
384
+ let names;
385
+ try {
386
+ names = (await readdir(dir)).filter((n) => n.endsWith(".jsonl"));
387
+ }
388
+ catch {
389
+ return [];
390
+ }
391
+ const loaded = await Promise.all(names.map((n) => loadSession(join(dir, n))));
392
+ return loaded
393
+ .filter((s) => s !== null && s.display.some((d) => d.kind === "user"))
394
+ .map((s) => ({
395
+ id: s.meta.id,
396
+ path: s.path,
397
+ surface: s.meta.surface ?? "terminal",
398
+ firstMessage: s.display.find((d) => d.kind === "user").text,
399
+ model: s.model,
400
+ costMicros: s.costMicros,
401
+ updatedAt: s.updatedAt,
402
+ }))
403
+ .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
404
+ }
405
+ /** "just now", "5m ago", "3h ago", "2d ago", or the date. */
406
+ export function timeAgo(date, now = new Date()) {
407
+ const s = Math.max(0, (now.getTime() - date.getTime()) / 1000);
408
+ if (s < 60)
409
+ return "just now";
410
+ if (s < 3600)
411
+ return `${Math.floor(s / 60)}m ago`;
412
+ if (s < 86_400)
413
+ return `${Math.floor(s / 3600)}h ago`;
414
+ if (s < 30 * 86_400)
415
+ return `${Math.floor(s / 86_400)}d ago`;
416
+ return date.toISOString().slice(0, 10);
417
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A server-sent events parser that only cares about `data:` fields. Feed it decoded text in any
3
+ * chunking; it calls `onData` once per event with the event's data lines joined by "\n".
4
+ */
5
+ export function createSseParser(onData) {
6
+ let buffer = "";
7
+ let data = [];
8
+ const line = (text) => {
9
+ if (text === "") {
10
+ if (data.length)
11
+ onData(data.join("\n"));
12
+ data = [];
13
+ return;
14
+ }
15
+ if (text.startsWith(":"))
16
+ return; // comment / keep-alive
17
+ const colon = text.indexOf(":");
18
+ const field = colon === -1 ? text : text.slice(0, colon);
19
+ if (field !== "data")
20
+ return;
21
+ let value = colon === -1 ? "" : text.slice(colon + 1);
22
+ if (value.startsWith(" "))
23
+ value = value.slice(1);
24
+ data.push(value);
25
+ };
26
+ return {
27
+ push(text) {
28
+ buffer += text;
29
+ // A trailing "\r" may be the first half of "\r\n": wait for the next chunk.
30
+ const re = /\r\n|\n|\r(?!$)/g;
31
+ let start = 0;
32
+ for (let m = re.exec(buffer); m; m = re.exec(buffer)) {
33
+ line(buffer.slice(start, m.index));
34
+ start = m.index + m[0].length;
35
+ }
36
+ buffer = buffer.slice(start);
37
+ },
38
+ /** Dispatches whatever is left, as if the stream ended with a blank line. */
39
+ flush() {
40
+ if (buffer)
41
+ line(buffer.replace(/\r$/, ""));
42
+ buffer = "";
43
+ line("");
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,196 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readOnlyWords } from "../readonly-command.js";
3
+ import { resolvePath, tildePath } from "./paths.js";
4
+ import { optionalInt, stringArg, truncateMiddle } from "./types.js";
5
+ const DEFAULT_TIMEOUT_MS = 120_000;
6
+ const MAX_TIMEOUT_MS = 600_000;
7
+ const MAX_OUTPUT_CHARS = 30_000;
8
+ /** Time between asking a command to stop and forcing it. */
9
+ const KILL_GRACE_MS = 2_000;
10
+ const isWindows = process.platform === "win32";
11
+ /** The shell commands run in: the user's own on macOS/Linux, PowerShell on Windows. */
12
+ export function shellFor(env) {
13
+ if (isWindows) {
14
+ return {
15
+ file: "powershell.exe",
16
+ args: (cmd) => ["-NoProfile", "-NonInteractive", "-Command", cmd],
17
+ name: "PowerShell",
18
+ };
19
+ }
20
+ const file = env.SHELL || "/bin/sh";
21
+ return { file, args: (cmd) => ["-c", cmd], name: file.split("/").pop() ?? "sh" };
22
+ }
23
+ /** Our API key never reaches commands; pagers and prompts that would wait forever are off. */
24
+ export function commandEnv(env) {
25
+ const out = {
26
+ ...env,
27
+ PAGER: "cat",
28
+ GIT_PAGER: "cat",
29
+ GIT_TERMINAL_PROMPT: "0",
30
+ };
31
+ delete out.REASONALLY_API_KEY;
32
+ return out;
33
+ }
34
+ /** Stops a command and everything it started (it runs in its own process group). */
35
+ export function killTree(child, signal = "SIGTERM") {
36
+ if (child.pid === undefined)
37
+ return;
38
+ try {
39
+ if (isWindows) {
40
+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }).on("error", () => { });
41
+ }
42
+ else {
43
+ process.kill(-child.pid, signal);
44
+ }
45
+ }
46
+ catch {
47
+ // already gone
48
+ }
49
+ }
50
+ const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g;
51
+ export const stripAnsi = (text) => text.replace(ANSI, "");
52
+ /** Runs one command to completion, a timeout, or `signal`. Output is stdout and stderr together. */
53
+ export function runCommand(command, opts) {
54
+ const started = Date.now();
55
+ const shell = shellFor(opts.env);
56
+ return new Promise((resolve) => {
57
+ let output = "";
58
+ let timedOut = false;
59
+ let aborted = false;
60
+ let settled = false;
61
+ const child = spawn(shell.file, shell.args(command), {
62
+ cwd: opts.cwd,
63
+ env: opts.env,
64
+ stdio: ["ignore", "pipe", "pipe"],
65
+ detached: !isWindows,
66
+ windowsHide: true,
67
+ });
68
+ // Keep a little more than the cap while running; truncate once at the end.
69
+ const append = (chunk) => {
70
+ const text = chunk.toString("utf8");
71
+ output += text;
72
+ if (output.length > MAX_OUTPUT_CHARS * 4) {
73
+ output = truncateMiddle(output, MAX_OUTPUT_CHARS * 2);
74
+ }
75
+ if (opts.onOutput && !settled) {
76
+ const plain = stripAnsi(text);
77
+ if (plain)
78
+ opts.onOutput(plain);
79
+ }
80
+ };
81
+ child.stdout?.on("data", append);
82
+ child.stderr?.on("data", append);
83
+ const pid = child.pid;
84
+ if (pid !== undefined)
85
+ opts.onProcess?.(pid, "start");
86
+ let forceTimer;
87
+ const stop = () => {
88
+ killTree(child, "SIGTERM");
89
+ forceTimer = setTimeout(() => killTree(child, "SIGKILL"), KILL_GRACE_MS);
90
+ forceTimer.unref();
91
+ };
92
+ const timer = setTimeout(() => {
93
+ timedOut = true;
94
+ stop();
95
+ }, opts.timeoutMs);
96
+ const onAbort = () => {
97
+ aborted = true;
98
+ stop();
99
+ };
100
+ if (opts.signal.aborted)
101
+ onAbort();
102
+ opts.signal.addEventListener("abort", onAbort, { once: true });
103
+ const finish = (exitCode) => {
104
+ if (settled)
105
+ return;
106
+ settled = true;
107
+ clearTimeout(timer);
108
+ opts.signal.removeEventListener("abort", onAbort);
109
+ // Something it started in the background may still hold the pipes open: stop listening.
110
+ child.stdout?.destroy();
111
+ child.stderr?.destroy();
112
+ if (pid !== undefined)
113
+ opts.onProcess?.(pid, "exit");
114
+ resolve({
115
+ output: truncateMiddle(stripAnsi(output), MAX_OUTPUT_CHARS),
116
+ exitCode,
117
+ timedOut,
118
+ aborted,
119
+ ms: Date.now() - started,
120
+ });
121
+ };
122
+ child.on("error", (error) => {
123
+ output += `\n${error.message}`;
124
+ finish(null);
125
+ });
126
+ // Give the pipes a moment to drain after the shell itself exits.
127
+ child.on("exit", (code, signal) => {
128
+ setTimeout(() => finish(code ?? (signal ? null : 0)), 50);
129
+ });
130
+ child.on("close", (code) => finish(code));
131
+ });
132
+ }
133
+ const seconds = (ms) => `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`;
134
+ export const bashTool = {
135
+ name: "bash",
136
+ description: "Run a shell command in the project folder and get its output (stdout and stderr together, " +
137
+ "trimmed if long). Each call starts fresh in the project folder: `cd` doesn't carry over. " +
138
+ "Nothing is typed into it, so avoid commands that wait for input, and don't start servers or " +
139
+ "watchers that never exit. Default timeout 2 minutes (max 10).",
140
+ parameters: {
141
+ type: "object",
142
+ properties: {
143
+ command: { type: "string", description: "The command line to run." },
144
+ timeout_ms: { type: "integer", description: "Timeout in milliseconds (default 120000)." },
145
+ },
146
+ required: ["command"],
147
+ additionalProperties: false,
148
+ },
149
+ async prepare(args, ctx) {
150
+ const command = stringArg(args, "command");
151
+ const timeoutMs = optionalInt(args, "timeout_ms", 1000, MAX_TIMEOUT_MS) ?? DEFAULT_TIMEOUT_MS;
152
+ const firstLine = command.split("\n")[0];
153
+ const short = firstLine.length > 80 ? `${firstLine.slice(0, 77)}…` : firstLine;
154
+ // Commands that only look can run without asking in Plan mode: their files, resolved.
155
+ const words = isWindows ? null : readOnlyWords(command, shellFor(ctx.env).name);
156
+ const readOnlyPaths = words
157
+ ? [ctx.cwd, ...(await Promise.all(words.map((w) => resolvePath(w, ctx.cwd, ctx.home))))]
158
+ : undefined;
159
+ return {
160
+ kind: "exec",
161
+ paths: [ctx.cwd],
162
+ command,
163
+ readOnlyPaths,
164
+ title: `Run ${short}${command.includes("\n") ? " …" : ""}`,
165
+ preview: `$ ${command}\n\nin ${tildePath(ctx.cwd, ctx.home)}`,
166
+ async run() {
167
+ const result = await runCommand(command, {
168
+ cwd: ctx.cwd,
169
+ env: ctx.env,
170
+ signal: ctx.signal,
171
+ timeoutMs,
172
+ onOutput: ctx.output,
173
+ onProcess: ctx.process,
174
+ });
175
+ const status = result.aborted
176
+ ? "stopped"
177
+ : result.timedOut
178
+ ? `timed out after ${seconds(timeoutMs)}`
179
+ : result.exitCode === 0
180
+ ? "done"
181
+ : `exit ${result.exitCode ?? "?"}`;
182
+ const tail = result.aborted
183
+ ? "[Stopped by the user.]"
184
+ : result.timedOut
185
+ ? `[Timed out after ${seconds(timeoutMs)} and was stopped.]`
186
+ : `[Exit code ${result.exitCode ?? "unknown"}]`;
187
+ return {
188
+ output: `${result.output.trimEnd() || "(no output)"}\n${tail}`,
189
+ summary: `Ran ${short} · ${status} (${seconds(result.ms)})`,
190
+ isError: result.exitCode !== 0,
191
+ detail: result.output,
192
+ };
193
+ },
194
+ };
195
+ },
196
+ };
@@ -0,0 +1,33 @@
1
+ import { structuredPatch } from "diff";
2
+ /** Hunks wider than this are summarized, so a huge rewrite doesn't flood the screen. */
3
+ const MAX_PREVIEW_LINES = 400;
4
+ export function fileDiff(before, after) {
5
+ const patch = structuredPatch("a", "b", before, after, undefined, undefined, { context: 3 });
6
+ let added = 0;
7
+ let removed = 0;
8
+ const lines = [];
9
+ for (const hunk of patch.hunks) {
10
+ lines.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`);
11
+ for (const line of hunk.lines) {
12
+ if (line.startsWith("\\"))
13
+ continue; // ""
14
+ if (line.startsWith("+"))
15
+ added++;
16
+ else if (line.startsWith("-"))
17
+ removed++;
18
+ lines.push(line);
19
+ }
20
+ }
21
+ const text = lines.length > MAX_PREVIEW_LINES
22
+ ? [
23
+ ...lines.slice(0, MAX_PREVIEW_LINES),
24
+ `… ${lines.length - MAX_PREVIEW_LINES} more diff lines`,
25
+ ].join("\n")
26
+ : lines.join("\n");
27
+ return { added, removed, text };
28
+ }
29
+ /** The whole of a new file as added lines. */
30
+ export function newFileDiff(content) {
31
+ return fileDiff("", content);
32
+ }
33
+ export const diffStat = (d) => `+${d.added} −${d.removed}`;