@mrclrchtr/supi-tree-sitter 1.3.1 → 1.5.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 (37) hide show
  1. package/README.md +58 -39
  2. package/node_modules/@mrclrchtr/supi-core/README.md +107 -0
  3. package/node_modules/@mrclrchtr/supi-core/package.json +44 -0
  4. package/node_modules/@mrclrchtr/supi-core/src/api.ts +85 -0
  5. package/node_modules/@mrclrchtr/supi-core/src/config/config-settings.ts +76 -0
  6. package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +186 -0
  7. package/node_modules/@mrclrchtr/supi-core/src/context/context-messages.ts +119 -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/debug-registry.ts +255 -0
  11. package/node_modules/@mrclrchtr/supi-core/src/extension.ts +1 -0
  12. package/node_modules/@mrclrchtr/supi-core/src/index.ts +85 -0
  13. package/node_modules/@mrclrchtr/supi-core/src/path-utils.ts +40 -0
  14. package/node_modules/@mrclrchtr/supi-core/src/project-roots.ts +170 -0
  15. package/node_modules/@mrclrchtr/supi-core/src/registry-utils.ts +86 -0
  16. package/node_modules/@mrclrchtr/supi-core/src/session-utils.ts +29 -0
  17. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-command.ts +15 -0
  18. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +41 -0
  19. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-ui.ts +226 -0
  20. package/node_modules/@mrclrchtr/supi-core/src/terminal.ts +60 -0
  21. package/package.json +8 -3
  22. package/src/api.ts +6 -2
  23. package/src/index.ts +6 -2
  24. package/src/{runtime.ts → session/runtime.ts} +6 -5
  25. package/src/session/service-registry.ts +30 -0
  26. package/src/{session.ts → session/session.ts} +20 -12
  27. package/src/tool/action-specs.ts +92 -0
  28. package/src/{callees.ts → tool/callees.ts} +3 -3
  29. package/src/{exports.ts → tool/exports.ts} +4 -4
  30. package/src/{formatting.ts → tool/formatting.ts} +1 -1
  31. package/src/tool/guidance.ts +31 -0
  32. package/src/{imports.ts → tool/imports.ts} +4 -4
  33. package/src/{node-at.ts → tool/node-at.ts} +3 -3
  34. package/src/{outline.ts → tool/outline.ts} +3 -3
  35. package/src/tree-sitter.ts +118 -91
  36. package/src/types.ts +13 -2
  37. /package/src/{structure.ts → tool/structure.ts} +0 -0
@@ -0,0 +1,119 @@
1
+ // Shared context-message utilities for SuPi extensions.
2
+ //
3
+ // Provides a generic prune-and-reorder pattern for extensions that inject
4
+ // managed context messages (via `before_agent_start` with a `customType` and
5
+ // `contextToken`) and maintain them via the `context` event.
6
+
7
+ /**
8
+ * Minimal message shape needed for context-message operations.
9
+ * Extensions cast their event.messages entries to this type.
10
+ */
11
+ export type ContextMessageLike = {
12
+ role?: string;
13
+ customType?: string;
14
+ content?: unknown;
15
+ details?: unknown;
16
+ };
17
+
18
+ /**
19
+ * Extract the `contextToken` string from a message's `details` object.
20
+ * Returns `null` when the token is absent or not a string.
21
+ */
22
+ export function getContextToken(details: unknown): string | null {
23
+ if (!details || typeof details !== "object") return null;
24
+ const token = (details as { contextToken?: unknown }).contextToken;
25
+ return typeof token === "string" ? token : null;
26
+ }
27
+
28
+ /**
29
+ * Find the index of the last message with `role: "user"`.
30
+ * Returns `-1` when no user message exists.
31
+ */
32
+ export function findLastUserMessageIndex<T extends ContextMessageLike>(messages: T[]): number {
33
+ for (let index = messages.length - 1; index >= 0; index--) {
34
+ if (messages[index]?.role === "user") return index;
35
+ }
36
+ return -1;
37
+ }
38
+
39
+ /**
40
+ * Filter stale context messages and reorder the active one before the last user message.
41
+ *
42
+ * - Removes all messages matching `customType` whose token differs from `activeToken`.
43
+ * - When `activeToken` is `null`, removes **all** messages of that `customType`.
44
+ * - If the active context message is after the last user message, moves it before.
45
+ *
46
+ * Returns the modified array, or the original reference when no changes were needed.
47
+ */
48
+ export function pruneAndReorderContextMessages<T extends ContextMessageLike>(
49
+ messages: T[],
50
+ customType: string,
51
+ activeToken: string | null,
52
+ ): T[] {
53
+ // Remove stale messages of the target customType
54
+ const filtered = messages.filter((message) => {
55
+ if (message.customType !== customType) return true;
56
+ if (!activeToken) return false;
57
+ return getContextToken(message.details) === activeToken;
58
+ });
59
+
60
+ if (!activeToken) return filtered;
61
+
62
+ // Find the active context message
63
+ const contextIndex = filtered.findIndex(
64
+ (message) =>
65
+ message.customType === customType && getContextToken(message.details) === activeToken,
66
+ );
67
+ if (contextIndex === -1) return filtered;
68
+
69
+ // Find the last user message
70
+ const userIndex = findLastUserMessageIndex(filtered);
71
+ if (userIndex === -1 || contextIndex < userIndex) return filtered;
72
+
73
+ // Move context message before last user message
74
+ const next = [...filtered];
75
+ const [contextMessage] = next.splice(contextIndex, 1);
76
+ if (!contextMessage) return filtered;
77
+ next.splice(userIndex, 0, contextMessage);
78
+ return next;
79
+ }
80
+
81
+ /**
82
+ * Restore the raw prompt content on a context message that was swapped for display text.
83
+ *
84
+ * Extensions using `registerMessageRenderer` store their LLM-facing content in
85
+ * `details.promptContent` and put a human-readable summary in `content`. This function
86
+ * reverses the swap so the model sees the original prompt content.
87
+ *
88
+ * Returns the original array reference when no change is needed.
89
+ */
90
+ export function restorePromptContent<T extends ContextMessageLike>(
91
+ messages: T[],
92
+ customType: string,
93
+ activeToken: string | null,
94
+ ): T[] {
95
+ if (!activeToken) return messages;
96
+
97
+ const index = messages.findIndex(
98
+ (message) =>
99
+ message.customType === customType && getContextToken(message.details) === activeToken,
100
+ );
101
+ if (index === -1) return messages;
102
+
103
+ const promptContent = getPromptContent(messages[index]?.details);
104
+ if (!promptContent || messages[index]?.content === promptContent) return messages;
105
+
106
+ const next = [...messages];
107
+ next[index] = { ...next[index], content: promptContent };
108
+ return next;
109
+ }
110
+
111
+ /**
112
+ * Extract the `promptContent` string from a message's `details` object.
113
+ * Returns `null` when absent or not a string.
114
+ */
115
+ export function getPromptContent(details: unknown): string | null {
116
+ if (!details || typeof details !== "object") return null;
117
+ const promptContent = (details as { promptContent?: unknown }).promptContent;
118
+ return typeof promptContent === "string" ? promptContent : null;
119
+ }
@@ -0,0 +1,36 @@
1
+ // Context provider registry for SuPi extensions.
2
+ //
3
+ // Extensions declare context data providers via `registerContextProvider()` during their
4
+ // factory function. The `/supi-context` command reads them via `getRegisteredContextProviders()`.
5
+
6
+ import { createRegistry } from "../registry-utils.ts";
7
+
8
+ export interface ContextProvider {
9
+ /** Unique identifier — e.g. "rtk" */
10
+ id: string;
11
+ /** Human-readable label shown in the report */
12
+ label: string;
13
+ /** Return structured data for display, or null when unavailable. */
14
+ getData: () => Record<string, string | number> | null;
15
+ }
16
+
17
+ const registry = createRegistry<ContextProvider>("context-provider-registry");
18
+
19
+ /**
20
+ * Register a context data provider for an extension.
21
+ * Call during the extension factory function (not async handlers).
22
+ * Duplicate ids replace the previous registration.
23
+ */
24
+ export function registerContextProvider(provider: ContextProvider): void {
25
+ registry.register(provider.id, provider);
26
+ }
27
+
28
+ /** Get all registered context providers in registration order. */
29
+ export function getRegisteredContextProviders(): ContextProvider[] {
30
+ return registry.getAll();
31
+ }
32
+
33
+ /** Clear the registry — used by tests. */
34
+ export function clearRegisteredContextProviders(): void {
35
+ registry.clear();
36
+ }
@@ -0,0 +1,31 @@
1
+ // XML context tag wrapping for SuPi extensions.
2
+ //
3
+ // Produces machine-parseable <extension-context> blocks that:
4
+ // - Are LLM-friendly (structured XML)
5
+ // - Carry metadata via attributes (source, file, turn, etc.)
6
+ // - Can be reconstructed from session history via regex
7
+
8
+ /**
9
+ * Wrap content in an `<extension-context>` XML tag.
10
+ *
11
+ * @param source - Extension identifier (e.g. "supi-claude-md", "supi-lsp")
12
+ * @param content - The text content to wrap
13
+ * @param attrs - Optional additional attributes (rendered as key="value")
14
+ * @returns Formatted XML string
15
+ */
16
+ export function wrapExtensionContext(
17
+ source: string,
18
+ content: string,
19
+ attrs?: Record<string, string | number>,
20
+ ): string {
21
+ const attrParts = [`source="${source}"`];
22
+
23
+ if (attrs) {
24
+ for (const [key, value] of Object.entries(attrs)) {
25
+ attrParts.push(`${key}="${String(value)}"`);
26
+ }
27
+ }
28
+
29
+ const openTag = `<extension-context ${attrParts.join(" ")}>`;
30
+ return `${openTag}\n${content}\n</extension-context>`;
31
+ }
@@ -0,0 +1,255 @@
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 type DebugNotifyLevel = "off" | "warning" | "error";
10
+
11
+ export interface DebugRegistryConfig {
12
+ /** Whether producers should retain debug events. */
13
+ enabled: boolean;
14
+ /** What the agent-callable debug tool may return. */
15
+ agentAccess: DebugAgentAccess;
16
+ /** Maximum number of session-local events to keep in memory. */
17
+ maxEvents: number;
18
+ /** Minimum level that should notify the user; interpreted by UI extensions. */
19
+ notifyLevel: DebugNotifyLevel;
20
+ }
21
+
22
+ export const DEBUG_REGISTRY_DEFAULTS: DebugRegistryConfig = {
23
+ enabled: false,
24
+ agentAccess: "sanitized",
25
+ maxEvents: 100,
26
+ notifyLevel: "off",
27
+ };
28
+
29
+ export interface DebugEventInput {
30
+ source: string;
31
+ level: DebugLevel;
32
+ category: string;
33
+ message: string;
34
+ cwd?: string;
35
+ data?: unknown;
36
+ rawData?: unknown;
37
+ }
38
+
39
+ export interface DebugEvent extends DebugEventInput {
40
+ id: number;
41
+ timestamp: number;
42
+ data?: unknown;
43
+ rawData?: unknown;
44
+ }
45
+
46
+ export interface DebugEventQuery {
47
+ source?: string;
48
+ level?: DebugLevel;
49
+ category?: string;
50
+ limit?: number;
51
+ includeRaw?: boolean;
52
+ allowRaw?: boolean;
53
+ }
54
+
55
+ export interface DebugEventView {
56
+ id: number;
57
+ timestamp: number;
58
+ source: string;
59
+ level: DebugLevel;
60
+ category: string;
61
+ message: string;
62
+ cwd?: string;
63
+ data?: unknown;
64
+ rawData?: unknown;
65
+ }
66
+
67
+ export interface DebugEventQueryResult {
68
+ events: DebugEventView[];
69
+ rawAccessDenied: boolean;
70
+ }
71
+
72
+ export interface DebugSummary {
73
+ total: number;
74
+ byLevel: Partial<Record<DebugLevel, number>>;
75
+ bySource: Record<string, number>;
76
+ }
77
+
78
+ interface DebugRegistryState {
79
+ config: DebugRegistryConfig;
80
+ events: DebugEvent[];
81
+ nextId: number;
82
+ }
83
+
84
+ const REGISTRY_KEY = Symbol.for("@mrclrchtr/supi-core/debug-registry");
85
+ const SECRET_KEY_RE = /(?:token|password|passwd|secret|api[_-]?key|authorization|credential)/i;
86
+ const ENV_SECRET_RE =
87
+ /\b([A-Za-z0-9_]*(?:token|password|passwd|secret|api[_-]?key|authorization|credential)[A-Za-z0-9_]*)=(?:'[^']*'|"[^"]*"|\S+)/gi;
88
+ const AUTH_HEADER_RE = /\b(authorization\s*[:=]\s*)(?:bearer\s+)?[^\s;&|]+/gi;
89
+ const URL_SECRET_RE =
90
+ /([?&](?:token|password|passwd|secret|api[_-]?key|authorization|credential)=)[^&\s]+/gi;
91
+ const REDACTED = "[REDACTED]";
92
+
93
+ function cloneConfig(config: DebugRegistryConfig): DebugRegistryConfig {
94
+ return { ...config };
95
+ }
96
+
97
+ function getState(): DebugRegistryState {
98
+ let state = (globalThis as Record<symbol, unknown>)[REGISTRY_KEY] as
99
+ | DebugRegistryState
100
+ | undefined;
101
+ if (!state) {
102
+ state = {
103
+ config: cloneConfig(DEBUG_REGISTRY_DEFAULTS),
104
+ events: [],
105
+ nextId: 1,
106
+ };
107
+ (globalThis as Record<symbol, unknown>)[REGISTRY_KEY] = state;
108
+ }
109
+ return state;
110
+ }
111
+
112
+ function normalizeMaxEvents(value: number): number {
113
+ if (!Number.isFinite(value) || value <= 0) {
114
+ return DEBUG_REGISTRY_DEFAULTS.maxEvents;
115
+ }
116
+ return Math.floor(value);
117
+ }
118
+
119
+ function trimToMaxEvents(state: DebugRegistryState): void {
120
+ const maxEvents = normalizeMaxEvents(state.config.maxEvents);
121
+ if (state.events.length <= maxEvents) {
122
+ return;
123
+ }
124
+ state.events.splice(0, state.events.length - maxEvents);
125
+ }
126
+
127
+ function matchesQuery(event: DebugEvent, query: DebugEventQuery): boolean {
128
+ if (query.source && event.source !== query.source) return false;
129
+ if (query.level && event.level !== query.level) return false;
130
+ if (query.category && event.category !== query.category) return false;
131
+ return true;
132
+ }
133
+
134
+ function sanitizeString(value: string): string {
135
+ return value
136
+ .replace(ENV_SECRET_RE, (_match, key: string) => `${key}=${REDACTED}`)
137
+ .replace(AUTH_HEADER_RE, (_match, prefix: string) => `${prefix}${REDACTED}`)
138
+ .replace(URL_SECRET_RE, (_match, prefix: string) => `${prefix}${REDACTED}`);
139
+ }
140
+
141
+ function redactValue(value: unknown, depth: number): unknown {
142
+ if (depth <= 0) return "[MaxDepth]";
143
+ if (typeof value === "string") return sanitizeString(value);
144
+ if (typeof value !== "object" || value === null) return value;
145
+ if (Array.isArray(value)) return value.map((item) => redactValue(item, depth - 1));
146
+
147
+ const redacted: Record<string, unknown> = {};
148
+ for (const [key, item] of Object.entries(value)) {
149
+ redacted[key] = SECRET_KEY_RE.test(key) ? REDACTED : redactValue(item, depth - 1);
150
+ }
151
+ return redacted;
152
+ }
153
+
154
+ /** Configure the shared debug registry. Existing events are trimmed to the new max size. */
155
+ export function configureDebugRegistry(config: Partial<DebugRegistryConfig>): DebugRegistryConfig {
156
+ const state = getState();
157
+ state.config = {
158
+ ...state.config,
159
+ ...config,
160
+ maxEvents: normalizeMaxEvents(config.maxEvents ?? state.config.maxEvents),
161
+ };
162
+ trimToMaxEvents(state);
163
+ return getDebugRegistryConfig();
164
+ }
165
+
166
+ /** Return the active debug registry configuration. */
167
+ export function getDebugRegistryConfig(): DebugRegistryConfig {
168
+ return cloneConfig(getState().config);
169
+ }
170
+
171
+ /** Best-effort redaction helper for data exposed through sanitized debug views. */
172
+ export function redactDebugData<T>(value: T): T {
173
+ return redactValue(value, 8) as T;
174
+ }
175
+
176
+ /** Record a session-local debug event if debugging is enabled. */
177
+ export function recordDebugEvent(input: DebugEventInput): DebugEvent | null {
178
+ const state = getState();
179
+ if (!state.config.enabled) {
180
+ return null;
181
+ }
182
+
183
+ const event: DebugEvent = {
184
+ ...input,
185
+ id: state.nextId++,
186
+ timestamp: Date.now(),
187
+ data: input.data === undefined ? undefined : redactDebugData(input.data),
188
+ };
189
+ state.events.push(event);
190
+ trimToMaxEvents(state);
191
+ return { ...event };
192
+ }
193
+
194
+ /** Query retained debug events newest-first. Results are sanitized unless raw access is requested and allowed. */
195
+ export function getDebugEvents(query: DebugEventQuery = {}): DebugEventQueryResult {
196
+ const state = getState();
197
+ const allowRaw = Boolean(
198
+ query.includeRaw && query.allowRaw && state.config.agentAccess === "raw",
199
+ );
200
+ const rawAccessDenied = Boolean(query.includeRaw && !allowRaw);
201
+ const limit = query.limit && query.limit > 0 ? Math.floor(query.limit) : state.config.maxEvents;
202
+
203
+ const events = state.events
204
+ .filter((event) => matchesQuery(event, query))
205
+ .slice()
206
+ .reverse()
207
+ .slice(0, limit)
208
+ .map((event): DebugEventView => {
209
+ const view: DebugEventView = {
210
+ id: event.id,
211
+ timestamp: event.timestamp,
212
+ source: event.source,
213
+ level: event.level,
214
+ category: event.category,
215
+ message: event.message,
216
+ cwd: event.cwd,
217
+ data: event.data,
218
+ };
219
+ if (allowRaw && event.rawData !== undefined) {
220
+ view.rawData = event.rawData;
221
+ }
222
+ return view;
223
+ });
224
+
225
+ return { events, rawAccessDenied };
226
+ }
227
+
228
+ /** Return aggregate debug counts suitable for summary displays. */
229
+ export function getDebugSummary(): DebugSummary | null {
230
+ const events = getState().events;
231
+ if (events.length === 0) {
232
+ return null;
233
+ }
234
+
235
+ const summary: DebugSummary = { total: events.length, byLevel: {}, bySource: {} };
236
+ for (const event of events) {
237
+ summary.byLevel[event.level] = (summary.byLevel[event.level] ?? 0) + 1;
238
+ summary.bySource[event.source] = (summary.bySource[event.source] ?? 0) + 1;
239
+ }
240
+ return summary;
241
+ }
242
+
243
+ /** Clear retained events while preserving configuration. */
244
+ export function clearDebugEvents(): void {
245
+ const state = getState();
246
+ state.events = [];
247
+ }
248
+
249
+ /** Reset the debug registry to defaults; intended for tests. */
250
+ export function resetDebugRegistry(): void {
251
+ const state = getState();
252
+ state.config = cloneConfig(DEBUG_REGISTRY_DEFAULTS);
253
+ state.events = [];
254
+ state.nextId = 1;
255
+ }
@@ -0,0 +1 @@
1
+ export { registerSettingsCommand as default } from "./settings/settings-command.ts";
@@ -0,0 +1,85 @@
1
+ // supi-core — shared infrastructure for SuPi extensions.
2
+ // Provides XML context tag wrapping, unified config system, context-message utilities,
3
+ // and settings registry for supi-wide TUI settings.
4
+
5
+ export type { SupiConfigLocation, SupiConfigOptions } from "./config/config.ts";
6
+ export {
7
+ loadSupiConfig,
8
+ loadSupiConfigForScope,
9
+ removeSupiConfigKey,
10
+ writeSupiConfig,
11
+ } from "./config/config.ts";
12
+ export type { ConfigSettingsHelpers, ConfigSettingsOptions } from "./config/config-settings.ts";
13
+ export { registerConfigSettings } from "./config/config-settings.ts";
14
+ export type { ContextMessageLike } from "./context/context-messages.ts";
15
+ export {
16
+ findLastUserMessageIndex,
17
+ getContextToken,
18
+ getPromptContent,
19
+ pruneAndReorderContextMessages,
20
+ restorePromptContent,
21
+ } from "./context/context-messages.ts";
22
+ export type { ContextProvider } from "./context/context-provider-registry.ts";
23
+ export {
24
+ clearRegisteredContextProviders,
25
+ getRegisteredContextProviders,
26
+ registerContextProvider,
27
+ } from "./context/context-provider-registry.ts";
28
+ export { wrapExtensionContext } from "./context/context-tag.ts";
29
+ export type {
30
+ DebugAgentAccess,
31
+ DebugEvent,
32
+ DebugEventInput,
33
+ DebugEventQuery,
34
+ DebugEventQueryResult,
35
+ DebugEventView,
36
+ DebugLevel,
37
+ DebugNotifyLevel,
38
+ DebugRegistryConfig,
39
+ DebugSummary,
40
+ } from "./debug-registry.ts";
41
+ export {
42
+ clearDebugEvents,
43
+ configureDebugRegistry,
44
+ DEBUG_REGISTRY_DEFAULTS,
45
+ getDebugEvents,
46
+ getDebugRegistryConfig,
47
+ getDebugSummary,
48
+ recordDebugEvent,
49
+ redactDebugData,
50
+ resetDebugRegistry,
51
+ } from "./debug-registry.ts";
52
+ export { fileToUri, resolveToolPath, stripToolPathPrefix, uriToFile } from "./path-utils.ts";
53
+ export type { KnownRootEntry } from "./project-roots.ts";
54
+ export {
55
+ buildKnownRootsMap,
56
+ byPathDepth,
57
+ dedupeTopmostRoots,
58
+ findProjectRoot,
59
+ isWithin,
60
+ isWithinOrEqual,
61
+ mergeKnownRoots,
62
+ resolveKnownRoot,
63
+ segmentCount,
64
+ sortRootsBySpecificity,
65
+ walkProject,
66
+ } from "./project-roots.ts";
67
+ export { createRegistry, createSessionStateRegistry } from "./registry-utils.ts";
68
+ export { getActiveBranchEntries } from "./session-utils.ts";
69
+ export { registerSettingsCommand } from "./settings/settings-command.ts";
70
+ export type { SettingsScope, SettingsSection } from "./settings/settings-registry.ts";
71
+ export {
72
+ clearRegisteredSettings,
73
+ getRegisteredSettings,
74
+ registerSettings,
75
+ } from "./settings/settings-registry.ts";
76
+ export { createInputSubmenu, openSettingsOverlay } from "./settings/settings-ui.ts";
77
+ export type { TitleTarget } from "./terminal.ts";
78
+ export {
79
+ DONE_SYMBOL,
80
+ formatTitle,
81
+ signalBell,
82
+ signalDone,
83
+ signalWaiting,
84
+ WAITING_SYMBOL,
85
+ } from "./terminal.ts";
@@ -0,0 +1,40 @@
1
+ import * as path from "node:path";
2
+
3
+ /** Strip pi's optional leading `@` file-path prefix from a tool input. */
4
+ export function stripToolPathPrefix(target: string): string {
5
+ return target.startsWith("@") ? target.slice(1) : target;
6
+ }
7
+
8
+ /**
9
+ * Resolve a tool-style file path from a session cwd.
10
+ *
11
+ * Built-in pi file tools accept a leading `@` prefix in path arguments, so
12
+ * shared SuPi path helpers normalize that prefix before resolving relative
13
+ * paths.
14
+ */
15
+ export function resolveToolPath(cwd: string, target: string): string {
16
+ return path.resolve(cwd, stripToolPathPrefix(target));
17
+ }
18
+
19
+ /** Convert a file path to a file:// URI. */
20
+ export function fileToUri(filePath: string): string {
21
+ const resolved = path.resolve(filePath);
22
+ if (process.platform === "win32") {
23
+ return `file:///${resolved.replace(/\\/g, "/")}`;
24
+ }
25
+ return `file://${resolved}`;
26
+ }
27
+
28
+ /** Convert a file:// URI to a file path. */
29
+ export function uriToFile(uri: string): string {
30
+ if (!uri.startsWith("file://")) return uri;
31
+ let filePath = decodeURIComponent(uri.slice(7));
32
+ if (
33
+ process.platform === "win32" &&
34
+ filePath.startsWith("/") &&
35
+ /^[A-Za-z]:/.test(filePath.slice(1))
36
+ ) {
37
+ filePath = filePath.slice(1);
38
+ }
39
+ return filePath;
40
+ }