@mrclrchtr/supi-ask-user 4.7.0 → 4.8.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.
Files changed (28) hide show
  1. package/node_modules/@mrclrchtr/supi-core/README.md +26 -34
  2. package/node_modules/@mrclrchtr/supi-core/package.json +4 -7
  3. package/node_modules/@mrclrchtr/supi-core/src/api.ts +4 -6
  4. package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +0 -20
  5. package/node_modules/@mrclrchtr/supi-core/src/config/prompt-surface.ts +7 -1
  6. package/node_modules/@mrclrchtr/supi-core/src/config.ts +0 -1
  7. package/node_modules/@mrclrchtr/supi-core/src/context.ts +1 -9
  8. package/node_modules/@mrclrchtr/supi-core/src/index.ts +4 -6
  9. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +54 -28
  10. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +91 -125
  11. package/node_modules/@mrclrchtr/supi-core/src/settings.ts +10 -7
  12. package/package.json +2 -2
  13. package/src/api.ts +0 -2
  14. package/src/ask-user.ts +0 -1
  15. package/src/session/lock.ts +0 -4
  16. package/src/ui/form-component.ts +117 -114
  17. package/src/ui/form-render-primitives.ts +3 -1
  18. package/src/ui/form-view.ts +6 -0
  19. package/node_modules/@mrclrchtr/supi-core/src/context/context-messages.ts +0 -119
  20. package/node_modules/@mrclrchtr/supi-core/src/progress-widget.ts +0 -189
  21. package/node_modules/@mrclrchtr/supi-core/src/settings/scoped-settings-list.ts +0 -373
  22. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-action-menu.ts +0 -102
  23. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-command.ts +0 -15
  24. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-submenus.ts +0 -141
  25. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-ui.ts +0 -118
  26. package/node_modules/@mrclrchtr/supi-core/src/settings-ui.ts +0 -3
  27. package/node_modules/@mrclrchtr/supi-core/src/tool-framework.ts +0 -192
  28. package/src/index.ts +0 -25
@@ -1,33 +1,36 @@
1
- // supi-core settings domain — event-backed declarative settings contributions and command wiring.
2
-
3
- export { registerSettingsCommand } from "./settings/settings-command.ts";
1
+ // supi-core settings domain — settings modules and fixed-config adapters.
4
2
  export type {
3
+ SettingsActionRequest,
4
+ SettingsApplyResult,
5
5
  SettingsCollectionDiagnostic,
6
6
  SettingsCollectionResult,
7
+ SettingsContext,
7
8
  SettingsContributionCollector,
9
+ SettingsModule,
8
10
  SettingsScope,
9
- SettingsSection,
11
+ SettingsSnapshot,
10
12
  } from "./settings/settings-registry.ts";
11
13
  export {
12
14
  createSettingsContributionCollector,
13
15
  isSettingsContributionCollector,
16
+ registerSettings,
14
17
  SUPI_SETTINGS_COLLECT_EVENT,
15
18
  } from "./settings/settings-registry.ts";
16
19
  export type {
17
20
  BoolField,
18
21
  ConfigHelpers,
22
+ ConfigSettingsOptions,
19
23
  CustomField,
20
- DeclarativeSettingsOptions,
21
24
  EnumField,
22
25
  ModelPickerField,
23
26
  ModelPickerStaticOption,
24
27
  NumberField,
25
28
  ScopedFieldValue,
29
+ SettingsAction,
26
30
  SettingsField,
27
- SettingsFieldAction,
28
31
  SettingsPersistedChange,
29
32
  StringField,
30
33
  StringListField,
31
34
  ValueSource,
32
35
  } from "./settings/settings-schema.ts";
33
- export { registerDeclarativeSettings } from "./settings/settings-schema.ts";
36
+ export { defineConfigSettings } from "./settings/settings-schema.ts";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-ask-user",
3
- "version": "4.7.0",
3
+ "version": "4.8.0",
4
4
  "description": "Structured choice and text forms for agent-user decisions",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -32,7 +32,7 @@
32
32
  "!__tests__"
33
33
  ],
34
34
  "dependencies": {
35
- "@mrclrchtr/supi-core": "4.7.0"
35
+ "@mrclrchtr/supi-core": "4.8.0"
36
36
  },
37
37
  "bundledDependencies": [
38
38
  "@mrclrchtr/supi-core"
package/src/api.ts CHANGED
@@ -1,8 +1,6 @@
1
- export { default } from "./ask-user.ts";
2
1
  export { AskUserValidationError, normalizeQuestionnaire } from "./normalize.ts";
3
2
  export { AskUserParamsSchema } from "./schema.ts";
4
3
  export { AskUserController } from "./session/controller.ts";
5
- export { ActiveQuestionnaireLock } from "./session/lock.ts";
6
4
  export type {
7
5
  AskUserDetails,
8
6
  AskUserErrorDetails,
package/src/ask-user.ts CHANGED
@@ -203,7 +203,6 @@ function asFunction<T extends (...args: never[]) => unknown>(value: unknown): T
203
203
 
204
204
  export { AskUserValidationError, normalizeQuestionnaire } from "./normalize.ts";
205
205
  export { AskUserController } from "./session/controller.ts";
206
- export { ActiveQuestionnaireLock } from "./session/lock.ts";
207
206
  export {
208
207
  promptGuidelines as askUserPromptGuidelines,
209
208
  promptSnippet as askUserPromptSnippet,
@@ -12,8 +12,4 @@ export class ActiveQuestionnaireLock {
12
12
  release(): void {
13
13
  this.active = false;
14
14
  }
15
-
16
- isActive(): boolean {
17
- return this.active;
18
- }
19
15
  }
@@ -11,13 +11,31 @@ import {
11
11
  } from "@earendil-works/pi-tui";
12
12
  import type { NormalizedChoiceQuestion } from "../types.ts";
13
13
  import { renderFormFrame } from "./form-render.ts";
14
- import { defaultChoiceRowIndex, type FocusTarget, type FormMode } from "./form-view.ts";
14
+ import { defaultChoiceRowIndex, type FormMode, focusForMode } from "./form-view.ts";
15
15
  import type { FormArgs } from "./types.ts";
16
16
 
17
+ type QuestionnaireMode = "choice" | "text" | "review";
18
+
19
+ type CommentEdit =
20
+ | { kind: "form"; context: string }
21
+ | {
22
+ kind: "question";
23
+ questionId: string;
24
+ context: string;
25
+ returnChoiceFocusIndex: number;
26
+ }
27
+ | {
28
+ kind: "option";
29
+ questionId: string;
30
+ optionValue: string;
31
+ context: string;
32
+ returnChoiceFocusIndex: number;
33
+ };
34
+
17
35
  export class AskUserForm implements Component, Focusable {
18
36
  focused: boolean = false;
19
- private mode: FormMode = "choice";
20
- private focus: FocusTarget = "choices";
37
+ /** The base screen remains active while a temporary comment editor overlays it. */
38
+ private baseMode: QuestionnaireMode = "choice";
21
39
  private readonly editor: EditorComponent;
22
40
  private readonly editorHandlesEscape: boolean;
23
41
  private settingEditorText: boolean = false;
@@ -28,10 +46,7 @@ export class AskUserForm implements Component, Focusable {
28
46
  private cachedWidth: number | undefined;
29
47
  private cachedEditorFocused: boolean | undefined;
30
48
  private cachedLines: string[] | undefined;
31
- private commentQuestionId: string | undefined;
32
- private commentOptionValue: string | undefined;
33
- private returnChoiceFocusIndex: number | undefined;
34
- private editorContext: string | undefined;
49
+ private commentEdit: CommentEdit | undefined;
35
50
  private returnToReviewAfterEdit: boolean = false;
36
51
  private pendingEsc: boolean = false;
37
52
  private readonly onAbort: () => void;
@@ -57,7 +72,9 @@ export class AskUserForm implements Component, Focusable {
57
72
  }
58
73
 
59
74
  render(width: number): string[] {
60
- const editorFocused = this.focused && this.focus === "editor";
75
+ const mode = this.currentMode();
76
+ const focus = focusForMode(mode);
77
+ const editorFocused = this.focused && focus === "editor";
61
78
  if (isFocusable(this.editor)) this.editor.focused = editorFocused;
62
79
 
63
80
  if (
@@ -74,14 +91,14 @@ export class AskUserForm implements Component, Focusable {
74
91
  width,
75
92
  theme: this.args.theme,
76
93
  controller: this.args.controller,
77
- mode: this.mode,
78
- focus: this.focus,
94
+ mode,
95
+ focus,
79
96
  editor: this.editor,
80
97
  choiceFocusIndex: this.choiceFocusIndex,
81
98
  reviewFocusIndex: this.reviewFocusIndex,
82
99
  detailsText: this.currentDetailsText(),
83
100
  editorLabel: this.currentEditorLabel(),
84
- editorContext: this.editorContext,
101
+ editorContext: this.commentEdit?.context,
85
102
  });
86
103
  return this.cachedLines;
87
104
  }
@@ -97,13 +114,13 @@ export class AskUserForm implements Component, Focusable {
97
114
  if (this.handleEscapeKey(data)) return;
98
115
  if (this.handleNavigationKey(data)) return;
99
116
 
100
- if (this.mode === "review") {
101
- this.handleReviewInput(data);
117
+ if (this.isCommentEditorMode()) {
118
+ this.handleCommentEditorKey(data);
102
119
  return;
103
120
  }
104
121
 
105
- if (this.isCommentEditorMode()) {
106
- this.handleCommentEditorKey(data);
122
+ if (this.baseMode === "review") {
123
+ this.handleReviewInput(data);
107
124
  return;
108
125
  }
109
126
 
@@ -119,7 +136,7 @@ export class AskUserForm implements Component, Focusable {
119
136
  private handleEscapeKey(data: string): boolean {
120
137
  if (!matchesKey(data, Key.escape)) return false;
121
138
 
122
- if (this.editorHandlesEscape && (this.mode === "text" || this.isCommentEditorMode())) {
139
+ if (this.editorHandlesEscape && (this.baseMode === "text" || this.isCommentEditorMode())) {
123
140
  this.editor.handleInput(data);
124
141
  if (!this.closed) this.refresh();
125
142
  return true;
@@ -131,7 +148,7 @@ export class AskUserForm implements Component, Focusable {
131
148
  return true;
132
149
  }
133
150
 
134
- if (this.mode === "text") {
151
+ if (this.baseMode === "text") {
135
152
  this.pendingEsc = true;
136
153
  setTimeout(() => {
137
154
  if (this.pendingEsc) {
@@ -154,7 +171,7 @@ export class AskUserForm implements Component, Focusable {
154
171
  this.refresh();
155
172
  return;
156
173
  }
157
- if (this.mode === "text") {
174
+ if (this.baseMode === "text") {
158
175
  this.args.controller.cancel();
159
176
  this.finish();
160
177
  }
@@ -166,10 +183,10 @@ export class AskUserForm implements Component, Focusable {
166
183
  const direction = this.navigationDirectionFor(data);
167
184
  if (!direction) return false;
168
185
 
169
- if (direction === "forward" && this.mode !== "review") {
186
+ if (direction === "forward" && this.baseMode !== "review") {
170
187
  this.navigateForward();
171
188
  } else if (direction === "backward") {
172
- if (this.mode === "review") {
189
+ if (this.baseMode === "review") {
173
190
  this.saveCurrentChoiceFocus();
174
191
  this.goToLastQuestion();
175
192
  this.syncCurrentQuestion();
@@ -184,7 +201,7 @@ export class AskUserForm implements Component, Focusable {
184
201
  private navigationDirectionFor(data: string): "forward" | "backward" | undefined {
185
202
  if (matchesKey(data, Key.tab)) return "forward";
186
203
  if (matchesKey(data, Key.shift("tab"))) return "backward";
187
- if (this.mode === "text") return undefined;
204
+ if (this.baseMode === "text") return undefined;
188
205
  if (matchesKey(data, Key.left)) return "backward";
189
206
  if (matchesKey(data, Key.right)) return "forward";
190
207
  return undefined;
@@ -205,11 +222,7 @@ export class AskUserForm implements Component, Focusable {
205
222
  }
206
223
 
207
224
  private isCommentEditorMode(): boolean {
208
- return (
209
- this.mode === "question-comment" ||
210
- this.mode === "option-comment" ||
211
- this.mode === "form-comment"
212
- );
225
+ return this.commentEdit !== undefined;
213
226
  }
214
227
 
215
228
  invalidate(): void {
@@ -349,101 +362,93 @@ export class AskUserForm implements Component, Focusable {
349
362
  }
350
363
 
351
364
  private handleEditorSubmit(value: string): void {
352
- if (this.mode === "text") {
353
- this.args.controller.setTextAnswer(this.args.controller.currentQuestion.id, value);
354
- this.goNext();
355
- return;
356
- }
357
-
358
- if (this.mode === "form-comment") {
359
- this.args.controller.setComment(value);
360
- this.returnFromCommentEditor();
361
- this.refresh();
362
- return;
363
- }
364
-
365
- if (this.mode === "question-comment" && this.commentQuestionId) {
366
- this.args.controller.setQuestionComment(this.commentQuestionId, value);
367
- this.returnFromCommentEditor();
368
- this.refresh();
365
+ const edit = this.commentEdit;
366
+ if (!edit) {
367
+ if (this.baseMode === "text") {
368
+ this.args.controller.setTextAnswer(this.args.controller.currentQuestion.id, value);
369
+ this.goNext();
370
+ }
369
371
  return;
370
372
  }
371
373
 
372
- if (
373
- this.mode === "option-comment" &&
374
- this.commentQuestionId &&
375
- this.commentOptionValue !== undefined
376
- ) {
377
- const question = this.args.controller.questionnaire.questions.find(
378
- (q) => q.id === this.commentQuestionId,
379
- );
380
- if (question?.type === "choice") {
381
- const optIndex = question.options.findIndex((o) => o.value === this.commentOptionValue);
382
- if (optIndex >= 0) {
383
- this.args.controller.setChoiceOptionComment(question, optIndex, value);
374
+ switch (edit.kind) {
375
+ case "form":
376
+ this.args.controller.setComment(value);
377
+ break;
378
+ case "question":
379
+ this.args.controller.setQuestionComment(edit.questionId, value);
380
+ break;
381
+ case "option": {
382
+ const question = this.args.controller.questionnaire.questions.find(
383
+ (candidate) => candidate.id === edit.questionId,
384
+ );
385
+ if (question?.type === "choice") {
386
+ const optionIndex = question.options.findIndex(
387
+ (option) => option.value === edit.optionValue,
388
+ );
389
+ if (optionIndex >= 0) {
390
+ this.args.controller.setChoiceOptionComment(question, optionIndex, value);
391
+ }
384
392
  }
393
+ break;
385
394
  }
386
- this.returnFromCommentEditor();
387
- this.refresh();
388
395
  }
396
+
397
+ this.returnFromCommentEditor();
398
+ this.refresh();
389
399
  }
390
400
 
391
401
  private openFormCommentEditor(): void {
392
- this.commentQuestionId = undefined;
393
- this.commentOptionValue = undefined;
394
- this.returnChoiceFocusIndex = undefined;
395
- this.editorContext = this.args.controller.questionnaire.title ?? "Form";
396
- this.mode = "form-comment";
397
- this.focus = "editor";
402
+ this.commentEdit = {
403
+ kind: "form",
404
+ context: this.args.controller.questionnaire.title ?? "Form",
405
+ };
398
406
  this.setEditorText(this.args.controller.comment ?? "");
399
407
  this.refresh();
400
408
  }
401
409
 
402
410
  private openQuestionCommentEditor(questionId: string): void {
403
- this.commentQuestionId = questionId;
404
- this.commentOptionValue = undefined;
405
- this.returnChoiceFocusIndex = this.choiceFocusIndex;
406
- this.editorContext = this.args.controller.currentQuestion.header;
407
- this.mode = "question-comment";
408
- this.focus = "editor";
411
+ this.commentEdit = {
412
+ kind: "question",
413
+ questionId,
414
+ context: this.args.controller.currentQuestion.header,
415
+ returnChoiceFocusIndex: this.choiceFocusIndex,
416
+ };
409
417
  this.setEditorText(this.args.controller.getQuestionComment(questionId) ?? "");
410
418
  this.refresh();
411
419
  }
412
420
 
413
421
  private openOptionCommentEditor(question: NormalizedChoiceQuestion, optionIndex: number): void {
414
- const opt = question.options[optionIndex];
415
- if (!opt) return;
416
- this.commentQuestionId = question.id;
417
- this.commentOptionValue = opt.value;
418
- this.returnChoiceFocusIndex = optionIndex;
419
- this.editorContext = opt.label;
420
- this.mode = "option-comment";
421
- this.focus = "editor";
422
- this.setEditorText(this.args.controller.getOptionComment(question.id, opt.value) ?? "");
422
+ const option = question.options[optionIndex];
423
+ if (!option) return;
424
+ this.commentEdit = {
425
+ kind: "option",
426
+ questionId: question.id,
427
+ optionValue: option.value,
428
+ context: option.label,
429
+ returnChoiceFocusIndex: optionIndex,
430
+ };
431
+ this.setEditorText(this.args.controller.getOptionComment(question.id, option.value) ?? "");
423
432
  this.refresh();
424
433
  }
425
434
 
426
435
  private returnFromCommentEditor(): void {
427
- const prevMode = this.mode;
428
- const questionId = this.commentQuestionId;
429
- const optionValue = this.commentOptionValue;
430
- const returnChoiceFocusIndex = this.returnChoiceFocusIndex;
431
-
432
- this.commentQuestionId = undefined;
433
- this.commentOptionValue = undefined;
434
- this.returnChoiceFocusIndex = undefined;
435
- this.editorContext = undefined;
436
-
437
- if (prevMode === "form-comment") {
438
- this.mode = "review";
439
- this.focus = "review";
440
- this.setEditorText("");
441
- return;
442
- }
436
+ const edit = this.commentEdit;
437
+ if (!edit) return;
438
+ this.commentEdit = undefined;
443
439
 
444
- if (prevMode === "question-comment" || prevMode === "option-comment") {
445
- this.syncCurrentQuestion();
446
- this.restoreChoiceFocus(questionId, optionValue, returnChoiceFocusIndex);
440
+ switch (edit.kind) {
441
+ case "form":
442
+ this.baseMode = "review";
443
+ this.setEditorText("");
444
+ return;
445
+ case "question":
446
+ this.syncCurrentQuestion();
447
+ this.restoreChoiceFocus(edit.questionId, undefined, edit.returnChoiceFocusIndex);
448
+ return;
449
+ case "option":
450
+ this.syncCurrentQuestion();
451
+ this.restoreChoiceFocus(edit.questionId, edit.optionValue, edit.returnChoiceFocusIndex);
447
452
  }
448
453
  }
449
454
 
@@ -453,8 +458,7 @@ export class AskUserForm implements Component, Focusable {
453
458
  this.saveCurrentChoiceFocus();
454
459
  if (this.returnToReviewAfterEdit) {
455
460
  this.returnToReviewAfterEdit = false;
456
- this.mode = "review";
457
- this.focus = "review";
461
+ this.baseMode = "review";
458
462
  this.reviewFocusIndex = this.args.controller.questionnaire.questions.length;
459
463
  this.setEditorText("");
460
464
  this.refresh();
@@ -464,8 +468,7 @@ export class AskUserForm implements Component, Focusable {
464
468
  this.args.controller.currentIndex >=
465
469
  this.args.controller.questionnaire.questions.length - 1
466
470
  ) {
467
- this.mode = "review";
468
- this.focus = "review";
471
+ this.baseMode = "review";
469
472
  // Focus the Submit row by default so Enter submits immediately.
470
473
  this.reviewFocusIndex = this.args.controller.questionnaire.questions.length;
471
474
  this.refresh();
@@ -486,9 +489,6 @@ export class AskUserForm implements Component, Focusable {
486
489
  this.saveCurrentChoiceFocus();
487
490
  this.returnToReviewAfterEdit = opts.returnToReviewAfterEdit ?? false;
488
491
  this.args.controller.goTo(index);
489
- const q = this.args.controller.currentQuestion;
490
- this.mode = q.type === "text" ? "text" : "choice";
491
- this.focus = q.type === "text" ? "editor" : "choices";
492
492
  this.syncCurrentQuestion();
493
493
  this.refresh();
494
494
  }
@@ -497,14 +497,12 @@ export class AskUserForm implements Component, Focusable {
497
497
  const question = this.args.controller.currentQuestion;
498
498
 
499
499
  if (question.type === "text") {
500
- this.mode = "text";
501
- this.focus = "editor";
500
+ this.baseMode = "text";
502
501
  this.setEditorText(this.args.controller.getTextAnswer(question.id));
503
502
  return;
504
503
  }
505
504
 
506
- this.mode = "choice";
507
- this.focus = "choices";
505
+ this.baseMode = "choice";
508
506
  this.setEditorText("");
509
507
  this.choiceFocusIndex =
510
508
  this.choiceFocusByQuestionId.get(question.id) ??
@@ -519,7 +517,7 @@ export class AskUserForm implements Component, Focusable {
519
517
  }
520
518
 
521
519
  private syncTextAnswerFromEditor(): void {
522
- if (this.mode !== "text") return;
520
+ if (this.currentMode() !== "text") return;
523
521
  const question = this.args.controller.currentQuestion;
524
522
  if (question.type !== "text") return;
525
523
  this.args.controller.setTextAnswer(
@@ -567,20 +565,25 @@ export class AskUserForm implements Component, Focusable {
567
565
  this.args.tui.requestRender();
568
566
  }
569
567
 
568
+ private currentMode(): FormMode {
569
+ if (!this.commentEdit) return this.baseMode;
570
+ return `${this.commentEdit.kind}-comment`;
571
+ }
572
+
570
573
  private currentDetailsText(): string | undefined {
571
- if (this.mode !== "choice") return undefined;
574
+ if (this.currentMode() !== "choice") return undefined;
572
575
  const question = this.args.controller.currentQuestion;
573
576
  if (question.type !== "choice") return undefined;
574
577
  return question.options[this.choiceFocusIndex]?.details;
575
578
  }
576
579
 
577
580
  private currentEditorLabel(): string | undefined {
578
- switch (this.mode) {
579
- case "question-comment":
581
+ switch (this.commentEdit?.kind) {
582
+ case "question":
580
583
  return "Question comment";
581
- case "option-comment":
584
+ case "option":
582
585
  return "Option comment";
583
- case "form-comment":
586
+ case "form":
584
587
  return "Form comment";
585
588
  default:
586
589
  return undefined;
@@ -17,7 +17,9 @@ export function renderMiniBox(
17
17
  const lines = [
18
18
  border(`╭${"─".repeat(safe - 2)}╮`),
19
19
  `${border("│")} ${padRight(theme.fg("accent", theme.bold(title)), innerWidth)} ${border("│")}`,
20
- ...bodyLines.map((line) => `${border("│")} ${padRight(line, innerWidth)} ${border("│")}`),
20
+ ...bodyLines
21
+ .flatMap((line) => wrapTextWithAnsi(line, innerWidth))
22
+ .map((line) => `${border("│")} ${padRight(line, innerWidth)} ${border("│")}`),
21
23
  border(`╰${"─".repeat(safe - 2)}╯`),
22
24
  ];
23
25
 
@@ -10,6 +10,12 @@ export type FormMode =
10
10
  | "form-comment"
11
11
  | "option-comment";
12
12
 
13
+ /** Return the only valid focus target for a form mode. */
14
+ export function focusForMode(mode: FormMode): FocusTarget {
15
+ if (mode === "choice") return "choices";
16
+ return mode === "review" ? "review" : "editor";
17
+ }
18
+
13
19
  export function defaultChoiceRowIndex(
14
20
  controller: AskUserController,
15
21
  question: NormalizedChoiceQuestion,
@@ -1,119 +0,0 @@
1
- // Shared context-message utilities for SuPi extensions.
2
- //
3
- // Provides a generic prune-and-reorder pattern for extensions that inject
4
- // managed context messages (via `before_agent_start` with a `customType` and
5
- // `contextToken`) and maintain them via the `context` event.
6
-
7
- /**
8
- * Minimal message shape needed for context-message operations.
9
- * Extensions cast their event.messages entries to this type.
10
- */
11
- export type ContextMessageLike = {
12
- role?: string;
13
- customType?: string;
14
- content?: unknown;
15
- details?: unknown;
16
- };
17
-
18
- /**
19
- * Extract the `contextToken` string from a message's `details` object.
20
- * Returns `null` when the token is absent or not a string.
21
- */
22
- export function getContextToken(details: unknown): string | null {
23
- if (!details || typeof details !== "object") return null;
24
- const token = (details as { contextToken?: unknown }).contextToken;
25
- return typeof token === "string" ? token : null;
26
- }
27
-
28
- /**
29
- * Find the index of the last message with `role: "user"`.
30
- * Returns `-1` when no user message exists.
31
- */
32
- export function findLastUserMessageIndex<T extends ContextMessageLike>(messages: T[]): number {
33
- for (let index = messages.length - 1; index >= 0; index--) {
34
- if (messages[index]?.role === "user") return index;
35
- }
36
- return -1;
37
- }
38
-
39
- /**
40
- * Filter stale context messages and reorder the active one before the last user message.
41
- *
42
- * - Removes all messages matching `customType` whose token differs from `activeToken`.
43
- * - When `activeToken` is `null`, removes **all** messages of that `customType`.
44
- * - If the active context message is after the last user message, moves it before.
45
- *
46
- * Returns the modified array, or the original reference when no changes were needed.
47
- */
48
- export function pruneAndReorderContextMessages<T extends ContextMessageLike>(
49
- messages: T[],
50
- customType: string,
51
- activeToken: string | null,
52
- ): T[] {
53
- // Remove stale messages of the target customType
54
- const filtered = messages.filter((message) => {
55
- if (message.customType !== customType) return true;
56
- if (!activeToken) return false;
57
- return getContextToken(message.details) === activeToken;
58
- });
59
-
60
- if (!activeToken) return filtered;
61
-
62
- // Find the active context message
63
- const contextIndex = filtered.findIndex(
64
- (message) =>
65
- message.customType === customType && getContextToken(message.details) === activeToken,
66
- );
67
- if (contextIndex === -1) return filtered;
68
-
69
- // Find the last user message
70
- const userIndex = findLastUserMessageIndex(filtered);
71
- if (userIndex === -1 || contextIndex < userIndex) return filtered;
72
-
73
- // Move context message before last user message
74
- const next = [...filtered];
75
- const [contextMessage] = next.splice(contextIndex, 1);
76
- if (!contextMessage) return filtered;
77
- next.splice(userIndex, 0, contextMessage);
78
- return next;
79
- }
80
-
81
- /**
82
- * Restore the raw prompt content on a context message that was swapped for display text.
83
- *
84
- * Extensions using `registerMessageRenderer` store their LLM-facing content in
85
- * `details.promptContent` and put a human-readable summary in `content`. This function
86
- * reverses the swap so the model sees the original prompt content.
87
- *
88
- * Returns the original array reference when no change is needed.
89
- */
90
- export function restorePromptContent<T extends ContextMessageLike>(
91
- messages: T[],
92
- customType: string,
93
- activeToken: string | null,
94
- ): T[] {
95
- if (!activeToken) return messages;
96
-
97
- const index = messages.findIndex(
98
- (message) =>
99
- message.customType === customType && getContextToken(message.details) === activeToken,
100
- );
101
- if (index === -1) return messages;
102
-
103
- const promptContent = getPromptContent(messages[index]?.details);
104
- if (!promptContent || messages[index]?.content === promptContent) return messages;
105
-
106
- const next = [...messages];
107
- next[index] = { ...next[index], content: promptContent };
108
- return next;
109
- }
110
-
111
- /**
112
- * Extract the `promptContent` string from a message's `details` object.
113
- * Returns `null` when absent or not a string.
114
- */
115
- export function getPromptContent(details: unknown): string | null {
116
- if (!details || typeof details !== "object") return null;
117
- const promptContent = (details as { promptContent?: unknown }).promptContent;
118
- return typeof promptContent === "string" ? promptContent : null;
119
- }