@lune_99/pi-ask-question 0.1.0 → 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.
package/src/index.ts CHANGED
@@ -1,18 +1,38 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
 
3
3
  import { registerQuestionCommand } from "./commands/question.ts";
4
- import { reconcileQuestionDeliveries } from "./core/question-delivery.ts";
5
- import { ASK_QUESTION_ANSWER_MESSAGE, registerQuestionAnswerNotifications } from "./core/question-notification.ts";
6
- import { questionManager } from "./core/questionManager.ts";
4
+ import {
5
+ ASK_QUESTION_ANSWER_MESSAGE,
6
+ reconcileQuestionDeliveries,
7
+ registerQuestionAnswerNotifications,
8
+ releaseDeliveredQuestions,
9
+ type QuestionDeliveryOptions,
10
+ } from "./core/question-delivery.ts";
11
+ import { QuestionManager } from "./core/questionManager.ts";
7
12
  import { askUserQuestions } from "./tools/ask-user-questions.ts";
13
+ import { withdrawUserQuestions } from "./tools/withdraw-user-questions.ts";
8
14
  import {
9
15
  renderQuestionAnswerMessage,
10
16
  type AskQuestionAnswerMessageDetails,
11
17
  } from "./tui/question-answer-message.ts";
12
18
  import { createQuestionDockContribution } from "./tui/question-dock-contribution.ts";
13
- import { resetQuestionPanelState } from "./tui/panel/question-panel.ts";
19
+ import { QuestionPanels } from "./tui/panel/question-panel.ts";
14
20
 
15
21
  export default function (pi: ExtensionAPI): void {
22
+ installAskQuestion(pi);
23
+ }
24
+
25
+ /**
26
+ * Register the extension on `pi` and return the question manager of this load.
27
+ *
28
+ * The manager and the panel ownership belong to the load, not to the module: Pi reuses a loaded
29
+ * module for the sessions it starts in the same working directory, subagent runs included, and
30
+ * each of them owns its questions.
31
+ */
32
+ export function installAskQuestion(pi: ExtensionAPI): QuestionManager {
33
+ const questionManager = new QuestionManager();
34
+ const panels = new QuestionPanels(questionManager);
35
+
16
36
  /**
17
37
  * Write the question state, and report a failure instead of throwing it.
18
38
  *
@@ -32,33 +52,36 @@ export default function (pi: ExtensionAPI): void {
32
52
  }
33
53
  };
34
54
 
35
- const dock = createQuestionDockContribution(persist);
55
+ const dock = createQuestionDockContribution(questionManager, panels, persist);
36
56
 
37
57
  let unsubscribeManager: (() => void) | undefined;
38
58
  let unsubscribeNotifications: (() => void) | undefined;
39
59
 
40
- /** Report a delivery attempt that pi rejected synchronously; the outbox keeps the request. */
41
- const reportDeliveryFailure = (ctx: ExtensionContext, error: unknown): void => {
42
- ctx.ui.notify(
43
- `Question answers could not be delivered: ${error instanceof Error ? error.message : String(error)}`,
44
- "error",
45
- );
60
+ const unsubscribe = (): void => {
61
+ unsubscribeManager?.();
62
+ unsubscribeManager = undefined;
63
+ unsubscribeNotifications?.();
64
+ unsubscribeNotifications = undefined;
46
65
  };
47
66
 
67
+ /** Report a delivery attempt that pi rejected synchronously; the outbox keeps the request. */
68
+ const deliveryOptions = (ctx: ExtensionContext): QuestionDeliveryOptions => ({
69
+ onError: (error) => {
70
+ ctx.ui.notify(
71
+ `Question answers could not be delivered: ${error instanceof Error ? error.message : String(error)}`,
72
+ "error",
73
+ );
74
+ },
75
+ });
76
+
48
77
  pi.on("session_start", (_event, ctx) => {
49
78
  // The previous session's listeners close over its ctx and a duplicate subscription
50
79
  // would render and persist twice per event, so they go first - before the state
51
80
  // changes below would wake them.
52
- unsubscribeManager?.();
53
- unsubscribeManager = undefined;
54
- unsubscribeNotifications?.();
55
- unsubscribeNotifications = undefined;
81
+ unsubscribe();
56
82
  dock.detach({ retired: true });
57
83
 
58
- // Module state may survive extension reloads, so a session starts from its own
59
- // branch: clear first, then restore the question state recorded there.
60
- resetQuestionPanelState();
61
- questionManager.clearAll();
84
+ // A session starts from the question state recorded on its branch.
62
85
  questionManager.restore(ctx);
63
86
  dock.attach(ctx);
64
87
 
@@ -88,27 +111,32 @@ export default function (pi: ExtensionAPI): void {
88
111
 
89
112
  // Registered after the persist listener: the snapshot has to exist before the
90
113
  // answer message resumes the model.
91
- unsubscribeNotifications = registerQuestionAnswerNotifications(pi, {
92
- onError: (error) => reportDeliveryFailure(ctx, error),
93
- });
114
+ unsubscribeNotifications = registerQuestionAnswerNotifications(
115
+ pi,
116
+ questionManager,
117
+ deliveryOptions(ctx),
118
+ );
94
119
 
95
120
  // A session can start with settled answers whose message never reached the previous
96
121
  // one; the outbox is durable, so reconcile it against this branch. Confirmed answers
97
122
  // are released (and persisted), the rest are attempted again.
98
- reconcileQuestionDeliveries(pi, ctx, {
99
- onError: (error) => reportDeliveryFailure(ctx, error),
100
- });
123
+ reconcileQuestionDeliveries(pi, questionManager, ctx, deliveryOptions(ctx));
124
+ });
101
125
 
126
+ // A settled run has appended every answer message it accepted, so the confirmed ones leave
127
+ // the outbox here instead of riding along in every snapshot until the next session start.
128
+ pi.on("agent_settled", (_event, ctx) => {
129
+ releaseDeliveredQuestions(questionManager, ctx);
102
130
  });
103
131
 
104
132
  pi.on("session_shutdown", (_event, ctx) => {
105
133
  // Drafts change without a manager event, so the final snapshot is written here.
106
134
  persist(ctx);
107
- unsubscribeManager?.();
108
- unsubscribeManager = undefined;
109
- unsubscribeNotifications?.();
110
- unsubscribeNotifications = undefined;
135
+ unsubscribe();
111
136
  dock.detach();
137
+ // A panel that is still up belongs to the session that ends; the reset stops it from
138
+ // continuing after the boundary.
139
+ panels.reset();
112
140
  questionManager.clearAll();
113
141
  });
114
142
 
@@ -119,24 +147,25 @@ export default function (pi: ExtensionAPI): void {
119
147
  pi.on("session_tree", (_event, ctx) => {
120
148
  // The branch changed under the overlay, so a panel that is still up belongs to the
121
149
  // branch being left; the reset stops it from continuing into this one.
122
- resetQuestionPanelState();
150
+ panels.reset();
123
151
  questionManager.clearAll();
124
152
  questionManager.restore(ctx);
125
153
 
126
154
  // Reconciliation reads the branch that is active now, never the one being left:
127
155
  // branch A's undelivered answers must not be sent into branch B.
128
- reconcileQuestionDeliveries(pi, ctx, {
129
- onError: (error) => reportDeliveryFailure(ctx, error),
130
- });
156
+ reconcileQuestionDeliveries(pi, questionManager, ctx, deliveryOptions(ctx));
131
157
 
132
158
  dock.refresh();
133
159
  });
134
160
 
135
- pi.registerTool(askUserQuestions(persist));
136
- registerQuestionCommand(pi, persist);
161
+ pi.registerTool(askUserQuestions(questionManager, panels, persist));
162
+ pi.registerTool(withdrawUserQuestions(questionManager));
163
+ registerQuestionCommand(pi, questionManager, panels, persist);
137
164
 
138
165
  pi.registerMessageRenderer<AskQuestionAnswerMessageDetails>(
139
166
  ASK_QUESTION_ANSWER_MESSAGE,
140
167
  (message, _options, theme) => renderQuestionAnswerMessage(message.details, theme),
141
168
  );
169
+
170
+ return questionManager;
142
171
  }
@@ -2,43 +2,65 @@ import { defineTool, type ExtensionContext } from "@earendil-works/pi-coding-age
2
2
 
3
3
  import { Text } from "@earendil-works/pi-tui";
4
4
 
5
- import { formatPendingMessage, summarizeText } from "../core/question-format.ts";
6
- import { questionManager } from "../core/questionManager.ts";
7
- import { openQuestionPanel } from "../tui/panel/question-panel.ts";
5
+ import { committedRequestIds } from "../core/question-delivery.ts";
6
+ import {
7
+ formatAnswerMessage,
8
+ formatInterruptedMessage,
9
+ formatPendingMessage,
10
+ summarizeText,
11
+ } from "../core/question-format.ts";
12
+ import { toAnswerMessageQuestion, type QuestionManager } from "../core/questionManager.ts";
13
+ import type { AnswerMessageQuestion, AskQuestionAnswer } from "../core/question-types.ts";
14
+ import type { QuestionPanels } from "../tui/panel/question-panel.ts";
15
+ import { renderQuestionAnswerMessage } from "../tui/question-answer-message.ts";
8
16
 
9
17
  import Type from "typebox";
10
18
 
11
19
  export type AskUserQuestionsDetails =
12
20
  | {
13
- status: "pending";
14
- requestId: string;
15
- }
21
+ /** `waiting` is the partial result of a blocking call. */
22
+ status: "pending" | "waiting" | "interrupted";
23
+ requestId: string;
24
+ }
16
25
  | {
17
- status: "unavailable";
18
- };
26
+ status: "answered" | "skipped";
27
+ requestId: string;
28
+ questions: AnswerMessageQuestion[];
29
+ answers?: AskQuestionAnswer[];
30
+ }
31
+ | {
32
+ status: "unavailable";
33
+ };
19
34
 
20
35
  /**
21
- * The tool is asynchronous by design: it returns as soon as the panel is open, the model
22
- * keeps working on what it is sure about, and the answers arrive as a follow-up message.
36
+ * By default the tool does not wait: it returns as soon as the panel is open, the model keeps
37
+ * working on what it is sure about, and the answers arrive as a follow-up message. In block
38
+ * mode it waits until the user answers or skips, and returns that as its result.
23
39
  *
24
40
  * `persist` writes the pending questions (with drafts) into the session, which is what
25
41
  * keeps them answerable after Esc or a restart.
26
42
  */
27
- export function askUserQuestions(persist: (ctx: ExtensionContext) => void) {
43
+ export function askUserQuestions(
44
+ manager: QuestionManager,
45
+ panels: QuestionPanels,
46
+ persist: (ctx: ExtensionContext) => void,
47
+ ) {
28
48
  return defineTool({
29
49
  name: "ask_user_questions",
30
50
  label: "Ask User Questions",
51
+ // Each rule lives in one place: when and how to ask in the guidelines, what a field holds
52
+ // in its schema description. All of it is sent with every request.
31
53
  description:
32
- "Ask the user structured questions when their answer is needed to choose what to do next. Use this for user-owned decisions or meaningful tradeoffs that cannot be resolved from the conversation or workspace. The panel opens immediately and answers arrive later as a follow-up message.",
54
+ "Ask the user structured questions about user-owned decisions or meaningful tradeoffs. The panel opens immediately; answers arrive later as a follow-up message, or as this tool's result in block mode.",
33
55
 
34
56
  promptSnippet:
35
57
  "Ask for user-owned decisions; discover facts and use reasonable defaults yourself.",
36
58
 
37
59
  promptGuidelines: [
38
- "Ask only when the answer materially changes what you should do next; inspect the conversation and workspace first, and use reasonable defaults for low-impact choices.",
39
- "Ask the smallest set of questions needed. After calling the tool, continue independent work and stop only when further progress depends on the answers.",
40
- "Use option previews for concrete alternatives that benefit from visual comparison - code, configuration, structured text, or UI mockups - and do not add previews to simple preference questions. The pane is titled with the option label, so a preview must not repeat it; anything shared by every option belongs in displayText instead.",
41
- "Give every question a short header naming its subject ('Storage', 'Auth', 'Timeouts'); the panel shows it as the tab label. The header is required, so never number questions yourself or repeat the question text.",
60
+ "Ask only when the answer materially changes what you do next; inspect the conversation and workspace first, and use reasonable defaults for low-impact choices.",
61
+ "Use ask_user_questions mode 'block' when the next step depends on the answer and no independent work is left, to confirm a hard-to-undo action (delete, push, migrate), or when the choice controls most later work. Otherwise keep 'continue': do the independent work, and stop only when progress depends on the answers.",
62
+ "Add option previews only for concrete alternatives worth comparing - code, configuration, structured text or UI mockups - not for simple preferences. The pane is titled with the option label, so do not repeat it; content shared by every option belongs in displayText.",
63
+ "Give every question a short header naming its subject ('Storage', 'Auth', 'Timeouts'); it is the tab label, so never number questions or repeat the question text.",
42
64
  ],
43
65
  parameters: askUserQuestionsSchema,
44
66
  // The panel is a user interaction, not a nested-tool capability, and shared
@@ -46,7 +68,7 @@ export function askUserQuestions(persist: (ctx: ExtensionContext) => void) {
46
68
  exposure: "model-only",
47
69
  executionMode: "sequential",
48
70
 
49
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
71
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
50
72
  if (ctx.mode !== "tui") {
51
73
  return {
52
74
  content: [
@@ -60,37 +82,65 @@ export function askUserQuestions(persist: (ctx: ExtensionContext) => void) {
60
82
  };
61
83
  }
62
84
 
63
- const request = questionManager.create(params.questions);
85
+ const request = manager.create(params.questions, committedRequestIds(ctx));
86
+ const requestId = request.id;
87
+ // Registered before the panel opens, so the panel picks this request first.
88
+ const wait =
89
+ params.mode === "block" ? manager.waitForSettle(requestId, signal) : undefined;
90
+
91
+ // Not awaited: Esc closes the panel without an answer, so the overlay closing ends
92
+ // neither this call nor a wait.
93
+ void panels.open(ctx, { onDeferred: () => persist(ctx) });
94
+
95
+ if (!wait) {
96
+ return {
97
+ content: [{ type: "text" as const, text: formatPendingMessage(requestId) }],
98
+ details: { status: "pending", requestId } as AskUserQuestionsDetails,
99
+ };
100
+ }
101
+
102
+ onUpdate?.({
103
+ content: [{ type: "text" as const, text: "Waiting for the user's answers." }],
104
+ details: { status: "waiting", requestId } as AskUserQuestionsDetails,
105
+ });
64
106
 
65
- // Not awaited: the tool result is what lets the model keep working while the
66
- // user reads the panel.
67
- void openQuestionPanel(ctx, { onDeferred: () => persist(ctx) });
107
+ const outcome = await wait;
108
+
109
+ if (outcome.status === "interrupted") {
110
+ return {
111
+ content: [{ type: "text" as const, text: formatInterruptedMessage(requestId) }],
112
+ details: { status: "interrupted", requestId } as AskUserQuestionsDetails,
113
+ };
114
+ }
115
+
116
+ const settled = outcome.request;
68
117
 
69
118
  return {
70
- content: [
71
- {
72
- type: "text" as const,
73
- text: formatPendingMessage(),
74
- },
75
- ],
119
+ content: [{ type: "text" as const, text: formatAnswerMessage(settled) }],
76
120
  details: {
77
- status: "pending",
78
- requestId: request.id,
121
+ status: settled.status === "skipped" ? "skipped" : "answered",
122
+ requestId,
123
+ questions: settled.questions.map(toAnswerMessageQuestion),
124
+ answers: settled.answers,
79
125
  } as AskUserQuestionsDetails,
80
126
  };
81
127
  },
82
128
 
83
129
  renderCall(args, theme, _context) {
84
- const count = args.questions.length;
85
- const label = `${count} question${count === 1 ? "" : "s"}`;
130
+ // Pi renders the call while the model still streams its arguments, so any field can
131
+ // be missing yet. A throw here would swap the card for pi's raw-argument fallback.
132
+ const questions = Array.isArray(args.questions) ? args.questions : [];
133
+ const count = questions.length;
134
+ const label = `${count} question${count === 1 ? "" : "s"}${args.mode === "block" ? " · block" : ""}`;
86
135
 
87
- const lines = args.questions.map(
88
- (question) => theme.fg("text", summarizeText(question.question, 60)),
89
- );
136
+ const lines = questions
137
+ .filter((question) => typeof question?.question === "string")
138
+ .map((question) => theme.fg("text", summarizeText(question.question, 60)));
90
139
 
91
140
  return new Text(
92
- theme.fg("toolTitle", theme.bold("ask_user_questions ")) + theme.fg("muted", label) +
93
- (lines.length > 0 ? `\n${lines.join("\n")}` : ""),
141
+ theme.fg("toolTitle", theme.bold("ask_user_questions ")) +
142
+ theme.fg("muted", label) +
143
+ (lines.length > 0 ? `\n${lines.join("\n")}` : ""),
94
144
  0,
95
145
  0,
96
146
  );
@@ -99,16 +149,43 @@ export function askUserQuestions(persist: (ctx: ExtensionContext) => void) {
99
149
  renderResult(result, _options, theme, _context) {
100
150
  const details = result.details as AskUserQuestionsDetails | undefined;
101
151
 
102
- if (details?.status === "unavailable") {
103
- return new Text(theme.fg("error", result.content[0]?.type === "text" ? result.content[0].text : "unavailable"), 0, 0);
152
+ switch (details?.status) {
153
+ case "unavailable":
154
+ return new Text(
155
+ theme.fg(
156
+ "error",
157
+ result.content[0]?.type === "text"
158
+ ? result.content[0].text
159
+ : "unavailable",
160
+ ),
161
+ 0,
162
+ 0,
163
+ );
164
+ case "answered":
165
+ case "skipped":
166
+ return renderQuestionAnswerMessage(details, theme);
167
+ case "waiting":
168
+ return new Text(
169
+ theme.fg("warning", "the agent waits for your answer") +
170
+ theme.fg("dim", " · /question to reopen the panel"),
171
+ 0,
172
+ 0,
173
+ );
174
+ case "interrupted":
175
+ return new Text(
176
+ theme.fg("warning", "interrupted, still pending") +
177
+ theme.fg("dim", " · /question to answer"),
178
+ 0,
179
+ 0,
180
+ );
181
+ default:
182
+ return new Text(
183
+ theme.fg("warning", "waiting for the user") +
184
+ theme.fg("dim", " · /question to reopen the panel"),
185
+ 0,
186
+ 0,
187
+ );
104
188
  }
105
-
106
- return new Text(
107
- theme.fg("warning", "waiting for the user") +
108
- theme.fg("dim", " · /question to reopen the panel"),
109
- 0,
110
- 0,
111
- );
112
189
  },
113
190
  });
114
191
  }
@@ -118,20 +195,19 @@ const askUserQuestionsSchema = Type.Object({
118
195
  Type.Object({
119
196
  question: Type.String({
120
197
  description:
121
- "A single-sentence, atomic decision prompt shown to the user. Ask exactly one thing and include enough context to answer without reading surrounding prose.",
198
+ "One atomic decision prompt in a single sentence, with enough context to answer without reading surrounding prose.",
122
199
  }),
123
200
 
124
201
  header: Type.String({
125
202
  minLength: 1,
126
203
  maxLength: 16,
127
- description:
128
- "Short label naming this question's subject ('Storage', 'Auth', 'Timeouts'), shown as the tab label in the panel. Always provide it, keep it to a word or two, and never number the questions.",
204
+ description: "Tab label naming the question's subject in a word or two.",
129
205
  }),
130
206
 
131
207
  displayText: Type.Optional(
132
208
  Type.String({
133
209
  description:
134
- "Optional Markdown shown above the answer controls, the same for every option: the context or evidence the whole question needs, such as a diff, an excerpt, or the current values. It is not for generic explanation that belongs in the question or option descriptions, and anything that changes with the focused option belongs in that option's preview instead.",
210
+ "Markdown shown above the options, the same for every option: context or evidence the whole question needs, such as a diff, an excerpt or the current values.",
135
211
  }),
136
212
  ),
137
213
 
@@ -140,28 +216,27 @@ const askUserQuestionsSchema = Type.Object({
140
216
  Type.Object({
141
217
  label: Type.String({
142
218
  description:
143
- "Short, scannable user-visible choice label, preferably 1-5 words. If an option is clearly preferred, place it first and suffix the label with '(Recommended)'.",
219
+ "Short, scannable choice label, preferably 1-5 words. Put a clearly preferred option first and suffix its label with '(Recommended)'.",
144
220
  }),
145
221
 
146
222
  description: Type.Optional(
147
223
  Type.String({
148
224
  description:
149
- "One short sentence explaining the consequence, tradeoff, or meaning of selecting this option.",
225
+ "One short sentence on the consequence or tradeoff of this option.",
150
226
  }),
151
227
  ),
152
228
 
153
229
  preview: Type.Optional(
154
230
  Type.String({
155
231
  description:
156
- "Optional Markdown artifact for this one option, shown in a pane beside the options while it is focused and titled with its label. Use it when the choice is worth comparing rather than describing - a mockup, a code or config snippet, a concrete before/after - and keep it to roughly a dozen lines.",
232
+ "Markdown for this option only, shown beside the options while it is focused. Keep it to about a dozen lines.",
157
233
  }),
158
234
  ),
159
235
  }),
160
236
  {
161
237
  minItems: 2,
162
238
  maxItems: 4,
163
- description:
164
- "Two to four meaningful, mutually distinct choices. Omit the entire field for genuinely free-form input.",
239
+ description: "Two to four distinct choices. Omit for free-form input.",
165
240
  },
166
241
  ),
167
242
  ),
@@ -170,7 +245,7 @@ const askUserQuestionsSchema = Type.Object({
170
245
  Type.Boolean({
171
246
  default: false,
172
247
  description:
173
- "Whether multiple predefined options can validly apply at the same time. Keep false for mutually exclusive choices.",
248
+ "True when several options can apply at once; keep false for mutually exclusive choices.",
174
249
  }),
175
250
  ),
176
251
  }),
@@ -178,7 +253,18 @@ const askUserQuestionsSchema = Type.Object({
178
253
  minItems: 1,
179
254
  maxItems: 4,
180
255
  description:
181
- "Questions presented together in one panel. Prefer one question; batch up to four only when the decisions are independent and already known to be necessary.",
256
+ "Questions shown together in one panel. Prefer one; batch up to four only when the decisions are independent and already known to be necessary.",
182
257
  },
183
258
  ),
259
+
260
+ mode: Type.Optional(
261
+ // A plain string enum: some providers reject the anyOf/const schema of a literal union.
262
+ Type.Unsafe<"continue" | "block">({
263
+ type: "string",
264
+ enum: ["continue", "block"],
265
+ default: "continue",
266
+ description:
267
+ "'continue' returns at once and the answers arrive as a follow-up message; 'block' waits and returns them as this tool's result.",
268
+ }),
269
+ ),
184
270
  });
@@ -0,0 +1,169 @@
1
+ import { defineTool } from "@earendil-works/pi-coding-agent";
2
+
3
+ import { Text } from "@earendil-works/pi-tui";
4
+
5
+ import { committedRequestIds } from "../core/question-delivery.ts";
6
+ import { requestHeaders, singleLine, summarizeText } from "../core/question-format.ts";
7
+ import type { QuestionManager } from "../core/questionManager.ts";
8
+
9
+ import Type from "typebox";
10
+
11
+ export type WithdrawUserQuestionsDetails =
12
+ | {
13
+ status: "withdrawn";
14
+ requestId: string;
15
+ headers: string;
16
+ reason: string;
17
+ }
18
+ | {
19
+ /** The user answered or skipped first; the answer reaches the model anyway. */
20
+ status: "too-late";
21
+ requestId: string;
22
+ }
23
+ | {
24
+ status: "refused";
25
+ requestId: string;
26
+ };
27
+
28
+ /**
29
+ * Lets the agent take back its own pending question. The tool stays active at all times:
30
+ * switching tools on and off changes the system prompt and breaks the prompt cache.
31
+ */
32
+ export function withdrawUserQuestions(manager: QuestionManager) {
33
+ return defineTool({
34
+ name: "withdraw_user_questions",
35
+ label: "Withdraw User Questions",
36
+ description:
37
+ "Withdraw your own pending ask_user_questions request by its request id when it no longer needs the user's answer.",
38
+
39
+ promptSnippet: "Withdraw your own pending question when it no longer needs the user.",
40
+
41
+ promptGuidelines: [
42
+ "Withdraw a pending question when a file, tool or test answered it, the user answered it in a chat message, or the plan changed so it no longer matters; to improve a question, withdraw it and ask again.",
43
+ "Never withdraw because the user is slow or to decide a user-owned question yourself; if you withdraw and use a default, say which and why.",
44
+ ],
45
+ parameters: withdrawUserQuestionsSchema,
46
+ // It closes the shared panel, so it runs alone like `ask_user_questions`.
47
+ exposure: "model-only",
48
+ executionMode: "sequential",
49
+
50
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
51
+ const requestId = params.requestId.trim();
52
+ const reason = singleLine(params.reason);
53
+ const outcome = manager.withdraw(requestId, reason);
54
+
55
+ if (outcome.status === "withdrawn") {
56
+ return {
57
+ content: [
58
+ {
59
+ type: "text" as const,
60
+ text: `Withdrew request ${requestId}. The user will not answer it.`,
61
+ },
62
+ ],
63
+ details: {
64
+ status: "withdrawn",
65
+ requestId,
66
+ headers: requestHeaders(outcome.request),
67
+ reason,
68
+ } as WithdrawUserQuestionsDetails,
69
+ };
70
+ }
71
+
72
+ if (outcome.status === "waiting") {
73
+ return refused(
74
+ requestId,
75
+ `Request ${requestId} cannot be withdrawn: a blocking ask_user_questions call waits on it.`,
76
+ );
77
+ }
78
+
79
+ // A settled request leaves the outbox once its message is on the branch, so the
80
+ // branch is what still knows about it.
81
+ const inConversation = committedRequestIds(ctx).has(requestId);
82
+
83
+ if (outcome.status === "unknown" && !inConversation) {
84
+ return refused(requestId, `No pending question request has id ${requestId}.`);
85
+ }
86
+
87
+ const settled =
88
+ outcome.status !== "settled"
89
+ ? "answered or skipped"
90
+ : outcome.request.status === "skipped"
91
+ ? "skipped"
92
+ : "answered";
93
+
94
+ return {
95
+ content: [
96
+ {
97
+ type: "text" as const,
98
+ text: [
99
+ `Too late: the user already ${settled} request ${requestId}.`,
100
+ inConversation
101
+ ? "The answer message is already in the conversation."
102
+ : "The answer message will arrive as a follow-up message.",
103
+ ].join(" "),
104
+ },
105
+ ],
106
+ details: { status: "too-late", requestId } as WithdrawUserQuestionsDetails,
107
+ };
108
+ },
109
+
110
+ renderCall(args, theme, _context) {
111
+ // Pi renders the call while the model still streams its arguments.
112
+ const requestId = typeof args.requestId === "string" ? args.requestId : "";
113
+
114
+ return new Text(
115
+ theme.fg("toolTitle", theme.bold("withdraw_user_questions ")) +
116
+ theme.fg("muted", summarizeText(requestId, 40)),
117
+ 0,
118
+ 0,
119
+ );
120
+ },
121
+
122
+ renderResult(result, _options, theme, _context) {
123
+ const details = result.details as WithdrawUserQuestionsDetails | undefined;
124
+ const text = result.content[0]?.type === "text" ? result.content[0].text : "";
125
+
126
+ if (details?.status === "withdrawn") {
127
+ return new Text(
128
+ theme.bold(theme.fg("warning", "Question withdrawn")) +
129
+ theme.fg(
130
+ "muted",
131
+ [details.headers, details.reason]
132
+ .filter((part) => part.length > 0)
133
+ .map((part) => ` · ${summarizeText(part, 60)}`)
134
+ .join(""),
135
+ ),
136
+ 0,
137
+ 0,
138
+ );
139
+ }
140
+
141
+ return new Text(
142
+ theme.fg(details?.status === "too-late" ? "warning" : "error", text),
143
+ 0,
144
+ 0,
145
+ );
146
+ },
147
+ });
148
+ }
149
+
150
+ function refused(requestId: string, text: string) {
151
+ return {
152
+ content: [{ type: "text" as const, text }],
153
+ details: { status: "refused", requestId } as WithdrawUserQuestionsDetails,
154
+ isError: true,
155
+ };
156
+ }
157
+
158
+ const withdrawUserQuestionsSchema = Type.Object({
159
+ requestId: Type.String({
160
+ minLength: 1,
161
+ description: "The request id from the ask_user_questions result.",
162
+ }),
163
+
164
+ reason: Type.String({
165
+ minLength: 1,
166
+ description:
167
+ "Short reason shown to the user, such as 'answered by the test run' or 'replaced by a clearer question'.",
168
+ }),
169
+ });