agentx-sdk 0.2.1 → 0.3.1

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 (89) hide show
  1. package/README.md +629 -25
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +18 -4
  4. package/dist/agent.js.map +1 -1
  5. package/dist/config/config.d.ts +4 -4
  6. package/dist/config/config.d.ts.map +1 -1
  7. package/dist/config/config.js +3 -2
  8. package/dist/config/config.js.map +1 -1
  9. package/dist/contracts/entities/stores.d.ts +2 -0
  10. package/dist/contracts/entities/stores.d.ts.map +1 -1
  11. package/dist/core/compaction/tool-result-budget.d.ts.map +1 -1
  12. package/dist/core/compaction/tool-result-budget.js +8 -4
  13. package/dist/core/compaction/tool-result-budget.js.map +1 -1
  14. package/dist/core/context-builder.d.ts +2 -0
  15. package/dist/core/context-builder.d.ts.map +1 -1
  16. package/dist/core/context-builder.js +7 -2
  17. package/dist/core/context-builder.js.map +1 -1
  18. package/dist/core/conversation-manager.js +1 -1
  19. package/dist/core/conversation-manager.js.map +1 -1
  20. package/dist/core/react-loop.d.ts.map +1 -1
  21. package/dist/core/react-loop.js +8 -5
  22. package/dist/core/react-loop.js.map +1 -1
  23. package/dist/index.d.ts +1 -5
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +0 -2
  26. package/dist/index.js.map +1 -1
  27. package/dist/knowledge/knowledge-manager.d.ts.map +1 -1
  28. package/dist/knowledge/knowledge-manager.js +18 -10
  29. package/dist/knowledge/knowledge-manager.js.map +1 -1
  30. package/dist/knowledge/sqlite-vector-store.d.ts +2 -0
  31. package/dist/knowledge/sqlite-vector-store.d.ts.map +1 -1
  32. package/dist/knowledge/sqlite-vector-store.js +20 -1
  33. package/dist/knowledge/sqlite-vector-store.js.map +1 -1
  34. package/dist/llm/errors.d.ts.map +1 -1
  35. package/dist/llm/errors.js +12 -6
  36. package/dist/llm/errors.js.map +1 -1
  37. package/dist/llm/llm-client.d.ts +10 -0
  38. package/dist/llm/llm-client.d.ts.map +1 -1
  39. package/dist/llm/llm-client.js +47 -4
  40. package/dist/llm/llm-client.js.map +1 -1
  41. package/dist/llm/message-types.d.ts +0 -6
  42. package/dist/llm/message-types.d.ts.map +1 -1
  43. package/dist/memory/file-memory-system.d.ts +1 -1
  44. package/dist/memory/file-memory-system.d.ts.map +1 -1
  45. package/dist/memory/file-memory-system.js +15 -18
  46. package/dist/memory/file-memory-system.js.map +1 -1
  47. package/dist/memory/memory-extractor.d.ts +1 -0
  48. package/dist/memory/memory-extractor.d.ts.map +1 -1
  49. package/dist/memory/memory-extractor.js +4 -1
  50. package/dist/memory/memory-extractor.js.map +1 -1
  51. package/dist/memory/memory-paths.d.ts +25 -1
  52. package/dist/memory/memory-paths.d.ts.map +1 -1
  53. package/dist/memory/memory-paths.js +71 -6
  54. package/dist/memory/memory-paths.js.map +1 -1
  55. package/dist/memory/memory-relevance.d.ts +1 -0
  56. package/dist/memory/memory-relevance.d.ts.map +1 -1
  57. package/dist/memory/memory-relevance.js +4 -1
  58. package/dist/memory/memory-relevance.js.map +1 -1
  59. package/dist/memory/memory-scanner.d.ts.map +1 -1
  60. package/dist/memory/memory-scanner.js +2 -0
  61. package/dist/memory/memory-scanner.js.map +1 -1
  62. package/dist/memory/memory-tools.d.ts.map +1 -1
  63. package/dist/memory/memory-tools.js +81 -29
  64. package/dist/memory/memory-tools.js.map +1 -1
  65. package/dist/skills/skill-args.d.ts.map +1 -1
  66. package/dist/skills/skill-args.js +6 -4
  67. package/dist/skills/skill-args.js.map +1 -1
  68. package/dist/skills/skill-manager.d.ts +2 -0
  69. package/dist/skills/skill-manager.d.ts.map +1 -1
  70. package/dist/skills/skill-manager.js +4 -0
  71. package/dist/skills/skill-manager.js.map +1 -1
  72. package/dist/storage/sqlite-conversation-store.js +10 -1
  73. package/dist/storage/sqlite-conversation-store.js.map +1 -1
  74. package/dist/tools/builtin/bash.d.ts.map +1 -1
  75. package/dist/tools/builtin/bash.js +32 -2
  76. package/dist/tools/builtin/bash.js.map +1 -1
  77. package/dist/tools/builtin/glob.d.ts.map +1 -1
  78. package/dist/tools/builtin/glob.js +8 -4
  79. package/dist/tools/builtin/glob.js.map +1 -1
  80. package/dist/tools/builtin/grep.d.ts.map +1 -1
  81. package/dist/tools/builtin/grep.js +9 -2
  82. package/dist/tools/builtin/grep.js.map +1 -1
  83. package/dist/tools/builtin/web-fetch.d.ts.map +1 -1
  84. package/dist/tools/builtin/web-fetch.js +39 -0
  85. package/dist/tools/builtin/web-fetch.js.map +1 -1
  86. package/dist/tools/mcp-adapter.d.ts.map +1 -1
  87. package/dist/tools/mcp-adapter.js +52 -16
  88. package/dist/tools/mcp-adapter.js.map +1 -1
  89. package/package.json +4 -2
package/README.md CHANGED
@@ -1,5 +1,595 @@
1
1
  # AgentX SDK
2
2
 
3
+ TypeScript library for building conversational agents with LLMs. Streaming-first, tools, memory, knowledge/RAG, skills and MCP — all in-process, no frameworks.
4
+
5
+ ```bash
6
+ npm install agentx-sdk
7
+ ```
8
+
9
+ ## Quick Start
10
+
11
+ ```typescript
12
+ import { Agent } from 'agentx-sdk';
13
+
14
+ // Works with any OpenAI-compatible API (OpenRouter, OpenAI, Azure, Groq, etc.)
15
+ const agent = Agent.create({
16
+ apiKey: process.env.LLM_API_KEY!,
17
+ // baseUrl: 'https://api.openai.com/v1', // optional — defaults to OpenRouter
18
+ // model: 'gpt-4o', // optional — defaults to Claude Sonnet
19
+ });
20
+
21
+ // Simple chat
22
+ const response = await agent.chat('What is the capital of France?');
23
+
24
+ // Streaming
25
+ for await (const event of agent.stream('Explain recursion')) {
26
+ if (event.type === 'text_delta') process.stdout.write(event.content);
27
+ }
28
+
29
+ // Separate embedding provider (e.g. OpenAI direct for lower latency)
30
+ const agentWithEmbeddings = Agent.create({
31
+ apiKey: process.env.LLM_API_KEY!,
32
+ embedding: {
33
+ apiKey: process.env.OPENAI_API_KEY!,
34
+ baseUrl: 'https://api.openai.com/v1',
35
+ model: 'text-embedding-3-small',
36
+ },
37
+ });
38
+ ```
39
+
40
+ ## Tools
41
+
42
+ ```typescript
43
+ import { z } from 'zod';
44
+
45
+ agent.addTool({
46
+ name: 'weather',
47
+ description: 'Get current weather for a city',
48
+ parameters: z.object({ city: z.string() }),
49
+ execute: async ({ city }) => {
50
+ const res = await fetch(`https://api.weather.com/${city}`);
51
+ return await res.text();
52
+ },
53
+ });
54
+
55
+ await agent.chat('What is the weather in Sao Paulo?');
56
+ // The agent decides to call the tool automatically
57
+ ```
58
+
59
+ ### Builtin Tools
60
+
61
+ The SDK includes ready-to-use tools — filesystem, shell, web and interaction:
62
+
63
+ ```typescript
64
+ import { Agent, builtinTools } from 'agentx-sdk';
65
+
66
+ const agent = Agent.create({ apiKey: '...' });
67
+
68
+ // Register all (except askUser which needs a callback)
69
+ builtinTools.all().forEach(t => agent.addTool(t));
70
+
71
+ // Or register individually
72
+ agent.addTool(builtinTools.fileRead());
73
+ agent.addTool(builtinTools.fileWrite());
74
+ agent.addTool(builtinTools.fileEdit());
75
+ agent.addTool(builtinTools.glob());
76
+ agent.addTool(builtinTools.grep());
77
+ agent.addTool(builtinTools.bash());
78
+ agent.addTool(builtinTools.webFetch());
79
+
80
+ // askUser needs a callback — you implement the interaction
81
+ agent.addTool(builtinTools.askUser({
82
+ onAsk: async (question, options) => {
83
+ // Your logic (readline, UI, API, etc.)
84
+ return readline.question(question);
85
+ },
86
+ }));
87
+
88
+ // Shortcut: file ops only (read + write + edit + glob + grep)
89
+ builtinTools.fileOps().forEach(t => agent.addTool(t));
90
+ ```
91
+
92
+ | Tool | Name | Description |
93
+ |------|------|-------------|
94
+ | `builtinTools.fileRead()` | Read | Read files with line numbers and offset/limit |
95
+ | `builtinTools.fileWrite()` | Write | Write/create files (creates dirs automatically) |
96
+ | `builtinTools.fileEdit()` | Edit | Exact find/replace in files |
97
+ | `builtinTools.glob()` | Glob | Search files by pattern (`**/*.ts`) |
98
+ | `builtinTools.grep()` | Grep | Search content via regex in files |
99
+ | `builtinTools.bash()` | Bash | Execute shell commands with timeout |
100
+ | `builtinTools.webFetch()` | WebFetch | Fetch content from URL (HTML → text) |
101
+ | `builtinTools.askUser()` | AskUser | Ask the user a question (callback pattern) |
102
+
103
+ ## Skills
104
+
105
+ Skills are modular behaviors that modify the agent when activated. Unlike tools (which the LLM calls to obtain data), skills **inject instructions into the context** to guide LLM behavior.
106
+
107
+ ### Programmatic skill
108
+
109
+ ```typescript
110
+ agent.addSkill({
111
+ name: 'code-review',
112
+ description: 'Reviews code for quality and bugs',
113
+ instructions: `You are in code review mode.
114
+ Analyze for bugs, security issues, and performance.
115
+ Rate quality from 1-10.`,
116
+ triggerPrefix: '/review',
117
+ });
118
+
119
+ await agent.chat('/review function add(a, b) { return a + b; }');
120
+ ```
121
+
122
+ ### Skill with arguments
123
+
124
+ ```typescript
125
+ agent.addSkill({
126
+ name: 'translate',
127
+ description: 'Translates text to a target language',
128
+ instructions: 'Translate the following to $lang: $ARGS',
129
+ argNames: ['lang'],
130
+ triggerPrefix: '/translate',
131
+ });
132
+
133
+ // $lang = "pt", $ARGS = "Hello world"
134
+ await agent.chat('/translate pt Hello world');
135
+ ```
136
+
137
+ ### Skill with dynamic prompt
138
+
139
+ ```typescript
140
+ agent.addSkill({
141
+ name: 'explain',
142
+ description: 'Explains code at different levels',
143
+ instructions: '',
144
+ triggerPrefix: '/explain',
145
+ argNames: ['level'],
146
+ getPrompt: async (args, ctx) => {
147
+ const level = args.split(' ')[0] || 'intermediate';
148
+ return `Explain for a ${level} developer. Thread: ${ctx.threadId}`;
149
+ },
150
+ });
151
+
152
+ await agent.chat('/explain beginner What is a closure?');
153
+ ```
154
+
155
+ ### Skill with its own tools
156
+
157
+ Tools registered in the skill are activated **only when the skill is active** and removed at the end of the turn.
158
+
159
+ ```typescript
160
+ agent.addSkill({
161
+ name: 'file-manager',
162
+ description: 'File management operations',
163
+ instructions: 'You can read files using the read_file tool.',
164
+ triggerPrefix: '/files',
165
+ tools: [
166
+ {
167
+ name: 'read_file',
168
+ description: 'Read a file from disk',
169
+ parameters: z.object({ path: z.string() }),
170
+ execute: async ({ path }) => {
171
+ const fs = await import('fs/promises');
172
+ return fs.readFile(path as string, 'utf-8');
173
+ },
174
+ },
175
+ ],
176
+ });
177
+ ```
178
+
179
+ ### Skill with model discovery (whenToUse)
180
+
181
+ Skills with `whenToUse` are listed in the model context so it can proactively suggest them.
182
+
183
+ ```typescript
184
+ agent.addSkill({
185
+ name: 'deploy',
186
+ description: 'Deploy to production',
187
+ whenToUse: 'When user mentions deploy, release, ship, or push to prod',
188
+ instructions: 'Guide the user through deployment steps...',
189
+ // No triggerPrefix — activates via semantic matching or model suggestion
190
+ });
191
+ ```
192
+
193
+ ### Skill via SKILL.md file
194
+
195
+ Create markdown files with YAML frontmatter in a directory:
196
+
197
+ ```
198
+ .skills/
199
+ code-review/
200
+ SKILL.md
201
+ translate/
202
+ SKILL.md
203
+ ```
204
+
205
+ **`.skills/code-review/SKILL.md`:**
206
+
207
+ ```markdown
208
+ ---
209
+ name: code-review
210
+ description: Reviews code for quality and bugs
211
+ whenToUse: When user asks to review, audit, or check code quality
212
+ triggerPrefix: /review
213
+ aliases: [cr, audit]
214
+ argNames: [file]
215
+ allowedTools: [Read, Grep]
216
+ priority: 8
217
+ ---
218
+
219
+ You are in code review mode.
220
+ Review $file for bugs, security issues, and performance.
221
+ Skill directory: ${SKILL_DIR}
222
+ ```
223
+
224
+ **Loading:**
225
+
226
+ ```typescript
227
+ // Via config (auto-load in constructor)
228
+ const agent = Agent.create({
229
+ apiKey: '...',
230
+ skills: { skillsDir: './.skills' },
231
+ });
232
+
233
+ // Or manually
234
+ await agent.loadSkillsDir('./.skills');
235
+ ```
236
+
237
+ ### Conditional skill (path-activated)
238
+
239
+ Skills with `paths` remain inactive until a matching file is touched.
240
+
241
+ ```typescript
242
+ agent.addSkill({
243
+ name: 'ts-linter',
244
+ description: 'TypeScript linting rules',
245
+ instructions: 'Apply strict TypeScript linting...',
246
+ paths: ['src/**/*.ts', 'tests/**/*.ts'],
247
+ match: () => true,
248
+ });
249
+
250
+ // Activates when a file is touched
251
+ agent.activateSkillsForPaths(['src/agent.ts']);
252
+ ```
253
+
254
+ ### Exclusive skill
255
+
256
+ ```typescript
257
+ agent.addSkill({
258
+ name: 'focus-mode',
259
+ description: 'Deep focus on a single task',
260
+ instructions: 'Focus exclusively on the current task.',
261
+ triggerPrefix: '/focus',
262
+ exclusive: true, // blocks all other skills
263
+ });
264
+ ```
265
+
266
+ ### Frontmatter reference (SKILL.md)
267
+
268
+ | Field | Type | Description |
269
+ |-------|------|-------------|
270
+ | `name` | string | Unique skill name |
271
+ | `description` | string | Short description |
272
+ | `whenToUse` | string | Usage scenarios (for model discovery) |
273
+ | `triggerPrefix` | string | Activation prefix (e.g. `/review`) |
274
+ | `aliases` | string[] | Alternative names |
275
+ | `argNames` | string[] | Argument names for substitution |
276
+ | `allowedTools` | string[] | Tools the skill can use |
277
+ | `model` | string | Model override |
278
+ | `context` | `inline` \| `fork` | Execution mode |
279
+ | `paths` | string[] | Globs for conditional activation |
280
+ | `effort` | number | Computational effort hint (1-10) |
281
+ | `exclusive` | boolean | Blocks other skills |
282
+ | `priority` | number | Priority (higher wins) |
283
+ | `modelInvocable` | boolean | Whether the model can invoke (default: true) |
284
+
285
+ ### Skills API
286
+
287
+ ```typescript
288
+ agent.addSkill(skill) // register
289
+ agent.removeSkill('name') // remove
290
+ agent.listSkills() // list
291
+ await agent.loadSkillsDir('./skills') // load from directory
292
+ agent.activateSkillsForPaths(['file.ts']) // activate conditionals
293
+ ```
294
+
295
+ ### Matching hierarchy
296
+
297
+ Skills are evaluated at 4 levels (most specific first):
298
+
299
+ 1. **Prefix** — `input.startsWith(triggerPrefix)` (score 1.0)
300
+ 2. **Alias** — `input.startsWith(/alias)` (score 0.95)
301
+ 3. **Custom** — `skill.match(input)` returns true (score 0.8)
302
+ 4. **Semantic** — cosine similarity > 0.7 with `description + whenToUse` (requires EmbeddingService)
303
+
304
+ Maximum of 3 simultaneously active skills (configurable via `skills.maxActiveSkills`).
305
+
306
+ ## Memory
307
+
308
+ Persistent file-based memory system inspired by Claude Code.
309
+
310
+ ```typescript
311
+ // Save memory explicitly
312
+ await agent.remember('User prefers dark mode', 'user');
313
+
314
+ // Search relevant memories
315
+ const memories = await agent.recall('What are the user preferences?');
316
+
317
+ // Automatic extraction: after each turn, the agent extracts memories
318
+ // from the conversation in the background (fire-and-forget)
319
+ ```
320
+
321
+ Memories are `.md` files with YAML frontmatter in `.agentx/memory/` (configurable). Four types: `user`, `feedback`, `project`, `reference`.
322
+
323
+ ## Knowledge (RAG)
324
+
325
+ ```typescript
326
+ await agent.ingestKnowledge({
327
+ id: 'docs-api',
328
+ content: apiDocs,
329
+ metadata: { source: 'api-docs.md' },
330
+ });
331
+
332
+ // The agent automatically searches knowledge when relevant
333
+ await agent.chat('How do I authenticate with the API?');
334
+ ```
335
+
336
+ ## MCP (Model Context Protocol)
337
+
338
+ Connect to any MCP server to extend agent capabilities with external tools, resources and prompts.
339
+
340
+ ### Basic connection
341
+
342
+ ```typescript
343
+ await agent.connectMCP({
344
+ name: 'github',
345
+ transport: 'stdio',
346
+ command: 'npx',
347
+ args: ['-y', '@modelcontextprotocol/server-github'],
348
+ });
349
+
350
+ // Server tools are registered automatically (mcp__github__create_issue, etc.)
351
+ await agent.chat('List my open PRs');
352
+ await agent.disconnectMCP('github');
353
+ ```
354
+
355
+ ### Supported transports
356
+
357
+ ```typescript
358
+ // Stdio — local subprocess (Node, Python, Rust MCP servers)
359
+ await agent.connectMCP({
360
+ name: 'local-server',
361
+ transport: 'stdio',
362
+ command: 'npx',
363
+ args: ['-y', '@modelcontextprotocol/server-filesystem'],
364
+ });
365
+
366
+ // SSE — Server-Sent Events (long-lived connection)
367
+ await agent.connectMCP({
368
+ name: 'remote-sse',
369
+ transport: 'sse',
370
+ url: 'https://mcp.example.com/sse',
371
+ headers: { 'Authorization': 'Bearer sk-...' },
372
+ });
373
+
374
+ // HTTP — Streamable HTTP (modern servers, bidirectional)
375
+ await agent.connectMCP({
376
+ name: 'remote-http',
377
+ transport: 'http',
378
+ url: 'https://mcp.example.com/v1',
379
+ headers: { 'Authorization': 'Bearer sk-...' },
380
+ });
381
+ ```
382
+
383
+ ### Automatic tool annotations
384
+
385
+ MCP servers that declare `readOnlyHint` or `destructiveHint` in tools are automatically mapped to AgentTool flags:
386
+
387
+ | MCP Annotation | AgentTool Flag | Effect |
388
+ |---|---|---|
389
+ | `readOnlyHint: true` | `isReadOnly: true` + `isConcurrencySafe: true` | Tools run in parallel, no warning |
390
+ | `destructiveHint: true` | `isDestructive: true` | Model receives caution warning |
391
+
392
+ ### Server instructions
393
+
394
+ If the MCP server returns `instructions` in the handshake, they are automatically injected into the model context — the agent follows the server's guidance.
395
+
396
+ ### MCP Prompts as Skills
397
+
398
+ Prompts that the MCP server offers via `prompts/list` are automatically registered as skills. The model can invoke them via SkillTool:
399
+
400
+ ```typescript
401
+ await agent.connectMCP({
402
+ name: 'docs',
403
+ transport: 'stdio',
404
+ command: 'npx',
405
+ args: ['my-docs-server'],
406
+ });
407
+
408
+ // If the server has a "summarize" prompt, it becomes a skill: mcp__docs__summarize
409
+ // The model can call: Skill({ skill: "mcp__docs__summarize", args: "..." })
410
+ ```
411
+
412
+ ### Resources
413
+
414
+ ```typescript
415
+ // List available resources from a server
416
+ const resources = await agent.mcpAdapter.listResources('github');
417
+ // [{ uri: 'repo://owner/project', name: 'Project', serverName: 'github' }]
418
+
419
+ // Read resource content
420
+ const content = await agent.mcpAdapter.readResource('github', 'repo://owner/project');
421
+ ```
422
+
423
+ ### Full configuration
424
+
425
+ ```typescript
426
+ await agent.connectMCP({
427
+ name: 'my-server',
428
+ transport: 'stdio', // 'stdio' | 'sse' | 'http'
429
+ command: 'npx', // for stdio
430
+ args: ['-y', 'my-mcp-server'],
431
+ // url: 'https://...', // for sse/http
432
+ // headers: { ... }, // for sse/http
433
+ timeout: 30_000, // timeout per tool call (ms)
434
+ maxRetries: 3, // reconnection attempts
435
+ healthCheckInterval: 60_000, // periodic health check (ms)
436
+ isolateErrors: true, // errors don't propagate (default: true)
437
+ });
438
+ ```
439
+
440
+ ### Health monitoring
441
+
442
+ ```typescript
443
+ const health = agent.getHealth();
444
+ // {
445
+ // servers: [{
446
+ // name: 'github',
447
+ // status: 'connected', // 'connected' | 'disconnected' | 'error' | 'reconnecting'
448
+ // toolCount: 15,
449
+ // uptime: 120000
450
+ // }]
451
+ // }
452
+ ```
453
+
454
+ ### Deep JSON Schema
455
+
456
+ MCP tools with complex schemas (nested objects, arrays, enums) are automatically converted to Zod — works with GitHub, Slack, and any server that uses rich schemas:
457
+
458
+ ```typescript
459
+ // This works automatically — nested schema converted to Zod
460
+ await agent.chat('Create a GitHub issue with labels bug and urgent');
461
+ // LLM calls: mcp__github__create_issue({
462
+ // owner: "user", repo: "project",
463
+ // title: "...", labels: ["bug", "urgent"]
464
+ // })
465
+ ```
466
+
467
+ ## Streaming Events
468
+
469
+ ```typescript
470
+ for await (const event of agent.stream('Build a TODO app')) {
471
+ switch (event.type) {
472
+ case 'agent_start': // Execution started
473
+ case 'skill_activated': // Skill activated (event.skillName)
474
+ case 'text_delta': // Text chunk (event.content)
475
+ case 'text_done': // Full text complete
476
+ case 'tool_call_start': // Tool called
477
+ case 'tool_call_end': // Tool result
478
+ case 'turn_start': // Loop iteration started
479
+ case 'turn_end': // Loop iteration ended
480
+ case 'agent_end': // Finished (event.usage, event.duration)
481
+ case 'error': // Error (event.recoverable)
482
+ case 'warning': // Warning
483
+ case 'compaction': // Context compacted
484
+ case 'recovery': // Automatic recovery
485
+ case 'model_fallback': // Model fallback
486
+ }
487
+ }
488
+ ```
489
+
490
+ ## Configuration
491
+
492
+ ```typescript
493
+ const agent = Agent.create({
494
+ apiKey: 'sk-...',
495
+ baseUrl: 'https://api.openai.com/v1', // optional — any OpenAI-compatible URL
496
+ model: 'gpt-4o',
497
+ systemPrompt: 'You are a helpful assistant.',
498
+
499
+ // Separate embedding provider (optional)
500
+ embedding: {
501
+ apiKey: 'sk-...',
502
+ baseUrl: 'https://api.openai.com/v1',
503
+ model: 'text-embedding-3-small',
504
+ },
505
+
506
+ // Skills
507
+ skills: {
508
+ skillsDir: './.skills', // Auto-load skills from directory
509
+ maxActiveSkills: 3, // Max simultaneous skills
510
+ modelDiscovery: true, // List skills for model context
511
+ },
512
+
513
+ // Memory
514
+ memory: {
515
+ enabled: true,
516
+ memoryDir: '.agentx/memory/',
517
+ extractionEnabled: true,
518
+ samplingRate: 0.3, // 30% chance per turn
519
+ extractionInterval: 10, // Force every 10 turns
520
+ },
521
+
522
+ // Knowledge
523
+ knowledge: {
524
+ enabled: true,
525
+ chunkSize: 512,
526
+ topK: 5,
527
+ minScore: 0.3,
528
+ },
529
+
530
+ // Behavior
531
+ maxIterations: 10,
532
+ onToolError: 'continue', // 'continue' | 'stop' | 'retry'
533
+
534
+ // Cost control
535
+ costPolicy: {
536
+ maxTokensPerExecution: 50_000,
537
+ onLimitReached: 'stop',
538
+ },
539
+
540
+ // Context
541
+ maxContextTokens: 128_000,
542
+ compactionThreshold: 0.8,
543
+
544
+ // Recovery
545
+ fallbackModel: 'anthropic/claude-haiku-4-5-20251001',
546
+ maxOutputTokens: 4096,
547
+ escalatedMaxOutputTokens: 16384,
548
+
549
+ // Observability
550
+ logLevel: 'info',
551
+ });
552
+ ```
553
+
554
+ ## Pluggable Stores
555
+
556
+ ```typescript
557
+ import { Agent } from 'agentx-sdk';
558
+
559
+ // Custom conversation store (e.g. PostgreSQL)
560
+ const agent = Agent.create({
561
+ apiKey: '...',
562
+ conversation: { store: myPostgresConversationStore },
563
+ knowledge: { store: myPineconeVectorStore },
564
+ });
565
+ ```
566
+
567
+ Interfaces: `ConversationStore`, `VectorStore` — implement to use any backend.
568
+
569
+ ## Stack
570
+
571
+ | Layer | Technology |
572
+ |-------|-----------|
573
+ | Language | TypeScript 5.x |
574
+ | Runtime | Node.js 22+ |
575
+ | Validation | Zod 3.x |
576
+ | Persistence | better-sqlite3 + SQLite |
577
+ | Tools schema | zod-to-json-schema |
578
+ | LLM | Any OpenAI-compatible API (native fetch) |
579
+
580
+ **<= 4 direct dependencies.** Zero AI frameworks. No vendor lock-in.
581
+
582
+ ## License
583
+
584
+ MIT
585
+
586
+ ---
587
+
588
+ <details>
589
+ <summary><h1>Portugues</h1></summary>
590
+
591
+ # AgentX SDK
592
+
3
593
  Biblioteca TypeScript para construir agentes conversacionais com LLM. Streaming-first, tools, memory, knowledge/RAG, skills e MCP — tudo in-process, sem frameworks.
4
594
 
5
595
  ```bash
@@ -11,7 +601,11 @@ npm install agentx-sdk
11
601
  ```typescript
12
602
  import { Agent } from 'agentx-sdk';
13
603
 
14
- const agent = Agent.create({ apiKey: process.env.OPENROUTER_API_KEY! });
604
+ // Funciona com qualquer API OpenAI-compatible (OpenRouter, OpenAI, Azure, Groq, etc.)
605
+ const agent = Agent.create({
606
+ apiKey: process.env.LLM_API_KEY!,
607
+ // baseUrl: 'https://api.openai.com/v1', // opcional — default: OpenRouter
608
+ });
15
609
 
16
610
  // Chat simples
17
611
  const response = await agent.chat('Qual a capital da Franca?');
@@ -248,7 +842,7 @@ agent.addSkill({
248
842
  });
249
843
  ```
250
844
 
251
- ### Frontmatter reference (SKILL.md)
845
+ ### Referencia de frontmatter (SKILL.md)
252
846
 
253
847
  | Campo | Tipo | Descricao |
254
848
  |-------|------|-----------|
@@ -267,7 +861,7 @@ agent.addSkill({
267
861
  | `priority` | number | Prioridade (maior vence) |
268
862
  | `modelInvocable` | boolean | Se o modelo pode invocar (default: true) |
269
863
 
270
- ### Skills API
864
+ ### API de Skills
271
865
 
272
866
  ```typescript
273
867
  agent.addSkill(skill) // registrar
@@ -277,7 +871,7 @@ await agent.loadSkillsDir('./skills') // carregar de diretorio
277
871
  agent.activateSkillsForPaths(['file.ts']) // ativar condicionais
278
872
  ```
279
873
 
280
- ### Matching hierarchy
874
+ ### Hierarquia de matching
281
875
 
282
876
  Skills sao avaliadas em 4 niveis (mais especifico primeiro):
283
877
 
@@ -303,7 +897,7 @@ const memories = await agent.recall('What are the user preferences?');
303
897
  // da conversa em background (fire-and-forget)
304
898
  ```
305
899
 
306
- Memorias sao arquivos `.md` com frontmatter YAML em `~/.agent/memory/` (configuravel). Quatro tipos: `user`, `feedback`, `project`, `reference`.
900
+ Memorias sao arquivos `.md` com frontmatter YAML em `.agentx/memory/` (configuravel). Quatro tipos: `user`, `feedback`, `project`, `reference`.
307
901
 
308
902
  ## Knowledge (RAG)
309
903
 
@@ -348,7 +942,7 @@ await agent.connectMCP({
348
942
  args: ['-y', '@modelcontextprotocol/server-filesystem'],
349
943
  });
350
944
 
351
- // SSE — Server-Sent Events (long-lived connection)
945
+ // SSE — Server-Sent Events (conexao persistente)
352
946
  await agent.connectMCP({
353
947
  name: 'remote-sse',
354
948
  transport: 'sse',
@@ -356,7 +950,7 @@ await agent.connectMCP({
356
950
  headers: { 'Authorization': 'Bearer sk-...' },
357
951
  });
358
952
 
359
- // HTTP — Streamable HTTP (servers modernos, bidirectional)
953
+ // HTTP — Streamable HTTP (servers modernos, bidirecional)
360
954
  await agent.connectMCP({
361
955
  name: 'remote-http',
362
956
  transport: 'http',
@@ -365,16 +959,16 @@ await agent.connectMCP({
365
959
  });
366
960
  ```
367
961
 
368
- ### Tool annotations automaticas
962
+ ### Anotacoes automaticas de tools
369
963
 
370
964
  MCP servers que declaram `readOnlyHint` ou `destructiveHint` nas tools sao mapeados automaticamente para os flags do AgentTool:
371
965
 
372
- | MCP Annotation | AgentTool Flag | Efeito |
966
+ | Anotacao MCP | Flag AgentTool | Efeito |
373
967
  |---|---|---|
374
968
  | `readOnlyHint: true` | `isReadOnly: true` + `isConcurrencySafe: true` | Tools executam em paralelo, sem warning |
375
969
  | `destructiveHint: true` | `isDestructive: true` | Modelo recebe aviso de cautela |
376
970
 
377
- ### Server instructions
971
+ ### Instrucoes do server
378
972
 
379
973
  Se o MCP server retorna `instructions` no handshake, elas sao injetadas automaticamente no contexto do modelo — o agente segue as orientacoes do server.
380
974
 
@@ -422,7 +1016,7 @@ await agent.connectMCP({
422
1016
  });
423
1017
  ```
424
1018
 
425
- ### Health monitoring
1019
+ ### Monitoramento de saude
426
1020
 
427
1021
  ```typescript
428
1022
  const health = agent.getHealth();
@@ -472,28 +1066,36 @@ for await (const event of agent.stream('Build a TODO app')) {
472
1066
  }
473
1067
  ```
474
1068
 
475
- ## Configuration
1069
+ ## Configuracao
476
1070
 
477
1071
  ```typescript
478
1072
  const agent = Agent.create({
479
1073
  apiKey: 'sk-...',
480
- model: 'anthropic/claude-sonnet-4-20250514',
1074
+ baseUrl: 'https://api.openai.com/v1', // optional — any OpenAI-compatible URL
1075
+ model: 'gpt-4o',
481
1076
  systemPrompt: 'You are a helpful assistant.',
482
1077
 
1078
+ // Separate embedding provider (optional)
1079
+ embedding: {
1080
+ apiKey: 'sk-...',
1081
+ baseUrl: 'https://api.openai.com/v1',
1082
+ model: 'text-embedding-3-small',
1083
+ },
1084
+
483
1085
  // Skills
484
1086
  skills: {
485
- skillsDir: './.skills', // Auto-load skills from directory
486
- maxActiveSkills: 3, // Max simultaneous skills
487
- modelDiscovery: true, // List skills for model context
1087
+ skillsDir: './.skills', // Auto-load de skills do diretorio
1088
+ maxActiveSkills: 3, // Max skills simultaneas
1089
+ modelDiscovery: true, // Listar skills no contexto do modelo
488
1090
  },
489
1091
 
490
1092
  // Memory
491
1093
  memory: {
492
1094
  enabled: true,
493
- memoryDir: '~/.agent/memory/',
1095
+ memoryDir: '.agentx/memory/',
494
1096
  extractionEnabled: true,
495
- samplingRate: 0.3, // 30% chance per turn
496
- extractionInterval: 10, // Force every 10 turns
1097
+ samplingRate: 0.3, // 30% de chance por turn
1098
+ extractionInterval: 10, // Forcar a cada 10 turns
497
1099
  },
498
1100
 
499
1101
  // Knowledge
@@ -504,17 +1106,17 @@ const agent = Agent.create({
504
1106
  minScore: 0.3,
505
1107
  },
506
1108
 
507
- // Behavior
1109
+ // Comportamento
508
1110
  maxIterations: 10,
509
1111
  onToolError: 'continue', // 'continue' | 'stop' | 'retry'
510
1112
 
511
- // Cost control
1113
+ // Controle de custo
512
1114
  costPolicy: {
513
1115
  maxTokensPerExecution: 50_000,
514
1116
  onLimitReached: 'stop',
515
1117
  },
516
1118
 
517
- // Context
1119
+ // Contexto
518
1120
  maxContextTokens: 128_000,
519
1121
  compactionThreshold: 0.8,
520
1122
 
@@ -523,7 +1125,7 @@ const agent = Agent.create({
523
1125
  maxOutputTokens: 4096,
524
1126
  escalatedMaxOutputTokens: 16384,
525
1127
 
526
- // Observability
1128
+ // Observabilidade
527
1129
  logLevel: 'info',
528
1130
  });
529
1131
  ```
@@ -552,10 +1154,12 @@ Interfaces: `ConversationStore`, `VectorStore` — implemente para usar qualquer
552
1154
  | Validacao | Zod 3.x |
553
1155
  | Persistencia | better-sqlite3 + SQLite |
554
1156
  | Tools schema | zod-to-json-schema |
555
- | LLM | OpenRouter (fetch nativo) |
1157
+ | LLM | Qualquer API OpenAI-compatible (fetch nativo) |
556
1158
 
557
- **<= 4 dependencias diretas.** Zero frameworks de IA.
1159
+ **<= 4 dependencias diretas.** Zero frameworks de IA. Sem vendor lock-in.
558
1160
 
559
1161
  ## License
560
1162
 
561
1163
  MIT
1164
+
1165
+ </details>