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.
@@ -0,0 +1,152 @@
1
+ import {
2
+ defineLayeredSettings,
3
+ type LayeredSettingChange,
4
+ type ResolvedLayeredSettings,
5
+ } from "pi-hl-utils/layered-settings";
6
+ import { type Static, Type } from "typebox";
7
+
8
+ import {
9
+ type ConfigResult,
10
+ type Method,
11
+ type Strategy,
12
+ STRATEGIES,
13
+ type Threshold,
14
+ writesHandoff,
15
+ } from "./config.ts";
16
+
17
+ const MAX_COUNT = Number.MAX_SAFE_INTEGER;
18
+ const PERCENT = "^(0*100(\\.0+)?|0*[1-9]\\d?(\\.\\d+)?|0+\\.\\d*[1-9]\\d*)%$";
19
+
20
+ const method = Type.Union([Type.Literal("handoff"), Type.Literal("shake"), Type.Literal("soft")]);
21
+ const strategy = Type.Union([
22
+ Type.Literal("balanced"),
23
+ Type.Literal("frugal"),
24
+ Type.Literal("pi-summary"),
25
+ ]);
26
+ const count = Type.Optional(Type.Integer({ minimum: 0, maximum: MAX_COUNT }));
27
+
28
+ /** Authored options under `context-kit` in Pi's settings; every key is optional so absent values inherit. */
29
+ export const contextKitOptionsSchema = Type.Object(
30
+ {
31
+ enabled: Type.Optional(Type.Boolean()),
32
+ threshold: Type.Optional(
33
+ Type.Union([
34
+ Type.Integer({ minimum: 1, maximum: MAX_COUNT }),
35
+ Type.String({ pattern: PERCENT }),
36
+ Type.Literal("pi"),
37
+ ]),
38
+ ),
39
+ strategy: Type.Optional(strategy),
40
+ methodOrder: Type.Optional(Type.Array(method)),
41
+ background: Type.Optional(Type.Boolean()),
42
+ supersedeReads: Type.Optional(Type.Boolean()),
43
+ progressRatio: Type.Optional(Type.Number({ exclusiveMinimum: 0, maximum: 1 })),
44
+ pruneEnabled: Type.Optional(Type.Boolean()),
45
+ pruneProtectTokens: count,
46
+ pruneMinSavings: count,
47
+ pruneMinTokens: count,
48
+ shakeProtectTokens: count,
49
+ shakeMinSavings: count,
50
+ shakeBlockMinTokens: count,
51
+ },
52
+ { additionalProperties: false },
53
+ );
54
+
55
+ /** Layered options. `threshold` is a token count, a percentage such as `"75%"`, or `"pi"`. */
56
+ export interface ContextKitOptions {
57
+ enabled: boolean;
58
+ threshold: number | string;
59
+ strategy: Strategy;
60
+ /** Absent: the strategy's method order. */
61
+ methodOrder?: Method[];
62
+ /** Absent: the strategy's background setting. */
63
+ background?: boolean;
64
+ supersedeReads: boolean;
65
+ progressRatio: number;
66
+ pruneEnabled: boolean;
67
+ pruneProtectTokens: number;
68
+ pruneMinSavings: number;
69
+ pruneMinTokens: number;
70
+ shakeProtectTokens: number;
71
+ shakeMinSavings: number;
72
+ shakeBlockMinTokens: number;
73
+ }
74
+
75
+ export const contextKitDefaults: ContextKitOptions = {
76
+ enabled: true,
77
+ threshold: "75%",
78
+ strategy: "balanced",
79
+ supersedeReads: true,
80
+ progressRatio: 0.8,
81
+ pruneEnabled: true,
82
+ pruneProtectTokens: 40_000,
83
+ pruneMinSavings: 20_000,
84
+ pruneMinTokens: 50,
85
+ shakeProtectTokens: 16_000,
86
+ shakeMinSavings: 4_000,
87
+ shakeBlockMinTokens: 400,
88
+ };
89
+
90
+ /** Authored options as Pi's settings store them: every key optional, so absent values inherit. */
91
+ export type ContextKitOptionsPatch = Static<typeof contextKitOptionsSchema>;
92
+ export type ContextKitChange = LayeredSettingChange<ContextKitOptionsPatch>;
93
+
94
+ export const contextKitSettings = defineLayeredSettings({
95
+ namespace: "context-kit",
96
+ label: "context-kit",
97
+ schema: contextKitOptionsSchema,
98
+ defaults: contextKitDefaults,
99
+ sessionEntryType: "pi-context-kit-settings",
100
+ // The namespace marks a scope as moved, so the 0.3 block is not imported again.
101
+ keepEmptyNamespace: true,
102
+ });
103
+
104
+ /** The schema accepts only these three forms, so each one maps without a failure path. */
105
+ function thresholdOf(value: number | string): Threshold {
106
+ if (typeof value === "number") return { tokens: value };
107
+ return value === "pi" ? "pi" : { percent: Number.parseFloat(value) };
108
+ }
109
+
110
+ /** Maps resolved options to the runtime config, with a problem for each ineffective combination. */
111
+ export function contextKitConfig(
112
+ resolved: ResolvedLayeredSettings<ContextKitOptions>,
113
+ ): ConfigResult {
114
+ const { settings, sources } = resolved;
115
+ const { strategy } = settings;
116
+ const customOrder = sources.methodOrder !== "default";
117
+ const methodOrder = [...new Set(settings.methodOrder ?? STRATEGIES[strategy].methodOrder)];
118
+ const background = settings.background ?? STRATEGIES[strategy].background;
119
+ const problems: string[] = [];
120
+ if (sources.strategy !== "default" && customOrder)
121
+ problems.push(
122
+ `strategy "${strategy}" does not set the method order, because methodOrder replaces it`,
123
+ );
124
+ if (customOrder && sources.background !== "default" && background && !writesHandoff(methodOrder))
125
+ problems.push(
126
+ 'background has no effect, because "handoff" is not before "soft" in the method order',
127
+ );
128
+ return {
129
+ config: {
130
+ enabled: settings.enabled,
131
+ threshold: thresholdOf(settings.threshold),
132
+ strategy,
133
+ methodOrder,
134
+ customOrder,
135
+ background,
136
+ supersedeReads: settings.supersedeReads,
137
+ prune: {
138
+ enabled: settings.pruneEnabled,
139
+ protectTokens: settings.pruneProtectTokens,
140
+ minSavings: settings.pruneMinSavings,
141
+ minTokens: settings.pruneMinTokens,
142
+ },
143
+ shake: {
144
+ protectTokens: settings.shakeProtectTokens,
145
+ minSavings: settings.shakeMinSavings,
146
+ blockMinTokens: settings.shakeBlockMinTokens,
147
+ },
148
+ progressRatio: settings.progressRatio,
149
+ },
150
+ problems,
151
+ };
152
+ }
package/src/menu.ts ADDED
@@ -0,0 +1,159 @@
1
+ import type { LayeredSettingScope, LayeredSettingSource } from "pi-hl-utils/layered-settings";
2
+ import {
3
+ effectiveWithSource,
4
+ type SettingRow,
5
+ type SettingsMenuSpec,
6
+ } from "pi-hl-utils/settings-menu";
7
+
8
+ import {
9
+ type ContextKitChange,
10
+ type ContextKitOptions,
11
+ type ContextKitOptionsPatch,
12
+ contextKitSettings,
13
+ } from "./context-kit-settings.ts";
14
+
15
+ type OptionKey = keyof ContextKitOptionsPatch;
16
+
17
+ /** What the menu displays, read again after each change. */
18
+ export interface ContextKitMenuView {
19
+ headline: readonly string[];
20
+ /** Writable scopes; `project` only when the project is trusted. */
21
+ scopes: readonly LayeredSettingScope[];
22
+ /** Effective options after scope precedence. */
23
+ settings: ContextKitOptions;
24
+ sources: Readonly<Partial<Record<OptionKey, LayeredSettingSource>>>;
25
+ /** Options that each scope authors itself. */
26
+ authored: Readonly<Partial<Record<LayeredSettingScope, ContextKitOptionsPatch>>>;
27
+ }
28
+
29
+ /** The extension side of the menu: reads the view and applies one change. */
30
+ export interface ContextKitMenuHost {
31
+ view(): ContextKitMenuView;
32
+ /** Validates, persists, and applies one change; a rejection shows inline in the menu. */
33
+ apply(scope: LayeredSettingScope, change: ContextKitChange): Promise<void>;
34
+ }
35
+
36
+ const onOffKeys = new Set<OptionKey>(["enabled", "background", "supersedeReads", "pruneEnabled"]);
37
+ const strategyValues = ["balanced", "frugal", "pi-summary"] as const;
38
+
39
+ const descriptions = {
40
+ enabled:
41
+ "Makes room in a long conversation so the agent keeps working. Off leaves only Pi's own cleanup.",
42
+ threshold:
43
+ "Where cleanup starts: a token count, a percentage such as 75% of each window, or pi for Pi's own limit.",
44
+ strategy:
45
+ "balanced writes notes ahead of time. frugal shortens old outputs without a model call. pi-summary uses Pi's own summary.",
46
+ methodOrder:
47
+ "What to try, in order, when the context stays above the threshold after pruning. Overrides strategy.",
48
+ background: "Writes the handoff note in the background, before the threshold.",
49
+ supersedeReads: "Replaces the old copy of a file that the model read again.",
50
+ progressRatio:
51
+ "Each method must bring the context to this fraction of the threshold, or the next method runs.",
52
+ pruneEnabled: "Clears old tool outputs and file reads from the context.",
53
+ pruneProtectTokens: "Recent tokens that pruning leaves as they are.",
54
+ pruneMinSavings: "Pruning runs only when it saves at least this many tokens.",
55
+ pruneMinTokens: "Outputs smaller than this many tokens are never pruned.",
56
+ shakeProtectTokens: "Recent tokens that shaking leaves as they are.",
57
+ shakeMinSavings: "Shaking runs only when it saves at least this many tokens.",
58
+ shakeBlockMinTokens: "Blocks smaller than this many tokens are never elided.",
59
+ } satisfies Record<OptionKey, string>;
60
+
61
+ const hints: Partial<Record<OptionKey, string>> = {
62
+ threshold: "a token count, a percentage such as 75%, pi, or inherit",
63
+ strategy: "balanced, frugal, pi-summary, or inherit",
64
+ methodOrder: "handoff, shake and soft, comma-separated, or inherit",
65
+ progressRatio: "a number above 0, up to 1, or inherit",
66
+ };
67
+
68
+ /** Display text of an option value; an unset value reads as inherit. */
69
+ function valueText(value: unknown): string {
70
+ if (value === undefined) return "inherit";
71
+ if (Array.isArray(value)) return value.join(", ");
72
+ if (typeof value === "boolean") return value ? "on" : "off";
73
+ if (typeof value === "number" || typeof value === "string") return String(value);
74
+ throw new Error(`Unexpected option value: ${JSON.stringify(value)}`);
75
+ }
76
+
77
+ /** The JSON value that menu text stands for; the option schema validates it before any write. */
78
+ function menuValue(key: OptionKey, text: string): unknown {
79
+ if (onOffKeys.has(key)) return text === "on" ? true : text === "off" ? false : text;
80
+ if (key === "threshold" && /^\d+$/.test(text)) return Number(text);
81
+ if (key === "methodOrder") return text.split(",").map((method) => method.trim());
82
+ if (key === "strategy" || key === "threshold") return text;
83
+ return Number(text);
84
+ }
85
+
86
+ /** One change typed or chosen in the menu for one scope. */
87
+ export function menuChange(
88
+ key: string,
89
+ text: string,
90
+ scope: LayeredSettingScope,
91
+ ): ContextKitChange {
92
+ const optionKey = contextKitSettings.optionKey(key);
93
+ const value = text.trim();
94
+ if (value === "inherit") return { action: "inherit", key: optionKey };
95
+ if (value === "") throw new Error(`Enter a value for ${optionKey}, or inherit`);
96
+ return {
97
+ action: "set",
98
+ key: optionKey,
99
+ patch: contextKitSettings.parseOptions({ [optionKey]: menuValue(optionKey, value) }, scope),
100
+ };
101
+ }
102
+
103
+ /** Values a cycled row steps through; `inherit` removes the scope's own value. */
104
+ function cycleValues(key: OptionKey): readonly string[] {
105
+ if (key === "strategy") return ["inherit", ...strategyValues];
106
+ return ["inherit", "on", "off"];
107
+ }
108
+
109
+ function isCycleKey(key: OptionKey): boolean {
110
+ return key === "strategy" || onOffKeys.has(key);
111
+ }
112
+
113
+ function optionRow(
114
+ view: ContextKitMenuView,
115
+ scope: LayeredSettingScope,
116
+ id: string,
117
+ ): SettingRow<ContextKitChange> {
118
+ const key = contextKitSettings.optionKey(id);
119
+ const source = view.sources[key] ?? "default";
120
+ const fields = {
121
+ id: key,
122
+ label: source === "default" ? key : `${key} [${source}]`,
123
+ description: descriptions[key],
124
+ };
125
+ if (isCycleKey(key)) {
126
+ const own = view.authored[scope]?.[key];
127
+ return {
128
+ kind: "cycle",
129
+ ...fields,
130
+ values: cycleValues(key),
131
+ own: own === undefined ? undefined : valueText(own),
132
+ inEffect: effectiveWithSource(valueText(view.settings[key]), source),
133
+ source,
134
+ change: (value, scope) => menuChange(key, value, scope),
135
+ };
136
+ }
137
+ return {
138
+ kind: "input",
139
+ ...fields,
140
+ value: valueText(view.settings[key]),
141
+ hint: hints[key] ?? "a whole number, 0 or more, or inherit",
142
+ change: (text, scope) => menuChange(key, text, scope),
143
+ };
144
+ }
145
+
146
+ /** The `/context-kit` settings menu: a Scope row, then one row per option. */
147
+ export function contextKitMenuSpec(
148
+ host: ContextKitMenuHost,
149
+ ): SettingsMenuSpec<ContextKitMenuView, ContextKitChange> {
150
+ return {
151
+ title: "Context cleanup settings",
152
+ read: () => host.view(),
153
+ rows: (view, scope) => [
154
+ { kind: "scope" },
155
+ ...contextKitSettings.optionKeys.map((id) => optionRow(view, scope, id)),
156
+ ],
157
+ apply: (scope, change) => host.apply(scope, change),
158
+ };
159
+ }
package/src/migrate.ts CHANGED
@@ -1,6 +1,7 @@
1
+ import { isRecord } from "pi-hl-utils/record";
2
+
1
3
  import {
2
4
  isMethod,
3
- isRecord,
4
5
  isStrategy,
5
6
  type Method,
6
7
  STRATEGIES,
@@ -14,6 +15,97 @@ const NAMES = Object.keys(STRATEGIES).filter(isStrategy);
14
15
  /** Keys 0.3 had at the top level that 0.4 keeps under `advanced`, unchanged. */
15
16
  const ADVANCED = ["supersedeReads", "progressRatio", "prune", "shake"];
16
17
 
18
+ /** What one scope has before the import: its namespace, its 0.4 file and its 0.3 block. */
19
+ export interface ScopeSource {
20
+ /** Whether Pi's settings document of this scope already has the `context-kit` namespace. */
21
+ stored: boolean;
22
+ /** The scope's `context-kit.json`, when that file exists. */
23
+ file?: { path: string; content: Record<string, unknown> };
24
+ /** The 0.3 `contextKit` block of Pi's settings document, when it has one. */
25
+ legacy?: unknown;
26
+ }
27
+
28
+ /** Flat options to write to one scope's `context-kit` namespace, and the file they come from. */
29
+ export interface SettingsImport {
30
+ scope: "global" | "project";
31
+ options: Record<string, unknown>;
32
+ /** Renamed to `.migrated` after the options are written. */
33
+ file?: string;
34
+ }
35
+
36
+ /**
37
+ * Plans the import of each scope that has no `context-kit` namespace yet. A scope imports its
38
+ * `context-kit.json` when that file exists, else its 0.3 block. The project block converts over
39
+ * the global settings as they are after this import, as 0.3 merged them.
40
+ */
41
+ export function planSettingsImports(
42
+ global: ScopeSource,
43
+ project: ScopeSource | undefined,
44
+ ): SettingsImport[] {
45
+ const globalNested = nestedGlobal(global);
46
+ const imports: SettingsImport[] = [];
47
+ const globalImport = importOf("global", global, () => globalNested);
48
+ if (globalImport) imports.push(globalImport);
49
+ if (project) {
50
+ const projectImport = importOf("project", project, () =>
51
+ migrateProject(global.legacy ?? {}, project.legacy, globalNested),
52
+ );
53
+ if (projectImport) imports.push(projectImport);
54
+ }
55
+ return imports;
56
+ }
57
+
58
+ function nestedGlobal(global: ScopeSource): Record<string, unknown> {
59
+ if (global.file) return global.file.content;
60
+ return global.legacy === undefined ? {} : migrateLegacy(global.legacy);
61
+ }
62
+
63
+ function importOf(
64
+ scope: SettingsImport["scope"],
65
+ source: ScopeSource,
66
+ legacyNested: () => Record<string, unknown>,
67
+ ): SettingsImport | undefined {
68
+ if (source.stored) return undefined;
69
+ if (source.file)
70
+ return {
71
+ scope,
72
+ options: flattenSettings(source.file.content),
73
+ file: source.file.path,
74
+ };
75
+ if (source.legacy === undefined) return undefined;
76
+ return { scope, options: flattenSettings(legacyNested()) };
77
+ }
78
+
79
+ /**
80
+ * Converts 0.4 nested options, as `context-kit.json` and the 0.3 conversion write them, to the
81
+ * flat keys of the `context-kit` namespace. A nested key with an unknown name keeps its name, so
82
+ * the option schema rejects it.
83
+ */
84
+ export function flattenSettings(nested: Record<string, unknown>): Record<string, unknown> {
85
+ const { $schema: _schema, advanced, ...flat } = nested;
86
+ if (advanced === undefined) return flat;
87
+ if (!isRecord(advanced)) return { ...flat, advanced };
88
+ const { prune, shake, ...options } = advanced;
89
+ return {
90
+ ...flat,
91
+ ...options,
92
+ ...prefixed("prune", prune),
93
+ ...prefixed("shake", shake),
94
+ };
95
+ }
96
+
97
+ /** `{ enabled }` under `prune` becomes `{ pruneEnabled }`; a value that is not an object is kept as it is. */
98
+ function prefixed(prefix: string, value: unknown): Record<string, unknown> {
99
+ if (value === undefined) return {};
100
+ if (!isRecord(value)) return { [prefix]: value };
101
+ return Object.fromEntries(
102
+ Object.entries(value).map(([key, option]) => [
103
+ prefix + key.charAt(0).toUpperCase() + key.slice(1),
104
+ option,
105
+ ]),
106
+ );
107
+ }
108
+
17
109
  /**
18
110
  * Converts the 0.3 `contextKit` block of Pi's settings into the content of `context-kit.json`
19
111
  * with the same behavior. An invalid threshold or method order is dropped, so its default applies,
@@ -1,18 +1,8 @@
1
- import {
2
- chmodSync,
3
- existsSync,
4
- linkSync,
5
- mkdirSync,
6
- readFileSync,
7
- realpathSync,
8
- renameSync,
9
- rmSync,
10
- statSync,
11
- writeFileSync,
12
- } from "node:fs";
13
- import { dirname, join } from "node:path";
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
14
3
 
15
- import { isRecord } from "./config.ts";
4
+ import { errorText } from "pi-hl-utils/errors";
5
+ import { isRecord } from "pi-hl-utils/record";
16
6
 
17
7
  const FILE_NAME = "context-kit.json";
18
8
 
@@ -29,71 +19,6 @@ export function settingsPaths(agentDir: string, cwd: string, trusted: boolean):
29
19
  };
30
20
  }
31
21
 
32
- /** Merges the global and project files. A file that cannot be read is reported and ignored. */
33
- export function loadSettings(paths: SettingsPaths): {
34
- raw: Record<string, unknown>;
35
- problems: string[];
36
- } {
37
- const problems: string[] = [];
38
- let raw: Record<string, unknown> = {};
39
- for (const path of [paths.global, paths.project]) {
40
- if (!path) continue;
41
- try {
42
- raw = mergeSettings(raw, readSettingsFile(path));
43
- } catch (error) {
44
- problems.push(`${errorMessage(error)}, file ignored`);
45
- }
46
- }
47
- return { raw, problems };
48
- }
49
-
50
- /** Sets one top-level key and keeps the rest of the file. The file is replaced atomically. */
51
- export function updateSetting(path: string, key: string, value: unknown) {
52
- const next = { ...readSettingsFile(path), [key]: value };
53
- // The rename replaces the target, so a symbolic link, for example to dotfiles, stays.
54
- const target = existsSync(path) ? realpathSync(path) : path;
55
- mkdirSync(dirname(target), { recursive: true });
56
- const temporary = `${target}.${process.pid}.tmp`;
57
- try {
58
- writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`);
59
- if (existsSync(target)) chmodSync(temporary, statSync(target).mode);
60
- renameSync(temporary, target);
61
- } finally {
62
- rmSync(temporary, { force: true });
63
- }
64
- }
65
-
66
- /** Creates the file with this content. Returns false when the file exists, which it keeps. */
67
- export function createSettings(path: string, content: Record<string, unknown>): boolean {
68
- mkdirSync(dirname(path), { recursive: true });
69
- const temporary = `${path}.${process.pid}.tmp`;
70
- try {
71
- writeFileSync(temporary, `${JSON.stringify(content, null, 2)}\n`);
72
- // The link appears complete or not at all, and fails when the file exists, so two Pi
73
- // processes cannot both create it.
74
- linkSync(temporary, path);
75
- return true;
76
- } catch (error) {
77
- if (isRecord(error) && error.code === "EEXIST") return false;
78
- throw error;
79
- } finally {
80
- rmSync(temporary, { force: true });
81
- }
82
- }
83
-
84
- /**
85
- * Writes the key where it takes effect: the project file when that file sets it, otherwise the
86
- * global file. Returns the path written.
87
- */
88
- export function saveSetting(paths: SettingsPaths, key: string, value: unknown): string {
89
- const path =
90
- paths.project && readSettingsFile(paths.project)[key] !== undefined
91
- ? paths.project
92
- : paths.global;
93
- updateSetting(path, key, value);
94
- return path;
95
- }
96
-
97
22
  /** The content of one settings file, `{}` when it does not exist. Throws when it is not a JSON object. */
98
23
  export function readSettingsFile(path: string): Record<string, unknown> {
99
24
  let text: string;
@@ -101,13 +26,17 @@ export function readSettingsFile(path: string): Record<string, unknown> {
101
26
  text = readFileSync(path, "utf8");
102
27
  } catch (error) {
103
28
  if (isRecord(error) && error.code === "ENOENT") return {};
104
- throw new Error(`${path} cannot be read (${errorMessage(error)})`, { cause: error });
29
+ throw new Error(`${path} cannot be read (${errorText(error)})`, {
30
+ cause: error,
31
+ });
105
32
  }
106
33
  let value: unknown;
107
34
  try {
108
35
  value = JSON.parse(text);
109
36
  } catch (error) {
110
- throw new Error(`${path} is not valid JSON (${errorMessage(error)})`, { cause: error });
37
+ throw new Error(`${path} is not valid JSON (${errorText(error)})`, {
38
+ cause: error,
39
+ });
111
40
  }
112
41
  if (!isRecord(value)) throw new Error(`${path} must contain a JSON object`);
113
42
  return value;
@@ -134,7 +63,3 @@ export function mergeSettings(
134
63
  }
135
64
  return result;
136
65
  }
137
-
138
- function errorMessage(error: unknown): string {
139
- return error instanceof Error ? error.message : String(error);
140
- }
package/src/panel.ts DELETED
@@ -1,75 +0,0 @@
1
- import { type ContextKitConfig, type Strategy, type Threshold } from "./config.ts";
2
-
3
- /** The `SettingItem` fields of `@earendil-works/pi-tui` that the panel uses. */
4
- export interface PanelItem {
5
- id: "enabled" | "threshold" | "strategy";
6
- label: string;
7
- description: string;
8
- currentValue: string;
9
- values: string[];
10
- }
11
-
12
- const PI_LIMIT = "At Pi's limit";
13
- const THRESHOLDS = [...[50, 60, 70, 75, 80, 90].map((percent) => `${percent}% full`), PI_LIMIT];
14
- const METHODS: Readonly<Record<Strategy, string>> = {
15
- balanced: "Summary notes (recommended)",
16
- frugal: "Trim first",
17
- "pi-summary": "Pi's summary",
18
- };
19
-
20
- /** The settings the `/context-kit` panel edits, in plain words. The rest stay in the file. */
21
- export function panelItems(config: ContextKitConfig): PanelItem[] {
22
- const threshold = thresholdText(config.threshold);
23
- const items: PanelItem[] = [
24
- {
25
- id: "enabled",
26
- label: "Automatic cleanup",
27
- description:
28
- "Makes room in a long conversation so the agent keeps working. Off leaves only Pi's own cleanup.",
29
- currentValue: config.enabled ? "On" : "Off",
30
- values: ["On", "Off"],
31
- },
32
- {
33
- id: "threshold",
34
- label: "Clean up when the context is",
35
- description:
36
- "Lower keeps answers faster and cheaper. Higher keeps more detail. At Pi's limit waits as long as Pi does.",
37
- currentValue: threshold,
38
- values: THRESHOLDS.includes(threshold) ? THRESHOLDS : [threshold, ...THRESHOLDS],
39
- },
40
- ];
41
- if (config.customOrder) return items;
42
- items.push({
43
- id: "strategy",
44
- label: "Cleanup method",
45
- description:
46
- "Summary notes: the agent writes notes ahead of time and they replace old messages. Trim first: shorten large old outputs, with no extra model call. Pi's summary: Pi's own summary.",
47
- currentValue: METHODS[config.strategy],
48
- values: Object.values(METHODS),
49
- });
50
- return items;
51
- }
52
-
53
- /** The JSON value to write for a panel choice. */
54
- export function settingValue(id: string, value: string): unknown {
55
- if (id === "enabled") return value === "On";
56
- if (id === "strategy") return Object.entries(METHODS).find(([, label]) => label === value)?.[0];
57
- if (value === PI_LIMIT) return "pi";
58
- const tokens = /^(\d+) tokens$/.exec(value);
59
- return tokens ? Number(tokens[1]) : value.replace(/ full$/, "");
60
- }
61
-
62
- /** One line for modes without the panel. */
63
- export function summaryText(config: ContextKitConfig, file: string): string {
64
- if (!config.enabled) return `pi-context-kit: automatic cleanup off. Settings: ${file}`;
65
- const at = config.threshold === "pi" ? "Pi's limit" : thresholdText(config.threshold);
66
- const method = config.customOrder
67
- ? `custom methods (${config.methodOrder.join(", ") || "none"})`
68
- : METHODS[config.strategy].replace(" (recommended)", "").toLowerCase();
69
- return `pi-context-kit: automatic cleanup at ${at}, with ${method}. Settings: ${file}`;
70
- }
71
-
72
- function thresholdText(threshold: Threshold): string {
73
- if (threshold === "pi") return PI_LIMIT;
74
- return "tokens" in threshold ? `${threshold.tokens} tokens` : `${threshold.percent}% full`;
75
- }