@mrclrchtr/supi-skills 4.7.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 (38) hide show
  1. package/README.md +46 -0
  2. package/node_modules/@mrclrchtr/supi-core/README.md +112 -0
  3. package/node_modules/@mrclrchtr/supi-core/package.json +76 -0
  4. package/node_modules/@mrclrchtr/supi-core/src/api.ts +40 -0
  5. package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +201 -0
  6. package/node_modules/@mrclrchtr/supi-core/src/config/prompt-surface.ts +363 -0
  7. package/node_modules/@mrclrchtr/supi-core/src/config.ts +10 -0
  8. package/node_modules/@mrclrchtr/supi-core/src/context/context-provider-registry.ts +36 -0
  9. package/node_modules/@mrclrchtr/supi-core/src/context/context-tag.ts +31 -0
  10. package/node_modules/@mrclrchtr/supi-core/src/context.ts +8 -0
  11. package/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +287 -0
  12. package/node_modules/@mrclrchtr/supi-core/src/evidence-badge.ts +41 -0
  13. package/node_modules/@mrclrchtr/supi-core/src/footer-registry.ts +57 -0
  14. package/node_modules/@mrclrchtr/supi-core/src/index.ts +34 -0
  15. package/node_modules/@mrclrchtr/supi-core/src/llm.ts +201 -0
  16. package/node_modules/@mrclrchtr/supi-core/src/model-selection.ts +134 -0
  17. package/node_modules/@mrclrchtr/supi-core/src/path-utils.ts +44 -0
  18. package/node_modules/@mrclrchtr/supi-core/src/path.ts +2 -0
  19. package/node_modules/@mrclrchtr/supi-core/src/project-roots.ts +170 -0
  20. package/node_modules/@mrclrchtr/supi-core/src/project.ts +15 -0
  21. package/node_modules/@mrclrchtr/supi-core/src/prompt-surface.ts +4 -0
  22. package/node_modules/@mrclrchtr/supi-core/src/registry-utils.ts +93 -0
  23. package/node_modules/@mrclrchtr/supi-core/src/report.ts +121 -0
  24. package/node_modules/@mrclrchtr/supi-core/src/session-utils.ts +71 -0
  25. package/node_modules/@mrclrchtr/supi-core/src/session.ts +8 -0
  26. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +102 -0
  27. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +453 -0
  28. package/node_modules/@mrclrchtr/supi-core/src/settings.ts +36 -0
  29. package/node_modules/@mrclrchtr/supi-core/src/spinner-frames.ts +11 -0
  30. package/node_modules/@mrclrchtr/supi-core/src/status-spinner.ts +68 -0
  31. package/node_modules/@mrclrchtr/supi-core/src/terminal.ts +60 -0
  32. package/package.json +64 -0
  33. package/src/extension.ts +9 -0
  34. package/src/skill-catalog.ts +153 -0
  35. package/src/skill-load-settings.ts +305 -0
  36. package/src/skill-model-invocation.ts +134 -0
  37. package/src/skill-settings.ts +400 -0
  38. package/src/skill-shortcut.ts +123 -0
@@ -0,0 +1,287 @@
1
+ // Shared debug event registry for SuPi extensions.
2
+ //
3
+ // Extensions record session-local diagnostic events here. The user-facing
4
+ // supi-debug extension owns policy/configuration and exposes events through a
5
+ // command/tool while this module stays dependency-free for producers.
6
+
7
+ export type DebugLevel = "debug" | "info" | "warning" | "error";
8
+ export type DebugAgentAccess = "off" | "sanitized" | "raw";
9
+ export interface DebugRegistryConfig {
10
+ /** Whether producers should retain debug events. */
11
+ enabled: boolean;
12
+ /** What the agent-callable debug tool may return. */
13
+ agentAccess: DebugAgentAccess;
14
+ /** Maximum number of session-local events to keep in memory. */
15
+ maxEvents: number;
16
+ }
17
+
18
+ export const DEBUG_REGISTRY_DEFAULTS: DebugRegistryConfig = {
19
+ enabled: false,
20
+ agentAccess: "sanitized",
21
+ maxEvents: 100,
22
+ };
23
+
24
+ export interface DebugEventInput {
25
+ source: string;
26
+ level: DebugLevel;
27
+ category: string;
28
+ message: string;
29
+ cwd?: string;
30
+ data?: unknown;
31
+ rawData?: unknown;
32
+ }
33
+
34
+ export interface DebugEvent extends DebugEventInput {
35
+ id: number;
36
+ timestamp: number;
37
+ data?: unknown;
38
+ rawData?: unknown;
39
+ }
40
+
41
+ export interface DebugEventQuery {
42
+ source?: string;
43
+ level?: DebugLevel;
44
+ category?: string;
45
+ limit?: number;
46
+ includeRaw?: boolean;
47
+ allowRaw?: boolean;
48
+ }
49
+
50
+ export interface DebugEventView {
51
+ id: number;
52
+ timestamp: number;
53
+ source: string;
54
+ level: DebugLevel;
55
+ category: string;
56
+ message: string;
57
+ cwd?: string;
58
+ data?: unknown;
59
+ rawData?: unknown;
60
+ }
61
+
62
+ export interface DebugEventQueryResult {
63
+ events: DebugEventView[];
64
+ rawAccessDenied: boolean;
65
+ }
66
+
67
+ /** Receives a sanitized event whenever the registry records one. */
68
+ export type DebugEventListener = (event: DebugEventView) => void;
69
+
70
+ export interface DebugSummary {
71
+ total: number;
72
+ byLevel: Partial<Record<DebugLevel, number>>;
73
+ bySource: Record<string, number>;
74
+ }
75
+
76
+ interface DebugRegistryState {
77
+ config: DebugRegistryConfig;
78
+ events: DebugEvent[];
79
+ listeners: Set<DebugEventListener>;
80
+ nextId: number;
81
+ }
82
+
83
+ const REGISTRY_KEY = Symbol.for("@mrclrchtr/supi-core/debug-registry");
84
+ const SECRET_KEY_RE = /(?:token|password|passwd|secret|api[_-]?key|authorization|credential)/i;
85
+ const ENV_SECRET_RE =
86
+ /\b([A-Za-z0-9_]*(?:token|password|passwd|secret|api[_-]?key|authorization|credential)[A-Za-z0-9_]*)=(?:'[^']*'|"[^"]*"|\S+)/gi;
87
+ const AUTH_HEADER_RE = /\b(authorization\s*[:=]\s*)(?:bearer\s+)?[^\s;&|]+/gi;
88
+ const URL_SECRET_RE =
89
+ /([?&](?:token|password|passwd|secret|api[_-]?key|authorization|credential)=)[^&\s]+/gi;
90
+ const REDACTED = "[REDACTED]";
91
+
92
+ function cloneConfig(config: DebugRegistryConfig): DebugRegistryConfig {
93
+ return { ...config };
94
+ }
95
+
96
+ function getState(): DebugRegistryState {
97
+ let state = (globalThis as Record<symbol, unknown>)[REGISTRY_KEY] as
98
+ | DebugRegistryState
99
+ | undefined;
100
+ if (!state) {
101
+ state = {
102
+ config: cloneConfig(DEBUG_REGISTRY_DEFAULTS),
103
+ events: [],
104
+ listeners: new Set(),
105
+ nextId: 1,
106
+ };
107
+ (globalThis as Record<symbol, unknown>)[REGISTRY_KEY] = state;
108
+ }
109
+ // Keep the shared registry compatible with extension reloads that reuse an
110
+ // instance created before listeners existed.
111
+ if (!state.listeners) state.listeners = new Set();
112
+ return state;
113
+ }
114
+
115
+ function normalizeMaxEvents(value: number): number {
116
+ if (!Number.isFinite(value) || value <= 0) {
117
+ return DEBUG_REGISTRY_DEFAULTS.maxEvents;
118
+ }
119
+ return Math.floor(value);
120
+ }
121
+
122
+ function trimToMaxEvents(state: DebugRegistryState): void {
123
+ const maxEvents = normalizeMaxEvents(state.config.maxEvents);
124
+ if (state.events.length <= maxEvents) {
125
+ return;
126
+ }
127
+ state.events.splice(0, state.events.length - maxEvents);
128
+ }
129
+
130
+ /** Return whether a debug level is recognized by the registry. */
131
+ export function isDebugLevel(value: unknown): value is DebugLevel {
132
+ return value === "debug" || value === "info" || value === "warning" || value === "error";
133
+ }
134
+
135
+ /** Match a debug event against the supported source, level, and category filters. */
136
+ export function matchesDebugEventQuery(
137
+ event: Pick<DebugEventView, "source" | "level" | "category">,
138
+ query: Pick<DebugEventQuery, "source" | "level" | "category">,
139
+ ): boolean {
140
+ if (query.source && event.source !== query.source) return false;
141
+ if (query.level && event.level !== query.level) return false;
142
+ if (query.category && event.category !== query.category) return false;
143
+ return true;
144
+ }
145
+
146
+ function sanitizeString(value: string): string {
147
+ return value
148
+ .replace(ENV_SECRET_RE, (_match, key: string) => `${key}=${REDACTED}`)
149
+ .replace(AUTH_HEADER_RE, (_match, prefix: string) => `${prefix}${REDACTED}`)
150
+ .replace(URL_SECRET_RE, (_match, prefix: string) => `${prefix}${REDACTED}`);
151
+ }
152
+
153
+ function redactValue(value: unknown, depth: number): unknown {
154
+ if (depth <= 0) return "[MaxDepth]";
155
+ if (typeof value === "string") return sanitizeString(value);
156
+ if (typeof value !== "object" || value === null) return value;
157
+ if (Array.isArray(value)) return value.map((item) => redactValue(item, depth - 1));
158
+
159
+ const redacted: Record<string, unknown> = {};
160
+ for (const [key, item] of Object.entries(value)) {
161
+ redacted[key] = SECRET_KEY_RE.test(key) ? REDACTED : redactValue(item, depth - 1);
162
+ }
163
+ return redacted;
164
+ }
165
+
166
+ /** Configure the shared debug registry. Existing events are trimmed to the new max size. */
167
+ export function configureDebugRegistry(config: Partial<DebugRegistryConfig>): DebugRegistryConfig {
168
+ const state = getState();
169
+ state.config = {
170
+ ...state.config,
171
+ ...config,
172
+ maxEvents: normalizeMaxEvents(config.maxEvents ?? state.config.maxEvents),
173
+ };
174
+ trimToMaxEvents(state);
175
+ return getDebugRegistryConfig();
176
+ }
177
+
178
+ /** Return the active debug registry configuration. */
179
+ export function getDebugRegistryConfig(): DebugRegistryConfig {
180
+ return cloneConfig(getState().config);
181
+ }
182
+
183
+ /** Best-effort redaction helper for data exposed through sanitized debug views. */
184
+ export function redactDebugData<T>(value: T): T {
185
+ return redactValue(value, 8) as T;
186
+ }
187
+
188
+ function toSanitizedView(event: DebugEvent): DebugEventView {
189
+ return {
190
+ id: event.id,
191
+ timestamp: event.timestamp,
192
+ source: event.source,
193
+ level: event.level,
194
+ category: event.category,
195
+ message: event.message,
196
+ cwd: event.cwd,
197
+ data: event.data,
198
+ };
199
+ }
200
+
201
+ /** Subscribe to sanitized events. Listeners are isolated so diagnostics cannot disrupt producers. */
202
+ export function subscribeDebugEvents(listener: DebugEventListener): () => void {
203
+ const state = getState();
204
+ state.listeners.add(listener);
205
+ return () => state.listeners.delete(listener);
206
+ }
207
+
208
+ /** Record a session-local debug event if debugging is enabled. */
209
+ export function recordDebugEvent(input: DebugEventInput): DebugEvent | null {
210
+ const state = getState();
211
+ if (!state.config.enabled) {
212
+ return null;
213
+ }
214
+
215
+ const event: DebugEvent = {
216
+ ...input,
217
+ id: state.nextId++,
218
+ timestamp: Date.now(),
219
+ data: input.data === undefined ? undefined : redactDebugData(input.data),
220
+ };
221
+ state.events.push(event);
222
+ trimToMaxEvents(state);
223
+ const view = toSanitizedView(event);
224
+ for (const listener of state.listeners) {
225
+ try {
226
+ listener(view);
227
+ } catch {
228
+ // Debug-event consumers must not alter producer behavior.
229
+ }
230
+ }
231
+ return { ...event };
232
+ }
233
+
234
+ /** Query retained debug events newest-first. Results are sanitized unless raw access is requested and allowed. */
235
+ export function getDebugEvents(query: DebugEventQuery = {}): DebugEventQueryResult {
236
+ const state = getState();
237
+ const allowRaw = Boolean(
238
+ query.includeRaw && query.allowRaw && state.config.agentAccess === "raw",
239
+ );
240
+ const rawAccessDenied = Boolean(query.includeRaw && !allowRaw);
241
+ const limit = query.limit && query.limit > 0 ? Math.floor(query.limit) : state.config.maxEvents;
242
+
243
+ const events = state.events
244
+ .filter((event) => matchesDebugEventQuery(event, query))
245
+ .slice()
246
+ .reverse()
247
+ .slice(0, limit)
248
+ .map((event): DebugEventView => {
249
+ const view = toSanitizedView(event);
250
+ if (allowRaw && event.rawData !== undefined) {
251
+ view.rawData = event.rawData;
252
+ }
253
+ return view;
254
+ });
255
+
256
+ return { events, rawAccessDenied };
257
+ }
258
+
259
+ /** Return aggregate debug counts suitable for summary displays. */
260
+ export function getDebugSummary(): DebugSummary | null {
261
+ const events = getState().events;
262
+ if (events.length === 0) {
263
+ return null;
264
+ }
265
+
266
+ const summary: DebugSummary = { total: events.length, byLevel: {}, bySource: {} };
267
+ for (const event of events) {
268
+ summary.byLevel[event.level] = (summary.byLevel[event.level] ?? 0) + 1;
269
+ summary.bySource[event.source] = (summary.bySource[event.source] ?? 0) + 1;
270
+ }
271
+ return summary;
272
+ }
273
+
274
+ /** Clear retained events while preserving configuration. */
275
+ export function clearDebugEvents(): void {
276
+ const state = getState();
277
+ state.events = [];
278
+ }
279
+
280
+ /** Reset the debug registry to defaults; intended for tests. */
281
+ export function resetDebugRegistry(): void {
282
+ const state = getState();
283
+ state.config = cloneConfig(DEBUG_REGISTRY_DEFAULTS);
284
+ state.events = [];
285
+ state.listeners.clear();
286
+ state.nextId = 1;
287
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * TUI-facing evidence badge string formatter.
3
+ *
4
+ * Pure string formatting — no pi-tui dependency. Consumes evidence
5
+ * completeness metadata and produces compact human-readable badges.
6
+ */
7
+
8
+ /** Metadata describing how many evidence atoms were shown vs exist. */
9
+ export interface EvidenceBadgeInput {
10
+ shownCount: number;
11
+ totalCount: number | null;
12
+ omittedCount: number | null;
13
+ partialReason: string | null;
14
+ /** Human-readable label for the badge, e.g. "references", "symbols". */
15
+ label: string;
16
+ }
17
+
18
+ /**
19
+ * Format a compact evidence completeness badge.
20
+ *
21
+ * | Input | Output |
22
+ * |------------------------------------------------------|---------------------------------------|
23
+ * | shown=12, total=12, omitted=0, label="references" | `12 references` |
24
+ * | shown=8, total=20, omitted=12, label="symbols" | `8 of 20 symbols (12 omitted)` |
25
+ * | shown=5, total=null, omitted=2, reason="timeout" | `5 matches (2 collected omitted; more may exist — timeout)` |
26
+ */
27
+ export function formatEvidenceBadge(input: EvidenceBadgeInput): string {
28
+ const { shownCount, totalCount, omittedCount, partialReason, label } = input;
29
+
30
+ if (totalCount === null) {
31
+ const reasonSuffix = partialReason ? ` — ${partialReason}` : "";
32
+ const omittedPrefix = (omittedCount ?? 0) > 0 ? `${omittedCount} collected omitted; ` : "";
33
+ return `${shownCount} ${label} (${omittedPrefix}more may exist${reasonSuffix})`;
34
+ }
35
+
36
+ if (omittedCount !== null && omittedCount > 0) {
37
+ return `${shownCount} of ${totalCount} ${label} (${omittedCount} omitted)`;
38
+ }
39
+
40
+ return `${shownCount} ${label}`;
41
+ }
@@ -0,0 +1,57 @@
1
+ // Shared footer contribution registry for SuPi extensions.
2
+ //
3
+ // Extensions register pre-styled text chunks with a placement hint
4
+ // ("stats" for the metrics line, "status" for the extension status line).
5
+ // The custom footer in supi-extras (or PI's built-in footer) reads these
6
+ // contributions and renders them alongside the built-in metrics.
7
+
8
+ import { createRegistry } from "./registry-utils.ts";
9
+
10
+ /** Where the contribution should appear in the footer. */
11
+ export type FooterPlacement = "stats" | "stats-end" | "status";
12
+
13
+ /** A single footer contribution registered by an extension. */
14
+ export interface FooterContribution {
15
+ /** Unique key for this contribution. Re-registering with the same key replaces it. */
16
+ key: string;
17
+ /** Which footer line this belongs on. */
18
+ placement: FooterPlacement;
19
+ /**
20
+ * Sort order within the placement (lower values render further left). Default: 100.
21
+ * Priority 0 is reserved for the turn cache-hit part so it stays adjacent to CH.
22
+ */
23
+ priority?: number;
24
+ /** Return the pre-styled text for this contribution. Called on every render. */
25
+ render: () => string;
26
+ }
27
+
28
+ const registry = createRegistry<FooterContribution>("footer-contributions");
29
+
30
+ function sortByPriority(a: FooterContribution, b: FooterContribution): number {
31
+ return (a.priority ?? 100) - (b.priority ?? 100);
32
+ }
33
+
34
+ export const footerContributions = {
35
+ /** Register or replace a footer contribution. */
36
+ register(contribution: FooterContribution): void {
37
+ registry.register(contribution.key, contribution);
38
+ },
39
+
40
+ /** Remove a contribution (e.g. on session_shutdown or when disabled). */
41
+ unregister(key: string): void {
42
+ registry.unregister(key);
43
+ },
44
+
45
+ /** Get contributions for a specific placement, sorted by priority. */
46
+ getByPlacement(placement: FooterPlacement): FooterContribution[] {
47
+ return registry
48
+ .getAll()
49
+ .filter((c) => c.placement === placement)
50
+ .sort(sortByPriority);
51
+ },
52
+
53
+ /** Remove all contributions (primarily for tests). */
54
+ clear(): void {
55
+ registry.clear();
56
+ },
57
+ };
@@ -0,0 +1,34 @@
1
+ // supi-core — shared infrastructure for SuPi extensions.
2
+ // Provides XML context tag wrapping, unified config, prompt-surface resolution,
3
+ // and shared settings, reporting, and session utilities.
4
+ //
5
+ // Convenience barrel — re-exports all domain entry points.
6
+ // For lighter imports, use one of the domain subpaths directly
7
+ // (e.g. @mrclrchtr/supi-core/config, @mrclrchtr/supi-core/context).
8
+
9
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
10
+ export * from "./config.ts";
11
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
12
+ export * from "./context.ts";
13
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
14
+ export * from "./debug-registry.ts";
15
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
16
+ export * from "./footer-registry.ts";
17
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
18
+ export * from "./model-selection.ts";
19
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
20
+ export * from "./path.ts";
21
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
22
+ export * from "./project.ts";
23
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
24
+ export * from "./prompt-surface.ts";
25
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
26
+ export * from "./report.ts";
27
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
28
+ export * from "./session.ts";
29
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
30
+ export * from "./settings.ts";
31
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
32
+ export * from "./status-spinner.ts";
33
+ // biome-ignore lint/performance/noReExportAll: intentional convenience barrel
34
+ export * from "./terminal.ts";
@@ -0,0 +1,201 @@
1
+ import { complete } from "@earendil-works/pi-ai/compat";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import type { TSchema } from "typebox";
4
+ import { Value } from "typebox/value";
5
+
6
+ // Shared LLM utilities for SuPi extensions.
7
+ //
8
+ // Provides retry logic, structured LLM call helpers, and other
9
+ // common patterns for extensions that interact with AI models.
10
+
11
+ /**
12
+ * Options for {@link withRetry}.
13
+ */
14
+ export interface WithRetryOptions {
15
+ /** Maximum number of retry attempts after the initial call. Default: 2 */
16
+ retries?: number;
17
+ /** Base delay in milliseconds for exponential backoff. Default: 1000 */
18
+ baseDelayMs?: number;
19
+ /** AbortSignal to cancel retry loops. */
20
+ signal?: AbortSignal;
21
+ /** Called with each failed attempt's attempt index and error. */
22
+ logger?: (attempt: number, error: unknown) => void;
23
+ /** Called before each retry delay with attempt index and computed delay. */
24
+ onRetry?: (attempt: number, delayMs: number) => void;
25
+ }
26
+
27
+ /**
28
+ * Create a promise that resolves after `ms` milliseconds, or rejects if
29
+ * the signal fires before the timeout elapses.
30
+ */
31
+ function delay(ms: number, signal?: AbortSignal): Promise<void> {
32
+ return new Promise<void>((resolve, reject) => {
33
+ const timer = setTimeout(resolve, ms);
34
+ if (signal) {
35
+ const onAbort = () => {
36
+ clearTimeout(timer);
37
+ reject(new DOMException("Aborted", "AbortError"));
38
+ };
39
+ signal.addEventListener("abort", onAbort, { once: true });
40
+ }
41
+ });
42
+ }
43
+
44
+ /**
45
+ * Attempt an async operation with retries and exponential backoff.
46
+ *
47
+ * If the signal is already aborted on entry, the operation is skipped entirely.
48
+ * If the signal aborts during a delay, the delay is cancelled immediately.
49
+ *
50
+ * @param fn - The async operation to retry.
51
+ * @param options - Optional configuration for retries, backoff, signal, and callbacks.
52
+ * @returns The result on success, or `null` if all attempts fail or the signal aborts.
53
+ */
54
+ export async function withRetry<T>(
55
+ fn: () => Promise<T>,
56
+ options?: WithRetryOptions,
57
+ ): Promise<T | null> {
58
+ const { retries = 2, baseDelayMs = 1000, signal, logger, onRetry } = options ?? {};
59
+
60
+ if (signal?.aborted) return null;
61
+
62
+ for (let attempt = 0; attempt <= retries; attempt++) {
63
+ try {
64
+ return await fn();
65
+ } catch (err) {
66
+ logger?.(attempt, err);
67
+ if (attempt >= retries || signal?.aborted) continue;
68
+
69
+ const delayMs = baseDelayMs * 2 ** attempt;
70
+ onRetry?.(attempt, delayMs);
71
+
72
+ try {
73
+ await delay(delayMs, signal);
74
+ } catch {
75
+ // delay() only rejects on abort
76
+ return null;
77
+ }
78
+ }
79
+ }
80
+
81
+ return null;
82
+ }
83
+
84
+ /**
85
+ * Extract and validate JSON from LLM response content blocks.
86
+ *
87
+ * Finds the first JSON object `{...}` in the combined text content,
88
+ * parses it, and validates against a TypeBox schema.
89
+ *
90
+ * @param content - The LLM response content blocks.
91
+ * @param schema - TypeBox schema to validate against.
92
+ * @returns The parsed and validated result, or `null` if extraction or validation fails.
93
+ */
94
+ export function extractJsonFromResponse<T extends TSchema>(
95
+ content: ReadonlyArray<{ type: string; text?: string }>,
96
+ schema: T,
97
+ ): { parsed: import("typebox").Static<T> } | null {
98
+ const text = content
99
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
100
+ .map((c) => c.text)
101
+ .join("");
102
+
103
+ const jsonMatch = text.match(/\{[\s\S]*\}/);
104
+ if (!jsonMatch) return null;
105
+
106
+ try {
107
+ const parsed = JSON.parse(jsonMatch[0]);
108
+ if (Value.Check(schema, parsed)) {
109
+ return { parsed } as { parsed: import("typebox").Static<T> };
110
+ }
111
+ return null;
112
+ } catch {
113
+ return null;
114
+ }
115
+ }
116
+
117
+ // ── callWithJsonResponse ───────────────────────────────────────────────────
118
+
119
+ /**
120
+ * Options for {@link callWithJsonResponse}.
121
+ */
122
+ export interface CallWithJsonResponseOptions {
123
+ /** The prompt to send to the LLM. */
124
+ prompt: string;
125
+ /** Optional data context appended to the prompt. */
126
+ dataContext?: string;
127
+ /** Maximum tokens for the response. Default: 4096 */
128
+ maxTokens?: number;
129
+ /** System prompt for the LLM call. Default: "" */
130
+ systemPrompt?: string;
131
+ /** Number of retries for the LLM call. Default: 2 */
132
+ retries?: number;
133
+ }
134
+
135
+ /**
136
+ * Call the LLM with a prompt and validate the JSON response against a TypeBox schema.
137
+ *
138
+ * Handles model resolution, auth, retry via `withRetry`, text extraction,
139
+ * JSON regex matching, and TypeBox validation.
140
+ *
141
+ * Returns `null` when:
142
+ * - No model is available
143
+ * - All retries fail
144
+ * - Response contains no valid JSON
145
+ * - JSON doesn't match the schema
146
+ * - The request is aborted
147
+ *
148
+ * @param ctx - The extension context for model resolution and auth.
149
+ * @param options - Call options including prompt, schema, and retry config.
150
+ * @param schema - TypeBox schema to validate the JSON response against.
151
+ * @returns The parsed and validated result, or `null`.
152
+ */
153
+ export async function callWithJsonResponse<T extends TSchema>(
154
+ ctx: ExtensionContext,
155
+ options: CallWithJsonResponseOptions,
156
+ schema: T,
157
+ ): Promise<{ parsed: import("typebox").Static<T> } | null> {
158
+ const { prompt, dataContext, maxTokens = 4096, systemPrompt = "", retries = 2 } = options;
159
+
160
+ const model = ctx.model ?? ctx.modelRegistry.getAvailable()[0] ?? null;
161
+ if (!model) return null;
162
+
163
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
164
+ if (!auth.ok || !auth.apiKey) return null;
165
+
166
+ const fullPrompt = dataContext
167
+ ? `${prompt}
168
+
169
+ DATA:
170
+ ${dataContext}`
171
+ : prompt;
172
+
173
+ const response = await withRetry(
174
+ async () => {
175
+ return complete(
176
+ model,
177
+ {
178
+ systemPrompt,
179
+ messages: [
180
+ {
181
+ role: "user",
182
+ content: [{ type: "text", text: fullPrompt }],
183
+ timestamp: Date.now(),
184
+ },
185
+ ],
186
+ },
187
+ {
188
+ apiKey: auth.apiKey,
189
+ headers: auth.headers,
190
+ signal: ctx.signal,
191
+ maxTokens,
192
+ },
193
+ );
194
+ },
195
+ { retries, baseDelayMs: 1000, signal: ctx.signal },
196
+ );
197
+
198
+ if (!response) return null;
199
+
200
+ return extractJsonFromResponse(response.content, schema);
201
+ }