@yesvara/svara 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 (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +497 -0
  3. package/dist/chunk-CIESM3BP.mjs +33 -0
  4. package/dist/chunk-FEA5KIJN.mjs +418 -0
  5. package/dist/cli/index.d.mts +1 -0
  6. package/dist/cli/index.d.ts +1 -0
  7. package/dist/cli/index.js +328 -0
  8. package/dist/cli/index.mjs +39 -0
  9. package/dist/dev-OYGXXK2B.mjs +69 -0
  10. package/dist/index.d.mts +967 -0
  11. package/dist/index.d.ts +967 -0
  12. package/dist/index.js +1976 -0
  13. package/dist/index.mjs +1502 -0
  14. package/dist/new-7K4NIDZO.mjs +177 -0
  15. package/dist/retriever-4QY667XF.mjs +7 -0
  16. package/examples/01-basic/index.ts +26 -0
  17. package/examples/02-with-tools/index.ts +73 -0
  18. package/examples/03-rag-knowledge/index.ts +41 -0
  19. package/examples/04-multi-channel/index.ts +91 -0
  20. package/package.json +74 -0
  21. package/src/app/index.ts +176 -0
  22. package/src/channels/telegram.ts +122 -0
  23. package/src/channels/web.ts +118 -0
  24. package/src/channels/whatsapp.ts +161 -0
  25. package/src/cli/commands/dev.ts +87 -0
  26. package/src/cli/commands/new.ts +213 -0
  27. package/src/cli/index.ts +78 -0
  28. package/src/core/agent.ts +607 -0
  29. package/src/core/llm.ts +406 -0
  30. package/src/core/types.ts +183 -0
  31. package/src/database/schema.ts +79 -0
  32. package/src/database/sqlite.ts +239 -0
  33. package/src/index.ts +94 -0
  34. package/src/memory/context.ts +49 -0
  35. package/src/memory/conversation.ts +51 -0
  36. package/src/rag/chunker.ts +165 -0
  37. package/src/rag/loader.ts +216 -0
  38. package/src/rag/retriever.ts +248 -0
  39. package/src/tools/executor.ts +54 -0
  40. package/src/tools/index.ts +89 -0
  41. package/src/tools/registry.ts +44 -0
  42. package/src/types.ts +131 -0
  43. package/tsconfig.json +26 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yogiswara
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.
package/README.md ADDED
@@ -0,0 +1,497 @@
1
+ <div align="center">
2
+
3
+ # @yesvara/svara
4
+
5
+ **Build AI agents in 15 lines. Ship to production.**
6
+
7
+ A batteries-included Node.js framework for building agentic AI backends —
8
+ multi-channel, RAG-ready, and designed for developers who value simplicity.
9
+
10
+ [![npm version](https://img.shields.io/npm/v/@yesvara/svara?color=0ea5e9&label=npm)](https://www.npmjs.com/package/@yesvara/svara)
11
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](./LICENSE)
12
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen)](https://nodejs.org)
13
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue)](https://typescriptlang.org)
14
+
15
+ </div>
16
+
17
+ ---
18
+
19
+ ## Why SvaraJS?
20
+
21
+ Most AI frameworks make you think about infrastructure. SvaraJS makes you think about your agent.
22
+
23
+ ```ts
24
+ import { SvaraApp, SvaraAgent } from '@yesvara/svara';
25
+
26
+ const app = new SvaraApp();
27
+
28
+ const agent = new SvaraAgent({
29
+ name: 'Support Bot',
30
+ model: 'gpt-4o-mini', // provider auto-detected
31
+ knowledge: './docs', // PDF, MD, TXT — just point to a folder
32
+ });
33
+
34
+ app.route('/chat', agent.handler());
35
+ app.listen(3000);
36
+ // Done. Your agent handles 1000 conversations.
37
+ ```
38
+
39
+ That's it. No pipeline setup. No embedding boilerplate. No webhook configuration.
40
+ **Convention over configuration — like Express, but for AI.**
41
+
42
+ ---
43
+
44
+ ## Features
45
+
46
+ | | |
47
+ |---|---|
48
+ | **Zero-config LLM** | Pass a model name — provider is auto-detected |
49
+ | **Instant RAG** | Point to a folder, documents are indexed automatically |
50
+ | **Multi-channel** | WhatsApp, Telegram, and Web from one agent |
51
+ | **Tool calling** | Declarative tools with full TypeScript types |
52
+ | **Conversation memory** | Automatic per-session history, configurable window |
53
+ | **Express-compatible** | `agent.handler()` drops into any existing app |
54
+ | **Built-in database** | Zero-config SQLite for state, KV store, and history |
55
+ | **CLI included** | `svara new`, `svara dev`, `svara build` |
56
+
57
+ ---
58
+
59
+ ## Quick Start
60
+
61
+ ### 1. Install
62
+
63
+ ```bash
64
+ npm install @yesvara/svara
65
+ ```
66
+
67
+ ### 2. Set your API key
68
+
69
+ ```bash
70
+ # .env
71
+ OPENAI_API_KEY=sk-...
72
+ ```
73
+
74
+ ### 3. Create your agent
75
+
76
+ ```ts
77
+ // src/index.ts
78
+ import 'dotenv/config';
79
+ import { SvaraApp, SvaraAgent } from '@yesvara/svara';
80
+
81
+ const app = new SvaraApp({ cors: true });
82
+
83
+ const agent = new SvaraAgent({
84
+ name: 'Aria',
85
+ model: 'gpt-4o-mini',
86
+ systemPrompt: 'You are Aria, a helpful and friendly AI assistant.',
87
+ });
88
+
89
+ app.route('/chat', agent.handler());
90
+ app.listen(3000);
91
+ ```
92
+
93
+ ### 4. Run
94
+
95
+ ```bash
96
+ npx tsx src/index.ts
97
+ ```
98
+
99
+ ### 5. Chat
100
+
101
+ ```bash
102
+ curl -X POST http://localhost:3000/chat \
103
+ -H "Content-Type: application/json" \
104
+ -d '{ "message": "Hello! What can you do?", "sessionId": "user-1" }'
105
+ ```
106
+
107
+ ```json
108
+ {
109
+ "response": "Hi! I'm Aria, your AI assistant...",
110
+ "sessionId": "user-1",
111
+ "usage": { "totalTokens": 142 }
112
+ }
113
+ ```
114
+
115
+ ---
116
+
117
+ ## Supported Models
118
+
119
+ SvaraJS auto-detects the LLM provider from the model name. No extra config needed.
120
+
121
+ | Model string | Provider | Env key |
122
+ |---|---|---|
123
+ | `gpt-4o`, `gpt-4o-mini`, `gpt-4-turbo` | OpenAI | `OPENAI_API_KEY` |
124
+ | `claude-opus-4-6`, `claude-sonnet-4-6`, `claude-haiku-*` | Anthropic | `ANTHROPIC_API_KEY` |
125
+ | `llama3`, `mistral`, `gemma`, `phi3` | Ollama (local) | *(none)* |
126
+ | `llama-3.1-70b-versatile`, `mixtral-8x7b` | Groq | `GROQ_API_KEY` |
127
+
128
+ ```ts
129
+ // Switch models in one line — no other changes needed
130
+ const agent = new SvaraAgent({ name: 'Aria', model: 'claude-opus-4-6' });
131
+ const agent = new SvaraAgent({ name: 'Aria', model: 'llama3' }); // local
132
+ const agent = new SvaraAgent({ name: 'Aria', model: 'gpt-4o-mini' }); // cheap & fast
133
+ ```
134
+
135
+ ---
136
+
137
+ ## Core Concepts
138
+
139
+ ### SvaraAgent
140
+
141
+ The central class. Configure once, use everywhere.
142
+
143
+ ```ts
144
+ const agent = new SvaraAgent({
145
+ name: 'Support Bot', // Display name (used in logs & system prompt)
146
+ model: 'gpt-4o-mini', // LLM model — provider auto-detected
147
+ systemPrompt: 'You are...', // Optional — sensible default based on name
148
+ knowledge: './docs', // Optional — folder/glob for RAG
149
+ memory: { window: 20 }, // Optional — conversation history window
150
+ tools: [myTool], // Optional — functions the agent can call
151
+ temperature: 0.7, // Optional — creativity (0–2)
152
+ verbose: true, // Optional — detailed logs
153
+ });
154
+ ```
155
+
156
+ ### SvaraApp
157
+
158
+ A minimal HTTP server. Built on Express, zero config to start.
159
+
160
+ ```ts
161
+ const app = new SvaraApp({
162
+ cors: true, // Allow all origins (or pass a specific origin)
163
+ apiKey: 'secret-key', // Optional bearer token auth
164
+ });
165
+
166
+ app.route('/chat', agent.handler()); // Mount agent on a path
167
+ app.use(myMiddleware); // Add Express middleware
168
+ app.listen(3000);
169
+
170
+ // Access the raw Express app for advanced config
171
+ const expressApp = app.getExpressApp();
172
+ ```
173
+
174
+ ### Tools (`createTool`)
175
+
176
+ Give your agent superpowers. The LLM decides when to call each tool.
177
+
178
+ ```ts
179
+ import { createTool } from '@yesvara/svara';
180
+
181
+ const weatherTool = createTool({
182
+ name: 'get_weather',
183
+ description: 'Get current weather for a city. Use when the user asks about weather.',
184
+ parameters: {
185
+ city: { type: 'string', description: 'City name', required: true },
186
+ units: { type: 'string', description: 'celsius or fahrenheit', enum: ['celsius', 'fahrenheit'] },
187
+ },
188
+ async run({ city, units = 'celsius' }) {
189
+ const data = await fetchWeather(city as string);
190
+ return { temp: data.temp, condition: data.description };
191
+ },
192
+ });
193
+
194
+ agent.addTool(weatherTool);
195
+
196
+ // Chainable
197
+ agent
198
+ .addTool(weatherTool)
199
+ .addTool(emailTool)
200
+ .addTool(databaseTool);
201
+ ```
202
+
203
+ ### RAG (Knowledge Base)
204
+
205
+ Point to your documents. The agent reads them automatically.
206
+
207
+ ```ts
208
+ const agent = new SvaraAgent({
209
+ name: 'Support Bot',
210
+ model: 'gpt-4o-mini',
211
+ knowledge: './docs', // folder
212
+ // knowledge: './faqs.pdf', // single file
213
+ // knowledge: ['./docs', './policies/*.md'], // multiple globs
214
+ });
215
+
216
+ // Or add documents at runtime (hot reload, no restart)
217
+ await agent.addKnowledge('./new-policy-2024.pdf');
218
+ ```
219
+
220
+ Supported formats: **PDF, Markdown, TXT, DOCX, HTML, JSON**
221
+
222
+ ### Channels
223
+
224
+ One agent, multiple platforms.
225
+
226
+ ```ts
227
+ agent
228
+ .connectChannel('web', { port: 3000, cors: true })
229
+ .connectChannel('telegram', { token: process.env.TG_TOKEN })
230
+ .connectChannel('whatsapp', {
231
+ token: process.env.WA_TOKEN,
232
+ phoneId: process.env.WA_PHONE_ID,
233
+ verifyToken: process.env.WA_VERIFY_TOKEN,
234
+ });
235
+
236
+ await agent.start();
237
+ ```
238
+
239
+ ### Events
240
+
241
+ Hook into the agent lifecycle.
242
+
243
+ ```ts
244
+ agent.on('message:received', ({ message, sessionId }) => { /* log it */ });
245
+ agent.on('tool:call', ({ tools }) => { /* monitor usage */ });
246
+ agent.on('tool:result', ({ name, result }) => { /* cache results */ });
247
+ agent.on('message:sent', ({ response }) => { /* analytics */ });
248
+ agent.on('channel:ready', ({ channel }) => { /* notify */ });
249
+ ```
250
+
251
+ ---
252
+
253
+ ## Examples
254
+
255
+ ### Basic agent
256
+
257
+ ```ts
258
+ import { SvaraApp, SvaraAgent } from '@yesvara/svara';
259
+
260
+ const app = new SvaraApp({ cors: true });
261
+ const agent = new SvaraAgent({ name: 'Aria', model: 'gpt-4o-mini' });
262
+
263
+ app.route('/chat', agent.handler());
264
+ app.listen(3000);
265
+ ```
266
+
267
+ ### Agent with tools
268
+
269
+ ```ts
270
+ import { SvaraAgent, createTool } from '@yesvara/svara';
271
+
272
+ const agent = new SvaraAgent({ name: 'Aria', model: 'gpt-4o' });
273
+
274
+ agent.addTool(createTool({
275
+ name: 'get_time',
276
+ description: 'Get the current date and time',
277
+ parameters: {},
278
+ async run() {
279
+ return { time: new Date().toISOString() };
280
+ },
281
+ }));
282
+
283
+ const reply = await agent.chat('What time is it?');
284
+ console.log(reply); // "It's currently 14:32 UTC..."
285
+ ```
286
+
287
+ ### RAG-powered support bot
288
+
289
+ ```ts
290
+ const agent = new SvaraAgent({
291
+ name: 'Support Bot',
292
+ model: 'gpt-4o-mini',
293
+ knowledge: './docs',
294
+ systemPrompt: 'You are a customer support agent. Answer using the documentation.',
295
+ memory: { window: 20 },
296
+ });
297
+
298
+ await agent.start(); // indexes documents
299
+ ```
300
+
301
+ ### Multi-channel (Web + Telegram + WhatsApp)
302
+
303
+ ```ts
304
+ const agent = new SvaraAgent({
305
+ name: 'Aria',
306
+ model: 'gpt-4o-mini',
307
+ knowledge: './policies',
308
+ });
309
+
310
+ agent
311
+ .connectChannel('web', { port: 3000 })
312
+ .connectChannel('telegram', { token: process.env.TG_TOKEN })
313
+ .connectChannel('whatsapp', {
314
+ token: process.env.WA_TOKEN,
315
+ phoneId: process.env.WA_PHONE_ID,
316
+ verifyToken: process.env.WA_VERIFY_TOKEN,
317
+ });
318
+
319
+ await agent.start();
320
+ ```
321
+
322
+ ### Drop into an existing Express app
323
+
324
+ ```ts
325
+ import express from 'express';
326
+ import { SvaraAgent } from '@yesvara/svara';
327
+
328
+ const app = express();
329
+ app.use(express.json());
330
+
331
+ const agent = new SvaraAgent({ name: 'Aria', model: 'gpt-4o-mini' });
332
+
333
+ app.post('/api/chat', agent.handler()); // ← one line
334
+ app.listen(3000);
335
+ ```
336
+
337
+ ---
338
+
339
+ ## CLI
340
+
341
+ ```bash
342
+ # Scaffold a new project
343
+ svara new my-app
344
+
345
+ # Start dev server with hot-reload
346
+ svara dev
347
+
348
+ # Build for production
349
+ svara build
350
+ ```
351
+
352
+ ```
353
+ $ svara new my-app
354
+ ✨ Creating SvaraJS project: my-app
355
+
356
+ ✓ package.json
357
+ ✓ tsconfig.json
358
+ ✓ .env.example
359
+ ✓ src/index.ts
360
+ ✓ docs/README.md
361
+
362
+ 📦 Installing dependencies...
363
+
364
+ ✅ Project ready!
365
+
366
+ cd my-app
367
+ cp .env.example .env
368
+ npm run dev
369
+ ```
370
+
371
+ ---
372
+
373
+ ## Built-in Database
374
+
375
+ Zero-config SQLite for when you need persistent state.
376
+
377
+ ```ts
378
+ import { SvaraDB } from '@yesvara/svara';
379
+
380
+ const db = new SvaraDB('./data/agent.db');
381
+
382
+ // Simple queries
383
+ const users = db.query<User>('SELECT * FROM users WHERE active = ?', [1]);
384
+
385
+ // Key-value store
386
+ db.kv.set('feature:rag', true);
387
+ const enabled = db.kv.get<boolean>('feature:rag');
388
+
389
+ // Transactions
390
+ db.transaction(() => {
391
+ db.run('INSERT INTO orders ...', [...]);
392
+ db.run('UPDATE inventory ...', [...]);
393
+ });
394
+ ```
395
+
396
+ ---
397
+
398
+ ## Architecture
399
+
400
+ ```
401
+ @yesvara/svara/
402
+ ├── src/
403
+ │ ├── core/
404
+ │ │ ├── agent.ts # SvaraAgent — the main class
405
+ │ │ ├── llm.ts # LLM abstraction + provider auto-detection
406
+ │ │ └── types.ts # Internal types
407
+ │ ├── app/
408
+ │ │ └── index.ts # SvaraApp — HTTP framework wrapper
409
+ │ ├── channels/
410
+ │ │ ├── web.ts # REST API + SSE streaming
411
+ │ │ ├── telegram.ts # Telegram Bot API (polling + webhook)
412
+ │ │ └── whatsapp.ts # Meta WhatsApp Cloud API
413
+ │ ├── rag/
414
+ │ │ ├── loader.ts # Document loading (PDF, MD, DOCX, ...)
415
+ │ │ ├── chunker.ts # Chunking strategies (sentence, paragraph, fixed)
416
+ │ │ └── retriever.ts # Vector similarity search
417
+ │ ├── memory/
418
+ │ │ ├── conversation.ts # Per-session history with auto-trim
419
+ │ │ └── context.ts # LLM message builder + RAG injection
420
+ │ ├── tools/
421
+ │ │ ├── index.ts # createTool() helper
422
+ │ │ ├── registry.ts # Tool store
423
+ │ │ └── executor.ts # Concurrent execution with timeout protection
424
+ │ ├── database/
425
+ │ │ ├── sqlite.ts # SvaraDB wrapper (query, kv, transaction)
426
+ │ │ └── schema.ts # Internal SQLite schema
427
+ │ ├── cli/ # svara new / dev / build
428
+ │ ├── types.ts # Public types (exported to users)
429
+ │ └── index.ts # Public API surface
430
+ └── examples/
431
+ ├── 01-basic/ # 10-line agent
432
+ ├── 02-with-tools/ # createTool + events
433
+ ├── 03-rag-knowledge/ # Document Q&A
434
+ └── 04-multi-channel/ # Web + Telegram + WhatsApp
435
+ ```
436
+
437
+ ---
438
+
439
+ ## Web API Reference
440
+
441
+ When using `app.route('/chat', agent.handler())`:
442
+
443
+ **`POST /chat`**
444
+
445
+ Request:
446
+ ```json
447
+ {
448
+ "message": "What is the refund policy?",
449
+ "sessionId": "user-123",
450
+ "userId": "alice@example.com"
451
+ }
452
+ ```
453
+
454
+ Response:
455
+ ```json
456
+ {
457
+ "response": "Our refund policy allows returns within 30 days...",
458
+ "sessionId": "user-123",
459
+ "usage": {
460
+ "promptTokens": 312,
461
+ "completionTokens": 89,
462
+ "totalTokens": 401
463
+ },
464
+ "toolsUsed": []
465
+ }
466
+ ```
467
+
468
+ **`GET /health`** — always returns `{ "status": "ok" }`
469
+
470
+ ---
471
+
472
+ ## Contributing
473
+
474
+ Contributions are welcome! Please read [CONTRIBUTING.md](./CONTRIBUTING.md) first.
475
+
476
+ ```bash
477
+ git clone https://github.com/yesvara/svara
478
+ cd svara
479
+ npm install
480
+ npm run dev
481
+ ```
482
+
483
+ ---
484
+
485
+ ## License
486
+
487
+ MIT © [Yesvara](https://github.com/yogiswara92)
488
+
489
+ ---
490
+
491
+ <div align="center">
492
+
493
+ Built with ❤️ for developers who want to ship AI, not fight infrastructure.
494
+
495
+ **[Documentation](https://svarajs.yesvara.com)** · **[Examples](./examples)** · **[npm](https://npmjs.com/package/@yesvara/svara)**
496
+
497
+ </div>
@@ -0,0 +1,33 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
+ }) : x)(function(x) {
8
+ if (typeof require !== "undefined") return require.apply(this, arguments);
9
+ throw Error('Dynamic require of "' + x + '" is not supported');
10
+ });
11
+ var __esm = (fn, res) => function __init() {
12
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+
28
+ export {
29
+ __require,
30
+ __esm,
31
+ __export,
32
+ __toCommonJS
33
+ };