pi-onlooker 0.1.0 → 0.1.2
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/CHANGELOG.md +12 -2
- package/README.md +3 -5
- package/extensions/index.ts +74 -60
- package/node_modules/pi-hl-utils/LICENSE +21 -0
- package/node_modules/pi-hl-utils/package.json +47 -0
- package/node_modules/pi-hl-utils/src/errors.ts +9 -0
- package/{src/utils → node_modules/pi-hl-utils/src}/layered-settings.ts +156 -53
- package/{src/utils → node_modules/pi-hl-utils/src}/null-optional-arguments.ts +20 -19
- package/{src/utils → node_modules/pi-hl-utils/src}/pi-agent-session-discovery.ts +3 -1
- package/node_modules/pi-hl-utils/src/record.ts +3 -0
- package/node_modules/pi-hl-utils/src/settings-command.ts +213 -0
- package/node_modules/pi-hl-utils/src/settings-menu.ts +477 -0
- package/package.json +9 -2
- package/src/onlooker-calibration.ts +1 -2
- package/src/onlooker-command.ts +9 -33
- package/src/onlooker-contract.ts +0 -1
- package/src/onlooker-evidence.ts +3 -4
- package/src/onlooker-menu.ts +89 -227
- package/src/onlooker-observer.ts +12 -11
- package/src/onlooker-rendering.ts +17 -17
- package/src/onlooker-settings.ts +5 -53
- package/src/protected-tools.ts +2 -1
- package/src/utils/settings-command.ts +0 -92
- package/src/utils/settings-menu.ts +0 -258
- /package/{src/utils → node_modules/pi-hl-utils/src}/evidence.ts +0 -0
- /package/{src/utils → node_modules/pi-hl-utils/src}/expand-on-click.ts +0 -0
- /package/{src/utils → node_modules/pi-hl-utils/src}/token-calibration.ts +0 -0
- /package/{src/utils → node_modules/pi-hl-utils/src}/ui.ts +0 -0
|
@@ -1,8 +1,15 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
1
|
+
import {
|
|
2
|
+
getAgentDir,
|
|
3
|
+
SettingsManager,
|
|
4
|
+
type ExtensionAPI,
|
|
5
|
+
type ExtensionContext,
|
|
6
|
+
type SessionManager,
|
|
7
|
+
} from "@earendil-works/pi-coding-agent";
|
|
3
8
|
import { Type, type Static, type TObject } from "typebox";
|
|
4
9
|
import { Value } from "typebox/value";
|
|
5
10
|
|
|
11
|
+
import { isRecord } from "./record.ts";
|
|
12
|
+
|
|
6
13
|
/** Native layer an authored option is written to or replayed from. */
|
|
7
14
|
export type LayeredSettingScope = "session" | "global" | "project";
|
|
8
15
|
/** Native layer supplying an effective option. */
|
|
@@ -31,7 +38,9 @@ export type LayeredSettingMerges<Config> = {
|
|
|
31
38
|
[Key in keyof Config]?: LayeredSettingMerge<Config, Key>;
|
|
32
39
|
};
|
|
33
40
|
/** One layer's authored options, typed as the config values they set; `undefined` inherits. */
|
|
34
|
-
export type LayeredSettingLayer<Config> = {
|
|
41
|
+
export type LayeredSettingLayer<Config> = {
|
|
42
|
+
[Key in keyof Config]?: Config[Key] | undefined;
|
|
43
|
+
};
|
|
35
44
|
|
|
36
45
|
/** Input for {@link resolveLayeredOptions}. */
|
|
37
46
|
export interface ResolveLayeredOptionsInput<Config> {
|
|
@@ -80,14 +89,6 @@ export function resolveLayeredOptions<Config extends object>(
|
|
|
80
89
|
return { settings, sources };
|
|
81
90
|
}
|
|
82
91
|
|
|
83
|
-
/** A JSON object as stored in Pi's settings documents. */
|
|
84
|
-
export type SettingsJsonObject = Record<string, JsonValue>;
|
|
85
|
-
|
|
86
|
-
function isJsonObject(value: unknown): value is SettingsJsonObject {
|
|
87
|
-
// JSON.parse already established JSON data; distinguish object roots and namespaces from primitives and arrays.
|
|
88
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
92
|
/** Why {@link rewriteNamespaceDocument} refused a stored settings document. */
|
|
92
93
|
export type InvalidSettingsDocument = "malformed" | "root" | "namespace";
|
|
93
94
|
|
|
@@ -96,8 +97,10 @@ export interface RewriteNamespaceDocumentInput {
|
|
|
96
97
|
/** Current file text, or `undefined` when the file is absent. */
|
|
97
98
|
current: string | undefined;
|
|
98
99
|
namespace: string;
|
|
100
|
+
/** Keep an empty namespace instead of removing it. */
|
|
101
|
+
keepEmpty?: boolean;
|
|
99
102
|
/** Receives a copy of the stored namespace options and returns its replacement. */
|
|
100
|
-
update: (options:
|
|
103
|
+
update: (options: Record<string, unknown>) => Record<string, unknown>;
|
|
101
104
|
/** Builds the error thrown instead of overwriting a document that cannot be safely rewritten. */
|
|
102
105
|
invalid: (reason: InvalidSettingsDocument, cause: Error | undefined) => Error;
|
|
103
106
|
}
|
|
@@ -105,7 +108,8 @@ export interface RewriteNamespaceDocumentInput {
|
|
|
105
108
|
/**
|
|
106
109
|
* Rewrite one namespace of a Pi settings document, preserving every other setting. Strips a
|
|
107
110
|
* leading BOM, refuses documents whose root or namespace is not an object, and removes an empty
|
|
108
|
-
* namespace. Transport-independent: callers run it inside whichever
|
|
111
|
+
* namespace unless `keepEmpty` is set. Transport-independent: callers run it inside whichever
|
|
112
|
+
* lock and writer they use.
|
|
109
113
|
* @returns The replacement file text.
|
|
110
114
|
*/
|
|
111
115
|
export function rewriteNamespaceDocument(input: RewriteNamespaceDocumentInput): string {
|
|
@@ -115,11 +119,11 @@ export function rewriteNamespaceDocument(input: RewriteNamespaceDocumentInput):
|
|
|
115
119
|
} catch (cause) {
|
|
116
120
|
throw input.invalid("malformed", cause instanceof Error ? cause : undefined);
|
|
117
121
|
}
|
|
118
|
-
if (!
|
|
122
|
+
if (!isRecord(parsed)) throw input.invalid("root", undefined);
|
|
119
123
|
const stored = parsed[input.namespace];
|
|
120
|
-
if (stored !== undefined && !
|
|
124
|
+
if (stored !== undefined && !isRecord(stored)) throw input.invalid("namespace", undefined);
|
|
121
125
|
const updated = input.update({ ...stored });
|
|
122
|
-
if (Object.keys(updated).length === 0) delete parsed[input.namespace];
|
|
126
|
+
if (Object.keys(updated).length === 0 && !input.keepEmpty) delete parsed[input.namespace];
|
|
123
127
|
else parsed[input.namespace] = updated;
|
|
124
128
|
return `${JSON.stringify(parsed, null, 2)}\n`;
|
|
125
129
|
}
|
|
@@ -134,9 +138,9 @@ export interface LayeredSettingsDefinition<
|
|
|
134
138
|
Merge extends LayeredSettingMerges<Config> = {},
|
|
135
139
|
Entry extends string | undefined = undefined,
|
|
136
140
|
> {
|
|
137
|
-
/** Key under which authored options live in Pi's settings documents, e.g. `
|
|
141
|
+
/** Key under which authored options live in Pi's settings documents, e.g. `my-extension`. */
|
|
138
142
|
namespace: string;
|
|
139
|
-
/** Name used in error messages, e.g. `
|
|
143
|
+
/** Name used in error messages, e.g. `My extension`. */
|
|
140
144
|
label: string;
|
|
141
145
|
/** Schema of the authored options; every property must be optional so absent values inherit. */
|
|
142
146
|
schema: S;
|
|
@@ -145,6 +149,8 @@ export interface LayeredSettingsDefinition<
|
|
|
145
149
|
sessionEntryType?: Entry;
|
|
146
150
|
/** Per-key merge hooks for keys that merge across layers instead of replacing. */
|
|
147
151
|
merge?: Merge;
|
|
152
|
+
/** Keep the namespace in a settings document after its last option is removed. */
|
|
153
|
+
keepEmptyNamespace?: boolean;
|
|
148
154
|
}
|
|
149
155
|
|
|
150
156
|
/**
|
|
@@ -165,6 +171,19 @@ type LayeredSettingsConfigCheck<Options, Config> = [
|
|
|
165
171
|
? unknown
|
|
166
172
|
: { configMismatch: LayeredSettingsConfigMismatch<Options, Config> };
|
|
167
173
|
|
|
174
|
+
/** The settings and session a layered read or write runs against. */
|
|
175
|
+
export interface LayeredSettingsSession {
|
|
176
|
+
settingsManager: SettingsManager;
|
|
177
|
+
sessionManager: Pick<SessionManager, "getBranch">;
|
|
178
|
+
}
|
|
179
|
+
/** Effective settings that survive unreadable layers; `invalid` lists each layer left out. */
|
|
180
|
+
export interface LenientLayeredSettings<Options, Config> extends ResolvedLayeredSettings<Config> {
|
|
181
|
+
/** Usable authored options per scope; an unreadable scope or session entry authors nothing. */
|
|
182
|
+
authored: { global: Options; project: Options; session: Options };
|
|
183
|
+
/** Errors of the layers left out, in the order global, project, session. */
|
|
184
|
+
invalid: Error[];
|
|
185
|
+
}
|
|
186
|
+
|
|
168
187
|
/** Settings operations for one namespace; `Options` is `Static<S>`. */
|
|
169
188
|
export interface LayeredSettings<S extends TObject, Config extends object> {
|
|
170
189
|
/** Reject inherited or unknown property names before applying an authored change. */
|
|
@@ -178,10 +197,7 @@ export interface LayeredSettings<S extends TObject, Config extends object> {
|
|
|
178
197
|
readLayers(manager: SettingsManager): LayeredSettingsLayers<Static<S>>;
|
|
179
198
|
/** Resolve stored scopes without changing Pi's effective runtime overrides. */
|
|
180
199
|
readSettings(
|
|
181
|
-
session:
|
|
182
|
-
settingsManager: SettingsManager;
|
|
183
|
-
sessionManager: Pick<SessionManager, "getBranch">;
|
|
184
|
-
},
|
|
200
|
+
session: LayeredSettingsSession,
|
|
185
201
|
authored?: LayeredSettingsLayers<Static<S>>,
|
|
186
202
|
): ResolvedLayeredSettings<Config>;
|
|
187
203
|
/** Use Pi's actual backend: its generic storage API is not exported. */
|
|
@@ -199,6 +215,16 @@ export interface SessionLayeredSettings<
|
|
|
199
215
|
> extends LayeredSettings<S, Config> {
|
|
200
216
|
/** Replay only the selected branch's last complete override snapshot. */
|
|
201
217
|
readOverrides(manager: Pick<SessionManager, "getBranch">): Static<S>;
|
|
218
|
+
/** Like `readSettings`, but an unreadable layer is left out and listed in `invalid`. */
|
|
219
|
+
readSettingsLeniently(session: LayeredSettingsSession): LenientLayeredSettings<Static<S>, Config>;
|
|
220
|
+
/** Write one change; a session change is appended to the session as an entry through `pi`. */
|
|
221
|
+
writeChange(
|
|
222
|
+
pi: Pick<ExtensionAPI, "appendEntry">,
|
|
223
|
+
session: LayeredSettingsSession,
|
|
224
|
+
scope: LayeredSettingScope,
|
|
225
|
+
change: LayeredSettingChange<Static<S>>,
|
|
226
|
+
isCurrent: () => boolean,
|
|
227
|
+
): Promise<Static<S> | undefined>;
|
|
202
228
|
}
|
|
203
229
|
|
|
204
230
|
const optionalText = Type.Union([Type.String(), Type.Undefined()]);
|
|
@@ -233,7 +259,9 @@ export function defineLayeredSettings<
|
|
|
233
259
|
Merge extends LayeredSettingMerges<Config> = {},
|
|
234
260
|
>(
|
|
235
261
|
definition: LayeredSettingsDefinition<S, Config, Merge, string> &
|
|
236
|
-
LayeredSettingsConfigCheck<Static<S>, Config> & {
|
|
262
|
+
LayeredSettingsConfigCheck<Static<S>, Config> & {
|
|
263
|
+
sessionEntryType: string;
|
|
264
|
+
},
|
|
237
265
|
): SessionLayeredSettings<S, Config>;
|
|
238
266
|
export function defineLayeredSettings<
|
|
239
267
|
S extends TObject,
|
|
@@ -247,7 +275,8 @@ export function defineLayeredSettings<
|
|
|
247
275
|
type OptionKey = keyof Options & keyof Config & string;
|
|
248
276
|
type Layers = LayeredSettingsLayers<Options>;
|
|
249
277
|
type Change = LayeredSettingChange<Options>;
|
|
250
|
-
const { namespace, label, schema, defaults, sessionEntryType, merge } =
|
|
278
|
+
const { namespace, label, schema, defaults, sessionEntryType, merge, keepEmptyNamespace } =
|
|
279
|
+
definition;
|
|
251
280
|
if (!Value.Check(schema, {}))
|
|
252
281
|
throw new Error(`${label} settings schema must make every option optional`);
|
|
253
282
|
const keySchema = Type.KeyOf(schema);
|
|
@@ -260,17 +289,9 @@ export function defineLayeredSettings<
|
|
|
260
289
|
return Value.Check(keySchema, input);
|
|
261
290
|
}
|
|
262
291
|
// Native settings contain arbitrary authored JSON; this guard validates it with the option schema before use.
|
|
263
|
-
function isOptions(value: unknown): value is Options {
|
|
264
|
-
return Value.Check(schema, value);
|
|
265
|
-
}
|
|
266
|
-
// Validated options hold config values: the definition's config check proves `Options` assignable to this layer type.
|
|
267
|
-
function isConfigLayer(value: unknown): value is LayeredSettingLayer<Config> {
|
|
292
|
+
function isOptions(value: unknown): value is Options & LayeredSettingLayer<Config> {
|
|
268
293
|
return Value.Check(schema, value);
|
|
269
294
|
}
|
|
270
|
-
function configLayer(options: Options): LayeredSettingLayer<Config> {
|
|
271
|
-
if (!isConfigLayer(options)) throw new Error(`Invalid ${label} settings`);
|
|
272
|
-
return options;
|
|
273
|
-
}
|
|
274
295
|
// Session entry data is arbitrary JSON; this guard validates the versioned envelope before replay.
|
|
275
296
|
function isSessionData(value: unknown): value is { version: 1; overrides: Options } {
|
|
276
297
|
return Value.Check(sessionSchema, value);
|
|
@@ -282,19 +303,29 @@ export function defineLayeredSettings<
|
|
|
282
303
|
}
|
|
283
304
|
const optionKeys = Object.keys(schema.properties).map(optionKey);
|
|
284
305
|
|
|
285
|
-
|
|
286
|
-
function
|
|
287
|
-
const empty = {};
|
|
306
|
+
// Every option is optional, so the empty layer must pass the schema.
|
|
307
|
+
function checkedEmptyOptions(): Options {
|
|
308
|
+
const empty: unknown = {};
|
|
288
309
|
if (!isOptions(empty))
|
|
289
310
|
throw new Error(`${label} settings schema must make every option optional`);
|
|
290
311
|
return empty;
|
|
291
312
|
}
|
|
292
313
|
|
|
314
|
+
const empty = checkedEmptyOptions();
|
|
315
|
+
/** The options of a layer that authored nothing. */
|
|
316
|
+
function noOptions(): Options {
|
|
317
|
+
return structuredClone(empty);
|
|
318
|
+
}
|
|
319
|
+
|
|
293
320
|
// Native settings contain arbitrary authored JSON; the option schema validates it before use. SDK command tests exercise the boundary.
|
|
294
321
|
function parseOptions(value: unknown, source: LayeredSettingScope): Options {
|
|
295
322
|
if (value === undefined) return noOptions();
|
|
296
323
|
if (!isOptions(value)) {
|
|
297
324
|
const issue = Value.Errors(schema, value)[0];
|
|
325
|
+
if (issue?.schemaPath === "#/additionalProperties")
|
|
326
|
+
throw new Error(
|
|
327
|
+
`Invalid ${source} ${label} settings: unknown option ${issue.instancePath.slice(1)}`,
|
|
328
|
+
);
|
|
298
329
|
throw new Error(
|
|
299
330
|
`Invalid ${source} ${label} settings${issue?.instancePath ?? ""}: ${issue?.message ?? "invalid options"}`,
|
|
300
331
|
);
|
|
@@ -321,9 +352,7 @@ export function defineLayeredSettings<
|
|
|
321
352
|
const document =
|
|
322
353
|
scope === "global" ? manager.getGlobalSettings() : manager.getProjectSettings();
|
|
323
354
|
layers[scope] = parseOptions(
|
|
324
|
-
namespace
|
|
325
|
-
? Object.getOwnPropertyDescriptor(document, namespace)?.value
|
|
326
|
-
: undefined,
|
|
355
|
+
Object.getOwnPropertyDescriptor(document, namespace)?.value,
|
|
327
356
|
scope,
|
|
328
357
|
);
|
|
329
358
|
} catch (cause) {
|
|
@@ -335,27 +364,24 @@ export function defineLayeredSettings<
|
|
|
335
364
|
|
|
336
365
|
/** Resolve stored scopes without changing Pi's effective runtime overrides. */
|
|
337
366
|
function readSettings(
|
|
338
|
-
session:
|
|
339
|
-
settingsManager: SettingsManager;
|
|
340
|
-
sessionManager: Pick<SessionManager, "getBranch">;
|
|
341
|
-
},
|
|
367
|
+
session: LayeredSettingsSession,
|
|
342
368
|
authored = readLayers(session.settingsManager),
|
|
343
369
|
) {
|
|
344
370
|
if (authored.global instanceof Error) throw authored.global;
|
|
345
371
|
const trusted = session.settingsManager.isProjectTrusted();
|
|
346
372
|
if (trusted && authored.project instanceof Error) throw authored.project;
|
|
347
373
|
const layers: (readonly [LayeredSettingScope, LayeredSettingLayer<Config>])[] = [
|
|
348
|
-
["global",
|
|
349
|
-
[
|
|
350
|
-
"project",
|
|
351
|
-
configLayer(
|
|
352
|
-
trusted && !(authored.project instanceof Error) ? authored.project : noOptions(),
|
|
353
|
-
),
|
|
354
|
-
],
|
|
374
|
+
["global", authored.global],
|
|
375
|
+
["project", trusted && !(authored.project instanceof Error) ? authored.project : noOptions()],
|
|
355
376
|
];
|
|
356
377
|
if (sessionEntryType !== undefined)
|
|
357
|
-
layers.push(["session",
|
|
358
|
-
return resolveLayeredOptions<Config>({
|
|
378
|
+
layers.push(["session", readOverrides(session.sessionManager)]);
|
|
379
|
+
return resolveLayeredOptions<Config>({
|
|
380
|
+
defaults,
|
|
381
|
+
optionKeys,
|
|
382
|
+
layers,
|
|
383
|
+
merge,
|
|
384
|
+
});
|
|
359
385
|
}
|
|
360
386
|
|
|
361
387
|
/** Use Pi's actual backend: its generic storage API is not exported. */
|
|
@@ -382,6 +408,7 @@ export function defineLayeredSettings<
|
|
|
382
408
|
rewriteNamespaceDocument({
|
|
383
409
|
current,
|
|
384
410
|
namespace,
|
|
411
|
+
keepEmpty: keepEmptyNamespace === true,
|
|
385
412
|
invalid: (reason, cause) =>
|
|
386
413
|
reason === "malformed" && cause
|
|
387
414
|
? cause
|
|
@@ -406,5 +433,81 @@ export function defineLayeredSettings<
|
|
|
406
433
|
readSettings,
|
|
407
434
|
writeSettings,
|
|
408
435
|
};
|
|
409
|
-
|
|
436
|
+
if (sessionEntryType === undefined) return settings;
|
|
437
|
+
const sessionEntry = sessionEntryType;
|
|
438
|
+
|
|
439
|
+
/** Like `readSettings`; an unreadable layer or session entry is left out, and its error kept. */
|
|
440
|
+
function readSettingsLeniently(
|
|
441
|
+
session: LayeredSettingsSession,
|
|
442
|
+
): LenientLayeredSettings<Options, Config> {
|
|
443
|
+
// Pi reads an unloadable file as empty, so only its recorded error shows the problem.
|
|
444
|
+
const invalid: Error[] = session.settingsManager.drainErrors().map((entry) => entry.error);
|
|
445
|
+
const layers = readLayers(session.settingsManager);
|
|
446
|
+
const usable = (layer: Options | Error): Options => {
|
|
447
|
+
if (!(layer instanceof Error)) return layer;
|
|
448
|
+
invalid.push(layer);
|
|
449
|
+
return noOptions();
|
|
450
|
+
};
|
|
451
|
+
const authored = {
|
|
452
|
+
global: usable(layers.global),
|
|
453
|
+
project: usable(layers.project),
|
|
454
|
+
};
|
|
455
|
+
let sessionManager = session.sessionManager;
|
|
456
|
+
let overrides = noOptions();
|
|
457
|
+
try {
|
|
458
|
+
overrides = readOverrides(sessionManager);
|
|
459
|
+
} catch (cause) {
|
|
460
|
+
invalid.push(cause instanceof Error ? cause : new Error(String(cause)));
|
|
461
|
+
// An unreadable session entry counts as no session overrides.
|
|
462
|
+
sessionManager = { getBranch: () => [] };
|
|
463
|
+
}
|
|
464
|
+
const resolved = readSettings(
|
|
465
|
+
{ settingsManager: session.settingsManager, sessionManager },
|
|
466
|
+
authored,
|
|
467
|
+
);
|
|
468
|
+
return {
|
|
469
|
+
...resolved,
|
|
470
|
+
authored: { ...authored, session: overrides },
|
|
471
|
+
invalid,
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** Write one change unless the session changed first; a session change becomes the entry that replays it. */
|
|
476
|
+
async function writeChange(
|
|
477
|
+
pi: Pick<ExtensionAPI, "appendEntry">,
|
|
478
|
+
session: LayeredSettingsSession,
|
|
479
|
+
scope: LayeredSettingScope,
|
|
480
|
+
change: LayeredSettingChange<Options>,
|
|
481
|
+
isCurrent: () => boolean,
|
|
482
|
+
): Promise<Options | undefined> {
|
|
483
|
+
if (!isCurrent()) return undefined;
|
|
484
|
+
if (scope !== "session")
|
|
485
|
+
return writeSettings(session.settingsManager, scope, change, isCurrent);
|
|
486
|
+
const overrides = readOverrides(session.sessionManager);
|
|
487
|
+
if (change.action === "inherit") Reflect.deleteProperty(overrides, change.key);
|
|
488
|
+
else Object.assign(overrides, change.patch);
|
|
489
|
+
pi.appendEntry(sessionEntry, { version: 1, overrides });
|
|
490
|
+
return overrides;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return { ...settings, readOverrides, readSettingsLeniently, writeChange };
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** The settings and session of a command or menu on `ctx`; the project file is read only when trusted. */
|
|
497
|
+
export function layeredSettingsSession(
|
|
498
|
+
ctx: Pick<ExtensionContext, "cwd" | "isProjectTrusted" | "sessionManager">,
|
|
499
|
+
): LayeredSettingsSession {
|
|
500
|
+
return {
|
|
501
|
+
settingsManager: SettingsManager.create(ctx.cwd, getAgentDir(), {
|
|
502
|
+
projectTrusted: ctx.isProjectTrusted(),
|
|
503
|
+
}),
|
|
504
|
+
sessionManager: ctx.sessionManager,
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Scopes a settings menu offers: the project scope only while the project is trusted. */
|
|
509
|
+
export function layeredMenuScopes(
|
|
510
|
+
manager: Pick<SettingsManager, "isProjectTrusted">,
|
|
511
|
+
): LayeredSettingScope[] {
|
|
512
|
+
return manager.isProjectTrusted() ? ["session", "project", "global"] : ["session", "global"];
|
|
410
513
|
}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
|
-
// Model tool arguments and JSON Schemas are untyped JSON by nature. Every read narrows with
|
|
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
2
|
import { Value } from "typebox/value";
|
|
3
3
|
|
|
4
|
+
import { isRecord } from "./record.js";
|
|
5
|
+
|
|
6
|
+
type Entry = Readonly<Record<string, unknown>>;
|
|
7
|
+
|
|
4
8
|
/**
|
|
5
9
|
* Models trained on tool schemas that declare an optional parameter as `T | null` habitually pass
|
|
6
10
|
* `null` for "not given". Pi validates tool arguments against the declared schema, so a plain
|
|
@@ -22,16 +26,10 @@ import { Value } from "typebox/value";
|
|
|
22
26
|
* - Required `null`s are never repaired; validation reports them as before.
|
|
23
27
|
*/
|
|
24
28
|
|
|
25
|
-
type Entry = Readonly<Record<string, unknown>>;
|
|
26
|
-
|
|
27
|
-
function isEntry(value: unknown): value is Entry {
|
|
28
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
29
|
function satisfies(schema: unknown, value: unknown): boolean {
|
|
32
30
|
try {
|
|
33
31
|
// A malformed schema throws and counts as unsatisfied.
|
|
34
|
-
return
|
|
32
|
+
return isRecord(schema) && Value.Check(schema, value);
|
|
35
33
|
} catch {
|
|
36
34
|
return false;
|
|
37
35
|
}
|
|
@@ -40,7 +38,7 @@ function satisfies(schema: unknown, value: unknown): boolean {
|
|
|
40
38
|
/** Whether `null` is a legal value of `schema`; an unevaluable schema counts as legal, keeping `null`. */
|
|
41
39
|
function acceptsNull(schema: unknown): boolean {
|
|
42
40
|
// A reference cannot be resolved against its parent here, so it is kept, as Pi's own handling does.
|
|
43
|
-
if (!
|
|
41
|
+
if (!isRecord(schema) || typeof schema.$ref === "string") return true;
|
|
44
42
|
try {
|
|
45
43
|
// A malformed schema throws and keeps the null.
|
|
46
44
|
return Value.Check(schema, null);
|
|
@@ -76,29 +74,32 @@ function normalizeElements(schema: Entry, items: readonly unknown[]): unknown {
|
|
|
76
74
|
return copy ?? items;
|
|
77
75
|
}
|
|
78
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
|
+
|
|
79
84
|
function normalizeProperties(schema: Entry, value: Entry): unknown {
|
|
80
85
|
const { properties } = schema;
|
|
81
|
-
if (!
|
|
86
|
+
if (!isRecord(properties)) return value;
|
|
82
87
|
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
|
|
83
88
|
let copy: Record<string, unknown> | undefined;
|
|
84
89
|
for (const [key, propertySchema] of Object.entries(properties)) {
|
|
85
90
|
if (!Object.hasOwn(value, key)) continue;
|
|
86
91
|
const current = value[key];
|
|
87
|
-
|
|
88
|
-
copy ??= { ...value };
|
|
89
|
-
delete copy[key];
|
|
90
|
-
continue;
|
|
91
|
-
}
|
|
92
|
-
const normalized = normalize(propertySchema, current);
|
|
92
|
+
const normalized = normalizeProperty(propertySchema, current, required.has(key));
|
|
93
93
|
if (normalized === current) continue;
|
|
94
94
|
copy ??= { ...value };
|
|
95
|
-
copy[key]
|
|
95
|
+
if (normalized === DROP) delete copy[key];
|
|
96
|
+
else copy[key] = normalized;
|
|
96
97
|
}
|
|
97
98
|
return copy ?? value;
|
|
98
99
|
}
|
|
99
100
|
|
|
100
101
|
function normalize(schema: unknown, value: unknown): unknown {
|
|
101
|
-
if (!
|
|
102
|
+
if (!isRecord(schema)) return value;
|
|
102
103
|
let next = value;
|
|
103
104
|
if (Array.isArray(schema.allOf)) {
|
|
104
105
|
for (const member of schema.allOf) next = normalize(member, next);
|
|
@@ -107,7 +108,7 @@ function normalize(schema: unknown, value: unknown): unknown {
|
|
|
107
108
|
if (Array.isArray(union)) next = normalizeUnion(union, next);
|
|
108
109
|
}
|
|
109
110
|
if (Array.isArray(next)) return normalizeElements(schema, next);
|
|
110
|
-
return
|
|
111
|
+
return isRecord(next) ? normalizeProperties(schema, next) : next;
|
|
111
112
|
}
|
|
112
113
|
|
|
113
114
|
/**
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { AgentSession, ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
|
|
3
|
+
import { errorText } from "./errors.ts";
|
|
4
|
+
|
|
3
5
|
/** Native session identity only; callers validate the capabilities they require. */
|
|
4
6
|
export type DiscoverPiAgentSessionResult =
|
|
5
7
|
| { readonly ok: true; readonly session: AgentSession }
|
|
@@ -32,7 +34,7 @@ export function discoverPiAgentSession(
|
|
|
32
34
|
} catch (cause) {
|
|
33
35
|
return {
|
|
34
36
|
ok: false,
|
|
35
|
-
warning: `getAllTools capture failed: ${
|
|
37
|
+
warning: `getAllTools capture failed: ${errorText(cause)}`,
|
|
36
38
|
};
|
|
37
39
|
} finally {
|
|
38
40
|
Object.defineProperty(prototype, "getAllTools", descriptor);
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionAPI,
|
|
3
|
+
ExtensionCommandContext,
|
|
4
|
+
ExtensionContext,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import type { AutocompleteItem } from "@earendil-works/pi-tui";
|
|
7
|
+
|
|
8
|
+
import type { LayeredSettingScope } from "./layered-settings.js";
|
|
9
|
+
|
|
10
|
+
/** One parsed settings command. */
|
|
11
|
+
export type SettingsCommand<Options, Key extends string> =
|
|
12
|
+
| { action: "menu" }
|
|
13
|
+
| { action: "status" }
|
|
14
|
+
| { action: "set"; scope: LayeredSettingScope; key: Key; patch: Options }
|
|
15
|
+
| { action: "inherit"; scope: LayeredSettingScope; key: Key };
|
|
16
|
+
|
|
17
|
+
/** What a settings command supplies to {@link parseSettingsCommand}. */
|
|
18
|
+
export interface SettingsCommandSpec<Options, Key extends string> {
|
|
19
|
+
/** Error message for a malformed command or a scope flag on `status` or the bare menu. */
|
|
20
|
+
usage: string;
|
|
21
|
+
/** Validate a typed option key, throwing for an unknown one. */
|
|
22
|
+
optionKey: (text: string) => Key;
|
|
23
|
+
/** Validate `{ [key]: value }` for one scope, throwing for an invalid value. */
|
|
24
|
+
// The value is parsed user JSON; the spec's option schema validates it before use.
|
|
25
|
+
parseOptions: (value: unknown, scope: LayeredSettingScope) => Options;
|
|
26
|
+
/** The key and patch that `on` (true) and `off` (false) set; `inherit` alone clears this key. */
|
|
27
|
+
toggle: (enabled: boolean) => { key: Key; patch: Options };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Parse `[on|off|status|inherit [key]|set <key> <JSON>] [--global|--project]`. Blank input opens the menu. A trailing flag selects the scope, `session` by
|
|
32
|
+
* default. Validation errors come from the spec; a malformed command throws `spec.usage`.
|
|
33
|
+
*/
|
|
34
|
+
export function parseSettingsCommand<Options, Key extends string>(
|
|
35
|
+
input: string,
|
|
36
|
+
spec: SettingsCommandSpec<Options, Key>,
|
|
37
|
+
): SettingsCommand<Options, Key> {
|
|
38
|
+
const { text, scope, flagged } = splitScope(input);
|
|
39
|
+
if (text === "" || text === "status") {
|
|
40
|
+
if (flagged) throw new Error(spec.usage);
|
|
41
|
+
return text === "" ? { action: "menu" } : { action: "status" };
|
|
42
|
+
}
|
|
43
|
+
if (text === "on" || text === "off")
|
|
44
|
+
return { action: "set", scope, ...spec.toggle(text === "on") };
|
|
45
|
+
const inherit = /^inherit(?:\s+(\S+))?$/.exec(text);
|
|
46
|
+
if (inherit)
|
|
47
|
+
return {
|
|
48
|
+
action: "inherit",
|
|
49
|
+
scope,
|
|
50
|
+
key: spec.optionKey(inherit[1] ?? spec.toggle(true).key),
|
|
51
|
+
};
|
|
52
|
+
return parseSet(text, scope, spec);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function splitScope(input: string): {
|
|
56
|
+
text: string;
|
|
57
|
+
scope: LayeredSettingScope;
|
|
58
|
+
flagged: boolean;
|
|
59
|
+
} {
|
|
60
|
+
const trimmed = input.trim();
|
|
61
|
+
for (const scope of ["global", "project"] as const) {
|
|
62
|
+
const before = trimmed.slice(0, -`--${scope}`.length);
|
|
63
|
+
const text = before.trimEnd();
|
|
64
|
+
if (trimmed.endsWith(`--${scope}`) && text.length < before.length)
|
|
65
|
+
return { text, scope, flagged: true };
|
|
66
|
+
}
|
|
67
|
+
return { text: trimmed, scope: "session", flagged: false };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function parseSet<Options, Key extends string>(
|
|
71
|
+
text: string,
|
|
72
|
+
scope: LayeredSettingScope,
|
|
73
|
+
spec: SettingsCommandSpec<Options, Key>,
|
|
74
|
+
): SettingsCommand<Options, Key> {
|
|
75
|
+
const set = /^set\s+(\S+)\s+(\S[\s\S]*)$/.exec(text);
|
|
76
|
+
if (!set?.[1] || !set[2]) throw new Error(spec.usage);
|
|
77
|
+
const key = spec.optionKey(set[1]);
|
|
78
|
+
let value: unknown;
|
|
79
|
+
try {
|
|
80
|
+
value = JSON.parse(set[2]);
|
|
81
|
+
} catch (cause) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`${key} value is not JSON; quote text, for example "request" or "provider/model-id"`,
|
|
84
|
+
{ cause },
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
const patch = spec.parseOptions({ [key]: value }, scope);
|
|
88
|
+
return { action: "set", scope, key, patch };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** What a settings command supplies to {@link completeSettingsCommandArguments}. */
|
|
92
|
+
export interface SettingsCompletionSpec {
|
|
93
|
+
/** Option keys completed after `set ` and `inherit `. */
|
|
94
|
+
optionKeys: readonly string[];
|
|
95
|
+
/** The command's parser, used to offer a scope flag once the command is complete. */
|
|
96
|
+
parse: (text: string) => { action: string; scope?: LayeredSettingScope };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Native command completion values replace the entire argument prefix. */
|
|
100
|
+
export function completeSettingsCommandArguments(
|
|
101
|
+
prefix: string,
|
|
102
|
+
spec: SettingsCompletionSpec,
|
|
103
|
+
): AutocompleteItem[] {
|
|
104
|
+
const candidates = ["on", "off", "status", "inherit", "set"];
|
|
105
|
+
const keyPrefix = /^((?:set|inherit)\s+)\S*$/.exec(prefix)?.[1];
|
|
106
|
+
if (keyPrefix) candidates.push(...spec.optionKeys.map((key) => `${keyPrefix}${key}`));
|
|
107
|
+
const scopePrefix = beforeLastWord(prefix);
|
|
108
|
+
if (scopePrefix !== undefined) {
|
|
109
|
+
try {
|
|
110
|
+
if (spec.parse(scopePrefix).scope === "session")
|
|
111
|
+
candidates.push(`${scopePrefix}--global`, `${scopePrefix}--project`);
|
|
112
|
+
} catch {
|
|
113
|
+
// Incomplete commands and JSON values cannot accept a scope yet.
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return candidates
|
|
117
|
+
.filter((value) => value.startsWith(prefix))
|
|
118
|
+
.map((value) => ({ value, label: value }));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The prefix up to its last whitespace, when the word after it is empty or a flag. */
|
|
122
|
+
function beforeLastWord(prefix: string): string | undefined {
|
|
123
|
+
let end = prefix.length;
|
|
124
|
+
while (end > 0 && !/\s/.test(prefix.charAt(end - 1))) end--;
|
|
125
|
+
const word = prefix.slice(end);
|
|
126
|
+
return end > 0 && (word === "" || word.startsWith("--")) ? prefix.slice(0, end) : undefined;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The commands that apply one validated change: `set` and `inherit`. */
|
|
130
|
+
export type SettingsChangeCommand<Options, Key extends string> = Extract<
|
|
131
|
+
SettingsCommand<Options, Key>,
|
|
132
|
+
{ action: "set" | "inherit" }
|
|
133
|
+
>;
|
|
134
|
+
|
|
135
|
+
/** What one invocation of a settings command does; each extension owns its status text and errors. */
|
|
136
|
+
export interface SettingsCommandInvocation<Options, Key extends string> {
|
|
137
|
+
/** Throws when the command cannot run; it runs before the command is parsed. */
|
|
138
|
+
check?: () => void;
|
|
139
|
+
/** Shows the status: the `status` command, and the menu outside a TUI. */
|
|
140
|
+
status: () => void | Promise<void>;
|
|
141
|
+
/** Opens the settings menu in a TUI. */
|
|
142
|
+
menu: () => Promise<void>;
|
|
143
|
+
/** Applies one `set` or `inherit`. */
|
|
144
|
+
change: (command: SettingsChangeCommand<Options, Key>) => Promise<void>;
|
|
145
|
+
/** Receives a failure of the check, the parse or a hook; without it the failure propagates to Pi. */
|
|
146
|
+
fail?: (cause: unknown) => void;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** How a settings command parses, and what each invocation of it starts. */
|
|
150
|
+
export interface SettingsCommandDispatch<
|
|
151
|
+
Options,
|
|
152
|
+
Key extends string,
|
|
153
|
+
Context extends Pick<ExtensionContext, "mode">,
|
|
154
|
+
> {
|
|
155
|
+
parse: SettingsCommandSpec<Options, Key>;
|
|
156
|
+
/** Starts one invocation; undefined when there is nothing to run. */
|
|
157
|
+
start: (ctx: Context) => SettingsCommandInvocation<Options, Key> | undefined;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** What Pi needs to register one settings command. */
|
|
161
|
+
export interface SettingsCommandRegistration<
|
|
162
|
+
Options,
|
|
163
|
+
Key extends string,
|
|
164
|
+
> extends SettingsCommandDispatch<Options, Key, ExtensionCommandContext> {
|
|
165
|
+
name: string;
|
|
166
|
+
description: string;
|
|
167
|
+
/** Option keys completed after `set` and `inherit`. */
|
|
168
|
+
optionKeys: readonly string[];
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Runs one invocation: the check, then the parse, then the menu, status or change. A failure of
|
|
173
|
+
* any of them goes to `fail` when the invocation has one.
|
|
174
|
+
*/
|
|
175
|
+
function settingsCommandHandler<
|
|
176
|
+
Options,
|
|
177
|
+
Key extends string,
|
|
178
|
+
Context extends Pick<ExtensionContext, "mode">,
|
|
179
|
+
>(
|
|
180
|
+
dispatch: SettingsCommandDispatch<Options, Key, Context>,
|
|
181
|
+
): (args: string, ctx: Context) => Promise<void> {
|
|
182
|
+
return async (args, ctx) => {
|
|
183
|
+
const invocation = dispatch.start(ctx);
|
|
184
|
+
if (!invocation) return;
|
|
185
|
+
try {
|
|
186
|
+
invocation.check?.();
|
|
187
|
+
const command = parseSettingsCommand(args, dispatch.parse);
|
|
188
|
+
if (command.action === "menu" && ctx.mode === "tui") await invocation.menu();
|
|
189
|
+
else if (command.action === "set" || command.action === "inherit")
|
|
190
|
+
await invocation.change(command);
|
|
191
|
+
else await invocation.status();
|
|
192
|
+
} catch (cause) {
|
|
193
|
+
if (!invocation.fail) throw cause;
|
|
194
|
+
invocation.fail(cause);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Registers one settings command with its dispatch and its argument completions. */
|
|
200
|
+
export function registerSettingsCommand<Options, Key extends string>(
|
|
201
|
+
pi: Pick<ExtensionAPI, "registerCommand">,
|
|
202
|
+
registration: SettingsCommandRegistration<Options, Key>,
|
|
203
|
+
): void {
|
|
204
|
+
pi.registerCommand(registration.name, {
|
|
205
|
+
description: registration.description,
|
|
206
|
+
getArgumentCompletions: (prefix) =>
|
|
207
|
+
completeSettingsCommandArguments(prefix, {
|
|
208
|
+
optionKeys: registration.optionKeys,
|
|
209
|
+
parse: (text) => parseSettingsCommand(text, registration.parse),
|
|
210
|
+
}),
|
|
211
|
+
handler: settingsCommandHandler(registration),
|
|
212
|
+
});
|
|
213
|
+
}
|