pi-context-kit 0.4.3 → 0.4.4
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 +6 -0
- package/README.md +100 -87
- package/context-kit.schema.json +58 -77
- package/extensions/index.ts +200 -107
- 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/node_modules/pi-hl-utils/src/evidence.ts +363 -0
- package/node_modules/pi-hl-utils/src/expand-on-click.ts +90 -0
- package/node_modules/pi-hl-utils/src/layered-settings.ts +513 -0
- package/node_modules/pi-hl-utils/src/null-optional-arguments.ts +147 -0
- package/node_modules/pi-hl-utils/src/pi-agent-session-discovery.ts +48 -0
- 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/node_modules/pi-hl-utils/src/token-calibration.ts +39 -0
- package/node_modules/pi-hl-utils/src/ui.ts +355 -0
- package/package.json +7 -1
- package/src/command.ts +17 -0
- package/src/config.ts +1 -176
- package/src/context-kit-settings.ts +152 -0
- package/src/menu.ts +159 -0
- package/src/migrate.ts +93 -1
- package/src/settings-file.ts +10 -85
- package/src/panel.ts +0 -75
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import { keyText, type Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import {
|
|
3
|
+
Box,
|
|
4
|
+
type Container,
|
|
5
|
+
Spacer,
|
|
6
|
+
Text,
|
|
7
|
+
truncateToWidth,
|
|
8
|
+
type Component,
|
|
9
|
+
} from "@earendil-works/pi-tui";
|
|
10
|
+
|
|
11
|
+
/** The theme methods the shared UI helpers draw with; Pi's `Theme` satisfies it. */
|
|
12
|
+
export type UiTheme = Pick<Theme, "fg" | "bg" | "bold" | "strikethrough">;
|
|
13
|
+
|
|
14
|
+
/** Collapsed View preview lengths, copied from the Nearest Built-in tool of each kind. */
|
|
15
|
+
export const COLLAPSED_LINES = { fallback: 10, terminal: 5, search: 15, list: 20 } as const;
|
|
16
|
+
|
|
17
|
+
/** Pi's cap on a widget's rendered lines. */
|
|
18
|
+
const WIDGET_MAX_LINES = 10;
|
|
19
|
+
|
|
20
|
+
/** The shared Status Marks, for surfaces whose background does not show the outcome. */
|
|
21
|
+
export const STATUS_MARKS = {
|
|
22
|
+
active: "●",
|
|
23
|
+
idle: "○",
|
|
24
|
+
done: "✓",
|
|
25
|
+
failed: "✗",
|
|
26
|
+
warning: "!",
|
|
27
|
+
stopped: "■",
|
|
28
|
+
} as const;
|
|
29
|
+
|
|
30
|
+
export type StatusKind = keyof typeof STATUS_MARKS;
|
|
31
|
+
|
|
32
|
+
const STATUS_COLORS = {
|
|
33
|
+
active: "accent",
|
|
34
|
+
idle: "dim",
|
|
35
|
+
done: "success",
|
|
36
|
+
failed: "error",
|
|
37
|
+
warning: "warning",
|
|
38
|
+
stopped: "muted",
|
|
39
|
+
} as const satisfies Record<StatusKind, string>;
|
|
40
|
+
|
|
41
|
+
/** One Status Mark coloured from its theme role. */
|
|
42
|
+
export function statusMark(theme: Pick<UiTheme, "fg">, kind: StatusKind): string {
|
|
43
|
+
return theme.fg(STATUS_COLORS[kind], STATUS_MARKS[kind]);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The one inline separator. */
|
|
47
|
+
export const SEPARATOR = " · ";
|
|
48
|
+
|
|
49
|
+
/** Join non-empty parts with the inline separator in the `dim` role. */
|
|
50
|
+
export function joinInline(
|
|
51
|
+
theme: Pick<UiTheme, "fg">,
|
|
52
|
+
parts: readonly (string | undefined)[],
|
|
53
|
+
): string {
|
|
54
|
+
return parts.filter((part): part is string => Boolean(part)).join(theme.fg("dim", SEPARATOR));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A tool header in Pi's shape: the registered tool name in bold `toolTitle`, the target in
|
|
59
|
+
* `accent`, then extra arguments in `muted`.
|
|
60
|
+
*/
|
|
61
|
+
export function toolHeader(
|
|
62
|
+
theme: Pick<UiTheme, "fg" | "bold">,
|
|
63
|
+
name: string,
|
|
64
|
+
target?: string,
|
|
65
|
+
args?: string,
|
|
66
|
+
): string {
|
|
67
|
+
return [
|
|
68
|
+
theme.fg("toolTitle", theme.bold(name)),
|
|
69
|
+
target ? theme.fg("accent", target) : undefined,
|
|
70
|
+
args ? theme.fg("muted", args) : undefined,
|
|
71
|
+
]
|
|
72
|
+
.filter((part): part is string => part !== undefined)
|
|
73
|
+
.join(" ");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Pi's line-hint wording: `... (N more lines, ctrl+o to expand)`. */
|
|
77
|
+
export function expandHint(
|
|
78
|
+
theme: Pick<UiTheme, "fg">,
|
|
79
|
+
hidden: number,
|
|
80
|
+
direction: "more" | "earlier" = "more",
|
|
81
|
+
): string {
|
|
82
|
+
// Pi's own `keyHint` styles with its global theme, so build the hint from the injected one.
|
|
83
|
+
const key = theme.fg("dim", keyText("app.tools.expand"));
|
|
84
|
+
return `${theme.fg("muted", `... (${hidden} ${direction} lines,`)} ${key}${theme.fg("muted", " to expand")}${theme.fg("muted", ")")}`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The dim ` (ctrl+o to expand)` appended to a row that collapses to a summary line. */
|
|
88
|
+
export function summaryExpandHint(theme: Pick<UiTheme, "fg">): string {
|
|
89
|
+
return theme.fg("dim", ` (${keyText("app.tools.expand")} to expand)`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface PreviewOptions {
|
|
93
|
+
/** Lines shown when collapsed; use `COLLAPSED_LINES`. */
|
|
94
|
+
limit: number;
|
|
95
|
+
expanded: boolean;
|
|
96
|
+
/** Which end the Collapsed View keeps. Defaults to the head. */
|
|
97
|
+
keep?: "head" | "end";
|
|
98
|
+
/** Theme role for the body text. Defaults to `toolOutput`. */
|
|
99
|
+
color?: Parameters<UiTheme["fg"]>[0];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A body of lines in its Collapsed or Expanded View. The Collapsed View keeps `limit` lines from
|
|
104
|
+
* one end and adds Pi's Expand Hint; the Expanded View shows every line with no hint.
|
|
105
|
+
*/
|
|
106
|
+
export function previewBody(
|
|
107
|
+
theme: Pick<UiTheme, "fg">,
|
|
108
|
+
lines: readonly string[],
|
|
109
|
+
options: PreviewOptions,
|
|
110
|
+
): string[] {
|
|
111
|
+
const color = options.color ?? "toolOutput";
|
|
112
|
+
const styled = lines.map((line) => theme.fg(color, line));
|
|
113
|
+
const hidden = lines.length - options.limit;
|
|
114
|
+
if (options.expanded || hidden <= 0) return styled;
|
|
115
|
+
if (options.keep === "end") {
|
|
116
|
+
return [expandHint(theme, hidden, "earlier"), ...styled.slice(hidden)];
|
|
117
|
+
}
|
|
118
|
+
return [...styled.slice(0, options.limit), expandHint(theme, hidden)];
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Clips an already rendered child to `limit` visual lines (counted after wrapping), adding Pi's
|
|
123
|
+
* Expand Hint, wrapped to the available width, when lines are hidden. Use it for Markdown or other
|
|
124
|
+
* component bodies; use `previewBody` for plain lines. The Expanded View shows every line.
|
|
125
|
+
*/
|
|
126
|
+
export class CollapsedPreview implements Component {
|
|
127
|
+
constructor(
|
|
128
|
+
private readonly theme: Pick<UiTheme, "fg">,
|
|
129
|
+
private readonly child: Component,
|
|
130
|
+
private readonly options: { limit: number; expanded: boolean; keep?: "head" | "end" },
|
|
131
|
+
) {}
|
|
132
|
+
|
|
133
|
+
render(width: number): string[] {
|
|
134
|
+
const lines = this.child.render(width);
|
|
135
|
+
const hidden = lines.length - this.options.limit;
|
|
136
|
+
if (this.options.expanded || hidden <= 0) return lines;
|
|
137
|
+
const keepEnd = this.options.keep === "end";
|
|
138
|
+
const hint = new Text(
|
|
139
|
+
expandHint(this.theme, hidden, keepEnd ? "earlier" : "more"),
|
|
140
|
+
0,
|
|
141
|
+
0,
|
|
142
|
+
).render(width);
|
|
143
|
+
return keepEnd
|
|
144
|
+
? [...hint, ...lines.slice(hidden)]
|
|
145
|
+
: [...lines.slice(0, this.options.limit), ...hint];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
invalidate(): void {
|
|
149
|
+
this.child.invalidate();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function formatDuration(ms: number): string {
|
|
154
|
+
const seconds = ms / 1000;
|
|
155
|
+
if (seconds < 60) return `${seconds.toFixed(1)}s`;
|
|
156
|
+
const totalSeconds = Math.floor(seconds);
|
|
157
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
158
|
+
const remainder = totalSeconds % 60;
|
|
159
|
+
if (minutes < 60) return `${minutes}m ${remainder}s`;
|
|
160
|
+
return `${Math.floor(minutes / 60)}h ${minutes % 60}m ${remainder}s`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The parts of Pi's `ToolRenderContext` the duration footers read. */
|
|
164
|
+
export interface DurationContext {
|
|
165
|
+
/** Shared by every render of one tool row; keys the renderer's clock. */
|
|
166
|
+
state: WeakKey;
|
|
167
|
+
executionStarted: boolean;
|
|
168
|
+
/** Whether the call is still running; true for the call row until the final result. */
|
|
169
|
+
isPartial: boolean;
|
|
170
|
+
/** Pi records this only after `execute()` returns. */
|
|
171
|
+
durationMs: number | undefined;
|
|
172
|
+
invalidate(): void;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
interface DurationTracker {
|
|
176
|
+
startedAt: number | undefined;
|
|
177
|
+
endedAt: number | undefined;
|
|
178
|
+
interval: ReturnType<typeof setInterval> | undefined;
|
|
179
|
+
/** Set once a result renderer has run, so the call row stops showing its own footer. */
|
|
180
|
+
resultSeen: boolean;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const trackers = new WeakMap<WeakKey, DurationTracker>();
|
|
184
|
+
|
|
185
|
+
function trackerFor(context: DurationContext): DurationTracker {
|
|
186
|
+
let tracker = trackers.get(context.state);
|
|
187
|
+
if (!tracker) {
|
|
188
|
+
tracker = { startedAt: undefined, endedAt: undefined, interval: undefined, resultSeen: false };
|
|
189
|
+
trackers.set(context.state, tracker);
|
|
190
|
+
}
|
|
191
|
+
return tracker;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Start the renderer's own clock once the call is executing and redraw the row every second until
|
|
196
|
+
* the call finishes.
|
|
197
|
+
*/
|
|
198
|
+
function track(context: DurationContext, isPartial: boolean): DurationTracker {
|
|
199
|
+
const tracker = trackerFor(context);
|
|
200
|
+
if (tracker.startedAt === undefined && context.executionStarted) tracker.startedAt = Date.now();
|
|
201
|
+
if (tracker.startedAt === undefined) return tracker;
|
|
202
|
+
if (isPartial) {
|
|
203
|
+
tracker.interval ??= setInterval(() => context.invalidate(), 1000);
|
|
204
|
+
} else {
|
|
205
|
+
if (tracker.interval) clearInterval(tracker.interval);
|
|
206
|
+
tracker.interval = undefined;
|
|
207
|
+
tracker.endedAt ??= Date.now();
|
|
208
|
+
}
|
|
209
|
+
return tracker;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function elapsedMs(tracker: DurationTracker): number | undefined {
|
|
213
|
+
return tracker.startedAt === undefined
|
|
214
|
+
? undefined
|
|
215
|
+
: (tracker.endedAt ?? Date.now()) - tracker.startedAt;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Pi's duration footer for a result row: `Elapsed 1.2s` while the call runs, `Took 1.2s` once it
|
|
220
|
+
* finishes. A final result's recorded duration wins because it is monotonic and survives reloads;
|
|
221
|
+
* the renderer's own clock covers live progress and results stored without one. Absent when
|
|
222
|
+
* neither is known.
|
|
223
|
+
*/
|
|
224
|
+
export function durationFooter(
|
|
225
|
+
theme: Pick<UiTheme, "fg">,
|
|
226
|
+
context: DurationContext,
|
|
227
|
+
options: { isPartial: boolean },
|
|
228
|
+
): string | undefined {
|
|
229
|
+
const tracker = track(context, options.isPartial);
|
|
230
|
+
tracker.resultSeen = true;
|
|
231
|
+
if (!options.isPartial && context.durationMs !== undefined) {
|
|
232
|
+
return theme.fg("muted", `Took ${formatDuration(context.durationMs)}`);
|
|
233
|
+
}
|
|
234
|
+
const elapsed = elapsedMs(tracker);
|
|
235
|
+
if (elapsed === undefined) return undefined;
|
|
236
|
+
return theme.fg("muted", `${options.isPartial ? "Elapsed" : "Took"} ${formatDuration(elapsed)}`);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Append the duration footer to a result container, preceded by Pi's blank line as in its bash
|
|
241
|
+
* renderer. Adds nothing when no duration is known. Every result renderer uses this so the footer
|
|
242
|
+
* spaces identically in every package.
|
|
243
|
+
*/
|
|
244
|
+
export function appendDurationFooter(
|
|
245
|
+
container: Container,
|
|
246
|
+
theme: Pick<UiTheme, "fg">,
|
|
247
|
+
context: DurationContext,
|
|
248
|
+
options: { isPartial: boolean },
|
|
249
|
+
): void {
|
|
250
|
+
const footer = durationFooter(theme, context, options);
|
|
251
|
+
if (footer === undefined) return;
|
|
252
|
+
container.addChild(new Spacer(1));
|
|
253
|
+
container.addChild(new Text(footer, 0, 0));
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The `Elapsed` footer for a call row. Pi renders a result row only once a result exists, so a tool
|
|
258
|
+
* that sends no partial results shows its running time here. The footer disappears when a result
|
|
259
|
+
* row takes over, checked when drawn so both never show at once.
|
|
260
|
+
*/
|
|
261
|
+
export function callDurationFooter(
|
|
262
|
+
theme: Pick<UiTheme, "fg">,
|
|
263
|
+
context: DurationContext,
|
|
264
|
+
): Component {
|
|
265
|
+
const tracker = track(context, context.isPartial);
|
|
266
|
+
return {
|
|
267
|
+
render: () => {
|
|
268
|
+
const elapsed = elapsedMs(tracker);
|
|
269
|
+
if (tracker.resultSeen || tracker.endedAt !== undefined || elapsed === undefined) return [];
|
|
270
|
+
return [theme.fg("muted", `Elapsed ${formatDuration(elapsed)}`)];
|
|
271
|
+
},
|
|
272
|
+
invalidate: () => {},
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export interface WidgetLayout {
|
|
277
|
+
title: string;
|
|
278
|
+
/** Muted counts after the title, such as `3 active · 2 done`. */
|
|
279
|
+
counts?: string;
|
|
280
|
+
rows: readonly string[];
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* A widget in the shared layout: a bold `toolTitle` name with muted counts, then rows, kept under
|
|
285
|
+
* Pi's widget cap with a `... N more` line.
|
|
286
|
+
*/
|
|
287
|
+
export function widgetLines(theme: Pick<UiTheme, "fg" | "bold">, layout: WidgetLayout): string[] {
|
|
288
|
+
const header = [theme.fg("toolTitle", theme.bold(layout.title))];
|
|
289
|
+
if (layout.counts) header.push(theme.fg("muted", layout.counts));
|
|
290
|
+
const room = WIDGET_MAX_LINES - 1;
|
|
291
|
+
if (layout.rows.length <= room) return [header.join(" "), ...layout.rows];
|
|
292
|
+
const shown = room - 1;
|
|
293
|
+
return [
|
|
294
|
+
header.join(" "),
|
|
295
|
+
...layout.rows.slice(0, shown),
|
|
296
|
+
theme.fg("muted", `... ${layout.rows.length - shown} more`),
|
|
297
|
+
];
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** One footer status entry: an optional Status Mark, the name in `dim`, then the value. */
|
|
301
|
+
export function footerStatus(
|
|
302
|
+
theme: Pick<UiTheme, "fg">,
|
|
303
|
+
entry: { mark?: StatusKind; name: string; value: string },
|
|
304
|
+
): string {
|
|
305
|
+
return [
|
|
306
|
+
entry.mark ? statusMark(theme, entry.mark) : undefined,
|
|
307
|
+
theme.fg("dim", entry.name),
|
|
308
|
+
entry.value,
|
|
309
|
+
]
|
|
310
|
+
.filter((part): part is string => part !== undefined)
|
|
311
|
+
.join(" ");
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** The label line of a custom message or entry. */
|
|
315
|
+
export interface CustomMessageHeader {
|
|
316
|
+
outputPad: number;
|
|
317
|
+
/** Lowercase extension name, drawn as Pi's bold `[source]` label (`[branch]`, `[skill]`). */
|
|
318
|
+
source: string;
|
|
319
|
+
/** Pre-styled detail on the label's line, like the skill name in Pi's `[skill] name`. */
|
|
320
|
+
heading?: string;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Pi's custom-message look for message and entry renderers: a `customMessageBg` box padded by
|
|
325
|
+
* `outputPad`, a bold `[source]` label in `customMessageLabel` followed by the heading, and a
|
|
326
|
+
* spacer above the body when there is one.
|
|
327
|
+
*/
|
|
328
|
+
export function customMessageBox(
|
|
329
|
+
theme: Pick<UiTheme, "fg" | "bg" | "bold">,
|
|
330
|
+
header: CustomMessageHeader,
|
|
331
|
+
body: readonly Component[],
|
|
332
|
+
): Box {
|
|
333
|
+
const box = new Box(header.outputPad, 1, (text) => theme.bg("customMessageBg", text));
|
|
334
|
+
const label = theme.fg("customMessageLabel", theme.bold(`[${header.source}]`));
|
|
335
|
+
box.addChild(new Text(header.heading ? `${label} ${header.heading}` : label, 0, 0));
|
|
336
|
+
if (body.length > 0) box.addChild(new Spacer(1));
|
|
337
|
+
for (const child of body) box.addChild(child);
|
|
338
|
+
return box;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const ESCAPE = String.fromCharCode(27);
|
|
342
|
+
const RESET_SEQUENCE = new RegExp(`${ESCAPE}\\[0m`, "g");
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Clip plain text to `width` columns, ending with `...` when it is cut. Unlike pi-tui's
|
|
346
|
+
* `truncateToWidth` it emits no escape sequence, so the result can be styled afterwards.
|
|
347
|
+
*/
|
|
348
|
+
export function clipPlain(text: string, width: number): string {
|
|
349
|
+
return truncateToWidth(text, width, "...").replace(RESET_SEQUENCE, "");
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** A warning or error notification: `<Display Name>: message`. Info messages carry no prefix. */
|
|
353
|
+
export function noticeText(displayName: string, message: string): string {
|
|
354
|
+
return `${displayName}: ${message}`;
|
|
355
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-context-kit",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.4",
|
|
4
4
|
"description": "Keep long Pi coding agent sessions sharp. Clears old file reads and tool outputs from the context, writes the compaction summary in the background, and lets the agent recall the original text.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"coding-agent",
|
|
@@ -38,6 +38,9 @@
|
|
|
38
38
|
"check": "tsc --noEmit && vitest --run",
|
|
39
39
|
"prepublishOnly": "npm run check"
|
|
40
40
|
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"pi-hl-utils": "workspace:*"
|
|
43
|
+
},
|
|
41
44
|
"devDependencies": {
|
|
42
45
|
"@earendil-works/pi-ai": "^1.5.2",
|
|
43
46
|
"@earendil-works/pi-coding-agent": "^1.5.2",
|
|
@@ -53,6 +56,9 @@
|
|
|
53
56
|
"@earendil-works/pi-tui": "*",
|
|
54
57
|
"typebox": "*"
|
|
55
58
|
},
|
|
59
|
+
"bundledDependencies": [
|
|
60
|
+
"pi-hl-utils"
|
|
61
|
+
],
|
|
56
62
|
"engines": {
|
|
57
63
|
"node": ">=22.19.0",
|
|
58
64
|
"pi": ">=1.0.3"
|
package/src/command.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { SettingsCommandSpec } from "pi-hl-utils/settings-command";
|
|
2
|
+
|
|
3
|
+
import { type ContextKitOptionsPatch, contextKitSettings } from "./context-kit-settings.ts";
|
|
4
|
+
|
|
5
|
+
const usage =
|
|
6
|
+
"Usage: /context-kit [on|off|status|inherit [key]|set <key> <JSON>] [--global|--project]; /context-kit alone opens settings";
|
|
7
|
+
|
|
8
|
+
/** The `/context-kit` grammar; validated patches cannot invent option keys. */
|
|
9
|
+
export const contextKitCommandSpec: SettingsCommandSpec<
|
|
10
|
+
ContextKitOptionsPatch,
|
|
11
|
+
keyof ContextKitOptionsPatch
|
|
12
|
+
> = {
|
|
13
|
+
usage,
|
|
14
|
+
optionKey: contextKitSettings.optionKey,
|
|
15
|
+
parseOptions: contextKitSettings.parseOptions,
|
|
16
|
+
toggle: (enabled) => ({ key: "enabled", patch: { enabled } }),
|
|
17
|
+
};
|
package/src/config.ts
CHANGED
|
@@ -41,191 +41,16 @@ export interface ContextKitConfig {
|
|
|
41
41
|
progressRatio: number;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
-
export const DEFAULT_CONFIG: ContextKitConfig = {
|
|
45
|
-
enabled: true,
|
|
46
|
-
threshold: { percent: 75 },
|
|
47
|
-
strategy: "balanced",
|
|
48
|
-
methodOrder: [...STRATEGIES.balanced.methodOrder],
|
|
49
|
-
customOrder: false,
|
|
50
|
-
background: STRATEGIES.balanced.background,
|
|
51
|
-
supersedeReads: true,
|
|
52
|
-
prune: {
|
|
53
|
-
enabled: true,
|
|
54
|
-
protectTokens: 40_000,
|
|
55
|
-
minSavings: 20_000,
|
|
56
|
-
minTokens: 50,
|
|
57
|
-
},
|
|
58
|
-
shake: {
|
|
59
|
-
protectTokens: 16_000,
|
|
60
|
-
minSavings: 4_000,
|
|
61
|
-
blockMinTokens: 400,
|
|
62
|
-
},
|
|
63
|
-
progressRatio: 0.8,
|
|
64
|
-
};
|
|
65
|
-
|
|
66
44
|
export interface ConfigResult {
|
|
67
45
|
config: ContextKitConfig;
|
|
68
|
-
/** One message per
|
|
46
|
+
/** One message per ineffective combination of options. */
|
|
69
47
|
problems: string[];
|
|
70
48
|
}
|
|
71
49
|
|
|
72
|
-
type Check<T> = { read: (value: unknown) => T | undefined; must: string };
|
|
73
|
-
|
|
74
|
-
const boolean: Check<boolean> = {
|
|
75
|
-
read: (value) => (typeof value === "boolean" ? value : undefined),
|
|
76
|
-
must: "true or false",
|
|
77
|
-
};
|
|
78
|
-
const count: Check<number> = {
|
|
79
|
-
read: (value) => (Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : undefined),
|
|
80
|
-
must: "a whole number, 0 or more",
|
|
81
|
-
};
|
|
82
|
-
const ratio: Check<number> = {
|
|
83
|
-
read: (value) => (typeof value === "number" && value > 0 && value <= 1 ? value : undefined),
|
|
84
|
-
must: "a number above 0, up to 1",
|
|
85
|
-
};
|
|
86
|
-
const threshold: Check<Threshold> = {
|
|
87
|
-
read: parseThreshold,
|
|
88
|
-
must: 'a positive integer (tokens), a percentage such as "75%", or "pi"',
|
|
89
|
-
};
|
|
90
50
|
export const isStrategy = (value: unknown): value is Strategy =>
|
|
91
51
|
value === "balanced" || value === "frugal" || value === "pi-summary";
|
|
92
|
-
const strategy: Check<Strategy> = {
|
|
93
|
-
read: (value) => (isStrategy(value) ? value : undefined),
|
|
94
|
-
must: '"balanced", "frugal" or "pi-summary"',
|
|
95
|
-
};
|
|
96
52
|
export const isMethod = (value: unknown): value is Method =>
|
|
97
53
|
value === "handoff" || value === "shake" || value === "soft";
|
|
98
|
-
const methodOrder: Check<Method[]> = {
|
|
99
|
-
read: (value) =>
|
|
100
|
-
Array.isArray(value) && value.every(isMethod) ? [...new Set(value)] : undefined,
|
|
101
|
-
must: 'a list of "handoff", "shake" and "soft"',
|
|
102
|
-
};
|
|
103
|
-
|
|
104
|
-
function parseThreshold(value: unknown): Threshold | undefined {
|
|
105
|
-
if (value === "pi") return "pi";
|
|
106
|
-
if (Number.isSafeInteger(value) && Number(value) > 0) return { tokens: Number(value) };
|
|
107
|
-
const match = typeof value === "string" ? /^(\d+(?:\.\d+)?)%$/.exec(value) : null;
|
|
108
|
-
const percent = Number(match?.[1]);
|
|
109
|
-
return percent > 0 && percent <= 100 ? { percent } : undefined;
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/** Reads the keys of one settings object and reports invalid or unknown keys. */
|
|
113
|
-
class Section {
|
|
114
|
-
readonly #raw: Record<string, unknown>;
|
|
115
|
-
readonly #prefix: string;
|
|
116
|
-
readonly #problems: string[];
|
|
117
|
-
readonly #known = new Set<string>();
|
|
118
|
-
|
|
119
|
-
constructor(raw: unknown, path: string, problems: string[]) {
|
|
120
|
-
this.#prefix = path ? `${path}.` : "";
|
|
121
|
-
this.#problems = problems;
|
|
122
|
-
// Editors read `$schema` at the root of the file only.
|
|
123
|
-
if (!path) this.#known.add("$schema");
|
|
124
|
-
if (raw === undefined || isRecord(raw)) this.#raw = raw ?? {};
|
|
125
|
-
else {
|
|
126
|
-
problems.push(`${path || "the settings"} must be an object (default used)`);
|
|
127
|
-
this.#raw = {};
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/** Whether the key holds a valid value, so the default was not used. */
|
|
132
|
-
provides<T>(key: string, check: Check<T>): boolean {
|
|
133
|
-
return check.read(this.#raw[key]) !== undefined;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
get<T>(key: string, check: Check<T>, fallback: T): T {
|
|
137
|
-
this.#known.add(key);
|
|
138
|
-
const value = this.#raw[key];
|
|
139
|
-
if (value === undefined) return fallback;
|
|
140
|
-
const parsed = check.read(value);
|
|
141
|
-
if (parsed !== undefined) return parsed;
|
|
142
|
-
this.#problems.push(`${this.#prefix}${key} must be ${check.must} (default used)`);
|
|
143
|
-
return fallback;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
section(key: string): Section {
|
|
147
|
-
this.#known.add(key);
|
|
148
|
-
return new Section(this.#raw[key], `${this.#prefix}${key}`, this.#problems);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/** Reports keys that no `get` or `section` call read. Call it last. */
|
|
152
|
-
done(): void {
|
|
153
|
-
for (const key of Object.keys(this.#raw))
|
|
154
|
-
if (!this.#known.has(key)) this.#problems.push(`${this.#prefix}${key} is not a setting`);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** Validates the merged contents of the settings files. */
|
|
159
|
-
export function readConfig(raw: unknown): ConfigResult {
|
|
160
|
-
const problems: string[] = [];
|
|
161
|
-
const d = DEFAULT_CONFIG;
|
|
162
|
-
const root = new Section(raw, "", problems);
|
|
163
|
-
const enabled = root.get("enabled", boolean, d.enabled);
|
|
164
|
-
const limit = root.get("threshold", threshold, d.threshold);
|
|
165
|
-
const named = root.get("strategy", strategy, d.strategy);
|
|
166
|
-
const a = root.section("advanced");
|
|
167
|
-
const methods = a.get("methodOrder", methodOrder, STRATEGIES[named].methodOrder);
|
|
168
|
-
const background = a.get("background", boolean, STRATEGIES[named].background);
|
|
169
|
-
const supersedeReads = a.get("supersedeReads", boolean, d.supersedeReads);
|
|
170
|
-
const progressRatio = a.get("progressRatio", ratio, d.progressRatio);
|
|
171
|
-
const prune = readPrune(a.section("prune"));
|
|
172
|
-
const shake = readShake(a.section("shake"));
|
|
173
|
-
a.done();
|
|
174
|
-
root.done();
|
|
175
|
-
|
|
176
|
-
const customOrder = a.provides("methodOrder", methodOrder);
|
|
177
|
-
if (root.provides("strategy", strategy) && customOrder)
|
|
178
|
-
problems.push(
|
|
179
|
-
`strategy "${named}" does not set the method order, because advanced.methodOrder replaces it`,
|
|
180
|
-
);
|
|
181
|
-
if (customOrder && a.provides("background", boolean) && background && !writesHandoff(methods))
|
|
182
|
-
problems.push(
|
|
183
|
-
'advanced.background has no effect, because "handoff" is not before "soft" in the method order',
|
|
184
|
-
);
|
|
185
|
-
|
|
186
|
-
return {
|
|
187
|
-
config: {
|
|
188
|
-
enabled,
|
|
189
|
-
threshold: limit,
|
|
190
|
-
strategy: named,
|
|
191
|
-
methodOrder: [...methods],
|
|
192
|
-
customOrder,
|
|
193
|
-
background,
|
|
194
|
-
supersedeReads,
|
|
195
|
-
prune,
|
|
196
|
-
shake,
|
|
197
|
-
progressRatio,
|
|
198
|
-
},
|
|
199
|
-
problems,
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
function readPrune(p: Section): ContextKitConfig["prune"] {
|
|
204
|
-
const d = DEFAULT_CONFIG.prune;
|
|
205
|
-
const prune = {
|
|
206
|
-
enabled: p.get("enabled", boolean, d.enabled),
|
|
207
|
-
protectTokens: p.get("protectTokens", count, d.protectTokens),
|
|
208
|
-
minSavings: p.get("minSavings", count, d.minSavings),
|
|
209
|
-
minTokens: p.get("minTokens", count, d.minTokens),
|
|
210
|
-
};
|
|
211
|
-
p.done();
|
|
212
|
-
return prune;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
function readShake(s: Section): ShakeOptions {
|
|
216
|
-
const d = DEFAULT_CONFIG.shake;
|
|
217
|
-
const shake = {
|
|
218
|
-
protectTokens: s.get("protectTokens", count, d.protectTokens),
|
|
219
|
-
minSavings: s.get("minSavings", count, d.minSavings),
|
|
220
|
-
blockMinTokens: s.get("blockMinTokens", count, d.blockMinTokens),
|
|
221
|
-
};
|
|
222
|
-
s.done();
|
|
223
|
-
return shake;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
227
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
228
|
-
}
|
|
229
54
|
|
|
230
55
|
/** Soft ends the extension's strategy chain, even when other methods follow it. */
|
|
231
56
|
export function before(methods: readonly Method[], a: Method, b: Method): boolean {
|