@mrclrchtr/supi-consulting 0.0.0-stage → 9.0.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 (78) hide show
  1. package/CLAUDE.md +23 -0
  2. package/CONTEXT.md +53 -0
  3. package/README.md +104 -2
  4. package/docs/adr/0001-use-an-isolated-antigravity-home.md +5 -0
  5. package/node_modules/@mrclrchtr/supi-core/README.md +137 -0
  6. package/node_modules/@mrclrchtr/supi-core/package.json +73 -0
  7. package/node_modules/@mrclrchtr/supi-core/src/api.ts +42 -0
  8. package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +342 -0
  9. package/node_modules/@mrclrchtr/supi-core/src/config/prompt-surface.ts +363 -0
  10. package/node_modules/@mrclrchtr/supi-core/src/config.ts +17 -0
  11. package/node_modules/@mrclrchtr/supi-core/src/context/context-provider-registry.ts +36 -0
  12. package/node_modules/@mrclrchtr/supi-core/src/context/context-tag.ts +31 -0
  13. package/node_modules/@mrclrchtr/supi-core/src/context.ts +8 -0
  14. package/node_modules/@mrclrchtr/supi-core/src/debug-identity.ts +11 -0
  15. package/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +313 -0
  16. package/node_modules/@mrclrchtr/supi-core/src/debug-timing.ts +120 -0
  17. package/node_modules/@mrclrchtr/supi-core/src/debug.ts +14 -0
  18. package/node_modules/@mrclrchtr/supi-core/src/evidence-badge.ts +41 -0
  19. package/node_modules/@mrclrchtr/supi-core/src/footer-registry.ts +64 -0
  20. package/node_modules/@mrclrchtr/supi-core/src/index.ts +38 -0
  21. package/node_modules/@mrclrchtr/supi-core/src/llm.ts +356 -0
  22. package/node_modules/@mrclrchtr/supi-core/src/model-selection.ts +134 -0
  23. package/node_modules/@mrclrchtr/supi-core/src/path-utils.ts +44 -0
  24. package/node_modules/@mrclrchtr/supi-core/src/path.ts +2 -0
  25. package/node_modules/@mrclrchtr/supi-core/src/project-roots.ts +170 -0
  26. package/node_modules/@mrclrchtr/supi-core/src/project.ts +15 -0
  27. package/node_modules/@mrclrchtr/supi-core/src/prompt-surface.ts +4 -0
  28. package/node_modules/@mrclrchtr/supi-core/src/registry-utils.ts +93 -0
  29. package/node_modules/@mrclrchtr/supi-core/src/report.ts +121 -0
  30. package/node_modules/@mrclrchtr/supi-core/src/session-capabilities.ts +242 -0
  31. package/node_modules/@mrclrchtr/supi-core/src/session-capability-profiles.ts +240 -0
  32. package/node_modules/@mrclrchtr/supi-core/src/session-utils.ts +71 -0
  33. package/node_modules/@mrclrchtr/supi-core/src/session.ts +47 -0
  34. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +105 -0
  35. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +454 -0
  36. package/node_modules/@mrclrchtr/supi-core/src/settings.ts +36 -0
  37. package/node_modules/@mrclrchtr/supi-core/src/spinner-frames.ts +11 -0
  38. package/node_modules/@mrclrchtr/supi-core/src/status-spinner.ts +68 -0
  39. package/node_modules/@mrclrchtr/supi-core/src/terminal.ts +60 -0
  40. package/node_modules/@mrclrchtr/supi-core/src/tui.ts +141 -0
  41. package/package.json +73 -4
  42. package/scripts/live-probe.ts +139 -0
  43. package/src/agents/antigravity/activity.ts +22 -0
  44. package/src/agents/antigravity/adapter.ts +196 -0
  45. package/src/agents/antigravity/availability.ts +231 -0
  46. package/src/agents/antigravity/isolated-home.ts +346 -0
  47. package/src/agents/antigravity/models.ts +15 -0
  48. package/src/agents/antigravity/process/environment.ts +33 -0
  49. package/src/agents/antigravity/process/event-values.ts +273 -0
  50. package/src/agents/antigravity/process/events.ts +366 -0
  51. package/src/agents/antigravity/process/hooks.ts +219 -0
  52. package/src/agents/antigravity/process/ndjson.ts +120 -0
  53. package/src/agents/antigravity/process/protocol.ts +69 -0
  54. package/src/agents/antigravity/process/runner.ts +147 -0
  55. package/src/agents/antigravity/process/subprocess.ts +278 -0
  56. package/src/agents/antigravity/process/usage.ts +50 -0
  57. package/src/agents/antigravity/structured-output.ts +58 -0
  58. package/src/agents/antigravity/types.ts +17 -0
  59. package/src/agents/errors.ts +27 -0
  60. package/src/agents/types.ts +43 -0
  61. package/src/catalogue.ts +17 -0
  62. package/src/config.ts +26 -0
  63. package/src/conversation/handles.ts +187 -0
  64. package/src/evidence-hash.ts +6 -0
  65. package/src/extension.ts +26 -0
  66. package/src/footer-constants.ts +5 -0
  67. package/src/footer.ts +25 -0
  68. package/src/runtime.ts +244 -0
  69. package/src/settings.ts +38 -0
  70. package/src/tool/consulting_run/evidence.ts +169 -0
  71. package/src/tool/consulting_run/execute.ts +201 -0
  72. package/src/tool/consulting_run/guidance.ts +3 -0
  73. package/src/tool/consulting_run/input.ts +117 -0
  74. package/src/tool/consulting_run/register.ts +36 -0
  75. package/src/tool/consulting_run/render.ts +261 -0
  76. package/src/tool/consulting_run/result.ts +185 -0
  77. package/src/tool/consulting_run/spec.ts +20 -0
  78. package/src/types.ts +104 -0
@@ -0,0 +1,342 @@
1
+ // Shared config system for SuPi extensions.
2
+ //
3
+ // Global config: ~/.pi/agent/supi/config.json
4
+ // Project config: .pi/supi/config.json (relative to cwd)
5
+ // Resolution: hardcoded defaults ← global ← project
6
+
7
+ import * as fs from "node:fs";
8
+ import * as os from "node:os";
9
+ import * as path from "node:path";
10
+ import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent";
11
+
12
+ const GLOBAL_CONFIG_DIR = `${CONFIG_DIR_NAME}/agent/supi`;
13
+ const PROJECT_CONFIG_DIR = `${CONFIG_DIR_NAME}/supi`;
14
+ const CONFIG_FILE = "config.json";
15
+
16
+ function getGlobalConfigPath(homeDir?: string): string {
17
+ return path.join(homeDir ?? os.homedir(), GLOBAL_CONFIG_DIR, CONFIG_FILE);
18
+ }
19
+
20
+ function getProjectConfigPath(cwd: string): string {
21
+ return path.join(cwd, PROJECT_CONFIG_DIR, CONFIG_FILE);
22
+ }
23
+
24
+ /** Return the SuPi config file path for one scope. */
25
+ export function getSupiConfigPath(
26
+ scope: "global" | "project",
27
+ cwd: string,
28
+ options?: SupiConfigOptions,
29
+ ): string {
30
+ return scope === "global" ? getGlobalConfigPath(options?.homeDir) : getProjectConfigPath(cwd);
31
+ }
32
+
33
+ export function readJsonFile(filePath: string): Record<string, unknown> | null {
34
+ let content: string;
35
+ try {
36
+ content = fs.readFileSync(filePath, "utf-8");
37
+ } catch {
38
+ // ENOENT or permission error — silent, file may not exist
39
+ return null;
40
+ }
41
+
42
+ let parsed: unknown;
43
+ try {
44
+ parsed = JSON.parse(content);
45
+ } catch {
46
+ // biome-ignore lint/suspicious/noConsole: deliberate config parse warning
47
+ console.warn(`[supi-core] Failed to parse config file, ignoring: ${filePath}`);
48
+ return null;
49
+ }
50
+
51
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
52
+ return parsed as Record<string, unknown>;
53
+ }
54
+
55
+ // biome-ignore lint/suspicious/noConsole: deliberate config parse warning
56
+ console.warn(`[supi-core] Config file root is not an object, ignoring: ${filePath}`);
57
+ return null;
58
+ }
59
+
60
+ function shallowMerge<T>(base: T, ...overrides: Array<Record<string, unknown> | null>): T {
61
+ let result = { ...base };
62
+ for (const override of overrides) {
63
+ if (!override) continue;
64
+ result = { ...result, ...override };
65
+ }
66
+ return result;
67
+ }
68
+
69
+ export interface SupiConfigOptions {
70
+ homeDir?: string;
71
+ }
72
+
73
+ /** Options for loading automatic code-intelligence exclusions. */
74
+ export interface AutomaticExclusionOptions extends SupiConfigOptions {
75
+ /** Whether the project config is trusted and can apply. Defaults to true. */
76
+ projectTrusted?: boolean;
77
+ }
78
+
79
+ /**
80
+ * Load the one configured exclusion list shared by automatic LSP work and
81
+ * broad AST searches.
82
+ *
83
+ * Project values replace global values. An explicit empty project list clears
84
+ * the global list. The old `lsp.exclude` key is rejected in every applicable
85
+ * scope so automatic work cannot start without its former protection.
86
+ */
87
+ export function loadAutomaticExclusionPatterns(
88
+ cwd: string,
89
+ options: AutomaticExclusionOptions = {},
90
+ ): readonly string[] {
91
+ const projectTrusted = options.projectTrusted !== false;
92
+ const globalCodeIntelligence = loadSupiConfigSectionForScope("code-intelligence", cwd, {
93
+ scope: "global",
94
+ homeDir: options.homeDir,
95
+ });
96
+ const projectCodeIntelligence = projectTrusted
97
+ ? loadSupiConfigSectionForScope("code-intelligence", cwd, { scope: "project" })
98
+ : null;
99
+ const globalLsp = loadSupiConfigSectionForScope("lsp", cwd, {
100
+ scope: "global",
101
+ homeDir: options.homeDir,
102
+ });
103
+ const projectLsp = projectTrusted
104
+ ? loadSupiConfigSectionForScope("lsp", cwd, { scope: "project" })
105
+ : null;
106
+
107
+ const legacyPath = findLegacyExclusionPath(cwd, options, globalLsp, projectLsp);
108
+ if (legacyPath) {
109
+ throw new Error(
110
+ `Unsupported ${legacyPath.scope} configuration at ${legacyPath.path}: "lsp.exclude" was removed. Move its value to "code-intelligence.exclude". Automatic LSP and broad AST work did not start; reload after migration.`,
111
+ );
112
+ }
113
+
114
+ const source = findExclusionSource(cwd, options, {
115
+ projectTrusted,
116
+ globalCodeIntelligence,
117
+ projectCodeIntelligence,
118
+ });
119
+ return validateExclusionSource(source);
120
+ }
121
+
122
+ interface ExclusionSource {
123
+ value: unknown;
124
+ path: string;
125
+ }
126
+
127
+ interface LegacyExclusionPath {
128
+ scope: "global" | "project";
129
+ path: string;
130
+ }
131
+
132
+ function findLegacyExclusionPath(
133
+ cwd: string,
134
+ options: AutomaticExclusionOptions,
135
+ globalLsp: Record<string, unknown> | null,
136
+ projectLsp: Record<string, unknown> | null,
137
+ ): LegacyExclusionPath | null {
138
+ if (globalLsp && Object.hasOwn(globalLsp, "exclude")) {
139
+ return { scope: "global", path: getSupiConfigPath("global", cwd, options) };
140
+ }
141
+ if (projectLsp && Object.hasOwn(projectLsp, "exclude")) {
142
+ return { scope: "project", path: getSupiConfigPath("project", cwd) };
143
+ }
144
+ return null;
145
+ }
146
+
147
+ function findExclusionSource(
148
+ cwd: string,
149
+ options: AutomaticExclusionOptions,
150
+ sections: {
151
+ projectTrusted: boolean;
152
+ globalCodeIntelligence: Record<string, unknown> | null;
153
+ projectCodeIntelligence: Record<string, unknown> | null;
154
+ },
155
+ ): ExclusionSource | null {
156
+ const { projectTrusted, globalCodeIntelligence, projectCodeIntelligence } = sections;
157
+ if (
158
+ projectTrusted &&
159
+ projectCodeIntelligence &&
160
+ Object.hasOwn(projectCodeIntelligence, "exclude")
161
+ ) {
162
+ return { value: projectCodeIntelligence.exclude, path: getSupiConfigPath("project", cwd) };
163
+ }
164
+ if (globalCodeIntelligence && Object.hasOwn(globalCodeIntelligence, "exclude")) {
165
+ return {
166
+ value: globalCodeIntelligence.exclude,
167
+ path: getSupiConfigPath("global", cwd, options),
168
+ };
169
+ }
170
+ return null;
171
+ }
172
+
173
+ function validateExclusionSource(source: ExclusionSource | null): readonly string[] {
174
+ if (!source) return Object.freeze([]);
175
+ if (!Array.isArray(source.value) || !source.value.every((entry) => typeof entry === "string")) {
176
+ throw new Error(
177
+ `Invalid "code-intelligence.exclude" in ${source.path}: expected an array of gitignore-style strings. Automatic LSP and broad AST work did not start.`,
178
+ );
179
+ }
180
+ return Object.freeze([...source.value]);
181
+ }
182
+
183
+ /**
184
+ * Load and merge config for a given extension section.
185
+ *
186
+ * Resolution order: defaults ← global ← project
187
+ */
188
+ export function loadSupiConfig<T>(
189
+ section: string,
190
+ cwd: string,
191
+ defaults: T,
192
+ options?: SupiConfigOptions,
193
+ ): T {
194
+ const globalConfig = readJsonFile(getGlobalConfigPath(options?.homeDir));
195
+ const projectConfig = readJsonFile(getProjectConfigPath(cwd));
196
+
197
+ const globalSection = extractSection(globalConfig, section);
198
+ const projectSection = extractSection(projectConfig, section);
199
+
200
+ return shallowMerge(defaults, globalSection, projectSection);
201
+ }
202
+
203
+ /**
204
+ * Load config for a single scope only.
205
+ *
206
+ * Resolution order: defaults ← selected scope
207
+ *
208
+ * This is useful for settings UIs that need to show the raw values stored in
209
+ * one scope, rather than the effective merged config.
210
+ */
211
+ export function loadSupiConfigForScope<T>(
212
+ section: string,
213
+ cwd: string,
214
+ defaults: T,
215
+ options: { scope: "global" | "project" } & SupiConfigOptions,
216
+ ): T {
217
+ const config = readJsonFile(getSupiConfigPath(options.scope, cwd, { homeDir: options.homeDir }));
218
+
219
+ const scopedSection = extractSection(config, section);
220
+ return shallowMerge(defaults, scopedSection);
221
+ }
222
+
223
+ /** Load the raw object for one config section and one scope. */
224
+ export function loadSupiConfigSectionForScope(
225
+ section: string,
226
+ cwd: string,
227
+ options: { scope: "global" | "project" } & SupiConfigOptions,
228
+ ): Record<string, unknown> | null {
229
+ const config = readJsonFile(getSupiConfigPath(options.scope, cwd, { homeDir: options.homeDir }));
230
+ return extractSection(config, section);
231
+ }
232
+
233
+ export interface SupiConfigLocation {
234
+ section: string;
235
+ scope: "global" | "project";
236
+ cwd: string;
237
+ }
238
+
239
+ /**
240
+ * Write config values for a given extension section.
241
+ */
242
+ export function writeSupiConfig(
243
+ loc: SupiConfigLocation,
244
+ value: Record<string, unknown>,
245
+ options?: SupiConfigOptions,
246
+ ): void {
247
+ const configPath = getSupiConfigPath(loc.scope, loc.cwd, options);
248
+
249
+ const dir = path.dirname(configPath);
250
+ fs.mkdirSync(dir, { recursive: true });
251
+
252
+ const existing = readJsonFile(configPath) ?? {};
253
+ existing[loc.section] = {
254
+ ...((existing[loc.section] as Record<string, unknown>) ?? {}),
255
+ ...value,
256
+ };
257
+
258
+ fs.writeFileSync(configPath, `${JSON.stringify(existing, null, 2)}\n`, "utf-8");
259
+ }
260
+
261
+ /**
262
+ * Replace one complete config section while preserving other sections.
263
+ *
264
+ * This is useful for nested settings that must remove stale keys as part of
265
+ * one update. An empty section is removed from the config file.
266
+ */
267
+ export function replaceSupiConfigSection(
268
+ loc: SupiConfigLocation,
269
+ value: Record<string, unknown>,
270
+ options?: SupiConfigOptions,
271
+ ): void {
272
+ const configPath = getSupiConfigPath(loc.scope, loc.cwd, options);
273
+ const existing = readJsonFile(configPath) ?? {};
274
+
275
+ if (Object.keys(value).length > 0) existing[loc.section] = value;
276
+ else delete existing[loc.section];
277
+
278
+ const content = Object.keys(existing).length > 0 ? `${JSON.stringify(existing, null, 2)}\n` : "";
279
+ if (content) {
280
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
281
+ fs.writeFileSync(configPath, content, "utf-8");
282
+ return;
283
+ }
284
+
285
+ try {
286
+ fs.unlinkSync(configPath);
287
+ } catch {
288
+ // File may not exist.
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Remove a key from a config section.
294
+ * Used by `interval default` to remove the project override.
295
+ */
296
+ export function removeSupiConfigKey(
297
+ loc: SupiConfigLocation,
298
+ key: string,
299
+ options?: SupiConfigOptions,
300
+ ): void {
301
+ const configPath = getSupiConfigPath(loc.scope, loc.cwd, options);
302
+
303
+ const existing = readJsonFile(configPath);
304
+ if (!existing) return;
305
+
306
+ const sectionData = existing[loc.section] as Record<string, unknown> | undefined;
307
+ if (!sectionData) return;
308
+
309
+ delete sectionData[key];
310
+
311
+ if (Object.keys(sectionData).length === 0) {
312
+ delete existing[loc.section];
313
+ }
314
+
315
+ const dir = path.dirname(configPath);
316
+ fs.mkdirSync(dir, { recursive: true });
317
+
318
+ const content = Object.keys(existing).length > 0 ? `${JSON.stringify(existing, null, 2)}\n` : "";
319
+
320
+ if (content) {
321
+ // Directory guaranteed to exist since we just read from it
322
+ fs.writeFileSync(configPath, content, "utf-8");
323
+ } else {
324
+ try {
325
+ fs.unlinkSync(configPath);
326
+ } catch {
327
+ // File may not exist
328
+ }
329
+ }
330
+ }
331
+
332
+ function extractSection(
333
+ config: Record<string, unknown> | null,
334
+ section: string,
335
+ ): Record<string, unknown> | null {
336
+ if (!config) return null;
337
+ const data = config[section];
338
+ if (typeof data === "object" && data !== null && !Array.isArray(data)) {
339
+ return data as Record<string, unknown>;
340
+ }
341
+ return null;
342
+ }
@@ -0,0 +1,363 @@
1
+ // Configurable tool prompt-surface overrides.
2
+ //
3
+ // Resolution order: package defaults ← global SuPi config ← trusted project SuPi config.
4
+ // Project overrides are trust-gated; they require PI project trust and a PI-recognized
5
+ // trust-requiring resource (e.g. .pi/settings.json).
6
+
7
+ import {
8
+ type ExtensionContext,
9
+ hasTrustRequiringProjectResources,
10
+ } from "@earendil-works/pi-coding-agent";
11
+ import { loadSupiConfigSectionForScope, type SupiConfigOptions } from "./config.ts";
12
+
13
+ // ── Public types ───────────────────────────────────────────────────────────
14
+
15
+ /** Model-facing text that PI adds to one registered tool's prompt surface. */
16
+ export interface SuiPiToolPromptSurface {
17
+ description: string;
18
+ promptSnippet: string;
19
+ promptGuidelines: string[];
20
+ }
21
+
22
+ export type ToolPromptSurfaceDiagnosticCode =
23
+ | "invalidPromptSurfaceConfig"
24
+ | "invalidPromptSurfaceField"
25
+ | "projectPromptSurfaceIgnored";
26
+
27
+ export interface ToolPromptSurfaceDiagnostic {
28
+ code: ToolPromptSurfaceDiagnosticCode;
29
+ scope: "global" | "project";
30
+ section: string;
31
+ toolName: string;
32
+ message: string;
33
+ }
34
+
35
+ export interface ResolveToolPromptSurfaceOptions extends SupiConfigOptions {
36
+ section: string;
37
+ toolName: string;
38
+ defaults: SuiPiToolPromptSurface;
39
+ ctx: Pick<ExtensionContext, "cwd" | "isProjectTrusted">;
40
+ }
41
+
42
+ export interface ResolveToolPromptSurfaceResult {
43
+ surface: SuiPiToolPromptSurface;
44
+ diagnostics: ToolPromptSurfaceDiagnostic[];
45
+ }
46
+
47
+ // ── Private types ──────────────────────────────────────────────────────────
48
+
49
+ type PromptSurfaceField = keyof SuiPiToolPromptSurface;
50
+ type PromptSurfaceScope = ToolPromptSurfaceDiagnostic["scope"];
51
+
52
+ const PROMPT_SURFACE_FIELDS = new Set<string>(["description", "promptSnippet", "promptGuidelines"]);
53
+
54
+ const PROMPT_SURFACE_DIAGNOSTICS_KEY = Symbol.for(
55
+ "@mrclrchtr/supi-core/tool-prompt-surface/notified-diagnostics",
56
+ );
57
+
58
+ // ── Resolution ─────────────────────────────────────────────────────────────
59
+
60
+ /** Resolve a tool's model-facing prompt surface from defaults + SuPi config overrides. */
61
+ export function resolveToolPromptSurface(
62
+ options: ResolveToolPromptSurfaceOptions,
63
+ ): ResolveToolPromptSurfaceResult {
64
+ const diagnostics: ToolPromptSurfaceDiagnostic[] = [];
65
+ let surface = clonePromptSurface(options.defaults);
66
+
67
+ const globalSection = loadSupiConfigSectionForScope(options.section, options.ctx.cwd, {
68
+ scope: "global",
69
+ homeDir: options.homeDir,
70
+ });
71
+ surface = applyPromptSurfaceScope(surface, options, "global", globalSection, diagnostics);
72
+
73
+ const projectSection = loadSupiConfigSectionForScope(options.section, options.ctx.cwd, {
74
+ scope: "project",
75
+ homeDir: options.homeDir,
76
+ });
77
+ const projectPromptSurface = getPromptSurfaceConfig(projectSection, options.toolName, {
78
+ diagnostics,
79
+ options,
80
+ scope: "project",
81
+ });
82
+
83
+ if (projectPromptSurface) {
84
+ const hasTrustMarker = hasTrustRequiringProjectResources(options.ctx.cwd);
85
+ const projectTrusted = options.ctx.isProjectTrusted();
86
+ if (hasTrustMarker && projectTrusted) {
87
+ surface = applyPromptSurfaceConfig(
88
+ surface,
89
+ options.defaults,
90
+ projectPromptSurface,
91
+ options,
92
+ "project",
93
+ diagnostics,
94
+ );
95
+ } else {
96
+ diagnostics.push({
97
+ code: "projectPromptSurfaceIgnored",
98
+ scope: "project",
99
+ section: options.section,
100
+ toolName: options.toolName,
101
+ message: hasTrustMarker
102
+ ? `Project prompt-surface overrides for ${options.toolName} were ignored because the project is not trusted in PI.`
103
+ : `Project prompt-surface overrides for ${options.toolName} were ignored because ${options.ctx.cwd}/.pi/supi/config.json is not PI trust-gated. Add .pi/settings.json and trust the project to enable them.`,
104
+ });
105
+ }
106
+ }
107
+
108
+ return { surface, diagnostics };
109
+ }
110
+
111
+ /** Notify prompt-surface diagnostics once per session/tool/diagnostic code. */
112
+ export function notifyToolPromptSurfaceDiagnostics(
113
+ ctx: Pick<ExtensionContext, "sessionManager" | "ui">,
114
+ diagnostics: readonly ToolPromptSurfaceDiagnostic[],
115
+ ): void {
116
+ const globalRecord = globalThis as Record<symbol, Set<string> | undefined>;
117
+ const notified = globalRecord[PROMPT_SURFACE_DIAGNOSTICS_KEY] ?? new Set<string>();
118
+ globalRecord[PROMPT_SURFACE_DIAGNOSTICS_KEY] = notified;
119
+ const sessionId = ctx.sessionManager.getSessionId();
120
+
121
+ for (const diagnostic of diagnostics) {
122
+ const key = `${sessionId}:${diagnostic.section}:${diagnostic.toolName}:${diagnostic.code}`;
123
+ if (notified.has(key)) continue;
124
+ notified.add(key);
125
+ ctx.ui.notify(diagnostic.message, "warning");
126
+ }
127
+ }
128
+
129
+ // ── Scope helpers ──────────────────────────────────────────────────────────
130
+
131
+ // biome-ignore lint/complexity/useMaxParams: resolver dispatch with diagnostics
132
+ function applyPromptSurfaceScope(
133
+ current: SuiPiToolPromptSurface,
134
+ options: ResolveToolPromptSurfaceOptions,
135
+ scope: PromptSurfaceScope,
136
+ sectionConfig: Record<string, unknown> | null,
137
+ diagnostics: ToolPromptSurfaceDiagnostic[],
138
+ ): SuiPiToolPromptSurface {
139
+ const promptSurface = getPromptSurfaceConfig(sectionConfig, options.toolName, {
140
+ diagnostics,
141
+ options,
142
+ scope,
143
+ });
144
+ if (!promptSurface) return current;
145
+ return applyPromptSurfaceConfig(
146
+ current,
147
+ options.defaults,
148
+ promptSurface,
149
+ options,
150
+ scope,
151
+ diagnostics,
152
+ );
153
+ }
154
+
155
+ // biome-ignore lint/complexity/useMaxParams: per-scope config merger with diagnostics
156
+ function applyPromptSurfaceConfig(
157
+ current: SuiPiToolPromptSurface,
158
+ defaults: SuiPiToolPromptSurface,
159
+ config: Record<string, unknown>,
160
+ options: ResolveToolPromptSurfaceOptions,
161
+ scope: PromptSurfaceScope,
162
+ diagnostics: ToolPromptSurfaceDiagnostic[],
163
+ ): SuiPiToolPromptSurface {
164
+ let next = clonePromptSurface(current);
165
+
166
+ for (const field of getResetFields(config.$reset, options, scope, diagnostics)) {
167
+ next = { ...next, [field]: clonePromptSurfaceField(defaults[field]) };
168
+ }
169
+
170
+ const description = getOptionalNonEmptyString(
171
+ config.description,
172
+ "description",
173
+ options,
174
+ scope,
175
+ diagnostics,
176
+ );
177
+ if (description !== undefined) next.description = description;
178
+
179
+ const promptSnippet = getOptionalNonEmptyString(
180
+ config.promptSnippet,
181
+ "promptSnippet",
182
+ options,
183
+ scope,
184
+ diagnostics,
185
+ );
186
+ if (promptSnippet !== undefined) next.promptSnippet = promptSnippet;
187
+
188
+ const promptGuidelines = getOptionalStringArray(
189
+ config.promptGuidelines,
190
+ "promptGuidelines",
191
+ options,
192
+ scope,
193
+ diagnostics,
194
+ );
195
+ if (promptGuidelines !== undefined) next.promptGuidelines = promptGuidelines;
196
+
197
+ const prepend = getOptionalStringArray(
198
+ config.prependPromptGuidelines,
199
+ "prependPromptGuidelines",
200
+ options,
201
+ scope,
202
+ diagnostics,
203
+ );
204
+ if (prepend !== undefined) next.promptGuidelines = [...prepend, ...next.promptGuidelines];
205
+
206
+ const append = getOptionalStringArray(
207
+ config.appendPromptGuidelines,
208
+ "appendPromptGuidelines",
209
+ options,
210
+ scope,
211
+ diagnostics,
212
+ );
213
+ if (append !== undefined) next.promptGuidelines = [...next.promptGuidelines, ...append];
214
+
215
+ return next;
216
+ }
217
+
218
+ // ── Config extraction ──────────────────────────────────────────────────────
219
+
220
+ function getPromptSurfaceConfig(
221
+ sectionConfig: Record<string, unknown> | null,
222
+ toolName: string,
223
+ deps: {
224
+ diagnostics: ToolPromptSurfaceDiagnostic[];
225
+ options: ResolveToolPromptSurfaceOptions;
226
+ scope: PromptSurfaceScope;
227
+ },
228
+ ): Record<string, unknown> | null {
229
+ if (!sectionConfig) return null;
230
+ if (sectionConfig.tools === undefined) return null;
231
+ if (!isRecord(sectionConfig.tools)) {
232
+ pushInvalidConfig(deps, "tools must be an object.");
233
+ return null;
234
+ }
235
+ const toolConfig = sectionConfig.tools[toolName];
236
+ if (toolConfig === undefined) return null;
237
+ if (!isRecord(toolConfig)) {
238
+ pushInvalidConfig(deps, `tools.${toolName} must be an object.`);
239
+ return null;
240
+ }
241
+ if (toolConfig.promptSurface === undefined) return null;
242
+ if (!isRecord(toolConfig.promptSurface)) {
243
+ pushInvalidConfig(deps, `tools.${toolName}.promptSurface must be an object.`);
244
+ return null;
245
+ }
246
+ return toolConfig.promptSurface;
247
+ }
248
+
249
+ // ── Field validation ───────────────────────────────────────────────────────
250
+
251
+ function getResetFields(
252
+ value: unknown,
253
+ options: ResolveToolPromptSurfaceOptions,
254
+ scope: PromptSurfaceScope,
255
+ diagnostics: ToolPromptSurfaceDiagnostic[],
256
+ ): PromptSurfaceField[] {
257
+ if (value === undefined) return [];
258
+ if (!Array.isArray(value)) {
259
+ pushInvalidField(options, scope, diagnostics, "$reset", "must be an array.");
260
+ return [];
261
+ }
262
+ const fields: PromptSurfaceField[] = [];
263
+ for (const item of value) {
264
+ if (typeof item === "string" && PROMPT_SURFACE_FIELDS.has(item)) {
265
+ fields.push(item as PromptSurfaceField);
266
+ } else {
267
+ pushInvalidField(
268
+ options,
269
+ scope,
270
+ diagnostics,
271
+ "$reset",
272
+ `contains unsupported field ${JSON.stringify(item)}.`,
273
+ );
274
+ }
275
+ }
276
+ return fields;
277
+ }
278
+
279
+ // biome-ignore lint/complexity/useMaxParams: validation helper with diagnostics
280
+ function getOptionalNonEmptyString(
281
+ value: unknown,
282
+ field: string,
283
+ options: ResolveToolPromptSurfaceOptions,
284
+ scope: PromptSurfaceScope,
285
+ diagnostics: ToolPromptSurfaceDiagnostic[],
286
+ ): string | undefined {
287
+ if (value === undefined) return undefined;
288
+ if (typeof value === "string" && value.length > 0) return value;
289
+ pushInvalidField(options, scope, diagnostics, field, "must be a non-empty string.");
290
+ return undefined;
291
+ }
292
+
293
+ // biome-ignore lint/complexity/useMaxParams: validation helper with diagnostics
294
+ function getOptionalStringArray(
295
+ value: unknown,
296
+ field: string,
297
+ options: ResolveToolPromptSurfaceOptions,
298
+ scope: PromptSurfaceScope,
299
+ diagnostics: ToolPromptSurfaceDiagnostic[],
300
+ ): string[] | undefined {
301
+ if (value === undefined) return undefined;
302
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
303
+ return [...value];
304
+ }
305
+ pushInvalidField(options, scope, diagnostics, field, "must be an array of strings.");
306
+ return undefined;
307
+ }
308
+
309
+ // ── Diagnostics ────────────────────────────────────────────────────────────
310
+
311
+ function pushInvalidConfig(
312
+ deps: {
313
+ diagnostics: ToolPromptSurfaceDiagnostic[];
314
+ options: ResolveToolPromptSurfaceOptions;
315
+ scope: PromptSurfaceScope;
316
+ },
317
+ detail: string,
318
+ ): void {
319
+ deps.diagnostics.push({
320
+ // biome-ignore lint/security/noSecrets: false positive on string constant
321
+ code: "invalidPromptSurfaceConfig",
322
+ scope: deps.scope,
323
+ section: deps.options.section,
324
+ toolName: deps.options.toolName,
325
+ message: `Invalid prompt-surface config for ${deps.options.section}.${deps.options.toolName}: ${detail}`,
326
+ });
327
+ }
328
+
329
+ // biome-ignore lint/complexity/useMaxParams: diagnostics utility with many fields
330
+ function pushInvalidField(
331
+ options: ResolveToolPromptSurfaceOptions,
332
+ scope: PromptSurfaceScope,
333
+ diagnostics: ToolPromptSurfaceDiagnostic[],
334
+ field: string,
335
+ detail: string,
336
+ ): void {
337
+ diagnostics.push({
338
+ // biome-ignore lint/security/noSecrets: false positive on string constant
339
+ code: "invalidPromptSurfaceField",
340
+ scope,
341
+ section: options.section,
342
+ toolName: options.toolName,
343
+ message: `Invalid prompt-surface field ${field} for ${options.section}.${options.toolName}: ${detail}`,
344
+ });
345
+ }
346
+
347
+ // ── Cloning ────────────────────────────────────────────────────────────────
348
+
349
+ function clonePromptSurface(surface: SuiPiToolPromptSurface): SuiPiToolPromptSurface {
350
+ return {
351
+ description: surface.description,
352
+ promptSnippet: surface.promptSnippet,
353
+ promptGuidelines: [...surface.promptGuidelines],
354
+ };
355
+ }
356
+
357
+ function clonePromptSurfaceField<T extends string | string[]>(value: T): T {
358
+ return (Array.isArray(value) ? [...value] : value) as T;
359
+ }
360
+
361
+ function isRecord(value: unknown): value is Record<string, unknown> {
362
+ return typeof value === "object" && value !== null && !Array.isArray(value);
363
+ }