@agntk/core 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +22 -0
  2. package/package.json +13 -13
  3. package/dist/memory/engine.d.ts +0 -130
  4. package/dist/memory/engine.d.ts.map +0 -1
  5. package/dist/memory/engine.js +0 -227
  6. package/dist/memory/engine.js.map +0 -1
  7. package/dist/memory/vectra-store.d.ts +0 -31
  8. package/dist/memory/vectra-store.d.ts.map +0 -1
  9. package/dist/memory/vectra-store.js +0 -122
  10. package/dist/memory/vectra-store.js.map +0 -1
  11. package/dist/prompts/templates.d.ts +0 -11
  12. package/dist/prompts/templates.d.ts.map +0 -1
  13. package/dist/prompts/templates.js +0 -115
  14. package/dist/prompts/templates.js.map +0 -1
  15. package/dist/streaming/data-parts.d.ts +0 -163
  16. package/dist/streaming/data-parts.d.ts.map +0 -1
  17. package/dist/streaming/data-parts.js +0 -14
  18. package/dist/streaming/data-parts.js.map +0 -1
  19. package/dist/streaming/index.d.ts +0 -8
  20. package/dist/streaming/index.d.ts.map +0 -1
  21. package/dist/streaming/index.js +0 -10
  22. package/dist/streaming/index.js.map +0 -1
  23. package/dist/streaming/transient.d.ts +0 -136
  24. package/dist/streaming/transient.d.ts.map +0 -1
  25. package/dist/streaming/transient.js +0 -201
  26. package/dist/streaming/transient.js.map +0 -1
  27. package/dist/tools/provider.d.ts +0 -97
  28. package/dist/tools/provider.d.ts.map +0 -1
  29. package/dist/tools/provider.js +0 -178
  30. package/dist/tools/provider.js.map +0 -1
  31. package/dist/utils/logger.d.ts +0 -35
  32. package/dist/utils/logger.d.ts.map +0 -1
  33. package/dist/utils/logger.js +0 -149
  34. package/dist/utils/logger.js.map +0 -1
  35. package/dist/workflow/durable-agent.d.ts +0 -128
  36. package/dist/workflow/durable-agent.d.ts.map +0 -1
  37. package/dist/workflow/durable-agent.js +0 -323
  38. package/dist/workflow/durable-agent.js.map +0 -1
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Phoenixrr2113
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agntk/core",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "Opinionated agent SDK extending AI SDK's ToolLoopAgent",
6
6
  "main": "./dist/index.js",
@@ -32,24 +32,18 @@
32
32
  "default": "./dist/advanced/index.js"
33
33
  }
34
34
  },
35
- "scripts": {
36
- "build": "tsc && node ../../scripts/fix-esm-imports.mjs ./dist",
37
- "dev": "tsc --watch",
38
- "test": "vitest",
39
- "clean": "rm -rf dist"
40
- },
41
35
  "dependencies": {
42
- "@agntk/logger": "workspace:*",
43
36
  "@ai-sdk/openai-compatible": "^2.0.28",
44
37
  "ai": "6.0.77",
45
38
  "xstate": "^5.26.0",
46
- "zod": "^3.25.76"
39
+ "zod": "^3.25.76",
40
+ "@agntk/logger": "0.1.2"
47
41
  },
48
42
  "devDependencies": {
49
- "@agntk/config-typescript": "workspace:*",
50
43
  "@types/node": "^20.17.19",
51
44
  "typescript": "^5.7.3",
52
- "vitest": "^3.2.3"
45
+ "vitest": "^3.2.3",
46
+ "@agntk/config-typescript": "0.1.0"
53
47
  },
54
48
  "peerDependencies": {
55
49
  "@vercel/otel": "*",
@@ -97,5 +91,11 @@
97
91
  "workflow",
98
92
  "durable"
99
93
  ],
100
- "license": "MIT"
101
- }
94
+ "license": "MIT",
95
+ "scripts": {
96
+ "build": "tsc && node ../../scripts/fix-esm-imports.mjs ./dist",
97
+ "dev": "tsc --watch",
98
+ "test": "vitest",
99
+ "clean": "rm -rf dist"
100
+ }
101
+ }
@@ -1,130 +0,0 @@
1
- /**
2
- * @agntk/core - Unified Memory Engine
3
- *
4
- * Single write path: remember() → LLM extraction → parallel writes to Vectra + Graph.
5
- * Implements Mem0 ADD/UPDATE/DELETE/NOOP pattern with Hindsight 4-network taxonomy.
6
- *
7
- * Architecture:
8
- * - VectorStore: Semantic similarity search (Vectra)
9
- * - GraphStore: Structural relationships (Graphology via QueryPort)
10
- * - ExtractionModel: LLM-powered fact extraction
11
- * - ContradictionDetector: Write-time conflict detection
12
- */
13
- import type { LanguageModel } from 'ai';
14
- import type { MemoryStore, MemorySearchResult } from './vectra-store.js';
15
- import { type ExtractedFact, type MemoryOperation } from './extraction.js';
16
- /** Graph store interface — matches QueryPort episode/entity methods */
17
- export interface MemoryGraphStore {
18
- upsertEpisode(episode: {
19
- id: string;
20
- timestamp: string;
21
- type: 'conversation' | 'observation' | 'action' | 'decision' | 'learning';
22
- summary: string;
23
- content: string;
24
- entities: string[];
25
- relationships: string[];
26
- }): Promise<void>;
27
- linkEpisodeEntity(episodeId: string, entityName: string): Promise<void>;
28
- getEpisodesByQuery(query: string, limit: number): Promise<Array<{
29
- id?: string;
30
- summary?: string;
31
- content?: string;
32
- timestamp?: string;
33
- type?: string;
34
- properties?: Record<string, unknown>;
35
- }>>;
36
- upsertContradiction(contradiction: {
37
- id: string;
38
- detectedAt: string;
39
- resolution_winner: string | null;
40
- resolution_reasoning: string | null;
41
- factA_id: string;
42
- factA_statement: string;
43
- factA_source: string;
44
- factA_timestamp: string;
45
- factB_id: string;
46
- factB_statement: string;
47
- factB_source: string;
48
- factB_timestamp: string;
49
- }): Promise<void>;
50
- }
51
- /** Contradiction detector interface — matches brain's ContradictionDetector */
52
- export interface ContradictionDetectorPort {
53
- detect(statementA: string, statementB: string, metadataA?: {
54
- id: string;
55
- source: string;
56
- timestamp: string;
57
- }, metadataB?: {
58
- id: string;
59
- source: string;
60
- timestamp: string;
61
- }): {
62
- id: string;
63
- factA: Record<string, string>;
64
- factB: Record<string, string>;
65
- detectedAt: string;
66
- } | null;
67
- }
68
- /** Result of a unified remember() operation */
69
- export interface MemoryWriteResult {
70
- id: string;
71
- operation: MemoryOperation;
72
- facts: ExtractedFact[];
73
- vectorStoreId?: string;
74
- graphStoreId?: string;
75
- contradiction?: {
76
- id: string;
77
- existingFact: string;
78
- newFact: string;
79
- };
80
- }
81
- /** Configuration for the unified memory engine */
82
- export interface MemoryEngineConfig {
83
- /** Vector store for semantic search (Vectra) */
84
- vectorStore: MemoryStore;
85
- /** Graph store for structural queries (Graphology via QueryPort) — optional */
86
- graphStore?: MemoryGraphStore;
87
- /** LLM for extraction pipeline — optional, extraction disabled without it */
88
- extractionModel?: LanguageModel;
89
- /** Contradiction detector — optional */
90
- contradictionDetector?: ContradictionDetectorPort;
91
- /** Default top-K for recall */
92
- defaultTopK?: number;
93
- /** Default similarity threshold */
94
- defaultThreshold?: number;
95
- }
96
- /** The unified memory engine interface */
97
- export interface MemoryEngine {
98
- /** Store text with LLM extraction → parallel writes to vector + graph */
99
- remember(text: string, metadata?: Record<string, unknown>): Promise<MemoryWriteResult>;
100
- /** Semantic search via vector store */
101
- recall(query: string, options?: {
102
- topK?: number;
103
- threshold?: number;
104
- }): Promise<MemorySearchResult[]>;
105
- /** Graph-based knowledge query — returns episodes/entities matching query */
106
- queryKnowledge(query: string, limit?: number): Promise<Array<Record<string, unknown>>>;
107
- /** Remove a memory by ID from both stores */
108
- forget(id: string): Promise<boolean>;
109
- /** Get stats */
110
- count(): Promise<number>;
111
- /** Cleanup */
112
- close(): Promise<void>;
113
- }
114
- /**
115
- * Create a unified memory engine.
116
- *
117
- * @example
118
- * ```typescript
119
- * const engine = createMemoryEngine({
120
- * vectorStore: await createMemoryStore({ path: './.memory' }),
121
- * graphStore: new GraphologyAdapter(),
122
- * extractionModel: openai('gpt-4o-mini'),
123
- * });
124
- *
125
- * // Single remember() does extraction + parallel writes
126
- * const result = await engine.remember('TypeScript 5.3 supports import attributes');
127
- * ```
128
- */
129
- export declare function createMemoryEngine(config: MemoryEngineConfig): MemoryEngine;
130
- //# sourceMappingURL=engine.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/memory/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AAExC,OAAO,KAAK,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACtE,OAAO,EAEL,KAAK,aAAa,EAElB,KAAK,eAAe,EACrB,MAAM,cAAc,CAAC;AAQtB,uEAAuE;AACvE,MAAM,WAAW,gBAAgB;IAC/B,aAAa,CAAC,OAAO,EAAE;QACrB,EAAE,EAAE,MAAM,CAAC;QACX,SAAS,EAAE,MAAM,CAAC;QAClB,IAAI,EAAE,cAAc,GAAG,aAAa,GAAG,QAAQ,GAAG,UAAU,GAAG,UAAU,CAAC;QAC1E,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,MAAM,CAAC;QAChB,QAAQ,EAAE,MAAM,EAAE,CAAC;QACnB,aAAa,EAAE,MAAM,EAAE,CAAC;KACzB,GAA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M,EAAE,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAAC;IACtG,6EAA6E;IAC7E,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IACvF,6CAA6C;IAC7C,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACrC,gBAAgB;IAChB,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IACzB,cAAc;IACd,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAMD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CA0J3E"}
@@ -1,227 +0,0 @@
1
- /**
2
- * @agntk/core - Unified Memory Engine
3
- *
4
- * Single write path: remember() → LLM extraction → parallel writes to Vectra + Graph.
5
- * Implements Mem0 ADD/UPDATE/DELETE/NOOP pattern with Hindsight 4-network taxonomy.
6
- *
7
- * Architecture:
8
- * - VectorStore: Semantic similarity search (Vectra)
9
- * - GraphStore: Structural relationships (Graphology via QueryPort)
10
- * - ExtractionModel: LLM-powered fact extraction
11
- * - ContradictionDetector: Write-time conflict detection
12
- */
13
- import { createLogger } from '@agntk/logger';
14
- import { extractFacts, } from './extraction.js';
15
- const log = createLogger('@agntk/core:memory-engine');
16
- // ============================================================================
17
- // Implementation
18
- // ============================================================================
19
- /**
20
- * Create a unified memory engine.
21
- *
22
- * @example
23
- * ```typescript
24
- * const engine = createMemoryEngine({
25
- * vectorStore: await createMemoryStore({ path: './.memory' }),
26
- * graphStore: new GraphologyAdapter(),
27
- * extractionModel: openai('gpt-4o-mini'),
28
- * });
29
- *
30
- * // Single remember() does extraction + parallel writes
31
- * const result = await engine.remember('TypeScript 5.3 supports import attributes');
32
- * ```
33
- */
34
- export function createMemoryEngine(config) {
35
- const { vectorStore, graphStore, extractionModel, contradictionDetector, defaultTopK = 5, defaultThreshold = 0.7, } = config;
36
- return {
37
- async remember(text, metadata) {
38
- const writeId = generateWriteId();
39
- const timestamp = new Date().toISOString();
40
- log.debug('remember() — unified write path', { writeId, textLength: text.length });
41
- // Step 1: Extract facts via LLM (if model provided)
42
- let facts = [];
43
- if (extractionModel) {
44
- try {
45
- const done = log.time('extraction');
46
- const result = await extractFacts(text, { model: extractionModel });
47
- facts = result.facts;
48
- done();
49
- log.info('Extraction complete', { factCount: facts.length });
50
- }
51
- catch (error) {
52
- log.warn('Extraction failed, continuing with raw text', { error: String(error) });
53
- }
54
- }
55
- // Step 2: Check for contradictions against existing memories
56
- let contradictionResult;
57
- if (contradictionDetector && facts.length > 0) {
58
- try {
59
- contradictionResult = await detectContradictions(facts, vectorStore, contradictionDetector, graphStore, defaultTopK, defaultThreshold);
60
- }
61
- catch (error) {
62
- log.warn('Contradiction detection failed, continuing', { error: String(error) });
63
- }
64
- }
65
- // Step 3: Determine operation type
66
- const operation = contradictionResult ? 'UPDATE' : 'ADD';
67
- // Step 4: Parallel writes to vector store + graph store
68
- const writePromises = [];
69
- let vectorStoreId;
70
- let graphStoreId;
71
- // Vector store: store the raw text + extracted facts as metadata
72
- writePromises.push(vectorStore.remember(text, {
73
- ...metadata,
74
- writeId,
75
- timestamp,
76
- operation,
77
- networks: facts.map((f) => f.network),
78
- factCount: facts.length,
79
- facts: facts.map((f) => f.fact),
80
- }).then((id) => { vectorStoreId = id; }));
81
- // Graph store: create episode + link entities
82
- if (graphStore && facts.length > 0) {
83
- const episodeType = classifyEpisodeType(facts);
84
- const entityNames = [...new Set(facts.flatMap((f) => f.entities.map((e) => e.name)))];
85
- const relationshipStrings = facts.flatMap((f) => f.relationships.map((r) => `${r.from}-[${r.type}]->${r.to}`));
86
- writePromises.push((async () => {
87
- await graphStore.upsertEpisode({
88
- id: writeId,
89
- timestamp,
90
- type: episodeType,
91
- summary: facts.map((f) => f.fact).join('; '),
92
- content: text,
93
- entities: entityNames,
94
- relationships: relationshipStrings,
95
- });
96
- graphStoreId = writeId;
97
- // Link entities to the episode
98
- for (const entityName of entityNames) {
99
- await graphStore.linkEpisodeEntity(writeId, entityName);
100
- }
101
- })());
102
- }
103
- await Promise.all(writePromises);
104
- log.info('Unified write complete', {
105
- writeId,
106
- operation,
107
- factCount: facts.length,
108
- vectorStoreId,
109
- graphStoreId,
110
- hasContradiction: !!contradictionResult,
111
- });
112
- return {
113
- id: writeId,
114
- operation,
115
- facts,
116
- vectorStoreId,
117
- graphStoreId,
118
- contradiction: contradictionResult,
119
- };
120
- },
121
- async recall(query, options) {
122
- return vectorStore.recall(query, {
123
- topK: options?.topK ?? defaultTopK,
124
- threshold: options?.threshold ?? defaultThreshold,
125
- });
126
- },
127
- async queryKnowledge(query, limit = 10) {
128
- if (!graphStore) {
129
- log.debug('queryKnowledge called without graph store — returning empty');
130
- return [];
131
- }
132
- const episodes = await graphStore.getEpisodesByQuery(query, limit);
133
- return episodes.map((ep) => ({
134
- id: ep.id ?? ep.properties?.id,
135
- summary: ep.summary ?? ep.properties?.summary,
136
- content: ep.content ?? ep.properties?.content,
137
- timestamp: ep.timestamp ?? ep.properties?.timestamp,
138
- type: ep.type ?? ep.properties?.type,
139
- }));
140
- },
141
- async forget(id) {
142
- return vectorStore.forget(id);
143
- },
144
- async count() {
145
- return vectorStore.count();
146
- },
147
- async close() {
148
- await vectorStore.close();
149
- },
150
- };
151
- }
152
- // ============================================================================
153
- // Helpers
154
- // ============================================================================
155
- function generateWriteId() {
156
- return `mem_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
157
- }
158
- /**
159
- * Classify the episode type based on the dominant memory network.
160
- */
161
- function classifyEpisodeType(facts) {
162
- const counts = {
163
- world_fact: 0,
164
- experience: 0,
165
- entity_summary: 0,
166
- belief: 0,
167
- };
168
- for (const fact of facts) {
169
- counts[fact.network]++;
170
- }
171
- // Map network types to episode types
172
- if (counts.experience > 0)
173
- return 'action';
174
- if (counts.belief > 0)
175
- return 'decision';
176
- if (counts.entity_summary > counts.world_fact)
177
- return 'observation';
178
- return 'learning';
179
- }
180
- /**
181
- * Check new facts against existing memories for contradictions.
182
- */
183
- async function detectContradictions(newFacts, vectorStore, detector, graphStore, topK, threshold) {
184
- // For each new world_fact or belief, check against similar existing memories
185
- const checkableFacts = newFacts.filter((f) => f.network === 'world_fact' || f.network === 'belief');
186
- for (const newFact of checkableFacts) {
187
- const existing = await vectorStore.recall(newFact.fact, { topK, threshold });
188
- for (const match of existing) {
189
- const contradiction = detector.detect(match.item.text, newFact.fact, { id: match.item.id, source: 'memory', timestamp: match.item.timestamp.toISOString() }, { id: 'new', source: 'input', timestamp: new Date().toISOString() });
190
- if (contradiction) {
191
- log.info('Contradiction detected', {
192
- existing: match.item.text.slice(0, 80),
193
- new: newFact.fact.slice(0, 80),
194
- });
195
- // Store the contradiction in graph store if available
196
- if (graphStore) {
197
- try {
198
- await graphStore.upsertContradiction({
199
- id: contradiction.id,
200
- detectedAt: contradiction.detectedAt,
201
- resolution_winner: null,
202
- resolution_reasoning: null,
203
- factA_id: match.item.id,
204
- factA_statement: match.item.text,
205
- factA_source: 'memory',
206
- factA_timestamp: match.item.timestamp.toISOString(),
207
- factB_id: 'new',
208
- factB_statement: newFact.fact,
209
- factB_source: 'input',
210
- factB_timestamp: new Date().toISOString(),
211
- });
212
- }
213
- catch (error) {
214
- log.warn('Failed to store contradiction in graph', { error: String(error) });
215
- }
216
- }
217
- return {
218
- id: contradiction.id,
219
- existingFact: match.item.text,
220
- newFact: newFact.fact,
221
- };
222
- }
223
- }
224
- }
225
- return undefined;
226
- }
227
- //# sourceMappingURL=engine.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/memory/engine.ts"],"names":[],"mapp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AU,EAAE,aAAa,CAAC,UAAU;4BACpC,iBAAiB,EAAE,IAAI;4BACvB,oBAAoB,EAAE,IAAI;4BAC1B,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE;4BACvB,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI;4BAChC,YAAY,EAAE,QAAQ;4BACtB,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE;4BACnD,QAAQ,EAAE,KAAK;4BACf,eAAe,EAAE,OAAO,CAAC,IAAI;4BAC7B,YAAY,EAAE,OAAO;4BACrB,eAAe,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;yBAC1C,CAAC,CAAC;oBACL,CAAC;oBAAC,OAAO,KAAK,EAAE,CAAC;wBACf,GAAG,CAAC,IAAI,CAAC,wCAAwC,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;oBAC/E,CAAC;gBACH,CAAC;gBAED,OAAO;oBACL,EAAE,EAAE,aAAa,CAAC,EAAE;oBACpB,YAAY,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI;oBAC7B,OAAO,EAAE,OAAO,CAAC,IAAI;iBACtB,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC"}
@@ -1,31 +0,0 @@
1
- /**
2
- * @agntk/core - Vectra Memory Store
3
- *
4
- * Portable in-memory vector database using Vectra.
5
- * Zero native dependencies, file-based persistence.
6
- */
7
- import type { MemoryOptions } from '../types/agent.js';
8
- export interface MemoryItem {
9
- id: string;
10
- text: string;
11
- metadata?: Record<string, unknown>;
12
- timestamp: Date;
13
- }
14
- export interface MemorySearchResult {
15
- item: MemoryItem;
16
- score: number;
17
- }
18
- export interface MemoryStore {
19
- remember: (text: string, metadata?: Record<string, unknown>) => Promise<string>;
20
- recall: (query: string, options?: {
21
- topK?: number;
22
- threshold?: number;
23
- }) => Promise<MemorySearchResult[]>;
24
- forget: (id: string) => Promise<boolean>;
25
- forgetAll: (filter?: (item: MemoryItem) => boolean) => Promise<number>;
26
- count: () => Promise<number>;
27
- close: () => Promise<void>;
28
- }
29
- export declare function createMemoryStore(options?: MemoryOptions): Promise<MemoryStore>;
30
- export type { MemoryOptions };
31
- //# sourceMappingURL=vectra-store.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"vectra-store.d.ts","sourceRoot":"","sources":["../../src/memory/vectra-store.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAcH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAQpD,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,SAAS,EAAE,IAAI,CAAC;CACjB;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,UAAU,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAChF,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAAC;IAC1G,MAAM,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACzC,SAAS,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,OAAO,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACvE,KAAK,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7B,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5B;AAqCD,wBAAsB,iBAAiB,CAAC,OAAO,GAAE,aAAkB,GAAG,OAAO,CAAC,WAAW,CAAC,CAkGzF;AAMD,YAAY,EAAE,aAAa,EAAE,CAAC"}
@@ -1,122 +0,0 @@
1
- /**
2
- * @agntk/core - Vectra Memory Store
3
- *
4
- * Portable in-memory vector database using Vectra.
5
- * Zero native dependencies, file-based persistence.
6
- */
7
- import { LocalIndex } from 'vectra';
8
- import * as path from 'node:path';
9
- import * as fs from 'node:fs/promises';
10
- import { createLogger } from '@agntk/logger';
11
- import { getConfig } from '../config/index.js';
12
- import { DEFAULT_EMBEDDING_URL, DEFAULT_EMBEDDING_MODEL, DEFAULT_MEMORY_PATH, DEFAULT_MEMORY_TOP_K, DEFAULT_MEMORY_SIMILARITY_THRESHOLD, } from '../constants.js';
13
- const log = createLogger('@agntk/core:memory');
14
- // ============================================================================
15
- // Embedding - Using OpenAI directly
16
- // ============================================================================
17
- async function getEmbedding(text, modelName, embeddingUrl) {
18
- const apiKey = process.env['OPENAI_API_KEY'];
19
- if (!apiKey) {
20
- throw new Error('OPENAI_API_KEY required for memory embeddings');
21
- }
22
- const url = embeddingUrl ?? DEFAULT_EMBEDDING_URL;
23
- const response = await fetch(url, {
24
- method: 'POST',
25
- headers: {
26
- 'Content-Type': 'application/json',
27
- 'Authorization': `Bearer ${apiKey}`,
28
- },
29
- body: JSON.stringify({
30
- model: modelName ?? DEFAULT_EMBEDDING_MODEL,
31
- input: text,
32
- }),
33
- });
34
- if (!response.ok) {
35
- throw new Error(`Embedding failed: ${response.statusText}`);
36
- }
37
- const data = await response.json();
38
- return data.data[0].embedding;
39
- }
40
- // ============================================================================
41
- // Memory Store Implementation
42
- // ============================================================================
43
- export async function createMemoryStore(options = {}) {
44
- // Merge with config values
45
- const config = getConfig();
46
- const memoryConfig = (config.memory ?? {});
47
- const { path: storagePath = memoryConfig.path ?? DEFAULT_MEMORY_PATH, embedModel = memoryConfig.embedModel ?? DEFAULT_EMBEDDING_MODEL, topK = memoryConfig.topK ?? DEFAULT_MEMORY_TOP_K, similarityThreshold = memoryConfig.similarityThreshold ?? DEFAULT_MEMORY_SIMILARITY_THRESHOLD, } = options;
48
- log.info('Creating memory store', { path: storagePath, embedModel, topK });
49
- const absolutePath = path.resolve(storagePath);
50
- await fs.mkdir(absolutePath, { recursive: true });
51
- const index = new LocalIndex(absolutePath);
52
- if (!await index.isIndexCreated()) {
53
- await index.createIndex();
54
- }
55
- const store = {
56
- async remember(text, metadata) {
57
- const id = generateId();
58
- const vector = await getEmbedding(text, embedModel);
59
- await index.insertItem({
60
- id,
61
- vector,
62
- metadata: { text, timestamp: new Date().toISOString(), ...metadata },
63
- });
64
- return id;
65
- },
66
- async recall(query, opts) {
67
- const queryVector = await getEmbedding(query, embedModel);
68
- const k = opts?.topK ?? topK;
69
- const threshold = opts?.threshold ?? similarityThreshold;
70
- const results = await index.queryItems(queryVector, k);
71
- return results
72
- .filter(r => r.score >= threshold)
73
- .map(r => ({
74
- item: {
75
- id: r.item.id,
76
- text: r.item.metadata?.text ?? '',
77
- metadata: r.item.metadata,
78
- timestamp: new Date(r.item.metadata?.timestamp ?? Date.now()),
79
- },
80
- score: r.score,
81
- }));
82
- },
83
- async forget(id) {
84
- try {
85
- await index.deleteItem(id);
86
- return true;
87
- }
88
- catch (_e) {
89
- return false;
90
- }
91
- },
92
- async forgetAll(filter) {
93
- const items = await index.listItems();
94
- let deleted = 0;
95
- for (const item of items) {
96
- const memoryItem = {
97
- id: item.id,
98
- text: item.metadata?.text ?? '',
99
- metadata: item.metadata,
100
- timestamp: new Date(item.metadata?.timestamp ?? Date.now()),
101
- };
102
- if (!filter || filter(memoryItem)) {
103
- await index.deleteItem(item.id);
104
- deleted++;
105
- }
106
- }
107
- return deleted;
108
- },
109
- async count() {
110
- const items = await index.listItems();
111
- return items.length;
112
- },
113
- async close() {
114
- // Vectra auto-persists
115
- },
116
- };
117
- return store;
118
- }
119
- function generateId() {
120
- return `mem_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
121
- }
122
- //# sourceMappingURL=vectra-store.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"vectra-store.js","sourceRoot":"","sources":["../../src/memory/vectra-store.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EACL,qBAAqB,EACrB,uBAAuB,EACvB,mBAAmB,EACnB,oBAAoB,EACpB,mCAAmC,GACpC,MAAM,cAAc,CAAC;AAGtB,MAAM,GAAG,GAAG,YAAY,CAAC,oBAAoB,CAAC,CAAC;AA2B/C,+EAA+E;AAC/E,oCAAoC;AACpC,+EAA+E;AAE/E,KAAK,UAAU,YAAY,CAAC,IAAY,EAAE,SAAkB,EAAE,YAAqB;IACjF,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC7C,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,CAAC;IAED,MAAM,GAAG,GAAG,YAAY,IAAI,qBAAqB,CAAC;IAClD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;QAChC,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACP,cAAc,EAAE,kBAAkB;YAClC,eAAe,EAAE,UAAU,MAAM,EAAE;SACpC;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;YACnB,KAAK,EAAE,SAAS,IAAI,uBAAuB;YAC3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,UAAU;IACjB,OAAO,OAAO,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;AACxE,CAAC"}
@@ -1,11 +0,0 @@
1
- /**
2
- * @agntk/core - System Prompt Templates
3
- * Core system prompts for agent behavior
4
- *
5
- * @deprecated Use `presets/role-registry.ts` instead. That module is the canonical
6
- * source of truth for role prompts, used by `createAgent()` via `getRole()`.
7
- * This file is kept for backward compatibility of public exports only.
8
- */
9
- export declare const systemPrompt = "You are an autonomous agent. Your purpose is to accomplish the user's goal using whatever approach makes sense.\n\n# Philosophy\n\nYou have a mind and you have tools. Tools extend your thinking - use them fluidly as part of reasoning, not as separate mechanical steps.\n\nThere is no single correct workflow. Match your approach to the problem:\n- Reason through it, gather information, reason more, then act\n- Act immediately if the path is obvious\n- Start one approach, realize it's wrong, switch to another\n- Call multiple tools in parallel when they don't depend on each other\n\nWhen something doesn't work, adapt. When you need information, go get it. When uncertain, reason carefully. When clear, act directly.\n\nWhen errors occur, read them carefully. The error message usually points to the fix.\n\n# Action\n\nDo things, don't announce them. Instead of \"I'll search for X\", just search.\n\nBe autonomous. Complete tasks without asking permission at every step. Only ask the user when you genuinely need information only they can provide.\n\n# Thinking Out Loud\n\nBefore each action, briefly state:\n- **Goal**: What am I trying to accomplish?\n- **Approach**: Why is this the right tool/action?\n- **Risk**: What could go wrong?\n\nKeep it concise (1-2 sentences each). This helps the user understand your decisions.\n\n# Efficiency\n\nComplete tasks in the fewest steps possible:\n- Think first: What's the most direct path to the goal?\n- Use the right tool: Each tool's description explains when to use it\n- Chain when independent: Call multiple tools in parallel when they don't depend on each other\n- No random exploration: Every action should have a purpose\n\n# Tools\n\nYou have access to consolidated tools with multiple actions. Use the action parameter to specify what to do:\n\n**fs** - All file operations (read, write, edit, list, glob, grep, move, delete, info, mkdir)\n**shell** - Execute shell commands (with allowlisting for repeated commands)\n**web** - Search the internet (search) or fetch page content (fetch)\n**memory** - Knowledge graph operations (add, search, episodes, fact, entity, related)\n\n**delegate** - Parallel work: tool chains (steps), sub-agents (agent), or background processes (background)\n**task** - Manage background tasks (status, output, cancel, list, cleanup)\n\nAdditional tools: plan, ask_user, task_complete\n\nEach tool's description provides detailed guidance on when and how to use it. Read the descriptions to understand capabilities and constraints.\n\n# Delegation\n\nFor complex work, use the delegate tool:\n- **steps**: Execute multiple tool calls in sequence with dependency handling\n- **agent**: Spawn a specialized sub-agent (coder/researcher/analyst)\n- **background**: Start a long-running shell command\n\nAfter delegating, use the task tool to monitor progress and retrieve output.\n\n# Completion\n\nCall task_complete when you have fully accomplished what the user asked for.\n\nOnly call task_complete when truly done - not planned, not partially done, but actually complete.\n";
10
- export declare const rolePrompts: Record<string, string>;
11
- //# sourceMappingURL=templates.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/prompts/templates.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,eAAO,MAAM,YAAY,+/FAqExB,CAAC;AAEF,eAAO,MAAM,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAsC9C,CAAC"}