cortex-engine 0.1.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.
Files changed (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +154 -0
  3. package/dist/bin/cli.d.ts +13 -0
  4. package/dist/bin/cli.d.ts.map +1 -0
  5. package/dist/bin/cli.js +92 -0
  6. package/dist/bin/cli.js.map +1 -0
  7. package/dist/bin/config-cmd.d.ts +12 -0
  8. package/dist/bin/config-cmd.d.ts.map +1 -0
  9. package/dist/bin/config-cmd.js +184 -0
  10. package/dist/bin/config-cmd.js.map +1 -0
  11. package/dist/bin/config-loader.d.ts +12 -0
  12. package/dist/bin/config-loader.d.ts.map +1 -0
  13. package/dist/bin/config-loader.js +42 -0
  14. package/dist/bin/config-loader.js.map +1 -0
  15. package/dist/bin/digest-cmd.d.ts +13 -0
  16. package/dist/bin/digest-cmd.d.ts.map +1 -0
  17. package/dist/bin/digest-cmd.js +286 -0
  18. package/dist/bin/digest-cmd.js.map +1 -0
  19. package/dist/bin/init.d.ts +33 -0
  20. package/dist/bin/init.d.ts.map +1 -0
  21. package/dist/bin/init.js +355 -0
  22. package/dist/bin/init.js.map +1 -0
  23. package/dist/bin/serve.d.ts +15 -0
  24. package/dist/bin/serve.d.ts.map +1 -0
  25. package/dist/bin/serve.js +21 -0
  26. package/dist/bin/serve.js.map +1 -0
  27. package/dist/bridges/bridge.d.ts +46 -0
  28. package/dist/bridges/bridge.d.ts.map +1 -0
  29. package/dist/bridges/bridge.js +128 -0
  30. package/dist/bridges/bridge.js.map +1 -0
  31. package/dist/bridges/registry.d.ts +19 -0
  32. package/dist/bridges/registry.d.ts.map +1 -0
  33. package/dist/bridges/registry.js +36 -0
  34. package/dist/bridges/registry.js.map +1 -0
  35. package/dist/core/config.d.ts +108 -0
  36. package/dist/core/config.d.ts.map +1 -0
  37. package/dist/core/config.js +29 -0
  38. package/dist/core/config.js.map +1 -0
  39. package/dist/core/embed.d.ts +16 -0
  40. package/dist/core/embed.d.ts.map +1 -0
  41. package/dist/core/embed.js +7 -0
  42. package/dist/core/embed.js.map +1 -0
  43. package/dist/core/llm.d.ts +31 -0
  44. package/dist/core/llm.d.ts.map +1 -0
  45. package/dist/core/llm.js +13 -0
  46. package/dist/core/llm.js.map +1 -0
  47. package/dist/core/nli.d.ts +26 -0
  48. package/dist/core/nli.d.ts.map +1 -0
  49. package/dist/core/nli.js +11 -0
  50. package/dist/core/nli.js.map +1 -0
  51. package/dist/core/session.d.ts +26 -0
  52. package/dist/core/session.d.ts.map +1 -0
  53. package/dist/core/session.js +71 -0
  54. package/dist/core/session.js.map +1 -0
  55. package/dist/core/store.d.ts +58 -0
  56. package/dist/core/store.d.ts.map +1 -0
  57. package/dist/core/store.js +8 -0
  58. package/dist/core/store.js.map +1 -0
  59. package/dist/core/types.d.ts +148 -0
  60. package/dist/core/types.d.ts.map +1 -0
  61. package/dist/core/types.js +8 -0
  62. package/dist/core/types.js.map +1 -0
  63. package/dist/engines/cognition.d.ts +76 -0
  64. package/dist/engines/cognition.d.ts.map +1 -0
  65. package/dist/engines/cognition.js +441 -0
  66. package/dist/engines/cognition.js.map +1 -0
  67. package/dist/engines/digest.d.ts +52 -0
  68. package/dist/engines/digest.d.ts.map +1 -0
  69. package/dist/engines/digest.js +351 -0
  70. package/dist/engines/digest.js.map +1 -0
  71. package/dist/engines/fsrs.d.ts +44 -0
  72. package/dist/engines/fsrs.d.ts.map +1 -0
  73. package/dist/engines/fsrs.js +122 -0
  74. package/dist/engines/fsrs.js.map +1 -0
  75. package/dist/engines/keywords.d.ts +12 -0
  76. package/dist/engines/keywords.d.ts.map +1 -0
  77. package/dist/engines/keywords.js +45 -0
  78. package/dist/engines/keywords.js.map +1 -0
  79. package/dist/engines/memory.d.ts +55 -0
  80. package/dist/engines/memory.d.ts.map +1 -0
  81. package/dist/engines/memory.js +147 -0
  82. package/dist/engines/memory.js.map +1 -0
  83. package/dist/index.d.ts +42 -0
  84. package/dist/index.d.ts.map +1 -0
  85. package/dist/index.js +38 -0
  86. package/dist/index.js.map +1 -0
  87. package/dist/mcp/server.d.ts +12 -0
  88. package/dist/mcp/server.d.ts.map +1 -0
  89. package/dist/mcp/server.js +173 -0
  90. package/dist/mcp/server.js.map +1 -0
  91. package/dist/mcp/tools.d.ts +45 -0
  92. package/dist/mcp/tools.d.ts.map +1 -0
  93. package/dist/mcp/tools.js +814 -0
  94. package/dist/mcp/tools.js.map +1 -0
  95. package/dist/namespace/manager.d.ts +28 -0
  96. package/dist/namespace/manager.d.ts.map +1 -0
  97. package/dist/namespace/manager.js +73 -0
  98. package/dist/namespace/manager.js.map +1 -0
  99. package/dist/namespace/scoped-store.d.ts +43 -0
  100. package/dist/namespace/scoped-store.d.ts.map +1 -0
  101. package/dist/namespace/scoped-store.js +91 -0
  102. package/dist/namespace/scoped-store.js.map +1 -0
  103. package/dist/plugins/loader.d.ts +18 -0
  104. package/dist/plugins/loader.d.ts.map +1 -0
  105. package/dist/plugins/loader.js +71 -0
  106. package/dist/plugins/loader.js.map +1 -0
  107. package/dist/providers/nli-http.d.ts +34 -0
  108. package/dist/providers/nli-http.d.ts.map +1 -0
  109. package/dist/providers/nli-http.js +83 -0
  110. package/dist/providers/nli-http.js.map +1 -0
  111. package/dist/providers/ollama.d.ts +37 -0
  112. package/dist/providers/ollama.d.ts.map +1 -0
  113. package/dist/providers/ollama.js +103 -0
  114. package/dist/providers/ollama.js.map +1 -0
  115. package/dist/providers/vertex-embed.d.ts +38 -0
  116. package/dist/providers/vertex-embed.d.ts.map +1 -0
  117. package/dist/providers/vertex-embed.js +69 -0
  118. package/dist/providers/vertex-embed.js.map +1 -0
  119. package/dist/providers/vertex-llm.d.ts +25 -0
  120. package/dist/providers/vertex-llm.d.ts.map +1 -0
  121. package/dist/providers/vertex-llm.js +75 -0
  122. package/dist/providers/vertex-llm.js.map +1 -0
  123. package/dist/stores/firestore.d.ts +59 -0
  124. package/dist/stores/firestore.d.ts.map +1 -0
  125. package/dist/stores/firestore.js +530 -0
  126. package/dist/stores/firestore.js.map +1 -0
  127. package/dist/stores/sqlite.d.ts +43 -0
  128. package/dist/stores/sqlite.d.ts.map +1 -0
  129. package/dist/stores/sqlite.js +593 -0
  130. package/dist/stores/sqlite.js.map +1 -0
  131. package/dist/triggers/pipeline.d.ts +21 -0
  132. package/dist/triggers/pipeline.d.ts.map +1 -0
  133. package/dist/triggers/pipeline.js +30 -0
  134. package/dist/triggers/pipeline.js.map +1 -0
  135. package/dist/triggers/registry.d.ts +17 -0
  136. package/dist/triggers/registry.d.ts.map +1 -0
  137. package/dist/triggers/registry.js +32 -0
  138. package/dist/triggers/registry.js.map +1 -0
  139. package/package.json +94 -0
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Memory engine — prediction error gating, HyDE query expansion,
3
+ * spreading activation, and memory conversion utilities.
4
+ *
5
+ * Pure cognitive functions — no storage imports, no side effects.
6
+ * All state access goes through CortexStore / providers passed as arguments.
7
+ */
8
+ import type { CortexStore } from '../core/store.js';
9
+ import type { EmbedProvider } from '../core/embed.js';
10
+ import type { LLMProvider } from '../core/llm.js';
11
+ import type { Memory, MemorySummary, SearchResult, ActivationResult, GateResult } from '../core/types.js';
12
+ /** Similarity threshold above which a new observation is treated as a duplicate. */
13
+ export declare const SIMILARITY_MERGE = 0.85;
14
+ /** Similarity threshold above which a new observation is linked to an existing memory. */
15
+ export declare const SIMILARITY_LINK = 0.5;
16
+ /** Activation score decay factor per hop during spreading activation. */
17
+ export declare const ACTIVATION_DECAY = 0.5;
18
+ /** Maximum BFS depth for spreading activation traversal. */
19
+ export declare const MAX_ACTIVATION_DEPTH = 2;
20
+ /**
21
+ * Determine how a new observation should be ingested based on similarity
22
+ * to existing memories.
23
+ *
24
+ * - merge (>mergeThreshold): too similar to existing memory (duplicate risk)
25
+ * - link (>linkThreshold): moderately similar — store and link as related
26
+ * - novel: nothing close — candidate for a new memory concept
27
+ *
28
+ * Thresholds can be overridden per namespace via config.
29
+ */
30
+ export declare function predictionErrorGate(store: CortexStore, embedding: number[], thresholds?: {
31
+ merge?: number;
32
+ link?: number;
33
+ }): Promise<GateResult>;
34
+ /**
35
+ * Expand a user query using Hypothetical Document Embeddings (HyDE).
36
+ *
37
+ * Instead of embedding the raw query, asks the LLM to generate a
38
+ * hypothetical passage that would answer the query, then embeds THAT.
39
+ * This dramatically improves recall for concept-level questions.
40
+ */
41
+ export declare function hydeExpand(query: string, llm: LLMProvider, embed: EmbedProvider): Promise<number[]>;
42
+ /**
43
+ * Starting from a set of initial search results, traverse edges to activate
44
+ * related concepts via BFS. Returns primary results augmented with activated
45
+ * neighbors, ranked by combined activation score.
46
+ *
47
+ * Activation decays by ACTIVATION_DECAY (0.5) per hop, weighted by edge weight.
48
+ * Max depth defaults to 2 hops.
49
+ */
50
+ export declare function spreadActivation(store: CortexStore, initial: SearchResult[], depth?: number): Promise<ActivationResult[]>;
51
+ /**
52
+ * Convert a full Memory to a MemorySummary (strips embedding and other large fields).
53
+ */
54
+ export declare function memoryToSummary(memory: Memory): MemorySummary;
55
+ //# sourceMappingURL=memory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/engines/memory.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EACV,MAAM,EACN,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,UAAU,EAEX,MAAM,kBAAkB,CAAC;AAI1B,oFAAoF;AACpF,eAAO,MAAM,gBAAgB,OAAO,CAAC;AAErC,0FAA0F;AAC1F,eAAO,MAAM,eAAe,MAAO,CAAC;AAEpC,yEAAyE;AACzE,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAEpC,4DAA4D;AAC5D,eAAO,MAAM,oBAAoB,IAAI,CAAC;AAItC;;;;;;;;;GASG;AACH,wBAAsB,mBAAmB,CACvC,KAAK,EAAE,WAAW,EAClB,SAAS,EAAE,MAAM,EAAE,EACnB,UAAU,CAAC,EAAE;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GAC7C,OAAO,CAAC,UAAU,CAAC,CAkCrB;AAED;;;;;;GAMG;AACH,wBAAsB,UAAU,CAC9B,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,WAAW,EAChB,KAAK,EAAE,aAAa,GACnB,OAAO,CAAC,MAAM,EAAE,CAAC,CAWnB;AAED;;;;;;;GAOG;AACH,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,YAAY,EAAE,EACvB,KAAK,GAAE,MAA6B,GACnC,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAsD7B;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,CAc7D"}
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Memory engine — prediction error gating, HyDE query expansion,
3
+ * spreading activation, and memory conversion utilities.
4
+ *
5
+ * Pure cognitive functions — no storage imports, no side effects.
6
+ * All state access goes through CortexStore / providers passed as arguments.
7
+ */
8
+ // ─── Constants ────────────────────────────────────────────────────────────────
9
+ /** Similarity threshold above which a new observation is treated as a duplicate. */
10
+ export const SIMILARITY_MERGE = 0.85;
11
+ /** Similarity threshold above which a new observation is linked to an existing memory. */
12
+ export const SIMILARITY_LINK = 0.50;
13
+ /** Activation score decay factor per hop during spreading activation. */
14
+ export const ACTIVATION_DECAY = 0.5;
15
+ /** Maximum BFS depth for spreading activation traversal. */
16
+ export const MAX_ACTIVATION_DEPTH = 2;
17
+ // ─── Functions ────────────────────────────────────────────────────────────────
18
+ /**
19
+ * Determine how a new observation should be ingested based on similarity
20
+ * to existing memories.
21
+ *
22
+ * - merge (>mergeThreshold): too similar to existing memory (duplicate risk)
23
+ * - link (>linkThreshold): moderately similar — store and link as related
24
+ * - novel: nothing close — candidate for a new memory concept
25
+ *
26
+ * Thresholds can be overridden per namespace via config.
27
+ */
28
+ export async function predictionErrorGate(store, embedding, thresholds) {
29
+ const mergeThreshold = thresholds?.merge ?? SIMILARITY_MERGE;
30
+ const linkThreshold = thresholds?.link ?? SIMILARITY_LINK;
31
+ const results = await store.findNearest(embedding, 5);
32
+ if (results.length === 0) {
33
+ return { decision: 'novel', max_similarity: 0 };
34
+ }
35
+ let maxSimilarity = 0;
36
+ let nearestId = '';
37
+ for (const result of results) {
38
+ if (result.score > maxSimilarity) {
39
+ maxSimilarity = result.score;
40
+ nearestId = result.memory.id;
41
+ }
42
+ }
43
+ let decision;
44
+ if (maxSimilarity > mergeThreshold) {
45
+ decision = 'merge';
46
+ }
47
+ else if (maxSimilarity > linkThreshold) {
48
+ decision = 'link';
49
+ }
50
+ else {
51
+ decision = 'novel';
52
+ }
53
+ return {
54
+ decision,
55
+ nearest_id: decision !== 'novel' ? nearestId : undefined,
56
+ max_similarity: maxSimilarity,
57
+ };
58
+ }
59
+ /**
60
+ * Expand a user query using Hypothetical Document Embeddings (HyDE).
61
+ *
62
+ * Instead of embedding the raw query, asks the LLM to generate a
63
+ * hypothetical passage that would answer the query, then embeds THAT.
64
+ * This dramatically improves recall for concept-level questions.
65
+ */
66
+ export async function hydeExpand(query, llm, embed) {
67
+ const hypothetical = await llm.generate(`Write a short, factual passage (2-3 sentences) that would answer this question or describe this concept. Do not include any preamble — just the passage.\n\nQuery: ${query}`, {
68
+ temperature: 0.3,
69
+ maxTokens: 200,
70
+ systemPrompt: 'You are a knowledge retrieval assistant. Generate hypothetical document passages for semantic search.',
71
+ });
72
+ return embed.embed(hypothetical);
73
+ }
74
+ /**
75
+ * Starting from a set of initial search results, traverse edges to activate
76
+ * related concepts via BFS. Returns primary results augmented with activated
77
+ * neighbors, ranked by combined activation score.
78
+ *
79
+ * Activation decays by ACTIVATION_DECAY (0.5) per hop, weighted by edge weight.
80
+ * Max depth defaults to 2 hops.
81
+ */
82
+ export async function spreadActivation(store, initial, depth = MAX_ACTIVATION_DEPTH) {
83
+ const activated = new Map();
84
+ // Seed with initial matches
85
+ for (const result of initial) {
86
+ activated.set(result.memory.id, {
87
+ ...result,
88
+ hop_count: 0,
89
+ activation_path: [result.memory.id],
90
+ });
91
+ }
92
+ // BFS traversal
93
+ async function traverse(ids, currentDepth) {
94
+ if (currentDepth >= depth || ids.length === 0)
95
+ return;
96
+ // Get all edges from current frontier (batch)
97
+ const edges = await store.getEdgesForMemories(ids);
98
+ const nextIds = [];
99
+ for (const edge of edges) {
100
+ // Only follow forward edges (source_id in our frontier)
101
+ if (!ids.includes(edge.source_id))
102
+ continue;
103
+ const sourceResult = activated.get(edge.source_id);
104
+ if (!sourceResult)
105
+ continue;
106
+ const propagatedScore = sourceResult.score * ACTIVATION_DECAY * edge.weight;
107
+ const targetId = edge.target_id;
108
+ const existing = activated.get(targetId);
109
+ if (!existing || existing.score < propagatedScore) {
110
+ const memory = await store.getMemory(targetId);
111
+ if (!memory)
112
+ continue;
113
+ activated.set(targetId, {
114
+ memory: memoryToSummary(memory),
115
+ score: propagatedScore,
116
+ distance: 1 - propagatedScore,
117
+ hop_count: currentDepth + 1,
118
+ activation_path: [...sourceResult.activation_path, targetId],
119
+ });
120
+ nextIds.push(targetId);
121
+ }
122
+ }
123
+ await traverse(nextIds, currentDepth + 1);
124
+ }
125
+ await traverse(initial.map((r) => r.memory.id), 0);
126
+ return Array.from(activated.values())
127
+ .sort((a, b) => b.score - a.score);
128
+ }
129
+ /**
130
+ * Convert a full Memory to a MemorySummary (strips embedding and other large fields).
131
+ */
132
+ export function memoryToSummary(memory) {
133
+ return {
134
+ id: memory.id,
135
+ name: memory.name,
136
+ definition: memory.definition,
137
+ category: memory.category,
138
+ salience: memory.salience,
139
+ confidence: memory.confidence,
140
+ access_count: memory.access_count,
141
+ updated_at: memory.updated_at,
142
+ tags: memory.tags,
143
+ fsrs: memory.fsrs,
144
+ provenance: memory.provenance,
145
+ };
146
+ }
147
+ //# sourceMappingURL=memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.js","sourceRoot":"","sources":["../../src/engines/memory.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAcH,iFAAiF;AAEjF,oFAAoF;AACpF,MAAM,CAAC,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAErC,0FAA0F;AAC1F,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,CAAC;AAEpC,yEAAyE;AACzE,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAEpC,4DAA4D;AAC5D,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAEtC,iFAAiF;AAEjF;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,KAAkB,EAClB,SAAmB,EACnB,UAA8C;IAE9C,MAAM,cAAc,GAAG,UAAU,EAAE,KAAK,IAAI,gBAAgB,CAAC;IAC7D,MAAM,aAAa,GAAG,UAAU,EAAE,IAAI,IAAI,eAAe,CAAC;IAE1D,MAAM,OAAO,GAAG,MAAM,KAAK,CAAC,WAAW,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;IAEtD,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,cAAc,EAAE,CAAC,EAAE,CAAC;IAClD,CAAC;IAED,IAAI,aAAa,GAAG,CAAC,CAAC;IACtB,IAAI,SAAS,GAAG,EAAE,CAAC;IAEnB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,MAAM,CAAC,KAAK,GAAG,aAAa,EAAE,CAAC;YACjC,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC;YAC7B,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;Q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,MAAM,QAAQ,CAAC,OAAO,EAAE,YAAY,GAAG,CAAC,CAAC,CAAC;IAC5C,CAAC;IAED,MAAM,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAEnD,OAAO,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;SAClC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;AACvC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,eAAe,CAAC,MAAc;IAC5C,OAAO;QACL,EAAE,EAAE,MAAM,CAAC,EAAE;QACb,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,YAAY,EAAE,MAAM,CAAC,YAAY;QACjC,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,UAAU,EAAE,MAAM,CAAC,UAAU;KAC9B,CAAC;AACJ,CAAC"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * cortex-engine — portable cognitive engine for AI agents.
3
+ *
4
+ * Public API surface. Everything exported here is part of the stable API.
5
+ */
6
+ export type { CortexStore } from './core/store.js';
7
+ export type { EmbedProvider } from './core/embed.js';
8
+ export type { LLMProvider, GenerateOptions, GenerateJSONOptions } from './core/llm.js';
9
+ export type { NLIProvider, NLIResult, NLILabel } from './core/nli.js';
10
+ export type { CortexConfig, AgentConfig, NamespaceConfig, IngestionTriggerConfig, BridgeConfig, BridgeRuleConfig, ModelProvenanceConfig, BenchmarkConfig, } from './core/config.js';
11
+ export { DEFAULT_CONFIG } from './core/config.js';
12
+ export { Session } from './core/session.js';
13
+ export type { Memory, MemorySummary, MemoryCategory, FSRSData, FSRSState, Edge, EdgeRelation, Observation, OpsEntry, OpsEntryType, OpsStatus, OpsFilters, Signal, SignalType, BeliefEntry, SearchResult, ActivationResult, IngestDecision, GateResult, ScheduleResult, ModelProvenance, ConfidenceTier, QueryFilter, } from './core/types.js';
14
+ export { retrievability, scheduleNext, initialStability, FSRS_WEIGHTS, DESIRED_RETENTION, } from './engines/fsrs.js';
15
+ export { extractKeywords } from './engines/keywords.js';
16
+ export { predictionErrorGate, hydeExpand, spreadActivation, memoryToSummary, SIMILARITY_MERGE, SIMILARITY_LINK, ACTIVATION_DECAY, MAX_ACTIVATION_DEPTH, } from './engines/memory.js';
17
+ export { dreamConsolidate } from './engines/cognition.js';
18
+ export type { DreamResult, DreamOptions } from './engines/cognition.js';
19
+ export { digestDocument } from './engines/digest.js';
20
+ export type { DigestOptions, DigestResult } from './engines/digest.js';
21
+ export { SqliteCortexStore } from './stores/sqlite.js';
22
+ export { FirestoreCortexStore } from './stores/firestore.js';
23
+ export type { FirestoreStoreOptions } from './stores/firestore.js';
24
+ export { ScopedStore } from './namespace/scoped-store.js';
25
+ export { NamespaceManager } from './namespace/manager.js';
26
+ export { OllamaEmbedProvider, OllamaLLMProvider } from './providers/ollama.js';
27
+ export type { VertexEmbedOptions, VertexEmbedTaskType } from './providers/vertex-embed.js';
28
+ export type { VertexLLMOptions } from './providers/vertex-llm.js';
29
+ export { LocalNLIProvider, nliToCortexVerdict } from './providers/nli-http.js';
30
+ export { TriggerRegistry } from './triggers/registry.js';
31
+ export type { ResolvedTrigger } from './triggers/registry.js';
32
+ export { executeIngestionPipeline } from './triggers/pipeline.js';
33
+ export type { ToolHandler, PipelineResult, PipelineStepResult } from './triggers/pipeline.js';
34
+ export { BridgeRegistry } from './bridges/registry.js';
35
+ export type { ResolvedBridgeRule } from './bridges/registry.js';
36
+ export { evaluateCondition, interpolateTemplate, checkBridges } from './bridges/bridge.js';
37
+ export type { BridgeContext, BridgeResult } from './bridges/bridge.js';
38
+ export { createServer, startServer } from './mcp/server.js';
39
+ export { createTools, CORE_TOOLS } from './mcp/tools.js';
40
+ export type { ToolDefinition, ToolContext, ToolPlugin } from './mcp/tools.js';
41
+ export { loadPlugins } from './plugins/loader.js';
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,YAAY,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACnD,YAAY,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,YAAY,EAAE,WAAW,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACvF,YAAY,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAGtE,YAAY,EACV,YAAY,EACZ,WAAW,EACX,eAAe,EACf,sBAAsB,EACtB,YAAY,EACZ,gBAAgB,EAChB,qBAAqB,EACrB,eAAe,GAChB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGlD,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAG5C,YAAY,EACV,MAAM,EACN,aAAa,EACb,cAAc,EACd,QAAQ,EACR,SAAS,EACT,IAAI,EACJ,YAAY,EACZ,WAAW,EACX,QAAQ,EACR,YAAY,EACZ,SAAS,EACT,UAAU,EACV,MAAM,EACN,UAAU,EACV,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,cAAc,EACd,UAAU,EACV,cAAc,EACd,eAAe,EACf,cAAc,EACd,WAAW,GACZ,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,cAAc,EACd,YAAY,EACZ,gBAAgB,EAChB,YA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F,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,YAAY,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAC3F,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGvE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACzD,YAAY,EAAE,cAAc,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAG9E,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * cortex-engine — portable cognitive engine for AI agents.
3
+ *
4
+ * Public API surface. Everything exported here is part of the stable API.
5
+ */
6
+ export { DEFAULT_CONFIG } from './core/config.js';
7
+ // Session & provenance
8
+ export { Session } from './core/session.js';
9
+ // Engines (pure functions, storage-agnostic)
10
+ export { retrievability, scheduleNext, initialStability, FSRS_WEIGHTS, DESIRED_RETENTION, } from './engines/fsrs.js';
11
+ export { extractKeywords } from './engines/keywords.js';
12
+ export { predictionErrorGate, hydeExpand, spreadActivation, memoryToSummary, SIMILARITY_MERGE, SIMILARITY_LINK, ACTIVATION_DECAY, MAX_ACTIVATION_DEPTH, } from './engines/memory.js';
13
+ export { dreamConsolidate } from './engines/cognition.js';
14
+ export { digestDocument } from './engines/digest.js';
15
+ // Stores
16
+ export { SqliteCortexStore } from './stores/sqlite.js';
17
+ export { FirestoreCortexStore } from './stores/firestore.js';
18
+ // Namespace
19
+ export { ScopedStore } from './namespace/scoped-store.js';
20
+ export { NamespaceManager } from './namespace/manager.js';
21
+ // Providers — only always-available providers are re-exported as values.
22
+ // Vertex providers use optional peer deps and must be imported directly
23
+ // from 'cortex-engine/providers/vertex-embed' or 'cortex-engine/providers/vertex-llm'
24
+ // to avoid breaking consumers who don't install @google-cloud/*.
25
+ export { OllamaEmbedProvider, OllamaLLMProvider } from './providers/ollama.js';
26
+ export { LocalNLIProvider, nliToCortexVerdict } from './providers/nli-http.js';
27
+ // Triggers
28
+ export { TriggerRegistry } from './triggers/registry.js';
29
+ export { executeIngestionPipeline } from './triggers/pipeline.js';
30
+ // Bridges
31
+ export { BridgeRegistry } from './bridges/registry.js';
32
+ export { evaluateCondition, interpolateTemplate, checkBridges } from './bridges/bridge.js';
33
+ // MCP server
34
+ export { createServer, startServer } from './mcp/server.js';
35
+ export { createTools, CORE_TOOLS } from './mcp/tools.js';
36
+ // Plugins
37
+ export { loadPlugins } from './plugins/loader.js';
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAmBH,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,uBAAuB;AACvB,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AA6B5C,6CAA6C;AAC7C,OAAO,EACL,cAAc,EACd,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EACL,mBAAmB,EACnB,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAG1D,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAGrD,SAAS;AACT,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAI7D,YAAY;AACZ,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D,yEAAyE;AACzE,wEAAwE;AACxE,sFAAsF;AACtF,iEAAiE;AACjE,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAG/E,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE/E,WAAW;AACX,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAGlE,UAAU;AACV,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEvD,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAG3F,aAAa;AACb,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAGzD,UAAU;AACV,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * MCP Server for cortex-engine.
3
+ *
4
+ * Wires providers, stores, namespaces, triggers, and bridges together
5
+ * and exposes them as MCP tools over stdio.
6
+ */
7
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
8
+ import type { CortexConfig } from '../core/config.js';
9
+ export declare function createServer(config: CortexConfig): Promise<Server>;
10
+ /** Start the MCP server using stdio transport. Called by bin/serve.ts. */
11
+ export declare function startServer(config: CortexConfig): Promise<void>;
12
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AAMnE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAgBtD,wBAAsB,YAAY,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,CAyGxE;AAID,0EAA0E;AAC1E,wBAAsB,WAAW,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAIrE"}
@@ -0,0 +1,173 @@
1
+ /**
2
+ * MCP Server for cortex-engine.
3
+ *
4
+ * Wires providers, stores, namespaces, triggers, and bridges together
5
+ * and exposes them as MCP tools over stdio.
6
+ */
7
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
8
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
9
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
10
+ import { Session } from '../core/session.js';
11
+ import { NamespaceManager } from '../namespace/manager.js';
12
+ import { TriggerRegistry } from '../triggers/registry.js';
13
+ import { BridgeRegistry } from '../bridges/registry.js';
14
+ import { SqliteCortexStore } from '../stores/sqlite.js';
15
+ import { FirestoreCortexStore } from '../stores/firestore.js';
16
+ import { OllamaEmbedProvider, OllamaLLMProvider } from '../providers/ollama.js';
17
+ import { createTools, CORE_TOOLS } from './tools.js';
18
+ import { loadPlugins } from '../plugins/loader.js';
19
+ // ─── Server Factory ───────────────────────────────────────────────────────────
20
+ export async function createServer(config) {
21
+ // 1. Create providers based on config (async — vertex uses dynamic imports)
22
+ const embed = await createEmbedProvider(config);
23
+ const llm = await createLLMProvider(config);
24
+ // 2. Pre-initialize store backend (async for Firestore dynamic import)
25
+ const firestoreInit = config.store === 'firestore'
26
+ ? await initFirestoreDb(config)
27
+ : null;
28
+ // 3. Create namespace manager with store factory
29
+ const namespaces = new NamespaceManager(config, (_namespace, prefix) => {
30
+ if (config.store === 'sqlite') {
31
+ return new SqliteCortexStore(config.store_options?.sqlite_path ?? './cortex.db', prefix);
32
+ }
33
+ if (config.store === 'firestore') {
34
+ return new FirestoreCortexStore(firestoreInit.db, prefix, firestoreInit.FieldValue);
35
+ }
36
+ throw new Error(`Unsupported store: ${config.store}`);
37
+ });
38
+ // 4. Create registries
39
+ const triggers = new TriggerRegistry(config.namespaces);
40
+ const bridges = new BridgeRegistry(config.bridges ?? []);
41
+ // 5. Create session (auto-detect model)
42
+ const detected = Session.detectModel();
43
+ const provenanceConfig = config.model_provenance ?? {
44
+ default_model: 'unknown',
45
+ confidence_tiers: { high: [], medium: [], low: [] },
46
+ conflict_policy: 'latest_wins',
47
+ };
48
+ const session = new Session(detected.modelId, detected.modelFamily, detected.client, provenanceConfig.default_model, provenanceConfig);
49
+ // 6. Load plugins and merge with core tools
50
+ const coreTools = createTools();
51
+ const coreToolNames = new Set(coreTools.map(t => t.name));
52
+ const pluginTools = await loadPlugins(config.plugins ?? [], coreToolNames);
53
+ const allTools = [...coreTools, ...pluginTools];
54
+ // 7. Build tool context (includes allTools for trigger/bridge pipelines)
55
+ const ctx = { namespaces, embed, llm, session, triggers, bridges, allTools };
56
+ // 8. Filter active tools by namespace config + core set
57
+ const activeToolNames = namespaces.getActiveTools();
58
+ for (const t of CORE_TOOLS) {
59
+ activeToolNames.add(t);
60
+ }
61
+ // Plugin tools are always active (not gated by namespace config)
62
+ for (const t of pluginTools) {
63
+ activeToolNames.add(t.name);
64
+ }
65
+ const activeTools = allTools.filter(t => activeToolNames.has(t.name));
66
+ // 9. Create MCP server
67
+ const server = new Server({ name: 'cortex-engine', version: '0.1.0' }, { capabilities: { tools: {} } });
68
+ // ListTools handler
69
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
70
+ tools: activeTools.map(t => ({
71
+ name: t.name,
72
+ description: t.description,
73
+ inputSchema: t.inputSchema,
74
+ })),
75
+ }));
76
+ // CallTool handler
77
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
78
+ const { name, arguments: args } = request.params;
79
+ const tool = activeTools.find(t => t.name === name);
80
+ if (!tool) {
81
+ return {
82
+ content: [{ type: 'text', text: `Unknown tool: ${name}` }],
83
+ isError: true,
84
+ };
85
+ }
86
+ try {
87
+ const result = await tool.handler(args ?? {}, ctx);
88
+ return {
89
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
90
+ };
91
+ }
92
+ catch (err) {
93
+ const message = err instanceof Error ? err.message : String(err);
94
+ return {
95
+ content: [{ type: 'text', text: `Error in tool "${name}": ${message}` }],
96
+ isError: true,
97
+ };
98
+ }
99
+ });
100
+ return server;
101
+ }
102
+ // ─── Entry Point ─────────────────────────────────────────────────────────────
103
+ /** Start the MCP server using stdio transport. Called by bin/serve.ts. */
104
+ export async function startServer(config) {
105
+ const server = await createServer(config);
106
+ const transport = new StdioServerTransport();
107
+ await server.connect(transport);
108
+ }
109
+ // ─── Provider Factories ───────────────────────────────────────────────────────
110
+ // Firestore DB init — lazy-loads firebase-admin via dynamic import() to avoid
111
+ // requiring the SDK when running in SQLite-only mode.
112
+ async function initFirestoreDb(config) {
113
+ const { getApps, initializeApp } = await import('firebase-admin/app');
114
+ if (getApps().length === 0) {
115
+ initializeApp({
116
+ projectId: config.store_options?.gcp_project_id,
117
+ });
118
+ }
119
+ const { getFirestore, FieldValue } = await import('firebase-admin/firestore');
120
+ const db = config.store_options?.firestore_database_id
121
+ ? getFirestore(config.store_options.firestore_database_id)
122
+ : getFirestore();
123
+ db.settings({ ignoreUndefinedProperties: true });
124
+ return { db, FieldValue };
125
+ }
126
+ async function createEmbedProvider(config) {
127
+ switch (config.embed) {
128
+ case 'ollama':
129
+ return new OllamaEmbedProvider({
130
+ model: config.embed_options?.ollama_model,
131
+ baseUrl: config.embed_options?.ollama_url,
132
+ });
133
+ case 'vertex': {
134
+ const { PredictionServiceClient, helpers } = await import('@google-cloud/aiplatform');
135
+ const { VertexEmbedProvider } = await import('../providers/vertex-embed.js');
136
+ const location = config.embed_options?.vertex_location ?? 'us-central1';
137
+ const client = new PredictionServiceClient({
138
+ apiEndpoint: `${location}-aiplatform.googleapis.com`,
139
+ });
140
+ return new VertexEmbedProvider({
141
+ projectId: config.store_options?.gcp_project_id,
142
+ location,
143
+ model: config.embed_options?.vertex_model,
144
+ }, client, helpers);
145
+ }
146
+ default:
147
+ throw new Error(`Embed provider "${config.embed}" not yet implemented in this build`);
148
+ }
149
+ }
150
+ async function createLLMProvider(config) {
151
+ switch (config.llm) {
152
+ case 'ollama':
153
+ return new OllamaLLMProvider({
154
+ model: config.llm_options?.ollama_model,
155
+ baseUrl: config.llm_options?.ollama_url,
156
+ });
157
+ case 'gemini': {
158
+ const { VertexAI } = await import('@google-cloud/vertexai');
159
+ const { VertexLLMProvider } = await import('../providers/vertex-llm.js');
160
+ const projectId = config.store_options?.gcp_project_id ?? process.env['GOOGLE_CLOUD_PROJECT'] ?? '';
161
+ const location = config.llm_options?.vertex_location ?? 'us-central1';
162
+ const vertexAI = new VertexAI({ project: projectId, location });
163
+ return new VertexLLMProvider({
164
+ projectId,
165
+ location,
166
+ model: config.llm_options?.gemini_model,
167
+ }, vertexAI);
168
+ }
169
+ default:
170
+ throw new Error(`LLM provider "${config.llm}" not yet implemented in this build`);
171
+ }
172
+ }
173
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,c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Definition contains a JSON schema for MCP and a working handler.
5
+ * Handlers resolve the namespace, operate on the store, call engine functions,
6
+ * inject provenance from the session, and fire triggers/bridges after writes.
7
+ */
8
+ import type { EmbedProvider } from '../core/embed.js';
9
+ import type { LLMProvider } from '../core/llm.js';
10
+ import type { Session } from '../core/session.js';
11
+ import type { NamespaceManager } from '../namespace/manager.js';
12
+ import type { TriggerRegistry } from '../triggers/registry.js';
13
+ import type { BridgeRegistry } from '../bridges/registry.js';
14
+ /** Tool context passed to all handlers. */
15
+ export interface ToolContext {
16
+ namespaces: NamespaceManager;
17
+ embed: EmbedProvider;
18
+ llm: LLMProvider;
19
+ session: Session;
20
+ triggers: TriggerRegistry;
21
+ bridges: BridgeRegistry;
22
+ /** All registered tools (core + plugin), for trigger/bridge pipeline lookups. */
23
+ allTools: ToolDefinition[];
24
+ }
25
+ /** MCP-compatible tool definition with a working handler. */
26
+ export interface ToolDefinition {
27
+ name: string;
28
+ description: string;
29
+ inputSchema: {
30
+ type: 'object';
31
+ properties: Record<string, unknown>;
32
+ required?: string[];
33
+ };
34
+ handler: (args: Record<string, unknown>, ctx: ToolContext) => Promise<Record<string, unknown>>;
35
+ }
36
+ /** A plugin that contributes additional tools to the cortex engine. */
37
+ export interface ToolPlugin {
38
+ name: string;
39
+ tools: ToolDefinition[];
40
+ }
41
+ /** All 15 cognitive tool definitions. */
42
+ export declare function createTools(): ToolDefinition[];
43
+ /** Core tools that are always active regardless of namespace config. */
44
+ export declare const CORE_TOOLS: readonly ["query", "observe", "recall", "neighbors", "stats", "ops_append", "ops_query", "ops_update"];
45
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../src/mcp/tools.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AA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