pi-context-kit 0.4.3 → 0.4.5

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.
@@ -0,0 +1,549 @@
1
+ import {
2
+ getAgentDir,
3
+ SettingsManager,
4
+ type ExtensionAPI,
5
+ type ExtensionContext,
6
+ type SessionManager,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import { Type, type Static, type TObject } from "typebox";
9
+ import { Value } from "typebox/value";
10
+
11
+ import { isRecord } from "./record.ts";
12
+
13
+ /** Native layer an authored option is written to or replayed from. */
14
+ export type LayeredSettingScope = "session" | "global" | "project";
15
+ /** Native layer supplying an effective option. */
16
+ export type LayeredSettingSource = "default" | LayeredSettingScope;
17
+ /** Authored scopes cached at startup/reload; a failed scope keeps its error until corrected. */
18
+ export interface LayeredSettingsLayers<Options> {
19
+ global: Options | Error;
20
+ project: Options | Error;
21
+ }
22
+ /** A validated authored mutation, independent of its persistence scope. */
23
+ export type LayeredSettingChange<Options> =
24
+ | { action: "set"; key: keyof Options; patch: Options }
25
+ | { action: "inherit"; key: keyof Options };
26
+
27
+ /**
28
+ * Merges one layer's value for a key into the value accumulated from lower layers, instead of
29
+ * replacing it. Called once per layer that authored the key, lowest precedence first.
30
+ */
31
+ export type LayeredSettingMerge<Config, Key extends keyof Config> = (
32
+ current: Config[Key],
33
+ next: Config[Key],
34
+ source: LayeredSettingScope,
35
+ ) => Config[Key];
36
+ /** Per-key merge hooks; keys without one are replaced by the highest-precedence layer. */
37
+ export type LayeredSettingMerges<Config> = {
38
+ [Key in keyof Config]?: LayeredSettingMerge<Config, Key>;
39
+ };
40
+ /** One layer's authored options, typed as the config values they set; `undefined` inherits. */
41
+ export type LayeredSettingLayer<Config> = {
42
+ [Key in keyof Config]?: Config[Key] | undefined;
43
+ };
44
+
45
+ /** Input for {@link resolveLayeredOptions}. */
46
+ export interface ResolveLayeredOptionsInput<Config> {
47
+ defaults: Config;
48
+ /** Keys resolved, in order: each key is merged across every layer before the next key. */
49
+ optionKeys: readonly (keyof Config)[];
50
+ /** Layers lowest precedence first. */
51
+ layers: readonly (readonly [LayeredSettingScope, LayeredSettingLayer<Config>])[];
52
+ merge?: LayeredSettingMerges<Config> | undefined;
53
+ }
54
+ /** Effective settings and the source that supplied each key. */
55
+ export interface ResolvedLayeredSettings<Config> {
56
+ settings: Config;
57
+ sources: Record<string, LayeredSettingSource>;
58
+ }
59
+
60
+ /**
61
+ * Resolve effective settings: defaults, then each layer in order. A key a layer authors replaces
62
+ * the lower value, or is passed to that key's merge hook. A key authored as `undefined` inherits
63
+ * like an absent one. Also reports which source supplied each key. Pure: validation and trust gating belong to whoever built the layers.
64
+ */
65
+ export function resolveLayeredOptions<Config extends object>(
66
+ input: ResolveLayeredOptionsInput<Config>,
67
+ ): ResolvedLayeredSettings<Config> {
68
+ const settings = structuredClone(input.defaults);
69
+ const sources: Record<string, LayeredSettingSource> = {};
70
+ const apply = <Key extends keyof Config>(
71
+ key: Key,
72
+ layer: LayeredSettingLayer<Config>,
73
+ source: LayeredSettingScope,
74
+ ): boolean => {
75
+ if (!Object.hasOwn(layer, key)) return false;
76
+ const next = layer[key];
77
+ // An explicit `undefined` inherits, as an absent key does; merge hooks never receive it.
78
+ if (next === undefined) return false;
79
+ const hook = input.merge?.[key];
80
+ settings[key] = hook ? hook(settings[key], next, source) : next;
81
+ return true;
82
+ };
83
+ for (const key of input.optionKeys) {
84
+ sources[String(key)] = "default";
85
+ for (const [source, layer] of input.layers) {
86
+ if (apply(key, layer, source)) sources[String(key)] = source;
87
+ }
88
+ }
89
+ return { settings, sources };
90
+ }
91
+
92
+ // Settings text reaches terminal notifications; raw control characters would run escape sequences.
93
+ export function escapeControls(text: string): string {
94
+ return text.replace(
95
+ /\p{Cc}/gu,
96
+ (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`,
97
+ );
98
+ }
99
+
100
+ /** Why {@link rewriteNamespaceDocument} refused a stored settings document. */
101
+ export type InvalidSettingsDocument = "malformed" | "root" | "namespace";
102
+
103
+ /** Input for {@link rewriteNamespaceDocument}. */
104
+ export interface RewriteNamespaceDocumentInput {
105
+ /** Current file text, or `undefined` when the file is absent. */
106
+ current: string | undefined;
107
+ namespace: string;
108
+ /** Keep an empty namespace instead of removing it. */
109
+ keepEmpty?: boolean;
110
+ /** Receives a copy of the stored namespace options and returns its replacement. */
111
+ update: (options: Record<string, unknown>) => Record<string, unknown>;
112
+ /** Builds the error thrown instead of overwriting a document that cannot be safely rewritten. */
113
+ invalid: (reason: InvalidSettingsDocument, cause: Error | undefined) => Error;
114
+ }
115
+
116
+ /**
117
+ * Rewrite one namespace of a Pi settings document, preserving every other setting. Strips a
118
+ * leading BOM, refuses documents whose root or namespace is not an object, and removes an empty
119
+ * namespace unless `keepEmpty` is set. Transport-independent: callers run it inside whichever
120
+ * lock and writer they use.
121
+ * @returns The replacement file text.
122
+ */
123
+ export function rewriteNamespaceDocument(input: RewriteNamespaceDocumentInput): string {
124
+ let parsed: unknown;
125
+ try {
126
+ parsed = JSON.parse((input.current ?? "{}").replace(/^\uFEFF/, ""));
127
+ } catch (cause) {
128
+ throw input.invalid("malformed", cause instanceof Error ? cause : undefined);
129
+ }
130
+ if (!isRecord(parsed)) throw input.invalid("root", undefined);
131
+ const stored = parsed[input.namespace];
132
+ if (stored !== undefined && !isRecord(stored)) throw input.invalid("namespace", undefined);
133
+ const updated = input.update({ ...stored });
134
+ if (Object.keys(updated).length === 0 && !input.keepEmpty) delete parsed[input.namespace];
135
+ else parsed[input.namespace] = updated;
136
+ return `${JSON.stringify(parsed, null, 2)}\n`;
137
+ }
138
+
139
+ /**
140
+ * Definition of one extension's layered settings namespace. `Options` is `Static<S>`; `Merge`
141
+ * holds the per-key merge hooks and `Entry` the session entry type, both inferred.
142
+ */
143
+ export interface LayeredSettingsDefinition<
144
+ S extends TObject,
145
+ Config extends object,
146
+ Merge extends LayeredSettingMerges<Config> = {},
147
+ Entry extends string | undefined = undefined,
148
+ > {
149
+ /** Key under which authored options live in Pi's settings documents, e.g. `my-extension`. */
150
+ namespace: string;
151
+ /** Name used in error messages, e.g. `My extension`. */
152
+ label: string;
153
+ /** Schema of the authored options; every property must be optional so absent values inherit. */
154
+ schema: S;
155
+ defaults: Config;
156
+ /** Custom session entry type holding `{ version: 1, overrides }`; omit for no session layer. */
157
+ sessionEntryType?: Entry;
158
+ /** Per-key merge hooks for keys that merge across layers instead of replacing. */
159
+ merge?: Merge;
160
+ /** Keep the namespace in a settings document after its last option is removed. */
161
+ keepEmptyNamespace?: boolean;
162
+ globalOnlyKeys?: readonly (keyof Static<S> & keyof Config & string)[];
163
+ }
164
+
165
+ /**
166
+ * Option keys the definition's `Config` cannot hold: a key `Config` lacks, or a key whose authored
167
+ * value type is not assignable to its `Config` type.
168
+ */
169
+ export type LayeredSettingsConfigMismatch<Options, Config> = {
170
+ [Key in keyof Options]-?: Key extends keyof Config
171
+ ? [Exclude<Options[Key], undefined>] extends [Config[Key]]
172
+ ? never
173
+ : Key
174
+ : Key;
175
+ }[keyof Options];
176
+ /** Adds a type error naming the mismatched keys; `unknown` (no constraint) when there are none. */
177
+ type LayeredSettingsConfigCheck<Options, Config> = [
178
+ LayeredSettingsConfigMismatch<Options, Config>,
179
+ ] extends [never]
180
+ ? unknown
181
+ : { configMismatch: LayeredSettingsConfigMismatch<Options, Config> };
182
+
183
+ /** The settings and session a layered read or write runs against. */
184
+ export interface LayeredSettingsSession {
185
+ settingsManager: SettingsManager;
186
+ sessionManager: Pick<SessionManager, "getBranch">;
187
+ }
188
+ /** Effective settings that survive unreadable layers; `invalid` lists each layer left out. */
189
+ export interface LenientLayeredSettings<Options, Config> extends ResolvedLayeredSettings<Config> {
190
+ /** Usable authored options per scope; an unreadable scope or session entry authors nothing. */
191
+ authored: { global: Options; project: Options; session: Options };
192
+ /** Errors of the layers left out, in the order global, project, session. */
193
+ invalid: Error[];
194
+ }
195
+
196
+ /** Settings operations for one namespace; `Options` is `Static<S>`. */
197
+ export interface LayeredSettings<S extends TObject, Config extends object> {
198
+ /** Reject inherited or unknown property names before applying an authored change. */
199
+ optionKey(input: string): keyof Static<S> & string;
200
+ /** Schema property names, in schema order. */
201
+ optionKeys: readonly (keyof Static<S> & string)[];
202
+ /** Validate authored options read from, or about to be written to, a scope. */
203
+ // Native settings contain arbitrary authored JSON; the schema validates it before use.
204
+ parseOptions(value: unknown, source: LayeredSettingScope): Static<S>;
205
+ /** Read Pi's stored layers, preserving configuration failures until corrected. */
206
+ readLayers(manager: SettingsManager): LayeredSettingsLayers<Static<S>>;
207
+ /** Resolve stored scopes without changing Pi's effective runtime overrides. */
208
+ readSettings(
209
+ session: LayeredSettingsSession,
210
+ authored?: LayeredSettingsLayers<Static<S>>,
211
+ ): ResolvedLayeredSettings<Config>;
212
+ /** Use Pi's actual backend: its generic storage API is not exported. */
213
+ writeSettings(
214
+ manager: SettingsManager,
215
+ scope: "global" | "project",
216
+ change: LayeredSettingChange<Static<S>>,
217
+ isCurrent: () => boolean,
218
+ ): Promise<Static<S> | undefined>;
219
+ }
220
+ /** Layered settings with a session layer, so overrides can be replayed from a session branch. */
221
+ export interface SessionLayeredSettings<
222
+ S extends TObject,
223
+ Config extends object,
224
+ > extends LayeredSettings<S, Config> {
225
+ /** Replay only the selected branch's last complete override snapshot. */
226
+ readOverrides(manager: Pick<SessionManager, "getBranch">): Static<S>;
227
+ /** Like `readSettings`, but an unreadable layer is left out and listed in `invalid`. */
228
+ readSettingsLeniently(session: LayeredSettingsSession): LenientLayeredSettings<Static<S>, Config>;
229
+ /** Write one change; a session change is appended to the session as an entry through `pi`. */
230
+ writeChange(
231
+ pi: Pick<ExtensionAPI, "appendEntry">,
232
+ session: LayeredSettingsSession,
233
+ scope: LayeredSettingScope,
234
+ change: LayeredSettingChange<Static<S>>,
235
+ isCurrent: () => boolean,
236
+ ): Promise<Static<S> | undefined>;
237
+ }
238
+
239
+ const optionalText = Type.Union([Type.String(), Type.Undefined()]);
240
+ const storageSchema = Type.Object({
241
+ withLock: Type.Function(
242
+ [
243
+ Type.Union([Type.Literal("global"), Type.Literal("project")]),
244
+ Type.Function([optionalText], optionalText),
245
+ ],
246
+ Type.Void(),
247
+ ),
248
+ });
249
+
250
+ /**
251
+ * Define layered settings: authored options from Pi's global settings, trusted-project settings
252
+ * and (optionally) session overrides, resolved over defaults with precedence
253
+ * default < global < trusted project < session. The authored options are `Static<S>`; `Config`
254
+ * must hold every option key, with a type the authored value is assignable to unless the key
255
+ * has a merge hook. `readOverrides` exists only when `sessionEntryType` is given.
256
+ */
257
+ export function defineLayeredSettings<
258
+ S extends TObject,
259
+ Config extends object,
260
+ Merge extends LayeredSettingMerges<Config> = {},
261
+ >(
262
+ definition: LayeredSettingsDefinition<S, Config, Merge> &
263
+ LayeredSettingsConfigCheck<Static<S>, Config>,
264
+ ): LayeredSettings<S, Config>;
265
+ export function defineLayeredSettings<
266
+ S extends TObject,
267
+ Config extends object,
268
+ Merge extends LayeredSettingMerges<Config> = {},
269
+ >(
270
+ definition: LayeredSettingsDefinition<S, Config, Merge, string> &
271
+ LayeredSettingsConfigCheck<Static<S>, Config> & {
272
+ sessionEntryType: string;
273
+ },
274
+ ): SessionLayeredSettings<S, Config>;
275
+ export function defineLayeredSettings<
276
+ S extends TObject,
277
+ Config extends object,
278
+ Merge extends LayeredSettingMerges<Config>,
279
+ >(
280
+ definition: LayeredSettingsDefinition<S, Config, Merge, string | undefined> &
281
+ LayeredSettingsConfigCheck<Static<S>, Config>,
282
+ ): LayeredSettings<S, Config> | SessionLayeredSettings<S, Config> {
283
+ type Options = Static<S>;
284
+ type OptionKey = keyof Options & keyof Config & string;
285
+ type Layers = LayeredSettingsLayers<Options>;
286
+ type Change = LayeredSettingChange<Options>;
287
+ const {
288
+ namespace,
289
+ label,
290
+ schema,
291
+ defaults,
292
+ sessionEntryType,
293
+ merge,
294
+ keepEmptyNamespace,
295
+ globalOnlyKeys = [],
296
+ } = definition;
297
+ if (!Value.Check(schema, {}))
298
+ throw new Error(`${label} settings schema must make every option optional`);
299
+ const keySchema = Type.KeyOf(schema);
300
+ const sessionSchema = Type.Object(
301
+ { version: Type.Literal(1), overrides: schema },
302
+ { additionalProperties: false },
303
+ );
304
+
305
+ function isOptionKey(input: string): input is OptionKey {
306
+ return Value.Check(keySchema, input);
307
+ }
308
+ // Native settings contain arbitrary authored JSON; this guard validates it with the option schema before use.
309
+ function isOptions(value: unknown): value is Options & LayeredSettingLayer<Config> {
310
+ return Value.Check(schema, value);
311
+ }
312
+ // Session entry data is arbitrary JSON; this guard validates the versioned envelope before replay.
313
+ function isSessionData(value: unknown): value is { version: 1; overrides: Options } {
314
+ return Value.Check(sessionSchema, value);
315
+ }
316
+
317
+ function optionKey(input: string): OptionKey {
318
+ if (!isOptionKey(input)) throw new Error(`Unknown ${label} option: ${input}`);
319
+ return input;
320
+ }
321
+ const optionKeys = Object.keys(schema.properties).map(optionKey);
322
+
323
+ // Every option is optional, so the empty layer must pass the schema.
324
+ function checkedEmptyOptions(): Options {
325
+ const empty: unknown = {};
326
+ if (!isOptions(empty))
327
+ throw new Error(`${label} settings schema must make every option optional`);
328
+ return empty;
329
+ }
330
+
331
+ const empty = checkedEmptyOptions();
332
+ /** The options of a layer that authored nothing. */
333
+ function noOptions(): Options {
334
+ return structuredClone(empty);
335
+ }
336
+
337
+ function checkScope(options: Options, source: LayeredSettingScope): void {
338
+ if (source === "global") return;
339
+ for (const key of globalOnlyKeys) {
340
+ if (Object.hasOwn(options, key))
341
+ throw new Error(
342
+ `Invalid ${source} ${label} settings: ${key} is global-only; set it in global settings`,
343
+ );
344
+ }
345
+ }
346
+
347
+ // Native settings contain arbitrary authored JSON; the option schema validates it before use. SDK command tests exercise the boundary.
348
+ function parseOptions(value: unknown, source: LayeredSettingScope): Options {
349
+ if (value === undefined) return noOptions();
350
+ if (!isOptions(value)) {
351
+ const issue = Value.Errors(schema, value)[0];
352
+ if (issue?.schemaPath === "#/additionalProperties")
353
+ throw new Error(
354
+ `Invalid ${source} ${label} settings: unknown option ${escapeControls(issue.instancePath.slice(1))}`,
355
+ );
356
+ throw new Error(
357
+ `Invalid ${source} ${label} settings${escapeControls(issue?.instancePath ?? "")}: ${issue?.message ?? "invalid options"}`,
358
+ );
359
+ }
360
+ checkScope(value, source);
361
+ return structuredClone(value);
362
+ }
363
+
364
+ /** Replay only the selected branch's last complete override snapshot. */
365
+ function readOverrides(manager: Pick<SessionManager, "getBranch">): Options {
366
+ const entry = manager
367
+ .getBranch()
368
+ .findLast((item) => item.type === "custom" && item.customType === sessionEntryType);
369
+ if (!entry || entry.type !== "custom") return noOptions();
370
+ if (!isSessionData(entry.data)) throw new Error(`Invalid ${label} session settings`);
371
+ checkScope(entry.data.overrides, "session");
372
+ return structuredClone(entry.data.overrides);
373
+ }
374
+
375
+ /** Read Pi's stored layers, preserving configuration failures until corrected. */
376
+ function readLayers(manager: SettingsManager): Layers {
377
+ const layers: Layers = { global: noOptions(), project: noOptions() };
378
+ for (const scope of ["global", "project"] as const) {
379
+ try {
380
+ if (scope === "project" && !manager.isProjectTrusted()) continue;
381
+ const document =
382
+ scope === "global" ? manager.getGlobalSettings() : manager.getProjectSettings();
383
+ layers[scope] = parseOptions(
384
+ Object.getOwnPropertyDescriptor(document, namespace)?.value,
385
+ scope,
386
+ );
387
+ } catch (cause) {
388
+ layers[scope] = cause instanceof Error ? cause : new Error(String(cause));
389
+ }
390
+ }
391
+ return layers;
392
+ }
393
+
394
+ /** Resolve stored scopes without changing Pi's effective runtime overrides. */
395
+ function readSettings(
396
+ session: LayeredSettingsSession,
397
+ authored = readLayers(session.settingsManager),
398
+ ) {
399
+ if (authored.global instanceof Error) throw authored.global;
400
+ const project = session.settingsManager.isProjectTrusted() ? authored.project : noOptions();
401
+ if (project instanceof Error) throw project;
402
+ checkScope(project, "project");
403
+ const layers: (readonly [LayeredSettingScope, LayeredSettingLayer<Config>])[] = [
404
+ ["global", authored.global],
405
+ ["project", project],
406
+ ];
407
+ if (sessionEntryType !== undefined)
408
+ layers.push(["session", readOverrides(session.sessionManager)]);
409
+ return resolveLayeredOptions<Config>({
410
+ defaults,
411
+ optionKeys,
412
+ layers,
413
+ merge,
414
+ });
415
+ }
416
+
417
+ /** Use Pi's actual backend: its generic storage API is not exported. */
418
+ async function writeSettings(
419
+ manager: SettingsManager,
420
+ scope: "global" | "project",
421
+ change: Change,
422
+ isCurrent: () => boolean,
423
+ ): Promise<Options | undefined> {
424
+ const untrusted = () => new Error(`${label} project settings require a trusted project`);
425
+ if (scope === "project" && !manager.isProjectTrusted()) throw untrusted();
426
+ const candidate: unknown = Object.getOwnPropertyDescriptor(manager, "storage")?.value;
427
+ if (!Value.Check(storageSchema, candidate)) {
428
+ throw new Error(
429
+ `Unsupported Pi settings backend: ${label} cannot safely write scoped settings`,
430
+ );
431
+ }
432
+ const storage: Parameters<typeof SettingsManager.fromStorage>[0] = candidate;
433
+ await manager.flush();
434
+ if (!isCurrent()) return undefined;
435
+ if (scope === "project" && !manager.isProjectTrusted()) throw untrusted();
436
+ let updated: Options | undefined;
437
+ storage.withLock(scope, (current) =>
438
+ rewriteNamespaceDocument({
439
+ current,
440
+ namespace,
441
+ keepEmpty: keepEmptyNamespace === true,
442
+ invalid: (reason, cause) =>
443
+ reason === "malformed" && cause
444
+ ? new SyntaxError(escapeControls(cause.message), { cause })
445
+ : new Error(`Invalid ${scope} settings document; refusing to overwrite it`),
446
+ update: (stored) => {
447
+ const next = { ...stored };
448
+ if (change.action === "inherit") Reflect.deleteProperty(next, change.key);
449
+ else Object.assign(next, change.patch);
450
+ updated = parseOptions(next, scope);
451
+ return next;
452
+ },
453
+ }),
454
+ );
455
+ return updated;
456
+ }
457
+
458
+ const settings: LayeredSettings<S, Config> = {
459
+ optionKey,
460
+ optionKeys,
461
+ parseOptions,
462
+ readLayers,
463
+ readSettings,
464
+ writeSettings,
465
+ };
466
+ if (sessionEntryType === undefined) return settings;
467
+ const sessionEntry = sessionEntryType;
468
+
469
+ /** Like `readSettings`; an unreadable layer or session entry is left out, and its error kept. */
470
+ function readSettingsLeniently(
471
+ session: LayeredSettingsSession,
472
+ ): LenientLayeredSettings<Options, Config> {
473
+ // Pi reads an unloadable file as empty, so only its recorded error shows the problem.
474
+ const invalid: Error[] = session.settingsManager.drainErrors().map(
475
+ (entry) =>
476
+ new Error(escapeControls(entry.error.message), {
477
+ cause: entry.error,
478
+ }),
479
+ );
480
+ const layers = readLayers(session.settingsManager);
481
+ const usable = (layer: Options | Error): Options => {
482
+ if (!(layer instanceof Error)) return layer;
483
+ invalid.push(layer);
484
+ return noOptions();
485
+ };
486
+ const authored = {
487
+ global: usable(layers.global),
488
+ project: usable(layers.project),
489
+ };
490
+ let sessionManager = session.sessionManager;
491
+ let overrides = noOptions();
492
+ try {
493
+ overrides = readOverrides(sessionManager);
494
+ } catch (cause) {
495
+ invalid.push(cause instanceof Error ? cause : new Error(String(cause)));
496
+ // An unreadable session entry counts as no session overrides.
497
+ sessionManager = { getBranch: () => [] };
498
+ }
499
+ const resolved = readSettings(
500
+ { settingsManager: session.settingsManager, sessionManager },
501
+ authored,
502
+ );
503
+ return {
504
+ ...resolved,
505
+ authored: { ...authored, session: overrides },
506
+ invalid,
507
+ };
508
+ }
509
+
510
+ /** Write one change unless the session changed first; a session change becomes the entry that replays it. */
511
+ async function writeChange(
512
+ pi: Pick<ExtensionAPI, "appendEntry">,
513
+ session: LayeredSettingsSession,
514
+ scope: LayeredSettingScope,
515
+ change: LayeredSettingChange<Options>,
516
+ isCurrent: () => boolean,
517
+ ): Promise<Options | undefined> {
518
+ if (!isCurrent()) return undefined;
519
+ if (scope !== "session")
520
+ return writeSettings(session.settingsManager, scope, change, isCurrent);
521
+ const overrides = readOverrides(session.sessionManager);
522
+ if (change.action === "inherit") Reflect.deleteProperty(overrides, change.key);
523
+ else Object.assign(overrides, change.patch);
524
+ const validated = parseOptions(overrides, "session");
525
+ pi.appendEntry(sessionEntry, { version: 1, overrides: validated });
526
+ return validated;
527
+ }
528
+
529
+ return { ...settings, readOverrides, readSettingsLeniently, writeChange };
530
+ }
531
+
532
+ /** The settings and session of a command or menu on `ctx`; the project file is read only when trusted. */
533
+ export function layeredSettingsSession(
534
+ ctx: Pick<ExtensionContext, "cwd" | "isProjectTrusted" | "sessionManager">,
535
+ ): LayeredSettingsSession {
536
+ return {
537
+ settingsManager: SettingsManager.create(ctx.cwd, getAgentDir(), {
538
+ projectTrusted: ctx.isProjectTrusted(),
539
+ }),
540
+ sessionManager: ctx.sessionManager,
541
+ };
542
+ }
543
+
544
+ /** Scopes a settings menu offers: the project scope only while the project is trusted. */
545
+ export function layeredMenuScopes(
546
+ manager: Pick<SettingsManager, "isProjectTrusted">,
547
+ ): LayeredSettingScope[] {
548
+ return manager.isProjectTrusted() ? ["session", "project", "global"] : ["session", "global"];
549
+ }
@@ -0,0 +1,147 @@
1
+ // Model tool arguments and JSON Schemas are untyped JSON by nature. Every read narrows with isRecord/Array.isArray before use, and the table test in test/null-optional-arguments.test.ts exercises each shape.
2
+ import { Value } from "typebox/value";
3
+
4
+ import { isRecord } from "./record.js";
5
+
6
+ type Entry = Readonly<Record<string, unknown>>;
7
+
8
+ /**
9
+ * Models trained on tool schemas that declare an optional parameter as `T | null` habitually pass
10
+ * `null` for "not given". Pi validates tool arguments against the declared schema, so a plain
11
+ * `Type.Optional(T)` rejects that `null` and the call fails. The helpers here treat `null` as an
12
+ * omitted optional parameter, before validation, without changing the schema the model sees.
13
+ *
14
+ * Scope, shared by every package so behaviour is identical:
15
+ *
16
+ * - A property is dropped only when its value is `null`, it is not `required`, and its own schema
17
+ * rejects `null`. Where `null` has a meaning (`Type.Union([T, Type.Null()])`, `Type.Unknown()`),
18
+ * it is kept. A schema that cannot be evaluated on its own, such as a dangling `$ref`, is kept.
19
+ * - Nested optional properties are normalized too: through `properties`, array `items` and
20
+ * `prefixItems`, `allOf`, and `anyOf`/`oneOf` branches. Models write `null` for a nested optional
21
+ * field (a breakpoint's `condition`) as readily as for a top-level one, and a `null` that the
22
+ * schema rejects can only ever fail the call. A union value that already satisfies a branch is
23
+ * never rewritten; otherwise the first branch whose normalized value validates is used.
24
+ * - Values of records (`additionalProperties`, `patternProperties`) are left alone: their entries
25
+ * are not optional parameters, and dropping one would silently change which keys the tool sees.
26
+ * - Required `null`s are never repaired; validation reports them as before.
27
+ */
28
+
29
+ function satisfies(schema: unknown, value: unknown): boolean {
30
+ try {
31
+ // A malformed schema throws and counts as unsatisfied.
32
+ return isRecord(schema) && Value.Check(schema, value);
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ /** Whether `null` is a legal value of `schema`; an unevaluable schema counts as legal, keeping `null`. */
39
+ function acceptsNull(schema: unknown): boolean {
40
+ // A reference cannot be resolved against its parent here, so it is kept, as Pi's own handling does.
41
+ if (!isRecord(schema) || typeof schema.$ref === "string") return true;
42
+ try {
43
+ // A malformed schema throws and keeps the null.
44
+ return Value.Check(schema, null);
45
+ } catch {
46
+ return true;
47
+ }
48
+ }
49
+
50
+ function normalizeUnion(branches: readonly unknown[], value: unknown): unknown {
51
+ if (branches.some((branch) => satisfies(branch, value))) return value;
52
+ for (const branch of branches) {
53
+ const candidate = normalize(branch, value);
54
+ if (candidate !== value && satisfies(branch, candidate)) return candidate;
55
+ }
56
+ return value;
57
+ }
58
+
59
+ function normalizeElements(schema: Entry, items: readonly unknown[]): unknown {
60
+ const { prefixItems, items: itemSchema } = schema;
61
+ const positional = Array.isArray(prefixItems)
62
+ ? prefixItems
63
+ : Array.isArray(itemSchema)
64
+ ? itemSchema
65
+ : [];
66
+ const rest = Array.isArray(itemSchema) ? schema.additionalItems : itemSchema;
67
+ let copy: unknown[] | undefined;
68
+ for (const [index, item] of items.entries()) {
69
+ const normalized = normalize(positional[index] ?? rest, item);
70
+ if (normalized === item) continue;
71
+ copy ??= [...items];
72
+ copy[index] = normalized;
73
+ }
74
+ return copy ?? items;
75
+ }
76
+
77
+ const DROP = Symbol("drop");
78
+
79
+ function normalizeProperty(propertySchema: unknown, current: unknown, required: boolean): unknown {
80
+ if (current === null && !required && !acceptsNull(propertySchema)) return DROP;
81
+ return normalize(propertySchema, current);
82
+ }
83
+
84
+ function normalizeProperties(schema: Entry, value: Entry): unknown {
85
+ const { properties } = schema;
86
+ if (!isRecord(properties)) return value;
87
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
88
+ let copy: Record<string, unknown> | undefined;
89
+ for (const [key, propertySchema] of Object.entries(properties)) {
90
+ if (!Object.hasOwn(value, key)) continue;
91
+ const current = value[key];
92
+ const normalized = normalizeProperty(propertySchema, current, required.has(key));
93
+ if (normalized === current) continue;
94
+ copy ??= { ...value };
95
+ if (normalized === DROP) delete copy[key];
96
+ else copy[key] = normalized;
97
+ }
98
+ return copy ?? value;
99
+ }
100
+
101
+ function normalize(schema: unknown, value: unknown): unknown {
102
+ if (!isRecord(schema)) return value;
103
+ let next = value;
104
+ if (Array.isArray(schema.allOf)) {
105
+ for (const member of schema.allOf) next = normalize(member, next);
106
+ }
107
+ for (const union of [schema.anyOf, schema.oneOf]) {
108
+ if (Array.isArray(union)) next = normalizeUnion(union, next);
109
+ }
110
+ if (Array.isArray(next)) return normalizeElements(schema, next);
111
+ return isRecord(next) ? normalizeProperties(schema, next) : next;
112
+ }
113
+
114
+ /**
115
+ * `args` with every `null` for an optional parameter of `schema` removed, as if the model had
116
+ * omitted it. Returns `args` itself when nothing changes and never mutates it.
117
+ */
118
+ export function omitNullOptionalArguments(schema: unknown, args: unknown): unknown {
119
+ return normalize(schema, args);
120
+ }
121
+
122
+ interface ToolWithParameters {
123
+ readonly parameters: unknown;
124
+ readonly prepareArguments?: (args: unknown) => unknown;
125
+ }
126
+
127
+ /**
128
+ * Make `tool` accept `null` for its optional parameters by normalizing the arguments in
129
+ * `prepareArguments`, which Pi runs before schema validation for model calls and for nested calls
130
+ * from codemode scripts alike. A `prepareArguments` the tool already has runs on the normalized
131
+ * arguments, so it sees optional parameters omitted rather than `null`.
132
+ *
133
+ * Only `prepareArguments` is added: the tool's schema, description, and every other field are
134
+ * unchanged, so the declaration the model sees (and any provider prompt-cache prefix) is stable.
135
+ */
136
+ export function acceptNullForOptionalArguments<TTool extends ToolWithParameters>(
137
+ tool: TTool,
138
+ ): TTool & { readonly prepareArguments: (args: unknown) => unknown } {
139
+ const { parameters, prepareArguments } = tool;
140
+ return {
141
+ ...tool,
142
+ prepareArguments: (args: unknown) => {
143
+ const normalized = omitNullOptionalArguments(parameters, args);
144
+ return prepareArguments === undefined ? normalized : prepareArguments(normalized);
145
+ },
146
+ };
147
+ }