pi-better-show 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -72,13 +72,28 @@ A block whose body is not valid YAML, or does not fit its schema, becomes an `in
72
72
  ## Core API
73
73
 
74
74
  ```ts
75
- import { parse, toText, inline, encodeAnswer } from "pi-better-show";
75
+ import { parse, toText, inline, encodeAnswer, checkBlocks } from "pi-better-show";
76
76
 
77
77
  parse(markdown: string): Segment[]
78
78
  ```
79
79
 
80
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
81
 
82
+ ```ts
83
+ checkBlocks(markdown: string, options?: { mermaid?: (source: string) => string | undefined }): BlockProblem[]
84
+ formatProblems(name: string, problems: BlockProblem[]): string
85
+
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
+
82
97
  ```ts
83
98
  toText(segments: Segment[], profile: TextProfile): string
84
99
 
@@ -112,7 +127,7 @@ interface Answer {
112
127
  encodeAnswer(answer: Answer): string
113
128
  ```
114
129
 
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.
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: …`.
116
131
 
117
132
  | Kind | `fields` | Text |
118
133
  |---|---|---|
@@ -129,6 +144,8 @@ validateAnswer(block: BlockSegment, answer: Answer): { ok: true } | { ok: false;
129
144
 
130
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.
131
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
+
132
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.
133
150
 
134
151
  ## Server API
@@ -251,6 +268,8 @@ Then `/reload` in a running session.
251
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. |
252
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. |
253
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
+
254
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.
255
274
 
256
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.
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.0",
4
4
  "description": "Interactive blocks for agent-written Markdown: one vocabulary, text fallback, and answer encoding shared by every host, plus the show_doc extension for pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -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");
@@ -0,0 +1,353 @@
1
+ import { isMap, isScalar, isSeq, LineCounter, type Node, parseDocument, type Scalar } from "yaml";
2
+ import { locate } from "./parse.ts";
3
+ import type { BlockKind } from "./types.ts";
4
+
5
+ /**
6
+ * Finds what is wrong with the blocks of a Markdown file, so the agent that wrote it can fix them: a block that does
7
+ * not parse (the page shows its source), and the slips that parse without an error and lose data (a value cut at a
8
+ * ` #`, a key no block reads). Each problem carries the line of the Markdown file.
9
+ */
10
+
11
+ export interface BlockProblem {
12
+ kind: BlockKind;
13
+ /** 1-based line of the Markdown file. */
14
+ line: number;
15
+ /** Where in the block, as the author reads it: `form question "o5" choice 1 label`. */
16
+ path: string;
17
+ message: string;
18
+ /** `error`: the block cannot be drawn. `warning`: it is drawn, but part of what was written is lost. */
19
+ severity: "error" | "warning";
20
+ }
21
+
22
+ export interface CheckOptions {
23
+ /** Checks a Mermaid source and returns what is wrong with it; core carries no Mermaid parser, a host passes one. */
24
+ mermaid?: (source: string) => string | undefined;
25
+ }
26
+
27
+ interface Shape {
28
+ /** The keys the block reads at this level. */
29
+ keys?: readonly string[];
30
+ /** Keys that hold a list of items, with the shape of an item. */
31
+ lists?: Record<string, ListShape>;
32
+ /** Keys that hold a mapping. */
33
+ maps?: Record<string, Shape>;
34
+ /** The list a document that is a bare YAML list stands for. */
35
+ bare?: string;
36
+ }
37
+ interface ListShape {
38
+ noun: string;
39
+ item?: Shape;
40
+ /** Item keys that name an item, first found wins. */
41
+ names?: readonly string[];
42
+ }
43
+
44
+ const items = (noun: string, keys: readonly string[], names?: readonly string[]): ListShape => ({
45
+ noun,
46
+ item: { keys },
47
+ ...(names ? { names } : {}),
48
+ });
49
+
50
+ /** What each YAML kind reads, level by level; it mirrors the converters in blocks.ts and blocks-new.ts. */
51
+ const SHAPES: Record<string, Shape> = {
52
+ cards: { keys: ["cards"], bare: "cards", lists: { cards: items("card", ["title", "tone", "body"]) } },
53
+ options: {
54
+ keys: ["options"],
55
+ bare: "options",
56
+ lists: { options: items("option", ["title", "recommended", "body", "pros", "cons"]) },
57
+ },
58
+ form: {
59
+ keys: ["title", "submit", "questions"],
60
+ bare: "questions",
61
+ lists: {
62
+ questions: {
63
+ noun: "question",
64
+ names: ["name", "label"],
65
+ item: {
66
+ keys: ["name", "label", "type", "hint", "required", "other", "choices"],
67
+ lists: { choices: items("choice", ["value", "label", "note", "recommended"]) },
68
+ },
69
+ },
70
+ },
71
+ },
72
+ review: {
73
+ keys: ["title", "submit", "pick", "columns", "items"],
74
+ bare: "items",
75
+ lists: { items: items("item", ["name", "label", "image", "page", "height", "body"], ["name", "label"]) },
76
+ },
77
+ suggest: { keys: ["items"], bare: "items", lists: { items: items("suggestion", ["label", "text"]) } },
78
+ checklist: {
79
+ keys: ["title", "submit", "items"],
80
+ bare: "items",
81
+ lists: { items: items("item", ["name", "label", "checked", "note"], ["name", "label"]) },
82
+ },
83
+ table: {
84
+ keys: ["columns", "rows", "sort", "filter"],
85
+ lists: { columns: items("column", ["name", "label", "type", "align"], ["name", "label"]), rows: { noun: "row" } },
86
+ maps: { sort: { keys: ["column", "by", "direction", "dir"] } },
87
+ },
88
+ steps: { keys: ["items"], bare: "items", lists: { items: items("step", ["title", "status", "when", "body"]) } },
89
+ stats: {
90
+ keys: ["items"],
91
+ bare: "items",
92
+ lists: { items: items("stat", ["label", "value", "delta", "tone", "note"]) },
93
+ },
94
+ };
95
+
96
+ /** Keys whose value is an enum, flag or number: a ` #` after one is a plain comment, not lost text. */
97
+ const NON_TEXT_KEYS = new Set([
98
+ "status",
99
+ "type",
100
+ "align",
101
+ "direction",
102
+ "dir",
103
+ "checked",
104
+ "required",
105
+ "filter",
106
+ "height",
107
+ "columns",
108
+ "tone",
109
+ ]);
110
+
111
+ const QUOTE_HINT = 'quote any value that holds " #" or ": " (and commas inside {…})';
112
+
113
+ const short = (text: string, max = 40): string => (text.length > max ? `${text.slice(0, max)}…` : text);
114
+
115
+ /** Edit distance, to offer the known key a misspelling was probably meant for. */
116
+ function distance(a: string, b: string): number {
117
+ let row = Array.from({ length: b.length + 1 }, (_, index) => index);
118
+ for (let i = 1; i <= a.length; i++) {
119
+ const next = [i];
120
+ for (let j = 1; j <= b.length; j++) {
121
+ next[j] = Math.min(
122
+ (next[j - 1] as number) + 1,
123
+ (row[j] as number) + 1,
124
+ (row[j - 1] as number) + (a[i - 1] === b[j - 1] ? 0 : 1),
125
+ );
126
+ }
127
+ row = next;
128
+ }
129
+ return row[b.length] as number;
130
+ }
131
+
132
+ const nearest = (key: string, known: readonly string[]): string | undefined => {
133
+ const lower = key.toLowerCase();
134
+ return known.find((name) => name.toLowerCase() === lower || distance(lower, name.toLowerCase()) <= 2);
135
+ };
136
+
137
+ const quoteYaml = (text: string): string => `'${text.replace(/'/g, "''")}'`;
138
+
139
+ interface Context {
140
+ kind: BlockKind;
141
+ /** The file line of the block's opening fence: a source line n is file line `fence + n`. */
142
+ fence: number;
143
+ source: string;
144
+ lines: LineCounter;
145
+ out: BlockProblem[];
146
+ }
147
+
148
+ const lineOf = (context: Context, offset: number): number => context.fence + context.lines.linePos(offset).line;
149
+
150
+ function report(context: Context, offset: number, path: string, message: string): void {
151
+ context.out.push({ kind: context.kind, line: lineOf(context, offset), path, message, severity: "warning" });
152
+ }
153
+
154
+ /** A plain value that a ` #` on its line cut short: YAML reads the rest as a comment, so that text is lost. */
155
+ function checkComment(context: Context, node: Scalar, path: string): void {
156
+ if (node.type !== "PLAIN" || node.comment === undefined || node.comment === null || !node.range) return;
157
+ const [start, end] = node.range;
158
+ const rest = context.source.slice(
159
+ end,
160
+ context.source.indexOf("\n", end) < 0 ? undefined : context.source.indexOf("\n", end),
161
+ );
162
+ if (!/^[ \t]*#/.test(rest)) return;
163
+ const kept = context.source.slice(start, end);
164
+ const whole = `${kept}${rest}`.trimEnd();
165
+ const read = kept === "" ? "no value" : `the value ${JSON.stringify(kept)}`;
166
+ report(
167
+ context,
168
+ end,
169
+ path,
170
+ `a plain value ends at " #": ${JSON.stringify(rest.trim())} is read as a YAML comment and dropped, leaving ${read}; if it is text, quote the whole value: ${quoteYaml(whole)}`,
171
+ );
172
+ }
173
+
174
+ function checkKeys(context: Context, node: Node, shape: Shape | undefined, owner: string): void {
175
+ if (!isMap(node)) return;
176
+ for (const pair of node.items) {
177
+ const key = isScalar(pair.key) ? String(pair.key.value) : undefined;
178
+ const keyAt = isScalar(pair.key) && pair.key.range ? pair.key.range[0] : (node.range?.[0] ?? 0);
179
+ if (key !== undefined && shape?.keys && !shape.keys.includes(key)) {
180
+ const near = nearest(key, shape.keys);
181
+ report(
182
+ context,
183
+ keyAt,
184
+ owner,
185
+ `unknown key ${JSON.stringify(key)} is ignored${near ? ` (did you mean ${JSON.stringify(near)}?)` : ""}; this level reads: ${shape.keys.join(", ")}`,
186
+ );
187
+ }
188
+ walk(context, pair.value as Node | null, key === undefined ? undefined : shape, owner, key);
189
+ }
190
+ }
191
+
192
+ function itemName(item: Node | unknown, names: readonly string[] | undefined): string | undefined {
193
+ if (!isMap(item) || !names) return undefined;
194
+ for (const name of names) {
195
+ const found = item.items.find((pair) => isScalar(pair.key) && pair.key.value === name);
196
+ if (found && isScalar(found.value) && found.value.value !== null && found.value.value !== "")
197
+ return short(String(found.value.value), 30);
198
+ }
199
+ return undefined;
200
+ }
201
+
202
+ /** Walks a value, checking keys against `shape` (the owner's) and plain values for a cut-off comment. */
203
+ function walk(context: Context, node: Node | null, shape: Shape | undefined, owner: string, key: string | undefined) {
204
+ const path = key === undefined ? owner : `${owner} ${key}`;
205
+ const list = key === undefined ? undefined : shape?.lists?.[key];
206
+ if (isSeq(node)) {
207
+ for (const [index, item] of node.items.entries()) {
208
+ const name = itemName(item, list?.names);
209
+ const here = list
210
+ ? `${owner} ${list.noun} ${name === undefined ? index + 1 : JSON.stringify(name)}`
211
+ : `${path} ${index + 1}`;
212
+ walk(context, item as Node | null, list?.item, here, undefined);
213
+ }
214
+ } else if (isMap(node)) {
215
+ checkKeys(context, node, key === undefined ? shape : shape?.maps?.[key], path);
216
+ } else if (isScalar(node)) {
217
+ if (key !== undefined && NON_TEXT_KEYS.has(key)) return;
218
+ checkComment(context, node, path);
219
+ }
220
+ }
221
+
222
+ /** The YAML kinds, whose body is parsed as a document. */
223
+ const isYamlKind = (kind: BlockKind): boolean => kind in SHAPES;
224
+
225
+ function checkBody(context: Context): void {
226
+ const doc = parseDocument(context.source, { lineCounter: context.lines });
227
+ if (doc.errors.length > 0) return;
228
+ const shape = SHAPES[context.kind] as Shape;
229
+ const root = doc.contents;
230
+ const name = context.kind;
231
+ if (isSeq(root)) {
232
+ if (shape.bare === undefined) return;
233
+ const list = shape.lists?.[shape.bare];
234
+ for (const [index, item] of root.items.entries()) {
235
+ const label = itemName(item, list?.names);
236
+ const here = `${name} ${list?.noun ?? "item"} ${label === undefined ? index + 1 : JSON.stringify(label)}`;
237
+ walk(context, item as Node | null, list?.item, here, undefined);
238
+ }
239
+ } else if (isMap(root)) {
240
+ checkKeys(context, root, shape, name);
241
+ }
242
+ }
243
+
244
+ /** An invalid YAML block: YAML's own error points past a broken flow collection, so look back for the line that opened it. */
245
+ function yamlError(context: Context, error: string): { line: number; message: string; hint: string } | undefined {
246
+ const doc = parseDocument(context.source, { lineCounter: new LineCounter() });
247
+ const first = doc.errors[0];
248
+ if (!first) return undefined;
249
+ const lines = context.source.split("\n");
250
+ let at = first.linePos?.[0].line ?? 1;
251
+ const message = first.message
252
+ .split("\n")[0]
253
+ ?.replace(/ at line \d+, column \d+:?$/, "")
254
+ .replace(/:$/, "");
255
+ if (first.message.startsWith("Flow ")) {
256
+ const hit = (text: string): boolean => /[{[][^}\]]*\s#/.test(text);
257
+ for (let n = at; n >= Math.max(1, at - 50); n--) {
258
+ if (hit(lines[n - 1] ?? "")) {
259
+ at = n;
260
+ return { line: at, message: message ?? error, hint: QUOTE_HINT };
261
+ }
262
+ }
263
+ at = Math.max(1, at - 1);
264
+ return { line: at, message: message ?? error, hint: QUOTE_HINT };
265
+ }
266
+ const hint =
267
+ first.code === "MISSING_CHAR" ? "close the quote" : 'check the indentation, and quote text holding ": " or " #"';
268
+ return { line: at, message: message ?? error, hint };
269
+ }
270
+
271
+ /** A tree or mindmap error that names its source line. */
272
+ function sourceLine(context: Context, error: string): number | undefined {
273
+ const numbered = /^line (\d+): /.exec(error);
274
+ if (numbered) return Number(numbered[1]);
275
+ const listed = /^not a list item: (.*)$/.exec(error);
276
+ if (listed) {
277
+ const at = context.source.split("\n").findIndex((line) => line.trim() === (listed[1] as string));
278
+ return at < 0 ? undefined : at + 1;
279
+ }
280
+ return undefined;
281
+ }
282
+
283
+ /**
284
+ * The problems of every block in `markdown`, in document order. `error` problems are blocks that cannot be drawn
285
+ * (the page shows their source); `warning` problems are blocks that draw but lose part of what was written: a plain
286
+ * value cut at ` #`, a key the block does not read, a fence that never closes, a diagram `options.mermaid` refuses.
287
+ */
288
+ export function checkBlocks(markdown: string, options: CheckOptions = {}): BlockProblem[] {
289
+ const out: BlockProblem[] = [];
290
+ for (const { segment, line, closed, source } of locate(markdown)) {
291
+ if (segment.type === "markdown") continue;
292
+ const kind = segment.kind;
293
+ const context: Context = { kind, fence: line, source, lines: new LineCounter(), out };
294
+ if (segment.type === "invalid") {
295
+ let at = line;
296
+ let message = segment.error;
297
+ let hint = "";
298
+ if (isYamlKind(kind)) {
299
+ const found = yamlError(context, segment.error);
300
+ if (found) {
301
+ at = line + found.line;
302
+ message = found.message;
303
+ hint = found.hint;
304
+ }
305
+ } else {
306
+ const inner = sourceLine(context, segment.error);
307
+ if (inner !== undefined) {
308
+ at = line + inner;
309
+ message = segment.error.replace(/^line \d+: /, "");
310
+ }
311
+ }
312
+ out.push({
313
+ kind,
314
+ line: at,
315
+ path: kind,
316
+ message: `the ${kind} block is invalid and is shown as source: ${message}${hint ? `; ${hint}` : ""}`,
317
+ severity: "error",
318
+ });
319
+ } else if (isYamlKind(kind)) {
320
+ checkBody(context);
321
+ } else if (kind === "mermaid" && options.mermaid) {
322
+ const problem = options.mermaid(source);
323
+ if (problem !== undefined) {
324
+ out.push({
325
+ kind,
326
+ line: line + 1,
327
+ path: kind,
328
+ message: `the diagram will not draw: ${problem}`,
329
+ severity: "error",
330
+ });
331
+ }
332
+ }
333
+ if (!closed) {
334
+ out.push({
335
+ kind,
336
+ line,
337
+ path: kind,
338
+ message: `the ${kind} fence is never closed, so the block runs to the end of the file; add a closing fence`,
339
+ severity: "warning",
340
+ });
341
+ }
342
+ }
343
+ return out.sort((a, b) => a.line - b.line);
344
+ }
345
+
346
+ /** The problems as the lines an agent reads: `Block problems in notes.md:` then one `- line N path: message` each. */
347
+ export function formatProblems(name: string, problems: readonly BlockProblem[]): string {
348
+ const lines = problems.map(
349
+ (problem) =>
350
+ `- line ${problem.line} ${problem.path}${problem.severity === "warning" ? " (warning)" : ""}: ${problem.message}`,
351
+ );
352
+ return [`Block problems in ${name}:`, ...lines].join("\n");
353
+ }
package/src/core/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { encodeAnswer } from "./answer.ts";
2
- export { reviewItemName } from "./blocks.ts";
2
+ export { NOTE_FIELD, reviewItemName } from "./blocks.ts";
3
+ export { type BlockProblem, type CheckOptions, checkBlocks, formatProblems } from "./check.ts";
3
4
  export { inline, inlinePlain } from "./inline.ts";
4
5
  export { parse } from "./parse.ts";
5
6
  export { toText } from "./text.ts";
package/src/core/parse.ts CHANGED
@@ -96,21 +96,40 @@ function trimBlankEdges(lines: string[]): string {
96
96
  return lines.slice(start, end).join("\n");
97
97
  }
98
98
 
99
+ /** A segment with the 1-based line of the document where it starts (a block's opening fence); `closed` is false for a fence that never closes. */
100
+ export interface Located {
101
+ segment: Segment;
102
+ line: number;
103
+ closed: boolean;
104
+ /** A fenced block's text between its fences, as converted; empty for prose and alerts. */
105
+ source: string;
106
+ }
107
+
99
108
  /**
100
109
  * Splits a document into its prose and its blocks, in order. A block is a fenced code block whose first
101
110
  * word names a block kind (`form`, `table`, ...), or a GitHub alert; other code, and prose, stay Markdown.
102
111
  * A block whose body does not fit its schema becomes an `invalid` segment that keeps its source and the reason.
103
112
  */
104
113
  export function parse(markdown: string): Segment[] {
114
+ return locate(markdown).map((located) => located.segment);
115
+ }
116
+
117
+ /** `parse` with where each segment starts; `checkBlocks` reports problems by these lines. */
118
+ export function locate(markdown: string): Located[] {
105
119
  const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
106
- const segments: Segment[] = [];
120
+ const segments: Located[] = [];
107
121
  let prose: string[] = [];
122
+ let proseLine = 1;
108
123
  let index = 0;
109
124
  const flush = () => {
110
125
  const text = trimBlankEdges(prose);
111
- if (text !== "") segments.push({ type: "markdown", text });
126
+ if (text !== "") segments.push({ segment: { type: "markdown", text }, line: proseLine, closed: true, source: "" });
112
127
  prose = [];
113
128
  };
129
+ const addProse = (from: number, added: string[]) => {
130
+ if (prose.length === 0) proseLine = from + 1;
131
+ prose.push(...added);
132
+ };
114
133
 
115
134
  let i = 0;
116
135
  while (i < lines.length) {
@@ -124,6 +143,7 @@ export function parse(markdown: string): Segment[] {
124
143
  body.push((lines[end] as string).replace(new RegExp(`^ {0,${indent.length}}`), ""));
125
144
  end++;
126
145
  }
146
+ const closed = end < lines.length;
127
147
  const stop = Math.min(end + 1, lines.length);
128
148
  const kind = (info.trim().split(/\s+/)[0] as string).toLowerCase();
129
149
  if (fenceKinds.has(kind)) {
@@ -135,9 +155,9 @@ export function parse(markdown: string): Segment[] {
135
155
  lines.slice(i, stop).join("\n"),
136
156
  );
137
157
  if (segment.type === "block") index++;
138
- segments.push(segment);
158
+ segments.push({ segment, line: i + 1, closed, source: body.join("\n") });
139
159
  } else {
140
- prose.push(...lines.slice(i, stop));
160
+ addProse(i, lines.slice(i, stop));
141
161
  }
142
162
  i = stop;
143
163
  continue;
@@ -150,15 +170,20 @@ export function parse(markdown: string): Segment[] {
150
170
  const data = alertOf(run);
151
171
  if (data) {
152
172
  flush();
153
- segments.push({ type: "block", kind: "alert", data, raw: run.join("\n"), index: index++ });
173
+ segments.push({
174
+ segment: { type: "block", kind: "alert", data, raw: run.join("\n"), index: index++ },
175
+ line: i + 1,
176
+ closed: true,
177
+ source: "",
178
+ });
154
179
  } else {
155
- prose.push(...run);
180
+ addProse(i, run);
156
181
  }
157
182
  i = end;
158
183
  continue;
159
184
  }
160
185
 
161
- prose.push(line);
186
+ addProse(i, [line]);
162
187
  i++;
163
188
  }
164
189
  flush();
package/src/core/text.ts CHANGED
@@ -46,26 +46,30 @@ interface Replies {
46
46
  /** Followed by the pick sentence, when the review has one. */
47
47
  review: string;
48
48
  pick: (label: string | undefined) => string;
49
+ /** Closes a review reply, which has no fixed sentence of its own. */
50
+ welcome: string;
49
51
  suggest: string;
50
52
  checklist: string;
51
53
  }
52
54
 
53
55
  const REPLIES: Record<TextLang, Replies> = {
54
56
  en: {
55
- options: "Reply with a number.",
56
- form: (example) => `Reply in text, one line per question, like ${example}.`,
57
+ options: "Reply with a number. Other comments are welcome.",
58
+ form: (example) => `Reply in text, one line per question, like ${example}. Other comments are welcome.`,
57
59
  review: "Reply with a comment for each item, naming the item.",
58
60
  pick: (label) => ` Say which one you pick${label === undefined ? "" : ` (${label})`}.`,
61
+ welcome: " Other comments are welcome.",
59
62
  suggest: "You can reply: ",
60
- checklist: "Reply with the items you tick or leave unticked, naming each.",
63
+ checklist: "Reply with the items you tick or leave unticked, naming each. Other comments are welcome.",
61
64
  },
62
65
  "zh-TW": {
63
- options: "請回覆編號。",
64
- form: (example) => `請用文字回覆,每題一行,例如 ${example}。`,
66
+ options: "請回覆編號。也歡迎補充其他意見。",
67
+ form: (example) => `請用文字回覆,每題一行,例如 ${example}。也歡迎補充其他意見。`,
65
68
  review: "請逐項回覆意見,並寫明是哪一項。",
66
69
  pick: (label) => `請說明你選哪一項${label === undefined ? "" : `(${label})`}。`,
70
+ welcome: "也歡迎補充其他意見。",
67
71
  suggest: "可以回覆:",
68
- checklist: "請回覆你勾選或不勾選的項目,逐項寫明。",
72
+ checklist: "請回覆你勾選或不勾選的項目,逐項寫明。也歡迎補充其他意見。",
69
73
  },
70
74
  };
71
75
 
@@ -152,7 +156,7 @@ function review(dialect: Dialect, data: ReviewData): string {
152
156
  ]);
153
157
  const pick = data.pick === undefined ? "" : dialect.say.pick(data.pick === true ? undefined : data.pick);
154
158
  const title = data.title ? [bold(dialect, field(dialect, data.title))] : [];
155
- return [...title, ...lines, "", `${dialect.say.review}${pick}`].join("\n");
159
+ return [...title, ...lines, "", `${dialect.say.review}${pick}${dialect.say.welcome}`].join("\n");
156
160
  }
157
161
 
158
162
  function mindmap(dialect: Dialect, data: MindmapData): string {
@@ -1,4 +1,4 @@
1
- import { optionName, reviewItemName } from "./blocks.ts";
1
+ import { NOTE_FIELD, optionName, reviewItemName } from "./blocks.ts";
2
2
  import type { Answer, AnswerKind, BlockSegment, FormData, QuestionData } from "./types.ts";
3
3
 
4
4
  /** `reason` says what is wrong, for a host's refusal. */
@@ -116,9 +116,20 @@ function problem(block: BlockSegment, answer: Answer): string | undefined {
116
116
  }
117
117
  }
118
118
 
119
+ /** A form question or checklist item named like the reserved note field could not be told from the comments box. */
120
+ function reservedName(block: BlockSegment): string | undefined {
121
+ const clash =
122
+ block.kind === "form"
123
+ ? block.data.questions.some((question) => question.name === NOTE_FIELD)
124
+ : block.kind === "checklist"
125
+ ? block.data.items.some((item) => item.name === NOTE_FIELD)
126
+ : false;
127
+ return clash ? `the name ${quoted(NOTE_FIELD)} is reserved for other comments` : undefined;
128
+ }
129
+
119
130
  /**
120
131
  * Whether an untrusted `answer` fits `block`: its kind is the block's, every field names a question, choice, or item
121
- * of the block, several values appear only for a `multi` form question, required questions are answered, and there
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
122
133
  * are at most 64 fields of 1,024 characters each.
123
134
  */
124
135
  export function validateAnswer(block: BlockSegment, answer: Answer): Validation {
@@ -135,9 +146,14 @@ export function validateAnswer(block: BlockSegment, answer: Answer): Validation
135
146
  const expected = KINDS[block.kind];
136
147
  if (expected === undefined) return fail(`a ${block.kind} block takes no answer`);
137
148
  if (answer.kind !== expected) return fail(`answer kind ${quoted(answer.kind)} does not fit a ${block.kind} block`);
138
- if (answer.fields.length > MAX_FIELDS) return fail(`more than ${MAX_FIELDS} fields`);
149
+ if (answer.fields.filter(([name]) => name !== NOTE_FIELD).length > MAX_FIELDS)
150
+ return fail(`more than ${MAX_FIELDS} fields`);
139
151
  if (answer.fields.some(([name, value]) => name.length > MAX_LENGTH || value.length > MAX_LENGTH))
140
152
  return fail(`a field is longer than ${MAX_LENGTH} characters`);
141
- const found = problem(block, answer);
153
+ const notes = answer.fields.filter(([name]) => name === NOTE_FIELD);
154
+ if (notes.length > 1) return fail("several other comments");
155
+ const reserved = reservedName(block);
156
+ if (reserved) return fail(reserved);
157
+ const found = problem(block, { ...answer, fields: answer.fields.filter(([name]) => name !== NOTE_FIELD) });
142
158
  return found === undefined ? PASS : fail(found);
143
159
  }
@@ -1,8 +1,8 @@
1
- import { optionName } from "../core/blocks.ts";
1
+ import { NOTE_FIELD, optionName } from "../core/blocks.ts";
2
2
  import { inlinePlain } from "../core/inline.ts";
3
3
  import type { ChecklistData, OptionData, OptionsData, SuggestData } from "../core/types.ts";
4
4
  import { define, PbsElement } from "./base.ts";
5
- import { controlCss, fieldOf, sendingForm, sentBadge, submitRow } from "./controls.ts";
5
+ import { controlCss, fieldOf, noteBox, noteField, sendingForm, sentBadge, submitRow } from "./controls.ts";
6
6
  import { h, inlineNodes, prose, uid } from "./dom.ts";
7
7
 
8
8
  /** The elements that answer with a pick or ticks: options, suggest, checklist. */
@@ -15,9 +15,11 @@ import { h, inlineNodes, prose, uid } from "./dom.ts";
15
15
  export class PbsOptions extends PbsElement<OptionsData> {
16
16
  static override css = controlCss;
17
17
  #sent: number | undefined;
18
+ #note = "";
18
19
 
19
20
  protected override reset(): void {
20
21
  this.#sent = undefined;
22
+ this.#note = "";
21
23
  }
22
24
  protected override settled(): void {
23
25
  this.#sent = undefined;
@@ -28,11 +30,12 @@ export class PbsOptions extends PbsElement<OptionsData> {
28
30
  const selected =
29
31
  this.#sent ?? (picked === undefined ? undefined : data.options.findIndex((o, i) => optionName(o, i) === picked));
30
32
  const locked = this.answered !== undefined || this.#sent !== undefined;
33
+ const sentNote = fieldOf(this.answered, NOTE_FIELD) ?? (this.#sent === undefined ? "" : this.#note.trim());
31
34
  const pick = (index: number) => {
32
35
  if (locked) return;
33
36
  const ok = this.answer({
34
37
  kind: "pick",
35
- fields: [["picked", optionName(data.options[index] as OptionData, index)]],
38
+ fields: [["picked", optionName(data.options[index] as OptionData, index)], ...noteField(this.#note)],
36
39
  });
37
40
  if (!ok) return;
38
41
  this.#sent = index;
@@ -40,6 +43,15 @@ export class PbsOptions extends PbsElement<OptionsData> {
40
43
  this.focusIn("[data-selected] button");
41
44
  };
42
45
  return [
46
+ ...(locked
47
+ ? sentNote
48
+ ? [h("p", { part: "sent-note", class: "status" }, `${this.t("otherComments")}: ${sentNote}`)]
49
+ : []
50
+ : [
51
+ noteBox(this.t("otherComments"), this.#note, (text) => {
52
+ this.#note = text;
53
+ }),
54
+ ]),
43
55
  h(
44
56
  "div",
45
57
  { part: "grid", class: "grid", role: "list", "aria-label": this.t("options") },
@@ -153,9 +165,11 @@ export class PbsSuggest extends PbsElement<SuggestData> {
153
165
  export class PbsChecklist extends PbsElement<ChecklistData> {
154
166
  static override css = controlCss;
155
167
  #checked: boolean[] | undefined;
168
+ #note = "";
156
169
 
157
170
  protected override reset(): void {
158
171
  this.#checked = undefined;
172
+ this.#note = "";
159
173
  }
160
174
 
161
175
  protected view(data: ChecklistData): Node {
@@ -203,6 +217,7 @@ export class PbsChecklist extends PbsElement<ChecklistData> {
203
217
  },
204
218
  rows,
205
219
  );
220
+ const sentNote = fieldOf(locked, NOTE_FIELD);
206
221
  if (locked) {
207
222
  return h(
208
223
  "section",
@@ -210,6 +225,7 @@ export class PbsChecklist extends PbsElement<ChecklistData> {
210
225
  h("div", { class: "sent-head" }, title, sentBadge(this.t("submitted"))),
211
226
  group,
212
227
  progress,
228
+ sentNote && h("p", { part: "sent-note", class: "status" }, `${this.t("otherComments")}: ${sentNote}`),
213
229
  );
214
230
  }
215
231
  const { row, status } = submitRow(data.submit ? inlinePlain(data.submit) : this.t("send"));
@@ -218,10 +234,21 @@ export class PbsChecklist extends PbsElement<ChecklistData> {
218
234
  item.name,
219
235
  checked[index] ? "checked" : "unchecked",
220
236
  ]);
237
+ fields.push(...noteField(this.#note));
221
238
  if (this.answer({ kind: "checklist", ...(data.title ? { title: inlinePlain(data.title) } : {}), fields }))
222
239
  status.textContent = this.t("sent");
223
240
  };
224
- return sendingForm(send, { part: "checklist", class: "panel form-panel" }, title, group, progress, row);
241
+ return sendingForm(
242
+ send,
243
+ { part: "checklist", class: "panel form-panel" },
244
+ title,
245
+ group,
246
+ progress,
247
+ noteBox(this.t("otherComments"), this.#note, (text) => {
248
+ this.#note = text;
249
+ }),
250
+ row,
251
+ );
225
252
  }
226
253
  }
227
254
 
@@ -1,3 +1,4 @@
1
+ import { NOTE_FIELD } from "../core/blocks.ts";
1
2
  import type { AnsweredFields } from "./base.ts";
2
3
  import { type Child, h } from "./dom.ts";
3
4
 
@@ -48,6 +49,8 @@ fieldset.question { border: 0; min-width: 0; display: flex; flex-direction: colu
48
49
  .question .req { color: var(--_risk); }
49
50
  .question .hint { color: var(--_muted); font-size: 0.9em; }
50
51
  .question[aria-invalid="true"] .label { color: var(--_risk); }
52
+ .note-field { display: flex; flex-direction: column; gap: 0.3rem; }
53
+ .note-field .label { font-weight: 600; }
51
54
  .sent-head { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
52
55
  `;
53
56
 
@@ -58,6 +61,22 @@ export function submitRow(label: string): { row: HTMLElement; button: HTMLButton
58
61
  return { row: h("div", { part: "actions", class: "row" }, button, status), button, status };
59
62
  }
60
63
 
64
+ /** The fixed "Other comments" box above a submit button: its text is sent as the reserved `note` field when not blank. */
65
+ export function noteBox(label: string, value: string, onInput: (text: string) => void): HTMLElement {
66
+ const box = h("textarea", {
67
+ part: "note",
68
+ class: "note-box",
69
+ maxlength: 1024,
70
+ rows: 2,
71
+ value,
72
+ });
73
+ box.addEventListener("input", () => onInput(box.value));
74
+ return h("label", { part: "note-field", class: "note-field" }, h("span", { class: "label" }, label), box);
75
+ }
76
+
77
+ /** The reserved field for a note, or nothing when blank. */
78
+ export const noteField = (text: string): [string, string][] => (text.trim() ? [[NOTE_FIELD, text.trim()]] : []);
79
+
61
80
  /** A form wrapper that submits through `onSend`, from the button, Enter in a one-line box, or Ctrl/Cmd+Enter anywhere inside. */
62
81
  export function sendingForm(onSend: () => void, props: Record<string, string>, ...children: Child[]): HTMLFormElement {
63
82
  const form = h("form", { novalidate: true, ...props }, ...children);
@@ -1,7 +1,8 @@
1
+ import { NOTE_FIELD } from "../core/blocks.ts";
1
2
  import { inlinePlain } from "../core/inline.ts";
2
3
  import type { FormData, QuestionData } from "../core/types.ts";
3
4
  import { define, PbsElement } from "./base.ts";
4
- import { controlCss, fieldOf, sendingForm, sentBadge, submitRow } from "./controls.ts";
5
+ import { controlCss, fieldOf, noteBox, noteField, sendingForm, sentBadge, submitRow } from "./controls.ts";
5
6
  import { type Child, h, inlineNodes, uid } from "./dom.ts";
6
7
 
7
8
  /** What the agent reads for a question left empty; kept in English whatever the element's language, as pi-herdr-doc-review did. */
@@ -32,9 +33,11 @@ function answerOf(question: QuestionData, entry: Entry): string {
32
33
  export class PbsForm extends PbsElement<FormData> {
33
34
  static override css = controlCss;
34
35
  #entries: Entry[] | undefined;
36
+ #note = "";
35
37
 
36
38
  protected override reset(): void {
37
39
  this.#entries = undefined;
40
+ this.#note = "";
38
41
  }
39
42
 
40
43
  protected view(data: FormData): Node {
@@ -79,6 +82,7 @@ export class PbsForm extends PbsElement<FormData> {
79
82
  question.name,
80
83
  answerOf(question, entries[index] as Entry) || NO_ANSWER,
81
84
  ]);
85
+ fields.push(...noteField(this.#note));
82
86
  if (data.title) fields.unshift(["form", inlinePlain(data.title)]);
83
87
  const delivered = this.answer({
84
88
  kind: "form",
@@ -92,6 +96,9 @@ export class PbsForm extends PbsElement<FormData> {
92
96
  { part: "form", class: "panel form-panel", ...(data.title ? { "aria-label": inlinePlain(data.title) } : {}) },
93
97
  title,
94
98
  questions,
99
+ noteBox(this.t("otherComments"), this.#note, (text) => {
100
+ this.#note = text;
101
+ }),
95
102
  error,
96
103
  row,
97
104
  );
@@ -225,7 +232,7 @@ export class PbsForm extends PbsElement<FormData> {
225
232
  }),
226
233
  ...sent
227
234
  .filter(([name]) => name !== "form" && !known.has(name))
228
- .map(([name, value]): [string, string] => [name, value]),
235
+ .map(([name, value]): [string, string] => [name === NOTE_FIELD ? this.t("otherComments") : name, value]),
229
236
  ];
230
237
  return h(
231
238
  "section",
@@ -1,9 +1,9 @@
1
- import { reviewItemName } from "../core/blocks.ts";
1
+ import { NOTE_FIELD, reviewItemName } from "../core/blocks.ts";
2
2
  import { inlinePlain } from "../core/inline.ts";
3
3
  import type { ReviewData, ReviewItemData } from "../core/types.ts";
4
4
  import { type AnsweredFields, define, PbsElement } from "./base.ts";
5
5
  import { configuration } from "./config.ts";
6
- import { controlCss, sendingForm, sentBadge, submitRow } from "./controls.ts";
6
+ import { controlCss, noteBox, noteField, sendingForm, sentBadge, submitRow } from "./controls.ts";
7
7
  import { type Child, h, inlineNodes, prose, uid } from "./dom.ts";
8
8
 
9
9
  const reviewCss = `${controlCss}
@@ -36,11 +36,13 @@ export class PbsReview extends PbsElement<ReviewData> {
36
36
  static override css = reviewCss;
37
37
  #picked: string | undefined;
38
38
  #comments: string[] | undefined;
39
+ #note = "";
39
40
  readonly #group = uid("pbs-pick");
40
41
 
41
42
  protected override reset(): void {
42
43
  this.#picked = undefined;
43
44
  this.#comments = undefined;
45
+ this.#note = "";
44
46
  }
45
47
 
46
48
  protected view(data: ReviewData): Node {
@@ -71,10 +73,20 @@ export class PbsReview extends PbsElement<ReviewData> {
71
73
  });
72
74
  const silent = named.filter((_, index) => !(comments[index] as string).trim());
73
75
  if (silent.length > 0) fields.push(["silent", silent.join(", ")]);
76
+ fields.push(...noteField(this.#note));
74
77
  if (this.answer({ kind: "review", ...(data.title ? { title: inlinePlain(data.title) } : {}), fields }))
75
78
  status.textContent = this.t("sent");
76
79
  };
77
- return sendingForm(send, { part: "review", class: "panel form-panel review" }, title, grid, row);
80
+ return sendingForm(
81
+ send,
82
+ { part: "review", class: "panel form-panel review" },
83
+ title,
84
+ grid,
85
+ noteBox(this.t("otherComments"), this.#note, (text) => {
86
+ this.#note = text;
87
+ }),
88
+ row,
89
+ );
78
90
  }
79
91
 
80
92
  private item(item: ReviewItemData, index: number, pickLabel: string | undefined, comments: string[]): HTMLElement {
@@ -168,6 +180,7 @@ export class PbsReview extends PbsElement<ReviewData> {
168
180
  const comments = values("comment");
169
181
  const [picked] = values("picked");
170
182
  const [silent] = values("silent");
183
+ const [note] = values(NOTE_FIELD);
171
184
  const row = (label: string, value: string) => h("div", null, h("dt", null, label), h("dd", null, value));
172
185
  return h(
173
186
  "section",
@@ -179,6 +192,7 @@ export class PbsReview extends PbsElement<ReviewData> {
179
192
  picked && row(this.t("picked"), picked),
180
193
  items.map((item, index) => row(item, comments[index] ?? "")),
181
194
  silent && row(this.t("noFeedback"), silent),
195
+ note && row(this.t("otherComments"), note),
182
196
  ),
183
197
  );
184
198
  }
@@ -13,6 +13,7 @@ export interface Strings {
13
13
  unanswered: string;
14
14
  other: string;
15
15
  feedbackNote: string;
16
+ otherComments: string;
16
17
  noFeedback: string;
17
18
  reviewFallback: string;
18
19
  enlarge: string;
@@ -65,6 +66,7 @@ export const STRINGS: Record<Locale, Strings> = {
65
66
  unanswered: "Not answered yet: ",
66
67
  other: "Other (type your own)",
67
68
  feedbackNote: "Feedback (leave blank for none)",
69
+ otherComments: "Other comments",
68
70
  noFeedback: "No feedback",
69
71
  reviewFallback: "Review",
70
72
  enlarge: "Enlarge",
@@ -114,6 +116,7 @@ export const STRINGS: Record<Locale, Strings> = {
114
116
  unanswered: "還沒回答:",
115
117
  other: "其他(自行填寫)",
116
118
  feedbackNote: "回饋(留白代表沒意見)",
119
+ otherComments: "其他意見",
117
120
  noFeedback: "沒有意見",
118
121
  reviewFallback: "回饋",
119
122
  enlarge: "放大",
@@ -0,0 +1,35 @@
1
+ import { BLOCK_KINDS } from "../core/types.ts";
2
+
3
+ /**
4
+ * The block check for the agent: what is wrong with the blocks of a Markdown file, as the text `show_doc` and the
5
+ * write hook hand back. Nothing here loads at import: the checker (and with it the YAML parser) loads on the first
6
+ * file that holds a block fence, and Mermaid on the first file that holds a diagram.
7
+ */
8
+
9
+ const KINDS = BLOCK_KINDS.filter((kind) => kind !== "alert");
10
+ const BLOCK_FENCE = new RegExp(`^ {0,3}(?:\`{3,}|~{3,})[ \\t]*(?:${KINDS.join("|")})\\b`, "im");
11
+ const MERMAID_FENCE = /^ {0,3}(?:`{3,}|~{3,})[ \t]*mermaid\b/im;
12
+
13
+ export const hasBlockFence = (markdown: string): boolean => BLOCK_FENCE.test(markdown);
14
+
15
+ /** The problems of `markdown` worded for the agent, or undefined when there are none or the file holds no block fence. */
16
+ export async function checkText(name: string, markdown: string): Promise<string | undefined> {
17
+ if (!hasBlockFence(markdown)) return undefined;
18
+ const { checkBlocks, formatProblems } = await import("../core/check.ts");
19
+ const mermaid = MERMAID_FENCE.test(markdown) ? (await import("../server/index.ts")).mermaidSvg : undefined;
20
+ const problems = checkBlocks(markdown, {
21
+ ...(mermaid
22
+ ? {
23
+ mermaid: (source: string) => {
24
+ try {
25
+ mermaid(source);
26
+ return undefined;
27
+ } catch (error) {
28
+ return ((error instanceof Error ? error.message : String(error)).split("\n")[0] as string).trim();
29
+ }
30
+ },
31
+ }
32
+ : {}),
33
+ });
34
+ return problems.length === 0 ? undefined : formatProblems(name, problems);
35
+ }
@@ -15,6 +15,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:pat
15
15
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
16
16
  import { encodeAnswer } from "../core/answer.ts";
17
17
  import type { Answer } from "../core/types.ts";
18
+ import { checkText } from "./check.ts";
18
19
  import {
19
20
  ANSWER_EVENT,
20
21
  ANSWER_RESULT_EVENT,
@@ -319,13 +320,35 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
319
320
  return fromHome.startsWith("..") || isAbsolute(fromHome) ? basename(absolute) : join("~", fromHome);
320
321
  };
321
322
 
323
+ const nameFor = (cwd: string, absolute: string): string => {
324
+ const rel = relative(deps.realpath(cwd), absolute);
325
+ return rel.startsWith("..") ? outside(absolute) : rel;
326
+ };
327
+
322
328
  const load = (cwd: string, path: string): Loaded => {
323
329
  if (/[\n\r]/.test(path)) throw new Error(`cannot open a path containing a line break: ${JSON.stringify(path)}`);
324
330
  const absolute = deps.realpath(isAbsolute(path) ? path : resolve(cwd, path));
325
331
  const content = deps.readFile(absolute);
326
332
  if (content === undefined) throw new Error(`cannot read ${path}`);
327
- const rel = relative(deps.realpath(cwd), absolute);
328
- return { absolute, content, display: rel.startsWith("..") ? outside(absolute) : rel };
333
+ return { absolute, content, display: nameFor(cwd, absolute) };
334
+ };
335
+
336
+ /** What is wrong with the blocks of a Markdown text, worded for the agent; a failure of the check itself is reported, not hidden. */
337
+ const problemsIn = async (display: string, content: string): Promise<string | undefined> => {
338
+ try {
339
+ return await checkText(display, content);
340
+ } catch (error) {
341
+ return `Block check of ${display} failed: ${(error as Error).message}`;
342
+ }
343
+ };
344
+
345
+ /** The block problems of a Markdown file the agent just wrote, or undefined. */
346
+ const problemsOfFile = async (cwd: string, absolute: string): Promise<string | undefined> => {
347
+ if (!MARKDOWN_FILE.test(absolute)) return undefined;
348
+ const content = deps.readFile(absolute);
349
+ return content === undefined
350
+ ? undefined
351
+ : problemsIn(docs.get(absolute)?.display ?? nameFor(cwd, absolute), content);
329
352
  };
330
353
 
331
354
  /** Opens pages in the default browser; a page whose tab the user closed opens again. */
@@ -396,9 +419,15 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
396
419
  opened.push(`${list(texts)} in ${editor}`);
397
420
  }
398
421
  const feedback = texts.length > 0 ? " Their saved edits will reach you as review feedback." : "";
422
+ const checks = (
423
+ await Promise.all(
424
+ loaded.filter((doc) => MARKDOWN_FILE.test(doc.absolute)).map((doc) => problemsIn(doc.display, doc.content)),
425
+ )
426
+ ).filter((found): found is string => found !== undefined);
427
+ const problems = checks.map((found) => `\n\n${found}`).join("");
399
428
  return {
400
429
  opened: loaded.map((doc) => doc.display),
401
- text: `Opened ${opened.join(" and ")} and returned without waiting for the user.${feedback}`,
430
+ text: `Opened ${opened.join(" and ")} and returned without waiting for the user.${feedback}${problems}`,
402
431
  };
403
432
  };
404
433
 
@@ -445,6 +474,7 @@ export function createBetterShow(pi: ExtensionAPI, deps: Deps = defaultDeps()) {
445
474
 
446
475
  return {
447
476
  show,
477
+ problemsOfFile,
448
478
  docs,
449
479
  pages,
450
480
  edits,
@@ -55,9 +55,16 @@ export function install(pi: ExtensionAPI, deps: Deps = defaultDeps()): BetterSho
55
55
  const path = pathOf(ctx.cwd, event.input);
56
56
  if (!path) return;
57
57
  show.agentWrote(event.toolCallId, path);
58
- if (event.isError || !ctx.hasUI || process.env[AUTO_OPEN_ENV] === "off") return;
58
+ if (event.isError) return;
59
+ // The agent reads the block problems of what it just wrote in the result of the write itself.
60
+ const found = await show.problemsOfFile(ctx.cwd, path);
61
+ const amended =
62
+ found === undefined
63
+ ? undefined
64
+ : { content: [...event.content, { type: "text" as const, text: `\n\n${found}` }] };
65
+ if (!ctx.hasUI || process.env[AUTO_OPEN_ENV] === "off") return amended;
59
66
  const followUp = show.miniSddFollowUp(path);
60
- if (followUp.length === 0) return;
67
+ if (followUp.length === 0) return amended;
61
68
  try {
62
69
  await show.show(
63
70
  ctx.cwd,
@@ -68,6 +75,7 @@ export function install(pi: ExtensionAPI, deps: Deps = defaultDeps()): BetterSho
68
75
  } catch (error) {
69
76
  ctx.ui.notify(`better-show could not open ${path}: ${(error as Error).message}`, "warning");
70
77
  }
78
+ return amended;
71
79
  });
72
80
 
73
81
  const stopAnswers = pi.events.on(ANSWER_EVENT, show.onAnswer);
@@ -25,7 +25,8 @@ export const DESCRIPTION =
25
25
  "Put decisions that belong to the page (several questions, or a choice after a comparison) in a ```form at its end; ask a single short question with your question tool. " +
26
26
  'An .html page runs as written under a sandbox (scripts and forms, no storage, nothing from other sites): a <form action="cgi-bin:pi-answer"> sends its fields to you when submitted, and piBetterShow.send(fields) does the same from a script. ' +
27
27
  'When a page needs interaction (inputs that recompute, tabs, filters), write a .tsx or .jsx file and open it with view "page": React is built in, and the "pi-kit" module exports PbsBlock, PbsForm, PbsOptions, PbsReview, PbsChecklist, PbsTable, PbsCallout, PbsCards, PbsMindmap, PbsSuggest, PbsSteps, PbsStats, PbsDiff, PbsDiagram, PbsTree (props data, onAnswer; PbsBlock draws a parsed block), parse, encodeAnswer, and send(answer or fields) to hand you any values as a message. Import sibling modules freely; import no CSS. ' +
28
- "It returns at once without waiting for the user. Pages reload and edited documents refresh when you change them.";
28
+ 'It returns at once without waiting for the user. Block problems (a block that will not parse, a text value cut at " #", an unknown key) come back with line numbers in its result and in the result of your write or edit of a .md file; quote text values that hold " #" or ": ". ' +
29
+ "Pages reload and edited documents refresh when you change them.";
29
30
 
30
31
  export const parameters = Type.Object({
31
32
  paths: Type.Array(Type.String({ description: "File path, absolute or relative to the working directory" }), {