reasonally 0.3.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,315 @@
1
+ /**
2
+ * Which shell commands only look (Plan mode runs them without asking). Pure and deliberately
3
+ * strict: anything we can't read with certainty asks, as every command does today.
4
+ *
5
+ * A command qualifies when it's one line in a POSIX shell, made only of allowlisted programs
6
+ * joined by `|`, `&&`, `||` or `;`, with no expansion, substitution or redirection of any kind.
7
+ * The words that could name files come back so the caller can resolve them (symlinks followed)
8
+ * and check that each one stays inside the project and isn't a secret.
9
+ */
10
+ /** Shells whose quoting rules this file understands. */
11
+ const POSIX_SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh"]);
12
+ const MAX_LENGTH = 500;
13
+ const MAX_WORDS = 64;
14
+ /**
15
+ * Characters that mean expansion, substitution, redirection, globbing or more when unquoted
16
+ * (`$`, backticks, `(`, `)`, `{`, `}`, `<`, `>`, `*`, `?`, `[`, `]`, `\`, `!`, `#`).
17
+ */
18
+ const UNQUOTED_SPECIAL = new Set([..."$`(){}<>*?[]\\!#"]);
19
+ /**
20
+ * Special only where a word starts (`~` is the home folder, `=cmd` a program's path in zsh,
21
+ * `^x` a negated glob in zsh), or for `~`, right after `=` or `:`. Mid-word they're plain text,
22
+ * as in `HEAD~1` or `HEAD^`.
23
+ */
24
+ const WORD_START_SPECIAL = new Set([..."~=^"]);
25
+ /** Inside double quotes these still expand. */
26
+ const DOUBLE_QUOTED_SPECIAL = new Set([..."$`\\!"]);
27
+ /** Splits a command into segments of words, or null when it uses anything we don't accept. */
28
+ export function splitCommand(command) {
29
+ if (!command.trim() || command.length > MAX_LENGTH || /[\r\n\0]/.test(command))
30
+ return null;
31
+ const segments = [];
32
+ let words = [];
33
+ let word = "";
34
+ let inWord = false;
35
+ const endWord = () => {
36
+ if (inWord)
37
+ words.push(word);
38
+ word = "";
39
+ inWord = false;
40
+ };
41
+ const endSegment = () => {
42
+ endWord();
43
+ if (!words.length)
44
+ return false;
45
+ segments.push(words);
46
+ words = [];
47
+ return true;
48
+ };
49
+ for (let i = 0; i < command.length; i++) {
50
+ const c = command[i];
51
+ if (c === "'") {
52
+ const end = command.indexOf("'", i + 1);
53
+ if (end === -1)
54
+ return null;
55
+ word += command.slice(i + 1, end);
56
+ inWord = true;
57
+ i = end;
58
+ }
59
+ else if (c === '"') {
60
+ let j = i + 1;
61
+ for (; j < command.length && command[j] !== '"'; j++) {
62
+ if (DOUBLE_QUOTED_SPECIAL.has(command[j]))
63
+ return null;
64
+ }
65
+ if (j >= command.length)
66
+ return null;
67
+ word += command.slice(i + 1, j);
68
+ inWord = true;
69
+ i = j;
70
+ }
71
+ else if (c === " " || c === "\t") {
72
+ endWord();
73
+ }
74
+ else if (c === ";") {
75
+ if (!endSegment())
76
+ return null;
77
+ }
78
+ else if (c === "|") {
79
+ if (command[i + 1] === "&")
80
+ return null;
81
+ if (command[i + 1] === "|")
82
+ i++;
83
+ if (!endSegment())
84
+ return null;
85
+ }
86
+ else if (c === "&") {
87
+ if (command[i + 1] !== "&")
88
+ return null;
89
+ i++;
90
+ if (!endSegment())
91
+ return null;
92
+ }
93
+ else if (UNQUOTED_SPECIAL.has(c)) {
94
+ return null;
95
+ }
96
+ else {
97
+ if (WORD_START_SPECIAL.has(c)) {
98
+ const prev = word.at(-1);
99
+ if (!inWord || (c === "~" && (prev === "=" || prev === ":")))
100
+ return null;
101
+ }
102
+ word += c;
103
+ inWord = true;
104
+ }
105
+ }
106
+ if (!endSegment())
107
+ return null;
108
+ return segments;
109
+ }
110
+ const isFlag = (w) => w.startsWith("-") && w !== "-";
111
+ /** `-abc` (not `--abc`): its letters, for programs whose short flags can be grouped. */
112
+ const shortLetters = (w) => (w.startsWith("-") && !w.startsWith("--") ? w.slice(1) : "");
113
+ const longName = (w) => (w.startsWith("--") ? w.slice(2).split("=")[0] : null);
114
+ /** Refuses a flag when its long name is listed, or a short group has a listed letter. */
115
+ function flagsAllowed(args, longs, letters = "") {
116
+ for (const arg of args) {
117
+ if (!isFlag(arg))
118
+ continue;
119
+ const name = longName(arg);
120
+ if (name !== null) {
121
+ if (longs.some((l) => (l.endsWith("*") ? name.startsWith(l.slice(0, -1)) : name === l))) {
122
+ return false;
123
+ }
124
+ }
125
+ else if ([...shortLetters(arg)].some((ch) => letters.includes(ch))) {
126
+ return false;
127
+ }
128
+ }
129
+ return true;
130
+ }
131
+ const any = { allowed: () => true };
132
+ const PROGRAMS = {
133
+ ls: any,
134
+ pwd: any,
135
+ echo: any,
136
+ cat: any,
137
+ head: any,
138
+ basename: any,
139
+ dirname: any,
140
+ realpath: any,
141
+ which: any,
142
+ cmp: any,
143
+ stat: any,
144
+ tail: { allowed: (a) => flagsAllowed(a, ["follow*", "retry", "pid*"], "fF") },
145
+ wc: { allowed: (a) => flagsAllowed(a, ["files0-from*"]) },
146
+ du: { allowed: (a) => flagsAllowed(a, ["files0-from*"]) },
147
+ tree: { allowed: (a) => flagsAllowed(a, ["fromfile", "output*"], "oR") },
148
+ diff: {
149
+ allowed: (a) => flagsAllowed(a, ["recursive", "from-file*", "to-file*", "output*"], "r"),
150
+ },
151
+ grep: {
152
+ pattern: true,
153
+ allowed: (a) => flagsAllowed(a, ["recursive", "dereference-recursive", "directories*", "devices*", "file"], "rRdDf"),
154
+ },
155
+ rg: {
156
+ pattern: true,
157
+ allowed: (a) => flagsAllowed(a, ["pre", "pre-glob", "search-zip", "hidden", "unrestricted", "no-ignore*", "follow", "file"], "zuL.f"),
158
+ },
159
+ find: {
160
+ allowed: (a) => !a.some((w) => [
161
+ "-exec",
162
+ "-execdir",
163
+ "-ok",
164
+ "-okdir",
165
+ "-delete",
166
+ "-fprint",
167
+ "-fprint0",
168
+ "-fprintf",
169
+ "-fls",
170
+ "-L",
171
+ "-H",
172
+ "-follow",
173
+ ].includes(w)),
174
+ },
175
+ };
176
+ /** git subcommands that only read, and any extra rule for their arguments. */
177
+ const GIT_READS = {
178
+ status: () => true,
179
+ log: () => true,
180
+ show: () => true,
181
+ diff: () => true,
182
+ blame: () => true,
183
+ "ls-files": () => true,
184
+ "ls-tree": () => true,
185
+ "rev-parse": () => true,
186
+ describe: () => true,
187
+ shortlog: () => true,
188
+ grep: (a) => flagsAllowed(a, ["open-files-in-pager*"], "O"),
189
+ // Only the forms that list: any other word would create, rename or delete.
190
+ branch: (a) => listingOnly(a, ["-l", "--list"]),
191
+ tag: (a) => listingOnly(a, ["-l", "--list"]),
192
+ remote: (a) => a.every((w) => w === "-v" || w === "--verbose"),
193
+ stash: (a) => a[0] === "list" || a[0] === "show",
194
+ };
195
+ const BRANCH_TAG_FLAGS = new Set([
196
+ "-a",
197
+ "--all",
198
+ "-r",
199
+ "--remotes",
200
+ "-v",
201
+ "-vv",
202
+ "--verbose",
203
+ "-l",
204
+ "--list",
205
+ "--show-current",
206
+ "--merged",
207
+ "--no-merged",
208
+ "--contains",
209
+ "--no-contains",
210
+ "--points-at",
211
+ "--no-color",
212
+ "--color",
213
+ "--sort",
214
+ "--format",
215
+ "--column",
216
+ "--no-column",
217
+ "-n",
218
+ ]);
219
+ /** Only listing flags; plain words (patterns, commits) only after a flag that lists. */
220
+ function listingOnly(args, listFlags) {
221
+ const listing = args.some((a) => listFlags.includes(a));
222
+ let afterValueFlag = false;
223
+ for (const arg of args) {
224
+ if (isFlag(arg)) {
225
+ const name = arg.split("=")[0];
226
+ if (!BRANCH_TAG_FLAGS.has(name) && !/^-n\d+$/.test(arg))
227
+ return false;
228
+ afterValueFlag =
229
+ !arg.includes("=") &&
230
+ ["--merged", "--no-merged", "--contains", "--no-contains", "--points-at"].includes(name);
231
+ }
232
+ else {
233
+ if (!listing && !afterValueFlag)
234
+ return false;
235
+ afterValueFlag = false;
236
+ }
237
+ }
238
+ return true;
239
+ }
240
+ /** Flags no read-only git command needs, and that write files or run programs. */
241
+ const GIT_FORBIDDEN = ["output*", "ext-diff", "exec*", "upload-pack*", "receive-pack*"];
242
+ /** The words of one segment that could name files, or null when it might change something. */
243
+ function segmentPaths(words) {
244
+ const [program, ...rest] = words;
245
+ if (program.includes("/") || program.includes("="))
246
+ return null;
247
+ let args = rest;
248
+ let rule;
249
+ if (program === "git") {
250
+ const [sub, ...gitArgs] = rest;
251
+ // Global options (-c, -C, --git-dir, -p…) come before the subcommand: none are accepted.
252
+ if (!sub || isFlag(sub))
253
+ return null;
254
+ const check = GIT_READS[sub];
255
+ if (!check || !check(gitArgs) || !flagsAllowed(gitArgs, GIT_FORBIDDEN))
256
+ return null;
257
+ args = gitArgs;
258
+ rule = { allowed: () => true, pattern: sub === "grep" };
259
+ }
260
+ else {
261
+ rule = PROGRAMS[program];
262
+ if (!rule || !rule.allowed(args))
263
+ return null;
264
+ }
265
+ const paths = [];
266
+ // A pattern given by flag (or a listing with none) means every plain word is a file.
267
+ const noPatternWord = args.some((a) => ["-e", "-f", "--regexp", "--file", "--files", "--type-list"].includes(a.split("=")[0]));
268
+ let skipPattern = Boolean(rule.pattern) && !noPatternWord;
269
+ let afterE = false;
270
+ for (const arg of args) {
271
+ if (afterE) {
272
+ // The word after -e is a pattern, not a file.
273
+ afterE = false;
274
+ continue;
275
+ }
276
+ if (arg === "-e" || arg === "--regexp") {
277
+ afterE = true;
278
+ continue;
279
+ }
280
+ if (isFlag(arg)) {
281
+ // A value given with `=` might name a file (`--exclude-from=…`): check it too.
282
+ const eq = arg.indexOf("=");
283
+ if (eq !== -1 && eq < arg.length - 1)
284
+ paths.push(arg.slice(eq + 1));
285
+ continue;
286
+ }
287
+ if (skipPattern) {
288
+ skipPattern = false;
289
+ continue;
290
+ }
291
+ paths.push(arg);
292
+ }
293
+ return paths;
294
+ }
295
+ /**
296
+ * The words that could name files when `command` only looks, else null. `shell` is the name of
297
+ * the shell commands run in (`zsh`, `bash`…); any other shell's rules aren't ours to guess.
298
+ */
299
+ export function readOnlyWords(command, shell) {
300
+ if (!POSIX_SHELLS.has(shell))
301
+ return null;
302
+ const segments = splitCommand(command);
303
+ if (!segments)
304
+ return null;
305
+ if (segments.reduce((n, s) => n + s.length, 0) > MAX_WORDS)
306
+ return null;
307
+ const paths = [];
308
+ for (const segment of segments) {
309
+ const found = segmentPaths(segment);
310
+ if (!found)
311
+ return null;
312
+ paths.push(...found);
313
+ }
314
+ return paths;
315
+ }
@@ -3,9 +3,16 @@
3
3
  * `<config>/sessions/<project>/`. Owner-only, like everything else in the config folder.
4
4
  */
5
5
  import { createHash, randomBytes } from "node:crypto";
6
- import { appendFile, chmod, mkdir, readdir, readFile, stat } from "node:fs/promises";
6
+ import { access, appendFile, chmod, mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile, } from "node:fs/promises";
7
+ import { hostname } from "node:os";
7
8
  import { basename, join } from "node:path";
8
- import { CONTINUE_PROMPT, INTERRUPTED_NOTE } from "./loop-constants.js";
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
+ }
9
16
  /** The folder for one project's sessions: readable name plus a hash of the full path. */
10
17
  export function sessionsDir(configDir, cwd) {
11
18
  const name = basename(cwd)
@@ -14,23 +21,105 @@ export function sessionsDir(configDir, cwd) {
14
21
  const hash = createHash("sha256").update(cwd).digest("hex").slice(0, 10);
15
22
  return join(configDir, "sessions", `${name}-${hash}`);
16
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
+ }
17
99
  /** Appends records to a session file in order; the file is created with the first record. */
18
100
  export class SessionWriter {
19
101
  path;
20
102
  meta;
103
+ surface;
21
104
  chain = Promise.resolve();
22
105
  created;
23
106
  /** Set when a write failed (disk full, permissions); saving stops quietly after that. */
24
107
  failed = false;
25
- constructor(path, meta) {
108
+ beat;
109
+ constructor(path, meta,
110
+ /** Set for a new session that takes its lock when the file is created. */
111
+ surface = null) {
26
112
  this.path = path;
27
113
  this.meta = meta;
114
+ this.surface = surface;
28
115
  this.created = meta === null;
29
116
  }
30
- /** A new session; nothing is written until the first record. */
31
- static create(dir, cwd, model, now = new Date()) {
32
- const stamp = now.toISOString().replace(/[:.]/g, "-");
33
- const id = `${stamp}-${randomBytes(3).toString("hex")}`;
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);
34
123
  return new SessionWriter(join(dir, `${id}.jsonl`), {
35
124
  type: "meta",
36
125
  version: 1,
@@ -38,7 +127,8 @@ export class SessionWriter {
38
127
  cwd,
39
128
  model,
40
129
  createdAt: now.toISOString(),
41
- });
130
+ ...(surface ? { surface } : {}),
131
+ }, surface ?? null);
42
132
  }
43
133
  /** Continues an existing session file. */
44
134
  static resume(path) {
@@ -47,6 +137,32 @@ export class SessionWriter {
47
137
  get started() {
48
138
  return this.created;
49
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
+ }
50
166
  append(record) {
51
167
  if (this.failed)
52
168
  return;
@@ -59,6 +175,8 @@ export class SessionWriter {
59
175
  await appendFile(this.path, text, { mode: 0o600 });
60
176
  await chmod(this.path, 0o600);
61
177
  this.created = true;
178
+ if (this.surface && !(await claimSession(this.path, this.surface)))
179
+ this.keepLock();
62
180
  return;
63
181
  }
64
182
  await appendFile(this.path, text, { mode: 0o600 });
@@ -74,13 +192,96 @@ export class SessionWriter {
74
192
  }
75
193
  }
76
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];
77
273
  /** Strips our own markers from a user message, for showing it. */
78
274
  export function userText(content) {
79
275
  if (content === CONTINUE_PROMPT)
80
276
  return null;
81
- return content.startsWith(INTERRUPTED_NOTE)
82
- ? content.slice(INTERRUPTED_NOTE.length).trimStart()
83
- : content;
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;
84
285
  }
85
286
  /** Reads a session. Lines that don't parse (a crash mid-write) are skipped. */
86
287
  export async function loadSession(path) {
@@ -142,6 +343,24 @@ export async function loadSession(path) {
142
343
  display.push({ kind: "text", text: m.content });
143
344
  for (const call of m.tool_calls ?? []) {
144
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
+ }
145
364
  display.push({
146
365
  kind: "step",
147
366
  title: step?.title ?? call.function.name,
@@ -173,7 +392,9 @@ export async function listSessions(dir) {
173
392
  return loaded
174
393
  .filter((s) => s !== null && s.display.some((d) => d.kind === "user"))
175
394
  .map((s) => ({
395
+ id: s.meta.id,
176
396
  path: s.path,
397
+ surface: s.meta.surface ?? "terminal",
177
398
  firstMessage: s.display.find((d) => d.kind === "user").text,
178
399
  model: s.model,
179
400
  costMicros: s.costMicros,
@@ -1,5 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
- import { tildePath } from "./paths.js";
2
+ import { readOnlyWords } from "../readonly-command.js";
3
+ import { resolvePath, tildePath } from "./paths.js";
3
4
  import { optionalInt, stringArg, truncateMiddle } from "./types.js";
4
5
  const DEFAULT_TIMEOUT_MS = 120_000;
5
6
  const MAX_TIMEOUT_MS = 600_000;
@@ -66,13 +67,22 @@ export function runCommand(command, opts) {
66
67
  });
67
68
  // Keep a little more than the cap while running; truncate once at the end.
68
69
  const append = (chunk) => {
69
- output += chunk.toString("utf8");
70
+ const text = chunk.toString("utf8");
71
+ output += text;
70
72
  if (output.length > MAX_OUTPUT_CHARS * 4) {
71
73
  output = truncateMiddle(output, MAX_OUTPUT_CHARS * 2);
72
74
  }
75
+ if (opts.onOutput && !settled) {
76
+ const plain = stripAnsi(text);
77
+ if (plain)
78
+ opts.onOutput(plain);
79
+ }
73
80
  };
74
81
  child.stdout?.on("data", append);
75
82
  child.stderr?.on("data", append);
83
+ const pid = child.pid;
84
+ if (pid !== undefined)
85
+ opts.onProcess?.(pid, "start");
76
86
  let forceTimer;
77
87
  const stop = () => {
78
88
  killTree(child, "SIGTERM");
@@ -99,6 +109,8 @@ export function runCommand(command, opts) {
99
109
  // Something it started in the background may still hold the pipes open: stop listening.
100
110
  child.stdout?.destroy();
101
111
  child.stderr?.destroy();
112
+ if (pid !== undefined)
113
+ opts.onProcess?.(pid, "exit");
102
114
  resolve({
103
115
  output: truncateMiddle(stripAnsi(output), MAX_OUTPUT_CHARS),
104
116
  exitCode,
@@ -139,10 +151,16 @@ export const bashTool = {
139
151
  const timeoutMs = optionalInt(args, "timeout_ms", 1000, MAX_TIMEOUT_MS) ?? DEFAULT_TIMEOUT_MS;
140
152
  const firstLine = command.split("\n")[0];
141
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;
142
159
  return {
143
160
  kind: "exec",
144
161
  paths: [ctx.cwd],
145
162
  command,
163
+ readOnlyPaths,
146
164
  title: `Run ${short}${command.includes("\n") ? " …" : ""}`,
147
165
  preview: `$ ${command}\n\nin ${tildePath(ctx.cwd, ctx.home)}`,
148
166
  async run() {
@@ -151,6 +169,8 @@ export const bashTool = {
151
169
  env: ctx.env,
152
170
  signal: ctx.signal,
153
171
  timeoutMs,
172
+ onOutput: ctx.output,
173
+ onProcess: ctx.process,
154
174
  });
155
175
  const status = result.aborted
156
176
  ? "stopped"