pi-better-show 0.5.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,307 +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
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
+ ![A decision page: an alert, two options, and a form](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/decide.png)
73
9
 
74
- ```ts
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
- parse(markdown: string): Segment[]
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
- 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.
19
+ ## Fewer tokens
81
20
 
82
- ```ts
83
- checkBlocks(markdown: string, options?: { mermaid?: (source: string) => string | undefined }): BlockProblem[]
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
- interface BlockProblem {
87
- kind: BlockKind;
88
- line: number; // 1-based, in the Markdown file
89
- path: string; // e.g. form question "o5" choice 1 label
90
- message: string;
91
- severity: "error" | "warning";
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
- ```ts
116
- inline(text: string): InlineToken[] // restricted inline Markdown, tokenized, never HTML
117
- inlinePlain(text: string): string // the same text without markers
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
- interface Answer {
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
- | Kind | `fields` | Text |
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
- `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.
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
- mermaidSvg(source: string, options?: { scheme?: "light" | "dark" | DiagramColors; font?: string; transparent?: boolean }): string
157
- mermaidText(source: string, width = 60): string | undefined
158
- ```
45
+ ## What `show_doc` does
159
46
 
160
- `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`:
47
+ `show_doc({paths, reason, view})` returns at once; the agent does not wait for you.
161
48
 
162
- ```ts
163
- toText(parse(reply), { flavor: "discord", mermaid: mermaidText });
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
+ 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.
165
56
 
166
- ## Elements
57
+ ![The feedback panel with a comment on a selected passage](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/feedback.png)
167
58
 
168
- ```ts
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
- el.data = segment.data; // or <pbs-form data-json='{...}'>
173
- el.addEventListener("pbs-answer", (event) => send(encodeAnswer(event.detail)));
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
- 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).
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
- | `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`. |
203
- | `answered` / `data-answered` | property / attribute | The submitted `[name, value][]`: locks the element and shows them. `undefined` reopens it. |
204
- | `ref`, or `doc` and `block` attributes | property / attributes | The block's address, copied into every answer's `ref`. |
205
- | `density` | attribute and property | `comfortable` (default) or `compact`. |
206
- | `scheme` | attribute and property | `light` or `dark`, to force a scheme; else the element follows the host's `color-scheme`. |
207
- | `lang` | attribute (or an ancestor's, or the document's) | `zh*` shows Traditional Chinese, anything else English. |
208
- | `refresh()` | method | Draws again. Call it after the host changes `color-scheme` or the document `lang`, which an element cannot observe. |
209
-
210
- **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.
211
-
212
- **Looking after the host: `configure`**
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
- **Tokens.** Set a `--pbs-*` property on an element or any ancestor; each has a `light-dark()` default that follows the host's `color-scheme`.
79
+ A status page with `stats`, `steps`, and `table`:
226
80
 
227
- | Token | Meaning |
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
+ ![Stats tiles, a steps timeline, and a sortable table](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/status.png)
239
82
 
240
- **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.
83
+ A structure review with `tree`, `mermaid`, and `diff`:
241
84
 
242
- ## React
85
+ ![A directory tree with tags, a flowchart, and a diff](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/structure.png)
243
86
 
244
- ```tsx
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
- 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.
89
+ ![Two header designs to compare, with quick-reply chips below](https://raw.githubusercontent.com/wayne930242/pi-better-show/main/docs/images/review.png)
252
90
 
253
- ## The pi extension: `show_doc`
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
- `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).
93
+ ## Outside pi
256
94
 
257
- ```bash
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
- Then `/reload` in a running session.
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
- | `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. |
269
- | `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. |
270
-
271
- **Block problems.** `show_doc` appends the problems of each Markdown document it opens (`checkBlocks`, see Core API) after its usual reply, and the `write` and `edit` tools of the agent get them in their own result for a `.md` file that holds a block fence: `Block problems in questions.md:` then `- line 40 form question "o5" choice 1 label (warning): ...`. Files without block fences are not read by the checker; the YAML parser and Mermaid load on the first file that needs them. Mermaid is checked in the extension with `beautiful-mermaid`, which validates the diagram type and parses what it draws; it does not catch every syntax slip in a flowchart.
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
- **Event bus, contract version 2.** Other viewers (the pi-straw-boss GUI) read the same documents through `pi.events`; every payload carries `version: 2`.
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.5.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
  }
@@ -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, an optional `note` field (the "Other comments" box, once) is accepted on every kind, and there
133
- * are at most 64 fields of 1,024 characters each.
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.