npm package: @sourcegraph/the-orb-is-awake
Description: TypeScript SDK for Amp CLI - Build custom AI agents with Amp's capabilities
Author: The Amp Team at Sourcegraph
Latest version: 0.1.3

# Amp TypeScript SDK

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.

## Why use the Amp SDK?

The Amp TypeScript SDK brings the Amp agent directly into your applications with simple, reliable functionality:

- **Stream Inputs**: Send prompts and messages incrementally to the Amp agent
- **Stream Outputs**: Receive structured JSON responses (system, assistant, result) as the agent executes tasks
- **Multi-turn Conversations**: Maintain back-and-forth interactions across multiple executions
- **Thread Continuity**: Continue an existing thread (latest or by ID) to build stateful agent workflows
- **Programmatic Settings**: Configure working directories, settings, and tools without user prompts — ideal for automation
- **MCP Integration**: Extend Amp with custom Model Context Protocol servers and tools
- **Custom Tools**: Define and use custom tools to extend Amp's functionality with Toolboxes

## What can you build?

The Amp SDK enables a wide range of AI-powered applications:

### Development Tools

- **Code Review Agent**: Automated pull request analysis and feedback
- **Documentation Generator**: Create and maintain project documentation
- **Test Automation**: Generate and execute test suites
- **Migration Assistant**: Help upgrade codebases and refactor legacy code

### Workflow Automation

- **CI/CD Integration**: Smart build and deployment pipelines
- **Issue Triage**: Automatically categorize and prioritize bug reports
- **Code Quality Monitoring**: Continuous analysis of code health metrics
- **Release Management**: Automated changelog generation and version bumping

## Quick Start

### Installation

Install the Amp SDK using `npm` or `yarn`:

```bash
# npm
npm install @sourcegraph/amp-sdk

# yarn
yarn add @sourcegraph/amp-sdk
```

Once installed, add your API key to the environment. You can access your API key at [ampcode.com/settings](https://ampcode.com/settings).

```bash
export AMP_API_KEY=sgamp_your_api_key_here
```

### Your First Amp Command

Now that you have the SDK installed and your API key set up, you can start using Amp with the `execute()` function:

```typescript
import { execute } from '@sourcegraph/amp-sdk'

// Simple execution - get the final result
for await (const message of execute({ prompt: 'What files are in this directory?' })) {
	if (message.type === 'result' && !message.is_error) {
		console.log('Result:', message.result)
		break
	}
}
```

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.

## Core Concepts

### Message Streaming

The SDK streams different types of messages as your agent executes:

```typescript
for await (const message of execute({ prompt: 'Run tests' })) {
	if (message.type === 'system') {
		// Session info, available tools, MCP servers
		console.log('Available tools:', message.tools)
	} else if (message.type === 'assistant') {
		// AI responses and tool usage
		console.log('Assistant is working...')
	} else if (message.type === 'result') {
		// Final result (success or error)
		console.log('Done:', message.result)
	}
}
```

### Simple Result Extraction

When you just need the final result without handling streaming:

```typescript
async function getResult(prompt: string): Promise<string> {
	for await (const message of execute({ prompt, options: { dangerouslyAllowAll: true } })) {
		if (message.type === 'result') {
			if (message.is_error) {
				throw new Error(message.error)
			}
			return message.result
		}
	}
	throw new Error('No result received')
}

// Usage
try {
	const result = await getResult('List all TypeScript files in this project')
	console.log('Found files:', result)
} catch (error) {
	console.error('Failed:', error.message)
}
```

### Thread Continuity

Continue conversations across multiple interactions:

```typescript
// Continue the most recent conversation
for await (const message of execute({
	prompt: 'What was the last error you found?',
	options: { continue: true },
})) {
	if (message.type === 'result') {
		console.log(message.result)
	}
}

// Continue a specific thread by ID
for await (const message of execute({
	prompt: 'Can you update that code we discussed?',
	options: { continue: 'T-abc123-def456' },
})) {
	if (message.type === 'result') {
		console.log(message.result)
	}
}
```

## Common Configuration

### Skip Permission Prompts

For automation scenarios, bypass permission prompts:

```typescript
const options = {
	dangerouslyAllowAll: true, // Skip permission prompts
}

for await (const message of execute({
	prompt: 'Make changes without asking for permission',
	options,
})) {
	// Handle messages...
}
```

### Working Directory

Specify where Amp should run:

```typescript
for await (const message of execute({
	prompt: 'Refactor the auth module',
	options: { cwd: './my-project' },
})) {
	// Process messages...
}
```

### Enable Debug Logging

See what's happening under the hood:

```typescript
for await (const message of execute({
	prompt: 'Analyze this project',
	options: {
		logLevel: 'debug', // Shows CLI command in console
		logFile: './amp-debug.log', // Optional: write logs to file
	},
})) {
	// Process messages
}
```

## Advanced Usage

### Interactive Progress Tracking

For building user interfaces that show real-time progress:

```typescript
async function executeWithProgress(prompt: string) {
	console.log('Starting task...')

	for await (const message of execute({ prompt })) {
		if (message.type === 'system' && message.subtype === 'init') {
			console.log('Tools available:', message.tools.join(', '))
		} else if (message.type === 'assistant') {
			// Show tool usage or assistant responses
			const content = message.message.content[0]
			if (content.type === 'tool_use') {
				console.log(`Using ${content.name}...`)
			} else if (content.type === 'text') {
				console.log('Assistant:', content.text.slice(0, 100) + '...')
			}
		} else if (message.type === 'result') {
			if (message.is_error) {
				console.log('Failed:', message.error)
			} else {
				console.log('Completed successfully!')
				console.log(message.result)
			}
		}
	}
}
```

### Cancellation and Timeouts

Handle long-running operations gracefully:

```typescript
async function executeWithTimeout(prompt: string, timeoutMs = 30000) {
	const signal = AbortSignal.timeout(timeoutMs)

	try {
		for await (const message of execute({
			prompt,
			signal,
			options: { dangerouslyAllowAll: true },
		})) {
			if (message.type === 'result') {
				return message.result
			}
		}
	} catch (error) {
		if (error.message.includes('aborted')) {
			throw new Error(`Operation timed out after ${timeoutMs}ms`)
		}
		throw error
	}
}
```

### MCP (Model Context Protocol) Integration

Extend Amp's capabilities with custom tools and data sources:

```typescript
import { execute, type MCPConfig } from '@sourcegraph/amp-sdk'

const mcpConfig: MCPConfig = {
	playwright: {
		command: 'npx',
		args: ['-y', '@playwright/mcp@latest', '--headless'],
		env: { NODE_ENV: 'production' },
	},
	database: {
		command: 'node',
		args: ['./custom-mcp-server.js'],
		env: { DB_CONNECTION_STRING: process.env.DATABASE_URL },
	},
}

for await (const message of execute({
	prompt: 'Test the login flow on staging environment',
	options: { mcpConfig, dangerouslyAllowAll: true },
})) {
	if (message.type === 'system') {
		console.log(
			'MCP Servers:',
			message.mcp_servers.map((s) => `${s.name}: ${s.status}`),
		)
	}
	// Handle other messages...
}
```

To find out more about extending Amp with MCP servers, visit the [MCP Configuration](https://ampcode.com/manual#mcp) section of the manual.

### Multi-turn Conversations

Build streaming conversations using async generators:

```typescript
import { execute, createUserMessage } from '@sourcegraph/amp-sdk'

async function* generateMessages() {
	yield createUserMessage('Start analyzing the codebase')

	// Wait for some condition or user input
	await new Promise((resolve) => setTimeout(resolve, 1000))

	yield createUserMessage('Now focus on the authentication module')
}

for await (const message of execute({
	prompt: generateMessages(),
})) {
	if (message.type === 'result') {
		console.log(message.result)
	}
}
```

### Settings File Configuration

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:

```typescript
import { execute } from '@sourcegraph/amp-sdk'

// Use a custom settings file
for await (const message of execute({
	prompt: 'Deploy the application',
	options: {
		settingsFile: './settings.json',
		logLevel: 'debug',
	},
})) {
	// Handle messages...
}
```

Example `settings.json`:

```json
{
	"amp.mcpServers": {
		"playwright": {
			"command": "npx",
			"args": ["-y", "@playwright/mcp@latest", "--headless", "--isolated"]
		}
	},
	"amp.todos.enabled": false,
	"amp.commands.allowlist": ["npx", "node", "npm"],
	"amp.tools.disable": ["mermaid", "mcp__playwright__browser_resize"]
}
```

To find all available settings, see the [Configuration Settings](https://ampcode.com/manual#configuration).

### Custom Tools

Extend Amp's capabilities with custom toolbox scripts:

```typescript
for await (const message of execute({
	prompt: 'Use my custom deployment scripts',
	options: {
		toolbox: '/usr/repository-path/toolbox', // Path to toolbox scripts
	},
})) {
	// Handle messages...
}
```

To find out more about Amp Toolboxes, see the [Toolboxes](https://ampcode.com/manual#toolboxes) section of the Amp documentation.