pi-better-show 0.2.0 → 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 +12 -1
- package/package.json +1 -1
- package/src/core/blocks.ts +5 -0
- package/src/core/index.ts +1 -0
- package/src/core/text.ts +41 -5
- package/src/core/types.ts +7 -0
- package/src/core/validate.ts +133 -0
- package/src/elements/choice.ts +1 -3
package/README.md
CHANGED
|
@@ -54,10 +54,13 @@ interface TextProfile {
|
|
|
54
54
|
width?: number; // columns a diagram may take; default 60
|
|
55
55
|
mermaid?: (source: string, width: number) => string | undefined;
|
|
56
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"
|
|
57
58
|
}
|
|
58
59
|
```
|
|
59
60
|
|
|
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.
|
|
61
64
|
|
|
62
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`.
|
|
63
66
|
|
|
@@ -87,6 +90,14 @@ encodeAnswer(answer: Answer): string
|
|
|
87
90
|
| `suggest` | `[["text", text]]` | the text itself |
|
|
88
91
|
| `checklist` | one `[name, "checked" \| "unchecked"]` per item | `User updated the checklist "title":` then `☑`/`☐` lines |
|
|
89
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
|
+
|
|
90
101
|
## Server API
|
|
91
102
|
|
|
92
103
|
```ts
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-show",
|
|
3
|
-
"version": "0.
|
|
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",
|
package/src/core/blocks.ts
CHANGED
|
@@ -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
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, "",
|
|
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, "",
|
|
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 ? "" :
|
|
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, "",
|
|
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
|
|
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,6 +306,7 @@ 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
|
};
|
|
275
311
|
const keep = new Set<string>(profile.keep ?? []);
|
|
276
312
|
return segments
|
package/src/core/types.ts
CHANGED
|
@@ -233,7 +233,14 @@ export interface TextProfile {
|
|
|
233
233
|
mermaid?: (source: string, width: number) => string | undefined;
|
|
234
234
|
/** Kinds whose blocks (valid or invalid) are emitted as their `raw` text, for a surface that draws them itself. */
|
|
235
235
|
keep?: readonly BlockKind[];
|
|
236
|
+
/** Language of the reply instructions: `en` (default) or `zh-TW`; anything else is `en`. */
|
|
237
|
+
lang?: TextLang;
|
|
236
238
|
}
|
|
237
239
|
|
|
240
|
+
export type TextLang = "en" | "zh-TW";
|
|
241
|
+
|
|
238
242
|
/** The kinds a display surface (a chat UI that draws blocks itself) typically keeps through `toText`. */
|
|
239
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
|
+
}
|
package/src/elements/choice.ts
CHANGED
|
@@ -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,
|