@narumitw/pi-context-management 0.0.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/LICENSE +21 -0
- package/README.md +148 -0
- package/docs/context-management.md +257 -0
- package/package.json +57 -0
- package/src/context-management.ts +895 -0
- package/src/context-tools.ts +203 -0
- package/src/context-window.ts +393 -0
- package/src/fingerprint.ts +104 -0
- package/src/index.ts +1 -0
- package/src/notes-state.ts +144 -0
- package/src/pi-context-management.ts +105 -0
- package/src/recall-context.ts +524 -0
- package/src/settings-menu.ts +186 -0
- package/src/settings.ts +175 -0
- package/src/terminal.ts +6 -0
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from "node:util";
|
|
2
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
3
|
+
import { type SessionEntry, sessionEntryToContextMessages } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { createContextBranchScanBudget, parseContextManagementCompaction } from "./context-window.js";
|
|
5
|
+
import { sortedNotes } from "./notes-state.js";
|
|
6
|
+
|
|
7
|
+
export const MAX_RECALL_QUERY_LENGTH = 512;
|
|
8
|
+
export const MAX_RECALL_RESULT_BYTES = 32 * 1024;
|
|
9
|
+
export const MAX_RECALL_MATCHES = 20;
|
|
10
|
+
export const MAX_HISTORY_BRANCH_ENTRY_VISITS = 100_000;
|
|
11
|
+
const MAX_INDEXED_MESSAGE_CHARS = 256 * 1024;
|
|
12
|
+
// Bound source work separately so empty structures and removable terminal controls cannot bypass the limit.
|
|
13
|
+
const MAX_SCANNED_MESSAGE_UNITS = 4 * MAX_INDEXED_MESSAGE_CHARS;
|
|
14
|
+
const MAX_HISTORY_SEARCH_SCAN_UNITS = 4 * MAX_SCANNED_MESSAGE_UNITS;
|
|
15
|
+
const MAX_HISTORY_READ_SCAN_UNITS = MAX_HISTORY_SEARCH_SCAN_UNITS;
|
|
16
|
+
const MAX_HISTORY_READ_DEPTH = 512;
|
|
17
|
+
const READ_CHUNK_BYTES = 12 * 1024;
|
|
18
|
+
|
|
19
|
+
export type RecallSource = "history" | "notes";
|
|
20
|
+
export type RecallAction = "list" | "read" | "search";
|
|
21
|
+
|
|
22
|
+
export interface RecallContextInput {
|
|
23
|
+
source: RecallSource;
|
|
24
|
+
action: RecallAction;
|
|
25
|
+
id?: string;
|
|
26
|
+
query?: string;
|
|
27
|
+
cursor?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface RecallContextLimits {
|
|
31
|
+
firstWindowId?: string;
|
|
32
|
+
historyDetailScanUnits?: number;
|
|
33
|
+
historySearchScanUnits?: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface HistoryMessageItem {
|
|
37
|
+
id: string;
|
|
38
|
+
windowId?: string;
|
|
39
|
+
role: string;
|
|
40
|
+
message: AgentMessage;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface HistoryTraversalBudget {
|
|
44
|
+
remainingVisits: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function visitHistoryEntry(budget: HistoryTraversalBudget): void {
|
|
48
|
+
if (budget.remainingVisits <= 0) {
|
|
49
|
+
throw new Error("context_management_recall_context history branch traversal exceeded its entry limit");
|
|
50
|
+
}
|
|
51
|
+
budget.remainingVisits -= 1;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function parseCursor(cursor: string | undefined): number {
|
|
55
|
+
if (cursor === undefined) return 0;
|
|
56
|
+
if (!/^\d{1,12}$/.test(cursor)) throw new Error("context_management_recall_context cursor is invalid");
|
|
57
|
+
return Number.parseInt(cursor, 10);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function messagePayload(message: AgentMessage): unknown {
|
|
61
|
+
switch (message.role) {
|
|
62
|
+
case "compactionSummary":
|
|
63
|
+
return { summary: message.summary };
|
|
64
|
+
case "branchSummary":
|
|
65
|
+
return { summary: message.summary };
|
|
66
|
+
case "custom":
|
|
67
|
+
return { customType: message.customType, content: message.content };
|
|
68
|
+
case "toolResult":
|
|
69
|
+
return {
|
|
70
|
+
toolName: message.toolName,
|
|
71
|
+
toolCallId: message.toolCallId,
|
|
72
|
+
content: message.content,
|
|
73
|
+
isError: message.isError,
|
|
74
|
+
};
|
|
75
|
+
default: {
|
|
76
|
+
const candidate = message as unknown as Record<string, unknown>;
|
|
77
|
+
return Object.hasOwn(candidate, "content")
|
|
78
|
+
? { content: candidate.content }
|
|
79
|
+
: {
|
|
80
|
+
command: candidate.command,
|
|
81
|
+
output: candidate.output,
|
|
82
|
+
exitCode: candidate.exitCode,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function serializeMessage(message: AgentMessage): string {
|
|
89
|
+
let remainingUnits = MAX_HISTORY_READ_SCAN_UNITS;
|
|
90
|
+
const depths = new WeakMap<object, number>();
|
|
91
|
+
const serialized = JSON.stringify(
|
|
92
|
+
messagePayload(message),
|
|
93
|
+
function boundedReplacer(this: unknown, key, value: unknown) {
|
|
94
|
+
const holderDepth = typeof this === "object" && this !== null ? depths.get(this) : undefined;
|
|
95
|
+
const depth = key === "" && holderDepth === undefined ? 0 : (holderDepth ?? -1) + 1;
|
|
96
|
+
const units = 1 + key.length + (typeof value === "string" ? value.length : 0);
|
|
97
|
+
if (depth > MAX_HISTORY_READ_DEPTH || units > remainingUnits) {
|
|
98
|
+
throw new Error("context_management_recall_context history read exceeded its scan limit");
|
|
99
|
+
}
|
|
100
|
+
remainingUnits -= units;
|
|
101
|
+
if (typeof value === "object" && value !== null) depths.set(value, depth);
|
|
102
|
+
return value;
|
|
103
|
+
},
|
|
104
|
+
);
|
|
105
|
+
if (serialized === undefined) {
|
|
106
|
+
throw new Error("context_management_recall_context selected history payload is not serializable");
|
|
107
|
+
}
|
|
108
|
+
return JSON.stringify(sanitizeJsonValue(JSON.parse(serialized)));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
112
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const INDEXED_CONTENT = Symbol("pi-context-management-indexed-content");
|
|
116
|
+
|
|
117
|
+
interface IndexedContent {
|
|
118
|
+
[INDEXED_CONTENT]: true;
|
|
119
|
+
value: unknown;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function indexedContent(value: unknown): IndexedContent {
|
|
123
|
+
return { [INDEXED_CONTENT]: true, value };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function isIndexedContent(value: unknown): value is IndexedContent {
|
|
127
|
+
return typeof value === "object" && value !== null && (value as IndexedContent)[INDEXED_CONTENT] === true;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function indexedBlock(block: unknown): unknown {
|
|
131
|
+
if (!isRecord(block)) return block;
|
|
132
|
+
switch (block.type) {
|
|
133
|
+
case "text":
|
|
134
|
+
return { type: block.type, text: block.text };
|
|
135
|
+
case "image":
|
|
136
|
+
return { type: block.type, mimeType: block.mimeType };
|
|
137
|
+
case "thinking":
|
|
138
|
+
return {
|
|
139
|
+
type: block.type,
|
|
140
|
+
thinking: block.thinking,
|
|
141
|
+
...(typeof block.redacted === "boolean" ? { redacted: block.redacted } : {}),
|
|
142
|
+
};
|
|
143
|
+
case "toolCall":
|
|
144
|
+
return {
|
|
145
|
+
type: block.type,
|
|
146
|
+
id: block.id,
|
|
147
|
+
name: block.name,
|
|
148
|
+
...(block.name === "context_management_recall_context" ? {} : { arguments: block.arguments }),
|
|
149
|
+
...(typeof block.namespace === "string" ? { namespace: block.namespace } : {}),
|
|
150
|
+
};
|
|
151
|
+
default:
|
|
152
|
+
return block;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function messageIndexPayload(message: AgentMessage): unknown {
|
|
157
|
+
if (message.role === "toolResult" && message.toolName === "context_management_recall_context") {
|
|
158
|
+
return {
|
|
159
|
+
toolName: message.toolName,
|
|
160
|
+
toolCallId: message.toolCallId,
|
|
161
|
+
isError: message.isError,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
const payload = messagePayload(message);
|
|
165
|
+
if (!isRecord(payload) || !Object.hasOwn(payload, "content")) return payload;
|
|
166
|
+
return { ...payload, content: indexedContent(payload.content) };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function isExcludedFromModelContext(message: AgentMessage): boolean {
|
|
170
|
+
return message.role === "bashExecution" && message.excludeFromContext === true;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function* historyMessageItems(
|
|
174
|
+
entries: readonly SessionEntry[],
|
|
175
|
+
budget: HistoryTraversalBudget,
|
|
176
|
+
firstWindowId: string | undefined,
|
|
177
|
+
detailScanBudget: ReturnType<typeof createContextBranchScanBudget>,
|
|
178
|
+
): Generator<HistoryMessageItem> {
|
|
179
|
+
let windowId = firstWindowId;
|
|
180
|
+
for (const entry of entries) {
|
|
181
|
+
visitHistoryEntry(budget);
|
|
182
|
+
if (entry.type === "compaction") {
|
|
183
|
+
const details = parseContextManagementCompaction(entry, detailScanBudget);
|
|
184
|
+
if (details) windowId = details.currentWindowId;
|
|
185
|
+
}
|
|
186
|
+
const messages = sessionEntryToContextMessages(entry);
|
|
187
|
+
for (let index = 0; index < messages.length; index += 1) {
|
|
188
|
+
const message = messages[index];
|
|
189
|
+
if (isExcludedFromModelContext(message)) continue;
|
|
190
|
+
yield {
|
|
191
|
+
id: messages.length === 1 ? entry.id : `${entry.id}:${index}`,
|
|
192
|
+
...(windowId ? { windowId } : {}),
|
|
193
|
+
role: message.role,
|
|
194
|
+
message,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function isActiveToolCallMessage(message: AgentMessage, toolCallId: string | undefined): boolean {
|
|
201
|
+
return (
|
|
202
|
+
toolCallId !== undefined &&
|
|
203
|
+
message.role === "assistant" &&
|
|
204
|
+
message.content.some((block) => block.type === "toolCall" && block.id === toolCallId)
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function displayText(value: string): string {
|
|
209
|
+
return Array.from(stripVTControlCharacters(value), (character) => {
|
|
210
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
211
|
+
if (codePoint === 9 || codePoint === 10 || codePoint === 13) return character;
|
|
212
|
+
return codePoint < 32 || (codePoint >= 127 && codePoint <= 159) ? " " : character;
|
|
213
|
+
}).join("");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function normalizedSearchQuery(input: RecallContextInput): string {
|
|
217
|
+
if (!input.query || input.query.length > MAX_RECALL_QUERY_LENGTH || input.id !== undefined) {
|
|
218
|
+
throw new Error(
|
|
219
|
+
`context_management_recall_context search requires a query of 1-${MAX_RECALL_QUERY_LENGTH} characters and does not accept id`,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
const query = displayText(input.query).trim().toLowerCase();
|
|
223
|
+
if (!query) throw new Error("context_management_recall_context search query contains no visible text");
|
|
224
|
+
return query;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function preview(value: string): string {
|
|
228
|
+
const compact = displayText(value).replace(/\s+/g, " ").trim();
|
|
229
|
+
const characters = Array.from(compact);
|
|
230
|
+
return characters.length > 240 ? `${characters.slice(0, 239).join("")}…` : compact;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
interface SearchScanBudget {
|
|
234
|
+
remainingUnits: number;
|
|
235
|
+
exceeded: boolean;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
type PayloadFrame =
|
|
239
|
+
| { kind: "value"; value: unknown }
|
|
240
|
+
| { kind: "array"; value: unknown[]; index: number }
|
|
241
|
+
| { kind: "indexed-content"; value: unknown[]; index: number }
|
|
242
|
+
| { kind: "object"; entries: Iterator<[string, unknown]> }
|
|
243
|
+
| { kind: "text"; value: string };
|
|
244
|
+
|
|
245
|
+
function* ownEntries(value: object): Generator<[string, unknown]> {
|
|
246
|
+
for (const key in value) {
|
|
247
|
+
if (Object.hasOwn(value, key)) yield [key, (value as Record<string, unknown>)[key]];
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function boundedPayloadText(value: unknown, searchBudget?: SearchScanBudget): string {
|
|
252
|
+
let scannedUnits = 0;
|
|
253
|
+
let text = "";
|
|
254
|
+
const consume = (requestedUnits: number): number => {
|
|
255
|
+
const allowedByMessage = Math.min(requestedUnits, MAX_SCANNED_MESSAGE_UNITS - scannedUnits);
|
|
256
|
+
const consumedUnits = Math.min(allowedByMessage, searchBudget?.remainingUnits ?? allowedByMessage);
|
|
257
|
+
scannedUnits += consumedUnits;
|
|
258
|
+
if (searchBudget) {
|
|
259
|
+
searchBudget.remainingUnits -= consumedUnits;
|
|
260
|
+
if (consumedUnits < allowedByMessage) searchBudget.exceeded = true;
|
|
261
|
+
}
|
|
262
|
+
return consumedUnits;
|
|
263
|
+
};
|
|
264
|
+
const append = (value: string) => {
|
|
265
|
+
const part = value.slice(0, consume(value.length));
|
|
266
|
+
text += displayText(part).slice(0, MAX_INDEXED_MESSAGE_CHARS - text.length);
|
|
267
|
+
};
|
|
268
|
+
const frames: PayloadFrame[] = [{ kind: "value", value }];
|
|
269
|
+
while (
|
|
270
|
+
frames.length > 0 &&
|
|
271
|
+
scannedUnits < MAX_SCANNED_MESSAGE_UNITS &&
|
|
272
|
+
text.length < MAX_INDEXED_MESSAGE_CHARS &&
|
|
273
|
+
!searchBudget?.exceeded
|
|
274
|
+
) {
|
|
275
|
+
const frame = frames.pop();
|
|
276
|
+
if (!frame) break;
|
|
277
|
+
if (frame.kind === "text") {
|
|
278
|
+
append(frame.value);
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
if (frame.kind === "array") {
|
|
282
|
+
if (frame.index < frame.value.length) {
|
|
283
|
+
frames.push(
|
|
284
|
+
{ kind: "array", value: frame.value, index: frame.index + 1 },
|
|
285
|
+
{ kind: "value", value: frame.value[frame.index] },
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
if (frame.kind === "indexed-content") {
|
|
291
|
+
if (frame.index < frame.value.length && consume(1) === 1) {
|
|
292
|
+
frames.push(
|
|
293
|
+
{ kind: "indexed-content", value: frame.value, index: frame.index + 1 },
|
|
294
|
+
{ kind: "value", value: indexedBlock(frame.value[frame.index]) },
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
if (frame.kind === "object") {
|
|
300
|
+
const next = frame.entries.next();
|
|
301
|
+
if (!next.done) {
|
|
302
|
+
const [key, item] = next.value;
|
|
303
|
+
frames.push(
|
|
304
|
+
frame,
|
|
305
|
+
{ kind: "text", value: "\n" },
|
|
306
|
+
{ kind: "value", value: item },
|
|
307
|
+
{ kind: "text", value: `${key} ` },
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
if (consume(1) < 1) continue;
|
|
313
|
+
const item = frame.value;
|
|
314
|
+
if (typeof item === "string") {
|
|
315
|
+
append(item);
|
|
316
|
+
} else if (typeof item !== "object" || item === null) {
|
|
317
|
+
if (item !== undefined && typeof item !== "function" && typeof item !== "symbol") {
|
|
318
|
+
append(String(item));
|
|
319
|
+
}
|
|
320
|
+
} else if (isIndexedContent(item)) {
|
|
321
|
+
if (Array.isArray(item.value)) frames.push({ kind: "indexed-content", value: item.value, index: 0 });
|
|
322
|
+
else frames.push({ kind: "value", value: item.value });
|
|
323
|
+
} else if (Array.isArray(item)) {
|
|
324
|
+
frames.push({ kind: "array", value: item, index: 0 });
|
|
325
|
+
} else {
|
|
326
|
+
frames.push({ kind: "object", entries: ownEntries(item) });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return text;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function boundedMessageText(message: AgentMessage, searchBudget?: SearchScanBudget): string {
|
|
333
|
+
return boundedPayloadText(messageIndexPayload(message), searchBudget);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function paged<T>(values: readonly T[], offset: number) {
|
|
337
|
+
const items = values.slice(offset, offset + MAX_RECALL_MATCHES);
|
|
338
|
+
const next = offset + items.length;
|
|
339
|
+
return {
|
|
340
|
+
items,
|
|
341
|
+
...(next < values.length ? { nextCursor: String(next) } : {}),
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function searchPage<T>(values: Iterable<T>, offset: number, matches: (value: T) => boolean) {
|
|
346
|
+
const items: T[] = [];
|
|
347
|
+
let matchIndex = 0;
|
|
348
|
+
for (const value of values) {
|
|
349
|
+
if (!matches(value)) continue;
|
|
350
|
+
if (matchIndex >= offset) items.push(value);
|
|
351
|
+
matchIndex += 1;
|
|
352
|
+
if (items.length > MAX_RECALL_MATCHES) break;
|
|
353
|
+
}
|
|
354
|
+
const hasMore = items.length > MAX_RECALL_MATCHES;
|
|
355
|
+
return {
|
|
356
|
+
items: items.slice(0, MAX_RECALL_MATCHES),
|
|
357
|
+
...(hasMore ? { nextCursor: String(offset + MAX_RECALL_MATCHES) } : {}),
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function readChunk(value: string, offset: number) {
|
|
362
|
+
if (offset > value.length) throw new Error("context_management_recall_context cursor exceeds the selected item");
|
|
363
|
+
if (
|
|
364
|
+
offset > 0 &&
|
|
365
|
+
offset < value.length &&
|
|
366
|
+
/[\uDC00-\uDFFF]/.test(value[offset]) &&
|
|
367
|
+
/[\uD800-\uDBFF]/.test(value[offset - 1])
|
|
368
|
+
) {
|
|
369
|
+
throw new Error("context_management_recall_context cursor splits a Unicode code point");
|
|
370
|
+
}
|
|
371
|
+
let bytes = 0;
|
|
372
|
+
let next = offset;
|
|
373
|
+
for (const character of value.slice(offset)) {
|
|
374
|
+
const characterBytes = Buffer.byteLength(character, "utf8");
|
|
375
|
+
if (bytes + characterBytes > READ_CHUNK_BYTES) break;
|
|
376
|
+
bytes += characterBytes;
|
|
377
|
+
next += character.length;
|
|
378
|
+
}
|
|
379
|
+
const chunk = value.slice(offset, next);
|
|
380
|
+
return {
|
|
381
|
+
chunk,
|
|
382
|
+
...(next < value.length ? { nextCursor: String(next) } : {}),
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function sanitizeJsonValue(value: unknown): unknown {
|
|
387
|
+
if (typeof value === "string") return displayText(value);
|
|
388
|
+
if (Array.isArray(value)) return value.map(sanitizeJsonValue);
|
|
389
|
+
if (typeof value !== "object" || value === null) return value;
|
|
390
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [displayText(key), sanitizeJsonValue(item)]));
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function safeJson(value: unknown): string {
|
|
394
|
+
const text = JSON.stringify(sanitizeJsonValue(value), null, 2);
|
|
395
|
+
if (Buffer.byteLength(text, "utf8") > MAX_RECALL_RESULT_BYTES) {
|
|
396
|
+
throw new Error("context_management_recall_context result exceeded its output limit");
|
|
397
|
+
}
|
|
398
|
+
if (text.split("\n").length > 1_000) {
|
|
399
|
+
throw new Error("context_management_recall_context result exceeded its line limit");
|
|
400
|
+
}
|
|
401
|
+
return text;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
export function recallContext(
|
|
405
|
+
entries: readonly SessionEntry[],
|
|
406
|
+
input: RecallContextInput,
|
|
407
|
+
activeToolCallId?: string,
|
|
408
|
+
limits: RecallContextLimits = {},
|
|
409
|
+
): { text: string; details: Record<string, unknown> } {
|
|
410
|
+
if (input.source !== "history" && input.source !== "notes") {
|
|
411
|
+
throw new Error("context_management_recall_context source must be history or notes");
|
|
412
|
+
}
|
|
413
|
+
if (input.action !== "list" && input.action !== "read" && input.action !== "search") {
|
|
414
|
+
throw new Error("context_management_recall_context action must be list, read, or search");
|
|
415
|
+
}
|
|
416
|
+
const offset = parseCursor(input.cursor);
|
|
417
|
+
if (input.action === "read" && (!input.id || input.query !== undefined)) {
|
|
418
|
+
throw new Error("context_management_recall_context read requires id and does not accept query");
|
|
419
|
+
}
|
|
420
|
+
const searchQuery = input.action === "search" ? normalizedSearchQuery(input) : "";
|
|
421
|
+
if (input.action === "list" && (input.id !== undefined || input.query !== undefined)) {
|
|
422
|
+
throw new Error("context_management_recall_context list does not accept id or query");
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
if (input.source === "notes") {
|
|
426
|
+
const notes = sortedNotes(entries);
|
|
427
|
+
if (input.action === "list") {
|
|
428
|
+
const page = paged(
|
|
429
|
+
notes.map((note) => ({ id: note.name, bytes: Buffer.byteLength(note.content, "utf8") })),
|
|
430
|
+
offset,
|
|
431
|
+
);
|
|
432
|
+
return { text: safeJson({ source: "notes", action: "list", ...page }), details: page };
|
|
433
|
+
}
|
|
434
|
+
if (input.action === "read") {
|
|
435
|
+
const note = notes.find((candidate) => candidate.name === input.id);
|
|
436
|
+
if (!note) throw new Error(`Context note ${JSON.stringify(displayText(input.id ?? ""))} was not found`);
|
|
437
|
+
const page = readChunk(displayText(note.content), offset);
|
|
438
|
+
return {
|
|
439
|
+
text: safeJson({ source: "notes", action: "read", id: note.name, ...page }),
|
|
440
|
+
details: { source: "notes", id: note.name, ...page },
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
const matches = searchPage(notes, offset, (note) =>
|
|
444
|
+
displayText(`${note.name}\n${note.content.slice(0, MAX_INDEXED_MESSAGE_CHARS)}`)
|
|
445
|
+
.toLowerCase()
|
|
446
|
+
.includes(searchQuery),
|
|
447
|
+
);
|
|
448
|
+
const page = {
|
|
449
|
+
...matches,
|
|
450
|
+
items: matches.items.map((note) => ({ id: note.name, preview: preview(note.content) })),
|
|
451
|
+
};
|
|
452
|
+
return { text: safeJson({ source: "notes", action: "search", ...page }), details: page };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const detailScanBudget = createContextBranchScanBudget();
|
|
456
|
+
if (limits.historyDetailScanUnits !== undefined) {
|
|
457
|
+
detailScanBudget.remainingScanUnits = limits.historyDetailScanUnits;
|
|
458
|
+
}
|
|
459
|
+
const history = historyMessageItems(
|
|
460
|
+
entries,
|
|
461
|
+
{ remainingVisits: MAX_HISTORY_BRANCH_ENTRY_VISITS },
|
|
462
|
+
limits.firstWindowId,
|
|
463
|
+
detailScanBudget,
|
|
464
|
+
);
|
|
465
|
+
if (input.action === "list") {
|
|
466
|
+
const selected = searchPage(history, offset, () => true);
|
|
467
|
+
const page = {
|
|
468
|
+
...selected,
|
|
469
|
+
items: selected.items.map((item) => ({
|
|
470
|
+
id: item.id,
|
|
471
|
+
...(item.windowId ? { windowId: item.windowId } : {}),
|
|
472
|
+
role: item.role,
|
|
473
|
+
preview: preview(boundedMessageText(item.message)),
|
|
474
|
+
})),
|
|
475
|
+
};
|
|
476
|
+
return { text: safeJson({ source: "history", action: "list", ...page }), details: page };
|
|
477
|
+
}
|
|
478
|
+
if (input.action === "read") {
|
|
479
|
+
let item: HistoryMessageItem | undefined;
|
|
480
|
+
for (const candidate of history) {
|
|
481
|
+
if (candidate.id !== input.id) continue;
|
|
482
|
+
item = candidate;
|
|
483
|
+
break;
|
|
484
|
+
}
|
|
485
|
+
if (!item) throw new Error(`History item ${JSON.stringify(displayText(input.id ?? ""))} was not found`);
|
|
486
|
+
const content = serializeMessage(item.message);
|
|
487
|
+
const page = readChunk(content, offset);
|
|
488
|
+
return {
|
|
489
|
+
text: safeJson({
|
|
490
|
+
source: "history",
|
|
491
|
+
action: "read",
|
|
492
|
+
id: item.id,
|
|
493
|
+
...(item.windowId ? { windowId: item.windowId } : {}),
|
|
494
|
+
role: item.role,
|
|
495
|
+
...page,
|
|
496
|
+
}),
|
|
497
|
+
details: { source: "history", id: item.id, ...page },
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
const searchBudget: SearchScanBudget = {
|
|
501
|
+
remainingUnits: limits.historySearchScanUnits ?? MAX_HISTORY_SEARCH_SCAN_UNITS,
|
|
502
|
+
exceeded: false,
|
|
503
|
+
};
|
|
504
|
+
const indexedText = new Map<string, string>();
|
|
505
|
+
const matches = searchPage(history, offset, (item) => {
|
|
506
|
+
if (isActiveToolCallMessage(item.message, activeToolCallId)) return false;
|
|
507
|
+
const text = boundedMessageText(item.message, searchBudget);
|
|
508
|
+
if (searchBudget.exceeded) {
|
|
509
|
+
throw new Error("context_management_recall_context history search exceeded its scan limit");
|
|
510
|
+
}
|
|
511
|
+
indexedText.set(item.id, text);
|
|
512
|
+
return text.toLowerCase().includes(searchQuery);
|
|
513
|
+
});
|
|
514
|
+
const page = {
|
|
515
|
+
...matches,
|
|
516
|
+
items: matches.items.map((item) => ({
|
|
517
|
+
id: item.id,
|
|
518
|
+
...(item.windowId ? { windowId: item.windowId } : {}),
|
|
519
|
+
role: item.role,
|
|
520
|
+
preview: preview(indexedText.get(item.id) ?? ""),
|
|
521
|
+
})),
|
|
522
|
+
};
|
|
523
|
+
return { text: safeJson({ source: "history", action: "search", ...page }), details: page };
|
|
524
|
+
}
|