pi-better-show 0.5.0 → 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 +71 -262
- package/package.json +3 -2
- package/src/core/validate.ts +3 -2
- package/src/extension/controller.ts +72 -2
- package/src/extension/edit.ts +82 -29
- package/src/extension/index.ts +7 -0
package/README.md
CHANGED
|
@@ -1,307 +1,116 @@
|
|
|
1
1
|
# pi-better-show
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Let your pi agent show you a page instead of a wall of text, and answer it by clicking.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
The agent writes Markdown with fenced blocks (`` ```options ``, `` ```form ``, `` ```table ``, ...).
|
|
6
|
+
`show_doc` opens it in your browser, and every pick, form, or comment you send comes back to the agent as a message.
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
pi-better-show core: isomorphic, no DOM, no node APIs; depends on `yaml` only
|
|
9
|
-
pi-better-show/elements browser: framework-free custom elements, one per block kind (no yaml, no node APIs)
|
|
10
|
-
pi-better-show/react thin React wrappers over the elements (React is an optional peer)
|
|
11
|
-
pi-better-show/server node: Mermaid to SVG and to Unicode text (beautiful-mermaid)
|
|
12
|
-
pi-better-show/extension the pi extension: `show_doc`, a loopback page server, edit mode, event-bus contract v2
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
The package ships TypeScript source, with no build step. Source uses erasable syntax only, so it loads under node's type stripping and in bun and bundler pipelines.
|
|
16
|
-
|
|
17
|
-
## Blocks
|
|
18
|
-
|
|
19
|
-
A block is a fenced code block whose first word is the kind, or a GitHub alert. Text fields (`body`, `hint`, `note`, ...) take restricted inline Markdown: bold, italic, code, `http(s)` links, line breaks. No raw HTML anywhere.
|
|
20
|
-
|
|
21
|
-
| Kind | Written as | Answer kind |
|
|
22
|
-
|---|---|---|
|
|
23
|
-
| `alert` | `> [!NOTE\|TIP\|IMPORTANT\|WARNING\|CAUTION] title` quote | |
|
|
24
|
-
| `mermaid` | Mermaid source | |
|
|
25
|
-
| `diff` | unified diff | |
|
|
26
|
-
| `cards` | YAML list of `{title, tone, body}` | |
|
|
27
|
-
| `options` | YAML list of `{title, recommended, body, pros, cons}` | `pick` |
|
|
28
|
-
| `form` | YAML `{title, submit, questions: [{name, label, type, hint, required, other, choices}]}` | `form` |
|
|
29
|
-
| `review` | YAML `{title, submit, pick, columns, items: [{name, label, image, page, height, body}]}` | `review` |
|
|
30
|
-
| `mindmap` | indented Markdown list; the first item is the root | |
|
|
31
|
-
| `suggest` | YAML list of strings or `{label, text}` | `suggest` |
|
|
32
|
-
| `checklist` | YAML `{title, submit, items: [string \| {name, label, checked, note}]}` | `checklist` |
|
|
33
|
-
| `table` | YAML `{columns, rows, sort, filter}` | |
|
|
34
|
-
| `steps` | YAML `{items: [{title, status: done\|doing\|todo\|blocked, when, body}]}` | |
|
|
35
|
-
| `stats` | YAML list of `{label, value, delta, tone, note}` | |
|
|
36
|
-
| `tree` | indented lines (two spaces per level, first line the root): `name/` for a folder, then `{tags}` and ` # note` | |
|
|
37
|
-
|
|
38
|
-
**The `tree` block** shows a directory tree for structure reviews:
|
|
39
|
-
|
|
40
|
-
```tree
|
|
41
|
-
pi-better-show/
|
|
42
|
-
src/ # one package, four entries
|
|
43
|
-
core/ {focus} # parser and text, no DOM
|
|
44
|
-
parse.ts
|
|
45
|
-
validate.ts {new} # checks answers
|
|
46
|
-
elements/ # web components
|
|
47
|
-
tests/
|
|
48
|
-
README.md {changed}
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
A folder's name ends with `/`; tags are `new`, `changed`, `removed`, `focus`, `risk` (an unknown tag makes the block invalid); the note after ` # ` takes inline Markdown; a `… N more` line stands for entries a limit cut. A tree has at most 2,000 nodes and 32 levels (the root is level 1). The block carries a snapshot, so every host draws it; `toText` writes it in `tree` style (`├──`, `└──`, tags as `[new]`, notes after ` — `), in a fence on Discord.
|
|
52
|
-
|
|
53
|
-
**`pbs-tree`** prints the fence for a folder: `npx pbs-tree [dir]` or `bunx pbs-tree [dir]` (plain JavaScript on node built-ins; runs under node and bun). Output is sorted by name in byte order, so a snapshot is reproducible; symlinks are not followed. Flags follow Linux `tree` where they exist:
|
|
54
|
-
|
|
55
|
-
| Flag | Meaning |
|
|
56
|
-
|---|---|
|
|
57
|
-
| `-L n` | depth |
|
|
58
|
-
| `-d` | folders only |
|
|
59
|
-
| `-a` | include dot files (default skips them; `.git` is always skipped) |
|
|
60
|
-
| `-I pattern` | leave out names matching the glob (`*` `?` `[..]`); `\|` separates several; repeatable |
|
|
61
|
-
| `-P pattern` | list only files matching; a folder is kept when it holds a match (even below the `-L` cut); ignored with `-d` |
|
|
62
|
-
| `--gitignore` | honour `.gitignore` files, those of the folder and of the folders above it up to the repository's top |
|
|
63
|
-
| `--dirsfirst` | folders before files |
|
|
64
|
-
| `--filelimit n` | do not open a folder holding more than n entries; writes `… N more` in its place |
|
|
65
|
-
| `--prune` | drop folders that hold nothing (what `-L` hides still counts); ignored with `-d` |
|
|
66
|
-
| `--changed-since <rev>` | tag `new`, `changed`, `removed` from `git diff --name-status <rev>` against the working tree; removed files are listed though absent, untracked files are `new`, a rename is a removed and a new file |
|
|
67
|
-
|
|
68
|
-
A tree over the block's limits is refused (exit 1) with the node count; narrow it with `-L`, `-I`, `--gitignore`. Names that would read as a note or tags get a no-break space, and a newline in a name becomes `?`. Exit codes: 0, 1 for a failure (not a folder, git failed, too large), 2 for a bad flag.
|
|
69
|
-
|
|
70
|
-
A block whose body is not valid YAML, or does not fit its schema, becomes an `invalid` segment that keeps its source and the reason; nothing throws.
|
|
71
|
-
|
|
72
|
-
## Core API
|
|
8
|
+

|
|
73
9
|
|
|
74
|
-
|
|
75
|
-
import { parse, toText, inline, encodeAnswer, checkBlocks } from "pi-better-show";
|
|
10
|
+
When you press **Send** on the form above, the agent receives:
|
|
76
11
|
|
|
77
|
-
|
|
12
|
+
```text
|
|
13
|
+
User submitted a form in the HTML review pane:
|
|
14
|
+
- ttl: week
|
|
15
|
+
- extras: WAL mode, Nightly backup
|
|
16
|
+
- note: The API runs on two hosts next month.
|
|
78
17
|
```
|
|
79
18
|
|
|
80
|
-
|
|
19
|
+
## Fewer tokens
|
|
81
20
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
formatProblems(name: string, problems: BlockProblem[]): string
|
|
21
|
+
The agent writes data, not a web page: the package owns the layout, styles, controls, and the code that sends answers back.
|
|
22
|
+
For the four example pages in this README, writing the blocks took **1,253 output tokens**; asking the same model for one self-contained HTML page with the same content and working controls took **12,364**, about **10 times as many** (90% saved).
|
|
85
23
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
```
|
|
94
|
-
|
|
95
|
-
Tells the author what is wrong with the blocks of a file, where `parse` only keeps going. `error`: the block is invalid and the page shows its source (a YAML error is reported at the line that caused it; a flow collection broken by an unquoted ` #` points at the line that opened it). `warning`: the block draws, but part of what was written is lost: a plain value that a ` #` cut short (YAML reads the rest as a comment; the message names the key path and says to quote the value), a key the block does not read at that level (with the known keys, and a "did you mean" for a near miss), or a fence that never closes. Core has no Mermaid parser: pass `options.mermaid`, which returns what is wrong with a diagram source, to check diagrams too. Pure; it loads no more than `parse` does.
|
|
96
|
-
|
|
97
|
-
```ts
|
|
98
|
-
toText(segments: Segment[], profile: TextProfile): string
|
|
99
|
-
|
|
100
|
-
interface TextProfile {
|
|
101
|
-
flavor: "discord" | "line" | "plain"; // Discord Markdown, or plain text
|
|
102
|
-
width?: number; // columns a diagram may take; default 60
|
|
103
|
-
mermaid?: (source: string, width: number) => string | undefined;
|
|
104
|
-
keep?: readonly BlockKind[]; // kinds emitted as their `raw` text instead of converted
|
|
105
|
-
lang?: "en" | "zh-TW"; // language of the reply instructions; default "en", anything else is "en"
|
|
106
|
-
}
|
|
107
|
-
```
|
|
108
|
-
|
|
109
|
-
The interactive kinds end with a reply instruction (`options`, `form`, `review`, `suggest`, and `checklist`): "Reply with a number.", "Reply in text, one line per question, like `1: b`.", and so on. `lang: "zh-TW"` writes them in Traditional Chinese; pass the conversation's language when you know it. Block content is never translated.
|
|
110
|
-
|
|
111
|
-
Every `BlockSegment` and `InvalidSegment` carries `raw`: the block's exact original text, fences (or an alert's whole `>` quote) included, byte for byte. Kinds listed in `keep` are emitted as `raw` verbatim, valid or invalid, for a surface that draws them itself; other kinds convert as usual. `DISPLAY_KINDS` (`alert`, `cards`, `mermaid`, `mindmap`, `diff`, `table`, `steps`, `stats`, `tree`) is the usual `keep` list for such a surface; `INTERACTIVE_KINDS` (`options`, `suggest`, `form`, `checklist`, `review`) are the kinds a reader answers, the ones a surface that cannot draw them gets as reply instructions. Without `keep`, output is unchanged.
|
|
112
|
-
|
|
113
|
-
Renders a document for a surface that cannot draw blocks. A diagram goes through the `mermaid` hook; when there is no hook, or it returns `undefined` or a drawing wider than `width`, the output is the Mermaid source in a code block plus a pointer to the web view. No block-kind fence is left in the output, except Discord's native `diff`.
|
|
24
|
+
| Page | Blocks | HTML page (median) | HTML runs | Saved |
|
|
25
|
+
|---|---:|---:|---|---:|
|
|
26
|
+
| [Decision](https://github.com/wayne930242/pi-better-show/blob/main/examples/readme-decide.md): alert, options, form | 347 | 2,770 | 1,651 – 2,917 | 87% |
|
|
27
|
+
| [Status](https://github.com/wayne930242/pi-better-show/blob/main/examples/readme-status.md): stats, steps, table | 412 | 3,726 | 2,145 – 3,895 | 89% |
|
|
28
|
+
| [Structure](https://github.com/wayne930242/pi-better-show/blob/main/examples/readme-structure.md): tree, mermaid, diff | 338 | 3,719 | 3,514 – 4,064 | 91% |
|
|
29
|
+
| [Review](https://github.com/wayne930242/pi-better-show/blob/main/examples/readme-review.md): review, suggest | 156 | 2,149 | 2,008 – 2,478 | 93% |
|
|
30
|
+
| Total | 1,253 | 12,364 | | 90% |
|
|
114
31
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
displayWidth(text: string): number // terminal columns: CJK counts 2
|
|
119
|
-
reviewItemName(item): string // "B (dark header)"
|
|
32
|
+
Counts are Claude output tokens from `claude -p --model claude-sonnet-5-5` (3 to 5 HTML runs per page; the block count is the file echoed back verbatim), measured on 2026-11-10 with `scripts/token-bench.sh`.
|
|
33
|
+
None of the HTML pages had the feedback panel for commenting on a selected passage, which `show_doc` adds to every page.
|
|
34
|
+
The saving repeats on every revision, since the agent changes a few YAML lines instead of rewriting markup and script.
|
|
120
35
|
|
|
121
|
-
|
|
122
|
-
kind: "form" | "review" | "feedback" | "pick" | "suggest" | "checklist";
|
|
123
|
-
title?: string;
|
|
124
|
-
fields: [name: string, value: string][];
|
|
125
|
-
ref?: { doc?: string; block: number };
|
|
126
|
-
}
|
|
127
|
-
encodeAnswer(answer: Answer): string
|
|
128
|
-
```
|
|
129
|
-
|
|
130
|
-
`encodeAnswer` produces the text the agent reads. For `form`, `review`, and `feedback` it is byte-compatible with pi-herdr-doc-review's `formMessage`, `reviewMessage`, and `pageFeedbackMessage` given the same fields (the legacy `pi-kind` field is ignored). `ref` addresses the block for hosts and does not appear in the text. A `pi-note` field (see below) is appended as `Other comments: …`.
|
|
36
|
+
## Install
|
|
131
37
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
| `form` | one `[name, value]` per question | `User submitted a form ...` then `- name: value` lines |
|
|
135
|
-
| `review` | `title`, `picked`, `item`/`comment` pairs, `silent` | `User reviewed "title":` ... |
|
|
136
|
-
| `feedback` | `page`, `quote`/`comment` pairs, `overall` | `User feedback on the page "page":` ... |
|
|
137
|
-
| `pick` | `[["picked", option]]` | `User picked "option" for "title".` |
|
|
138
|
-
| `suggest` | `[["text", text]]` | the text itself |
|
|
139
|
-
| `checklist` | one `[name, "checked" \| "unchecked"]` per item | `User updated the checklist "title":` then `☑`/`☐` lines |
|
|
140
|
-
|
|
141
|
-
```ts
|
|
142
|
-
validateAnswer(block: BlockSegment, answer: Answer): { ok: true } | { ok: false; reason: string }
|
|
38
|
+
```bash
|
|
39
|
+
pi install npm:pi-better-show
|
|
143
40
|
```
|
|
144
41
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
**Other comments.** Every submittable element (`pbs-form`, `pbs-review`, `pbs-checklist`, `pbs-options`) shows a fixed "Other comments" box above its submit button (above the options in `pbs-options`; the box is read when the option is picked). Its trimmed text travels in the same answer as the reserved field `pi-note` (`NOTE_FIELD`), once, and a blank box sends nothing. `validateAnswer` accepts it for every interactive kind; a form question or checklist item may not be named `pi-note`. A host that shows the elements needs to do nothing new: the field is in `answer.fields`, so `validateAnswer` and `encodeAnswer` already pass it through. A host that rebuilds the answer from selected fields must forward `pi-note`; set `answered` to the submitted fields so the locked element shows it. The words are `otherComments` in `configure({strings})`.
|
|
148
|
-
|
|
149
|
-
**Several values.** A block that gathers several values (a `form` with a `multi` question, a `checklist`, a `review`) sends nothing on a tick, a pick, or typing: choices stay changeable until the reader presses Send, and a required `multi` question with none chosen is refused at that question. Only `options` and `suggest` send on the click.
|
|
150
|
-
|
|
151
|
-
## Server API
|
|
152
|
-
|
|
153
|
-
```ts
|
|
154
|
-
import { mermaidSvg, mermaidText } from "pi-better-show/server";
|
|
42
|
+
Then `/reload` in a running session.
|
|
43
|
+
If you use `pi-herdr-doc-review`, uninstall it first (`pi uninstall npm:pi-herdr-doc-review`): both register `show_doc`.
|
|
155
44
|
|
|
156
|
-
|
|
157
|
-
mermaidText(source: string, width = 60): string | undefined
|
|
158
|
-
```
|
|
45
|
+
## What `show_doc` does
|
|
159
46
|
|
|
160
|
-
`
|
|
47
|
+
`show_doc({paths, reason, view})` returns at once; the agent does not wait for you.
|
|
161
48
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
49
|
+
- `view: "page"` opens the file in your default browser.
|
|
50
|
+
Markdown renders with its blocks; `.html`, `.tsx`, and `.jsx` run in a sandboxed frame; images show as they are.
|
|
51
|
+
- `view: "edit"` (the default) opens the file in your editor.
|
|
52
|
+
Your saves reach the agent as one net diff per file, without starting a turn.
|
|
53
|
+
- Select any passage on a page to comment on it.
|
|
54
|
+
The feedback panel sends your comments and an overall note in one message.
|
|
55
|
+
- Open pages reload when the agent edits the file.
|
|
165
56
|
|
|
166
|
-
|
|
57
|
+

|
|
167
58
|
|
|
168
|
-
|
|
169
|
-
import "pi-better-show/elements"; // defines every pbs-* tag (a no-op without a DOM)
|
|
170
|
-
import { configure } from "pi-better-show/elements";
|
|
59
|
+
## Blocks
|
|
171
60
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
el.answered = event.detail.fields; // once delivered: locks the element and shows what was sent
|
|
175
|
-
```
|
|
61
|
+
A block is a fenced code block whose first word is its kind, or a GitHub alert (`> [!NOTE]`).
|
|
62
|
+
Most take YAML; text fields take bold, italic, code, and `http(s)` links, never raw HTML.
|
|
176
63
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
| Tag | Block | `data` | Answer | Parts |
|
|
180
|
-
|---|---|---|---|---|
|
|
181
|
-
| `pbs-callout` | `alert` | `AlertData` | | `callout` `header` `icon` `title` `body` |
|
|
182
|
-
| `pbs-cards` | `cards` | `CardsData` | | `grid` `card` `title` `icon` `body` |
|
|
183
|
-
| `pbs-options` | `options` | `OptionsData` | `pick` | `grid` `option` `title` `badge` `body` `pros` `cons` `actions` `pick` `status` |
|
|
184
|
-
| `pbs-form` | `form` | `FormData` | `form` | `form` `title` `question` `label` `hint` `choices` `choice` `badge` `other` `textarea` `error` `actions` `submit` `status` `sent` |
|
|
185
|
-
| `pbs-review` | `review` | `ReviewData` | `review` | `review` `title` `items` `item` `item-title` `pick` `media` `image` `enlarge` `frame` `unavailable` `body` `comment` `actions` `submit` `status` `lightbox` `close` `sent` |
|
|
186
|
-
| `pbs-mindmap` | `mindmap` | `MindmapData` | | `mindmap` `tree` `item` `node` `toggle` `label` `group` |
|
|
187
|
-
| `pbs-suggest` | `suggest` | `SuggestData` | `suggest` | `suggest` `chips` `chip` `status` |
|
|
188
|
-
| `pbs-checklist` | `checklist` | `ChecklistData` | `checklist` | `checklist` `title` `items` `item` `progress` `actions` `submit` `status` `sent` |
|
|
189
|
-
| `pbs-table` | `table` | `TableData` | | `table` `bar` `filter` `count` `scroll` `header` `head` `sort` `body` `row` `cell` `empty` |
|
|
190
|
-
| `pbs-steps` | `steps` | `StepsData` | | `steps` `step` `rail` `marker` `content` `title` `badge` `when` `body` |
|
|
191
|
-
| `pbs-stats` | `stats` | `StatsData` | | `grid` `stat` `label` `value` `delta` `note` |
|
|
192
|
-
| `pbs-diff` | `diff` | `DiffData` | | `diff` `scroll` `line` |
|
|
193
|
-
| `pbs-diagram` | `mermaid` | `MermaidData` | | `diagram` `image` `source` `note` |
|
|
194
|
-
| `pbs-tree` | `tree` | `TreeData` | | `treeview` `bar` `expand-all` `collapse-all` `tree` `item` `node` `toggle` `name` `count` `tags` `tag` `note` `more` `group` |
|
|
195
|
-
|
|
196
|
-
`TAGS` maps a block kind to its tag. There is no whole-document element: the extension renders Markdown on its page server, and other hosts use their own renderer.
|
|
197
|
-
|
|
198
|
-
**Attributes and properties** (every element)
|
|
199
|
-
|
|
200
|
-
| Name | Kind | Meaning |
|
|
64
|
+
| Kind | Shows | You answer by |
|
|
201
65
|
|---|---|---|
|
|
202
|
-
| `
|
|
203
|
-
| `
|
|
204
|
-
| `
|
|
205
|
-
| `
|
|
206
|
-
| `
|
|
207
|
-
| `
|
|
208
|
-
| `
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
```ts
|
|
215
|
-
configure({
|
|
216
|
-
strings: { "zh-Hant": { send: "送出" } }, // per locale, per word (see Strings)
|
|
217
|
-
diagramUrl: (source, scheme) => `/diagram.svg?...`, // an image URL for pbs-diagram; without it the source is shown
|
|
218
|
-
imageUrl: (ref) => `/files/${ref}`, // a review item's `image`; default admits http(s) and raster data URLs only
|
|
219
|
-
pageUrl: (ref) => `/pages/${ref}`, // a review item's `page`, shown in a sandboxed frame; without it, its name
|
|
220
|
-
});
|
|
221
|
-
```
|
|
222
|
-
|
|
223
|
-
Serve diagram images from `pi-better-show/server` (`mermaidSvg(source, { scheme, transparent: true })`); no diagram markup enters the page. `resetConfiguration()` restores the defaults.
|
|
66
|
+
| `alert` | a callout (`NOTE`, `TIP`, `IMPORTANT`, `WARNING`, `CAUTION`) | |
|
|
67
|
+
| `options` | choices side by side, with pros and cons | picking one |
|
|
68
|
+
| `form` | single, multi, and text questions | Send |
|
|
69
|
+
| `review` | designs, screenshots, or prototypes to compare | commenting and picking |
|
|
70
|
+
| `checklist` | items to tick | Send |
|
|
71
|
+
| `suggest` | quick-reply chips | clicking one |
|
|
72
|
+
| `cards`, `stats` | tiles with a tone | |
|
|
73
|
+
| `steps` | a timeline with status | |
|
|
74
|
+
| `table` | sortable, filterable rows | |
|
|
75
|
+
| `tree` | a directory tree with tags and notes (`npx pbs-tree` prints one) | |
|
|
76
|
+
| `mindmap` | a collapsible outline | |
|
|
77
|
+
| `mermaid`, `diff` | a diagram, a coloured diff | |
|
|
224
78
|
|
|
225
|
-
|
|
79
|
+
A status page with `stats`, `steps`, and `table`:
|
|
226
80
|
|
|
227
|
-
|
|
228
|
-
|---|---|
|
|
229
|
-
| `--pbs-bg` `--pbs-surface` | Panel background; tinted surface (table header, code) |
|
|
230
|
-
| `--pbs-fg` `--pbs-muted` | Text; secondary text |
|
|
231
|
-
| `--pbs-line` `--pbs-control` | Panel and divider lines; the edge of an input (3:1 against its surface) |
|
|
232
|
-
| `--pbs-accent` `--pbs-on-accent` | Buttons, links, selection; text on them |
|
|
233
|
-
| `--pbs-note` `--pbs-ok` `--pbs-warn` `--pbs-risk` | Tones |
|
|
234
|
-
| `--pbs-radius` `--pbs-gap` | Corner radius; space between blocks and inside them |
|
|
235
|
-
| `--pbs-font` `--pbs-mono` `--pbs-font-size` | Type |
|
|
236
|
-
| `--pbs-font-display` | Titles and headings (defaults to `--pbs-font`) |
|
|
237
|
-
|
|
238
|
-
Structure carries `part` names for `::part()` restyling. A panel has the same border on all four sides, or none; a tone shows as a tint, a badge, an icon, and the heading colour, never a coloured or thicker one-sided border. `examples/demo.css` maps the Roundtable and Straw boss tokens as examples.
|
|
81
|
+

|
|
239
82
|
|
|
240
|
-
|
|
83
|
+
A structure review with `tree`, `mermaid`, and `diff`:
|
|
241
84
|
|
|
242
|
-
|
|
85
|
+

|
|
243
86
|
|
|
244
|
-
|
|
245
|
-
import { PbsBlock, PbsForm } from "pi-better-show/react";
|
|
246
|
-
|
|
247
|
-
<PbsBlock segment={segment} doc="chat-7" onAnswer={(answer) => send(encodeAnswer(answer))} />
|
|
248
|
-
<PbsForm data={formData} answered={fields} density="compact" onAnswer={...} />
|
|
249
|
-
```
|
|
87
|
+
A design review with `review` and `suggest`:
|
|
250
88
|
|
|
251
|
-
|
|
89
|
+

|
|
252
90
|
|
|
253
|
-
|
|
91
|
+
A block that does not parse shows its source and the reason on the page, and the agent's `write` and `edit` results list the problem with its line number.
|
|
254
92
|
|
|
255
|
-
|
|
93
|
+
## Outside pi
|
|
256
94
|
|
|
257
|
-
|
|
258
|
-
pi uninstall npm:pi-herdr-doc-review # same tool name: do not load both
|
|
259
|
-
pi install npm:pi-better-show
|
|
260
|
-
```
|
|
95
|
+
The block vocabulary is a library too, so other hosts (a GUI, a chat bridge) draw the same blocks and send the same answers:
|
|
261
96
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
**Tool.** `show_doc({paths, reason, view})` returns at once, without waiting for you.
|
|
265
|
-
|
|
266
|
-
| View | Opens |
|
|
97
|
+
| Entry | For |
|
|
267
98
|
|---|---|
|
|
268
|
-
| `
|
|
269
|
-
| `
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
**Markdown pages.** Prose is Markdown with raw HTML left as text; every block above becomes its element. Select a passage to comment on it; the panel collects comments and an overall note and sends them in one message. A form, pick, chip, checklist, or review reaches the agent as a message: steered into a running turn, or starting a turn when the agent is idle (`encodeAnswer`). Diagrams are drawn on the server, in the page's colour scheme. Images and links resolve against the page's directory: nothing loads from above it, from a dot file or directory, or from another site. Every response carries a CSP, and the server answers only the loopback host.
|
|
274
|
-
|
|
275
|
-
**Agent pages.** `.html` and `.tsx`/`.jsx` run in `<iframe sandbox="allow-scripts allow-forms">` without `allow-same-origin`: no storage, no cookies, and no way to answer on its own: the server refuses a POST whose Origin is not its own (a frame's is `null`) or that is not JSON, and an event stream not opened from its own page. A `<form action="cgi-bin:pi-answer">` or `piBetterShow.send(fields)` answers through the page around the frame. The page around the frame carries the same feedback panel as a Markdown page: the frame reports the text the user selects to its parent by `postMessage({source: "pbs-frame", type: "selection", text})` (cut to 2000 characters, accepted only from the page's own frame with origin `null`), the user comments on passages and adds an overall note, and one Send delivers a `feedback` answer named by the HTML `<title>`, else the file name. A TSX page works the same way. A TSX page's default export is a React component, built by esbuild on each load with the React this package ships; `import {PbsBlock, PbsForm, ..., parse, encodeAnswer, send} from "pi-kit"` gives it the wrappers.
|
|
276
|
-
|
|
277
|
-
**Edit mode.** Your editor opens the file and the extension watches it. When you save, the change since the version the agent last saw goes to it as a zero-context diff (`@@` headers carry line numbers): steered into a running turn, or attached to your next message when idle, so a save never starts a turn. A save in the same instant as the agent's own write is not reported.
|
|
278
|
-
|
|
279
|
-
**Live reload and closing.** When the agent edits a shown document (`write`, `edit`, or `bash`), open tabs reload. When you close the last tab, the server stops after 30 seconds, and the next `show_doc` starts a new one and opens its pages again; showing a page whose tab you closed opens it again.
|
|
280
|
-
|
|
281
|
-
**Mini SDD.** When the agent writes a `docs/specs/<slug>/spec.md` whose header says `Status: proposed`, the folder's `decision.md`, `spec.md`, `design.md`, and `verification.md` open as pages on their own (only when pi has a UI); a phase file written later joins. `PI_BETTER_SHOW_AUTO_OPEN=off` stops it.
|
|
99
|
+
| `pi-better-show` | `parse`, `toText` (a plain-text or Discord fallback), `encodeAnswer`, `validateAnswer`, `checkBlocks` |
|
|
100
|
+
| `pi-better-show/elements` | framework-free custom elements, one per block kind |
|
|
101
|
+
| `pi-better-show/react` | React wrappers over the elements |
|
|
102
|
+
| `pi-better-show/server` | Mermaid to SVG and to Unicode text |
|
|
282
103
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
| Event | Payload |
|
|
286
|
-
|---|---|
|
|
287
|
-
| `better-show:documents` | `{version, documents}` in full on every change (a document shown, changed by the agent or saved by you, a page closed) and `[]` when the session ends. Each entry is `{id, kind: "blocks" \| "html" \| "text", display, reason, revision, onScreen, capability?, assets?}`. There is no path: `display` is relative to the working directory, else a `~` path, else the base name. While the page server runs, `capability` is, for a document on screen or open in the editor, the URL that serves the document (Markdown text for `blocks` and `text`; the page as a frame loads it, to be shown in an iframe with `sandbox="allow-scripts allow-forms"`, for `html`) and `assets` the directory URL its relative references resolve against. The list keeps the 32 most recent documents. |
|
|
288
|
-
| `better-show:documents-request` | `{version}` asks for the list again; it is sent once on `better-show:documents`. Another `version`, or a request after the session ended, is ignored. |
|
|
289
|
-
| `better-show:answer` | `{version, id, answerId, answer}` with `answer` an `Answer`. It reaches the agent as the same message a page answer produces. |
|
|
290
|
-
| `better-show:answer-result` | `{version, id, answerId, accepted, reason?}`; `reason` is `closed`, `invalid` (wrong version or shape, or a `text` document), `empty`, or a delivery error. A repeated `answerId` gets its first result back and delivers nothing again. A payload without a string `id` and `answerId` gets no reply. |
|
|
291
|
-
|
|
292
|
-
A viewer that shows an `html` document in a frame receives its answers as `postMessage({source: "pbs-frame", type: "answer", answerId, answer})` from the frame (origin `"null"`) and replies `{source: "pbs-host", type: "answer-result", answerId, accepted, reason?}`. It also receives `{source: "pbs-frame", type: "selection", text, top?, left?}` whenever the user's selection in the frame changes (`text` is empty when it was cleared) and may offer its own feedback panel with it.
|
|
293
|
-
|
|
294
|
-
**Moving from pi-herdr-doc-review.** Uninstall it and install this package; `show_doc` keeps its name and parameters. Gone: Herdr panes, nvim and vim, Chawan and terminal-browser, and the `<pi-*>` page-kit tags (write `form`, `review`, ... blocks instead, or use the `pbs-*` elements). The event names changed from `doc-review:*` (version 1) to `better-show:*` (version 2).
|
|
295
|
-
|
|
296
|
-
Try it without pi: `bun run show` starts the page server on `examples/` with a fake pi that prints each message the agent would receive.
|
|
104
|
+
The [reference](https://github.com/wayne930242/pi-better-show/blob/main/docs/reference.md) covers every block's schema, these APIs, theming tokens, and the extension's event bus.
|
|
297
105
|
|
|
298
106
|
## Development
|
|
299
107
|
|
|
300
|
-
```
|
|
108
|
+
```bash
|
|
301
109
|
bun install
|
|
302
110
|
bun test
|
|
303
111
|
bun run check # tsc, tsc for core without node types, biome
|
|
304
112
|
bun run demo # examples/elements.html on http://127.0.0.1:4177/
|
|
113
|
+
bun run show # the show_doc page server on examples/, with a fake pi that prints each message
|
|
305
114
|
```
|
|
306
115
|
|
|
307
116
|
## License
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-show",
|
|
3
|
-
"version": "0.
|
|
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",
|
|
@@ -85,6 +85,7 @@
|
|
|
85
85
|
"pi": {
|
|
86
86
|
"extensions": [
|
|
87
87
|
"./src/extension/index.ts"
|
|
88
|
-
]
|
|
88
|
+
],
|
|
89
|
+
"image": "https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/decide.png"
|
|
89
90
|
}
|
|
90
91
|
}
|
package/src/core/validate.ts
CHANGED
|
@@ -129,8 +129,9 @@ function reservedName(block: BlockSegment): string | undefined {
|
|
|
129
129
|
|
|
130
130
|
/**
|
|
131
131
|
* Whether an untrusted `answer` fits `block`: its kind is the block's, every field names a question, choice, or item
|
|
132
|
-
* of the block, several values appear only for a `multi` form question, required questions are answered,
|
|
133
|
-
* are at most 64 fields of 1,024
|
|
132
|
+
* of the block, several values appear only for a `multi` form question, required questions are answered, one optional
|
|
133
|
+
* `pi-note` field (the "Other comments" box) is accepted on every kind, and there are at most 64 fields of 1,024
|
|
134
|
+
* characters each.
|
|
134
135
|
*/
|
|
135
136
|
export function validateAnswer(block: BlockSegment, answer: Answer): Validation {
|
|
136
137
|
// The answer comes from outside: check its shape before reading it.
|
|
@@ -27,7 +27,15 @@ import {
|
|
|
27
27
|
type PublishedDocument,
|
|
28
28
|
parseAnswer,
|
|
29
29
|
} from "./contract.ts";
|
|
30
|
-
import {
|
|
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
|
-
|
|
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;
|
package/src/extension/edit.ts
CHANGED
|
@@ -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
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
const
|
|
86
|
-
|
|
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
|
|
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
|
-
/**
|
|
148
|
-
function report(
|
|
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
|
-
|
|
152
|
-
|
|
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
|
-
|
|
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
|
-
|
|
209
|
+
events.changed(doc.display);
|
|
164
210
|
}
|
|
165
211
|
|
|
166
|
-
/** A call ended:
|
|
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
|
|
177
|
-
//
|
|
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 (
|
|
180
|
-
|
|
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
|
-
/**
|
|
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
|
},
|
package/src/extension/index.ts
CHANGED
|
@@ -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) => {
|