用SessionStore适配器把会话记录镜像到外部存储

Claude Agent SDK默认把会话记录写入本地JSONL文件,SessionStore适配器可将同一批记录转发到对象存储、键值库或数据库,使不同主机在相同工作目录下恢复会话,并让记录在容器重启后仍可读取。

默认情况下, SDK 将会话记录稿写入 JSONL 文件 `~/.claude/projects/` 在本地文件系统上。 `SessionStore` 适配器允许您将这些记录抄录到自己的后端, 如对象商店、 密钥值商店或数据库, 因此, 在一个主机上创建的会话可以从匹配的工作目录运行到另一个主机上 。 使用会话商店的常见理由 : - **多主机部署.** 没有服务器的功能,自动缩放的工人,以及CI的跑步者不会共享一个文件系统。共享的商店可以让复制品恢复彼此的会话。 - **达利布利.** 本地的容器是麻黄的,一个外部商店能够存活下来重启和重新部署。 - **合规与审计.** 将笔录保存在您已经管理的存储器中, 并有您自己的保存规则, 加密和访问控制 。 ## 那个... `SessionStore` 接口 A `SessionStore` 是一个具有两种要求方法的对象, `append` 财务报告和财务报告 `load`,以及四种可选方法。SDK呼叫 `append` 在查询时撰写记录条目, `load` 把它们读回来做简历。 ``` // Exported from @anthropic-ai/claude-agent-sdk as // SessionStore, SessionKey, SessionStoreEntry, SessionSummaryEntry. type SessionKey = { projectKey: string; sessionId: string; subpath?: string; }; type SessionStore = { // Required append(key: SessionKey, entries: SessionStoreEntry[]): Promise<void>; load(key: SessionKey): Promise<SessionStoreEntry[] | null>; // Optional listSessions?( projectKey: string, ): Promise<Array<{ sessionId: string; mtime: number }>>; listSessionSummaries?(projectKey: string): Promise<SessionSummaryEntry[]>; delete?(key: SessionKey): Promise<void>; listSubkeys?(key: { projectKey: string; sessionId: string; }): Promise<string[]>; }; type SessionSummaryEntry = { sessionId: string; mtime: number; data: Record<string, unknown>; }; ``` ``` # Exported from claude_agent_sdk as # SessionStore, SessionKey, SessionStoreEntry, SessionSummaryEntry. class SessionKey(TypedDict): project_key: str session_id: str subpath: NotRequired[str] class SessionStore(Protocol): # Required async def append( self, key: SessionKey, entries: list[SessionStoreEntry] ) -> None: ... async def load(self, key: SessionKey) -> list[SessionStoreEntry] | None: ... # Optional — omit or raise NotImplementedError async def list_sessions( self, project_key: str ) -> list[SessionStoreListEntry]: ... async def list_session_summaries( self, project_key: str ) -> list[SessionSummaryEntry]: ... async def delete(self, key: SessionKey) -> None: ... async def list_subkeys(self, key: SessionListSubkeysKey) -> list[str]: ... class SessionSummaryEntry(TypedDict): session_id: str mtime: int data: dict[str, Any] ``` `SessionKey` 地址是一份笔录 `projectKey` 是工作目录中一个稳定、文件系统安全的编码, `sessionId` 是会话 UUID,并且 `subpath` 当条目属于子代理记录或侧车厢文件而非主对话时,设置。因为 `projectKey` 在 TypeScript 中, 如果您设定了, 则将工作目录、 恢复或继续从商店中复制到匹配原始运行的工作目录。 [`CLAUDE_CODE_PROJECT_DIR_NAME`](<https://code.claude.com/docs/en/sessions#name-the-project-directory-yourself>) 旁边 `CLAUDE_CONFIG_DIR` 在查询中 [`env` 选项](<https://code.claude.com/docs/en/agent-sdk/typescript#options>),则查询条目的 SDK 键及其 `resume` 财务报告和财务报告 `continue` 以这个名字来称呼,因为像这样的独立助手 `listSessions` 财务报告和财务报告 `deleteSession` 带不带 `env` 并读取进程环境, 设置 `CLAUDE_CONFIG_DIR` 和主机进程环境中的相同名称。需要代理 SDK v0.3.234 或稍后。 `subpath` 作为不透明的密钥后缀; 它遵循了在线版式, 例如 `subagents/agent-<id>`时 `subpath` 未定义密钥是指主记录。 | 方法 | 要求数 | 何时打电话 | | --- | --- | --- | | `append` | 对 | 每批笔录条目在本地写完后,条目为JSON安全对象,本地JSONL中每行1个. | | `load` | 对 | 在子进程产生之前 `resume` 设置或 `continue: true` 解决最新的存储会话,并在上市时每会话返回一次 `listSessionSummaries`返回时 `null` 如果会话未知。 | | `listSessions` | 没有 | 以 `listSessions({ sessionStore })` 和通过 `query()`/`startup()` 与 `continue: true`如果未定义, `continue: true` 抛掷,和 `listSessions({ sessionStore })` 抛出,除非 `listSessionSummaries` 已执行。 | | `listSessionSummaries` | 没有 | 以 `listSessions({ sessionStore })` 。将摘要保存在内。 `append`。如果未定义,则列名将追溯到 `listSessions` 加上每次会议一次 `load`. | | `delete` | 没有 | 以 `deleteSession({ sessionStore })`。删除主密钥(否) `subpath`)必须连结到该会话的所有子密钥,并删除会话摘要条目,所以删除的会话停止出现于 `listSessionSummaries`。如果未定义,则删除是非操作,它适合仅附件的后端。 | | `listSubkeys` | 没有 | 在恢复期间, 发现子代理记录。 如果未定义, 只有主记录被恢复 。 | 在一个 `SessionSummaryEntry`, `mtime` 是侧车的存储写入时间,必须共享时钟源 `mtime` 数值 `listSessions` 返回时输入。 `data` 是不透明的 SDK 所属状态; 在不解译的情况下逐字坚持它。 通过调用导出状态来构建条目 `foldSessionSummary` 帮手, `fold_session_summary` 在 Python 中,每批内置 `append`。跳过按键有 `subpath`; 子代理笔录不得为主会话摘要提供内容。折叠从不设定 `mtime`:在持续的时间刻印,通过 `options.mtime` 参数在 TypeScript 中,或者在 Python 中返回的条目上覆盖字段。同步 `append` 调用相同的会话可以在侧车上进行比赛,因此串行 read-fold-write 用交易, compare-and-swap, 或每会话锁; 折叠本身是纯的。 对于 SDK 用笔录所做的 `load` 返回,参见 [从店里继续](<https://code.claude.com/docs/en/agent-sdk/session-storage#resume-from-the-store>). ## 快速启动 SDK号舰只 `InMemorySessionStore` 用于开发与测试。下面的例子运行一个与所附加的商店的查询,从结果消息中捕捉会话 ID,然后在第二秒中从商店恢复 `query()` 第二通电话通过同一商店例加 `resume`,所以SDK从商店装入记录片,而不是本地文件系统: ``` import { query, InMemorySessionStore } from "@anthropic-ai/claude-agent-sdk"; const store = new InMemorySessionStore(); let sessionId: string | undefined; try { for await (const message of query({ prompt: "List the TypeScript files under src/", options: { sessionStore: store }, })) { if (message.type === "result") { sessionId = message.session_id; } } } catch (error) { // A single-shot query() throws after yielding an error result. If the // failure was an error result, sessionId was already captured by the loop // above; connection or process failures yield no result message. console.error(`Session ended with an error: ${error}`); } // Resume from the store. The agent has full context from the first call. for await (const message of query({ prompt: "Summarize what those files do", options: { sessionStore: store, resume: sessionId }, })) { if (message.type === "result" && message.subtype === "success") { console.log(message.result); } } ``` ``` import asyncio from claude_agent_sdk import ( ClaudeAgentOptions, InMemorySessionStore, ResultMessage, query, ) store = InMemorySessionStore() async def main(): session_id = None try: async for message in query( prompt="List the Python files under src/", options=ClaudeAgentOptions(session_store=store), ): if isinstance(message, ResultMessage): session_id = message.session_id except Exception as error: # A single-shot query() raises after yielding an error result. If the # failure was an error result, session_id was already captured by the # loop above; connection or process failures yield no result message. print(f"Session ended with an error: {error}") # Resume from the store. The agent has full context from the first call. async for message in query( prompt="Summarize what those files do", options=ClaudeAgentOptions(session_store=store, resume=session_id), ): if isinstance(message, ResultMessage) and message.subtype == "success": print(message.result) asyncio.run(main()) ``` 第二个查询打印出第一个查询中的文件摘要,显示从商店中完整上下文恢复的代理. ## 写自己的适配器 执行 `append` 财务报告和财务报告 `load` 相对于您的后端。 添加 `listSessions`, `listSessionSummaries`, `delete`,以及 `listSubkeys` 如果你想的话 `listSessions()`单调元数据读作: `deleteSession()`,并且副代理恢复到对商店的工作。 `append` 输入为 `SessionStoreEntry` (a `{ type: string; ... }` 对象)。把它们当作不透明的 JSON 安全值:坚持它们,然后把它们从 `load` 同样的顺序。 `load` 必须返回与附件的深等值的条目; 字节相等的序列化不需要, 因此重排对象密钥的后端, 如二进制的 JSON 列类型, 是罚款的 。 ## 参考执行情况 SDK两个寄存器都包含以下可运行的参考适配器: [`examples/session-stores/`](<https://github.com/anthropics/claude-agent-sdk-typescript/tree/main/examples/session-stores>) 在TypeScript中,以及 [`examples/session_stores/`](<https://github.com/anthropics/claude-agent-sdk-python/tree/main/examples/session_stores>) 在 Python 中。每个存储类型有一个适配器,每个都显示 `append` 财务报告和财务报告 `load` 映射到这类后端。 它们不是作为软件包发布的; 将最接近后端的类型适配器复制到您的工程中, 安装您的后端客户端, 并修改它 。 | 存储类型 | 存储模型 | 示例适配器 | | --- | --- | --- | | 对象存储 | 每个文件一个部分 `append()`; `load()` 列出部件、类型和装饰。 | S3 ([TypeScript](<https://github.com/anthropics/claude-agent-sdk-typescript/tree/main/examples/session-stores/s3>), [Python 键](<https://github.com/anthropics/claude-agent-sdk-python/blob/main/examples/session_stores/s3_session_store.py>)) | | 关键值存储 | 每张记录单上一张 `append()` 推向并 `load()` 读取范围,加上排序的会话索引。 | 红色( RDIS )[TypeScript](<https://github.com/anthropics/claude-agent-sdk-typescript/tree/main/examples/session-stores/redis>), [Python 键](<https://github.com/anthropics/claude-agent-sdk-python/blob/main/examples/session_stores/redis_session_store.py>)) | | 关系数据库或文档存储 | 每个条目一行或文档,存储为JSON,并由插入上指定的密钥命令. | 邮资( U)[TypeScript](<https://github.com/anthropics/claude-agent-sdk-typescript/tree/main/examples/session-stores/postgres>), [Python 键](<https://github.com/anthropics/claude-agent-sdk-python/blob/main/examples/session_stores/postgres_session_store.py>)) | 每个适配器都使用一个预配置客户端实例,所以您可以控制证书, TLS, 区域, 和集合。 下面的例子将对象存储适配器连接到 `query()` 然后在另一主机上继续播放: TypeScript ``` import { query } from "@anthropic-ai/claude-agent-sdk"; import { S3Client } from "@aws-sdk/client-s3"; import { S3SessionStore } from "./S3SessionStore"; // copied from examples/session-stores/s3 const bucket = process.env.TRANSCRIPT_BUCKET; if (!bucket) { throw new Error( "Set the TRANSCRIPT_BUCKET environment variable to the name of an S3 bucket your AWS account owns" ); } const store = new S3SessionStore({ bucket, 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); } } // Later, possibly on a different host: for await (const message of query({ prompt: "Continue where we left off", options: { sessionStore: store, resume: "previous-session-id" }, })) { // ... } ``` ### 验证您的适配器 两艘SDK都装了套装 声称行为合同 `append`, `load`,而可选方法必须满足。可选方法测试在未执行时自动跳过。在 TypeScript 中,复制 [`shared/conformance.ts`](<https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/examples/session-stores/shared/conformance.ts>) 从示例目录到测试套件。 在 Python 中, 套件中的套件船。 要用 pytest 运行它, 它不是 SDK 依赖性, 请先安装 pytest : ``` pip install pytest ``` 然后将适配器传递到测试文件中的套房,作为零参数工厂, `run_session_store_conformance` 每份合同只要打个电话 来建造一家新店: Python 键 ``` import pytest from claude_agent_sdk.testing import run_session_store_conformance @pytest.mark.anyio async def test_my_store_conformance(): await run_session_store_conformance(MyRedisStore) ``` 传球 `MyRedisStore` 类本身,就像这个例子一样,当构造器不采任何参数时就起作用了。对于一个使用预配置客户端的适配器,通过一个构建商店的羊排。由于合同重复使用相同的会话密钥,每个厂家的返回必须从空存储开始,所以羊排服务是否孤立了每个呼叫的备份存储,例如新鲜的内存假冒,一个独特的密钥前缀,或者一个新建测试数据库。 ## 行为说明 ### 双写结构 Claude代码子进程总是先将每批记录条目写到本地磁盘,然后SDK然后将同样的批次转发到您的商店 `append()`,因此该商店是当地记录的镜像,而不是替代。哪个副本比运行有效,取决于运行是如何开始的 : - **新鲜会话, 或当商店没有时间进行会话时恢复会话**:您配置目录下的本地语录比运行时间长,商店收到副本. - **运行 [店里恢复营业](<https://code.claude.com/docs/en/agent-sdk/session-storage#resume-from-the-store>)**:在运行尾端删除本地副本,因此商店持有唯一耐用副本. 如果您不想在本地磁盘上留下新的会话记录, 请设定 `CLAUDE_CONFIG_DIR` 到一个新的私人临时目录 `options.env`。从商店恢复的运行已经删除其本地副本, 因此不需要设置。 在 TypeScript 中, 展开 `process.env` 输入 `env` 以及,自从 [`env` 选项](<https://code.claude.com/docs/en/agent-sdk/typescript#options>) 替换子进程环境。如果设置 `CLAUDE_CONFIG_DIR` 到临时目录,并用 [Claude.ai 登录](<https://code.claude.com/docs/en/authentication#credential-management>) 或一个 [`apiKeyHelper`](<https://code.claude.com/docs/en/settings-reference#apikeyhelper>) 在您的用户中 `settings.json`,运行失败 `Not logged in`。要认证运行,设置长寿符,设置API密钥,或者复制您的配置文件 : - **长寿代号**: 如果你自己在克劳德的订阅下运行代理, 设置 `CLAUDE_CODE_OAUTH_TOKEN` 输入 `env` 以表示从 [`claude setup-token`](<https://code.claude.com/docs/en/authentication#generate-a-long-lived-token>)。只能用这个符号提出模型请求,所以 [连接器](<https://code.claude.com/docs/en/mcp#use-mcp-servers-from-claude-ai>) 如此一来, - **API 密钥**: 设置 `ANTHROPIC_API_KEY` 输入 `env`. - **配置文件**: 如果您通过您通常配置目录中的文件签名, 如 OAuth 证书或一个 `apiKeyHelper` 在您的用户中 `settings.json`,将其复制到临时目录中。 两个选项与镜像相冲突,如果两个选项都与商店结合,则SDK在启动时投出: - **`persistSession: false`** 在 TypeScript 中: 关闭本地写入的镜像是建于此。 Python SDK 没有相应的选项 。 - **文件检查**, `enableFileCheckpointing` 在 TypeScript 中,或 `enable_file_checkpointing` 在 Python 中: 直接将其文件备份写入本地磁盘, 而 SDK 并没有把它们映射到商店中 。 ### 从店里继续 当你通过时 `resume`,或 `continue: true` 在 TypeScript 中,或 `continue_conversation=True` 在 Python 中, 与商店一起, SDK 要求商店在生成子进程前提供一份记录: - **`resume`**: SDK 请求您通过的 ID 的会话. - **`continue: true`** 或 时 间 **`continue_conversation=True`**:SDK要求该店最新会话. 当商店返回记录稿时,SDK将其写入一个临时配置目录,并运行子进程。 `CLAUDE_CONFIG_DIR` 指向此处, 当运行结束时删除目录。 运行的本地语录会被删除, 因此商店持有此路径上唯一耐用的副本 。 SDK 也用您真实配置目录中的文件来种子临时目录。 复制的内容因语言而异 : - **TypeScript**: 全权证书, `.claude.json`,以及您的用户 `settings.json`从。 `settings.json` 它将临时配置目录下不正确的密钥剥离 : `enabledPlugins`, `extraKnownMarketplaces`,其编号: [`additionalMarketplaces`](<https://code.claude.com/docs/en/settings-reference#extraknownmarketplaces>) 别名,以及任何 `CLAUDE_CONFIG_DIR` 在文档中 `env` 块。在代理 SDK v0.3.232 之前, SDK 没有剥离别名。 Auth 配置在设置中, 例如 [`apiKeyHelper`](<https://code.claude.com/docs/en/settings-reference#apikeyhelper>),当您从商店恢复工作。在代理SDK v0.3.222之前,TypeScript SDK只复制了证书和 `.claude.json`. - **Python 键**: 全权证书和 `.claude.json` 只有,所以一个应用 认证通过 `apiKeyHelper` 在您的用户中 `settings.json` 失败 `Not logged in` 当从商店恢复时。 `apiKeyHelper` 在管理下的或项目设置中仍然有效,因为Claude Code从地点读取这些文件 `CLAUDE_CONFIG_DIR` 这不会影响我们。 当商店对会话无所事事时,SDK会运行在您真实的配置目录下,结果取决于您通过的选项 : - **`resume`**:两个SDK将ID通过子进程,子进程完全恢复本地记录为 `resume` 没有商店。 - **`continue: true`** 在 TypeScript 中: SDK 开始一个新的会话. - **`continue_conversation=True`** 在 Python 中: SDK 从最新的本地会话继续. ### 镜像写得最好 若为: `append()` 拒绝时, SDK 将批次重复两次, 并进行简短的备份, 总共最多三次尝试。 取消时间的呼声没有重新尝试, 因为原呼号可能仍然在降落。 因为重试的批次可以重新发送已经落地的条目, 从而被复制 。 `entry.uuid` 在您的帐号中 `append()` 执行,并保留每个没有 `uuid`如果批次仍然失败,则SDK记录错误,发出 a `{ type: "system", subtype: "mirror_error" }` 消息输入指令器, 将批次放下, 继续查询。 存储中断不会打断代理, 因为子进程会先在本地写入 。 监视器用于 `mirror_error` 以检测存储数据丢失。运行中 [店里恢复营业](<https://code.claude.com/docs/en/agent-sdk/session-storage#resume-from-the-store>)一旦运行结束,一个掉下来的批次就没有幸存的复制品。 ### `getSessionMessages` 返回交易后链条 `getSessionMessages({ sessionStore })` 返回代理机在恢复时看到的链接信件链。在自动压缩后,较早的转弯将被摘要替换,因此存储 503 原始条目的会话可以返回 18 消息。 `getSessionMessages`。对于完整的原始历史,包括交易前转折和元数据条目,调用 `store.load(key)` 直接来. ### `forkSession` 不是一个字节副本 `forkSession({ sessionStore })` 读取源条目,每条重写 `sessionId` 字段和重映射信件 UUID,然后在新密钥下附加已转换的条目。适配器级副本或 `CopyObject` 快捷键将生成一个仍然引用旧会话 ID 的语录,所以 SDK 不使用 。 ### 副代理记录 子代理记录抄录在下面 `subpath: "subagents/agent-<id>"`. `listSubagents({ sessionStore })` 要求适配器执行 `listSubkeys`; `getSubagentMessages({ sessionStore })` 可用时使用它,但在未定义时又回到直接的子路径。 Resume also calls `listSubkeys` 以恢复子代理文件;没有它,只有主记录稿才被实现。 ### 保留 SDK 从未从您的商店中自行删除。 保留是适配器的责任: 使用您的后端的过期或寿命周期机制, 或根据您的合规要求运行预定的清理。 本地笔录如下 。 `CLAUDE_CONFIG_DIR` 被独立地覆盖 `cleanupPeriodDays` 设置,随 [保留扫描规则](<https://code.claude.com/docs/en/claude-directory#cleaned-up-automatically>)运行 [店里恢复营业](<https://code.claude.com/docs/en/agent-sdk/session-storage#resume-from-the-store>) 当地没有笔录,所以对于经营你的商店来说, 保留是唯一的保留。 ## 获得支持 下列 TypeScript SDK 函数接受 a `sessionStore` 选项,并在提供本地文件系统时对照该存储系统运行: - [`query()`](<https://code.claude.com/docs/en/agent-sdk/typescript#query>) - [`startup()`](<https://code.claude.com/docs/en/agent-sdk/typescript#startup>) - [`listSessions()`](<https://code.claude.com/docs/en/agent-sdk/typescript#listsessions>) - [`getSessionInfo()`](<https://code.claude.com/docs/en/agent-sdk/typescript#getsessioninfo>) - [`getSessionMessages()`](<https://code.claude.com/docs/en/agent-sdk/typescript#getsessionmessages>) - [`renameSession()`](<https://code.claude.com/docs/en/agent-sdk/typescript#renamesession>) - [`tagSession()`](<https://code.claude.com/docs/en/agent-sdk/typescript#tagsession>) - [`deleteSession()`](<https://code.claude.com/docs/en/agent-sdk/typescript>) - [`forkSession()`](<https://code.claude.com/docs/en/agent-sdk/typescript#forksession>) - [`listSubagents()`](<https://code.claude.com/docs/en/agent-sdk/typescript>) - [`getSubagentMessages()`](<https://code.claude.com/docs/en/agent-sdk/typescript>) 在 Python SDK 中,设定 `session_store` 输入 [`ClaudeAgentOptions`](<https://code.claude.com/docs/en/agent-sdk/python#claudeagentoptions>) 运行 `query()` 其余的操作都有一个由商店支撑的 Python 函数,该函数将商店当作一个论据: `list_sessions_from_store()`, `get_session_info_from_store()`, `get_session_messages_from_store()`, `list_subagents_from_store()`, `get_subagent_messages_from_store()`, `rename_session_via_store()`, `tag_session_via_store()`, `delete_session_via_store()`,以及 `fork_session_via_store()`. `startup()` 没有 Python 等同的函数。 [Python SDK 参考文献](<https://code.claude.com/docs/en/agent-sdk/python#functions>),例如, `list_sessions()`,阅读本地会话文件。 ## 相关资源 - [与届会的合作](<https://code.claude.com/docs/en/agent-sdk/sessions>): 没有自定义商店的继续、恢复和叉 - [主办 SDK](<https://code.claude.com/docs/en/agent-sdk/hosting>):多东道国环境的部署模式 - [TypeScript `Options`](<https://code.claude.com/docs/en/agent-sdk/typescript#options>): 完全选项参考 - [参考执行情况](<https://code.claude.com/docs/en/agent-sdk/session-storage#reference-implementations>): 在 SDK 寄存器中, 用于对象商店、 键值商店和数据库的可运行实例适配器

查看原始来源