@introspection-ai/recipes 0.46.1 → 0.47.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.
@@ -4,19 +4,23 @@
4
4
  * the right of Pi's terminal, so the user can read it before approving it.
5
5
  *
6
6
  * An agent gets it by listing `show_artifact` in its `tools`, like
7
- * `ask_user_question`. Only markdown is shown for now; the tool is named for
8
- * artifacts so other formats can join it without renaming a tool Recipes
9
- * already list. The panel exists only in Pi's interactive terminal; anywhere
10
- * else the tool returns the path as text.
7
+ * `ask_user_question`. Any text file can be shown: markdown renders, code and
8
+ * other text are highlighted, and a file can be shown as of a git commit or
9
+ * as a diff against one (or against the version this session last showed).
10
+ * The panel exists only in Pi's interactive terminal; elsewhere the result's
11
+ * `details` carry the file and the diff, so a host such as a browser can
12
+ * render them itself.
11
13
  */
12
- import { spawn } from "node:child_process";
13
- import { readdirSync, readFileSync, realpathSync, statSync, watch, } from "node:fs";
14
+ import { execFileSync, spawn } from "node:child_process";
15
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync, watch, } from "node:fs";
14
16
  import { basename, dirname, extname, isAbsolute, relative, resolve, sep, } from "node:path";
17
+ import { generateDiffString, getLanguageFromPath, } from "@earendil-works/pi-coding-agent";
15
18
  import { Type } from "typebox";
16
19
  import { ARTIFACT_PANEL_MIN_TERMINAL_COLUMNS, ARTIFACT_PANEL_OVERLAY_OPTIONS, ArtifactPanel, } from "./artifact-viewer-tui.js";
20
+ import { artifactDiffCounts, artifactKind, SHOW_ARTIFACT_TOOL_NAME, } from "./artifact.js";
17
21
  import { createReviewArtifactsTool, REVIEW_ARTIFACTS_TOOL_NAME, } from "./artifact-review.js";
18
22
  import { artifactPanelControl, setArtifactPanelControl, } from "./interaction-tui.js";
19
- export const SHOW_ARTIFACT_TOOL_NAME = "show_artifact";
23
+ export { SHOW_ARTIFACT_TOOL_NAME } from "./artifact.js";
20
24
  /** The viewer's commands, as subcommands of Recipes' own `/recipe` so they
21
25
  * never clash with another extension's or the user's commands. */
22
26
  const VIEW_ARTIFACT_COMMAND = "recipe view";
@@ -86,12 +90,53 @@ const SKIPPED_FOLDERS = new Set([
86
90
  /** Where an owner's reviewable files usually live, listed first. */
87
91
  const PREFERRED_PARTS = ["docs/", "evals/cases/", "prompts/", "outputs/"];
88
92
  const MAX_LISTED_FILES = 50;
93
+ /** Extensions of files that are never text, left out of the file list without reading them. */
94
+ const BINARY_EXTENSIONS = new Set([
95
+ "png",
96
+ "jpg",
97
+ "jpeg",
98
+ "gif",
99
+ "webp",
100
+ "ico",
101
+ "bmp",
102
+ "tiff",
103
+ "pdf",
104
+ "zip",
105
+ "gz",
106
+ "tgz",
107
+ "bz2",
108
+ "xz",
109
+ "7z",
110
+ "tar",
111
+ "jar",
112
+ "wasm",
113
+ "so",
114
+ "dylib",
115
+ "dll",
116
+ "exe",
117
+ "bin",
118
+ "woff",
119
+ "woff2",
120
+ "ttf",
121
+ "otf",
122
+ "mp3",
123
+ "mp4",
124
+ "mov",
125
+ "wav",
126
+ "parquet",
127
+ "sqlite",
128
+ "db",
129
+ "docx",
130
+ "xlsx",
131
+ "pptx",
132
+ ].map((extension) => `.${extension}`));
89
133
  /**
90
- * The markdown files under `cwd` matching `query` (a substring of the path,
91
- * case-insensitive), the usual review files first. Bounded in depth and count
92
- * so a large workspace stays quick; hidden folders and build output are skipped.
134
+ * The text files under `cwd` matching `query` (a substring of the path,
135
+ * case-insensitive): the usual review folders first, then markdown, then the
136
+ * rest. Bounded in depth and count so a large workspace stays quick; hidden
137
+ * folders, build output and binary file types are skipped.
93
138
  */
94
- export function markdownFilesFor(cwd, query) {
139
+ export function artifactFilesFor(cwd, query) {
95
140
  const found = [];
96
141
  const walk = (dir, depth) => {
97
142
  if (depth > 6 || found.length >= 1000)
@@ -111,7 +156,8 @@ export function markdownFilesFor(cwd, query) {
111
156
  if (!SKIPPED_FOLDERS.has(entry.name))
112
157
  walk(path, depth + 1);
113
158
  }
114
- else if (entry.isFile() && isMarkdownPath(entry.name)) {
159
+ else if (entry.isFile() &&
160
+ !BINARY_EXTENSIONS.has(extname(entry.name).toLowerCase())) {
115
161
  found.push(relative(cwd, path).split(sep).join("/"));
116
162
  }
117
163
  }
@@ -124,25 +170,47 @@ export function markdownFilesFor(cwd, query) {
124
170
  };
125
171
  return found
126
172
  .filter((path) => path.toLowerCase().includes(needle))
127
- .sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))
173
+ .sort((a, b) => rank(a) - rank(b) ||
174
+ Number(!isMarkdownPath(a)) - Number(!isMarkdownPath(b)) ||
175
+ a.localeCompare(b))
128
176
  .slice(0, MAX_LISTED_FILES)
129
177
  .map((path) => ({ value: path, label: path }));
130
178
  }
131
179
  /** File extensions the panel renders. */
132
180
  const ARTIFACT_MARKDOWN_EXTENSIONS = [".md", ".markdown"];
181
+ /** The largest file the viewer reads. */
182
+ const ARTIFACT_MAX_BYTES = 1024 * 1024;
183
+ /** The most of a file (and of its diff) a result's `details` carry, as a review's interrupt does. */
184
+ const ARTIFACT_DETAILS_MAX_BYTES = 256 * 1024;
185
+ /** The bytes read to tell a text file from a binary one. */
186
+ const BINARY_SNIFF_BYTES = 8192;
187
+ /** `diff` against the version this session last showed. */
188
+ const DIFF_PREVIOUS = "previous";
189
+ /** A git revision: a name, a hash, or one with `~`/`^`/`@{…}`; never an option. */
190
+ const GIT_REF = /^[A-Za-z0-9_][\w./~^@{}-]*$/;
133
191
  const BUILTIN_OWNER = "<builtin:show_artifact>";
134
192
  const DEFAULT_DEBOUNCE_MS = 100;
135
193
  const description = [
136
- "Show a markdown file to the user in a panel on the right of the terminal, rendered as markdown.",
137
- "Call this when you want the user to read a markdown file you wrote (a brief, test cases, a report), especially before asking them to approve it, instead of only printing its path.",
138
- "`path` is relative to the working directory. Only markdown files (.md, .markdown) can be shown for now.",
139
- "The panel opens without taking the user's keyboard and re-renders when the file changes, so you don't need to call this again after editing a file it already shows.",
140
- "Outside Pi's interactive terminal there is no panel: the result says so, and you should tell the user where the file is.",
194
+ "Show a file to the user beside the conversation: markdown rendered, code and other text highlighted, HTML as source (a browser host renders it).",
195
+ "Call this when you want the user to read a file you wrote (a brief, test cases, a report, code), especially before asking them to approve it, instead of only printing its path.",
196
+ "`path` is relative to the working directory and must be a text file. `ref` and `diff` work like git, in the working directory's repository:",
197
+ "- `{ path }`: the file as it is now.",
198
+ '- `{ path, ref: "HEAD~1" }`: the file at a commit, like `git show HEAD~1:path`.',
199
+ '- `{ path, diff: "HEAD" }`: what changed since a commit, like `git diff HEAD -- path`.',
200
+ '- `{ path, ref: "HEAD", diff: "main" }`: what changed between two commits, like `git diff main HEAD -- path`.',
201
+ '- `{ path, diff: "previous" }`: what changed since you last showed it in this session; use it after revising a file the user is reading.',
202
+ "The panel re-renders when the file changes, so you don't need to call this again after editing a file it already shows.",
141
203
  ].join("\n");
142
204
  const parameters = Type.Object({
143
205
  path: Type.String({
144
- description: 'The markdown file to show, relative to the working directory (e.g. "evals/cases/refund.md").',
206
+ description: 'The file to show, relative to the working directory (e.g. "evals/cases/refund.md").',
145
207
  }),
208
+ ref: Type.Optional(Type.String({
209
+ description: "Show the file as of this git commit (a hash, a branch, HEAD~1) instead of as it is now.",
210
+ })),
211
+ diff: Type.Optional(Type.String({
212
+ description: `Show a diff instead of the whole file: "${DIFF_PREVIOUS}" for what changed since you last showed it, or a git ref to compare against.`,
213
+ })),
146
214
  }, { additionalProperties: false });
147
215
  function isInside(root, target) {
148
216
  const rel = relative(root, target);
@@ -152,23 +220,41 @@ function isInside(root, target) {
152
220
  function isMarkdownPath(path) {
153
221
  return ARTIFACT_MARKDOWN_EXTENSIONS.includes(extname(path).toLowerCase());
154
222
  }
223
+ /** Whether a file's first bytes hold a NUL, as a binary file's do. */
224
+ function looksBinary(absolutePath) {
225
+ const fd = openSync(absolutePath, "r");
226
+ try {
227
+ const buffer = Buffer.alloc(BINARY_SNIFF_BYTES);
228
+ const read = readSync(fd, buffer, 0, buffer.length, 0);
229
+ return buffer.subarray(0, read).includes(0);
230
+ }
231
+ finally {
232
+ closeSync(fd);
233
+ }
234
+ }
155
235
  /**
156
236
  * Resolve `path` against `cwd` and check that it names an existing markdown
157
- * file inside `cwd`, following symlinks. Throws an error the model or user can
158
- * act on.
237
+ * file inside `cwd`, following symlinks; with `anyText`, any text file up to
238
+ * `ARTIFACT_MAX_BYTES`. Throws an error the model or user can act on.
159
239
  */
160
- export function resolveArtifactPath(cwd, path) {
240
+ export function resolveArtifactPath(cwd, path, { anyText = false, inWorkingTree = true, } = {}) {
161
241
  const input = path.trim();
162
242
  if (!input)
163
- throw new Error("Give the path of a markdown file to show.");
243
+ throw new Error(`Give the path of a ${anyText ? "" : "markdown "}file to show.`);
164
244
  const root = resolve(cwd);
165
245
  const absolutePath = resolve(root, input);
166
246
  if (!isInside(root, absolutePath)) {
167
247
  throw new Error(`${input} is outside the working directory; only files under ${root} can be shown.`);
168
248
  }
169
- if (!isMarkdownPath(absolutePath)) {
249
+ if (!anyText && !isMarkdownPath(absolutePath)) {
170
250
  throw new Error(`${input} is not a markdown file; only ${ARTIFACT_MARKDOWN_EXTENSIONS.join(" and ")} files can be shown for now.`);
171
251
  }
252
+ const resolved = {
253
+ absolutePath,
254
+ relativePath: relative(root, absolutePath).split(sep).join("/"),
255
+ };
256
+ if (!inWorkingTree)
257
+ return resolved;
172
258
  let stats;
173
259
  try {
174
260
  stats = statSync(absolutePath);
@@ -178,14 +264,17 @@ export function resolveArtifactPath(cwd, path) {
178
264
  }
179
265
  if (!stats.isFile())
180
266
  throw new Error(`${input} is not a file.`);
267
+ if (anyText && stats.size > ARTIFACT_MAX_BYTES) {
268
+ throw new Error(`${input} is ${Math.ceil(stats.size / 1024)} KB, over the ${ARTIFACT_MAX_BYTES / 1024} KB the viewer reads; show a smaller file or a part of it.`);
269
+ }
270
+ if (anyText && looksBinary(absolutePath)) {
271
+ throw new Error(`${input} is not a text file, so it can't be shown.`);
272
+ }
181
273
  // A symlink inside the working directory may still point outside it.
182
274
  if (!isInside(realpathSync(root), realpathSync(absolutePath))) {
183
275
  throw new Error(`${input} links outside the working directory; only files under ${root} can be shown.`);
184
276
  }
185
- return {
186
- absolutePath,
187
- relativePath: relative(root, absolutePath).split(sep).join("/"),
188
- };
277
+ return resolved;
189
278
  }
190
279
  /** The default `o` action: the platform's "open with default app" command. */
191
280
  function openWithSystemApp(absolutePath) {
@@ -257,21 +346,157 @@ export function watchFileWithFs(absolutePath, onChange) {
257
346
  function workspaceRoot(target) {
258
347
  return resolve(target.absolutePath, ...target.relativePath.split("/").map(() => ".."));
259
348
  }
349
+ /** A file at `ref` in the working directory's git repository. */
350
+ function gitVersion(target, ref) {
351
+ if (!GIT_REF.test(ref)) {
352
+ throw new Error(`${ref} is not a git ref; give a commit hash, a branch or tag, or one like HEAD~1.`);
353
+ }
354
+ let text;
355
+ try {
356
+ // `./` resolves the path against the working directory, wherever the repository's root is.
357
+ text = execFileSync("git", ["show", `${ref}:./${target.relativePath}`], {
358
+ cwd: workspaceRoot(target),
359
+ encoding: "utf8",
360
+ maxBuffer: ARTIFACT_MAX_BYTES,
361
+ stdio: ["ignore", "pipe", "pipe"],
362
+ });
363
+ }
364
+ catch (error) {
365
+ if (error.code === "ENOBUFS") {
366
+ throw new Error(`${target.relativePath} at ${ref} is over the ${ARTIFACT_MAX_BYTES / 1024} KB the viewer reads.`);
367
+ }
368
+ if (git(target, ["rev-parse", "--git-dir"]) === undefined) {
369
+ throw new Error(`${target.relativePath} isn't in a git repository, so it has no version at ${ref}.`);
370
+ }
371
+ throw new Error(`${target.relativePath} has no version at ${ref} in the working directory's git repository.`);
372
+ }
373
+ // The version at the ref gets the checks a working-tree file gets on disk.
374
+ if (text.includes("\0")) {
375
+ throw new Error(`${target.relativePath} at ${ref} is not a text file, so it can't be shown.`);
376
+ }
377
+ return text;
378
+ }
260
379
  /**
261
- * Read an open file for the panel. Every refresh re-runs `resolveArtifactPath`,
262
- * since the file may since have become a symlink, or a link may point outside
263
- * the working directory; a path that no longer passes reads as unreadable.
380
+ * The file at `ref` as a diff's base: empty when the commit exists but the
381
+ * file was added since, as `git diff <ref> -- path` shows it all as added.
382
+ * A ref naming no commit still fails.
264
383
  */
265
- function readDocument(target) {
266
- let markdown;
384
+ function gitBaseVersion(target, ref) {
385
+ try {
386
+ return gitVersion(target, ref);
387
+ }
388
+ catch (error) {
389
+ const commit = GIT_REF.test(ref)
390
+ ? git(target, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`])
391
+ : undefined;
392
+ const inCommit = commit === undefined
393
+ ? undefined
394
+ : git(target, ["cat-file", "-e", `${ref}:./${target.relativePath}`]);
395
+ if (commit !== undefined && inCommit === undefined)
396
+ return "";
397
+ throw error;
398
+ }
399
+ }
400
+ /** Run git in the working directory's repository; undefined outside one or on failure. */
401
+ function git(target, args) {
267
402
  try {
268
- resolveArtifactPath(workspaceRoot(target), target.relativePath);
269
- markdown = readFileSync(target.absolutePath, "utf8");
403
+ return execFileSync("git", args, {
404
+ cwd: workspaceRoot(target),
405
+ encoding: "utf8",
406
+ maxBuffer: ARTIFACT_MAX_BYTES,
407
+ stdio: ["ignore", "pipe", "ignore"],
408
+ }).trim();
270
409
  }
271
410
  catch {
272
- markdown = undefined;
411
+ return undefined;
412
+ }
413
+ }
414
+ /** The branch (or short commit when detached) and whether the tree has uncommitted changes, as a zsh git prompt shows them. */
415
+ function gitState(target) {
416
+ const branch = git(target, ["rev-parse", "--abbrev-ref", "HEAD"]);
417
+ if (branch === undefined)
418
+ return undefined;
419
+ const name = branch === "HEAD"
420
+ ? (git(target, ["rev-parse", "--short", "HEAD"]) ?? branch)
421
+ : branch;
422
+ const status = git(target, ["status", "--porcelain", "--untracked-files=no"]);
423
+ return { branch: name, dirty: Boolean(status) };
424
+ }
425
+ /** The file as `source` names it: at its ref, or as it is now. */
426
+ function readSource(source) {
427
+ if (source.ref)
428
+ return gitVersion(source.target, source.ref);
429
+ if (source.deleted && !existsSync(source.target.absolutePath))
430
+ return "";
431
+ // A re-read re-checks the path: the file may since have become a link out of the working directory.
432
+ resolveArtifactPath(workspaceRoot(source.target), source.target.relativePath, {
433
+ anyText: true,
434
+ });
435
+ return readFileSync(source.target.absolutePath, "utf8");
436
+ }
437
+ /** Read an open file for the panel; a file that no longer passes reads as unreadable. */
438
+ function readDocument(source) {
439
+ const path = source.target.relativePath;
440
+ const language = getLanguageFromPath(path);
441
+ const title = source.ref ? `${path} @ ${source.ref}` : path;
442
+ let text;
443
+ try {
444
+ text = readSource(source);
445
+ }
446
+ catch {
447
+ text = undefined;
448
+ }
449
+ const state = gitState(source.target);
450
+ let diff;
451
+ if (source.base && text !== undefined) {
452
+ let baseText = source.base.text;
453
+ if (baseText === undefined && source.base.ref) {
454
+ try {
455
+ baseText = gitBaseVersion(source.target, source.base.ref);
456
+ }
457
+ catch {
458
+ baseText = undefined;
459
+ }
460
+ }
461
+ if (baseText !== undefined) {
462
+ const diffText = generateDiffString(baseText, text).diff;
463
+ diff = {
464
+ against: source.base.label,
465
+ text: diffText,
466
+ ...artifactDiffCounts(diffText),
467
+ };
468
+ }
273
469
  }
274
- return { title: target.relativePath, markdown };
470
+ return {
471
+ title,
472
+ kind: artifactKind(path),
473
+ text,
474
+ language,
475
+ ...(state ? { git: state } : {}),
476
+ ...(diff ? { diff } : {}),
477
+ ...(diff && source.diffFirst ? { diffFirst: true } : {}),
478
+ };
479
+ }
480
+ /** A document's diff for `details`, its text capped. */
481
+ function cappedDiff(diff) {
482
+ const text = capped(diff.text);
483
+ return {
484
+ against: diff.against,
485
+ text: text.text,
486
+ added: diff.added,
487
+ removed: diff.removed,
488
+ ...(text.truncated ? { truncated: true } : {}),
489
+ };
490
+ }
491
+ /** `text` cut to `ARTIFACT_DETAILS_MAX_BYTES`, on a character boundary. */
492
+ function capped(text) {
493
+ const bytes = new TextEncoder().encode(text);
494
+ if (bytes.length <= ARTIFACT_DETAILS_MAX_BYTES)
495
+ return { text };
496
+ const kept = new TextDecoder()
497
+ .decode(bytes.subarray(0, ARTIFACT_DETAILS_MAX_BYTES))
498
+ .replace(/\uFFFD$/, "");
499
+ return { text: kept, truncated: true };
275
500
  }
276
501
  /**
277
502
  * One session's viewer: at most one panel, the file it shows, and the last
@@ -280,6 +505,8 @@ function readDocument(target) {
280
505
  class ArtifactViewer {
281
506
  open;
282
507
  last;
508
+ /** What the tool last showed of each path, for `diff: "previous"`. */
509
+ shownVersions = new Map();
283
510
  openExternal;
284
511
  watchFile;
285
512
  debounceMs;
@@ -288,7 +515,7 @@ class ArtifactViewer {
288
515
  this.watchFile = options.watchFile ?? watchFileWithFs;
289
516
  this.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
290
517
  }
291
- /** The last markdown file shown or written, relative to the working directory. */
518
+ /** The last file shown or written, relative to the working directory. */
292
519
  get lastPath() {
293
520
  return this.last;
294
521
  }
@@ -298,31 +525,39 @@ class ArtifactViewer {
298
525
  get isHidden() {
299
526
  return this.open?.handle?.isHidden() ?? false;
300
527
  }
301
- /** Remember a markdown file the agent wrote, for `/recipe view` with no argument. */
528
+ /** What the tool last showed of `path`, if anything. */
529
+ shownVersion(path) {
530
+ return this.shownVersions.get(path);
531
+ }
532
+ /** Record what the tool showed of `path`. */
533
+ recordShown(path, text) {
534
+ this.shownVersions.set(path, text);
535
+ }
536
+ /** Remember a file the agent wrote, for `/recipe view` with no argument. */
302
537
  remember(cwd, path) {
303
- if (!isMarkdownPath(path))
304
- return;
305
538
  try {
306
- this.last = resolveArtifactPath(cwd, path).relativePath;
539
+ this.last = resolveArtifactPath(cwd, path, {
540
+ anyText: true,
541
+ }).relativePath;
307
542
  }
308
543
  catch {
309
544
  // Not a file we could show; keep the previous one.
310
545
  }
311
546
  }
312
547
  /**
313
- * Show `target` in the panel, opening it if needed. The panel never takes
548
+ * Show `source` in the panel, opening it if needed. The panel never takes
314
549
  * focus unless `focus` is set.
315
550
  */
316
- show(ctx, target, focus = false) {
317
- this.last = target.relativePath;
551
+ show(ctx, source, focus = false) {
552
+ this.last = source.target.relativePath;
318
553
  if (this.open) {
319
- this.open.target = target;
320
- // Before Pi builds the panel, the factory picks up the new target.
554
+ this.open.source = source;
555
+ // Before Pi builds the panel, the factory picks up the new source.
321
556
  if (!this.open.panel)
322
557
  return;
323
558
  this.open.stopWatching();
324
- this.open.panel.setDocument(readDocument(target));
325
- this.open.stopWatching = this.watch(target);
559
+ this.open.panel.setDocument(readDocument(source));
560
+ this.open.stopWatching = this.watch(source);
326
561
  if (focus)
327
562
  this.focus();
328
563
  return;
@@ -331,7 +566,7 @@ class ArtifactViewer {
331
566
  const state = {
332
567
  panel: undefined,
333
568
  handle: undefined,
334
- target,
569
+ source,
335
570
  close: () => done?.(undefined),
336
571
  stopWatching: () => { },
337
572
  };
@@ -340,13 +575,13 @@ class ArtifactViewer {
340
575
  void ctx.ui
341
576
  .custom((tui, theme, _keybindings, finish) => {
342
577
  done = finish;
343
- state.panel = new ArtifactPanel(tui, theme, readDocument(state.target), {
578
+ state.panel = new ArtifactPanel(tui, theme, readDocument(state.source), {
344
579
  openExternal: () => this.openCurrent(ctx),
345
580
  unfocus: () => this.unfocus(),
346
581
  close: () => state.close(),
347
582
  disposed: () => this.release(state),
348
583
  });
349
- state.stopWatching = this.watch(state.target);
584
+ state.stopWatching = this.watch(state.source);
350
585
  return state.panel;
351
586
  }, {
352
587
  overlay: true,
@@ -408,7 +643,7 @@ class ArtifactViewer {
408
643
  this.open.panel?.requestRender();
409
644
  }
410
645
  openCurrent(ctx) {
411
- const target = this.open?.target;
646
+ const target = this.open?.source.target;
412
647
  if (!target)
413
648
  return;
414
649
  Promise.resolve()
@@ -417,16 +652,19 @@ class ArtifactViewer {
417
652
  ctx.ui.notify(`Could not open ${target.relativePath}: ${error instanceof Error ? error.message : String(error)}`, "error");
418
653
  });
419
654
  }
420
- watch(target) {
655
+ watch(source) {
656
+ // A commit's version never changes, and its file may be gone from the working tree.
657
+ if (source.ref)
658
+ return () => { };
421
659
  let timer;
422
- const stop = this.watchFile(target.absolutePath, () => {
660
+ const stop = this.watchFile(source.target.absolutePath, () => {
423
661
  if (timer)
424
662
  clearTimeout(timer);
425
663
  timer = setTimeout(() => {
426
664
  timer = undefined;
427
- if (this.open?.target !== target)
665
+ if (this.open?.source !== source)
428
666
  return;
429
- this.open.panel?.setDocument(readDocument(target), true);
667
+ this.open.panel?.setDocument(readDocument(source), true);
430
668
  }, this.debounceMs);
431
669
  });
432
670
  return () => {
@@ -452,32 +690,175 @@ class ArtifactViewer {
452
690
  function errorText(error) {
453
691
  return error instanceof Error ? error.message : String(error);
454
692
  }
693
+ /**
694
+ * What to show of `target`: at `ref` or as it is now, diffed against `diff`
695
+ * (`previous` or a git ref) when given. Records what is shown, for the next
696
+ * `previous`; `note` says when there was nothing earlier to compare against.
697
+ */
698
+ function artifactSourceFor(viewer, target, ref, diff, deleted = false) {
699
+ const source = {
700
+ target,
701
+ ...(ref ? { ref } : {}),
702
+ ...(deleted ? { deleted } : {}),
703
+ };
704
+ const current = readSource(source);
705
+ const against = diff?.trim();
706
+ const previous = viewer.shownVersion(target.relativePath);
707
+ const previousBase = previous === undefined
708
+ ? undefined
709
+ : { label: "the version shown before", text: previous };
710
+ let note = "";
711
+ if (against === DIFF_PREVIOUS) {
712
+ if (previousBase)
713
+ source.base = previousBase;
714
+ else
715
+ note = ` Nothing of ${target.relativePath} was shown earlier in this session, so the whole file is shown.`;
716
+ }
717
+ else if (against) {
718
+ // Fails here, with the reason, when the ref names no commit.
719
+ const base = gitBaseVersion(target, against);
720
+ if (deleted && base === "") {
721
+ throw new Error(`${target.relativePath} does not exist, and isn't in ${against} either.`);
722
+ }
723
+ source.base = { label: against, ref: against };
724
+ }
725
+ else if (!ref || diff !== undefined) {
726
+ // With no diff named, `d` still offers one: against HEAD for a tracked file, else the version shown before.
727
+ const tracked = git(target, ["cat-file", "-e", `HEAD:./${target.relativePath}`]) !==
728
+ undefined;
729
+ if (tracked)
730
+ source.base = { label: "HEAD", ref: "HEAD" };
731
+ else if (previousBase)
732
+ source.base = previousBase;
733
+ if (deleted && !tracked) {
734
+ throw new Error(`${target.relativePath} does not exist, and isn't in HEAD either.`);
735
+ }
736
+ }
737
+ // A bare `diff` (`""`) opens on the diff `d` would show.
738
+ if (diff !== undefined && source.base)
739
+ source.diffFirst = true;
740
+ else if (diff !== undefined && !against && !source.base)
741
+ note = ` ${target.relativePath} isn't tracked by git and wasn't shown earlier in this session, so there is nothing to diff against.`;
742
+ viewer.recordShown(target.relativePath, current);
743
+ return { source, current, note };
744
+ }
745
+ /** `--name value`, `--name=value`, or a bare `--name` (value undefined). */
746
+ const COMMAND_OPTION = (name) => new RegExp(`(?:^|\\s)--${name}(?:(?:=|\\s+)(?!--)(\\S+))?(?=\\s|$)`);
747
+ /**
748
+ * Resolve a path to show. A file gone from the working tree passes only when
749
+ * a git base is asked for (`diff` other than `previous`, or a bare one, which
750
+ * diffs against HEAD): it then shows as removed, as `git diff <ref> -- path` does.
751
+ */
752
+ function resolveShownPath(cwd, path, ref, diff) {
753
+ if (ref) {
754
+ return {
755
+ target: resolveArtifactPath(cwd, path, {
756
+ anyText: true,
757
+ inWorkingTree: false,
758
+ }),
759
+ deleted: false,
760
+ };
761
+ }
762
+ try {
763
+ return {
764
+ target: resolveArtifactPath(cwd, path, { anyText: true }),
765
+ deleted: false,
766
+ };
767
+ }
768
+ catch (error) {
769
+ const gitBase = diff !== undefined && diff.trim() !== DIFF_PREVIOUS;
770
+ if (!gitBase)
771
+ throw error;
772
+ const target = resolveArtifactPath(cwd, path, {
773
+ anyText: true,
774
+ inWorkingTree: false,
775
+ });
776
+ // A file that exists but fails a check (binary, too large) still fails.
777
+ if (existsSync(target.absolutePath))
778
+ throw error;
779
+ return { target, deleted: true };
780
+ }
781
+ }
782
+ /**
783
+ * `/recipe view`'s arguments: a path, `--ref <ref>` and `--diff [<ref|previous>]`.
784
+ * A bare `--diff` (`diff: ""`) opens on the diff `d` would show.
785
+ */
786
+ function commandArgs(args, cwd) {
787
+ let rest = args;
788
+ let spaced = false;
789
+ const option = (name) => {
790
+ const match = COMMAND_OPTION(name).exec(rest);
791
+ if (!match)
792
+ return undefined;
793
+ rest = rest.replace(match[0], " ");
794
+ if (name === "diff")
795
+ spaced = match[1] !== undefined && !match[0].includes("=");
796
+ return match[1] ?? "";
797
+ };
798
+ let diff = option("diff");
799
+ const ref = option("ref");
800
+ let path = commandPath(rest);
801
+ // `--diff <file>` with no other path, when that names a file: a bare `--diff` on it.
802
+ // `--diff=<ref>`, and a value naming no file, stay a base for the last file shown.
803
+ if (!path &&
804
+ diff &&
805
+ diff !== DIFF_PREVIOUS &&
806
+ spaced &&
807
+ existsSync(resolve(cwd, commandPath(diff)))) {
808
+ path = commandPath(diff);
809
+ diff = "";
810
+ }
811
+ return {
812
+ path,
813
+ ...(ref ? { ref } : {}),
814
+ ...(diff !== undefined ? { diff } : {}),
815
+ };
816
+ }
455
817
  /** Build the tool over a session's viewer. */
456
818
  function createShowArtifactTool(viewer) {
457
819
  const tool = {
458
820
  name: SHOW_ARTIFACT_TOOL_NAME,
459
821
  label: "Show artifact",
460
822
  description,
461
- promptSnippet: "Show the user a markdown file you wrote, rendered in a panel beside the conversation",
823
+ promptSnippet: "Show the user a file you wrote, or what changed in it, beside the conversation",
462
824
  promptGuidelines: [
463
- "When you write a markdown file the user should read or approve (a brief, test cases, a report), show it with show_artifact instead of only printing its path.",
825
+ "When you write a file the user should read or approve (a brief, test cases, a report, code), show it with show_artifact instead of only printing its path; after revising one, show it with diff to point at what changed.",
464
826
  ],
465
827
  parameters,
466
828
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
467
- const target = resolveArtifactPath(ctx.cwd, params.path);
829
+ const ref = params.ref?.trim() || undefined;
830
+ const { target, deleted } = resolveShownPath(ctx.cwd, params.path, ref, params.diff);
831
+ const { source, current, note } = artifactSourceFor(viewer, target, ref, params.diff, deleted);
832
+ const document = readDocument(source);
833
+ const content = capped(current);
834
+ const details = {
835
+ path: target.relativePath,
836
+ shown: false,
837
+ kind: artifactKind(target.relativePath),
838
+ ...(document.language ? { language: document.language } : {}),
839
+ ...(ref ? { ref } : {}),
840
+ content: content.text,
841
+ ...(content.truncated ? { truncated: true } : {}),
842
+ ...(document.git ? { git: document.git } : {}),
843
+ ...(document.diff ? { diff: cappedDiff(document.diff) } : {}),
844
+ ...(document.diffFirst ? { opens: "diff" } : {}),
845
+ };
846
+ const what = document.diffFirst
847
+ ? `the diff of ${document.title} against ${document.diff.against}`
848
+ : document.title;
468
849
  if (ctx.mode !== "tui") {
469
850
  return {
470
851
  content: [
471
852
  {
472
853
  type: "text",
473
- text: `The file is at ${target.relativePath}. The artifact panel is only available in Pi's interactive terminal, so tell the user where the file is.`,
854
+ text: `There is no artifact panel here; the result carries ${what} for a host that displays it (a browser does). If the user may not see it, tell them where the file is.${note}`,
474
855
  },
475
856
  ],
476
- details: { path: target.relativePath, shown: false },
857
+ details,
477
858
  };
478
859
  }
479
860
  // It takes the keyboard as it opens, so Esc or q closes it without a shortcut first.
480
- viewer.show(ctx, target, true);
861
+ viewer.show(ctx, source, true);
481
862
  const columns = process.stdout.columns;
482
863
  if (columns !== undefined &&
483
864
  columns < ARTIFACT_PANEL_MIN_TERMINAL_COLUMNS) {
@@ -485,20 +866,20 @@ function createShowArtifactTool(viewer) {
485
866
  content: [
486
867
  {
487
868
  type: "text",
488
- text: `The terminal is ${columns} columns wide, too narrow for the panel (it needs ${ARTIFACT_PANEL_MIN_TERMINAL_COLUMNS}), so the user can't see ${target.relativePath}: tell them where the file is, or put what they need in your message. The panel appears if they widen the terminal.`,
869
+ text: `The terminal is ${columns} columns wide, too narrow for the panel (it needs ${ARTIFACT_PANEL_MIN_TERMINAL_COLUMNS}), so the user can't see ${target.relativePath}: tell them where the file is, or put what they need in your message. The panel appears if they widen the terminal.${note}`,
489
870
  },
490
871
  ],
491
- details: { path: target.relativePath, shown: false },
872
+ details,
492
873
  };
493
874
  }
494
875
  return {
495
876
  content: [
496
877
  {
497
878
  type: "text",
498
- text: `Showing ${target.relativePath} in the panel on the right, which has the keyboard: the user scrolls it and closes it with Esc or q, which returns them to the editor; /${VIEW_ARTIFACT_COMMAND} reopens it.`,
879
+ text: `Showing ${what} in the panel on the right, which has the keyboard: the user scrolls it and closes it with Esc or q, which returns them to the editor; /${VIEW_ARTIFACT_COMMAND} reopens it.${note}`,
499
880
  },
500
881
  ],
501
- details: { path: target.relativePath, shown: true },
882
+ details: { ...details, shown: true },
502
883
  };
503
884
  },
504
885
  };
@@ -536,20 +917,25 @@ export function artifactViewerExtension(registrations, options = {}, agentTools
536
917
  ctx.ui.notify(`/${VIEW_ARTIFACT_COMMAND} needs Pi's interactive terminal.`, "warning");
537
918
  return;
538
919
  }
539
- const path = commandPath(args) || viewer.lastPath;
920
+ const parsed = commandArgs(args, ctx.cwd);
921
+ const path = parsed.path || viewer.lastPath;
540
922
  if (!path) {
541
- ctx.ui.notify(`Usage: /${VIEW_ARTIFACT_COMMAND} <file.md>. With no file, it shows the last markdown file the agent showed or wrote.`, "info");
923
+ ctx.ui.notify(`Usage: /${VIEW_ARTIFACT_COMMAND} <file> [--diff [<ref|previous>]] [--ref <ref>]. With no file, it shows the last file the agent showed or wrote.`, "info");
542
924
  return;
543
925
  }
544
926
  try {
545
- viewer.show(ctx, resolveArtifactPath(ctx.cwd, path), true);
927
+ const { target, deleted } = resolveShownPath(ctx.cwd, path, parsed.ref, parsed.diff);
928
+ const { source, note } = artifactSourceFor(viewer, target, parsed.ref, parsed.diff, deleted);
929
+ viewer.show(ctx, source, true);
930
+ if (note)
931
+ ctx.ui.notify(note.trim(), "info");
546
932
  }
547
933
  catch (error) {
548
934
  ctx.ui.notify(errorText(error), "warning");
549
935
  }
550
936
  }, {
551
- description: "Show a markdown file in the panel on the right",
552
- complete: (argument, cwd) => markdownFilesFor(cwd, argument),
937
+ description: "Show a file in the panel on the right (--diff for what changed since HEAD, or --diff <ref|previous>; --ref <ref> for a commit's version)",
938
+ complete: (argument, cwd) => artifactFilesFor(cwd, argument),
553
939
  });
554
940
  pi.on("tool_result", (event, ctx) => {
555
941
  if (event.isError)