@aiti-ai/pi-ask-user 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 agegr
4
+ Copyright (c) 2026 aiti-ai contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,108 @@
1
- # Temporary Holding Version
1
+ # pi-ask-user
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An `ask_user` tool for [pi](https://pi.dev): the model asks up to four
4
+ multiple-choice questions at once, and waits for the answers. The person can
5
+ always answer in their own words instead.
6
+
7
+ It is also the example web plugin for [Pi Web](https://github.com/aiti-ai/aiti-ai/blob/main/README.md) ([ADR
8
+ 0008](https://github.com/aiti-ai/aiti-ai/blob/main/docs/adr/0008-web-plugins.md)). The pi CLI shows the questions as a
9
+ TUI questionnaire. Pi Web draws them as a card in the chat, with the same
10
+ extension, and falls back to that questionnaire if the card cannot load.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ pi install npm:@aiti-ai/pi-ask-user
16
+ ```
17
+
18
+ Or in Pi Web: Settings › Plugins, add `npm:@aiti-ai/pi-ask-user`. Then start a
19
+ new session. The first one after install says what to try, once:
20
+
21
+ ```text
22
+ /ask-user-demo
23
+ ```
24
+
25
+ asks the agent to plan a small todo app, and to ask you three questions first
26
+ (a language with code previews, storage, and features you can pick several of).
27
+ Otherwise the model reaches for `ask_user` on its own when a request is
28
+ ambiguous; nothing runs at session start.
29
+
30
+ From a checkout of this repository, `pi install ./examples/pi-ask-user` loads
31
+ the folder where it is, so an edit shows after `/reload`.
32
+
33
+ ## Files
34
+
35
+ | File | Runs in | What it does |
36
+ |---|---|---|
37
+ | `extension.ts` | pi | Registers `ask_user`, opens the questionnaire with `ctx.ui.custom`, and sends Pi Web's two messages |
38
+ | `questionnaire.ts` | pi | The TUI questionnaire: the CLI's UI, and Pi Web's fallback |
39
+ | `first-run.ts` | pi | The one-time hint, remembered by `pi-ask-user.json` in pi's agent dir |
40
+ | `answers.ts` | pi | The question and answer shapes, the answer check, and the text the model reads |
41
+ | `web/ask-user.ts` | Pi Web's card frame | The card. One self-contained module with no imports, so it copies the shapes it needs |
42
+
43
+ ## The tool
44
+
45
+ ```json
46
+ {
47
+ "questions": [
48
+ {
49
+ "question": "Which database should the service use?",
50
+ "header": "Database",
51
+ "options": [
52
+ { "label": "PostgreSQL", "description": "Relational, strong consistency", "preview": "image: postgres:17" },
53
+ { "label": "SQLite", "description": "Single file, zero setup" }
54
+ ],
55
+ "multiSelect": false
56
+ }
57
+ ]
58
+ }
59
+ ```
60
+
61
+ - 1 to 4 questions, each with 2 to 4 options. `preview` is optional, and is
62
+ shown while that option is focused.
63
+ - "Other" is added by the UI, never by the model.
64
+ - The card also offers a note field below the questions: optional words that
65
+ supplement the picks without replacing them. Its answer value is then
66
+ `{ answers: Answer[], note: string }` instead of a plain `Answer[]`; the
67
+ extension unwraps both shapes, and the model reads the note as a `Note:` line.
68
+ - The recap the card shows after answering carries the note too: `📝` plus its
69
+ first 60 characters on the collapsed line (the full text as the tooltip),
70
+ and the whole note under `Notes` when the recap is expanded.
71
+ - The answer for each question is `{ selected: string[], other?: string }`. The
72
+ model reads it as text, and the card reads it from the result's `details`.
73
+ - Esc or Cancel declines. An answer that names an option the question does not
74
+ have, or picks two in a single-select question, also counts as declined. The
75
+ card's answer comes from the browser, so the extension checks it as it
76
+ checks the TUI's.
77
+
78
+ ## Keys
79
+
80
+ | | TUI | Card |
81
+ |---|---|---|
82
+ | Pick an option | number key, or ↑↓ and Enter | number key, or click |
83
+ | Toggle (multi-select) | Space or number key | number key, or click |
84
+ | Next question | ←→, Tab | ←→, or the tabs |
85
+ | Own answer | the last number, then type and Enter | the "Other" field |
86
+ | Note | — | the field below the questions; Enter makes a new line, Ctrl/Cmd+Enter submits |
87
+ | Submit | Enter on Submit | Submit, or Enter in "Other" |
88
+ | Cancel | Esc | Esc, or Cancel |
89
+
90
+ A single-select pick moves on to the next unanswered question. With only one
91
+ question, it submits.
92
+
93
+ ## How the two halves connect
94
+
95
+ ```ts
96
+ // extension.ts
97
+ const value = await ctx.ui.custom((tui, theme, _keybindings, done) => {
98
+ pi.events.emit("pi-web/v1/claim-ui", { toolCallId }); // Pi Web: the card answers this
99
+ return new Questionnaire(questions, theme, () => tui.requestRender(), done);
100
+ });
101
+
102
+ pi.events.emit("pi-web/v1/tool-card", { tool: "ask_user", entry: "./web/ask-user.ts" });
103
+ ```
104
+
105
+ The pi CLI ignores both messages. In Pi Web, the card's `card.done(answers)` is
106
+ the factory's `done`, so the extension gets its answer the same way in both.
107
+ The [author's guide](https://github.com/aiti-ai/aiti-ai/blob/main/docs/integrations.md#web-cards-for-extension-tools-and-commands)
108
+ has the card's whole API.
package/answers.ts ADDED
@@ -0,0 +1,97 @@
1
+ // The questions and answers both halves agree on. The web card (web/ask-user.ts) is one
2
+ // self-contained file, so it keeps its own copy of these shapes.
3
+
4
+ export interface QuestionOption {
5
+ label: string;
6
+ description: string;
7
+ preview?: string;
8
+ }
9
+
10
+ export interface Question {
11
+ question: string;
12
+ header: string;
13
+ options: QuestionOption[];
14
+ multiSelect?: boolean;
15
+ }
16
+
17
+ /** One question's answer: the options picked, in their order, and the person's own words. */
18
+ export interface Answer {
19
+ selected: string[];
20
+ other?: string;
21
+ }
22
+
23
+ export const MAX_OTHER_CHARS = 2000;
24
+
25
+ /** The note field's cap: the person's optional words below the questions (web card). */
26
+ export const MAX_NOTE_CHARS = 2000;
27
+
28
+ /** The web card's done value: its answers, plus the optional note from the field below. */
29
+ export interface CardReply {
30
+ answers: Answer[];
31
+ note?: string;
32
+ }
33
+
34
+ /**
35
+ * The reply either half hands over: the TUI questionnaire resolves a plain Answer[], the web
36
+ * card may wrap one with its bottom note. Both normalize here, so the extension reads one
37
+ * shape; anything malformed counts as no answer.
38
+ */
39
+ export function parseCardReply(
40
+ questions: readonly Question[],
41
+ value: unknown,
42
+ ): { answers?: Answer[]; note?: string } {
43
+ const wrapped = value !== null && typeof value === "object" && !Array.isArray(value)
44
+ ? value as { answers?: unknown; note?: unknown }
45
+ : { answers: value };
46
+ const note = typeof wrapped.note === "string" ? wrapped.note.trim().slice(0, MAX_NOTE_CHARS) : "";
47
+ return { answers: normalizeAnswers(questions, wrapped.answers), ...(note ? { note } : {}) };
48
+ }
49
+
50
+ /** Why these questions cannot be asked, for the model to fix; undefined when they can. */
51
+ export function questionsProblem(questions: readonly Question[]): string | undefined {
52
+ for (const [index, question] of questions.entries()) {
53
+ const labels = question.options.map((option) => option.label.trim());
54
+ if (labels.some((label) => !label)) return `Question ${index + 1} has an option without a label.`;
55
+ if (new Set(labels).size !== labels.length) return `Question ${index + 1} repeats an option label.`;
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ /**
61
+ * An answer from the TUI or the web card, checked against its questions: only their own
62
+ * option labels, at least one choice each, and one at most where only one may be picked.
63
+ * The card's answer comes from the browser, so anything else counts as no answer.
64
+ */
65
+ export function normalizeAnswers(questions: readonly Question[], value: unknown): Answer[] | undefined {
66
+ if (!Array.isArray(value) || value.length !== questions.length) return undefined;
67
+ const answers: Answer[] = [];
68
+ for (const [index, question] of questions.entries()) {
69
+ const raw: unknown = value[index];
70
+ if (!raw || typeof raw !== "object") return undefined;
71
+ const { selected, other } = raw as { selected?: unknown; other?: unknown };
72
+ if (selected !== undefined && !Array.isArray(selected)) return undefined;
73
+ const picked = selected ?? [];
74
+ const labels = question.options.map((option) => option.label);
75
+ if (!picked.every((label) => typeof label === "string" && labels.includes(label))) return undefined;
76
+ const ordered = labels.filter((label) => picked.includes(label));
77
+ const text = typeof other === "string" ? other.trim().slice(0, MAX_OTHER_CHARS) : "";
78
+ const count = ordered.length + (text ? 1 : 0);
79
+ if (count === 0 || (!question.multiSelect && count > 1)) return undefined;
80
+ answers.push(text ? { selected: ordered, other: text } : { selected: ordered });
81
+ }
82
+ return answers;
83
+ }
84
+
85
+ export const DECLINED = "The user declined to answer the questions.";
86
+
87
+ /** The tool result the model reads: the answers, plus the note when the person wrote one. */
88
+ export function formatAnswers(questions: readonly Question[], answers: readonly Answer[], note?: string): string {
89
+ const lines = questions.map((question, index) => {
90
+ const answer = answers[index];
91
+ const parts = [...answer.selected];
92
+ if (answer.other) parts.push(`(own words) ${JSON.stringify(answer.other)}`);
93
+ return `- ${question.question} → ${parts.join("; ")}`;
94
+ });
95
+ const body = `The user answered:\n${lines.join("\n")}`;
96
+ return note ? `${body}\nNote: ${note}` : body;
97
+ }
package/extension.ts ADDED
@@ -0,0 +1,110 @@
1
+ // pi-ask-user: an ask_user tool written as Pi Web's ADR 0008 describes. The pi CLI loads this
2
+ // file as it is and shows the TUI questionnaire; Pi Web draws web/ask-user.ts instead, and
3
+ // the two pi-web/v1 messages below are the only part of it that knows about Pi Web.
4
+
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import { Type } from "typebox";
7
+ import { type Answer, type CardReply, DECLINED, formatAnswers, parseCardReply, type Question, questionsProblem } from "./answers.ts";
8
+ import { hintOnce } from "./first-run.ts";
9
+ import { Questionnaire } from "./questionnaire.ts";
10
+
11
+ const OptionSchema = Type.Object({
12
+ label: Type.String({ description: "The choice itself, 1 to 5 words" }),
13
+ description: Type.String({ description: "What picking it means, or what it implies" }),
14
+ preview: Type.Optional(
15
+ Type.String({ description: "A code snippet or plain-text mockup shown while this option is focused" }),
16
+ ),
17
+ });
18
+
19
+ const QuestionSchema = Type.Object({
20
+ question: Type.String({ description: "The full question, ending with a question mark" }),
21
+ header: Type.String({ description: "A very short label for the question's tab, at most 12 characters" }),
22
+ options: Type.Array(OptionSchema, {
23
+ minItems: 2,
24
+ maxItems: 4,
25
+ description: "2 to 4 distinct choices. Do not add an \"Other\" choice: the person can always write their own answer",
26
+ }),
27
+ multiSelect: Type.Optional(Type.Boolean({ description: "Let the person pick several options" })),
28
+ });
29
+
30
+ const Parameters = Type.Object({
31
+ questions: Type.Array(QuestionSchema, { minItems: 1, maxItems: 4, description: "1 to 4 questions, asked together" }),
32
+ });
33
+
34
+ /** What the result carries for renderers: the questions, and the answers or null when declined. */
35
+ export interface AskUserDetails {
36
+ questions: Question[];
37
+ answers: Answer[] | null;
38
+ /** The person's optional note from the web card's bottom field (undefined when none). */
39
+ note?: string;
40
+ }
41
+
42
+ export default function askUser(pi: ExtensionAPI) {
43
+ pi.registerTool({
44
+ name: "ask_user",
45
+ label: "Ask user",
46
+ description:
47
+ "Ask the user up to four multiple-choice questions and wait for the answers. Use it when a request is "
48
+ + "ambiguous or underspecified and the answer changes what you do next: unclear requirements, a choice "
49
+ + "between approaches with real trade-offs, or a preference only the user can state. Give each question 2 to "
50
+ + "4 concrete options with a short description of what each implies, and a preview (a code snippet or a "
51
+ + "plain-text mockup) where seeing it helps the choice. The user can always answer in their own words instead. "
52
+ + "Do not use it for facts you can find out yourself, or to ask permission for routine steps.",
53
+ promptSnippet: "Ask the user multiple-choice questions when a request is ambiguous and the choice is theirs",
54
+ promptGuidelines: [
55
+ "Use ask_user instead of guessing when a request is ambiguous and the answer changes what you do; ask related questions together in one call.",
56
+ "Use ask_user only for decisions that are the user's to make, not for facts you can find out with your other tools.",
57
+ ],
58
+ parameters: Parameters,
59
+
60
+ async execute(toolCallId, params, _signal, _onUpdate, ctx) {
61
+ const questions: Question[] = params.questions;
62
+ const problem = questionsProblem(questions);
63
+ if (problem) throw new Error(problem);
64
+ if (ctx.mode !== "tui") {
65
+ return { content: [{ type: "text", text: "Questions need an interactive session." }], details: { questions, answers: null } };
66
+ }
67
+
68
+ const value = await ctx.ui.custom<Answer[] | CardReply | undefined>((tui, theme, _keybindings, done) => {
69
+ // Pi Web: its web card answers this request. Sent before the factory's first await.
70
+ pi.events.emit("pi-web/v1/claim-ui", { toolCallId });
71
+ return new Questionnaire(questions, theme, () => tui.requestRender(), done);
72
+ });
73
+
74
+ // The card's answer comes from the browser: read it as the TUI's would be. The web card
75
+ // wraps the answers with its bottom note; the TUI questionnaire resolves a plain array.
76
+ const reply = value === undefined ? undefined : parseCardReply(questions, value);
77
+ const answers = reply?.answers;
78
+ const details: AskUserDetails = { questions, answers: answers ?? null };
79
+ if (answers && reply?.note) details.note = reply.note;
80
+ return {
81
+ content: [{ type: "text", text: answers ? formatAnswers(questions, answers, reply?.note) : DECLINED }],
82
+ details,
83
+ };
84
+ },
85
+ });
86
+
87
+ // A small decision to try the tool on, asked for only when the person runs the command.
88
+ pi.registerCommand("ask-user-demo", {
89
+ description: "See ask_user: the agent asks you a few questions before it plans",
90
+ handler: async (_args, ctx) => {
91
+ if (!ctx.isIdle()) {
92
+ ctx.ui.notify("Wait for the agent to finish, then run /ask-user-demo again.", "warning");
93
+ return;
94
+ }
95
+ pi.sendUserMessage(DEMO_PROMPT);
96
+ },
97
+ });
98
+
99
+ hintOnce(pi, "pi-ask-user", "ask_user is installed: run /ask-user-demo to have the agent ask you a few questions.");
100
+
101
+ // Pi Web: draw ask_user's calls with this card, resolved inside this package.
102
+ pi.events.emit("pi-web/v1/tool-card", { tool: "ask_user", entry: "./web/ask-user.ts" });
103
+ }
104
+
105
+ const DEMO_PROMPT = [
106
+ "Let's try the ask_user tool. I want a small command-line todo app.",
107
+ "Before you plan anything, call ask_user once with three questions: which language to write it in (each option's preview a few lines of its code),",
108
+ "where the todos are stored, and which extra features I want (several may apply).",
109
+ "Then reply with a five-line plan based on my answers. Do not create or edit any files.",
110
+ ].join(" ");
package/first-run.ts ADDED
@@ -0,0 +1,22 @@
1
+ // A hint shown once, in the first interactive session after the package is installed, so a
2
+ // new user knows what to try. Remembered by a small file in pi's agent dir; nothing calls the
3
+ // model or runs a tool on its own.
4
+
5
+ import { mkdirSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { type ExtensionAPI, getAgentDir } from "@earendil-works/pi-coding-agent";
8
+
9
+ export function hintOnce(pi: ExtensionAPI, name: string, message: string): void {
10
+ pi.on("session_start", (_event, ctx) => {
11
+ if (!ctx.hasUI || ctx.mode !== "tui") return;
12
+ try {
13
+ const dir = getAgentDir();
14
+ mkdirSync(dir, { recursive: true });
15
+ // "wx" fails when the file exists: shown already, here or in a session that started meanwhile.
16
+ writeFileSync(join(dir, `${name}.json`), `${JSON.stringify({ hintShown: new Date().toISOString() })}\n`, { flag: "wx" });
17
+ } catch {
18
+ return;
19
+ }
20
+ ctx.ui.notify(message, "info");
21
+ });
22
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@aiti-ai/pi-ask-user",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "An ask_user tool for pi: up to four multiple-choice questions, drawn as a card in Pi Web, with an optional note below the choices",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "pi-package",
9
+ "pi-web"
10
+ ],
11
+ "homepage": "https://github.com/aiti-ai/aiti-ai/tree/main/examples/pi-ask-user#readme",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/aiti-ai/aiti-ai.git",
15
+ "directory": "examples/pi-ask-user"
16
+ },
17
+ "bugs": {
18
+ "url": "https://github.com/aiti-ai/aiti-ai/issues"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "files": [
24
+ "LICENSE",
25
+ "extension.ts",
26
+ "questionnaire.ts",
27
+ "answers.ts",
28
+ "first-run.ts",
29
+ "web"
30
+ ],
31
+ "pi": {
32
+ "extensions": [
33
+ "./extension.ts"
34
+ ]
35
+ },
36
+ "peerDependencies": {
37
+ "@earendil-works/pi-coding-agent": "*",
38
+ "@earendil-works/pi-tui": "*",
39
+ "typebox": "*"
40
+ },
41
+ "contentHash": "915abda899525444"
42
+ }
@@ -0,0 +1,230 @@
1
+ // The questionnaire as a pi TUI component: what the pi CLI shows, and what Pi Web shows in
2
+ // its extension panel when the web card cannot load.
3
+
4
+ import type { Theme } from "@earendil-works/pi-coding-agent";
5
+ import { type Component, Input, Key, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
6
+ import { type Answer, normalizeAnswers, type Question } from "./answers.ts";
7
+
8
+ const OTHER = "Other";
9
+
10
+ export class Questionnaire implements Component {
11
+ private tab = 0;
12
+ private readonly cursor: number[];
13
+ private readonly picked: Set<string>[];
14
+ private readonly other: string[];
15
+ private editing = false;
16
+ private readonly input = new Input();
17
+ private cached: { width: number; lines: string[] } | undefined;
18
+
19
+ constructor(
20
+ private readonly questions: readonly Question[],
21
+ private readonly theme: Theme,
22
+ private readonly requestRender: () => void,
23
+ private readonly done: (answers: Answer[] | undefined) => void,
24
+ ) {
25
+ this.cursor = questions.map(() => 0);
26
+ this.picked = questions.map(() => new Set<string>());
27
+ this.other = questions.map(() => "");
28
+ this.input.onSubmit = (value) => this.finishEditing(value);
29
+ this.input.onEscape = () => this.stopEditing();
30
+ }
31
+
32
+ private get multi(): boolean {
33
+ return this.questions.length > 1;
34
+ }
35
+
36
+ /** The review tab after the questions, only when there are several. */
37
+ private get onReview(): boolean {
38
+ return this.multi && this.tab === this.questions.length;
39
+ }
40
+
41
+ private answers(): Answer[] | undefined {
42
+ return normalizeAnswers(
43
+ this.questions,
44
+ this.questions.map((_, i) => ({ selected: [...this.picked[i]], other: this.other[i] })),
45
+ );
46
+ }
47
+
48
+ private answered(index: number): boolean {
49
+ return this.picked[index].size > 0 || this.other[index].trim() !== "";
50
+ }
51
+
52
+ private refresh(): void {
53
+ this.cached = undefined;
54
+ this.requestRender();
55
+ }
56
+
57
+ private submit(): void {
58
+ const answers = this.answers();
59
+ if (answers) this.done(answers);
60
+ }
61
+
62
+ /** After a single-select pick: the next unanswered question, else the review, else done. */
63
+ private advance(): void {
64
+ if (!this.multi) {
65
+ this.submit();
66
+ return;
67
+ }
68
+ const next = this.questions.findIndex((_, i) => i > this.tab && !this.answered(i));
69
+ this.tab = next >= 0 ? next : this.questions.length;
70
+ }
71
+
72
+ private activate(index: number): void {
73
+ const question = this.questions[this.tab];
74
+ if (index === question.options.length) {
75
+ this.editing = true;
76
+ this.input.focused = true;
77
+ this.input.setValue(this.other[this.tab]);
78
+ return;
79
+ }
80
+ const label = question.options[index].label;
81
+ const picked = this.picked[this.tab];
82
+ if (question.multiSelect) {
83
+ if (picked.has(label)) picked.delete(label);
84
+ else picked.add(label);
85
+ return;
86
+ }
87
+ picked.clear();
88
+ picked.add(label);
89
+ this.other[this.tab] = "";
90
+ this.advance();
91
+ }
92
+
93
+ private finishEditing(value: string): void {
94
+ const question = this.questions[this.tab];
95
+ this.other[this.tab] = value.trim();
96
+ this.stopEditing();
97
+ if (!question.multiSelect && this.other[this.tab]) {
98
+ this.picked[this.tab].clear();
99
+ this.advance();
100
+ this.refresh();
101
+ }
102
+ }
103
+
104
+ private stopEditing(): void {
105
+ this.editing = false;
106
+ this.input.focused = false;
107
+ this.refresh();
108
+ }
109
+
110
+ handleInput(data: string): void {
111
+ if (this.editing) {
112
+ this.input.handleInput(data);
113
+ this.refresh();
114
+ return;
115
+ }
116
+ if (matchesKey(data, Key.escape)) {
117
+ this.done(undefined);
118
+ return;
119
+ }
120
+ if (this.multi && (matchesKey(data, Key.tab) || matchesKey(data, Key.right))) {
121
+ this.tab = (this.tab + 1) % (this.questions.length + 1);
122
+ } else if (this.multi && (matchesKey(data, Key.shift("tab")) || matchesKey(data, Key.left))) {
123
+ this.tab = (this.tab + this.questions.length) % (this.questions.length + 1);
124
+ } else if (this.onReview) {
125
+ if (matchesKey(data, Key.enter)) this.submit();
126
+ } else {
127
+ const rows = this.questions[this.tab].options.length + 1;
128
+ const digit = Number(data);
129
+ if (matchesKey(data, Key.up)) {
130
+ this.cursor[this.tab] = (this.cursor[this.tab] + rows - 1) % rows;
131
+ } else if (matchesKey(data, Key.down)) {
132
+ this.cursor[this.tab] = (this.cursor[this.tab] + 1) % rows;
133
+ } else if (Number.isInteger(digit) && digit >= 1 && digit <= rows) {
134
+ this.cursor[this.tab] = digit - 1;
135
+ this.activate(digit - 1);
136
+ } else if (matchesKey(data, Key.space)) {
137
+ this.activate(this.cursor[this.tab]);
138
+ } else if (matchesKey(data, Key.enter)) {
139
+ // Enter picks, except in an answered multi-select question, which it leaves.
140
+ if (this.questions[this.tab].multiSelect && this.answered(this.tab)) this.advance();
141
+ else this.activate(this.cursor[this.tab]);
142
+ } else {
143
+ return;
144
+ }
145
+ }
146
+ this.refresh();
147
+ }
148
+
149
+ invalidate(): void {
150
+ this.cached = undefined;
151
+ }
152
+
153
+ render(width: number): string[] {
154
+ if (this.cached?.width === width) return this.cached.lines;
155
+ const { theme } = this;
156
+ const w = Math.max(20, width);
157
+ const lines: string[] = [];
158
+ const wrap = (text: string, indent = "") => {
159
+ for (const line of wrapTextWithAnsi(text, Math.max(1, w - visibleWidth(indent)))) lines.push(indent + line);
160
+ };
161
+
162
+ lines.push(theme.fg("accent", "─".repeat(w)));
163
+ if (this.multi) {
164
+ const tabs = this.questions.map((question, i) => {
165
+ const text = ` ${this.answered(i) ? "■" : "□"} ${question.header} `;
166
+ return i === this.tab ? theme.bg("selectedBg", theme.fg("text", text)) : theme.fg(this.answered(i) ? "success" : "muted", text);
167
+ });
168
+ const review = " ✓ Submit ";
169
+ tabs.push(this.onReview ? theme.bg("selectedBg", theme.fg("text", review)) : theme.fg(this.answers() ? "success" : "dim", review));
170
+ wrap(tabs.join(" "), " ");
171
+ lines.push("");
172
+ }
173
+
174
+ if (this.onReview) {
175
+ this.renderReview(wrap);
176
+ } else {
177
+ this.renderQuestion(w, lines, wrap);
178
+ }
179
+
180
+ lines.push("");
181
+ const help = this.editing
182
+ ? "Enter save · Esc back"
183
+ : this.onReview
184
+ ? "Enter submit · ←→ questions · Esc cancel"
185
+ : `↑↓ move · ${this.questions[this.tab].multiSelect ? "Space toggle · Enter next" : "Enter pick"}${this.multi ? " · ←→ questions" : ""} · Esc cancel`;
186
+ wrap(theme.fg("dim", help), " ");
187
+ lines.push(theme.fg("accent", "─".repeat(w)));
188
+ this.cached = { width, lines };
189
+ return lines;
190
+ }
191
+
192
+ private renderQuestion(w: number, lines: string[], wrap: (text: string, indent?: string) => void): void {
193
+ const { theme } = this;
194
+ const question = this.questions[this.tab];
195
+ const picked = this.picked[this.tab];
196
+ const cursor = this.cursor[this.tab];
197
+ wrap(theme.bold(question.question), " ");
198
+ lines.push("");
199
+ const rows = [...question.options, { label: OTHER, description: "", preview: undefined }];
200
+ rows.forEach((option, i) => {
201
+ const isOther = i === question.options.length;
202
+ const on = isOther ? this.other[this.tab] !== "" : picked.has(option.label);
203
+ const mark = question.multiSelect ? (on ? "[x]" : "[ ]") : on ? "(•)" : "( )";
204
+ const pointer = i === cursor ? theme.fg("accent", "› ") : " ";
205
+ const text = isOther && this.other[this.tab] ? `${OTHER}: ${this.other[this.tab]}` : option.label;
206
+ wrap(`${pointer}${theme.fg(on ? "accent" : "text", `${mark} ${i + 1}. ${text}`)}`, " ");
207
+ if (option.description) wrap(theme.fg("muted", option.description), " ");
208
+ if (isOther && this.editing) {
209
+ for (const line of this.input.render(Math.max(10, w - 8))) lines.push(` ${line}`);
210
+ }
211
+ });
212
+ const preview = question.options[cursor]?.preview;
213
+ if (preview) {
214
+ lines.push("");
215
+ for (const line of preview.split("\n")) {
216
+ lines.push(` ${theme.fg("dim", "│")} ${truncateToWidth(line, Math.max(1, w - 3))}`);
217
+ }
218
+ }
219
+ }
220
+
221
+ private renderReview(wrap: (text: string, indent?: string) => void): void {
222
+ const { theme } = this;
223
+ this.questions.forEach((question, i) => {
224
+ const parts = [...this.picked[i]];
225
+ if (this.other[i]) parts.push(`"${this.other[i]}"`);
226
+ const answer = parts.length ? theme.fg("text", parts.join(", ")) : theme.fg("warning", "unanswered");
227
+ wrap(`${theme.fg("muted", `${question.header}: `)}${answer}`, " ");
228
+ });
229
+ }
230
+ }
@@ -0,0 +1,487 @@
1
+ // ask_user's web card for Pi Web (ADR 0008). It runs in a sandboxed frame with no network,
2
+ // as one self-contained module: no imports, so the shapes in ../answers.ts are copied here.
3
+ // Erasable TypeScript only, and nothing newer than old Safari (16.2) parses. The person's
4
+ // optional note below the questions rides the done value wrapped (see parseCardReply there),
5
+ // and the UI strings follow the locale the page hands the card ("zh*" reads the Chinese table).
6
+
7
+ type QuestionOption = { label: string; description?: string; preview?: string };
8
+ type Question = { question: string; header?: string; options: QuestionOption[]; multiSelect?: boolean };
9
+ type Answer = { selected: string[]; other?: string };
10
+ type Details = { questions?: Question[]; answers?: Answer[] | null; note?: string };
11
+
12
+ type Card = {
13
+ el: HTMLElement;
14
+ tool: {
15
+ toolCallId: string;
16
+ args: { questions?: Question[] } | undefined;
17
+ status: "running" | "done" | "error";
18
+ result?: { content?: unknown; details?: unknown };
19
+ };
20
+ waiting: boolean;
21
+ /** The page's UI locale ("en", "zh-CN", ...), picked from the host's snapshot. */
22
+ locale?: string;
23
+ done(value: unknown): boolean;
24
+ cancel(): boolean;
25
+ };
26
+
27
+ // The app's --font-mono names web fonts the frame cannot load, and falls through to a
28
+ // proportional CJK font before any monospace one: the system's own monospace fonts come first.
29
+ const CSS = `
30
+ :root { --card-mono: ui-monospace, "SF Mono", Menlo, Consolas, "DejaVu Sans Mono", var(--font-mono); }
31
+ .ask { display: flex; flex-direction: column; gap: 10px; }
32
+ .tabs { display: flex; gap: 4px; flex-wrap: wrap; }
33
+ .tab { font: inherit; font-size: 12px; padding: 2px 10px; border-radius: 999px; border: 1px solid var(--border); background: none; color: var(--text-muted); cursor: pointer; transition: background 140ms ease, border-color 140ms ease, color 140ms ease; }
34
+ .tab:hover { color: var(--text); }
35
+ .tab[aria-selected="true"] { border-color: var(--accent); color: var(--text); background: var(--bg-selected); }
36
+ .tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
37
+ .tab .tick { color: var(--success, var(--accent)); margin-left: 4px; }
38
+ .stage { display: flex; flex-direction: column; gap: 8px; animation: enter 160ms ease-out; }
39
+ @keyframes enter { from { opacity: 0; transform: translateY(3px); } }
40
+ .question { font-weight: 600; margin: 0; }
41
+ .body { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; }
42
+ .body.has-preview { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
43
+ @media (max-width: 520px) { .body.has-preview { grid-template-columns: minmax(0, 1fr); } }
44
+ .options { display: flex; flex-direction: column; gap: 6px; }
45
+ .option { display: flex; gap: 10px; align-items: flex-start; width: 100%; box-sizing: border-box; text-align: left; font: inherit; color: var(--text); padding: 8px 10px; border-radius: 8px; border: 1px solid var(--border); background: var(--bg-panel); cursor: pointer; transition: background 140ms ease, border-color 140ms ease; }
46
+ .option:hover { background: var(--bg-hover); }
47
+ .option:focus-visible, .other-input:focus-visible { outline: 2px solid var(--accent); outline-offset: -1px; }
48
+ .option[aria-checked="true"] { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 10%, var(--bg-panel)); }
49
+ .mark { position: relative; flex: none; width: 16px; height: 16px; margin-top: 2px; border: 1.5px solid var(--text-dim); box-sizing: border-box; transition: border-color 140ms ease, background 140ms ease; }
50
+ .radio .mark { border-radius: 50%; }
51
+ .check .mark { border-radius: 4px; }
52
+ .mark::after { content: ""; position: absolute; transform: scale(0); transition: transform 140ms ease-out; }
53
+ .radio .mark::after { inset: 3px; border-radius: 50%; background: var(--accent-contrast, #fff); }
54
+ .check .mark::after { left: 4px; top: 1px; width: 4px; height: 8px; border: solid var(--accent-contrast, #fff); border-width: 0 2px 2px 0; transform: rotate(45deg) scale(0); }
55
+ .option[aria-checked="true"] .mark { border-color: var(--accent); background: var(--accent); }
56
+ .radio[aria-checked="true"] .mark::after { transform: scale(1); }
57
+ .check[aria-checked="true"] .mark::after { transform: rotate(45deg) scale(1); }
58
+ .text { display: flex; flex-direction: column; gap: 1px; min-width: 0; flex: 1; }
59
+ .label { font-weight: 500; }
60
+ .description { color: var(--text-muted); font-size: 12px; }
61
+ .key { flex: none; min-width: 18px; text-align: center; font-family: var(--card-mono); font-size: 11px; color: var(--text-dim); border: 1px solid var(--border); border-radius: 4px; margin-top: 1px; }
62
+ .other-input { font: inherit; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 4px 8px; margin-top: 4px; width: 100%; box-sizing: border-box; }
63
+ .preview { margin: 0; padding: 10px; border-radius: 8px; border: 1px solid var(--border); background: var(--bg); font-family: var(--card-mono); font-size: 12px; line-height: 1.45; white-space: pre; overflow: auto; max-height: 320px; color: var(--text); }
64
+ .bar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
65
+ .hint { color: var(--text-dim); font-size: 11px; margin-right: auto; }
66
+ .button { font: inherit; font-size: 12px; padding: 5px 14px; border-radius: 8px; border: 1px solid var(--border); background: none; color: var(--text); cursor: pointer; transition: background 140ms ease, opacity 140ms ease; }
67
+ .button:hover:not(:disabled) { background: var(--bg-hover); }
68
+ .button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
69
+ .button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-contrast, #fff); }
70
+ .button.primary:hover:not(:disabled) { background: var(--accent-hover, var(--accent)); }
71
+ .button:disabled { opacity: 0.45; cursor: default; }
72
+ @media (hover: none) { .key, .hint { display: none; } .bar .button { flex: 1; padding: 8px 14px; } }
73
+ .summary summary { cursor: pointer; color: var(--text-muted); list-style: none; display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 2px 8px; align-items: baseline; }
74
+ .summary summary::-webkit-details-marker { display: none; }
75
+ .summary summary .state { grid-column: 1; color: var(--success, var(--accent)); font-weight: 600; }
76
+ .summary .answers { grid-column: 2; min-width: 0; }
77
+ .summary .note-badge { grid-column: 2; color: var(--accent); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
78
+ .summary summary b { color: var(--text); font-weight: 500; }
79
+ .summary dl { margin: 8px 0 0; padding-left: 10px; border-left: 2px solid var(--border); animation: enter 160ms ease-out; }
80
+ .summary dt { color: var(--text-muted); font-size: 12px; }
81
+ .summary dd { margin: 0 0 6px; }
82
+ .declined { display: flex; gap: 8px; color: var(--text-muted); }
83
+ .declined .state { color: var(--text-dim); font-weight: 600; }
84
+ .muted { color: var(--text-muted); }
85
+ .note { display: flex; flex-direction: column; gap: 3px; }
86
+ .note-label { color: var(--text-muted); font-size: 11px; }
87
+ .note-input { font: inherit; color: var(--text); background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 6px 8px; width: 100%; box-sizing: border-box; font-size: 12px; line-height: 1.5; resize: vertical; min-height: 46px; }
88
+ .note-input:focus-visible { outline: 2px solid var(--accent); outline-offset: -1px; }
89
+ @media (prefers-reduced-motion: reduce) { .ask *, .summary * { animation: none !important; transition: none !important; } }
90
+ `;
91
+
92
+ const MAX_NOTE_CHARS = 2000;
93
+
94
+ /** UI strings: zh* locales read the Chinese table, anything else the English one. */
95
+ const STRINGS = {
96
+ en: {
97
+ other: "Other",
98
+ otherPlaceholder: "Type your own answer",
99
+ submit: "Submit",
100
+ cancel: "Cancel",
101
+ noteLabel: "Notes (optional)",
102
+ notePlaceholder: "Add context, adjust what the options mean, or answer beyond them…",
103
+ notesLabel: "Notes",
104
+ declined: "Declined",
105
+ couldNotAsk: "The questions could not be asked.",
106
+ noQuestions: "No questions.",
107
+ keysSingle: "1–9 pick · Esc cancel",
108
+ keysMulti: "1–9 pick · ←→ questions · Esc cancel",
109
+ },
110
+ zh: {
111
+ other: "其他",
112
+ otherPlaceholder: "输入你自己的回答",
113
+ submit: "提交",
114
+ cancel: "取消",
115
+ noteLabel: "补充说明(可选)",
116
+ notePlaceholder: "补充上下文、修正选项含义,或写出选项之外的回答…",
117
+ notesLabel: "补充说明",
118
+ declined: "已取消",
119
+ couldNotAsk: "问题未能送达。",
120
+ noQuestions: "没有问题。",
121
+ keysSingle: "1–9 选择 · Esc 取消",
122
+ keysMulti: "1–9 选择 · ←→ 切题 · Esc 取消",
123
+ },
124
+ } as const;
125
+
126
+ // Wide on purpose: the zh table holds its own literals (`as const` above), so the
127
+ // narrow `typeof STRINGS.en` return type would reject it.
128
+ function stringsOf(locale: unknown): Record<keyof typeof STRINGS.en, string> {
129
+ return typeof locale === "string" && locale.toLowerCase().startsWith("zh") ? STRINGS.zh : STRINGS.en;
130
+ }
131
+
132
+ function el<K extends keyof HTMLElementTagNameMap>(tag: K, className?: string, text?: string): HTMLElementTagNameMap[K] {
133
+ const node = document.createElement(tag);
134
+ if (className) node.className = className;
135
+ if (text !== undefined) node.textContent = text;
136
+ return node;
137
+ }
138
+
139
+ function questionsOf(card: Card): Question[] {
140
+ const details = card.tool.result?.details as Details | undefined;
141
+ const questions = details?.questions ?? card.tool.args?.questions;
142
+ return Array.isArray(questions) ? questions : [];
143
+ }
144
+
145
+ function answerText(answer: Answer | undefined): string {
146
+ if (!answer) return "—";
147
+ const parts = answer.selected.slice();
148
+ if (answer.other) parts.push(`“${answer.other}”`);
149
+ return parts.join(", ");
150
+ }
151
+
152
+ export default function askUserCard(initial: Card) {
153
+ let card = initial;
154
+ const questions = questionsOf(card);
155
+ const picked = questions.map(() => [] as string[]);
156
+ const other = questions.map(() => "");
157
+ /** The person's optional note from the card's bottom field; rides the done value. */
158
+ let note = "";
159
+ let tab = 0;
160
+ // The option whose preview shows: the focused or hovered one, else the picked one.
161
+ let previewIndex: number | null = null;
162
+ let focusAfterRender: number | null = null;
163
+ // Kept across updates, which redraw the card: an expanded summary stays expanded.
164
+ let summaryOpen = false;
165
+ // The question last drawn, so a redraw of the same one does not ease in again.
166
+ let shownTab = -1;
167
+
168
+ const style = el("style");
169
+ style.textContent = CSS;
170
+ document.head.append(style);
171
+
172
+ const answered = (i: number) => picked[i].length > 0 || other[i].trim() !== "";
173
+ const complete = () => questions.every((_, i) => answered(i));
174
+ const answers = (): Answer[] => questions.map((_, i) => {
175
+ const text = other[i].trim();
176
+ return text ? { selected: picked[i].slice(), other: text } : { selected: picked[i].slice() };
177
+ });
178
+
179
+ /** The done value: plain answers when no note, the wrapped shape the extension unwraps. */
180
+ function submit() {
181
+ if (!complete()) return;
182
+ const trimmed = note.trim().slice(0, MAX_NOTE_CHARS);
183
+ card.done(trimmed ? { answers: answers(), note: trimmed } : answers());
184
+ }
185
+
186
+ /** After a single-select pick: the next unanswered question, or the answer when it was the last. */
187
+ function advance() {
188
+ if (questions.length === 1) {
189
+ submit();
190
+ return;
191
+ }
192
+ const next = questions.findIndex((_, i) => i > tab && !answered(i));
193
+ if (next >= 0) {
194
+ tab = next;
195
+ previewIndex = null;
196
+ focusAfterRender = 0;
197
+ }
198
+ render();
199
+ }
200
+
201
+ function pick(index: number) {
202
+ const question = questions[tab];
203
+ const label = question.options[index].label;
204
+ if (question.multiSelect) {
205
+ const at = picked[tab].indexOf(label);
206
+ if (at >= 0) picked[tab].splice(at, 1);
207
+ else picked[tab] = question.options.map((option) => option.label).filter((l) => l === label || picked[tab].includes(l));
208
+ focusAfterRender = index;
209
+ render();
210
+ return;
211
+ }
212
+ picked[tab] = [label];
213
+ other[tab] = "";
214
+ focusAfterRender = index;
215
+ advance();
216
+ }
217
+
218
+ function setOther(value: string) {
219
+ other[tab] = value;
220
+ if (!questions[tab].multiSelect && value.trim()) picked[tab] = [];
221
+ }
222
+
223
+ function renderSummary() {
224
+ const STR = stringsOf(card.locale);
225
+ const details = card.tool.result?.details as Details | undefined;
226
+ const given = details?.answers;
227
+ if (card.tool.status === "error") {
228
+ const content = card.tool.result?.content;
229
+ const text = Array.isArray(content) ? content.map((block: { text?: string }) => block.text ?? "").join("\n") : "";
230
+ card.el.replaceChildren(el("div", "muted", text || STR.couldNotAsk));
231
+ return;
232
+ }
233
+ if (!given) {
234
+ const declined = el("div", "declined");
235
+ declined.append(el("span", "state", "✕"), STR.declined);
236
+ card.el.replaceChildren(declined);
237
+ return;
238
+ }
239
+ const box = el("details", "summary");
240
+ box.open = summaryOpen;
241
+ box.ontoggle = () => { summaryOpen = box.open; };
242
+ const line = el("summary");
243
+ const answersLine = el("span", "answers");
244
+ questions.forEach((question, i) => {
245
+ if (i > 0) answersLine.append(" · ");
246
+ answersLine.append(`${question.header ?? `Q${i + 1}`}: `, el("b", undefined, answerText(given[i])));
247
+ });
248
+ line.append(el("span", "state", "✓"), answersLine);
249
+ // The note rides the collapsed line too: a recap that hid it read as "my note was lost".
250
+ if (details?.note) {
251
+ const preview = details.note.length > 60 ? `${details.note.slice(0, 60)}…` : details.note;
252
+ const badge = el("span", "note-badge", `📝 ${preview}`);
253
+ badge.title = details.note;
254
+ line.append(badge);
255
+ }
256
+ const list = el("dl");
257
+ questions.forEach((question, i) => list.append(el("dt", undefined, question.question), el("dd", undefined, answerText(given[i]))));
258
+ if (details?.note) list.append(el("dt", undefined, STR.notesLabel), el("dd", undefined, details.note));
259
+ box.append(line, list);
260
+ card.el.replaceChildren(box);
261
+ }
262
+
263
+ function renderPending() {
264
+ // Running, but the request is not (or no longer) this card's: show what is being asked.
265
+ const list = el("dl");
266
+ for (const question of questions) {
267
+ list.append(el("dt", undefined, question.question), el("dd", "muted", question.options.map((o) => o.label).join(" · ")));
268
+ }
269
+ card.el.replaceChildren(list);
270
+ }
271
+
272
+ function render() {
273
+ const STR = stringsOf(card.locale);
274
+ if (card.tool.result) return renderSummary();
275
+ if (!card.waiting) return renderPending();
276
+ if (questions.length === 0) return card.el.replaceChildren(el("div", "muted", STR.noQuestions));
277
+
278
+ const question = questions[tab];
279
+ const root = el("div", "ask");
280
+
281
+ if (questions.length > 1) {
282
+ const tabs = el("div", "tabs");
283
+ tabs.setAttribute("role", "tablist");
284
+ questions.forEach((item, i) => {
285
+ const button = el("button", "tab", item.header ?? `Q${i + 1}`);
286
+ button.type = "button";
287
+ button.setAttribute("role", "tab");
288
+ button.setAttribute("aria-selected", String(i === tab));
289
+ if (answered(i)) button.append(el("span", "tick", "✓"));
290
+ button.onclick = () => { tab = i; previewIndex = null; focusAfterRender = 0; render(); };
291
+ tabs.append(button);
292
+ });
293
+ root.append(tabs);
294
+ }
295
+
296
+ // The question and its options: drawn again on each render, eased in only when the question changes.
297
+ const stage = el("div", "stage");
298
+ if (tab === shownTab) stage.style.animation = "none";
299
+ shownTab = tab;
300
+ stage.append(el("p", "question", question.question));
301
+
302
+ const options = el("div", "options");
303
+ options.setAttribute("role", question.multiSelect ? "group" : "radiogroup");
304
+ options.setAttribute("aria-label", question.question);
305
+ const kind = question.multiSelect ? "check" : "radio";
306
+ question.options.forEach((option, i) => {
307
+ const button = el("button", `option ${kind}`);
308
+ button.type = "button";
309
+ button.setAttribute("role", question.multiSelect ? "checkbox" : "radio");
310
+ button.setAttribute("aria-checked", String(picked[tab].includes(option.label)));
311
+ button.dataset.index = String(i);
312
+ const text = el("span", "text");
313
+ text.append(el("span", "label", option.label));
314
+ if (option.description) text.append(el("span", "description", option.description));
315
+ button.append(el("span", "mark"), text, el("span", "key", String(i + 1)));
316
+ button.onclick = () => pick(i);
317
+ const showPreview = () => {
318
+ if (previewIndex === i) return;
319
+ previewIndex = i;
320
+ updatePreview();
321
+ };
322
+ button.onfocus = showPreview;
323
+ button.onmouseenter = showPreview;
324
+ options.append(button);
325
+ });
326
+
327
+ // "Other": the person's own words, always offered, never one of the model's options.
328
+ const otherRow = el("label", `option ${kind}`);
329
+ otherRow.setAttribute("aria-checked", String(other[tab].trim() !== ""));
330
+ const otherText = el("span", "text");
331
+ otherText.append(el("span", "label", STR.other));
332
+ const input = el("input", "other-input");
333
+ input.type = "text";
334
+ input.placeholder = STR.otherPlaceholder;
335
+ input.maxLength = 2000;
336
+ input.value = other[tab];
337
+ input.dataset.index = String(question.options.length);
338
+ input.oninput = () => {
339
+ const before = answered(tab);
340
+ setOther(input.value);
341
+ otherRow.setAttribute("aria-checked", String(input.value.trim() !== ""));
342
+ for (const button of Array.from(options.querySelectorAll<HTMLElement>("button[role]"))) {
343
+ button.setAttribute("aria-checked", String(picked[tab].includes(question.options[Number(button.dataset.index)].label)));
344
+ }
345
+ if (before !== answered(tab)) updateBar();
346
+ };
347
+ otherText.append(input);
348
+ otherRow.append(el("span", "mark"), otherText, el("span", "key", String(question.options.length + 1)));
349
+ options.append(otherRow);
350
+
351
+ const body = el("div", "body");
352
+ body.append(options);
353
+ const hasPreview = question.options.some((option) => option.preview);
354
+ const preview = el("pre", "preview");
355
+ if (hasPreview) {
356
+ body.classList.add("has-preview");
357
+ body.append(preview);
358
+ }
359
+ function updatePreview() {
360
+ if (!hasPreview) return;
361
+ const pickedIndex = question.options.findIndex((option) => picked[tab].includes(option.label) && option.preview);
362
+ const index = previewIndex !== null && question.options[previewIndex]?.preview ? previewIndex
363
+ : pickedIndex >= 0 ? pickedIndex
364
+ : question.options.findIndex((option) => option.preview);
365
+ preview.textContent = question.options[index]?.preview ?? "";
366
+ }
367
+ updatePreview();
368
+ stage.append(body);
369
+ root.append(stage);
370
+
371
+ // The person's note: supplements the picks without replacing them, always offered.
372
+ const noteWrap = el("label", "note");
373
+ noteWrap.append(el("span", "note-label", STR.noteLabel));
374
+ const noteArea = el("textarea", "note-input");
375
+ noteArea.maxLength = MAX_NOTE_CHARS;
376
+ noteArea.rows = 2;
377
+ noteArea.placeholder = STR.notePlaceholder;
378
+ noteArea.value = note;
379
+ noteArea.oninput = () => { note = noteArea.value; };
380
+ noteWrap.append(noteArea);
381
+ root.append(noteWrap);
382
+
383
+ const bar = el("div", "bar");
384
+ const keys = questions.length > 1 ? STR.keysMulti : STR.keysSingle;
385
+ bar.append(el("span", "hint", keys));
386
+ const cancel = el("button", "button", STR.cancel);
387
+ cancel.type = "button";
388
+ cancel.onclick = () => card.cancel();
389
+ const send = el("button", "button primary", STR.submit);
390
+ send.type = "button";
391
+ send.onclick = submit;
392
+ function updateBar() {
393
+ send.disabled = !complete();
394
+ const tick = root.querySelectorAll<HTMLElement>(".tab")[tab];
395
+ if (tick && answered(tab) !== !!tick.querySelector(".tick")) {
396
+ if (answered(tab)) tick.append(el("span", "tick", "✓"));
397
+ else tick.querySelector(".tick")?.remove();
398
+ }
399
+ }
400
+ bar.append(cancel, send);
401
+ root.append(bar);
402
+ updateBar();
403
+
404
+ card.el.replaceChildren(root);
405
+ if (focusAfterRender !== null) {
406
+ const target = root.querySelector<HTMLElement>(`[data-index="${focusAfterRender}"]`);
407
+ focusAfterRender = null;
408
+ target?.focus();
409
+ }
410
+ }
411
+
412
+ function moveFocus(step: number) {
413
+ const rows = Array.from(card.el.querySelectorAll<HTMLElement>(".options [data-index]"));
414
+ if (rows.length === 0) return;
415
+ const at = rows.indexOf(document.activeElement as HTMLElement);
416
+ const next = at < 0 ? (step > 0 ? 0 : rows.length - 1) : (at + step + rows.length) % rows.length;
417
+ rows[next].focus();
418
+ }
419
+
420
+ function onKey(event: KeyboardEvent) {
421
+ if (!card.waiting || card.tool.result || questions.length === 0) return;
422
+ const tag = (event.target as HTMLElement | null)?.tagName;
423
+ const inInput = tag === "INPUT";
424
+ const inNote = tag === "TEXTAREA";
425
+ if (event.key === "Escape") {
426
+ event.preventDefault();
427
+ if (inInput || inNote) (event.target as HTMLElement).blur();
428
+ else card.cancel();
429
+ return;
430
+ }
431
+ // Plain Enter keeps its newline inside the note; Ctrl/Cmd+Enter submits from anywhere.
432
+ if (event.key === "Enter" && (inInput || event.metaKey || event.ctrlKey)) {
433
+ event.preventDefault();
434
+ if (complete()) submit();
435
+ else if (inInput && answered(tab)) advance();
436
+ return;
437
+ }
438
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
439
+ if (inNote) return; // the caret moves through the note's lines
440
+ event.preventDefault();
441
+ moveFocus(event.key === "ArrowDown" ? 1 : -1);
442
+ return;
443
+ }
444
+ if (inInput || inNote || event.metaKey || event.ctrlKey || event.altKey) return;
445
+ if ((event.key === "ArrowRight" || event.key === "ArrowLeft") && questions.length > 1) {
446
+ event.preventDefault();
447
+ tab = (tab + (event.key === "ArrowRight" ? 1 : questions.length - 1)) % questions.length;
448
+ previewIndex = null;
449
+ focusAfterRender = 0;
450
+ render();
451
+ return;
452
+ }
453
+ const digit = Number(event.key);
454
+ const question = questions[tab];
455
+ if (Number.isInteger(digit) && digit >= 1 && digit <= question.options.length + 1) {
456
+ event.preventDefault();
457
+ if (digit <= question.options.length) pick(digit - 1);
458
+ else card.el.querySelector<HTMLInputElement>(".other-input")?.focus();
459
+ }
460
+ }
461
+
462
+ // Pi Web focuses the frame once the card is ready; a focus() made before that did not take.
463
+ function onFrameFocus() {
464
+ if (card.waiting && !card.tool.result && document.activeElement === document.body) {
465
+ card.el.querySelector<HTMLElement>(".options [data-index]")?.focus();
466
+ }
467
+ }
468
+
469
+ document.addEventListener("keydown", onKey);
470
+ window.addEventListener("focus", onFrameFocus);
471
+ focusAfterRender = card.waiting ? 0 : null;
472
+ render();
473
+
474
+ return {
475
+ update(next: Card) {
476
+ const wasWaiting = card.waiting;
477
+ card = next;
478
+ if (card.waiting && !wasWaiting) focusAfterRender = 0;
479
+ render();
480
+ },
481
+ dispose() {
482
+ document.removeEventListener("keydown", onKey);
483
+ window.removeEventListener("focus", onFrameFocus);
484
+ style.remove();
485
+ },
486
+ };
487
+ }