@agi-cli/sdk 0.1.26

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 (48) hide show
  1. package/README.md +675 -0
  2. package/package.json +73 -0
  3. package/src/agent/types.ts +19 -0
  4. package/src/errors.ts +102 -0
  5. package/src/index.ts +109 -0
  6. package/src/providers/resolver.ts +84 -0
  7. package/src/streaming/artifacts.ts +41 -0
  8. package/src/tools/builtin/bash.ts +73 -0
  9. package/src/tools/builtin/bash.txt +7 -0
  10. package/src/tools/builtin/edit.ts +145 -0
  11. package/src/tools/builtin/edit.txt +7 -0
  12. package/src/tools/builtin/fileCache.ts +39 -0
  13. package/src/tools/builtin/finish.ts +13 -0
  14. package/src/tools/builtin/finish.txt +5 -0
  15. package/src/tools/builtin/fs/cd.ts +19 -0
  16. package/src/tools/builtin/fs/cd.txt +5 -0
  17. package/src/tools/builtin/fs/index.ts +20 -0
  18. package/src/tools/builtin/fs/ls.ts +57 -0
  19. package/src/tools/builtin/fs/ls.txt +8 -0
  20. package/src/tools/builtin/fs/pwd.ts +17 -0
  21. package/src/tools/builtin/fs/pwd.txt +5 -0
  22. package/src/tools/builtin/fs/read.ts +49 -0
  23. package/src/tools/builtin/fs/read.txt +8 -0
  24. package/src/tools/builtin/fs/tree.ts +67 -0
  25. package/src/tools/builtin/fs/tree.txt +8 -0
  26. package/src/tools/builtin/fs/util.ts +95 -0
  27. package/src/tools/builtin/fs/write.ts +61 -0
  28. package/src/tools/builtin/fs/write.txt +8 -0
  29. package/src/tools/builtin/git.commit.txt +6 -0
  30. package/src/tools/builtin/git.diff.txt +5 -0
  31. package/src/tools/builtin/git.status.txt +5 -0
  32. package/src/tools/builtin/git.ts +96 -0
  33. package/src/tools/builtin/glob.ts +82 -0
  34. package/src/tools/builtin/glob.txt +8 -0
  35. package/src/tools/builtin/grep.ts +138 -0
  36. package/src/tools/builtin/grep.txt +9 -0
  37. package/src/tools/builtin/ignore.ts +45 -0
  38. package/src/tools/builtin/patch.ts +273 -0
  39. package/src/tools/builtin/patch.txt +7 -0
  40. package/src/tools/builtin/plan.ts +58 -0
  41. package/src/tools/builtin/plan.txt +6 -0
  42. package/src/tools/builtin/progress.ts +55 -0
  43. package/src/tools/builtin/progress.txt +7 -0
  44. package/src/tools/builtin/ripgrep.ts +71 -0
  45. package/src/tools/builtin/ripgrep.txt +7 -0
  46. package/src/tools/loader.ts +383 -0
  47. package/src/types/index.ts +11 -0
  48. package/src/types/types.ts +4 -0
package/README.md ADDED
@@ -0,0 +1,675 @@
1
+ # @agi-cli/sdk
2
+
3
+ **Batteries-included AI agent SDK.** Build AI assistants with tools, streaming, and multi-provider support in minutes.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @agi-cli/sdk
9
+ # or
10
+ bun add @agi-cli/sdk
11
+ ```
12
+
13
+ **That's it. No need to install `ai`, `@ai-sdk/anthropic`, `hono`, or anything else.** Everything is included.
14
+
15
+ ---
16
+
17
+ ## Quick Start
18
+
19
+ ### 1. Simple AI Call
20
+
21
+ ```typescript
22
+ import { generateText, resolveModel } from '@agi-cli/sdk';
23
+
24
+ const model = await resolveModel('anthropic', 'claude-sonnet-4');
25
+
26
+ const result = await generateText({
27
+ model,
28
+ prompt: 'Explain quantum computing in one sentence'
29
+ });
30
+
31
+ console.log(result.text);
32
+ ```
33
+
34
+ ### 2. AI Agent with Tools
35
+
36
+ ```typescript
37
+ import { generateText, resolveModel, discoverProjectTools } from '@agi-cli/sdk';
38
+
39
+ const model = await resolveModel('anthropic', 'claude-sonnet-4');
40
+ const tools = await discoverProjectTools(process.cwd());
41
+
42
+ const result = await generateText({
43
+ model,
44
+ prompt: 'List all TypeScript files and count total lines',
45
+ tools: Object.fromEntries(tools.map(t => [t.name, t.tool])),
46
+ maxSteps: 10
47
+ });
48
+
49
+ console.log(result.text);
50
+ ```
51
+
52
+ **That's it!** Your agent now has access to:
53
+ - File operations (read, write, edit, ls, tree)
54
+ - Code search (glob, grep, ripgrep)
55
+ - Git operations (status, diff, commit, log)
56
+ - Shell execution (bash)
57
+ - And more...
58
+
59
+ ### 3. HTTP Server
60
+
61
+ ```typescript
62
+ import { createServer } from '@agi-cli/sdk';
63
+
64
+ const app = createServer();
65
+
66
+ // Start server
67
+ export default {
68
+ port: 3000,
69
+ fetch: app.fetch
70
+ };
71
+ ```
72
+
73
+ Run it:
74
+ ```bash
75
+ bun run server.ts
76
+ ```
77
+
78
+ Your agent is now available at `http://localhost:3000` with:
79
+ - `POST /ask` - Ask questions
80
+ - `GET /sessions` - List sessions
81
+ - `GET /openapi.json` - OpenAPI spec
82
+ - And more...
83
+
84
+ ---
85
+
86
+ ## Complete Examples
87
+
88
+ ### Example 1: Code Review Bot
89
+
90
+ ```typescript
91
+ import { generateText, resolveModel, discoverProjectTools } from '@agi-cli/sdk';
92
+
93
+ async function reviewFile(filePath: string) {
94
+ const model = await resolveModel('anthropic', 'claude-sonnet-4');
95
+ const tools = await discoverProjectTools(process.cwd());
96
+
97
+ const result = await generateText({
98
+ model,
99
+ prompt: `Review ${filePath} for code quality, security, and best practices. Provide specific suggestions.`,
100
+ tools: Object.fromEntries(tools.map(t => [t.name, t.tool])),
101
+ maxSteps: 10
102
+ });
103
+
104
+ return result.text;
105
+ }
106
+
107
+ // Usage
108
+ const review = await reviewFile('src/auth.ts');
109
+ console.log(review);
110
+ ```
111
+
112
+ ### Example 2: Interactive Agent
113
+
114
+ ```typescript
115
+ import { generateText, resolveModel, discoverProjectTools } from '@agi-cli/sdk';
116
+
117
+ async function interactiveAgent() {
118
+ const model = await resolveModel('openai', 'gpt-4o');
119
+ const tools = await discoverProjectTools(process.cwd());
120
+ const toolMap = Object.fromEntries(tools.map(t => [t.name, t.tool]));
121
+
122
+ const messages = [];
123
+
124
+ while (true) {
125
+ const userInput = prompt('You: ');
126
+ if (userInput === 'exit') break;
127
+
128
+ messages.push({ role: 'user', content: userInput });
129
+
130
+ const result = await generateText({
131
+ model,
132
+ messages,
133
+ tools: toolMap,
134
+ maxSteps: 15
135
+ });
136
+
137
+ console.log('Agent:', result.text);
138
+ messages.push({ role: 'assistant', content: result.text });
139
+ }
140
+ }
141
+
142
+ interactiveAgent();
143
+ ```
144
+
145
+ ### Example 3: Streaming Responses
146
+
147
+ ```typescript
148
+ import { streamText, resolveModel, discoverProjectTools } from '@agi-cli/sdk';
149
+
150
+ async function streamingAgent(prompt: string) {
151
+ const model = await resolveModel('google', 'gemini-1.5-pro');
152
+ const tools = await discoverProjectTools(process.cwd());
153
+
154
+ const stream = streamText({
155
+ model,
156
+ prompt,
157
+ tools: Object.fromEntries(tools.map(t => [t.name, t.tool])),
158
+ maxSteps: 10
159
+ });
160
+
161
+ // Stream to console
162
+ for await (const chunk of stream.textStream) {
163
+ process.stdout.write(chunk);
164
+ }
165
+ }
166
+
167
+ streamingAgent('Refactor the authentication module for better security');
168
+ ```
169
+
170
+ ### Example 4: Custom Tool
171
+
172
+ ```typescript
173
+ import { generateText, resolveModel, discoverProjectTools, tool, z } from '@agi-cli/sdk';
174
+
175
+ // Define custom tool
176
+ const weatherTool = tool({
177
+ description: 'Get weather for a city',
178
+ parameters: z.object({
179
+ city: z.string(),
180
+ units: z.enum(['celsius', 'fahrenheit']).default('celsius')
181
+ }),
182
+ execute: async ({ city, units }) => {
183
+ const data = await fetch(`https://api.weather.com/${city}`).then(r => r.json());
184
+ return { temperature: data.temp, city, units };
185
+ }
186
+ });
187
+
188
+ // Use with agent
189
+ const model = await resolveModel('anthropic', 'claude-sonnet-4');
190
+ const builtinTools = await discoverProjectTools(process.cwd());
191
+
192
+ const result = await generateText({
193
+ model,
194
+ prompt: 'What\'s the weather in Tokyo and New York?',
195
+ tools: {
196
+ ...Object.fromEntries(builtinTools.map(t => [t.name, t.tool])),
197
+ weather: weatherTool
198
+ },
199
+ maxSteps: 5
200
+ });
201
+
202
+ console.log(result.text);
203
+ ```
204
+
205
+ ### Example 5: HTTP API Server
206
+
207
+ ```typescript
208
+ import { createServer, generateText, resolveModel, discoverProjectTools } from '@agi-cli/sdk';
209
+
210
+ const app = createServer();
211
+
212
+ // Add custom route
213
+ app.post('/custom-ask', async (c) => {
214
+ const { prompt } = await c.req.json();
215
+
216
+ const model = await resolveModel('anthropic', 'claude-sonnet-4');
217
+ const tools = await discoverProjectTools(process.cwd());
218
+
219
+ const result = await generateText({
220
+ model,
221
+ prompt,
222
+ tools: Object.fromEntries(tools.map(t => [t.name, t.tool])),
223
+ maxSteps: 10
224
+ });
225
+
226
+ return c.json({ response: result.text });
227
+ });
228
+
229
+ export default {
230
+ port: 3000,
231
+ fetch: app.fetch
232
+ };
233
+ ```
234
+
235
+ ---
236
+
237
+ ## Built-in Tools (15+)
238
+
239
+ Your agent has access to these tools automatically:
240
+
241
+ ### File Operations
242
+ - `read` - Read file contents
243
+ - `write` - Write to files
244
+ - `edit` - Edit files with diff-based changes
245
+ - `ls` - List directory contents
246
+ - `cd` - Change directory
247
+ - `pwd` - Print working directory
248
+ - `tree` - Show directory tree
249
+
250
+ ### Search & Find
251
+ - `glob` - Find files by pattern (e.g., `*.ts`)
252
+ - `grep` - Search file contents
253
+ - `ripgrep` - Fast content search (if installed)
254
+
255
+ ### Git Operations
256
+ - `git_status` - Show git status
257
+ - `git_diff` - Show git diff
258
+ - `git_commit` - Create commit
259
+ - `git_log` - Show git log
260
+
261
+ ### Execution
262
+ - `bash` - Run shell commands
263
+
264
+ ### Planning
265
+ - `update_plan` - Update task plan
266
+ - `progress_update` - Report progress
267
+ - `finish` - Mark task complete
268
+
269
+ ---
270
+
271
+ ## Supported Providers
272
+
273
+ Switch providers without changing code:
274
+
275
+ ```typescript
276
+ // OpenAI
277
+ const model = await resolveModel('openai', 'gpt-4o-mini');
278
+
279
+ // Anthropic
280
+ const model = await resolveModel('anthropic', 'claude-sonnet-4');
281
+
282
+ // Google
283
+ const model = await resolveModel('google', 'gemini-1.5-pro');
284
+
285
+ // OpenRouter (100+ models)
286
+ const model = await resolveModel('openrouter', 'anthropic/claude-3.5-sonnet');
287
+
288
+ // OpenCode (specialized code models)
289
+ const model = await resolveModel('opencode', 'qwen3-coder-14b');
290
+ ```
291
+
292
+ Set API keys via environment variables:
293
+ ```bash
294
+ export OPENAI_API_KEY=sk-...
295
+ export ANTHROPIC_API_KEY=sk-ant-...
296
+ export GOOGLE_GENERATIVE_AI_API_KEY=...
297
+ ```
298
+
299
+ Or pass directly:
300
+ ```typescript
301
+ const model = await resolveModel('openai', 'gpt-4o', {
302
+ apiKey: 'sk-...'
303
+ });
304
+ ```
305
+
306
+ ---
307
+
308
+ ## Configuration
309
+
310
+ The SDK integrates with AGI's configuration system:
311
+
312
+ ```typescript
313
+ import { loadConfig, readConfig } from '@agi-cli/sdk';
314
+
315
+ // Load config from .agi/config.json
316
+ const config = await loadConfig(process.cwd());
317
+
318
+ console.log(config.defaults);
319
+ // { agent: 'general', provider: 'anthropic', model: 'claude-sonnet-4' }
320
+
321
+ // Use configured defaults
322
+ const model = await resolveModel(
323
+ config.defaults.provider,
324
+ config.defaults.model
325
+ );
326
+ ```
327
+
328
+ ---
329
+
330
+ ## Custom Tools (Plugins)
331
+
332
+ Create reusable tools in `.agi/tools/{name}/tool.js`:
333
+
334
+ ```javascript
335
+ // .agi/tools/database/tool.js
336
+ export default {
337
+ name: 'query_database',
338
+ description: 'Query the database',
339
+ parameters: {
340
+ query: {
341
+ type: 'string',
342
+ description: 'SQL query to execute'
343
+ }
344
+ },
345
+ async execute({ input, exec, fs }) {
346
+ const result = await exec('sqlite3', ['db.sqlite', input.query]);
347
+ return {
348
+ success: true,
349
+ data: result.stdout
350
+ };
351
+ }
352
+ };
353
+ ```
354
+
355
+ Tools are auto-discovered by `discoverProjectTools()`.
356
+
357
+ **Available helpers in `execute()`:**
358
+ - `input` - Tool parameters
359
+ - `exec(cmd, args)` - Run shell commands
360
+ - `fs.readFile(path)` - Read files
361
+ - `fs.writeFile(path, content)` - Write files
362
+ - `fs.exists(path)` - Check file exists
363
+ - `project` / `projectRoot` / `directory` - Path info
364
+ - `env` - Environment variables
365
+
366
+ ---
367
+
368
+ ## Database & Sessions
369
+
370
+ Store conversation history:
371
+
372
+ ```typescript
373
+ import { getDb, dbSchema } from '@agi-cli/sdk';
374
+
375
+ const db = await getDb(process.cwd());
376
+
377
+ // Query sessions
378
+ const sessions = await db.select().from(dbSchema.sessions).limit(10);
379
+
380
+ // Query messages
381
+ const messages = await db
382
+ .select()
383
+ .from(dbSchema.messages)
384
+ .where(eq(dbSchema.messages.sessionId, sessionId));
385
+ ```
386
+
387
+ ---
388
+
389
+ ## Authentication
390
+
391
+ Manage provider credentials:
392
+
393
+ ```typescript
394
+ import { getAllAuth, setAuth, getAuth } from '@agi-cli/sdk';
395
+
396
+ // Get all stored credentials
397
+ const auth = await getAllAuth();
398
+
399
+ // Set API key
400
+ await setAuth('openai', {
401
+ type: 'api',
402
+ key: 'sk-...'
403
+ });
404
+
405
+ // Get provider auth
406
+ const openaiAuth = await getAuth('openai');
407
+ ```
408
+
409
+ ---
410
+
411
+ ## What Can You Build?
412
+
413
+ 1. **AI-Powered CLIs** - Interactive command-line tools
414
+ 2. **Code Assistants** - Review, refactor, document code
415
+ 3. **Project Automation** - Smart build tools, deployment scripts
416
+ 4. **Development Bots** - Slack/Discord bots for codebases
417
+ 5. **Custom Agents** - Task-specific AI agents
418
+ 6. **IDE Extensions** - AI features for editors
419
+ 7. **API Services** - HTTP APIs with AI + tools
420
+ 8. **Desktop Apps** - Electron/Tauri apps with AI
421
+ 9. **Documentation Generators** - Auto-generate docs
422
+ 10. **Testing Tools** - AI-powered test generation
423
+
424
+ ---
425
+
426
+ ## API Reference
427
+
428
+ ### Core Functions
429
+
430
+ #### `generateText(options)`
431
+ Generate text with optional tools.
432
+
433
+ ```typescript
434
+ const result = await generateText({
435
+ model, // Model from resolveModel()
436
+ prompt: string, // Or use 'messages' for multi-turn
437
+ tools?: object, // Optional tools
438
+ maxSteps?: number, // Max tool calls (default: 1)
439
+ temperature?: number,
440
+ maxTokens?: number
441
+ });
442
+ ```
443
+
444
+ #### `streamText(options)`
445
+ Stream text generation.
446
+
447
+ ```typescript
448
+ const stream = streamText({
449
+ model,
450
+ prompt: string,
451
+ tools?: object,
452
+ maxSteps?: number
453
+ });
454
+
455
+ for await (const chunk of stream.textStream) {
456
+ console.log(chunk);
457
+ }
458
+ ```
459
+
460
+ #### `generateObject(options)`
461
+ Generate structured JSON.
462
+
463
+ ```typescript
464
+ const result = await generateObject({
465
+ model,
466
+ schema: z.object({ ... }),
467
+ prompt: string
468
+ });
469
+ ```
470
+
471
+ #### `streamObject(options)`
472
+ Stream structured JSON generation.
473
+
474
+ ---
475
+
476
+ ### Provider Functions
477
+
478
+ #### `resolveModel(provider, model, config?)`
479
+ Get model instance.
480
+
481
+ ```typescript
482
+ const model = await resolveModel(
483
+ 'anthropic', // Provider
484
+ 'claude-sonnet-4', // Model ID
485
+ { apiKey: '...' } // Optional config
486
+ );
487
+ ```
488
+
489
+ #### `catalog`
490
+ Provider/model catalog.
491
+
492
+ ```typescript
493
+ import { catalog } from '@agi-cli/sdk';
494
+
495
+ // List all providers
496
+ console.log(Object.keys(catalog));
497
+ // ['openai', 'anthropic', 'google', ...]
498
+
499
+ // List OpenAI models
500
+ console.log(catalog.openai.models.map(m => m.id));
501
+ ```
502
+
503
+ ---
504
+
505
+ ### Tool Functions
506
+
507
+ #### `discoverProjectTools(projectRoot, globalConfigDir?)`
508
+ Discover all available tools.
509
+
510
+ ```typescript
511
+ const tools = await discoverProjectTools(process.cwd());
512
+
513
+ // Convert to object for generateText()
514
+ const toolMap = Object.fromEntries(
515
+ tools.map(t => [t.name, t.tool])
516
+ );
517
+ ```
518
+
519
+ #### `tool(definition)`
520
+ Create custom tool.
521
+
522
+ ```typescript
523
+ import { tool, z } from '@agi-cli/sdk';
524
+
525
+ const myTool = tool({
526
+ description: 'Tool description',
527
+ parameters: z.object({ ... }),
528
+ execute: async (params) => { ... }
529
+ });
530
+ ```
531
+
532
+ ---
533
+
534
+ ### Server Functions
535
+
536
+ #### `createServer()`
537
+ Create HTTP server.
538
+
539
+ ```typescript
540
+ const app = createServer();
541
+
542
+ // The server includes:
543
+ // - POST /ask - Ask questions
544
+ // - GET /sessions - List sessions
545
+ // - GET /sessions/:id/messages - Get messages
546
+ // - GET /openapi.json - OpenAPI spec
547
+ ```
548
+
549
+ ---
550
+
551
+ ### Configuration Functions
552
+
553
+ #### `loadConfig(projectRoot?)`
554
+ Load AGI configuration.
555
+
556
+ ```typescript
557
+ const config = await loadConfig(process.cwd());
558
+ // Returns: { defaults, providers, paths }
559
+ ```
560
+
561
+ #### `readConfig(projectRoot?)`
562
+ Load config + auth.
563
+
564
+ ```typescript
565
+ const { cfg, auth } = await readConfig(process.cwd());
566
+ ```
567
+
568
+ ---
569
+
570
+ ### Database Functions
571
+
572
+ #### `getDb(projectRoot?)`
573
+ Get database instance.
574
+
575
+ ```typescript
576
+ const db = await getDb(process.cwd());
577
+
578
+ // Use with Drizzle ORM
579
+ import { dbSchema } from '@agi-cli/sdk';
580
+ const sessions = await db.select().from(dbSchema.sessions);
581
+ ```
582
+
583
+ ---
584
+
585
+ ## Types
586
+
587
+ All types are exported:
588
+
589
+ ```typescript
590
+ import type {
591
+ // AI SDK types
592
+ CoreMessage,
593
+ Tool,
594
+
595
+ // Provider types
596
+ ProviderName,
597
+ ProviderId,
598
+ ModelInfo,
599
+ ModelConfig,
600
+
601
+ // Tool types
602
+ DiscoveredTool,
603
+
604
+ // Config types
605
+ AGIConfig,
606
+ ProviderConfig,
607
+ Scope,
608
+
609
+ // Auth types
610
+ AuthInfo,
611
+ OAuth,
612
+
613
+ // Other types
614
+ ExecutionContext,
615
+ ToolResult,
616
+ Artifact,
617
+ FileDiffArtifact
618
+ } from '@agi-cli/sdk';
619
+ ```
620
+
621
+ ---
622
+
623
+ ## Environment Variables
624
+
625
+ ```bash
626
+ # Provider API Keys
627
+ OPENAI_API_KEY=sk-...
628
+ ANTHROPIC_API_KEY=sk-ant-...
629
+ GOOGLE_GENERATIVE_AI_API_KEY=...
630
+ OPENROUTER_API_KEY=...
631
+ OPENCODE_API_KEY=...
632
+
633
+ # Optional
634
+ AGI_DEBUG_TOOLS=1 # Debug tool loading
635
+ ```
636
+
637
+ ---
638
+
639
+ ## Why Use This SDK?
640
+
641
+ ### ✅ **Batteries Included**
642
+ Everything you need in one package. No need to install `ai`, provider packages, or anything else.
643
+
644
+ ### ✅ **Zero Configuration**
645
+ Works out of the box. Add config only if you need it.
646
+
647
+ ### ✅ **15+ Built-in Tools**
648
+ File operations, Git, search, bash - ready to use.
649
+
650
+ ### ✅ **Multi-Provider**
651
+ Switch between OpenAI, Anthropic, Google without code changes.
652
+
653
+ ### ✅ **HTTP Server Included**
654
+ Create API endpoints in seconds.
655
+
656
+ ### ✅ **Extensible**
657
+ Add custom tools easily with the plugin system.
658
+
659
+ ### ✅ **Type-Safe**
660
+ Full TypeScript support with exported types.
661
+
662
+ ---
663
+
664
+ ## License
665
+
666
+ MIT - see [LICENSE](../../LICENSE)
667
+
668
+ ---
669
+
670
+ ## Links
671
+
672
+ - [GitHub](https://github.com/ntishxyz/agi)
673
+ - [Documentation](https://github.com/ntishxyz/agi#readme)
674
+ - [Architecture](https://github.com/ntishxyz/agi/blob/main/ARCHITECTURE.md)
675
+ - [Issues](https://github.com/ntishxyz/agi/issues)