pi-better-show 0.1.2 → 0.3.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
@@ -53,9 +53,15 @@ interface TextProfile {
53
53
  flavor: "discord" | "line" | "plain"; // Discord Markdown, or plain text
54
54
  width?: number; // columns a diagram may take; default 60
55
55
  mermaid?: (source: string, width: number) => string | undefined;
56
+ keep?: readonly BlockKind[]; // kinds emitted as their `raw` text instead of converted
57
+ lang?: "en" | "zh-TW"; // language of the reply instructions; default "en", anything else is "en"
56
58
  }
57
59
  ```
58
60
 
61
+ The interactive kinds end with a reply instruction (`options`, `form`, `review`, `suggest`, and `checklist`): "Reply with a number.", "Reply in text, one line per question, like `1: b`.", and so on. `lang: "zh-TW"` writes them in Traditional Chinese; pass the conversation's language when you know it. Block content is never translated.
62
+
63
+ Every `BlockSegment` and `InvalidSegment` carries `raw`: the block's exact original text, fences (or an alert's whole `>` quote) included, byte for byte. Kinds listed in `keep` are emitted as `raw` verbatim, valid or invalid, for a surface that draws them itself; other kinds convert as usual. `DISPLAY_KINDS` (`alert`, `cards`, `mermaid`, `mindmap`, `diff`, `table`, `steps`, `stats`) is the usual `keep` list for such a surface; `INTERACTIVE_KINDS` (`options`, `suggest`, `form`, `checklist`, `review`) are the kinds a reader answers, the ones a surface that cannot draw them gets as reply instructions. Without `keep`, output is unchanged.
64
+
59
65
  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
66
 
61
67
  ```ts
@@ -84,6 +90,14 @@ encodeAnswer(answer: Answer): string
84
90
  | `suggest` | `[["text", text]]` | the text itself |
85
91
  | `checklist` | one `[name, "checked" \| "unchecked"]` per item | `User updated the checklist "title":` then `☑`/`☐` lines |
86
92
 
93
+ ```ts
94
+ validateAnswer(block: BlockSegment, answer: Answer): { ok: true } | { ok: false; reason: string }
95
+ ```
96
+
97
+ `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.
98
+
99
+ **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.
100
+
87
101
  ## Server API
88
102
 
89
103
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-show",
3
- "version": "0.1.2",
3
+ "version": "0.3.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 { inlinePlain } from "./inline.ts";
1
2
  import { entryOf, itemsOf, list, mappingOf, oneOf, positiveNumber, recommended, record, text } from "./normalize.ts";
2
3
  import type {
3
4
  CardsData,
@@ -112,6 +113,10 @@ export function reviewNames(names: (string | undefined)[]): string[] {
112
113
  export const reviewItemName = (item: { name: string; label?: string }): string =>
113
114
  item.label ? `${item.name} (${item.label})` : item.name;
114
115
 
116
+ /** The name an option answers with: its plain title, else its 1-based number. */
117
+ export const optionName = (option: { title?: string }, index: number): string =>
118
+ option.title ? inlinePlain(option.title) : String(index + 1);
119
+
115
120
  export function review(data: unknown): ReviewData {
116
121
  const raw = mappingOf(data);
117
122
  const entries = itemsOf(data, "items").map((entry) => entryOf(entry, "image", "item"));
package/src/core/index.ts CHANGED
@@ -4,4 +4,5 @@ export { inline, inlinePlain } from "./inline.ts";
4
4
  export { parse } from "./parse.ts";
5
5
  export { toText } from "./text.ts";
6
6
  export * from "./types.ts";
7
+ export { type Validation, validateAnswer } from "./validate.ts";
7
8
  export { displayWidth } from "./width.ts";
package/src/core/parse.ts CHANGED
@@ -55,12 +55,17 @@ const CONVERTERS: { [K in Exclude<BlockKind, "alert">]: Convert<K> } = {
55
55
  const messageOf = (error: unknown): string =>
56
56
  ((error instanceof Error ? error.message : String(error)).split("\n")[0] as string).replace(/:$/, "");
57
57
 
58
- function convert(kind: Exclude<BlockKind, "alert">, source: string, index: number): BlockSegment | InvalidSegment {
58
+ function convert(
59
+ kind: Exclude<BlockKind, "alert">,
60
+ source: string,
61
+ index: number,
62
+ raw: string,
63
+ ): BlockSegment | InvalidSegment {
59
64
  try {
60
65
  const data = (CONVERTERS[kind] as Convert<BlockKind>)(source);
61
- return { type: "block", kind, data, index } as BlockSegment;
66
+ return { type: "block", kind, data, raw, index } as BlockSegment;
62
67
  } catch (error) {
63
- return { type: "invalid", kind, source, error: messageOf(error) };
68
+ return { type: "invalid", kind, source, raw, error: messageOf(error) };
64
69
  }
65
70
  }
66
71
 
@@ -121,7 +126,12 @@ export function parse(markdown: string): Segment[] {
121
126
  const kind = (info.trim().split(/\s+/)[0] as string).toLowerCase();
122
127
  if (fenceKinds.has(kind)) {
123
128
  flush();
124
- const segment = convert(kind as Exclude<BlockKind, "alert">, body.join("\n"), index);
129
+ const segment = convert(
130
+ kind as Exclude<BlockKind, "alert">,
131
+ body.join("\n"),
132
+ index,
133
+ lines.slice(i, stop).join("\n"),
134
+ );
125
135
  if (segment.type === "block") index++;
126
136
  segments.push(segment);
127
137
  } else {
@@ -138,7 +148,7 @@ export function parse(markdown: string): Segment[] {
138
148
  const data = alertOf(run);
139
149
  if (data) {
140
150
  flush();
141
- segments.push({ type: "block", kind: "alert", data, index: index++ });
151
+ segments.push({ type: "block", kind: "alert", data, raw: run.join("\n"), index: index++ });
142
152
  } else {
143
153
  prose.push(...run);
144
154
  }
package/src/core/text.ts CHANGED
@@ -19,6 +19,7 @@ import type {
19
19
  StepsData,
20
20
  SuggestData,
21
21
  TableData,
22
+ TextLang,
22
23
  TextProfile,
23
24
  } from "./types.ts";
24
25
  import { displayWidth } from "./width.ts";
@@ -32,8 +33,40 @@ interface Dialect {
32
33
  markdown: boolean;
33
34
  width: number;
34
35
  mermaid: TextProfile["mermaid"];
36
+ say: Replies;
35
37
  }
36
38
 
39
+ /** The reply instructions of the interactive kinds. */
40
+ interface Replies {
41
+ options: string;
42
+ /** Followed by an example, `1: b`. */
43
+ form: (example: string) => string;
44
+ /** Followed by the pick sentence, when the review has one. */
45
+ review: string;
46
+ pick: (label: string | undefined) => string;
47
+ suggest: string;
48
+ checklist: string;
49
+ }
50
+
51
+ const REPLIES: Record<TextLang, Replies> = {
52
+ en: {
53
+ options: "Reply with a number.",
54
+ form: (example) => `Reply in text, one line per question, like ${example}.`,
55
+ review: "Reply with a comment for each item, naming the item.",
56
+ pick: (label) => ` Say which one you pick${label === undefined ? "" : ` (${label})`}.`,
57
+ suggest: "You can reply: ",
58
+ checklist: "Reply with the items you tick or leave unticked, naming each.",
59
+ },
60
+ "zh-TW": {
61
+ options: "請回覆編號。",
62
+ form: (example) => `請用文字回覆,每題一行,例如 ${example}。`,
63
+ review: "請逐項回覆意見,並寫明是哪一項。",
64
+ pick: (label) => `請說明你選哪一項${label === undefined ? "" : `(${label})`}。`,
65
+ suggest: "可以回覆:",
66
+ checklist: "請回覆你勾選或不勾選的項目,逐項寫明。",
67
+ },
68
+ };
69
+
37
70
  const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim();
38
71
  const letter = (index: number): string => (index < 26 ? String.fromCharCode(97 + index) : String(index + 1));
39
72
  const star = (recommended: Recommended | undefined): string =>
@@ -87,7 +120,7 @@ function options(dialect: Dialect, data: OptionsData): string {
87
120
  ...option.cons.map((con) => ` − ${oneLine(field(dialect, con))}`),
88
121
  ];
89
122
  });
90
- return [...lines, "", "Reply with a number."].join("\n");
123
+ return [...lines, "", dialect.say.options].join("\n");
91
124
  }
92
125
 
93
126
  function form(dialect: Dialect, data: FormData): string {
@@ -106,7 +139,7 @@ function form(dialect: Dialect, data: FormData): string {
106
139
  });
107
140
  const title = data.title ? [bold(dialect, field(dialect, data.title))] : [];
108
141
  const example = dialect.markdown ? "`1: b`" : "1: b";
109
- return [...title, ...lines, "", `Reply in text, one line per question, like ${example}.`].join("\n");
142
+ return [...title, ...lines, "", dialect.say.form(example)].join("\n");
110
143
  }
111
144
 
112
145
  function review(dialect: Dialect, data: ReviewData): string {
@@ -115,9 +148,9 @@ function review(dialect: Dialect, data: ReviewData): string {
115
148
  ...(item.image ? [` image: ${item.image}`] : []),
116
149
  ...(item.page ? [` page: ${item.page}`] : []),
117
150
  ]);
118
- const pick = data.pick === undefined ? "" : ` Say which one you pick${data.pick === true ? "" : ` (${data.pick})`}.`;
151
+ const pick = data.pick === undefined ? "" : dialect.say.pick(data.pick === true ? undefined : data.pick);
119
152
  const title = data.title ? [bold(dialect, field(dialect, data.title))] : [];
120
- return [...title, ...lines, "", `Reply with a comment for each item, naming the item.${pick}`].join("\n");
153
+ return [...title, ...lines, "", `${dialect.say.review}${pick}`].join("\n");
121
154
  }
122
155
 
123
156
  function mindmap(dialect: Dialect, data: MindmapData): string {
@@ -132,7 +165,7 @@ function mindmap(dialect: Dialect, data: MindmapData): string {
132
165
 
133
166
  function suggest(dialect: Dialect, data: SuggestData): string {
134
167
  if (data.items.length === 0) return "";
135
- return `You can reply: ${data.items.map((item) => field(dialect, item.label)).join(" | ")}`;
168
+ return `${dialect.say.suggest}${data.items.map((item) => field(dialect, item.label)).join(" | ")}`;
136
169
  }
137
170
 
138
171
  function checklist(dialect: Dialect, data: ChecklistData): string {
@@ -143,6 +176,8 @@ function checklist(dialect: Dialect, data: ChecklistData): string {
143
176
  (item) =>
144
177
  `${item.checked ? "☑" : "☐"} ${joined(dialect, field(dialect, item.label), item.note && oneLine(field(dialect, item.note)))}`,
145
178
  ),
179
+ "",
180
+ dialect.say.checklist,
146
181
  ].join("\n");
147
182
  }
148
183
 
@@ -271,9 +306,12 @@ export function toText(segments: Segment[], profile: TextProfile): string {
271
306
  markdown: profile.flavor === "discord",
272
307
  width: profile.width ?? DEFAULT_WIDTH,
273
308
  mermaid: profile.mermaid,
309
+ say: REPLIES[profile.lang === "zh-TW" ? "zh-TW" : "en"],
274
310
  };
311
+ const keep = new Set<string>(profile.keep ?? []);
275
312
  return segments
276
313
  .map((segment) => {
314
+ if (segment.type !== "markdown" && keep.has(segment.kind)) return segment.raw;
277
315
  if (segment.type === "markdown") return dialect.markdown ? segment.text : plainProse(segment.text);
278
316
  if (segment.type === "invalid") return invalid(dialect, segment);
279
317
  return block(dialect, segment);
package/src/core/types.ts CHANGED
@@ -191,6 +191,8 @@ export type BlockSegment = {
191
191
  type: "block";
192
192
  kind: K;
193
193
  data: BlockDataMap[K];
194
+ /** The block's exact original text, fences (or an alert's whole `>` quote) included. */
195
+ raw: string;
194
196
  /** Counts the document's blocks of every kind from 0, in order; invalid blocks take no number. */
195
197
  index: number;
196
198
  };
@@ -200,6 +202,8 @@ export interface InvalidSegment {
200
202
  kind: BlockKind;
201
203
  /** The block's text between its fences (an alert's whole quote). */
202
204
  source: string;
205
+ /** The block's exact original text, fences (or an alert's whole `>` quote) included. */
206
+ raw: string;
203
207
  error: string;
204
208
  }
205
209
  export type Segment = MarkdownSegment | BlockSegment | InvalidSegment;
@@ -227,4 +231,16 @@ export interface TextProfile {
227
231
  width?: number;
228
232
  /** Draws a diagram as text, or returns undefined when it cannot (invalid, or wider than `width`). */
229
233
  mermaid?: (source: string, width: number) => string | undefined;
234
+ /** Kinds whose blocks (valid or invalid) are emitted as their `raw` text, for a surface that draws them itself. */
235
+ keep?: readonly BlockKind[];
236
+ /** Language of the reply instructions: `en` (default) or `zh-TW`; anything else is `en`. */
237
+ lang?: TextLang;
230
238
  }
239
+
240
+ export type TextLang = "en" | "zh-TW";
241
+
242
+ /** The kinds a display surface (a chat UI that draws blocks itself) typically keeps through `toText`. */
243
+ export const DISPLAY_KINDS = ["alert", "cards", "mermaid", "mindmap", "diff", "table", "steps", "stats"] as const;
244
+
245
+ /** The kinds a reader answers; a surface that cannot draw them gets their reply instructions from `toText`. */
246
+ export const INTERACTIVE_KINDS = ["options", "suggest", "form", "checklist", "review"] as const;
@@ -0,0 +1,133 @@
1
+ import { optionName, reviewItemName } from "./blocks.ts";
2
+ import type { Answer, AnswerKind, BlockSegment, FormData, QuestionData } from "./types.ts";
3
+
4
+ /** `reason` says what is wrong, for a host's refusal. */
5
+ export type Validation = { ok: true } | { ok: false; reason: string };
6
+
7
+ const MAX_FIELDS = 64;
8
+ const MAX_LENGTH = 1024;
9
+ /** What the form element writes for a question left empty. */
10
+ const NO_ANSWER = "(no answer)";
11
+
12
+ const KINDS: Partial<Record<BlockSegment["kind"], AnswerKind>> = {
13
+ options: "pick",
14
+ suggest: "suggest",
15
+ form: "form",
16
+ checklist: "checklist",
17
+ review: "review",
18
+ };
19
+
20
+ const fail = (reason: string): Validation => ({ ok: false, reason });
21
+ const PASS: Validation = { ok: true };
22
+ const quoted = (text: string): string => JSON.stringify(text.length > 40 ? `${text.slice(0, 40)}…` : text);
23
+
24
+ type Fields = Answer["fields"];
25
+
26
+ const valuesOf = (fields: Fields, name: string): string[] =>
27
+ fields.filter(([key]) => key === name).map(([, value]) => value);
28
+
29
+ /** A choice question's value is a choice's value, or the joined list the form element sends; free text only where `other` allows. */
30
+ function choiceProblem(question: QuestionData, value: string): string | undefined {
31
+ if (question.other !== false || value === NO_ANSWER) return undefined;
32
+ const known = new Set(question.choices.map((choice) => choice.value));
33
+ if (known.has(value)) return undefined;
34
+ const parts = question.type === "multi" ? value.split(", ") : [value];
35
+ const unknown = parts.find((part) => !known.has(part));
36
+ return unknown === undefined ? undefined : `unknown choice ${quoted(unknown)} for question ${quoted(question.name)}`;
37
+ }
38
+
39
+ function formProblem(data: FormData, fields: Fields): string | undefined {
40
+ const questions = new Map(data.questions.map((question) => [question.name, question]));
41
+ const seen = new Set<string>();
42
+ for (const [name, value] of fields) {
43
+ if (name === "form") continue;
44
+ const question = questions.get(name);
45
+ if (!question) return `unknown question ${quoted(name)}`;
46
+ if (seen.has(name) && question.type !== "multi")
47
+ return `several values for ${quoted(name)}, which is not a multi question`;
48
+ seen.add(name);
49
+ if (question.type !== "text") {
50
+ const problem = choiceProblem(question, value);
51
+ if (problem) return problem;
52
+ }
53
+ }
54
+ const missing = data.questions.find(
55
+ (question) =>
56
+ question.required && !valuesOf(fields, question.name).some((value) => value.trim() !== "" && value !== NO_ANSWER),
57
+ );
58
+ return missing ? `required question ${quoted(missing.name)} is not answered` : undefined;
59
+ }
60
+
61
+ function reviewProblem(block: Extract<BlockSegment, { kind: "review" }>, fields: Fields): string | undefined {
62
+ const names = block.data.items.map(reviewItemName);
63
+ const known = new Set(names);
64
+ for (const [name, value] of fields) {
65
+ if (name === "title" || name === "comment") continue;
66
+ if (name === "picked") {
67
+ if (block.data.pick === undefined) return "this review has no pick";
68
+ if (!known.has(value)) return `unknown item ${quoted(value)}`;
69
+ } else if (name === "item") {
70
+ if (!known.has(value)) return `unknown item ${quoted(value)}`;
71
+ } else if (name === "silent") {
72
+ const unknown = known.has(value) ? undefined : value.split(", ").find((part) => !known.has(part));
73
+ if (unknown !== undefined) return `unknown item ${quoted(unknown)}`;
74
+ } else return `unknown field ${quoted(name)}`;
75
+ }
76
+ if (valuesOf(fields, "picked").length > 1) return "only one item can be picked";
77
+ if (valuesOf(fields, "title").length > 1) return "several titles";
78
+ if (valuesOf(fields, "comment").length > valuesOf(fields, "item").length) return "a comment without an item";
79
+ const items = valuesOf(fields, "item");
80
+ if (new Set(items).size !== items.length) return "an item is named twice";
81
+ return undefined;
82
+ }
83
+
84
+ function problem(block: BlockSegment, answer: Answer): string | undefined {
85
+ const { fields } = answer;
86
+ switch (block.kind) {
87
+ case "options": {
88
+ if (fields.length !== 1 || fields[0]?.[0] !== "picked") return "a pick carries exactly one picked field";
89
+ const picked = fields[0][1];
90
+ return block.data.options.some((option, index) => optionName(option, index) === picked)
91
+ ? undefined
92
+ : `unknown option ${quoted(picked)}`;
93
+ }
94
+ case "suggest": {
95
+ if (fields.length !== 1 || fields[0]?.[0] !== "text") return "a suggestion carries exactly one text field";
96
+ const text = fields[0][1];
97
+ return block.data.items.some((item) => item.text === text) ? undefined : `unknown suggestion ${quoted(text)}`;
98
+ }
99
+ case "form":
100
+ return formProblem(block.data, fields);
101
+ case "review":
102
+ return reviewProblem(block, fields);
103
+ case "checklist": {
104
+ const names = new Set(block.data.items.map((item) => item.name));
105
+ const seen = new Set<string>();
106
+ for (const [name, state] of fields) {
107
+ if (!names.has(name)) return `unknown item ${quoted(name)}`;
108
+ if (seen.has(name)) return `item ${quoted(name)} appears twice`;
109
+ seen.add(name);
110
+ if (state !== "checked" && state !== "unchecked") return `unknown mark ${quoted(state)}`;
111
+ }
112
+ return undefined;
113
+ }
114
+ default:
115
+ return `a ${block.kind} block takes no answer`;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * 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
122
+ * are at most 64 fields of 1,024 characters each.
123
+ */
124
+ export function validateAnswer(block: BlockSegment, answer: Answer): Validation {
125
+ const expected = KINDS[block.kind];
126
+ if (expected === undefined) return fail(`a ${block.kind} block takes no answer`);
127
+ if (answer.kind !== expected) return fail(`answer kind ${quoted(answer.kind)} does not fit a ${block.kind} block`);
128
+ if (answer.fields.length > MAX_FIELDS) return fail(`more than ${MAX_FIELDS} fields`);
129
+ if (answer.fields.some(([name, value]) => name.length > MAX_LENGTH || value.length > MAX_LENGTH))
130
+ return fail(`a field is longer than ${MAX_LENGTH} characters`);
131
+ const found = problem(block, answer);
132
+ return found === undefined ? PASS : fail(found);
133
+ }
@@ -1,3 +1,4 @@
1
+ import { optionName } from "../core/blocks.ts";
1
2
  import { inlinePlain } from "../core/inline.ts";
2
3
  import type { ChecklistData, OptionData, OptionsData, SuggestData } from "../core/types.ts";
3
4
  import { define, PbsElement } from "./base.ts";
@@ -6,9 +7,6 @@ import { h, inlineNodes, prose, uid } from "./dom.ts";
6
7
 
7
8
  /** The elements that answer with a pick or ticks: options, suggest, checklist. */
8
9
 
9
- const optionName = (option: OptionData, index: number): string =>
10
- option.title ? inlinePlain(option.title) : String(index + 1);
11
-
12
10
  /**
13
11
  * One-shot elements (options, suggest) lock themselves once a listener takes the answer, so a double click sends
14
12
  * once; the host's `answered` then shows what was sent. Setting `answered` (even to `undefined`) clears the local lock,