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.
@@ -1,4 +1,4 @@
1
- import { existsSync } from "node:fs";
1
+ import { existsSync, renameSync } from "node:fs";
2
2
 
3
3
  import { type Api, getCurrentSystemMessage, type Message, type Model } from "@earendil-works/pi-ai";
4
4
  import {
@@ -10,15 +10,22 @@ import {
10
10
  generateSummaryWithUsage,
11
11
  getAgentDir,
12
12
  getLatestCompactionEntry,
13
- getSettingsListTheme,
14
13
  type ProjectedSessionEntry,
15
14
  type SessionBeforeCompactEvent,
16
15
  type SessionEntry,
17
16
  SettingsManager,
18
- type Theme,
19
17
  type TurnEndEvent,
20
18
  } from "@earendil-works/pi-coding-agent";
21
- import { Container, SettingsList, Text } from "@earendil-works/pi-tui";
19
+ import { stripTerminalSequences } from "@earendil-works/pi-tui";
20
+ import { errorText } from "pi-hl-utils/errors";
21
+ import {
22
+ layeredMenuScopes,
23
+ layeredSettingsSession,
24
+ type LayeredSettingScope,
25
+ type LayeredSettingSource,
26
+ } from "pi-hl-utils/layered-settings";
27
+ import { registerSettingsCommand } from "pi-hl-utils/settings-command";
28
+ import { SettingsMenu } from "pi-hl-utils/settings-menu";
22
29
  import { Type } from "typebox";
23
30
 
24
31
  import {
@@ -27,14 +34,20 @@ import {
27
34
  firstEntryAfter,
28
35
  type Note,
29
36
  } from "../src/background.ts";
37
+ import { contextKitCommandSpec } from "../src/command.ts";
30
38
  import {
31
39
  before,
32
40
  type ContextKitConfig,
33
41
  ownThreshold,
34
- readConfig,
35
42
  speculationLead,
36
43
  writesHandoff,
37
44
  } from "../src/config.ts";
45
+ import {
46
+ type ContextKitChange,
47
+ type ContextKitOptionsPatch,
48
+ contextKitConfig,
49
+ contextKitSettings,
50
+ } from "../src/context-kit-settings.ts";
38
51
  import {
39
52
  applyEdits,
40
53
  contextTokens,
@@ -44,17 +57,15 @@ import {
44
57
  } from "../src/context.ts";
45
58
  import { handoffSummary } from "../src/handoff.ts";
46
59
  import { type MaintenancePlan, planMaintenance } from "../src/maintain.ts";
47
- import { migrateLegacy, migrateProject } from "../src/migrate.ts";
60
+ import {
61
+ contextKitMenuSpec,
62
+ type ContextKitMenuHost,
63
+ type ContextKitMenuView,
64
+ } from "../src/menu.ts";
65
+ import { planSettingsImports, type ScopeSource, type SettingsImport } from "../src/migrate.ts";
48
66
  import { requestNote } from "../src/note.ts";
49
- import { panelItems, settingValue, summaryText } from "../src/panel.ts";
50
67
  import { readEntry, searchEntries } from "../src/recall.ts";
51
- import {
52
- createSettings,
53
- loadSettings,
54
- readSettingsFile,
55
- saveSetting,
56
- settingsPaths,
57
- } from "../src/settings-file.ts";
68
+ import { readSettingsFile, settingsPaths } from "../src/settings-file.ts";
58
69
  import { freedNotice, statusText } from "../src/status.ts";
59
70
 
60
71
  // One closure per session: Pi and pi-subagents load the extension once per session in the same process.
@@ -79,17 +90,34 @@ export default function contextKit(pi: ExtensionAPI): void {
79
90
  const paths = (ctx: ExtensionContext) =>
80
91
  settingsPaths(getAgentDir(), ctx.cwd, ctx.isProjectTrusted());
81
92
 
82
- /** Reads the settings files on each use, so a change applies at the next turn. */
83
- const settings = (ctx: ExtensionContext): ContextKitConfig => {
84
- const files = loadSettings(paths(ctx));
85
- const { config, problems } = readConfig(files.raw);
86
- const message = [...files.problems, ...problems].join("; ");
93
+ /** Warns once per distinct set of problems; the warning points to /context-kit. */
94
+ const report = (ctx: ExtensionContext, problems: string[]) => {
95
+ const message = problems.join("; ");
87
96
  if (message && message !== reported)
88
- ctx.ui.notify(
97
+ notify(
98
+ ctx,
89
99
  `pi-context-kit settings need attention: ${message}. Type /context-kit to see them.`,
90
100
  "warning",
91
101
  );
92
102
  reported = message;
103
+ };
104
+
105
+ /** Reads Pi's settings files on each call, so a change applies at the next turn. */
106
+ const readSettingsOf = (ctx: ExtensionContext) => {
107
+ const session = layeredSettingsSession(ctx);
108
+ const lenient = contextKitSettings.readSettingsLeniently(session);
109
+ const { config, problems } = contextKitConfig(lenient);
110
+ return {
111
+ manager: session.settingsManager,
112
+ lenient,
113
+ config,
114
+ problems: [...lenient.invalid.map((error) => error.message), ...problems],
115
+ };
116
+ };
117
+
118
+ const settings = (ctx: ExtensionContext): ContextKitConfig => {
119
+ const { config, problems } = readSettingsOf(ctx);
120
+ report(ctx, problems);
93
121
  return config;
94
122
  };
95
123
 
@@ -146,14 +174,14 @@ export default function contextKit(pi: ExtensionAPI): void {
146
174
  // Maintenance needs a model with a context window, so `window` is set whenever `output` is.
147
175
  const window = turn.ctx.model?.contextWindow;
148
176
  if (output && window)
149
- turn.ctx.ui.notify(freedNotice(count([]), count(turn.result.edits), window), "info");
177
+ notify(turn.ctx, freedNotice(count([]), count(turn.result.edits), window), "info");
150
178
  showStatus(turn.ctx, turn.config, turn.result.tokens);
151
179
  return output;
152
180
  };
153
181
 
154
182
  const warn = (ctx: ExtensionContext, error: unknown, fallback: string, what = "handoff note") => {
155
- const message = error instanceof Error ? error.message : String(error);
156
- ctx.ui.notify(`pi-context-kit: ${what} failed (${message}). ${fallback}`, "warning");
183
+ const message = errorText(error);
184
+ notify(ctx, `pi-context-kit: ${what} failed (${message}). ${fallback}`, "warning");
157
185
  };
158
186
 
159
187
  /** Pi's summary at the extension's threshold, because Pi's own hook waits for Pi's threshold. */
@@ -479,44 +507,63 @@ export default function contextKit(pi: ExtensionAPI): void {
479
507
  background.invalidate(epoch(branch), branch);
480
508
  showStatus(ctx);
481
509
  });
482
- /** Writes the 0.3 settings of each scope to its own file, unless that file exists. */
483
- const migrate = (ctx: ExtensionContext) => {
484
- const { global, project } = paths(ctx);
485
- const piSettings = SettingsManager.create(ctx.cwd, getAgentDir(), {
486
- projectTrusted: ctx.isProjectTrusted(),
487
- });
488
- // Pi reports its own unreadable settings. The project file depends on the global block, so
510
+ /** One settings write per scope: an invalid option throws before any write. */
511
+ async function importOptions(manager: SettingsManager, item: SettingsImport): Promise<void> {
512
+ const patch = parseImported(item);
513
+ // `key` is read only by `inherit`, so any option name serves for `set`.
514
+ await contextKitSettings.writeSettings(
515
+ manager,
516
+ item.scope,
517
+ { action: "set", key: "enabled", patch },
518
+ () => true,
519
+ );
520
+ }
521
+
522
+ /** Imports each scope's context-kit.json or 0.3 block, unless that scope already has a namespace. */
523
+ async function migrate(ctx: ExtensionContext): Promise<void> {
524
+ const manager = layeredSettingsSession(ctx).settingsManager;
525
+ // Pi reports its own unreadable settings. The project import depends on the global one, so
489
526
  // neither moves until Pi reads both.
490
- if (piSettings.drainErrors().length > 0) return;
491
- const oldGlobal: unknown = Reflect.get(piSettings.getGlobalSettings(), "contextKit");
492
- const oldProject: unknown = Reflect.get(piSettings.getProjectSettings(), "contextKit");
493
- const scopes = [
494
- { old: oldGlobal, file: global, content: () => migrateLegacy(oldGlobal) },
495
- {
496
- old: oldProject,
497
- file: project,
498
- // Runs after the global file is written, which the project file then overrides.
499
- content: () => migrateProject(oldGlobal, oldProject, readSettingsFile(global)),
500
- },
501
- ];
502
- for (const { old, file, content } of scopes) {
503
- if (old === undefined || !file) continue;
504
- try {
505
- if (!createSettings(file, content())) continue;
506
- } catch (error) {
507
- warn(ctx, error, "Defaults apply until it works.", `saving ${file}`);
508
- // The project file depends on the global file, so both wait for the next start.
509
- return;
510
- }
511
- ctx.ui.notify(
512
- `pi-context-kit moved its settings to ${file}. The "contextKit" entry in Pi's settings.json is no longer used.`,
513
- "info",
527
+ if (manager.drainErrors().length > 0) return;
528
+ const { global, project } = paths(ctx);
529
+ try {
530
+ const imports = planSettingsImports(
531
+ scopeSource(manager.getGlobalSettings(), global),
532
+ project === undefined ? undefined : scopeSource(manager.getProjectSettings(), project),
514
533
  );
534
+ const renamed: string[] = [];
535
+ for (const item of imports) {
536
+ await importOptions(manager, item);
537
+ if (item.file) {
538
+ try {
539
+ renameSync(item.file, `${item.file}.migrated`);
540
+ } catch (error) {
541
+ notify(
542
+ ctx,
543
+ `pi-context-kit: settings were imported, but renaming ${item.file} failed (${errorText(error)}). The file stays in place and is not imported again.`,
544
+ "warning",
545
+ );
546
+ return;
547
+ }
548
+ renamed.push(`${item.file} was renamed to ${item.file}.migrated.`);
549
+ }
550
+ }
551
+ if (imports.length > 0)
552
+ notify(
553
+ ctx,
554
+ [
555
+ 'pi-context-kit moved its settings into Pi\'s settings.json under "context-kit". The 0.3 "contextKit" entry is no longer read.',
556
+ ...renamed,
557
+ ].join(" "),
558
+ "info",
559
+ );
560
+ } catch (error) {
561
+ warn(ctx, error, "Defaults apply until it works.", "moving settings");
515
562
  }
516
- };
563
+ }
517
564
 
518
- pi.on("session_start", (_event, ctx) => {
519
- migrate(ctx);
565
+ pi.on("session_start", async (_event, ctx) => {
566
+ await migrate(ctx);
520
567
  showStatus(ctx);
521
568
  });
522
569
  // A compaction returned from turn_end emits no session_compact.
@@ -530,66 +577,81 @@ export default function contextKit(pi: ExtensionAPI): void {
530
577
  statusContext = undefined;
531
578
  });
532
579
 
533
- /** Returns whether the setting was saved. */
534
- const choose = (ctx: ExtensionContext, id: string, value: string) => {
535
- try {
536
- saveSetting(paths(ctx), id, settingValue(id, value));
537
- return true;
538
- } catch (error) {
539
- const message = error instanceof Error ? error.message : String(error);
540
- ctx.ui.notify(`pi-context-kit: ${message}`, "error");
541
- return false;
542
- } finally {
543
- showStatus(ctx);
544
- }
580
+ /** Persists one change: the session's entries, or the scope's settings through Pi's backend. */
581
+ async function applyChange(
582
+ ctx: ExtensionContext,
583
+ scope: LayeredSettingScope,
584
+ change: ContextKitChange,
585
+ ): Promise<void> {
586
+ await contextKitSettings.writeChange(
587
+ pi,
588
+ layeredSettingsSession(ctx),
589
+ scope,
590
+ change,
591
+ () => true,
592
+ );
593
+ }
594
+
595
+ /** What the menu shows, read again after each change. */
596
+ const menuView = (ctx: ExtensionContext): ContextKitMenuView => {
597
+ const read = readSettingsOf(ctx);
598
+ return {
599
+ headline: [statusOf(ctx, read.config, liveTokens(ctx)) ?? "", ...read.problems],
600
+ scopes: layeredMenuScopes(read.manager),
601
+ // The strategy supplies the method order and background unless the scope sets them.
602
+ settings: {
603
+ ...read.lenient.settings,
604
+ background: read.config.background,
605
+ methodOrder: read.config.methodOrder,
606
+ },
607
+ sources: strategySources(read.lenient.sources),
608
+ authored: read.lenient.authored,
609
+ };
545
610
  };
546
611
 
547
- const panelHeader = (ctx: ExtensionContext, theme: Theme) => {
548
- const status = statusOf(ctx, settings(ctx), liveTokens(ctx)) ?? "";
549
- const { global, project } = paths(ctx);
550
- const files =
551
- project && existsSync(project) ? `${global}, and for this project ${project}` : global;
552
- return `${theme.fg("accent", theme.bold("pi-context-kit"))} ${status}\n${theme.fg("dim", `Saved in ${files}`)}`;
612
+ /** An unset background or method order comes from the strategy, so it shows where that is set. */
613
+ const strategySources = (sources: Record<string, LayeredSettingSource>) => {
614
+ const derived = (key: string): LayeredSettingSource => {
615
+ const own = sources[key] ?? "default";
616
+ return own === "default" ? (sources.strategy ?? "default") : own;
617
+ };
618
+ return {
619
+ ...sources,
620
+ background: derived("background"),
621
+ methodOrder: derived("methodOrder"),
622
+ };
553
623
  };
554
624
 
555
- pi.registerCommand("context-kit", {
625
+ const menuHost = (ctx: ExtensionContext): ContextKitMenuHost => ({
626
+ view: () => menuView(ctx),
627
+ apply: async (scope, change) => {
628
+ await applyChange(ctx, scope, change);
629
+ showStatus(ctx);
630
+ },
631
+ });
632
+
633
+ registerSettingsCommand(pi, {
634
+ name: "context-kit",
556
635
  description: "Show and change pi-context-kit settings",
557
- handler: async (_args, ctx) => {
636
+ optionKeys: contextKitSettings.optionKeys,
637
+ parse: contextKitCommandSpec,
638
+ start(ctx) {
558
639
  // The settings warning points here, so it shows again.
559
640
  reported = "";
560
- const config = settings(ctx);
561
- if (ctx.mode !== "tui") {
562
- ctx.ui.notify(summaryText(config, paths(ctx).global), "info");
563
- return;
564
- }
565
- await ctx.ui.custom<undefined>((tui, theme, _keybindings, done) => {
566
- const items = panelItems(config);
567
- const saved = new Map<string, string>(items.map((item) => [item.id, item.currentValue]));
568
- const header = new Text(panelHeader(ctx, theme));
569
- const list = new SettingsList(
570
- items,
571
- items.length,
572
- getSettingsListTheme(),
573
- (id, value) => {
574
- // The list shows the new value before this runs.
575
- if (choose(ctx, id, value)) saved.set(id, value);
576
- else list.updateValue(id, saved.get(id) ?? value);
577
- header.setText(panelHeader(ctx, theme));
578
- },
579
- () => done(undefined),
580
- );
581
- const container = new Container();
582
- container.addChild(header);
583
- container.addChild(list);
584
- return {
585
- render: (width: number) => container.render(width),
586
- invalidate: () => container.invalidate(),
587
- handleInput: (data: string) => {
588
- list.handleInput(data);
589
- tui.requestRender();
590
- },
591
- };
592
- });
641
+ return {
642
+ status: () => notify(ctx, summaryText(settings(ctx)), "info"),
643
+ async menu() {
644
+ await ctx.ui.custom<void>(
645
+ (tui, theme, _keybindings, done) =>
646
+ new SettingsMenu(contextKitMenuSpec(menuHost(ctx)), { tui, theme }, () => done()),
647
+ );
648
+ },
649
+ async change(command) {
650
+ await applyChange(ctx, command.scope, command);
651
+ showStatus(ctx);
652
+ },
653
+ fail: (cause) => notify(ctx, `pi-context-kit: ${errorText(cause)}`, "error"),
654
+ };
593
655
  },
594
656
  });
595
657
 
@@ -704,3 +766,58 @@ function recentStart(ctx: ExtensionContext, keepRecentTokens: number): string |
704
766
  const cut = findCutPoint(entries, 0, entries.length, keepRecentTokens);
705
767
  return entries[cut.firstKeptEntryIndex]?.id;
706
768
  }
769
+
770
+ /** The scope's document with its `context-kit` namespace, and its file when that file exists. */
771
+ function scopeSource(document: object, path: string): ScopeSource {
772
+ const source: ScopeSource = {
773
+ stored: Reflect.get(document, "context-kit") !== undefined,
774
+ legacy: Reflect.get(document, "contextKit"),
775
+ };
776
+ return existsSync(path) ? { ...source, file: { path, content: readSettingsFile(path) } } : source;
777
+ }
778
+
779
+ /** Validates an import's options; an error names the `context-kit.json` they come from. */
780
+ function parseImported(item: SettingsImport): ContextKitOptionsPatch {
781
+ try {
782
+ return contextKitSettings.parseOptions(item.options, item.scope);
783
+ } catch (error) {
784
+ if (!item.file) throw error;
785
+ const message = errorText(error);
786
+ throw new Error(`${item.file} is invalid (${message})`, { cause: error });
787
+ }
788
+ }
789
+
790
+ function notify(ctx: ExtensionContext, text: string, type: "info" | "warning" | "error"): void {
791
+ ctx.ui.notify(displayText(text), type);
792
+ }
793
+
794
+ /**
795
+ * Error and settings text without terminal controls: pi-tui writes notice text to the terminal as is.
796
+ * Keeps tabs and line breaks.
797
+ */
798
+ function displayText(text: string): string {
799
+ return Array.from(stripTerminalSequences(text).replace(/\r\n?/g, "\n"))
800
+ .filter((char) => char === "\n" || char === "\t" || !isControlCharacter(char))
801
+ .join("");
802
+ }
803
+
804
+ /** C0, DEL and C1 controls. */
805
+ function isControlCharacter(char: string): boolean {
806
+ const code = char.charCodeAt(0);
807
+ return code < 0x20 || (code >= 0x7f && code <= 0x9f);
808
+ }
809
+
810
+ /** One-line status for modes without the settings menu. */
811
+ function summaryText(config: ContextKitConfig): string {
812
+ if (!config.enabled) return "pi-context-kit: automatic cleanup off. Settings: /context-kit";
813
+ const at =
814
+ config.threshold === "pi"
815
+ ? "Pi's limit"
816
+ : "tokens" in config.threshold
817
+ ? `${config.threshold.tokens} tokens`
818
+ : `${config.threshold.percent}%`;
819
+ const method = config.customOrder
820
+ ? `custom methods (${config.methodOrder.join(", ") || "none"})`
821
+ : config.strategy;
822
+ return `pi-context-kit: automatic cleanup at ${at}, with ${method}. Settings: /context-kit`;
823
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Hugo Lopes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "pi-hl-utils",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "description": "Shared code for the Pi extensions of this repository.",
6
+ "license": "MIT",
7
+ "files": [
8
+ "src"
9
+ ],
10
+ "type": "module",
11
+ "exports": {
12
+ "./errors": "./src/errors.ts",
13
+ "./evidence": "./src/evidence.ts",
14
+ "./expand-on-click": "./src/expand-on-click.ts",
15
+ "./layered-settings": "./src/layered-settings.ts",
16
+ "./null-optional-arguments": "./src/null-optional-arguments.ts",
17
+ "./pi-agent-session-discovery": "./src/pi-agent-session-discovery.ts",
18
+ "./record": "./src/record.ts",
19
+ "./settings-command": "./src/settings-command.ts",
20
+ "./settings-menu": "./src/settings-menu.ts",
21
+ "./token-calibration": "./src/token-calibration.ts",
22
+ "./ui": "./src/ui.ts",
23
+ "./testing/*": "./testing/*.ts"
24
+ },
25
+ "scripts": {
26
+ "check": "tsc --noEmit && vitest --run"
27
+ },
28
+ "devDependencies": {
29
+ "@earendil-works/pi-ai": "^1.5.2",
30
+ "@earendil-works/pi-coding-agent": "^1.5.2",
31
+ "@earendil-works/pi-tui": "^1.5.2",
32
+ "@types/node": "^26.6.6",
33
+ "typebox": "^1.4.3",
34
+ "typescript": "^7.0.2",
35
+ "vitest": "^5.0.3"
36
+ },
37
+ "peerDependencies": {
38
+ "@earendil-works/pi-ai": "*",
39
+ "@earendil-works/pi-coding-agent": "*",
40
+ "@earendil-works/pi-tui": "*",
41
+ "typebox": "*"
42
+ },
43
+ "engines": {
44
+ "node": ">=22.19.0",
45
+ "pi": ">=1.0.3"
46
+ }
47
+ }
@@ -0,0 +1,9 @@
1
+ /** A thrown value's message, or its string form. */
2
+ export function errorText(cause: unknown): string {
3
+ return cause instanceof Error ? cause.message : String(cause);
4
+ }
5
+
6
+ /** Whether a thrown value is a file system error for a missing path. */
7
+ export function isMissingFileError(cause: unknown): boolean {
8
+ return cause instanceof Error && "code" in cause && cause.code === "ENOENT";
9
+ }