@mrclrchtr/supi-web 7.1.1 → 7.2.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/README.md +19 -5
- package/node_modules/@mrclrchtr/supi-core/README.md +127 -0
- package/node_modules/@mrclrchtr/supi-core/package.json +72 -0
- package/node_modules/@mrclrchtr/supi-core/src/api.ts +40 -0
- package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +232 -0
- package/node_modules/@mrclrchtr/supi-core/src/config/prompt-surface.ts +363 -0
- package/node_modules/@mrclrchtr/supi-core/src/config.ts +12 -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 +308 -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 +36 -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-utils.ts +71 -0
- package/node_modules/@mrclrchtr/supi-core/src/session.ts +8 -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 +453 -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/package.json +8 -3
- package/src/api.ts +1 -0
- package/src/config.ts +29 -0
- package/src/settings-registration.ts +63 -0
- package/src/tool/tool-specs.ts +21 -0
- package/src/tool/web_search/bx.ts +178 -0
- package/src/tool/web_search/execute.ts +39 -0
- package/src/tool/web_search/guidance.ts +6 -0
- package/src/tool/web_search/input.ts +91 -0
- package/src/tool/web_search/parse.ts +92 -0
- package/src/tool/web_search/register.ts +16 -0
- package/src/tool/web_search/render.ts +95 -0
- package/src/tool/web_search/result.ts +58 -0
- package/src/tool/web_search/spec.ts +18 -0
- package/src/web.ts +26 -3
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
|
|
4
|
+
const IGNORED_DIRECTORIES = new Set(["node_modules", ".git", ".pnpm"]);
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Walk a project directory tree, calling `onDirectory` for each directory.
|
|
8
|
+
* Skips `node_modules`, `.git`, and `.pnpm`.
|
|
9
|
+
* Stops at depth 0.
|
|
10
|
+
*/
|
|
11
|
+
export function walkProject(
|
|
12
|
+
directory: string,
|
|
13
|
+
depth: number,
|
|
14
|
+
onDirectory: (directory: string, entryNames: Set<string>) => void,
|
|
15
|
+
): void {
|
|
16
|
+
let entries: fs.Dirent[];
|
|
17
|
+
try {
|
|
18
|
+
entries = fs.readdirSync(directory, { withFileTypes: true });
|
|
19
|
+
} catch {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const entryNames = new Set(entries.map((entry) => entry.name));
|
|
24
|
+
onDirectory(directory, entryNames);
|
|
25
|
+
|
|
26
|
+
if (depth <= 0) return;
|
|
27
|
+
|
|
28
|
+
for (const entry of entries) {
|
|
29
|
+
if (!entry.isDirectory()) continue;
|
|
30
|
+
if (IGNORED_DIRECTORIES.has(entry.name)) continue;
|
|
31
|
+
walkProject(path.join(directory, entry.name), depth - 1, onDirectory);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Search upward from `startDir` for any of the `markers` files/dirs.
|
|
37
|
+
* Returns the directory containing the first found marker, or `fallback`.
|
|
38
|
+
*/
|
|
39
|
+
export function findProjectRoot(startDir: string, markers: string[], fallback: string): string {
|
|
40
|
+
let dir = path.resolve(startDir);
|
|
41
|
+
const root = path.parse(dir).root;
|
|
42
|
+
|
|
43
|
+
while (dir !== root) {
|
|
44
|
+
for (const marker of markers) {
|
|
45
|
+
if (fs.existsSync(path.join(dir, marker))) {
|
|
46
|
+
return dir;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const parent = path.dirname(dir);
|
|
50
|
+
if (parent === dir) break;
|
|
51
|
+
dir = parent;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return fallback;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Deduplicate overlapping roots, keeping only the topmost (shortest path) roots.
|
|
59
|
+
*/
|
|
60
|
+
export function dedupeTopmostRoots(roots: string[]): string[] {
|
|
61
|
+
const accepted: string[] = [];
|
|
62
|
+
|
|
63
|
+
for (const root of [...new Set(roots.map((entry) => path.resolve(entry)))].sort(byPathDepth)) {
|
|
64
|
+
const isChild = accepted.some((parent) => root !== parent && isWithin(parent, root));
|
|
65
|
+
if (!isChild) {
|
|
66
|
+
accepted.push(root);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return accepted;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Minimal shape accepted by `buildKnownRootsMap`.
|
|
75
|
+
* Structurally compatible with `DetectedProjectServer` and similar
|
|
76
|
+
* `{ name, root }` records — callers may pass a wider type safely.
|
|
77
|
+
*/
|
|
78
|
+
export type KnownRootEntry = { name: string; root: string };
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Build a map of language/server name to sorted, deduplicated root paths.
|
|
82
|
+
*
|
|
83
|
+
* Accepts an array of detected project entries (e.g. from LSP project discovery)
|
|
84
|
+
* and groups them by name with roots sorted by specificity.
|
|
85
|
+
*/
|
|
86
|
+
export function buildKnownRootsMap(detected: KnownRootEntry[]): Map<string, string[]> {
|
|
87
|
+
const next = new Map<string, string[]>();
|
|
88
|
+
|
|
89
|
+
for (const entry of detected) {
|
|
90
|
+
const roots = next.get(entry.name) ?? [];
|
|
91
|
+
if (!roots.includes(entry.root)) roots.push(entry.root);
|
|
92
|
+
next.set(entry.name, sortRootsBySpecificity(roots));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return next;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Merge a new root into an existing list, deduplicating and sorting.
|
|
100
|
+
*
|
|
101
|
+
* Returns the original reference when the root is already present.
|
|
102
|
+
*/
|
|
103
|
+
export function mergeKnownRoots(roots: string[], root: string): string[] {
|
|
104
|
+
if (roots.includes(root)) return roots;
|
|
105
|
+
return sortRootsBySpecificity([...roots, root]);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Resolve the most specific known root that contains `filePath`.
|
|
110
|
+
*
|
|
111
|
+
* Searches the given roots list (presumed sorted by specificity) and returns
|
|
112
|
+
* the first root that contains or equals `filePath`.
|
|
113
|
+
*
|
|
114
|
+
* @returns The matching root string, or `null` when none match.
|
|
115
|
+
*/
|
|
116
|
+
export function resolveKnownRoot(filePath: string, roots: string[]): string | null {
|
|
117
|
+
const resolvedPath = path.resolve(filePath);
|
|
118
|
+
return roots.find((root) => isWithinOrEqual(root, resolvedPath)) ?? null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Sort roots by specificity (deepest/longest first), then alphabetically.
|
|
123
|
+
*
|
|
124
|
+
* Deduplicates by resolved path before sorting.
|
|
125
|
+
*/
|
|
126
|
+
export function sortRootsBySpecificity(roots: string[]): string[] {
|
|
127
|
+
return [...new Set(roots.map((root) => path.resolve(root)))].sort(
|
|
128
|
+
(a, b) => b.length - a.length || a.localeCompare(b),
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Check if `child` is strictly inside `parent`.
|
|
134
|
+
*
|
|
135
|
+
* Returns `true` when `child` is a subdirectory of `parent`.
|
|
136
|
+
* Returns `false` for the same path.
|
|
137
|
+
*/
|
|
138
|
+
export function isWithin(parent: string, child: string): boolean {
|
|
139
|
+
const relative = path.relative(parent, child);
|
|
140
|
+
return relative !== "" && !relative.startsWith(`..${path.sep}`) && relative !== "..";
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Check if `filePath` is inside `root` or is the same path.
|
|
145
|
+
*
|
|
146
|
+
* Combines exact-path equality with `isWithin` semantics.
|
|
147
|
+
*/
|
|
148
|
+
export function isWithinOrEqual(root: string, filePath: string): boolean {
|
|
149
|
+
const relative = path.relative(root, filePath);
|
|
150
|
+
return relative === "" || isWithin(root, filePath);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Comparator for sorting paths by depth (shallowest first), then alphabetically.
|
|
155
|
+
*
|
|
156
|
+
* Useful with `.sort()` on arrays of path strings.
|
|
157
|
+
*/
|
|
158
|
+
export function byPathDepth(a: string, b: string): number {
|
|
159
|
+
const depthDiff = segmentCount(a) - segmentCount(b);
|
|
160
|
+
return depthDiff !== 0 ? depthDiff : a.localeCompare(b);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Count path segments in a resolved absolute path.
|
|
165
|
+
*
|
|
166
|
+
* @example segmentCount("/a/b/c") // 3
|
|
167
|
+
*/
|
|
168
|
+
export function segmentCount(target: string): number {
|
|
169
|
+
return path.resolve(target).split(path.sep).filter(Boolean).length;
|
|
170
|
+
}
|