pi-context-kit 0.4.1 → 0.4.3

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
@@ -76,15 +76,11 @@ const boolean: Check<boolean> = {
76
76
  must: "true or false",
77
77
  };
78
78
  const count: Check<number> = {
79
- read: (value) =>
80
- Number.isSafeInteger(value) && Number(value) >= 0
81
- ? Number(value)
82
- : undefined,
79
+ read: (value) => (Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : undefined),
83
80
  must: "a whole number, 0 or more",
84
81
  };
85
82
  const ratio: Check<number> = {
86
- read: (value) =>
87
- typeof value === "number" && value > 0 && value <= 1 ? value : undefined,
83
+ read: (value) => (typeof value === "number" && value > 0 && value <= 1 ? value : undefined),
88
84
  must: "a number above 0, up to 1",
89
85
  };
90
86
  const threshold: Check<Threshold> = {
@@ -101,18 +97,14 @@ export const isMethod = (value: unknown): value is Method =>
101
97
  value === "handoff" || value === "shake" || value === "soft";
102
98
  const methodOrder: Check<Method[]> = {
103
99
  read: (value) =>
104
- Array.isArray(value) && value.every(isMethod)
105
- ? [...new Set(value)]
106
- : undefined,
100
+ Array.isArray(value) && value.every(isMethod) ? [...new Set(value)] : undefined,
107
101
  must: 'a list of "handoff", "shake" and "soft"',
108
102
  };
109
103
 
110
104
  function parseThreshold(value: unknown): Threshold | undefined {
111
105
  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;
106
+ if (Number.isSafeInteger(value) && Number(value) > 0) return { tokens: Number(value) };
107
+ const match = typeof value === "string" ? /^(\d+(?:\.\d+)?)%$/.exec(value) : null;
116
108
  const percent = Number(match?.[1]);
117
109
  return percent > 0 && percent <= 100 ? { percent } : undefined;
118
110
  }
@@ -131,9 +123,7 @@ class Section {
131
123
  if (!path) this.#known.add("$schema");
132
124
  if (raw === undefined || isRecord(raw)) this.#raw = raw ?? {};
133
125
  else {
134
- problems.push(
135
- `${path || "the settings"} must be an object (default used)`,
136
- );
126
+ problems.push(`${path || "the settings"} must be an object (default used)`);
137
127
  this.#raw = {};
138
128
  }
139
129
  }
@@ -149,9 +139,7 @@ class Section {
149
139
  if (value === undefined) return fallback;
150
140
  const parsed = check.read(value);
151
141
  if (parsed !== undefined) return parsed;
152
- this.#problems.push(
153
- `${this.#prefix}${key} must be ${check.must} (default used)`,
154
- );
142
+ this.#problems.push(`${this.#prefix}${key} must be ${check.must} (default used)`);
155
143
  return fallback;
156
144
  }
157
145
 
@@ -163,8 +151,7 @@ class Section {
163
151
  /** Reports keys that no `get` or `section` call read. Call it last. */
164
152
  done(): void {
165
153
  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`);
154
+ if (!this.#known.has(key)) this.#problems.push(`${this.#prefix}${key} is not a setting`);
168
155
  }
169
156
  }
170
157
 
@@ -177,11 +164,7 @@ export function readConfig(raw: unknown): ConfigResult {
177
164
  const limit = root.get("threshold", threshold, d.threshold);
178
165
  const named = root.get("strategy", strategy, d.strategy);
179
166
  const a = root.section("advanced");
180
- const methods = a.get(
181
- "methodOrder",
182
- methodOrder,
183
- STRATEGIES[named].methodOrder,
184
- );
167
+ const methods = a.get("methodOrder", methodOrder, STRATEGIES[named].methodOrder);
185
168
  const background = a.get("background", boolean, STRATEGIES[named].background);
186
169
  const supersedeReads = a.get("supersedeReads", boolean, d.supersedeReads);
187
170
  const progressRatio = a.get("progressRatio", ratio, d.progressRatio);
@@ -195,12 +178,7 @@ export function readConfig(raw: unknown): ConfigResult {
195
178
  problems.push(
196
179
  `strategy "${named}" does not set the method order, because advanced.methodOrder replaces it`,
197
180
  );
198
- if (
199
- customOrder &&
200
- a.provides("background", boolean) &&
201
- background &&
202
- !writesHandoff(methods)
203
- )
181
+ if (customOrder && a.provides("background", boolean) && background && !writesHandoff(methods))
204
182
  problems.push(
205
183
  'advanced.background has no effect, because "handoff" is not before "soft" in the method order',
206
184
  );
@@ -250,11 +228,7 @@ export function isRecord(value: unknown): value is Record<string, unknown> {
250
228
  }
251
229
 
252
230
  /** 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 {
231
+ export function before(methods: readonly Method[], a: Method, b: Method): boolean {
258
232
  const index = methods.indexOf(a);
259
233
  const other = methods.indexOf(b);
260
234
  const soft = methods.indexOf("soft");
@@ -271,10 +245,7 @@ export function writesHandoff(methods: readonly Method[]): boolean {
271
245
  }
272
246
 
273
247
  /** 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 {
248
+ export function ownThreshold(config: ContextKitConfig, contextWindow: number): number {
278
249
  const value = config.threshold;
279
250
  if (value === "pi") return Number.POSITIVE_INFINITY;
280
251
  if ("tokens" in value) return Math.min(contextWindow - 1, value.tokens);
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;
package/src/migrate.ts CHANGED
@@ -28,10 +28,7 @@ export function migrateLegacy(legacy: unknown): Record<string, unknown> {
28
28
  const { strategy, order, background } = methods(old);
29
29
  if (strategy && strategy !== "balanced") result.strategy = strategy;
30
30
  if (!strategy) advanced.methodOrder = order;
31
- if (
32
- writesHandoff(order) &&
33
- background !== STRATEGIES[strategy ?? "balanced"].background
34
- )
31
+ if (writesHandoff(order) && background !== STRATEGIES[strategy ?? "balanced"].background)
35
32
  advanced.background = background;
36
33
  return withAdvanced(result, advanced);
37
34
  }
@@ -47,10 +44,7 @@ export function migrateProject(
47
44
  globalFile: Record<string, unknown>,
48
45
  ): Record<string, unknown> {
49
46
  const project = isRecord(projectLegacy) ? projectLegacy : {};
50
- const merged = mergeSettings(
51
- isRecord(globalLegacy) ? globalLegacy : {},
52
- project,
53
- );
47
+ const merged = mergeSettings(isRecord(globalLegacy) ? globalLegacy : {}, project);
54
48
  const result: Record<string, unknown> = {};
55
49
  if (typeof project.enabled === "boolean") result.enabled = project.enabled;
56
50
  if ("thresholdTokens" in project || "thresholdPercent" in project)
@@ -70,15 +64,12 @@ function projectMethods(
70
64
  globalFile: Record<string, unknown>,
71
65
  ): { strategy?: Strategy; advanced: Record<string, unknown> } {
72
66
  const { strategy, order, background } = methods(merged);
73
- const globalAdvanced = isRecord(globalFile.advanced)
74
- ? globalFile.advanced
75
- : {};
67
+ const globalAdvanced = isRecord(globalFile.advanced) ? globalFile.advanced : {};
76
68
  const advanced: Record<string, unknown> = {};
77
69
  // false avoids the "no effect" warning for a global background that this order does not use.
78
70
  if (writesHandoff(order) || "background" in globalAdvanced)
79
71
  advanced.background = writesHandoff(order) && background;
80
- if (strategy && !("methodOrder" in globalAdvanced))
81
- return { strategy, advanced };
72
+ if (strategy && !("methodOrder" in globalAdvanced)) return { strategy, advanced };
82
73
  return { advanced: { methodOrder: order, ...advanced } };
83
74
  }
84
75
 
@@ -114,8 +105,7 @@ function threshold(old: Record<string, unknown>): number | string {
114
105
  const tokens = old.thresholdTokens;
115
106
  if (Number.isSafeInteger(tokens) && Number(tokens) > 0) return Number(tokens);
116
107
  const percent = old.thresholdPercent;
117
- if (typeof percent === "number" && percent > 0 && percent <= 100)
118
- return `${percent}%`;
108
+ if (typeof percent === "number" && percent > 0 && percent <= 100) return `${percent}%`;
119
109
  return "pi";
120
110
  }
121
111
 
@@ -129,7 +119,5 @@ function methodOrder(value: unknown): Method[] {
129
119
  }
130
120
 
131
121
  function same(a: readonly Method[], b: readonly Method[]): boolean {
132
- return (
133
- a.length === b.length && a.every((method, index) => method === b[index])
134
- );
122
+ return a.length === b.length && a.every((method, index) => method === b[index]);
135
123
  }
package/src/note.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Api, Message, Model, ThinkingLevel } from "@earendil-works/pi-ai";
2
2
  import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
3
+
3
4
  import type { Note } from "./background.ts";
4
5
  import { handoffContext, handoffNote } from "./handoff.ts";
5
6
 
@@ -11,19 +12,17 @@ export interface NoteRequest {
11
12
  messages: readonly Message[];
12
13
  /** The session's level: Anthropic drops the cached messages when thinking differs. */
13
14
  reasoning: ThinkingLevel | undefined;
14
- focus?: string;
15
+ focus?: string | undefined;
15
16
  signal: AbortSignal;
16
- maxTokens?: number;
17
+ maxTokens: number;
17
18
  }
18
19
 
19
20
  /** Sends the turn's tool_choice too: Anthropic drops the cached messages when it differs. */
20
- export async function requestNote(
21
- request: NoteRequest,
22
- ): Promise<Note | undefined> {
21
+ export async function requestNote(request: NoteRequest): Promise<Note | undefined> {
23
22
  const context = handoffContext(request.messages, request.focus);
24
23
  const response = await request.registry
25
24
  .streamSimple(request.model, context, {
26
- reasoning: request.reasoning,
25
+ ...(request.reasoning === undefined ? {} : { reasoning: request.reasoning }),
27
26
  maxTokens: request.maxTokens,
28
27
  signal: request.signal,
29
28
  sessionId: request.sessionId,
package/src/panel.ts CHANGED
@@ -1,8 +1,4 @@
1
- import {
2
- type ContextKitConfig,
3
- type Strategy,
4
- type Threshold,
5
- } from "./config.ts";
1
+ import { type ContextKitConfig, type Strategy, type Threshold } from "./config.ts";
6
2
 
7
3
  /** The `SettingItem` fields of `@earendil-works/pi-tui` that the panel uses. */
8
4
  export interface PanelItem {
@@ -14,10 +10,7 @@ export interface PanelItem {
14
10
  }
15
11
 
16
12
  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
- ];
13
+ const THRESHOLDS = [...[50, 60, 70, 75, 80, 90].map((percent) => `${percent}% full`), PI_LIMIT];
21
14
  const METHODS: Readonly<Record<Strategy, string>> = {
22
15
  balanced: "Summary notes (recommended)",
23
16
  frugal: "Trim first",
@@ -42,9 +35,7 @@ export function panelItems(config: ContextKitConfig): PanelItem[] {
42
35
  description:
43
36
  "Lower keeps answers faster and cheaper. Higher keeps more detail. At Pi's limit waits as long as Pi does.",
44
37
  currentValue: threshold,
45
- values: THRESHOLDS.includes(threshold)
46
- ? THRESHOLDS
47
- : [threshold, ...THRESHOLDS],
38
+ values: THRESHOLDS.includes(threshold) ? THRESHOLDS : [threshold, ...THRESHOLDS],
48
39
  },
49
40
  ];
50
41
  if (config.customOrder) return items;
@@ -62,8 +53,7 @@ export function panelItems(config: ContextKitConfig): PanelItem[] {
62
53
  /** The JSON value to write for a panel choice. */
63
54
  export function settingValue(id: string, value: string): unknown {
64
55
  if (id === "enabled") return value === "On";
65
- if (id === "strategy")
66
- return Object.entries(METHODS).find(([, label]) => label === value)?.[0];
56
+ if (id === "strategy") return Object.entries(METHODS).find(([, label]) => label === value)?.[0];
67
57
  if (value === PI_LIMIT) return "pi";
68
58
  const tokens = /^(\d+) tokens$/.exec(value);
69
59
  return tokens ? Number(tokens[1]) : value.replace(/ full$/, "");
@@ -71,10 +61,8 @@ export function settingValue(id: string, value: string): unknown {
71
61
 
72
62
  /** One line for modes without the panel. */
73
63
  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);
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);
78
66
  const method = config.customOrder
79
67
  ? `custom methods (${config.methodOrder.join(", ") || "none"})`
80
68
  : METHODS[config.strategy].replace(" (recommended)", "").toLowerCase();
@@ -83,7 +71,5 @@ export function summaryText(config: ContextKitConfig, file: string): string {
83
71
 
84
72
  function thresholdText(threshold: Threshold): string {
85
73
  if (threshold === "pi") return PI_LIMIT;
86
- return "tokens" in threshold
87
- ? `${threshold.tokens} tokens`
88
- : `${threshold.percent}% full`;
74
+ return "tokens" in threshold ? `${threshold.tokens} tokens` : `${threshold.percent}% full`;
89
75
  }
package/src/prune.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ProjectedSessionEntry } from "@earendil-works/pi-coding-agent";
2
+
2
3
  import { type Edit, messageTokens, withContent } from "./context.ts";
3
4
  import { newestToolResults, type ToolResult } from "./tool-calls.ts";
4
5
 
@@ -38,7 +39,7 @@ export function pruneToolOutputs(
38
39
  savings += edit.saved;
39
40
  edits.push(edit.edit);
40
41
  }
41
- return savings >= options.minSavings ? edits.reverse() : [];
42
+ return savings >= options.minSavings ? edits.toReversed() : [];
42
43
  }
43
44
 
44
45
  function pruneEdit(
package/src/recall.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Worker } from "node:worker_threads";
2
+
2
3
  import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
3
4
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
4
5
 
@@ -21,8 +22,7 @@ const DEFAULT_CHARS = 20_000;
21
22
  const SNIPPET_CHARS = 160;
22
23
  const REGEX_DEADLINE_MS = 500;
23
24
 
24
- type RegexWorkerResult =
25
- { type: "success"; indexes: number[] } | { type: "error"; error: string };
25
+ type RegexWorkerResult = { type: "success"; indexes: number[] } | { type: "error"; error: string };
26
26
 
27
27
  /** Searches the raw text of every entry on the branch, including compacted and edited ones. */
28
28
  export async function searchEntries(
@@ -40,25 +40,20 @@ export async function searchEntries(
40
40
  options.query,
41
41
  signal,
42
42
  )
43
- : indexed.map(({ text }) =>
44
- text.toLowerCase().indexOf(options.query.toLowerCase()),
45
- );
43
+ : indexed.map(({ text }) => text.toLowerCase().indexOf(options.query.toLowerCase()));
46
44
  const hits: string[] = [];
47
45
  for (let i = indexed.length - 1; i >= 0; i--) {
48
46
  const item = indexed[i];
49
47
  const index = indexes[i];
50
48
  if (item && index !== undefined && index >= 0)
51
- hits.push(
52
- `${item.entry.id} ${entryLabel(item.entry)}: ${snippet(item.text, index)}`,
53
- );
49
+ hits.push(`${item.entry.id} ${entryLabel(item.entry)}: ${snippet(item.text, index)}`);
54
50
  }
55
51
  if (hits.length === 0) return "No entries match.";
56
52
  const offset = clamp(options.offset, 0, hits.length, 0);
57
53
  const limit = clamp(options.limit, 1, MAX_RESULTS, DEFAULT_RESULTS);
58
54
  const page = hits.slice(offset, offset + limit);
59
55
  const end = offset + page.length;
60
- if (end < hits.length)
61
- page.push(`[${hits.length} matches. Use offset=${end} for more.]`);
56
+ if (end < hits.length) page.push(`[${hits.length} matches. Use offset=${end} for more.]`);
62
57
  return page.join("\n");
63
58
  }
64
59
 
@@ -112,11 +107,7 @@ function regexIndexes(
112
107
  const onAbort = () => finish(() => reject(new Error("Search aborted.")));
113
108
  const timer = setTimeout(
114
109
  () =>
115
- finish(() =>
116
- reject(
117
- new Error(`Regex search exceeded ${REGEX_DEADLINE_MS}ms deadline.`),
118
- ),
119
- ),
110
+ finish(() => reject(new Error(`Regex search exceeded ${REGEX_DEADLINE_MS}ms deadline.`))),
120
111
  REGEX_DEADLINE_MS,
121
112
  );
122
113
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -127,10 +118,7 @@ function regexIndexes(
127
118
  });
128
119
  worker.once("error", (error) => finish(() => reject(error)));
129
120
  worker.once("exit", (code) => {
130
- if (code !== 0)
131
- finish(() =>
132
- reject(new Error(`Regex worker exited with code ${code}.`)),
133
- );
121
+ if (code !== 0) finish(() => reject(new Error(`Regex worker exited with code ${code}.`)));
134
122
  });
135
123
  });
136
124
  }
@@ -138,9 +126,7 @@ function regexIndexes(
138
126
  function entryLabel(entry: SessionEntry): string {
139
127
  if (entry.type !== "message") return entry.type;
140
128
  const { message } = entry;
141
- return message.role === "toolResult"
142
- ? `toolResult ${message.toolName}`
143
- : message.role;
129
+ return message.role === "toolResult" ? `toolResult ${message.toolName}` : message.role;
144
130
  }
145
131
 
146
132
  function entryText(entry: SessionEntry): string {
@@ -157,9 +143,7 @@ function entryText(entry: SessionEntry): string {
157
143
  }
158
144
  }
159
145
 
160
- function messageText(
161
- message: Extract<SessionEntry, { type: "message" }>["message"],
162
- ): string {
146
+ function messageText(message: Extract<SessionEntry, { type: "message" }>["message"]): string {
163
147
  switch (message.role) {
164
148
  case "user":
165
149
  case "custom":
@@ -176,19 +160,17 @@ function messageText(
176
160
  return `[${message.toolName} result${message.isError ? " error" : ""}]\n${contentText(message.content)}`;
177
161
  case "system":
178
162
  return "";
163
+ case "bashExecution":
164
+ return message.excludeFromContext ? "" : JSON.stringify(message);
179
165
  default:
180
166
  return JSON.stringify(message);
181
167
  }
182
168
  }
183
169
 
184
- function contentText(
185
- content: string | readonly (TextContent | ImageContent)[],
186
- ): string {
170
+ function contentText(content: string | readonly (TextContent | ImageContent)[]): string {
187
171
  if (typeof content === "string") return content;
188
172
  return content
189
- .map((block) =>
190
- block.type === "text" ? block.text : `[image ${block.mimeType}]`,
191
- )
173
+ .map((block) => (block.type === "text" ? block.text : `[image ${block.mimeType}]`))
192
174
  .join("\n");
193
175
  }
194
176
 
@@ -201,12 +183,7 @@ function snippet(text: string, index: number): string {
201
183
  return `${start > 0 ? "…" : ""}${flat}${start + SNIPPET_CHARS < text.length ? "…" : ""}`;
202
184
  }
203
185
 
204
- function clamp(
205
- value: number | undefined,
206
- min: number,
207
- max: number,
208
- fallback: number,
209
- ): number {
186
+ function clamp(value: number | undefined, min: number, max: number, fallback: number): number {
210
187
  if (value === undefined || !Number.isFinite(value)) return fallback;
211
188
  return Math.min(max, Math.max(min, Math.floor(value)));
212
189
  }