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.
@@ -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,21 @@ 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 { errorText } from "pi-hl-utils/errors";
20
+ import {
21
+ layeredMenuScopes,
22
+ layeredSettingsSession,
23
+ type LayeredSettingScope,
24
+ type LayeredSettingSource,
25
+ } from "pi-hl-utils/layered-settings";
26
+ import { registerSettingsCommand } from "pi-hl-utils/settings-command";
27
+ import { SettingsMenu } from "pi-hl-utils/settings-menu";
22
28
  import { Type } from "typebox";
23
29
 
24
30
  import {
@@ -27,14 +33,20 @@ import {
27
33
  firstEntryAfter,
28
34
  type Note,
29
35
  } from "../src/background.ts";
36
+ import { contextKitCommandSpec } from "../src/command.ts";
30
37
  import {
31
38
  before,
32
39
  type ContextKitConfig,
33
40
  ownThreshold,
34
- readConfig,
35
41
  speculationLead,
36
42
  writesHandoff,
37
43
  } from "../src/config.ts";
44
+ import {
45
+ type ContextKitChange,
46
+ type ContextKitOptionsPatch,
47
+ contextKitConfig,
48
+ contextKitSettings,
49
+ } from "../src/context-kit-settings.ts";
38
50
  import {
39
51
  applyEdits,
40
52
  contextTokens,
@@ -44,17 +56,15 @@ import {
44
56
  } from "../src/context.ts";
45
57
  import { handoffSummary } from "../src/handoff.ts";
46
58
  import { type MaintenancePlan, planMaintenance } from "../src/maintain.ts";
47
- import { migrateLegacy, migrateProject } from "../src/migrate.ts";
59
+ import {
60
+ contextKitMenuSpec,
61
+ type ContextKitMenuHost,
62
+ type ContextKitMenuView,
63
+ } from "../src/menu.ts";
64
+ import { planSettingsImports, type ScopeSource, type SettingsImport } from "../src/migrate.ts";
48
65
  import { requestNote } from "../src/note.ts";
49
- import { panelItems, settingValue, summaryText } from "../src/panel.ts";
50
66
  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";
67
+ import { readSettingsFile, settingsPaths } from "../src/settings-file.ts";
58
68
  import { freedNotice, statusText } from "../src/status.ts";
59
69
 
60
70
  // One closure per session: Pi and pi-subagents load the extension once per session in the same process.
@@ -79,17 +89,33 @@ export default function contextKit(pi: ExtensionAPI): void {
79
89
  const paths = (ctx: ExtensionContext) =>
80
90
  settingsPaths(getAgentDir(), ctx.cwd, ctx.isProjectTrusted());
81
91
 
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("; ");
92
+ /** Warns once per distinct set of problems; the warning points to /context-kit. */
93
+ const report = (ctx: ExtensionContext, problems: string[]) => {
94
+ const message = problems.join("; ");
87
95
  if (message && message !== reported)
88
96
  ctx.ui.notify(
89
97
  `pi-context-kit settings need attention: ${message}. Type /context-kit to see them.`,
90
98
  "warning",
91
99
  );
92
100
  reported = message;
101
+ };
102
+
103
+ /** Reads Pi's settings files on each call, so a change applies at the next turn. */
104
+ const readSettingsOf = (ctx: ExtensionContext) => {
105
+ const session = layeredSettingsSession(ctx);
106
+ const lenient = contextKitSettings.readSettingsLeniently(session);
107
+ const { config, problems } = contextKitConfig(lenient);
108
+ return {
109
+ manager: session.settingsManager,
110
+ lenient,
111
+ config,
112
+ problems: [...lenient.invalid.map((error) => error.message), ...problems],
113
+ };
114
+ };
115
+
116
+ const settings = (ctx: ExtensionContext): ContextKitConfig => {
117
+ const { config, problems } = readSettingsOf(ctx);
118
+ report(ctx, problems);
93
119
  return config;
94
120
  };
95
121
 
@@ -152,7 +178,7 @@ export default function contextKit(pi: ExtensionAPI): void {
152
178
  };
153
179
 
154
180
  const warn = (ctx: ExtensionContext, error: unknown, fallback: string, what = "handoff note") => {
155
- const message = error instanceof Error ? error.message : String(error);
181
+ const message = errorText(error);
156
182
  ctx.ui.notify(`pi-context-kit: ${what} failed (${message}). ${fallback}`, "warning");
157
183
  };
158
184
 
@@ -479,44 +505,61 @@ export default function contextKit(pi: ExtensionAPI): void {
479
505
  background.invalidate(epoch(branch), branch);
480
506
  showStatus(ctx);
481
507
  });
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
508
+ /** One settings write per scope: an invalid option throws before any write. */
509
+ async function importOptions(manager: SettingsManager, item: SettingsImport): Promise<void> {
510
+ const patch = parseImported(item);
511
+ // `key` is read only by `inherit`, so any option name serves for `set`.
512
+ await contextKitSettings.writeSettings(
513
+ manager,
514
+ item.scope,
515
+ { action: "set", key: "enabled", patch },
516
+ () => true,
517
+ );
518
+ }
519
+
520
+ /** Imports each scope's context-kit.json or 0.3 block, unless that scope already has a namespace. */
521
+ async function migrate(ctx: ExtensionContext): Promise<void> {
522
+ const manager = layeredSettingsSession(ctx).settingsManager;
523
+ // Pi reports its own unreadable settings. The project import depends on the global one, so
489
524
  // 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",
525
+ if (manager.drainErrors().length > 0) return;
526
+ const { global, project } = paths(ctx);
527
+ try {
528
+ const imports = planSettingsImports(
529
+ scopeSource(manager.getGlobalSettings(), global),
530
+ project === undefined ? undefined : scopeSource(manager.getProjectSettings(), project),
514
531
  );
532
+ const renamed: string[] = [];
533
+ for (const item of imports) {
534
+ await importOptions(manager, item);
535
+ if (item.file) {
536
+ try {
537
+ renameSync(item.file, `${item.file}.migrated`);
538
+ } catch (error) {
539
+ ctx.ui.notify(
540
+ `pi-context-kit: settings were imported, but renaming ${item.file} failed (${errorText(error)}). The file stays in place and is not imported again.`,
541
+ "warning",
542
+ );
543
+ return;
544
+ }
545
+ renamed.push(`${item.file} was renamed to ${item.file}.migrated.`);
546
+ }
547
+ }
548
+ if (imports.length > 0)
549
+ ctx.ui.notify(
550
+ [
551
+ 'pi-context-kit moved its settings into Pi\'s settings.json under "context-kit". The 0.3 "contextKit" entry is no longer read.',
552
+ ...renamed,
553
+ ].join(" "),
554
+ "info",
555
+ );
556
+ } catch (error) {
557
+ warn(ctx, error, "Defaults apply until it works.", "moving settings");
515
558
  }
516
- };
559
+ }
517
560
 
518
- pi.on("session_start", (_event, ctx) => {
519
- migrate(ctx);
561
+ pi.on("session_start", async (_event, ctx) => {
562
+ await migrate(ctx);
520
563
  showStatus(ctx);
521
564
  });
522
565
  // A compaction returned from turn_end emits no session_compact.
@@ -530,66 +573,81 @@ export default function contextKit(pi: ExtensionAPI): void {
530
573
  statusContext = undefined;
531
574
  });
532
575
 
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
- }
576
+ /** Persists one change: the session's entries, or the scope's settings through Pi's backend. */
577
+ async function applyChange(
578
+ ctx: ExtensionContext,
579
+ scope: LayeredSettingScope,
580
+ change: ContextKitChange,
581
+ ): Promise<void> {
582
+ await contextKitSettings.writeChange(
583
+ pi,
584
+ layeredSettingsSession(ctx),
585
+ scope,
586
+ change,
587
+ () => true,
588
+ );
589
+ }
590
+
591
+ /** What the menu shows, read again after each change. */
592
+ const menuView = (ctx: ExtensionContext): ContextKitMenuView => {
593
+ const read = readSettingsOf(ctx);
594
+ return {
595
+ headline: [statusOf(ctx, read.config, liveTokens(ctx)) ?? "", ...read.problems],
596
+ scopes: layeredMenuScopes(read.manager),
597
+ // The strategy supplies the method order and background unless the scope sets them.
598
+ settings: {
599
+ ...read.lenient.settings,
600
+ background: read.config.background,
601
+ methodOrder: read.config.methodOrder,
602
+ },
603
+ sources: strategySources(read.lenient.sources),
604
+ authored: read.lenient.authored,
605
+ };
545
606
  };
546
607
 
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}`)}`;
608
+ /** An unset background or method order comes from the strategy, so it shows where that is set. */
609
+ const strategySources = (sources: Record<string, LayeredSettingSource>) => {
610
+ const derived = (key: string): LayeredSettingSource => {
611
+ const own = sources[key] ?? "default";
612
+ return own === "default" ? (sources.strategy ?? "default") : own;
613
+ };
614
+ return {
615
+ ...sources,
616
+ background: derived("background"),
617
+ methodOrder: derived("methodOrder"),
618
+ };
553
619
  };
554
620
 
555
- pi.registerCommand("context-kit", {
621
+ const menuHost = (ctx: ExtensionContext): ContextKitMenuHost => ({
622
+ view: () => menuView(ctx),
623
+ apply: async (scope, change) => {
624
+ await applyChange(ctx, scope, change);
625
+ showStatus(ctx);
626
+ },
627
+ });
628
+
629
+ registerSettingsCommand(pi, {
630
+ name: "context-kit",
556
631
  description: "Show and change pi-context-kit settings",
557
- handler: async (_args, ctx) => {
632
+ optionKeys: contextKitSettings.optionKeys,
633
+ parse: contextKitCommandSpec,
634
+ start(ctx) {
558
635
  // The settings warning points here, so it shows again.
559
636
  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
- });
637
+ return {
638
+ status: () => ctx.ui.notify(summaryText(settings(ctx)), "info"),
639
+ async menu() {
640
+ await ctx.ui.custom<void>(
641
+ (tui, theme, _keybindings, done) =>
642
+ new SettingsMenu(contextKitMenuSpec(menuHost(ctx)), { tui, theme }, () => done()),
643
+ );
644
+ },
645
+ async change(command) {
646
+ await applyChange(ctx, command.scope, command);
647
+ showStatus(ctx);
648
+ },
649
+ fail: (cause) => ctx.ui.notify(`pi-context-kit: ${errorText(cause)}`, "error"),
650
+ };
593
651
  },
594
652
  });
595
653
 
@@ -704,3 +762,38 @@ function recentStart(ctx: ExtensionContext, keepRecentTokens: number): string |
704
762
  const cut = findCutPoint(entries, 0, entries.length, keepRecentTokens);
705
763
  return entries[cut.firstKeptEntryIndex]?.id;
706
764
  }
765
+
766
+ /** The scope's document with its `context-kit` namespace, and its file when that file exists. */
767
+ function scopeSource(document: object, path: string): ScopeSource {
768
+ const source: ScopeSource = {
769
+ stored: Reflect.get(document, "context-kit") !== undefined,
770
+ legacy: Reflect.get(document, "contextKit"),
771
+ };
772
+ return existsSync(path) ? { ...source, file: { path, content: readSettingsFile(path) } } : source;
773
+ }
774
+
775
+ /** Validates an import's options; an error names the `context-kit.json` they come from. */
776
+ function parseImported(item: SettingsImport): ContextKitOptionsPatch {
777
+ try {
778
+ return contextKitSettings.parseOptions(item.options, item.scope);
779
+ } catch (error) {
780
+ if (!item.file) throw error;
781
+ const message = errorText(error);
782
+ throw new Error(`${item.file} is invalid (${message})`, { cause: error });
783
+ }
784
+ }
785
+
786
+ /** One-line status for modes without the settings menu. */
787
+ function summaryText(config: ContextKitConfig): string {
788
+ if (!config.enabled) return "pi-context-kit: automatic cleanup off. Settings: /context-kit";
789
+ const at =
790
+ config.threshold === "pi"
791
+ ? "Pi's limit"
792
+ : "tokens" in config.threshold
793
+ ? `${config.threshold.tokens} tokens`
794
+ : `${config.threshold.percent}%`;
795
+ const method = config.customOrder
796
+ ? `custom methods (${config.methodOrder.join(", ") || "none"})`
797
+ : config.strategy;
798
+ return `pi-context-kit: automatic cleanup at ${at}, with ${method}. Settings: /context-kit`;
799
+ }
@@ -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
+ }