# @ampcode/sdk 中文文档

规范地址：https://npmcn.com/package/%40ampcode/sdk/

版本：0\.1\.0-20261028101623-g93a0da1
npm 元数据更新时间：2026-10-28T10:20:48.496Z
中文译文更新时间：2026-11-06T01:12:01.944Z
软件包许可：Amp Commercial License

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40ampcode/sdk
原文对照：https://npmcn.com/package/%40ampcode/sdk/?lang=original
项目主页：https://ampcode.com/
源码仓库：https://github.com/ampcode/amp

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：226 kB，10 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=18
- 运行依赖：2 个
- 首次发布：2026-05-13T06:56:45.940Z
- 最新版本发布：2026-10-28T10:20:48.231Z
- 近 30 天下载量：27638（2026-10-06 至 2026-11-04，npm 官方下载统计）
- 已发布版本数：101（近 12 个月 101 个）

## 中文简介

TypeScript SDK for Amp CLI - 构建具有 Amp 能力的自定义 AI 代理

## 安装

```sh
npm install @ampcode/sdk
```

也可以使用：`pnpm add @ampcode/sdk`、`yarn add @ampcode/sdk`、`bun add @ampcode/sdk`

## README

# AMP 类型脚本 SDK

使用 Amp SDK 程序在您运行 TypeScript 的任何地方部署 Amp 代理 。 执行 AMP CLI 在程序上命令全类型安全,流回响应,并完全控制您的 AI 编码代理工作流程.

## 为什么用Amp SDK?

Amp TypeScript SDK 将 Amp 代理直接带入您的应用程序, 具有简单可靠的功能 :

-   **串流输入**: 递增向 Amp 代理发送提示和信件
-   **连续产出**: 接收结构化的 JSON 响应( 系统, 助手, 结果), 因为代理执行任务
-   **多回合对话**:在多次处决之间保持前后互动
-   **线条连续性**: 继续一个已存在的线程( 最新或通过 ID) 来构建状态代理工作流程
-   **程序设置**: 配置没有用户提示的工作目录、设置和工具——自动化的理想
-   **MCP 一体化**: 使用自定义的模型上下文协议服务器和工具扩展 Amp
-   **自定义技能**: 定义并使用自定义代理技能来扩展 Amp 的功能

## 你能造出什么来?

Amp SDK 启用了广泛的AI驱动应用程序:

### 开发工具

-   **代码审查代理**:自动拉动请求分析和反馈
-   **文档生成器**: 创建和维护项目文档
-   **测试自动化**: 生成并执行测试套件
-   **移徙助理**: 帮助更新代码库并重构遗留代码

### 工作流程自动化

-   **CI/CD 一体化**:智能建设和部署管道
-   **问题 Trage**: 自动分类和优先排序错误报告
-   **守则质量监测**:持续分析代码健康衡量标准
-   **发行管理**: 自动更改日志生成和版本起伏

## 快速启动

### 安装

```bash
# Install the Amp SDK using npm
npm install @ampcode/sdk

# or yarn
yarn add @ampcode/sdk

# Optional: manually install the Amp CLI, already a dependency
npx -y @ampcode/sdk install
```

如果您需要在 Amp Neo 之前使用 Amp, 请安装遗留的 SDK 发布 [`@ampcode/sdk@0.1.0-20260528044221-ge0e19fa`](https://www.npmjs.com/package/@ampcode/sdk/v/0.1.0-20260528044221-ge0e19fa)数字 :

```bash
npm install @ampcode/sdk@0.1.0-20260528044221-ge0e19fa
```

SDK需要一个Amp CLI版本,该版本至少是被您SDK发布所支撑的版本. 狦 组织通过Homebrew,Artifactory或另一个内部分配通道安装 AMP CLI, 您可以继续使用该安装,只要其版本足够新.

安装后, 请将您的 API 密钥添加到环境中 。 您可以访问您的 API 密钥 [安全设置](https://ampcode.com/settings/security#access-token)。 。 。 .

```bash
export AMP_API_KEY=sgamp_your_api_key_here
```

### 您的第一个 AMP 命令

现在您已经安装了 SDK 并设置了您的 API 密钥, 您可以开始使用 Amp `execute()` 函数 :

```typescript
import { execute } from '@ampcode/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
    }
}
```

这个 `execute()` 函数仅需要您提供 `prompt` 要开始。 SDK 串流消息作为代理工作,让你处理响应并直接将其集成到您的应用程序中.

## 核心概念

### 信件流

在您的代理执行时, SDK 流出不同类型的消息 :

```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)
    }
}
```

### 简单结果提取

当你只需要最后的结果而不处理流:

```typescript
async function getResult(prompt: string): Promise<string> {
    for await (const message of execute({ prompt })) {
        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)
}
```

### 线条连续性

继续跨越多种互动的对话 :

```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)
    }
}
```

## 常见配置

### 工作目录

指定 Amp 运行位置 :

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

### 启用调试日志

看看车盖下面发生了什么

```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
}
```

### 代理模式

选择要使用的代理模式 。 模式控制模型、系统提示和工具选择 :

```typescript
for await (const message of execute({
    prompt: 'Quickly fix this typo',
    options: {
        mode: 'low', // Use low mode for faster responses
    },
})) {
    // Process messages
}
```

可用模式 :

-   `low`: 快速、低成本模式,用于定义清晰的小型任务
-   `medium` (默认):大多数任务的默认,平衡质量,速度和成本
-   `high`: 用于需要更深入推理并能容忍更多时间和成本的困难任务
-   `ultra`: 当最大能力比速度或成本更重要时,用于最困难的开放式任务

### 努力的理由

设置支持模式的模型推理工作 :

```typescript
for await (const message of execute({
    prompt: 'Think carefully and explain your plan before coding.',
    options: {
        mode: 'medium',
        effort: 'high',
    },
})) {
    if (message.type === 'result') {
        console.log(message.result)
        break
    }
}
```

现有努力水平:

-   `none`
-   `minimal`
-   `low`
-   `medium`
-   `high`
-   `xhigh`
-   `max`

### 线索标签

将标签添加到线程中 `execute()`。 。 。 .

```typescript
for await (const message of execute({
    prompt: 'Summarize this repo',
    options: {
        labels: ['sdk', 'summary'],
    },
})) {
    if (message.type === 'result') {
        console.log(message.result)
        break
    }
}
```

### 线索标题

创建线程时设定标题 。 您无法使用 `title` 当继续一条线.

```typescript
for await (const message of execute({
    prompt: 'Review pull request 42',
    options: {
        executor: 'orb',
        title: 'Review acme/widgets#42',
    },
})) {
    if (message.type === 'result') {
        console.log(message.result)
        break
    }
}
```

### 远程执行器

默认情况下,代理运行在本地 APP CLI 进程中. 设定 `executor: 'orb'` 运行在 Amp 中 云沙盒,或 `executor: 'runner'` 与 `runnerId` 运行在您启动的 AMP CLI 跑取器上 与 `amp --no-tui --runner-id <id>`在这两种情况下,地方进程只产生结果. 要求数 `AMP_API_KEY`。 。 。 .

```typescript
for await (const message of execute({
    prompt: 'Run the integration tests and summarize any failures',
    options: {
        executor: 'runner',
        runnerId: 'build-box-1',
        runnerDir: '/home/build/code/my-project',
    },
})) {
    if (message.type === 'result') {
        console.log(message.result)
        break
    }
}
```

`runnerDir` 选择一个由跑者服务的绝对目录。 开始跑步 与 `--dir /home/build/code/my-project`,或者通过跑道发现来注册目录,或者 `amp runner dirs add`。关闭使用跑者起始目录的选项. 每个线程都有一个工作目录. 要在多个目录中运行, 请分别 `execute()` 打电话 继续线程保留其已存在的目录并忽略此选项 . `cwd` 只设定 本地 CLI 子进程目录; 它不选择运行器上的目录.

`project` 仅适用于 `executor: 'orb'`。 。 。 . 只有本地选项( O)`permissions`, (中文(简体) ), `enabledTools`, (中文(简体) ), `skills`, (中文(简体) ), `mcpConfig`, (中文(简体) ), `dangerouslyAllowAll`(中文(简体) ) 而流出输入提示不适用于远程执行器。 插件代理模式必须装入 跑垒的.

### 线索可见度

控制谁可以看到线程由 `execute()`数字 :

```typescript
for await (const message of execute({
    prompt: 'Analyze this private codebase',
    options: {
        visibility: 'private', // Only you can see this thread
    },
})) {
    if (message.type === 'result') {
        console.log(message.result)
        break
    }
}
```

可用可见度 :

-   `workspace` (默认):所有工作空间成员可见
-   `private`: 只有你看得见
-   `unlisted`: 任何有链接的人都能看到
-   `group`: 显示您的用户组成员( 企业)

### 工具权限

使用一个 [自定义插件](https://ampcode.com/docs/customize/plugins#example-plugin-permissions) 用于控制工具的使用. 工作空间管理员可以将其作为一个 [全局工作空间插件](https://ampcode.com/docs/customize/global-plugins-and-skills#publish-for-everyone)。 。 。 .

## 高级使用

### 互动进展跟踪

用于构建显示实时进度的用户界面:

```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)
            }
        }
    }
}
```

### 取消和超时

优雅地处理长期运作:

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

    try {
        for await (const message of execute({
            prompt,
            signal,
        })) {
            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(模式背景协议) 整合

使用自定义工具和数据源扩展 Amp 的能力 :

```typescript
import { execute, type MCPConfig } from '@ampcode/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: '${DATABASE_URL}' },
    },
}

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

偏爱 `${VAR}` 用于连接字符串和 API 令牌等秘密的占位符。 Amp在启动每个 MCP 服务器时从它的环境下扩展它们,所以秘密值从不需要出现在配置本身中. 占位符在 stdio 工作 `command`, (中文(简体) ), `args`,以及 `env` 在远程服务器中 `url` 财务报告和审定财务报表 `headers` 数值.

要了解更多关于使用 MCP 服务器扩展 Amp 的信息, 请访问 [MCP 配置](https://ampcode.com/docs/customize/mcp) 部分.

### 多回合对话

使用同步生成器构建流式对话框 :

```typescript
import { execute, createUserMessage } from '@ampcode/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)
    }
}
```

### 设置文件配置

配置 Amp 设置文件的行为, 如 `settings.json`。 您可以为 Amp 提供您在工程中保存的自定义设置文件 :

```typescript
import { execute } from '@ampcode/sdk'

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

示例 `settings.json`数字 :

```json
{
    "amp.mcpServers": {
        "playwright": {
            "command": "npx",
            "args": ["-y", "@playwright/mcp@latest", "--headless", "--isolated"]
        }
    },
    "amp.tools.disable": ["web_search", "mcp__playwright__browser_resize"]
}
```

要找到所有可用的设置,请参见 [配置设置](https://ampcode.com/docs/cli/settings)。 。 。 .

### 自定义技能

从指定的目录装入自定义技能 :

```typescript
for await (const message of execute({
    prompt: 'Use my custom deployment skill',
    options: {
        skills: './my-skills', // Path to custom skills directory
    },
})) {
    // Process messages
}
```

要多学习如何创造定制技能,请参看 [代理技能](https://ampcode.com/docs/customize/skills) amp文档的章节.

## 职能

### 执行( )

在程序上执行 AMP CLI 命令的主要功能.

```typescript
function execute(options: ExecuteOptions): AsyncIterable<StreamMessage>
```

#### 参数

-   `options` (单位:千美元)[`ExecuteOptions`](https://npmcn.com/package/%40ampcode/sdk/#readme-executeoptions)) - 执行配置

#### 回返

-   `AsyncIterable<StreamMessage>` - Amp CLI 的讯息流

#### 示例

```typescript
import { execute } from '@ampcode/sdk'

for await (const message of execute({
    prompt: 'Analyze this codebase',
    options: {
        cwd: './my-project',
    },
})) {
    if (message.type === 'assistant') {
        console.log('Assistant:', message.message.content)
    } else if (message.type === 'result') {
        console.log('Final result:', message.result)
        break
    }
}
```

### 创建 UserMessage ()

帮助器功能为流畅的对话创建适当的格式化的用户输入消息.

```typescript
function createUserMessage(text: string, options?: { requestId?: string }): UserInputMessage
```

#### 参数

-   `text` (单位:千美元)`string`) - 用户消息的文本内容
-   `options.requestId` (单位:千美元)`string`,可选) - A 1–256字符ID. 重用它进行重试 相同的线程可以防止 Amp 创建另一个用户消息.

#### 回返

-   [`UserInputMessage`](https://npmcn.com/package/%40ampcode/sdk/#readme-userinputmessage) - 格式化用户输入信息

#### 示例

```typescript
import { createUserMessage } from '@ampcode/sdk'

const message = createUserMessage('Analyze this code', { requestId: 'analysis-123' })
console.log(message)
// Output: { type: 'user', requestId: 'analysis-123', message: { role: 'user', content: [{ type: 'text', text: 'Analyze this code' }] } }
```

### 线程. new ()

创建新空线索并返回其ID .

```typescript
async function threads.new(options?: ThreadsNewOptions): Promise<string>
```

#### 参数

-   `options` (单位:千美元)[`ThreadsNewOptions`](https://npmcn.com/package/%40ampcode/sdk/#readme-threadsnewoptions),可选) - 新线程配置

#### 回返

-   `Promise<string>` - 线程标识

#### 示例

```typescript
import { threads } from '@ampcode/sdk'

// Create a new private thread
const threadId = await threads.new({ visibility: 'private' })
console.log('Created thread:', threadId)
```

### 线程. markdown ()

得到一条线导出 作为标记下.

```typescript
async function threads.markdown(options: ThreadsMarkdownOptions): Promise<string>
```

#### 参数

-   `options` (单位:千美元)[`ThreadsMarkdownOptions`](https://npmcn.com/package/%40ampcode/sdk/#readme-threadsmarkdownoptions)\- 包含线程ID的选项

#### 回返

-   `Promise<string>` - 线程内容作为标记下

#### 示例

```typescript
import { threads } from '@ampcode/sdk'

// Get thread content as markdown
const markdown = await threads.markdown({ threadId: 'T-abc123-def456' })
console.log(markdown)
```

### 线程. set多玩家( )

打开或关闭一条贡献线条(多玩家). 只工作于有共享(非私有)能见度的 Orb 线程和共享-runner 线程,并且只用于线程所有者.

```typescript
async function threads.setMultiplayer(options: ThreadsSetMultiplayerOptions): Promise<void>
```

#### 参数

-   `options` (单位:千美元)[`ThreadsSetMultiplayerOptions`](https://npmcn.com/package/%40ampcode/sdk/#readme-threadssetmultiplayeroptions)) - 线程ID,启用的旗帜,以及可选的打开窗口持续时间

#### 回返

-   `Promise<void>`

#### 示例

```typescript
import { threads } from '@ampcode/sdk'

// Open a thread for contributions for the default duration (currently 3 hours)
await threads.setMultiplayer({ threadId: 'T-abc123-def456' })

// Open a thread for contributions for 12 hours
await threads.setMultiplayer({ threadId: 'T-abc123-def456', hours: 12 })

// Close a thread for contributions
await threads.setMultiplayer({ threadId: 'T-abc123-def456', enabled: false })
```

## 类型

### 执行选项

配置选项 `execute()` 函数.

```typescript
interface ExecuteOptions {
    prompt: string | AsyncIterable<UserInputMessage>
    options?: AmpOptions
    signal?: AbortSignal
}
```

#### 属性

| 财产 | 类型 | 需求 | 说明 |
| --- | --- | --- | --- |
| `prompt` | `string | AsyncIterable<UserInputMessage>` | 对 | 输入提示作为多回合对话用户消息的字符串或同步 |
| `options` | [`AmpOptions`](https://npmcn.com/package/%40ampcode/sdk/#readme-ampoptions) | 没有 | CLI 配置选项 |
| `signal` | `AbortSignal` | 没有 | 用于取消支持的信号 |

### 选项

配置映射到 AMP CLI 旗的选项 .

```typescript
interface AmpOptions {
    cwd?: string
    mode?: string // Prefer 'low', 'medium', 'high', or 'ultra'
    effort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'
    noArchiveAfterExecute?: boolean
    visibility?: 'private' | 'unlisted' | 'workspace' | 'group'
    settingsFile?: string
    logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'audit'
    logFile?: string
    mcpConfig?: string | MCPConfig
    env?: Record<string, string>
    continue?: boolean | string
    skills?: string
    enabledTools?: string[]
    labels?: string[]
    thinking?: boolean
    executor?: 'local' | 'orb' | 'runner'
    runnerId?: string
    runnerDir?: string
    project?: string
    title?: string
}
```

内置模式是 `'low'`, (中文(简体) ), `'medium'`, (中文(简体) ), `'high'`,以及 `'ultra'`。也可以通过 自定义插件定义模式的字符串 .

#### 属性

| 财产 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `cwd` | `string` | `process.cwd()` | 本地 CLI 子进程的工作目录 |
| `mode` | `string` | `'medium'` | 代理模式。 偏爱 `'low'`, (中文(简体) ), `'medium'`, (中文(简体) ), `'high'`,或 `'ultra'`; 自定义插件定义模式字符串也被接受 |
| `effort` | `'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'` | \- 说吧 | 支助模式的合理努力 |
| `noArchiveAfterExecute` | `boolean` | `false` | 执行完成后保留新执行线索未存档 |
| `visibility` | `'private' | 'unlisted' | 'workspace' | 'group'` | `'workspace'` | 线索可见度 |
| `settingsFile` | `string` | \- 说吧 | 自定义设置文件路径 |
| `logLevel` | `'debug' | 'info' | 'warn' | 'error' | 'audit'` | `'info'` | 记录动词级别 |
| `logFile` | `string` | \- 说吧 | 写入日志的路径 |
| `continue` | `boolean | string` | `false` | 继续最近线索( N)`true`)或特定线程由ID(`string`(中文(简体) ) |
| `mcpConfig` | `string | MCPConfig` | \- 说吧 | MCP 服务器配置为 JSON 字符串, 或配置对象 |
| `env` | `Record<string, string>` | \- 说吧 | 其他环境变量 |
| `skills` | `string` | \- 说吧 | 带有自定义技能的文件夹路径 |
| `enabledTools` | `string[]` | \- 说吧 | 启用的工具名称模式(图) `amp.tools.enable`(中文(简体) ) |
| `labels` | `string[]` | \- 说吧 | 要添加到线程中的标签 |
| `thinking` | `boolean` | `false` | 在结果流中包含思维块 |
| `executor` | `'local' | 'orb' | 'runner'` | `'local'` | 在本地的 CLI 进程、 远程 或 AMP CLI 运行 |
| `runnerId` | `string` | \- 说吧 | 新建跑道线程的运行者 ID; 需要 `executor: 'runner'` |
| `runnerDir` | `string` | \- 说吧 | 用于新运行线程的已服务目录的绝对路径; 需要 `executor: 'runner'` |
| `project` | `string` | 推断 | 新 Orb 线程的 mp 工程; 需要 `executor: 'orb'` |
| `title` | `string` | \- 说吧 | 新线程的标题, 最多256个字符 |

## 信件类型

SDK在执行期间流出各种消息类型. 所有消息都执行基础 `StreamMessage` 类型.

### 系统信息

包含会话信息和可用工具的初始信息.

```typescript
interface SystemMessage {
    type: 'system'
    subtype: 'init'
    session_id: string
    cwd: string
    tools: string[]
    mcp_servers: Array<{
        name: string
        status: 'connected' | 'connecting' | 'connection-failed' | 'disabled'
    }>
}
```

#### 属性

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `session_id` | `string` | 执行会话的唯一标识符 |
| `cwd` | `string` | 当前工作目录 |
| `tools` | `string[]` | 可用工具名称列表 |
| `mcp_servers` | `Array<{name: string, status: string}>` | MCP服务器的状况 |

### 助理秘书

AI助理回应,包含文本内容和工具使用.

```typescript
interface AssistantMessage {
    type: 'assistant'
    session_id: string
    message: {
        id: string
        type: 'message'
        role: 'assistant'
        model: string
        content: Array<TextContent | ToolUseContent>
        stop_reason: 'end_turn' | 'tool_use' | 'max_tokens' | null
        stop_sequence: string | null
        usage?: Usage
    }
    parent_tool_use_id: string | null
}
```

#### 属性

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `session_id` | `string` | 执行会话的唯一标识符 |
| `message` | `object` | 助理的信息内容 |
| `parent_tool_use_id` | `string | null` | 如果这是工具响应, 则使用父工具的标识 |

### 用户信息

用户输入和工具结果.

```typescript
interface UserMessage {
    type: 'user'
    session_id: string
    message: {
        role: 'user'
        content: Array<TextContent | ToolResultContent>
    }
    parent_tool_use_id: string | null
}
```

#### 属性

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `session_id` | `string` | 执行会话的唯一标识符 |
| `message` | `object` | 用户信件内容 |
| `parent_tool_use_id` | `string | null` | 如果这是工具响应, 则使用父工具的标识 |

### 结果

最终成功执行结果.

```typescript
interface ResultMessage {
    type: 'result'
    subtype: 'success'
    session_id: string
    is_error: false
    result: string
    duration_ms: number
    num_turns: number
    usage?: Usage
    permission_denials?: string[]
}
```

#### 属性

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `session_id` | `string` | 执行会话的唯一标识符 |
| `result` | `string` | 助理的最后结果 |
| `duration_ms` | `number` | 总执行时间( 毫秒) |
| `num_turns` | `number` | 对话次数 |
| `usage` | [`Usage`](https://npmcn.com/package/%40ampcode/sdk/#readme-usage) | 脚本使用信息 |
| `permission_denials` | `string[]` | 被拒绝的权限列表 |

### 错误结果

显示执行失败的最终出错结果 .

```typescript
interface ErrorResultMessage {
    type: 'result'
    subtype: 'error_during_execution' | 'error_max_turns'
    session_id: string
    is_error: true
    error: string
    duration_ms: number
    num_turns: number
    usage?: Usage
    permission_denials?: string[]
}
```

#### 属性

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `session_id` | `string` | 执行会话的唯一标识符 |
| `error` | `string` | 描述出错的错误消息 |
| `duration_ms` | `number` | 总执行时间( 毫秒) |
| `num_turns` | `number` | 对话次数 |
| `usage` | [`Usage`](https://npmcn.com/package/%40ampcode/sdk/#readme-usage) | 脚本使用信息 |
| `permission_denials` | `string[]` | 被拒绝的权限列表 |

### 文本关联

纯文本内容块.

```typescript
interface TextContent {
    type: 'text'
    text: string
}
```

### 工具使用关联

工具执行请求 .

```typescript
interface ToolUseContent {
    type: 'tool_use'
    id: string
    name: string
    input: Record<string, unknown>
}
```

### 工具结果关联

工具执行的结果 .

```typescript
interface ToolResultContent {
    type: 'tool_result'
    tool_use_id: string
    content: string
    is_error: boolean
}
```

### 使用量

从API电话调用和计费信息.

```typescript
interface Usage {
    input_tokens: number
    cache_creation_input_tokens?: number
    cache_read_input_tokens?: number
    output_tokens: number
    service_tier?: string
}
```

#### 属性

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `input_tokens` | `number` | 使用的输入符数 |
| `cache_creation_input_tokens` | `number` | 用于缓存创建的托肯 |
| `cache_read_input_tokens` | `number` | 从缓存读取鼠标 |
| `output_tokens` | `number` | 生成输出符数 |
| `service_tier` | `string` | 用于此请求的服务级别 |

## 输入类型

### 用户输入信

用于流媒体对话的已格式化用户输入消息 .

```typescript
interface UserInputMessage {
    type: 'user'
    requestId?: string
    message: {
        role: 'user'
        content: Array<{
            type: 'text'
            text: string
        }>
    }
}
```

### MCPONFIG 中东欧

MCP(模式上下文协议)服务器配置 。 支持基于stdio和基于HTTP的服务器.

```typescript
type MCPConfig = Record<string, MCPServer>

// MCPServer is a union of stdio and HTTP server configurations
```

`MCPServer` 接受一个 stdio 服务器配置( 使用 `command`)或 HTTP 服务器配置(与 `url`:

```typescript
const mcpConfig: MCPConfig = {
    playwright: { command: 'npx', args: ['-y', '@playwright/mcp'] },
    remote: { url: 'https://api.example.com/mcp' },
}
```

#### MCPServer 属性

**Stdio 服务器 :**

| 财产 | 类型 | 需求 | 说明 |
| --- | --- | --- | --- |
| `command` | `string` | 对 | 启动 MCP 服务器的命令 |
| `args` | `string[]` | 没有 | 命令行参数 |
| `env` | `Record<string, string>` | 没有 | 服务器的环境变量 |
| `disabled` | `boolean` | 没有 | 此服务器是否被禁用 |

**HTTP 服务器 :**

| 财产 | 类型 | 需求 | 说明 |
| --- | --- | --- | --- |
| `url` | `string` | 对 | HTTP MCP 服务器的 URL |
| `headers` | `Record<string, string>` | 没有 | 随请求发送的 HTTP 信头 |
| `transport` | `string` | 没有 | 运输类型(如"sse") |
| `oauth` | `object` | 没有 | 认证的 OAuth 配置 |
| `disabled` | `boolean` | 没有 | 此服务器是否被禁用 |

**OAuth 配置( 用于 HTTP 服务器) :**

| 财产 | 类型 | 需求 | 说明 |
| --- | --- | --- | --- |
| `clientId` | `string` | 对 | OAuth 客户端标识 |
| `clientSecret` | `string` | 没有 | OAuth 客户端秘密 |
| `authUrl` | `string` | 对 | OAuth 授权 URL |
| `tokenUrl` | `string` | 对 | OAuth 代号 URL |
| `scopes` | `string[]` | 没有 | 授权范围 |
| `redirectUrl` | `string` | 没有 | OAuth 重定向 URL |

### 新选项

创建新线程的选项 .

```typescript
interface ThreadsNewOptions {
    visibility?: 'private' | 'unlisted' | 'workspace' | 'group'
}
```

#### 属性

| 财产 | 类型 | 需求 | 说明 |
| --- | --- | --- | --- |
| `visibility` | `'private' | 'unlisted' | 'workspace' | 'group'` | 没有 | 线索可见度 |

### 线索马克倒置选项

获取线程标记的选项 .

```typescript
interface ThreadsMarkdownOptions {
    threadId: string
}
```

#### 属性

| 财产 | 类型 | 需求 | 说明 |
| --- | --- | --- | --- |
| `threadId` | `string` | 对 | 线程标识以获得下标记 |

### 线索设置多玩家选项

为贡献打开或关闭线索的选项(多玩家). 期限选项为总和;总数必须在5分钟至7天之间。 何时 `enabled` 实值 `true` 而不给出持续时间,则使用服务器默认值(目前为3小时). 当 `enabled` 实值 `false`。 。 。 .

```typescript
interface ThreadsSetMultiplayerOptions {
    threadId: string
    enabled?: boolean
    minutes?: number
    hours?: number
    days?: number
    weeks?: number
}
```

#### 属性

| 财产 | 类型 | 需求 | 说明 |
| --- | --- | --- | --- |
| `threadId` | `string` | 对 | 要更新的线程 ID |
| `enabled` | `boolean` | 没有 | 是否打开供稿线索( 默认) `true`(中文(简体) ) |
| `minutes` | `number` | 没有 | 开放窗口持续时间(分钟) |
| `hours` | `number` | 没有 | 开放窗口持续时间(小时) |
| `days` | `number` | 没有 | 开放窗口持续天数 |
| `weeks` | `number` | 没有 | 开放窗口持续时间(周) |

## 所需资源

-   节点.js 18或以上

## 常见问题

### @ampcode/sdk 是什么？

TypeScript SDK for Amp CLI - 构建具有 Amp 能力的自定义 AI 代理

### 如何安装 @ampcode/sdk？

在项目目录运行 npm install @ampcode/sdk，或使用 pnpm add / yarn add / bun add。它还提供命令行工具 amp-sdk，可以用 npx amp-sdk 直接运行。

### @ampcode/sdk 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @ampcode/sdk 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @ampcode/sdk 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @ampcode/sdk 可以商用吗？

@ampcode/sdk 使用 Amp Commercial License 许可。声明的许可为 Amp Commercial License，请阅读许可原文确认使用条件。以上为概括，不构成法律意见，请以许可原文为准。

### @ampcode/sdk 的下载量有多少？

根据 npm 官方下载统计，@ampcode/sdk 在 2026/10/06 – 2026/11/04 这 30 天内被下载 27,638 次，日均约 921 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @ampcode/sdk 还在维护吗？

最新版本 0\.1\.0-20261028101623-g93a0da1 发布于 2026/10/28（8 天前）；至今共发布 101 个版本，其中过去 12 个月发布了 101 个；首次发布于 2026/05/13。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

