@lune_99/pi-ask-question 0.0.0-stage → 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,708 @@
1
+ import { randomBytes } from "node:crypto";
2
+
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+
5
+ import type {
6
+ AnswerMessageQuestion,
7
+ AskQuestion,
8
+ AskQuestionAnswer,
9
+ AskQuestionDraft,
10
+ AskQuestionRequest,
11
+ AskQuestionStateSnapshot,
12
+ } from "./question-types.ts";
13
+
14
+ export type {
15
+ AnswerMessageQuestion,
16
+ AskQuestion,
17
+ AskQuestionAnswer,
18
+ AskQuestionDraft,
19
+ AskQuestionOption,
20
+ AskQuestionRequest,
21
+ AskQuestionStateSnapshot,
22
+ AskQuestionStatus,
23
+ } from "./question-types.ts";
24
+
25
+ /**
26
+ * Custom session entry holding the question state.
27
+ *
28
+ * A question outlives the turn that asked it: the user may close the panel with Esc,
29
+ * quit Pi, and answer after a restart. The snapshot is written whenever the pending
30
+ * set, a draft or the delivery outbox changes at a settle point, and read back from
31
+ * the active branch.
32
+ */
33
+ export const QUESTION_STATE_ENTRY = "pi-ask-question-state";
34
+
35
+ export type QuestionManagerEvent =
36
+ | { type: "request-created"; id: string }
37
+ | { type: "request-shown"; id: string }
38
+ | { type: "request-answered"; id: string }
39
+ | { type: "request-skipped"; id: string }
40
+ | { type: "request-withdrawn"; id: string; reason: string }
41
+ | { type: "request-wait-started"; id: string }
42
+ | { type: "request-wait-ended"; id: string }
43
+ | { type: "request-delivered"; id: string }
44
+ | { type: "requests-restored" }
45
+ | { type: "requests-cleared" };
46
+
47
+ /** How a blocking tool call's wait ended; an interrupted request stays pending. */
48
+ export type QuestionWaitOutcome =
49
+ | { status: "settled"; request: Readonly<AskQuestionRequest> }
50
+ | { status: "interrupted" };
51
+
52
+ /**
53
+ * Result of a withdrawal. Only a pending request can be withdrawn: a settled one already has an
54
+ * answer on its way to the model, and a waited-on one belongs to the paused tool call.
55
+ */
56
+ export type QuestionWithdrawOutcome =
57
+ | { status: "withdrawn"; request: Readonly<AskQuestionRequest> }
58
+ | { status: "settled"; request: Readonly<AskQuestionRequest> }
59
+ | { status: "waiting" }
60
+ | { status: "unknown" };
61
+
62
+ export type QuestionManagerListener = (event: QuestionManagerEvent) => void;
63
+ export type QuestionManagerListenerErrorHandler = (
64
+ error: unknown,
65
+ event: QuestionManagerEvent,
66
+ ) => void;
67
+
68
+ export class QuestionManager {
69
+ private readonly pending = new Map<string, AskQuestionRequest>();
70
+ /**
71
+ * Settled requests whose answer message is not confirmed in the session yet.
72
+ *
73
+ * `pi.sendMessage()` is only an attempt: pi can queue a steered message and drop it
74
+ * before it reaches the session. A settled request therefore stays here - durable and
75
+ * out of the pending queue - until the branch really carries its message.
76
+ */
77
+ private readonly outbox = new Map<string, AskQuestionRequest>();
78
+ /**
79
+ * Blocking tool calls by the request they wait on. They live in memory only: after a restart
80
+ * pi closes the orphaned call, and the restored request is delivered as a message.
81
+ */
82
+ private readonly waiters = new Map<string, (outcome: QuestionWaitOutcome) => void>();
83
+ private readonly listeners = new Map<
84
+ QuestionManagerListener,
85
+ QuestionManagerListenerErrorHandler | undefined
86
+ >();
87
+ private shownSeqCounter = 0;
88
+ /**
89
+ * JSON of the state the active branch already records, or `undefined` when unknown.
90
+ *
91
+ * Every `appendEntry` adds a session line and a tree node, and quit and `/tree` persist
92
+ * whether or not anything changed, so a snapshot equal to this one is not written again.
93
+ */
94
+ private persistedSnapshot: string | undefined;
95
+
96
+ /**
97
+ * `reservedIds` are ids the new request must not take, such as those of the answer messages on
98
+ * the branch: reconciliation matches a message by id and would release the new request unsent.
99
+ */
100
+ create(
101
+ questions: readonly AskQuestion[],
102
+ reservedIds: ReadonlySet<string> = new Set(),
103
+ ): AskQuestionRequest {
104
+ const request: AskQuestionRequest = {
105
+ id: this.newRequestId(reservedIds),
106
+ createdAt: Date.now(),
107
+ questions: questions.map(copyQuestion),
108
+ status: "pending",
109
+ draft: emptyDraft(questions.length),
110
+ };
111
+
112
+ this.pending.set(request.id, request);
113
+ this.emit({ type: "request-created", id: request.id });
114
+
115
+ return request;
116
+ }
117
+
118
+ get(id: string): Readonly<AskQuestionRequest> | undefined {
119
+ return this.pending.get(id) ?? this.outbox.get(id);
120
+ }
121
+
122
+ /** Pending requests oldest first; this is the order they were created in. */
123
+ getPendingRequests(): readonly AskQuestionRequest[] {
124
+ return Array.from(this.pending.values()).sort(
125
+ (left, right) => left.createdAt - right.createdAt,
126
+ );
127
+ }
128
+
129
+ /**
130
+ * The pending request the panel should show next.
131
+ *
132
+ * A request a blocking tool call waits on comes first, because the agent cannot continue
133
+ * without it. After that, least recently shown first, with a request that was never shown
134
+ * ahead of all of them: a question that just arrived has to surface immediately, while one the
135
+ * user dismissed with Esc must not pop back up in front of it. Requests that were never shown
136
+ * fall back to the order they were created in.
137
+ */
138
+ nextPendingRequest(): AskQuestionRequest | undefined {
139
+ let next: AskQuestionRequest | undefined;
140
+
141
+ for (const request of this.getPendingRequests()) {
142
+ if (next === undefined || this.showsBefore(request, next)) {
143
+ next = request;
144
+ }
145
+ }
146
+
147
+ return next;
148
+ }
149
+
150
+ /** Whether a blocking tool call waits on the pending request `id`. */
151
+ isWaiting(id: string): boolean {
152
+ return this.waiters.has(id);
153
+ }
154
+
155
+ /**
156
+ * Hold the answer of pending request `id` for a blocking tool call.
157
+ *
158
+ * The promise resolves with the settled request, which then skips the outbox: the tool result
159
+ * carries the answer. When `signal` aborts first, or the state is cleared, it resolves as
160
+ * interrupted and the request stays pending, so a later answer is delivered as a message.
161
+ */
162
+ waitForSettle(id: string, signal: AbortSignal | undefined): Promise<QuestionWaitOutcome> {
163
+ if (!this.pending.has(id) || this.waiters.has(id)) {
164
+ throw new Error(`Question request ${id} is not pending or already has a waiter`);
165
+ }
166
+
167
+ if (signal?.aborted) {
168
+ return Promise.resolve({ status: "interrupted" });
169
+ }
170
+
171
+ const onAbort = (): void => {
172
+ if (this.releaseWaiter(id, { status: "interrupted" })) {
173
+ this.emit({ type: "request-wait-ended", id });
174
+ }
175
+ };
176
+
177
+ const outcome = new Promise<QuestionWaitOutcome>((resolve) => {
178
+ this.waiters.set(id, (result) => {
179
+ signal?.removeEventListener("abort", onAbort);
180
+ resolve(result);
181
+ });
182
+ });
183
+
184
+ // pi waits for the run to become idle before an abort completes, and it has no tool
185
+ // timeout, so a wait that ignored the signal would hang Esc.
186
+ signal?.addEventListener("abort", onAbort, { once: true });
187
+ this.emit({ type: "request-wait-started", id });
188
+
189
+ return outcome;
190
+ }
191
+
192
+ /**
193
+ * Record that the panel is showing `id`, which moves it behind the requests it passed.
194
+ *
195
+ * The event is what keeps every ordering reader in step: the dock names the request this
196
+ * moved to the front, and the new `shownSeq` reaches the next snapshot with it.
197
+ */
198
+ markShown(id: string): void {
199
+ const request = this.getPendingRequest(id);
200
+
201
+ if (request) {
202
+ request.shownSeq = ++this.shownSeqCounter;
203
+ this.emit({ type: "request-shown", id });
204
+ }
205
+ }
206
+
207
+ getPendingRequest(id: string): AskQuestionRequest | undefined {
208
+ return this.pending.get(id);
209
+ }
210
+
211
+ /**
212
+ * The panel owns the pending request's draft and mutates it in place, so a snapshot
213
+ * always sees the latest focus and written text without a separate write path.
214
+ */
215
+ submit(id: string, answers: readonly AskQuestionAnswer[]): boolean {
216
+ const request = this.getPendingRequest(id);
217
+
218
+ // Settling is idempotent: a submit can race a skip or a shutdown, and only the
219
+ // first one may count (or be delivered twice).
220
+ if (!request) {
221
+ return false;
222
+ }
223
+
224
+ request.status = "answered";
225
+ request.answers = answers.map(copyAnswer);
226
+ this.settle(request);
227
+
228
+ this.emit({ type: "request-answered", id });
229
+
230
+ return true;
231
+ }
232
+
233
+ skip(id: string): boolean {
234
+ const request = this.getPendingRequest(id);
235
+
236
+ if (!request) {
237
+ return false;
238
+ }
239
+
240
+ // A skip is delivered as a custom message too, so it takes the same durable path
241
+ // as an answer: dropping it from the outbox would lose the model's only notice.
242
+ request.status = "skipped";
243
+ this.settle(request);
244
+
245
+ this.emit({ type: "request-skipped", id });
246
+
247
+ return true;
248
+ }
249
+
250
+ /**
251
+ * Remove pending request `id` without an answer; no message is sent, the withdrawing tool
252
+ * result is the record. Like submit and skip, only the first of them counts.
253
+ */
254
+ withdraw(id: string, reason: string): QuestionWithdrawOutcome {
255
+ const settled = this.outbox.get(id);
256
+
257
+ if (settled) {
258
+ return { status: "settled", request: settled };
259
+ }
260
+
261
+ const request = this.pending.get(id);
262
+
263
+ if (!request) {
264
+ return { status: "unknown" };
265
+ }
266
+
267
+ if (this.waiters.has(id)) {
268
+ return { status: "waiting" };
269
+ }
270
+
271
+ this.pending.delete(id);
272
+ this.emit({ type: "request-withdrawn", id, reason });
273
+
274
+ return { status: "withdrawn", request };
275
+ }
276
+
277
+ /** Settled requests whose answer message is not confirmed in the session yet. */
278
+ getUndeliveredRequests(): readonly Readonly<AskQuestionRequest>[] {
279
+ return Array.from(this.outbox.values()).sort(
280
+ (left, right) => left.createdAt - right.createdAt,
281
+ );
282
+ }
283
+
284
+ /**
285
+ * Release a settled request once its message is confirmed to be on the session branch.
286
+ *
287
+ * The event is what makes the persistence listener write an outbox without it, so a
288
+ * later restore cannot bring it back and deliver a second copy.
289
+ */
290
+ acknowledgeDelivery(id: string): boolean {
291
+ if (!this.outbox.delete(id)) {
292
+ return false;
293
+ }
294
+
295
+ this.emit({ type: "request-delivered", id });
296
+
297
+ return true;
298
+ }
299
+
300
+ /** Drop every request, pending or not; a session starts from its own branch. */
301
+ clearAll(): void {
302
+ this.persistedSnapshot = undefined;
303
+
304
+ // A waiting tool call must not outlive the state it waits on; the branch being restored
305
+ // brings the request back as pending, to be answered by message.
306
+ for (const id of [...this.waiters.keys()]) {
307
+ this.releaseWaiter(id, { status: "interrupted" });
308
+ }
309
+
310
+ if (this.pending.size === 0 && this.outbox.size === 0) {
311
+ return;
312
+ }
313
+
314
+ this.pending.clear();
315
+ this.outbox.clear();
316
+ this.emit({ type: "requests-cleared" });
317
+ }
318
+
319
+ /**
320
+ * Persist the pending requests (with drafts) and the delivery outbox into the session of `pi`,
321
+ * unless the active branch already records this exact state.
322
+ */
323
+ persist(pi: ExtensionAPI): void {
324
+ const snapshot = this.snapshot();
325
+ const serialized = JSON.stringify(snapshot);
326
+
327
+ if (serialized === this.persistedSnapshot) {
328
+ return;
329
+ }
330
+
331
+ pi.appendEntry(QUESTION_STATE_ENTRY, snapshot);
332
+ // Only a write that succeeded counts; a failed one is attempted again next time.
333
+ this.persistedSnapshot = serialized;
334
+ }
335
+
336
+ snapshot(): AskQuestionStateSnapshot {
337
+ return {
338
+ requests: this.getPendingRequests().map((request) => structuredClone(request)),
339
+ outbox: this.getUndeliveredRequests().map((request) => structuredClone(request)),
340
+ };
341
+ }
342
+
343
+ /** Restore the newest snapshot on the active branch; the newest state always wins. */
344
+ restore(ctx: ExtensionContext): void {
345
+ const wasEmpty = this.pending.size === 0 && this.outbox.size === 0;
346
+ const snapshot = newestSnapshot(ctx);
347
+ const restored = snapshot !== undefined && this.restoreSnapshot(snapshot);
348
+
349
+ // The branch record is known only when no live request was merged into it. It is set
350
+ // before the event, so the persistence listener does not write the branch's own state
351
+ // back onto it.
352
+ this.persistedSnapshot = wasEmpty ? JSON.stringify(this.snapshot()) : undefined;
353
+
354
+ if (restored) {
355
+ this.emit({ type: "requests-restored" });
356
+ }
357
+ }
358
+
359
+ /**
360
+ * `onError` reports a listener that threw. Passing one is what keeps a failure visible:
361
+ * the listener that writes the snapshot is also the one whose failure would silently
362
+ * lose it, and the others must keep running either way.
363
+ */
364
+ subscribe(
365
+ listener: QuestionManagerListener,
366
+ onError?: QuestionManagerListenerErrorHandler,
367
+ ): () => void {
368
+ this.listeners.set(listener, onError);
369
+
370
+ return () => {
371
+ this.listeners.delete(listener);
372
+ };
373
+ }
374
+
375
+ /**
376
+ * Settling is one move: out of the pending queue, into the durable outbox. The request must
377
+ * not be asked again, but its payload has to survive until pi's session really carries the
378
+ * answer message.
379
+ *
380
+ * Only the delivery payload goes along. The draft stays with the panel - keeping it would
381
+ * duplicate a written answer - and `displayText` and the previews are panel input that every
382
+ * later snapshot would otherwise copy until the delivery is confirmed.
383
+ */
384
+ private settle(request: AskQuestionRequest): void {
385
+ request.settledAt = Date.now();
386
+ request.questions = request.questions.map(toAnswerMessageQuestion);
387
+ request.draft = emptyDraft(request.questions.length);
388
+ this.pending.delete(request.id);
389
+
390
+ // A waiting tool call returns the answer as its result; an outbox entry would deliver it a
391
+ // second time as a message.
392
+ if (!this.releaseWaiter(request.id, { status: "settled", request })) {
393
+ this.outbox.set(request.id, request);
394
+ }
395
+ }
396
+
397
+ /** Resolve and drop the waiter of `id`; returns whether there was one. */
398
+ private releaseWaiter(id: string, outcome: QuestionWaitOutcome): boolean {
399
+ const resolve = this.waiters.get(id);
400
+
401
+ if (!resolve) {
402
+ return false;
403
+ }
404
+
405
+ this.waiters.delete(id);
406
+ resolve(outcome);
407
+
408
+ return true;
409
+ }
410
+
411
+ /**
412
+ * Eight hex digits are short enough for the model to copy into `withdraw_user_questions`.
413
+ * Requests restored from older sessions keep their UUIDs.
414
+ */
415
+ private newRequestId(reservedIds: ReadonlySet<string>): string {
416
+ for (;;) {
417
+ const id = randomBytes(4).toString("hex");
418
+
419
+ if (!this.hasRequest(id) && !reservedIds.has(id)) {
420
+ return id;
421
+ }
422
+ }
423
+ }
424
+
425
+ private showsBefore(left: AskQuestionRequest, right: AskQuestionRequest): boolean {
426
+ const leftWaits = this.waiters.has(left.id);
427
+
428
+ if (leftWaits !== this.waiters.has(right.id)) {
429
+ return leftWaits;
430
+ }
431
+
432
+ return shownOrder(left) < shownOrder(right);
433
+ }
434
+
435
+ /** Returns whether anything was restored; the caller emits the event. */
436
+ private restoreSnapshot(snapshot: AskQuestionStateSnapshot): boolean {
437
+ let restored = false;
438
+
439
+ for (const saved of snapshot.requests) {
440
+ // A live request with the same id is newer than the snapshot; the entry is
441
+ // only a fallback for state this process no longer has.
442
+ if (!isStoredRequest(saved) || this.hasRequest(saved.id)) {
443
+ continue;
444
+ }
445
+
446
+ this.pending.set(saved.id, normalizePendingRequest(saved));
447
+ this.shownSeqCounter = Math.max(this.shownSeqCounter, saved.shownSeq ?? 0);
448
+ restored = true;
449
+ }
450
+
451
+ // Settled requests are restored as settled: turning them back into pending would
452
+ // ask the user again, and dropping them would lose an answer the model never saw.
453
+ for (const saved of snapshot.outbox) {
454
+ if (!isStoredRequest(saved) || this.hasRequest(saved.id)) {
455
+ continue;
456
+ }
457
+
458
+ const settled = normalizeSettledRequest(saved);
459
+
460
+ if (!settled) {
461
+ continue;
462
+ }
463
+
464
+ this.outbox.set(settled.id, settled);
465
+ restored = true;
466
+ }
467
+
468
+ return restored;
469
+ }
470
+
471
+ /** Whether either queue already holds `id`; a snapshot never replaces live state. */
472
+ private hasRequest(id: string): boolean {
473
+ return this.pending.has(id) || this.outbox.has(id);
474
+ }
475
+
476
+ private emit(event: QuestionManagerEvent): void {
477
+ for (const [listener, onError] of this.listeners) {
478
+ try {
479
+ listener(event);
480
+ } catch (error) {
481
+ // One failing listener cannot break the others, but its failure is reported
482
+ // rather than hidden: it may be the one that persists the snapshot.
483
+ this.reportListenerError(onError, error, event);
484
+ }
485
+ }
486
+ }
487
+
488
+ private reportListenerError(
489
+ onError: QuestionManagerListenerErrorHandler | undefined,
490
+ error: unknown,
491
+ event: QuestionManagerEvent,
492
+ ): void {
493
+ try {
494
+ onError?.(error, event);
495
+ } catch {
496
+ // The reporter is the last line of defence; its own failure must not surface as a
497
+ // broken emit either.
498
+ }
499
+ }
500
+ }
501
+
502
+ function copyQuestion(question: AskQuestion): AskQuestion {
503
+ return {
504
+ ...question,
505
+ // A stored entry can be malformed; `options` has to be an array before it is mapped.
506
+ options: Array.isArray(question.options)
507
+ ? question.options.map((option) => ({ ...option }))
508
+ : undefined,
509
+ };
510
+ }
511
+
512
+ /** The fields an answer message reads: the label, the prompt and the option names. */
513
+ export function toAnswerMessageQuestion(question: AskQuestion): AnswerMessageQuestion {
514
+ return {
515
+ header: question.header,
516
+ question: question.question,
517
+ options: question.options?.map((option) => ({ label: option.label })),
518
+ };
519
+ }
520
+
521
+ function copyAnswer(answer: AskQuestionAnswer): AskQuestionAnswer {
522
+ return createAnswer(
523
+ Array.isArray(answer.selectedIndexes) ? [...answer.selectedIndexes] : [],
524
+ typeof answer.customText === "string" && answer.customText.length > 0
525
+ ? answer.customText
526
+ : undefined,
527
+ );
528
+ }
529
+
530
+ /** Custom text is a separate kind of answer, so an unset one is omitted instead of `undefined`. */
531
+ function createAnswer(
532
+ selectedIndexes: number[],
533
+ customText: string | undefined,
534
+ ): AskQuestionAnswer {
535
+ return customText === undefined ? { selectedIndexes } : { selectedIndexes, customText };
536
+ }
537
+
538
+ /** A stored answer can come from an older or hand-edited session entry, so it is validated. */
539
+ function normalizeAnswer(value: unknown): AskQuestionAnswer | undefined {
540
+ if (!value || typeof value !== "object") {
541
+ return undefined;
542
+ }
543
+
544
+ const candidate = value as { selectedIndexes?: unknown; customText?: unknown };
545
+
546
+ const selectedIndexes = Array.isArray(candidate.selectedIndexes)
547
+ ? candidate.selectedIndexes.filter(
548
+ (index): index is number =>
549
+ typeof index === "number" && Number.isInteger(index) && index >= 0,
550
+ )
551
+ : [];
552
+ const customText =
553
+ typeof candidate.customText === "string" && candidate.customText.length > 0
554
+ ? candidate.customText
555
+ : undefined;
556
+
557
+ if (selectedIndexes.length === 0 && customText === undefined) {
558
+ return undefined;
559
+ }
560
+
561
+ return createAnswer(selectedIndexes, customText);
562
+ }
563
+
564
+ function emptyDraft(questionCount: number): AskQuestionDraft {
565
+ return {
566
+ currentIndex: 0,
567
+ optionIndex: 0,
568
+ answers: new Array(questionCount).fill(undefined),
569
+ customDrafts: new Array(questionCount).fill(undefined),
570
+ };
571
+ }
572
+
573
+ function normalizePendingRequest(saved: AskQuestionRequest): AskQuestionRequest {
574
+ return {
575
+ id: saved.id,
576
+ createdAt: typeof saved.createdAt === "number" ? saved.createdAt : Date.now(),
577
+ shownSeq:
578
+ typeof saved.shownSeq === "number" && Number.isFinite(saved.shownSeq)
579
+ ? saved.shownSeq
580
+ : undefined,
581
+ questions: saved.questions.map(copyQuestion),
582
+ status: "pending",
583
+ draft: normalizeDraft(saved.draft, saved.questions.length),
584
+ };
585
+ }
586
+
587
+ /**
588
+ * A settled outbox entry read back from a snapshot.
589
+ *
590
+ * Only the delivery payload is kept: a settled request never reopens, so neither its draft nor
591
+ * its panel-only question fields are restored. An answered entry without valid answers cannot
592
+ * be delivered and is not guessed at.
593
+ */
594
+ function normalizeSettledRequest(saved: AskQuestionRequest): AskQuestionRequest | undefined {
595
+ if (saved.status !== "answered" && saved.status !== "skipped") {
596
+ return undefined;
597
+ }
598
+
599
+ const request: AskQuestionRequest = {
600
+ id: saved.id,
601
+ createdAt: typeof saved.createdAt === "number" ? saved.createdAt : Date.now(),
602
+ questions: saved.questions.map((question) =>
603
+ toAnswerMessageQuestion(copyQuestion(question)),
604
+ ),
605
+ status: saved.status,
606
+ draft: emptyDraft(saved.questions.length),
607
+ settledAt: typeof saved.settledAt === "number" ? saved.settledAt : Date.now(),
608
+ };
609
+
610
+ if (saved.status === "answered") {
611
+ const answers = normalizeAnswers(saved.answers);
612
+
613
+ if (!answers) {
614
+ return undefined;
615
+ }
616
+
617
+ request.answers = answers;
618
+ }
619
+
620
+ return request;
621
+ }
622
+
623
+ /** A settled answer list from durable state; every entry has to be a real answer. */
624
+ function normalizeAnswers(saved: unknown): AskQuestionAnswer[] | undefined {
625
+ if (!Array.isArray(saved) || saved.length === 0) {
626
+ return undefined;
627
+ }
628
+
629
+ const answers = saved.map((answer) => normalizeAnswer(answer));
630
+
631
+ return answers.every((answer): answer is AskQuestionAnswer => answer !== undefined)
632
+ ? answers
633
+ : undefined;
634
+ }
635
+
636
+ /** Requests that were never shown sort before every shown one. */
637
+ function shownOrder(request: AskQuestionRequest): number {
638
+ return request.shownSeq ?? -1;
639
+ }
640
+
641
+ function normalizeDraft(
642
+ draft: AskQuestionDraft | undefined,
643
+ questionCount: number,
644
+ ): AskQuestionDraft {
645
+ const normalized = emptyDraft(questionCount);
646
+
647
+ if (!draft) {
648
+ return normalized;
649
+ }
650
+
651
+ normalized.currentIndex = clampIndex(draft.currentIndex, questionCount);
652
+ normalized.optionIndex = Math.max(0, draft.optionIndex ?? 0);
653
+ normalized.answers = normalized.answers.map((_, index) =>
654
+ normalizeAnswer(draft.answers?.[index]),
655
+ );
656
+ normalized.customDrafts = normalized.customDrafts.map((_, index) => {
657
+ const text = draft.customDrafts?.[index];
658
+
659
+ return typeof text === "string" ? text : undefined;
660
+ });
661
+
662
+ return normalized;
663
+ }
664
+
665
+ /** The panel may have been closed on the submit tab, so the index can reach `questionCount`. */
666
+ function clampIndex(index: number, questionCount: number): number {
667
+ if (!Number.isFinite(index)) {
668
+ return 0;
669
+ }
670
+
671
+ return Math.min(questionCount, Math.max(0, Math.trunc(index)));
672
+ }
673
+
674
+ /**
675
+ * The newest state entry on the active branch, when it matches the schema this build writes.
676
+ *
677
+ * Only the newest entry counts: a malformed one is not guessed at and not patched over with an
678
+ * older one.
679
+ */
680
+ function newestSnapshot(ctx: ExtensionContext): AskQuestionStateSnapshot | undefined {
681
+ const branch = ctx.sessionManager.getBranch();
682
+
683
+ for (let index = branch.length - 1; index >= 0; index--) {
684
+ const entry = branch[index];
685
+
686
+ if (!entry || entry.type !== "custom" || entry.customType !== QUESTION_STATE_ENTRY) {
687
+ continue;
688
+ }
689
+
690
+ const snapshot = entry.data as Partial<AskQuestionStateSnapshot> | undefined;
691
+
692
+ return snapshot && Array.isArray(snapshot.requests) && Array.isArray(snapshot.outbox)
693
+ ? (snapshot as AskQuestionStateSnapshot)
694
+ : undefined;
695
+ }
696
+
697
+ return undefined;
698
+ }
699
+
700
+ function isStoredRequest(value: unknown): value is AskQuestionRequest {
701
+ if (!value || typeof value !== "object") {
702
+ return false;
703
+ }
704
+
705
+ const request = value as Partial<AskQuestionRequest>;
706
+
707
+ return typeof request.id === "string" && Array.isArray(request.questions);
708
+ }