> ## Content Index
> Fetch the complete content index at: http://47.93.196.89/llms.txt
> Use this file to discover other available public pages before exploring further.

# pi-durable 使用指南（中文 README）
- URL: http://47.93.196.89/durable-readme/
- Published: 2026-11-25T03:54:01.000Z
- Updated: 2026-11-25T03:54:01.000Z
- Author: Ansel
- Tags: Durable

# @earendil-works/pi-durable

> **实验性。** 不同发布版本之间，API 可能随时变更，恕不另行通知。

Durable 是一套支持持久化的智能体运行环境。对话、模型轮次、工具调用和应用自己的状态都先提交到存储，再对外展示。如果进程在一轮中途退出，重新打开存储即可从中断处接着工作。如果当时正在请求模型，这次请求会计作失败并按策略重试，因此反复导致进程退出的请求最终也会结束。见[持久化与恢复](#persist-and-resume)。

模型访问基于 [@earendil-works/pi-ai](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/ai/README.md?ref=47.93.196.89)，文档状态由 `@earendil-works/chord` 提供。

## 目录

- [安装](#installation)
- [快速入门](#quick-start)
- [基本概念](#concepts)
- [持久化与恢复](#persist-and-resume)
- [扩展](#extensions)
- [工具](#tools)
- [代码模式](#code-mode)
- [系统提示词](#system-prompt)
- [每段对话的智能体配置](#per-conversation-agent)
- [设置](#settings)
- [环境](#environment)
- [热重载](#reload)
- [观察对话](#watching-a-conversation)
- [忙碌中的对话](#busy-conversations)
- [重置与交接](#reset-and-handoff)
- [上下文压缩](#compaction)
- 智能体事件（实验性）
- [钩子](#hooks)
- [更多对话与分支](#more-conversations-and-forks)
- [中止与子智能体](#abort-and-subagents)
- [子任务](#child-tasks)
- [任务图](#task-graph)
- [自定义状态](#your-own-state)
- [用量与费用](#usage-and-cost)
- [存储](#storage)
- [错误](#errors)
- [示例](#examples)
- [设计文档](#design-documents)

## 安装

```bash
npm install @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chord

```

## 快速入门

```typescript
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
import { createModels } from "@earendil-works/pi-ai/models";
import { openaiProvider } from "@earendil-works/pi-ai/providers/openai";
import { AssistantEntry, createRegistry, Harness, MemoryStorage } from "@earendil-works/pi-durable";

const context = BACKGROUND_CONTEXT;

const models = createModels();
models.setProvider(openaiProvider()); // reads OPENAI_API_KEY

const harness = await Harness.open(new MemoryStorage(), { models, registry: createRegistry() }, context);
const root = await harness.root(context, { agent: { model: { provider: "openai", modelId: "gpt-6-sol" } } });

const submission = await root.submit({ type: "input", content: "What is the capital of France?" }, context);
const settled = await submission.wait(context);
if (settled.status === "done" && settled.type === "input") {
	const answer = await root.commit((tx) => tx.entry(AssistantEntry, settled.answer), context);
	console.log(answer?.model?.[0]);
}
await harness.close(context);

```

这段代码依次做了以下几件事。

- `Harness.open()` 在存储后端之上开启一个 Session。`MemoryStorage` 将全部数据保存在内存中。
- `root()` 返回根对话，首次调用时按给定的智能体配置创建。对话是一份由不可变条目组成的交互记录。
- `submit()` 将输入可靠地写入存储并返回 `Submission`。内置的生成任务调用模型，将回答追加到对话记录。
- 输入有了答案（`done`），或已失败（`unanswered`，并附原因）时，`wait()` 返回结果。

每个异步调用都接收 Chord 的 `Context`，其中包含取消信息和当前的 `TelemetrySpan`。`BACKGROUND_CONTEXT` 永不主动取消，使用空操作 span。根遥测适配器归 Harness 所有，不保存在 `Context` 里。取消一次等待只会结束这次等待，后台工作会继续。

`HarnessOptions.identity` 决定模型请求怎样向提供方标识应用，使用 pi-ai 的 `ClientIdentity`，并覆盖合并到 `DEFAULT_HARNESS_IDENTITY` 上。默认的 `{ attribution: PI_ATTRIBUTION }` 会在 OpenRouter、NVIDIA NIM 和 OpenCode 的归属标头中标明 pi。它用于生成、压缩、钩子和工具，优先于宿主创建 `Models` 时指定的身份。可传入你自己应用的归属信息，如 `{ attribution: { name: "my-app", url: "https://my-app.example" } }`，也可传 `{ attribution: null }` 以省略归属信息。

`HarnessOptions.telemetry` 接收宿主持有的 `TelemetryContext`，来自 `@earendil-works/pi-telemetry`，可选支持 `propagation` 和 `metrics`。未传时遥测为空操作。包根入口导出的 `DURABLE_TELEMETRY_SCHEMA` 描述有类型的 span、事件和指标。属性只含 ID 和控制元数据，不含消息、参数、结果；可通过 ID 找到对话记录。

- `pi.durable.submit` 覆盖公开的提交调用及其存储提交。对 `admit(tx, draft)`，它只覆盖接纳输入的阶段。在你自己的事务落盘前，`result` 是暂定结果，事务事件记入该事务的上下文。每个输入新开一条根追踪，并链接调用方当前的 span；写入则是调用方的子 span。重复的 `requestId` 保留原提交及其追踪载体。压缩写入等内部接纳操作在所属阶段的 span 上记事件，不单开提交 span。
- `pi.durable.phase` 覆盖每个任务的一次运行或中止阶段，包括提交本阶段决定；不跨越下个阶段、持久等待或重启。属性标明任务、阶段、尝试次数（如有）、`resumed` 和结果。工具阶段还标明工具及调用。嵌套任务和后台压缩继承创建它们的阶段，模型请求接收该阶段的上下文。钩子不另建 span。
- 阶段失败会把状态设为错误，写入固定类别（`task_faulted`、`task_failed` 或 `task_orphaned`）和最多 500 个字符的诊断消息，孤立任务使用其成为孤立任务的原因。诊断可能包含调用方内容；不会记录错误详情或异常名称。`aborted` 的状态仍是 `ok`，包括因关闭或取消而中断的情况。
- 每份 `onReport` 报告也会在当前 span 发出 `pi.durable.report` 事件。没有 span 时，空操作 span 丢弃事件，不会创建根报告 span。只记录 `type`（报告的 `kind`）、可选的固定 `reason`、`extension` 和 `task.id`，不含错误载荷。`pi.durable.reports` 仅按 `type` 统计全部报告，包括没有 span 的报告。时钟故障上报时没有阶段上下文。`onReport` 回调行为保持原样。
- 已提交的条目和已有定论的提交分别发出 `pi.durable.entry` 和 `pi.durable.submission`。运行中已提交的阶段变化发出 `pi.durable.checkpoint`；嵌套调用复用已保存的结果时发出 `pi.durable.replay`。
- 追踪传播把可选的不透明 `trace` 载体保存在提交与任务的 JSON 中，无需迁移存储。阶段 span 提取对应任务已存的载体；缺失或无法识别时从适配器根部开始。省略 `TaskOptions.trace` 会继承创建方的载体；也可显式覆盖，或用 `"root"` 从适配器根部开始而不保存载体。多个排队输入一起启动一次运行时，沿用第一个输入的追踪，首次调用的阶段 span 通过不可变的任务 `links` 链接其他输入。运行中追加引导消息（steer）会留在当前追踪，它的提交 span 链接本次运行已存的载体。重新打开任务后，首次调用沿用同一条追踪，并标记 `resumed: true`。
- 记录的指标有 `pi.durable.phase.duration`（毫秒，按任务、阶段和结果区分）和 `pi.durable.tasks.active`（活跃任务数，按任务名区分），不带记录 ID。关闭 Harness 后会释放它的活跃计数。

## 基本概念

- **Harness** 由一个打开的存储和在其上运行智能体的机制组成。所有变更排成一列依次原子提交，写入成功后才对外可见。
- **对话（Conversation）** 是一份交互记录。`root()` 在首次使用时创建根对话，你还可以创建其他对话或从已有对话分支。`Conversation` 句柄自身不保存状态，应按 `id` 比较两个句柄。
- **条目（Entry）** 是一条不可变的对话记录，例如用户消息（`pi.user`）、模型响应（`pi.assistant`）、工具结果（`pi.tool-result`）、系统提示词变化（`pi.system`）、重置（`pi.reset`）或自定义种类。模型能看到最近一次重置开始的条目。
- **提交（Commit）** 是一次原子写入。`conversation.commit((tx) => ...)` 可以同时追加条目、编辑文档和创建任务，要么全部存储成功，要么全部不生效。
- **文档（Document）** 是与对话记录一同保存、在提交中修改的有类型 JSON 状态。内置文档分别保存对话的智能体选择（`pi.agent`）、面向提供方的会话身份（`pi.provider`）、执行中的生成与工具（`pi.live`）、排队的提交（`pi.inbox`）和费用（`pi.usage`）。
- **任务（Task）** 是持久状态机，每一步都保存检查点，进程重启后从最近的检查点继续。任务归所属对话或另一个任务所有。Harness 用内置任务生成回答。`pi.generation` 调用模型，拥有各次工具调用的 `pi.tool` 任务，等它们完成后，把运行交给下一次生成。
- **提交项（Submission）** 是交给对话的一份输入或一条待写入的条目，可以等待其处理结果。
- **轮次和运行（turn、run）**。一次模型响应及其工具调用构成一轮。从收到输入到给出最终回答之间的全部轮次构成一次运行。运行期间对话处于忙碌状态。
- **扩展（Extension）** 是有名字的一组工具、系统提示词片段、钩子、包装器和任务。
- **注册表（Registry）** 保存当前进程安装的扩展。Harness 运行期间注册表可以变化，新工作使用变更后的状态。
- **智能体（Agent）** 是对话运行时采用的模型、思考级别、扩展、工具、指令和工作目录。每个对话在 `pi.agent` 中按名称保存这些选择，每次使用时再对照注册表解析。

一份输入得到回答时，对应的条目与任务如下。

```text
submit(input) → pi.user
  pi.generation → pi.system (only if the prompt or tools changed), pi.assistant (tool calls)
    pi.tool × n → pi.tool-result × n   (owned by the generation, which waits for them)
  pi.generation → pi.assistant (answer) → submission done

```

## 持久化与恢复

使用 SQLite 或 JSONL 存储可让对话跨重启保留。

```typescript
import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";

const harness = await Harness.open(await openNodeSqliteStorage("./session.sqlite"), { models, registry }, context);
const root = await harness.root(context); // the same root as last time
harness.resume(); // continue any run the last process left unfinished

```

进程崩溃或关闭时中断的工作保持待处理。`resume()` 启动任务调度器，提交或等待也能启动它。如果一个进程只展示由另一进程驱动的会话，打开时传 `readOnly: true`。此时不会恢复任务，所有写入、`resume()` 以及会运行任务的调用都以 `ReadOnlySession` 拒绝。此选项只控制 Harness。先打开 JSONL 存储时也须用 `openNodeJsonlStorage(directory, context, { readOnly: true })`，因为可写模式会修复文件，写进程可能正往里面追加内容（见[存储](#storage)）。SQLite 照常打开即可，文件锁允许读取者和写入者共存。每个对话在 `pi.provider` 保存自己的 UUIDv7，并以 `sessionId` 传给 pi-ai，用于提供方的提示词缓存和会话亲和性。重新打开、重试、重置、压缩或更换模型都会保留此身份；子对话和分支取得新身份。旧版对话会在首次生成或压缩请求前取得并保存身份。

使用相同 `requestId` 重试时，返回原有的提交项，避免提交两次。

```typescript
const submission = await root.submit({ type: "input", content: "Hello", requestId: "greeting-1" }, context);
// After a restart: the same request ID finds the same submission.
const again = await root.submit({ type: "input", content: "Hello", requestId: "greeting-1" }, context);
// again.id === submission.id

```

`harness.submission(id)` 按 ID 重新取得提交项，例如重启后继续等待它。

### 休眠与唤醒

任务要等待某个时刻，就以休眠结束当前阶段。休眠状态会落盘，等待期间无需保留执行实例，可以跨越重启；Harness 的时钟达到 `until` 时，任务从检查点恢复。

```typescript
const Reminder = defineTask<{ text: string; at: number }, { phase: "wait" } | { phase: "deliver" }, null>({
	name: "app.reminder",
	version: 1,
	initial: () => ({ phase: "wait" }),
	phases: {
		// Resolves once the sleep is stored; the phase ends there.
		wait: (task, runtime, context) => runtime.sleepUntil(task.input.at, { phase: "deliver" }, context),
		deliver: async (task, runtime, context) => {
			await notify(task.input.text);
			await runtime.commit(() => ({ status: "terminal", outcome: { status: "completed", result: null } }), context);
		},
	},
	abort: (_task, runtime, context) =>
		runtime.commit(() => ({ status: "terminal", outcome: { status: "aborted" } }), context),
});

```

阶段内部不会从一条语句中间休眠恢复。重启后会从阶段开头重跑，所以等待之后的工作应放到下一阶段，并把所需数据放进检查点。由 `runtime.commit()` 返回 `{ status: "sleeping", until, checkpoint }` 有相同的休眠语义，还可与其他写入一起提交。传 `signals` 时信号也能将其唤醒（见[信号](#signals)），这时 `until` 可省略。内置任务的重试退避和轮询延期响应也用这套机制。

Session、调度器和任务用 `setTimer`（默认 `setTimeout`）设置定时器，通过 `now`（默认 `Date.now`）读取时间。两者一同传入即可让 Harness 使用模拟时钟。Node.js 环境、文件监听器和图像工作进程仍使用自己的定时器。休眠截止时间按 `now` 的时钟存储，打开同一存储的进程必须使用同一种时钟。调度期间，定时器会在任务到期时将其恢复，等待期间让 Node.js 进程保持存活。

对于进程可能被回收的宿主（如 Cloudflare Durable Object），唤醒由宿主负责。提供 `onWake` 后，Harness 不为休眠设置定时器，而会在 `harness.wake()` 的结果变化时通知宿主。`active` 表明有任务可立即运行或正在运行，`at` 给出最早到期的休眠。宿主保持闹钟已设置，在响起时调用 `resume()`。

```typescript
export class Session extends DurableObject<Env> {
	#harness!: Harness;

	constructor(ctx: DurableObjectState, env: Env) {
		super(ctx, env);
		void ctx.blockConcurrencyWhile(async () => {
			// A fallback before anything can throw: an object whose open or recovery fails is started again.
			const fallback = Date.now() + 60_000;
			const current = await ctx.storage.getAlarm();
			if (current === null || current > fallback) await ctx.storage.setAlarm(fallback);
			const storage = await openDurableObjectSqliteStorage(ctx.storage);
			const onWake = (wake: Wake) =>
				// A failed alarm write resets the object; it arms again when it next starts.
				void this.#arm(wake).catch(() => ctx.abort("Alarm write failed"));
			this.#harness = await Harness.open(storage, { models, registry, onWake }, context);
			// Armed before `resume()` runs anything, as for any call that can start work.
			await this.#arm(this.#harness.wake());
			this.#harness.resume(); // work a lost instance left, and due sleeps
		});
	}

	override async alarm(): Promise<void> {
		await this.#arm({ ...this.#harness.wake(), active: true });
		this.#harness.resume(); // due sleeps and work a lost instance left
	}

	// Arm before any call that can start work (submit, signal, compact, abortTask, abort, a registry change): `onWake`
	// runs after the commit. An early alarm is harmless, a missing one strands the work.
	async submit(conversation: Conversation, input: string, requestId: string): Promise<void> {
		await this.#arm({ ...this.#harness.wake(), active: true });
		await conversation.submit({ type: "input", content: input, requestId }, context);
	}

	async #arm(wake: Wake): Promise<void> {
		// A recovery heartbeat while work runs, never later than the earliest sleep.
		const heartbeat = wake.active ? Date.now() + 60_000 : undefined;
		const at = heartbeat === undefined || wake.at === undefined ? (heartbeat ?? wake.at) : Math.min(heartbeat, wake.at);
		if (at === undefined) await this.ctx.storage.deleteAlarm();
		else await this.ctx.storage.setAlarm(at);
	}
}

```

默认的 `setTimer` 在 Workers 中不会设置仅用于释放内存的定时器，避免未到期的定时器妨碍对象休眠或回收。内存改在之后的提交中释放。

### 信号

信号是外部向存活任务送达的有类型 JSON 值，如 webhook 的结果或人的回答。任务在某个键上休眠，期间不占用进程；`harness.wake()` 不会因此显示 `active`，`at` 表示它的截止时间（如有）。先用 pi-schema 的模式定义信号类型，再在某个键上休眠，唤醒后读取值。

```typescript
import { obj, str } from "@earendil-works/pi-schema";
import { defineSignal, defineTask } from "@earendil-works/pi-durable";

const HOUR = 60 * 60 * 1000;
const Answer = defineSignal({ name: "app.answer", version: 1, schema: obj({ text: str() }) });

const AskPerson = defineTask<{ question: string }, { phase: "ask" } | { phase: "answered" }, string | null>({
	name: "app.ask-person",
	version: 1,
	initial: () => ({ phase: "ask" }),
	phases: {
		// Wakes on the answer, or after four hours, whichever comes first.
		ask: (_task, runtime, context) =>
			runtime.commit(
				() => ({
					status: "sleeping",
					signals: [Answer.key("answer")],
					until: runtime.now() + 4 * HOUR,
					checkpoint: { phase: "answered" },
				}),
				context,
			),
		answered: async (task, runtime, context) => {
			// task.state.wake says why: { reason: "signal", signal, key } or { reason: "expired" }.
			const state = await runtime.readSignal(Answer, "answer", context); // { kind: "value", value }, { kind: "expired" }, or undefined
			const text = state?.kind === "value" ? state.value.text : null;
			await runtime.commit(() => ({ status: "terminal", outcome: { status: "completed", result: text } }), context);
		},
	},
	abort: (_task, runtime, context) =>
		runtime.commit(() => ({ status: "terminal", outcome: { status: "aborted" } }), context),
});

// Whatever shows the question (an inbox, a chat bridge) keeps the task ID and delivers the answer:
const result = await harness.signal(taskId, Answer, "answer", { text: "Yes" }, context);

```

- **送达结果。** `delivered` 表示已持久保存；`duplicate` 表示该键已有值（如 webhook 重试）；`invalid` 表示与模式不符；`closed` 表示任务结束、已中止或已过截止时间；另有 `not_found`。宿主应将 `duplicate` 和 `closed` 作为最终结果回复发送方。`tx.signal()` 可在你自己的事务内送达，须在第一次写表之前调用。系统不验证发送者身份，宿主应负责认证。
- **提前到达。** 信号在任务开始等其键之前抵达，值也会保留，随后休眠时立即唤醒。
- **每个键只等待一次。** 唤醒会消耗所用的键，再次等待同一个键将被拒绝。同一种信号要等第二次，应使用新键，例如 `ci-1` 和 `ci-2`。
- **值应小。** 值保存在任务记录中；大数据应发送引用，如文档 ID 或 CI 运行 ID。
- **由任务唤醒。** 在 `waiting` 状态中指定 `policy: "any"`，`on` 中任一任务结束就恢复；此时 `task.state.wake` 为 `{ reason: "tasks", ended }`。
- **由提交项唤醒。** 提交时传入 `notify: { taskId, key }`，处理结束后会向该任务送达内置信号 `SubmissionSettled`，内容就是 `wait()` 返回的记录。工具借此等待子智能体而无需占着进程，见[可挂起的工具](#tools-that-park)。

### 失败与恢复

**反复崩溃。** 某项工作若总是在下个检查点前耗尽内存或 CPU，任其恢复就会无限重复崩溃。模型请求期间宿主退出，按 `settings.retry` 计为失败一次，已收到的部分回答会以中止条目保留。下次尝试先等退避期（可在 `docs["pi.live"].generation.retry` 中看到），重试耗尽后运行以 `docs["pi.live"].runFailure` 的 `interrupted` 原因结束。若当时正在取一个延期响应，下一次尝试继续轮询原响应，不重新发起请求；运行结束时取消它。正常关闭不同于崩溃，被关闭打断的请求会重新发送。其他工作按中断次数计数。打开存储时，为每个被崩溃、回收或重置打断的任务增加计数，任务提交新状态后清零。计数达到 `settings.restartLimit`（默认 5，设为 `Infinity` 则永远不会因这个计数结束任务）后，工具调用以错误结果结束，诊断码为 `restart_limit`；压缩失败写入 `compactionFailure`；运行以 `runFailure`、原因 `restart_limit` 结束（为中断请求计费时反复崩溃也一样）；自定义任务变为 `faulted`，报告 `task_faulted`，原因为 `restart_limit`。内置任务报告 `task_interrupted`，以 `interrupted` 结束的运行也如此，因此崩溃循环总会传到 `onReport`。进程退出时正在运行的每个任务都会计数，包括并未引发崩溃的任务。中止处理器被打断同样多次也会令其任务变为 `faulted`；由人中止的运行仍以 `aborted` 结束，`detail` 说明中断情况。

**报告。** `onReport(report)` 每次接收一个 `Report`，含 `error`，以 `report.kind` 标明事件。`storage_failed` 表示导致 Harness 失败的存储错误，常由平台重置引起。任务相关类别有 `task_faulted`、`task_interrupted`（崩溃使任务终止，附 `report.reason` 和 `report.restarts`）、`migration_failed`、`task_outdated`（`reason` 为 `missing_task`、`task_too_old` 或 `migration_failed`，也是受阻任务显示的原因）以及 `task_error`。`report.task` 给出任务的 `id`、`kind`、`conversationId`，`report.extension` 指出安装它的扩展。`extension_error` 用于钩子、片段、包装器和工具，并附扩展名称。`host_error` 用于宿主回调，其名称在 `report.callback` 中。另有 `listener_error`。宿主可把同一种任务的 `task_faulted` 报告送给自己的熔断器。

**失败后排队的输入。** 如果运行因模型错误、缺少模型、没有可回答的内容、达到轮数上限或反复崩溃（`interrupted`、`restart_limit`）而结束，后面排队的输入会等到下个输入抵达。`settings.afterFailedRun` 可改变该行为。`continue` 像正常作答后那样立即用队列启动下一次运行，`withdraw` 则将这些提交项结算为 `unanswered`，原因为 `run_failed`。

**受阻任务。** 缺少任务定义或无法迁移时，任务图也会显示受阻原因。注册表变化若解除了阻塞，`onWake` 会报告 Session 已活跃，宿主无需轮询。

## 扩展

除内置任务外，Harness 执行的代码以具名扩展的形式安装在当前进程拥有的注册表里。

```typescript
import { createRegistry, defineExtension, defineTool, hook, section, ToolTask } from "@earendil-works/pi-durable";
import { CodingTools } from "@earendil-works/pi-durable/tools";

const Coding = defineExtension({
	name: "coding",
	sections: [section("preamble", () => "You are a concise coding assistant.", { tag: false })],
	hooks: [hook(ToolTask, { beforeTool: (call) => (isDangerous(call) ? { block: "Needs approval" } : undefined) })],
});

const registry = createRegistry();
registry.install(CodingTools);
registry.install(Coding);

```

扩展可提供 `tools`、`sections`、`hooks`、`wraps`（按名称装饰工具或提示词片段）和 `tasks`。默认情况下，每个对话按安装顺序选择全部已安装扩展。注册表本身不写入存储，对话只保存扩展名称。

## 工具

`@earendil-works/pi-durable/tools` 提供 `read`、`write`、`edit`、`bash`，以及包含这四种工具的 `CodingTools` 扩展。它们只通过本次调用的执行环境访问文件和进程，见[环境](#environment)。

`read` 将图像文件返回为一个图像内容块，调用它的程序得到 `ImageContent`。大小采用模型的 `inputLimits.images.resize` 限制，默认为 2000×2000 像素，base64 编码后最多 4.5 MB。没有图像处理器时，从文件头读尺寸，原样发送符合限制的 PNG、JPEG、GIF 和 WebP，不解码；其他格式或超限图像会被拒绝。有处理器时，每张图都解码，按 EXIF 方向转正，BMP 转为 PNG，并按需缩小。基于 Photon 的处理器运行在 WebAssembly 上，只在导入时加载。

```typescript
import { createNodePhotonImages } from "@earendil-works/pi-durable/images/node"; // or /images/cloudflare, or createPhotonImages(wasm) from /images
import { createCodingTools } from "@earendil-works/pi-durable/tools";

registry.install(createCodingTools({ images: await createNodePhotonImages() }));

```

图像也可能来自其他工具的结果（如 MCP 工具或代码模式的 `image()`），或宿主传入的附件。`@earendil-works/pi-durable/images/fit` 能配合任意处理器，在保存前将图像调整至对话模型的限制内，此后对话记录和提供方的提示词缓存都不必改写。`createFitImagesExtension(images)` 是覆盖所有送给模型的工具结果的 `afterTool` 钩子，用一条 `info` 诊断说明改动。`fitImage(bytes, mimeType, imageLimits(model), images)` 在宿主提交前处理附件，同时返回给模型的说明。像编码智能体一样，每张图都要解码，损坏图像不会进入记录；无法准备的图像会被省略，并留下说明。

```typescript
import { createFitImagesExtension } from "@earendil-works/pi-durable/images/fit";

const images = await createNodePhotonImages();
registry.install(createCodingTools({ images }));
registry.install(createFitImagesExtension(images));

```

不支持图像输入的模型会看到占位符。是否替换按请求决定，所以换到视觉模型后，它仍能看到先前读取的图。`read` 在 `details.imageUnsupportedByModel` 中记录不支持图像的模型名称，供界面展示。`/images/node` 在工作线程处理图像，一张大照片即便要一两秒也不会阻塞事件循环。连续 30 秒没有图像，线程退出并释放 Photon 的 WebAssembly 内存（`createNodePhotonImages({ worker: false, idleMs })`）。在其他环境中，`createPhotonImages()` 和 `/images/cloudflare` 使用调用线程，解码按图像完整尺寸占用 WebAssembly 内存，之后其内存不会缩小。Cloudflare Workers 等内存受限的宿主若无法保证图像很小，应省略处理器。

用 JSON Schema 定义自己的工具，此处用 `@earendil-works/pi-schema` 构建模式。`defineTool()` 根据 `parameters` 推导 `args` 的类型（使用 pi-schema 的 `Static`，其他 JSON Schema 得到 `unknown`）。Harness 在 `execute()` 前转换并验证参数。`api.output()` 流式输出执行进度；如果 `execute()` 返回时未给出 `output`，这些输出就成为结果。

```typescript
import { num, obj, str } from "@earendil-works/pi-schema";

const count = defineTool({
	name: "count",
	description: "Count from 1 to n",
	parameters: obj({ n: num() }),
	execute: async (args, api) => {
		for (let i = 1; i <= args.n; i++) api.output(`${i}\n`);
		return {};
	},
});
registry.install(defineExtension({ name: "count", tools: [count] }));

```

每次调用都是独立的持久任务，先提交调用意图，再执行 `execute()`。进程中途退出时，只有声明了 `replay: "safe"` 的工具才会在重新打开后重跑；否则模型收到 `interrupted` 错误结果，以及此前已提交的输出。声明可安全重放的工具若连续中断 `settings.restartLimit` 次，会以 `restart_limit` 错误结束。`execute()` 抛异常也会给模型一个错误结果。结果可附 `usage`，计入对话的[用量](#usage-and-cost)。也可返回 `control: { terminate: true }`；同一轮的全部结果都提出终止时，本次运行结束，不再请求模型。

结果有三条渠道。`output` 给模型，`structuredOutput` 给调用工具的程序（见[工具调用其他工具](#calling-tools-from-tools)），`details` 给界面。工具声明了 `structuredOutputSchema` 就要返回相符的 `structuredOutput`，由 Harness 验证。未声明模式时，程序得到有大小上限的输出。单段文字返回字符串，单张图返回其 `ImageContent`，空结果返回 `""`，其余返回内容列表，出错时也适用。`structuredOutput` 始终是工具自己给出的值。有模式的工具报错时保留它返回的值，没有该值时错误文本进入 `tool_error` 诊断，抛出异常的消息也如此。对话记录只保存 `output` 和 `details`。

```typescript
const lines = defineTool({
	name: "lines",
	description: "Count the lines of a file",
	parameters: obj({ path: str() }),
	structuredOutputSchema: obj({ lines: num() }),
	execute: async (args, api, context) => {
		const text = await readText(api, args.path, context);
		const count = text.split("\n").length;
		return { output: [{ type: "text", text: `${count} lines` }], structuredOutput: { lines: count } };
	},
});

```

嵌套调用的 `structuredOutput` 缺失、未声明或不合法，会得到含 `invalid_structured_output` 诊断的错误结果。模型直接发起的调用不会读取该字段，所以会丢弃它并通过 `onReport` 报告。错误结果可不提供结构化输出；程序此时可在 `tool_error` 诊断里找到文字。由 Harness 生成的错误（被阻止、无效、中断、中止）都不带结构化输出，即使 `afterTool` 钩子返回了也一样，原因见 `diagnostics`。如果钩子将错误转为成功，无模式工具的程序会得到其输出。`afterTool` 钩子若对有模式工具的 `output` 做脱敏，也必须对 `structuredOutput` 做同样处理。内置 `bash` 返回 `{ output, truncated, fullOutputPath?, exitCode }`，其中 `output` 是模型能看到的输出末尾，通过 `api.retainedOutput()` 读取。非零退出码会给出仍携带该值的错误结果。内置 `read` 将文本文件返回为字符串，将图片返回为 `ImageContent`，代码模式用 `image()` 显示它。

如果选中的多个扩展提供同名工具，后安装的替换先安装的。`wrapTool()` 装饰最终选中的实现。

```typescript
const Venv = defineExtension({ name: "venv", tools: [createBashTool({ commandPrefix: "source .venv/bin/activate" })] });
const Timing = defineExtension({
	name: "timing",
	wraps: [wrapTool(createBashTool(), (bash) => ({ ...bash, execute: (args, api, ctx) => timed(() => bash.execute(args, api, ctx)) }))],
});

```

### 工具调用其他工具

工具通过 `api.executeTool()` 调用另一个工具，代码模式脚本和 MCP 桥接也是这样工作。嵌套调用有自己的工具任务，归调用方任务所有。它会验证参数、执行 `ToolTask` 钩子、遵守自己的输出限制和重放策略，结果直接返回调用方，不进入对话记录。

```typescript
const testsPass = defineTool({
	name: "tests_pass",
	description: "Run the test suite and say whether it passed",
	parameters: obj({}),
	execute: async (_args, api, context) => {
		const run = await api.executeTool("bash", { command: "npm test" }, context, { progress: false });
		// Absent when bash did not finish, for example on a timeout.
		const exitCode = (run.structuredOutput as { exitCode: number } | undefined)?.exitCode;
		return { output: [{ type: "text", text: exitCode === 0 ? "passed" : "failed" }] };
	},
});

```

- 调用方收到 `taskId`、`structuredOutput`、`details`、`diagnostics`、`usage`、`isError`，面向模型的 `output` 不在其中。嵌套调用被阻止、参数无效、失败或中止都会返回 `isError` 结果。如果 `execute()` 已返回、调用方已中止或 Harness 已关闭，`executeTool()` 本身会拒绝。取消其 `context` 仅停止等待。
- 钩子可读取嵌套调用的 `call.parent`，因此防护逻辑可以区别对待脚本发起的调用。
- 调用方运行期间，`docs["pi.live"].nestedTools` 显示嵌套调用、调用方的 `parentCallId` 与 `parentTaskId`、实际参数，完成后还有 `summary`（错误、时长、用量）。嵌套调用的完整结果暂存在调用方的 `NestedCallDoc`。设置 `progress: false` 可避免将运行中输出放入 `pi.live`。调用方结算前，会中止所有遗留的嵌套调用，包括更早尝试启动的调用。调用方的结果消息不列出这些调用，但各自的任务记录会保留。
- 每次嵌套调用有一个键，默认取它在调用方所有嵌套调用中的位置，也可传 `{ key }`。允许重放的调用方在崩溃后按原顺序调用或传入相同键，就会重新取得原有调用，无论已完成还是仍在运行。如果崩溃发生在嵌套调用保存结果之前，按其自身的 `replay` 策略处理。所以有外部副作用的工具即使允许重放，也须自己保证幂等性。不可安全重放的调用方不会重跑，重启后其未完成的嵌套调用及其拥有的一切会在重新执行前被放弃。
- 嵌套调用的 `usage` 记在该工具名下；如果调用方把它再放入自己的结果，就会重复计数。
- 嵌套结果只在调用方结算前保存在调用方的任务文档中。每次调用对应一份 `NestedCallDoc`，按调用键索引，内容为 `{ taskId, result? }`。嵌套调用的任务记录只保留一份简短回执。存储的结果就是 `executeTool()` 的返回值，不含给模型的 `output`，因此图像和 `bash` 输出末尾都只存一次。
- 嵌套深度没有上限。使用默认 `callers` 的工具甚至可调用自身，必要时可按下文限制 `callers`。

### 可挂起的工具

工具若要等待外部事件，如 CI webhook、人的回答或慢作业，可返回挂起请求。`{ kind: "sleep", signals?, until?, checkpoint? }` 表示休眠，`{ kind: "wait", on, policy, checkpoint? }` 用来等待本调用拥有的任务，此时不必占用进程。唤醒后，以相同参数再次执行 `execute()`，由 `api.wake` 说明唤醒原因，`api.checkpoint` 携带挂起时保存的状态。首次调用时两者均为 `undefined`。工具在挂起期间被停止时，`cancel` 清理外部工作。

```typescript
const HOUR = 60 * 60 * 1000;
const CiResult = defineSignal({ name: "app.ci-result", version: 1, schema: obj({ status: oneOf(["passed", "failed"]), logUrl: str() }) });
const CiParameters = obj({ ref: str() });

const runCi = defineTool<typeof CiParameters, JsonValue, { buildId: string }>({
	name: "run_ci",
	description: "Run CI on a git ref and report the result",
	parameters: CiParameters,
	replay: "safe",
	async execute({ ref }, api, context) {
		const state = await api.readSignal(CiResult, "done", context);
		if (state?.kind === "value") {
			return { output: [{ type: "text", text: `CI ${state.value.status}: ${state.value.logUrl}` }], isError: state.value.status !== "passed" };
		}
		if (state !== undefined) return { output: [{ type: "text", text: "CI never reported" }], isError: true };
		// A fresh call. The tool's own idempotency key, memoized before the external call, so a rerun finds the same build.
		const runId = await api.memo("ci.run", crypto.randomUUID(), context);
		await webhooks.expect(runId, api.taskId, CiResult, "done", context); // your registry: the webhook signals this task
		const build = await ci.trigger({ ref, idempotencyKey: runId }, context);
		return { kind: "sleep", checkpoint: { buildId: build.id }, signals: [CiResult.key("done")], until: api.now() + 2 * HOUR };
	},
	// Runs when the call is stopped while parked; may run more than once.
	async cancel(_args, api, context) {
		if (api.checkpoint !== undefined) await ci.cancel(api.checkpoint.buildId, context);
		else await ci.cancelByKey((await api.memo<string>("ci.run", context))!, context);
	},
});

```

- **崩溃。** 挂起状态写入前崩溃，可安全重放的 `execute()` 会重新执行，因此要先记下幂等键。已挂起时重启不会执行工具代码，不可重放的工具也一样，并会保留嵌套调用和子任务。
- **`cancel`。** 调用在挂起时被中止，或已唤醒但尚未再次挂起就被打断并中止时，会运行清理回调。不可重放的调用在唤醒后以 `interrupted` 结束前也会运行它。如果执行中发现中止标记而拒绝本次挂起，也会就地执行回调，用的是本次尚未存储的检查点。回调内 `api.wake` 为 `undefined`，`api.checkpoint` 取上次挂起的检查点，不能创建嵌套调用或任务。首次执行若尚未挂起就被打断，不会运行清理回调；要靠幂等键找到遗留工作。
- **并行子任务。** `api.executeTool(name, args, context, { key, wait: false })` 启动嵌套调用并立即返回 `{ taskId, result(context) }`。用 `{ wait: { on: [taskId, ...], policy: "any" } }` 挂起，之后读取 `api.wake.ended`。`api.createTask(task, input, { ownership, key })` 可按键找回同一任务。唤醒后的嵌套调用和子任务需要显式键，因为同一位置可能已对应不同调用。按通常方式等待 `executeTool()`，即使嵌套调用已经挂起，调用方仍占用进程。
- **子智能体。** 向子对话提交时附上 `notify: { taskId: api.taskId, key: "answered" }`，再挂起等待 `SubmissionSettled.key("answered")`；信号的值就是子对话提交项的结算记录。
- **状态与结果。** 挂起的调用在 `pi.live` 中标记为 `sleeping` 或 `waiting`，不含输出，详情与诊断保留到下一次执行。`durationMs` 从调用开始计时，含挂起期间。挂起请求不符合规则（同时使用 `sleep` 和 `wait`、重用已消耗的键、等待不属于自己的任务）时，调用以 `invalid_park` 错误结束。包装器不能自行挂起，只能原样返回底层工具的挂起请求。

示例 [40](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/40-tool-waits-for-webhook.ts?ref=47.93.196.89) 至 [43](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/43-subagent-waits.ts?ref=47.93.196.89) 分别结合崩溃或手动停止演示这些用法。

### 谁可以调用工具

工具的 `callers` 决定调用者可以是模型、通过 `executeTool()` 的其他工具，还是两者（默认）。对话的 `modelTools` 可以缩小提供给模型的工具范围，同时让其他工具仍能调用它们。

```typescript
const codemode = defineTool({ name: "codemode", callers: ["model"], ... }); // scripts cannot start scripts
const search = defineTool({ name: "mcp__github__search", callers: ["tools"], ... }); // never offered to the model

// The model is offered only codemode; its scripts call read, bash, and the MCP tools.
await root.configure({ modelTools: [codemode] }, context);
// The model is offered everything but bash, which scripts may still call.
await root.configure({ modelTools: { remove: [bash] } }, context);

```

`conversation.agent()` 解析两份列表。`tools` 提供给模型，`callable` 供嵌套调用查找。实际启用哪些工具由 `tools` 决定，`modelTools` 不能增加未启用的工具。

标记 `deferred: true` 的工具在加载前不会提供给模型，其他工具随时可调用。`@earendil-works/pi-durable/tool-search` 提供的 `tool_search` 工具（`createToolSearchExtension()`）让模型搜索延迟加载的工具，通过 `control.addTools` 加载匹配项，并记入 `modelTools`。已加载的工具在当前分支上持续可用，即使压缩之后也是如此；`codemode` 提示词片段省略未加载的工具。适合 MCP 服务器等大型工具集。

### 重启时应放弃的任务

如果创建者只在内存中等待任务、重启后也不会接着处理，可以用 `abandonOnRestart: true` 创建任务。另一个 Harness 开始调度时，若发现它仍存活，会在再次执行前以 `abortReason: "restart"` 中止它及其拥有的一切。不可安全重放的工具所发起的嵌套调用，以及它通过 `api.createTask()` 创建的子任务，都会自动采用这个行为。如果放弃任务时找不到定义，它会等扩展安装后再让中止处理器清理。调用方和对话也会跟着等待，`harness.inspect()` 显示它受阻。此时再次中止会令它成为孤立任务，与其他受阻任务的中止行为相同。

## 代码模式

`@earendil-works/pi-durable/codemode` 提供 `codemode` 工具。模型编写 JavaScript，在 QuickJS 沙箱（`@earendil-works/pi-codemode`）内通过 `await tools.<name>(args)` 调用对话可用的工具。每一次都是嵌套工具调用，模型只收到脚本输出。重启后脚本能接着执行，已完成的调用无需重做。

```typescript
import { CodemodeSandbox } from "@earendil-works/pi-codemode";
import { createCodemodeExtension } from "@earendil-works/pi-durable/codemode";

registry.install(createCodemodeExtension({ sandbox: new CodemodeSandbox({ memoryLimitBytes: 256 * 1024 * 1024 }) }));

```

扩展还添加 `codemode` 提示词片段，在 token 预算内以 TypeScript 声明列出脚本能调用的工具。其他工具可用 `searchTools()`、`describeTool()`、`describeNamespace()` 查找。扩展可声明 `namespace: { name, description, instructions? }` 以按命名空间组织工具，例如每台 MCP 服务器一个扩展。片段列出每个选中扩展的命名空间和单行说明，即使它暂时还没有工具；`describeNamespace()` 返回该命名空间的使用说明。结果呈现方式类似编码智能体，包含标题、脚本输出，失败时还列出已发出的调用。超过 `max_output_tokens` 的文字被截断，全文写入临时文件。脚本还可使用 `models.*` 提供的模型目录、`models.classify()`、`models.generateImages()`，后两者通过内部工具的嵌套调用执行（用 `models: false` 禁用）。在 Cloudflare 上改传 `RemoteCodemodeSandbox`。执行中关闭沙箱（例如关机）不会给脚本定下结果，下一进程中的沙箱会接手恢复。失败的嵌套调用通常在脚本中以其错误文字拒绝，但如果工具声明了模式并随错误返回自定义值，脚本可取得该值。例如 `tools.bash` 即使非零退出也返回 `{ output, exitCode, ... }`，所以脚本要检查 `exitCode`。`store(key, value)` 和 `load(key)` 按对话保留 JSON 值，分支看到的是分支起点当时的值。

重启恢复的原理是确定性重放。沙箱使用虚拟时钟、带种子的随机数和 UTC；工具先把每个结果写入日志，再交给脚本。重启后重新执行脚本，依原顺序交回日志里的结果，脚本就会用同样的参数发出同样的调用。这些调用按键重新接上原嵌套调用，脚本随后继续。如果重跑走了不同路径、沙箱指纹或代码模式版本变化，或其间超过 `timeout_ms`，则以错误结束调用。重启时正在执行的嵌套调用，遵循其自身的重放策略。

## 系统提示词

每次请求前，系统按顺序渲染选中扩展的各个片段来构造系统提示词。每个片段可以读取解析好的智能体配置、本次请求的环境和已提交的文档。

```typescript
section("cwd", (input) => input.env?.cwd); // rendered as <cwd>\n...\n</cwd>; undefined omits it

```

对话的 `instructions` 最后渲染，片段名为 `instructions`。片段和工具的变更以标明位置的系统条目写入对话记录。只有变化的部分才重新发送，从而保持提供方提示词缓存可用。如果某个片段每次都生成不同内容，例如当前时间，就会破坏缓存效果。

## 每段对话的智能体配置

每个对话把运行配置存入其 `pi.agent` 文档。`configure()` 在一次提交中修改它；未设置字段沿用宿主配置。

```typescript
await root.configure(
	{
		model: { provider: "openai", modelId: "gpt-6-sol" },
		thinkingLevel: "high",
		extensions: { remove: [Coding] }, // edits the host default; an array selects exactly these, in order
		tools: [readTool, bashTool], // an array enables exactly these; { remove: [...] } drops some
		modelTools: [readTool], // of those, offer the model only read; tools may still call bash
		instructions: "Only read; never edit files.",
		cwd: "/work/repo",
		maxTurns: 50, // tool rounds one run takes at most; unset: no limit
	},
	context,
);
await root.configure({ tools: null }, context); // null clears a field back to the host default
const agent = await root.agent(context); // resolved: model, extensions, tools, sections, cwd

```

扩展和工具以对象传入、按名称保存，因此保存的名称可以比代码存在得更久。卸载扩展后，选中它的对话暂时得不到它，重新安装即可恢复。`createConversation()`、`fork()` 和 `root()` 都可通过 `agent` 接受同样的变更。任务拥有的对话（如子智能体对话）从所属任务所在对话复制初始配置。分支继承父对话在分支条目处的配置。请求在准备时固定模型、提示词与提供的工具，之后的变更从下一次请求生效。工具调用和钩子按各自任务阶段解析智能体，每次使用时依据当前 `cwd` 构建环境，因此更改 `cwd` 或扩展也可能影响模型已经发出的调用。

**轮数上限。** `maxTurns` 限制一次运行的工具轮数。达到上限的那一轮仍执行工具，随后运行像失败一样以 `unanswered`、原因 `turn_limit` 结束（记录 `runFailure`，由 `settings.afterFailedRun` 决定其后排队输入的处理）。一旦有最终答案就结束运行，所以不会因此截断答案。计数保存在 `docs["pi.live"].run.turns`，可跨重启恢复。每次运行从 0 开始，包括由继续请求启动的运行（见[忙碌中的对话](#busy-conversations)）。自动继续的宿主或工具每次都有新预算，须自行限制循环。`onYield` 发起的继续同样清零，扩展可通过 `api.snapshot` 读取 `pi.live.run.turns` 和 `pi.agent.maxTurns`，自行限制次数。传给 `configure()` 的值若不是至少为 1 的整数或 `null`，会抛 `RangeError`。变更在当前轮末生效，子对话和分支像其他智能体配置一样继承它。

## 设置

用 `settings` 传入所有对话共用的运行策略。策略每次使用都读取，不写入存储，因此可用 getter 动态获取，例如从设置文件读取。

```typescript
const harness = await Harness.open(storage, {
	models,
	registry,
	settings: {
		extensions: [CodingTools, Coding], // default selection; absent: every installed extension
		stream: { timeoutMs: 120_000 },
		retry: { maxRetries: 3 },
		compaction: { reserveTokens: 16384 },
		progress: { partialIntervalMs: 100, outputIntervalMs: 100, persistWithinMs: 1_000 },
		toolExecution: "parallel",
		contextRetentionMs: 600_000, // inactive conversations (idle, or all live work parked) keep their context in memory this long (checked lazily where background timers are declined, as in Workers)
		documentRetentionMs: 600_000, // loaded documents nothing observes stay in memory this long after their last use; observed ones always
		get followUpMode() {
			return userSettings.followUpMode;
		},
	},
}, context);

```

## 环境

`env` 为每次工具调用、提示词片段渲染和 `runtime.env()` 构建执行环境。它接收对话 ID、智能体的 `cwd`，并可读取已提交状态，因此同一个函数可以给每段对话分配一个目录或容器。

```typescript
import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";

const harness = await Harness.open(storage, {
	models,
	registry,
	env: ({ cwd }) => new NodeExecutionEnv({ cwd: cwd ?? process.cwd() }),
}, context);

```

`env` 抛出的异常会转为本次调用的错误结果。没提供环境时，内置工具也以错误结果结束。每次调用都创建新环境对象没有问题，`edit` 和 `write` 按环境的 `id` 和路径，串行修改同一个文件。自定义 `ExecutionEnv` 应设置 `id`，使相同 ID 在相同路径看到同一批文件，如每个容器使用一个 ID。

宿主也可直接使用环境，例如显示项目文件。`openBinaryReader()` 从一个已打开的文件中按字节范围读取，`openDirReader()` 分页读取目录，`exec()` 配合 argv 数组直接运行程序而不经过 shell，并标明各段输出来自哪个流。

```typescript
const status = { stdout: "", stderr: "" };
await env.exec(["git", "status", "--porcelain=v2", "-z"], {
	onOutput: (text, _context, { stream }) => {
		status[stream] += text;
	},
}, context);

```

取消上下文可停止一次调用；`cleanup()` 用于关闭整个环境。与下文存储类似，自定义环境可使用 `@earendil-works/pi-durable/testing` 导出的 `registerEnvConformance()` 检验自身是否符合约定。

某些环境还实现可选的 `listFiles()`，像 `fd` 一样列出指定目录下任意深度的文件和子目录，跳过被 git 忽略的项，达到限制时以 `truncated` 标记。`NodeExecutionEnv` 不提供该方法，pi-env 的 `RemoteExecutionEnv` 和 `LocalExecutionEnv` 提供。方法缺失或返回 `not_supported` 时，调用方退回到自行遍历。

```typescript
const listing = await env.listFiles?.(".", { exclude: ["node_modules"], maxEntries: 50_000 }, context);

```

## 热重载

重新安装一个同名扩展会一步完成原位替换。

```typescript
registry.install(await loadCodingExtension()); // same name "coding": replaces the installed one

```

`registry.uninstall(extension)` 按名称移除已安装的扩展，无论当前安装的是哪个对象。

已启动的工作保留取得的代码。运行中的工具按旧实现完成，每个任务阶段在开始时基于当时的注册表解析一次钩子和智能体。下一阶段、请求或调用才使用新代码。重启后应重新安装相同扩展，一旦安装，属于其 `tasks` 的待处理任务就可恢复。

## 观察对话

界面所需的数据都是已提交的状态。`watch()` 返回对话结构化视图的观察句柄。连接时先取得当前值，以后每次提交只要影响视图，就连同这次提交的 Chord 变更操作一起送达，每次只执行一个回调。

```typescript
const watch = await root.watch(context);
render(watch.value); // the state at attachment
watch.start(async (call) => {
	if (call.kind !== "value") return; // Durable's watches end on a failure; they never send a failed call
	const { value, ops } = call;
	// value.entries: a window over the transcript, newest last; value.before: the entry just before it
	// value.docs["pi.live"]: the run, the running generation (streamed partial, retry, deferred), tool calls (output,
	//   details), compactions, and why the last run ended without an answer (runFailure)
	// value.docs["pi.inbox"], value.docs["pi.usage"], value.docs["pi.agent"], value.docs["pi.provider"]
	render(value);
	await send(ops); // for example to a remote client that applies them
});
// later: await watch.stop();

```

视图的 `entries` 只覆盖一个窗口，因此首次读取和重连都无需载入完整记录。默认从最近 50 条开始，后续条目追加到末尾；当窗口将超过 100 条时，一次删除最旧的一段，只留最近 50 条。`watch(context, { min, max })` 可调整上下限。`from` 选择初始值从何处开始（断线后 `transcript.resume` 也这样做）；连接后提交的每条新记录都会追加。所以 `from` 如果越过最新条目，初始窗口为空，随后仍会接收新条目。压缩摘要与重置也作为普通条目留在原位，摘要的 `head` 指向被概括范围的末尾。`conversation.context()` 返回模型实际看到的有效记录。

`ConversationTranscript` 帮客户端记住已滑出窗口的记录。把视图的每个值交给 `merge()`，渲染它返回的 `items`，即客户端掌握的整份记录。顶部带“加载更早内容”标记；卡顿或重连时漏掉的区间带“加载更多”标记。

```typescript
import { ConversationTranscript } from "@earendil-works/pi-durable";

const transcript = new ConversationTranscript((query, limit, ctx) => root.entries(query, limit, undefined, ctx));
const watch = await root.watch(context);
render(transcript.merge(watch.value));
watch.start(async (call) => {
	if (call.kind === "value") render(transcript.merge(call.value));
});

// When a marker scrolls into view:
render(await transcript.loadEarlier(context)); // the page before the oldest entry
render(await transcript.fillGap(gap, context)); // the next page of a gap item

// Reconnect after a drop: only what was missed, when it fits the window, otherwise the newest entries and a gap.
const resumed = await root.watch(context, transcript.resume);

```

条目提交后不再变化，所以合并只会添加。没有新增内容时返回原来的 `items` 数组。见 `test/examples/31-transcript.ts`。

监听使用 Chord 的 `WatchHandle`，由 `@earendil-works/chord/watch` 导出，Durable 也重新导出。每次回调收到一个按 `kind` 区分的 `WatchCall` 和最近一次提交的上下文；值通知为 `{ kind: "value", value, ops, retired }`。Chord 还用 `{ kind: "failed", error }` 通知源可恢复的故障；Durable 的故障是终局性的，会直接结束监听。监听只结束一次，`closed`（或 `stop()`）给出按 `kind` 区分的 `WatchEnd`。可能值有 `stopped`、`aborted`（取得句柄时的上下文被取消）、`ended`（Harness 关闭，或任务文档所属任务结束）、`listener_error` 和 `failed`（Harness 失败）。结束后保留最后的值，释放对 Harness 的引用。

有些适配器必须与 Durable 的内存同步变化，例如把对话视图变成 Chord 的数据源。这时应安装同步观察者。`harness.observeConversation(id, observer, context)`、`harness.observeTaskGraph(observer, context)` 和 `harness.observeDoc(token, ...scope, observer, context)` 返回当前 `value` 与 `detach()`；此后每个变化在内存采纳时立刻原样交给 `observer.advance(call, context)`，形式为 `WatchCall`（一律是 `value` 调用），不折叠。持久提交在存储的提交过程中通知；延期提交立即通知，早于落盘。文档观察者按地址上的每次变化分别收到调用，同一提交先退役再重建文档会收到两次。注册表变化若改变任务的 `blocked` 原因，任务图也会在没有提交时前进。在 `observeXXX()` 的 Promise 完成前就可能收到变更，其操作从观察开始时的 `value` 应用。`observer.end(end)` 携带 `WatchEnd` 且只调用一次。Harness 关闭时为 `ended`，任务文档则在结束所属任务的提交让文档退役后立即结束；Harness 失败时为 `failed`。`advance` 只应快速记录变化，不等待异步操作、不调用 Harness、不抛错，因为每次提交都要等它。抛异常或返回拒绝的 Promise 会被上报，观察者被解除，结束原因为 `listener_error`。异步监听建立在这些观察者之上。

回调执行期间完成的提交会合并到下次回调。它收到最新视图和折叠后的全部操作，如对同一字符串的追加会拼接，对同一字段的多次设置只留最后一次。若积压超过 10,000 个操作，则以一次根替换 `[["r", view]]` 送出最新完整视图，含其条目窗口。迟到或重连的客户端从当前视图开始，不重放历史。

默认情况下，部分回答与工具输出最多每 100 毫秒提交一次，监听立即看到每次提交。存储稍后将它们一起持久化为延期提交（见[自定义状态](#your-own-state)），通常随下一个读取 `pi.live` 的提交写入，例如回答或工具调用结束时；最迟等待 `settings.progress.persistWithinMs`（默认 1,000 毫秒）。崩溃最多可能损失约这样一个时间窗口的回答或输出。流在第一秒内崩溃，可能没有中止条目，也不会记录这次尝试的用量。用 `settings.progress` 调整间隔，例如远程存储可用 `{ partialIntervalMs: 500, outputIntervalMs: 500 }` 降低提交频率。

## 忙碌中的对话

运行正在处理输入时，对话处于忙碌状态。向忙碌的对话提交，会把提交项放入该对话收件箱，视图中对应 `docs["pi.inbox"]`。

```typescript
await root.submit({ type: "input", content: "Also run the tests" }, context); // follow-up (default)
await root.submit({ type: "input", content: "Use pnpm, not npm", whenBusy: "steer" }, context);
await root.submit({ type: "input", content: "Only if idle", whenBusy: "reject" }, context); // throws ConversationBusy
await root.submit({ type: "input", content: "Only if busy", whenBusy: "steer", whenIdle: "reject" }, context); // throws ConversationIdle when idle
await root.submit({ type: "write", entry: { kind: "app.note", data: "user opened a file" } }, context);

```

- **引导消息（steer）** 在当前工具轮结束后写入，加入正在执行的运行。
- **后续消息（follow-up）** 在当次运行给出答案后写入，并启动下次运行。
- **`whenIdle: "reject"`** 在没有运行执行时拒绝输入，因此这类输入不会自己启动一次运行。与 `whenBusy: "steer"` 搭配时，它要么引导当前运行，要么抛 `ConversationIdle`。已回答但还在等待[运行结束任务](#work-at-the-end-of-a-run) 的运行仍在工作，这时输入会排队，之后启动下次运行。
- **`admit(tx, draft)`** 按同样规则在你自己的事务中接纳提交，返回提交项 ID。你的检查、接纳决定和写入一起成功或一起回滚。  
```typescript  
const id = await harness.commit(async (tx) => {  
  const chat = await tx.doc(MyChat, root.id); // your own conversation document  
  if (chat.muted.includes(userId)) throw new Error("Muted");  
  const id = await root.admit(tx, { type: "input", content: text, whenBusy: "steer", whenIdle: "reject" });  
  chat.sent.push({ id, userId }); // your own state, same commit  
  return id;  
}, context);  
```  
每个事务只调用一次，而且要在本事务的表写入（`appendEntry()`、`createTask()`、另一次接纳）之前；任何路径违反规则都抛 `ReadAfterWrite`。文档则可在它之前或之后读写。输入被拒绝（`ConversationBusy`、`ConversationIdle`）时在任何写入前抛出，可由你捕获。事务落盘前接纳是暂定的，如果回调随后抛错，这个提交项就不存在。任务和工具可在其事务中通过 `api.conversation(id)` 做相同的事，写入的条目带任务的 `byTaskId`。
- **写入** 只追加条目，不请求模型。只含 `kind` 和 `data` 的写入不影响模型可见内容，因此立即追加，即使运行中也无需排队；例如聊天消息发送后就能显示。它可能比更早提交但仍在排队的内容先出现。不过如果前面排队的是重置，写入会等待，以免被重置隐藏。带 `model`、`head` 或 `edits` 的写入则像引导消息一样等到下一个边界。
- `await submission.abort(context)` 撤回排队的提交项。
- [设置](#settings) 中的 `steeringMode: "all"` 和 `followUpMode: "all"` 会让队列中的所有项目一次写入，默认则每轮处理一个。

运行失败时，排队的项目留在收件箱，直到下一次输入、需要排队的写入或继续请求到来，再按先后顺序写入。

运行未回答就结束时，`docs["pi.live"].runFailure` 会记录原因，直到下一次运行开始。可能是 `model_error`、`no_model`（`detail` 记录错误文字或缺少的模型）、`aborted`、`reset`、`interrupted`（模型回答时宿主停止且没有剩余重试机会）、`faulted`、`orphaned`、`restart_limit`（运行所属任务无法继续）、`turn_limit`（工具轮达到对话的 `maxTurns`）或 `nothing_to_answer`（下文的继续请求发现没有待回答内容）。其中也列出该运行的输入，均结算为 `unanswered`，原因通常相同。孤立运行的输入则记录成为孤立任务的原因（`missing_task`、`task_too_old`、`migration_failed`）；`no_model` 在结算结果中不带 `detail`，见规范第 8.2 节。

要在不输入新消息的情况下继续，可提交一次继续请求。它以现有上下文启动运行，让模型回答之前遗留的用户消息或工具结果。

```typescript
const live = await harness.snapshot(LiveDoc, root.id, context);
if (live?.run === undefined && live?.runFailure !== undefined) {
	const resumed = await root.submit({ type: "continue" }, context); // throws ConversationBusy while busy
	await resumed.wait(context); // done with the answer, or unanswered like any run
}

```

继续请求从不排队。当前仍在运行时会抛 `ConversationBusy`，因为有没有内容可继续取决于该运行的结果。上次失败遗留的排队项目会先写入，并加入新运行。上下文为空或末尾已经是回答（包括因输出限制被截断的纯文本回答）时，不发请求，以 `unanswered`、原因 `nothing_to_answer` 结束。带工具调用的截断回答可以继续，因为那些调用没有执行，上下文最后存的是它们的错误结果。工具可通过 `api.conversation(id)` 继续自己拥有的对话，就像向这些对话提交内容一样。

输入默认以 `pi.user` 条目写入。若要换一种展示形式，可给输入的 `entry` 指定自定义种类和数据，模型仍将 `content` 视作用户消息。

```typescript
await root.submit(
	{
		type: "input",
		content: "ann: can you check the build?",
		entry: { kind: "chat.mention", data: { author: "ann", text: "can you check the build?" } },
	},
	context,
);
// placed as { kind: "chat.mention", data: { author: "ann", ... }, model: [{ role: "user", content: "ann: can you check the build?" }] }

```

处理方式与普通输入一致，可以启动运行、引导、跟进或拒绝，并可得到回答。排队期间收件箱项目携带该条目。种类名称不能以 `pi.` 开头。

## 重置与交接

`reset()` 开启新的上下文。旧条目不再对模型可见，但仍保存在存储中。

```typescript
await root.reset(undefined, context);                                  // start from nothing
await root.reset("We were fixing the flaky login test. Continue.", context); // start from a handoff note

```

忙碌时，重置像写入一样排队。如果在工具轮中放入重置，当前运行结束，其输入结算为 `unanswered`、原因为 `reset`，排队的输入在新上下文中执行。

工具可返回 `control: { handoff: "..." }`，以其中的文字写入同样的重置，但让当前运行继续。下一次模型请求采用新上下文，原提交项以最终回答结算。排队的写入和引导消息排在交接文字之后，后续消息等待运行结束；排队的 `reset()` 仍会结束运行。如果本轮所有调用同时都返回 `terminate: true`，则在交接后结束运行。

## 上下文压缩

压缩会缩短模型看到的上下文。它概括较早的条目，追加一条 `pi.compaction` 存放摘要，并标记要保留的首条记录。早期条目仍留在存储中。

```typescript
const id = await root.compact("Keep the failing test names", context); // manual, with optional instructions
const { outcome } = (await harness.waitForTask(id, context)).state;
if (outcome.status === "completed" && outcome.result.submissionId !== undefined) {
	const placed = await (await harness.submission(outcome.result.submissionId, context))!.wait(context);
	console.log(placed.status); // "done", or "unanswered" with reason "stale"
}

```

生成摘要期间，对话继续工作。空闲时立即放入摘要，否则等到下个轮次边界。按 Esc（`abort()`）可取消手动压缩。

生成任务也会自动压缩，由[设置](#settings) 控制。

```typescript
settings: {
	compaction: {
		enabled: true, // automatic compaction; manual compact() always works
		reserveTokens: 16384, // above contextWindow - reserveTokens, the next request waits for a compaction
		keepRecentTokens: 20000, // roughly how much recent context stays verbatim
		backgroundTokens: 32768, // this far below that, a compaction starts in the background; 0 disables it
		modelOverrides: {
			// exact "provider/modelId"; each field set here replaces the one above for that model
			"local/small-32k": { reserveTokens: 4096, keepRecentTokens: 8000, backgroundTokens: 4096 },
		},
	},
}

```

固定的 token 数往往无法同时适应 32k 和 1M 的上下文窗口，`modelOverrides` 让一个 Harness 能服务两者。检查阈值、处理上下文溢出以及选择摘要范围时，都用对话当时的模型选择配置项。

单个对话可以有同样结构的压缩设置，像 `maxTurns` 一样保存在智能体配置中。

```typescript
await root.configure({ compaction: { enabled: false } }, context); // no automatic compaction here, on any model
await research.configure(
	{ compaction: { keepRecentTokens: 60000, modelOverrides: { "local/small-32k": { keepRecentTokens: 12000 } } } },
	context,
);
await root.configure({ compaction: null }, context); // back to the settings

```

每个字段按优先级取最先设置它的一层。依次是对话的 `modelOverrides` 项、全局设置的 `modelOverrides` 项、对话的普通字段、全局普通字段。模型专用值优先于通用值；同层次上，对话优先于 Harness。上例中的 `research` 在所有层都没有模型覆盖时保留 60000 个 token，在 `local/small-32k` 上保留 12000；没有自己的覆盖项就会采用全局的 8000。例外是对话设置的 `enabled: false`，它优先于全局的模型覆盖。修改会整体替换已存的压缩设置。token 数若不是非负整数，`configure()` 抛 `RangeError`。子对话和分支按通常规则继承它。

提供方因上下文过长而拒绝请求时，生成任务会压缩并重试一次。如果一个摘要要裁去的位置早于当前上下文起点，放置摘要时以 `stale` 结算，所以多个摘要同时处理时，以推进最远的裁剪点为准。摘要费用计入 `pi.usage`。`CompactionTask` 上的 `beforeCompact` 钩子可以拒绝压缩，也可提供自己的摘要。

生成任务在阻塞阈值处等待的压缩若失败，生成也随之失败，不发模型请求。输入以 `unanswered`、原因 `model_error` 和详情 `Compaction failed: <error>` 结算。如果没有可压缩内容或压缩被拒绝，则请求继续。

运行中的压缩列在 `docs["pi.live"].compactions`，含 `trigger`（`manual`、`threshold` 或 `overflow`）、尝试次数和重试退避。最近一次失败的任务、触发原因和错误保存在 `docs["pi.live"].compactionFailure`，直到某次压缩成功产出摘要。

## 钩子

扩展可通过钩子观察或调整内置任务，在选择该扩展的对话中生效。

```typescript
import { GenerationTask, hook, ToolTask } from "@earendil-works/pi-durable";

const Guard = defineExtension({
	name: "guard",
	hooks: [
		hook(ToolTask, { beforeTool: (call) => (call.name === "bash" ? { block: "bash is disabled here" } : undefined) }),
		hook(GenerationTask, { onYield: (answer) => (needsMoreWork(answer) ? { kind: "continue", continue: "Keep going." } : undefined) }),
	],
});

```

- **生成任务。** `beforeRequest` 替换一次请求的消息；`beforeProviderRequest` 替换该次发送给提供方的请求体，例如设置专用字段；另有 `afterResponse`。`onYield` 可增加一条用户消息继续运行，也可用任务决定是否接受回答。`afterTools` 在本轮工具执行完毕后运行，可返回本轮结束前需执行的任务。`afterRun` 指定整个运行结束前需执行的任务。用下文的 `hookTask()` 构建这些任务。
- **工具。** `beforeTool` 可阻止调用、改写参数或使调用等待（见下文），`afterTool` 可替换结果。`afterTool` 能看到工具任务写下的每个结果，包括 Harness 自己生成的错误结果（不可用、无效、阻止、中断、达到重启上限、中止），通过诊断码区分。超过 `settings.restartLimit` 后不再运行。中止时，它在中止处理器内执行，所以慢钩子会延迟 `abort()`。

要使钩子只影响某些对话，只在那些对话选用其扩展即可，例如 `configure({ extensions: { add: [Guard] } })`。

钩子可读已提交的文档（`api.snapshot()`）和对话原始历史（`api.entry()`、`api.entries()`）。压缩不会改动这些原始历史。

### 工具执行前的检查

`beforeTool` 钩子可返回 `{ sleep: { signals?, until? } }`，使调用在真正执行前挂起，例如等人批准。每次唤醒都从头检查，包括重新执行所有 `beforeTool` 钩子。检查逻辑用 `api.readSignal()` 读取自己的键，再决定放行、阻止，或换一个新键继续休眠。

```typescript
const Approval = defineSignal({ name: "approvals.decision", version: 1, schema: obj({ allow: bool() }) });
const DAY = 24 * 60 * 60 * 1000;

const Approvals = defineExtension({
	name: "approvals",
	hooks: [
		hook(ToolTask, {
			beforeTool: async (call, api, context) => {
				if (call.name !== "bash" || !isRisky(call.arguments)) return undefined;
				const key = digest(call.arguments); // other arguments, another question
				const state = await api.readSignal(Approval, key, context);
				// One deadline per question: later passes reuse the memoized one.
				const until = await api.memo(`approvals.until.${key}`, api.now() + DAY, context);
				if (state === undefined) return { sleep: { signals: [Approval.key(key)], until } };
				if (state.kind === "expired") return { block: "No approval within a day" };
				return state.value.allow ? undefined : { block: "Not approved" };
			},
		}),
	],
});

```

- 遇到第一个 `block` 或 `sleep` 就停止执行后续检查。只有一次完整检查两者都未出现，才会执行调用。此后不再为这次调用运行 `beforeTool`。
- 等待时，该调用的状态为 `sleeping`。负责展示问题的组件用 `harness.signal()` 和状态中给出的任务 ID 送回答案。
- 安装、卸载扩展及重新打开 Harness 都会唤醒挂起的检查，以当前安装的检查规则为准。像上例一样记住所定截止时间，并让检查的副作用具有幂等性，因为每次唤醒都会再跑一次。
- 批准只针对审批时看到的参数；若后续钩子改写它们，实际执行的可能是未经批准的参数。安排扩展顺序时要考虑这一点。
- 不合规的休眠（既无 `until` 也无信号，或重复使用已经等待过的键）会让调用以 `invalid_park` 错误结果结束。

### 运行结束时的工作

运行已回答之后，`afterRun` 钩子无需工具调用也能启动持久工作，例如在改过文件后运行项目测试。钩子返回用 `hookTask()` 构建的任务，生成任务将它们创建为子任务，等其完成再结束本次运行。

```typescript
import { defineExtension, GenerationTask, hook, hookTask, ToolResultEntry } from "@earendil-works/pi-durable";

const TestsAfterEdits = defineExtension({
	name: "tests-after-edits",
	tasks: [RunTests], // a task of yours, defineTask(): runs the tests, then commits its result
	hooks: [
		hook(GenerationTask, {
			afterRun: async (run, api, context) => {
				// The run's own entries, also those a compaction summarized.
				const range = { minEntryId: run.first, maxEntryId: run.last, order: "ascending" } as const;
				const { items } = await api.entries(range, 1000, undefined, context); // page with `next` for longer runs
				const edited = items.some((entry) => {
					const message = entry.model?.[0];
					return ToolResultEntry.is(entry) && message?.role === "toolResult" && message.toolName === "edit";
				});
				return edited ? { tasks: [hookTask(RunTests, { command: "npm test" })] } : undefined;
			},
		}),
	],
});

```

- **时机。** 最终回答或 `terminate` 轮之后执行；`onYield` 决定继续当前运行时不执行，失败或中止后也不执行。
- **先交付回答。** 调用钩子前，回答已提交，本次运行的输入已结算为 `done`，所以 `Submission.wait()` 在回答出现时就返回。
- **任务结束前仍算忙碌。** `pi.live.run` 继续保留，`run.afterRun` 列出这些任务，对话仍忙碌，`waitForIdle()` 也会等它们。点击停止会中止它们，崩溃后会恢复。如果崩溃发生在任务创建前，就重新询问钩子；已创建后不再重复询问。
- **其间收到输入。** 引导和后续消息排队，任务结束后启动新运行。`whenBusy: "reject"` 和继续请求会抛 `ConversationBusy`。
- **让模型收到结果。** 任务在提交前用 `const handle = (await runtime.conversation(runtime.conversationId, context))!` 取得对话句柄，再在事务中、自己的表写入之前用 `handle.admit(tx, draft)` 接纳一条写入或后续消息（如“测试失败……”）。两者都在运行结束时放入；写入排在所有已排队的用户输入前，后续消息则遵守队列顺序。后续消息会启动一次修复运行，再次询问 `afterRun`，而且轮数预算刷新，所以扩展应自行限制这类循环。
- **无效请求。** 请求了未安装或内置的任务、输入不是 JSON、`initial()` 抛异常等情况，会通过 `onReport` 按钩子所属扩展报告，并跳过该请求，运行仍正常结束。

### 接受回答前和一轮结束前的工作

`onYield` 和 `afterTools` 钩子同样用 `hookTask()` 返回任务，由生成任务作为子任务创建。

```typescript
const Reviewer = defineExtension({
	name: "reviewer",
	tasks: [Review, AskToGoOn], // tasks of yours
	hooks: [
		hook(GenerationTask, {
			// Review completes with a YieldDecision: { continue: "Explain your reasoning." } sends the agent back.
			onYield: async () => ({ tasks: [hookTask(Review, null)] }),
			// AskToGoOn completes with an AfterToolsDecision: { terminate: true } ends the run after this round.
			afterTools: async () => ({ tasks: [hookTask(AskToGoOn, null)] }),
		}),
	],
});

```

- **`onYield` 任务决定是否接受答案。** 回答已写入记录，但本次运行的输入仍未结算，所以 `Submission.wait()` 及其他调用者都只会看到任务最终认可的回答。任务从 `docs["pi.live"].run.yield.answer` 找到答案条目。按创建顺序，第一个以 `{ continue }` 携带有效用户输入完成的任务，会让智能体在同一次运行中继续，除非其间已有用户消息或重置排队。无效的继续输入会让判断顺延到下一个任务。这适合复核回答；若是交付已被认可的回答之类的工作，使用 `afterRun`。
- **`afterTools` 任务在当前轮结束前运行。** 任务如果以 `{ terminate: true }` 完成，本次运行结束，效果等同于该轮全部工具都要求终止。如想改变智能体方向，可在任务最后的事务中提交一条引导消息。除 `null` 和 `AfterToolsDecision` 外，其他结果均上报并忽略。
- **挂起。** 这些任务可以休眠等待信号，例如某人的回答；Session 在等待期间不占用进程。

## 更多对话与分支

```typescript
const other = await harness.createConversation({ ownership: { kind: "ownerless" } }, context);
const fork = await root.fork(entryId, { ownership: { kind: "ownerless" } }, context);

```

分支看到父对话截至 `entryId` 的条目，随后独立发展。它保留父对话在该条目处的智能体配置，取得新的提供方会话身份。创建对话和创建分支都接受 `agent` 和 `init`，在创建事务内生效。

## 中止与子智能体

`await root.abort(context)` 停止一个对话。排队的输入被撤回，排队的写入保留，当前工作中的每个任务都被中止。对话进入空闲后该调用返回。

对话可以**归一个任务所有**。子智能体工具在 `api.commit()` 中以 `ownership: { kind: "task", taskId: api.taskId }` 创建子对话，再通过 `api.conversation(id)` 驱动它。

```typescript
const Subagent: Extension = defineExtension({
	name: "subagent",
	tools: [
		defineTool({
			name: "subagent",
			description: "Delegate a self-contained task to a subagent and get its answer back.",
			parameters: obj({ task: str() }),
			replay: "safe", // a rerun after a crash finds the same child and submission
			execute: async (args, api, context) => {
				const child = await api.commit(async (tx) => {
					// The ownership index remembers the child, so a rerun reuses it.
					const existing = (await tx.scanConversations({ ownerTaskId: api.taskId }, 1)).items[0];
					if (existing !== undefined) return existing.id;
					// Starts as a copy of this conversation's agent: model, extensions, tools, cwd.
					const created = await tx.createConversation({ ownership: { kind: "task", taskId: api.taskId } });
					// A cheaper model, and no subagents of its own.
					await configure(tx, created.id, { model: haiku, extensions: { remove: [Subagent] } });
					return created.id;
				}, context);
				await api.details({ conversationId: child }, context); // lets a UI attach to the child
				const request = { type: "input", content: args.task, requestId: `subagent:${api.taskId}` } as const;
				const settled = await (await (await api.conversation(child, context))!.submit(request, context)).wait(context);
				return { output: [{ type: "text", text: settled.status }] };
			},
		}),
	],
});

```

所有权决定如何处理子工作。

- 中止调用会中止其子对话。调用失败也一样，例如 `execute()` 抛错，或崩溃打断了一个不可安全重放的调用。
- 子对话空闲后，父对话才算空闲。
- 用 `{ background: true }` 创建的任务形成一道所有权边界。父对话中止时，它拥有的工作继续，也不会让父对话保持忙碌。使用 `root.abort(context, { background: true })` 则连它一并中止。

下面两个示例给出了这两种模式的应用代码。

- [21-subagent-foreground.ts](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/21-subagent-foreground.ts?ref=47.93.196.89) 实现上文的工具，返回子对话的回答。界面通过调用的 `details` 找到子对话，在调用下面缩进打印子对话的事件。
- [22-subagent-background.ts](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/22-subagent-background.ts?ref=47.93.196.89) 用一个 `subagent` 工具管理持久子智能体，可以启动、发送引导或后续消息、等待、停止和列举子智能体。每个子智能体归一个后台锚点任务所有，因此父对话的 Esc 和等待空闲操作都不会传到它。每条消息交给后台报告任务，取得回答后以跟进输入的形式发回父对话；请求 ID 保证重启不会重复发送消息或报告。

## 子任务

任务可以拥有子任务，用 `ownership: { kind: "task", taskId }` 创建，并提交 `waiting` 状态来等待它们。

```typescript
pay: async (task, runtime, context) => {
	await runtime.commit(async (tx) => {
		const payments = [];
		for (const card of task.input.cards) {
			payments.push(await tx.createTask(Payment, { card }, { ownership: { kind: "task", taskId: task.id } }));
		}
		// Resume in `decide` once every payment is done; the first failure aborts the rest.
		return { status: "waiting", checkpoint: { phase: "decide", payments }, on: payments, policy: "failFast" };
	}, context);
},
decide: async (task, runtime, context) => {
	const outcomes = await runtime.outcomes(task.state.checkpoint.payments, context);
	// ...commit the checkout's own outcome
},

```

- **等待。** 等待期间任务不执行代码。`allSettled` 在 `on` 中每个任务都完成时恢复；`failFast` 还会在首个子任务失败时中止其他子任务；`any` 在任一任务完成时恢复，`task.state.wake`（`{ reason: "tasks", ended }`）列出已结束者。使用 `allSettled` 或 `any` 时，`on` 也可包含其他任务。
- **完成。** 如果任务已有结果而它拥有的工作仍在运行，会进入 `completing`。结果已定，但要等所属工作全部结束才进入终态，`waitForTask()` 才返回。若结果为失败或中止，会先中止这些工作。
- **中止。** 自下而上处理。先中止任务所拥有的工作，全部结束后再启动它自己的中止处理器，让每个任务负责撤销自身的影响。

[23-child-tasks.ts](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/23-child-tasks.ts?ref=47.93.196.89) 演示一笔结账包含四项付款，涵盖银行卡拒付、取消结账，以及付款正在进行时重启。

## 任务图

`harness.watchTaskGraph(context)` 把 Session 中全部活跃任务作为一个值观察，适用于任务面板或调试，用法类似对话的 `watch()`。每个节点记录所有权边（`owner` 指向所属任务；若直接归对话所有则为空）、状态、是否为 `background`、是否被标记中止，以及它拥有的对话。

```typescript
const graph = await harness.watchTaskGraph(context);
graph.start(async (call) => {
	if (call.kind !== "value") return;
	for (const node of Object.values(call.value.tasks)) {
		const status = node.state.status === "waiting" ? `waiting on ${node.state.on.join(", ")}` : node.state.status;
		console.log(`${node.id} ${node.kind} ${status}`, node.owner ?? `conversation ${node.conversationId}`);
	}
});

```

任务在创建它的提交中出现，在使它进入终态的提交中离开。状态均为已提交的状态，包括 `pending`、`running`、`waiting`（带 `on`、`policy`）、`sleeping`（可含 `until` 与正在等待的 `signals` 键）以及 `completing`（含已决定的结果状态）。重启后，原为 `running` 的任务显示为 `pending`，直到再次执行。待处理任务是否因缺少定义而受阻由 `harness.inspect()` 报告，不属于图本身。图只列活跃任务。一旦子智能体的所有者任务结束，之后在其对话中新建的任务就是顶层节点，由对话的 `ConversationRecord.owner`（也在视图的 `conversation` 中）链接父级。[23-child-tasks.ts](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/23-child-tasks.ts?ref=47.93.196.89) 会在付款进行时打印结账任务树。

## 自定义状态

文档是有类型的 JSON 对象，能与条目一同提交。先定义文档，再在提交中编辑它。

```typescript
import { defineDoc } from "@earendil-works/pi-durable";

const Todos = defineDoc<{ items: string[] }>({
	kind: "app.todos",
	version: 1,
	scope: "conversation",
	history: "latest", // or "rewindable" to read old values with snapshotAsOf()
	fork: "initial", // what a fork starts with: "initial", "current", or "asOf"
	initial: () => ({ items: [] }),
	checkpointWhen: () => false, // required: true stores this change as a complete base, bounding replay
});

await root.commit(async (tx) => {
	(await tx.doc(Todos, root.id)).items.push("write docs");
}, context);
console.log(await harness.snapshot(Todos, root.id, context));

```

如果丢失某个提交的变更代价很小，例如流式进度，可以先显示、稍后持久化。

```typescript
await root.commit(
	async (tx) => {
		(await tx.doc(Todos, root.id)).items.push("draft"); // a document like Todos: latest, fork "initial"
	},
	context,
	{ persistence: { kind: "deferred", withinMs: 1_000 } }, // without withinMs: settings.progress.persistWithinMs
);

```

监听和视图立即看到变化。下个读写该文档的提交、文档离开内存前或关闭时，都会写入存储，最迟约 `withinMs` 后持久化。`observeCommits()` 到那时才看到实际落盘的内容（被提交退役的文档只显示退役）。崩溃会丢失尚未落盘的部分，因此要基于这类值生成持久数据，应在读取它的提交内完成。只有单纯修改已有文档且文档具备 `history: "latest"`、`fork: "initial"` 的提交才会延期。如果同时含条目、新文档、任务状态等任意其他变更，就立即持久化。

`harness.watchDoc()` 可像前述视图一样观察单份文档。它跟随文档地址。退役通知带 `retired: true`、上次已送达的值（退役事务中对该值的修改不再展示）和空操作列表。之后同一地址创建文档，会在原监听上以 `[["r", value]]` 送达。任务文档的监听随所属任务以 `ended` 结束，时间在结束任务的事务所发退役通知返回后；如果通知从未送达（监听没有启动），则在 Harness 关闭时结束。同步观察者在退役后立即收到 `end({ kind: "ended" })`。每次创建或分支对话的事务都运行 `HarnessOptions.conversationCreated(tx, conversation)`，包括工具直接调用 `tx.createConversation()`，因此每段对话都能得到你定义的文档。`createConversation()`、`fork()`、`root()` 的 `init` 在同一事务写入本次调用的数据。扩展的工具、片段、钩子可通过 `api` 或 `input.read` 读取自己的文档，缺失时按默认值处理（见 [10-extension-state.ts](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/10-extension-state.ts?ref=47.93.196.89)）。

## 用量与费用

每段对话在 `docs["pi.usage"]` 中汇总 token 数与费用，模型响应按 `provider/model` 区分，上报用量的工具结果按工具名区分。失败与中止的尝试也计入。要查询整个 Session 的用量可使用下列代码。

```typescript
const usage = await harness.usage(context); // { models: { "openai/gpt-6-sol": Usage }, tools: {...} }

```

## 存储

| 后端                        | 导入方式                                                                                                  | 说明                                                                                                                   |
| ------------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| 内存                        | 从包根入口导入 MemoryStorage                                                                                 | 不持久化。                                                                                                                |
| IndexedDB                 | 从 @earendil-works/pi-durable/storage/indexeddb 导入 IndexedDbStorage.open(name)                         | 仅用于浏览器，数据放在一个 IndexedDB 数据库中。                                                                                        |
| SQLite                    | 从 @earendil-works/pi-durable/storage/sqlite/node 导入 openNodeSqliteStorage(file)                       | 一个数据库文件，使用 WAL 模式和 synchronous = NORMAL。进程崩溃后提交仍在，断电或宿主故障可能丢失最近一次提交。                                                 |
| JSONL                     | 从 @earendil-works/pi-durable/storage/jsonl/node 导入 openNodeJsonlStorage(directory, context)           | 在一个目录中仅追加文件。传 { fsync: true } 在写入每个提交标记前刷盘；传 { readOnly: true } 可查看另一进程正在写的目录。完整历史也会驻留内存，使用量随历史增长。长期运行的智能体宜用 SQLite。 |
| Cloudflare Durable Object | 从 @earendil-works/pi-durable/storage/sqlite/cloudflare 导入 openDurableObjectSqliteStorage(ctx.storage) | 使用单个 SQLite 型 Durable Object 的 SQLite 存储。每次提交对应一个存储事务。                                                               |

浏览器中通过 `await IndexedDbStorage.open(name)` 打开 IndexedDB。同一时间只允许一个所有者占用数据库，应在整个生命周期内持有 [Web Lock](https://developer.mozilla.org/docs/Web/API/Web%5FLocks%5FAPI?ref=47.93.196.89)，避免多个标签页或工作线程争用。需要长期保留时调用 `await navigator.storage.persist()`。

共用数据库时，可给 SQLite 存储的表和索引加命名空间。把 `{ prefix: "pi_" }` 传给 `SqliteStorage.open(database, options)`、`openNodeSqliteStorage(path, options)` 或 `openDurableObjectSqliteStorage(ctx.storage, options)`。存储层将前缀直接拼入生成的 SQL，适配器无需特别处理。前缀须为 SQLite 合法标识符，不能以 `sqlite_` 开头。宿主也可能额外保留前缀，例如 Durable Objects 的 `_cf_`。修改前缀不会迁移已有数据。

通过 Cloudflare 适配器在同一个存储对象上打开的多个 Pi 存储自动共用操作队列。若要与宿主的表共用一个数据库，应创建一个适配器，让 Pi 和宿主的所有查询都经过它。直接调用底层存储会绕过队列，可能随 Pi 的事务一起回滚。

```typescript
const database = new DurableObjectSqliteDatabase(ctx.storage);
const piStorage = await SqliteStorage.open(database, { prefix: "pi_" });
await database.exec("CREATE TABLE IF NOT EXISTS host_notes (text TEXT)");
await database.run("INSERT INTO host_notes (text) VALUES (?)", text);

```

一份存储同一时间只能由一个进程写入，系统没有跨进程锁。以可写模式打开 JSONL 本身就会写文件：截断写残的行和未确认的附属记录，删除后续提交已使其失去用途的附属记录。查看另一进程正在写的目录时，应使用 `{ readOnly: true }`。这样打开不会写入，只在内存中跳过同样的记录，保留打开时已提交的状态。其 `commit()` 以 `JsonlStorageReadOnlyError` 拒绝。若只读打开与提交发生竞争，会重试打开。可移植的 SQLite 和 JSONL 核心（`/storage/sqlite`、`/storage/jsonl`）不依赖 Node API，在 Bun 或 Cloudflare Durable Objects 等环境中也能运行，只需提供异步 `SqliteDatabase` 接口或 `@earendil-works/pi-durable/env` 导出的 `FileSystem`。

SQLite 适配器实现返回 Promise 的 `exec`、`run`、`get`、`all`、`transaction` 和 `close`。`run`、`get`、`all` 接收 SQL 文本和按位置绑定的参数，适配器可按 SQL 文本缓存预编译语句。事务回调取得一个事务句柄，事务内的全部操作都必须使用它；回调结束后句柄即失效。适配器会将无关操作和其他事务排队直到本事务结束，因此在回调内直接调用 `database` 本身，会永远等不到结果。

```typescript
await database.transaction(async (transaction) => {
	await transaction.exec("CREATE TABLE example (value TEXT)");
	await transaction.run("INSERT INTO example (value) VALUES (?)", "stored atomically");
});

```

自定义后端的 `commit(batches, receive, context)` 应按顺序存储 `batches`，每批独立原子提交，分配自己的序号，并按照前面批次留下的状态验证，尽量减少往返次数。一旦某批未通过后端检查（全局 ID、文档操作、副本解析），就停止。之前的批次保持已存，该批及后续均不存储。持久化完成后，按顺序对每个已存批次同步调用 `receive(index, seq)`，最后返回 `{ stored, refused? }`。结果不确定时（连接丢失、语句或 `COMMIT` 失败）则拒绝。`receive` 是持久化回执。Session 稍后逐批发布，内存和所有视图都不会呈现一批内部不完整的日志。`receive` 不调用 Storage 的任何方法，也不会抛错。自定义后端可使用任意兼容 Vitest 或 Jest 的运行器执行共享一致性测试，其中也会检查这项约定。

```typescript
import { registerStorageConformance } from "@earendil-works/pi-durable/testing";
import { describe, expect, it } from "vitest";

registerStorageConformance({ describe, expect, it }, "My Storage", async (use) => {
	const storage = await openMyStorage();
	try {
		await use(storage);
	} finally {
		await closeMyStorage(storage);
	}
});

```

包的根入口会加载 pi-schema，因为工具任务使用 pi-ai 的 `validateToolArguments()` 验证参数。

## 错误

错误的影响范围由以下三条规则决定。

1. **存储错误会结束 Harness。** 触发错误的调用以原错误拒绝。此后所有调用及已挂起的等待都以 `SessionFailed` 拒绝，其 `cause` 为原错误。监听以 `failed` 结束，执行中的任务收到中止信号，`onReport` 收到一次错误报告。随后 Harness 自行关闭。它不重试，自定义存储应自行重试暂时性故障。可通过重新打开来恢复；提交具有原子性，存储仍一致。使用相同 `requestId` 重提可找回已接纳的提交项。
2. **无效读取只使本次调用失败。** 游标无效、对话不存在或文档没有保留所需历史时，存储读取抛出 `StorageRequestError`。取消读取也只影响这次读取。这一例外仅适用于读操作；`commit()` 或 `mintId()` 抛出的任何错误，包括 `StorageRequestError`，都按第一条规则结束 Harness。
3. **应用代码的失败通常只影响其工作单元。** 任务阶段抛错会令该任务故障，工具抛错会得到错误结果，钩子抛错会上报并跳过（`beforeTool` 此时阻止调用），提交回调抛错会回滚那次提交。监听器抛错或返回被拒绝的 Promise 会被报告，其他监听器仍然执行。例外是宿主 `RegistryReader` 的 `snapshot()` 抛错，Harness 没有它就无法调度，因此会像遇到存储错误一样失败。

当 Harness 通过 `close()` 或因存储错误完成关闭时，`harness.closed` 结束等待。宿主因而可以按下面的方式在失败后重新启动。

```typescript
harness.closed.then((end) => {
	if (end.kind === "failed") reopen(end.error);
});

```

故障会触发 Harness 自行关闭。即使存储无法正常关闭，关闭流程完成后 `closed` 也会结束等待。关闭过程会等待运行中的任务代码返回，忽略中止信号的代码会延迟 `closed`。

## 示例

可运行的示例位于 [test/examples](https://github.com/earendil-works/pi/tree/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples?ref=47.93.196.89)。要运行其中一个，请在本包目录执行以下命令。

```bash
node --conditions=source --experimental-strip-types test/examples/13-chat.ts

```

| 示例                                                                                                                                                                                                                                                                                                                  | 演示内容                                                                    |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| [13-chat](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/13-chat.ts?ref=47.93.196.89)                                                                                                                                                            | 一次提问和回答。                                                                |
| [15-real-model](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/15-real-model.ts?ref=47.93.196.89)                                                                                                                                                | 从 OpenAI 流式接收回答。                                                        |
| [16-coding-tools](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/16-coding-tools.ts?ref=47.93.196.89)                                                                                                                                            | 在 JSONL 存储上执行包含工具调用的一轮对话。                                               |
| [17-print](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/17-print.ts?ref=47.93.196.89)                                                                                                                                                          | 打印模式，提交提示词并打印答案。                                                        |
| [18-json](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/18-json.ts?ref=47.93.196.89)                                                                                                                                                            | JSON 模式，在 SQLite、JSONL 或内存后端输出原始视图操作，也可输出每次变化追加的条目和 pi.live。            |
| [19-inbox](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/19-inbox.ts?ref=47.93.196.89)                                                                                                                                                          | 对话忙碌时引导、跟进、写入和撤回。                                                       |
| [20-late-join](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/20-late-join.ts?ref=47.93.196.89)                                                                                                                                                  | 运行中途连接视图，先看到正在执行的工具输出，再看到流式回答。                                          |
| [21-subagent-foreground](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/21-subagent-foreground.ts?ref=47.93.196.89)                                                                                                                              | 可安全重放的子智能体工具，子对话归调用所有，并在调用下方显示子对话记录。                                    |
| [22-subagent-background](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/22-subagent-background.ts?ref=47.93.196.89)                                                                                                                              | 持久子智能体的创建、引导、停止、列举和答案回报，重启后仍可继续。                                        |
| [23-child-tasks](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/23-child-tasks.ts?ref=47.93.196.89)                                                                                                                                              | 结账任务拥有四项付款并等待它们，演示 failFast、中止与重启。                                      |
| [24-compaction](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/24-compaction.ts?ref=47.93.196.89)                                                                                                                                                | 长对话的后台压缩、手动压缩，以及上下文溢出后的压缩。                                              |
| [25-coding-agent](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/25-coding-agent.ts?ref=47.93.196.89)                                                                                                                                            | 使用 CodingTools，从设置对象读取实时配置，让执行环境跟随对话的工作目录。                              |
| [26-plan-mode](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/26-plan-mode.ts?ref=47.93.196.89)                                                                                                                                                  | 以扩展和自有文档实现只读计划模式，通过 configure() 切换。                                     |
| [27-reviewer](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/27-reviewer.ts?ref=47.93.196.89)                                                                                                                                                    | 复核者使用独立对话，拥有自己的模型、扩展、工具、目录和复核循环。                                        |
| [28-sandbox-per-conversation](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/28-sandbox-per-conversation.ts?ref=47.93.196.89)                                                                                                                    | 根据应用文档查找每个对话独立的执行环境。                                                    |
| [29-tool-override](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/29-tool-override.ts?ref=47.93.196.89)                                                                                                                                          | 为部分对话替换同名 bash，再用包装器测量最终选中实现的耗时。                                        |
| [30-reload-and-restart](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/30-reload-and-restart.ts?ref=47.93.196.89)                                                                                                                                | 调用进行时热重载扩展，重启后仍保留已经存储的选择。                                               |
| [31-transcript](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/31-transcript.ts?ref=47.93.196.89)                                                                                                                                                | 客户端从窗口视图拼出完整记录，包括实时追加、卡顿后出现缺口、加载缺口与更早页面，以及用 from 恢复。                    |
| [32-tests-after-edits](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/32-tests-after-edits.ts?ref=47.93.196.89)                                                                                                                                  | 每次改过文件的运行结束后，用 afterRun 钩子执行测试；失败时启动修复运行，其间输入排队等待。                      |
| [33-turn-limit-and-continue](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/33-turn-limit-and-continue.ts?ref=47.93.196.89)                                                                                                                      | 每段对话各自设置轮数上限、查看 runFailure，并在没有新用户消息时继续。                                |
| [34-submit-in-commit](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/34-submit-in-commit.ts?ref=47.93.196.89)                                                                                                                                    | 宿主在自己的事务中使用 admit(tx, draft) 和 whenIdle: "reject" 接纳访客的引导输入。            |
| [35-durable-on-the-store](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/35-durable-on-the-store.ts?ref=47.93.196.89)                                                                                                                            | Harness 在 Chord 宿主存储中使用 StoreStorage，与 Chord 对象的表并存，共用提交队列、ID 分配器和导出操作。 |
| [36-durable-views](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/36-durable-views.ts?ref=47.93.196.89)                                                                                                                                          | Chord 对象通过 self.follow 跟随 Durable 视图，展示收到的帧，以及读取该值的成员。                  |
| [37-harness-registry](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/37-harness-registry.ts?ref=47.93.196.89)                                                                                                                                    | 将 Harness 放入 Chord 对象，通过 Chord 注册表贡献扩展；当前 Harness 关闭时，跟随者切换到下一个。        |
| [38-signals](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/38-signals.ts?ref=47.93.196.89)                                                                                                                                                      | defineSignal()、harness.signal() 的每种结果，以及提前到达的信号怎样立即唤醒休眠任务。              |
| [39-ask-a-person](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/39-ask-a-person.ts?ref=47.93.196.89)                                                                                                                                            | 任务带截止时间休眠等待人的回答，展示按时作答、超时后拒绝迟到回答，以及休眠时调用 wake()。                        |
| [40-tool-waits-for-webhook](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/40-tool-waits-for-webhook.ts?ref=47.93.196.89)                                                                                                                        | CI 工具挂起等待 webhook 信号。演示挂起前崩溃时记住幂等键，以及挂起时停止如何调用 cancel。                  |
| [41-tool-polls](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/41-tool-polls.ts?ref=47.93.196.89)                                                                                                                                                | 工具以定时挂起和退避策略轮询长时间运行的作业。                                                 |
| [42-parallel-children](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/42-parallel-children.ts?ref=47.93.196.89)                                                                                                                                  | 使用 executeTool(..., { wait: false }) 和带 policy: "any" 的挂起，跨多次唤醒按键收集结果。  |
| [43-subagent-waits](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/43-subagent-waits.ts?ref=47.93.196.89)                                                                                                                                        | 子智能体等人回答时，调用它的工具通过 notify 挂起等待 SubmissionSettled。                       |
| [44-approval-gate](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/44-approval-gate.ts?ref=47.93.196.89)                                                                                                                                          | 以参数为键的 beforeTool 审批检查，记住截止时间。第二道检查每次唤醒都要询问，并演示拒绝和过期。                   |
| [45-review-on-yield](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/45-review-on-yield.ts?ref=47.93.196.89)                                                                                                                                      | 用 onYield 复核任务的 { continue } 要求智能体继续工作，以及已排队的用户消息怎样取得优先权。               |
| [46-after-tools-terminate](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/46-after-tools-terminate.ts?ref=47.93.196.89)                                                                                                                          | afterTools 任务询问人是否继续，先发送引导，随后返回 { terminate: true }。                    |
| [47-fit-images](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/47-fit-images.ts?ref=47.93.196.89)                                                                                                                                                | 存储前按模型的大小限制处理图像。附件照片使用 fitImage，工具截图使用 fit-images 扩展。                   |
| [00](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/00-conversation.ts?ref=47.93.196.89)–[12](https://github.com/earendil-works/pi/blob/69a6993486acee850d14a4a1547daa4a167228ad/packages/durable/test/examples/12-recovery.ts?ref=47.93.196.89) | 底层机制，包括会话、文档、分支、监听、Harness、智能体配置、热重载、扩展状态、任务与恢复。                        |

调用 OpenAI 的示例需要 `OPENAI_API_KEY`，其余示例大多使用模拟提供方。

## 设计文档

- [docs/spec.md](https://github.com/earendil-works/pi/blob/main/packages/durable/docs/spec.md?ref=47.93.196.89) 为规范性说明。

基准测试命令为 `npm run bench:storage`、`npm run bench:storage:memory`、`npm run bench:tool-output` 和 `npm run bench:nested-tools`。

## 许可证

MIT