@agi-cli/sdk 0.1.50 → 0.1.51

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 (3) hide show
  1. package/README.md +237 -538
  2. package/package.json +6 -3
  3. package/src/index.ts +119 -17
package/README.md CHANGED
@@ -1,675 +1,374 @@
1
1
  # @agi-cli/sdk
2
2
 
3
- **Batteries-included AI agent SDK.** Build AI assistants with tools, streaming, and multi-provider support in minutes.
3
+ > **The single source of truth for AGI CLI functionality** - Comprehensive, tree-shakable, and developer-friendly.
4
+
5
+ ## Overview
6
+
7
+ `@agi-cli/sdk` is the unified SDK for building AI agents with AGI CLI. It re-exports all functionality from the underlying packages (`@agi-cli/core`, `@agi-cli/providers`, `@agi-cli/auth`, etc.) in a tree-shakable way.
8
+
9
+ **Why use the SDK?**
10
+ - ✅ **Single import**: All functionality from one package
11
+ - ✅ **Tree-shakable**: Bundlers only include what you use
12
+ - ✅ **Type-safe**: Full TypeScript support with comprehensive types
13
+ - ✅ **Zero circular dependencies**: Clean architecture
14
+ - ✅ **Consistent API**: No need to remember which package exports what
4
15
 
5
16
  ## Installation
6
17
 
7
18
  ```bash
8
- npm install @agi-cli/sdk
9
- # or
10
19
  bun add @agi-cli/sdk
11
20
  ```
12
21
 
13
- **That's it. No need to install `ai`, `@ai-sdk/anthropic`, `hono`, or anything else.** Everything is included.
14
-
15
- ---
16
-
17
22
  ## Quick Start
18
23
 
19
- ### 1. Simple AI Call
20
-
21
24
  ```typescript
22
25
  import { generateText, resolveModel } from '@agi-cli/sdk';
26
+ import type { ProviderId } from '@agi-cli/sdk';
23
27
 
24
- const model = await resolveModel('anthropic', 'claude-sonnet-4');
28
+ const model = resolveModel('anthropic', 'claude-3-5-sonnet-20241022');
25
29
 
26
- const result = await generateText({
30
+ const { text } = await generateText({
27
31
  model,
28
- prompt: 'Explain quantum computing in one sentence'
32
+ prompt: 'What is the meaning of life?',
29
33
  });
30
34
 
31
- console.log(result.text);
35
+ console.log(text);
32
36
  ```
33
37
 
34
- ### 2. AI Agent with Tools
38
+ ## What's Included?
35
39
 
36
- ```typescript
37
- import { generateText, resolveModel, discoverProjectTools } from '@agi-cli/sdk';
40
+ ### Types (from `@agi-cli/types`)
38
41
 
39
- const model = await resolveModel('anthropic', 'claude-sonnet-4');
40
- const tools = await discoverProjectTools(process.cwd());
42
+ All shared types are available:
41
43
 
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);
44
+ ```typescript
45
+ import type {
46
+ ProviderId,
47
+ ModelInfo,
48
+ AuthInfo,
49
+ AGIConfig,
50
+ ProviderConfig,
51
+ Scope
52
+ } from '@agi-cli/sdk';
50
53
  ```
51
54
 
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...
55
+ ### Providers (from `@agi-cli/providers`)
58
56
 
59
- ### 3. HTTP Server
57
+ Provider catalog and utilities:
60
58
 
61
59
  ```typescript
62
- import { createServer } from '@agi-cli/sdk';
60
+ import {
61
+ catalog,
62
+ isProviderId,
63
+ providerIds,
64
+ defaultModelFor,
65
+ hasModel,
66
+ isProviderAuthorized,
67
+ validateProviderModel,
68
+ estimateModelCostUsd,
69
+ providerEnvVar,
70
+ readEnvKey,
71
+ setEnvKey
72
+ } from '@agi-cli/sdk';
63
73
 
64
- const app = createServer();
74
+ // Check available providers
75
+ console.log(providerIds); // ['openai', 'anthropic', 'google', 'openrouter', 'opencode']
65
76
 
66
- // Start server
67
- export default {
68
- port: 3000,
69
- fetch: app.fetch
70
- };
71
- ```
77
+ // Get model information
78
+ const models = catalog.anthropic.models;
72
79
 
73
- Run it:
74
- ```bash
75
- bun run server.ts
80
+ // Validate provider/model combination
81
+ const result = validateProviderModel('anthropic', 'claude-3-5-sonnet-20241022');
76
82
  ```
77
83
 
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
- ---
84
+ ### Authentication (from `@agi-cli/auth`)
85
85
 
86
- ## Complete Examples
87
-
88
- ### Example 1: Code Review Bot
86
+ Manage API keys and OAuth:
89
87
 
90
88
  ```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
- ```
89
+ import {
90
+ getAuth,
91
+ setAuth,
92
+ removeAuth,
93
+ getAllAuth,
94
+ authorize,
95
+ createApiKey
96
+ } from '@agi-cli/sdk';
111
97
 
112
- ### Example 2: Interactive Agent
98
+ // Set API key
99
+ await setAuth('openai', { apiKey: 'sk-...' });
113
100
 
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
- }
101
+ // Get auth info
102
+ const auth = await getAuth('openai');
141
103
 
142
- interactiveAgent();
104
+ // OAuth flow
105
+ const url = await authorize('anthropic');
106
+ console.log(`Visit: ${url}`);
143
107
  ```
144
108
 
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
- ```
109
+ ### Configuration (from `@agi-cli/config`)
169
110
 
170
- ### Example 4: Custom Tool
111
+ Load and manage configuration:
171
112
 
172
113
  ```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
- });
114
+ import { loadConfig, readConfig } from '@agi-cli/sdk';
115
+ import type { AGIConfig } from '@agi-cli/sdk';
201
116
 
202
- console.log(result.text);
117
+ const config = await loadConfig();
118
+ console.log(config.provider); // 'anthropic'
119
+ console.log(config.model); // 'claude-3-5-sonnet-20241022'
203
120
  ```
204
121
 
205
- ### Example 5: HTTP API Server
122
+ ### Prompts (from `@agi-cli/prompts`)
206
123
 
207
- ```typescript
208
- import { createServer, generateText, resolveModel, discoverProjectTools } from '@agi-cli/sdk';
124
+ Pre-built system prompts:
209
125
 
210
- const app = createServer();
126
+ ```typescript
127
+ import { systemPrompt, codeContext } from '@agi-cli/sdk';
211
128
 
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 });
129
+ const prompt = systemPrompt('dev', {
130
+ workdir: '/home/user/project',
131
+ platform: 'linux',
227
132
  });
228
133
 
229
- export default {
230
- port: 3000,
231
- fetch: app.fetch
232
- };
134
+ const context = codeContext({ includeGitInfo: true });
233
135
  ```
234
136
 
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
137
+ ### Core AI Functions (from `@agi-cli/core`)
249
138
 
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:
139
+ AI SDK re-exports and utilities:
274
140
 
275
141
  ```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
- ```
142
+ import {
143
+ generateText,
144
+ streamText,
145
+ generateObject,
146
+ streamObject,
147
+ tool,
148
+ resolveModel,
149
+ discoverProjectTools,
150
+ buildFsTools,
151
+ buildGitTools,
152
+ createFileDiffArtifact,
153
+ z
154
+ } from '@agi-cli/sdk';
155
+ import type { CoreMessage, Tool, DiscoveredTool } from '@agi-cli/sdk';
298
156
 
299
- Or pass directly:
300
- ```typescript
301
- const model = await resolveModel('openai', 'gpt-4o', {
302
- apiKey: 'sk-...'
157
+ // Generate text
158
+ const { text } = await generateText({
159
+ model: resolveModel('anthropic'),
160
+ prompt: 'Hello!',
303
161
  });
304
- ```
305
-
306
- ---
307
-
308
- ## Configuration
309
-
310
- The SDK integrates with AGI's configuration system:
311
162
 
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' }
163
+ // Stream text with tools
164
+ const { textStream } = streamText({
165
+ model: resolveModel('openai'),
166
+ prompt: 'What files are in the current directory?',
167
+ tools: buildFsTools(),
168
+ });
320
169
 
321
- // Use configured defaults
322
- const model = await resolveModel(
323
- config.defaults.provider,
324
- config.defaults.model
325
- );
326
- ```
170
+ // Generate structured output
171
+ const { object } = await generateObject({
172
+ model: resolveModel('anthropic'),
173
+ schema: z.object({
174
+ name: z.string(),
175
+ age: z.number(),
176
+ }),
177
+ prompt: 'Generate a person',
178
+ });
327
179
 
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
- };
180
+ // Discover project tools
181
+ const tools = await discoverProjectTools('/path/to/project');
353
182
  ```
354
183
 
355
- Tools are auto-discovered by `discoverProjectTools()`.
184
+ ### Database (from `@agi-cli/database`)
356
185
 
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:
186
+ Database access:
371
187
 
372
188
  ```typescript
373
189
  import { getDb, dbSchema } from '@agi-cli/sdk';
374
190
 
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));
191
+ const db = getDb();
192
+ const messages = await db.select().from(dbSchema.messages);
385
193
  ```
386
194
 
387
- ---
195
+ ### Server (from `@agi-cli/server`)
388
196
 
389
- ## Authentication
390
-
391
- Manage provider credentials:
197
+ Create an HTTP server:
392
198
 
393
199
  ```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
- });
200
+ import { createServer } from '@agi-cli/sdk';
404
201
 
405
- // Get provider auth
406
- const openaiAuth = await getAuth('openai');
202
+ const app = createServer();
407
203
  ```
408
204
 
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
- ```
205
+ ### Error Handling (from `@agi-cli/core`)
443
206
 
444
- #### `streamText(options)`
445
- Stream text generation.
207
+ Typed error classes:
446
208
 
447
209
  ```typescript
448
- const stream = streamText({
449
- model,
450
- prompt: string,
451
- tools?: object,
452
- maxSteps?: number
453
- });
210
+ import {
211
+ AGIError,
212
+ AuthError,
213
+ ConfigError,
214
+ ToolError,
215
+ ProviderError,
216
+ DatabaseError,
217
+ ValidationError,
218
+ NotFoundError,
219
+ ServiceError
220
+ } from '@agi-cli/sdk';
454
221
 
455
- for await (const chunk of stream.textStream) {
456
- console.log(chunk);
222
+ try {
223
+ // ... your code
224
+ } catch (error) {
225
+ if (error instanceof AuthError) {
226
+ console.error('Authentication failed:', error.message);
227
+ }
457
228
  }
458
229
  ```
459
230
 
460
- #### `generateObject(options)`
461
- Generate structured JSON.
231
+ ## Tree-Shaking
232
+
233
+ The SDK is fully tree-shakable. Modern bundlers (Vite, Rollup, esbuild, webpack) will only include the code you actually use:
462
234
 
463
235
  ```typescript
464
- const result = await generateObject({
465
- model,
466
- schema: z.object({ ... }),
467
- prompt: string
468
- });
236
+ // Only includes generateText and resolveModel code
237
+ import { generateText, resolveModel } from '@agi-cli/sdk';
469
238
  ```
470
239
 
471
- #### `streamObject(options)`
472
- Stream structured JSON generation.
240
+ ## Direct Package Access (Not Recommended)
473
241
 
474
- ---
475
-
476
- ### Provider Functions
477
-
478
- #### `resolveModel(provider, model, config?)`
479
- Get model instance.
242
+ While you _can_ import directly from individual packages, we recommend using the SDK for consistency:
480
243
 
481
244
  ```typescript
482
- const model = await resolveModel(
483
- 'anthropic', // Provider
484
- 'claude-sonnet-4', // Model ID
485
- { apiKey: '...' } // Optional config
486
- );
245
+ // Discouraged - fragmented imports
246
+ import { catalog } from '@agi-cli/providers';
247
+ import { generateText } from '@agi-cli/core';
248
+ import type { ProviderId } from '@agi-cli/types';
249
+
250
+ // ✅ Recommended - single source of truth
251
+ import { catalog, generateText } from '@agi-cli/sdk';
252
+ import type { ProviderId } from '@agi-cli/sdk';
487
253
  ```
488
254
 
489
- #### `catalog`
490
- Provider/model catalog.
255
+ ## Architecture
491
256
 
492
- ```typescript
493
- import { catalog } from '@agi-cli/sdk';
257
+ The SDK follows a clean dependency graph with zero circular dependencies:
494
258
 
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));
259
+ ```
260
+ @agi-cli/types (foundation)
261
+
262
+ @agi-cli/providers, @agi-cli/auth, @agi-cli/config
263
+
264
+ @agi-cli/database, @agi-cli/prompts
265
+
266
+ @agi-cli/core
267
+
268
+ @agi-cli/server
269
+
270
+ @agi-cli/sdk ← YOU ARE HERE (single source of truth)
501
271
  ```
502
272
 
503
- ---
504
-
505
- ### Tool Functions
273
+ ## Examples
506
274
 
507
- #### `discoverProjectTools(projectRoot, globalConfigDir?)`
508
- Discover all available tools.
275
+ ### Basic Agent
509
276
 
510
277
  ```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.
278
+ import { generateText, resolveModel } from '@agi-cli/sdk';
521
279
 
522
- ```typescript
523
- import { tool, z } from '@agi-cli/sdk';
280
+ const model = resolveModel('anthropic');
524
281
 
525
- const myTool = tool({
526
- description: 'Tool description',
527
- parameters: z.object({ ... }),
528
- execute: async (params) => { ... }
282
+ const { text } = await generateText({
283
+ model,
284
+ prompt: 'Explain TypeScript generics',
529
285
  });
530
- ```
531
286
 
532
- ---
533
-
534
- ### Server Functions
287
+ console.log(text);
288
+ ```
535
289
 
536
- #### `createServer()`
537
- Create HTTP server.
290
+ ### Agent with Tools
538
291
 
539
292
  ```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
- ```
293
+ import { streamText, resolveModel, buildFsTools, buildGitTools } from '@agi-cli/sdk';
548
294
 
549
- ---
550
-
551
- ### Configuration Functions
295
+ const tools = {
296
+ ...buildFsTools(),
297
+ ...buildGitTools(),
298
+ };
552
299
 
553
- #### `loadConfig(projectRoot?)`
554
- Load AGI configuration.
300
+ const { textStream } = streamText({
301
+ model: resolveModel('openai'),
302
+ prompt: 'What Git branch am I on? List the files in the current directory.',
303
+ tools,
304
+ });
555
305
 
556
- ```typescript
557
- const config = await loadConfig(process.cwd());
558
- // Returns: { defaults, providers, paths }
306
+ for await (const chunk of textStream) {
307
+ process.stdout.write(chunk);
308
+ }
559
309
  ```
560
310
 
561
- #### `readConfig(projectRoot?)`
562
- Load config + auth.
311
+ ### Structured Output
563
312
 
564
313
  ```typescript
565
- const { cfg, auth } = await readConfig(process.cwd());
566
- ```
314
+ import { generateObject, resolveModel, z } from '@agi-cli/sdk';
315
+
316
+ const schema = z.object({
317
+ sentiment: z.enum(['positive', 'negative', 'neutral']),
318
+ confidence: z.number().min(0).max(1),
319
+ keywords: z.array(z.string()),
320
+ });
567
321
 
568
- ---
322
+ const { object } = await generateObject({
323
+ model: resolveModel('anthropic'),
324
+ schema,
325
+ prompt: 'Analyze: "This SDK is amazing!"',
326
+ });
569
327
 
570
- ### Database Functions
328
+ console.log(object);
329
+ // { sentiment: 'positive', confidence: 0.95, keywords: ['amazing', 'SDK'] }
330
+ ```
571
331
 
572
- #### `getDb(projectRoot?)`
573
- Get database instance.
332
+ ### With Configuration
574
333
 
575
334
  ```typescript
576
- const db = await getDb(process.cwd());
335
+ import { generateText, resolveModel, loadConfig } from '@agi-cli/sdk';
577
336
 
578
- // Use with Drizzle ORM
579
- import { dbSchema } from '@agi-cli/sdk';
580
- const sessions = await db.select().from(dbSchema.sessions);
581
- ```
337
+ const config = await loadConfig();
338
+ const model = resolveModel(config.provider, config.model);
582
339
 
583
- ---
340
+ const { text } = await generateText({
341
+ model,
342
+ prompt: 'Hello from AGI CLI!',
343
+ temperature: config.temperature,
344
+ });
345
+ ```
584
346
 
585
- ## Types
347
+ ## TypeScript
586
348
 
587
- All types are exported:
349
+ Full TypeScript support with comprehensive types:
588
350
 
589
351
  ```typescript
590
- import type {
591
- // AI SDK types
352
+ import type {
353
+ ProviderId,
354
+ ModelInfo,
355
+ AGIConfig,
592
356
  CoreMessage,
593
357
  Tool,
594
-
595
- // Provider types
596
- ProviderName,
597
- ProviderId,
598
- ModelInfo,
599
- ModelConfig,
600
-
601
- // Tool types
602
358
  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
359
  Artifact,
617
- FileDiffArtifact
360
+ ExecutionContext
618
361
  } from '@agi-cli/sdk';
619
- ```
620
-
621
- ---
622
-
623
- ## Environment Variables
624
362
 
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
363
+ // All types are fully documented and type-safe
364
+ const providerId: ProviderId = 'anthropic';
365
+ const config: AGIConfig = await loadConfig();
635
366
  ```
636
367
 
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
368
  ## License
665
369
 
666
- MIT - see [LICENSE](../../LICENSE)
667
-
668
- ---
370
+ MIT
669
371
 
670
- ## Links
372
+ ## Contributing
671
373
 
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)
374
+ See the main repository for contribution guidelines.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@agi-cli/sdk",
3
- "version": "0.1.50",
4
- "description": "AI agent SDK for building intelligent assistants",
3
+ "version": "0.1.51",
4
+ "description": "AI agent SDK for building intelligent assistants - tree-shakable and comprehensive",
5
5
  "author": "ntishxyz",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/ntishxyz/agi#readme",
@@ -48,6 +48,7 @@
48
48
  "@agi-cli/providers": "0.1.0",
49
49
  "@agi-cli/prompts": "0.1.0",
50
50
  "@agi-cli/server": "0.1.0",
51
+ "@agi-cli/types": "0.1.0",
51
52
  "ai": "^5.0.43",
52
53
  "@ai-sdk/anthropic": "^2.0.16",
53
54
  "@ai-sdk/openai": "^2.0.30",
@@ -70,6 +71,8 @@
70
71
  "anthropic",
71
72
  "openai",
72
73
  "development",
73
- "assistant"
74
+ "assistant",
75
+ "tree-shakable",
76
+ "typescript"
74
77
  ]
75
78
  }
package/src/index.ts CHANGED
@@ -1,27 +1,56 @@
1
- // =======================
2
- // Re-export everything from @agi-cli/core
3
- // =======================
4
- export * from '@agi-cli/core';
1
+ // ============================================================================
2
+ // @agi-cli/sdk - Tree-shakable AI Agent SDK
3
+ // ============================================================================
4
+ // This is the SINGLE source of truth for all AGI CLI functionality.
5
+ // All exports are tree-shakable - bundlers will only include what you use.
6
+ //
7
+ // Usage:
8
+ // import { generateText, resolveModel } from '@agi-cli/sdk';
9
+ // import type { ProviderId, AGIConfig } from '@agi-cli/sdk';
10
+ //
11
+ // Note: Direct package imports are still available but discouraged:
12
+ // import { catalog } from '@agi-cli/providers'; // ❌ Discouraged
13
+ // import { catalog } from '@agi-cli/sdk'; // ✅ Recommended
14
+ // ============================================================================
5
15
 
6
16
  // =======================
7
- // Server (batteries included)
17
+ // Types (from @agi-cli/types)
8
18
  // =======================
9
- export { createApp as createServer } from '@agi-cli/server';
19
+ // Provider types
20
+ export type { ProviderId, ModelInfo } from '@agi-cli/types';
10
21
 
11
- // =======================
12
- // Database (convenience re-export)
13
- // =======================
14
- export { getDb } from '@agi-cli/database';
15
- export * as dbSchema from '@agi-cli/database/schema';
22
+ // Auth types
23
+ export type { ApiAuth, OAuth, AuthInfo, AuthFile } from '@agi-cli/types';
24
+
25
+ // Config types
26
+ export type {
27
+ Scope,
28
+ ProviderConfig,
29
+ DefaultConfig,
30
+ PathConfig,
31
+ AGIConfig,
32
+ } from '@agi-cli/types';
16
33
 
17
34
  // =======================
18
- // Configuration (convenience re-export)
35
+ // Providers (from @agi-cli/providers)
19
36
  // =======================
20
- export { loadConfig, read as readConfig } from '@agi-cli/config';
21
- export type { AGIConfig, ProviderConfig, Scope } from '@agi-cli/config';
37
+ export { catalog } from '@agi-cli/providers';
38
+ export {
39
+ isProviderId,
40
+ providerIds,
41
+ defaultModelFor,
42
+ hasModel,
43
+ } from '@agi-cli/providers';
44
+ export {
45
+ isProviderAuthorized,
46
+ ensureProviderEnv,
47
+ } from '@agi-cli/providers';
48
+ export { validateProviderModel } from '@agi-cli/providers';
49
+ export { estimateModelCostUsd } from '@agi-cli/providers';
50
+ export { providerEnvVar, readEnvKey, setEnvKey } from '@agi-cli/providers';
22
51
 
23
52
  // =======================
24
- // Authentication (convenience re-export)
53
+ // Authentication (from @agi-cli/auth)
25
54
  // =======================
26
55
  export {
27
56
  getAllAuth,
@@ -34,9 +63,82 @@ export {
34
63
  openAuthUrl,
35
64
  createApiKey,
36
65
  } from '@agi-cli/auth';
37
- export type { AuthInfo, OAuth } from '@agi-cli/auth';
38
66
 
39
67
  // =======================
40
- // Agent Types (from SDK-specific modules)
68
+ // Configuration (from @agi-cli/config)
69
+ // =======================
70
+ export { loadConfig, read as readConfig } from '@agi-cli/config';
71
+
72
+ // =======================
73
+ // Prompts (from @agi-cli/prompts)
74
+ // =======================
75
+ export { providerBasePrompt } from '@agi-cli/prompts';
76
+
77
+ // =======================
78
+ // Database (from @agi-cli/database)
79
+ // =======================
80
+ export { getDb } from '@agi-cli/database';
81
+ export * as dbSchema from '@agi-cli/database/schema';
82
+
83
+ // =======================
84
+ // Core AI Functions (from @agi-cli/core)
85
+ // =======================
86
+ // AI SDK re-exports
87
+ export {
88
+ generateText,
89
+ streamText,
90
+ generateObject,
91
+ streamObject,
92
+ tool,
93
+ } from '@agi-cli/core';
94
+ export type { CoreMessage, Tool } from '@agi-cli/core';
95
+
96
+ // Provider & Model Resolution
97
+ export { resolveModel } from '@agi-cli/core';
98
+ export type { ProviderName, ModelConfig } from '@agi-cli/core';
99
+
100
+ // Tools
101
+ export { discoverProjectTools } from '@agi-cli/core';
102
+ export type { DiscoveredTool } from '@agi-cli/core';
103
+ export { buildFsTools } from '@agi-cli/core';
104
+ export { buildGitTools } from '@agi-cli/core';
105
+
106
+ // Streaming & Artifacts
107
+ export {
108
+ createFileDiffArtifact,
109
+ createToolResultPayload,
110
+ } from '@agi-cli/core';
111
+ export type {
112
+ Artifact,
113
+ FileDiffArtifact,
114
+ FileArtifact,
115
+ } from '@agi-cli/core';
116
+
117
+ // Core Types
118
+ export type { ExecutionContext, ToolResult } from '@agi-cli/core';
119
+
120
+ // Error Handling
121
+ export {
122
+ AGIError,
123
+ AuthError,
124
+ ConfigError,
125
+ ToolError,
126
+ ProviderError,
127
+ DatabaseError,
128
+ ValidationError,
129
+ NotFoundError,
130
+ ServiceError,
131
+ } from '@agi-cli/core';
132
+
133
+ // Schema Validation
134
+ export { z } from '@agi-cli/core';
135
+
136
+ // =======================
137
+ // Server (from @agi-cli/server)
138
+ // =======================
139
+ export { createApp as createServer } from '@agi-cli/server';
140
+
141
+ // =======================
142
+ // SDK-specific Agent Types
41
143
  // =======================
42
144
  export type { AgentConfig, AgentConfigEntry } from './agent/types.ts';