@earendil-works/pi-durable 0.99.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +557 -46
  3. package/dist/entries.d.ts +20 -2
  4. package/dist/entries.d.ts.map +1 -1
  5. package/dist/entries.js +14 -1
  6. package/dist/entries.js.map +1 -1
  7. package/dist/env/index.d.ts +18 -38
  8. package/dist/env/index.d.ts.map +1 -1
  9. package/dist/env/index.js +2 -0
  10. package/dist/env/index.js.map +1 -1
  11. package/dist/env/node.d.ts +2 -0
  12. package/dist/env/node.d.ts.map +1 -1
  13. package/dist/env/node.js +53 -58
  14. package/dist/env/node.js.map +1 -1
  15. package/dist/harness/agent.d.ts +31 -0
  16. package/dist/harness/agent.d.ts.map +1 -0
  17. package/dist/harness/agent.js +209 -0
  18. package/dist/harness/agent.js.map +1 -0
  19. package/dist/harness/compaction.d.ts +56 -0
  20. package/dist/harness/compaction.d.ts.map +1 -0
  21. package/dist/harness/compaction.js +382 -0
  22. package/dist/harness/compaction.js.map +1 -0
  23. package/dist/harness/context.d.ts +8 -0
  24. package/dist/harness/context.d.ts.map +1 -1
  25. package/dist/harness/context.js +32 -21
  26. package/dist/harness/context.js.map +1 -1
  27. package/dist/harness/define.d.ts +18 -0
  28. package/dist/harness/define.d.ts.map +1 -0
  29. package/dist/harness/define.js +25 -0
  30. package/dist/harness/define.js.map +1 -0
  31. package/dist/harness/events.d.ts +166 -0
  32. package/dist/harness/events.d.ts.map +1 -0
  33. package/dist/harness/events.js +319 -0
  34. package/dist/harness/events.js.map +1 -0
  35. package/dist/harness/generation.d.ts +36 -7
  36. package/dist/harness/generation.d.ts.map +1 -1
  37. package/dist/harness/generation.js +356 -82
  38. package/dist/harness/generation.js.map +1 -1
  39. package/dist/harness/harness.d.ts.map +1 -1
  40. package/dist/harness/harness.js +141 -106
  41. package/dist/harness/harness.js.map +1 -1
  42. package/dist/harness/inbox.d.ts +59 -0
  43. package/dist/harness/inbox.d.ts.map +1 -0
  44. package/dist/harness/inbox.js +97 -0
  45. package/dist/harness/inbox.js.map +1 -0
  46. package/dist/harness/json.d.ts +10 -0
  47. package/dist/harness/json.d.ts.map +1 -0
  48. package/dist/harness/json.js +33 -0
  49. package/dist/harness/json.js.map +1 -0
  50. package/dist/harness/live.d.ts +66 -7
  51. package/dist/harness/live.d.ts.map +1 -1
  52. package/dist/harness/live.js +71 -7
  53. package/dist/harness/live.js.map +1 -1
  54. package/dist/harness/output.d.ts +62 -0
  55. package/dist/harness/output.d.ts.map +1 -0
  56. package/dist/harness/output.js +261 -0
  57. package/dist/harness/output.js.map +1 -0
  58. package/dist/harness/prompt.d.ts +9 -6
  59. package/dist/harness/prompt.d.ts.map +1 -1
  60. package/dist/harness/prompt.js +57 -14
  61. package/dist/harness/prompt.js.map +1 -1
  62. package/dist/harness/registry.d.ts +2 -3
  63. package/dist/harness/registry.d.ts.map +1 -1
  64. package/dist/harness/registry.js +69 -277
  65. package/dist/harness/registry.js.map +1 -1
  66. package/dist/harness/scheduler.d.ts +42 -12
  67. package/dist/harness/scheduler.d.ts.map +1 -1
  68. package/dist/harness/scheduler.js +649 -75
  69. package/dist/harness/scheduler.js.map +1 -1
  70. package/dist/harness/submissions.d.ts +14 -9
  71. package/dist/harness/submissions.d.ts.map +1 -1
  72. package/dist/harness/submissions.js +76 -34
  73. package/dist/harness/submissions.js.map +1 -1
  74. package/dist/harness/task-graph.d.ts +49 -0
  75. package/dist/harness/task-graph.d.ts.map +1 -0
  76. package/dist/harness/task-graph.js +163 -0
  77. package/dist/harness/task-graph.js.map +1 -0
  78. package/dist/harness/tool.d.ts +36 -0
  79. package/dist/harness/tool.d.ts.map +1 -0
  80. package/dist/harness/tool.js +415 -0
  81. package/dist/harness/tool.js.map +1 -0
  82. package/dist/harness/types.d.ts +330 -125
  83. package/dist/harness/types.d.ts.map +1 -1
  84. package/dist/harness/types.js.map +1 -1
  85. package/dist/harness/usage.d.ts +18 -0
  86. package/dist/harness/usage.d.ts.map +1 -0
  87. package/dist/harness/usage.js +57 -0
  88. package/dist/harness/usage.js.map +1 -0
  89. package/dist/harness/view.d.ts +43 -0
  90. package/dist/harness/view.d.ts.map +1 -0
  91. package/dist/harness/view.js +189 -0
  92. package/dist/harness/view.js.map +1 -0
  93. package/dist/index.d.ts +13 -5
  94. package/dist/index.d.ts.map +1 -1
  95. package/dist/index.js +8 -2
  96. package/dist/index.js.map +1 -1
  97. package/dist/session/observation.d.ts +18 -11
  98. package/dist/session/observation.d.ts.map +1 -1
  99. package/dist/session/observation.js +24 -13
  100. package/dist/session/observation.js.map +1 -1
  101. package/dist/session/session.d.ts +10 -1
  102. package/dist/session/session.d.ts.map +1 -1
  103. package/dist/session/session.js +23 -5
  104. package/dist/session/session.js.map +1 -1
  105. package/dist/session/transaction.d.ts +12 -3
  106. package/dist/session/transaction.d.ts.map +1 -1
  107. package/dist/session/transaction.js +90 -31
  108. package/dist/session/transaction.js.map +1 -1
  109. package/dist/storage/jsonl/storage.d.ts +22 -2
  110. package/dist/storage/jsonl/storage.d.ts.map +1 -1
  111. package/dist/storage/jsonl/storage.js +1 -1
  112. package/dist/storage/jsonl/storage.js.map +1 -1
  113. package/dist/storage/memory.js +1 -1
  114. package/dist/storage/memory.js.map +1 -1
  115. package/dist/storage/sqlite/database.d.ts +26 -19
  116. package/dist/storage/sqlite/database.d.ts.map +1 -1
  117. package/dist/storage/sqlite/database.js.map +1 -1
  118. package/dist/storage/sqlite/index.d.ts +1 -1
  119. package/dist/storage/sqlite/index.d.ts.map +1 -1
  120. package/dist/storage/sqlite/index.js.map +1 -1
  121. package/dist/storage/sqlite/migrations.js +7 -7
  122. package/dist/storage/sqlite/migrations.js.map +1 -1
  123. package/dist/storage/sqlite/node.d.ts +23 -7
  124. package/dist/storage/sqlite/node.d.ts.map +1 -1
  125. package/dist/storage/sqlite/node.js +129 -47
  126. package/dist/storage/sqlite/node.js.map +1 -1
  127. package/dist/storage/sqlite/storage.d.ts +12 -0
  128. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  129. package/dist/storage/sqlite/storage.js +121 -129
  130. package/dist/storage/sqlite/storage.js.map +1 -1
  131. package/dist/testing/storage-benchmark.d.ts.map +1 -1
  132. package/dist/testing/storage-benchmark.js +0 -1
  133. package/dist/testing/storage-benchmark.js.map +1 -1
  134. package/dist/testing/storage-conformance.d.ts.map +1 -1
  135. package/dist/testing/storage-conformance.js +34 -2
  136. package/dist/testing/storage-conformance.js.map +1 -1
  137. package/dist/tools/bash.d.ts +28 -0
  138. package/dist/tools/bash.d.ts.map +1 -0
  139. package/dist/tools/bash.js +70 -0
  140. package/dist/tools/bash.js.map +1 -0
  141. package/dist/tools/edit-diff.d.ts +89 -0
  142. package/dist/tools/edit-diff.d.ts.map +1 -0
  143. package/dist/tools/edit-diff.js +386 -0
  144. package/dist/tools/edit-diff.js.map +1 -0
  145. package/dist/tools/edit.d.ts +18 -0
  146. package/dist/tools/edit.d.ts.map +1 -0
  147. package/dist/tools/edit.js +117 -0
  148. package/dist/tools/edit.js.map +1 -0
  149. package/dist/tools/env.d.ts +5 -0
  150. package/dist/tools/env.d.ts.map +1 -0
  151. package/dist/tools/env.js +7 -0
  152. package/dist/tools/env.js.map +1 -0
  153. package/dist/tools/file-mutation-queue.d.ts +9 -0
  154. package/dist/tools/file-mutation-queue.d.ts.map +1 -0
  155. package/dist/tools/file-mutation-queue.js +52 -0
  156. package/dist/tools/file-mutation-queue.js.map +1 -0
  157. package/dist/tools/image.d.ts +2 -0
  158. package/dist/tools/image.d.ts.map +1 -0
  159. package/dist/tools/image.js +92 -0
  160. package/dist/tools/image.js.map +1 -0
  161. package/dist/tools/index.d.ts +23 -0
  162. package/dist/tools/index.d.ts.map +1 -0
  163. package/dist/tools/index.js +15 -0
  164. package/dist/tools/index.js.map +1 -0
  165. package/dist/tools/path-utils.d.ts +5 -0
  166. package/dist/tools/path-utils.d.ts.map +1 -0
  167. package/dist/tools/path-utils.js +26 -0
  168. package/dist/tools/path-utils.js.map +1 -0
  169. package/dist/tools/read.d.ts +17 -0
  170. package/dist/tools/read.d.ts.map +1 -0
  171. package/dist/tools/read.js +101 -0
  172. package/dist/tools/read.js.map +1 -0
  173. package/dist/tools/write.d.ts +10 -0
  174. package/dist/tools/write.d.ts.map +1 -0
  175. package/dist/tools/write.js +31 -0
  176. package/dist/tools/write.js.map +1 -0
  177. package/dist/{env/utils/truncate.d.ts → truncate.d.ts} +1 -17
  178. package/dist/truncate.d.ts.map +1 -0
  179. package/dist/truncate.js +146 -0
  180. package/dist/truncate.js.map +1 -0
  181. package/dist/types.d.ts +97 -19
  182. package/dist/types.d.ts.map +1 -1
  183. package/dist/types.js.map +1 -1
  184. package/package.json +32 -14
  185. package/dist/env/utils/adaptive-publisher.d.ts +0 -24
  186. package/dist/env/utils/adaptive-publisher.d.ts.map +0 -1
  187. package/dist/env/utils/adaptive-publisher.js +0 -79
  188. package/dist/env/utils/adaptive-publisher.js.map +0 -1
  189. package/dist/env/utils/output-capture.d.ts +0 -31
  190. package/dist/env/utils/output-capture.d.ts.map +0 -1
  191. package/dist/env/utils/output-capture.js +0 -238
  192. package/dist/env/utils/output-capture.js.map +0 -1
  193. package/dist/env/utils/truncate.d.ts.map +0 -1
  194. package/dist/env/utils/truncate.js +0 -294
  195. package/dist/env/utils/truncate.js.map +0 -1
  196. package/dist/harness/config.d.ts +0 -20
  197. package/dist/harness/config.d.ts.map +0 -1
  198. package/dist/harness/config.js +0 -18
  199. package/dist/harness/config.js.map +0 -1
  200. package/docs/chord-delta-findings.md +0 -358
  201. package/docs/pico-v5-chord-usage.md +0 -373
  202. package/docs/pico-v5-handoff.md +0 -581
  203. package/docs/pico-v5.md +0 -3084
package/README.md CHANGED
@@ -1,86 +1,597 @@
1
1
  # @earendil-works/pi-durable
2
2
 
3
- Durable conversation, task, and document runtime for Pi.
3
+ > **Experimental.** The API changes without notice between releases.
4
4
 
5
- This package contains the Pico runtime. Its current public API provides durable record contracts and memory, JSONL, and SQLite storage implementations:
5
+ A durable agent harness. Conversations, model turns, tool calls, and your own state are committed to storage before anything is shown. If the process dies mid-turn, reopening the storage picks the work up where it stopped.
6
6
 
7
- ```ts
8
- import { MemoryStorage, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
9
- ```
7
+ Built on [`@earendil-works/pi-ai`](../ai/README.md) for model access and `@earendil-works/chord` for document state.
8
+
9
+ ## Table of Contents
10
+
11
+ - [Installation](#installation)
12
+ - [Quick Start](#quick-start)
13
+ - [Concepts](#concepts)
14
+ - [Persist and Resume](#persist-and-resume)
15
+ - [Extensions](#extensions)
16
+ - [Tools](#tools)
17
+ - [System Prompt](#system-prompt)
18
+ - [Per-Conversation Agent](#per-conversation-agent)
19
+ - [Settings](#settings)
20
+ - [Environment](#environment)
21
+ - [Reload](#reload)
22
+ - [Watching a Conversation](#watching-a-conversation)
23
+ - [Busy Conversations](#busy-conversations)
24
+ - [Reset and Handoff](#reset-and-handoff)
25
+ - [Compaction](#compaction)
26
+ - [Agent Events (Experimental)](#agent-events-experimental)
27
+ - [Hooks](#hooks)
28
+ - [More Conversations and Forks](#more-conversations-and-forks)
29
+ - [Abort and Subagents](#abort-and-subagents)
30
+ - [Child Tasks](#child-tasks)
31
+ - [Task Graph](#task-graph)
32
+ - [Your Own State](#your-own-state)
33
+ - [Usage and Cost](#usage-and-cost)
34
+ - [Storage](#storage)
35
+ - [Examples](#examples)
36
+ - [Design Documents](#design-documents)
10
37
 
11
- The root export is runtime-neutral. Storage implementations also have explicit subpaths:
38
+ ## Installation
12
39
 
13
- ```ts
14
- import { MemoryStorage } from "@earendil-works/pi-durable/storage/memory";
40
+ ```bash
41
+ npm install @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chord
15
42
  ```
16
43
 
17
- Node applications can open file-backed JSONL or SQLite storage through Node-only subpaths:
44
+ ## Quick Start
18
45
 
19
- ```ts
46
+ ```typescript
20
47
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
21
- import { openNodeJsonlStorage } from "@earendil-works/pi-durable/storage/jsonl/node";
48
+ import { createModels } from "@earendil-works/pi-ai/models";
49
+ import { openaiProvider } from "@earendil-works/pi-ai/providers/openai";
50
+ import { AssistantEntry, createRegistry, Harness, MemoryStorage } from "@earendil-works/pi-durable";
51
+
52
+ const context = BACKGROUND_CONTEXT;
53
+
54
+ const models = createModels();
55
+ models.setProvider(openaiProvider()); // reads OPENAI_API_KEY
56
+
57
+ const harness = await Harness.open(new MemoryStorage(), { models, registry: createRegistry() }, context);
58
+ const root = await harness.root(context, { agent: { model: { provider: "openai", modelId: "gpt-6-sol" } } });
59
+
60
+ const submission = await root.submit({ type: "input", content: "What is the capital of France?" }, context);
61
+ const settled = await submission.wait(context);
62
+ if (settled.status === "done" && settled.type === "input") {
63
+ const answer = await root.commit((tx) => tx.entry(AssistantEntry, settled.answer), context);
64
+ console.log(answer?.model?.[0]);
65
+ }
66
+ await harness.close(context);
67
+ ```
68
+
69
+ What happened:
70
+
71
+ - `Harness.open()` opens a Session over a storage backend. `MemoryStorage` keeps everything in memory.
72
+ - `root()` returns the root conversation, creating it on first use with the given agent choices. A conversation is a transcript of immutable entries.
73
+ - `submit()` durably admits your input and returns a `Submission`. A built-in generation task calls the model and appends the answer.
74
+ - `wait()` resolves once the input is answered (`done`) or has failed (`unanswered`, with a reason).
75
+
76
+ Every async call takes a Chord `Context`, which carries cancellation. `BACKGROUND_CONTEXT` never cancels. Cancelling a wait only cancels that wait, never the work.
77
+
78
+ ## Concepts
79
+
80
+ - **Harness**: one open storage plus the machinery that runs agents on it. All changes go through one line of atomic commits, and nothing is shown before its commit is stored.
81
+ - **Conversation**: a transcript. `root()` creates the root conversation on first use; you can create more and fork them. A `Conversation` handle holds no state; compare handles by `id`.
82
+ - **Entry**: one immutable transcript record, such as a user message (`pi.user`), a model response (`pi.assistant`), a tool result (`pi.tool-result`), a system prompt change (`pi.system`), a reset (`pi.reset`), or your own kind. The model sees the entries from the newest reset onward.
83
+ - **Commit**: an atomic write. `conversation.commit((tx) => ...)` can append entries, edit documents, and create tasks together; either all of it is stored or none of it.
84
+ - **Document**: typed JSON state stored next to the transcript and changed in commits. Built-in ones hold each conversation's agent choices (`pi.agent`), the running generation and tools (`pi.live`), queued submissions (`pi.inbox`), and spend (`pi.usage`).
85
+ - **Task**: a durable state machine that saves a checkpoint at every step, so a restarted process continues from the last one. Every task has an owner: its conversation, or another task. The Harness runs answers as built-in tasks: `pi.generation` calls the model and owns the `pi.tool` tasks of its tool calls, waits for them, and hands the run to the next generation.
86
+ - **Submission**: something you hand to a conversation, either user input or an entry to write, which you can wait for.
87
+ - **Turn and run**: a turn is one model response and its tool calls; a run is the turns from an input to its final answer. A conversation is busy while a run is going.
88
+ - **Extension**: a named bundle of tools, system prompt sections, hooks, wrappers, and tasks.
89
+ - **Registry**: the extensions this process installed. It can change while the Harness runs; new work uses the new state.
90
+ - **Agent**: what a conversation runs with: model, thinking level, selected extensions, tools, instructions, and working directory. Stored per conversation as names in `pi.agent`, resolved against the registry at each use.
91
+
92
+ One answered input, as entries and tasks:
93
+
94
+ ```text
95
+ submit(input) → pi.user
96
+ pi.generation → pi.system (only if the prompt or tools changed), pi.assistant (tool calls)
97
+ pi.tool × n → pi.tool-result × n (owned by the generation, which waits for them)
98
+ pi.generation → pi.assistant (answer) → submission done
99
+ ```
100
+
101
+ ## Persist and Resume
102
+
103
+ Use SQLite or JSONL storage to keep conversations across restarts:
104
+
105
+ ```typescript
22
106
  import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
23
107
 
24
- const jsonl = await openNodeJsonlStorage("./session", BACKGROUND_CONTEXT);
25
- const sqlite = await openNodeSqliteStorage("./session.sqlite");
108
+ const harness = await Harness.open(await openNodeSqliteStorage("./session.sqlite"), { models, registry }, context);
109
+ const root = await harness.root(context); // the same root as last time
110
+ harness.resume(); // continue any run the last process left unfinished
111
+ ```
112
+
113
+ Work interrupted by a crash or close stays pending. `resume()` starts the task scheduler; submitting or waiting starts it too. A retried submission with the same `requestId` returns the existing submission instead of submitting twice:
114
+
115
+ ```typescript
116
+ const submission = await root.submit({ type: "input", content: "Hello", requestId: "greeting-1" }, context);
117
+ // After a restart: the same request ID finds the same submission.
118
+ const again = await root.submit({ type: "input", content: "Hello", requestId: "greeting-1" }, context);
119
+ // again.id === submission.id
120
+ ```
121
+
122
+ `harness.submission(id)` reacquires a submission by ID, for example to wait for it after a restart.
123
+
124
+ ## Extensions
125
+
126
+ Code the Harness runs, other than its built-in tasks, comes in named extensions installed in a registry your process owns:
127
+
128
+ ```typescript
129
+ import { createRegistry, defineExtension, defineTool, hook, section, ToolTask } from "@earendil-works/pi-durable";
130
+ import { CodingTools } from "@earendil-works/pi-durable/tools";
131
+
132
+ const Coding = defineExtension({
133
+ name: "coding",
134
+ sections: [section("preamble", () => "You are a concise coding assistant.", { tag: false })],
135
+ hooks: [hook(ToolTask, { beforeTool: (call) => (isDangerous(call) ? { block: "Needs approval" } : undefined) })],
136
+ });
137
+
138
+ const registry = createRegistry();
139
+ registry.install(CodingTools);
140
+ registry.install(Coding);
141
+ ```
142
+
143
+ An extension may bring `tools`, `sections`, `hooks`, `wraps` (decorators of a tool or section by name), and `tasks`. By default every conversation selects every installed extension, in install order. Nothing in the registry is stored; conversations store extension names.
144
+
145
+ ## Tools
146
+
147
+ `@earendil-works/pi-durable/tools` provides `read`, `write`, `edit`, and `bash`, and the `CodingTools` extension with all four. They touch files and processes only through the call's environment (see [Environment](#environment)). Reading images is not supported yet.
148
+
149
+ Define your own tool with a TypeBox schema. `defineTool()` types `args` from `parameters`, which the Harness validates before `execute()`. `api.output()` streams running output, which becomes the result when `execute()` returns no `content`:
150
+
151
+ ```typescript
152
+ import { Type } from "@earendil-works/pi-ai";
153
+
154
+ const count = defineTool({
155
+ name: "count",
156
+ description: "Count from 1 to n",
157
+ parameters: Type.Object({ n: Type.Number() }),
158
+ execute: async (args, api) => {
159
+ for (let i = 1; i <= args.n; i++) api.output(`${i}\n`);
160
+ return {};
161
+ },
162
+ });
163
+ registry.install(defineExtension({ name: "count", tools: [count] }));
164
+ ```
165
+
166
+ Each call runs as its own durable task. Its intent is committed before `execute()` runs. If the process dies mid-call, the tool reruns on reopen only when it is declared `replay: "safe"`; otherwise the model gets an `interrupted` error result with the output committed so far. Throwing from `execute()` gives the model an error result. A result can also return `usage`, which is added to the conversation's [usage](#usage-and-cost). It can also return `control: { terminate: true }`: when every result of the round asks for it, the run ends without another model request.
167
+
168
+ A later extension's tool with the same name replaces an earlier one where both are selected, and `wrapTool()` decorates whichever tool won:
169
+
170
+ ```typescript
171
+ const Venv = defineExtension({ name: "venv", tools: [createBashTool({ commandPrefix: "source .venv/bin/activate" })] });
172
+ const Timing = defineExtension({
173
+ name: "timing",
174
+ wraps: [wrapTool(createBashTool(), (bash) => ({ ...bash, execute: (args, api, ctx) => timed(() => bash.execute(args, api, ctx)) }))],
175
+ });
176
+ ```
177
+
178
+ ## System Prompt
179
+
180
+ The system prompt is built from the selected extensions' sections, rendered in order before each request. A section sees the resolved agent, the environment built for the request, and committed documents:
181
+
182
+ ```typescript
183
+ section("cwd", (input) => input.env?.cwd); // rendered as <cwd>\n...\n</cwd>; undefined omits it
184
+ ```
185
+
186
+ A conversation's `instructions` render last, as the section `instructions`. Sections and tool changes are stored as positional system entries in the transcript. Only what changed is sent again, which keeps provider prompt caches warm. A section that returns something different every time, such as the current time, defeats that.
187
+
188
+ ## Per-Conversation Agent
189
+
190
+ Each conversation stores what it runs with in its `pi.agent` document. `configure()` changes it in one commit; unset fields follow the host:
191
+
192
+ ```typescript
193
+ await root.configure(
194
+ {
195
+ model: { provider: "openai", modelId: "gpt-6-sol" },
196
+ thinkingLevel: "high",
197
+ extensions: { remove: [Coding] }, // edits the host default; an array selects exactly these, in order
198
+ tools: [readTool, bashTool], // an array offers exactly these; { remove: [...] } drops some
199
+ instructions: "Only read; never edit files.",
200
+ cwd: "/work/repo",
201
+ },
202
+ context,
203
+ );
204
+ await root.configure({ tools: null }, context); // null clears a field back to the host default
205
+ const agent = await root.agent(context); // resolved: model, extensions, tools, sections, cwd
206
+ ```
207
+
208
+ Extensions and tools are passed as objects and stored by name, so a stored name outlives its code: after an extension is uninstalled, conversations that select it just stop getting it until it is installed again. `createConversation()`, `fork()`, and `root()` take the same change as `agent`. A task-owned conversation, such as a subagent's, starts as a copy of its owner's conversation's agent. A fork starts with the agent its parent had at the fork entry. The model, prompt, and offered tools of a request are fixed when it is prepared; a change applies from the next request. Tool calls and hooks use the agent as their task phase resolves it, and the environment is built from the current `cwd` at each use, so a `cwd` or extension change can reach calls the model already made.
209
+
210
+ ## Settings
211
+
212
+ Run policy shared by every conversation is passed as `settings`. It is read at every use and never stored, so getters make it live, for example backed by a settings file:
213
+
214
+ ```typescript
215
+ const harness = await Harness.open(storage, {
216
+ models,
217
+ registry,
218
+ settings: {
219
+ extensions: [CodingTools, Coding], // default selection; absent: every installed extension
220
+ stream: { timeoutMs: 120_000 },
221
+ retry: { maxRetries: 3 },
222
+ compaction: { reserveTokens: 16384 },
223
+ toolExecution: "parallel",
224
+ get followUpMode() {
225
+ return userSettings.followUpMode;
226
+ },
227
+ },
228
+ }, context);
229
+ ```
230
+
231
+ ## Environment
232
+
233
+ `env` builds the execution environment for each tool call, section rendering, and `runtime.env()`. It receives the conversation's ID, its agent `cwd`, and committed reads, so one function serves a directory per conversation or a container per conversation:
234
+
235
+ ```typescript
236
+ import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
237
+
238
+ const harness = await Harness.open(storage, {
239
+ models,
240
+ registry,
241
+ env: ({ cwd }) => new NodeExecutionEnv({ cwd: cwd ?? process.cwd() }),
242
+ }, context);
243
+ ```
244
+
245
+ A throw from `env` becomes the call's error result. Without an environment, the built-in tools fail with an error result. A fresh environment object per call is fine: `edit` and `write` serialize changes to one file by the environment's `id` and path. A custom `ExecutionEnv` sets `id` so that equal ids see the same files at the same paths, for example one id per container.
246
+
247
+ ## Reload
248
+
249
+ Installing an extension with an installed name replaces it in place, in one step:
250
+
251
+ ```typescript
252
+ registry.install(await loadCodingExtension()); // same name "coding": replaces the installed one
253
+ ```
254
+
255
+ `registry.uninstall(extension)` removes the installed extension with that name, whichever object it is.
256
+
257
+ Work that already started keeps the code it took: a running tool call finishes under its old implementation, and each task phase resolves hooks and the agent once, from the registry at the phase's start. The next phase, request, or call uses the new code. After a restart, install the same extensions again; pending tasks of an extension's `tasks` resume once it is installed.
258
+
259
+ ## Watching a Conversation
260
+
261
+ Everything a UI needs is committed state. `viewState()` returns the conversation's structural view as a read-only Chord state, updated after every commit that touches it:
262
+
263
+ ```typescript
264
+ const view = await root.viewState(context);
265
+ view.subscribe((value) => {
266
+ // value.entries: the active transcript
267
+ // value.docs["pi.live"]: the running generation (streamed partial, retry, deferred) and tool calls (output, details)
268
+ // value.docs["pi.inbox"], value.docs["pi.usage"], value.docs["pi.agent"]
269
+ render(value);
270
+ });
271
+ // later: view.dispose();
272
+ ```
273
+
274
+ `watch()` delivers the same view with the exact Chord operations of each commit, one callback at a time:
275
+
276
+ ```typescript
277
+ const watch = await root.watch(context);
278
+ render(watch.value); // the state at attachment
279
+ watch.start(async (value, ops) => {
280
+ await send(ops); // for example to a remote client that applies them
281
+ });
282
+ // later: await watch.stop();
26
283
  ```
27
284
 
28
- The portable JSONL core accepts the `FileSystem` capability exported from `@earendil-works/pi-durable/env`. Its `fsync` option defaults to `false`; enabling it flushes affected sidecars before appending the main commit marker. One `JsonlStorage` owner must serialize writes to a storage directory; cross-process locking and ID allocation are not supported.
285
+ A slow watch keeps at most 100 undelivered frames. After that, the pending frames are replaced by one frame holding the whole newest view. A client that joins late or reconnects starts from the current view; nothing is replayed.
29
286
 
30
- The portable SQLite core, minimal database facade, and ordered schema migrations are exported from `@earendil-works/pi-durable/storage/sqlite`. Adapters for synchronous SQLite environments such as Bun and Cloudflare Durable Objects can implement that facade without importing Node APIs. Remote asynchronous APIs such as Cloudflare D1 cannot implement this synchronous facade; they require a dedicated `Storage` backend.
287
+ Partial answers and tool output are committed at most every 100 ms, so a crash loses at most that window.
31
288
 
32
- The Node adapter uses WAL mode with `synchronous = NORMAL` and checkpoints the WAL on close. Acknowledged commits survive process crashes, but the newest commits may be lost after a power or host failure. One `SqliteStorage` owner must serialize writes to a database file; cross-process ID allocation is not supported.
289
+ ## Busy Conversations
33
290
 
34
- ## Storage conformance
291
+ A conversation is busy while a run is working on an input. Submitting to a busy conversation queues the submission in the conversation's inbox, `docs["pi.inbox"]` in the view:
292
+
293
+ ```typescript
294
+ await root.submit({ type: "input", content: "Also run the tests" }, context); // follow-up (default)
295
+ await root.submit({ type: "input", content: "Use pnpm, not npm", whenBusy: "steer" }, context);
296
+ await root.submit({ type: "input", content: "Only if idle", whenBusy: "reject" }, context); // throws ConversationBusy
297
+ await root.submit({ type: "write", entry: { kind: "app.note", data: "user opened a file" } }, context);
298
+ ```
35
299
 
36
- Storage adapters can register the runner-independent conformance cases through the testing entry. The convenience adapter accepts Vitest/Jest-compatible runner functions without importing either package:
300
+ - **Steers** are placed after the current tool round and join the running work.
301
+ - **Follow-ups** are placed when the run answers, and start the next run.
302
+ - **Writes** append an entry without asking the model anything.
303
+ - `await submission.abort(context)` withdraws a queued submission.
304
+ - The [settings](#settings) `steeringMode: "all"` and `followUpMode: "all"` place every queued item at once instead of one per turn.
37
305
 
38
- ```ts
306
+ If a run fails, queued items stay in the inbox until the next submission places them, oldest first.
307
+
308
+ ## Reset and Handoff
309
+
310
+ `reset()` starts a new context. The model no longer sees older entries, but they stay in storage:
311
+
312
+ ```typescript
313
+ await root.reset(undefined, context); // start from nothing
314
+ await root.reset("We were fixing the flaky login test. Continue.", context); // start from a handoff note
315
+ ```
316
+
317
+ While busy, the reset is queued like a write. When it is placed during a tool round, the current run ends. A tool can request the same with `control: { handoff: "..." }`.
318
+
319
+ ## Compaction
320
+
321
+ Compaction shrinks what the model sees: it summarizes older entries and appends a `pi.compaction` entry that holds the summary and heads the first entry it keeps. Older entries stay in storage.
322
+
323
+ ```typescript
324
+ const id = await root.compact("Keep the failing test names", context); // manual, with optional instructions
325
+ const { outcome } = (await harness.waitForTask(id, context)).state;
326
+ if (outcome.status === "completed" && outcome.result.submissionId !== undefined) {
327
+ const placed = await (await harness.submission(outcome.result.submissionId, context))!.wait(context);
328
+ console.log(placed.status); // "done", or "unanswered" with reason "stale"
329
+ }
330
+ ```
331
+
332
+ The conversation keeps working while the summary is made. The summary is placed at once when the conversation is idle, otherwise at the next turn boundary. Esc (`abort()`) cancels a manual compaction.
333
+
334
+ Generation also compacts on its own, controlled by the [settings](#settings):
335
+
336
+ ```typescript
337
+ settings: {
338
+ compaction: {
339
+ enabled: true, // automatic compaction; manual compact() always works
340
+ reserveTokens: 16384, // above contextWindow - reserveTokens, the next request waits for a compaction
341
+ keepRecentTokens: 20000, // roughly how much recent context stays verbatim
342
+ backgroundTokens: 32768, // this far below that, a compaction starts in the background; 0 disables it
343
+ },
344
+ }
345
+ ```
346
+
347
+ When a provider rejects a request because the context is too long, generation compacts and retries once. A summary that would cut before the start of the current context settles as `stale` when it is placed, so when several are in flight, the furthest cut stays in effect. Summarization spend counts in `pi.usage`. A `beforeCompact` hook on `CompactionTask` can decline or supply its own summary.
348
+
349
+ Running compactions are listed in `docs["pi.live"].compactions` with their reason, attempt, and retry backoff. The agent events add `compaction_start` and `compaction_end`, and a `compactions` field in the snapshot.
350
+
351
+ ## Agent Events (Experimental)
352
+
353
+ For consumers that want coding-agent style events (`message_start`, `message_update`, `tool_execution_start`, ...) instead of structural state:
354
+
355
+ ```typescript
356
+ import { watchEvents } from "@earendil-works/pi-durable";
357
+
358
+ const stream = await watchEvents(harness, root.id, context);
359
+ initialize(stream.snapshot); // entries, run, in-flight generation, tools, compactions, inbox, agent, usage
360
+ stream.start(async (events) => {
361
+ for (const event of events) console.log(JSON.stringify(event));
362
+ });
363
+ ```
364
+
365
+ Events are derived from commits, one batch per commit, and apply on top of the snapshot. Message and tool updates carry deltas: text and thinking appends, appended tool-call argument text, and output trims and appends. When a consumer falls more than 100 batches behind, it receives a fresh `snapshot` event instead. See `test/examples/19-json.ts` for the full stream of one run.
366
+
367
+ ## Hooks
368
+
369
+ Hooks let extensions observe or adjust the built-in tasks, in the conversations that select them:
370
+
371
+ ```typescript
372
+ import { GenerationTask, hook, ToolTask } from "@earendil-works/pi-durable";
373
+
374
+ const Guard = defineExtension({
375
+ name: "guard",
376
+ hooks: [
377
+ hook(ToolTask, { beforeTool: (call) => (call.name === "bash" ? { block: "bash is disabled here" } : undefined) }),
378
+ hook(GenerationTask, { onYield: (answer) => (needsMoreWork(answer) ? { continue: "Keep going." } : undefined) }),
379
+ ],
380
+ });
381
+ ```
382
+
383
+ - **Generation:** `beforeRequest` (replace the messages of one request), `afterResponse`, `onYield` (continue the run with another user message), and `afterTools` (runs once a round's tools are done).
384
+ - **Tools:** `beforeTool` (block or rewrite arguments) and `afterTool` (replace the result).
385
+
386
+ To limit a hook to some conversations, select its extension only there, for example with `configure({ extensions: { add: [Guard] } })`.
387
+
388
+ ## More Conversations and Forks
389
+
390
+ ```typescript
391
+ const other = await harness.createConversation({ ownership: { kind: "ownerless" } }, context);
392
+ const fork = await root.fork(entryId, { ownership: { kind: "ownerless" } }, context);
393
+ ```
394
+
395
+ A fork sees its parent's entries up to `entryId` and continues independently. It keeps the parent's agent as of that entry. Both take `agent` and `init`, applied in the creating commit.
396
+
397
+ ## Abort and Subagents
398
+
399
+ `await root.abort(context)` stops a conversation: queued inputs are withdrawn (queued writes stay), every task of its current work is aborted, and the call resolves once the conversation is idle.
400
+
401
+ A conversation can be **owned** by a task. A subagent tool creates its child inside `api.commit()` with `ownership: { kind: "task", taskId: api.taskId }`, then drives it through `api.conversation(id)`:
402
+
403
+ ```typescript
404
+ const Subagent: Extension = defineExtension({
405
+ name: "subagent",
406
+ tools: [
407
+ defineTool({
408
+ name: "subagent",
409
+ description: "Delegate a self-contained task to a subagent and get its answer back.",
410
+ parameters: Type.Object({ task: Type.String() }),
411
+ replay: "safe", // a rerun after a crash finds the same child and submission
412
+ execute: async (args, api, context) => {
413
+ const child = await api.commit(async (tx) => {
414
+ // The ownership index remembers the child, so a rerun reuses it.
415
+ const existing = (await tx.scanConversations({ ownerTaskId: api.taskId }, 1)).items[0];
416
+ if (existing !== undefined) return existing.id;
417
+ // Starts as a copy of this conversation's agent: model, extensions, tools, cwd.
418
+ const created = await tx.createConversation({ ownership: { kind: "task", taskId: api.taskId } });
419
+ // A cheaper model, and no subagents of its own.
420
+ await configure(tx, created.id, { model: haiku, extensions: { remove: [Subagent] } });
421
+ return created.id;
422
+ }, context);
423
+ await api.details({ conversationId: child }, context); // lets a UI attach to the child
424
+ const request = { type: "input", content: args.task, requestId: `subagent:${api.taskId}` } as const;
425
+ const settled = await (await (await api.conversation(child, context))!.submit(request, context)).wait(context);
426
+ return { content: [{ type: "text", text: settled.status }] };
427
+ },
428
+ }),
429
+ ],
430
+ });
431
+ ```
432
+
433
+ Owned work belongs to its owner:
434
+
435
+ - Aborting the call aborts the child. So does the call failing: `execute()` throwing, or a crash that interrupts a call that is not replay-safe.
436
+ - The parent is idle only once the child is.
437
+ - A task created with `{ background: true }` is a boundary: work it owns survives the parent's abort and does not keep the parent busy. `root.abort(context, { background: true })` aborts it too.
438
+
439
+ The examples show both patterns as product code:
440
+
441
+ - [`22-subagent-foreground.ts`](test/examples/22-subagent-foreground.ts): the tool above, returning the child's answer. The UI finds the child through the call's `details` and prints the child's events indented under the call.
442
+ - [`23-subagent-background.ts`](test/examples/23-subagent-background.ts): persistent subagents behind one `subagent` tool that spawns, messages (steer or follow-up), waits for, stops, and lists them. Each child is owned by a background anchor task, so the parent's Esc and idle waits never reach it. Each message is delivered by a background reporter task that posts the answer back to the parent as a follow-up input once it arrives; request IDs keep a restart from sending a message or a report twice.
443
+
444
+ ## Child Tasks
445
+
446
+ A task can own child tasks, created with `ownership: { kind: "task", taskId }`, and wait for them by committing a `waiting` state:
447
+
448
+ ```typescript
449
+ pay: async (task, runtime, context) => {
450
+ await runtime.commit(async (tx) => {
451
+ const payments = [];
452
+ for (const card of task.input.cards) {
453
+ payments.push(await tx.createTask(Payment, { card }, { ownership: { kind: "task", taskId: task.id } }));
454
+ }
455
+ // Resume in `decide` once every payment is done; the first failure aborts the rest.
456
+ return { status: "waiting", checkpoint: { phase: "decide", payments }, on: payments, policy: "failFast" };
457
+ }, context);
458
+ },
459
+ decide: async (task, runtime, context) => {
460
+ const outcomes = await runtime.outcomes(task.state.checkpoint.payments, context);
461
+ // ...commit the checkout's own outcome
462
+ },
463
+ ```
464
+
465
+ - **Waiting:** the task runs no code while it waits. With `allSettled` it resumes once every task in `on` is done; with `failFast` the first failed child also aborts the others. `on` may name other tasks too, with `allSettled`.
466
+ - **Finishing:** a task that finishes while work it owns is still running is `completing`: its outcome is decided, but it becomes terminal, and `waitForTask()` returns, only once that work is done. A failed or aborted outcome aborts that work first.
467
+ - **Aborting:** abort runs bottom-up. Aborting a task aborts the work it owns first, and its own abort handler starts only once that work is done, so each task undoes its own effects.
468
+
469
+ [`24-child-tasks.ts`](test/examples/24-child-tasks.ts) runs a checkout with four payments: a declined card, a cancelled checkout, and a restart while the payments run.
470
+
471
+ ## Task Graph
472
+
473
+ `harness.taskGraph(context)` shows every live task of the Session as one Chord state, for a task panel or debugging. Each node has its owner edge (`owner` task, or none for a task its conversation owns), its status, whether it is `background` or abort-marked, and the conversations it owns. `harness.watchTaskGraph(context)` delivers the same value as a watch, like a conversation's `watch()`.
474
+
475
+ ```typescript
476
+ const graph = await harness.taskGraph(context);
477
+ graph.subscribe((value) => {
478
+ for (const node of Object.values(value.tasks)) {
479
+ const status = node.state.status === "waiting" ? `waiting on ${node.state.on.join(", ")}` : node.state.status;
480
+ console.log(`${node.id} ${node.kind} ${status}`, node.owner ?? `conversation ${node.conversationId}`);
481
+ }
482
+ });
483
+ ```
484
+
485
+ A task appears with the commit that creates it and leaves with the commit that makes it terminal. Statuses are the committed ones: `pending`, `running`, `waiting` (with `on` and `policy`), and `completing` (with the held outcome's status). After a restart, tasks that were `running` show as `pending` until they run again. Whether a pending task is blocked by a missing definition is not part of the graph; `harness.inspect()` reports that. The graph lists live tasks only: once a subagent's owner task is terminal, a later task in its conversation is a top-level node, and the conversation's `ConversationRecord.owner` (also in its view's `conversation`) links it to its parent. [`24-child-tasks.ts`](test/examples/24-child-tasks.ts) prints the checkout's tree while its payments run.
486
+
487
+ ## Your Own State
488
+
489
+ Documents are typed JSON objects committed together with entries. Define one, and edit it in a commit:
490
+
491
+ ```typescript
492
+ import { defineDoc } from "@earendil-works/pi-durable";
493
+
494
+ const Todos = defineDoc<{ items: string[] }>({
495
+ kind: "app.todos",
496
+ version: 1,
497
+ scope: "conversation",
498
+ history: "latest", // or "rewindable" to read old values with snapshotAsOf()
499
+ fork: "initial", // what a fork starts with: "initial", "current", or "asOf"
500
+ initial: () => ({ items: [] }),
501
+ });
502
+
503
+ await root.commit(async (tx) => {
504
+ (await tx.doc(Todos, root.id)).items.push("write docs");
505
+ }, context);
506
+ console.log(await harness.snapshot(Todos, root.id, context));
507
+ ```
508
+
509
+ `harness.watchDoc()` and `harness.documentState()` observe one document like the view above. `HarnessOptions.conversationCreated(tx, conversation)` runs in every commit that creates or forks a conversation, including a tool's raw `tx.createConversation()`, so every conversation gets your documents; `init` in `createConversation()`, `fork()`, and `root()` writes per-call data in the same commit. An extension's tools, sections, and hooks read their own documents through `api` or `input.read`, and treat an absent one as its default ([`11-extension-state.ts`](test/examples/11-extension-state.ts)).
510
+
511
+ ## Usage and Cost
512
+
513
+ Each conversation keeps token and cost totals in `docs["pi.usage"]`: per `provider/model` for model responses, and per tool name for tool results that report usage. Failed and aborted attempts count too. For the whole Session:
514
+
515
+ ```typescript
516
+ const usage = await harness.usage(context); // { models: { "openai/gpt-6-sol": Usage }, tools: {...} }
517
+ ```
518
+
519
+ ## Storage
520
+
521
+ | Backend | Import | Notes |
522
+ |---|---|---|
523
+ | Memory | `MemoryStorage` from the package root | Nothing is persisted. |
524
+ | SQLite | `openNodeSqliteStorage(file)` from `@earendil-works/pi-durable/storage/sqlite/node` | One database file. WAL mode with `synchronous = NORMAL`: commits survive process crashes; the newest may be lost on power or host failure. |
525
+ | JSONL | `openNodeJsonlStorage(directory, context)` from `@earendil-works/pi-durable/storage/jsonl/node` | Append-only files in one directory. Pass `{ fsync: true }` to flush before each commit marker. |
526
+
527
+ One process owns a storage at a time; there is no cross-process locking. The portable SQLite and JSONL cores (`/storage/sqlite`, `/storage/jsonl`) run without Node APIs, for example on Bun or in Cloudflare Durable Objects, given an asynchronous `SqliteDatabase` facade or a `FileSystem` from `@earendil-works/pi-durable/env`.
528
+
529
+ SQLite adapters implement promise-based `exec`, `run`, `get`, `all`, `transaction`, and `close`. `run`, `get`, and `all` take SQL text plus positional bindings; adapters may cache prepared statements by SQL text. A transaction callback receives a transaction handle; all work in the transaction must use it, and the handle expires when the callback settles. Adapters must queue unrelated operations and other transactions until the transaction finishes, so calling `database` itself inside the callback never settles:
530
+
531
+ ```typescript
532
+ await database.transaction(async (transaction) => {
533
+ await transaction.exec("CREATE TABLE example (value TEXT)");
534
+ await transaction.run("INSERT INTO example (value) VALUES (?)", "stored atomically");
535
+ });
536
+ ```
537
+
538
+ Custom backends can run the shared conformance suite with any Vitest- or Jest-compatible runner:
539
+
540
+ ```typescript
39
541
  import { registerStorageConformance } from "@earendil-works/pi-durable/testing";
40
542
  import { describe, expect, it } from "vitest";
41
543
 
42
- registerStorageConformance({ describe, expect, it }, "Some Custom Storage", async (use) => {
43
- const storage = await openCustomStorage();
544
+ registerStorageConformance({ describe, expect, it }, "My Storage", async (use) => {
545
+ const storage = await openMyStorage();
44
546
  try {
45
547
  await use(storage);
46
548
  } finally {
47
- await closeStorage(storage);
549
+ await closeMyStorage(storage);
48
550
  }
49
551
  });
50
552
  ```
51
553
 
52
- The provider must call and await `use` exactly once with isolated storage. Other runners can use `createStorageConformance` with their own `StorageConformanceAssertions` implementation.
554
+ The package root loads TypeBox, because the tool task validates arguments with pi-ai's `validateToolArguments()`. That costs about 23 MB of peak RSS unbundled, about 4 MB in a tree-shaken bundle.
53
555
 
54
- ## Storage benchmarks
556
+ ## Examples
55
557
 
56
- From this package directory:
558
+ Runnable examples live in [`test/examples`](test/examples). Run one from this package directory with:
57
559
 
58
- ```sh
59
- npm run bench:storage
60
- npm run bench:storage:memory
560
+ ```bash
561
+ node --conditions=source --experimental-strip-types test/examples/14-chat.ts
61
562
  ```
62
563
 
63
- The timing suite runs shared deterministic workloads against the built-in memory, JSONL, and SQLite adapters. Third-party adapters can import the same seeds and workload definitions from `@earendil-works/pi-durable/testing` and use their platform's timing runner:
564
+ | Example | Shows |
565
+ |---|---|
566
+ | [14-chat](test/examples/14-chat.ts) | One question and answer |
567
+ | [16-real-model](test/examples/16-real-model.ts) | Streaming an answer from OpenAI |
568
+ | [17-coding-tools](test/examples/17-coding-tools.ts) | A tool-using turn on JSONL storage |
569
+ | [18-print](test/examples/18-print.ts) | Print mode: submit a prompt, print the answer |
570
+ | [19-json](test/examples/19-json.ts) | JSON mode: agent events or raw view operations, on SQLite, JSONL, or memory |
571
+ | [20-inbox](test/examples/20-inbox.ts) | Steers, follow-ups, writes, and withdrawal while busy |
572
+ | [21-late-join](test/examples/21-late-join.ts) | Attaching a view and an event stream mid-run |
573
+ | [22-subagent-foreground](test/examples/22-subagent-foreground.ts) | A replay-safe subagent tool whose child the call owns, with the child's events under the call |
574
+ | [23-subagent-background](test/examples/23-subagent-background.ts) | Persistent subagents: spawn, steer, stop, list, answers reported back, restart-safe |
575
+ | [24-child-tasks](test/examples/24-child-tasks.ts) | A checkout that owns and waits for four payments: failFast, abort, restart |
576
+ | [25-compaction](test/examples/25-compaction.ts) | A long chat compacted in the background, manually, and after a context overflow |
577
+ | [26-coding-agent](test/examples/26-coding-agent.ts) | CodingTools, live settings from a settings object, an environment that follows the conversation's directory |
578
+ | [27-plan-mode](test/examples/27-plan-mode.ts) | A read-only plan mode as an extension with its own document, switched with `configure()` |
579
+ | [28-reviewer](test/examples/28-reviewer.ts) | A reviewer conversation with its own model, extensions, tools, directory, and review loop |
580
+ | [29-sandbox-per-conversation](test/examples/29-sandbox-per-conversation.ts) | An environment per conversation, looked up from an app document |
581
+ | [30-tool-override](test/examples/30-tool-override.ts) | A same-name bash for some conversations, and a wrapper that times whichever bash won |
582
+ | [31-reload-and-restart](test/examples/31-reload-and-restart.ts) | Reloading an extension mid-call, and stored choices surviving a restart |
583
+ | [00](test/examples/00-conversation.ts)–[13](test/examples/13-recovery.ts) | The layers underneath: sessions, documents, forks, watches, the Harness, agent configuration, reload, extension state, tasks, recovery |
64
584
 
65
- ```ts
66
- import {
67
- seedStorageBenchmark,
68
- seedStorageWriteBenchmark,
69
- STORAGE_READ_BENCHMARKS,
70
- STORAGE_WRITE_BENCHMARKS,
71
- } from "@earendil-works/pi-durable/testing";
585
+ Examples that call OpenAI need `OPENAI_API_KEY`; most use the faux provider otherwise.
72
586
 
73
- const dataset = await seedStorageBenchmark(readStorage);
74
- await STORAGE_READ_BENCHMARKS[0].run(readStorage, dataset);
587
+ ## Design Documents
75
588
 
76
- await seedStorageWriteBenchmark(freshWriteStorage);
77
- await STORAGE_WRITE_BENCHMARKS[0].run(freshWriteStorage);
78
- ```
589
+ - [`docs/spec.md`](https://github.com/earendil-works/pi/blob/main/packages/durable/docs/spec.md): the normative specification
590
+ - [`docs/pico-v5-handoff.md`](https://github.com/earendil-works/pi/blob/main/packages/durable/docs/pico-v5-handoff.md): the implementation plan
591
+ - [`docs/pico-v5-chord-usage.md`](https://github.com/earendil-works/pi/blob/main/packages/durable/docs/pico-v5-chord-usage.md): how the package uses Chord
79
592
 
80
- Read scenarios reuse one seeded store; each write sample requires a fresh seeded store. The workloads cover representative commits, indexed reads, pagination, fork traversal, document replay, historical reads, and persistent-backend reopen. The footprint suite measures each built-in adapter in a separate process at 1k and 10k scales and reports heap, RSS, external memory, file counts, and on-disk JSONL/SQLite size. These synthetic workloads are baselines for regression analysis, not production capacity limits or CI pass/fail thresholds.
593
+ Benchmarks: `npm run bench:storage`, `npm run bench:storage:memory`, and `npm run bench:tool-output`.
81
594
 
82
- The normative design and implementation sequence are in:
595
+ ## License
83
596
 
84
- - [`docs/pico-v5.md`](docs/pico-v5.md)
85
- - [`docs/pico-v5-handoff.md`](docs/pico-v5-handoff.md)
86
- - [`docs/pico-v5-chord-usage.md`](docs/pico-v5-chord-usage.md)
597
+ MIT