pi-better-show 0.4.0 → 0.5.2

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
@@ -1,288 +1,116 @@
1
1
  # pi-better-show
2
2
 
3
- Interactive blocks for agent-written Markdown. An agent writes fenced blocks (`` ```form ``, `` ```table ``, ...); this package owns what they mean, so every host (a local pi session, a GUI, a chat bridge) shares one block vocabulary, one text fallback for surfaces that cannot draw blocks, and one encoding for the answers users send back.
3
+ Let your pi agent show you a page instead of a wall of text, and answer it by clicking.
4
4
 
5
- Status: 0.1.0, core, server, elements, React wrappers, and the `show_doc` pi extension. Design: `docs/specs/2026-11-07-better-show/spec.md`.
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
8
+ ![A decision page: an alert, two options, and a form](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/decide.png)
18
9
 
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.
10
+ When you press **Send** on the form above, the agent receives:
20
11
 
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}
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.
49
17
  ```
50
18
 
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.
19
+ ## Fewer tokens
52
20
 
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 |
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).
67
23
 
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.
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% |
69
31
 
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.
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.
71
35
 
72
- ## Core API
73
-
74
- ```ts
75
- import { parse, toText, inline, encodeAnswer } from "pi-better-show";
76
-
77
- parse(markdown: string): Segment[]
78
- ```
79
-
80
- Splits a document into `{type: "markdown", text}`, `{type: "block", kind, data, index}`, and `{type: "invalid", kind, source, error}` segments, in order. `data` is typed per kind (`BlockDataMap`). `index` counts the document's blocks of every kind from 0; invalid blocks take no number. `index` is the block's address for answers.
81
-
82
- ```ts
83
- toText(segments: Segment[], profile: TextProfile): string
84
-
85
- interface TextProfile {
86
- flavor: "discord" | "line" | "plain"; // Discord Markdown, or plain text
87
- width?: number; // columns a diagram may take; default 60
88
- mermaid?: (source: string, width: number) => string | undefined;
89
- keep?: readonly BlockKind[]; // kinds emitted as their `raw` text instead of converted
90
- lang?: "en" | "zh-TW"; // language of the reply instructions; default "en", anything else is "en"
91
- }
92
- ```
36
+ ## Install
93
37
 
94
- 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.
95
-
96
- 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.
97
-
98
- 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`.
99
-
100
- ```ts
101
- inline(text: string): InlineToken[] // restricted inline Markdown, tokenized, never HTML
102
- inlinePlain(text: string): string // the same text without markers
103
- displayWidth(text: string): number // terminal columns: CJK counts 2
104
- reviewItemName(item): string // "B (dark header)"
105
-
106
- interface Answer {
107
- kind: "form" | "review" | "feedback" | "pick" | "suggest" | "checklist";
108
- title?: string;
109
- fields: [name: string, value: string][];
110
- ref?: { doc?: string; block: number };
111
- }
112
- encodeAnswer(answer: Answer): string
113
- ```
114
-
115
- `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.
116
-
117
- | Kind | `fields` | Text |
118
- |---|---|---|
119
- | `form` | one `[name, value]` per question | `User submitted a form ...` then `- name: value` lines |
120
- | `review` | `title`, `picked`, `item`/`comment` pairs, `silent` | `User reviewed "title":` ... |
121
- | `feedback` | `page`, `quote`/`comment` pairs, `overall` | `User feedback on the page "page":` ... |
122
- | `pick` | `[["picked", option]]` | `User picked "option" for "title".` |
123
- | `suggest` | `[["text", text]]` | the text itself |
124
- | `checklist` | one `[name, "checked" \| "unchecked"]` per item | `User updated the checklist "title":` then `☑`/`☐` lines |
125
-
126
- ```ts
127
- validateAnswer(block: BlockSegment, answer: Answer): { ok: true } | { ok: false; reason: string }
38
+ ```bash
39
+ pi install npm:pi-better-show
128
40
  ```
129
41
 
130
- `validateAnswer` is for a host that receives an `Answer` from an untrusted client. It accepts the answer when its `kind` fits the block (`options` takes `pick`, the others their own kind), every field names a question, choice, or item of that block, and there are at most 64 fields of at most 1,024 characters each. Several values for one name are accepted only for a `multi` form question (as repeated fields, or the joined value the form element sends); a `single` or `text` question, a pick, and a suggestion take one. A required question must be answered (an empty value or `(no answer)` is not an answer). On a `form` question without an `other` box, a value must be one of its choices. A `checklist` field is an item name once with `checked` or `unchecked`; a `review` may carry `picked` only when the block has `pick`. On refusal `reason` says why, for the host's error reply. Blocks that take no answer (display kinds) are refused.
131
-
132
- **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.
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`.
133
44
 
134
- ## Server API
45
+ ## What `show_doc` does
135
46
 
136
- ```ts
137
- import { mermaidSvg, mermaidText } from "pi-better-show/server";
47
+ `show_doc({paths, reason, view})` returns at once; the agent does not wait for you.
138
48
 
139
- mermaidSvg(source: string, options?: { scheme?: "light" | "dark" | DiagramColors; font?: string; transparent?: boolean }): string
140
- mermaidText(source: string, width = 60): string | undefined
141
- ```
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
+ Each save reaches the agent as a diff, 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.
142
56
 
143
- `mermaidSvg` draws a self-contained SVG in the colours of `scheme` (use real colours; an image URL cannot read the host page's CSS). It has no `@import` and no `<script>`, and throws on a source it cannot draw. `mermaidText` draws Unicode box drawing, and returns `undefined` when the source is invalid, a line is wider than `width`, or a wide (CJK, emoji) character would misalign the boxes. It is the `mermaid` hook for `toText`:
57
+ ![The feedback panel with a comment on a selected passage](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/feedback.png)
144
58
 
145
- ```ts
146
- toText(parse(reply), { flavor: "discord", mermaid: mermaidText });
147
- ```
148
-
149
- ## Elements
150
-
151
- ```ts
152
- import "pi-better-show/elements"; // defines every pbs-* tag (a no-op without a DOM)
153
- import { configure } from "pi-better-show/elements";
59
+ ## Blocks
154
60
 
155
- el.data = segment.data; // or <pbs-form data-json='{...}'>
156
- el.addEventListener("pbs-answer", (event) => send(encodeAnswer(event.detail)));
157
- el.answered = event.detail.fields; // once delivered: locks the element and shows what was sent
158
- ```
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.
159
63
 
160
- A host gives an element the block's parsed `data` and listens for `pbs-answer` (bubbles, composed, cancelable) whose `detail` is a core `Answer`. An element never reads or writes HTML: text reaches the page as text nodes, and links are `http(s)` only with `rel="noopener noreferrer"` and `target="_blank"`. Each element is a shadow root with constructed stylesheets (`adoptedStyleSheets`), so it runs under `default-src 'self'`: no `<style>` element, no `style` attribute. `examples/` is such a page; run it with `bun run demo` (loopback, port 4177).
161
-
162
- | Tag | Block | `data` | Answer | Parts |
163
- |---|---|---|---|---|
164
- | `pbs-callout` | `alert` | `AlertData` | | `callout` `header` `icon` `title` `body` |
165
- | `pbs-cards` | `cards` | `CardsData` | | `grid` `card` `title` `icon` `body` |
166
- | `pbs-options` | `options` | `OptionsData` | `pick` | `grid` `option` `title` `badge` `body` `pros` `cons` `actions` `pick` `status` |
167
- | `pbs-form` | `form` | `FormData` | `form` | `form` `title` `question` `label` `hint` `choices` `choice` `badge` `other` `textarea` `error` `actions` `submit` `status` `sent` |
168
- | `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` |
169
- | `pbs-mindmap` | `mindmap` | `MindmapData` | | `mindmap` `tree` `item` `node` `toggle` `label` `group` |
170
- | `pbs-suggest` | `suggest` | `SuggestData` | `suggest` | `suggest` `chips` `chip` `status` |
171
- | `pbs-checklist` | `checklist` | `ChecklistData` | `checklist` | `checklist` `title` `items` `item` `progress` `actions` `submit` `status` `sent` |
172
- | `pbs-table` | `table` | `TableData` | | `table` `bar` `filter` `count` `scroll` `header` `head` `sort` `body` `row` `cell` `empty` |
173
- | `pbs-steps` | `steps` | `StepsData` | | `steps` `step` `rail` `marker` `content` `title` `badge` `when` `body` |
174
- | `pbs-stats` | `stats` | `StatsData` | | `grid` `stat` `label` `value` `delta` `note` |
175
- | `pbs-diff` | `diff` | `DiffData` | | `diff` `scroll` `line` |
176
- | `pbs-diagram` | `mermaid` | `MermaidData` | | `diagram` `image` `source` `note` |
177
- | `pbs-tree` | `tree` | `TreeData` | | `treeview` `bar` `expand-all` `collapse-all` `tree` `item` `node` `toggle` `name` `count` `tags` `tag` `note` `more` `group` |
178
-
179
- `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.
180
-
181
- **Attributes and properties** (every element)
182
-
183
- | Name | Kind | Meaning |
64
+ | Kind | Shows | You answer by |
184
65
  |---|---|---|
185
- | `data` / `data-json` | property / attribute | The block's data; bad JSON or a shape the element cannot draw shows an error panel and fires `pbs-error`. |
186
- | `answered` / `data-answered` | property / attribute | The submitted `[name, value][]`: locks the element and shows them. `undefined` reopens it. |
187
- | `ref`, or `doc` and `block` attributes | property / attributes | The block's address, copied into every answer's `ref`. |
188
- | `density` | attribute and property | `comfortable` (default) or `compact`. |
189
- | `scheme` | attribute and property | `light` or `dark`, to force a scheme; else the element follows the host's `color-scheme`. |
190
- | `lang` | attribute (or an ancestor's, or the document's) | `zh*` shows Traditional Chinese, anything else English. |
191
- | `refresh()` | method | Draws again. Call it after the host changes `color-scheme` or the document `lang`, which an element cannot observe. |
192
-
193
- **Answers.** A pick (`pbs-options`) or a chip (`pbs-suggest`) sends at once and locks itself once a listener takes the event; a listener that calls `preventDefault()` refuses it and the element stays open. A form, review, or checklist stays editable after sending (the status line says "Sent."), so the user can send a changed answer; the host locks it by setting `answered`. A form's required questions are checked before sending. Ctrl/Cmd+Enter sends from a text box.
194
-
195
- **Looking after the host: `configure`**
196
-
197
- ```ts
198
- configure({
199
- strings: { "zh-Hant": { send: "送出" } }, // per locale, per word (see Strings)
200
- diagramUrl: (source, scheme) => `/diagram.svg?...`, // an image URL for pbs-diagram; without it the source is shown
201
- imageUrl: (ref) => `/files/${ref}`, // a review item's `image`; default admits http(s) and raster data URLs only
202
- pageUrl: (ref) => `/pages/${ref}`, // a review item's `page`, shown in a sandboxed frame; without it, its name
203
- });
204
- ```
205
-
206
- Serve diagram images from `pi-better-show/server` (`mermaidSvg(source, { scheme, transparent: true })`); no diagram markup enters the page. `resetConfiguration()` restores the defaults.
207
-
208
- **Tokens.** Set a `--pbs-*` property on an element or any ancestor; each has a `light-dark()` default that follows the host's `color-scheme`.
209
-
210
- | Token | Meaning |
211
- |---|---|
212
- | `--pbs-bg` `--pbs-surface` | Panel background; tinted surface (table header, code) |
213
- | `--pbs-fg` `--pbs-muted` | Text; secondary text |
214
- | `--pbs-line` `--pbs-control` | Panel and divider lines; the edge of an input (3:1 against its surface) |
215
- | `--pbs-accent` `--pbs-on-accent` | Buttons, links, selection; text on them |
216
- | `--pbs-note` `--pbs-ok` `--pbs-warn` `--pbs-risk` | Tones |
217
- | `--pbs-radius` `--pbs-gap` | Corner radius; space between blocks and inside them |
218
- | `--pbs-font` `--pbs-mono` `--pbs-font-size` | Type |
219
- | `--pbs-font-display` | Titles and headings (defaults to `--pbs-font`) |
220
-
221
- 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.
222
-
223
- **Keyboard.** Every control is a native control, labelled. `pbs-mindmap` follows the ARIA tree pattern (arrows move, Right and Left open and close, Enter and Space toggle, Home and End jump); `pbs-tree` follows it too, and opens folders to depth 2 (deeper folders that hold a tagged node open their path) with "expand all" and "collapse all" buttons; `pbs-table` sorts from header buttons (`aria-sort`) and filters from a labelled search box.
224
-
225
- ## React
226
-
227
- ```tsx
228
- import { PbsBlock, PbsForm } from "pi-better-show/react";
229
-
230
- <PbsBlock segment={segment} doc="chat-7" onAnswer={(answer) => send(encodeAnswer(answer))} />
231
- <PbsForm data={formData} answered={fields} density="compact" onAnswer={...} />
232
- ```
233
-
234
- One component per element (`PbsCallout` ... `PbsTree`) plus `PbsBlock`, which draws a `parse` segment with the element for its kind and addresses it by its `index`. Props: `data`, `answered`, `onAnswer(answer, event)` (return `false` to refuse), `blockRef`, `density`, `scheme`, `lang`, `className`, `id`, `ref`. A parent render with equal `data` does not redraw the element or clear what the user typed. React 19 or later, as an optional peer dependency.
235
-
236
- ## The pi extension: `show_doc`
237
-
238
- `pi-better-show` is a pi package: it adds `show_doc`, which shows the agent's documents in your default browser or your editor and carries what you do there back to the agent as messages. It replaces `pi-herdr-doc-review` (same tool name, no Herdr, no terminal panes).
239
-
240
- ```bash
241
- pi uninstall npm:pi-herdr-doc-review # same tool name: do not load both
242
- pi install npm:pi-better-show
243
- ```
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 | |
244
78
 
245
- Then `/reload` in a running session.
79
+ A status page with `stats`, `steps`, and `table`:
246
80
 
247
- **Tool.** `show_doc({paths, reason, view})` returns at once, without waiting for you.
81
+ ![Stats tiles, a steps timeline, and a sortable table](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/status.png)
248
82
 
249
- | View | Opens |
250
- |---|---|
251
- | `page` | The default browser (`open`, `xdg-open`), one tab per page, on a loopback page server behind a random token. `.md` renders with its blocks; `.html`, `.tsx`, `.jsx` run in a sandboxed frame; images show as they are. |
252
- | `edit` (default) | A text file in your editor: `PI_BETTER_SHOW_EDITOR` (a command line, for example `code -r` or `subl`), else `code`, else `open -t` / `xdg-open`. It must return at once; terminal editors do not work. |
83
+ A structure review with `tree`, `mermaid`, and `diff`:
253
84
 
254
- **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.
85
+ ![A directory tree with tags, a flowchart, and a diff](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/structure.png)
255
86
 
256
- **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.
87
+ A design review with `review` and `suggest`:
257
88
 
258
- **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.
89
+ ![Two header designs to compare, with quick-reply chips below](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/review.png)
259
90
 
260
- **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.
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.
261
92
 
262
- **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.
93
+ ## Outside pi
263
94
 
264
- **Event bus, contract version 2.** Other viewers (the pi-straw-boss GUI) read the same documents through `pi.events`; every payload carries `version: 2`.
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:
265
96
 
266
- | Event | Payload |
97
+ | Entry | For |
267
98
  |---|---|
268
- | `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. |
269
- | `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. |
270
- | `better-show:answer` | `{version, id, answerId, answer}` with `answer` an `Answer`. It reaches the agent as the same message a page answer produces. |
271
- | `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. |
272
-
273
- 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.
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 |
274
103
 
275
- **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).
276
-
277
- 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.
278
105
 
279
106
  ## Development
280
107
 
281
- ```
108
+ ```bash
282
109
  bun install
283
110
  bun test
284
111
  bun run check # tsc, tsc for core without node types, biome
285
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
286
114
  ```
287
115
 
288
116
  ## License
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-show",
3
- "version": "0.4.0",
3
+ "version": "0.5.2",
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
  }
@@ -1,3 +1,4 @@
1
+ import { NOTE_FIELD } from "./blocks.ts";
1
2
  import type { Answer } from "./types.ts";
2
3
 
3
4
  type Fields = readonly (readonly [string, string])[];
@@ -64,6 +65,16 @@ function checklistText(fields: Fields, title: string | undefined): string {
64
65
  */
65
66
  export function encodeAnswer(answer: Answer): string {
66
67
  const fields = answer.fields.filter(([name]) => name !== "pi-kind");
68
+ if (answer.kind === "feedback") return encodeKind(answer, fields);
69
+ const note = first(fields, NOTE_FIELD)?.trim();
70
+ const body = encodeKind(
71
+ answer,
72
+ fields.filter(([name]) => name !== NOTE_FIELD),
73
+ );
74
+ return note ? `${body}\n\nOther comments: ${note}` : body;
75
+ }
76
+
77
+ function encodeKind(answer: Answer, fields: Fields): string {
67
78
  switch (answer.kind) {
68
79
  case "form":
69
80
  return formText(fields);
@@ -1,3 +1,4 @@
1
+ import { NOTE_FIELD } from "./blocks.ts";
1
2
  import { entryOf, flag, itemsOf, mappingOf, oneOf, record, requiredText, text } from "./normalize.ts";
2
3
  import type {
3
4
  Cell,
@@ -59,8 +60,10 @@ export function checklist(data: unknown): ChecklistData {
59
60
  const item = entryOf(entry, "label", "item");
60
61
  const label = text(item.label ?? item.name, "label");
61
62
  if (label === undefined) throw new Error("each checklist item needs a label or a name");
63
+ const name = text(item.name, "name") ?? label;
64
+ if (name === NOTE_FIELD) throw new Error('the item name "pi-note" is reserved for the other-comments box');
62
65
  return {
63
- name: text(item.name, "name") ?? label,
66
+ name,
64
67
  label,
65
68
  checked: flag(item.checked, "checked") ?? false,
66
69
  note: text(item.note, "note"),
@@ -37,6 +37,12 @@ export function options(data: unknown): OptionsData {
37
37
  };
38
38
  }
39
39
 
40
+ /**
41
+ * The reserved field every submittable block may add to its answer: the free text from the "Other comments" box.
42
+ * It is omitted when the box is empty, appears at most once, and no form question or checklist item may use the name.
43
+ */
44
+ export const NOTE_FIELD = "pi-note";
45
+
40
46
  const QUESTION_TYPES = ["single", "multi", "text"] as const;
41
47
 
42
48
  function choice(entry: unknown): ChoiceData {
@@ -56,6 +62,7 @@ function question(item: unknown): QuestionData {
56
62
  const label = text(raw.label, "label");
57
63
  const name = text(raw.name, "name") ?? label;
58
64
  if (name === undefined) throw new Error("each question needs a name or a label");
65
+ if (name === NOTE_FIELD) throw new Error('the question name "pi-note" is reserved for the other-comments box');
59
66
  const entries: unknown[] = Array.isArray(raw.choices) ? raw.choices : list(raw.choices, "choices");
60
67
  const choices = entries.map(choice);
61
68
  const type: QuestionType = oneOf(raw.type, QUESTION_TYPES, "type") ?? (choices.length > 0 ? "single" : "text");