@lune_99/pi-ask-question 0.0.0-stage → 0.1.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/CHANGELOG.md +66 -0
- package/LICENSE +21 -0
- package/README.md +101 -2
- package/docs/question-answer-row.png +0 -0
- package/docs/question-answer-row.svg +16 -0
- package/docs/question-dock.png +0 -0
- package/docs/question-dock.svg +8 -0
- package/docs/question-panel.png +0 -0
- package/docs/question-panel.svg +58 -0
- package/package.json +62 -5
- package/src/commands/question.ts +25 -0
- package/src/core/question-delivery.ts +111 -0
- package/src/core/question-format.ts +109 -0
- package/src/core/question-notification.ts +34 -0
- package/src/core/question-types.ts +91 -0
- package/src/core/questionManager.ts +484 -0
- package/src/index.ts +142 -0
- package/src/tools/ask-user-questions.ts +184 -0
- package/src/tui/panel/question-panel-controller.ts +261 -0
- package/src/tui/panel/question-panel-renderer.ts +813 -0
- package/src/tui/panel/question-panel.ts +702 -0
- package/src/tui/preview/preview-box.ts +168 -0
- package/src/tui/preview/preview-layout.ts +116 -0
- package/src/tui/preview/preview-renderer.ts +129 -0
- package/src/tui/question-answer-message.ts +42 -0
- package/src/tui/question-dock-contribution.ts +41 -0
- package/src/tui/question-dock.ts +68 -0
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
ExtensionAPI,
|
|
5
|
+
ExtensionContext,
|
|
6
|
+
} from "@earendil-works/pi-coding-agent";
|
|
7
|
+
|
|
8
|
+
import type {
|
|
9
|
+
AskQuestion,
|
|
10
|
+
AskQuestionAnswer,
|
|
11
|
+
AskQuestionDraft,
|
|
12
|
+
AskQuestionRequest,
|
|
13
|
+
AskQuestionStateSnapshot,
|
|
14
|
+
} from "./question-types.ts";
|
|
15
|
+
|
|
16
|
+
export type {
|
|
17
|
+
AnswerMessageQuestion,
|
|
18
|
+
AskQuestion,
|
|
19
|
+
AskQuestionAnswer,
|
|
20
|
+
AskQuestionDraft,
|
|
21
|
+
AskQuestionOption,
|
|
22
|
+
AskQuestionRequest,
|
|
23
|
+
AskQuestionStateSnapshot,
|
|
24
|
+
AskQuestionStatus,
|
|
25
|
+
} from "./question-types.ts";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Custom session entry holding the question state.
|
|
29
|
+
*
|
|
30
|
+
* A question outlives the turn that asked it: the user may close the panel with Esc,
|
|
31
|
+
* quit Pi, and answer after a restart. The snapshot is written whenever the pending
|
|
32
|
+
* set, a draft or the delivery outbox changes at a settle point, and read back from
|
|
33
|
+
* the active branch.
|
|
34
|
+
*/
|
|
35
|
+
export const QUESTION_STATE_ENTRY = "pi-ask-question-state";
|
|
36
|
+
|
|
37
|
+
export type QuestionManagerEvent =
|
|
38
|
+
| { type: "request-created"; id: string }
|
|
39
|
+
| { type: "request-shown"; id: string }
|
|
40
|
+
| { type: "request-answered"; id: string }
|
|
41
|
+
| { type: "request-skipped"; id: string }
|
|
42
|
+
| { type: "request-delivered"; id: string }
|
|
43
|
+
| { type: "requests-restored" }
|
|
44
|
+
| { type: "requests-cleared" };
|
|
45
|
+
|
|
46
|
+
export type QuestionManagerListener = (event: QuestionManagerEvent) => void;
|
|
47
|
+
export type QuestionManagerListenerErrorHandler = (error: unknown, event: QuestionManagerEvent) => void;
|
|
48
|
+
|
|
49
|
+
export class QuestionManager {
|
|
50
|
+
private readonly pending = new Map<string, AskQuestionRequest>();
|
|
51
|
+
/**
|
|
52
|
+
* Settled requests whose answer message is not confirmed in the session yet.
|
|
53
|
+
*
|
|
54
|
+
* `pi.sendMessage()` is only an attempt: pi can queue a steered message and drop it
|
|
55
|
+
* before it reaches the session. A settled request therefore stays here - durable and
|
|
56
|
+
* out of the pending queue - until the branch really carries its message.
|
|
57
|
+
*/
|
|
58
|
+
private readonly outbox = new Map<string, AskQuestionRequest>();
|
|
59
|
+
private readonly listeners = new Map<QuestionManagerListener, QuestionManagerListenerErrorHandler | undefined>();
|
|
60
|
+
private shownSeqCounter = 0;
|
|
61
|
+
|
|
62
|
+
create(questions: readonly AskQuestion[]): AskQuestionRequest {
|
|
63
|
+
const request: AskQuestionRequest = {
|
|
64
|
+
id: randomUUID(),
|
|
65
|
+
createdAt: Date.now(),
|
|
66
|
+
questions: questions.map(copyQuestion),
|
|
67
|
+
status: "pending",
|
|
68
|
+
draft: emptyDraft(questions.length),
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
this.pending.set(request.id, request);
|
|
72
|
+
this.emit({ type: "request-created", id: request.id });
|
|
73
|
+
|
|
74
|
+
return request;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
get(id: string): Readonly<AskQuestionRequest> | undefined {
|
|
78
|
+
return this.pending.get(id) ?? this.outbox.get(id);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Pending requests oldest first; this is the order they were created in. */
|
|
82
|
+
getPendingRequests(): readonly AskQuestionRequest[] {
|
|
83
|
+
return Array.from(this.pending.values())
|
|
84
|
+
.sort((left, right) => left.createdAt - right.createdAt);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The pending request the panel should show next.
|
|
89
|
+
*
|
|
90
|
+
* Least recently shown first, with a request that was never shown ahead of all of them: a
|
|
91
|
+
* question that just arrived has to surface immediately, while one the user dismissed with
|
|
92
|
+
* Esc must not pop back up in front of it. Requests that were never shown fall back to the
|
|
93
|
+
* order they were created in.
|
|
94
|
+
*/
|
|
95
|
+
nextPendingRequest(): AskQuestionRequest | undefined {
|
|
96
|
+
let next: AskQuestionRequest | undefined;
|
|
97
|
+
|
|
98
|
+
for (const request of this.getPendingRequests()) {
|
|
99
|
+
if (next === undefined || shownOrder(request) < shownOrder(next)) {
|
|
100
|
+
next = request;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return next;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Record that the panel is showing `id`, which moves it behind the requests it passed.
|
|
109
|
+
*
|
|
110
|
+
* The event is what keeps every ordering reader in step: the dock names the request this
|
|
111
|
+
* moved to the front, and the new `shownSeq` reaches the next snapshot with it.
|
|
112
|
+
*/
|
|
113
|
+
markShown(id: string): void {
|
|
114
|
+
const request = this.getPendingRequest(id);
|
|
115
|
+
|
|
116
|
+
if (request) {
|
|
117
|
+
request.shownSeq = ++this.shownSeqCounter;
|
|
118
|
+
this.emit({ type: "request-shown", id });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
getPendingRequest(id: string): AskQuestionRequest | undefined {
|
|
123
|
+
return this.pending.get(id);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The panel owns the pending request's draft and mutates it in place, so a snapshot
|
|
128
|
+
* always sees the latest focus and written text without a separate write path.
|
|
129
|
+
*/
|
|
130
|
+
submit(id: string, answers: readonly AskQuestionAnswer[]): boolean {
|
|
131
|
+
const request = this.getPendingRequest(id);
|
|
132
|
+
|
|
133
|
+
// Settling is idempotent: a submit can race a skip or a shutdown, and only the
|
|
134
|
+
// first one may count (or be delivered twice).
|
|
135
|
+
if (!request) {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
request.status = "answered";
|
|
140
|
+
request.answers = answers.map(copyAnswer);
|
|
141
|
+
request.settledAt = Date.now();
|
|
142
|
+
|
|
143
|
+
// Settling is one move: out of the pending queue, into the durable outbox. The
|
|
144
|
+
// request must not be asked again, but its payload has to survive until pi's
|
|
145
|
+
// session really carries the answer message. The draft stays with the panel: keeping
|
|
146
|
+
// it would duplicate a written answer in the outbox and the snapshot.
|
|
147
|
+
request.draft = emptyDraft(request.questions.length);
|
|
148
|
+
this.pending.delete(id);
|
|
149
|
+
this.outbox.set(id, request);
|
|
150
|
+
|
|
151
|
+
this.emit({ type: "request-answered", id });
|
|
152
|
+
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
skip(id: string): boolean {
|
|
157
|
+
const request = this.getPendingRequest(id);
|
|
158
|
+
|
|
159
|
+
if (!request) {
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
request.status = "skipped";
|
|
164
|
+
request.settledAt = Date.now();
|
|
165
|
+
|
|
166
|
+
// A skip is delivered as a custom message too, so it takes the same durable path
|
|
167
|
+
// as an answer: dropping it from the outbox would lose the model's only notice.
|
|
168
|
+
request.draft = emptyDraft(request.questions.length);
|
|
169
|
+
this.pending.delete(id);
|
|
170
|
+
this.outbox.set(id, request);
|
|
171
|
+
|
|
172
|
+
this.emit({ type: "request-skipped", id });
|
|
173
|
+
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Settled requests whose answer message is not confirmed in the session yet. */
|
|
178
|
+
getUndeliveredRequests(): readonly Readonly<AskQuestionRequest>[] {
|
|
179
|
+
return Array.from(this.outbox.values())
|
|
180
|
+
.sort((left, right) => left.createdAt - right.createdAt);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Release a settled request once its message is confirmed to be on the session branch.
|
|
185
|
+
*
|
|
186
|
+
* The event is what makes the persistence listener write an outbox without it, so a
|
|
187
|
+
* later restore cannot bring it back and deliver a second copy.
|
|
188
|
+
*/
|
|
189
|
+
acknowledgeDelivery(id: string): boolean {
|
|
190
|
+
if (!this.outbox.delete(id)) {
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
this.emit({ type: "request-delivered", id });
|
|
195
|
+
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Drop every request, pending or not; a session starts from its own branch. */
|
|
200
|
+
clearAll(): void {
|
|
201
|
+
if (this.pending.size === 0 && this.outbox.size === 0) {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
this.pending.clear();
|
|
206
|
+
this.outbox.clear();
|
|
207
|
+
this.emit({ type: "requests-cleared" });
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Persist the pending requests (with drafts) and the delivery outbox into the session of `pi`. */
|
|
211
|
+
persist(pi: ExtensionAPI): void {
|
|
212
|
+
pi.appendEntry(QUESTION_STATE_ENTRY, this.snapshot());
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
snapshot(): AskQuestionStateSnapshot {
|
|
216
|
+
return {
|
|
217
|
+
requests: this.getPendingRequests().map((request) => structuredClone(request)),
|
|
218
|
+
outbox: this.getUndeliveredRequests().map((request) => structuredClone(request)),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Restore the newest snapshot on the active branch; the newest state always wins. */
|
|
223
|
+
restore(ctx: ExtensionContext): void {
|
|
224
|
+
const branch = ctx.sessionManager.getBranch();
|
|
225
|
+
|
|
226
|
+
for (let index = branch.length - 1; index >= 0; index--) {
|
|
227
|
+
const entry = branch[index];
|
|
228
|
+
|
|
229
|
+
if (!entry || entry.type !== "custom" || entry.customType !== QUESTION_STATE_ENTRY) {
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const snapshot = entry.data as Partial<AskQuestionStateSnapshot> | undefined;
|
|
234
|
+
|
|
235
|
+
// The newest state entry wins, but only when it matches the schema this build
|
|
236
|
+
// writes; a malformed snapshot is not guessed at and not patched over.
|
|
237
|
+
if (snapshot && Array.isArray(snapshot.requests) && Array.isArray(snapshot.outbox)) {
|
|
238
|
+
this.restoreSnapshot(snapshot as AskQuestionStateSnapshot);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* `onError` reports a listener that threw. Passing one is what keeps a failure visible:
|
|
247
|
+
* the listener that writes the snapshot is also the one whose failure would silently
|
|
248
|
+
* lose it, and the others must keep running either way.
|
|
249
|
+
*/
|
|
250
|
+
subscribe(listener: QuestionManagerListener, onError?: QuestionManagerListenerErrorHandler): () => void {
|
|
251
|
+
this.listeners.set(listener, onError);
|
|
252
|
+
|
|
253
|
+
return () => {
|
|
254
|
+
this.listeners.delete(listener);
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
private restoreSnapshot(snapshot: AskQuestionStateSnapshot): void {
|
|
259
|
+
let restored = false;
|
|
260
|
+
|
|
261
|
+
for (const saved of snapshot.requests) {
|
|
262
|
+
// A live request with the same id is newer than the snapshot; the entry is
|
|
263
|
+
// only a fallback for state this process no longer has.
|
|
264
|
+
if (!isStoredRequest(saved) || this.hasRequest(saved.id)) {
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
this.pending.set(saved.id, normalizePendingRequest(saved));
|
|
269
|
+
this.shownSeqCounter = Math.max(this.shownSeqCounter, saved.shownSeq ?? 0);
|
|
270
|
+
restored = true;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Settled requests are restored as settled: turning them back into pending would
|
|
274
|
+
// ask the user again, and dropping them would lose an answer the model never saw.
|
|
275
|
+
for (const saved of snapshot.outbox) {
|
|
276
|
+
if (!isStoredRequest(saved) || this.hasRequest(saved.id)) {
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const settled = normalizeSettledRequest(saved);
|
|
281
|
+
|
|
282
|
+
if (!settled) {
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
this.outbox.set(settled.id, settled);
|
|
287
|
+
restored = true;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (restored) {
|
|
291
|
+
this.emit({ type: "requests-restored" });
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Whether either queue already holds `id`; a snapshot never replaces live state. */
|
|
296
|
+
private hasRequest(id: string): boolean {
|
|
297
|
+
return this.pending.has(id) || this.outbox.has(id);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
private emit(event: QuestionManagerEvent): void {
|
|
301
|
+
for (const [listener, onError] of this.listeners) {
|
|
302
|
+
try {
|
|
303
|
+
listener(event);
|
|
304
|
+
} catch (error) {
|
|
305
|
+
// One failing listener cannot break the others, but its failure is reported
|
|
306
|
+
// rather than hidden: it may be the one that persists the snapshot.
|
|
307
|
+
this.reportListenerError(onError, error, event);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
private reportListenerError(
|
|
313
|
+
onError: QuestionManagerListenerErrorHandler | undefined,
|
|
314
|
+
error: unknown,
|
|
315
|
+
event: QuestionManagerEvent,
|
|
316
|
+
): void {
|
|
317
|
+
try {
|
|
318
|
+
onError?.(error, event);
|
|
319
|
+
} catch {
|
|
320
|
+
// The reporter is the last line of defence; its own failure must not surface as a
|
|
321
|
+
// broken emit either.
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function copyQuestion(question: AskQuestion): AskQuestion {
|
|
327
|
+
return {
|
|
328
|
+
...question,
|
|
329
|
+
// A stored entry can be malformed; `options` has to be an array before it is mapped.
|
|
330
|
+
options: Array.isArray(question.options)
|
|
331
|
+
? question.options.map((option) => ({ ...option }))
|
|
332
|
+
: undefined,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function copyAnswer(answer: AskQuestionAnswer): AskQuestionAnswer {
|
|
337
|
+
return createAnswer(
|
|
338
|
+
Array.isArray(answer.selectedIndexes) ? [...answer.selectedIndexes] : [],
|
|
339
|
+
typeof answer.customText === "string" && answer.customText.length > 0 ? answer.customText : undefined,
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Custom text is a separate kind of answer, so an unset one is omitted instead of `undefined`. */
|
|
344
|
+
function createAnswer(selectedIndexes: number[], customText: string | undefined): AskQuestionAnswer {
|
|
345
|
+
return customText === undefined
|
|
346
|
+
? { selectedIndexes }
|
|
347
|
+
: { selectedIndexes, customText };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** A stored answer can come from an older or hand-edited session entry, so it is validated. */
|
|
351
|
+
function normalizeAnswer(value: unknown): AskQuestionAnswer | undefined {
|
|
352
|
+
if (!value || typeof value !== "object") {
|
|
353
|
+
return undefined;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const candidate = value as { selectedIndexes?: unknown; customText?: unknown };
|
|
357
|
+
|
|
358
|
+
const selectedIndexes = Array.isArray(candidate.selectedIndexes)
|
|
359
|
+
? candidate.selectedIndexes.filter(
|
|
360
|
+
(index): index is number => typeof index === "number" && Number.isInteger(index) && index >= 0,
|
|
361
|
+
)
|
|
362
|
+
: [];
|
|
363
|
+
const customText = typeof candidate.customText === "string" && candidate.customText.length > 0
|
|
364
|
+
? candidate.customText
|
|
365
|
+
: undefined;
|
|
366
|
+
|
|
367
|
+
if (selectedIndexes.length === 0 && customText === undefined) {
|
|
368
|
+
return undefined;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
return createAnswer(selectedIndexes, customText);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function emptyDraft(questionCount: number): AskQuestionDraft {
|
|
375
|
+
return {
|
|
376
|
+
currentIndex: 0,
|
|
377
|
+
optionIndex: 0,
|
|
378
|
+
answers: new Array(questionCount).fill(undefined),
|
|
379
|
+
customDrafts: new Array(questionCount).fill(undefined),
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function normalizePendingRequest(saved: AskQuestionRequest): AskQuestionRequest {
|
|
384
|
+
return {
|
|
385
|
+
id: saved.id,
|
|
386
|
+
createdAt: typeof saved.createdAt === "number" ? saved.createdAt : Date.now(),
|
|
387
|
+
shownSeq: typeof saved.shownSeq === "number" && Number.isFinite(saved.shownSeq) ? saved.shownSeq : undefined,
|
|
388
|
+
questions: saved.questions.map(copyQuestion),
|
|
389
|
+
status: "pending",
|
|
390
|
+
draft: normalizeDraft(saved.draft, saved.questions.length),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* A settled outbox entry read back from a snapshot.
|
|
396
|
+
*
|
|
397
|
+
* Only the delivery payload is kept: a settled request never reopens, so its draft is not
|
|
398
|
+
* restored as panel state. An answered entry without valid answers cannot be delivered and
|
|
399
|
+
* is not guessed at.
|
|
400
|
+
*/
|
|
401
|
+
function normalizeSettledRequest(saved: AskQuestionRequest): AskQuestionRequest | undefined {
|
|
402
|
+
if (saved.status !== "answered" && saved.status !== "skipped") {
|
|
403
|
+
return undefined;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const request: AskQuestionRequest = {
|
|
407
|
+
id: saved.id,
|
|
408
|
+
createdAt: typeof saved.createdAt === "number" ? saved.createdAt : Date.now(),
|
|
409
|
+
questions: saved.questions.map(copyQuestion),
|
|
410
|
+
status: saved.status,
|
|
411
|
+
draft: emptyDraft(saved.questions.length),
|
|
412
|
+
settledAt: typeof saved.settledAt === "number" ? saved.settledAt : Date.now(),
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
if (saved.status === "answered") {
|
|
416
|
+
const answers = normalizeAnswers(saved.answers);
|
|
417
|
+
|
|
418
|
+
if (!answers) {
|
|
419
|
+
return undefined;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
request.answers = answers;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
return request;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** A settled answer list from durable state; every entry has to be a real answer. */
|
|
429
|
+
function normalizeAnswers(saved: unknown): AskQuestionAnswer[] | undefined {
|
|
430
|
+
if (!Array.isArray(saved) || saved.length === 0) {
|
|
431
|
+
return undefined;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const answers = saved.map((answer) => normalizeAnswer(answer));
|
|
435
|
+
|
|
436
|
+
return answers.every((answer): answer is AskQuestionAnswer => answer !== undefined) ? answers : undefined;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** Requests that were never shown sort before every shown one. */
|
|
440
|
+
function shownOrder(request: AskQuestionRequest): number {
|
|
441
|
+
return request.shownSeq ?? -1;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function normalizeDraft(draft: AskQuestionDraft | undefined, questionCount: number): AskQuestionDraft {
|
|
445
|
+
const normalized = emptyDraft(questionCount);
|
|
446
|
+
|
|
447
|
+
if (!draft) {
|
|
448
|
+
return normalized;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
normalized.currentIndex = clampIndex(draft.currentIndex, questionCount);
|
|
452
|
+
normalized.optionIndex = Math.max(0, draft.optionIndex ?? 0);
|
|
453
|
+
normalized.answers = normalized.answers.map((_, index) => normalizeAnswer(draft.answers?.[index]));
|
|
454
|
+
normalized.customDrafts = normalized.customDrafts.map((_, index) => {
|
|
455
|
+
const text = draft.customDrafts?.[index];
|
|
456
|
+
|
|
457
|
+
return typeof text === "string" ? text : undefined;
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
return normalized;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** The panel may have been closed on the submit tab, so the index can reach `questionCount`. */
|
|
464
|
+
function clampIndex(index: number, questionCount: number): number {
|
|
465
|
+
if (!Number.isFinite(index)) {
|
|
466
|
+
return 0;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
return Math.min(questionCount, Math.max(0, Math.trunc(index)));
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function isStoredRequest(value: unknown): value is AskQuestionRequest {
|
|
473
|
+
if (!value || typeof value !== "object") {
|
|
474
|
+
return false;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const request = value as Partial<AskQuestionRequest>;
|
|
478
|
+
|
|
479
|
+
return typeof request.id === "string" && Array.isArray(request.questions);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// Shared singleton: its state outlives extension reloads, which is why the extension
|
|
483
|
+
// clears it on session start before restoring from the branch.
|
|
484
|
+
export const questionManager = new QuestionManager();
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
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";
|
|
7
|
+
import { askUserQuestions } from "./tools/ask-user-questions.ts";
|
|
8
|
+
import {
|
|
9
|
+
renderQuestionAnswerMessage,
|
|
10
|
+
type AskQuestionAnswerMessageDetails,
|
|
11
|
+
} from "./tui/question-answer-message.ts";
|
|
12
|
+
import { createQuestionDockContribution } from "./tui/question-dock-contribution.ts";
|
|
13
|
+
import { resetQuestionPanelState } from "./tui/panel/question-panel.ts";
|
|
14
|
+
|
|
15
|
+
export default function (pi: ExtensionAPI): void {
|
|
16
|
+
/**
|
|
17
|
+
* Write the question state, and report a failure instead of throwing it.
|
|
18
|
+
*
|
|
19
|
+
* Everything that persists does a lifecycle step right after - the overlay closes, the
|
|
20
|
+
* session shuts down, the branch switches - and a throw from `appendEntry` would leave
|
|
21
|
+
* that step half done. The user still has to learn that the state will not survive a
|
|
22
|
+
* restart, so the failure is shown rather than dropped.
|
|
23
|
+
*/
|
|
24
|
+
const persist = (ctx: ExtensionContext): void => {
|
|
25
|
+
try {
|
|
26
|
+
questionManager.persist(pi);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
ctx.ui.notify(
|
|
29
|
+
`Question state could not be saved: ${error instanceof Error ? error.message : String(error)}`,
|
|
30
|
+
"error",
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const dock = createQuestionDockContribution(persist);
|
|
36
|
+
|
|
37
|
+
let unsubscribeManager: (() => void) | undefined;
|
|
38
|
+
let unsubscribeNotifications: (() => void) | undefined;
|
|
39
|
+
|
|
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
|
+
);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
pi.on("session_start", (_event, ctx) => {
|
|
49
|
+
// The previous session's listeners close over its ctx and a duplicate subscription
|
|
50
|
+
// would render and persist twice per event, so they go first - before the state
|
|
51
|
+
// changes below would wake them.
|
|
52
|
+
unsubscribeManager?.();
|
|
53
|
+
unsubscribeManager = undefined;
|
|
54
|
+
unsubscribeNotifications?.();
|
|
55
|
+
unsubscribeNotifications = undefined;
|
|
56
|
+
dock.detach({ retired: true });
|
|
57
|
+
|
|
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();
|
|
62
|
+
questionManager.restore(ctx);
|
|
63
|
+
dock.attach(ctx);
|
|
64
|
+
|
|
65
|
+
unsubscribeManager = questionManager.subscribe(
|
|
66
|
+
(event) => {
|
|
67
|
+
try {
|
|
68
|
+
// `requests-cleared` is the session-boundary reset, not a state change;
|
|
69
|
+
// writing an empty snapshot there would shadow the pending questions of
|
|
70
|
+
// the branch being restored.
|
|
71
|
+
if (event.type !== "requests-cleared") {
|
|
72
|
+
persist(ctx);
|
|
73
|
+
}
|
|
74
|
+
} finally {
|
|
75
|
+
// A snapshot that failed must not also leave the dock showing stale order.
|
|
76
|
+
dock.refresh();
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
(error) => {
|
|
80
|
+
// Persistence reports its own failures; this is for a listener that threw for
|
|
81
|
+
// another reason, such as the dock render.
|
|
82
|
+
ctx.ui.notify(
|
|
83
|
+
`Question dock could not be updated: ${error instanceof Error ? error.message : String(error)}`,
|
|
84
|
+
"error",
|
|
85
|
+
);
|
|
86
|
+
},
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
// Registered after the persist listener: the snapshot has to exist before the
|
|
90
|
+
// answer message resumes the model.
|
|
91
|
+
unsubscribeNotifications = registerQuestionAnswerNotifications(pi, {
|
|
92
|
+
onError: (error) => reportDeliveryFailure(ctx, error),
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
// A session can start with settled answers whose message never reached the previous
|
|
96
|
+
// one; the outbox is durable, so reconcile it against this branch. Confirmed answers
|
|
97
|
+
// are released (and persisted), the rest are attempted again.
|
|
98
|
+
reconcileQuestionDeliveries(pi, ctx, {
|
|
99
|
+
onError: (error) => reportDeliveryFailure(ctx, error),
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
105
|
+
// Drafts change without a manager event, so the final snapshot is written here.
|
|
106
|
+
persist(ctx);
|
|
107
|
+
unsubscribeManager?.();
|
|
108
|
+
unsubscribeManager = undefined;
|
|
109
|
+
unsubscribeNotifications?.();
|
|
110
|
+
unsubscribeNotifications = undefined;
|
|
111
|
+
dock.detach();
|
|
112
|
+
questionManager.clearAll();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
pi.on("session_before_tree", (_event, ctx) => {
|
|
116
|
+
persist(ctx);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
pi.on("session_tree", (_event, ctx) => {
|
|
120
|
+
// The branch changed under the overlay, so a panel that is still up belongs to the
|
|
121
|
+
// branch being left; the reset stops it from continuing into this one.
|
|
122
|
+
resetQuestionPanelState();
|
|
123
|
+
questionManager.clearAll();
|
|
124
|
+
questionManager.restore(ctx);
|
|
125
|
+
|
|
126
|
+
// Reconciliation reads the branch that is active now, never the one being left:
|
|
127
|
+
// branch A's undelivered answers must not be sent into branch B.
|
|
128
|
+
reconcileQuestionDeliveries(pi, ctx, {
|
|
129
|
+
onError: (error) => reportDeliveryFailure(ctx, error),
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
dock.refresh();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
pi.registerTool(askUserQuestions(persist));
|
|
136
|
+
registerQuestionCommand(pi, persist);
|
|
137
|
+
|
|
138
|
+
pi.registerMessageRenderer<AskQuestionAnswerMessageDetails>(
|
|
139
|
+
ASK_QUESTION_ANSWER_MESSAGE,
|
|
140
|
+
(message, _options, theme) => renderQuestionAnswerMessage(message.details, theme),
|
|
141
|
+
);
|
|
142
|
+
}
|