# https://github.com/anthropics/claude-agent-sdk-typescript 项目说明书

生成时间：2026-06-17 11:35:16 UTC

## 目录

- [Claude Agent SDK 简介与快速上手](#page-introduction)
- [可定制的 SessionStore 存储后端](#page-session-store)
- [会话恢复与历史消息检索](#page-session-resume)
- [子代理、工具集成与最新变更](#page-subagents-tools)

<a id='page-introduction'></a>

## Claude Agent SDK 简介与快速上手

### 相关页面

相关主题：[可定制的 SessionStore 存储后端](#page-session-store), [会话恢复与历史消息检索](#page-session-resume)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/README.md)
- [examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)
- [examples/session-stores/shared/conformance.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts)
- [examples/session-stores/s3/src/S3SessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/src/S3SessionStore.ts)
- [examples/session-stores/s3/src/index.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/src/index.ts)
- [examples/session-stores/redis/src/RedisSessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/src/RedisSessionStore.ts)
- [examples/session-stores/redis/src/index.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/src/index.ts)
- [examples/session-stores/postgres/src/PostgresSessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/src/PostgresSessionStore.ts)
- [examples/session-stores/postgres/demo.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/demo.ts)
- [examples/session-stores/s3/package.json](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/package.json)
- [examples/session-stores/redis/package.json](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/package.json)
- [examples/session-stores/postgres/package.json](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/package.json)
</details>

# Claude Agent SDK 简介与快速上手

## 项目概览

Claude Agent SDK 是 Anthropic 官方发布的 TypeScript / JavaScript SDK，用于以编程方式构建具备 Claude Code 能力的 AI 代理。该 SDK 让开发者能够创建可理解代码库、编辑文件、运行命令并执行复杂工作流的自主代理，其核心入口为异步可迭代的 `query()` 函数。

资料来源：[README.md:1-15]()

SDK 此前名为 "Claude Code SDK"，迁移到现名称时引入了破坏性变更；官方提供迁移指南供现有用户参考。

资料来源：[README.md:17-25]()

## 安装与基础用法

### 安装

通过 npm 安装：

```sh
npm install @anthropic-ai/claude-agent-sdk
```

资料来源：[README.md:9-15]()

### 最简示例

以下示例改编自 PostgreSQL 适配器的 demo 文件，演示了 `query()` 的典型用法：通过 `prompt` 字段传入用户输入，遍历消息流并提取 `session_id` 以备后续 `resume` 使用。

资料来源：[examples/session-stores/postgres/demo.ts:1-30]()

```typescript
import { query } from '@anthropic-ai/claude-agent-sdk'

const sessionMessages = []
let sessionId: string | undefined

for await (const message of query({ prompt: 'Reply with exactly the word: pineapple' })) {
  if (message.type === 'system' && message.subtype === 'init') {
    sessionId = message.session_id
  }
  if (message.type === 'result') {
    console.log(`[${message.subtype}]`, 'result' in message ? message.result : '')
  }
  sessionMessages.push(message)
}
```

## 会话管理与自定义存储后端

### SessionStore 接口

SDK 默认将会话数据存储于本地路径 `~/.claude/projects/{cwd-path-with-dashes}/{sessionId}.jsonl`，这一硬编码路径在云原生与 Kubernetes 部署中存在挑战。仓库通过 `examples/session-stores/` 提供了三种参考实现：S3、Redis、Postgres，它们均实现 `SessionStore` 协议并通过 `shared/conformance.ts` 中定义的 13 条行为契约进行验证。

资料来源：[examples/session-stores/README.md:1-30]() 资料来源：[examples/session-stores/shared/conformance.ts:1-50]()

### 后端适配器对照

| 适配器 | 后端客户端 | 单元测试 | 实时测试 |
| --- | --- | --- | --- |
| `s3/` | `@aws-sdk/client-s3` | 进程内 mock | 环境变量触发 (`SESSION_STORE_S3_*`) |
| `redis/` | `ioredis` | 进程内 mock | 环境变量触发 (`SESSION_STORE_REDIS_URL`) |
| `postgres/` | `pg` | 仅构造器 | 环境变量触发 (`SESSION_STORE_POSTGRES_URL`) |

资料来源：[examples/session-stores/README.md:1-30]() 资料来源：[examples/session-stores/s3/package.json:1-20]() 资料来源：[examples/session-stores/redis/package.json:1-20]() 资料来源：[examples/session-stores/postgres/package.json:1-20]()

### Redis 键空间设计

`RedisSessionStore` 使用 `:` 作为键分隔符，避免与 SDK 的 `/` 风格 `projectKey` 冲突；保留位置用于子路径集合与项目级会话索引。

资料来源：[examples/session-stores/redis/src/RedisSessionStore.ts:1-30]()

```
{prefix}:{projectKey}:{sessionId}             list   主转录条目 (JSON)
{prefix}:{projectKey}:{sessionId}:{subpath}   list   子代理转录条目
{prefix}:{projectKey}:{sessionId}:__subkeys   set    该会话下的子路径
{prefix}:{projectKey}:__sessions              zset   sessionId → mtime(ms)
```

### 在 `query()` 中注入自定义存储

```typescript
import { S3Client } from '@aws-sdk/client-s3'
import { query } from '@anthropic-ai/claude-agent-sdk'
import { S3SessionStore } from './S3SessionStore.js'

const store = new S3SessionStore({
  bucket: 'my-claude-sessions',
  prefix: 'transcripts',
  client: new S3Client({ region: 'us-east-1' }),
})

for await (const message of query({
  prompt: 'Hello!',
  options: { sessionStore: store },
})) {
  if (message.type === 'result' && message.subtype === 'success') {
    console.log(message.result)
  }
}
```

资料来源：[examples/session-stores/s3/src/S3SessionStore.ts:1-50]() 资料来源：[examples/session-stores/s3/src/index.ts:1-2]()

## 工作流概览

```mermaid
sequenceDiagram
    participant App as 应用代码
    participant SDK as Claude Agent SDK
    participant Store as SessionStore
    participant CLI as Claude Code CLI

    App->>SDK: query({ prompt, options })
    SDK->>CLI: 启动子进程 (JSONL 流)
    CLI-->>SDK: 流式消息
    SDK->>Store: append(key, entries)
    SDK-->>App: yield message

    App->>SDK: query({ options: { resume: sessionId } })
    SDK->>Store: load(key)
    Store-->>SDK: 历史条目
    SDK-->>App: 续接会话
```

## 社区关注的常见问题

- **历史消息检索（Issue #14）**：`query({ options: { resume: sessionId } })` 续接会话时，SDK 仅流式传输新增消息，目前无法以编程方式检索历史对话。
- **异步子代理错误（Issue #130）**：异步子代理成功时 SDK 抛出 `only prompt commands are supported in streaming mode` 并以退出码 1 终止，影响 0.1.77 及之后到至少 0.2.5 的版本；同步子代理不受影响。
- **Zod v3 依赖（Issue #38）**：当前自定义工具回调要求 zod v3 依赖，v4 升级正在跟踪。
- **云端存储后端（Issue #97）**：默认本地文件路径难以适配云原生部署；`examples/session-stores/` 提供三种参考实现但**不在发布的 npm 包中**，需手动复制到项目中。
- **会话管理文档（Issue #3）**：官方文档未明确会话存储位置、如何更换后端，以及如何"重放"代理以恢复至特定状态。

资料来源：[examples/session-stores/README.md:1-30]()

## 参见

- 官方文档：https://docs.claude.com/en/api/agent-sdk/overview
- 迁移指南：https://docs.claude.com/en/docs/claude-code/sdk/migration-guide
- SessionStore 参考实现目录：[examples/session-stores/](https://github.com/anthropics/claude-agent-sdk-typescript/tree/main/examples/session-stores)
- 数据使用政策：https://docs.anthropic.com/en/docs/claude-code/data-usage

---

<a id='page-session-store'></a>

## 可定制的 SessionStore 存储后端

### 相关页面

相关主题：[Claude Agent SDK 简介与快速上手](#page-introduction), [会话恢复与历史消息检索](#page-session-resume)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)
- [examples/session-stores/shared/conformance.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts)
- [examples/session-stores/s3/src/S3SessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/src/S3SessionStore.ts)
- [examples/session-stores/s3/package.json](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/package.json)
- [examples/session-stores/redis/src/RedisSessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/src/RedisSessionStore.ts)
- [examples/session-stores/redis/package.json](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/package.json)
- [examples/session-stores/postgres/src/PostgresSessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/src/PostgresSessionStore.ts)
- [examples/session-stores/postgres/package.json](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/package.json)
- [examples/session-stores/postgres/demo.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/demo.ts)
</details>

# 可定制的 SessionStore 存储后端

## 概述与背景

`SessionStore` 是 `@anthropic-ai/claude-agent-sdk` 暴露的可插拔存储抽象，允许用户将对话转写（transcript）持久化到本地磁盘以外的存储介质。社区长期反馈（issue #3「Session management is not clearly documented and exposed」与 issue #97「Customizable Session Storage Backend for Cloud/Kubernetes Deployments」）指出，默认的本地 `~/.claude/projects/{cwd-path-with-dashes}/{sessionId}.jsonl` 路径在云原生、容器化或多实例部署场景下存在天然缺陷——它把无状态 Pod 强行绑死在本地文件系统上，阻碍水平扩展与跨节点恢复。

SDK 本身保持精简：通过 `query({ options: { sessionStore } })` 注入自定义实现，将 S3、Redis、Postgres 等可选重依赖排除在主包之外。官方在 `examples/session-stores/` 目录提供三套参考适配器，供用户直接复制或作为编写自有后端的模板。资料来源：[examples/session-stores/README.md:1-15]()

## 架构与目录组织

参考适配器以独立子包形式组织在 `examples/session-stores/` 下，遵循统一布局：

```
{s3,redis,postgres}/
  src/{Backend}SessionStore.ts   # 适配器实现
  src/index.ts                   # 类型与类导出
  test/                          # 单元 + env-gated 实时测试
  demo.ts                        # 可运行的 query() + resume 往返
  package.json
  tsconfig.json
shared/
  conformance.ts                 # 13 条契约的行为验证套件
```

三个后端的实现对照如下：

| 适配器 | 后端客户端 | 单元测试 | 实时测试触发 |
| --- | --- | --- | --- |
| `s3/` | `@aws-sdk/client-s3` | 内存 mock | 环境变量 `SESSION_STORE_S3_*` |
| `redis/` | `ioredis` | 内存 mock | `SESSION_STORE_REDIS_URL` |
| `postgres/` | `pg` | 仅构造函数 | `SESSION_STORE_POSTGRES_URL` |

资料来源：[examples/session-stores/README.md:18-30]()

```mermaid
graph LR
  A[query 调用方] -->|options.sessionStore| B[SessionStore 接口]
  B --> C[S3SessionStore]
  B --> D[RedisSessionStore]
  B --> E[PostgresSessionStore]
  B --> F[InMemorySessionStore/默认]
  C --> G[(S3 对象)]
  D --> H[(Redis List/Set/ZSet)]
  E --> I[(Postgres JSONB)]
```

## 三个参考适配器的实现要点

### S3 — `S3SessionStore.ts`

将转写条目写入 JSONL part 文件，键名形如 `s3://{bucket}/{prefix}{projectKey}/{sessionId}/part-{epochMs13}-{rand6}.jsonl`。每次 `append()` 都生成新 part；`load()` 通过 `ListObjectsV2` 列举、`Delimiter: '/'` 限定为顶层 part 避免与子代理条目混叠，然后按名排序并拼接。子路径（subagent transcript）通过 S3 key 层级自然派生。资料来源：[examples/session-stores/s3/src/S3SessionStore.ts:50-130]()

### Redis — `RedisSessionStore.ts`

使用 `':'` 分隔的键方案（避免与 SDK 的 `/` projectKey 冲突）：

```
{prefix}:{projectKey}:{sessionId}             list   — 主转写条目（JSON）
{prefix}:{projectKey}:{sessionId}:{subpath}   list   — 子代理条目
{prefix}:{projectKey}:{sessionId}:__subkeys   set    — 该会话下的子路径
{prefix}:{projectKey}:__sessions              zset   — sessionId → mtime(ms)
```

每次 `append()` 在一个 `MULTI` 中完成 `RPUSH` 与索引更新；`load()` 直接 `LRANGE 0 -1`。主转写追加才更新 `__sessions` 索引，与 `InMemorySessionStore.listSessions()` 的「无 subpath」过滤以及 S3 适配器仅基于主 part 推导 mtime 的行为保持一致。资料来源：[examples/session-stores/redis/src/RedisSessionStore.ts:30-95]()

### Postgres — `PostgresSessionStore.ts`

单表设计，一张 JSONB 列表存储所有条目，排序由 `BIGSERIAL` 主键保证：

```sql
CREATE TABLE IF NOT EXISTS claude_session_entries (
  id          BIGSERIAL PRIMARY KEY,
  project_key TEXT NOT NULL,
  session_id  TEXT NOT NULL,
  subpath     TEXT,
  entry       JSONB NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
```

构造时通过正则 `/^[A-Za-z_][A-Za-z0-9_]*$/` 校验 `tableName`，防止 SQL 注入。需要在启动时显式调用 `ensureSchema()` 幂等建表。资料来源：[examples/session-stores/postgres/src/PostgresSessionStore.ts:15-60]()

## 契约与一致性验证

`shared/conformance.ts` 定义 13 条行为契约，覆盖 `append → load` 往返、多调用顺序、空数组无副作用、未知 key 返回 `null`、子路径行为、JSON 字段顺序无关等。任何新适配器只要通过此套件即视为满足 SDK 依赖的转写镜像与恢复语义。工厂函数需保证每次返回全新、隔离的存储实例（如唯一表名/键前缀）。资料来源：[examples/session-stores/shared/conformance.ts:1-60]()

```typescript
import { describe } from 'bun:test'
import { runSessionStoreConformance } from './conformance.ts'

describe('MyStore', () => {
  runSessionStoreConformance(async () => new MyStore(/* 全新隔离状态 */))
})
```

资料来源：[examples/session-stores/README.md:60-70]()

## 生产部署注意事项

参考代码非生产级。上线前需重点关注：

- **失败语义**：`append()` 失败被 SDK 记录为流式错误并上抛，不会阻塞会话流，但会产生「静默镜像缺口」，必须监控。资料来源：[examples/session-stores/README.md:80-90]()
- **保留策略**：SDK 不会主动删除条目，需后端自实现 TTL、S3 生命周期规则或 `DELETE WHERE created_at < ...` 等清理作业；Postgres 表会无界增长。
- **S3 时钟偏斜**：part 文件排序依赖客户端墙钟，多写入者存在时钟偏斜时需额外协调。所需 IAM 权限：`s3:PutObject`、`s3:GetObject`、`s3:ListBucket`、`s3:DeleteObject`。
- **本地副本独立**：`CLAUDE_CONFIG_DIR` 下的磁盘转写由 CLI 的 `cleanupPeriodDays` 单独管理，不与自定义 store 联动。

## 关联的社区诉求

- **历史消息回放（issue #14）**：恢复会话时 SDK 仅流式推送新消息；自定义 `SessionStore.load()` 是当前唯一可在恢复前读取完整历史的入口，自建后端可借此实现历史拉取。
- **Kubernetes 友好（issue #97）**：自定义 store 让 Pod 无状态化，会话数据外迁至共享后端，配合 resume API 可在任意节点上「重放」代理。
- **会话管理可发现性（issue #3）**：`SessionStore` 是文档中未被充分暴露的核心扩展点；正确实现 `listSessions()` 后即可构建原生「会话列表 UI」。

## See Also

- [issue #97：Cloud/Kubernetes 可定制存储后端](https://github.com/anthropics/claude-agent-sdk-typescript/issues/97)
- [issue #3：会话管理文档与可发现性](https://github.com/anthropics/claude-agent-sdk-typescript/issues/3)
- [issue #14：恢复会话时检索历史消息](https://github.com/anthropics/claude-agent-sdk-typescript/issues/14)

---

<a id='page-session-resume'></a>

## 会话恢复与历史消息检索

### 相关页面

相关主题：[Claude Agent SDK 简介与快速上手](#page-introduction), [可定制的 SessionStore 存储后端](#page-session-store)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/README.md)
- [examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)
- [examples/session-stores/shared/conformance.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts)
- [examples/session-stores/s3/src/S3SessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/src/S3SessionStore.ts)
- [examples/session-stores/redis/src/RedisSessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/src/RedisSessionStore.ts)
- [examples/session-stores/postgres/src/PostgresSessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/src/PostgresSessionStore.ts)
</details>

# 会话恢复与历史消息检索

## 概述

Claude Agent SDK 通过 `query()` 流式接口提供编程式 Agent 调用能力。在 `options.sessionStore` 与 `options.resume` 这两个选项背后，存在一套用于"会话恢复 (session resume)"与"历史消息检索 (historical message retrieval)"的存储协议 [`SessionStore`](https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk)。仓库在 `examples/session-stores/` 目录下提供了 S3、Redis、Postgres 三套**参考适配器**以及一份 13 项行为契约的一致性测试，用于把会话转录 (transcript) 镜像到任意后端（[README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/README.md)、[examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。

> 这些适配器位于 `examples/` 之下，不随 `@anthropic-ai/claude-agent-sdk` 主包发布，也不参与仓库 CI；它们通过拷贝目录的方式集成到用户项目中（[examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。

## SessionStore 协议契约

`SessionStore` 是一个**结构化**（structural typing）的接口，定义了 SDK 在转录镜像与恢复时依赖的全部读写操作。从一致性测试的本地类型副本可以直接读出其形状（[examples/session-stores/shared/conformance.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts)）：

| 方法 | 是否必选 | 行为 |
| --- | --- | --- |
| `append(key, entries)` | 必选 | 将一批 `SessionStoreEntry` 追加到指定 `SessionKey`，原子地写入主转录或子代理子路径 |
| `load(key)` | 必选 | 按顺序读取已写入的条目；不存在时返回 `null` |
| `listSessions(projectKey)` | 可选 | 返回该 project 下全部 `{ sessionId, mtime }` |
| `delete(key)` | 可选 | 删除主转录及全部子代理子路径；索引键须同步清理 |
| `listSubkeys({ projectKey, sessionId })` | 可选 | 枚举该会话下所有 subagent 子路径 |

`SessionKey = { projectKey, sessionId, subpath? }`，其中 `subpath` 缺省指向**主转录**，否则指向**子代理** (subagent) 的独立转录（[examples/session-stores/shared/conformance.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts)、[examples/session-stores/redis/src/RedisSessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/src/RedisSessionStore.ts)）。

## 数据流：写入、镜像与恢复

```mermaid
flowchart LR
    A["query() 流"] -->|"append(key, entries)"| B[(SessionStore 后端)]
    B -->|"load(key)"| C["历史消息流"]
    C -->|"render / replay"| D[消费方]
    B -->|"listSessions()"| E[会话索引]
    E -->|"挑选 sessionId"| A
```

主流程可概括为三步：① `query()` 在产生消息时调用 `append()` 把条目写入 store；② 用户可通过 `listSessions()` 拿到 `{ sessionId, mtime }` 列表并选中目标会话；③ 下一次 `query({ options: { resume: sessionId, sessionStore } })` 通过 `load()` 回放历史，从而让 Agent 在原有上下文上继续推进（[examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)、[examples/session-stores/shared/conformance.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts)）。

## 三种参考适配器

| 适配器 | 后端客户端 | 数据布局 | 一致性策略 |
| --- | --- | --- | --- |
| S3 ([`S3SessionStore.ts`](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/src/S3SessionStore.ts)) | `@aws-sdk/client-s3` | `{prefix}{projectKey}/{sessionId}/part-{epochMs13}-{rand6}.jsonl` | `load()` 列出 part 后**排序拼接**；同实例同毫秒用 `rand6` 后缀消歧（[examples/session-stores/s3/src/S3SessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/src/S3SessionStore.ts)）|
| Redis ([`RedisSessionStore.ts`](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/src/RedisSessionStore.ts)) | `ioredis` | `RPUSH` 至 list；`__subkeys` (set) 与 `__sessions` (zset) 作为索引键；单 `MULTI` 提交 | `append()` 在一个 `MULTI` 中完成 RPUSH 与索引更新（[examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）|
| Postgres ([`PostgresSessionStore.ts`](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/src/PostgresSessionStore.ts)) | `pg` (node-postgres) | 单表 `claude_session_entries (project_key, session_id, subpath, entry JSONB)`，`ensureSchema()` 幂等建表 | `load()` 用 `IS NOT DISTINCT FROM` 同时匹配 `subpath` 为 `NULL` 与具体值的情况（[examples/session-stores/postgres/src/PostgresSessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/src/PostgresSessionStore.ts)）|

所有适配器**都**实现 `listSubkeys()`，从而在恢复主会话时能枚举并回放其下子代理的转录（[examples/session-stores/s3/src/S3SessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/src/S3SessionStore.ts)、[examples/session-stores/redis/src/RedisSessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/src/RedisSessionStore.ts)）。

## 验证自定义适配器

`shared/conformance.ts` 提供 13 项行为契约的 `bun:test` 套件；接入时只需让工厂函数返回**隔离的、每次新构造**的 store 实例（[examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)、[examples/session-stores/shared/conformance.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts)）：

```ts
import { describe } from 'bun:test'
import { runSessionStoreConformance } from './conformance.ts'
import { MyStore } from './MyStore'

describe('MyStore', () => {
  runSessionStoreConformance(async () => new MyStore(/* 隔离状态 */))
})
```

需要注意：一致性套件只验证**正确性**而不验证**弹性**，需自行压测；`append()` 失败会被记录并以流错误形式上抛，**不会**阻塞对话，因此生产环境应监控这些错误以避免"沉默镜像缺口"（[examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。

## 已知限制与社区讨论

- **历史消息检索 API 缺失**（社区 #14）：当通过 `query({ options: { resume: sessionId } })` 恢复会话时，SDK 仅流式产出**新**消息，目前没有官方 API 直接回放历史 `SessionStoreEntry`；消费者必须自己持有 `sessionStore` 并调用 `load()` 拿到完整转录后自行渲染（[examples/session-stores/s3/src/S3SessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/src/S3SessionStore.ts)）。
- **会话存储后端硬编码**（社区 #97、#3）：CLI 默认把转录写到 `~/.claude/projects/{cwd-path-with-dashes}/{sessionId}.jsonl`，云原生 / Kubernetes 等无盘环境必须通过自定义 `SessionStore` 接管；这是当前参考适配器存在的主要动机（[examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。
- **保留策略**：SDK 不会主动 `delete()` 你的存储，需要自行实现 TTL 或生命周期策略；CLI 端的 `CLAUDE_CONFIG_DIR` 转录则由 `cleanupPeriodDays` 独立清理（[examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。
- **写入时钟假设**（S3）：S3 适配器使用**客户端墙钟**对 part 文件排序，多写者时钟偏移可能破坏顺序（[examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。

## See Also

- [README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/README.md) — SDK 总览与安装
- [examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md) — SessionStore 适配器使用与生产清单
- [examples/session-stores/shared/conformance.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts) — 13 项行为契约一致性套件

---

<a id='page-subagents-tools'></a>

## 子代理、工具集成与最新变更

### 相关页面

相关主题：[Claude Agent SDK 简介与快速上手](#page-introduction)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/README.md)
- [examples/session-stores/README.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)
- [examples/session-stores/shared/conformance.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts)
- [examples/session-stores/s3/src/S3SessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/src/S3SessionStore.ts)
- [examples/session-stores/redis/src/RedisSessionStore.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/src/RedisSessionStore.ts)
- [examples/session-stores/postgres/demo.ts](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/demo.ts)
- [examples/session-stores/s3/package.json](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/s3/package.json)
- [examples/session-stores/redis/package.json](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/package.json)
- [examples/session-stores/postgres/package.json](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/postgres/package.json)
</details>

# 子代理、工具集成与最新变更

## 概述

本页聚焦 Claude Agent SDK 的三个交叉主题：异步子代理（async subagent）执行模式与已知缺陷、工具调用在消息流中的呈现形态、以及社区最关注的可插拔会话存储后端。底层 SDK 包通过 `query()` 提供流式消息接口（[README.md:9](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/README.md)），而 `examples/session-stores/` 目录则提供 S3、Redis、Postgres 三种参考适配器，供用户在云原生或 Kubernetes 环境下替换默认的本地文件系统存储（[examples/session-stores/README.md:5-9](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。

## 子代理与异步执行

社区 issue #130 报告：当一个**异步子代理**执行成功后，Agents SDK 会抛出 `only prompt commands are supported in streaming mode` 错误，并以退出码 1 终止进程。同步子代理不受影响。问题的首个故障版本为 `0.1.77`，截至 `0.2.5` 仍存在。该缺陷直接影响在 TypeScript 中通过 `query()` 启动后台 agent 后等待通知的场景。

为缓解此问题，最新版本 v0.3.179 的发布说明中提到："Fixed `-p` mode exiting before a completed background agent's notification was delivered, causing interim text to ship as the final result"，即 CLI 会在后台 agent 完成通知送达后才结束 `-p` 模式的会话（社区上下文 - Latest Release v0.3.179）。开发者在编写 TypeScript 调用方时仍应主动监听流消息中 `type === 'result'` 的最终消息，并在业务层对退出码做兜底处理。

## 工具集成与消息形态

### `tool_use_meta` 侧车字段

v0.3.179 新增了 assistant 消息的可选 `tool_use_meta` 侧车对象，用于提供工具调用的"展示友好名"，让 SDK 消费者在 UI 层渲染人类可读标签而无需自行映射原始的线协议名称（社区上下文 - Latest Release v0.3.179）。该字段对调用方完全可选，旧版消费者在反序列化时不会因此报错。

### 自定义工具回调与 zod 版本

社区 issue #38 追踪 SDK 当前要求 `zod@3` 作为 peer 依赖，以支持自定义工具回调的 schema 校验。该 issue 是 zod 3 相关问题的汇总入口；当项目其余部分已升级到 zod 4 时，需要在升级 SDK 之前评估 schema 兼容性与运行时校验路径。

## 会话存储后端适配

`examples/session-stores/` 目录提供三套参考实现，均通过 `query({ options: { sessionStore } })` 接入。表格汇总了关键差异：

| 适配器 | 后端客户端 | 单元测试 | 实时测试门控 |
| --- | --- | --- | --- |
| `s3/` | `@aws-sdk/client-s3` | 进程内 mock | `SESSION_STORE_S3_*` |
| `redis/` | `ioredis` | 进程内 mock | `SESSION_STORE_REDIS_URL` |
| `postgres/` | `pg` | 仅构造期 | `SESSION_STORE_POSTGRES_URL` |

数据来源：[examples/session-stores/README.md:13-17](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)

每个适配器共享 `shared/conformance.ts` 中的 13 项行为契约（例如 `append then load returns same entries in same order`、`load unknown key returns null`、`multiple append calls preserve call order`、`append([]) is a no-op` 等）（[examples/session-stores/shared/conformance.ts:71-112](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts)）。该套件以 bun:test 运行，工厂函数每次调用须返回全新隔离存储（如唯一表名或键前缀）（[examples/session-stores/README.md:86-92](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。

下面以 Redis 适配器为例展示其键空间设计（[examples/session-stores/redis/src/RedisSessionStore.ts:21-29](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/redis/src/RedisSessionStore.ts)）：

```mermaid
flowchart LR
  PK["prefix:projectKey"] --> Main["sessionId (LIST, RPUSH)"]
  PK --> Sub["sessionId:subpath (LIST)"]
  PK --> IndexS["sessionId:__subkeys (SET)"]
  PK --> IndexZ["__sessions (ZSET, score=mtime)"]
```

`append()` 在单个 `MULTI` 中执行 `RPUSH` 与索引更新，`load()` 使用 `LRANGE 0 -1` 拉取全部条目。S3 适配器则按 JSONL 分片写入 `s3://{bucket}/{prefix}{projectKey}/{sessionId}/part-{epochMs13}-{rand6}.jsonl`，`load()` 通过列举、排序并拼接分片完成（[examples/session-stores/README.md:124-140](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。

## 关键使用模式与生产清单

- **会话回放（resume）**：通过 `query({ options: { resume: sessionId, sessionStore } })` 复用已有会话，但社区 issue #14 指出 SDK 尚不暴露历史消息的编程化读取接口，调用方需自行 `load()` 后再做合并渲染。
- **存储可靠性**：适配器仅保证**正确性**，不保证**韧性**；`append()` 失败仅记录并以流错误形式上报，不会阻塞会话（[examples/session-stores/README.md:96-104](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。
- **保留策略**：SDK 仅在显式调用 `delete()` 时清理数据，TTL 与生命周期由调用方负责；本地 CLI 的 `cleanupPeriodDays` 与远端存储相互独立。
- **运行示例**：`cd examples/session-stores/redis && npm install && npm test` 启动无需真实后端的单元测试；`npm run test:live` 则需要 `docker run -d -p 6379:6379 redis:7-alpine` 等前置服务（[examples/session-stores/README.md:60-73](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/README.md)）。

## 最新变更摘要（v0.3.179）

1. assistant 消息新增可选 `tool_use_meta` 侧车，提供工具调用的展示友好名。
2. 修复 `-p` 模式下后台 agent 完成通知未送达即退出的缺陷。
3. 修复远程（stream-json）会话在某些情况下持续显示为 busy 的问题。

## See Also

- 会话管理与 resume：docs/agent-sdk/sessions
- 自定义工具与 zod 校验升级路径：issue #38
- 异步子代理缺陷追踪：issue #130
- 云原生存储后端设计动机：issue #97

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：anthropics/claude-agent-sdk-typescript-agent-workflow

摘要：发现 8 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。

## 1. 身份坑 · 仓库名和安装名不一致

- 严重度：medium
- 证据强度：runtime_trace
- 发现：仓库名 `claude-agent-sdk-typescript-agent-workflow` 与安装入口 `@anthropic-ai/claude-agent-sdk` 不完全一致。
- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- 复现命令：`npm install @anthropic-ai/claude-agent-sdk`
- 证据：identity.distribution | https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk | repo=claude-agent-sdk-typescript-agent-workflow; install=@anthropic-ai/claude-agent-sdk

## 2. 配置坑 · 可能修改宿主 AI 配置

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 证据：capability.host_targets | https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk | host_targets=claude_code, claude

## 3. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 证据：capability.assumptions | https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk | README/documentation is current enough for a first validation pass.

## 4. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 证据：evidence.maintainer_signals | https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk | last_activity_observed missing

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 证据：downstream_validation.risk_items | https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk | no_demo; severity=medium

## 6. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 证据：risks.scoring_risks | https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk | no_demo; severity=medium

## 7. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 证据：evidence.maintainer_signals | https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk | issue_or_pr_quality=unknown

## 8. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 证据：evidence.maintainer_signals | https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk | release_recency=unknown

<!-- canonical_name: anthropics/claude-agent-sdk-typescript-agent-workflow; human_manual_source: deepwiki_human_wiki -->
