pi-context-kit 0.4.2 → 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.
Files changed (39) hide show
  1. package/CHANGELOG.md +22 -8
  2. package/LICENSE +1 -1
  3. package/README.md +162 -151
  4. package/context-kit.schema.json +62 -78
  5. package/extensions/index.ts +279 -256
  6. package/node_modules/pi-hl-utils/LICENSE +21 -0
  7. package/node_modules/pi-hl-utils/package.json +47 -0
  8. package/node_modules/pi-hl-utils/src/errors.ts +9 -0
  9. package/node_modules/pi-hl-utils/src/evidence.ts +363 -0
  10. package/node_modules/pi-hl-utils/src/expand-on-click.ts +90 -0
  11. package/node_modules/pi-hl-utils/src/layered-settings.ts +513 -0
  12. package/node_modules/pi-hl-utils/src/null-optional-arguments.ts +147 -0
  13. package/node_modules/pi-hl-utils/src/pi-agent-session-discovery.ts +48 -0
  14. package/node_modules/pi-hl-utils/src/record.ts +3 -0
  15. package/node_modules/pi-hl-utils/src/settings-command.ts +213 -0
  16. package/node_modules/pi-hl-utils/src/settings-menu.ts +477 -0
  17. package/node_modules/pi-hl-utils/src/token-calibration.ts +39 -0
  18. package/node_modules/pi-hl-utils/src/ui.ts +355 -0
  19. package/package.json +42 -44
  20. package/src/background.ts +2 -3
  21. package/src/command.ts +17 -0
  22. package/src/config.ts +3 -207
  23. package/src/context-kit-settings.ts +152 -0
  24. package/src/context.ts +43 -16
  25. package/src/files.ts +6 -13
  26. package/src/handoff.ts +3 -7
  27. package/src/maintain.ts +6 -19
  28. package/src/menu.ts +159 -0
  29. package/src/migrate.ts +99 -19
  30. package/src/note.ts +5 -6
  31. package/src/prune.ts +2 -1
  32. package/src/recall.ts +14 -37
  33. package/src/settings-file.ts +13 -101
  34. package/src/shake.ts +6 -12
  35. package/src/stale.ts +22 -26
  36. package/src/status.ts +2 -6
  37. package/src/tool-calls.ts +2 -3
  38. package/README.zh-CN.md +0 -387
  39. package/src/panel.ts +0 -89
package/src/config.ts CHANGED
@@ -41,220 +41,19 @@ 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 invalid value or ineffective combination. Each invalid value keeps its default. */
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) =>
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",
89
- };
90
- const threshold: Check<Threshold> = {
91
- read: parseThreshold,
92
- must: 'a positive integer (tokens), a percentage such as "75%", or "pi"',
93
- };
94
50
  export const isStrategy = (value: unknown): value is Strategy =>
95
51
  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"',
99
- };
100
52
  export const isMethod = (value: unknown): value is Method =>
101
53
  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"',
108
- };
109
-
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
- }
119
-
120
- /** Reads the keys of one settings object and reports invalid or unknown keys. */
121
- class Section {
122
- readonly #raw: Record<string, unknown>;
123
- readonly #prefix: string;
124
- readonly #problems: string[];
125
- readonly #known = new Set<string>();
126
-
127
- constructor(raw: unknown, path: string, problems: string[]) {
128
- this.#prefix = path ? `${path}.` : "";
129
- this.#problems = problems;
130
- // Editors read `$schema` at the root of the file only.
131
- if (!path) this.#known.add("$schema");
132
- if (raw === undefined || isRecord(raw)) this.#raw = raw ?? {};
133
- else {
134
- problems.push(
135
- `${path || "the settings"} must be an object (default used)`,
136
- );
137
- this.#raw = {};
138
- }
139
- }
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
-
146
- get<T>(key: string, check: Check<T>, fallback: T): T {
147
- this.#known.add(key);
148
- const value = this.#raw[key];
149
- if (value === undefined) return fallback;
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
- );
155
- return fallback;
156
- }
157
-
158
- section(key: string): Section {
159
- this.#known.add(key);
160
- return new Section(this.#raw[key], `${this.#prefix}${key}`, this.#problems);
161
- }
162
-
163
- /** Reports keys that no `get` or `section` call read. Call it last. */
164
- done(): void {
165
- for (const key of Object.keys(this.#raw))
166
- if (!this.#known.has(key))
167
- this.#problems.push(`${this.#prefix}${key} is not a setting`);
168
- }
169
- }
170
-
171
- /** Validates the merged contents of the settings files. */
172
- export function readConfig(raw: unknown): ConfigResult {
173
- const problems: string[] = [];
174
- const d = DEFAULT_CONFIG;
175
- const root = new Section(raw, "", problems);
176
- const enabled = root.get("enabled", boolean, d.enabled);
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,
184
- );
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();
191
- root.done();
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
-
208
- return {
209
- config: {
210
- enabled,
211
- threshold: limit,
212
- strategy: named,
213
- methodOrder: [...methods],
214
- customOrder,
215
- background,
216
- supersedeReads,
217
- prune,
218
- shake,
219
- progressRatio,
220
- },
221
- problems,
222
- };
223
- }
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
-
248
- export function isRecord(value: unknown): value is Record<string, unknown> {
249
- return typeof value === "object" && value !== null && !Array.isArray(value);
250
- }
251
54
 
252
55
  /** 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 {
56
+ export function before(methods: readonly Method[], a: Method, b: Method): boolean {
258
57
  const index = methods.indexOf(a);
259
58
  const other = methods.indexOf(b);
260
59
  const soft = methods.indexOf("soft");
@@ -271,10 +70,7 @@ export function writesHandoff(methods: readonly Method[]): boolean {
271
70
  }
272
71
 
273
72
  /** The configured threshold for this context window, or +Infinity when only Pi's threshold applies. */
274
- export function ownThreshold(
275
- config: ContextKitConfig,
276
- contextWindow: number,
277
- ): number {
73
+ export function ownThreshold(config: ContextKitConfig, contextWindow: number): number {
278
74
  const value = config.threshold;
279
75
  if (value === "pi") return Number.POSITIVE_INFINITY;
280
76
  if ("tokens" in value) return Math.min(contextWindow - 1, value.tokens);
@@ -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/context.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { ImageContent, TextContent, ThinkingContent, ToolCall } from "@earendil-works/pi-ai";
2
+ import { getCurrentSystemMessage } from "@earendil-works/pi-ai";
1
3
  import {
2
4
  type ContextEditableContent,
3
5
  type ContextEditEntryDraft,
@@ -18,39 +20,66 @@ export interface Edit {
18
20
  content: ContextEditableContent;
19
21
  }
20
22
 
21
- const EDITABLE_ROLES = new Set(["user", "assistant", "toolResult", "custom"]);
23
+ function isEditable(message: AgentMessage): message is EditableMessage {
24
+ return (
25
+ message.role === "user" ||
26
+ message.role === "assistant" ||
27
+ message.role === "toolResult" ||
28
+ message.role === "custom"
29
+ );
30
+ }
22
31
 
23
32
  /** The single editable message an entry contributes, if any. */
24
- export function editableMessage(
25
- entry: ProjectedSessionEntry,
26
- ): EditableMessage | undefined {
33
+ export function editableMessage(entry: ProjectedSessionEntry): EditableMessage | undefined {
27
34
  if (entry.messages.length !== 1) return undefined;
28
35
  const [message] = entry.messages;
29
- return message && EDITABLE_ROLES.has(message.role)
30
- ? (message as EditableMessage)
31
- : undefined;
36
+ return message && isEditable(message) ? message : undefined;
32
37
  }
33
38
 
34
39
  /** Same rule as Pi's projected estimate: the current system message plus every other message. */
35
40
  export function contextTokens(messages: readonly AgentMessage[]): number {
36
- let system: AgentMessage | undefined;
37
- let tokens = 0;
41
+ const system = getCurrentSystemMessage(messages);
42
+ let tokens = system ? estimateTokens(system) : 0;
38
43
  for (const message of messages) {
39
- if (message.role === "system") system = message;
40
- else tokens += estimateTokens(message);
44
+ if (message.role !== "system") tokens += estimateTokens(message);
41
45
  }
42
- return tokens + (system ? estimateTokens(system) : 0);
46
+ return tokens;
43
47
  }
44
48
 
45
49
  export function messageTokens(message: AgentMessage): number {
46
50
  return estimateTokens(message);
47
51
  }
48
52
 
53
+ type ContentPart = Exclude<ContextEditableContent, string>[number];
54
+
55
+ function isTextOrImage(part: ContentPart): part is TextContent | ImageContent {
56
+ return part.type === "text" || part.type === "image";
57
+ }
58
+
59
+ function isAssistantPart(part: ContentPart): part is TextContent | ThinkingContent | ToolCall {
60
+ return part.type === "text" || part.type === "thinking" || part.type === "toolCall";
61
+ }
62
+
63
+ /** Applies replacement content the way Pi does: roles without string content get one text part. */
49
64
  export function withContent(
50
65
  message: EditableMessage,
51
66
  content: ContextEditableContent,
52
67
  ): EditableMessage {
53
- return { ...message, content } as EditableMessage;
68
+ const parts = typeof content === "string" ? [{ type: "text" as const, text: content }] : content;
69
+ switch (message.role) {
70
+ case "user":
71
+ case "custom":
72
+ if (typeof content === "string") return { ...message, content };
73
+ if (content.every(isTextOrImage)) return { ...message, content };
74
+ break;
75
+ case "assistant":
76
+ if (parts.every(isAssistantPart)) return { ...message, content: parts };
77
+ break;
78
+ case "toolResult":
79
+ if (parts.every(isTextOrImage)) return { ...message, content: parts };
80
+ break;
81
+ }
82
+ throw new Error(`A ${message.role} message cannot hold this replacement content.`);
54
83
  }
55
84
 
56
85
  /** Applies edits to projected entries without mutating them. */
@@ -69,9 +98,7 @@ export function applyEdits(
69
98
  });
70
99
  }
71
100
 
72
- export function projectedMessages(
73
- entries: readonly ProjectedSessionEntry[],
74
- ): AgentMessage[] {
101
+ export function projectedMessages(entries: readonly ProjectedSessionEntry[]): AgentMessage[] {
75
102
  return entries.flatMap((entry) => entry.messages);
76
103
  }
77
104
 
package/src/files.ts CHANGED
@@ -27,28 +27,21 @@ export function fileLists(branch: readonly SessionEntry[]): FileLists {
27
27
  if (block.type === "toolCall") add(block.name, block.arguments);
28
28
  }
29
29
  } else if (message.role === "toolResult") {
30
- for (const call of message.nestedCalls?.calls ?? [])
31
- add(call.name, call.arguments);
30
+ for (const call of message.nestedCalls?.calls ?? []) add(call.name, call.arguments);
32
31
  }
33
32
  }
34
33
  return {
35
- readFiles: [...read].filter((path) => !modified.has(path)).sort(),
36
- modifiedFiles: [...modified].sort(),
34
+ readFiles: [...read].filter((path) => !modified.has(path)).toSorted(),
35
+ modifiedFiles: [...modified].toSorted(),
37
36
  };
38
37
  }
39
38
 
40
39
  /** The file sections Pi appends to its own compaction summaries. */
41
- export function formatFileLists({
42
- readFiles,
43
- modifiedFiles,
44
- }: FileLists): string {
40
+ export function formatFileLists({ readFiles, modifiedFiles }: FileLists): string {
45
41
  const sections: string[] = [];
46
- if (readFiles.length > 0)
47
- sections.push(`<read-files>\n${readFiles.join("\n")}\n</read-files>`);
42
+ if (readFiles.length > 0) sections.push(`<read-files>\n${readFiles.join("\n")}\n</read-files>`);
48
43
  if (modifiedFiles.length > 0) {
49
- sections.push(
50
- `<modified-files>\n${modifiedFiles.join("\n")}\n</modified-files>`,
51
- );
44
+ sections.push(`<modified-files>\n${modifiedFiles.join("\n")}\n</modified-files>`);
52
45
  }
53
46
  return sections.join("\n\n");
54
47
  }
package/src/handoff.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { AssistantMessage, Context, Message } from "@earendil-works/pi-ai";
2
2
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
+
3
4
  import { type FileLists, fileLists, formatFileLists } from "./files.ts";
4
5
 
5
6
  /** Asks for the sections of Pi's own compaction summary, written from the live context. */
@@ -31,10 +32,7 @@ What the user is trying to accomplish.
31
32
  The most recent messages stay visible after the note, but cover them too. Be dense and specific.`;
32
33
 
33
34
  /** The live conversation plus a final request for a handoff note, so the cached prefix is reused. */
34
- export function handoffContext(
35
- messages: readonly Message[],
36
- focus?: string,
37
- ): Context {
35
+ export function handoffContext(messages: readonly Message[], focus?: string): Context {
38
36
  const text = focus?.trim()
39
37
  ? `${HANDOFF_PROMPT}\n\nGive extra attention to: ${focus.trim()}`
40
38
  : HANDOFF_PROMPT;
@@ -57,9 +55,7 @@ export function handoffNote(response: AssistantMessage): string | undefined {
57
55
  response.stopReason === "aborted" ||
58
56
  response.stopReason === "length"
59
57
  ) {
60
- throw new Error(
61
- response.errorMessage ?? `Handoff request ${response.stopReason}`,
62
- );
58
+ throw new Error(response.errorMessage ?? `Handoff request ${response.stopReason}`);
63
59
  }
64
60
  // Text next to a tool call is a preamble to more work, not a note.
65
61
  if (response.content.some((block) => block.type === "toolCall")) {
package/src/maintain.ts CHANGED
@@ -1,11 +1,7 @@
1
1
  import type { ProjectedSessionEntry } from "@earendil-works/pi-coding-agent";
2
- import {
3
- applyEdits,
4
- contextTokens,
5
- type Edit,
6
- projectedMessages,
7
- } from "./context.ts";
2
+
8
3
  import type { ContextKitConfig } from "./config.ts";
4
+ import { applyEdits, contextTokens, type Edit, projectedMessages } from "./context.ts";
9
5
  import { pruneToolOutputs } from "./prune.ts";
10
6
  import { type ShakeOptions, shake } from "./shake.ts";
11
7
  import { supersededReads } from "./stale.ts";
@@ -44,23 +40,14 @@ export function planMaintenance(input: MaintenanceInput): MaintenancePlan {
44
40
  const unchanged = { edits: [], tokens: input.tokens };
45
41
  if (input.tokens <= input.threshold) return unchanged;
46
42
 
47
- const stale = options.supersedeReads
48
- ? supersededReads(input.entries, input.edited)
49
- : [];
43
+ const stale = options.supersedeReads ? supersededReads(input.entries, input.edited) : [];
50
44
  const afterStale = applyEdits(input.entries, stale);
51
45
 
52
- const edited = new Set([
53
- ...input.edited,
54
- ...stale.map((edit) => edit.targetId),
55
- ]);
56
- const pruned = options.prune.enabled
57
- ? pruneToolOutputs(afterStale, edited, options.prune)
58
- : [];
46
+ const edited = new Set([...input.edited, ...stale.map((edit) => edit.targetId)]);
47
+ const pruned = options.prune.enabled ? pruneToolOutputs(afterStale, edited, options.prune) : [];
59
48
  const afterPrune = applyEdits(afterStale, pruned);
60
49
  const shaken = options.shake ? shake(afterPrune, options.shake) : [];
61
- const reducedTokens = contextTokens(
62
- projectedMessages(applyEdits(afterPrune, shaken)),
63
- );
50
+ const reducedTokens = contextTokens(projectedMessages(applyEdits(afterPrune, shaken)));
64
51
  if (reducedTokens <= input.threshold * options.progressRatio) {
65
52
  const edits = latestPerTarget([...stale, ...pruned, ...shaken]);
66
53
  return edits.length > 0 ? { edits, tokens: reducedTokens } : unchanged;