pi-better-show 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +241 -2
- package/package.json +84 -4
- package/src/core/answer.ts +81 -0
- package/src/core/blocks-new.ts +159 -0
- package/src/core/blocks.ts +134 -0
- package/src/core/index.ts +7 -0
- package/src/core/inline.ts +202 -0
- package/src/core/normalize.ts +82 -0
- package/src/core/parse.ts +154 -0
- package/src/core/text.ts +283 -0
- package/src/core/types.ts +230 -0
- package/src/core/width.ts +32 -0
- package/src/elements/base.ts +218 -0
- package/src/elements/choice.ts +234 -0
- package/src/elements/config.ts +58 -0
- package/src/elements/controls.ts +94 -0
- package/src/elements/display.ts +276 -0
- package/src/elements/dom.ts +92 -0
- package/src/elements/form.ts +245 -0
- package/src/elements/index.ts +54 -0
- package/src/elements/mindmap.ts +180 -0
- package/src/elements/review.ts +189 -0
- package/src/elements/strings.ts +148 -0
- package/src/elements/styles.ts +148 -0
- package/src/elements/table.ts +186 -0
- package/src/extension/assets.ts +46 -0
- package/src/extension/client/bridge.ts +26 -0
- package/src/extension/client/feedback.ts +223 -0
- package/src/extension/client/frame.ts +97 -0
- package/src/extension/client/host-config.ts +51 -0
- package/src/extension/client/host.ts +36 -0
- package/src/extension/client/kit.tsx +24 -0
- package/src/extension/client/page.css +255 -0
- package/src/extension/client/page.ts +68 -0
- package/src/extension/contract.ts +61 -0
- package/src/extension/controller.ts +450 -0
- package/src/extension/edit.ts +238 -0
- package/src/extension/files.ts +49 -0
- package/src/extension/index.ts +86 -0
- package/src/extension/react-page.ts +185 -0
- package/src/extension/render.ts +87 -0
- package/src/extension/server.ts +473 -0
- package/src/extension/tool.ts +55 -0
- package/src/react/index.ts +156 -0
- package/src/server/index.ts +64 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 wayne930242
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,242 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-better-show
|
|
2
2
|
|
|
3
|
-
|
|
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.
|
|
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`.
|
|
6
|
+
|
|
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
|
+
|
|
37
|
+
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.
|
|
38
|
+
|
|
39
|
+
## Core API
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { parse, toText, inline, encodeAnswer } from "pi-better-show";
|
|
43
|
+
|
|
44
|
+
parse(markdown: string): Segment[]
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
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.
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
toText(segments: Segment[], profile: TextProfile): string
|
|
51
|
+
|
|
52
|
+
interface TextProfile {
|
|
53
|
+
flavor: "discord" | "line" | "plain"; // Discord Markdown, or plain text
|
|
54
|
+
width?: number; // columns a diagram may take; default 60
|
|
55
|
+
mermaid?: (source: string, width: number) => string | undefined;
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
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`.
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
inline(text: string): InlineToken[] // restricted inline Markdown, tokenized, never HTML
|
|
63
|
+
inlinePlain(text: string): string // the same text without markers
|
|
64
|
+
displayWidth(text: string): number // terminal columns: CJK counts 2
|
|
65
|
+
reviewItemName(item): string // "B (dark header)"
|
|
66
|
+
|
|
67
|
+
interface Answer {
|
|
68
|
+
kind: "form" | "review" | "feedback" | "pick" | "suggest" | "checklist";
|
|
69
|
+
title?: string;
|
|
70
|
+
fields: [name: string, value: string][];
|
|
71
|
+
ref?: { doc?: string; block: number };
|
|
72
|
+
}
|
|
73
|
+
encodeAnswer(answer: Answer): string
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`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.
|
|
77
|
+
|
|
78
|
+
| Kind | `fields` | Text |
|
|
79
|
+
|---|---|---|
|
|
80
|
+
| `form` | one `[name, value]` per question | `User submitted a form ...` then `- name: value` lines |
|
|
81
|
+
| `review` | `title`, `picked`, `item`/`comment` pairs, `silent` | `User reviewed "title":` ... |
|
|
82
|
+
| `feedback` | `page`, `quote`/`comment` pairs, `overall` | `User feedback on the page "page":` ... |
|
|
83
|
+
| `pick` | `[["picked", option]]` | `User picked "option" for "title".` |
|
|
84
|
+
| `suggest` | `[["text", text]]` | the text itself |
|
|
85
|
+
| `checklist` | one `[name, "checked" \| "unchecked"]` per item | `User updated the checklist "title":` then `☑`/`☐` lines |
|
|
86
|
+
|
|
87
|
+
## Server API
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
import { mermaidSvg, mermaidText } from "pi-better-show/server";
|
|
91
|
+
|
|
92
|
+
mermaidSvg(source: string, options?: { scheme?: "light" | "dark" | DiagramColors; font?: string; transparent?: boolean }): string
|
|
93
|
+
mermaidText(source: string, width = 60): string | undefined
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`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`:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
toText(parse(reply), { flavor: "discord", mermaid: mermaidText });
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Elements
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import "pi-better-show/elements"; // defines every pbs-* tag (a no-op without a DOM)
|
|
106
|
+
import { configure } from "pi-better-show/elements";
|
|
107
|
+
|
|
108
|
+
el.data = segment.data; // or <pbs-form data-json='{...}'>
|
|
109
|
+
el.addEventListener("pbs-answer", (event) => send(encodeAnswer(event.detail)));
|
|
110
|
+
el.answered = event.detail.fields; // once delivered: locks the element and shows what was sent
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
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).
|
|
114
|
+
|
|
115
|
+
| Tag | Block | `data` | Answer | Parts |
|
|
116
|
+
|---|---|---|---|---|
|
|
117
|
+
| `pbs-callout` | `alert` | `AlertData` | | `callout` `header` `icon` `title` `body` |
|
|
118
|
+
| `pbs-cards` | `cards` | `CardsData` | | `grid` `card` `title` `icon` `body` |
|
|
119
|
+
| `pbs-options` | `options` | `OptionsData` | `pick` | `grid` `option` `title` `badge` `body` `pros` `cons` `actions` `pick` `status` |
|
|
120
|
+
| `pbs-form` | `form` | `FormData` | `form` | `form` `title` `question` `label` `hint` `choices` `choice` `badge` `other` `textarea` `error` `actions` `submit` `status` `sent` |
|
|
121
|
+
| `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` |
|
|
122
|
+
| `pbs-mindmap` | `mindmap` | `MindmapData` | | `mindmap` `tree` `item` `node` `toggle` `label` `group` |
|
|
123
|
+
| `pbs-suggest` | `suggest` | `SuggestData` | `suggest` | `suggest` `chips` `chip` `status` |
|
|
124
|
+
| `pbs-checklist` | `checklist` | `ChecklistData` | `checklist` | `checklist` `title` `items` `item` `progress` `actions` `submit` `status` `sent` |
|
|
125
|
+
| `pbs-table` | `table` | `TableData` | | `table` `bar` `filter` `count` `scroll` `header` `head` `sort` `body` `row` `cell` `empty` |
|
|
126
|
+
| `pbs-steps` | `steps` | `StepsData` | | `steps` `step` `rail` `marker` `content` `title` `badge` `when` `body` |
|
|
127
|
+
| `pbs-stats` | `stats` | `StatsData` | | `grid` `stat` `label` `value` `delta` `note` |
|
|
128
|
+
| `pbs-diff` | `diff` | `DiffData` | | `diff` `scroll` `line` |
|
|
129
|
+
| `pbs-diagram` | `mermaid` | `MermaidData` | | `diagram` `image` `source` `note` |
|
|
130
|
+
|
|
131
|
+
`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.
|
|
132
|
+
|
|
133
|
+
**Attributes and properties** (every element)
|
|
134
|
+
|
|
135
|
+
| Name | Kind | Meaning |
|
|
136
|
+
|---|---|---|
|
|
137
|
+
| `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`. |
|
|
138
|
+
| `answered` / `data-answered` | property / attribute | The submitted `[name, value][]`: locks the element and shows them. `undefined` reopens it. |
|
|
139
|
+
| `ref`, or `doc` and `block` attributes | property / attributes | The block's address, copied into every answer's `ref`. |
|
|
140
|
+
| `density` | attribute and property | `comfortable` (default) or `compact`. |
|
|
141
|
+
| `scheme` | attribute and property | `light` or `dark`, to force a scheme; else the element follows the host's `color-scheme`. |
|
|
142
|
+
| `lang` | attribute (or an ancestor's, or the document's) | `zh*` shows Traditional Chinese, anything else English. |
|
|
143
|
+
| `refresh()` | method | Draws again. Call it after the host changes `color-scheme` or the document `lang`, which an element cannot observe. |
|
|
144
|
+
|
|
145
|
+
**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.
|
|
146
|
+
|
|
147
|
+
**Looking after the host: `configure`**
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
configure({
|
|
151
|
+
strings: { "zh-Hant": { send: "送出" } }, // per locale, per word (see Strings)
|
|
152
|
+
diagramUrl: (source, scheme) => `/diagram.svg?...`, // an image URL for pbs-diagram; without it the source is shown
|
|
153
|
+
imageUrl: (ref) => `/files/${ref}`, // a review item's `image`; default admits http(s) and raster data URLs only
|
|
154
|
+
pageUrl: (ref) => `/pages/${ref}`, // a review item's `page`, shown in a sandboxed frame; without it, its name
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Serve diagram images from `pi-better-show/server` (`mermaidSvg(source, { scheme, transparent: true })`); no diagram markup enters the page. `resetConfiguration()` restores the defaults.
|
|
159
|
+
|
|
160
|
+
**Tokens.** Set a `--pbs-*` property on an element or any ancestor; each has a `light-dark()` default that follows the host's `color-scheme`.
|
|
161
|
+
|
|
162
|
+
| Token | Meaning |
|
|
163
|
+
|---|---|
|
|
164
|
+
| `--pbs-bg` `--pbs-surface` | Panel background; tinted surface (table header, code) |
|
|
165
|
+
| `--pbs-fg` `--pbs-muted` | Text; secondary text |
|
|
166
|
+
| `--pbs-line` `--pbs-control` | Panel and divider lines; the edge of an input (3:1 against its surface) |
|
|
167
|
+
| `--pbs-accent` `--pbs-on-accent` | Buttons, links, selection; text on them |
|
|
168
|
+
| `--pbs-note` `--pbs-ok` `--pbs-warn` `--pbs-risk` | Tones |
|
|
169
|
+
| `--pbs-radius` `--pbs-gap` | Corner radius; space between blocks and inside them |
|
|
170
|
+
| `--pbs-font` `--pbs-mono` `--pbs-font-size` | Type |
|
|
171
|
+
| `--pbs-font-display` | Titles and headings (defaults to `--pbs-font`) |
|
|
172
|
+
|
|
173
|
+
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.
|
|
174
|
+
|
|
175
|
+
**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-table` sorts from header buttons (`aria-sort`) and filters from a labelled search box.
|
|
176
|
+
|
|
177
|
+
## React
|
|
178
|
+
|
|
179
|
+
```tsx
|
|
180
|
+
import { PbsBlock, PbsForm } from "pi-better-show/react";
|
|
181
|
+
|
|
182
|
+
<PbsBlock segment={segment} doc="chat-7" onAnswer={(answer) => send(encodeAnswer(answer))} />
|
|
183
|
+
<PbsForm data={formData} answered={fields} density="compact" onAnswer={...} />
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
One component per element (`PbsCallout` ... `PbsDiagram`) 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.
|
|
187
|
+
|
|
188
|
+
## The pi extension: `show_doc`
|
|
189
|
+
|
|
190
|
+
`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).
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
pi uninstall npm:pi-herdr-doc-review # same tool name: do not load both
|
|
194
|
+
pi install npm:pi-better-show
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Then `/reload` in a running session.
|
|
198
|
+
|
|
199
|
+
**Tool.** `show_doc({paths, reason, view})` returns at once, without waiting for you.
|
|
200
|
+
|
|
201
|
+
| View | Opens |
|
|
202
|
+
|---|---|
|
|
203
|
+
| `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. |
|
|
204
|
+
| `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. |
|
|
205
|
+
|
|
206
|
+
**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.
|
|
207
|
+
|
|
208
|
+
**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. 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.
|
|
209
|
+
|
|
210
|
+
**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.
|
|
211
|
+
|
|
212
|
+
**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.
|
|
213
|
+
|
|
214
|
+
**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.
|
|
215
|
+
|
|
216
|
+
**Event bus, contract version 2.** Other viewers (the pi-straw-boss GUI) read the same documents through `pi.events`; every payload carries `version: 2`.
|
|
217
|
+
|
|
218
|
+
| Event | Payload |
|
|
219
|
+
|---|---|
|
|
220
|
+
| `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. |
|
|
221
|
+
| `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. |
|
|
222
|
+
| `better-show:answer` | `{version, id, answerId, answer}` with `answer` an `Answer`. It reaches the agent as the same message a page answer produces. |
|
|
223
|
+
| `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. |
|
|
224
|
+
|
|
225
|
+
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?}`.
|
|
226
|
+
|
|
227
|
+
**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).
|
|
228
|
+
|
|
229
|
+
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.
|
|
230
|
+
|
|
231
|
+
## Development
|
|
232
|
+
|
|
233
|
+
```
|
|
234
|
+
bun install
|
|
235
|
+
bun test
|
|
236
|
+
bun run check # tsc, tsc for core without node types, biome
|
|
237
|
+
bun run demo # examples/elements.html on http://127.0.0.1:4177/
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
## License
|
|
241
|
+
|
|
242
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,86 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-show",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.2",
|
|
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
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "wayne930242",
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"README.md",
|
|
11
|
+
"LICENSE"
|
|
12
|
+
],
|
|
13
|
+
"exports": {
|
|
14
|
+
".": "./src/core/index.ts",
|
|
15
|
+
"./elements": "./src/elements/index.ts",
|
|
16
|
+
"./react": "./src/react/index.ts",
|
|
17
|
+
"./server": "./src/server/index.ts",
|
|
18
|
+
"./extension": "./src/extension/index.ts"
|
|
19
|
+
},
|
|
20
|
+
"scripts": {
|
|
21
|
+
"test": "bun test",
|
|
22
|
+
"check": "tsc --noEmit && tsc -p tsconfig.core.json && biome check .",
|
|
23
|
+
"demo": "bun examples/serve.ts",
|
|
24
|
+
"show": "bun examples/show-harness.ts"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"beautiful-mermaid": "1.1.3",
|
|
28
|
+
"esbuild": "0.28.2",
|
|
29
|
+
"markdown-it": "15.0.3",
|
|
30
|
+
"pbs-page-react": "npm:react@19.3.1",
|
|
31
|
+
"pbs-page-react-dom": "npm:react-dom@19.3.1",
|
|
32
|
+
"yaml": "2.9.1"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@biomejs/biome": "2.6.6",
|
|
36
|
+
"@earendil-works/pi-coding-agent": "1.5.0",
|
|
37
|
+
"@happy-dom/global-registrator": "21.0.4",
|
|
38
|
+
"@types/bun": "1.4.4",
|
|
39
|
+
"@types/markdown-it": "14.2.0",
|
|
40
|
+
"@types/node": "26.6.6",
|
|
41
|
+
"@types/react": "19.3.0",
|
|
42
|
+
"@types/react-dom": "19.3.0",
|
|
43
|
+
"happy-dom": "21.0.4",
|
|
44
|
+
"react": "19.3.1",
|
|
45
|
+
"react-dom": "19.3.1",
|
|
46
|
+
"typebox": "1.4.5",
|
|
47
|
+
"typescript": "7.0.2"
|
|
48
|
+
},
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "git+https://github.com/wayne930242/pi-better-show.git"
|
|
52
|
+
},
|
|
53
|
+
"keywords": [
|
|
54
|
+
"pi-package",
|
|
55
|
+
"pi",
|
|
56
|
+
"markdown",
|
|
57
|
+
"blocks",
|
|
58
|
+
"mermaid",
|
|
59
|
+
"form",
|
|
60
|
+
"chat",
|
|
61
|
+
"web-components",
|
|
62
|
+
"react",
|
|
63
|
+
"custom-elements"
|
|
64
|
+
],
|
|
65
|
+
"peerDependencies": {
|
|
66
|
+
"react": ">=19",
|
|
67
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
68
|
+
"typebox": "*"
|
|
69
|
+
},
|
|
70
|
+
"peerDependenciesMeta": {
|
|
71
|
+
"react": {
|
|
72
|
+
"optional": true
|
|
73
|
+
},
|
|
74
|
+
"@earendil-works/pi-coding-agent": {
|
|
75
|
+
"optional": true
|
|
76
|
+
},
|
|
77
|
+
"typebox": {
|
|
78
|
+
"optional": true
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
"pi": {
|
|
82
|
+
"extensions": [
|
|
83
|
+
"./src/extension/index.ts"
|
|
84
|
+
]
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { Answer } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
type Fields = readonly (readonly [string, string])[];
|
|
4
|
+
|
|
5
|
+
const first = (fields: Fields, name: string): string | undefined => fields.find(([key]) => key === name)?.[1];
|
|
6
|
+
const all = (fields: Fields, name: string): string[] =>
|
|
7
|
+
fields.filter(([key]) => key === name).map(([, value]) => value);
|
|
8
|
+
|
|
9
|
+
/** The agent's view of one submitted form: one `- name: value` line per field. */
|
|
10
|
+
function formText(fields: Fields): string {
|
|
11
|
+
const lines = fields.map(([name, value]) => `- ${name}: ${value}`);
|
|
12
|
+
return `User submitted a form in the HTML review pane:\n${lines.join("\n") || "(no fields)"}`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** A page's feedback panel: each commented passage quoted with its comment, then the overall note. */
|
|
16
|
+
function feedbackText(fields: Fields, title: string | undefined): string {
|
|
17
|
+
const quotes = all(fields, "quote");
|
|
18
|
+
const comments = all(fields, "comment");
|
|
19
|
+
const parts = quotes.map((quote, index) => {
|
|
20
|
+
const quoted = quote
|
|
21
|
+
? quote
|
|
22
|
+
.split("\n")
|
|
23
|
+
.map((line) => `> ${line}`)
|
|
24
|
+
.join("\n")
|
|
25
|
+
: "";
|
|
26
|
+
return [quoted, comments[index] || "(no comment)"].filter(Boolean).join("\n");
|
|
27
|
+
});
|
|
28
|
+
const overall = first(fields, "overall");
|
|
29
|
+
if (overall) parts.push(`Overall: ${overall}`);
|
|
30
|
+
return `User feedback on the page "${first(fields, "page") ?? title ?? ""}":\n\n${parts.join("\n\n") || "(empty)"}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A sent review: the picked item, each commented item with its comment, and the items left blank (no feedback). */
|
|
34
|
+
function reviewText(fields: Fields, title: string | undefined): string {
|
|
35
|
+
const comments = all(fields, "comment");
|
|
36
|
+
const lines = all(fields, "item").map(
|
|
37
|
+
(item, index) => `- ${item}: ${(comments[index] ?? "").replace(/\n/g, "\n ")}`,
|
|
38
|
+
);
|
|
39
|
+
const picked = first(fields, "picked");
|
|
40
|
+
const silent = first(fields, "silent");
|
|
41
|
+
return [
|
|
42
|
+
`User reviewed "${first(fields, "title") ?? title ?? ""}":`,
|
|
43
|
+
...(picked ? [`Picked: ${picked}`] : []),
|
|
44
|
+
...lines,
|
|
45
|
+
...(silent ? [`No feedback on: ${silent}`] : []),
|
|
46
|
+
].join("\n");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function pickText(fields: Fields, title: string | undefined): string {
|
|
50
|
+
const picked = first(fields, "picked") ?? "";
|
|
51
|
+
return `User picked "${picked}"${title ? ` for "${title}"` : ""}.`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function checklistText(fields: Fields, title: string | undefined): string {
|
|
55
|
+
const lines = fields.map(([name, state]) => `${state === "checked" ? "☑" : "☐"} ${name}`);
|
|
56
|
+
return [`User updated the checklist${title ? ` "${title}"` : ""}:`, ...lines].join("\n");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The text the agent reads for an answer. `form`, `review`, and `feedback` are byte-compatible with
|
|
61
|
+
* pi-herdr-doc-review's `formMessage`, `reviewMessage`, and `pageFeedbackMessage` for the same fields;
|
|
62
|
+
* the legacy `pi-kind` field is ignored because `answer.kind` carries it. `ref` addresses the block for
|
|
63
|
+
* hosts and does not appear in the text.
|
|
64
|
+
*/
|
|
65
|
+
export function encodeAnswer(answer: Answer): string {
|
|
66
|
+
const fields = answer.fields.filter(([name]) => name !== "pi-kind");
|
|
67
|
+
switch (answer.kind) {
|
|
68
|
+
case "form":
|
|
69
|
+
return formText(fields);
|
|
70
|
+
case "review":
|
|
71
|
+
return reviewText(fields, answer.title);
|
|
72
|
+
case "feedback":
|
|
73
|
+
return feedbackText(fields, answer.title);
|
|
74
|
+
case "pick":
|
|
75
|
+
return pickText(fields, answer.title);
|
|
76
|
+
case "suggest":
|
|
77
|
+
return first(fields, "text") ?? fields.map(([, value]) => value).join("\n");
|
|
78
|
+
case "checklist":
|
|
79
|
+
return checklistText(fields, answer.title);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { entryOf, flag, itemsOf, mappingOf, oneOf, record, requiredText, text } from "./normalize.ts";
|
|
2
|
+
import type {
|
|
3
|
+
Cell,
|
|
4
|
+
ChecklistData,
|
|
5
|
+
ColumnType,
|
|
6
|
+
MindmapData,
|
|
7
|
+
MindmapNode,
|
|
8
|
+
StatsData,
|
|
9
|
+
StepsData,
|
|
10
|
+
SuggestData,
|
|
11
|
+
TableColumn,
|
|
12
|
+
TableData,
|
|
13
|
+
} from "./types.ts";
|
|
14
|
+
|
|
15
|
+
/** The blocks pi-better-show adds to the show-doc vocabulary. */
|
|
16
|
+
|
|
17
|
+
const LIST_ITEM = /^([ \t]*)(?:[-*+]|\d+[.)])[ \t]+(.*)$/;
|
|
18
|
+
|
|
19
|
+
/** An indented Markdown list; the first item is the root and every other item hangs below it. */
|
|
20
|
+
export function mindmap(source: string): MindmapData {
|
|
21
|
+
const lines = source.split("\n").filter((line) => line.trim() !== "");
|
|
22
|
+
if (lines.length === 0) throw new Error("a mindmap needs an indented list");
|
|
23
|
+
const stack: { indent: number; node: MindmapNode }[] = [];
|
|
24
|
+
let root: MindmapNode | undefined;
|
|
25
|
+
for (const line of lines) {
|
|
26
|
+
const item = LIST_ITEM.exec(line);
|
|
27
|
+
if (!item) throw new Error(`not a list item: ${line.trim()}`);
|
|
28
|
+
const label = (item[2] as string).trim();
|
|
29
|
+
if (label === "") throw new Error("a list item has no text");
|
|
30
|
+
const indent = (item[1] as string).replace(/\t/g, " ").length;
|
|
31
|
+
const node: MindmapNode = { text: label, children: [] };
|
|
32
|
+
while (stack.length > 0 && (stack[stack.length - 1] as { indent: number }).indent >= indent) stack.pop();
|
|
33
|
+
const parent = stack[stack.length - 1];
|
|
34
|
+
if (parent) parent.node.children.push(node);
|
|
35
|
+
else if (root) throw new Error("a mindmap has one root: indent the other top-level items under it");
|
|
36
|
+
else root = node;
|
|
37
|
+
stack.push({ indent, node });
|
|
38
|
+
}
|
|
39
|
+
return { root: root as MindmapNode };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function suggest(data: unknown): SuggestData {
|
|
43
|
+
return {
|
|
44
|
+
items: itemsOf(data, "items").map((entry) => {
|
|
45
|
+
const raw = entryOf(entry, "label", "suggestion");
|
|
46
|
+
const label = text(raw.label ?? raw.text, "label");
|
|
47
|
+
if (label === undefined) throw new Error("each suggestion needs a label or a text");
|
|
48
|
+
return { label, text: text(raw.text, "text") ?? label };
|
|
49
|
+
}),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function checklist(data: unknown): ChecklistData {
|
|
54
|
+
const raw = mappingOf(data);
|
|
55
|
+
return {
|
|
56
|
+
title: text(raw.title, "title"),
|
|
57
|
+
submit: text(raw.submit, "submit"),
|
|
58
|
+
items: itemsOf(data, "items").map((entry) => {
|
|
59
|
+
const item = entryOf(entry, "label", "item");
|
|
60
|
+
const label = text(item.label ?? item.name, "label");
|
|
61
|
+
if (label === undefined) throw new Error("each checklist item needs a label or a name");
|
|
62
|
+
return {
|
|
63
|
+
name: text(item.name, "name") ?? label,
|
|
64
|
+
label,
|
|
65
|
+
checked: flag(item.checked, "checked") ?? false,
|
|
66
|
+
note: text(item.note, "note"),
|
|
67
|
+
};
|
|
68
|
+
}),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const COLUMN_TYPES = ["text", "number", "date"] as const;
|
|
73
|
+
const ALIGNS = ["left", "center", "right"] as const;
|
|
74
|
+
|
|
75
|
+
function column(entry: unknown): TableColumn {
|
|
76
|
+
const raw = entryOf(entry, "name", "column");
|
|
77
|
+
const name = text(raw.name ?? raw.label, "name");
|
|
78
|
+
if (name === undefined) throw new Error("each column needs a name or a label");
|
|
79
|
+
const type: ColumnType = oneOf(raw.type, COLUMN_TYPES, "type") ?? "text";
|
|
80
|
+
return {
|
|
81
|
+
name,
|
|
82
|
+
label: text(raw.label, "label") ?? name,
|
|
83
|
+
align: oneOf(raw.align, ALIGNS, "align") ?? (type === "number" ? "right" : "left"),
|
|
84
|
+
type,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function cell(value: unknown): Cell {
|
|
89
|
+
if (value === undefined || value === null) return null;
|
|
90
|
+
if (typeof value === "object") throw new Error("a table cell must be text, a number, or a boolean");
|
|
91
|
+
return value as Cell;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function sortOf(value: unknown, columns: TableColumn[]): TableData["sort"] {
|
|
95
|
+
if (value === undefined || value === null) return undefined;
|
|
96
|
+
const raw = typeof value === "object" ? record(value, "sort") : { column: value };
|
|
97
|
+
let reference = text(raw.column ?? raw.by, "sort column") ?? "";
|
|
98
|
+
let direction = oneOf(raw.direction ?? raw.dir, ["asc", "desc"] as const, "sort direction");
|
|
99
|
+
if (typeof value !== "object" && reference.startsWith("-")) {
|
|
100
|
+
reference = reference.slice(1);
|
|
101
|
+
direction = "desc";
|
|
102
|
+
}
|
|
103
|
+
const index = columns.findIndex((entry) => entry.name === reference || entry.label === reference);
|
|
104
|
+
if (index < 0) throw new Error(`sort names no column: ${reference}`);
|
|
105
|
+
return { column: index, direction: direction ?? "asc" };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function table(data: unknown): TableData {
|
|
109
|
+
const raw = record(data, "table");
|
|
110
|
+
const rawRows = itemsOf(raw, "rows");
|
|
111
|
+
const given = raw.columns === undefined ? undefined : itemsOf(raw, "columns");
|
|
112
|
+
const objects = rawRows.filter((row) => row !== null && typeof row === "object" && !Array.isArray(row)) as Record<
|
|
113
|
+
string,
|
|
114
|
+
unknown
|
|
115
|
+
>[];
|
|
116
|
+
// Without `columns`, the keys of the mapping rows name them, in the order they first appear.
|
|
117
|
+
const columns = (given ?? [...new Set(objects.flatMap((row) => Object.keys(row)))]).map(column);
|
|
118
|
+
if (columns.length === 0) throw new Error("a table needs `columns`, or rows written as mappings");
|
|
119
|
+
const rows = rawRows.map((row) => {
|
|
120
|
+
if (Array.isArray(row)) {
|
|
121
|
+
if (row.length > columns.length) throw new Error(`a row has ${row.length} cells for ${columns.length} columns`);
|
|
122
|
+
return columns.map((_, index) => cell(row[index]));
|
|
123
|
+
}
|
|
124
|
+
const mapping = record(row, "row");
|
|
125
|
+
return columns.map((entry) => cell(mapping[entry.name] ?? mapping[entry.label]));
|
|
126
|
+
});
|
|
127
|
+
return { columns, rows, sort: sortOf(raw.sort, columns), filter: flag(raw.filter, "filter") ?? false };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const STEP_STATUSES = ["done", "doing", "todo", "blocked"] as const;
|
|
131
|
+
|
|
132
|
+
export function steps(data: unknown): StepsData {
|
|
133
|
+
return {
|
|
134
|
+
items: itemsOf(data, "items").map((entry) => {
|
|
135
|
+
const item = entryOf(entry, "title", "step");
|
|
136
|
+
return {
|
|
137
|
+
title: requiredText(item.title, "a step's title"),
|
|
138
|
+
status: oneOf(item.status, STEP_STATUSES, "status") ?? "todo",
|
|
139
|
+
when: text(item.when, "when"),
|
|
140
|
+
body: text(item.body, "body"),
|
|
141
|
+
};
|
|
142
|
+
}),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function stats(data: unknown): StatsData {
|
|
147
|
+
return {
|
|
148
|
+
items: itemsOf(data, "items").map((entry) => {
|
|
149
|
+
const item = record(entry, "stat");
|
|
150
|
+
return {
|
|
151
|
+
label: requiredText(item.label, "a stat's label"),
|
|
152
|
+
value: requiredText(item.value, "a stat's value"),
|
|
153
|
+
delta: text(item.delta, "delta"),
|
|
154
|
+
tone: text(item.tone, "tone"),
|
|
155
|
+
note: text(item.note, "note"),
|
|
156
|
+
};
|
|
157
|
+
}),
|
|
158
|
+
};
|
|
159
|
+
}
|