@deepagents/context 0.6.0 → 0.8.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/dist/index.js ADDED
@@ -0,0 +1,1766 @@
1
+ // packages/context/src/lib/context.ts
2
+ function isFragment(data) {
3
+ return typeof data === "object" && data !== null && "name" in data && "data" in data && typeof data.name === "string";
4
+ }
5
+ function isFragmentObject(data) {
6
+ return typeof data === "object" && data !== null && !Array.isArray(data) && !isFragment(data);
7
+ }
8
+ function isMessageFragment(fragment2) {
9
+ return fragment2.type === "message";
10
+ }
11
+
12
+ // packages/context/src/lib/estimate.ts
13
+ import { encode } from "gpt-tokenizer";
14
+ var defaultTokenizer = {
15
+ encode(text) {
16
+ return encode(text);
17
+ },
18
+ count(text) {
19
+ return encode(text).length;
20
+ }
21
+ };
22
+ var ModelsRegistry = class {
23
+ #cache = /* @__PURE__ */ new Map();
24
+ #loaded = false;
25
+ #tokenizers = /* @__PURE__ */ new Map();
26
+ #defaultTokenizer = defaultTokenizer;
27
+ /**
28
+ * Load models data from models.dev API
29
+ */
30
+ async load() {
31
+ if (this.#loaded) return;
32
+ const response = await fetch("https://models.dev/api.json");
33
+ if (!response.ok) {
34
+ throw new Error(`Failed to fetch models: ${response.statusText}`);
35
+ }
36
+ const data = await response.json();
37
+ for (const [providerId, provider] of Object.entries(data)) {
38
+ for (const [modelId, model] of Object.entries(provider.models)) {
39
+ const info = {
40
+ id: model.id,
41
+ name: model.name,
42
+ family: model.family,
43
+ cost: model.cost,
44
+ limit: model.limit,
45
+ provider: providerId
46
+ };
47
+ this.#cache.set(`${providerId}:${modelId}`, info);
48
+ }
49
+ }
50
+ this.#loaded = true;
51
+ }
52
+ /**
53
+ * Get model info by ID
54
+ * @param modelId - Model ID (e.g., "openai:gpt-4o")
55
+ */
56
+ get(modelId) {
57
+ return this.#cache.get(modelId);
58
+ }
59
+ /**
60
+ * Check if a model exists in the registry
61
+ */
62
+ has(modelId) {
63
+ return this.#cache.has(modelId);
64
+ }
65
+ /**
66
+ * List all available model IDs
67
+ */
68
+ list() {
69
+ return [...this.#cache.keys()];
70
+ }
71
+ /**
72
+ * Register a custom tokenizer for specific model families
73
+ * @param family - Model family name (e.g., "llama", "claude")
74
+ * @param tokenizer - Tokenizer implementation
75
+ */
76
+ registerTokenizer(family, tokenizer) {
77
+ this.#tokenizers.set(family, tokenizer);
78
+ }
79
+ /**
80
+ * Set the default tokenizer used when no family-specific tokenizer is registered
81
+ */
82
+ setDefaultTokenizer(tokenizer) {
83
+ this.#defaultTokenizer = tokenizer;
84
+ }
85
+ /**
86
+ * Get the appropriate tokenizer for a model
87
+ */
88
+ getTokenizer(modelId) {
89
+ const model = this.get(modelId);
90
+ if (model) {
91
+ const familyTokenizer = this.#tokenizers.get(model.family);
92
+ if (familyTokenizer) {
93
+ return familyTokenizer;
94
+ }
95
+ }
96
+ return this.#defaultTokenizer;
97
+ }
98
+ /**
99
+ * Estimate token count and cost for given text and model
100
+ * @param modelId - Model ID to use for pricing (e.g., "openai:gpt-4o")
101
+ * @param input - Input text (prompt)
102
+ */
103
+ estimate(modelId, input) {
104
+ const model = this.get(modelId);
105
+ if (!model) {
106
+ throw new Error(
107
+ `Model "${modelId}" not found. Call load() first or check model ID.`
108
+ );
109
+ }
110
+ const tokenizer = this.getTokenizer(modelId);
111
+ const tokens = tokenizer.count(input);
112
+ const cost = tokens / 1e6 * model.cost.input;
113
+ return {
114
+ model: model.id,
115
+ provider: model.provider,
116
+ tokens,
117
+ cost,
118
+ limits: {
119
+ context: model.limit.context,
120
+ output: model.limit.output,
121
+ exceedsContext: tokens > model.limit.context
122
+ }
123
+ };
124
+ }
125
+ };
126
+ var _registry = null;
127
+ function getModelsRegistry() {
128
+ if (!_registry) {
129
+ _registry = new ModelsRegistry();
130
+ }
131
+ return _registry;
132
+ }
133
+
134
+ // packages/context/src/lib/renderers/abstract.renderer.ts
135
+ import pluralize from "pluralize";
136
+ import { titlecase } from "stringcase";
137
+ var ContextRenderer = class {
138
+ options;
139
+ constructor(options = {}) {
140
+ this.options = options;
141
+ }
142
+ /**
143
+ * Check if data is a primitive (string, number, boolean).
144
+ */
145
+ isPrimitive(data) {
146
+ return typeof data === "string" || typeof data === "number" || typeof data === "boolean";
147
+ }
148
+ /**
149
+ * Group fragments by name for groupFragments option.
150
+ */
151
+ groupByName(fragments) {
152
+ const groups = /* @__PURE__ */ new Map();
153
+ for (const fragment2 of fragments) {
154
+ const existing = groups.get(fragment2.name) ?? [];
155
+ existing.push(fragment2);
156
+ groups.set(fragment2.name, existing);
157
+ }
158
+ return groups;
159
+ }
160
+ /**
161
+ * Template method - dispatches value to appropriate handler.
162
+ */
163
+ renderValue(key, value, ctx) {
164
+ if (value == null) {
165
+ return "";
166
+ }
167
+ if (isFragment(value)) {
168
+ return this.renderFragment(value, ctx);
169
+ }
170
+ if (Array.isArray(value)) {
171
+ return this.renderArray(key, value, ctx);
172
+ }
173
+ if (isFragmentObject(value)) {
174
+ return this.renderObject(key, value, ctx);
175
+ }
176
+ return this.renderPrimitive(key, String(value), ctx);
177
+ }
178
+ /**
179
+ * Render all entries of an object.
180
+ */
181
+ renderEntries(data, ctx) {
182
+ return Object.entries(data).map(([key, value]) => this.renderValue(key, value, ctx)).filter(Boolean);
183
+ }
184
+ };
185
+ var XmlRenderer = class extends ContextRenderer {
186
+ render(fragments) {
187
+ return fragments.map((f) => this.#renderTopLevel(f)).filter(Boolean).join("\n");
188
+ }
189
+ #renderTopLevel(fragment2) {
190
+ if (this.isPrimitive(fragment2.data)) {
191
+ return this.#leafRoot(fragment2.name, String(fragment2.data));
192
+ }
193
+ if (Array.isArray(fragment2.data)) {
194
+ return this.#renderArray(fragment2.name, fragment2.data, 0);
195
+ }
196
+ if (isFragment(fragment2.data)) {
197
+ const child = this.renderFragment(fragment2.data, { depth: 1, path: [] });
198
+ return this.#wrap(fragment2.name, [child]);
199
+ }
200
+ return this.#wrap(
201
+ fragment2.name,
202
+ this.renderEntries(fragment2.data, { depth: 1, path: [] })
203
+ );
204
+ }
205
+ #renderArray(name, items, depth) {
206
+ const fragmentItems = items.filter(isFragment);
207
+ const nonFragmentItems = items.filter((item) => !isFragment(item));
208
+ const children = [];
209
+ for (const item of nonFragmentItems) {
210
+ if (item != null) {
211
+ children.push(
212
+ this.#leaf(pluralize.singular(name), String(item), depth + 1)
213
+ );
214
+ }
215
+ }
216
+ if (this.options.groupFragments && fragmentItems.length > 0) {
217
+ const groups = this.groupByName(fragmentItems);
218
+ for (const [groupName, groupFragments] of groups) {
219
+ const groupChildren = groupFragments.map(
220
+ (frag) => this.renderFragment(frag, { depth: depth + 2, path: [] })
221
+ );
222
+ const pluralName = pluralize.plural(groupName);
223
+ children.push(this.#wrapIndented(pluralName, groupChildren, depth + 1));
224
+ }
225
+ } else {
226
+ for (const frag of fragmentItems) {
227
+ children.push(
228
+ this.renderFragment(frag, { depth: depth + 1, path: [] })
229
+ );
230
+ }
231
+ }
232
+ return this.#wrap(name, children);
233
+ }
234
+ #leafRoot(tag, value) {
235
+ const safe = this.#escape(value);
236
+ if (safe.includes("\n")) {
237
+ return `<${tag}>
238
+ ${this.#indent(safe, 2)}
239
+ </${tag}>`;
240
+ }
241
+ return `<${tag}>${safe}</${tag}>`;
242
+ }
243
+ renderFragment(fragment2, ctx) {
244
+ const { name, data } = fragment2;
245
+ if (this.isPrimitive(data)) {
246
+ return this.#leaf(name, String(data), ctx.depth);
247
+ }
248
+ if (isFragment(data)) {
249
+ const child = this.renderFragment(data, { ...ctx, depth: ctx.depth + 1 });
250
+ return this.#wrapIndented(name, [child], ctx.depth);
251
+ }
252
+ if (Array.isArray(data)) {
253
+ return this.#renderArrayIndented(name, data, ctx.depth);
254
+ }
255
+ const children = this.renderEntries(data, { ...ctx, depth: ctx.depth + 1 });
256
+ return this.#wrapIndented(name, children, ctx.depth);
257
+ }
258
+ #renderArrayIndented(name, items, depth) {
259
+ const fragmentItems = items.filter(isFragment);
260
+ const nonFragmentItems = items.filter((item) => !isFragment(item));
261
+ const children = [];
262
+ for (const item of nonFragmentItems) {
263
+ if (item != null) {
264
+ children.push(
265
+ this.#leaf(pluralize.singular(name), String(item), depth + 1)
266
+ );
267
+ }
268
+ }
269
+ if (this.options.groupFragments && fragmentItems.length > 0) {
270
+ const groups = this.groupByName(fragmentItems);
271
+ for (const [groupName, groupFragments] of groups) {
272
+ const groupChildren = groupFragments.map(
273
+ (frag) => this.renderFragment(frag, { depth: depth + 2, path: [] })
274
+ );
275
+ const pluralName = pluralize.plural(groupName);
276
+ children.push(this.#wrapIndented(pluralName, groupChildren, depth + 1));
277
+ }
278
+ } else {
279
+ for (const frag of fragmentItems) {
280
+ children.push(
281
+ this.renderFragment(frag, { depth: depth + 1, path: [] })
282
+ );
283
+ }
284
+ }
285
+ return this.#wrapIndented(name, children, depth);
286
+ }
287
+ renderPrimitive(key, value, ctx) {
288
+ return this.#leaf(key, value, ctx.depth);
289
+ }
290
+ renderArray(key, items, ctx) {
291
+ if (!items.length) {
292
+ return "";
293
+ }
294
+ const itemTag = pluralize.singular(key);
295
+ const children = items.filter((item) => item != null).map((item) => this.#leaf(itemTag, String(item), ctx.depth + 1));
296
+ return this.#wrapIndented(key, children, ctx.depth);
297
+ }
298
+ renderObject(key, obj, ctx) {
299
+ const children = this.renderEntries(obj, { ...ctx, depth: ctx.depth + 1 });
300
+ return this.#wrapIndented(key, children, ctx.depth);
301
+ }
302
+ #escape(value) {
303
+ if (value == null) {
304
+ return "";
305
+ }
306
+ return value.replaceAll(/&/g, "&amp;").replaceAll(/</g, "&lt;").replaceAll(/>/g, "&gt;").replaceAll(/"/g, "&quot;").replaceAll(/'/g, "&apos;");
307
+ }
308
+ #indent(text, spaces) {
309
+ if (!text.trim()) {
310
+ return "";
311
+ }
312
+ const padding = " ".repeat(spaces);
313
+ return text.split("\n").map((line) => line.length ? padding + line : padding).join("\n");
314
+ }
315
+ #leaf(tag, value, depth) {
316
+ const safe = this.#escape(value);
317
+ const pad = " ".repeat(depth);
318
+ if (safe.includes("\n")) {
319
+ return `${pad}<${tag}>
320
+ ${this.#indent(safe, (depth + 1) * 2)}
321
+ ${pad}</${tag}>`;
322
+ }
323
+ return `${pad}<${tag}>${safe}</${tag}>`;
324
+ }
325
+ #wrap(tag, children) {
326
+ const content = children.filter(Boolean).join("\n");
327
+ if (!content) {
328
+ return "";
329
+ }
330
+ return `<${tag}>
331
+ ${content}
332
+ </${tag}>`;
333
+ }
334
+ #wrapIndented(tag, children, depth) {
335
+ const content = children.filter(Boolean).join("\n");
336
+ if (!content) {
337
+ return "";
338
+ }
339
+ const pad = " ".repeat(depth);
340
+ return `${pad}<${tag}>
341
+ ${content}
342
+ ${pad}</${tag}>`;
343
+ }
344
+ };
345
+ var MarkdownRenderer = class extends ContextRenderer {
346
+ render(fragments) {
347
+ return fragments.map((f) => {
348
+ const title = `## ${titlecase(f.name)}`;
349
+ if (this.isPrimitive(f.data)) {
350
+ return `${title}
351
+ ${String(f.data)}`;
352
+ }
353
+ if (Array.isArray(f.data)) {
354
+ return `${title}
355
+ ${this.#renderArray(f.data, 0)}`;
356
+ }
357
+ if (isFragment(f.data)) {
358
+ return `${title}
359
+ ${this.renderFragment(f.data, { depth: 0, path: [] })}`;
360
+ }
361
+ return `${title}
362
+ ${this.renderEntries(f.data, { depth: 0, path: [] }).join("\n")}`;
363
+ }).join("\n\n");
364
+ }
365
+ #renderArray(items, depth) {
366
+ const fragmentItems = items.filter(isFragment);
367
+ const nonFragmentItems = items.filter((item) => !isFragment(item));
368
+ const lines = [];
369
+ for (const item of nonFragmentItems) {
370
+ if (item != null) {
371
+ lines.push(`${this.#pad(depth)}- ${String(item)}`);
372
+ }
373
+ }
374
+ if (this.options.groupFragments && fragmentItems.length > 0) {
375
+ const groups = this.groupByName(fragmentItems);
376
+ for (const [groupName, groupFragments] of groups) {
377
+ const pluralName = pluralize.plural(groupName);
378
+ lines.push(`${this.#pad(depth)}- **${titlecase(pluralName)}**:`);
379
+ for (const frag of groupFragments) {
380
+ lines.push(this.renderFragment(frag, { depth: depth + 1, path: [] }));
381
+ }
382
+ }
383
+ } else {
384
+ for (const frag of fragmentItems) {
385
+ lines.push(this.renderFragment(frag, { depth, path: [] }));
386
+ }
387
+ }
388
+ return lines.join("\n");
389
+ }
390
+ #pad(depth) {
391
+ return " ".repeat(depth);
392
+ }
393
+ #leaf(key, value, depth) {
394
+ return `${this.#pad(depth)}- **${key}**: ${value}`;
395
+ }
396
+ #arrayItem(item, depth) {
397
+ if (isFragment(item)) {
398
+ return this.renderFragment(item, { depth, path: [] });
399
+ }
400
+ if (isFragmentObject(item)) {
401
+ return this.renderEntries(item, {
402
+ depth,
403
+ path: []
404
+ }).join("\n");
405
+ }
406
+ return `${this.#pad(depth)}- ${String(item)}`;
407
+ }
408
+ renderFragment(fragment2, ctx) {
409
+ const { name, data } = fragment2;
410
+ const header = `${this.#pad(ctx.depth)}- **${name}**:`;
411
+ if (this.isPrimitive(data)) {
412
+ return `${this.#pad(ctx.depth)}- **${name}**: ${String(data)}`;
413
+ }
414
+ if (isFragment(data)) {
415
+ const child = this.renderFragment(data, { ...ctx, depth: ctx.depth + 1 });
416
+ return [header, child].join("\n");
417
+ }
418
+ if (Array.isArray(data)) {
419
+ const children2 = data.filter((item) => item != null).map((item) => this.#arrayItem(item, ctx.depth + 1));
420
+ return [header, ...children2].join("\n");
421
+ }
422
+ const children = this.renderEntries(data, {
423
+ ...ctx,
424
+ depth: ctx.depth + 1
425
+ }).join("\n");
426
+ return [header, children].join("\n");
427
+ }
428
+ renderPrimitive(key, value, ctx) {
429
+ return this.#leaf(key, value, ctx.depth);
430
+ }
431
+ renderArray(key, items, ctx) {
432
+ const header = `${this.#pad(ctx.depth)}- **${key}**:`;
433
+ const children = items.filter((item) => item != null).map((item) => this.#arrayItem(item, ctx.depth + 1));
434
+ return [header, ...children].join("\n");
435
+ }
436
+ renderObject(key, obj, ctx) {
437
+ const header = `${this.#pad(ctx.depth)}- **${key}**:`;
438
+ const children = this.renderEntries(obj, {
439
+ ...ctx,
440
+ depth: ctx.depth + 1
441
+ }).join("\n");
442
+ return [header, children].join("\n");
443
+ }
444
+ };
445
+ var TomlRenderer = class extends ContextRenderer {
446
+ render(fragments) {
447
+ return fragments.map((f) => {
448
+ if (this.isPrimitive(f.data)) {
449
+ return `${f.name} = ${this.#formatValue(f.data)}`;
450
+ }
451
+ if (Array.isArray(f.data)) {
452
+ return this.#renderTopLevelArray(f.name, f.data);
453
+ }
454
+ if (isFragment(f.data)) {
455
+ return [
456
+ `[${f.name}]`,
457
+ this.renderFragment(f.data, { depth: 0, path: [f.name] })
458
+ ].join("\n");
459
+ }
460
+ const entries = this.#renderObjectEntries(f.data, [f.name]);
461
+ return [`[${f.name}]`, ...entries].join("\n");
462
+ }).join("\n\n");
463
+ }
464
+ #renderTopLevelArray(name, items) {
465
+ const fragmentItems = items.filter(isFragment);
466
+ const nonFragmentItems = items.filter(
467
+ (item) => !isFragment(item) && item != null
468
+ );
469
+ if (fragmentItems.length > 0) {
470
+ const parts = [`[${name}]`];
471
+ for (const frag of fragmentItems) {
472
+ parts.push(this.renderFragment(frag, { depth: 0, path: [name] }));
473
+ }
474
+ return parts.join("\n");
475
+ }
476
+ const values = nonFragmentItems.map((item) => this.#formatValue(item));
477
+ return `${name} = [${values.join(", ")}]`;
478
+ }
479
+ /**
480
+ * Override renderValue to preserve type information for TOML formatting.
481
+ */
482
+ renderValue(key, value, ctx) {
483
+ if (value == null) {
484
+ return "";
485
+ }
486
+ if (isFragment(value)) {
487
+ return this.renderFragment(value, ctx);
488
+ }
489
+ if (Array.isArray(value)) {
490
+ return this.renderArray(key, value, ctx);
491
+ }
492
+ if (isFragmentObject(value)) {
493
+ return this.renderObject(key, value, ctx);
494
+ }
495
+ return `${key} = ${this.#formatValue(value)}`;
496
+ }
497
+ renderPrimitive(key, value, _ctx) {
498
+ return `${key} = ${this.#formatValue(value)}`;
499
+ }
500
+ renderArray(key, items, _ctx) {
501
+ const values = items.filter((item) => item != null).map((item) => this.#formatValue(item));
502
+ return `${key} = [${values.join(", ")}]`;
503
+ }
504
+ renderObject(key, obj, ctx) {
505
+ const newPath = [...ctx.path, key];
506
+ const entries = this.#renderObjectEntries(obj, newPath);
507
+ return ["", `[${newPath.join(".")}]`, ...entries].join("\n");
508
+ }
509
+ #renderObjectEntries(obj, path) {
510
+ return Object.entries(obj).map(([key, value]) => {
511
+ if (value == null) {
512
+ return "";
513
+ }
514
+ if (isFragmentObject(value)) {
515
+ const newPath = [...path, key];
516
+ const entries = this.#renderObjectEntries(value, newPath);
517
+ return ["", `[${newPath.join(".")}]`, ...entries].join("\n");
518
+ }
519
+ if (Array.isArray(value)) {
520
+ const values = value.filter((item) => item != null).map((item) => this.#formatValue(item));
521
+ return `${key} = [${values.join(", ")}]`;
522
+ }
523
+ return `${key} = ${this.#formatValue(value)}`;
524
+ }).filter(Boolean);
525
+ }
526
+ renderFragment(fragment2, ctx) {
527
+ const { name, data } = fragment2;
528
+ const newPath = [...ctx.path, name];
529
+ if (this.isPrimitive(data)) {
530
+ return `${name} = ${this.#formatValue(data)}`;
531
+ }
532
+ if (isFragment(data)) {
533
+ return [
534
+ "",
535
+ `[${newPath.join(".")}]`,
536
+ this.renderFragment(data, { ...ctx, path: newPath })
537
+ ].join("\n");
538
+ }
539
+ if (Array.isArray(data)) {
540
+ const fragmentItems = data.filter(isFragment);
541
+ const nonFragmentItems = data.filter(
542
+ (item) => !isFragment(item) && item != null
543
+ );
544
+ if (fragmentItems.length > 0) {
545
+ const parts = ["", `[${newPath.join(".")}]`];
546
+ for (const frag of fragmentItems) {
547
+ parts.push(this.renderFragment(frag, { ...ctx, path: newPath }));
548
+ }
549
+ return parts.join("\n");
550
+ }
551
+ const values = nonFragmentItems.map((item) => this.#formatValue(item));
552
+ return `${name} = [${values.join(", ")}]`;
553
+ }
554
+ const entries = this.#renderObjectEntries(data, newPath);
555
+ return ["", `[${newPath.join(".")}]`, ...entries].join("\n");
556
+ }
557
+ #escape(value) {
558
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
559
+ }
560
+ #formatValue(value) {
561
+ if (typeof value === "string") {
562
+ return `"${this.#escape(value)}"`;
563
+ }
564
+ if (typeof value === "boolean" || typeof value === "number") {
565
+ return String(value);
566
+ }
567
+ if (typeof value === "object" && value !== null) {
568
+ return JSON.stringify(value);
569
+ }
570
+ return `"${String(value)}"`;
571
+ }
572
+ };
573
+ var ToonRenderer = class extends ContextRenderer {
574
+ render(fragments) {
575
+ return fragments.map((f) => this.#renderTopLevel(f)).filter(Boolean).join("\n");
576
+ }
577
+ #renderTopLevel(fragment2) {
578
+ const { name, data } = fragment2;
579
+ if (this.isPrimitive(data)) {
580
+ return `${name}: ${this.#formatValue(data)}`;
581
+ }
582
+ if (Array.isArray(data)) {
583
+ return this.#renderArrayField(name, data, 0);
584
+ }
585
+ if (isFragment(data)) {
586
+ const child = this.renderFragment(data, { depth: 1, path: [] });
587
+ return `${name}:
588
+ ${child}`;
589
+ }
590
+ if (isFragmentObject(data)) {
591
+ const entries = this.#renderObjectEntries(data, 1);
592
+ if (!entries) {
593
+ return `${name}:`;
594
+ }
595
+ return `${name}:
596
+ ${entries}`;
597
+ }
598
+ return `${name}:`;
599
+ }
600
+ #renderArrayField(key, items, depth) {
601
+ const filtered = items.filter((item) => item != null);
602
+ if (filtered.length === 0) {
603
+ return `${this.#pad(depth)}${key}[0]:`;
604
+ }
605
+ const fragmentItems = filtered.filter(isFragment);
606
+ if (fragmentItems.length > 0) {
607
+ return this.#renderMixedArray(key, filtered, depth);
608
+ }
609
+ if (filtered.every((item) => this.#isPrimitiveValue(item))) {
610
+ return this.#renderPrimitiveArray(key, filtered, depth);
611
+ }
612
+ if (this.#isTabularArray(filtered)) {
613
+ return this.#renderTabularArray(key, filtered, depth);
614
+ }
615
+ return this.#renderMixedArray(key, filtered, depth);
616
+ }
617
+ #isPrimitiveValue(value) {
618
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
619
+ }
620
+ #isTabularArray(items) {
621
+ if (items.length === 0) return false;
622
+ const objects = items.filter(isFragmentObject);
623
+ if (objects.length !== items.length) return false;
624
+ const firstKeys = Object.keys(objects[0]).sort().join(",");
625
+ for (const obj of objects) {
626
+ if (Object.keys(obj).sort().join(",") !== firstKeys) {
627
+ return false;
628
+ }
629
+ for (const value of Object.values(obj)) {
630
+ if (!this.#isPrimitiveValue(value) && value !== null) {
631
+ return false;
632
+ }
633
+ }
634
+ }
635
+ return true;
636
+ }
637
+ #renderPrimitiveArray(key, items, depth) {
638
+ const values = items.map((item) => this.#formatValue(item)).join(",");
639
+ return `${this.#pad(depth)}${key}[${items.length}]: ${values}`;
640
+ }
641
+ #renderTabularArray(key, items, depth) {
642
+ if (items.length === 0) {
643
+ return `${this.#pad(depth)}${key}[0]:`;
644
+ }
645
+ const fields = Object.keys(items[0]);
646
+ const header = `${this.#pad(depth)}${key}[${items.length}]{${fields.join(",")}}:`;
647
+ const rows = items.map((obj) => {
648
+ const values = fields.map((f) => this.#formatValue(obj[f]));
649
+ return `${this.#pad(depth + 1)}${values.join(",")}`;
650
+ });
651
+ return [header, ...rows].join("\n");
652
+ }
653
+ #renderMixedArray(key, items, depth) {
654
+ const header = `${this.#pad(depth)}${key}[${items.length}]:`;
655
+ const lines = items.map((item) => this.#renderListItem(item, depth + 1));
656
+ return [header, ...lines].join("\n");
657
+ }
658
+ #renderListItem(item, depth) {
659
+ if (this.#isPrimitiveValue(item)) {
660
+ return `${this.#pad(depth)}- ${this.#formatValue(item)}`;
661
+ }
662
+ if (isFragment(item)) {
663
+ const rendered = this.renderFragment(item, {
664
+ depth: depth + 1,
665
+ path: []
666
+ });
667
+ if (this.isPrimitive(item.data)) {
668
+ return `${this.#pad(depth)}- ${item.name}: ${this.#formatValue(item.data)}`;
669
+ }
670
+ return `${this.#pad(depth)}- ${item.name}:
671
+ ${rendered.split("\n").slice(1).join("\n")}`;
672
+ }
673
+ if (Array.isArray(item)) {
674
+ const content = this.#renderArrayField("", item, depth + 1);
675
+ return `${this.#pad(depth)}-${content.trimStart()}`;
676
+ }
677
+ if (isFragmentObject(item)) {
678
+ const entries = this.#renderObjectEntries(item, depth + 1);
679
+ if (!entries) {
680
+ return `${this.#pad(depth)}-`;
681
+ }
682
+ const lines = entries.split("\n");
683
+ const first = lines[0].trimStart();
684
+ const rest = lines.slice(1).join("\n");
685
+ return rest ? `${this.#pad(depth)}- ${first}
686
+ ${rest}` : `${this.#pad(depth)}- ${first}`;
687
+ }
688
+ return `${this.#pad(depth)}- ${this.#formatValue(item)}`;
689
+ }
690
+ #renderObjectEntries(obj, depth) {
691
+ const lines = [];
692
+ for (const [key, value] of Object.entries(obj)) {
693
+ if (value == null) continue;
694
+ if (this.#isPrimitiveValue(value)) {
695
+ lines.push(`${this.#pad(depth)}${key}: ${this.#formatValue(value)}`);
696
+ } else if (Array.isArray(value)) {
697
+ lines.push(this.#renderArrayField(key, value, depth));
698
+ } else if (isFragmentObject(value)) {
699
+ const nested = this.#renderObjectEntries(value, depth + 1);
700
+ if (nested) {
701
+ lines.push(`${this.#pad(depth)}${key}:
702
+ ${nested}`);
703
+ } else {
704
+ lines.push(`${this.#pad(depth)}${key}:`);
705
+ }
706
+ }
707
+ }
708
+ return lines.join("\n");
709
+ }
710
+ renderFragment(fragment2, ctx) {
711
+ const { name, data } = fragment2;
712
+ if (this.isPrimitive(data)) {
713
+ return `${this.#pad(ctx.depth)}${name}: ${this.#formatValue(data)}`;
714
+ }
715
+ if (isFragment(data)) {
716
+ const child = this.renderFragment(data, {
717
+ ...ctx,
718
+ depth: ctx.depth + 1
719
+ });
720
+ return `${this.#pad(ctx.depth)}${name}:
721
+ ${child}`;
722
+ }
723
+ if (Array.isArray(data)) {
724
+ return this.#renderArrayField(name, data, ctx.depth);
725
+ }
726
+ if (isFragmentObject(data)) {
727
+ const entries = this.#renderObjectEntries(data, ctx.depth + 1);
728
+ if (!entries) {
729
+ return `${this.#pad(ctx.depth)}${name}:`;
730
+ }
731
+ return `${this.#pad(ctx.depth)}${name}:
732
+ ${entries}`;
733
+ }
734
+ return `${this.#pad(ctx.depth)}${name}:`;
735
+ }
736
+ renderPrimitive(key, value, ctx) {
737
+ return `${this.#pad(ctx.depth)}${key}: ${this.#formatValue(value)}`;
738
+ }
739
+ renderArray(key, items, ctx) {
740
+ return this.#renderArrayField(key, items, ctx.depth);
741
+ }
742
+ renderObject(key, obj, ctx) {
743
+ const entries = this.#renderObjectEntries(obj, ctx.depth + 1);
744
+ if (!entries) {
745
+ return `${this.#pad(ctx.depth)}${key}:`;
746
+ }
747
+ return `${this.#pad(ctx.depth)}${key}:
748
+ ${entries}`;
749
+ }
750
+ #pad(depth) {
751
+ return " ".repeat(depth);
752
+ }
753
+ #needsQuoting(value) {
754
+ if (value === "") return true;
755
+ if (value !== value.trim()) return true;
756
+ if (["true", "false", "null"].includes(value.toLowerCase())) return true;
757
+ if (/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(value)) return true;
758
+ if (/[:\\"'[\]{}|,\t\n\r]/.test(value)) return true;
759
+ if (value.startsWith("-")) return true;
760
+ return false;
761
+ }
762
+ #escape(value) {
763
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
764
+ }
765
+ #canonicalizeNumber(n) {
766
+ if (!Number.isFinite(n)) return "null";
767
+ if (Object.is(n, -0)) return "0";
768
+ return String(n);
769
+ }
770
+ #formatValue(value) {
771
+ if (value === null) return "null";
772
+ if (typeof value === "boolean") return String(value);
773
+ if (typeof value === "number") return this.#canonicalizeNumber(value);
774
+ if (typeof value === "string") {
775
+ if (this.#needsQuoting(value)) {
776
+ return `"${this.#escape(value)}"`;
777
+ }
778
+ return value;
779
+ }
780
+ return `"${this.#escape(JSON.stringify(value))}"`;
781
+ }
782
+ };
783
+
784
+ // packages/context/src/lib/store/store.ts
785
+ var ContextStore = class {
786
+ };
787
+
788
+ // packages/context/src/lib/store/sqlite.store.ts
789
+ import { DatabaseSync } from "node:sqlite";
790
+ var STORE_DDL = `
791
+ -- Chats table
792
+ CREATE TABLE IF NOT EXISTS chats (
793
+ id TEXT PRIMARY KEY,
794
+ title TEXT,
795
+ metadata TEXT,
796
+ createdAt INTEGER NOT NULL,
797
+ updatedAt INTEGER NOT NULL
798
+ );
799
+
800
+ CREATE INDEX IF NOT EXISTS idx_chats_updatedAt ON chats(updatedAt);
801
+
802
+ -- Messages table (nodes in the DAG)
803
+ CREATE TABLE IF NOT EXISTS messages (
804
+ id TEXT PRIMARY KEY,
805
+ chatId TEXT NOT NULL,
806
+ parentId TEXT,
807
+ name TEXT NOT NULL,
808
+ type TEXT,
809
+ data TEXT NOT NULL,
810
+ persist INTEGER NOT NULL DEFAULT 1,
811
+ createdAt INTEGER NOT NULL,
812
+ FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
813
+ FOREIGN KEY (parentId) REFERENCES messages(id)
814
+ );
815
+
816
+ CREATE INDEX IF NOT EXISTS idx_messages_chatId ON messages(chatId);
817
+ CREATE INDEX IF NOT EXISTS idx_messages_parentId ON messages(parentId);
818
+
819
+ -- Branches table (pointers to head messages)
820
+ CREATE TABLE IF NOT EXISTS branches (
821
+ id TEXT PRIMARY KEY,
822
+ chatId TEXT NOT NULL,
823
+ name TEXT NOT NULL,
824
+ headMessageId TEXT,
825
+ isActive INTEGER NOT NULL DEFAULT 0,
826
+ createdAt INTEGER NOT NULL,
827
+ FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
828
+ FOREIGN KEY (headMessageId) REFERENCES messages(id),
829
+ UNIQUE(chatId, name)
830
+ );
831
+
832
+ CREATE INDEX IF NOT EXISTS idx_branches_chatId ON branches(chatId);
833
+
834
+ -- Checkpoints table (pointers to message nodes)
835
+ CREATE TABLE IF NOT EXISTS checkpoints (
836
+ id TEXT PRIMARY KEY,
837
+ chatId TEXT NOT NULL,
838
+ name TEXT NOT NULL,
839
+ messageId TEXT NOT NULL,
840
+ createdAt INTEGER NOT NULL,
841
+ FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
842
+ FOREIGN KEY (messageId) REFERENCES messages(id),
843
+ UNIQUE(chatId, name)
844
+ );
845
+
846
+ CREATE INDEX IF NOT EXISTS idx_checkpoints_chatId ON checkpoints(chatId);
847
+
848
+ -- FTS5 virtual table for full-text search
849
+ -- Using external content mode (content='') so we manage sync manually
850
+ CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
851
+ messageId,
852
+ chatId,
853
+ name,
854
+ content,
855
+ content='',
856
+ tokenize='porter unicode61'
857
+ );
858
+ `;
859
+ var SqliteContextStore = class extends ContextStore {
860
+ #db;
861
+ constructor(path) {
862
+ super();
863
+ this.#db = new DatabaseSync(path);
864
+ this.#db.exec("PRAGMA foreign_keys = ON");
865
+ this.#db.exec(STORE_DDL);
866
+ }
867
+ // ==========================================================================
868
+ // Chat Operations
869
+ // ==========================================================================
870
+ async createChat(chat) {
871
+ this.#db.prepare(
872
+ `INSERT INTO chats (id, title, metadata, createdAt, updatedAt)
873
+ VALUES (?, ?, ?, ?, ?)`
874
+ ).run(
875
+ chat.id,
876
+ chat.title ?? null,
877
+ chat.metadata ? JSON.stringify(chat.metadata) : null,
878
+ chat.createdAt,
879
+ chat.updatedAt
880
+ );
881
+ }
882
+ async getChat(chatId) {
883
+ const row = this.#db.prepare("SELECT * FROM chats WHERE id = ?").get(chatId);
884
+ if (!row) {
885
+ return void 0;
886
+ }
887
+ return {
888
+ id: row.id,
889
+ title: row.title ?? void 0,
890
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
891
+ createdAt: row.createdAt,
892
+ updatedAt: row.updatedAt
893
+ };
894
+ }
895
+ async updateChat(chatId, updates) {
896
+ const setClauses = [];
897
+ const params = [];
898
+ if (updates.title !== void 0) {
899
+ setClauses.push("title = ?");
900
+ params.push(updates.title ?? null);
901
+ }
902
+ if (updates.metadata !== void 0) {
903
+ setClauses.push("metadata = ?");
904
+ params.push(JSON.stringify(updates.metadata));
905
+ }
906
+ if (updates.updatedAt !== void 0) {
907
+ setClauses.push("updatedAt = ?");
908
+ params.push(updates.updatedAt);
909
+ }
910
+ if (setClauses.length === 0) {
911
+ return;
912
+ }
913
+ params.push(chatId);
914
+ this.#db.prepare(`UPDATE chats SET ${setClauses.join(", ")} WHERE id = ?`).run(...params);
915
+ }
916
+ async listChats() {
917
+ const rows = this.#db.prepare(
918
+ `SELECT
919
+ c.id,
920
+ c.title,
921
+ c.createdAt,
922
+ c.updatedAt,
923
+ COUNT(DISTINCT m.id) as messageCount,
924
+ COUNT(DISTINCT b.id) as branchCount
925
+ FROM chats c
926
+ LEFT JOIN messages m ON m.chatId = c.id
927
+ LEFT JOIN branches b ON b.chatId = c.id
928
+ GROUP BY c.id
929
+ ORDER BY c.updatedAt DESC`
930
+ ).all();
931
+ return rows.map((row) => ({
932
+ id: row.id,
933
+ title: row.title ?? void 0,
934
+ messageCount: row.messageCount,
935
+ branchCount: row.branchCount,
936
+ createdAt: row.createdAt,
937
+ updatedAt: row.updatedAt
938
+ }));
939
+ }
940
+ // ==========================================================================
941
+ // Message Operations (Graph Nodes)
942
+ // ==========================================================================
943
+ async addMessage(message) {
944
+ this.#db.prepare(
945
+ `INSERT INTO messages (id, chatId, parentId, name, type, data, persist, createdAt)
946
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
947
+ ).run(
948
+ message.id,
949
+ message.chatId,
950
+ message.parentId,
951
+ message.name,
952
+ message.type ?? null,
953
+ JSON.stringify(message.data),
954
+ message.persist ? 1 : 0,
955
+ message.createdAt
956
+ );
957
+ const content = typeof message.data === "string" ? message.data : JSON.stringify(message.data);
958
+ this.#db.prepare(
959
+ `INSERT INTO messages_fts(messageId, chatId, name, content)
960
+ VALUES (?, ?, ?, ?)`
961
+ ).run(message.id, message.chatId, message.name, content);
962
+ }
963
+ async getMessage(messageId) {
964
+ const row = this.#db.prepare("SELECT * FROM messages WHERE id = ?").get(messageId);
965
+ if (!row) {
966
+ return void 0;
967
+ }
968
+ return {
969
+ id: row.id,
970
+ chatId: row.chatId,
971
+ parentId: row.parentId,
972
+ name: row.name,
973
+ type: row.type ?? void 0,
974
+ data: JSON.parse(row.data),
975
+ persist: row.persist === 1,
976
+ createdAt: row.createdAt
977
+ };
978
+ }
979
+ async getMessageChain(headId) {
980
+ const rows = this.#db.prepare(
981
+ `WITH RECURSIVE chain AS (
982
+ SELECT *, 0 as depth FROM messages WHERE id = ?
983
+ UNION ALL
984
+ SELECT m.*, c.depth + 1 FROM messages m
985
+ INNER JOIN chain c ON m.id = c.parentId
986
+ )
987
+ SELECT * FROM chain
988
+ ORDER BY depth DESC`
989
+ ).all(headId);
990
+ return rows.map((row) => ({
991
+ id: row.id,
992
+ chatId: row.chatId,
993
+ parentId: row.parentId,
994
+ name: row.name,
995
+ type: row.type ?? void 0,
996
+ data: JSON.parse(row.data),
997
+ persist: row.persist === 1,
998
+ createdAt: row.createdAt
999
+ }));
1000
+ }
1001
+ async hasChildren(messageId) {
1002
+ const row = this.#db.prepare(
1003
+ "SELECT EXISTS(SELECT 1 FROM messages WHERE parentId = ?) as hasChildren"
1004
+ ).get(messageId);
1005
+ return row.hasChildren === 1;
1006
+ }
1007
+ // ==========================================================================
1008
+ // Branch Operations
1009
+ // ==========================================================================
1010
+ async createBranch(branch) {
1011
+ this.#db.prepare(
1012
+ `INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
1013
+ VALUES (?, ?, ?, ?, ?, ?)`
1014
+ ).run(
1015
+ branch.id,
1016
+ branch.chatId,
1017
+ branch.name,
1018
+ branch.headMessageId,
1019
+ branch.isActive ? 1 : 0,
1020
+ branch.createdAt
1021
+ );
1022
+ }
1023
+ async getBranch(chatId, name) {
1024
+ const row = this.#db.prepare("SELECT * FROM branches WHERE chatId = ? AND name = ?").get(chatId, name);
1025
+ if (!row) {
1026
+ return void 0;
1027
+ }
1028
+ return {
1029
+ id: row.id,
1030
+ chatId: row.chatId,
1031
+ name: row.name,
1032
+ headMessageId: row.headMessageId,
1033
+ isActive: row.isActive === 1,
1034
+ createdAt: row.createdAt
1035
+ };
1036
+ }
1037
+ async getActiveBranch(chatId) {
1038
+ const row = this.#db.prepare("SELECT * FROM branches WHERE chatId = ? AND isActive = 1").get(chatId);
1039
+ if (!row) {
1040
+ return void 0;
1041
+ }
1042
+ return {
1043
+ id: row.id,
1044
+ chatId: row.chatId,
1045
+ name: row.name,
1046
+ headMessageId: row.headMessageId,
1047
+ isActive: true,
1048
+ createdAt: row.createdAt
1049
+ };
1050
+ }
1051
+ async setActiveBranch(chatId, branchId) {
1052
+ this.#db.prepare("UPDATE branches SET isActive = 0 WHERE chatId = ?").run(chatId);
1053
+ this.#db.prepare("UPDATE branches SET isActive = 1 WHERE id = ?").run(branchId);
1054
+ }
1055
+ async updateBranchHead(branchId, messageId) {
1056
+ this.#db.prepare("UPDATE branches SET headMessageId = ? WHERE id = ?").run(messageId, branchId);
1057
+ }
1058
+ async listBranches(chatId) {
1059
+ const branches = this.#db.prepare(
1060
+ `SELECT
1061
+ b.id,
1062
+ b.name,
1063
+ b.headMessageId,
1064
+ b.isActive,
1065
+ b.createdAt
1066
+ FROM branches b
1067
+ WHERE b.chatId = ?
1068
+ ORDER BY b.createdAt ASC`
1069
+ ).all(chatId);
1070
+ const result = [];
1071
+ for (const branch of branches) {
1072
+ let messageCount = 0;
1073
+ if (branch.headMessageId) {
1074
+ const countRow = this.#db.prepare(
1075
+ `WITH RECURSIVE chain AS (
1076
+ SELECT id, parentId FROM messages WHERE id = ?
1077
+ UNION ALL
1078
+ SELECT m.id, m.parentId FROM messages m
1079
+ INNER JOIN chain c ON m.id = c.parentId
1080
+ )
1081
+ SELECT COUNT(*) as count FROM chain`
1082
+ ).get(branch.headMessageId);
1083
+ messageCount = countRow.count;
1084
+ }
1085
+ result.push({
1086
+ id: branch.id,
1087
+ name: branch.name,
1088
+ headMessageId: branch.headMessageId,
1089
+ isActive: branch.isActive === 1,
1090
+ messageCount,
1091
+ createdAt: branch.createdAt
1092
+ });
1093
+ }
1094
+ return result;
1095
+ }
1096
+ // ==========================================================================
1097
+ // Checkpoint Operations
1098
+ // ==========================================================================
1099
+ async createCheckpoint(checkpoint) {
1100
+ this.#db.prepare(
1101
+ `INSERT INTO checkpoints (id, chatId, name, messageId, createdAt)
1102
+ VALUES (?, ?, ?, ?, ?)
1103
+ ON CONFLICT(chatId, name) DO UPDATE SET
1104
+ messageId = excluded.messageId,
1105
+ createdAt = excluded.createdAt`
1106
+ ).run(
1107
+ checkpoint.id,
1108
+ checkpoint.chatId,
1109
+ checkpoint.name,
1110
+ checkpoint.messageId,
1111
+ checkpoint.createdAt
1112
+ );
1113
+ }
1114
+ async getCheckpoint(chatId, name) {
1115
+ const row = this.#db.prepare("SELECT * FROM checkpoints WHERE chatId = ? AND name = ?").get(chatId, name);
1116
+ if (!row) {
1117
+ return void 0;
1118
+ }
1119
+ return {
1120
+ id: row.id,
1121
+ chatId: row.chatId,
1122
+ name: row.name,
1123
+ messageId: row.messageId,
1124
+ createdAt: row.createdAt
1125
+ };
1126
+ }
1127
+ async listCheckpoints(chatId) {
1128
+ const rows = this.#db.prepare(
1129
+ `SELECT id, name, messageId, createdAt
1130
+ FROM checkpoints
1131
+ WHERE chatId = ?
1132
+ ORDER BY createdAt DESC`
1133
+ ).all(chatId);
1134
+ return rows.map((row) => ({
1135
+ id: row.id,
1136
+ name: row.name,
1137
+ messageId: row.messageId,
1138
+ createdAt: row.createdAt
1139
+ }));
1140
+ }
1141
+ async deleteCheckpoint(chatId, name) {
1142
+ this.#db.prepare("DELETE FROM checkpoints WHERE chatId = ? AND name = ?").run(chatId, name);
1143
+ }
1144
+ // ==========================================================================
1145
+ // Search Operations
1146
+ // ==========================================================================
1147
+ async searchMessages(chatId, query, options) {
1148
+ const limit = options?.limit ?? 20;
1149
+ const roles = options?.roles;
1150
+ let sql = `
1151
+ SELECT
1152
+ m.id,
1153
+ m.chatId,
1154
+ m.parentId,
1155
+ m.name,
1156
+ m.type,
1157
+ m.data,
1158
+ m.persist,
1159
+ m.createdAt,
1160
+ fts.rank,
1161
+ snippet(messages_fts, 3, '<mark>', '</mark>', '...', 32) as snippet
1162
+ FROM messages_fts fts
1163
+ JOIN messages m ON m.id = fts.messageId
1164
+ WHERE messages_fts MATCH ?
1165
+ AND fts.chatId = ?
1166
+ `;
1167
+ const params = [query, chatId];
1168
+ if (roles && roles.length > 0) {
1169
+ const placeholders = roles.map(() => "?").join(", ");
1170
+ sql += ` AND fts.name IN (${placeholders})`;
1171
+ params.push(...roles);
1172
+ }
1173
+ sql += " ORDER BY fts.rank LIMIT ?";
1174
+ params.push(limit);
1175
+ const rows = this.#db.prepare(sql).all(...params);
1176
+ return rows.map((row) => ({
1177
+ message: {
1178
+ id: row.id,
1179
+ chatId: row.chatId,
1180
+ parentId: row.parentId,
1181
+ name: row.name,
1182
+ type: row.type ?? void 0,
1183
+ data: JSON.parse(row.data),
1184
+ persist: row.persist === 1,
1185
+ createdAt: row.createdAt
1186
+ },
1187
+ rank: row.rank,
1188
+ snippet: row.snippet
1189
+ }));
1190
+ }
1191
+ // ==========================================================================
1192
+ // Visualization Operations
1193
+ // ==========================================================================
1194
+ async getGraph(chatId) {
1195
+ const messageRows = this.#db.prepare(
1196
+ `SELECT id, parentId, name, data, createdAt
1197
+ FROM messages
1198
+ WHERE chatId = ?
1199
+ ORDER BY createdAt ASC`
1200
+ ).all(chatId);
1201
+ const nodes = messageRows.map((row) => {
1202
+ const data = JSON.parse(row.data);
1203
+ const content = typeof data === "string" ? data : JSON.stringify(data);
1204
+ return {
1205
+ id: row.id,
1206
+ parentId: row.parentId,
1207
+ role: row.name,
1208
+ content: content.length > 50 ? content.slice(0, 50) + "..." : content,
1209
+ createdAt: row.createdAt
1210
+ };
1211
+ });
1212
+ const branchRows = this.#db.prepare(
1213
+ `SELECT name, headMessageId, isActive
1214
+ FROM branches
1215
+ WHERE chatId = ?
1216
+ ORDER BY createdAt ASC`
1217
+ ).all(chatId);
1218
+ const branches = branchRows.map((row) => ({
1219
+ name: row.name,
1220
+ headMessageId: row.headMessageId,
1221
+ isActive: row.isActive === 1
1222
+ }));
1223
+ const checkpointRows = this.#db.prepare(
1224
+ `SELECT name, messageId
1225
+ FROM checkpoints
1226
+ WHERE chatId = ?
1227
+ ORDER BY createdAt ASC`
1228
+ ).all(chatId);
1229
+ const checkpoints = checkpointRows.map((row) => ({
1230
+ name: row.name,
1231
+ messageId: row.messageId
1232
+ }));
1233
+ return {
1234
+ chatId,
1235
+ nodes,
1236
+ branches,
1237
+ checkpoints
1238
+ };
1239
+ }
1240
+ };
1241
+
1242
+ // packages/context/src/lib/store/memory.store.ts
1243
+ var InMemoryContextStore = class extends SqliteContextStore {
1244
+ constructor() {
1245
+ super(":memory:");
1246
+ }
1247
+ };
1248
+
1249
+ // packages/context/src/lib/visualize.ts
1250
+ function visualizeGraph(data) {
1251
+ if (data.nodes.length === 0) {
1252
+ return `[chat: ${data.chatId}]
1253
+
1254
+ (empty)`;
1255
+ }
1256
+ const childrenByParentId = /* @__PURE__ */ new Map();
1257
+ const branchHeads = /* @__PURE__ */ new Map();
1258
+ const checkpointsByMessageId = /* @__PURE__ */ new Map();
1259
+ for (const node of data.nodes) {
1260
+ const children = childrenByParentId.get(node.parentId) ?? [];
1261
+ children.push(node);
1262
+ childrenByParentId.set(node.parentId, children);
1263
+ }
1264
+ for (const branch of data.branches) {
1265
+ if (branch.headMessageId) {
1266
+ const heads = branchHeads.get(branch.headMessageId) ?? [];
1267
+ heads.push(branch.isActive ? `${branch.name} *` : branch.name);
1268
+ branchHeads.set(branch.headMessageId, heads);
1269
+ }
1270
+ }
1271
+ for (const checkpoint of data.checkpoints) {
1272
+ const cps = checkpointsByMessageId.get(checkpoint.messageId) ?? [];
1273
+ cps.push(checkpoint.name);
1274
+ checkpointsByMessageId.set(checkpoint.messageId, cps);
1275
+ }
1276
+ const roots = childrenByParentId.get(null) ?? [];
1277
+ const lines = [`[chat: ${data.chatId}]`, ""];
1278
+ function renderNode(node, prefix, isLast, isRoot) {
1279
+ const connector = isRoot ? "" : isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
1280
+ const contentPreview = node.content.replace(/\n/g, " ");
1281
+ let line = `${prefix}${connector}${node.id.slice(0, 8)} (${node.role}): "${contentPreview}"`;
1282
+ const branches = branchHeads.get(node.id);
1283
+ if (branches) {
1284
+ line += ` <- [${branches.join(", ")}]`;
1285
+ }
1286
+ const checkpoints = checkpointsByMessageId.get(node.id);
1287
+ if (checkpoints) {
1288
+ line += ` {${checkpoints.join(", ")}}`;
1289
+ }
1290
+ lines.push(line);
1291
+ const children = childrenByParentId.get(node.id) ?? [];
1292
+ const childPrefix = isRoot ? "" : prefix + (isLast ? " " : "\u2502 ");
1293
+ for (let i = 0; i < children.length; i++) {
1294
+ renderNode(children[i], childPrefix, i === children.length - 1, false);
1295
+ }
1296
+ }
1297
+ for (let i = 0; i < roots.length; i++) {
1298
+ renderNode(roots[i], "", i === roots.length - 1, true);
1299
+ }
1300
+ lines.push("");
1301
+ lines.push("Legend: * = active branch, {...} = checkpoint");
1302
+ return lines.join("\n");
1303
+ }
1304
+
1305
+ // packages/context/src/index.ts
1306
+ var ContextEngine = class {
1307
+ /** Non-message fragments (role, hints, etc.) - not persisted in graph */
1308
+ #contextFragments = [];
1309
+ /** Pending message fragments to be added to graph */
1310
+ #pendingMessages = [];
1311
+ #store;
1312
+ #chatId;
1313
+ #branchName;
1314
+ #branch = null;
1315
+ #chatData = null;
1316
+ #initialized = false;
1317
+ constructor(options) {
1318
+ if (!options.chatId) {
1319
+ throw new Error("chatId is required");
1320
+ }
1321
+ this.#store = options.store;
1322
+ this.#chatId = options.chatId;
1323
+ this.#branchName = options.branch ?? "main";
1324
+ }
1325
+ /**
1326
+ * Initialize the chat and branch if they don't exist.
1327
+ */
1328
+ async #ensureInitialized() {
1329
+ if (this.#initialized) {
1330
+ return;
1331
+ }
1332
+ const existingChat = await this.#store.getChat(this.#chatId);
1333
+ if (existingChat) {
1334
+ this.#chatData = existingChat;
1335
+ } else {
1336
+ const now = Date.now();
1337
+ this.#chatData = {
1338
+ id: this.#chatId,
1339
+ createdAt: now,
1340
+ updatedAt: now
1341
+ };
1342
+ await this.#store.createChat(this.#chatData);
1343
+ }
1344
+ const existingBranch = await this.#store.getBranch(
1345
+ this.#chatId,
1346
+ this.#branchName
1347
+ );
1348
+ if (existingBranch) {
1349
+ this.#branch = existingBranch;
1350
+ } else {
1351
+ this.#branch = {
1352
+ id: crypto.randomUUID(),
1353
+ chatId: this.#chatId,
1354
+ name: this.#branchName,
1355
+ headMessageId: null,
1356
+ isActive: true,
1357
+ createdAt: Date.now()
1358
+ };
1359
+ await this.#store.createBranch(this.#branch);
1360
+ }
1361
+ this.#initialized = true;
1362
+ }
1363
+ /**
1364
+ * Get the current chat ID.
1365
+ */
1366
+ get chatId() {
1367
+ return this.#chatId;
1368
+ }
1369
+ /**
1370
+ * Get the current branch name.
1371
+ */
1372
+ get branch() {
1373
+ return this.#branchName;
1374
+ }
1375
+ /**
1376
+ * Get metadata for the current chat.
1377
+ * Returns null if the chat hasn't been initialized yet.
1378
+ */
1379
+ get chat() {
1380
+ if (!this.#chatData) {
1381
+ return null;
1382
+ }
1383
+ return {
1384
+ id: this.#chatData.id,
1385
+ createdAt: this.#chatData.createdAt,
1386
+ updatedAt: this.#chatData.updatedAt,
1387
+ title: this.#chatData.title,
1388
+ metadata: this.#chatData.metadata
1389
+ };
1390
+ }
1391
+ /**
1392
+ * Add fragments to the context.
1393
+ *
1394
+ * - Message fragments (user/assistant) are queued for persistence
1395
+ * - Non-message fragments (role/hint) are kept in memory for system prompt
1396
+ */
1397
+ set(...fragments) {
1398
+ for (const fragment2 of fragments) {
1399
+ if (isMessageFragment(fragment2)) {
1400
+ this.#pendingMessages.push(fragment2);
1401
+ } else {
1402
+ this.#contextFragments.push(fragment2);
1403
+ }
1404
+ }
1405
+ return this;
1406
+ }
1407
+ /**
1408
+ * Render all fragments using the provided renderer.
1409
+ * @internal Use resolve() instead for public API.
1410
+ */
1411
+ render(renderer) {
1412
+ return renderer.render(this.#contextFragments);
1413
+ }
1414
+ /**
1415
+ * Resolve context into AI SDK-ready format.
1416
+ *
1417
+ * - Initializes chat and branch if needed
1418
+ * - Loads message history from the graph (walking parent chain)
1419
+ * - Separates context fragments for system prompt
1420
+ * - Combines with pending messages
1421
+ *
1422
+ * @example
1423
+ * ```ts
1424
+ * const context = new ContextEngine({ store, chatId: 'chat-1' })
1425
+ * .set(role('You are helpful'), user('Hello'));
1426
+ *
1427
+ * const { systemPrompt, messages } = await context.resolve();
1428
+ * await generateText({ system: systemPrompt, messages });
1429
+ * ```
1430
+ */
1431
+ async resolve(options = {}) {
1432
+ await this.#ensureInitialized();
1433
+ const renderer = options.renderer ?? new XmlRenderer();
1434
+ const systemPrompt = renderer.render(this.#contextFragments);
1435
+ const persistedMessages = [];
1436
+ if (this.#branch?.headMessageId) {
1437
+ const chain = await this.#store.getMessageChain(
1438
+ this.#branch.headMessageId
1439
+ );
1440
+ persistedMessages.push(...chain);
1441
+ }
1442
+ const messages = persistedMessages.map((msg) => ({
1443
+ role: msg.name,
1444
+ content: String(msg.data)
1445
+ }));
1446
+ for (const fragment2 of this.#pendingMessages) {
1447
+ messages.push({
1448
+ role: fragment2.name,
1449
+ content: String(fragment2.data)
1450
+ });
1451
+ }
1452
+ return { systemPrompt, messages };
1453
+ }
1454
+ /**
1455
+ * Save pending messages to the graph.
1456
+ *
1457
+ * Each message is added as a node with parentId pointing to the previous message.
1458
+ * The branch head is updated to point to the last message.
1459
+ *
1460
+ * @example
1461
+ * ```ts
1462
+ * context.set(user('Hello'));
1463
+ * // AI responds...
1464
+ * context.set(assistant('Hi there!'));
1465
+ * await context.save(); // Persist to graph
1466
+ * ```
1467
+ */
1468
+ async save() {
1469
+ await this.#ensureInitialized();
1470
+ if (this.#pendingMessages.length === 0) {
1471
+ return;
1472
+ }
1473
+ let parentId = this.#branch.headMessageId;
1474
+ const now = Date.now();
1475
+ for (const fragment2 of this.#pendingMessages) {
1476
+ const messageData = {
1477
+ id: fragment2.id ?? crypto.randomUUID(),
1478
+ chatId: this.#chatId,
1479
+ parentId,
1480
+ name: fragment2.name,
1481
+ type: fragment2.type,
1482
+ data: fragment2.data,
1483
+ persist: fragment2.persist ?? true,
1484
+ createdAt: now
1485
+ };
1486
+ await this.#store.addMessage(messageData);
1487
+ parentId = messageData.id;
1488
+ }
1489
+ await this.#store.updateBranchHead(this.#branch.id, parentId);
1490
+ this.#branch.headMessageId = parentId;
1491
+ await this.#store.updateChat(this.#chatId, { updatedAt: now });
1492
+ if (this.#chatData) {
1493
+ this.#chatData.updatedAt = now;
1494
+ }
1495
+ this.#pendingMessages = [];
1496
+ }
1497
+ /**
1498
+ * Estimate token count and cost for the current context.
1499
+ *
1500
+ * @param modelId - Model ID (e.g., "openai:gpt-4o", "anthropic:claude-3-5-sonnet")
1501
+ * @param options - Optional settings
1502
+ * @returns Estimate result with token counts and costs
1503
+ */
1504
+ async estimate(modelId, options = {}) {
1505
+ const renderer = options.renderer ?? new XmlRenderer();
1506
+ const renderedContext = this.render(renderer);
1507
+ const registry = getModelsRegistry();
1508
+ await registry.load();
1509
+ return registry.estimate(modelId, renderedContext);
1510
+ }
1511
+ /**
1512
+ * Rewind to a specific message by ID.
1513
+ *
1514
+ * Creates a new branch from that message, preserving the original branch.
1515
+ * The new branch becomes active.
1516
+ *
1517
+ * @param messageId - The message ID to rewind to
1518
+ * @returns The new branch info
1519
+ *
1520
+ * @example
1521
+ * ```ts
1522
+ * context.set(user('What is 2 + 2?', { id: 'q1' }));
1523
+ * context.set(assistant('The answer is 5.', { id: 'wrong' })); // Oops!
1524
+ * await context.save();
1525
+ *
1526
+ * // Rewind to the question, creates new branch
1527
+ * const newBranch = await context.rewind('q1');
1528
+ *
1529
+ * // Now add correct answer on new branch
1530
+ * context.set(assistant('The answer is 4.'));
1531
+ * await context.save();
1532
+ * ```
1533
+ */
1534
+ async rewind(messageId) {
1535
+ await this.#ensureInitialized();
1536
+ const message = await this.#store.getMessage(messageId);
1537
+ if (!message) {
1538
+ throw new Error(`Message "${messageId}" not found`);
1539
+ }
1540
+ if (message.chatId !== this.#chatId) {
1541
+ throw new Error(`Message "${messageId}" belongs to a different chat`);
1542
+ }
1543
+ const branches = await this.#store.listBranches(this.#chatId);
1544
+ const newBranchName = `${this.#branchName}-v${branches.length + 1}`;
1545
+ const newBranch = {
1546
+ id: crypto.randomUUID(),
1547
+ chatId: this.#chatId,
1548
+ name: newBranchName,
1549
+ headMessageId: messageId,
1550
+ isActive: false,
1551
+ createdAt: Date.now()
1552
+ };
1553
+ await this.#store.createBranch(newBranch);
1554
+ await this.#store.setActiveBranch(this.#chatId, newBranch.id);
1555
+ this.#branch = { ...newBranch, isActive: true };
1556
+ this.#branchName = newBranchName;
1557
+ this.#pendingMessages = [];
1558
+ const chain = await this.#store.getMessageChain(messageId);
1559
+ return {
1560
+ id: newBranch.id,
1561
+ name: newBranch.name,
1562
+ headMessageId: newBranch.headMessageId,
1563
+ isActive: true,
1564
+ messageCount: chain.length,
1565
+ createdAt: newBranch.createdAt
1566
+ };
1567
+ }
1568
+ /**
1569
+ * Create a checkpoint at the current position.
1570
+ *
1571
+ * A checkpoint is a named pointer to the current branch head.
1572
+ * Use restore() to return to this point later.
1573
+ *
1574
+ * @param name - Name for the checkpoint
1575
+ * @returns The checkpoint info
1576
+ *
1577
+ * @example
1578
+ * ```ts
1579
+ * context.set(user('I want to learn a new skill.'));
1580
+ * context.set(assistant('Would you like coding or cooking?'));
1581
+ * await context.save();
1582
+ *
1583
+ * // Save checkpoint before user's choice
1584
+ * const cp = await context.checkpoint('before-choice');
1585
+ * ```
1586
+ */
1587
+ async checkpoint(name) {
1588
+ await this.#ensureInitialized();
1589
+ if (!this.#branch?.headMessageId) {
1590
+ throw new Error("Cannot create checkpoint: no messages in conversation");
1591
+ }
1592
+ const checkpoint = {
1593
+ id: crypto.randomUUID(),
1594
+ chatId: this.#chatId,
1595
+ name,
1596
+ messageId: this.#branch.headMessageId,
1597
+ createdAt: Date.now()
1598
+ };
1599
+ await this.#store.createCheckpoint(checkpoint);
1600
+ return {
1601
+ id: checkpoint.id,
1602
+ name: checkpoint.name,
1603
+ messageId: checkpoint.messageId,
1604
+ createdAt: checkpoint.createdAt
1605
+ };
1606
+ }
1607
+ /**
1608
+ * Restore to a checkpoint by creating a new branch from that point.
1609
+ *
1610
+ * @param name - Name of the checkpoint to restore
1611
+ * @returns The new branch info
1612
+ *
1613
+ * @example
1614
+ * ```ts
1615
+ * // User chose cooking, but wants to try coding path
1616
+ * await context.restore('before-choice');
1617
+ *
1618
+ * context.set(user('I want to learn coding.'));
1619
+ * context.set(assistant('Python is a great starting language!'));
1620
+ * await context.save();
1621
+ * ```
1622
+ */
1623
+ async restore(name) {
1624
+ await this.#ensureInitialized();
1625
+ const checkpoint = await this.#store.getCheckpoint(this.#chatId, name);
1626
+ if (!checkpoint) {
1627
+ throw new Error(
1628
+ `Checkpoint "${name}" not found in chat "${this.#chatId}"`
1629
+ );
1630
+ }
1631
+ return this.rewind(checkpoint.messageId);
1632
+ }
1633
+ /**
1634
+ * Switch to a different branch by name.
1635
+ *
1636
+ * @param name - Branch name to switch to
1637
+ *
1638
+ * @example
1639
+ * ```ts
1640
+ * // List branches (via store)
1641
+ * const branches = await store.listBranches(context.chatId);
1642
+ * console.log(branches); // [{name: 'main', ...}, {name: 'main-v2', ...}]
1643
+ *
1644
+ * // Switch to original branch
1645
+ * await context.switchBranch('main');
1646
+ * ```
1647
+ */
1648
+ async switchBranch(name) {
1649
+ await this.#ensureInitialized();
1650
+ const branch = await this.#store.getBranch(this.#chatId, name);
1651
+ if (!branch) {
1652
+ throw new Error(`Branch "${name}" not found in chat "${this.#chatId}"`);
1653
+ }
1654
+ await this.#store.setActiveBranch(this.#chatId, branch.id);
1655
+ this.#branch = { ...branch, isActive: true };
1656
+ this.#branchName = name;
1657
+ this.#pendingMessages = [];
1658
+ }
1659
+ /**
1660
+ * Update metadata for the current chat.
1661
+ *
1662
+ * @param updates - Partial metadata to merge (title, metadata)
1663
+ *
1664
+ * @example
1665
+ * ```ts
1666
+ * await context.updateChat({
1667
+ * title: 'Coding Help Session',
1668
+ * metadata: { tags: ['python', 'debugging'] }
1669
+ * });
1670
+ * ```
1671
+ */
1672
+ async updateChat(updates) {
1673
+ await this.#ensureInitialized();
1674
+ const now = Date.now();
1675
+ const storeUpdates = {
1676
+ updatedAt: now
1677
+ };
1678
+ if (updates.title !== void 0) {
1679
+ storeUpdates.title = updates.title;
1680
+ }
1681
+ if (updates.metadata !== void 0) {
1682
+ storeUpdates.metadata = {
1683
+ ...this.#chatData?.metadata,
1684
+ ...updates.metadata
1685
+ };
1686
+ }
1687
+ await this.#store.updateChat(this.#chatId, storeUpdates);
1688
+ if (this.#chatData) {
1689
+ if (storeUpdates.title !== void 0) {
1690
+ this.#chatData.title = storeUpdates.title;
1691
+ }
1692
+ if (storeUpdates.metadata !== void 0) {
1693
+ this.#chatData.metadata = storeUpdates.metadata;
1694
+ }
1695
+ this.#chatData.updatedAt = now;
1696
+ }
1697
+ }
1698
+ /**
1699
+ * Consolidate context fragments (no-op for now).
1700
+ *
1701
+ * This is a placeholder for future functionality that merges context fragments
1702
+ * using specific rules. Currently, it does nothing.
1703
+ *
1704
+ * @experimental
1705
+ */
1706
+ consolidate() {
1707
+ return void 0;
1708
+ }
1709
+ };
1710
+ function hint(text) {
1711
+ return {
1712
+ name: "hint",
1713
+ data: text
1714
+ };
1715
+ }
1716
+ function fragment(name, ...children) {
1717
+ return {
1718
+ name,
1719
+ data: children
1720
+ };
1721
+ }
1722
+ function role(content) {
1723
+ return {
1724
+ name: "role",
1725
+ data: content
1726
+ };
1727
+ }
1728
+ function user(content, options) {
1729
+ return {
1730
+ id: options?.id ?? crypto.randomUUID(),
1731
+ name: "user",
1732
+ data: content,
1733
+ type: "message",
1734
+ persist: true
1735
+ };
1736
+ }
1737
+ function assistant(content, options) {
1738
+ return {
1739
+ id: options?.id ?? crypto.randomUUID(),
1740
+ name: "assistant",
1741
+ data: content,
1742
+ type: "message",
1743
+ persist: true
1744
+ };
1745
+ }
1746
+ export {
1747
+ ContextEngine,
1748
+ ContextStore,
1749
+ InMemoryContextStore,
1750
+ MarkdownRenderer,
1751
+ ModelsRegistry,
1752
+ SqliteContextStore,
1753
+ TomlRenderer,
1754
+ ToonRenderer,
1755
+ XmlRenderer,
1756
+ assistant,
1757
+ defaultTokenizer,
1758
+ fragment,
1759
+ getModelsRegistry,
1760
+ hint,
1761
+ isMessageFragment,
1762
+ role,
1763
+ user,
1764
+ visualizeGraph
1765
+ };
1766
+ //# sourceMappingURL=index.js.map