@sayknow-cli/agent-core 0.2.2

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 (55) hide show
  1. package/CHANGELOG.md +588 -0
  2. package/README.md +473 -0
  3. package/dist/types/agent-loop.d.ts +56 -0
  4. package/dist/types/agent.d.ts +381 -0
  5. package/dist/types/append-only-context.d.ts +124 -0
  6. package/dist/types/compaction/branch-summarization.d.ts +103 -0
  7. package/dist/types/compaction/compaction.d.ts +253 -0
  8. package/dist/types/compaction/entries.d.ts +109 -0
  9. package/dist/types/compaction/errors.d.ts +26 -0
  10. package/dist/types/compaction/index.d.ts +11 -0
  11. package/dist/types/compaction/messages.d.ts +61 -0
  12. package/dist/types/compaction/openai.d.ts +62 -0
  13. package/dist/types/compaction/pruning.d.ts +37 -0
  14. package/dist/types/compaction/utils.d.ts +32 -0
  15. package/dist/types/compaction.d.ts +1 -0
  16. package/dist/types/harmony-leak.d.ts +99 -0
  17. package/dist/types/index.d.ts +10 -0
  18. package/dist/types/proxy.d.ts +84 -0
  19. package/dist/types/run-collector.d.ts +196 -0
  20. package/dist/types/telemetry.d.ts +596 -0
  21. package/dist/types/thinking.d.ts +18 -0
  22. package/dist/types/types.d.ts +430 -0
  23. package/package.json +75 -0
  24. package/src/agent-loop.ts +1302 -0
  25. package/src/agent.ts +1531 -0
  26. package/src/append-only-context.ts +460 -0
  27. package/src/compaction/branch-summarization.ts +358 -0
  28. package/src/compaction/compaction.ts +1342 -0
  29. package/src/compaction/entries.ts +139 -0
  30. package/src/compaction/errors.ts +31 -0
  31. package/src/compaction/index.ts +12 -0
  32. package/src/compaction/messages.ts +212 -0
  33. package/src/compaction/openai.ts +570 -0
  34. package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
  35. package/src/compaction/prompts/branch-summary-context.md +5 -0
  36. package/src/compaction/prompts/branch-summary-preamble.md +2 -0
  37. package/src/compaction/prompts/branch-summary.md +30 -0
  38. package/src/compaction/prompts/compaction-short-summary.md +9 -0
  39. package/src/compaction/prompts/compaction-summary-context.md +5 -0
  40. package/src/compaction/prompts/compaction-summary.md +38 -0
  41. package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
  42. package/src/compaction/prompts/compaction-update-summary.md +45 -0
  43. package/src/compaction/prompts/file-operations.md +10 -0
  44. package/src/compaction/prompts/handoff-document.md +49 -0
  45. package/src/compaction/prompts/summarization-system.md +3 -0
  46. package/src/compaction/pruning.ts +431 -0
  47. package/src/compaction/utils.ts +185 -0
  48. package/src/compaction.ts +1 -0
  49. package/src/harmony-leak.ts +428 -0
  50. package/src/index.ts +19 -0
  51. package/src/proxy.ts +326 -0
  52. package/src/run-collector.ts +631 -0
  53. package/src/telemetry.ts +2049 -0
  54. package/src/thinking.ts +20 -0
  55. package/src/types.ts +490 -0
@@ -0,0 +1,460 @@
1
+ /**
2
+ * Append-only context mode — stabilizes the byte prefix sent to the LLM
3
+ * across turns so provider prefix caches (DeepSeek, Anthropic, etc.)
4
+ * hit at the maximum possible rate.
5
+ *
6
+ * Two mechanisms:
7
+ *
8
+ * 1. **StablePrefix** — system prompt + tool specs are computed once
9
+ * and frozen. Subsequent turns reuse the exact same byte sequence
10
+ * unless `invalidate()` is called (e.g. after MCP reconnect).
11
+ *
12
+ * 2. **AppendOnlyLog** — messages only grow; prior turns are never
13
+ * re-serialized. Combined with a stable prefix, only the user's new
14
+ * message delta is a cache miss each turn.
15
+ */
16
+
17
+ import type { Context, Message, Tool } from "@sayknow-cli/ai";
18
+ import { normalizeTools } from "./agent-loop";
19
+ import type { AgentContext } from "./types";
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // StablePrefix (formerly ImmutablePrefix)
23
+ // ---------------------------------------------------------------------------
24
+
25
+ /** Frozen system prompt + tool spec snapshot. */
26
+ export interface StablePrefixSnapshot {
27
+ systemPrompt: string[];
28
+ tools: Tool[];
29
+ fingerprint: string;
30
+ }
31
+
32
+ /** Options threaded through `build()` so the snapshot reflects loop-time settings. */
33
+ export interface BuildOptions {
34
+ /** Inject the `_i` intent field into tool schemas (must match agent-loop's normalizeTools). */
35
+ intentTracing: boolean;
36
+ }
37
+
38
+ /**
39
+ * A frozen prefix (system prompt + tools) that produces stable byte
40
+ * sequences across `build()` calls.
41
+ *
42
+ * The first `build()` snapshots the live state. Subsequent calls reuse
43
+ * the cached copy until `invalidate()` is called or the live state's
44
+ * fingerprint changes.
45
+ */
46
+ export class StablePrefix {
47
+ #snapshot: StablePrefixSnapshot | null = null;
48
+ #version = 0;
49
+ #sourceSystemPrompt: readonly string[] | null = null;
50
+ #sourceTools: AgentContext["tools"] | null = null;
51
+ #sourceIntentTracing: boolean | null = null;
52
+
53
+ get fingerprint(): string {
54
+ return this.#snapshot?.fingerprint ?? "<unbuilt>";
55
+ }
56
+ get version(): number {
57
+ return this.#version;
58
+ }
59
+ get built(): boolean {
60
+ return this.#snapshot !== null;
61
+ }
62
+
63
+ exportSnapshot(): StablePrefixSnapshot | null {
64
+ return this.#snapshot ? cloneJson(this.#snapshot) : null;
65
+ }
66
+
67
+ importSnapshot(snapshot: StablePrefixSnapshot, options: BuildOptions): void {
68
+ const systemPrompt = cloneJson(snapshot.systemPrompt);
69
+ const tools = normalizeImportedTools(snapshot.tools, options);
70
+ const fingerprint = computeFingerprint(systemPrompt, tools, options);
71
+ this.#sourceSystemPrompt = null;
72
+ this.#sourceTools = null;
73
+ this.#sourceIntentTracing = null;
74
+ if (fingerprint !== snapshot.fingerprint) {
75
+ throw new Error(
76
+ `StablePrefix.importSnapshot() fingerprint mismatch: expected ${fingerprint}, received ${snapshot.fingerprint}`,
77
+ );
78
+ }
79
+ this.#snapshot = { systemPrompt, tools, fingerprint };
80
+ this.#version++;
81
+ }
82
+
83
+ /**
84
+ * Build or rebuild from live context.
85
+ * Returns `true` if the prefix actually changed (cache miss imminent).
86
+ */
87
+ build(context: AgentContext, options: BuildOptions): boolean {
88
+ if (
89
+ this.#snapshot &&
90
+ this.#sourceSystemPrompt === context.systemPrompt &&
91
+ this.#sourceTools === context.tools &&
92
+ this.#sourceIntentTracing === options.intentTracing
93
+ ) {
94
+ const sourceFingerprint = takeSnapshot(context, options).fingerprint;
95
+ if (this.#snapshot.fingerprint === sourceFingerprint) return false;
96
+ }
97
+ const snapshot = takeSnapshot(context, options);
98
+ if (this.#snapshot && this.#snapshot.fingerprint === snapshot.fingerprint) {
99
+ this.#sourceSystemPrompt = context.systemPrompt;
100
+ this.#sourceTools = context.tools;
101
+ this.#sourceIntentTracing = options.intentTracing;
102
+ return false;
103
+ }
104
+ this.#snapshot = snapshot;
105
+ this.#sourceSystemPrompt = context.systemPrompt;
106
+ this.#sourceTools = context.tools;
107
+ this.#sourceIntentTracing = options.intentTracing;
108
+ this.#version++;
109
+ return true;
110
+ }
111
+
112
+ /** Force rebuild on the next `build()` call. */
113
+ invalidate(): void {
114
+ this.#snapshot = null;
115
+ this.#sourceSystemPrompt = null;
116
+ this.#sourceTools = null;
117
+ this.#sourceIntentTracing = null;
118
+ }
119
+
120
+ /**
121
+ * Returns the cached prefix.
122
+ * @throws if `build()` was never called.
123
+ */
124
+ toContext(): { systemPrompt: string[]; tools: Tool[] } {
125
+ const s = this.#snapshot;
126
+ if (!s) throw new Error("StablePrefix.toContext() called before build()");
127
+ return { systemPrompt: cloneJson(s.systemPrompt), tools: cloneJson(s.tools) };
128
+ }
129
+ }
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // AppendOnlyLog
133
+ // ---------------------------------------------------------------------------
134
+
135
+ /**
136
+ * Append-only message log at the `Message[]` (provider-level) layer.
137
+ *
138
+ * The only mutation path is `replaceTail()`, reserved for compaction.
139
+ * Every other operation is append-only.
140
+ */
141
+ export class AppendOnlyLog {
142
+ #entries: Message[] = [];
143
+
144
+ get length(): number {
145
+ return this.#entries.length;
146
+ }
147
+
148
+ append(message: any): void {
149
+ this.#entries.push(message);
150
+ }
151
+
152
+ extend(messages: any[]): void {
153
+ for (const m of messages) this.#entries.push(m);
154
+ }
155
+
156
+ /** Replace the last entry — only legal for compaction. */
157
+ replaceTail(replacement: any): void {
158
+ const idx = this.#entries.length - 1;
159
+ if (idx >= 0) this.#entries[idx] = replacement;
160
+ }
161
+
162
+ /** Returns a shallow copy of all entries. */
163
+ toMessages(): Message[] {
164
+ return this.#entries.slice();
165
+ }
166
+
167
+ /** Direct readonly access for in-place inspection. */
168
+ entries(): readonly Message[] {
169
+ return this.#entries;
170
+ }
171
+
172
+ clear(): void {
173
+ this.#entries = [];
174
+ }
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // AppendOnlyContextManager
179
+ // ---------------------------------------------------------------------------
180
+
181
+ /**
182
+ * Manages a stable prefix + append-only log for the agent loop.
183
+ *
184
+ * Call `build(context)` each turn to get a `Context` with stable
185
+ * `systemPrompt` and `tools` and append-only messages. Call
186
+ * `syncMessages(normalizedMessages)` after `convertToLlm` each
187
+ * turn to keep the log in sync.
188
+ *
189
+ * Example:
190
+ * ```
191
+ * const mgr = new AppendOnlyContextManager();
192
+ * const ctx = mgr.build(context); // first call snapshots prefix
193
+ * mgr.syncMessages(normalized); // grow the log
194
+ * ctx = mgr.build(context); // subsequent calls use cache
195
+ * ```
196
+ */
197
+ export class AppendOnlyContextManager {
198
+ readonly prefix = new StablePrefix();
199
+ readonly log = new AppendOnlyLog();
200
+ /** How many normalized messages were synced into the log as of the last sync. */
201
+ #lastSyncCount = 0;
202
+ /** Per-synced-message content hashes (rolling digest). Detects in-place rewrites without retaining a full serialized-history string. */
203
+ #syncedHashes: (number | bigint)[] = [];
204
+ /** Number of provider-normalized messages that were seeded before child-local messages. */
205
+ #seededPrefixCount = 0;
206
+
207
+ static forkFromSeed(args: {
208
+ prefixSnapshot?: StablePrefixSnapshot;
209
+ messages?: readonly Message[];
210
+ options: BuildOptions;
211
+ }): AppendOnlyContextManager {
212
+ const manager = new AppendOnlyContextManager();
213
+ if (args.prefixSnapshot) {
214
+ manager.prefix.importSnapshot(args.prefixSnapshot, args.options);
215
+ }
216
+ if (args.messages) {
217
+ manager.seedNormalizedMessages(args.messages);
218
+ }
219
+ return manager;
220
+ }
221
+
222
+ build(context: AgentContext, options: BuildOptions): Context {
223
+ this.prefix.build(context, options);
224
+ const { systemPrompt, tools } = this.prefix.toContext();
225
+ return { systemPrompt, messages: this.log.toMessages(), tools };
226
+ }
227
+
228
+ /**
229
+ * Sync normalized (provider-level) messages into the append-only log.
230
+ *
231
+ * Detects both compaction (shorter array) and in-place rewrites
232
+ * (same length, changed content via a rolling digest).
233
+ */
234
+ syncMessages(normalizedMessages: any[]): void {
235
+ const seededPrefixLength = this.#seededPrefixCount;
236
+ const includesSeedPrefix =
237
+ seededPrefixLength > 0 &&
238
+ normalizedMessages.length >= seededPrefixLength &&
239
+ this.#rangeHashesEqual(normalizedMessages, this.log.entries(), seededPrefixLength);
240
+ const messagesToSync =
241
+ seededPrefixLength > 0 && !includesSeedPrefix
242
+ ? [...this.log.entries().slice(0, seededPrefixLength), ...normalizedMessages]
243
+ : normalizedMessages;
244
+
245
+ // Detect in-place rewrites of already-synced messages via per-message content
246
+ // hashes (no retained full serialized-history string; F5).
247
+ if (
248
+ this.#lastSyncCount > 0 &&
249
+ this.#lastSyncCount <= messagesToSync.length &&
250
+ this.#prefixChanged(messagesToSync, this.#lastSyncCount)
251
+ ) {
252
+ if (this.#seededPrefixCount > 0) {
253
+ // F9: a seeded fork whose inherited prefix changed (e.g. after compaction)
254
+ // rebases onto the new provider context instead of throwing.
255
+ this.#rebaseToBaseline(normalizedMessages);
256
+ return;
257
+ }
258
+ this.log.clear();
259
+ this.#lastSyncCount = 0;
260
+ this.#syncedHashes = [];
261
+ }
262
+
263
+ // Compaction — array shrunk. Seeded forks preserve the inherited prefix and
264
+ // append child-local deltas, so a shorter child array is not a compaction signal
265
+ // while a seed prefix is active; a genuine seeded compaction rebases (F9).
266
+ if (messagesToSync.length < this.#lastSyncCount) {
267
+ if (this.#seededPrefixCount > 0) {
268
+ this.#rebaseToBaseline(normalizedMessages);
269
+ return;
270
+ }
271
+ this.log.clear();
272
+ this.#lastSyncCount = 0;
273
+ this.#syncedHashes = [];
274
+ }
275
+
276
+ const newMsgs = messagesToSync.slice(this.#lastSyncCount);
277
+ for (const msg of newMsgs) {
278
+ this.log.append(msg);
279
+ }
280
+
281
+ this.#lastSyncCount = messagesToSync.length;
282
+ this.#syncedHashes = this.#hashRange(messagesToSync, 0, messagesToSync.length);
283
+ }
284
+
285
+ seedNormalizedMessages(messages: readonly Message[], options?: { reset?: boolean }): void {
286
+ if (this.log.length > 0 && options?.reset !== true) {
287
+ throw new Error("AppendOnlyContextManager.seedNormalizedMessages() cannot seed a non-empty log without reset");
288
+ }
289
+ const clonedMessages = cloneJson([...messages]);
290
+ this.log.clear();
291
+ this.log.extend(clonedMessages);
292
+ this.#lastSyncCount = clonedMessages.length;
293
+ this.#syncedHashes = this.#hashRange(clonedMessages, 0, clonedMessages.length);
294
+ this.#seededPrefixCount = clonedMessages.length;
295
+ }
296
+
297
+ /** Reset prefix + log for a model/provider switch while mode stays active. */
298
+ invalidateForModelChange(): void {
299
+ this.prefix.invalidate();
300
+ this.log.clear();
301
+ this.#lastSyncCount = 0;
302
+ this.#syncedHashes = [];
303
+ this.#seededPrefixCount = 0;
304
+ }
305
+
306
+ /** Reset the sync cursor AND clear the log. */
307
+ resetSyncCursor(): void {
308
+ this.log.clear();
309
+ this.#lastSyncCount = 0;
310
+ this.#syncedHashes = [];
311
+ this.#seededPrefixCount = 0;
312
+ }
313
+
314
+ appendMessage(message: any): void {
315
+ this.log.append(message);
316
+ }
317
+
318
+ replaceTailMessage(message: any): void {
319
+ this.log.replaceTail(message);
320
+ }
321
+
322
+ invalidate(): void {
323
+ this.prefix.invalidate();
324
+ }
325
+
326
+ reset(context: AgentContext, options: BuildOptions): void {
327
+ this.prefix.invalidate();
328
+ this.log.clear();
329
+ this.#lastSyncCount = 0;
330
+ this.#syncedHashes = [];
331
+ this.#seededPrefixCount = 0;
332
+ this.prefix.build(context, options);
333
+ }
334
+
335
+ #hashMessage(message: unknown): number | bigint {
336
+ return hashSource(JSON.stringify(message) ?? "null");
337
+ }
338
+
339
+ #hashRange(messages: readonly unknown[], start: number, end: number): (number | bigint)[] {
340
+ const out: (number | bigint)[] = [];
341
+ for (let i = start; i < end; i++) out.push(this.#hashMessage(messages[i]));
342
+ return out;
343
+ }
344
+
345
+ /** True when the first `count` messages of `a` and `b` are content-equal by per-message hash. */
346
+ #rangeHashesEqual(a: readonly unknown[], b: readonly unknown[], count: number): boolean {
347
+ for (let i = 0; i < count; i++) {
348
+ if (this.#hashMessage(a[i]) !== this.#hashMessage(b[i])) return false;
349
+ }
350
+ return true;
351
+ }
352
+
353
+ /** True when any of the first `count` already-synced messages changed content (in-place rewrite). */
354
+ #prefixChanged(messages: readonly unknown[], count: number): boolean {
355
+ if (count > this.#syncedHashes.length) return false;
356
+ for (let i = 0; i < count; i++) {
357
+ if (this.#hashMessage(messages[i]) !== this.#syncedHashes[i]) return true;
358
+ }
359
+ return false;
360
+ }
361
+
362
+ /** F9: reset the seeded log to a new provider-visible baseline (seeded compaction/rebase). */
363
+ #rebaseToBaseline(messages: readonly unknown[]): void {
364
+ this.log.clear();
365
+ this.log.extend([...messages]);
366
+ this.#lastSyncCount = messages.length;
367
+ this.#seededPrefixCount = 0;
368
+ this.#syncedHashes = this.#hashRange(messages, 0, messages.length);
369
+ }
370
+ }
371
+
372
+ // ---------------------------------------------------------------------------
373
+ // Snapshot helpers
374
+ // ---------------------------------------------------------------------------
375
+
376
+ function hashSource(source: string): number | bigint {
377
+ return typeof Bun !== "undefined" ? Bun.hash(source) : hashString32(source);
378
+ }
379
+
380
+ function hashString32(value: string): number {
381
+ let hash = 0;
382
+ for (let i = 0; i < value.length; i++) {
383
+ hash = ((hash << 5) - hash + value.charCodeAt(i)) | 0;
384
+ }
385
+ return hash >>> 0;
386
+ }
387
+
388
+ function takeSnapshot(context: AgentContext, options: BuildOptions): StablePrefixSnapshot {
389
+ const systemPrompt = [...context.systemPrompt];
390
+ const tools = normalizeTools(context.tools, options.intentTracing) ?? [];
391
+ return {
392
+ systemPrompt,
393
+ tools,
394
+ fingerprint: computeFingerprint(systemPrompt, tools, options),
395
+ };
396
+ }
397
+
398
+ function normalizeImportedTools(tools: readonly Tool[], options: BuildOptions): Tool[] {
399
+ const clonedTools = cloneJson(tools);
400
+ const normalizedTools = normalizeTools(clonedTools as AgentContext["tools"], options.intentTracing) ?? [];
401
+ return cloneJson(normalizedTools);
402
+ }
403
+
404
+ export function cloneJson<T>(value: T): T {
405
+ return cloneJsonValue(value) as T;
406
+ }
407
+
408
+ function cloneJsonValue(value: unknown, key = "", applyToJson = true): unknown {
409
+ if (value === null) return null;
410
+ const type = typeof value;
411
+ if (type === "number") return Number.isFinite(value) ? value : null;
412
+ // JSON.stringify drops function/symbol/undefined values (object props
413
+ // omitted, array elements become null via the array walk below).
414
+ if (type === "undefined" || type === "function" || type === "symbol") return undefined;
415
+ if (type !== "object") return value;
416
+ if (applyToJson) {
417
+ // JSON.stringify performs a single Get of `toJSON` per holder/key and
418
+ // serializes the returned replacement WITHOUT re-dispatching the
419
+ // replacement's own toJSON at the same level (nested properties still
420
+ // dispatch normally). Mirror that exactly to keep byte parity.
421
+ const toJSON = (value as { toJSON?: unknown }).toJSON;
422
+ if (typeof toJSON === "function") {
423
+ return cloneJsonValue(toJSON.call(value, key), key, false);
424
+ }
425
+ }
426
+ if (Array.isArray(value)) {
427
+ const cloned: unknown[] = new Array(value.length);
428
+ for (let i = 0; i < value.length; i++) {
429
+ const item = Object.hasOwn(value, i) ? cloneJsonValue(value[i], String(i)) : undefined;
430
+ cloned[i] = item === undefined ? null : item;
431
+ }
432
+ return cloned;
433
+ }
434
+ const cloned: Record<string, unknown> = {};
435
+ for (const key of Object.keys(value as object)) {
436
+ const clonedValue = cloneJsonValue((value as Record<string, unknown>)[key], key);
437
+ if (clonedValue !== undefined) cloned[key] = clonedValue;
438
+ }
439
+ return cloned;
440
+ }
441
+
442
+ function computeFingerprint(systemPrompt: string[], tools: Tool[], options: BuildOptions): string {
443
+ const payload = JSON.stringify({
444
+ s: systemPrompt,
445
+ t: tools.map(t => ({
446
+ n: t.name,
447
+ d: t.description,
448
+ p: t.parameters,
449
+ s: t.strict,
450
+ cf: t.customFormat,
451
+ cw: t.customWireName,
452
+ })),
453
+ i: options.intentTracing,
454
+ });
455
+ let hash = 0;
456
+ for (let i = 0; i < payload.length; i++) {
457
+ hash = ((hash << 5) - hash + payload.charCodeAt(i)) | 0;
458
+ }
459
+ return (hash >>> 0).toString(36);
460
+ }