@ftrdotdev/pi-inquiry 0.2.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.
@@ -0,0 +1,185 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import type { ExtensionUIContext, Theme } from "@earendil-works/pi-coding-agent";
3
+ import { KeybindingsManager, TUI_KEYBINDINGS } from "@earendil-works/pi-tui";
4
+ import { initialMachineState, step, type MachineState } from "../core/machine.ts";
5
+ import { KeyEvent } from "../core/keyboard.ts";
6
+ import { Option, Question } from "../core/domain.ts";
7
+ import { codePointToUtf16, makeSceneRenderer, runQuestionUi, utf16ToCodePoint } from "./pi-ui.ts";
8
+
9
+ describe("makeSceneRenderer cache", () => {
10
+ const fixture = (): { state: MachineState; theme: Theme; paints: () => number } => {
11
+ let count = 0;
12
+ const theme = {
13
+ fg: (_color: string, text: string): string => {
14
+ count++;
15
+ return text;
16
+ },
17
+ inverse: (text: string): string => {
18
+ count++;
19
+ return text;
20
+ },
21
+ bold: (text: string): string => text,
22
+ } as unknown as Theme;
23
+ const state = initialMachineState([
24
+ new Question({
25
+ id: "q1",
26
+ label: "Q1",
27
+ prompt: "Pick one?",
28
+ options: [new Option({ label: "Yes" }), new Option({ label: "No" })],
29
+ allowOther: true,
30
+ }),
31
+ ]);
32
+ return { state, theme, paints: () => count };
33
+ };
34
+
35
+ it("serves the cached lines across frames while state and width are unchanged", () => {
36
+ const { state, theme, paints } = fixture();
37
+ const cell = { state };
38
+ const scene = makeSceneRenderer(() => cell.state, theme);
39
+ const first = scene.render(40);
40
+ expect(paints()).toBeGreaterThan(0);
41
+ const before = paints();
42
+ expect(scene.render(40)).toBe(first); // same array, no repaint
43
+ expect(scene.render(40)).toBe(first);
44
+ expect(paints()).toBe(before);
45
+ });
46
+
47
+ it("repaints when the terminal width changes", () => {
48
+ const { state, theme, paints } = fixture();
49
+ const cell = { state };
50
+ const scene = makeSceneRenderer(() => cell.state, theme);
51
+ scene.render(40);
52
+ const before = paints();
53
+ const resized = scene.render(50);
54
+ expect(resized.length).toBeGreaterThan(0);
55
+ expect(paints()).toBeGreaterThan(before);
56
+ });
57
+
58
+ it("repaints when the machine emits a new state snapshot", () => {
59
+ const { state, theme, paints } = fixture();
60
+ const cell = { state };
61
+ const scene = makeSceneRenderer(() => cell.state, theme);
62
+ scene.render(40);
63
+ const before = paints();
64
+ cell.state = step(cell.state, KeyEvent.down).state; // fresh immutable snapshot
65
+ scene.render(40);
66
+ expect(paints()).toBeGreaterThan(before);
67
+ });
68
+
69
+ it("invalidate() forces a repaint so cached colors follow theme changes", () => {
70
+ const { state, theme, paints } = fixture();
71
+ const cell = { state };
72
+ const scene = makeSceneRenderer(() => cell.state, theme);
73
+ scene.render(40);
74
+ const before = paints();
75
+ scene.invalidate(); // the TUI calls this on theme changes
76
+ scene.render(40);
77
+ expect(paints()).toBeGreaterThan(before);
78
+ });
79
+ });
80
+
81
+ describe("runQuestionUi input routing", () => {
82
+ // A fake extension UI that captures the component returned by the custom
83
+ // factory and records tool-expansion toggles. `custom` never resolves — the
84
+ // questionnaire only closes when the flow calls `done`.
85
+ const makeFakeUi = (): {
86
+ ui: ExtensionUIContext;
87
+ component: () => { handleInput: (data: string) => void };
88
+ setToolsExpanded: ReturnType<typeof vi.fn>;
89
+ } => {
90
+ let expanded = false;
91
+ let component: { handleInput: (data: string) => void } | undefined;
92
+ // Mirror the app's KEYBINDINGS: TUI defaults plus the app.tools.expand
93
+ // action (default ctrl+o), so `matches` has real semantics.
94
+ const keybindings = new KeybindingsManager({
95
+ ...TUI_KEYBINDINGS,
96
+ "app.tools.expand": { defaultKeys: "ctrl+o" },
97
+ });
98
+ const ui = {
99
+ custom: (
100
+ factory: (
101
+ tui: unknown,
102
+ theme: unknown,
103
+ injectedKeybindings: unknown,
104
+ done: () => void,
105
+ ) => unknown,
106
+ ) => {
107
+ component = factory({ requestRender: () => {} }, {}, keybindings, () => {}) as {
108
+ handleInput: (data: string) => void;
109
+ };
110
+ return new Promise(() => {});
111
+ },
112
+ getToolsExpanded: () => expanded,
113
+ setToolsExpanded: vi.fn((value: boolean) => {
114
+ expanded = value;
115
+ }),
116
+ };
117
+ return {
118
+ ui: ui as unknown as ExtensionUIContext,
119
+ component: () => component!,
120
+ setToolsExpanded: ui.setToolsExpanded as unknown as ReturnType<typeof vi.fn>,
121
+ };
122
+ };
123
+
124
+ const questions = [
125
+ new Question({
126
+ id: "q1",
127
+ label: "Q1",
128
+ prompt: "Pick one?",
129
+ options: [new Option({ label: "Yes" })],
130
+ allowOther: true,
131
+ }),
132
+ ];
133
+
134
+ it("toggles tool output expansion on ctrl+o while the questionnaire is open", () => {
135
+ const { ui, component, setToolsExpanded } = makeFakeUi();
136
+ void runQuestionUi(ui, questions, "/tmp");
137
+ component().handleInput("\x0f"); // ctrl+o
138
+ expect(setToolsExpanded).toHaveBeenCalledWith(true);
139
+ component().handleInput("\x0f");
140
+ expect(setToolsExpanded).toHaveBeenCalledWith(false);
141
+ });
142
+
143
+ it("does not treat other keys as the expand toggle", () => {
144
+ const { ui, component, setToolsExpanded } = makeFakeUi();
145
+ void runQuestionUi(ui, questions, "/tmp");
146
+ // ctrl+e is not the expand toggle by default.
147
+ component().handleInput("\x05");
148
+ expect(setToolsExpanded).not.toHaveBeenCalled();
149
+ });
150
+
151
+ it("does not swallow question-flow keys", () => {
152
+ const { ui, component, setToolsExpanded } = makeFakeUi();
153
+ void runQuestionUi(ui, questions, "/tmp");
154
+ // 'a' is a printable character the flow feeds into the answer editor.
155
+ component().handleInput("a");
156
+ expect(setToolsExpanded).not.toHaveBeenCalled();
157
+ });
158
+ });
159
+
160
+ describe("cursor unit conversion", () => {
161
+ it("round-trips ASCII text", () => {
162
+ const text = "@src/main.ts";
163
+ for (let i = 0; i <= text.length; i++) {
164
+ expect(utf16ToCodePoint(text, codePointToUtf16(text, i))).toBe(i);
165
+ }
166
+ });
167
+
168
+ it("counts surrogate pairs as single code points", () => {
169
+ // 😀 is 2 UTF-16 code units but 1 code point
170
+ const text = "😀 @s";
171
+ expect(codePointToUtf16(text, 0)).toBe(0);
172
+ expect(codePointToUtf16(text, 1)).toBe(2); // after the emoji
173
+ expect(codePointToUtf16(text, 2)).toBe(3); // after the space
174
+ expect(codePointToUtf16(text, 4)).toBe(5); // end of text
175
+ expect(utf16ToCodePoint(text, 5)).toBe(4);
176
+ expect(utf16ToCodePoint(text, 2)).toBe(1);
177
+ });
178
+
179
+ it("clamps out-of-range cursors", () => {
180
+ expect(codePointToUtf16("ab", 99)).toBe(2);
181
+ expect(codePointToUtf16("ab", -1)).toBe(0);
182
+ expect(utf16ToCodePoint("ab", 99)).toBe(2);
183
+ expect(utf16ToCodePoint("ab", -1)).toBe(0);
184
+ });
185
+ });
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Bridge between the pure Effect core and pi's custom UI.
3
+ *
4
+ * The flow program runs on a forked fiber. `handleInput` parses raw key data
5
+ * into core key events and feeds them through a queue; `render` builds the
6
+ * scene from the latest machine state at the current terminal width; `done`
7
+ * resolves the custom-UI promise when the flow completes.
8
+ *
9
+ * This is the thickest part of the fringe. Everything above this file in the
10
+ * core is pi-free.
11
+ */
12
+
13
+ import { Effect, Fiber, Queue } from "effect";
14
+ import { existsSync } from "fs";
15
+ import { homedir } from "os";
16
+ import { delimiter, join } from "path";
17
+ import { CombinedAutocompleteProvider } from "@earendil-works/pi-tui";
18
+ import type { ExtensionUIContext, Theme } from "@earendil-works/pi-coding-agent";
19
+ import { QuestionResult, type Question } from "../core/domain.ts";
20
+ import { initialMachineState, type MachineState } from "../core/machine.ts";
21
+ import { buildScene } from "../core/scene.ts";
22
+ import { FileSuggestions, Keyboard, Renderer } from "../core/services.ts";
23
+ import { runQuestionnaire } from "../core/flow.ts";
24
+ import type { KeyEvent } from "../core/keyboard.ts";
25
+ import { parseKey } from "./keys.ts";
26
+ import { paintScene } from "./painter.ts";
27
+
28
+ export const runQuestionUi = (
29
+ ui: ExtensionUIContext,
30
+ questions: readonly Question[],
31
+ cwd: string,
32
+ ): Promise<QuestionResult> =>
33
+ ui.custom<QuestionResult>((tui, theme, keybindings, done) => {
34
+ const keys = Effect.runSync(Queue.unbounded<KeyEvent>());
35
+ const cell: { state: MachineState } = { state: initialMachineState(questions) };
36
+
37
+ const keyboard: Keyboard["Service"] = {
38
+ nextKey: () => Queue.take(keys),
39
+ };
40
+ const renderer: Renderer["Service"] = {
41
+ present: (state) =>
42
+ Effect.sync(() => {
43
+ cell.state = state;
44
+ tui.requestRender();
45
+ }),
46
+ complete: (result) =>
47
+ Effect.sync(() => {
48
+ done(result);
49
+ }),
50
+ };
51
+
52
+ const fiber = Effect.runFork(
53
+ runQuestionnaire(questions).pipe(
54
+ Effect.provideService(Keyboard, keyboard),
55
+ Effect.provideService(Renderer, renderer),
56
+ Effect.provideService(FileSuggestions, makeFileSuggestions(cwd)),
57
+ Effect.catchCause((cause) =>
58
+ Effect.sync(() => {
59
+ console.error("question flow failed", cause);
60
+ done(new QuestionResult({ questions: [...questions], answers: [], cancelled: true }));
61
+ }),
62
+ ),
63
+ ),
64
+ );
65
+
66
+ // Width/state-keyed render cache: the TUI calls render() on every
67
+ // frame, but the scene only changes when the machine emits a new
68
+ // snapshot or the terminal is resized (tui.md "Performance").
69
+ const scene = makeSceneRenderer(() => cell.state, theme);
70
+ return {
71
+ render: (width) => scene.render(width),
72
+ invalidate: () => {
73
+ scene.invalidate();
74
+ tui.requestRender();
75
+ },
76
+ handleInput: (data) => {
77
+ // app.tools.expand (default ctrl+o): keep the transcript's tool-output
78
+ // expansion toggle working while the questionnaire owns input focus.
79
+ // The app only routes app actions through the editor, which is not
80
+ // focused here, so intercept the key ourselves. keybindings.matches()
81
+ // honors the user's keybindings.json (rebinds, "[]" disables).
82
+ if (keybindings.matches(data, "app.tools.expand")) {
83
+ ui.setToolsExpanded(!ui.getToolsExpanded());
84
+ return;
85
+ }
86
+ const key = parseKey(data);
87
+ if (key) Effect.runSync(Queue.offer(keys, key));
88
+ },
89
+ dispose: () => {
90
+ Effect.runSync(Fiber.interrupt(fiber));
91
+ },
92
+ };
93
+ });
94
+
95
+ /**
96
+ * Width/state-keyed scene renderer for the question box (tui.md
97
+ * "Performance"). `buildScene` is pure and the machine emits a fresh
98
+ * immutable snapshot on every transition, so identical (width, state) pairs
99
+ * always paint identical lines — the cache serves those lines across TUI
100
+ * frames while nothing changed, instead of rebuilding and repainting the
101
+ * scene. `invalidate()` clears the cache: the TUI calls it on theme changes,
102
+ * so the ANSI colors baked into cached lines are always rebuilt from the
103
+ * current theme.
104
+ */
105
+ export const makeSceneRenderer = (
106
+ getState: () => MachineState,
107
+ theme: Theme,
108
+ ): { render(width: number): string[]; invalidate(): void } => {
109
+ let cachedWidth: number | undefined;
110
+ let cachedState: MachineState | undefined;
111
+ let cachedLines: string[] | undefined;
112
+ return {
113
+ render(width: number): string[] {
114
+ const state = getState();
115
+ if (cachedLines !== undefined && cachedState === state && cachedWidth === width) {
116
+ return cachedLines;
117
+ }
118
+ cachedState = state;
119
+ cachedWidth = width;
120
+ cachedLines = paintScene(buildScene(state, width), theme);
121
+ return cachedLines;
122
+ },
123
+ invalidate(): void {
124
+ cachedWidth = undefined;
125
+ cachedState = undefined;
126
+ cachedLines = undefined;
127
+ },
128
+ };
129
+ };
130
+
131
+ /**
132
+ * File completion for the inline editor, backed by pi-tui's
133
+ * `CombinedAutocompleteProvider` — the same machinery the main editor uses —
134
+ * so `@` suggestions (fuzzy search, `~` expansion, quoted prefixes, directory
135
+ * continuation) behave identically. Slash commands are not offered: the
136
+ * editor takes a free-text answer.
137
+ *
138
+ * The core editor addresses characters by code point; the provider works in
139
+ * UTF-16 code units, so both directions are converted at this seam.
140
+ */
141
+ const makeFileSuggestions = (cwd: string): FileSuggestions["Service"] => {
142
+ const provider = new CombinedAutocompleteProvider([], cwd, resolveFdPath());
143
+ return {
144
+ query: (text, cursor, force) =>
145
+ Effect.tryPromise(() =>
146
+ provider.getSuggestions([text], 0, codePointToUtf16(text, cursor), {
147
+ signal: new AbortController().signal,
148
+ force: force ?? false,
149
+ }),
150
+ ).pipe(
151
+ Effect.map((result) =>
152
+ result === null ? null : { prefix: result.prefix, items: result.items },
153
+ ),
154
+ // A failed lookup just closes the popup; it must never break the flow.
155
+ Effect.catch(() => Effect.succeed(null)),
156
+ ),
157
+ apply: (text, cursor, item, prefix) =>
158
+ Effect.sync(() => {
159
+ const applied = provider.applyCompletion(
160
+ [text],
161
+ 0,
162
+ codePointToUtf16(text, cursor),
163
+ item,
164
+ prefix,
165
+ );
166
+ const line = applied.lines[0] ?? "";
167
+ return { text: line, cursor: utf16ToCodePoint(line, applied.cursorCol) };
168
+ }),
169
+ };
170
+ };
171
+
172
+ /** Code-point index (core editor unit) -> UTF-16 code-unit offset. */
173
+ export const codePointToUtf16 = (text: string, cursor: number): number =>
174
+ Array.from(text)
175
+ .slice(0, Math.max(0, Math.min(cursor, Array.from(text).length)))
176
+ .join("").length;
177
+
178
+ /** UTF-16 code-unit offset -> code-point index. */
179
+ export const utf16ToCodePoint = (text: string, offset: number): number =>
180
+ Array.from(text.slice(0, Math.max(0, Math.min(offset, text.length)))).length;
181
+
182
+ /**
183
+ * Locate the `fd` binary used by the provider for fuzzy file search.
184
+ *
185
+ * pi ensures `fd` is available at startup (downloading it into the agent bin
186
+ * dir when the system lacks it), so check the system PATH first, then pi's
187
+ * managed bin dirs. Returns undefined when unavailable; the provider then
188
+ * yields no `@` candidates, matching the main editor without fd.
189
+ */
190
+ const resolveFdPath = (): string | undefined => {
191
+ for (const name of ["fd", "fdfind"]) {
192
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
193
+ if (dir !== "" && existsSync(join(dir, name))) return name;
194
+ }
195
+ }
196
+ const agentDirs = [
197
+ process.env.PI_CODING_AGENT_DIR,
198
+ process.env.TAU_CODING_AGENT_DIR,
199
+ join(homedir(), ".pi", "agent"),
200
+ join(homedir(), ".config", "pi", "agent"),
201
+ ];
202
+ for (const dir of agentDirs) {
203
+ if (!dir) continue;
204
+ for (const name of ["fd", "fdfind"]) {
205
+ const candidate = join(dir, "bin", name);
206
+ if (existsSync(candidate)) return candidate;
207
+ }
208
+ }
209
+ return undefined;
210
+ };
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Pins the contract between the Effect-generated parameter schema and pi's
3
+ * runtime validation. `validateToolCall` is the real pipeline pi runs on
4
+ * every tool call: prepareArguments -> typebox Convert/Compile/Check.
5
+ */
6
+ import { describe, expect, it } from "vitest";
7
+ import { validateToolCall } from "@earendil-works/pi-ai";
8
+ import { QuestionListParamsJsonSchema } from "../core/domain.ts";
9
+
10
+ type ToolLike = Parameters<typeof validateToolCall>[0];
11
+ type ToolCallLike = Parameters<typeof validateToolCall>[1];
12
+
13
+ const tools = [
14
+ { name: "question", parameters: QuestionListParamsJsonSchema },
15
+ ] as unknown as ToolLike;
16
+ const call = (arguments_: unknown) =>
17
+ ({ name: "question", arguments: arguments_ }) as unknown as ToolCallLike;
18
+
19
+ describe("pi validation of the generated schema", () => {
20
+ it("accepts valid arguments", () => {
21
+ const args = { questions: [{ prompt: "Pick?", options: [{ label: "Yes" }] }] };
22
+ expect(validateToolCall(tools, call(args))).toEqual(args);
23
+ });
24
+
25
+ it("accepts full arguments with ids, labels and allowOther", () => {
26
+ const args = {
27
+ questions: [
28
+ {
29
+ id: "scope",
30
+ label: "Scope",
31
+ prompt: "Pick?",
32
+ options: [{ label: "A", description: "desc" }],
33
+ allowOther: false,
34
+ },
35
+ ],
36
+ };
37
+ expect(validateToolCall(tools, call(args))).toEqual(args);
38
+ });
39
+
40
+ it("tolerates legacy extra option keys such as value", () => {
41
+ const args = { questions: [{ prompt: "p", options: [{ value: "yes", label: "Yes" }] }] };
42
+ expect(validateToolCall(tools, call(args))).toEqual(args);
43
+ });
44
+
45
+ it("coerces stringified booleans", () => {
46
+ const args = { questions: [{ prompt: "p", options: [{ label: "a" }], allowOther: "false" }] };
47
+ expect(validateToolCall(tools, call(args))).toEqual({
48
+ questions: [{ prompt: "p", options: [{ label: "a" }], allowOther: false }],
49
+ });
50
+ });
51
+
52
+ it("accepts an empty questions array (handled in execute)", () => {
53
+ expect(validateToolCall(tools, call({ questions: [] }))).toEqual({ questions: [] });
54
+ });
55
+
56
+ it("rejects arguments missing questions", () => {
57
+ expect(() => validateToolCall(tools, call({}))).toThrow(
58
+ /Validation failed for tool "question"/,
59
+ );
60
+ });
61
+
62
+ it("rejects a question missing its options", () => {
63
+ expect(() => validateToolCall(tools, call({ questions: [{ prompt: "p" }] }))).toThrow(
64
+ /questions\.0\.options/,
65
+ );
66
+ });
67
+ });
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Pins the tool registration contract: name, discovery content, the
3
+ * parameter schema (single-sourced from the core), and the legacy
4
+ * prepareArguments shim wiring.
5
+ */
6
+ import { describe, expect, it } from "vitest";
7
+ import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
8
+ import question from "./question.ts";
9
+ import { QuestionListParamsJsonSchema } from "../core/domain.ts";
10
+
11
+ const register = (): ToolDefinition<any, unknown, any> => {
12
+ let captured: ToolDefinition<any, unknown, any> | undefined;
13
+ const fakeApi = {
14
+ registerTool: (tool: ToolDefinition<any, unknown, any>) => {
15
+ captured = tool;
16
+ },
17
+ } as unknown as ExtensionAPI;
18
+ question(fakeApi);
19
+ if (!captured) throw new Error("registerTool was not called");
20
+ return captured;
21
+ };
22
+
23
+ describe("question tool registration", () => {
24
+ it("registers under the legacy name with a stable label", () => {
25
+ const tool = register();
26
+ expect(tool.name).toBe("question");
27
+ expect(tool.label).toBe("Question");
28
+ expect(tool.executionMode).toBe("sequential");
29
+ });
30
+
31
+ it("describes when to use the tool", () => {
32
+ const tool = register();
33
+ expect(tool.description).toContain("multiple-choice questions");
34
+ expect(tool.description).toContain("Prefer this over asking in plain text");
35
+ });
36
+
37
+ it("provides a prompt snippet naming the tool", () => {
38
+ const tool = register();
39
+ expect(tool.promptSnippet).toBeTruthy();
40
+ expect(tool.promptSnippet).toContain("question");
41
+ });
42
+
43
+ it("provides guidelines that each name the tool", () => {
44
+ const tool = register();
45
+ expect(tool.promptGuidelines).toHaveLength(4);
46
+ for (const bullet of tool.promptGuidelines ?? []) {
47
+ expect(bullet).toContain("question");
48
+ }
49
+ expect(tool.promptGuidelines?.join("\n")).toContain(
50
+ "instead of ending your reply with a question",
51
+ );
52
+ });
53
+
54
+ it("uses the core-generated schema as parameters (single source)", () => {
55
+ const tool = register();
56
+ expect(tool.parameters).toBe(QuestionListParamsJsonSchema);
57
+ expect(JSON.stringify(tool.parameters)).toBe(JSON.stringify(QuestionListParamsJsonSchema));
58
+ });
59
+
60
+ it("wires the legacy prepareArguments shim", () => {
61
+ const tool = register();
62
+ const prepared = tool.prepareArguments?.({
63
+ question: "Go?",
64
+ options: [{ label: "Yes" }],
65
+ });
66
+ expect(prepared).toEqual({ questions: [{ prompt: "Go?", options: [{ label: "Yes" }] }] });
67
+ const passthrough = { questions: [{ prompt: "p", options: [{ label: "a" }] }] };
68
+ expect(tool.prepareArguments?.(passthrough)).toBe(passthrough);
69
+ });
70
+ });