pi-context-kit 0.3.1 → 0.4.0

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/src/config.ts CHANGED
@@ -1,41 +1,53 @@
1
1
  import type { PruneOptions } from "./prune.ts";
2
2
  import type { ShakeOptions } from "./shake.ts";
3
3
 
4
+ /** Where maintenance starts. `"pi"` leaves only Pi's own compaction threshold. */
5
+ export type Threshold = { tokens: number } | { percent: number } | "pi";
6
+
7
+ /**
8
+ * `handoff`: compact with a note written by the session model.
9
+ * `shake`: elide large blocks and images from older messages, without a model call.
10
+ * `soft`: leave compaction to Pi's own summary.
11
+ */
12
+ export type Method = "handoff" | "shake" | "soft";
13
+
14
+ /** Named method orders, so most users never edit `advanced.methodOrder`. */
15
+ export type Strategy = "balanced" | "frugal" | "pi-summary";
16
+
17
+ export const STRATEGIES: Readonly<
18
+ Record<Strategy, { methodOrder: readonly Method[]; background: boolean }>
19
+ > = {
20
+ balanced: { methodOrder: ["handoff", "shake", "soft"], background: true },
21
+ frugal: { methodOrder: ["shake", "handoff", "soft"], background: false },
22
+ "pi-summary": { methodOrder: ["soft"], background: false },
23
+ };
24
+
4
25
  export interface ContextKitConfig {
5
26
  /** Turns off maintenance and handoff compaction. `recall` stays available. */
6
27
  enabled: boolean;
7
- /** Compact above this many tokens. -1 uses `thresholdPercent`. Overrides `thresholdPercent`. */
8
- thresholdTokens: number;
9
- /** Compact above this percentage of the context window. -1 uses Pi's threshold only. */
10
- thresholdPercent: number;
28
+ threshold: Threshold;
29
+ strategy: Strategy;
11
30
  /** What to try, in order, when the context stays above the threshold after pruning. */
12
31
  methodOrder: Method[];
32
+ /** `advanced.methodOrder` sets the method order, so `strategy` does not. */
33
+ customOrder: boolean;
34
+ /** Write the handoff note in the background before the threshold. */
35
+ background: boolean;
13
36
  /** Replace older reads of a file that was read again. */
14
37
  supersedeReads: boolean;
15
38
  prune: PruneOptions & { enabled: boolean };
16
39
  shake: ShakeOptions;
17
40
  /** Pruning and shaking must reach this fraction of the threshold, or compaction runs instead. */
18
41
  progressRatio: number;
19
- /** Write the handoff note in the background before the threshold. */
20
- asyncEnabled: boolean;
21
42
  }
22
43
 
23
- /**
24
- * `handoff`: compact with a note written by the session model.
25
- * `shake`: elide large blocks and images from older messages, without a model call.
26
- * `soft`: leave compaction to Pi's own summary.
27
- */
28
- export type Method = "handoff" | "shake" | "soft";
29
-
30
- const METHODS: readonly Method[] = ["handoff", "shake", "soft"];
31
- /** Methods that oh-my-pi offers and Pi lacks. They are skipped like methods that are unavailable. */
32
- const UNAVAILABLE: readonly unknown[] = ["remote", "snapcompact"];
33
-
34
44
  export const DEFAULT_CONFIG: ContextKitConfig = {
35
45
  enabled: true,
36
- thresholdTokens: -1,
37
- thresholdPercent: -1,
38
- methodOrder: [...METHODS],
46
+ threshold: { percent: 75 },
47
+ strategy: "balanced",
48
+ methodOrder: [...STRATEGIES.balanced.methodOrder],
49
+ customOrder: false,
50
+ background: STRATEGIES.balanced.background,
39
51
  supersedeReads: true,
40
52
  prune: {
41
53
  enabled: true,
@@ -49,162 +61,224 @@ export const DEFAULT_CONFIG: ContextKitConfig = {
49
61
  blockMinTokens: 400,
50
62
  },
51
63
  progressRatio: 0.8,
52
- asyncEnabled: true,
53
64
  };
54
65
 
55
66
  export interface ConfigResult {
56
67
  config: ContextKitConfig;
57
- /** One message per invalid value. Each invalid value keeps its default. */
68
+ /** One message per invalid value or ineffective combination. Each invalid value keeps its default. */
58
69
  problems: string[];
59
70
  }
60
71
 
61
- type Check<T> = { test: (value: unknown) => value is T; must: string };
72
+ type Check<T> = { read: (value: unknown) => T | undefined; must: string };
62
73
 
63
74
  const boolean: Check<boolean> = {
64
- test: (value) => typeof value === "boolean",
65
- must: "a boolean",
75
+ read: (value) => (typeof value === "boolean" ? value : undefined),
76
+ must: "true or false",
66
77
  };
67
78
  const count: Check<number> = {
68
- test: (value): value is number =>
69
- Number.isSafeInteger(value) && Number(value) >= 0,
70
- must: "a non-negative integer",
79
+ read: (value) =>
80
+ Number.isSafeInteger(value) && Number(value) >= 0
81
+ ? Number(value)
82
+ : undefined,
83
+ must: "a whole number, 0 or more",
84
+ };
85
+ const ratio: Check<number> = {
86
+ read: (value) =>
87
+ typeof value === "number" && value > 0 && value <= 1 ? value : undefined,
88
+ must: "a number above 0, up to 1",
71
89
  };
72
- const tokens: Check<number> = {
73
- test: (value): value is number =>
74
- value === -1 || (Number.isSafeInteger(value) && Number(value) > 0),
75
- must: "-1 or a positive integer",
90
+ const threshold: Check<Threshold> = {
91
+ read: parseThreshold,
92
+ must: 'a positive integer (tokens), a percentage such as "75%", or "pi"',
76
93
  };
77
- const percent: Check<number> = {
78
- test: (value): value is number =>
79
- value === -1 || (typeof value === "number" && value > 0 && value <= 100),
80
- must: "-1 or a number in (0, 100]",
94
+ export const isStrategy = (value: unknown): value is Strategy =>
95
+ value === "balanced" || value === "frugal" || value === "pi-summary";
96
+ const strategy: Check<Strategy> = {
97
+ read: (value) => (isStrategy(value) ? value : undefined),
98
+ must: '"balanced", "frugal" or "pi-summary"',
81
99
  };
82
- const ratio: Check<number> = {
83
- test: (value): value is number =>
84
- typeof value === "number" && value > 0 && value <= 1,
85
- must: "a number in (0, 1]",
100
+ export const isMethod = (value: unknown): value is Method =>
101
+ value === "handoff" || value === "shake" || value === "soft";
102
+ const methodOrder: Check<Method[]> = {
103
+ read: (value) =>
104
+ Array.isArray(value) && value.every(isMethod)
105
+ ? [...new Set(value)]
106
+ : undefined,
107
+ must: 'a list of "handoff", "shake" and "soft"',
86
108
  };
87
109
 
88
- const isMethod = (value: unknown): value is Method =>
89
- METHODS.some((method) => method === value);
90
- const methodOrder: Check<unknown[]> = {
91
- test: (value): value is unknown[] =>
92
- Array.isArray(value) &&
93
- value.every((method) => isMethod(method) || UNAVAILABLE.includes(method)),
94
- must: 'an array of "handoff", "shake", "soft", "remote" or "snapcompact"',
95
- };
110
+ function parseThreshold(value: unknown): Threshold | undefined {
111
+ if (value === "pi") return "pi";
112
+ if (Number.isSafeInteger(value) && Number(value) > 0)
113
+ return { tokens: Number(value) };
114
+ const match =
115
+ typeof value === "string" ? /^(\d+(?:\.\d+)?)%$/.exec(value) : null;
116
+ const percent = Number(match?.[1]);
117
+ return percent > 0 && percent <= 100 ? { percent } : undefined;
118
+ }
96
119
 
97
120
  /** Reads the keys of one settings object and reports invalid or unknown keys. */
98
121
  class Section {
99
122
  readonly #raw: Record<string, unknown>;
100
- readonly #path: string;
123
+ readonly #prefix: string;
101
124
  readonly #problems: string[];
102
125
  readonly #known = new Set<string>();
103
126
 
104
127
  constructor(raw: unknown, path: string, problems: string[]) {
105
- this.#path = path;
128
+ this.#prefix = path ? `${path}.` : "";
106
129
  this.#problems = problems;
130
+ // Editors read `$schema` at the root of the file only.
131
+ if (!path) this.#known.add("$schema");
107
132
  if (raw === undefined || isRecord(raw)) this.#raw = raw ?? {};
108
133
  else {
109
- problems.push(`${path} must be an object`);
134
+ problems.push(
135
+ `${path || "the settings"} must be an object (default used)`,
136
+ );
110
137
  this.#raw = {};
111
138
  }
112
139
  }
113
140
 
141
+ /** Whether the key holds a valid value, so the default was not used. */
142
+ provides<T>(key: string, check: Check<T>): boolean {
143
+ return check.read(this.#raw[key]) !== undefined;
144
+ }
145
+
114
146
  get<T>(key: string, check: Check<T>, fallback: T): T {
115
147
  this.#known.add(key);
116
148
  const value = this.#raw[key];
117
149
  if (value === undefined) return fallback;
118
- if (check.test(value)) return value;
119
- this.#problems.push(`${this.#path}.${key} must be ${check.must}`);
150
+ const parsed = check.read(value);
151
+ if (parsed !== undefined) return parsed;
152
+ this.#problems.push(
153
+ `${this.#prefix}${key} must be ${check.must} (default used)`,
154
+ );
120
155
  return fallback;
121
156
  }
122
157
 
123
158
  section(key: string): Section {
124
159
  this.#known.add(key);
125
- return new Section(this.#raw[key], `${this.#path}.${key}`, this.#problems);
160
+ return new Section(this.#raw[key], `${this.#prefix}${key}`, this.#problems);
126
161
  }
127
162
 
128
163
  /** Reports keys that no `get` or `section` call read. Call it last. */
129
164
  done(): void {
130
165
  for (const key of Object.keys(this.#raw))
131
166
  if (!this.#known.has(key))
132
- this.#problems.push(`${this.#path}.${key} is not a setting`);
167
+ this.#problems.push(`${this.#prefix}${key} is not a setting`);
133
168
  }
134
169
  }
135
170
 
136
- /** Validates the `contextKit` value of Pi's settings. */
171
+ /** Validates the merged contents of the settings files. */
137
172
  export function readConfig(raw: unknown): ConfigResult {
138
173
  const problems: string[] = [];
139
174
  const d = DEFAULT_CONFIG;
140
- const root = new Section(raw, "contextKit", problems);
175
+ const root = new Section(raw, "", problems);
141
176
  const enabled = root.get("enabled", boolean, d.enabled);
142
- const thresholdTokens = root.get(
143
- "thresholdTokens",
144
- tokens,
145
- d.thresholdTokens,
177
+ const limit = root.get("threshold", threshold, d.threshold);
178
+ const named = root.get("strategy", strategy, d.strategy);
179
+ const a = root.section("advanced");
180
+ const methods = a.get(
181
+ "methodOrder",
182
+ methodOrder,
183
+ STRATEGIES[named].methodOrder,
146
184
  );
147
- const thresholdPercent = root.get(
148
- "thresholdPercent",
149
- percent,
150
- d.thresholdPercent,
151
- );
152
- const methods = root.get("methodOrder", methodOrder, d.methodOrder);
153
- const supersedeReads = root.get("supersedeReads", boolean, d.supersedeReads);
154
- const progressRatio = root.get("progressRatio", ratio, d.progressRatio);
155
-
156
- const p = root.section("prune");
157
- const prune = {
158
- enabled: p.get("enabled", boolean, d.prune.enabled),
159
- protectTokens: p.get("protectTokens", count, d.prune.protectTokens),
160
- minSavings: p.get("minSavings", count, d.prune.minSavings),
161
- minTokens: p.get("minTokens", count, d.prune.minTokens),
162
- };
163
- p.done();
164
-
165
- const s = root.section("shake");
166
- const shake = {
167
- protectTokens: s.get("protectTokens", count, d.shake.protectTokens),
168
- minSavings: s.get("minSavings", count, d.shake.minSavings),
169
- blockMinTokens: s.get("blockMinTokens", count, d.shake.blockMinTokens),
170
- };
171
- s.done();
172
-
173
- const asyncEnabled = root.get("asyncEnabled", boolean, d.asyncEnabled);
185
+ const background = a.get("background", boolean, STRATEGIES[named].background);
186
+ const supersedeReads = a.get("supersedeReads", boolean, d.supersedeReads);
187
+ const progressRatio = a.get("progressRatio", ratio, d.progressRatio);
188
+ const prune = readPrune(a.section("prune"));
189
+ const shake = readShake(a.section("shake"));
190
+ a.done();
174
191
  root.done();
175
192
 
193
+ const customOrder = a.provides("methodOrder", methodOrder);
194
+ if (root.provides("strategy", strategy) && customOrder)
195
+ problems.push(
196
+ `strategy "${named}" does not set the method order, because advanced.methodOrder replaces it`,
197
+ );
198
+ if (
199
+ customOrder &&
200
+ a.provides("background", boolean) &&
201
+ background &&
202
+ !writesHandoff(methods)
203
+ )
204
+ problems.push(
205
+ 'advanced.background has no effect, because "handoff" is not before "soft" in the method order',
206
+ );
207
+
176
208
  return {
177
209
  config: {
178
210
  enabled,
179
- thresholdTokens,
180
- thresholdPercent,
181
- methodOrder: [...new Set(methods.filter(isMethod))],
211
+ threshold: limit,
212
+ strategy: named,
213
+ methodOrder: [...methods],
214
+ customOrder,
215
+ background,
182
216
  supersedeReads,
183
217
  prune,
184
218
  shake,
185
219
  progressRatio,
186
- asyncEnabled,
187
220
  },
188
221
  problems,
189
222
  };
190
223
  }
191
224
 
225
+ function readPrune(p: Section): ContextKitConfig["prune"] {
226
+ const d = DEFAULT_CONFIG.prune;
227
+ const prune = {
228
+ enabled: p.get("enabled", boolean, d.enabled),
229
+ protectTokens: p.get("protectTokens", count, d.protectTokens),
230
+ minSavings: p.get("minSavings", count, d.minSavings),
231
+ minTokens: p.get("minTokens", count, d.minTokens),
232
+ };
233
+ p.done();
234
+ return prune;
235
+ }
236
+
237
+ function readShake(s: Section): ShakeOptions {
238
+ const d = DEFAULT_CONFIG.shake;
239
+ const shake = {
240
+ protectTokens: s.get("protectTokens", count, d.protectTokens),
241
+ minSavings: s.get("minSavings", count, d.minSavings),
242
+ blockMinTokens: s.get("blockMinTokens", count, d.blockMinTokens),
243
+ };
244
+ s.done();
245
+ return shake;
246
+ }
247
+
192
248
  export function isRecord(value: unknown): value is Record<string, unknown> {
193
249
  return typeof value === "object" && value !== null && !Array.isArray(value);
194
250
  }
195
251
 
252
+ /** Soft ends the extension's strategy chain, even when other methods follow it. */
253
+ export function before(
254
+ methods: readonly Method[],
255
+ a: Method,
256
+ b: Method,
257
+ ): boolean {
258
+ const index = methods.indexOf(a);
259
+ const other = methods.indexOf(b);
260
+ const soft = methods.indexOf("soft");
261
+ const stop = Math.min(
262
+ other >= 0 ? other : Number.POSITIVE_INFINITY,
263
+ soft >= 0 ? soft : Number.POSITIVE_INFINITY,
264
+ );
265
+ return index >= 0 && index < stop;
266
+ }
267
+
268
+ /** Whether the method order writes handoff notes at all. */
269
+ export function writesHandoff(methods: readonly Method[]): boolean {
270
+ return before(methods, "handoff", "soft");
271
+ }
272
+
196
273
  /** The configured threshold for this context window, or +Infinity when only Pi's threshold applies. */
197
274
  export function ownThreshold(
198
275
  config: ContextKitConfig,
199
276
  contextWindow: number,
200
277
  ): number {
201
- if (config.thresholdTokens > 0)
202
- return Math.min(contextWindow - 1, config.thresholdTokens);
203
- if (config.thresholdPercent > 0)
204
- return Math.floor(
205
- (contextWindow * Math.min(99, config.thresholdPercent)) / 100,
206
- );
207
- return Number.POSITIVE_INFINITY;
278
+ const value = config.threshold;
279
+ if (value === "pi") return Number.POSITIVE_INFINITY;
280
+ if ("tokens" in value) return Math.min(contextWindow - 1, value.tokens);
281
+ return Math.floor((contextWindow * Math.min(99, value.percent)) / 100);
208
282
  }
209
283
 
210
284
  /**
package/src/migrate.ts ADDED
@@ -0,0 +1,135 @@
1
+ import {
2
+ isMethod,
3
+ isRecord,
4
+ isStrategy,
5
+ type Method,
6
+ STRATEGIES,
7
+ type Strategy,
8
+ writesHandoff,
9
+ } from "./config.ts";
10
+ import { mergeSettings } from "./settings-file.ts";
11
+
12
+ const NAMES = Object.keys(STRATEGIES).filter(isStrategy);
13
+
14
+ /** Keys 0.3 had at the top level that 0.4 keeps under `advanced`, unchanged. */
15
+ const ADVANCED = ["supersedeReads", "progressRatio", "prune", "shake"];
16
+
17
+ /**
18
+ * Converts the 0.3 `contextKit` block of Pi's settings into the content of `context-kit.json`
19
+ * with the same behavior. An invalid threshold or method order is dropped, so its default applies,
20
+ * as in 0.3. Other values are copied, so the usual checks report an invalid one.
21
+ */
22
+ export function migrateLegacy(legacy: unknown): Record<string, unknown> {
23
+ const old = isRecord(legacy) ? legacy : {};
24
+ const result: Record<string, unknown> = {};
25
+ if (typeof old.enabled === "boolean") result.enabled = old.enabled;
26
+ result.threshold = threshold(old);
27
+ const advanced = copyAdvanced(old);
28
+ const { strategy, order, background } = methods(old);
29
+ if (strategy && strategy !== "balanced") result.strategy = strategy;
30
+ if (!strategy) advanced.methodOrder = order;
31
+ if (
32
+ writesHandoff(order) &&
33
+ background !== STRATEGIES[strategy ?? "balanced"].background
34
+ )
35
+ advanced.background = background;
36
+ return withAdvanced(result, advanced);
37
+ }
38
+
39
+ /**
40
+ * Converts the 0.3 project block, which Pi merged over the global block. It writes only what the
41
+ * project block sets, with the values of the merged block, and overrides `globalFile` where that
42
+ * changes the method order or background.
43
+ */
44
+ export function migrateProject(
45
+ globalLegacy: unknown,
46
+ projectLegacy: unknown,
47
+ globalFile: Record<string, unknown>,
48
+ ): Record<string, unknown> {
49
+ const project = isRecord(projectLegacy) ? projectLegacy : {};
50
+ const merged = mergeSettings(
51
+ isRecord(globalLegacy) ? globalLegacy : {},
52
+ project,
53
+ );
54
+ const result: Record<string, unknown> = {};
55
+ if (typeof project.enabled === "boolean") result.enabled = project.enabled;
56
+ if ("thresholdTokens" in project || "thresholdPercent" in project)
57
+ result.threshold = threshold(merged);
58
+ const advanced = copyAdvanced(project);
59
+ if ("methodOrder" in project || "asyncEnabled" in project) {
60
+ const over = projectMethods(merged, globalFile);
61
+ if (over.strategy) result.strategy = over.strategy;
62
+ Object.assign(advanced, over.advanced);
63
+ }
64
+ return withAdvanced(result, advanced);
65
+ }
66
+
67
+ /** The method settings of the merged block, written so that they override `globalFile`. */
68
+ function projectMethods(
69
+ merged: Record<string, unknown>,
70
+ globalFile: Record<string, unknown>,
71
+ ): { strategy?: Strategy; advanced: Record<string, unknown> } {
72
+ const { strategy, order, background } = methods(merged);
73
+ const globalAdvanced = isRecord(globalFile.advanced)
74
+ ? globalFile.advanced
75
+ : {};
76
+ const advanced: Record<string, unknown> = {};
77
+ // false avoids the "no effect" warning for a global background that this order does not use.
78
+ if (writesHandoff(order) || "background" in globalAdvanced)
79
+ advanced.background = writesHandoff(order) && background;
80
+ if (strategy && !("methodOrder" in globalAdvanced))
81
+ return { strategy, advanced };
82
+ return { advanced: { methodOrder: order, ...advanced } };
83
+ }
84
+
85
+ /** The strategy with the same method order, if any, and the background setting of 0.3. */
86
+ function methods(old: Record<string, unknown>): {
87
+ strategy: Strategy | undefined;
88
+ order: Method[];
89
+ background: boolean;
90
+ } {
91
+ const order = methodOrder(old.methodOrder);
92
+ return {
93
+ strategy: NAMES.find((name) => same(STRATEGIES[name].methodOrder, order)),
94
+ order,
95
+ background: typeof old.asyncEnabled === "boolean" ? old.asyncEnabled : true,
96
+ };
97
+ }
98
+
99
+ function copyAdvanced(old: Record<string, unknown>): Record<string, unknown> {
100
+ const advanced: Record<string, unknown> = {};
101
+ for (const key of ADVANCED) if (key in old) advanced[key] = old[key];
102
+ return advanced;
103
+ }
104
+
105
+ function withAdvanced(
106
+ result: Record<string, unknown>,
107
+ advanced: Record<string, unknown>,
108
+ ): Record<string, unknown> {
109
+ return Object.keys(advanced).length > 0 ? { ...result, advanced } : result;
110
+ }
111
+
112
+ /** 0.3 used `thresholdTokens` when both thresholds were set. */
113
+ function threshold(old: Record<string, unknown>): number | string {
114
+ const tokens = old.thresholdTokens;
115
+ if (Number.isSafeInteger(tokens) && Number(tokens) > 0) return Number(tokens);
116
+ const percent = old.thresholdPercent;
117
+ if (typeof percent === "number" && percent > 0 && percent <= 100)
118
+ return `${percent}%`;
119
+ return "pi";
120
+ }
121
+
122
+ /** 0.3 skipped "remote" and "snapcompact", which 0.4 rejects, and used the default for other values. */
123
+ function methodOrder(value: unknown): Method[] {
124
+ const known = Array.isArray(value)
125
+ ? value.filter((method) => method !== "remote" && method !== "snapcompact")
126
+ : undefined;
127
+ if (known?.every(isMethod)) return [...new Set(known)];
128
+ return [...STRATEGIES.balanced.methodOrder];
129
+ }
130
+
131
+ function same(a: readonly Method[], b: readonly Method[]): boolean {
132
+ return (
133
+ a.length === b.length && a.every((method, index) => method === b[index])
134
+ );
135
+ }
package/src/panel.ts ADDED
@@ -0,0 +1,89 @@
1
+ import {
2
+ type ContextKitConfig,
3
+ type Strategy,
4
+ type Threshold,
5
+ } from "./config.ts";
6
+
7
+ /** The `SettingItem` fields of `@earendil-works/pi-tui` that the panel uses. */
8
+ export interface PanelItem {
9
+ id: "enabled" | "threshold" | "strategy";
10
+ label: string;
11
+ description: string;
12
+ currentValue: string;
13
+ values: string[];
14
+ }
15
+
16
+ const PI_LIMIT = "At Pi's limit";
17
+ const THRESHOLDS = [
18
+ ...[50, 60, 70, 75, 80, 90].map((percent) => `${percent}% full`),
19
+ PI_LIMIT,
20
+ ];
21
+ const METHODS: Readonly<Record<Strategy, string>> = {
22
+ balanced: "Summary notes (recommended)",
23
+ frugal: "Trim first",
24
+ "pi-summary": "Pi's summary",
25
+ };
26
+
27
+ /** The settings the `/context-kit` panel edits, in plain words. The rest stay in the file. */
28
+ export function panelItems(config: ContextKitConfig): PanelItem[] {
29
+ const threshold = thresholdText(config.threshold);
30
+ const items: PanelItem[] = [
31
+ {
32
+ id: "enabled",
33
+ label: "Automatic cleanup",
34
+ description:
35
+ "Makes room in a long conversation so the agent keeps working. Off leaves only Pi's own cleanup.",
36
+ currentValue: config.enabled ? "On" : "Off",
37
+ values: ["On", "Off"],
38
+ },
39
+ {
40
+ id: "threshold",
41
+ label: "Clean up when the context is",
42
+ description:
43
+ "Lower keeps answers faster and cheaper. Higher keeps more detail. At Pi's limit waits as long as Pi does.",
44
+ currentValue: threshold,
45
+ values: THRESHOLDS.includes(threshold)
46
+ ? THRESHOLDS
47
+ : [threshold, ...THRESHOLDS],
48
+ },
49
+ ];
50
+ if (config.customOrder) return items;
51
+ items.push({
52
+ id: "strategy",
53
+ label: "Cleanup method",
54
+ description:
55
+ "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.",
56
+ currentValue: METHODS[config.strategy],
57
+ values: Object.values(METHODS),
58
+ });
59
+ return items;
60
+ }
61
+
62
+ /** The JSON value to write for a panel choice. */
63
+ export function settingValue(id: string, value: string): unknown {
64
+ if (id === "enabled") return value === "On";
65
+ if (id === "strategy")
66
+ return Object.entries(METHODS).find(([, label]) => label === value)?.[0];
67
+ if (value === PI_LIMIT) return "pi";
68
+ const tokens = /^(\d+) tokens$/.exec(value);
69
+ return tokens ? Number(tokens[1]) : value.replace(/ full$/, "");
70
+ }
71
+
72
+ /** One line for modes without the panel. */
73
+ export function summaryText(config: ContextKitConfig, file: string): string {
74
+ if (!config.enabled)
75
+ return `pi-context-kit: automatic cleanup off. Settings: ${file}`;
76
+ const at =
77
+ config.threshold === "pi" ? "Pi's limit" : thresholdText(config.threshold);
78
+ const method = config.customOrder
79
+ ? `custom methods (${config.methodOrder.join(", ") || "none"})`
80
+ : METHODS[config.strategy].replace(" (recommended)", "").toLowerCase();
81
+ return `pi-context-kit: automatic cleanup at ${at}, with ${method}. Settings: ${file}`;
82
+ }
83
+
84
+ function thresholdText(threshold: Threshold): string {
85
+ if (threshold === "pi") return PI_LIMIT;
86
+ return "tokens" in threshold
87
+ ? `${threshold.tokens} tokens`
88
+ : `${threshold.percent}% full`;
89
+ }