@ampcode/sdk 0.0.0-placeholder → 0.1.0-20260513070248-g548495c

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.
package/README.md CHANGED
@@ -1,3 +1,1122 @@
1
- # @ampcode/sdk
1
+ # Amp TypeScript SDK
2
2
 
3
- Placeholder package for npm configuration.
3
+ Use the Amp SDK to programmatically deploy the Amp agent anywhere you run TypeScript. Execute Amp CLI commands programmatically with full type safety, streaming responses, and complete control over your AI coding agent workflows.
4
+
5
+ ## Why use the Amp SDK?
6
+
7
+ The Amp TypeScript SDK brings the Amp agent directly into your applications with simple, reliable functionality:
8
+
9
+ - **Stream Inputs**: Send prompts and messages incrementally to the Amp agent
10
+ - **Stream Outputs**: Receive structured JSON responses (system, assistant, result) as the agent executes tasks
11
+ - **Multi-turn Conversations**: Maintain back-and-forth interactions across multiple executions
12
+ - **Thread Continuity**: Continue an existing thread (latest or by ID) to build stateful agent workflows
13
+ - **Programmatic Settings**: Configure working directories, settings, and tools without user prompts — ideal for automation
14
+ - **MCP Integration**: Extend Amp with custom Model Context Protocol servers and tools
15
+ - **Custom Skills**: Define and use custom agent skills to extend Amp's functionality
16
+
17
+ ## What can you build?
18
+
19
+ The Amp SDK enables a wide range of AI-powered applications:
20
+
21
+ ### Development Tools
22
+
23
+ - **Code Review Agent**: Automated pull request analysis and feedback
24
+ - **Documentation Generator**: Create and maintain project documentation
25
+ - **Test Automation**: Generate and execute test suites
26
+ - **Migration Assistant**: Help upgrade codebases and refactor legacy code
27
+
28
+ ### Workflow Automation
29
+
30
+ - **CI/CD Integration**: Smart build and deployment pipelines
31
+ - **Issue Triage**: Automatically categorize and prioritize bug reports
32
+ - **Code Quality Monitoring**: Continuous analysis of code health metrics
33
+ - **Release Management**: Automated changelog generation and version bumping
34
+
35
+ ## Quick Start
36
+
37
+ ### Installation
38
+
39
+ ```bash
40
+ # Install the Amp SDK using npm
41
+ npm install @ampcode/sdk
42
+
43
+ # or yarn
44
+ yarn add @ampcode/sdk
45
+
46
+ # Install or upgrade the Amp CLI used by the SDK (optional if a compatible version is already installed)
47
+ npx -y @ampcode/sdk install
48
+ ```
49
+
50
+ The SDK requires an Amp CLI version that is at least the version pinned by your SDK release. If your
51
+ organization installs Amp CLI through Homebrew, Artifactory, or another internal distribution channel,
52
+ you can keep using that installation as long as its version is new enough.
53
+
54
+ Once installed, add your API key to the environment. You can access your API key at [ampcode.com/settings](https://ampcode.com/settings).
55
+
56
+ ```bash
57
+ export AMP_API_KEY=sgamp_your_api_key_here
58
+ ```
59
+
60
+ ### Your First Amp Command
61
+
62
+ Now that you have the SDK installed and your API key set up, you can start using Amp with the `execute()` function:
63
+
64
+ ```typescript
65
+ import { execute } from '@ampcode/sdk'
66
+
67
+ // Simple execution - get the final result
68
+ for await (const message of execute({ prompt: 'What files are in this directory?' })) {
69
+ if (message.type === 'result' && !message.is_error) {
70
+ console.log('Result:', message.result)
71
+ break
72
+ }
73
+ }
74
+ ```
75
+
76
+ The `execute()` function only requires that you provide a `prompt` to get started. The SDK streams messages as the agent works, letting you handle responses and integrate them directly into your application.
77
+
78
+ ## Core Concepts
79
+
80
+ ### Message Streaming
81
+
82
+ The SDK streams different types of messages as your agent executes:
83
+
84
+ ```typescript
85
+ for await (const message of execute({ prompt: 'Run tests' })) {
86
+ if (message.type === 'system') {
87
+ // Session info, available tools, MCP servers
88
+ console.log('Available tools:', message.tools)
89
+ } else if (message.type === 'assistant') {
90
+ // AI responses and tool usage
91
+ console.log('Assistant is working...')
92
+ } else if (message.type === 'result') {
93
+ // Final result (success or error)
94
+ console.log('Done:', message.result)
95
+ }
96
+ }
97
+ ```
98
+
99
+ ### Simple Result Extraction
100
+
101
+ When you just need the final result without handling streaming:
102
+
103
+ ```typescript
104
+ async function getResult(prompt: string): Promise<string> {
105
+ for await (const message of execute({ prompt, options: { dangerouslyAllowAll: true } })) {
106
+ if (message.type === 'result') {
107
+ if (message.is_error) {
108
+ throw new Error(message.error)
109
+ }
110
+ return message.result
111
+ }
112
+ }
113
+ throw new Error('No result received')
114
+ }
115
+
116
+ // Usage
117
+ try {
118
+ const result = await getResult('List all TypeScript files in this project')
119
+ console.log('Found files:', result)
120
+ } catch (error) {
121
+ console.error('Failed:', error.message)
122
+ }
123
+ ```
124
+
125
+ ### Thread Continuity
126
+
127
+ Continue conversations across multiple interactions:
128
+
129
+ ```typescript
130
+ // Continue the most recent conversation
131
+ for await (const message of execute({
132
+ prompt: 'What was the last error you found?',
133
+ options: { continue: true },
134
+ })) {
135
+ if (message.type === 'result') {
136
+ console.log(message.result)
137
+ }
138
+ }
139
+
140
+ // Continue a specific thread by ID
141
+ for await (const message of execute({
142
+ prompt: 'Can you update that code we discussed?',
143
+ options: { continue: 'T-abc123-def456' },
144
+ })) {
145
+ if (message.type === 'result') {
146
+ console.log(message.result)
147
+ }
148
+ }
149
+ ```
150
+
151
+ ## Common Configuration
152
+
153
+ ### Skip Permission Prompts
154
+
155
+ For automation scenarios, bypass permission prompts:
156
+
157
+ ```typescript
158
+ const options = {
159
+ dangerouslyAllowAll: true, // Skip permission prompts
160
+ }
161
+
162
+ for await (const message of execute({
163
+ prompt: 'Make changes without asking for permission',
164
+ options,
165
+ })) {
166
+ // Handle messages...
167
+ }
168
+ ```
169
+
170
+ ### Working Directory
171
+
172
+ Specify where Amp should run:
173
+
174
+ ```typescript
175
+ for await (const message of execute({
176
+ prompt: 'Refactor the auth module',
177
+ options: { cwd: './my-project' },
178
+ })) {
179
+ // Process messages...
180
+ }
181
+ ```
182
+
183
+ ### Enable Debug Logging
184
+
185
+ See what's happening under the hood:
186
+
187
+ ```typescript
188
+ for await (const message of execute({
189
+ prompt: 'Analyze this project',
190
+ options: {
191
+ logLevel: 'debug', // Shows CLI command in console
192
+ logFile: './amp-debug.log', // Optional: write logs to file
193
+ },
194
+ })) {
195
+ // Process messages
196
+ }
197
+ ```
198
+
199
+ ### Agent Mode
200
+
201
+ Select which agent mode to use. The mode controls the model, system prompt, and tool selection:
202
+
203
+ ```typescript
204
+ for await (const message of execute({
205
+ prompt: 'Quickly fix this typo',
206
+ options: {
207
+ mode: 'rush', // Use rush mode for faster responses
208
+ },
209
+ })) {
210
+ // Process messages
211
+ }
212
+ ```
213
+
214
+ Available modes:
215
+
216
+ - `smart` (default): Balanced mode with full capabilities
217
+ - `rush`: Faster responses with streamlined tool usage
218
+ - `large`: 1M-token long-context workhorse
219
+ - `deep`: Extended reasoning for complex tasks
220
+
221
+ ### Thread Labels
222
+
223
+ Add labels to threads created by `execute()`.
224
+
225
+ ```typescript
226
+ for await (const message of execute({
227
+ prompt: 'Summarize this repo',
228
+ options: {
229
+ labels: ['sdk', 'summary'],
230
+ },
231
+ })) {
232
+ if (message.type === 'result') {
233
+ console.log(message.result)
234
+ break
235
+ }
236
+ }
237
+ ```
238
+
239
+ ### Thread Visibility
240
+
241
+ Control who can see threads created by `execute()`:
242
+
243
+ ```typescript
244
+ for await (const message of execute({
245
+ prompt: 'Analyze this private codebase',
246
+ options: {
247
+ visibility: 'private', // Only you can see this thread
248
+ },
249
+ })) {
250
+ if (message.type === 'result') {
251
+ console.log(message.result)
252
+ break
253
+ }
254
+ }
255
+ ```
256
+
257
+ Available visibility levels:
258
+
259
+ - `workspace` (default): Visible to all workspace members
260
+ - `private`: Only visible to you
261
+ - `public`: Visible to anyone with the link
262
+ - `group`: Visible to members of your user group (Enterprise)
263
+
264
+ ### Tool Permissions
265
+
266
+ Control which tools Amp can use with fine-grained permissions:
267
+
268
+ ```typescript
269
+ import { execute, createPermission } from '@ampcode/sdk'
270
+
271
+ for await (const message of execute({
272
+ prompt: 'List files and run tests',
273
+ options: {
274
+ permissions: [
275
+ // Allow listing files
276
+ createPermission('Bash', 'allow', { matches: { cmd: 'ls *' } }),
277
+ // Allow running tests
278
+ createPermission('Bash', 'allow', { matches: { cmd: 'npm test' } }),
279
+ // Ask before reading sensitive files
280
+ createPermission('Read', 'ask', { matches: { path: '/etc/*' } }),
281
+ ],
282
+ },
283
+ })) {
284
+ // Process messages
285
+ }
286
+ ```
287
+
288
+ Permission rules support:
289
+
290
+ - **Pattern matching**: Use `*` wildcards and regex patterns
291
+ - **Context control**: Restrict rules to main thread or sub-agents
292
+ - **Delegation**: Delegate permission decisions to external programs
293
+
294
+ Learn more about permissions in the [manual](https://ampcode.com/manual#permissions) and the [appendix](https://ampcode.com/manual/appendix#permissions-reference).
295
+
296
+ ## Advanced Usage
297
+
298
+ ### Interactive Progress Tracking
299
+
300
+ For building user interfaces that show real-time progress:
301
+
302
+ ```typescript
303
+ async function executeWithProgress(prompt: string) {
304
+ console.log('Starting task...')
305
+
306
+ for await (const message of execute({ prompt })) {
307
+ if (message.type === 'system' && message.subtype === 'init') {
308
+ console.log('Tools available:', message.tools.join(', '))
309
+ } else if (message.type === 'assistant') {
310
+ // Show tool usage or assistant responses
311
+ const content = message.message.content[0]
312
+ if (content.type === 'tool_use') {
313
+ console.log(`Using ${content.name}...`)
314
+ } else if (content.type === 'text') {
315
+ console.log('Assistant:', content.text.slice(0, 100) + '...')
316
+ }
317
+ } else if (message.type === 'result') {
318
+ if (message.is_error) {
319
+ console.log('Failed:', message.error)
320
+ } else {
321
+ console.log('Completed successfully!')
322
+ console.log(message.result)
323
+ }
324
+ }
325
+ }
326
+ }
327
+ ```
328
+
329
+ ### Cancellation and Timeouts
330
+
331
+ Handle long-running operations gracefully:
332
+
333
+ ```typescript
334
+ async function executeWithTimeout(prompt: string, timeoutMs = 30000) {
335
+ const signal = AbortSignal.timeout(timeoutMs)
336
+
337
+ try {
338
+ for await (const message of execute({
339
+ prompt,
340
+ signal,
341
+ options: { dangerouslyAllowAll: true },
342
+ })) {
343
+ if (message.type === 'result') {
344
+ return message.result
345
+ }
346
+ }
347
+ } catch (error) {
348
+ if (error.message.includes('aborted')) {
349
+ throw new Error(`Operation timed out after ${timeoutMs}ms`)
350
+ }
351
+ throw error
352
+ }
353
+ }
354
+ ```
355
+
356
+ ### MCP (Model Context Protocol) Integration
357
+
358
+ Extend Amp's capabilities with custom tools and data sources:
359
+
360
+ ```typescript
361
+ import { execute, type MCPConfig } from '@ampcode/sdk'
362
+
363
+ const mcpConfig: MCPConfig = {
364
+ playwright: {
365
+ command: 'npx',
366
+ args: ['-y', '@playwright/mcp@latest', '--headless'],
367
+ env: { NODE_ENV: 'production' },
368
+ },
369
+ database: {
370
+ command: 'node',
371
+ args: ['./custom-mcp-server.js'],
372
+ env: { DB_CONNECTION_STRING: process.env.DATABASE_URL },
373
+ },
374
+ }
375
+
376
+ for await (const message of execute({
377
+ prompt: 'Test the login flow on staging environment',
378
+ options: { mcpConfig, dangerouslyAllowAll: true },
379
+ })) {
380
+ if (message.type === 'system') {
381
+ console.log(
382
+ 'MCP Servers:',
383
+ message.mcp_servers.map((s) => `${s.name}: ${s.status}`),
384
+ )
385
+ }
386
+ // Handle other messages...
387
+ }
388
+ ```
389
+
390
+ To find out more about extending Amp with MCP servers, visit the [MCP Configuration](https://ampcode.com/manual#mcp) section of the manual.
391
+
392
+ ### Multi-turn Conversations
393
+
394
+ Build streaming conversations using async generators:
395
+
396
+ ```typescript
397
+ import { execute, createUserMessage } from '@ampcode/sdk'
398
+
399
+ async function* generateMessages() {
400
+ yield createUserMessage('Start analyzing the codebase')
401
+
402
+ // Wait for some condition or user input
403
+ await new Promise((resolve) => setTimeout(resolve, 1000))
404
+
405
+ yield createUserMessage('Now focus on the authentication module')
406
+ }
407
+
408
+ for await (const message of execute({
409
+ prompt: generateMessages(),
410
+ })) {
411
+ if (message.type === 'result') {
412
+ console.log(message.result)
413
+ }
414
+ }
415
+ ```
416
+
417
+ ### Settings File Configuration
418
+
419
+ Configure Amp's behavior with a settings file, like the `settings.json`. You can provide Amp with a custom settings file you have saved in your project:
420
+
421
+ ```typescript
422
+ import { execute } from '@ampcode/sdk'
423
+
424
+ // Use a custom settings file
425
+ for await (const message of execute({
426
+ prompt: 'Deploy the application',
427
+ options: {
428
+ settingsFile: './settings.json',
429
+ logLevel: 'debug',
430
+ },
431
+ })) {
432
+ // Handle messages...
433
+ }
434
+ ```
435
+
436
+ Example `settings.json`:
437
+
438
+ ```json
439
+ {
440
+ "amp.mcpServers": {
441
+ "playwright": {
442
+ "command": "npx",
443
+ "args": ["-y", "@playwright/mcp@latest", "--headless", "--isolated"]
444
+ }
445
+ },
446
+ "amp.commands.allowlist": ["npx", "node", "npm"],
447
+ "amp.tools.disable": ["web_search", "mcp__playwright__browser_resize"]
448
+ }
449
+ ```
450
+
451
+ To find all available settings, see the [Configuration Settings](https://ampcode.com/manual#configuration).
452
+
453
+ ### Custom Tools
454
+
455
+ Extend Amp's capabilities with custom toolbox scripts:
456
+
457
+ ```typescript
458
+ for await (const message of execute({
459
+ prompt: 'Use my custom deployment scripts',
460
+ options: {
461
+ toolbox: '/usr/repository-path/toolbox', // Path to toolbox scripts
462
+ },
463
+ })) {
464
+ // Handle messages...
465
+ }
466
+ ```
467
+
468
+ To find out more about Amp Toolboxes, see the [Toolboxes](https://ampcode.com/manual#toolboxes) section of the Amp documentation.
469
+
470
+ ### Custom Skills
471
+
472
+ Load custom skills from a specified directory:
473
+
474
+ ```typescript
475
+ for await (const message of execute({
476
+ prompt: 'Use my custom deployment skill',
477
+ options: {
478
+ skills: './my-skills', // Path to custom skills directory
479
+ },
480
+ })) {
481
+ // Process messages
482
+ }
483
+ ```
484
+
485
+ To learn more about creating custom skills, see the [Agent Skills](https://ampcode.com/manual#agent-skills) section of the Amp documentation.
486
+
487
+ ## Functions
488
+
489
+ ### execute()
490
+
491
+ The main function for executing Amp CLI commands programmatically.
492
+
493
+ ```typescript
494
+ function execute(options: ExecuteOptions): AsyncIterable<StreamMessage>
495
+ ```
496
+
497
+ #### Parameters
498
+
499
+ - `options` ([`ExecuteOptions`](#executeoptions)) - Configuration for the execution
500
+
501
+ #### Returns
502
+
503
+ - `AsyncIterable<StreamMessage>` - Stream of messages from the Amp CLI
504
+
505
+ #### Example
506
+
507
+ ```typescript
508
+ import { execute } from '@ampcode/sdk'
509
+
510
+ for await (const message of execute({
511
+ prompt: 'Analyze this codebase',
512
+ options: {
513
+ cwd: './my-project',
514
+ dangerouslyAllowAll: true,
515
+ },
516
+ })) {
517
+ if (message.type === 'assistant') {
518
+ console.log('Assistant:', message.message.content)
519
+ } else if (message.type === 'result') {
520
+ console.log('Final result:', message.result)
521
+ break
522
+ }
523
+ }
524
+ ```
525
+
526
+ ### createUserMessage()
527
+
528
+ Helper function to create properly formatted user input messages for streaming conversations.
529
+
530
+ ```typescript
531
+ function createUserMessage(text: string): UserInputMessage
532
+ ```
533
+
534
+ #### Parameters
535
+
536
+ - `text` (`string`) - The text content for the user message
537
+
538
+ #### Returns
539
+
540
+ - [`UserInputMessage`](#userinputmessage) - A formatted user input message
541
+
542
+ #### Example
543
+
544
+ ```typescript
545
+ import { createUserMessage } from '@ampcode/sdk'
546
+
547
+ const message = createUserMessage('Analyze this code')
548
+ console.log(message)
549
+ // Output: { type: 'user', message: { role: 'user', content: [{ type: 'text', text: 'Analyze this code' }] } }
550
+ ```
551
+
552
+ ### createPermission()
553
+
554
+ Helper function to create permission objects for controlling tool usage.
555
+
556
+ ```typescript
557
+ function createPermission(
558
+ tool: string,
559
+ action: 'allow' | 'reject' | 'ask' | 'delegate',
560
+ options?: {
561
+ matches?: Record<string, PermissionMatchCondition>
562
+ context?: 'thread' | 'subagent'
563
+ to?: string
564
+ },
565
+ ): Permission
566
+ ```
567
+
568
+ #### Parameters
569
+
570
+ - `tool` (`string`) - The name of the tool to which this permission applies (supports glob patterns)
571
+ - `action` (`'allow' | 'reject' | 'ask' | 'delegate'`) - How Amp should proceed when matched
572
+ - `options` (`object`, optional) - Additional configuration for the permission
573
+ - `matches` ([`Record<string, PermissionMatchCondition>`](#permissionmatchcondition)) - Match conditions for tool arguments
574
+ - `context` (`'thread' | 'subagent'`) - Only apply this rule in specific context
575
+ - `to` (`string`) - Command to delegate to (required when action is `'delegate'`)
576
+
577
+ #### Returns
578
+
579
+ - [`Permission`](#permission) - A permission object that can be used in the permissions array
580
+
581
+ #### Examples
582
+
583
+ ```typescript
584
+ import { createPermission } from '@ampcode/sdk'
585
+
586
+ // Allow all Bash commands
587
+ createPermission('Bash', 'allow')
588
+
589
+ // Allow specific git commands
590
+ createPermission('Bash', 'allow', {
591
+ matches: { cmd: 'git *' },
592
+ })
593
+
594
+ // Ask before allowing Read operations on sensitive paths
595
+ createPermission('Read', 'ask', {
596
+ matches: { path: '/etc/*' },
597
+ })
598
+
599
+ // Delegate web browsing to a custom command
600
+ createPermission('mcp__playwright__*', 'delegate', {
601
+ to: 'node browse.js',
602
+ })
603
+
604
+ // Only apply in subagent context
605
+ createPermission('Bash', 'reject', {
606
+ context: 'subagent',
607
+ })
608
+ ```
609
+
610
+ ### threads.new()
611
+
612
+ Create a new empty thread and return its ID.
613
+
614
+ ```typescript
615
+ async function threads.new(options?: ThreadsNewOptions): Promise<string>
616
+ ```
617
+
618
+ #### Parameters
619
+
620
+ - `options` ([`ThreadsNewOptions`](#threadsnewoptions), optional) - Configuration for the new thread
621
+
622
+ #### Returns
623
+
624
+ - `Promise<string>` - The thread ID
625
+
626
+ #### Example
627
+
628
+ ```typescript
629
+ import { threads } from '@ampcode/sdk'
630
+
631
+ // Create a new private thread
632
+ const threadId = await threads.new({ visibility: 'private' })
633
+ console.log('Created thread:', threadId)
634
+ ```
635
+
636
+ ### threads.markdown()
637
+
638
+ Get a thread rendered as markdown.
639
+
640
+ ```typescript
641
+ async function threads.markdown(options: ThreadsMarkdownOptions): Promise<string>
642
+ ```
643
+
644
+ #### Parameters
645
+
646
+ - `options` ([`ThreadsMarkdownOptions`](#threadsmarkdownoptions)) - Options containing the thread ID
647
+
648
+ #### Returns
649
+
650
+ - `Promise<string>` - The thread content as markdown
651
+
652
+ #### Example
653
+
654
+ ```typescript
655
+ import { threads } from '@ampcode/sdk'
656
+
657
+ // Get thread content as markdown
658
+ const markdown = await threads.markdown({ threadId: 'T-abc123-def456' })
659
+ console.log(markdown)
660
+ ```
661
+
662
+ ## Types
663
+
664
+ ### ExecuteOptions
665
+
666
+ Configuration options for the `execute()` function.
667
+
668
+ ```typescript
669
+ interface ExecuteOptions {
670
+ prompt: string | AsyncIterable<UserInputMessage>
671
+ options?: AmpOptions
672
+ signal?: AbortSignal
673
+ }
674
+ ```
675
+
676
+ #### Properties
677
+
678
+ | Property | Type | Required | Description |
679
+ | --------- | ------------------------------------------- | -------- | -------------------------------------------------------------------------------------------- |
680
+ | `prompt` | `string \| AsyncIterable<UserInputMessage>` | Yes | The input prompt as a string or async iterable of user messages for multi-turn conversations |
681
+ | `options` | [`AmpOptions`](#ampoptions) | No | CLI configuration options |
682
+ | `signal` | `AbortSignal` | No | Signal for cancellation support |
683
+
684
+ ### AmpOptions
685
+
686
+ Configuration options that map to Amp CLI flags.
687
+
688
+ ```typescript
689
+ interface AmpOptions {
690
+ cwd?: string
691
+ mode?: 'smart' | 'rush' | 'large'
692
+ dangerouslyAllowAll?: boolean
693
+ archive?: boolean
694
+ visibility?: 'public' | 'private' | 'workspace' | 'group'
695
+ settingsFile?: string
696
+ logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'audit'
697
+ logFile?: string
698
+ mcpConfig?: string | MCPConfig
699
+ env?: Record<string, string>
700
+ continue?: boolean | string
701
+ toolbox?: string
702
+ skills?: string
703
+ permissions?: Permission[]
704
+ labels?: string[]
705
+ thinking?: boolean
706
+ }
707
+ ```
708
+
709
+ #### Properties
710
+
711
+ | Property | Type | Default | Description |
712
+ | --------------------- | --------------------------------------------------- | --------------- | ------------------------------------------------------------------------ |
713
+ | `cwd` | `string` | `process.cwd()` | Current working directory for execution |
714
+ | `mode` | `'smart' \| 'rush' \| 'large'` | `'smart'` | Agent mode - controls model, system prompt, and tool selection |
715
+ | `dangerouslyAllowAll` | `boolean` | `false` | Allow all tool usage without permission prompts |
716
+ | `visibility` | `'public' \| 'private' \| 'workspace' \| 'group'` | `'workspace'` | Thread visibility level |
717
+ | `settingsFile` | `string` | - | Path to custom settings file |
718
+ | `logLevel` | `'debug' \| 'info' \| 'warn' \| 'error' \| 'audit'` | `'info'` | Logging verbosity level |
719
+ | `logFile` | `string` | - | Path to write logs |
720
+ | `continue` | `boolean \| string` | `false` | Continue most recent thread (`true`) or specific thread by ID (`string`) |
721
+ | `mcpConfig` | `string \| MCPConfig` | - | MCP server configuration as JSON string, or config object |
722
+ | `env` | `Record<string, string>` | - | Additional environment variables |
723
+ | `toolbox` | `string` | - | Folder path with toolbox scripts |
724
+ | `skills` | `string` | - | Folder path with custom skills |
725
+ | `permissions` | [`Permission[]`](#permission) | - | Permission rules for tool usage |
726
+ | `labels` | `string[]` | - | Labels to add to the thread |
727
+ | `thinking` | `boolean` | `false` | Include thinking blocks in the result stream |
728
+
729
+ ## Message Types
730
+
731
+ The SDK streams various message types during execution. All messages implement the base `StreamMessage` type.
732
+
733
+ ### SystemMessage
734
+
735
+ Initial message containing session information and available tools.
736
+
737
+ ```typescript
738
+ interface SystemMessage {
739
+ type: 'system'
740
+ subtype: 'init'
741
+ session_id: string
742
+ cwd: string
743
+ tools: string[]
744
+ mcp_servers: Array<{
745
+ name: string
746
+ status: 'connected' | 'connecting' | 'connection-failed' | 'disabled'
747
+ }>
748
+ }
749
+ ```
750
+
751
+ #### Properties
752
+
753
+ | Property | Type | Description |
754
+ | ------------- | --------------------------------------- | -------------------------------------------- |
755
+ | `session_id` | `string` | Unique identifier for this execution session |
756
+ | `cwd` | `string` | Current working directory |
757
+ | `tools` | `string[]` | List of available tool names |
758
+ | `mcp_servers` | `Array<{name: string, status: string}>` | Status of MCP servers |
759
+
760
+ ### AssistantMessage
761
+
762
+ AI assistant responses with text content and tool usage.
763
+
764
+ ```typescript
765
+ interface AssistantMessage {
766
+ type: 'assistant'
767
+ session_id: string
768
+ message: {
769
+ id: string
770
+ type: 'message'
771
+ role: 'assistant'
772
+ model: string
773
+ content: Array<TextContent | ToolUseContent>
774
+ stop_reason: 'end_turn' | 'tool_use' | 'max_tokens' | null
775
+ stop_sequence: string | null
776
+ usage?: Usage
777
+ }
778
+ parent_tool_use_id: string | null
779
+ }
780
+ ```
781
+
782
+ #### Properties
783
+
784
+ | Property | Type | Description |
785
+ | -------------------- | ---------------- | ------------------------------------------------ |
786
+ | `session_id` | `string` | Unique identifier for this execution session |
787
+ | `message` | `object` | The assistant's message content |
788
+ | `parent_tool_use_id` | `string \| null` | ID of parent tool use if this is a tool response |
789
+
790
+ ### UserMessage
791
+
792
+ User input and tool results.
793
+
794
+ ```typescript
795
+ interface UserMessage {
796
+ type: 'user'
797
+ session_id: string
798
+ message: {
799
+ role: 'user'
800
+ content: Array<TextContent | ToolResultContent>
801
+ }
802
+ parent_tool_use_id: string | null
803
+ }
804
+ ```
805
+
806
+ #### Properties
807
+
808
+ | Property | Type | Description |
809
+ | -------------------- | ---------------- | ------------------------------------------------ |
810
+ | `session_id` | `string` | Unique identifier for this execution session |
811
+ | `message` | `object` | The user's message content |
812
+ | `parent_tool_use_id` | `string \| null` | ID of parent tool use if this is a tool response |
813
+
814
+ ### ResultMessage
815
+
816
+ Final successful execution result.
817
+
818
+ ```typescript
819
+ interface ResultMessage {
820
+ type: 'result'
821
+ subtype: 'success'
822
+ session_id: string
823
+ is_error: false
824
+ result: string
825
+ duration_ms: number
826
+ num_turns: number
827
+ usage?: Usage
828
+ permission_denials?: string[]
829
+ }
830
+ ```
831
+
832
+ #### Properties
833
+
834
+ | Property | Type | Description |
835
+ | -------------------- | ----------------- | -------------------------------------------- |
836
+ | `session_id` | `string` | Unique identifier for this execution session |
837
+ | `result` | `string` | The final result from the assistant |
838
+ | `duration_ms` | `number` | Total execution time in milliseconds |
839
+ | `num_turns` | `number` | Number of conversation turns |
840
+ | `usage` | [`Usage`](#usage) | Token usage information |
841
+ | `permission_denials` | `string[]` | List of permissions that were denied |
842
+
843
+ ### ErrorResultMessage
844
+
845
+ Final error result indicating execution failure.
846
+
847
+ ```typescript
848
+ interface ErrorResultMessage {
849
+ type: 'result'
850
+ subtype: 'error_during_execution' | 'error_max_turns'
851
+ session_id: string
852
+ is_error: true
853
+ error: string
854
+ duration_ms: number
855
+ num_turns: number
856
+ usage?: Usage
857
+ permission_denials?: string[]
858
+ }
859
+ ```
860
+
861
+ #### Properties
862
+
863
+ | Property | Type | Description |
864
+ | -------------------- | ----------------- | -------------------------------------------- |
865
+ | `session_id` | `string` | Unique identifier for this execution session |
866
+ | `error` | `string` | Error message describing what went wrong |
867
+ | `duration_ms` | `number` | Total execution time in milliseconds |
868
+ | `num_turns` | `number` | Number of conversation turns |
869
+ | `usage` | [`Usage`](#usage) | Token usage information |
870
+ | `permission_denials` | `string[]` | List of permissions that were denied |
871
+
872
+ ### TextContent
873
+
874
+ Plain text content block.
875
+
876
+ ```typescript
877
+ interface TextContent {
878
+ type: 'text'
879
+ text: string
880
+ }
881
+ ```
882
+
883
+ ### ToolUseContent
884
+
885
+ Tool execution request.
886
+
887
+ ```typescript
888
+ interface ToolUseContent {
889
+ type: 'tool_use'
890
+ id: string
891
+ name: string
892
+ input: Record<string, unknown>
893
+ }
894
+ ```
895
+
896
+ ### ToolResultContent
897
+
898
+ Result from tool execution.
899
+
900
+ ```typescript
901
+ interface ToolResultContent {
902
+ type: 'tool_result'
903
+ tool_use_id: string
904
+ content: string
905
+ is_error: boolean
906
+ }
907
+ ```
908
+
909
+ ### Usage
910
+
911
+ Token usage and billing information from API calls.
912
+
913
+ ```typescript
914
+ interface Usage {
915
+ input_tokens: number
916
+ cache_creation_input_tokens?: number
917
+ cache_read_input_tokens?: number
918
+ output_tokens: number
919
+ service_tier?: string
920
+ }
921
+ ```
922
+
923
+ #### Properties
924
+
925
+ | Property | Type | Description |
926
+ | ----------------------------- | -------- | ---------------------------------- |
927
+ | `input_tokens` | `number` | Number of input tokens used |
928
+ | `cache_creation_input_tokens` | `number` | Tokens used for cache creation |
929
+ | `cache_read_input_tokens` | `number` | Tokens read from cache |
930
+ | `output_tokens` | `number` | Number of output tokens generated |
931
+ | `service_tier` | `string` | Service tier used for this request |
932
+
933
+ ## Input Types
934
+
935
+ ### UserInputMessage
936
+
937
+ Formatted user input message for streaming conversations.
938
+
939
+ ```typescript
940
+ interface UserInputMessage {
941
+ type: 'user'
942
+ message: {
943
+ role: 'user'
944
+ content: Array<{
945
+ type: 'text'
946
+ text: string
947
+ }>
948
+ }
949
+ }
950
+ ```
951
+
952
+ ### MCPConfig
953
+
954
+ Configuration for MCP (Model Context Protocol) servers. Supports both stdio-based and HTTP-based servers.
955
+
956
+ ```typescript
957
+ type MCPConfig = Record<string, MCPServer>
958
+
959
+ // MCPServer is a union of stdio and HTTP server configurations
960
+ ```
961
+
962
+ `MCPServer` accepts either a stdio server config (with `command`) or an HTTP server config (with `url`):
963
+
964
+ ```typescript
965
+ const mcpConfig: MCPConfig = {
966
+ playwright: { command: 'npx', args: ['-y', '@playwright/mcp'] },
967
+ remote: { url: 'https://api.example.com/mcp' },
968
+ }
969
+ ```
970
+
971
+ #### MCPServer Properties
972
+
973
+ **Stdio server:**
974
+
975
+ | Property | Type | Required | Description |
976
+ | ---------- | ------------------------ | -------- | ------------------------------------ |
977
+ | `command` | `string` | Yes | Command to start the MCP server |
978
+ | `args` | `string[]` | No | Command line arguments |
979
+ | `env` | `Record<string, string>` | No | Environment variables for the server |
980
+ | `disabled` | `boolean` | No | Whether this server is disabled |
981
+
982
+ **HTTP server:**
983
+
984
+ | Property | Type | Required | Description |
985
+ | ----------- | ------------------------ | -------- | -------------------------------------- |
986
+ | `url` | `string` | Yes | URL of the HTTP MCP server |
987
+ | `headers` | `Record<string, string>` | No | HTTP headers to send with requests |
988
+ | `transport` | `string` | No | Transport type (e.g., "sse") |
989
+ | `oauth` | `object` | No | OAuth configuration for authentication |
990
+ | `disabled` | `boolean` | No | Whether this server is disabled |
991
+
992
+ **OAuth config (for HTTP servers):**
993
+
994
+ | Property | Type | Required | Description |
995
+ | -------------- | ---------- | -------- | ----------------------- |
996
+ | `clientId` | `string` | Yes | OAuth client ID |
997
+ | `clientSecret` | `string` | No | OAuth client secret |
998
+ | `authUrl` | `string` | Yes | OAuth authorization URL |
999
+ | `tokenUrl` | `string` | Yes | OAuth token URL |
1000
+ | `scopes` | `string[]` | No | OAuth scopes |
1001
+ | `redirectUrl` | `string` | No | OAuth redirect URL |
1002
+
1003
+ ### ThreadsNewOptions
1004
+
1005
+ Options for creating a new thread.
1006
+
1007
+ ```typescript
1008
+ interface ThreadsNewOptions {
1009
+ visibility?: 'private' | 'public' | 'workspace' | 'group'
1010
+ }
1011
+ ```
1012
+
1013
+ #### Properties
1014
+
1015
+ | Property | Type | Required | Description |
1016
+ | ------------ | ------------------------------------------------- | -------- | ----------------- |
1017
+ | `visibility` | `'private' \| 'public' \| 'workspace' \| 'group'` | No | Thread visibility |
1018
+
1019
+ ### ThreadsMarkdownOptions
1020
+
1021
+ Options for getting thread markdown.
1022
+
1023
+ ```typescript
1024
+ interface ThreadsMarkdownOptions {
1025
+ threadId: string
1026
+ }
1027
+ ```
1028
+
1029
+ #### Properties
1030
+
1031
+ | Property | Type | Required | Description |
1032
+ | ---------- | -------- | -------- | --------------------------------- |
1033
+ | `threadId` | `string` | Yes | The thread ID to get markdown for |
1034
+
1035
+ ### Permission
1036
+
1037
+ Individual permission rule for controlling tool usage.
1038
+
1039
+ ```typescript
1040
+ interface Permission {
1041
+ tool: string
1042
+ matches?: Record<string, PermissionMatchCondition>
1043
+ action: 'allow' | 'reject' | 'ask' | 'delegate'
1044
+ context?: 'thread' | 'subagent'
1045
+ to?: string
1046
+ }
1047
+ ```
1048
+
1049
+ #### Properties
1050
+
1051
+ | Property | Type | Required | Description |
1052
+ | --------- | -------------------------------------------- | -------- | ----------------------------------------------------------- |
1053
+ | `tool` | `string` | Yes | Tool name (supports glob patterns like `Bash` or `mcp__*`) |
1054
+ | `matches` | `Record<string, PermissionMatchCondition>` | No | Match conditions for tool arguments |
1055
+ | `action` | `'allow' \| 'reject' \| 'ask' \| 'delegate'` | Yes | How Amp should proceed when the rule matches |
1056
+ | `context` | `'thread' \| 'subagent'` | No | Apply rule only in main thread or sub-agents |
1057
+ | `to` | `string` | No | Command to delegate to (required when action is `delegate`) |
1058
+
1059
+ #### Example
1060
+
1061
+ ```typescript
1062
+ import { execute, createPermission } from '@ampcode/sdk'
1063
+
1064
+ for await (const message of execute({
1065
+ prompt: 'Deploy the application',
1066
+ options: {
1067
+ permissions: [
1068
+ // Allow git commands
1069
+ createPermission('Bash', 'allow', { matches: { cmd: 'git *' } }),
1070
+ // Allow reading files
1071
+ createPermission('Read', 'allow'),
1072
+ ],
1073
+ },
1074
+ })) {
1075
+ // Handle messages
1076
+ }
1077
+ ```
1078
+
1079
+ ### PermissionMatchCondition
1080
+
1081
+ Match condition for tool arguments. Supports strings (with glob patterns or regex), arrays (OR logic), booleans, numbers, null, undefined, and nested objects.
1082
+
1083
+ ```typescript
1084
+ type PermissionMatchCondition =
1085
+ | string
1086
+ | PermissionMatchCondition[]
1087
+ | { [key: string]: PermissionMatchCondition }
1088
+ | boolean
1089
+ | number
1090
+ | null
1091
+ | undefined
1092
+ ```
1093
+
1094
+ #### Examples
1095
+
1096
+ ```typescript
1097
+ // String pattern with wildcard
1098
+ {
1099
+ cmd: 'npm *'
1100
+ }
1101
+
1102
+ // Array for OR logic
1103
+ {
1104
+ cmd: ['npm install', 'npm test', 'npm run build']
1105
+ }
1106
+
1107
+ // Regex pattern
1108
+ {
1109
+ cmd: '/^git (status|log|diff)$/'
1110
+ }
1111
+
1112
+ // Nested object matching
1113
+ {
1114
+ env: {
1115
+ NODE_ENV: 'production'
1116
+ }
1117
+ }
1118
+ ```
1119
+
1120
+ ## Requirements
1121
+
1122
+ - Node.js 18 or higher