@mrclrchtr/supi-consulting 0.0.0-stage → 8.0.1
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/CLAUDE.md +23 -0
- package/CONTEXT.md +53 -0
- package/README.md +104 -2
- package/docs/adr/0001-use-an-isolated-antigravity-home.md +5 -0
- package/node_modules/@mrclrchtr/supi-core/README.md +137 -0
- package/node_modules/@mrclrchtr/supi-core/package.json +77 -0
- package/node_modules/@mrclrchtr/supi-core/src/api.ts +42 -0
- package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +342 -0
- package/node_modules/@mrclrchtr/supi-core/src/config/prompt-surface.ts +363 -0
- package/node_modules/@mrclrchtr/supi-core/src/config.ts +17 -0
- package/node_modules/@mrclrchtr/supi-core/src/context/context-provider-registry.ts +36 -0
- package/node_modules/@mrclrchtr/supi-core/src/context/context-tag.ts +31 -0
- package/node_modules/@mrclrchtr/supi-core/src/context.ts +8 -0
- package/node_modules/@mrclrchtr/supi-core/src/debug-identity.ts +11 -0
- package/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +313 -0
- package/node_modules/@mrclrchtr/supi-core/src/debug-timing.ts +120 -0
- package/node_modules/@mrclrchtr/supi-core/src/debug.ts +14 -0
- package/node_modules/@mrclrchtr/supi-core/src/evidence-badge.ts +41 -0
- package/node_modules/@mrclrchtr/supi-core/src/footer-registry.ts +64 -0
- package/node_modules/@mrclrchtr/supi-core/src/index.ts +38 -0
- package/node_modules/@mrclrchtr/supi-core/src/llm.ts +356 -0
- package/node_modules/@mrclrchtr/supi-core/src/model-selection.ts +134 -0
- package/node_modules/@mrclrchtr/supi-core/src/path-utils.ts +44 -0
- package/node_modules/@mrclrchtr/supi-core/src/path.ts +2 -0
- package/node_modules/@mrclrchtr/supi-core/src/project-roots.ts +170 -0
- package/node_modules/@mrclrchtr/supi-core/src/project.ts +15 -0
- package/node_modules/@mrclrchtr/supi-core/src/prompt-surface.ts +4 -0
- package/node_modules/@mrclrchtr/supi-core/src/registry-utils.ts +93 -0
- package/node_modules/@mrclrchtr/supi-core/src/report.ts +121 -0
- package/node_modules/@mrclrchtr/supi-core/src/session-capabilities.ts +242 -0
- package/node_modules/@mrclrchtr/supi-core/src/session-capability-profiles.ts +240 -0
- package/node_modules/@mrclrchtr/supi-core/src/session-utils.ts +71 -0
- package/node_modules/@mrclrchtr/supi-core/src/session.ts +47 -0
- package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +105 -0
- package/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +454 -0
- package/node_modules/@mrclrchtr/supi-core/src/settings.ts +36 -0
- package/node_modules/@mrclrchtr/supi-core/src/spinner-frames.ts +11 -0
- package/node_modules/@mrclrchtr/supi-core/src/status-spinner.ts +68 -0
- package/node_modules/@mrclrchtr/supi-core/src/terminal.ts +60 -0
- package/node_modules/@mrclrchtr/supi-core/src/tui.ts +141 -0
- package/package.json +78 -4
- package/scripts/live-probe.ts +139 -0
- package/src/agents/antigravity/activity.ts +22 -0
- package/src/agents/antigravity/adapter.ts +196 -0
- package/src/agents/antigravity/availability.ts +231 -0
- package/src/agents/antigravity/isolated-home.ts +346 -0
- package/src/agents/antigravity/models.ts +15 -0
- package/src/agents/antigravity/process/environment.ts +33 -0
- package/src/agents/antigravity/process/event-values.ts +273 -0
- package/src/agents/antigravity/process/events.ts +366 -0
- package/src/agents/antigravity/process/hooks.ts +219 -0
- package/src/agents/antigravity/process/ndjson.ts +120 -0
- package/src/agents/antigravity/process/protocol.ts +69 -0
- package/src/agents/antigravity/process/runner.ts +147 -0
- package/src/agents/antigravity/process/subprocess.ts +278 -0
- package/src/agents/antigravity/process/usage.ts +50 -0
- package/src/agents/antigravity/structured-output.ts +58 -0
- package/src/agents/antigravity/types.ts +17 -0
- package/src/agents/errors.ts +27 -0
- package/src/agents/types.ts +43 -0
- package/src/catalogue.ts +17 -0
- package/src/config.ts +26 -0
- package/src/conversation/handles.ts +187 -0
- package/src/evidence-hash.ts +6 -0
- package/src/extension.ts +26 -0
- package/src/footer-constants.ts +5 -0
- package/src/footer.ts +25 -0
- package/src/runtime.ts +244 -0
- package/src/settings.ts +38 -0
- package/src/tool/consulting_run/evidence.ts +169 -0
- package/src/tool/consulting_run/execute.ts +201 -0
- package/src/tool/consulting_run/guidance.ts +3 -0
- package/src/tool/consulting_run/input.ts +117 -0
- package/src/tool/consulting_run/register.ts +36 -0
- package/src/tool/consulting_run/render.ts +261 -0
- package/src/tool/consulting_run/result.ts +185 -0
- package/src/tool/consulting_run/spec.ts +20 -0
- package/src/types.ts +104 -0
|
@@ -0,0 +1,38 @@
|
|
|
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.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 "./llm.ts";
|
|
19
|
+
// biome-ignore lint/performance/noReExportAll: intentional convenience barrel
|
|
20
|
+
export * from "./model-selection.ts";
|
|
21
|
+
// biome-ignore lint/performance/noReExportAll: intentional convenience barrel
|
|
22
|
+
export * from "./path.ts";
|
|
23
|
+
// biome-ignore lint/performance/noReExportAll: intentional convenience barrel
|
|
24
|
+
export * from "./project.ts";
|
|
25
|
+
// biome-ignore lint/performance/noReExportAll: intentional convenience barrel
|
|
26
|
+
export * from "./prompt-surface.ts";
|
|
27
|
+
// biome-ignore lint/performance/noReExportAll: intentional convenience barrel
|
|
28
|
+
export * from "./report.ts";
|
|
29
|
+
// biome-ignore lint/performance/noReExportAll: intentional convenience barrel
|
|
30
|
+
export * from "./session.ts";
|
|
31
|
+
// biome-ignore lint/performance/noReExportAll: intentional convenience barrel
|
|
32
|
+
export * from "./settings.ts";
|
|
33
|
+
// biome-ignore lint/performance/noReExportAll: intentional convenience barrel
|
|
34
|
+
export * from "./status-spinner.ts";
|
|
35
|
+
// biome-ignore lint/performance/noReExportAll: intentional convenience barrel
|
|
36
|
+
export * from "./terminal.ts";
|
|
37
|
+
// biome-ignore lint/performance/noReExportAll: intentional convenience barrel
|
|
38
|
+
export * from "./tui.ts";
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type {
|
|
3
|
+
Api,
|
|
4
|
+
AssistantMessage,
|
|
5
|
+
Context,
|
|
6
|
+
Model,
|
|
7
|
+
ModelsApiStreamOptions,
|
|
8
|
+
ModelsSimpleStreamOptions,
|
|
9
|
+
ProviderHeaders,
|
|
10
|
+
} from "@earendil-works/pi-ai";
|
|
11
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import type { TSchema } from "typebox";
|
|
13
|
+
import { Value } from "typebox/value";
|
|
14
|
+
|
|
15
|
+
// Shared LLM utilities for SuPi extensions.
|
|
16
|
+
//
|
|
17
|
+
// Provides PI-owned model requests, retry logic, structured LLM call helpers,
|
|
18
|
+
// and other common patterns for extensions that interact with AI models.
|
|
19
|
+
|
|
20
|
+
const MODEL_REQUEST_NAMESPACE = "supi-direct-model-request-v1";
|
|
21
|
+
|
|
22
|
+
type ModelRequestOptions<T> = Omit<T, "apiKey" | "env" | "sessionId"> & {
|
|
23
|
+
/** Stable feature scope. Do not include prompt, turn, or retry data. */
|
|
24
|
+
affinityScope: string;
|
|
25
|
+
/** PI owns these fields, including for APIs with open-ended option types. */
|
|
26
|
+
apiKey?: never;
|
|
27
|
+
env?: never;
|
|
28
|
+
sessionId?: never;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** API-specific completion options. PI owns auth, environment, and identity. */
|
|
32
|
+
export type CompleteModelRequestOptions<TApi extends Api = Api> = ModelRequestOptions<
|
|
33
|
+
ModelsApiStreamOptions<TApi>
|
|
34
|
+
>;
|
|
35
|
+
|
|
36
|
+
/** Provider-neutral completion options. PI owns auth, environment, and identity. */
|
|
37
|
+
export type CompleteSimpleModelRequestOptions = ModelRequestOptions<ModelsSimpleStreamOptions>;
|
|
38
|
+
|
|
39
|
+
function createModelRequestAffinityId(
|
|
40
|
+
sessionId: string,
|
|
41
|
+
affinityScope: string,
|
|
42
|
+
model: Model<Api>,
|
|
43
|
+
): string {
|
|
44
|
+
const material = JSON.stringify([
|
|
45
|
+
MODEL_REQUEST_NAMESPACE,
|
|
46
|
+
sessionId,
|
|
47
|
+
affinityScope,
|
|
48
|
+
model.provider,
|
|
49
|
+
model.id,
|
|
50
|
+
]);
|
|
51
|
+
const digest = createHash("sha256").update(material, "utf8").digest("hex");
|
|
52
|
+
return `supi-${digest.slice(0, 56)}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function isOpenCodeModel(model: Model<Api>): boolean {
|
|
56
|
+
if (model.provider === "opencode" || model.provider === "opencode-go") return true;
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
return new URL(model.baseUrl).hostname === "opencode.ai";
|
|
60
|
+
} catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function hasHeader(headers: ProviderHeaders, name: string): boolean {
|
|
66
|
+
const lowerName = name.toLowerCase();
|
|
67
|
+
return Object.keys(headers).some((headerName) => headerName.toLowerCase() === lowerName);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function addOpenCodeDefaultHeaders(
|
|
71
|
+
model: Model<Api>,
|
|
72
|
+
affinityId: string,
|
|
73
|
+
headers: ProviderHeaders,
|
|
74
|
+
): ProviderHeaders {
|
|
75
|
+
if (!isOpenCodeModel(model)) return headers;
|
|
76
|
+
|
|
77
|
+
const result = { ...headers };
|
|
78
|
+
if (!hasHeader(result, "x-opencode-session")) {
|
|
79
|
+
result["x-opencode-session"] = affinityId;
|
|
80
|
+
}
|
|
81
|
+
if (!hasHeader(result, "x-opencode-client")) {
|
|
82
|
+
result["x-opencode-client"] = "pi";
|
|
83
|
+
}
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Keep request identity and header policy identical for both completion paths. */
|
|
88
|
+
function prepareModelRequestOptions<
|
|
89
|
+
T extends Pick<ModelsSimpleStreamOptions, "signal" | "transformHeaders">,
|
|
90
|
+
>(ctx: ExtensionContext, model: Model<Api>, options: ModelRequestOptions<T>): T {
|
|
91
|
+
const { affinityScope, transformHeaders: callerTransformHeaders, ...requestOptions } = options;
|
|
92
|
+
const safeRequestOptions = { ...requestOptions };
|
|
93
|
+
delete safeRequestOptions.apiKey;
|
|
94
|
+
delete safeRequestOptions.env;
|
|
95
|
+
delete safeRequestOptions.sessionId;
|
|
96
|
+
|
|
97
|
+
const affinityId = createModelRequestAffinityId(
|
|
98
|
+
ctx.sessionManager.getSessionId(),
|
|
99
|
+
affinityScope,
|
|
100
|
+
model,
|
|
101
|
+
);
|
|
102
|
+
const transformHeaders = async (headers: ProviderHeaders): Promise<ProviderHeaders> => {
|
|
103
|
+
const transformed = callerTransformHeaders ? await callerTransformHeaders(headers) : headers;
|
|
104
|
+
return addOpenCodeDefaultHeaders(model, affinityId, transformed);
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// Restore PI's option type after removing owned fields.
|
|
108
|
+
return {
|
|
109
|
+
...safeRequestOptions,
|
|
110
|
+
signal: safeRequestOptions.signal ?? ctx.signal,
|
|
111
|
+
sessionId: affinityId,
|
|
112
|
+
transformHeaders,
|
|
113
|
+
} as unknown as T;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Complete an API-specific request through PI's model registry.
|
|
118
|
+
*
|
|
119
|
+
* PI resolves auth, headers, environment, and the effective endpoint. SuPi adds
|
|
120
|
+
* a stable opaque feature identity and OpenCode header defaults. This helper
|
|
121
|
+
* does not retry, validate output, or present errors. It supplies no output cap
|
|
122
|
+
* when `maxTokens` is omitted; use {@link completeSimpleModelRequest} for PI's
|
|
123
|
+
* model-derived defaults and context-aware limits.
|
|
124
|
+
*/
|
|
125
|
+
export async function completeModelRequest<TApi extends Api>(
|
|
126
|
+
ctx: ExtensionContext,
|
|
127
|
+
model: Model<TApi>,
|
|
128
|
+
context: Context,
|
|
129
|
+
options: CompleteModelRequestOptions<TApi>,
|
|
130
|
+
): Promise<AssistantMessage> {
|
|
131
|
+
return ctx.modelRegistry.complete(
|
|
132
|
+
model,
|
|
133
|
+
context,
|
|
134
|
+
prepareModelRequestOptions<ModelsApiStreamOptions<TApi>>(ctx, model, options),
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Complete a provider-neutral request through PI's registry simple path.
|
|
140
|
+
*
|
|
141
|
+
* Requires PI 0.86.0 or later. PI's provider handles simple options, including
|
|
142
|
+
* model-derived output limits and context estimates. Request identity, header
|
|
143
|
+
* policy, and error behavior match {@link completeModelRequest}.
|
|
144
|
+
*/
|
|
145
|
+
export async function completeSimpleModelRequest(
|
|
146
|
+
ctx: ExtensionContext,
|
|
147
|
+
model: Model<Api>,
|
|
148
|
+
context: Context,
|
|
149
|
+
options: CompleteSimpleModelRequestOptions,
|
|
150
|
+
): Promise<AssistantMessage> {
|
|
151
|
+
return ctx.modelRegistry
|
|
152
|
+
.streamSimple(
|
|
153
|
+
model,
|
|
154
|
+
context,
|
|
155
|
+
prepareModelRequestOptions<ModelsSimpleStreamOptions>(ctx, model, options),
|
|
156
|
+
)
|
|
157
|
+
.result();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Options for {@link withRetry}.
|
|
162
|
+
*/
|
|
163
|
+
export interface WithRetryOptions {
|
|
164
|
+
/** Maximum number of retry attempts after the initial call. Default: 2 */
|
|
165
|
+
retries?: number;
|
|
166
|
+
/** Base delay in milliseconds for exponential backoff. Default: 1000 */
|
|
167
|
+
baseDelayMs?: number;
|
|
168
|
+
/** AbortSignal to cancel retry loops. */
|
|
169
|
+
signal?: AbortSignal;
|
|
170
|
+
/** Called with each failed attempt's attempt index and error. */
|
|
171
|
+
logger?: (attempt: number, error: unknown) => void;
|
|
172
|
+
/** Called before each retry delay with attempt index and computed delay. */
|
|
173
|
+
onRetry?: (attempt: number, delayMs: number) => void;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Create a promise that resolves after `ms` milliseconds, or rejects if
|
|
178
|
+
* the signal fires before the timeout elapses.
|
|
179
|
+
*/
|
|
180
|
+
function delay(ms: number, signal?: AbortSignal): Promise<void> {
|
|
181
|
+
return new Promise<void>((resolve, reject) => {
|
|
182
|
+
const timer = setTimeout(resolve, ms);
|
|
183
|
+
if (signal) {
|
|
184
|
+
const onAbort = () => {
|
|
185
|
+
clearTimeout(timer);
|
|
186
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
187
|
+
};
|
|
188
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Attempt an async operation with retries and exponential backoff.
|
|
195
|
+
*
|
|
196
|
+
* If the signal is already aborted on entry, the operation is skipped entirely.
|
|
197
|
+
* If the signal aborts during a delay, the delay is cancelled immediately.
|
|
198
|
+
*
|
|
199
|
+
* @param fn - The async operation to retry.
|
|
200
|
+
* @param options - Optional configuration for retries, backoff, signal, and callbacks.
|
|
201
|
+
* @returns The result on success, or `null` if all attempts fail or the signal aborts.
|
|
202
|
+
*/
|
|
203
|
+
export async function withRetry<T>(
|
|
204
|
+
fn: () => Promise<T>,
|
|
205
|
+
options?: WithRetryOptions,
|
|
206
|
+
): Promise<T | null> {
|
|
207
|
+
const { retries = 2, baseDelayMs = 1000, signal, logger, onRetry } = options ?? {};
|
|
208
|
+
|
|
209
|
+
if (signal?.aborted) return null;
|
|
210
|
+
|
|
211
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
212
|
+
try {
|
|
213
|
+
return await fn();
|
|
214
|
+
} catch (err) {
|
|
215
|
+
logger?.(attempt, err);
|
|
216
|
+
if (attempt >= retries || signal?.aborted) continue;
|
|
217
|
+
|
|
218
|
+
const delayMs = baseDelayMs * 2 ** attempt;
|
|
219
|
+
onRetry?.(attempt, delayMs);
|
|
220
|
+
|
|
221
|
+
try {
|
|
222
|
+
await delay(delayMs, signal);
|
|
223
|
+
} catch {
|
|
224
|
+
// delay() only rejects on abort
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Extract and validate JSON from LLM response content blocks.
|
|
235
|
+
*
|
|
236
|
+
* Finds the first JSON object `{...}` in the combined text content,
|
|
237
|
+
* parses it, and validates against a TypeBox schema.
|
|
238
|
+
*
|
|
239
|
+
* @param content - The LLM response content blocks.
|
|
240
|
+
* @param schema - TypeBox schema to validate against.
|
|
241
|
+
* @returns The parsed and validated result, or `null` if extraction or validation fails.
|
|
242
|
+
*/
|
|
243
|
+
export function extractJsonFromResponse<T extends TSchema>(
|
|
244
|
+
content: ReadonlyArray<{ type: string; text?: string }>,
|
|
245
|
+
schema: T,
|
|
246
|
+
): { parsed: import("typebox").Static<T> } | null {
|
|
247
|
+
const text = content
|
|
248
|
+
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
249
|
+
.map((c) => c.text)
|
|
250
|
+
.join("");
|
|
251
|
+
|
|
252
|
+
const jsonMatch = text.match(/\{[\s\S]*\}/);
|
|
253
|
+
if (!jsonMatch) return null;
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
const parsed = JSON.parse(jsonMatch[0]);
|
|
257
|
+
if (Value.Check(schema, parsed)) {
|
|
258
|
+
return { parsed } as { parsed: import("typebox").Static<T> };
|
|
259
|
+
}
|
|
260
|
+
return null;
|
|
261
|
+
} catch {
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// ── callWithJsonResponse ───────────────────────────────────────────────────
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Options for {@link callWithJsonResponse}.
|
|
270
|
+
*/
|
|
271
|
+
export interface CallWithJsonResponseOptions {
|
|
272
|
+
/** The prompt to send to the LLM. */
|
|
273
|
+
prompt: string;
|
|
274
|
+
/** Stable feature scope for request affinity. Do not include prompt or retry data. */
|
|
275
|
+
affinityScope: string;
|
|
276
|
+
/** Optional data context appended to the prompt. */
|
|
277
|
+
dataContext?: string;
|
|
278
|
+
/** Maximum tokens for the response. Default: 4096 */
|
|
279
|
+
maxTokens?: number;
|
|
280
|
+
/** System prompt for the LLM call. Default: "" */
|
|
281
|
+
systemPrompt?: string;
|
|
282
|
+
/** Number of retries for the LLM call. Default: 2 */
|
|
283
|
+
retries?: number;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Call the LLM with a prompt and validate the JSON response against a TypeBox schema.
|
|
288
|
+
*
|
|
289
|
+
* Handles model resolution, retry via `withRetry`, text extraction, JSON
|
|
290
|
+
* matching, and TypeBox validation. The request itself stays under PI
|
|
291
|
+
* registry authority through {@link completeModelRequest}.
|
|
292
|
+
*
|
|
293
|
+
* Returns `null` when:
|
|
294
|
+
* - No model is available
|
|
295
|
+
* - All retries fail
|
|
296
|
+
* - Response contains no valid JSON
|
|
297
|
+
* - JSON doesn't match the schema
|
|
298
|
+
* - The request is aborted
|
|
299
|
+
*
|
|
300
|
+
* @param ctx - The extension context for model selection and PI registry access.
|
|
301
|
+
* @param options - Call options including prompt, schema, and retry config.
|
|
302
|
+
* @param schema - TypeBox schema to validate the JSON response against.
|
|
303
|
+
* @returns The parsed and validated result, or `null`.
|
|
304
|
+
*/
|
|
305
|
+
export async function callWithJsonResponse<T extends TSchema>(
|
|
306
|
+
ctx: ExtensionContext,
|
|
307
|
+
options: CallWithJsonResponseOptions,
|
|
308
|
+
schema: T,
|
|
309
|
+
): Promise<{ parsed: import("typebox").Static<T> } | null> {
|
|
310
|
+
const {
|
|
311
|
+
prompt,
|
|
312
|
+
affinityScope,
|
|
313
|
+
dataContext,
|
|
314
|
+
maxTokens = 4096,
|
|
315
|
+
systemPrompt = "",
|
|
316
|
+
retries = 2,
|
|
317
|
+
} = options;
|
|
318
|
+
|
|
319
|
+
const model = ctx.model ?? ctx.modelRegistry.getAvailable()[0] ?? null;
|
|
320
|
+
if (!model) return null;
|
|
321
|
+
|
|
322
|
+
const fullPrompt = dataContext
|
|
323
|
+
? `${prompt}
|
|
324
|
+
|
|
325
|
+
DATA:
|
|
326
|
+
${dataContext}`
|
|
327
|
+
: prompt;
|
|
328
|
+
|
|
329
|
+
const response = await withRetry(
|
|
330
|
+
async () =>
|
|
331
|
+
completeModelRequest(
|
|
332
|
+
ctx,
|
|
333
|
+
model,
|
|
334
|
+
{
|
|
335
|
+
systemPrompt,
|
|
336
|
+
messages: [
|
|
337
|
+
{
|
|
338
|
+
role: "user",
|
|
339
|
+
content: [{ type: "text", text: fullPrompt }],
|
|
340
|
+
timestamp: Date.now(),
|
|
341
|
+
},
|
|
342
|
+
],
|
|
343
|
+
},
|
|
344
|
+
{
|
|
345
|
+
affinityScope,
|
|
346
|
+
signal: ctx.signal,
|
|
347
|
+
maxTokens,
|
|
348
|
+
},
|
|
349
|
+
),
|
|
350
|
+
{ retries, baseDelayMs: 1000, signal: ctx.signal },
|
|
351
|
+
);
|
|
352
|
+
|
|
353
|
+
if (!response) return null;
|
|
354
|
+
|
|
355
|
+
return extractJsonFromResponse(response.content, schema);
|
|
356
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared model-selection helpers for SuPi extensions.
|
|
3
|
+
*
|
|
4
|
+
* Provides scoped-model listing using PI's `enabledModels` configuration,
|
|
5
|
+
* matching the same semantics as the `@mrclrchtr/supi-review` model picker.
|
|
6
|
+
*
|
|
7
|
+
* @module
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Model } from "@earendil-works/pi-ai/compat";
|
|
11
|
+
import { type ExtensionContext, SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
|
|
13
|
+
// ── Types ──────────────────────────────────────────────────────────────────
|
|
14
|
+
|
|
15
|
+
/** A selectable model entry with display metadata. */
|
|
16
|
+
export interface ModelSelection {
|
|
17
|
+
/** Canonical `provider/model-id` string. */
|
|
18
|
+
canonicalId: string;
|
|
19
|
+
/** Provider name, e.g. `"anthropic"`. */
|
|
20
|
+
provider: string;
|
|
21
|
+
/** Model id, e.g. `"claude-sonnet-4-5"`. */
|
|
22
|
+
id: string;
|
|
23
|
+
// biome-ignore lint/suspicious/noExplicitAny: Model<any> is pi's canonical type
|
|
24
|
+
model: Model<any>;
|
|
25
|
+
/** Human-readable label (model name or canonicalId). */
|
|
26
|
+
label: string;
|
|
27
|
+
/** Optional description (canonicalId when different from label). */
|
|
28
|
+
description?: string;
|
|
29
|
+
/** Whether this model is the current session model. */
|
|
30
|
+
isCurrent: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// ── Helpers ────────────────────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
/** Build the canonical `provider/model-id` string. */
|
|
36
|
+
export function toCanonicalModelId(
|
|
37
|
+
model: Pick<NonNullable<ExtensionContext["model"]>, "provider" | "id">,
|
|
38
|
+
): string {
|
|
39
|
+
return `${model.provider}/${model.id}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* List selectable models from PI's scoped model configuration.
|
|
44
|
+
*
|
|
45
|
+
* Only models that match the configured `enabledModels` patterns are offered.
|
|
46
|
+
* The current session model is included only when it is inside that scoped set.
|
|
47
|
+
* Returns an empty array when no scoped model patterns are configured.
|
|
48
|
+
*/
|
|
49
|
+
export function getSelectableModels(
|
|
50
|
+
ctx: Pick<ExtensionContext, "cwd" | "modelRegistry" | "model">,
|
|
51
|
+
enabledModelPatterns = SettingsManager.create(ctx.cwd).getEnabledModels(),
|
|
52
|
+
): ModelSelection[] {
|
|
53
|
+
if (!enabledModelPatterns || enabledModelPatterns.length === 0) {
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const byCanonicalId = new Map<string, ModelSelection>();
|
|
58
|
+
const availableModels = filterByEnabledModels(
|
|
59
|
+
enabledModelPatterns,
|
|
60
|
+
ctx.modelRegistry.getAvailable(),
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
const addModel = (
|
|
64
|
+
// biome-ignore lint/suspicious/noExplicitAny: Model<any> is pi's canonical type
|
|
65
|
+
model: Model<any>,
|
|
66
|
+
isCurrent: boolean,
|
|
67
|
+
) => {
|
|
68
|
+
const canonicalId = toCanonicalModelId(model);
|
|
69
|
+
const existing = byCanonicalId.get(canonicalId);
|
|
70
|
+
if (existing) {
|
|
71
|
+
if (isCurrent) existing.isCurrent = true;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
byCanonicalId.set(canonicalId, {
|
|
76
|
+
canonicalId,
|
|
77
|
+
provider: model.provider,
|
|
78
|
+
id: model.id,
|
|
79
|
+
model,
|
|
80
|
+
label: model.name ?? canonicalId,
|
|
81
|
+
description: canonicalId,
|
|
82
|
+
isCurrent,
|
|
83
|
+
});
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
if (ctx.model && matchModelPatterns(ctx.model, enabledModelPatterns)) {
|
|
87
|
+
addModel(ctx.model, true);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
for (const model of availableModels) {
|
|
91
|
+
addModel(
|
|
92
|
+
model,
|
|
93
|
+
ctx.model ? toCanonicalModelId(model) === toCanonicalModelId(ctx.model) : false,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return Array.from(byCanonicalId.values()).sort((a, b) => {
|
|
98
|
+
if (a.isCurrent !== b.isCurrent) return a.isCurrent ? -1 : 1;
|
|
99
|
+
return a.canonicalId.localeCompare(b.canonicalId);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ── Private helpers ────────────────────────────────────────────────────────
|
|
104
|
+
|
|
105
|
+
function filterByEnabledModels<T extends { provider: string; id: string }>(
|
|
106
|
+
patterns: string[],
|
|
107
|
+
models: T[],
|
|
108
|
+
): T[] {
|
|
109
|
+
return models.filter((model) => matchModelPatterns(model, patterns));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function matchModelPatterns(model: { provider: string; id: string }, patterns: string[]): boolean {
|
|
113
|
+
return patterns.some((pattern) => matchModelPattern(model, pattern));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function matchModelPattern(model: { provider: string; id: string }, pattern: string): boolean {
|
|
117
|
+
const canonicalId = `${model.provider}/${model.id}`;
|
|
118
|
+
if (pattern.includes("/")) {
|
|
119
|
+
return simpleGlobMatch(canonicalId, pattern);
|
|
120
|
+
}
|
|
121
|
+
return simpleGlobMatch(model.id, pattern) || simpleGlobMatch(canonicalId, pattern);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function simpleGlobMatch(text: string, pattern: string): boolean {
|
|
125
|
+
if (!pattern.includes("*") && !pattern.includes("?")) {
|
|
126
|
+
return text.toLowerCase() === pattern.toLowerCase();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const regex = pattern
|
|
130
|
+
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
131
|
+
.replace(/\*/g, ".*")
|
|
132
|
+
.replace(/\?/g, ".");
|
|
133
|
+
return new RegExp(`^${regex}$`, "i").test(text);
|
|
134
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
3
|
+
|
|
4
|
+
/** Strip pi's optional leading `@` file-path prefix from a tool input. */
|
|
5
|
+
export function stripToolPathPrefix(target: string): string {
|
|
6
|
+
return target.startsWith("@") ? target.slice(1) : target;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Resolve a tool-style file path from a session cwd.
|
|
11
|
+
*
|
|
12
|
+
* Built-in pi file tools accept a leading `@` prefix in path arguments, so
|
|
13
|
+
* shared SuPi path helpers normalize that prefix before resolving relative
|
|
14
|
+
* paths.
|
|
15
|
+
*/
|
|
16
|
+
export function resolveToolPath(cwd: string, target: string): string {
|
|
17
|
+
return path.resolve(cwd, stripToolPathPrefix(target));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Convert a file path to a file:// URI.
|
|
22
|
+
*
|
|
23
|
+
* Uses Node's `pathToFileURL` to produce a standards-compliant URI with
|
|
24
|
+
* proper percent-encoding of spaces, hashes, and other special characters.
|
|
25
|
+
*/
|
|
26
|
+
export function fileToUri(filePath: string): string {
|
|
27
|
+
return pathToFileURL(filePath).href;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Convert a file:// URI to a file path.
|
|
32
|
+
*
|
|
33
|
+
* Uses Node's `fileURLToPath` for standards-compliant decoding. Non-file
|
|
34
|
+
* URIs are passed through unchanged so consumers (such as LSP diagnostic
|
|
35
|
+
* handling) remain compatible with non-file URI schemes.
|
|
36
|
+
*/
|
|
37
|
+
export function uriToFile(uri: string): string {
|
|
38
|
+
if (!uri.startsWith("file://")) return uri;
|
|
39
|
+
try {
|
|
40
|
+
return fileURLToPath(uri);
|
|
41
|
+
} catch {
|
|
42
|
+
return uri;
|
|
43
|
+
}
|
|
44
|
+
}
|