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,48 @@
1
+ import type { AgentSession, ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ import { errorText } from "./errors.ts";
4
+
5
+ /** Native session identity only; callers validate the capabilities they require. */
6
+ export type DiscoverPiAgentSessionResult =
7
+ | { readonly ok: true; readonly session: AgentSession }
8
+ | { readonly ok: false; readonly warning: string };
9
+
10
+ /** Use the extension's host-resolved class: a compiled dependency's SDK import may be a different instance. */
11
+ export function discoverPiAgentSession(
12
+ pi: Pick<ExtensionAPI, "getAllTools">,
13
+ sessionClass: typeof AgentSession,
14
+ ): DiscoverPiAgentSessionResult {
15
+ const prototype = sessionClass.prototype;
16
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "getAllTools");
17
+ // This native SDK descriptor boundary requires only a callable data method; session identity is validated after delegation and callers own capability checks.
18
+ if (descriptor === undefined || typeof descriptor.value !== "function") {
19
+ return { ok: false, warning: "AgentSession.getAllTools is not the tested data method" };
20
+ }
21
+
22
+ const originalGetAllTools = prototype.getAllTools;
23
+ const receivers: AgentSession[] = [];
24
+ Object.defineProperty(prototype, "getAllTools", {
25
+ ...descriptor,
26
+ value(this: AgentSession) {
27
+ receivers.push(this);
28
+ return originalGetAllTools.call(this);
29
+ },
30
+ });
31
+
32
+ try {
33
+ pi.getAllTools();
34
+ } catch (cause) {
35
+ return {
36
+ ok: false,
37
+ warning: `getAllTools capture failed: ${errorText(cause)}`,
38
+ };
39
+ } finally {
40
+ Object.defineProperty(prototype, "getAllTools", descriptor);
41
+ }
42
+
43
+ const [session] = receivers;
44
+ if (!(session instanceof sessionClass)) {
45
+ return { ok: false, warning: "getAllTools did not delegate to an AgentSession" };
46
+ }
47
+ return { ok: true, session };
48
+ }
@@ -0,0 +1,3 @@
1
+ export function isRecord(value: unknown): value is Record<string, unknown> {
2
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3
+ }
@@ -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
+ }