@ftrdotdev/pi-inquiry 0.8.0 → 0.9.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/src/sdk/pi-ui.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * core is pi-free.
11
11
  */
12
12
 
13
- import { Effect, Fiber, Queue } from "effect";
13
+ import { Effect, Fiber, Queue, Schema } from "effect";
14
14
  import { existsSync } from "fs";
15
15
  import { homedir } from "os";
16
16
  import { delimiter, join } from "path";
@@ -27,6 +27,7 @@ import { FileSuggestions, Keyboard, Renderer } from "../core/services.ts";
27
27
  import { runQuestionnaire } from "../core/flow.ts";
28
28
  import type { KeyEvent } from "../core/keyboard.ts";
29
29
  import { parseKey } from "./keys.ts";
30
+ import { isNonEmptyString } from "../core/text.ts";
30
31
  import { paintScene } from "./painter.ts";
31
32
 
32
33
  /**
@@ -36,108 +37,121 @@ import { paintScene } from "./painter.ts";
36
37
  */
37
38
  export const questionClipboardText = (state: MachineState): string => {
38
39
  const question = state.questions[state.currentTab];
39
- if (!question) return "";
40
+ if (question === undefined) return "";
40
41
  const lines = [question.prompt, ...question.options.map((o, i) => `${i + 1}. ${o.label}`)];
41
42
  if (question.allowOther) lines.push(`${question.options.length + 1}. Type something.`);
42
43
  return lines.join("\n");
43
44
  };
44
45
 
46
+ /**
47
+ * Program-status message (OSC 7501) shown while the questionnaire waits.
48
+ * The message is fixed text: pi reports blocked prompts, and model output
49
+ * must never reach the program-status stream.
50
+ */
51
+ const blockedMessage = (questions: readonly Question[]): string =>
52
+ questions.length > 1 ? `Answer ${questions.length} questions` : "Answer the question";
53
+
45
54
  export const runQuestionUi = (
46
55
  ui: ExtensionUIContext,
47
56
  questions: readonly Question[],
48
57
  cwd: string,
49
58
  ): Promise<QuestionResult> =>
50
- ui.custom<QuestionResult>((tui, theme, keybindings, done) => {
51
- const keys = Effect.runSync(Queue.unbounded<KeyEvent>());
52
- const cell: { state: MachineState } = { state: initialMachineState(questions) };
53
-
54
- const keyboard: Keyboard["Service"] = {
55
- nextKey: () => Queue.take(keys),
56
- };
57
- const renderer: Renderer["Service"] = {
58
- present: (state) =>
59
- Effect.sync(() => {
60
- cell.state = state;
61
- tui.requestRender();
62
- }),
63
- complete: (result) =>
64
- Effect.sync(() => {
65
- done(result);
66
- }),
67
- };
59
+ ui.custom<QuestionResult>(
60
+ (tui, theme, keybindings, done) => {
61
+ const keys = Effect.runSync(Queue.unbounded<KeyEvent>());
62
+ const cell: { state: MachineState } = { state: initialMachineState(questions) };
68
63
 
69
- const fiber = Effect.runFork(
70
- runQuestionnaire(questions).pipe(
71
- Effect.provideService(Keyboard, keyboard),
72
- Effect.provideService(Renderer, renderer),
73
- Effect.provideService(FileSuggestions, makeFileSuggestions(cwd)),
74
- Effect.catchCause((cause) =>
64
+ const keyboard: Keyboard["Service"] = {
65
+ nextKey: Queue.take(keys),
66
+ };
67
+ const renderer: Renderer["Service"] = {
68
+ present: (state) =>
75
69
  Effect.sync(() => {
76
- console.error("question flow failed", cause);
77
- done(new QuestionResult({ questions: [...questions], answers: [], cancelled: true }));
70
+ cell.state = state;
71
+ tui.requestRender();
78
72
  }),
73
+ complete: (result) =>
74
+ Effect.sync(() => {
75
+ done(result);
76
+ }),
77
+ };
78
+
79
+ const fiber = Effect.runFork(
80
+ runQuestionnaire(questions).pipe(
81
+ Effect.provideService(Keyboard, keyboard),
82
+ Effect.provideService(Renderer, renderer),
83
+ Effect.provideService(FileSuggestions, makeFileSuggestions(cwd)),
84
+ Effect.catchCause((cause) =>
85
+ Effect.sync(() => {
86
+ console.error("question flow failed", cause);
87
+ done(
88
+ QuestionResult.make({ questions: [...questions], answers: [], cancelled: true }),
89
+ );
90
+ }),
91
+ ),
79
92
  ),
80
- ),
81
- );
93
+ );
82
94
 
83
- // Width/state-keyed render cache: the TUI calls render() on every
84
- // frame, but the scene only changes when the machine emits a new
85
- // snapshot or the terminal is resized (tui.md "Performance").
86
- const scene = makeSceneRenderer(() => cell.state, theme);
95
+ // Width/state-keyed render cache: the TUI calls render() on every
96
+ // frame, but the scene only changes when the machine emits a new
97
+ // snapshot or the terminal is resized (tui.md "Performance").
98
+ const scene = makeSceneRenderer(() => cell.state, theme);
87
99
 
88
- const feed = (data: string): void => {
89
- // app.tools.expand (default ctrl+o): keep the transcript's tool-output
90
- // expansion toggle working while the questionnaire owns input focus.
91
- // The app only routes app actions through the editor, which is not
92
- // focused here, so intercept the key ourselves. keybindings.matches()
93
- // honors the user's keybindings.json (rebinds, "[]" disables).
94
- if (keybindings.matches(data, "app.tools.expand")) {
95
- ui.setToolsExpanded(!ui.getToolsExpanded());
96
- return;
97
- }
98
- // ctrl+y copies the current question's text. The core has no binding
99
- // for it, so it never reaches the keyboard queue.
100
- if (data === "\x19") {
101
- const text = questionClipboardText(cell.state);
102
- if (text !== "") {
103
- void copyToClipboard(text).then(
104
- () => ui.notify("Copied question"),
105
- (cause: unknown) =>
106
- ui.notify(
107
- `Copy failed: ${cause instanceof Error ? cause.message : String(cause)}`,
108
- "error",
109
- ),
110
- );
100
+ const feed = (data: string): void => {
101
+ // app.tools.expand (default ctrl+o): keep the transcript's tool-output
102
+ // expansion toggle working while the questionnaire owns input focus.
103
+ // The app only routes app actions through the editor, which is not
104
+ // focused here, so intercept the key ourselves. keybindings.matches()
105
+ // honors the user's keybindings.json (rebinds, "[]" disables).
106
+ if (keybindings.matches(data, "app.tools.expand")) {
107
+ ui.setToolsExpanded(!ui.getToolsExpanded());
108
+ return;
111
109
  }
112
- return;
113
- }
114
- const key = parseKey(data);
115
- if (key) Effect.runSync(Queue.offer(keys, key));
116
- };
110
+ // ctrl+y copies the current question's text. The core has no binding
111
+ // for it, so it never reaches the keyboard queue.
112
+ if (data === "\x19") {
113
+ const text = questionClipboardText(cell.state);
114
+ if (text !== "") {
115
+ void copyToClipboard(text).then(
116
+ () => ui.notify("Copied question"),
117
+ (cause: unknown) =>
118
+ ui.notify(
119
+ `Copy failed: ${cause instanceof Error ? cause.message : String(cause)}`,
120
+ "error",
121
+ ),
122
+ );
123
+ }
124
+ return;
125
+ }
126
+ const key = parseKey(data);
127
+ if (key !== null) Effect.runSync(Queue.offer(keys, key));
128
+ };
117
129
 
118
- return {
119
- render: (width) => scene.render(width),
120
- invalidate: () => {
121
- scene.invalidate();
122
- tui.requestRender();
123
- },
124
- handleInput: feed,
125
- // pi normalizes wheel events to logical lines (the renderer applies
126
- // `WheelScrollAccelerator`), so the delta is the step count directly.
127
- // Reuse the arrow-key path so wheel and keyboard share one cursor model.
128
- handleMouse: (event) => {
129
- if (event.type !== "wheel") return undefined;
130
- const delta = event.wheelDelta ?? 0;
131
- if (delta === 0) return { handled: false };
132
- const arrow = delta > 0 ? "\x1b[B" : "\x1b[A";
133
- for (let i = 0; i < Math.abs(delta); i++) feed(arrow);
134
- return { handled: true };
135
- },
136
- dispose: () => {
137
- Effect.runSync(Fiber.interrupt(fiber));
138
- },
139
- };
140
- });
130
+ return {
131
+ render: (width) => scene.render(width),
132
+ invalidate: () => {
133
+ scene.invalidate();
134
+ tui.requestRender();
135
+ },
136
+ handleInput: feed,
137
+ // pi normalizes wheel events to logical lines (the renderer applies
138
+ // `WheelScrollAccelerator`), so the delta is the step count directly.
139
+ // Reuse the arrow-key path so wheel and keyboard share one cursor model.
140
+ handleMouse: (event) => {
141
+ if (event.type !== "wheel") return undefined;
142
+ const delta = event.wheelDelta ?? 0;
143
+ if (delta === 0) return { handled: false };
144
+ const arrow = delta > 0 ? "\x1b[B" : "\x1b[A";
145
+ for (let i = 0; i < Math.abs(delta); i++) feed(arrow);
146
+ return { handled: true };
147
+ },
148
+ dispose: () => {
149
+ Fiber.interrupt(fiber).pipe(Effect.runSync);
150
+ },
151
+ };
152
+ },
153
+ { blocked: { kind: "question", message: blockedMessage(questions) } },
154
+ );
141
155
 
142
156
  /**
143
157
  * Width/state-keyed scene renderer for the question box (tui.md
@@ -175,6 +189,15 @@ export const makeSceneRenderer = (
175
189
  };
176
190
  };
177
191
 
192
+ /**
193
+ * A failed completion lookup. The popup closes on any failure, so the error
194
+ * carries the cause for tracing only; it never reaches the user.
195
+ */
196
+ class CompletionLookupError extends Schema.TaggedError<
197
+ CompletionLookupError,
198
+ { readonly brand: unique symbol }
199
+ >()("CompletionLookupError", { cause: Schema.Unknown }) {}
200
+
178
201
  /**
179
202
  * File completion for the inline editor, backed by pi-tui's
180
203
  * `CombinedAutocompleteProvider` — the same machinery the main editor uses —
@@ -189,17 +212,19 @@ const makeFileSuggestions = (cwd: string): FileSuggestions["Service"] => {
189
212
  const provider = new CombinedAutocompleteProvider([], cwd, resolveFdPath());
190
213
  return {
191
214
  query: (text, cursor, force) =>
192
- Effect.tryPromise(() =>
193
- provider.getSuggestions([text], 0, codePointToUtf16(text, cursor), {
194
- signal: new AbortController().signal,
195
- force: force ?? false,
196
- }),
197
- ).pipe(
215
+ Effect.tryPromise({
216
+ try: () =>
217
+ provider.getSuggestions([text], 0, codePointToUtf16(text, cursor), {
218
+ signal: new AbortController().signal,
219
+ force: force ?? false,
220
+ }),
221
+ catch: (cause) => CompletionLookupError.make({ cause }),
222
+ }).pipe(
198
223
  Effect.map((result) =>
199
224
  result === null ? null : { prefix: result.prefix, items: result.items },
200
225
  ),
201
226
  // A failed lookup just closes the popup; it must never break the flow.
202
- Effect.catch(() => Effect.succeed(null)),
227
+ Effect.orElseSucceed(() => null),
203
228
  ),
204
229
  apply: (text, cursor, item, prefix) =>
205
230
  Effect.sync(() => {
@@ -247,7 +272,7 @@ const resolveFdPath = (): string | undefined => {
247
272
  join(homedir(), ".config", "pi", "agent"),
248
273
  ];
249
274
  for (const dir of agentDirs) {
250
- if (!dir) continue;
275
+ if (!isNonEmptyString(dir)) continue;
251
276
  for (const name of ["fd", "fdfind"]) {
252
277
  const candidate = join(dir, "bin", name);
253
278
  if (existsSync(candidate)) return candidate;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Pins the contract between the Effect-generated parameter schema and pi's
3
3
  * runtime validation. `validateToolCall` is the real pipeline pi runs on
4
- * every tool call: prepareArguments -> typebox Convert/Compile/Check.
4
+ * every tool call: prepareArguments -> pi-schema coercion and validation.
5
5
  */
6
6
  import { describe, expect, it } from "vitest";
7
7
  import { validateToolCall } from "@earendil-works/pi-ai";
@@ -86,7 +86,7 @@ describe("pi validation of the generated schema", () => {
86
86
  tools,
87
87
  call({ questions: [{ prompt: "p", options: [{ label: "a", recommended: "yes" }] }] }),
88
88
  ),
89
- ).toThrow(/recommended.*must be boolean/);
89
+ ).toThrow(/recommended: expected boolean, got string/);
90
90
  });
91
91
 
92
92
  it("accepts an empty questions array (handled in execute)", () => {
@@ -4,12 +4,9 @@
4
4
  * prepareArguments shim wiring.
5
5
  */
6
6
  import { describe, expect, it, vi } from "vitest";
7
- import type {
8
- ExtensionAPI,
9
- ExtensionToolContext,
10
- Theme,
11
- ToolDefinition,
12
- } from "@earendil-works/pi-coding-agent";
7
+ import { themeDouble } from "@ftrdotdev/pi-test-kit";
8
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
9
+ import { inquiryApiDouble, questionCtxDouble } from "../../test-support/doubles.ts";
13
10
  import question from "./question.ts";
14
11
  import {
15
12
  Answer,
@@ -21,23 +18,20 @@ import {
21
18
 
22
19
  const register = (): ToolDefinition<any, unknown, any> => {
23
20
  let captured: ToolDefinition<any, unknown, any> | undefined;
24
- const fakeApi = {
21
+ const fakeApi = inquiryApiDouble({
25
22
  registerTool: (tool: ToolDefinition<any, unknown, any>) => {
26
23
  captured = tool;
27
24
  },
28
- } as unknown as ExtensionAPI;
25
+ });
29
26
  question(fakeApi);
30
- if (!captured) throw new Error("registerTool was not called");
27
+ if (captured === undefined) throw new Error("registerTool was not called");
31
28
  return captured;
32
29
  };
33
30
 
34
31
  /** Theme double: every style and colour returns its text unchanged. */
35
- const theme = {
36
- style: (text: string) => text,
37
- fg: (_color: string, text: string) => text,
38
- } as unknown as Theme;
32
+ const theme = themeDouble();
39
33
 
40
- const rendered = (component: { render(width: number): string[] }): string =>
34
+ const rendered = (component: { render(width: number): readonly string[] }): string =>
41
35
  component
42
36
  .render(200)
43
37
  .map((l) => l.trimEnd())
@@ -137,21 +131,21 @@ describe("question tool renderers and execute (unchanged surfaces)", () => {
137
131
 
138
132
  it("execute keeps the marker out of the answer text", async () => {
139
133
  const tool = register();
140
- const recorded = new Question({
134
+ const recorded = Question.make({
141
135
  id: "q1",
142
136
  label: "Q1",
143
137
  prompt: "Pick one?",
144
- options: [new Option({ label: "First", recommended: true })],
138
+ options: [Option.make({ label: "First", recommended: true })],
145
139
  allowOther: false,
146
140
  multiple: false,
147
141
  });
148
- const result = new QuestionResult({
142
+ const result = QuestionResult.make({
149
143
  questions: [recorded],
150
- answers: [new Answer({ id: "q1", label: "First", wasCustom: false, index: 1 })],
144
+ answers: [Answer.make({ id: "q1", label: "First", wasCustom: false, index: 1 })],
151
145
  cancelled: false,
152
146
  });
153
147
  const custom = vi.fn(() => Promise.resolve(result));
154
- const ctx = { mode: "tui", ui: { custom } } as unknown as ExtensionToolContext;
148
+ const ctx = questionCtxDouble({ mode: "tui", ui: { custom } });
155
149
  const out = await tool.execute(
156
150
  "call-1",
157
151
  {
@@ -177,7 +171,7 @@ describe("question tool execute: invalid recommendations", () => {
177
171
  it("returns one invalid-parameters message and cancelled details without opening the UI", async () => {
178
172
  const tool = register();
179
173
  const custom = vi.fn();
180
- const ctx = { mode: "tui", ui: { custom } } as unknown as ExtensionToolContext;
174
+ const ctx = questionCtxDouble({ mode: "tui", ui: { custom } });
181
175
  const out = await tool.execute(
182
176
  "call-1",
183
177
  {
@@ -11,7 +11,6 @@
11
11
 
12
12
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
13
  import { Text } from "@earendil-works/pi-tui";
14
- import type { TSchema } from "typebox";
15
14
  import {
16
15
  QuestionListParamsJsonSchema,
17
16
  decodeParams,
@@ -61,7 +60,7 @@ export default function question(pi: ExtensionAPI) {
61
60
  description:
62
61
  "Ask the user one or more multiple-choice questions. The tool returns the user's answers. Use the tool when you need input from the user. Clarify requirements, choose an approach, or confirm a decision. Prefer this over asking in plain text. A single question shows an option list. Multiple questions show a tabbed interface with a submit tab. The user can also type a custom answer. Set multiple: true to ask for one or more answers as checkboxes.",
63
62
  // Single source of truth: generated from the Effect schema in the core.
64
- parameters: QuestionListParamsJsonSchema as TSchema,
63
+ parameters: QuestionListParamsJsonSchema,
65
64
  promptSnippet: questionToolSystemPromptContribution.snippet,
66
65
  promptGuidelines: [...questionToolSystemPromptContribution.guidelines],
67
66
  executionMode: "sequential",
@@ -152,7 +151,7 @@ export default function question(pi: ExtensionAPI) {
152
151
  let text =
153
152
  theme.style("question ", { fg: "toolTitle", bold: true }) +
154
153
  theme.fg("muted", `${qs.length} questions`);
155
- if (labels) {
154
+ if (labels !== "") {
156
155
  text += theme.fg("dim", ` (${labels})`);
157
156
  }
158
157
  return new Text(text, 0, 0);
@@ -166,11 +165,11 @@ export default function question(pi: ExtensionAPI) {
166
165
  cancelled?: boolean;
167
166
  }
168
167
  | undefined;
169
- if (!details || !Array.isArray(details.answers)) {
168
+ if (details === undefined || !Array.isArray(details.answers)) {
170
169
  const text = result.content[0];
171
170
  return new Text(text?.type === "text" ? text.text : "", 0, 0);
172
171
  }
173
- if (details.cancelled) {
172
+ if (details.cancelled ?? false) {
174
173
  return new Text(theme.fg("warning", "Cancelled"), 0, 0);
175
174
  }
176
175
  // Group by question so a multi-select answer renders as one line.
@@ -184,7 +183,7 @@ export default function question(pi: ExtensionAPI) {
184
183
  const parts = ans.map((a) =>
185
184
  a.wasCustom
186
185
  ? `${theme.fg("muted", "(wrote) ")}${a.label}`
187
- : `${a.index ? `${a.index}. ` : ""}${a.label}`,
186
+ : `${a.index !== undefined ? `${a.index}. ` : ""}${a.label}`,
188
187
  );
189
188
  return `${theme.fg("success", "✓ ")}${theme.fg("accent", id)}: ${parts.join(", ")}`;
190
189
  });