@floydous/pi-agent-kernel 0.3.1 → 0.3.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.
@@ -1,365 +0,0 @@
1
- /**
2
- * Per-session content-addressed dedup store.
3
- *
4
- * Trigger: SHA-256 of the rendered tool-result text combined with the tool
5
- * name and a stable digest of the input parameters. Same content + same
6
- * tool + same params = dedup. Same content + different tool or different
7
- * params = new ref. This is a strict byte-equality rule with one extra
8
- * dimension (input identity) so that `read(file, offset=1, limit=200)`
9
- * and `read(file, offset=100, limit=100)` are not deduped against each
10
- * other, even if the rendered bytes happen to overlap.
11
- *
12
- * Reference format: "r1", "r2", ... per-session monotonic counter.
13
- * LRU-bounded: oldest entries are evicted when the per-session cap is
14
- * exceeded, with a preference for evicting entries the LLM has already
15
- * lost track of (entries whose `lastSeenInContext` is below the session's
16
- * current compaction counter).
17
- *
18
- * Compaction safety: each entry records `lastSeenInContext` (the compaction
19
- * counter value at the time the result was emitted). A duplicate is only
20
- * deduped when the prior entry's `lastSeenInContext` matches the current
21
- * compaction counter for the session — meaning the LLM still has the prior
22
- * full text in its current context. After any compaction, the next duplicate
23
- * is treated as a new first occurrence.
24
- */
25
-
26
- import * as crypto from "node:crypto";
27
-
28
- export interface DedupEntry {
29
- shortRef: string;
30
- contentHash: string;
31
- /** Tool name (e.g. "read", "code_search", "bash"). */
32
- toolName: string;
33
- /** Full SHA-256 digest of the stable input parameters; authoritative key. */
34
- paramsHash: string;
35
- /** Short hex digest of the input parameters for display; 4 hex chars. */
36
- paramsKey: string;
37
- callId: string;
38
- fullText: string;
39
- sizeBytes: number;
40
- lastSeenInContext: number;
41
- }
42
-
43
- export interface RecordResult {
44
- isDuplicate: boolean;
45
- shortRef: string;
46
- priorRef: string | null;
47
- }
48
-
49
- export interface DedupStoreOptions {
50
- /** Don't record or dedup results whose text length is <= this many bytes. */
51
- minBytes?: number;
52
- /**
53
- * LRU cap per session. Oldest entries are evicted first, with a
54
- * preference for evicting entries the LLM has lost track of (post-
55
- * compaction) before evicting still-live ones.
56
- */
57
- maxEntriesPerSession?: number;
58
- }
59
-
60
- const DEFAULT_MIN_BYTES = 80;
61
- const DEFAULT_MAX_ENTRIES = 1024;
62
-
63
- export class DedupStore {
64
- private bySession = new Map<string, SessionState>();
65
- private minBytes: number;
66
- private maxEntries: number;
67
-
68
- constructor(options: DedupStoreOptions = {}) {
69
- this.minBytes = options.minBytes ?? DEFAULT_MIN_BYTES;
70
- this.maxEntries = options.maxEntriesPerSession ?? DEFAULT_MAX_ENTRIES;
71
- }
72
-
73
- private getOrCreateSession(sessionId: string): SessionState {
74
- let s = this.bySession.get(sessionId);
75
- if (!s) {
76
- s = {
77
- entries: new Map<string, DedupEntry>(),
78
- byDedupKey: new Map<string, string>(),
79
- insertionOrder: [],
80
- compactionCounter: 0,
81
- nextRefNumber: 1,
82
- };
83
- this.bySession.set(sessionId, s);
84
- }
85
- return s;
86
- }
87
-
88
- /**
89
- * Record a tool result and decide whether the caller should emit a dedup
90
- * reference or the full text.
91
- *
92
- * @param toolName The name of the tool that produced the result. Used
93
- * as part of the dedup key so `read` and `code_search` of the
94
- * same file produce different refs.
95
- * @param inputParams The tool's input parameters as a plain object
96
- * (e.g. `event.input`). The store applies a stable key-sorted
97
- * stringify so insertion order does not affect the dedup key.
98
- * @param isError Pass-through if true. Errors are never deduped.
99
- * @param currentCompactionCounter Pass the session's current compaction
100
- * counter so the store can decide whether a prior entry is still
101
- * "live" in the LLM's context.
102
- */
103
- record(
104
- sessionId: string,
105
- callId: string,
106
- toolName: string,
107
- inputParams: unknown,
108
- fullText: string,
109
- isError: boolean,
110
- currentCompactionCounter: number,
111
- ): RecordResult {
112
- // Errors and short results are never deduped. Return a fresh ref
113
- // (caller will not use it for a dedup notice; full text is emitted).
114
- if (isError || Buffer.byteLength(fullText, "utf8") <= this.minBytes) {
115
- const s = this.getOrCreateSession(sessionId);
116
- const shortRef = this.allocateRef(s);
117
- const paramsHash = hashParams(inputParams);
118
- const paramsKey = paramsHash.slice(0, 4);
119
- s.entries.set(shortRef, {
120
- shortRef,
121
- contentHash: hashOf(fullText),
122
- toolName,
123
- paramsHash,
124
- paramsKey,
125
- callId,
126
- fullText,
127
- sizeBytes: Buffer.byteLength(fullText, "utf8"),
128
- lastSeenInContext: currentCompactionCounter,
129
- });
130
- // Don't index by dedup key — we don't want a future identical
131
- // content to become a dedup reference to an error or short result.
132
- s.insertionOrder.push(shortRef);
133
- this.evictIfNeeded(s);
134
- return { isDuplicate: false, shortRef, priorRef: null };
135
- }
136
-
137
- const s = this.getOrCreateSession(sessionId);
138
- const contentHash = hashOf(fullText);
139
- const paramsHash = hashParams(inputParams);
140
- const paramsKey = paramsHash.slice(0, 4);
141
- const dedupKey = contentHash + ":" + toolName + ":" + paramsHash;
142
- const priorRef = s.byDedupKey.get(dedupKey);
143
-
144
- if (
145
- priorRef !== undefined &&
146
- s.entries.has(priorRef) &&
147
- s.entries.get(priorRef)!.lastSeenInContext === currentCompactionCounter
148
- ) {
149
- // Duplicate AND same tool + same params AND the LLM still has
150
- // the prior full text. Promote the matched entry to MRU so an
151
- // access-ordered LRU does not evict a hot reference.
152
- this.touchInOrder(s, priorRef);
153
- return { isDuplicate: true, shortRef: priorRef, priorRef };
154
- }
155
-
156
- // Not a duplicate (or a stale one — pre-compaction). Allocate a new
157
- // ref and store. A different `toolName` or different `inputParams`
158
- // naturally produces a different dedupKey, so it does not dedup
159
- // against an existing entry even if `fullText` is byte-equal.
160
- const shortRef = this.allocateRef(s);
161
- s.entries.set(shortRef, {
162
- shortRef,
163
- contentHash,
164
- toolName,
165
- paramsHash,
166
- paramsKey,
167
- callId,
168
- fullText,
169
- sizeBytes: Buffer.byteLength(fullText, "utf8"),
170
- lastSeenInContext: currentCompactionCounter,
171
- });
172
- s.byDedupKey.set(dedupKey, shortRef);
173
- s.insertionOrder.push(shortRef);
174
- this.evictIfNeeded(s);
175
- return { isDuplicate: false, shortRef, priorRef: null };
176
- }
177
-
178
- /**
179
- * Retrieve the full text and metadata for a previously-allocated ref.
180
- * Returns null if the ref is unknown in this session.
181
- */
182
- get(
183
- sessionId: string,
184
- shortRef: string,
185
- ): { fullText: string; sizeBytes: number; toolName: string; paramsKey: string } | null {
186
- const s = this.bySession.get(sessionId);
187
- if (!s) return null;
188
- const entry = s.entries.get(shortRef);
189
- if (!entry) return null;
190
- return {
191
- fullText: entry.fullText,
192
- sizeBytes: entry.sizeBytes,
193
- toolName: entry.toolName,
194
- paramsKey: entry.paramsKey,
195
- };
196
- }
197
-
198
- /**
199
- * Increment the per-session compaction counter. After this call, any
200
- * prior entry that was recorded before the increment will fail the
201
- * `lastSeenInContext === currentCompactionCounter` check on the next
202
- * `record`, so the next duplicate will be treated as a new first
203
- * occurrence.
204
- */
205
- onCompaction(sessionId: string): void {
206
- const s = this.getOrCreateSession(sessionId);
207
- s.compactionCounter += 1;
208
- }
209
-
210
- /**
211
- * Diagnostic accessor. Returns the current compaction counter for the
212
- * session (0 if no compaction has been recorded).
213
- */
214
- getCompactionCounter(sessionId: string): number {
215
- const s = this.bySession.get(sessionId);
216
- return s?.compactionCounter ?? 0;
217
- }
218
-
219
- /**
220
- * Test-only / diagnostic. Number of entries currently held for the session.
221
- */
222
- size(sessionId: string): number {
223
- return this.bySession.get(sessionId)?.entries.size ?? 0;
224
- }
225
-
226
- /**
227
- * Test-only / cleanup. Drop all state for a session.
228
- */
229
- clearSession(sessionId: string): void {
230
- this.bySession.delete(sessionId);
231
- }
232
-
233
- private allocateRef(s: SessionState): string {
234
- const n = s.nextRefNumber++;
235
- return `r${n}`;
236
- }
237
-
238
- /**
239
- * Evict down to the cap. When choosing which entry to evict, prefer
240
- * ones the LLM has already lost track of (post-compaction: their
241
- * `lastSeenInContext` is below the current compaction counter). Only
242
- * fall back to plain LRU (oldest in `insertionOrder`) when no such
243
- * "dead" entries exist.
244
- *
245
- * This is the durability fix from the real-world test: previously, the
246
- * LRU could evict a reference that was still visible in the LLM's
247
- * context, making recall() return "no content stored". Now, anything
248
- * the LLM can still see is preserved at the cost of evicting older
249
- * already-summarized content.
250
- */
251
- private evictIfNeeded(s: SessionState): void {
252
- while (s.insertionOrder.length > this.maxEntries) {
253
- // Pass 1: try to evict an entry that is already dead to the LLM
254
- // (lastSeenInContext is below the current compaction counter).
255
- let evictedAny = false;
256
- for (let i = 0; i < s.insertionOrder.length; i++) {
257
- const candidateRef = s.insertionOrder[i];
258
- const entry = s.entries.get(candidateRef);
259
- if (entry && entry.lastSeenInContext < s.compactionCounter) {
260
- this.evictOne(s, candidateRef);
261
- evictedAny = true;
262
- break;
263
- }
264
- }
265
- if (evictedAny) continue;
266
- // Pass 2: nothing dead to evict. Fall back to plain LRU
267
- // (oldest at the head of insertionOrder). This is the case
268
- // where the cap is too small for the current live context.
269
- const oldestRef = s.insertionOrder.shift();
270
- if (oldestRef === undefined) break;
271
- this.evictOne(s, oldestRef);
272
- }
273
- }
274
-
275
- private evictOne(s: SessionState, ref: string): void {
276
- const entry = s.entries.get(ref);
277
- if (!entry) return;
278
- s.entries.delete(ref);
279
- const dedupKey = entry.contentHash + ":" + entry.toolName + ":" + entry.paramsHash;
280
- // Only delete from byDedupKey if the stored ref still points to
281
- // this entry. (A different entry with the same dedup key may have
282
- // overwritten it; in that case we should not delete the new ref.)
283
- if (s.byDedupKey.get(dedupKey) === ref) {
284
- s.byDedupKey.delete(dedupKey);
285
- }
286
- const idx = s.insertionOrder.indexOf(ref);
287
- if (idx >= 0) s.insertionOrder.splice(idx, 1);
288
- }
289
-
290
- /** Move a ref to the most-recently-used end of the insertion order. */
291
- private touchInOrder(s: SessionState, ref: string): void {
292
- const idx = s.insertionOrder.indexOf(ref);
293
- if (idx === -1) return;
294
- s.insertionOrder.splice(idx, 1);
295
- s.insertionOrder.push(ref);
296
- }
297
- }
298
-
299
- interface SessionState {
300
- entries: Map<string, DedupEntry>;
301
- /** Map from `contentHash:toolName:paramsHash` to ref. */
302
- byDedupKey: Map<string, string>;
303
- /**
304
- * MRU-ordered list of refs. New allocations and dedup hits push to the
305
- * tail; eviction removes from the head. A hit on a prior entry promotes
306
- * it to MRU so the LRU reflects actual access pattern, not just insertion.
307
- */
308
- insertionOrder: string[];
309
- compactionCounter: number;
310
- nextRefNumber: number;
311
- }
312
-
313
- function hashOf(text: string): string {
314
- return crypto.createHash("sha256").update(text, "utf8").digest("hex");
315
- }
316
-
317
- /** Full SHA-256 digest of the stable input parameters. */
318
- function hashParams(inputParams: unknown): string {
319
- const s = typeof inputParams === "string" ? inputParams : stableStringify(inputParams);
320
- return crypto.createHash("sha256").update(s, "utf8").digest("hex");
321
- }
322
-
323
- /**
324
- * Stable JSON stringify with sorted keys. Two equivalent objects with
325
- * different key insertion order produce the same string. This makes the
326
- * paramsKey deterministic for a given semantic input, so
327
- * `read({path: "a"})` and `read({path: "a"})` always match even if the
328
- * harness builds the object in different orders.
329
- */
330
- export function stableStringify(value: unknown): string {
331
- return stringifyStable(value, new Set<unknown>());
332
- }
333
-
334
- function stringifyStable(value: unknown, seen: Set<unknown>): string {
335
- if (value === null) return "null";
336
- if (value === undefined) return "undefined";
337
- const t = typeof value;
338
- if (t === "string") return JSON.stringify(value);
339
- if (t === "number" || t === "boolean") return String(value);
340
- if (t === "bigint") return value.toString();
341
- if (Array.isArray(value)) {
342
- if (seen.has(value)) return '"[circular]"';
343
- seen.add(value);
344
- const parts: string[] = [];
345
- for (const v of value) parts.push(stringifyStable(v, seen));
346
- seen.delete(value);
347
- return "[" + parts.join(",") + "]";
348
- }
349
- if (t === "object") {
350
- const obj = value as Record<string, unknown>;
351
- if (seen.has(obj)) return '"[circular]"';
352
- seen.add(obj);
353
- const keys = Object.keys(obj).sort();
354
- const parts: string[] = [];
355
- for (const k of keys) {
356
- const v = obj[k];
357
- if (v === undefined) continue;
358
- parts.push(JSON.stringify(k) + ":" + stringifyStable(v, seen));
359
- }
360
- seen.delete(obj);
361
- return "{" + parts.join(",") + "}";
362
- }
363
- // Function, symbol, etc. — not a meaningful input parameter; skip.
364
- return '"[unsupported]"';
365
- }
@@ -1,155 +0,0 @@
1
- // Recall Tool
2
- // Dereferences a [=rN,sizeB,tool,paramsKey] dedup notice back to the full
3
- // original tool-result text. No preamble, no formatting — bare bytes only.
4
-
5
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
- import { Type } from "typebox";
7
- import { Text, makeOutputText } from "../ui/tui_utils";
8
- import type { DedupStore } from "./content_store";
9
- import type { SessionDeps } from "../tools/context";
10
-
11
- export interface RecallDeps extends SessionDeps {
12
- getDedupStore: () => DedupStore;
13
- }
14
-
15
- export interface RecallEntry {
16
- fullText: string;
17
- sizeBytes: number;
18
- toolName: string;
19
- paramsKey: string;
20
- }
21
-
22
- /**
23
- * Pure decision logic. Extracted from the tool so it can be unit-tested
24
- * without the Pi extension harness.
25
- *
26
- * Returns one of:
27
- * - { kind: "ok", fullText, sizeBytes, toolName, paramsKey }
28
- * - { kind: "error", message } (validation failure or unknown ref)
29
- */
30
- export function decideRecall(
31
- ref: unknown,
32
- store: {
33
- get: (sessionId: string, ref: string) => RecallEntry | null;
34
- },
35
- sessionId: string,
36
- ):
37
- | { kind: "ok"; fullText: string; sizeBytes: number; toolName: string; paramsKey: string }
38
- | { kind: "error"; message: string } {
39
- const refStr = typeof ref === "string" ? ref.trim() : "";
40
- if (!refStr) {
41
- return { kind: "error", message: "[recall] ref is required (e.g. 'r1')." };
42
- }
43
- if (!/^r\d+$/.test(refStr)) {
44
- return {
45
- kind: "error",
46
- message: `[recall] invalid ref '${refStr}'; expected format 'rN' where N is a positive integer.`,
47
- };
48
- }
49
- const got = store.get(sessionId, refStr);
50
- if (got === null) {
51
- return {
52
- kind: "error",
53
- message: `[recall] no content stored at ref '${refStr}' in this session.`,
54
- };
55
- }
56
- return {
57
- kind: "ok",
58
- fullText: got.fullText,
59
- sizeBytes: got.sizeBytes,
60
- toolName: got.toolName,
61
- paramsKey: got.paramsKey,
62
- };
63
- }
64
-
65
- /** Extracted pattern: registers the `recall` tool. */
66
- export function registerRecallTool(pi: ExtensionAPI, deps: RecallDeps): void {
67
- pi.registerTool({
68
- name: "recall",
69
- label: "Recall Dedup'd Result",
70
- description:
71
- "Recover full text of tool result replaced by dedup reference [=rN,...].",
72
- promptSnippet: "Recover full text of a dedup'd tool result by 'rN' ref",
73
- renderShell: "default",
74
- parameters: Type.Object({
75
- ref: Type.String({
76
- description: "The reference identifier (e.g. 'r1', 'r2')",
77
- }),
78
- }),
79
- async execute(
80
- _toolCallId: string,
81
- params: any,
82
- _signal: any,
83
- _onUpdate: any,
84
- ctx: any,
85
- ): Promise<any> {
86
- const ref = (params?.ref || "").trim();
87
- if (!ref) {
88
- return {
89
- content: [
90
- { type: "text", text: "[recall] ref is required (e.g. 'r1')." },
91
- ],
92
- isError: true,
93
- };
94
- }
95
- if (!/^r\d+$/.test(ref)) {
96
- return {
97
- content: [
98
- {
99
- type: "text",
100
- text: `[recall] invalid ref '${ref}'; expected format 'rN' where N is a positive integer.`,
101
- },
102
- ],
103
- isError: true,
104
- };
105
- }
106
-
107
- const sessionId = deps.getSessionId(ctx);
108
- const store = deps.getDedupStore();
109
- const got = store.get(sessionId, ref);
110
- if (got === null) {
111
- return {
112
- content: [
113
- {
114
- type: "text",
115
- text: `[recall] no content stored at ref '${ref}' in this session.`,
116
- },
117
- ],
118
- isError: true,
119
- };
120
- }
121
-
122
- // Bare text. No preamble, no formatting. The LLM knows what rN is.
123
- // Include toolName and paramsKey in the `details` so the host
124
- // TUI can show provenance but the LLM-context output stays bare.
125
- return {
126
- content: [{ type: "text", text: got.fullText }],
127
- details: {
128
- ref,
129
- sizeBytes: got.sizeBytes,
130
- toolName: got.toolName,
131
- paramsKey: got.paramsKey,
132
- },
133
- };
134
- },
135
- renderCall(args: any, theme: any, _context: any) {
136
- return makeOutputText(
137
- `${theme.fg("toolTitle", theme.bold("recall"))} ${theme.fg("accent", args?.ref || "")}`,
138
- );
139
- },
140
- renderResult(result: any, options: any, theme: any, context: any) {
141
- if (context.isError) {
142
- const errMsg =
143
- result.content?.find((c: any) => c.type === "text")?.text ||
144
- "Recall failed";
145
- return makeOutputText(`\n${theme.fg("error", errMsg)}`);
146
- }
147
- if (!options.expanded) {
148
- return new Text("", 0, 0);
149
- }
150
- const output =
151
- result.content?.find((c: any) => c.type === "text")?.text || "";
152
- return makeOutputText(`\n${theme.fg("toolOutput", output)}`);
153
- },
154
- });
155
- }