@mrclrchtr/supi-antigravity 6.4.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.
- package/CLAUDE.md +21 -0
- package/CONTEXT.md +53 -0
- package/README.md +75 -0
- package/docs/adr/0001-use-an-isolated-antigravity-home.md +5 -0
- package/node_modules/@mrclrchtr/supi-core/README.md +118 -0
- package/node_modules/@mrclrchtr/supi-core/package.json +76 -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 +57 -0
- package/node_modules/@mrclrchtr/supi-core/src/index.ts +34 -0
- package/node_modules/@mrclrchtr/supi-core/src/llm.ts +201 -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 +79 -0
- package/scripts/live-probe.ts +161 -0
- package/src/activity.ts +22 -0
- package/src/availability.ts +231 -0
- package/src/catalogue.ts +21 -0
- package/src/config.ts +26 -0
- package/src/conversation/handles.ts +183 -0
- package/src/extension.ts +22 -0
- package/src/isolated-home.ts +346 -0
- package/src/process/environment.ts +33 -0
- package/src/process/event-values.ts +279 -0
- package/src/process/events.ts +365 -0
- package/src/process/hooks.ts +219 -0
- package/src/process/ndjson.ts +120 -0
- package/src/process/protocol.ts +69 -0
- package/src/process/runner.ts +147 -0
- package/src/process/subprocess.ts +278 -0
- package/src/process/usage.ts +50 -0
- package/src/runtime.ts +118 -0
- package/src/settings.ts +38 -0
- package/src/structured-output.ts +58 -0
- package/src/tool/antigravity_run/evidence.ts +169 -0
- package/src/tool/antigravity_run/execute.ts +225 -0
- package/src/tool/antigravity_run/guidance.ts +3 -0
- package/src/tool/antigravity_run/input.ts +106 -0
- package/src/tool/antigravity_run/register.ts +36 -0
- package/src/tool/antigravity_run/render.ts +236 -0
- package/src/tool/antigravity_run/result.ts +186 -0
- package/src/tool/antigravity_run/spec.ts +20 -0
- package/src/types.ts +107 -0
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// supi-core project domain — project root discovery and traversal.
|
|
2
|
+
export type { KnownRootEntry } from "./project-roots.ts";
|
|
3
|
+
export {
|
|
4
|
+
buildKnownRootsMap,
|
|
5
|
+
byPathDepth,
|
|
6
|
+
dedupeTopmostRoots,
|
|
7
|
+
findProjectRoot,
|
|
8
|
+
isWithin,
|
|
9
|
+
isWithinOrEqual,
|
|
10
|
+
mergeKnownRoots,
|
|
11
|
+
resolveKnownRoot,
|
|
12
|
+
segmentCount,
|
|
13
|
+
sortRootsBySpecificity,
|
|
14
|
+
walkProject,
|
|
15
|
+
} from "./project-roots.ts";
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Shared registry utility for SuPi extensions.
|
|
2
|
+
//
|
|
3
|
+
// Provides a globalThis-backed registry pattern so that all jiti module instances
|
|
4
|
+
// (resolved through different node_modules symlinks) share the same Map.
|
|
5
|
+
// Without this, each symlink path gets its own module copy and its own Map,
|
|
6
|
+
// so registrations from one instance are invisible to consumers in another.
|
|
7
|
+
|
|
8
|
+
import * as path from "node:path";
|
|
9
|
+
|
|
10
|
+
const SYMBOL_PREFIX = "@mrclrchtr/supi-core/";
|
|
11
|
+
|
|
12
|
+
function getGlobalRegistryMap<T>(name: string): Map<string, T> {
|
|
13
|
+
const key = Symbol.for(SYMBOL_PREFIX + name);
|
|
14
|
+
let map = (globalThis as Record<symbol, unknown>)[key] as Map<string, T> | undefined;
|
|
15
|
+
if (!map) {
|
|
16
|
+
map = new Map<string, T>();
|
|
17
|
+
(globalThis as Record<symbol, unknown>)[key] = map;
|
|
18
|
+
}
|
|
19
|
+
return map;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Create a named registry backed by `globalThis` + `Symbol.for`.
|
|
24
|
+
*
|
|
25
|
+
* The registry is lazily initialized on first access and shared across all
|
|
26
|
+
* jiti module instances via the global symbol namespace.
|
|
27
|
+
*
|
|
28
|
+
* @typeParam T - The value type stored in the registry.
|
|
29
|
+
* @param name - Unique registry name (used to construct the `Symbol.for` key).
|
|
30
|
+
* @returns An object with `register`, `unregister`, `getAll`, and `clear` functions.
|
|
31
|
+
*/
|
|
32
|
+
export function createRegistry<T>(name: string) {
|
|
33
|
+
const getMap = (): Map<string, T> => getGlobalRegistryMap<T>(name);
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
/**
|
|
37
|
+
* Register a value by id. Duplicate ids silently replace the previous registration.
|
|
38
|
+
*/
|
|
39
|
+
register: (id: string, value: T): void => {
|
|
40
|
+
getMap().set(id, value);
|
|
41
|
+
},
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Remove a registration by id. No-op if not registered.
|
|
45
|
+
*/
|
|
46
|
+
unregister: (id: string): void => {
|
|
47
|
+
getMap().delete(id);
|
|
48
|
+
},
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Get all registered values in registration order.
|
|
52
|
+
*/
|
|
53
|
+
getAll: (): T[] => {
|
|
54
|
+
return Array.from(getMap().values());
|
|
55
|
+
},
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Clear all entries from the registry (primarily for tests).
|
|
59
|
+
*/
|
|
60
|
+
clear: (): void => {
|
|
61
|
+
getMap().clear();
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Create a named session-state registry keyed by normalized cwd.
|
|
68
|
+
*
|
|
69
|
+
* This helper is intended for session-scoped runtime services that should be
|
|
70
|
+
* shared across duplicate jiti module instances while keeping package-specific
|
|
71
|
+
* state unions and convenience wrappers local to the calling package.
|
|
72
|
+
*/
|
|
73
|
+
export function createSessionStateRegistry<TState>(name: string) {
|
|
74
|
+
const getMap = (): Map<string, TState> => getGlobalRegistryMap<TState>(name);
|
|
75
|
+
const normalizeCwd = (cwd: string): string => path.resolve(cwd);
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
/** Get the current state for one session cwd. */
|
|
79
|
+
get: (cwd: string): TState | undefined => {
|
|
80
|
+
return getMap().get(normalizeCwd(cwd));
|
|
81
|
+
},
|
|
82
|
+
|
|
83
|
+
/** Store the current state for one session cwd. */
|
|
84
|
+
set: (cwd: string, state: TState): void => {
|
|
85
|
+
getMap().set(normalizeCwd(cwd), state);
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
/** Clear the current state for one session cwd. */
|
|
89
|
+
clear: (cwd: string): void => {
|
|
90
|
+
getMap().delete(normalizeCwd(cwd));
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|