pi-better-show 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -49,7 +49,7 @@ If you use `pi-herdr-doc-review`, uninstall it first (`pi uninstall npm:pi-herdr
49
49
  - `view: "page"` opens the file in your default browser.
50
50
  Markdown renders with its blocks; `.html`, `.tsx`, and `.jsx` run in a sandboxed frame; images show as they are.
51
51
  - `view: "edit"` (the default) opens the file in your editor.
52
- Each save reaches the agent as a diff, without starting a turn.
52
+ Your saves reach the agent as one net diff per file, without starting a turn.
53
53
  - Select any passage on a page to comment on it.
54
54
  The feedback panel sends your comments and an overall note in one message.
55
55
  - Open pages reload when the agent edits the file.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-show",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "description": "Interactive blocks for agent-written Markdown: one vocabulary, text fallback, and answer encoding shared by every host, plus the show_doc extension for pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -27,7 +27,15 @@ import {
27
27
  type PublishedDocument,
28
28
  parseAnswer,
29
29
  } from "./contract.ts";
30
- import { createEditSession, defaultLaunch, defaultRun, EDITOR_ENV, type EditDeps, WATCH_MS } from "./edit.ts";
30
+ import {
31
+ createEditSession,
32
+ defaultLaunch,
33
+ defaultRun,
34
+ EDITOR_ENV,
35
+ type EditDeps,
36
+ SETTLE_MS,
37
+ WATCH_MS,
38
+ } from "./edit.ts";
31
39
  import { createAllowList, HTML_FILE, IMAGE_FILE, MARKDOWN_FILE, REACT_FILE } from "./files.ts";
32
40
  import type { PageServer, PageServerOptions } from "./server.ts";
33
41
 
@@ -58,6 +66,8 @@ export interface Deps extends EditDeps {
58
66
  realpath: (path: string) => string;
59
67
  newId: () => string;
60
68
  now: () => number;
69
+ /** Runs `run` after `ms`; the returned function cancels it. */
70
+ schedule: (run: () => void, ms: number) => () => void;
61
71
  }
62
72
 
63
73
  /**
@@ -96,6 +106,11 @@ export const defaultDeps = (): Deps => ({
96
106
  realpath: (path) => (existsSync(path) ? realpathSync(path) : path),
97
107
  newId: randomUUID,
98
108
  now: Date.now,
109
+ schedule: (run, ms) => {
110
+ const timer = setTimeout(run, ms);
111
+ timer.unref?.();
112
+ return () => clearTimeout(timer);
113
+ },
99
114
  });
100
115
 
101
116
  interface DocEntry {
@@ -143,7 +158,48 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
143
158
  if (ctx?.hasUI) ctx.ui.notify(`${notice} go to the agent with your next message.`, "info");
144
159
  };
145
160
 
146
- const edits = createEditSession(deps, (message, display) => deliver(message, `Your edits to ${display}`));
161
+ // The user's saves are held, not sent one by one: when idle, their net change joins the next run as it starts;
162
+ // while the agent works, it is steered in once the saves stop for SETTLE_MS.
163
+ let cancelSettle: (() => void) | undefined;
164
+ /** The file of the last change waiting to be reported, while one waits. */
165
+ let waiting: string | undefined;
166
+ /** The user was told their edits wait for their next message. */
167
+ let told = false;
168
+ const busy = (): boolean => ctx !== undefined && !ctx.isIdle();
169
+ const editMessage = (text: string) => ({ customType: MESSAGE_TYPE, content: text, display: true });
170
+ const stopSettle = (): void => {
171
+ cancelSettle?.();
172
+ cancelSettle = undefined;
173
+ };
174
+ /** Takes every unreported change; the user's next change starts a new report. */
175
+ const takeEdits = (): string | undefined => {
176
+ stopSettle();
177
+ waiting = undefined;
178
+ told = false;
179
+ return edits.take();
180
+ };
181
+ const tellHeld = (display: string): void => {
182
+ if (told || !ctx?.hasUI) return;
183
+ told = true;
184
+ ctx.ui.notify(`Your edits to ${display} go to the agent with your next message.`, "info");
185
+ };
186
+ const settleLater = (display: string): void => {
187
+ stopSettle();
188
+ cancelSettle = deps.schedule(() => {
189
+ cancelSettle = undefined;
190
+ if (!busy()) return tellHeld(display);
191
+ const text = takeEdits();
192
+ if (text) pi.sendMessage(editMessage(text), { deliverAs: "steer" });
193
+ }, SETTLE_MS);
194
+ };
195
+ const edits = createEditSession(deps, {
196
+ changed: (display) => {
197
+ waiting = display;
198
+ if (busy()) settleLater(display);
199
+ else tellHeld(display);
200
+ },
201
+ urgent: (text) => deliver(text, "Your edits"),
202
+ });
147
203
 
148
204
  const listed = (): PublishedDocument[] =>
149
205
  [...docs.values()].map((entry) => ({
@@ -462,8 +518,20 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
462
518
  /** A turn or run ended: tool calls that never ended no longer hold back the user's saves. */
463
519
  const agentSettled = (): void => edits.settle();
464
520
 
521
+ /** A run starts: the user's edits since the agent last saw each file join it as one message, or nothing when none changed. */
522
+ const agentStarting = (): { customType: string; content: string; display: boolean } | undefined => {
523
+ const text = takeEdits();
524
+ return text ? editMessage(text) : undefined;
525
+ };
526
+
527
+ /** A run started without a prompt (a queued message or a retry): edits still waiting go in once the saves settle. */
528
+ const agentStarted = (): void => {
529
+ if (waiting !== undefined && !cancelSettle) settleLater(waiting);
530
+ };
531
+
465
532
  const shutdown = (): void => {
466
533
  closed = true;
534
+ stopSettle();
467
535
  docs.clear();
468
536
  answers.clear();
469
537
  edits.close();
@@ -484,6 +552,8 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
484
552
  agentWrote,
485
553
  agentWillWrite,
486
554
  agentSettled,
555
+ agentStarting,
556
+ agentStarted,
487
557
  shutdown,
488
558
  setContext: (next: ExtensionContext) => {
489
559
  ctx = next;
@@ -5,6 +5,10 @@ import { join } from "node:path";
5
5
 
6
6
  export const EDITOR_ENV = "PI_BETTER_SHOW_EDITOR";
7
7
  export const MAX_DIFF_CHARS = 20_000;
8
+ /** A reported diff keeps at most this many lines. */
9
+ export const MAX_DIFF_LINES = 200;
10
+ /** While the agent works, edits are reported once the user stopped saving for this long. */
11
+ export const SETTLE_MS = 3000;
8
12
  export const WATCH_MS = 500;
9
13
 
10
14
  export interface RunResult {
@@ -76,24 +80,27 @@ export function shellWords(line: string): string[] {
76
80
  return words;
77
81
  }
78
82
 
79
- /** The user's edits as zero-context hunks: the `@@` headers carry the line numbers. */
83
+ /** The user's edits as zero-context hunks: the `@@` headers carry the line numbers. A long diff keeps its first lines and says how many it left out. */
80
84
  export function feedbackMessage(display: string, diff: string, duringShell = false): string {
81
- const hunks = diff
82
- .split("\n")
83
- .filter((line) => !line.startsWith("--- ") && !line.startsWith("+++ "))
84
- .join("\n");
85
- const body =
86
- hunks.length > MAX_DIFF_CHARS ? `${hunks.slice(0, MAX_DIFF_CHARS)}\n… (truncated; read ${display})\n` : hunks;
85
+ const lines = diff.split("\n").filter((line) => !line.startsWith("--- ") && !line.startsWith("+++ "));
86
+ if (lines.at(-1) === "") lines.pop();
87
+ const kept = lines.slice(0, MAX_DIFF_LINES).join("\n");
88
+ const body = kept.slice(0, MAX_DIFF_CHARS);
89
+ const left = lines.length - Math.min(lines.length, MAX_DIFF_LINES);
90
+ const more = left > 0 ? `: ${left} more diff line${left === 1 ? "" : "s"}` : "";
91
+ const cut = left > 0 || body.length < kept.length ? `\n… (truncated${more}; read ${display})` : "";
87
92
  const head = duringShell
88
93
  ? `${display} changed while a shell command ran; this may include the command's own changes, not only the user's edits:`
89
94
  : `User edited ${display}:`;
90
- return `${head}\n\`\`\`diff\n${body}\`\`\``;
95
+ return `${head}\n\`\`\`diff\n${body}${cut}\n\`\`\``;
91
96
  }
92
97
 
93
98
  interface Watched {
94
99
  display: string;
95
- /** The content the agent last saw. */
100
+ /** The content the agent last saw: the baseline of the next report. */
96
101
  snapshot: string;
102
+ /** Part of the change not yet reported came while a shell command ran. */
103
+ duringShell: boolean;
97
104
  stop: () => void;
98
105
  onError: (error: Error) => void;
99
106
  }
@@ -104,7 +111,19 @@ interface Active {
104
111
  before: Map<string, string>;
105
112
  }
106
113
 
107
- export function createEditSession(deps: EditDeps, onEdit: (message: string, display: string) => void) {
114
+ export interface EditEvents {
115
+ /** A shown file changed in a way the agent has not seen; it waits for `take`. Called on every such change. */
116
+ changed: (display: string) => void;
117
+ /** The agent is about to write a file whose unreported change it must see first: deliver this at once. */
118
+ urgent: (message: string) => void;
119
+ }
120
+
121
+ /**
122
+ * Watches the documents opened in the user's editor and keeps what changed since the agent last saw each one.
123
+ * Saves are not reported one by one: `take` reports the net change of every file since the last report, once,
124
+ * so intermediate states never reach the agent and a change undone before the report sends nothing.
125
+ */
126
+ export function createEditSession(deps: EditDeps, events: EditEvents) {
108
127
  const watched = new Map<string, Watched>();
109
128
  /**
110
129
  * Tool calls running now, by tool call id: a change seen meanwhile is the agent's. They are keyed by id so a call
@@ -144,15 +163,42 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
144
163
  const paused = (path: string): boolean =>
145
164
  [...active.values()].some((call) => call.path === undefined || call.path === path);
146
165
 
147
- /** Reports how `path` went from `from` to `content`, and makes `content` the version the agent saw. */
148
- function report(path: string, doc: Watched, from: string, content: string, duringShell: boolean): void {
166
+ /** The diff of a file from what the agent saw to `content`, as a message section; the agent has now seen `content`. */
167
+ function report(doc: Watched, content: string): string {
149
168
  scratch ??= deps.makeDir();
150
169
  const before = join(scratch, "before");
151
- deps.writeFile(before, from);
152
- const diff = deps.run("diff", ["-U0", "--label", `a/${doc.display}`, "--label", `b/${doc.display}`, before, path]);
170
+ const after = join(scratch, "after");
171
+ deps.writeFile(before, doc.snapshot);
172
+ // The content read, not the file: a save landing between the read and the diff waits for the next report.
173
+ deps.writeFile(after, content);
174
+ const diff = deps.run("diff", ["-U0", "--label", `a/${doc.display}`, "--label", `b/${doc.display}`, before, after]);
153
175
  if (diff.status !== 0 && diff.status !== 1) throw new Error(`diff failed: ${diff.stderr.trim()}`);
176
+ const section = feedbackMessage(doc.display, diff.stdout, doc.duringShell);
154
177
  doc.snapshot = content;
155
- onEdit(feedbackMessage(doc.display, diff.stdout, duringShell), doc.display);
178
+ doc.duringShell = false;
179
+ return section;
180
+ }
181
+
182
+ /** The net change of each file (of `only`, when given) since the agent last saw it, in one message; undefined when nothing changed. */
183
+ function take(only?: string): string | undefined {
184
+ const sections: string[] = [];
185
+ for (const [path, doc] of watched) {
186
+ if ((only !== undefined && path !== only) || paused(path)) continue;
187
+ const content = deps.readFile(path);
188
+ if (content === undefined) continue;
189
+ if (content === doc.snapshot) {
190
+ doc.duringShell = false;
191
+ continue;
192
+ }
193
+ try {
194
+ sections.push(report(doc, content));
195
+ } catch (error) {
196
+ doc.snapshot = content;
197
+ doc.duringShell = false;
198
+ doc.onError(error as Error);
199
+ }
200
+ }
201
+ return sections.length > 0 ? sections.join("\n\n") : undefined;
156
202
  }
157
203
 
158
204
  function onChange(path: string): void {
@@ -160,10 +206,10 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
160
206
  if (!doc || paused(path)) return;
161
207
  const content = deps.readFile(path);
162
208
  if (content === undefined || content === doc.snapshot) return;
163
- report(path, doc, doc.snapshot, content, false);
209
+ events.changed(doc.display);
164
210
  }
165
211
 
166
- /** A call ended: the version the agent saw is what is on disk now, except that a shell command's window reports what changed in it. */
212
+ /** A call ended: a write or edit's result is the version the agent saw; a shell command's window joins what waits to be reported. */
167
213
  function release(id: string): void {
168
214
  const call = active.get(id);
169
215
  if (!call) return;
@@ -172,23 +218,24 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
172
218
  if (call.path !== undefined && call.path !== path) continue;
173
219
  const content = deps.readFile(path);
174
220
  if (content === undefined) continue;
221
+ if (call.path !== undefined) {
222
+ doc.snapshot = content;
223
+ doc.duringShell = false;
224
+ continue;
225
+ }
175
226
  // Measured against what the agent last saw, so a save the watcher had not seen yet still counts, and a
176
- // second shell command ending on the same change reports nothing again. The label says whether the change
177
- // came while the command ran.
227
+ // second shell command ending on the same change adds nothing. The label says whether the change came while
228
+ // the command ran.
229
+ if (content === doc.snapshot) continue;
178
230
  const began = call.before.get(path);
179
- if (call.path === undefined && content !== doc.snapshot) {
180
- try {
181
- report(path, doc, doc.snapshot, content, began === undefined || content !== began);
182
- } catch (error) {
183
- doc.snapshot = content;
184
- doc.onError(error as Error);
185
- }
186
- } else doc.snapshot = content;
231
+ if (began === undefined || content !== began) doc.duringShell = true;
232
+ events.changed(doc.display);
187
233
  }
188
234
  }
189
235
 
190
236
  return {
191
237
  open,
238
+ take,
192
239
  /** Starts watching a document; a document already watched keeps the version the agent saw. */
193
240
  watch(path: string, display: string, content: string, onError: (error: Error) => void): void {
194
241
  const known = watched.get(path);
@@ -203,10 +250,13 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
203
250
  onError(error as Error);
204
251
  }
205
252
  });
206
- watched.set(path, { display, snapshot: content, stop, onError });
253
+ watched.set(path, { display, snapshot: content, duringShell: false, stop, onError });
207
254
  },
208
255
  has: (path: string): boolean => watched.has(path),
209
- /** The tool call `id` is about to write `path` (or run a shell command, when `path` is undefined). */
256
+ /**
257
+ * The tool call `id` is about to write `path` (or run a shell command, when `path` is undefined). Before a write
258
+ * or edit replaces the version the agent saw, the user's unreported change to that file goes out at once.
259
+ */
210
260
  willWrite(id: string, path: string | undefined): void {
211
261
  const before = new Map<string, string>();
212
262
  if (path === undefined) {
@@ -214,6 +264,9 @@ export function createEditSession(deps: EditDeps, onEdit: (message: string, disp
214
264
  const content = deps.readFile(watchedPath);
215
265
  if (content !== undefined) before.set(watchedPath, content);
216
266
  }
267
+ } else if (watched.has(path)) {
268
+ const message = take(path);
269
+ if (message) events.urgent(message);
217
270
  }
218
271
  active.set(id, { path, before });
219
272
  },
@@ -46,6 +46,13 @@ export function install(pi: ExtensionAPI, deps: Deps = defaultDeps()): BetterSho
46
46
  }
47
47
  });
48
48
  pi.on("turn_end", () => show.agentSettled());
49
+ // The user's saves reach the agent as one net diff per file when a run starts, instead of one message per save.
50
+ pi.on("before_agent_start", (_event, ctx) => {
51
+ show.setContext(ctx);
52
+ const message = show.agentStarting();
53
+ return message ? { message } : undefined;
54
+ });
55
+ pi.on("agent_start", () => show.agentStarted());
49
56
  pi.on("agent_end", () => show.agentSettled());
50
57
 
51
58
  pi.on("tool_result", async (event, ctx) => {