@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/docs/pico-v5.md DELETED
@@ -1,3084 +0,0 @@
1
- # Pico5 specification
2
-
3
- Pico5 is a durable, extensible agent harness. This document is normative.
4
- Pico5 uses existing package types as follows:
5
-
6
- ```ts
7
- import type {
8
- AttachedReplicatedState,
9
- Context,
10
- Draft,
11
- JsonRepresentation,
12
- JsonValue,
13
- ReplicatedState,
14
- } from "@earendil-works/chord";
15
- import type { Op } from "@earendil-works/chord/delta";
16
- import type {
17
- AssistantMessage,
18
- CacheRetention,
19
- DeferredHandle,
20
- Message,
21
- Models,
22
- ModelThinkingLevel,
23
- TextContent,
24
- Tool,
25
- ToolReference,
26
- ToolResultMessage,
27
- Transport,
28
- UserMessage,
29
- } from "@earendil-works/pi-ai";
30
-
31
- type JsonObject = { [key: string]: JsonValue };
32
- type TaskOutcomeError = { message: string; detail?: JsonValue };
33
- ```
34
-
35
- Pico5 targets the transcript `SystemMessage` contract from pi-ai PR
36
- [#9548](https://github.com/earendil-works/pi/pull/9548). `Message` includes that
37
- type once the PR lands.
38
-
39
- The core rule is:
40
-
41
- > A Session atomically commits immutable entries, full task records, and
42
- > Chord-tracked documents. Only committed state is observable.
43
-
44
- ## 1. Terms and invariants
45
-
46
- - A **Session** owns one mutation line, conversations, entries, tasks,
47
- submissions, and documents.
48
- - A **conversation** is a transcript scope. It may fork another conversation.
49
- - An **entry** is an immutable transcript record.
50
- - A **task** is a durable state machine attached to one conversation.
51
- - A **document** is mutable JSON state represented by Chord operations and
52
- occasional complete bases.
53
- - A **definition** is a typed token describing one document or document family.
54
- - A **source** exposes committed document changes to Chord without exposing a
55
- mutable object.
56
- - A **turn** is one assistant response and the tool calls it makes. A **run**
57
- is the sequence of turns from an admitted input to the final answer; turn
58
- boundaries (section 6) sit between its turns. A conversation is busy while a
59
- run is active.
60
-
61
- Required invariants:
62
-
63
- 1. One Session commit is atomic across all record and document writes.
64
- 2. A document update is published only after its storage commit succeeds.
65
- 3. All visible progress is durable. There is no volatile publication path.
66
- 4. External effects do not run inside the Session mutation transaction.
67
- 5. Entries and IDs are immutable and never reused after a committed write.
68
- 6. Document drafts are fully revoked when their transaction callback settles:
69
- the Session synchronously prepares or aborts every open change at that point.
70
- Values assigned into a draft are copied by value and must be strict JSON.
71
- 7. The mutation line remains held through storage settlement and committed-state
72
- adoption. Commit/close observers run synchronously only to capture immutable
73
- state; document-state and watch user callbacks run later, off the line.
74
- 8. An uncertain storage failure is fatal to the open Session. It publishes
75
- nothing and must be reopened. Preparation and checkpoint failures occur before
76
- storage admission and roll back normally.
77
-
78
- ## 2. Core records
79
-
80
- The concrete JSON representations may add bookkeeping fields, but must preserve
81
- these contracts.
82
-
83
- ```ts
84
- declare const idBrand: unique symbol;
85
- type Id<Kind extends string, Type = unknown> = number & {
86
- readonly [idBrand]: {
87
- readonly kind: Kind;
88
- readonly type: Type;
89
- };
90
- };
91
- type ConversationId = Id<"conversation">;
92
- type EntryId = Id<"entry">;
93
- type TaskId<Result = unknown> = Id<"task", Result>;
94
- type SubmissionId = Id<"submission">;
95
- type DocumentId = Id<"document">;
96
-
97
- declare const seqBrand: unique symbol;
98
- /** Strictly increases between commits; gaps are permitted. */
99
- type Seq = number & { readonly [seqBrand]: "sequence" };
100
- const ROOT_CONVERSATION_ID = 1 as ConversationId;
101
-
102
- type ConversationOwnership =
103
- | { readonly kind: "ownerless" }
104
- | { readonly kind: "task"; readonly taskId: TaskId };
105
-
106
- type ConversationRecord = {
107
- readonly id: ConversationId;
108
- readonly parent?: {
109
- readonly conversationId: ConversationId;
110
- readonly at: EntryId;
111
- };
112
- readonly owner?: {
113
- readonly conversationId: ConversationId;
114
- readonly taskId: TaskId;
115
- };
116
- };
117
- ```
118
-
119
- The referenced pi-ai member is:
120
-
121
- ```ts
122
- interface SystemMessage {
123
- role: "system";
124
- content: string | TextContent[];
125
- sections?: Record<string, string | null>;
126
- toolsAdded?: Tool[];
127
- toolsRemoved?: ToolReference[];
128
- timestamp: number;
129
- }
130
- ```
131
-
132
- In pi-ai, `content` is the base prompt on the leading message and additional
133
- instruction text on later messages. `sections` is an ordered named patch: a
134
- string adds or replaces a section, while `null` removes it. `toolsRemoved` is
135
- applied before `toolsAdded` within one message. Replaying every system message
136
- in transcript order yields the effective prompt and tool set.
137
-
138
- Pico always writes `content: ""`. Every prompt part, including the preamble, is
139
- a named section produced by the registry's system prompt slot (section 7.4).
140
-
141
- ```ts
142
- type ContextEdit = {
143
- readonly target: EntryId;
144
- } & (
145
- | { readonly action: "omit"; readonly messages?: never }
146
- | { readonly action: "replace"; readonly messages: readonly Message[] }
147
- );
148
-
149
- type EntryRecord = {
150
- readonly id: EntryId;
151
- readonly conversationId: ConversationId;
152
- readonly kind: string;
153
- readonly model?: readonly Message[];
154
- readonly data?: JsonValue;
155
- readonly head?: EntryId;
156
- readonly edits?: readonly ContextEdit[];
157
- readonly byTaskId?: TaskId;
158
- };
159
-
160
- type EntryDraft = Omit<EntryRecord, "id" | "conversationId" | "byTaskId" | "head"> & {
161
- readonly head?: EntryId | "self";
162
- };
163
-
164
- type SubmissionRecordBase = {
165
- readonly id: SubmissionId;
166
- readonly conversationId: ConversationId;
167
- readonly requestId?: string;
168
- };
169
-
170
- type SubmissionRecord =
171
- | (SubmissionRecordBase & {
172
- readonly type: "input";
173
- } & (
174
- | {
175
- readonly status: "queued";
176
- readonly entry?: never;
177
- readonly answer?: never;
178
- readonly reason?: never;
179
- readonly detail?: never;
180
- }
181
- | {
182
- readonly status: "placed";
183
- readonly entry: EntryId;
184
- readonly answer?: never;
185
- readonly reason?: never;
186
- readonly detail?: never;
187
- }
188
- | {
189
- readonly status: "done";
190
- readonly entry: EntryId;
191
- readonly answer: EntryId;
192
- readonly reason?: never;
193
- readonly detail?: never;
194
- }
195
- | {
196
- readonly status: "unanswered";
197
- readonly entry?: EntryId;
198
- readonly answer?: never;
199
- readonly reason: string;
200
- readonly detail?: JsonValue;
201
- }
202
- ))
203
- | (SubmissionRecordBase & {
204
- readonly type: "write";
205
- } & (
206
- | {
207
- readonly status: "queued";
208
- readonly entry?: never;
209
- readonly answer?: never;
210
- readonly reason?: never;
211
- readonly detail?: never;
212
- }
213
- | {
214
- readonly status: "done";
215
- readonly entry: EntryId;
216
- readonly answer?: never;
217
- readonly reason?: never;
218
- readonly detail?: never;
219
- }
220
- | {
221
- readonly status: "unanswered";
222
- readonly entry?: never;
223
- readonly answer?: never;
224
- readonly reason: string;
225
- readonly detail?: JsonValue;
226
- }
227
- ));
228
-
229
- type SubmissionSettlement =
230
- | { readonly status: "done"; readonly answer: EntryId }
231
- | { readonly status: "unanswered"; readonly reason: string; readonly detail?: JsonValue };
232
-
233
- type SubmissionCreate = SubmissionRecord extends infer Record
234
- ? Record extends SubmissionRecord
235
- ? Omit<Record, "id">
236
- : never
237
- : never;
238
- ```
239
-
240
- ID brands are compile-time only. IDs and sequences remain ordinary numbers in
241
- memory, JSON, JSONL, and SQLite. Code applies a brand only at a trusted creation
242
- or decoding boundary. The distinct sequence brand prevents an entity ID from
243
- being used as a document commit point.
244
-
245
- Conversation history parenting and task ownership are separate:
246
-
247
- - `parent` controls inherited entries and historical documents.
248
- - `owner` records task attribution and connects scopes for subtree abort and idle traversal. It is not an access-control capability.
249
- - Creation always supplies `ConversationOwnership` explicitly. The Session
250
- derives the persisted owner's conversation from the named task; callers never
251
- construct the persisted owner pair.
252
-
253
- A conversation's owner remains recorded after the owning task becomes terminal.
254
-
255
- ### 2.1 Entries and context
256
-
257
- Entry IDs are Session-global and ordered. `parent.at` is an entry in the parent
258
- history visible to the child.
259
-
260
- The active transcript is the raw entry range from the newest applicable `head`
261
- through the tail. A head on an entry changes subsequent context; it does not
262
- remove older entries from storage. Fork traversal is child entries followed by
263
- parent entries through each `parent.at` cap.
264
-
265
- Context derivation:
266
-
267
- 1. Find the newest visible entry `H` at or before the cutoff that has `head`.
268
- 2. Let `from = H.head`, or transcript start when `H` is absent.
269
- 3. Scan visible entries from `from` through the cutoff.
270
- 4. For each target, the newest edit in that range wins. `omit` contributes no
271
- model messages; `replace` contributes its `messages` instead of the target's.
272
- 5. If `H` exists, context entries are `H` followed by non-head entries in the
273
- range. Otherwise they are the range.
274
- 6. Keep every positional system message and its tool/section changes.
275
- 7. Move each assistant's tool results, found before the next assistant message,
276
- directly after it in tool-call order, ahead of any intervening user or system
277
- message. The provider protocol requires results to follow their call.
278
- 8. Synthesize an error result for every call without one, for example after a
279
- fork cut or at an interrupted tail. Drop tool results with no preceding call.
280
- 9. Exclude model-less entries and assistant messages with `aborted`, `error`, or
281
- `deferred` stop reasons from future provider requests.
282
-
283
- Views carry raw active entries. UI reduction and model-context reduction are
284
- separate consumers. Older stored history is available through the owning
285
- `Conversation` object's cursor-based `entries()` scan.
286
-
287
- ### 2.2 Public Harness surface
288
-
289
- This is the v1 host-facing API. Pico5 is not implemented yet, but implementations
290
- must expose this shape rather than inventing a different facade during package
291
- 24.
292
-
293
- ```ts
294
- type ModelRef = {
295
- readonly provider: string;
296
- readonly modelId: string;
297
- };
298
-
299
- type UserInput = UserMessage["content"];
300
-
301
- type SubmissionDraft = {
302
- readonly requestId?: string;
303
- } & (
304
- | {
305
- readonly type: "input";
306
- readonly content: UserInput;
307
- readonly whenBusy?: "steer" | "followUp" | "reject";
308
- readonly entry?: never;
309
- }
310
- | {
311
- readonly type: "write";
312
- readonly entry: EntryDraft;
313
- readonly content?: never;
314
- readonly whenBusy?: never;
315
- }
316
- );
317
-
318
- type InputSubmissionDraft = Extract<SubmissionDraft, { readonly type: "input" }>;
319
-
320
- /** Runs inside the creating commit, after the conversation and its configuration exist. */
321
- type ConversationInit = (tx: Tx, conversationId: ConversationId) => void | Promise<void>;
322
-
323
- type ConversationCreateOptions = {
324
- readonly ownership: ConversationOwnership;
325
- readonly init?: ConversationInit;
326
- };
327
-
328
- type AnyTask = {
329
- readonly definition: {
330
- readonly name: string;
331
- readonly version: number;
332
- readonly initial: unknown;
333
- readonly phases: Readonly<Record<string, unknown>>;
334
- readonly abort: unknown;
335
- readonly migrate?: unknown;
336
- readonly hooks?: object;
337
- };
338
- };
339
-
340
- type HarnessOptions<Tool extends ToolRegistration = ToolRegistration> = {
341
- readonly models: Models; // the pi-ai Models interface
342
- readonly registry: RegistryReader<Tool>; // section 7.1
343
- readonly now?: () => number;
344
- readonly onReport?: (error: unknown) => void;
345
- };
346
-
347
- /** Curated pi-ai request options; absent fields use pi-ai defaults. */
348
- type ConversationStreamOptions = {
349
- transport?: Transport;
350
- timeoutMs?: number;
351
- /** Provider/SDK retries inside one request attempt. */
352
- maxRetries?: number;
353
- maxRetryDelayMs?: number;
354
- headers?: Record<string, string>;
355
- metadata?: JsonObject;
356
- cacheRetention?: CacheRetention;
357
- deferred?: boolean | { window?: "15m" | "1h" | "24h" };
358
- };
359
-
360
- /** Durable generation attempt retries; the JSON shape of pi-ai `RetryPolicy`. */
361
- type ConversationRetryPolicy = {
362
- enabled: boolean;
363
- maxRetries: number;
364
- baseDelayMs: number;
365
- maxAgentDelayMs?: number;
366
- };
367
-
368
- type ConversationConfigState = {
369
- model?: ModelRef;
370
- thinkingLevel: ModelThinkingLevel;
371
- activeTools: string[];
372
- streamOptions?: ConversationStreamOptions;
373
- retry?: ConversationRetryPolicy;
374
- };
375
-
376
- /** Built-in rewindable configuration document; see below. */
377
- declare const ConversationConfig: RewindableConversationDocToken<ConversationConfigState>;
378
-
379
- /** Entry whose `data` has type `D`; `never` means the kind carries no data. */
380
- type TypedEntry<D extends JsonValue> = Omit<EntryRecord, "data"> &
381
- ([D] extends [never] ? { readonly data?: never } : { readonly data: D });
382
-
383
- type TypedEntryDraft<D extends JsonValue> = Omit<EntryDraft, "kind" | "data"> &
384
- ([D] extends [never] ? { readonly data?: never } : { readonly data: D });
385
-
386
- interface Entry<D extends JsonValue = never> {
387
- readonly kind: string;
388
- is(entry: EntryRecord | undefined): entry is TypedEntry<D>;
389
- }
390
-
391
- function defineEntry<D extends JsonValue = never>(kind: string): Entry<D>;
392
-
393
- type ContextView = {
394
- readonly head: EntryRecord | undefined;
395
- readonly entries: readonly EntryRecord[];
396
- readonly messages: readonly Message[];
397
- };
398
-
399
- type SettledSubmissionRecord = SubmissionRecord & {
400
- readonly status: "done" | "unanswered";
401
- };
402
-
403
- interface Submission {
404
- readonly id: SubmissionId;
405
- status(context: Context): Promise<SubmissionRecord>;
406
- wait(context: Context): Promise<SettledSubmissionRecord>;
407
- abort(context: Context): Promise<"aborted" | "already_placed" | "settled">;
408
- }
409
-
410
- type SettledTask<R> = TaskRecord<JsonValue, JsonValue, R> & {
411
- readonly state: Extract<TaskState<JsonValue, R>, { status: "terminal" }>;
412
- };
413
-
414
- type TaskInspection = {
415
- readonly record: TaskRecord<JsonValue, JsonValue, JsonValue>;
416
- readonly state:
417
- | { readonly kind: "running" }
418
- | { readonly kind: "ready"; readonly migrates: boolean }
419
- | { readonly kind: "waiting"; readonly on: readonly TaskId[] }
420
- | {
421
- readonly kind: "blocked";
422
- readonly reason: "missing_task" | "task_too_old" | "migration_failed";
423
- readonly error?: unknown;
424
- };
425
- };
426
-
427
- type HarnessInspection = {
428
- readonly scheduling: "paused" | "running" | "closing";
429
- readonly tasks: readonly TaskInspection[];
430
- /** Queued and placed submissions in ID order. */
431
- readonly submissions: readonly SubmissionRecord[];
432
- readonly registry: readonly RegistryFailure[];
433
- };
434
-
435
- type ConversationWatch = WatchHandle<ConversationView>;
436
-
437
- type HooksOf<K> = K extends Task<infer _I, infer _S, infer _R, infer H>
438
- ? H
439
- : never;
440
-
441
- interface Conversation {
442
- readonly id: ConversationId;
443
- submit(submission: SubmissionDraft, context: Context): Promise<Submission>;
444
-
445
- getModel(context: Context): Promise<ModelRef | undefined>;
446
- setModel(model: ModelRef | undefined, context: Context): Promise<void>;
447
- getThinkingLevel(context: Context): Promise<ModelThinkingLevel>;
448
- setThinkingLevel(level: ModelThinkingLevel, context: Context): Promise<void>;
449
- getActiveTools(context: Context): Promise<readonly string[]>;
450
- setActiveTools(names: readonly string[], context: Context): Promise<void>;
451
- getStreamOptions(context: Context): Promise<ConversationStreamOptions>;
452
- setStreamOptions(options: ConversationStreamOptions, context: Context): Promise<void>;
453
- getRetryPolicy(context: Context): Promise<ConversationRetryPolicy>;
454
- setRetryPolicy(policy: ConversationRetryPolicy | undefined, context: Context): Promise<void>;
455
-
456
- commit<T>(
457
- change: (tx: Tx) => T | Promise<T>,
458
- context: Context,
459
- ): Promise<T>;
460
- context(context: Context): Promise<ContextView>;
461
- entries(
462
- query: Omit<EntryQuery, "conversationId">,
463
- limit: number,
464
- cursor: Cursor | undefined,
465
- context: Context,
466
- ): Promise<Page<EntryRecord, Cursor>>;
467
- fork(
468
- at: EntryId,
469
- options: ConversationCreateOptions,
470
- context: Context,
471
- ): Promise<Conversation>;
472
- collapse(instructions: string | undefined, context: Context): Promise<TaskId>;
473
- reset(handoff: string | undefined, context: Context): Promise<void>;
474
- abort(context: Context): Promise<void>;
475
- waitForIdle(context: Context): Promise<void>;
476
- viewState(context: Context): Promise<AttachedReplicatedState<ConversationView>>;
477
- watch(context: Context): Promise<ConversationWatch>;
478
- }
479
-
480
- interface Harness extends Session {
481
- resume(): void;
482
-
483
- root(
484
- context: Context,
485
- options?: { readonly init?: ConversationInit },
486
- ): Promise<Conversation>;
487
- conversation(id: ConversationId, context: Context): Promise<Conversation | undefined>;
488
- createConversation(options: ConversationCreateOptions, context: Context): Promise<Conversation>;
489
-
490
- getTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined>;
491
- inspect(context: Context): Promise<HarnessInspection>;
492
- submission(id: SubmissionId, context: Context): Promise<Submission | undefined>;
493
- abortSubmission(
494
- id: SubmissionId,
495
- context: Context,
496
- conversationId?: ConversationId,
497
- ): Promise<"aborted" | "already_placed" | "settled" | "not_found">;
498
- abortTask(id: TaskId, context: Context): Promise<"marked" | "terminal">;
499
- waitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>>;
500
- waitForIdle(context: Context): Promise<void>;
501
- }
502
-
503
- declare const Harness: {
504
- open<Tool extends ToolRegistration>(
505
- storage: Storage,
506
- options: HarnessOptions<Tool>,
507
- context: Context,
508
- ): Promise<Harness>;
509
- };
510
- ```
511
-
512
- This intentionally retains the useful Pico3 host shape. It removes Pico3's
513
- fixed `rewindable()`/`sticky()` accessors, namespace router, semantic view events,
514
- and manual Chord view bridge. Typed Pico5 documents and the structural
515
- conversation watch replace those surfaces. `submit()` durably admits either a
516
- user input or passive entry write and returns one `Submission` that tracks its
517
- settlement.
518
-
519
- `Harness.open()` binds the Session to one application-owned registry (section
520
- 7.1). `createRegistry()` pre-registers the built-in task definitions (section 8);
521
- they cannot be disposed or replaced, and open rejects a registry whose snapshot
522
- lacks any of them or the built-in `pi` conversation setup.
523
- Open changes surviving `running` tasks to `pending` and does nothing else to
524
- task records: it never migrates or terminalizes a task because its definition
525
- is missing or unmigratable. Such a task stays `pending` and is **blocked**: the
526
- scheduler skips it and reconsiders it whenever the registry changes (section
527
- 5.4). Any built-in document touched by recovery migrates through its ordinary
528
- typed access path. Open does not scan or migrate other documents. No handler
529
- dispatches during open. Applications should register tasks before open so
530
- recovered work can resume immediately; registration after open also unblocks it.
531
-
532
- The root conversation always has reserved ID `ROOT_CONVERSATION_ID` (`1`).
533
- `root(context, { init })` creates it lazily: when the root is absent, one commit
534
- on the Session line creates the ownerless root, its default configuration, and
535
- runs `init(tx, rootId)`. When the root already exists, `init` is ignored and no
536
- write occurs. Reopen finds the same root by its reserved ID. A conversation with
537
- no configured model produces a durable `no_model` generation failure.
538
-
539
- `resume()` is idempotent while running and only enables scheduling. It does not
540
- repeat open-time reconciliation, and it throws after close. Work that must happen
541
- before any task runs, such as registration or seeding, happens before
542
- `resume()`. Calls that ask for progress also enable scheduling, so they never
543
- wait on a paused Harness: `Conversation.submit()`, `Submission.wait()`,
544
- `Harness.waitForTask()`, `Harness.waitForIdle()`, and
545
- `Conversation.waitForIdle()`. Recovered work starts with them. A viewer that only
546
- reads never enables scheduling.
547
-
548
- `createConversation({ ownership, init })` and
549
- `fork(at, { ownership, init })` commit atomically: the conversation, its
550
- explicitly selected ownership, its configuration, and every write made by `init`.
551
- A first input is an ordinary `submit()` afterward. A request ID makes a retried
552
- `submit()` to the same conversation exactly-once; a host that must survive a
553
- crash between the two calls first finds its conversation again, for example
554
- through a key written by `init`. Host callers must choose ownerless or task
555
- ownership; neither the Harness nor a conversation handle infers ownership from
556
- call context. A new independent conversation receives the default configuration
557
- before `init` runs. A fork receives the configuration visible at `at` through
558
- the ordinary `asOf` fork policy; `init` may then override it with
559
- `tx.doc(ConversationConfig, id)`. Other documents follow their own definitions
560
- without special handling.
561
-
562
- Every Harness commit that creates or forks a conversation runs the registry's
563
- conversation setups (section 7.1) in the same commit, whether through the
564
- conveniences or through raw `tx.createConversation()` and `tx.forkConversation()`,
565
- for example inside a tool commit. The built-in `pi` setup runs first: an
566
- independent conversation gets the default configuration and a fork keeps its
567
- `asOf` copy, and both get an empty `pi.live`. Applications register setups for
568
- their own documents the same way. The conveniences add only `init` and its checks,
569
- which run after every setup. A conversation created by a plain Session has no
570
- built-in documents; its configuration reads as
571
- `ConversationConfig.definition.initial()` until something writes it.
572
-
573
- The built-in conversation configuration document is final at version 1:
574
-
575
- | field | value |
576
- |---|---|
577
- | kind | `pi.conversation.config` |
578
- | version | `1` (no migration) |
579
- | scope/history/fork | conversation, `rewindable`, `asOf` |
580
- | schema | `ConversationConfigState` |
581
- | `initial()` | `{ thinkingLevel: "off", activeTools: [] }` |
582
- | checkpoint | complete base on every change |
583
- | view mount | `docs["pi.conversation.config"]` |
584
-
585
- It has no prompt sections: prompt text is produced per request by the registry
586
- (section 7.4). Any code may edit it with
587
- `tx.doc(ConversationConfig, id)`, including in the same commit as a create or
588
- fork. The getters return immutable committed values, falling back to
589
- `initial()` when the document is absent; they never write. `getStreamOptions()`
590
- returns `{}` and `getRetryPolicy()` returns the default policy
591
- `{ enabled: true, maxRetries: 3, baseDelayMs: 2000, maxAgentDelayMs: 60000 }`
592
- when the field is absent; `setRetryPolicy(undefined)` removes the field.
593
- `streamOptions` are forwarded to every generation request of the conversation;
594
- `streamOptions.maxRetries` are provider retries inside one request, while `retry`
595
- governs durable generation attempts (section 8). Each setter performs
596
- one ordinary Session commit against the document. A setter does not start
597
- generation or append a system entry. Request preparation later compares the
598
- desired configuration with transcript history and appends the required
599
- positional system baseline or delta.
600
-
601
- Default active tools for a root or independent conversation, including one
602
- created through `tx.createConversation()` in a Harness commit, are the names of
603
- every tool registered when its creation commit runs, in registry order.
604
- `setActiveTools()` rejects the whole operation without a write when a name is
605
- duplicated or when a name that was not already active in that conversation is
606
- not registered. The create/fork conveniences check only one thing about `init`
607
- writes: names that `init` newly activates must be registered. Names that were
608
- already active are never revalidated, so stale unregistered names survive every
609
- edit. All other raw document writes are trusted and unchecked, so other writers,
610
- such as post-tools `addTools`, never fault because of registry movement. Readers tolerate what raw
611
- writes can produce: request preparation offers the first occurrence of a
612
- duplicated name, and post-tools `addTools` appends only names not already
613
- active.
614
-
615
- `init` runs after the conversation creation, which is a table write, so table
616
- reads inside it throw `ReadAfterWrite` (section 4). Document access remains
617
- available.
618
-
619
- The configuration document records the desired loadout; the registry records
620
- what this process can execute now. An active name may therefore be unregistered,
621
- for example during extension reload, after restart before registration, or in a
622
- fork opened by a process that lacks an extension. The document is never
623
- rewritten because of registry movement, so a re-registered tool becomes available
624
- again without host action. Hosts derive current availability as active names
625
- that are currently registered.
626
-
627
- A missing tool implementation never fails a request. Request preparation offers
628
- only active names that are currently registered. If the replayed tool state still
629
- offers an unregistered name, the appended system delta lists it in
630
- `toolsRemoved`; when the name is registered again, a later delta adds its current
631
- declaration. When the model calls a tool that is not offered or whose
632
- implementation is unavailable at execution time, the tool task appends an error
633
- tool result with `details: { code: "tool_unavailable" }` stating that the tool is
634
- not available, and the run continues so the model can react.
635
-
636
- A `Conversation.commit()` is a Session commit bound to that conversation.
637
- `tx.createTask()` defaults `TaskOptions.conversationId` to the bound conversation.
638
- `Conversation.entries()` binds the query to that conversation and paginates its
639
- fork-aware stored history; callers cannot substitute another conversation ID.
640
- Generic Session-wide document operations remain available directly on `Harness`
641
- because `Harness extends Session`.
642
-
643
- `fork()` requires a concrete visible parent entry and explicit ownership, then
644
- applies section 3.7.
645
- `collapse()` returns the newly admitted background collapse task ID, not its
646
- future summary entry. `reset()` durably admits a passive self-head reset or
647
- handoff write and then resolves; while busy, placement follows section 6 and may
648
- occur later. Observe its placement through the conversation watch. An idle wait
649
- does not guarantee placement of queued passive writes.
650
-
651
- `abortTask()` commits `abortRequested` and the durable foreground-subtree
652
- cascade, then signals and joins the active run; the scheduler then starts the
653
- abort invocation. Marking without signalling is internal: the cascade marks
654
- owned tasks in the same commit. `Conversation.abort()` withdraws queued
655
- input submissions, marks non-background tasks selected by ordinary ownership
656
- traversal, signals them, and resolves only after that scope is ordinarily idle.
657
- Passive writes and background subtrees survive. Conversation idle means no live
658
- non-background task selected from that conversation. Harness idle applies the
659
- same traversal from every ownerless conversation root. Pending dependency- or
660
- deadline-blocked work is still live and therefore not idle. Cancelling an idle
661
- wait aborts only that waiter.
662
-
663
- Conversation handles are stateless; compare them by `id`. Hosts discover
664
- conversations through lookups and scans. An activity view that lists active
665
- conversations and reports conversations becoming active or idle is specified
666
- with run control (Package 17); there is no creation listener.
667
-
668
- `submit()` returns after durable admission, not settlement. An input submission
669
- creates a user message with the admission timestamp; `whenBusy` defaults to
670
- `followUp`. A write submission uses the ordered passive path in section 6 and
671
- never starts generation. `Submission.wait()` settles an input only after its
672
- answer or terminal failure; it settles a write when the entry is placed or the
673
- write becomes terminally unplaceable. Cancelling `wait()` only cancels that wait.
674
- It does not withdraw the submission; `Submission.abort()` is the explicit queued
675
- withdrawal operation. `Harness.submission()` reacquires a submission after
676
- reopen; records remain queryable after settlement.
677
-
678
- `abortTask()` durably requests cancellation and returns `marked` after the mark
679
- is committed, any active run invocation has joined, and an abort invocation has
680
- been scheduled, or a blocked task has been settled as `orphaned` (section 5.4);
681
- it does not await terminal settlement. `waitForTask()` observes
682
- the terminal receipt. Aborting an already terminal task returns `terminal`; an
683
- unknown ID rejects. Explicit task abort includes a background task. Cancelling a
684
- task or idle wait does not abort work.
685
-
686
- `inspect()` returns live work at one point on the Session line, for recovery
687
- decisions after open, viewers, and diagnostics. It writes nothing, does not
688
- enable scheduling, and runs no task code. Each pending or running task carries
689
- its state under the current registry: `running` with an active invocation;
690
- `ready` when the next scheduling pass would reserve it, with `migrates` when its
691
- definition is newer and has `migrate`; `waiting` on unfinished dependencies; or
692
- `blocked` (section 5.4). A migration shows as failed only after the scheduler
693
- tried it, or when the newer definition has no `migrate`; inspection never runs
694
- one to find out. Blocked reasons are derived, never stored. Queued and placed
695
- submissions and the registry's wrapper failures complete the view. Finished
696
- tasks, settled submissions, transcripts, and documents use their own APIs.
697
-
698
- `Conversation.viewState()` returns its current structural mount as a disposable
699
- read-only Chord state. `Conversation.watch()` atomically captures that immutable
700
- revision and registers for later exact complete-commit frames. Its `WatchHandle`
701
- uses the same serialized asynchronous, bounded-buffer contract as `watchDoc()`
702
- in section 9.2. Neither carries semantic events or owns a second persistence
703
- authority.
704
-
705
- `close()` seals mutation admission and
706
- task reservation, signals invocations, and stops future watch deliveries. Outside
707
- the Session line it lets already-admitted storage commits settle, joins
708
- task/tool/hook invocations, then closes states and storage. Already-running watch
709
- callbacks remain caller-owned and may finish independently. Close writes no task
710
- outcome. Handles belong to that open Harness and must be reacquired after reopen.
711
-
712
- ## 3. Documents
713
-
714
- ### 3.1 Definitions
715
-
716
- Scope directly determines document ownership and lifetime. Only conversation
717
- documents declare history and fork behavior.
718
-
719
- ```ts
720
- type LatestConversationSemantics = {
721
- readonly scope: "conversation";
722
- readonly history: "latest";
723
- readonly fork: "current" | "initial";
724
- };
725
-
726
- type RewindableConversationSemantics = {
727
- readonly scope: "conversation";
728
- readonly history: "rewindable";
729
- readonly fork: "asOf" | "current" | "initial";
730
- };
731
-
732
- type DocumentSemantics =
733
- | { readonly scope: "session" }
734
- | LatestConversationSemantics
735
- | RewindableConversationSemantics
736
- | { readonly scope: "task" };
737
-
738
- type CheckpointInfo = {
739
- /** Deltas already stored after the newest base, excluding this change. */
740
- readonly deltasSinceBase: number;
741
- };
742
-
743
- type CommonDocDefinition<T extends JsonObject> = {
744
- readonly kind: string;
745
- readonly version: number;
746
- initial(): T;
747
- migrate?(value: JsonObject, fromVersion: number): T;
748
- checkpointWhen?(value: Readonly<T>, ops: readonly Op[], info: CheckpointInfo): boolean;
749
- };
750
-
751
- type DocDefinition<T extends JsonObject> =
752
- CommonDocDefinition<T> & DocumentSemantics;
753
-
754
- type DocFamilyDefinition<T extends JsonObject, I extends JsonValue> =
755
- Omit<CommonDocDefinition<T>, "initial"> & DocumentSemantics & {
756
- readonly family: true;
757
- initial(seed: I): T;
758
- };
759
-
760
- declare const docType: unique symbol;
761
- interface DocToken<T extends JsonObject, D extends DocDefinition<T>> {
762
- readonly definition: D;
763
- readonly [docType]?: T;
764
- }
765
- interface DocFamilyToken<
766
- T extends JsonObject,
767
- I extends JsonValue,
768
- D extends DocFamilyDefinition<T, I>,
769
- > {
770
- readonly definition: D;
771
- readonly [docType]?: T;
772
- }
773
-
774
- type SessionDocToken<T extends JsonObject> = DocToken<
775
- T,
776
- CommonDocDefinition<T> & { readonly scope: "session" }
777
- >;
778
- type ConversationDocToken<T extends JsonObject> = DocToken<
779
- T,
780
- CommonDocDefinition<T> & (LatestConversationSemantics | RewindableConversationSemantics)
781
- >;
782
- type RewindableConversationDocToken<T extends JsonObject> = DocToken<
783
- T,
784
- CommonDocDefinition<T> & RewindableConversationSemantics
785
- >;
786
- type TaskDocToken<T extends JsonObject> = DocToken<
787
- T,
788
- CommonDocDefinition<T> & { readonly scope: "task" }
789
- >;
790
-
791
- type SessionDocFamilyToken<T extends JsonObject, I extends JsonValue> = DocFamilyToken<
792
- T,
793
- I,
794
- DocFamilyDefinition<T, I> & { readonly scope: "session" }
795
- >;
796
- type ConversationDocFamilyToken<T extends JsonObject, I extends JsonValue> = DocFamilyToken<
797
- T,
798
- I,
799
- DocFamilyDefinition<T, I> & (LatestConversationSemantics | RewindableConversationSemantics)
800
- >;
801
- type RewindableConversationDocFamilyToken<T extends JsonObject, I extends JsonValue> = DocFamilyToken<
802
- T,
803
- I,
804
- DocFamilyDefinition<T, I> & RewindableConversationSemantics
805
- >;
806
- type TaskDocFamilyToken<T extends JsonObject, I extends JsonValue> = DocFamilyToken<
807
- T,
808
- I,
809
- DocFamilyDefinition<T, I> & { readonly scope: "task" }
810
- >;
811
-
812
- function defineDoc<T extends JsonObject>(
813
- definition: CommonDocDefinition<T> & { readonly scope: "session" },
814
- ): SessionDocToken<T>;
815
- function defineDoc<T extends JsonObject>(
816
- definition: CommonDocDefinition<T> & LatestConversationSemantics,
817
- ): ConversationDocToken<T>;
818
- function defineDoc<T extends JsonObject>(
819
- definition: CommonDocDefinition<T> & RewindableConversationSemantics,
820
- ): RewindableConversationDocToken<T>;
821
- function defineDoc<T extends JsonObject>(
822
- definition: CommonDocDefinition<T> & { readonly scope: "task" },
823
- ): TaskDocToken<T>;
824
-
825
- function defineDocFamily<T extends JsonObject, I extends JsonValue>(
826
- definition: Omit<CommonDocDefinition<T>, "initial"> & {
827
- readonly family: true;
828
- readonly scope: "session";
829
- initial(seed: I): T;
830
- },
831
- ): SessionDocFamilyToken<T, I>;
832
- function defineDocFamily<T extends JsonObject, I extends JsonValue>(
833
- definition: Omit<CommonDocDefinition<T>, "initial"> & LatestConversationSemantics & {
834
- readonly family: true;
835
- initial(seed: I): T;
836
- },
837
- ): ConversationDocFamilyToken<T, I>;
838
- function defineDocFamily<T extends JsonObject, I extends JsonValue>(
839
- definition: Omit<CommonDocDefinition<T>, "initial"> & RewindableConversationSemantics & {
840
- readonly family: true;
841
- initial(seed: I): T;
842
- },
843
- ): RewindableConversationDocFamilyToken<T, I>;
844
- function defineDocFamily<T extends JsonObject, I extends JsonValue>(
845
- definition: Omit<CommonDocDefinition<T>, "initial"> & {
846
- readonly family: true;
847
- readonly scope: "task";
848
- initial(seed: I): T;
849
- },
850
- ): TaskDocFamilyToken<T, I>;
851
- ```
852
-
853
- Validation rules:
854
-
855
- - Versions are positive integers.
856
- - Typed access rejects when the token's scope or conversation history/fork policy
857
- disagrees with the persisted incarnation. A migration cannot reinterpret those
858
- lifetime semantics.
859
- - Session documents are current-only and belong to the Session. Closing and
860
- reopening the Session does not retire them.
861
- - Conversation documents declare `history` and `fork`; `fork: "asOf"` requires
862
- `history: "rewindable"`.
863
- - Task documents are current-only, are never copied by a conversation fork, and
864
- retire atomically when their task becomes terminal.
865
- - `initial()` and `migrate()` return JSON objects.
866
-
867
- `checkpointWhen()` only selects complete storage bases to bound replay. It does
868
- not change scope, lifetime, history, or fork semantics.
869
-
870
- Concrete built-in document grouping and semantics are declared when the built-in
871
- definitions are implemented. The generic document mechanism does not special
872
- case model, tool, inbox, or presentation state.
873
-
874
- ### 3.2 Records and lifetimes
875
-
876
- A persisted document instance has one `DocumentRecord`:
877
-
878
- ```ts
879
- type DocumentRecord = {
880
- readonly id: DocumentId; // unique incarnation
881
- readonly kind: string; // stable definition kind
882
- readonly key?: string; // families only
883
- readonly createdAt: Seq; // stamped by the committing storage
884
- readonly retiredAt?: Seq;
885
- } & (
886
- | { readonly scope: { readonly kind: "session" } }
887
- | ({ readonly scope: { readonly kind: "conversation"; readonly conversationId: ConversationId } } & (
888
- | { readonly history: "latest"; readonly fork: "current" | "initial" }
889
- | {
890
- readonly history: "rewindable";
891
- readonly fork: "asOf" | "current" | "initial";
892
- }
893
- ))
894
- | { readonly scope: { readonly kind: "task"; readonly taskId: TaskId } }
895
- );
896
-
897
- type DocumentCreate = DocumentRecord extends infer Record
898
- ? Record extends DocumentRecord
899
- ? Omit<Record, "createdAt" | "retiredAt">
900
- : never
901
- : never;
902
- ```
903
-
904
- `id` is never reused. Retiring and recreating the same logical kind, scope, and
905
- family key creates a new incarnation. Membership is the half-open interval
906
- `createdAt <= at < retiredAt`; an unretired incarnation has no upper bound. A
907
- creation retired in the same commit has an empty lifetime.
908
-
909
- A singleton is identified logically by kind and scope. A family is identified
910
- logically by kind, scope, and `key`. The record preserves scope and conversation
911
- history/fork semantics so unavailable extension code does not make existing data
912
- disappear. Definition versions belong to stored bases and deltas because one
913
- incarnation may contain records written by multiple definition versions.
914
- `DocumentCreate` is not another persisted record; it is the same scoped union
915
- without storage-assigned lifetime fields.
916
-
917
- ### 3.3 Access and creation
918
-
919
- There is no mutable `session.document()` API.
920
-
921
- ```ts
922
- interface Session extends DocumentObserver {
923
- commit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;
924
- close(context: Context): Promise<void>;
925
- subscribeCommits(listener: (publication: CommitPublication, context: Context) => void): () => void;
926
- subscribeClose(listener: () => void): () => void;
927
-
928
- snapshot<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<Readonly<T> | undefined>;
929
- snapshot<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId, context: Context): Promise<Readonly<T> | undefined>;
930
- snapshot<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId, context: Context): Promise<Readonly<T> | undefined>;
931
- snapshot<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string, context: Context): Promise<Readonly<T> | undefined>;
932
- snapshot<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, context: Context): Promise<Readonly<T> | undefined>;
933
- snapshot<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, context: Context): Promise<Readonly<T> | undefined>;
934
-
935
- snapshotAsOf<T extends JsonObject>(token: RewindableConversationDocToken<T>, conversationId: ConversationId, at: EntryId, context: Context): Promise<Readonly<T> | undefined>;
936
- snapshotAsOf<T extends JsonObject, I extends JsonValue>(token: RewindableConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, at: EntryId, context: Context): Promise<Readonly<T> | undefined>;
937
-
938
- documentState<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<DocumentState<T> | undefined>;
939
- documentState<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId, context: Context): Promise<DocumentState<T> | undefined>;
940
- documentState<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId, context: Context): Promise<DocumentState<T> | undefined>;
941
- documentState<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string, context: Context): Promise<DocumentState<T> | undefined>;
942
- documentState<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, context: Context): Promise<DocumentState<T> | undefined>;
943
- documentState<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, context: Context): Promise<DocumentState<T> | undefined>;
944
- }
945
-
946
- interface Tx {
947
- conversation(id: ConversationId): Promise<ConversationRecord | undefined>;
948
- entry(id: EntryId): Promise<EntryRecord | undefined>;
949
- /** Undefined when the entry is absent or has another kind. */
950
- entry<D extends JsonValue>(token: Entry<D>, id: EntryId): Promise<TypedEntry<D> | undefined>;
951
- task(id: TaskId): Promise<TaskRecord<JsonValue, JsonValue, JsonValue> | undefined>;
952
- scanConversations(query: ConversationQuery, limit: number, cursor?: Cursor): Promise<Page<ConversationRecord, Cursor>>;
953
- scanEntries(query: EntryQuery, limit: number, cursor?: Cursor): Promise<Page<EntryRecord, Cursor>>;
954
- scanTasks(query: TaskQuery, limit: number, cursor?: Cursor): Promise<Page<TaskRecord<JsonValue, JsonValue, JsonValue>, Cursor>>;
955
-
956
- createConversation(options: { readonly ownership: ConversationOwnership }): Promise<ConversationRecord>;
957
- forkConversation(
958
- parentConversationId: ConversationId,
959
- at: EntryId,
960
- options: { readonly ownership: ConversationOwnership },
961
- ): Promise<ConversationRecord>;
962
- appendEntry(conversationId: ConversationId, value: EntryDraft): Promise<EntryRecord>;
963
- /** The token supplies `kind` and types `data`. */
964
- appendEntry<D extends JsonValue>(
965
- token: Entry<D>, conversationId: ConversationId, value: TypedEntryDraft<D>,
966
- ): Promise<TypedEntry<D>>;
967
- createTask<I, S extends { phase: string }, R, H extends object>(
968
- task: Task<I, S, R, H>, input: I, options?: TaskOptions,
969
- ): Promise<TaskId<R>>;
970
- /** Settle a queued or placed submission; only a placed input can be answered. A settled one stays unchanged. */
971
- settleSubmission(id: SubmissionId, settlement: SubmissionSettlement): void;
972
-
973
- doc<T extends JsonObject>(token: SessionDocToken<T>): Promise<Draft<T>>;
974
- doc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId): Promise<Draft<T>>;
975
- doc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId): Promise<Draft<T>>;
976
- doc<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string, seed: I): Promise<Draft<T>>;
977
- doc<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, seed: I): Promise<Draft<T>>;
978
- doc<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, seed: I): Promise<Draft<T>>;
979
-
980
- retireDoc<T extends JsonObject>(token: SessionDocToken<T>): Promise<void>;
981
- retireDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId): Promise<void>;
982
- retireDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId): Promise<void>;
983
- retireDoc<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string): Promise<void>;
984
- retireDoc<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string): Promise<void>;
985
- retireDoc<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string): Promise<void>;
986
- }
987
- ```
988
-
989
- ID-creating transaction methods are asynchronous because remote storage may
990
- allocate globally unique numeric IDs durably. Conversation creation always
991
- requires explicit ownership; no transaction wrapper injects the executing task.
992
- For task ownership, the caller supplies only a typed task ID. The Session derives
993
- the persisted owner conversation from the task's final candidate record.
994
-
995
- An owner task may be committed or staged earlier in the same transaction. Before
996
- Storage admission, the Session rejects a missing, terminal, or abort-marked owner,
997
- including one made terminal or abort-marked later in that transaction. Existing
998
- owner edges remain valid when their owners terminalize afterward. Conversation
999
- creation returns an inert record, never an operational handle.
1000
- `forkConversation()` additionally validates one visible entry and applies section
1001
- 3.7. Only public typed `tx.doc()` is get-or-create. Internal fork copying may create
1002
- new incarnations directly from stored values without a definition. `tx.doc()`
1003
- receives the definition token that supplies
1004
- its static type, initializer, migration, and checkpoint policy. Scope-preserving
1005
- token overloads require callers to supply only the concrete conversation/task ID
1006
- and, for a family, its key and creation seed. Ordinary definitions are not
1007
- registered and ordinary documents are not scanned at open.
1008
-
1009
- - Existing instances are reconstructed and migrated lazily according to section
1010
- 3.6. A migration reached through `tx.doc()` is staged in its enclosing
1011
- transaction.
1012
- - A missing singleton calls the token's `initial()`. A missing family member calls
1013
- `initial(seed)`. Creation stores an initial base.
1014
- - The first acquisition of one logical address is memoized before awaiting. Later
1015
- acquisitions in that transaction return the same draft; for a missing family,
1016
- the first call's detached seed wins and later seeds are ignored.
1017
- - `snapshot()`, `snapshotAsOf()`, `documentState()`, and `watchDoc()` never create
1018
- or persist migration. They return `undefined` when the requested incarnation is
1019
- absent and migrate a reconstructed value only in memory.
1020
- - Task-scoped `tx.doc()` validates against the transaction's latest candidate task
1021
- record, falling back to committed state. This internal validation is not a
1022
- caller table read and does not trigger `ReadAfterWrite`. Its conversation is
1023
- derived from the task record.
1024
- - `retireDoc()` resolves the logical address without creating it. Retirement of
1025
- an acquired draft persists its final content before retirement. A later
1026
- `tx.doc()` at that address in the same transaction creates a new incarnation
1027
- with a new draft and ID.
1028
- - A terminal candidate rejects later task-document access. Terminal settlement
1029
- retires both existing task documents and task documents created earlier in the
1030
- same transaction.
1031
- - `snapshot()` returns the current shareable immutable revision. Mutation of it
1032
- or any retained descendant is unsupported; callers that need mutable ownership
1033
- must copy it first.
1034
- - `documentState()` returns a disposable read-only Chord state bound to one committed incarnation.
1035
- - `tx.doc()` returns one revocable Astra overlay `Draft<T>` for the transaction.
1036
- - Historical reads never create documents in the past.
1037
-
1038
- `snapshotAsOf()` is available only for rewindable conversation documents. It
1039
- validates that `at` is visible through the requested conversation's ancestry,
1040
- selects the ancestor conversation that owns that entry, then finds the logical
1041
- singleton/family incarnation whose creation/retirement interval contains the
1042
- entry's commit. It never starts from today's incarnation and never creates an
1043
- instance. It returns `undefined` when no such instance existed.
1044
-
1045
- After `B` forks `A` at entry `E`, asking for `B`'s state at inherited `E` reads
1046
- `A`'s historical instance; `B`'s copied incarnation was created later. If an
1047
- instance was retired and recreated, historical lookup selects the incarnation
1048
- alive at the target commit.
1049
-
1050
- ### 3.4 Mutation ownership
1051
-
1052
- Pico uses Chord Delta's Astra-immutable transaction shape directly:
1053
-
1054
- ```ts
1055
- interface Prepared<T extends object> {
1056
- readonly base: T;
1057
- readonly value: T;
1058
- readonly ops: readonly Op[];
1059
- readonly baseRevision: number;
1060
- abort(): void;
1061
- }
1062
- interface Change<T extends object> {
1063
- readonly state: Draft<T>;
1064
- prepare(): Prepared<T>;
1065
- abort(): void;
1066
- }
1067
- interface Tracker<T extends object> {
1068
- readonly value: T;
1069
- readonly revision: number;
1070
- beginChange(): Change<T>;
1071
- prepareReplace(value: T): Prepared<T>;
1072
- adopt(prepared: Prepared<T>): void;
1073
- }
1074
- ```
1075
-
1076
- Each loaded document owns one tracker whose `value` is its current immutable
1077
- revision. Immutability is a trusted ownership contract, not runtime freezing:
1078
- a revision and its descendants must never be mutated after transfer to the
1079
- tracker. `prepare()` revokes the draft, emits detached self-contained
1080
- operations, and computes `value` with the optimized immutable applier before
1081
- Storage admission. Unchanged subtrees are structurally shared with `base`.
1082
- Operation placement payloads may also be shared with `value`; mutating either a
1083
- prepared operation or an immutable revision is unsupported. Astra preserves an
1084
- empty operation batch for changes it proves are no-ops, but Pico performs no
1085
- additional whole-value equality pass for nonempty structural batches.
1086
-
1087
- `abort()` is idempotent. `adopt()` accepts only a prepared result from that
1088
- tracker at its current revision, then performs only a synchronous pointer swap
1089
- to the already-computed immutable `value`. It performs no diffing, application,
1090
- allocation, or callback. The Session line permits at most one open change per
1091
- tracker and ensures no result becomes stale between preparation, Storage
1092
- settlement, and adoption.
1093
-
1094
- The first `tx.doc()` acquisition calls `tracker.beginChange()` and memoizes that
1095
- change's draft for the rest of the possibly async Session callback.
1096
-
1097
- Transaction behavior:
1098
-
1099
- ```text
1100
- begin transaction
1101
- acquire and memoize document changes by logical address
1102
- mutate revocable Astra overlay drafts
1103
- callback settles
1104
- seal Tx; synchronously prepare or abort every open change, revoking every draft
1105
- if any acquisition is pending: abort open changes, reject, then drain and abort it
1106
- callback fails with no pending acquisition
1107
- abort every open change; persist and publish nothing
1108
- callback succeeds with no pending acquisition
1109
- prepare every open change -> immutable next revision + self-contained Chord Op[]
1110
- Session evaluates each required/ordinary document write exactly once
1111
- prepare every affected loaded conversation mount revision
1112
- Storage.commit persists the atomic batch while the Session line remains held
1113
- storage succeeds
1114
- adopt every prepared change by pointer swap and enqueue immutable revision/ops publication
1115
- release the line; invoke listeners later
1116
- storage fails
1117
- abort every prepared change, poison Session, and publish nothing
1118
- ```
1119
-
1120
- A pending acquisition that resolves after sealing never exposes a draft; its
1121
- change is aborted and its promise rejects. The Session observes every such
1122
- settlement before releasing the line. Initializer, migration, and replacement
1123
- roots come from caller code: the Session copies each one into exclusive kernel
1124
- ownership, rejecting any value that is not strict JSON, before it becomes an
1125
- immutable tracker revision. Loaded and fork-copy roots are already detached
1126
- strict JSON from Storage and enter the tracker without another copy. Chord's
1127
- `track()` and `prepareReplace()` take ownership in O(1) without traversal, so
1128
- every root they receive must come from one of these sources. Migration callbacks
1129
- never receive a live tracker revision.
1130
-
1131
- Preparation, validation, checkpoint, or mounted-view preparation failure occurs
1132
- before Storage admission and rolls back normally. The Session performs no
1133
- strict-JSON walk of prepared operations or selected bases: roots are checked on
1134
- entry and Chord checks every draft placement, so every revision, operation
1135
- payload, and base is strict JSON by construction. Tracker branding and `baseRevision` enforce ownership and staleness; the
1136
- Session never substitutes caller-created prepared values. The prepared immutable
1137
- candidate itself becomes the adopted and published value. Storage receives that complete value only when the
1138
- Session selects a base; otherwise it receives only the prepared operation batch.
1139
- An existing current-version document with an empty batch writes and publishes
1140
- nothing. A nonempty structural batch whose final value is deeply equal to its
1141
- base remains a valid durable change and publication. Creation and required
1142
- version transitions still write a base when their prepared batch is empty; an
1143
- equal-value version base does not emit a watch update.
1144
-
1145
- Values assigned into a draft are copied immediately by value. Repeated
1146
- placements are independent. Chord checks each placement while copying it and
1147
- throws at the offending assignment, before the draft changes, when the value is
1148
- not strict JSON: `undefined` array elements or nested object values, non-finite
1149
- numbers, functions, symbols, bigints, accessors, symbol keys, sparse arrays, or
1150
- objects whose prototype is neither `Object.prototype` nor `null`. Assigning
1151
- `undefined` directly to an object property deletes that property. Draft reads, draft writes, and all `Tx` operations
1152
- reject after the callback settles. The prepared immutable value remains readable
1153
- by Session-owned checkpoint and Storage preparation.
1154
-
1155
- ```ts
1156
- let escaped: Draft<LiveState>;
1157
- await session.commit(async tx => {
1158
- escaped = await tx.doc(LiveDoc, conversationId);
1159
- });
1160
- escaped.message = message; // throws: the draft was revoked
1161
- ```
1162
-
1163
- Fire-and-forget work that mutates a draft before the owner callback settles may
1164
- silently enter that transaction and is unsupported.
1165
-
1166
- ### 3.5 Bases and checkpoints
1167
-
1168
- Creation always stores a complete base.
1169
-
1170
- For an ordinary later mutation, the definition alone decides whether the
1171
- storage record is a base:
1172
-
1173
- ```ts
1174
- const useBase = definition.checkpointWhen?.(candidateValue, ops, { deltasSinceBase }) ?? false;
1175
- ```
1176
-
1177
- The Session evaluates this predicate exactly once after tracker preparation.
1178
- `deltasSinceBase` counts the deltas already stored after the incarnation's newest
1179
- base, excluding the change being evaluated. Storage reports it when it
1180
- materializes the current value; the Session advances it after each adopted write
1181
- and resets it after every base, so evaluation performs no Storage read.
1182
- Creation and version transitions require bases and do not call it. The Session
1183
- then gives Storage only the selected representation:
1184
-
1185
- ```text
1186
- required or predicate true -> base with complete value
1187
- otherwise -> delta with the prepared Chord operation batch
1188
- ```
1189
-
1190
- A Chord root-replacement operation remains a delta unless the definition selected
1191
- a checkpoint; it does not authorize reclamation. Predicate failure aborts the
1192
- prepared transaction before Storage admission. Storage executes no definition
1193
- code and never receives an unused complete candidate with a selected delta.
1194
-
1195
- - For Session, task, and latest conversation documents, a committed base permits
1196
- physical reclamation of older records.
1197
- - For rewindable conversation documents, bases bound replay but never permit
1198
- removal of addressable history.
1199
- - A definition that never checkpoints may create an unbounded replay tail. That
1200
- is a definition bug, not a backend heuristic.
1201
- - Storage does not count encoded bytes, compare against `initial()`, or invent
1202
- checkpoints.
1203
-
1204
- A definition can bound replay directly:
1205
-
1206
- ```ts
1207
- checkpointWhen: (_value, _ops, info) => info.deltasSinceBase >= 31
1208
- ```
1209
-
1210
- A high-churn live document can checkpoint when it becomes empty:
1211
-
1212
- ```ts
1213
- checkpointWhen: (value, _ops) =>
1214
- value.message === undefined &&
1215
- value.tools.length === 0
1216
- ```
1217
-
1218
- ### 3.6 Versions and migrations
1219
-
1220
- One migration callback handles every supported older version.
1221
-
1222
- ```text
1223
- stored == token -> use value
1224
- stored < token -> call migrate(value, storedVersion)
1225
- stored > token -> reject typed access
1226
- no migrate -> reject older stored version
1227
- ```
1228
-
1229
- `migrate()` is pure and returns a complete current-version value. Migration is
1230
- access-driven: `tx.doc()`, `snapshot()`, `snapshotAsOf()`, `documentState()`, and
1231
- `watchDoc()` reconstruct and migrate through the token supplied to that call.
1232
- Harness open does not sweep ordinary documents.
1233
-
1234
- - Read-only access migrates only in memory and never writes. It may cache a
1235
- tracker over that migrated immutable revision together with the older stored
1236
- version marker; the next successful `tx.doc()` access still writes the required
1237
- current-version base. A cached tracker serves only tokens of the version its value was
1238
- materialized for. Access with any other version, such as a token from reloaded
1239
- extension code, drops it and reloads the stored value, so each token migrates
1240
- from the stored version or rejects a newer one. Migration always starts from a detached stored value.
1241
- `tx.doc()` stages migration in its enclosing transaction; callback failure
1242
- persists nothing, and later draft edits coalesce into one final required base.
1243
- - Rewindable history is not rewritten. Current and historical reconstructed
1244
- values are migrated after replay.
1245
- - The first `tx.doc()` transaction after any stored-version migration writes a
1246
- required current-version base, even when the migrated JSON is deeply equal.
1247
- - A fork obtains the selected stored value/version from Storage rather than a
1248
- typed migrated tracker cache. The child copies that stored pair and migrates on
1249
- later typed access.
1250
- - Unaccessed documents and documents with unavailable definitions preserve their stored instances,
1251
- versions, and bytes.
1252
-
1253
- ### 3.7 Forks
1254
-
1255
- A conversation fork points to one concrete visible entry `E`.
1256
-
1257
- The child transcript includes entries through `E`, even if the same commit also
1258
- appended later entries. Document state at `E` is the final state of the commit
1259
- containing `E`. Different document states require separate commits.
1260
-
1261
- Each conversation document follows the history/fork policy persisted in its
1262
- `DocumentRecord`:
1263
-
1264
- | conversation setting | child value |
1265
- |---|---|
1266
- | `fork: "asOf"` | parent value at `E`'s commit |
1267
- | `fork: "current"` | committed parent value selected when the fork commit runs |
1268
- | `fork: "initial"` | no copied instance; initializer on first child access |
1269
-
1270
- `current` and `asOf` copy logically present conversation singleton and family
1271
- instances, preserving unknown definitions and their stored versions. Copied
1272
- values become independent child instances with new IDs and initial bases.
1273
- `initial` copies no instance; first access in the child creates it from the
1274
- supplied definition. Task documents and tasks are never copied. Session documents
1275
- remain shared and are not rewindable.
1276
-
1277
- Fork copying reads committed stored values rather than typed tracker caches. A
1278
- transaction that creates a fork therefore rejects if it also writes one of the
1279
- parent's `fork: "current"` documents; commit the parent change first so the fork
1280
- has one unambiguous stored source revision.
1281
-
1282
- Forks stage backend-side `document.copy` commands carrying the child create
1283
- record and an exact source incarnation/point. Storage materializes each source
1284
- and persists its stored value/version as the child's independent initial base;
1285
- remote Storage performs this server-side. Every copy reads committed pre-batch
1286
- source state independent of write-array order. A selected source may not be
1287
- created, changed, or retired in the same batch. Copying remains atomic with the
1288
- conversation, overrides, registry writes, and other mutations.
1289
-
1290
- An unaccessed copy retains only its descriptor in Session memory. Typed access
1291
- inside the creating transaction lazily reads the detached source, migrates when
1292
- required, and replaces the copy with one ordinary child create containing the
1293
- final prepared value. Definition-free copies publish explicit `document.copy`
1294
- metadata rather than a value. That metadata announces Storage-backed initial
1295
- state and is never interpreted as a document value. Document states, watches,
1296
- and mounted views hydrate by capturing their baseline and subscription
1297
- atomically on the Session line: a later commit already present becomes the
1298
- baseline, while one committed after registration is delivered. Publications
1299
- and watches are convergence mechanisms, not audit streams. A mounted aggregate
1300
- must acquire all of its document baselines and commit subscription in one
1301
- Session-line operation so it never exposes a mixture from one commit.
1302
-
1303
- ## 4. Transactions and storage ownership
1304
-
1305
- A Session commit callback may be asynchronous. It owns the Session mutation
1306
- line through callback execution, preparation, storage settlement, committed
1307
- baseline adoption, and publication enqueue. Commit observers run on the
1308
- line; document-state and watch user callbacks run later.
1309
- External model, process, tool, network, and human effects run outside it.
1310
- `subscribeCommits()` observes complete immutable publications synchronously on
1311
- the line after adoption. `subscribeClose()` observes close synchronously when it
1312
- begins, after admission is sealed; the Harness stops watches and signals task
1313
- invocations there. Both return idempotent disposers; their listeners must not
1314
- throw, block, or call Session APIs. Document-state subscribers and watch
1315
- listeners still run later, off the line.
1316
-
1317
- ```ts
1318
- await session.commit(async tx => {
1319
- const conversation = await tx.conversation(conversationId); // table read
1320
- const live = await tx.doc(LiveDoc, conversationId);
1321
-
1322
- await tx.appendEntry(conversationId, message); // first table write
1323
- delete live.message; // document mutation remains valid
1324
- await tx.createTask(Follow, { after: message.id }); // further table writes are fine
1325
- }, context);
1326
- ```
1327
-
1328
- Mutation admission occurs on the Session line before a commit callback starts. Closing seals mutation admission and task
1329
- reservation. Already-admitted commits settle before storage closes. Once a
1330
- commit is admitted, caller cancellation does not interrupt storage settlement or
1331
- undo the commit. Cancelling a close wait does not reopen admission.
1332
-
1333
- Table rules:
1334
-
1335
- - Tables are conversations, entries, tasks, and submissions.
1336
- - Table reads are allowed before the first table write.
1337
- - Any table read after the first table write throws `ReadAfterWrite`.
1338
- - Document access and read-your-writes remain available after table writes.
1339
- - Creation methods return their created ID/record; callers do not read it back.
1340
-
1341
- Storage ownership:
1342
-
1343
- - Commit arguments are borrowed until `Storage.commit()` settles.
1344
- - Anything retained after settlement is detached first.
1345
- - Memory storage recursively copies retained JSON containers.
1346
- - JSONL and SQLite detach through serialization and decoded indexes.
1347
- - Every storage read returns a detached JSON value.
1348
- - Immutable strings may be shared; mutable arrays and objects may not.
1349
-
1350
- ## 5. Tasks
1351
-
1352
- ### 5.1 Definition
1353
-
1354
- ```ts
1355
- type TaskOutcome<R> =
1356
- | { readonly status: "completed"; readonly result: R }
1357
- | { readonly status: "failed"; readonly error: TaskOutcomeError; readonly result?: R }
1358
- | { readonly status: "aborted"; readonly reason?: string; readonly result?: R }
1359
- | { readonly status: "orphaned"; readonly reason: string }
1360
- | { readonly status: "faulted"; readonly error: TaskOutcomeError };
1361
-
1362
- type TaskState<S, R> =
1363
- | { readonly status: "pending"; readonly checkpoint: S }
1364
- | { readonly status: "running"; readonly checkpoint: S }
1365
- | { readonly status: "terminal"; readonly outcome: TaskOutcome<R> };
1366
-
1367
- type TaskRecord<I, S, R> = {
1368
- readonly id: TaskId<R>;
1369
- readonly conversationId: ConversationId;
1370
- readonly kind: string;
1371
- readonly version: number;
1372
- readonly input: I;
1373
- readonly after: readonly TaskId[];
1374
- readonly background: boolean;
1375
- readonly abortRequested: boolean;
1376
- } & (
1377
- | {
1378
- readonly state: Extract<TaskState<S, R>, { status: "pending" | "running" }>;
1379
- readonly memos?: Readonly<Record<string, JsonValue>>;
1380
- }
1381
- | {
1382
- readonly state: Extract<TaskState<S, R>, { status: "terminal" }>;
1383
- readonly memos?: never;
1384
- }
1385
- );
1386
-
1387
- type RunningTask<I, S, R> = TaskRecord<I, S, R> & {
1388
- readonly state: Extract<TaskState<S, R>, { status: "running" }>;
1389
- };
1390
-
1391
- /** State a task commits for itself: a replacement checkpoint or its terminal outcome. */
1392
- type NextTaskState<S, R> = Extract<TaskState<S, R>, { status: "running" | "terminal" }>;
1393
-
1394
- interface HookRunner<H extends object> {
1395
- each<K extends keyof H>(name: K, invoke: (handler: H[K]) => void | Promise<void>): Promise<void>;
1396
- }
1397
-
1398
- type PhaseHandler<I, P, S, R, H extends object> = (
1399
- task: RunningTask<I, P, R>,
1400
- runtime: TaskRuntime<I, S, R, H>,
1401
- context: Context,
1402
- ) => Promise<void>;
1403
-
1404
- interface TaskRuntime<I, S, R, H extends object> extends DocumentObserver, DocumentReader {
1405
- readonly taskId: TaskId<R>;
1406
- readonly conversationId: ConversationId;
1407
- readonly signal: AbortSignal;
1408
- /** Registry snapshot of the current phase; refreshed at every phase boundary. */
1409
- readonly registry: RegistrySnapshot<ToolRegistration>;
1410
- readonly models: Models;
1411
- readonly hooks: HookRunner<H>;
1412
-
1413
- commit(
1414
- change: (
1415
- tx: Tx,
1416
- current: RunningTask<I, S, R>,
1417
- ) => NextTaskState<S, R> | undefined | Promise<NextTaskState<S, R> | undefined>,
1418
- context: Context,
1419
- ): Promise<void>;
1420
-
1421
- memo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;
1422
- memo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;
1423
- conversation(id: ConversationId, context: Context): Promise<ConversationHandle | undefined>;
1424
- /** Committed raw active transcript and model context, optionally cut off at `at`. */
1425
- context(conversationId: ConversationId, context: Context, at?: EntryId): Promise<ContextView>;
1426
- /** The Harness clock. */
1427
- now(): number;
1428
- /** Forward a non-fatal failure to `HarnessOptions.onReport`. */
1429
- report(error: unknown): void;
1430
- sleep(until: number, context: Context): Promise<void>;
1431
- }
1432
-
1433
- type TaskDefinition<I, S extends { phase: string }, R, H extends object> = {
1434
- readonly name: string;
1435
- readonly version: number;
1436
- initial(input: I): S;
1437
- readonly phases: {
1438
- [P in S["phase"]]: PhaseHandler<I, Extract<S, { phase: P }>, S, R, H>;
1439
- };
1440
- abort(task: RunningTask<I, S, R>, runtime: TaskRuntime<I, S, R, H>, context: Context): Promise<void>;
1441
- migrate?(input: JsonValue, checkpoint: JsonValue, fromVersion: number): {
1442
- input: I;
1443
- checkpoint: S;
1444
- };
1445
- readonly hooks?: H;
1446
- };
1447
-
1448
- interface Task<I, S extends { phase: string }, R, H extends object> {
1449
- readonly definition: TaskDefinition<I, S, R, H>;
1450
- }
1451
-
1452
- type TaskOptions = {
1453
- readonly conversationId?: ConversationId;
1454
- readonly after?: readonly TaskId[];
1455
- readonly background?: boolean;
1456
- };
1457
-
1458
- function defineTask<I, S extends { phase: string }, R, H extends object = {}>(
1459
- definition: TaskDefinition<I, S, R, H>,
1460
- ): Task<I, S, R, H>;
1461
- ```
1462
-
1463
- `TaskId<R>` is the numeric task ID itself with an erased result-type brand. It
1464
- replaces a separate task-reference wrapper: `createTask()` returns `TaskId<R>`,
1465
- typed waits infer `R` from that ID, and result-agnostic operations accept
1466
- `TaskId<unknown>`. A task's `conversationId` is immutable after creation; a
1467
- replacement that moves an existing task to another conversation rejects before
1468
- Storage admission so persisted conversation-owner edges cannot become stale.
1469
-
1470
- The phase map is exhaustive and phase-narrowed. A handler may perform several
1471
- commits around one effect, but each durable checkpoint is a full replacement.
1472
- `TaskRuntime.commit()` rereads and gates the current durable task on the Session
1473
- line before invoking its callback. It rejects when the invocation has ended, the
1474
- Harness is closing, the task is terminal, or a run invocation's task carries an
1475
- abort mark. Its `tx.createTask()` defaults to the task's conversation, and every
1476
- entry it appends records the task as `byTaskId`. When the
1477
- callback returns a state, the runtime replaces the task's state in the same
1478
- commit, so the checkpoint or outcome is atomic with the callback's entries,
1479
- documents, and child tasks and is type-checked against the task's checkpoint and
1480
- result types. Returning nothing leaves the state unchanged. A terminal state
1481
- drops the memos. `pending` is never returned; only reconciliation and handover
1482
- write it.
1483
-
1484
- `Tx` has no task replacement operation. A task changes only its own state,
1485
- through its runtime. The scheduler owns reservation, reconciliation, handover,
1486
- faults, and orphaning; `abortTask()` owns abort marks. Other code
1487
- stops a task with `abortTask()` and reads its result with `waitForTask()`.
1488
-
1489
- ```ts
1490
- // Intent, effect, outcome.
1491
- prepare: async (task, runtime, context) => {
1492
- await runtime.commit(() => ({ status: "running", checkpoint: { phase: "charge", key: newKey() } }), context);
1493
- },
1494
- charge: async (task, runtime, context) => {
1495
- const receipt = await payments.charge(task.state.checkpoint.key); // idempotent by key
1496
- await runtime.commit(async (tx, current) => {
1497
- const entry = await tx.appendEntry(current.conversationId, receiptEntry(receipt));
1498
- return { status: "terminal", outcome: { status: "completed", result: { entryId: entry.id } } };
1499
- }, context);
1500
- },
1501
- // The abort handler decides the outcome; returning without one faults the task.
1502
- abort: async (task, runtime, context) => {
1503
- await payments.cancel(task.state.checkpoint);
1504
- await runtime.commit(() => ({ status: "terminal", outcome: { status: "aborted", reason: "user" } }), context);
1505
- },
1506
- ```
1507
- `memo(name, candidate)` is one gated commit; `memo(name)` reads the committed
1508
- record. `sleep(until)` compares against the Harness `now` clock and rejects when
1509
- the invocation is signalled or its context is cancelled. Watches acquired through
1510
- the runtime stop when the invocation ends. `snapshot()`/`snapshotAsOf()` read
1511
- committed documents, for example to supply `PromptInput.read` (section 7.4).
1512
- `context()` captures its bounds on the Session line and derives the view from
1513
- immutable entries off the line, like `Conversation.context()`. Like every runtime
1514
- operation, these reject after the invocation ends.
1515
-
1516
- Reservation durably changes `pending` to `running`. One invocation runs phase
1517
- handlers in sequence; checkpoint commits retain `running`. Before every phase,
1518
- including the first, the scheduler runs one step callback on the Session line.
1519
- It reads the committed task and synchronously applies the first matching rule
1520
- below to the phase that just returned. It writes any fault or handover in the
1521
- same commit, together with the Harness cleanup for a scheduler-written outcome
1522
- (section 5.4), which may await document access inside that callback. It ends
1523
- the invocation there when a rule stops it. A runtime commit the
1524
- invocation queued earlier therefore either lands before the step and counts, or
1525
- reaches the line after it and rejects. Before the first phase only rules 1–3
1526
- apply:
1527
-
1528
- 1. Terminal: stop.
1529
- 2. Session closing: stop; preserve the checkpoint and any abort mark for reopen.
1530
- 3. Run mode with a durable abort mark: end and join the run invocation, then
1531
- dispatch a fresh abort invocation.
1532
- 4. Uncaught error: write terminal `faulted`.
1533
- 5. Checkpoint changed, including progress within the same phase: refresh the
1534
- registry snapshot and either hand over (section 5.4) or invoke the phase
1535
- handler in the same task invocation.
1536
- 6. Checkpoint unchanged: write terminal `faulted` because no durable progress
1537
- was made.
1538
-
1539
- An abort invocation runs its abort handler once. After it settles, a step
1540
- applies rules 1, 2, and 4; a handler that returns without a terminal outcome
1541
- faults the task. When Storage rejects a step's fault or handover write, the
1542
- invocation still ends; the task stays `running` and the next reservation runs it
1543
- again.
1544
-
1545
- On open, running-task reconciliation changes surviving `running` tasks back to
1546
- `pending`, preserving their checkpoint and abort mark. Task migration runs at
1547
- reservation, atomically with `pending -> running`. One callback handles every
1548
- supported older version. A task whose definition is missing, older than the
1549
- stored version, or fails migration stays `pending` and blocked until a fitting
1550
- definition is registered or the task is aborted (section 5.4).
1551
- `close()` marks the runtime closing, seals admission and reservation, signals
1552
- invocations, and stops watches. Outside the Session line it settles admitted
1553
- commits and joins invocations before closing storage. Already-running watch callbacks remain
1554
- caller-owned. Later runtime commits reject, and close writes no task outcome. Closing
1555
- starts no fresh phase or abort invocation. It does not set abort marks,
1556
- terminalize tasks, retire task documents, or publish document retirement. The
1557
- hosting layer withdraws services and
1558
- detaches clients; reconnecting to a reopened Session hydrates the last committed
1559
- state and resumes recovery from its durable checkpoints.
1560
-
1561
- ### 5.2 Effect sandwich
1562
-
1563
- ```text
1564
- commit intent phase
1565
- perform external effect
1566
- commit outcome or next phase
1567
- ```
1568
-
1569
- Reopening in an intent phase means the effect may have happened. The phase
1570
- handler retries safely, polls an external handle, or records interruption.
1571
- Deferred providers are represented by a durable phase containing their handle
1572
- and next poll time.
1573
-
1574
- Runtime-owned memos are small first-writer-wins values stored in the live task
1575
- envelope. Candidate insertion and reading the winner are one Session commit, so
1576
- concurrent candidates return the same durable winner. Memos survive checkpoints
1577
- and disappear in the terminal replacement. Bulk progress belongs in a document.
1578
-
1579
- ### 5.3 Terminal tasks and dependencies
1580
-
1581
- The terminal task record is the durable result receipt. Its result may directly
1582
- contain a small value or reference an entry:
1583
-
1584
- ```ts
1585
- { status: "completed", result: { entryId: toolResultId } }
1586
- ```
1587
-
1588
- A terminal transition atomically:
1589
-
1590
- 1. Writes the terminal task record.
1591
- 2. Appends any result entries.
1592
- 3. Retires all documents scoped to that task.
1593
- 4. Resolves any submissions settled by the task.
1594
-
1595
- The execution checkpoint and memos disappear from the terminal representation.
1596
- Terminal records remain queryable for dependencies, waiters, inspection, and
1597
- reopen. A normal run becomes eligible when every `after` task is terminal. An abort
1598
- mark bypasses dependencies so pending work can always reach its abort handler,
1599
- or its `orphaned` settlement when its definition is unavailable.
1600
-
1601
- ### 5.4 Scheduler, abort, and ownership
1602
-
1603
- The scheduler serially reserves eligible tasks, then runs handlers off the
1604
- Session line. One in-memory `TaskInvocation` contains mode, abort controller,
1605
- and completion promise.
1606
-
1607
- Abort protocol:
1608
-
1609
- ```text
1610
- commit abortRequested
1611
- signal and join active run invocation
1612
- start a fresh abort invocation
1613
- abort handler commits terminal outcome
1614
- ```
1615
-
1616
- A run invocation may not commit after its durable abort mark appears. Every
1617
- runtime operation rejects after its owning invocation ends, even while the
1618
- Session remains open. Returning from one phase handler does not end an invocation
1619
- that continues into another phase. Invocation mode is volatile and derived from
1620
- the durable mark on reopen. Cancelling one caller's `Context` only cancels
1621
- that call or wait; it does not durably abort shared work unless the invoked API
1622
- commits an abort mark.
1623
-
1624
- A task may create owned conversations. Conversations are durable scopes; tasks
1625
- are the units of live work counted by idle and marked by abort. History parents
1626
- are irrelevant to ownership traversal.
1627
-
1628
- Ordinary traversal starts at an explicitly addressed conversation, visits its
1629
- tasks, and follows conversations owned by each non-background task. It follows
1630
- owner edges after the owner becomes terminal, but a background owner is a
1631
- boundary: ordinary traversal skips that task and its complete owned subtree.
1632
- Direct conversation operations start inside that conversation regardless of its
1633
- owner. Directly aborting a live background task includes that task and follows
1634
- its ordinary owned subtree; nested background owners remain boundaries. Full
1635
- teardown crosses every boundary, marks every live task, and must seal new
1636
- admission while it gathers the complete indexed ownership subtree.
1637
-
1638
- `Conversation.abort()` withdraws queued inputs and marks live non-background
1639
- tasks selected by ordinary traversal. `Conversation.waitForIdle()` waits until
1640
- that traversal contains no live non-background task. Harness idle performs the
1641
- same traversal from every ownerless conversation root rather than globally
1642
- counting tasks, so ordinary work below a background owner does not block it.
1643
- Explicit `waitForTask()` waits for its referenced task regardless of the task's
1644
- background flag.
1645
-
1646
- An abort mark atomically and idempotently cascades to foreground-owned work,
1647
- including conversations, tasks, and submissions staged in the same transaction.
1648
- Terminal outcomes `failed`, `faulted`, `orphaned`, and `aborted` record the same
1649
- durable cancellation intent; `completed` does not. Conversation records and
1650
- owner edges are never retired with the task. Active invocations are signalled
1651
- after commit, and a terminal receipt guarantees durable cancellation intent,
1652
- not descendant quiescence.
1653
-
1654
- Every run invocation start resolves the task's definition by `TaskRecord.kind`
1655
- from the scheduler's current registry snapshot:
1656
-
1657
- ```text
1658
- definition missing -> stay pending, blocked: missing_task
1659
- stored version newer than it -> stay pending, blocked: task_too_old
1660
- stored version older than it -> migrate(input, checkpoint, storedVersion)
1661
- failure -> stay pending, blocked: migration_failed
1662
- success -> commit migrated record + running atomically
1663
- equal version -> commit running
1664
- ```
1665
-
1666
- An abort invocation resolves the definition the same way. When the definition
1667
- can take the task, its abort handler runs; otherwise the task is orphaned as
1668
- described below.
1669
-
1670
- A failed migration is reported once through `onReport` and retried only after
1671
- the registry resolves a different definition object for the task's kind.
1672
-
1673
- The Harness never terminalizes a task merely because registry code is missing or
1674
- incompatible, neither at open nor later. A blocked task without an abort mark
1675
- keeps its durable record unchanged, remains live, still blocks ordinary idle
1676
- waits, and is reconsidered whenever the registry changes. The blocked reason is derived
1677
- runtime state, not a persisted task status. Document migration remains
1678
- access-driven.
1679
-
1680
- Aborting a blocked task cannot run its abort handler, because that code is
1681
- missing or cannot take the task. The Harness therefore settles it as terminal
1682
- `orphaned` instead of `aborted`: `aborted` means the task's own abort handler
1683
- ran and decided the outcome, while `orphaned` means no task code ran, so external
1684
- effects the task started may remain uncleaned. The orphaned `reason` is the
1685
- blocked reason (`missing_task`, `task_too_old`, or `migration_failed`). When
1686
- `abortTask()` finds no active invocation and the current snapshot
1687
- cannot take the task, the marking commit settles it directly; otherwise the
1688
- scheduler settles it when it would reserve the abort invocation. Only an abort (direct, by
1689
- conversation, or by cascade) orphans a task; a missing definition alone never
1690
- does. The orphaning commit performs the cleanup the task's code cannot: affected
1691
- input submissions become unanswered with the reason, any matching active run
1692
- control is cleared, and task-scoped documents retire. No transcript entry is
1693
- written; the terminal task record and unanswered submissions carry the reason.
1694
- Faulting a run task performs the same control/submission cleanup with a
1695
- `faulted` outcome.
1696
-
1697
- The scheduler knows nothing about runs or task kinds. The Harness, which owns
1698
- submissions, run control, and the built-in tasks, gives it one hook that the
1699
- scheduler calls in the same commit for every terminal outcome it writes itself
1700
- (`faulted` and `orphaned`). The hook ignores tasks whose kind is not a built-in
1701
- run kind, so it never creates `pi.live` elsewhere. It settles the run when
1702
- `pi.live.run` names the task (section 8): its inputs become `unanswered` with reason `faulted`
1703
- (detail: the error message) or the blocked reason, and `run` and `generation`
1704
- are removed. Outcomes a task commits for itself do their own settlement.
1705
-
1706
- At every normal phase boundary (section 5.1, rule 5), the step refreshes the
1707
- invocation's registry snapshot. If the task definition resolved by name is a different object
1708
- than the one the invocation started with and the new definition can reserve the
1709
- task (same version, or a higher version with `migrate`), the invocation hands
1710
- over: the step commits the task back to `pending` with its checkpoint, memos,
1711
- and abort mark and ends the invocation, and the next reservation starts a fresh invocation under the new
1712
- definition, applying the reservation rules above. When the definition is missing
1713
- or cannot reserve the task, the invocation keeps running under its old
1714
- definition, reports once through `onReport` per resolved definition, and
1715
- reconsiders at its next boundary. A handler that
1716
- never settles never hands over.
1717
-
1718
- ## 6. Submissions and inbox
1719
-
1720
- Submission records back awaitable host objects. Admission is Harness-internal;
1721
- run tasks settle the inputs they answer with `tx.settleSubmission()`. The inbox
1722
- itself is an ordered conversation document containing tagged items:
1723
-
1724
- ```ts
1725
- type InboxItem =
1726
- | { readonly id: SubmissionId; readonly mode: "steer" | "followUp"; readonly message: Message }
1727
- | { readonly id: SubmissionId; readonly mode: "write"; readonly entry: EntryDraft };
1728
- ```
1729
-
1730
- Run control lives in the built-in live document `pi.live` (section 8). Its
1731
- optional `run` value names the task currently responsible for the run and its
1732
- placed input-submission IDs. `run !== undefined` defines `busy`; get-or-create
1733
- of the idle document does not. The value remains while generation, tools, and
1734
- post-tools hand work to one another. The ID list is mutable state because a
1735
- boundary adds placed steering inputs to an active run; every terminal path
1736
- settles exactly the listed inputs.
1737
-
1738
- Admission and terminal transitions:
1739
-
1740
- | action | submission state | other writes |
1741
- |---|---|---|
1742
- | idle input submission | `placed`, with user entry | create run controller/generation |
1743
- | busy input submission | `queued` | append steer/follow-up inbox item |
1744
- | idle write submission | `done`, with entry | append entry; no run |
1745
- | busy write submission | `queued` | append write inbox item |
1746
- | boundary places user item | `placed`, with entry | add ID to current/successor run |
1747
- | boundary places write | `done`, with entry | append entry |
1748
- | run answers | input `done`, with required answer entry | clear/hand off run controller |
1749
- | run fails or aborts | input `unanswered`, with reason | clear/hand off run controller |
1750
- | withdraw queued item | `unanswered`, reason `aborted` | remove inbox item |
1751
- | stale item | `unanswered`, reason `stale` | remove inbox item |
1752
-
1753
- `requestId` deduplicates within one conversation before any write; reusing one
1754
- for the other submission type rejects. A busy input with `whenBusy: "reject"`
1755
- writes no record and reports `ConversationBusy`. Before an idle input places its
1756
- own entry, it runs a final boundary to drain older eligible queued items. A
1757
- `Submission` waits until `done` or `unanswered`; abort withdraws only a still-
1758
- queued submission, reports `already_placed` for a placed input, and reports
1759
- `settled` for any terminal submission. Conversation abort withdraws queued steer/follow-up submissions but keeps writes
1760
- for later placement.
1761
-
1762
- Boundary selection is deterministic by item ID:
1763
-
1764
- | boundary | write | steer | follow-up |
1765
- |---|---|---|---|
1766
- | `postTools` | all | first/all by mode | none |
1767
- | `final` | all | first/all by mode | first/all by mode |
1768
-
1769
- A queued self-head write cuts older pending user items: those submissions become
1770
- stale, the write is placed, and the current run terminates. Other head writes
1771
- whose target predates the caller's newest known head are stale.
1772
-
1773
- At ordinary `postTools`, generation continues even with no queued trigger;
1774
- selected steer IDs join that continuation. A terminating/handoff post-tools
1775
- boundary uses final behavior instead. At `final`, the current run's placed
1776
- input submissions settle first; selected user IDs start one successor generation. Writes
1777
- never trigger generation by themselves. A final boundary without continuation
1778
- or user triggers leaves the conversation idle.
1779
-
1780
- Selected and stale items are removed positionally while retained item order is
1781
- preserved. Chord's Astra operation generator must express scattered removals
1782
- without carrying retained values; IDs are not substituted for positional inbox
1783
- semantics.
1784
-
1785
- ## 7. Registry, hooks, tools, and system prompt
1786
-
1787
- ### 7.1 Registry
1788
-
1789
- Extension code reaches the Harness through one application-owned registry. The
1790
- registry is process-local, may outlive a Harness, and is the only place tools,
1791
- tool wrappers, hooks, tasks, and the system prompt are registered. Nothing
1792
- in it is persisted; durable state stays in conversations, entries, tasks, and
1793
- documents.
1794
-
1795
- ```ts
1796
- type DocumentReader = Pick<Session, "snapshot" | "snapshotAsOf">;
1797
-
1798
- interface Registration {
1799
- /** Idempotent; removes exactly the registrations this token covers. */
1800
- dispose(): void;
1801
- }
1802
-
1803
- type ToolWrapper<Tool extends ToolRegistration> = (tool: Tool) => Tool;
1804
-
1805
- type HookScope = {
1806
- readonly conversationId: ConversationId;
1807
- /** Also match conversations owned, transitively, by tasks of this conversation. */
1808
- readonly subtree?: boolean;
1809
- };
1810
-
1811
- type PromptInput<Tool extends ToolRegistration> = {
1812
- readonly conversationId: ConversationId;
1813
- /** Active and registered tools in configured order, as offered in this request. */
1814
- readonly tools: readonly Tool[];
1815
- /** Sections already in effect after replaying the active transcript. */
1816
- readonly shown: Readonly<Record<string, string>>;
1817
- readonly model?: ModelRef;
1818
- readonly thinkingLevel: ModelThinkingLevel;
1819
- /** Committed document reads. */
1820
- readonly read: DocumentReader;
1821
- };
1822
-
1823
- type PromptSection<Tool extends ToolRegistration> = {
1824
- readonly key: string;
1825
- render(
1826
- input: PromptInput<Tool>,
1827
- context: Context,
1828
- ): string | undefined | Promise<string | undefined>;
1829
- /** Default true: wrap the text as `<key>\n...\n</key>`. */
1830
- readonly tag?: boolean;
1831
- };
1832
-
1833
- type PromptSectionWrapper<Tool extends ToolRegistration> = (
1834
- section: PromptSection<Tool>,
1835
- ) => PromptSection<Tool>;
1836
-
1837
- /**
1838
- * Stages the documents every new conversation gets, inside the creating commit, after fork copies and before host
1839
- * `init`. Table reads throw; a fork (`conversation.parent`) already holds its copied documents. A throw fails the
1840
- * creation.
1841
- */
1842
- type ConversationSetup = (
1843
- tx: Tx,
1844
- conversation: ConversationRecord,
1845
- registry: RegistrySnapshot<ToolRegistration>,
1846
- ) => void | Promise<void>;
1847
-
1848
- type RegistryFailure = {
1849
- readonly kind: "tool" | "section";
1850
- /** Tool name or section key. */
1851
- readonly name: string;
1852
- readonly error: unknown;
1853
- };
1854
-
1855
- interface RegistryReader<Tool extends ToolRegistration = ToolRegistration> {
1856
- /** Immutable view of the whole current registry. */
1857
- snapshot(): RegistrySnapshot<Tool>;
1858
- /** Called synchronously after every publication; wakes the scheduler to reconsider blocked tasks. */
1859
- subscribe(listener: () => void): () => void;
1860
- }
1861
-
1862
- interface RegistrySnapshot<Tool extends ToolRegistration> {
1863
- /** Composed tools in registry order; a tool whose wrapper failed is absent. */
1864
- tools(): readonly Tool[];
1865
- tool(name: string): Tool | undefined;
1866
- /** Base tool names in registry order, including tools whose wrappers fail. */
1867
- toolNames(): readonly string[];
1868
- task(name: string): AnyTask | undefined;
1869
- /** Hooks registered for tasks with `task`'s name, in registry order. */
1870
- hooks<K extends AnyTask>(task: K): readonly {
1871
- readonly handlers: Partial<HooksOf<K>>;
1872
- readonly scope?: HookScope;
1873
- }[];
1874
- /** Composed sections in registry order; a section whose wrapper failed is absent. */
1875
- sections(): readonly PromptSection<Tool>[];
1876
- /** Wrapper failures of this state; the Harness reports them where it uses them. */
1877
- failures(): readonly RegistryFailure[];
1878
- /** Conversation setups in registry order, the built-in `pi` setup first. */
1879
- conversationSetups(): readonly { readonly key: string; readonly setup: ConversationSetup }[];
1880
- }
1881
-
1882
- interface Registry<Tool extends ToolRegistration = ToolRegistration> extends RegistryReader<Tool> {
1883
- readonly tools: {
1884
- add(tool: Tool): Registration;
1885
- wrap(name: string, key: string, wrapper: ToolWrapper<Tool>): Registration;
1886
- list(): readonly Tool[];
1887
- };
1888
- readonly hooks: {
1889
- add<K extends AnyTask>(
1890
- task: K,
1891
- handlers: Partial<HooksOf<K>>,
1892
- options?: { readonly scope?: HookScope; readonly key?: string },
1893
- ): Registration;
1894
- };
1895
- readonly tasks: {
1896
- add(task: AnyTask): Registration;
1897
- list(): readonly AnyTask[];
1898
- };
1899
- readonly conversations: {
1900
- setup(key: string, setup: ConversationSetup): Registration;
1901
- };
1902
- readonly systemPrompt: {
1903
- section(
1904
- key: string,
1905
- render: PromptSection<Tool>["render"],
1906
- options?: { readonly tag?: boolean },
1907
- ): Registration;
1908
- wrap(key: string, wrapperKey: string, wrapper: PromptSectionWrapper<Tool>): Registration;
1909
- sections(): readonly PromptSection<Tool>[];
1910
- };
1911
- batch(register: () => void): Registration;
1912
- }
1913
-
1914
- function createRegistry<Tool extends ToolRegistration = ToolRegistration>(): Registry<Tool>;
1915
- ```
1916
-
1917
- The `Tool` parameter lets applications attach metadata such as prompt snippets to
1918
- their tools; the Harness only relies on `ToolRegistration`. Pi-ai declarations
1919
- derived from a registered tool keep only pi-ai `Tool` fields (`toToolDeclaration`),
1920
- so application metadata never enters the transcript.
1921
-
1922
- Registration rules:
1923
-
1924
- - `createRegistry()` starts with the built-in task definitions of section 8 and
1925
- the built-in `pi` conversation setup registered first. They have no
1926
- `Registration`, so they cannot be disposed, and the duplicate rule rejects
1927
- another task with a built-in name or another `pi` setup. `tasks.list()`
1928
- includes them. Hooks register against built-in tasks like any other task.
1929
- Setup keys are unique and ordered like section keys.
1930
- - Tool names, section keys, and task names are unique among published
1931
- registrations. Tool wrapper keys are unique per tool name, section wrapper
1932
- keys per section key, and hook keys per task name. Duplicates reject.
1933
- Section keys match `^[a-z][a-z0-9_-]*$`.
1934
- - Keyed slots are ordered by the position at which their key was first
1935
- registered. The registry remembers that position forever, so re-registering an
1936
- existing key, as a reload does, keeps its position; a new key appends. Hooks
1937
- without a key append.
1938
- - Registered objects are immutable and wrappers are pure: a wrapper returns a
1939
- new object and never mutates its input.
1940
- - Every call outside `batch()` publishes immediately. Publication is synchronous,
1941
- invokes no extension callback, and notifies subscribers.
1942
-
1943
- `batch(register)` stages every registration and disposal made while `register`
1944
- runs and publishes once when it returns. It validates only the final staged
1945
- state, so order inside the block does not matter: disposing an old tool and
1946
- adding its replacement is a gapless reload. If `register` throws, returns a
1947
- thenable, or the final state is invalid, nothing is published, staged disposals
1948
- are rolled back, and `batch()` throws. Only registrations made synchronously
1949
- inside `register` belong to the batch; a registration made later by a detached
1950
- continuation is an ordinary immediate registration. Calling `batch()` inside a
1951
- batch is a programming error and throws. The returned `Registration` covers every
1952
- registration added in the batch that was not disposed inside it.
1953
-
1954
- A snapshot is a plain immutable value; nothing is released. The scheduler takes
1955
- one per phase-handler invocation and passes it through the runtime; handlers and
1956
- hooks read that snapshot and never take their own. At every normal phase boundary
1957
- the scheduler takes a fresh one (section 5.4). A tool task keeps the composed tool
1958
- it pinned until execution settles. Different phases may observe different
1959
- registry states; nothing requires one run to see a single registry state across
1960
- its generation, tool, and post-tools tasks. Host operations, such as the create
1961
- conveniences, take one snapshot inside their commit.
1962
-
1963
- ```ts
1964
- // ToolTask is the built-in tool task's token; its hooks are listed in section 7.2.
1965
- const registration = registry.batch(() => {
1966
- registry.tools.add(grep);
1967
- registry.hooks.add(ToolTask, { beforeTool: audit }, { key: "audit" });
1968
- });
1969
- // later, reload: publish the replacement at once
1970
- registry.batch(() => {
1971
- registration.dispose();
1972
- registry.tools.add(grepV2);
1973
- registry.hooks.add(ToolTask, { beforeTool: audit2 }, { key: "audit" });
1974
- });
1975
- ```
1976
-
1977
- The registry does not track which running work still uses a disposed
1978
- registration. Work that already started keeps using the code it took, so an
1979
- extension that frees resources right after `dispose()` can make a still-running
1980
- call fail with an ordinary error result. Extensions that need graceful disposal
1981
- manage their resources' lifetime themselves, for example by reference counting.
1982
-
1983
- ### 7.2 Hooks
1984
-
1985
- A hook is a typed question asked by a task before it commits a decision. Hooks
1986
- are declared by task definition and registered through `registry.hooks.add()`
1987
- Session-wide or, with `scope`, for one conversation and optionally its owned
1988
- subtree. Subtree matching follows conversation ownership, not history parents.
1989
- Registration is typed by the task token, but dispatch matches the task's name,
1990
- so hooks survive a reload of their task; keeping hook signatures compatible
1991
- across task versions is the task author's responsibility. Hooks run in registry
1992
- order off the line; a crash before the consuming commit may rerun them. Abort
1993
- errors always propagate.
1994
-
1995
- | hook | composition | ordinary throw |
1996
- |---|---|---|
1997
- | `beforeRequest` | replacement chain | report, continue |
1998
- | `afterResponse` | all observers | report, continue |
1999
- | `onYield` | first continuation wins | report, continue |
2000
- | `beforeTool` | call replacement chain; first block wins | block tool with error text |
2001
- | `afterTool` | result replacement chain | report, continue |
2002
- | `afterTools` | all observers | report, continue |
2003
- | `beforeCollapse` | first decision wins | report, continue |
2004
-
2005
- Hooks use task memos for durable first-writer-wins decisions. There is no public
2006
- semantic event channel; current UI status is document state.
2007
-
2008
- ### 7.3 Tools
2009
-
2010
- ```ts
2011
- type ToolControl = {
2012
- readonly addTools?: readonly string[];
2013
- readonly terminate?: true;
2014
- readonly handoff?: string;
2015
- };
2016
-
2017
- type ToolExecutionResult = {
2018
- readonly content?: ToolResultMessage["content"];
2019
- readonly isError?: boolean;
2020
- readonly details?: JsonValue;
2021
- readonly control?: ToolControl;
2022
- };
2023
-
2024
- interface ConversationHandle {
2025
- readonly id: ConversationId;
2026
- submit(submission: InputSubmissionDraft, context: Context): Promise<Submission>;
2027
- abort(context: Context): Promise<void>;
2028
- waitForIdle(context: Context): Promise<void>;
2029
- }
2030
-
2031
- interface ToolExecutionApi extends DocumentObserver, DocumentReader {
2032
- readonly taskId: TaskId;
2033
- readonly conversationId: ConversationId;
2034
- readonly callId: string;
2035
- output(chunk: string | Uint8Array): void;
2036
- details(value: JsonValue, context: Context): Promise<void>;
2037
- commit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;
2038
- memo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;
2039
- memo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;
2040
- createTask<I, S extends { phase: string }, R, H extends object>(
2041
- task: Task<I, S, R, H>,
2042
- input: I,
2043
- options: Omit<TaskOptions, "conversationId">,
2044
- context: Context,
2045
- ): Promise<TaskId<R>>;
2046
- getTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined>;
2047
- waitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>>;
2048
- conversation(id: ConversationId, context: Context): Promise<ConversationHandle | undefined>;
2049
- }
2050
-
2051
- type ToolRegistration = Tool & {
2052
- readonly replay?: "safe" | "unsafe";
2053
- readonly outputLimits?: {
2054
- readonly maxBytes?: number;
2055
- readonly maxLines?: number;
2056
- readonly retain?: "head" | "tail";
2057
- };
2058
- execute(
2059
- args: JsonValue,
2060
- api: ToolExecutionApi,
2061
- context: Context,
2062
- ): Promise<ToolExecutionResult>;
2063
- };
2064
- ```
2065
-
2066
- Omitted `replay` is `unsafe`. Omitted `outputLimits` are 50 KiB, 2,000 lines,
2067
- and `retain: "head"`.
2068
-
2069
- A running tool reports two things to the UI, mirroring the two halves of its
2070
- final result:
2071
-
2072
- - `output(chunk)` appends running text output, like stdout. If `execute()` omits
2073
- `content`, the final retained output becomes one text content item; no output
2074
- becomes an empty content list.
2075
- - `details(value)` replaces the running details with a complete JSON value; it
2076
- does not merge keys. If `execute()` omits `details`, the last value becomes the
2077
- final `details`, so a renderer handles one details shape from the first
2078
- update through the final result.
2079
-
2080
- Neither is sent to the model while the tool runs. `output()` synchronously
2081
- accepts UTF-8 output into that invocation-owned bounded buffer and throws after
2082
- invocation end. Throttled commits publish the retained output, dropped
2083
- byte/line counts, and the current details in the tool presentation document. Explicit
2084
- text in explicit result content is bounded by the same limits before transcript
2085
- persistence; non-text content is retained as declared by its pi-ai type.
2086
-
2087
- `output()` never spills complete output to a file because spilling requires a
2088
- filesystem, which may be remote or unavailable. A tool that must preserve
2089
- complete output spills through the `ExecutionEnv` or `FileSystem` it was given,
2090
- such as shell execution with spill capture, and reports the resulting path in its
2091
- details.
2092
-
2093
- The `details()` promise resolves after the corresponding or coalesced document
2094
- commit. During normal settlement, accepted output updates drain before
2095
- the tool-result entry and terminal task record commit. Abort and close obey
2096
- invocation and Session admission gates: uncommitted buffered updates may be
2097
- discarded, while admitted commits settle. Cancellation, callback, tracker
2098
- preparation, and checkpoint failures occur before Storage admission and do not
2099
- poison the Session. An uncertain Storage failure follows the fatal Session rule.
2100
-
2101
- Tools are registry entries (section 7.1) with name, description, JSON schema,
2102
- replay policy, and execute function. `registry.tools.wrap(name, key, wrapper)`
2103
- decorates a tool without replacing it. Each snapshot composes the current base
2104
- tool with its wrappers in registry order; a wrapper never captures a base, so
2105
- reloading the base keeps its wrappers. A wrapper that throws or returns a tool
2106
- with a different name makes that tool absent from the snapshot (fail closed:
2107
- not offered, and calls produce `tool_unavailable`) and is reported. A wrapper
2108
- without a base contributes nothing. The composite supplies the declaration,
2109
- argument validation, replay policy, and execution.
2110
-
2111
- A tool call is accepted only if it was offered in the request's effective
2112
- system/tool history. A call to a tool that is not offered or has no registered
2113
- implementation produces the `tool_unavailable` error result described in section
2114
- 2.2 instead of failing the run. The tool task resolves the composed tool once
2115
- from its snapshot before argument validation and pins it until execution
2116
- settles, even across later snapshot refreshes. Arguments must satisfy both the offered
2117
- declaration and the pinned implementation's schema; they are validated before
2118
- and after `beforeTool` hooks.
2119
-
2120
- After hooks and validation, the tool task durably records the final call and
2121
- resolved replay policy before execution. Recovery does not rerun `beforeTool`
2122
- and passes the same stored arguments to `execute()`. A replay-safe tool may
2123
- reconstruct a submission from those arguments when that transformation is pure.
2124
- Random values, timestamps, mutable document/configuration reads, or other derived
2125
- inputs that must remain stable are first captured in a durable memo, checkpoint,
2126
- or task input. A background supervisor receives the final submission draft in
2127
- its own durable input so it can finish independently. Recovery does not let a
2128
- changed registry declaration alter the stored replay policy.
2129
-
2130
- A tool-acquired conversation handle accepts only input submissions; tools use
2131
- ordinary transaction writes for passive entries.
2132
-
2133
- A tool executes in a durable task. It may:
2134
-
2135
- - publish bounded running output and details to its presentation document;
2136
- - commit memos;
2137
- - create and wait for tasks;
2138
- - atomically create or fork explicitly owned conversations through `commit()`;
2139
- - observe documents for which it has a token/reference;
2140
- - mutate authorized documents through `commit()`;
2141
- - return bounded model content and separate diagnostic details.
2142
-
2143
- Tool operations use the invoking task's admission and invocation-lifetime gates.
2144
- Task creation defaults to that task's conversation. Trusted document and
2145
- conversation access follows sections 3.3 and 9.2; there is no additional subtree
2146
- authorization layer. Possession of a Session-global typed ID is sufficient in
2147
- trusted code.
2148
-
2149
- Tools have no conversation-creation convenience method. They create or fork a
2150
- conversation inside `commit()`, state its ownership explicitly, atomically stage
2151
- any related document/task writes, and receive only the inert record. After that
2152
- commit settles, `conversation(id)` acquires an invocation-bound operational
2153
- handle for submission, explicit abort, and idle waits without changing
2154
- ownership. A commit callback must not call `conversation()` or use a previously
2155
- acquired handle: nested Session operations and external effects are forbidden
2156
- while the mutation line is held. A handle's operations reject after the
2157
- invocation ends. A `Submission` returned by its `submit()` is invocation-bound in
2158
- the same way; the admitted submission remains durable after those methods reject.
2159
- Invocation-owned document watches stop when the invocation ends.
2160
-
2161
- A foreground subagent conversation is explicitly owned by its tool task. One
2162
- transaction creates or forks the child and records its durable registry mapping;
2163
- after settlement the tool reacquires the child, submits with the registered
2164
- request ID, and waits for that submission's result. Aborting or abnormally
2165
- terminalizing the tool task cascades through the owned scope.
2166
-
2167
- A background subagent is provisioned in one transaction. After deduplicating by
2168
- its durable registry key, the tool stages a background supervisor task `B`, a
2169
- child conversation `C` explicitly owned by `B`, and the registry mapping from the
2170
- semantic name to `C` plus its stable request ID. `B` may be staged earlier in the
2171
- same transaction and used immediately as `C`'s owner. Its durable input contains
2172
- the exact submission draft and the registry location/key; it need not contain
2173
- `C`'s not-yet-created ID. Once scheduled, `B` resolves `C` from the mapping,
2174
- verifies the immutable owner edge, and performs normal `Conversation.submit()`.
2175
- A crash before admission makes `B` retry; a crash after admission returns the
2176
- existing request-ID-deduplicated `Submission`. The initiating tool may race the
2177
- same submit for lower latency and wait only for the durable admission receipt.
2178
- The supervisor may complete after setup: its terminal record retains
2179
- `background`, so ancestor ordinary abort and idle traversal continue to stop at
2180
- its owned scope.
2181
-
2182
- Applications may maintain a conversation document mapping semantic subagent
2183
- names to durable conversation IDs and application-minted submission request IDs.
2184
- Such a live registry uses `fork: "initial"` so children do not inherit the
2185
- parent's agent list and its update is not a selected fork source. Conversation
2186
- creation/forking, supervisor creation when applicable, and the registry mapping
2187
- commit atomically. The supervisor input, tool's durable final arguments, or a
2188
- durable checkpoint must retain enough information to reconstruct the exact
2189
- submission draft; the registry itself need not duplicate that payload. Initial
2190
- or later input then uses the registered stable request ID with the full
2191
- `Conversation.submit()` state machine. A crash before admission leaves a durable
2192
- request to submit; a crash after admission retries the same request and receives
2193
- the existing `Submission`. A read-only lookup by conversation/request ID can
2194
- report absence or return the durable queued/placed/done/unanswered receipt.
2195
- Submission admission therefore needs no private transaction shortcut and does
2196
- not move onto `Tx`. Kernel ownership indexes independently drive abort and idle
2197
- traversal.
2198
-
2199
- A tool result may request `addTools`, `terminate`, or `handoff`. Post-tools
2200
- applies added tool names to configured loadout, uses a final boundary for
2201
- terminate/handoff, and writes a headed handoff entry when requested.
2202
-
2203
- On reopen, a tool reruns only when both its stored intent policy and the current
2204
- registered declaration say `safe`. A current `unsafe` declaration may veto a
2205
- stored-safe replay; a current-safe declaration never upgrades stored unsafe. A
2206
- tool with no current registration is treated as `unsafe`. Every other orphaned
2207
- effect produces an interrupted result containing the
2208
- durable partial output. Completed, failed, and aborted
2209
- tool terminal outcomes retain their tool-result entry ID for post-tools.
2210
-
2211
- ### 7.4 System prompt and dynamic tools
2212
-
2213
- Pico has no durable prompt sections. The registry's system prompt slot produces
2214
- the desired sections for each request; the transcript's `pi.system` entries are
2215
- the only durable record of what the model saw. Pico stores prompt and tool
2216
- changes directly as PR #9548 `SystemMessage` values at their transcript
2217
- positions, always with empty `content`:
2218
-
2219
- ```ts
2220
- type SystemEntry = EntryRecord & {
2221
- readonly kind: "pi.system";
2222
- readonly model: readonly [SystemMessage];
2223
- };
2224
-
2225
- const baseline: SystemMessage = {
2226
- role: "system",
2227
- content: "",
2228
- sections: { preamble: renderedPreamble, cwd: renderedCwd },
2229
- toolsAdded: allEffectiveTools,
2230
- timestamp: now,
2231
- };
2232
-
2233
- const delta: SystemMessage = {
2234
- role: "system",
2235
- content: "",
2236
- sections: { cwd: nextRenderedCwd, legacy: null },
2237
- toolsRemoved: [{ name: "read" }],
2238
- toolsAdded: [nextRead],
2239
- timestamp: now,
2240
- };
2241
- ```
2242
-
2243
- Generation preparation takes these steps against its phase snapshot:
2244
-
2245
- 1. Read the committed configuration and replay the active transcript's system
2246
- messages into the shown sections and offered tools.
2247
- 2. Compute the desired tools: active names that the snapshot resolves, in
2248
- configured order, as composed by their wrappers.
2249
- 3. Render every registered section, in registry order, with `PromptInput`: the
2250
- conversation, those tools, the shown sections, the configured model and
2251
- thinking level, and a `DocumentReader` for committed documents (the task
2252
- runtime). The results are the desired sections.
2253
- 4. Compare desired sections and tool declarations with the replayed state and
2254
- append one positional `pi.system` entry when they differ.
2255
-
2256
- Preparation does not recheck the transcript before appending: only the Harness
2257
- writes to a busy conversation, through submissions, run tasks, and boundaries,
2258
- so the transcript it read is still current (section 12).
2259
-
2260
- Model and thinking level are request options, not prompt state.
2261
-
2262
- Registered sections are the only source of prompt text; there is no separate
2263
- builder. `systemPrompt.section(key, render, { tag })` adds a section, and
2264
- `systemPrompt.wrap(key, wrapperKey, wrapper)` decorates one, composed per
2265
- snapshot like tool wrappers. Sections render in registry order: the position at
2266
- which each key was first registered. A section whose `render` returns
2267
- `undefined` is omitted, which is how a section varies by conversation. With
2268
- `tag` omitted or true, text is wrapped as `<key>\n...\n</key>`. A section that
2269
- throws keeps its shown text, if any, and is reported; the request is still sent.
2270
- Errors thrown after the generation invocation is cancelled propagate; an abort
2271
- error of the section's own, such as its fetch timing out, is an ordinary failure. With no registered sections, the desired section set is
2272
- empty.
2273
-
2274
- A minimal prompt is one untagged section:
2275
-
2276
- ```ts
2277
- registry.systemPrompt.section("preamble", () => "You are a helpful assistant.", { tag: false });
2278
- ```
2279
-
2280
- Sections read per-conversation data through `input.read`. For example, a
2281
- coding agent keeps its own conversation document with the agent kind, preamble,
2282
- and working directory; its preamble and cwd sections render from that document,
2283
- and its AGENTS.md and skills sections return `undefined` for subagent
2284
- conversations.
2285
- Renderers must be deterministic for equal inputs: any change in rendered text,
2286
- such as an embedded timestamp, appends a system delta and invalidates provider
2287
- prompt caches.
2288
-
2289
- Replay applies messages in transcript order. Non-empty `content` appends
2290
- instructions. A section string adds or replaces that name without moving an
2291
- existing section; `null` removes it, and a later re-addition appends it to the
2292
- ordered section map. Within one message, tool removals happen before additions,
2293
- so a same-name replacement gets the new declaration and position.
2294
-
2295
- Preparation compares both values and order. If values can be patched without
2296
- changing order, it emits the minimal patch. If shown and desired section order
2297
- differ, one commit appends two `pi.system` entries: the first removes every
2298
- shown section with `null`, and the second re-adds every desired section in
2299
- desired order. This makes order-only changes and deletion/re-addition between
2300
- requests replay exactly; merely restating equal values is insufficient.
2301
-
2302
- A PR #9548 `SystemMessage` is always a patch, not a reset: it cannot remove
2303
- previous `content` or restore section order merely by restating current values.
2304
- Therefore, when a head removes the previous request-visible baseline, which is
2305
- the case when the active context has a head marker and no `pi.system` entry
2306
- follows that marker, the new
2307
- `pi.system` entry adds `ContextEdit` omissions for every earlier `pi.system`
2308
- entry still retained after the cut. Its own message is then a complete baseline
2309
- containing every desired section in order and every effective tool declaration.
2310
- Model-context replay sees the new baseline instead of the omitted retained
2311
- deltas. Preparation writes this baseline even when it restates the replayed
2312
- values, so every later preparation finds a `pi.system` entry after the marker.
2313
- Head rebaselining takes precedence over ordinary order/value patching.
2314
- Without a head cut, an order mismatch uses the two-entry remove/re-add sequence
2315
- above; only when order already matches does preparation emit the minimal changed
2316
- values, `null` removals, and tool additions/removals. A changed tool declaration
2317
- is removed and re-added in the same message. When the offered tool order differs
2318
- from the desired order, the message removes every offered tool and re-adds the
2319
- desired tools in order.
2320
-
2321
- The rendered strings stored in historical `SystemMessage.sections` remain
2322
- authoritative even if the current renderer changes. Pi-ai decides whether to
2323
- send the messages positionally to a capable provider or fold them into one
2324
- leading system message; Pico does not rewrite its stored transcript for provider
2325
- compatibility.
2326
-
2327
- ### 7.5 Extension reload
2328
-
2329
- Extension code is reloaded in process through the registry. The host publishes
2330
- the new registrations and disposes the old ones in one `batch()`. The Harness
2331
- keeps running; no close or reopen is required.
2332
-
2333
- - New phase invocations and tool tasks use the new registrations immediately;
2334
- running invocations see them at their next phase boundary.
2335
- - Work already running keeps its snapshot until its phase handler settles, and a
2336
- pinned tool keeps its implementation until its execution settles. Replacement
2337
- never signals or interrupts it. Resources the old code uses are the
2338
- extension's responsibility (section 7.1).
2339
- - A task definition replaced by name hands over at its next normal phase boundary
2340
- (section 5.4). A task definition must increase its version when the meaning
2341
- of persisted input or checkpoint state changes and migrate supported older
2342
- state; a failed migration blocks the task rather than terminalizing it.
2343
- - Keyed registrations re-registered under the same key keep their position, so a
2344
- reload does not reorder hooks, tools, or sections.
2345
- - Document definitions are passed explicitly to typed access and need no
2346
- registration; changed tokens take effect on their next access.
2347
-
2348
- If old extension code ignores cancellation and never settles, new work already
2349
- uses the replacement. Harness close still joins every invocation. Safe forced termination of arbitrary
2350
- non-cooperative JavaScript requires worker/process isolation; that host
2351
- terminates the process and reopens the Session from durable state. Old and new
2352
- Harness instances must never own the same Session concurrently.
2353
-
2354
- ## 8. Built-in tasks
2355
-
2356
- The initial implementation provides:
2357
-
2358
- | kind | responsibility |
2359
- |---|---|
2360
- | `pi.generation` | prepare system/loadout, request or poll model, retry, classify response |
2361
- | `pi.tool` | validate, hook, execute, persist output and details, append result |
2362
- | `pi.post-tools` | wait for tools, apply controls, run boundary, continue generation |
2363
- | `pi.collapse` | select a transcript range, summarize, append a headed summary |
2364
-
2365
- Generation uses `HarnessOptions.models` without a Pico-specific model adapter. It
2366
- resolves `models.getModel(ref.provider, ref.modelId)`, builds a pi-ai `Context`
2367
- from the prepared prompt/messages/tools, and calls `models.streamSimple()` with
2368
- the task invocation's abort signal and configured reasoning/options. Deferred
2369
- continuation calls `models.fetchDeferred()` and `models.cancelDeferred()` with
2370
- that same model and signal. Missing models and synchronous/streamed pi-ai errors
2371
- are classified into the durable generation outcomes below.
2372
-
2373
- Generation and tool progress are throttled durable document commits. A crash may
2374
- lose only the uncommitted throttle window. Recovery converts committed partials
2375
- to normal interrupted/aborted transcript entries, clears presentation state,
2376
- and then retries or terminates according to the task phase. Retry deadlines,
2377
- attempts, compaction, and tool progress are current document state for late
2378
- joiners; completed-attempt usage/accounting is an entry or terminal detail.
2379
- Bounded output records whether content was truncated and any retained file path.
2380
-
2381
- Compaction changes model context by appending a summary entry with a head. It
2382
- does not delete transcript history.
2383
-
2384
- ### 8.1 Built-in entries
2385
-
2386
- Built-in entry kinds carry no `data`; each is exported as an `Entry` token.
2387
-
2388
- | kind | `model` | written by |
2389
- |---|---|---|
2390
- | `pi.user` | `[UserMessage]`, timestamp from the Harness clock at admission or placement | submissions |
2391
- | `pi.assistant` | `[AssistantMessage]` with any stop reason | generation |
2392
- | `pi.system` | `[SystemMessage]` with `content: ""` (section 7.4) | generation preparation |
2393
- | `pi.tool-result` | `[ToolResultMessage]` | tool tasks |
2394
-
2395
- Every provider result becomes a `pi.assistant` entry: answers, failed attempts
2396
- with their error text and usage, and converted partials with stop reason
2397
- `aborted`. Context derivation (section 2.1, rule 9) keeps failed and aborted
2398
- messages out of later requests, so no separate usage or notice kind exists.
2399
-
2400
- ### 8.2 Live document
2401
-
2402
- ```ts
2403
- type LiveState = {
2404
- /** Run control (section 6); present exactly while the conversation is busy. */
2405
- run?: { taskId: TaskId; inputs: SubmissionId[] };
2406
- /** Presentation of the current generation attempt. */
2407
- generation?: {
2408
- attempt: number;
2409
- /** Committed throttled partial of the in-flight response. */
2410
- message?: JsonRepresentation<AssistantMessage>;
2411
- /** Durable backoff before the next attempt. */
2412
- retry?: { at: number; error: string };
2413
- /** Provider-side deferred response being polled. */
2414
- deferred?: { pollAt: number };
2415
- };
2416
- };
2417
- ```
2418
-
2419
- | field | value |
2420
- |---|---|
2421
- | kind | `pi.live` |
2422
- | version | `1` |
2423
- | scope/history/fork | conversation, `latest`, `initial` |
2424
- | `initial()` | `{}` |
2425
- | checkpoint | complete base whenever `generation` is absent |
2426
- | view mount | `docs["pi.live"]` |
2427
- | created | with every Harness conversation (section 2.2) |
2428
-
2429
- Nothing is in flight at every turn boundary and while idle, so the stored delta
2430
- chain spans at most one generation, including its retries and deferred polls, or
2431
- one tool round, and each base is small. Tool progress adds its own condition with the tool task.
2432
-
2433
- Tool progress and compaction status join this document with the tool and
2434
- collapse tasks. Partials are normalized to strict JSON before assignment. Every
2435
- terminal path of a run task removes `run` and `generation` in the commit that
2436
- settles the run's inputs. `tx.settleSubmission()` stages each input's new status
2437
- and resolves the transaction's latest candidate submission record, falling back
2438
- to committed state, during assembly, like task-document validation (section 3.3),
2439
- so it is not a caller table read and works after the commit's first table write.
2440
-
2441
- ### 8.3 Generation
2442
-
2443
- ```ts
2444
- type GenerationInput = {};
2445
- type GenerationCheckpoint =
2446
- | { phase: "prepare"; attempt: number }
2447
- | {
2448
- phase: "request";
2449
- attempt: number;
2450
- model: ModelRef;
2451
- thinkingLevel: ModelThinkingLevel;
2452
- streamOptions: ConversationStreamOptions;
2453
- /** Newest entry included in the request. */
2454
- cutoff: EntryId;
2455
- }
2456
- | { phase: "retry"; attempt: number; until: number }
2457
- | { phase: "poll"; attempt: number; model: ModelRef; handle: DeferredHandle; pollAt: number };
2458
- type GenerationResult = { entryId: EntryId };
2459
- ```
2460
-
2461
- `pi.generation` is version 1 and starts at `{ phase: "prepare", attempt: 1 }`.
2462
- The run's inputs live in `pi.live.run`, not in the task input.
2463
-
2464
- - `prepare` runs section 7.4 against the committed configuration. When no model
2465
- is configured or `models.getModel()` does not know it, the task fails with
2466
- `no_model`. Otherwise one commit appends the planned `pi.system` entries and
2467
- moves to `request` with the new tail as `cutoff` and the configuration's model,
2468
- thinking level, and stream options.
2469
- - `request` and `poll` resolve the checkpoint's model through
2470
- `models.getModel()`; an unknown model fails the task with `no_model`, like
2471
- `prepare`. `request` converts a leftover partial (below) before it resolves
2472
- the model.
2473
- - `request` first converts a committed partial left in `pi.live` by an
2474
- interrupted attempt into an aborted `pi.assistant` entry. It then streams the
2475
- model context through `cutoff` with the invocation signal, the thinking level
2476
- as `reasoning` (omitted for `off`), and the pinned `streamOptions`,
2477
- committing throttled partials. Recovery resends the same messages with the
2478
- same pinned model, thinking level, and stream options.
2479
- - Before classifying, the handler stops the partial throttle and awaits any
2480
- partial commit in flight, so no stale partial lands after the outcome. The
2481
- terminal message is classified in one commit that also clears the partial:
2482
- - `stop`/`length`: append the answer, settle the run's inputs `done`, remove
2483
- `run` and `generation`, and complete with `{ entryId }`. The same commit
2484
- applies the final boundary (section 6).
2485
- - `toolUse`: append the assistant entry and continue through the tool chain.
2486
- - `error` that `isRetryableAssistantError()` accepts while the conversation's
2487
- retry policy allows another attempt (`enabled` and `attempt <= maxRetries`,
2488
- so `maxRetries` counts retries after the first attempt): append the error entry and move to
2489
- `retry` with `until = now + retryDelayMs(policy, attempt)`.
2490
- - any other `error`, or `aborted` without an abort mark: append the error
2491
- entry, settle the inputs `unanswered` with `model_error`, remove `run` and
2492
- `generation`, and fail.
2493
- - `deferred`: move to `poll` with `pollAt = now + (handle.pollAfterMs ?? 5000)`.
2494
- - `retry` sleeps until `until`, then returns to `prepare` with the next attempt,
2495
- so configuration changes made during the backoff apply.
2496
- - `poll` sleeps until `pollAt` and calls `models.fetchDeferred()`. A still
2497
- deferred result moves `pollAt` strictly later; any other result is classified
2498
- as above.
2499
- - The abort handler calls `models.cancelDeferred()` in `poll` when the model is
2500
- known (a failure is reported), converts a committed partial, settles the inputs `unanswered` with
2501
- `aborted`, removes `run` and `generation`, and ends `aborted`.
2502
-
2503
- Input submissions settle `unanswered` with one of these reasons: `no_model`,
2504
- `model_error` (detail: provider error text), `aborted`, `faulted` (detail: error
2505
- message), or an orphaning blocked reason (section 5.4). Fault and orphan
2506
- settlement discard a committed partial without writing a transcript entry.
2507
-
2508
-
2509
- ## 9. Document observation and Chord
2510
-
2511
- ### 9.1 Document state
2512
-
2513
- Chord's existing replicated-state layer exposes this source-adoption contract:
2514
-
2515
- ```ts
2516
- interface ReplicatedStateSourceFrame<T> {
2517
- readonly cursor: number;
2518
- readonly value: T;
2519
- readonly ops: readonly Op[];
2520
- readonly context: Context;
2521
- }
2522
-
2523
- interface ReplicatedStateSourceAttachment<T> {
2524
- /** Fixed immutable snapshot captured at the atomic attachment boundary. */
2525
- readonly snapshot: { readonly value: T; readonly cursor: number };
2526
- /** Install the sole listener and synchronously drain every buffered frame. */
2527
- activate(listener: (frame: ReplicatedStateSourceFrame<T>) => void): void;
2528
- dispose(): void;
2529
- }
2530
-
2531
- interface ReplicatedStateSource<T> {
2532
- /** Atomically capture a snapshot and begin buffering every later commit. */
2533
- attach(): ReplicatedStateSourceAttachment<T>;
2534
- }
2535
-
2536
- interface ReplicatedStateSourceOptions {
2537
- readonly onError?: (error: Error) => void;
2538
- }
2539
-
2540
- interface AttachedReplicatedState<T> extends ReplicatedState<T> {
2541
- readonly value: T;
2542
- dispose(): void;
2543
- }
2544
-
2545
- function replicatedState<T>(
2546
- source: ReplicatedStateSource<T>,
2547
- options?: ReplicatedStateSourceOptions,
2548
- ): AttachedReplicatedState<T>;
2549
-
2550
- type DocumentState<T extends JsonObject> =
2551
- AttachedReplicatedState<Readonly<T> | null>;
2552
-
2553
- type WatchEnd =
2554
- | { readonly reason: "stopped" | "cancelled" | "session_closed" | "retired" }
2555
- | { readonly reason: "listener_error"; readonly error: Error };
2556
-
2557
- interface WatchHandle<T> {
2558
- /** Acquisition revision before start; latest delivered immutable revision afterward. */
2559
- readonly value: T;
2560
- /** Installs the sole serialized asynchronous listener. */
2561
- start(listener: (value: T, ops: readonly Op[], context: Context) => Promise<void>): void;
2562
- /** Idempotently stops future callbacks and returns this watch's terminal result. */
2563
- stop(): Promise<WatchEnd>;
2564
- /** Settles when the watch terminates; an already-running callback remains caller-owned. */
2565
- readonly closed: Promise<WatchEnd>;
2566
- }
2567
-
2568
- type DocumentWatch<T extends JsonObject> = WatchHandle<Readonly<T> | null>;
2569
-
2570
- interface DocumentObserver {
2571
- watchDoc<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<DocumentWatch<T> | undefined>;
2572
- watchDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId, context: Context): Promise<DocumentWatch<T> | undefined>;
2573
- watchDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId, context: Context): Promise<DocumentWatch<T> | undefined>;
2574
- watchDoc<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string, context: Context): Promise<DocumentWatch<T> | undefined>;
2575
- watchDoc<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, context: Context): Promise<DocumentWatch<T> | undefined>;
2576
- watchDoc<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, context: Context): Promise<DocumentWatch<T> | undefined>;
2577
- }
2578
- ```
2579
-
2580
- `documentState()` attaches Pico's committed document stream to Chord before
2581
- returning. The returned state is already hydrated with the exact shareable
2582
- immutable revision, has no mutation methods, and publishes every later exact
2583
- committed revision and operation batch without another tracker, value copy, or
2584
- re-diff. Disposing it unregisters only that observation; Pico remains the sole
2585
- document mutator.
2586
-
2587
- State and watch acquisition never create; absent lookup returns `undefined`.
2588
- Successful acquisition binds one concrete incarnation. Retirement publishes a
2589
- JSON `null` root replacement and ends that incarnation's stream. If the state
2590
- remains exposed, consumers see `null`, never stale state. A later recreation
2591
- requires acquiring a new state or watch.
2592
-
2593
- Each document state assigns its own in-memory contiguous Chord delivery sequence.
2594
- Pico does not persist or expose that sequence through `WatchHandle`. States and watches retain immutable revisions independently of the loaded tracker
2595
- cache. Reopen creates a new state lifetime and hydration.
2596
-
2597
- Internally, state attachment uses Chord's synchronous atomic snapshot-and-register
2598
- boundary: the snapshot includes every commit before attachment, and every later
2599
- exact frame is buffered until activation. This prevents a snapshot from being
2600
- paired with operations based on a newer unseen revision.
2601
-
2602
- ### 9.2 `watchDoc`
2603
-
2604
- Tasks, hooks, and tools may observe any existing document for which their code
2605
- has a token and owner/key. There is no additional subtree permission system inside trusted
2606
- Session code.
2607
-
2608
- On the Session line, `watchDoc()` resolves one existing concrete incarnation,
2609
- captures its current immutable tracker revision in O(1), and registers for every
2610
- later exact committed revision and operation batch. It returns `undefined` when
2611
- absent. Before `start()`, `watch.value` remains the acquisition revision while
2612
- later frames buffer.
2613
-
2614
- ```ts
2615
- const watch = await api.watchDoc(JobOutputDoc, producerTaskId, context);
2616
- if (watch === undefined) return;
2617
- try {
2618
- await initializeConsumer(watch.value, context);
2619
- watch.start(async (value, ops, deliveryContext) => {
2620
- await consume(value, ops, deliveryContext);
2621
- });
2622
- } catch (error) {
2623
- await watch.stop();
2624
- throw error;
2625
- }
2626
- ```
2627
-
2628
- `start()` installs the sole listener and schedules delivery; it never invokes
2629
- user code inline. Each callback receives the exact immutable committed value and
2630
- the exact operation batch that produced it. Immediately before invocation,
2631
- `watch.value` advances to that value. The watch awaits the listener before
2632
- starting its next callback, but Session commits never wait for callback
2633
- settlement.
2634
-
2635
- A watch retains at most 100 pending committed frames, excluding the frame already
2636
- being delivered. Adding frame 101 replaces the complete undelivered suffix with
2637
- one self-contained root replacement `[["r", newestValue]]`, using the newest
2638
- exact immutable revision and that commit's Context. Later exact frames follow
2639
- that replacement normally. Another overflow replaces the pending suffix again.
2640
- No serialized-byte measurement, value copy, operation replay, or re-diff occurs.
2641
- This is convergent observation, not an audit stream; consumers requiring every
2642
- transition must persist those facts separately.
2643
-
2644
- `watch.value` and every previously returned revision remain stable forever under
2645
- the trusted immutability contract. Consumers must not mutate them or retained
2646
- descendants. The selected commit Context's values are preserved without inheriting the
2647
- producer's cancellation. A callback owns its own asynchronous work.
2648
-
2649
- A watch remains bound to its original incarnation. Retirement queues the exact
2650
- terminal `[["r", null]]` frame, or folds it into an overflow replacement with
2651
- value `null`. After that callback settles, the watch closes as `retired` and never
2652
- follows a replacement incarnation.
2653
-
2654
- `stop()` is idempotent. It synchronously unregisters, discards pending frames,
2655
- prevents another callback from starting, and returns the common terminal promise.
2656
- An already-running callback is not aborted or joined and remains caller-owned.
2657
- The acquisition `Context` governs watch lifetime. Cancellation during acquisition
2658
- cleans up before rejecting; later cancellation and Session close stop future
2659
- delivery similarly. Listener failure discards pending work and closes only that
2660
- watch as `listener_error`. The first termination reason wins, and every late
2661
- rejection is observed.
2662
-
2663
- ### 9.3 Conversation view
2664
-
2665
- The public view is a fixed structural mount of selected built-in documents:
2666
-
2667
- ```ts
2668
- type ConversationView = {
2669
- readonly conversation: ConversationRecord;
2670
- readonly entries: readonly EntryRecord[];
2671
- readonly docs: Readonly<Record<string, JsonObject>>;
2672
- };
2673
- ```
2674
-
2675
- The concrete built-in document IDs and fields are public protocol once their
2676
- implementation layer is approved. Third-party documents are initially exposed
2677
- through their own Chord services, not automatically mounted.
2678
-
2679
- The mount consumes one complete Session commit and publishes one Chord batch:
2680
-
2681
- ```text
2682
- document op ["s", ["generation", "message"], value]
2683
- -> view op ["s", ["docs", "pi.live", "generation", "message"], value]
2684
- ```
2685
-
2686
- Entry appends/head changes and every changed mounted document are included in
2687
- the same publication. Before Storage admission, the Session derives the mounted
2688
- operation batch and prepares each affected loaded mount's next immutable revision
2689
- with the optimized immutable applier. Failure rolls back normally. After Storage
2690
- success, finalization only installs the prepared mount pointers/cursors and
2691
- enqueues publication. Mounted document revisions may be structurally shared
2692
- because they obey the same trusted immutability contract. The mount performs no
2693
- semantic projection and owns no second persistence authority. A Chord adapter
2694
- assigns a contiguous in-memory delivery sequence per view source lifetime.
2695
-
2696
- `Conversation.viewState()` exposes the mount directly as a disposable read-only
2697
- Chord state for facets and UI services. `Conversation.watch()` exposes the same
2698
- mount through Package 12's serialized exact-frame watch with bounded pending
2699
- frames and full-value overflow replacements. An empty mounted operation batch
2700
- creates no revision; a redundant nonempty batch remains a real publication.
2701
- Neither API adds another tracker, persistence authority, or semantic event
2702
- envelope.
2703
-
2704
- ### 9.4 Agent-mode notifications
2705
-
2706
- The Session kernel and Chord structural sources do not maintain a semantic event
2707
- journal. Coding-agent JSON/RPC compatibility uses a thin agent-mode adapter
2708
- derived from each uncoalesced committed publication before any per-watch
2709
- overflow replacement. It owns no tracker or persistence and emits notifications only after
2710
- the commit that makes them true.
2711
-
2712
- The adapter protocol covers run start/settlement, committed assistant progress,
2713
- message entry settlement, tool intent/progress/result, submission queue/outcome,
2714
- retry/deferred/compaction state, configuration changes, and faults. One commit
2715
- may produce an ordered batch. Progress notifications represent Pico's throttled
2716
- durable partials, not every raw provider frame. The exact legacy `AgentEvent`
2717
- wire format is not preserved.
2718
-
2719
- Notifications have no hydration or replay contract. A consumer requiring a
2720
- complete lifecycle subscribes before admitting the submission; a late or reconnecting
2721
- consumer hydrates structural state and history instead. Product adapters apply
2722
- these rules:
2723
-
2724
- - TUI hydrates and renders `ConversationView`, then applies structural updates;
2725
- notifications may drive transient animation but are not its authority.
2726
- - Print awaits its input `Submission` and prints that submission's answer.
2727
- - JSON/RPC expose correlated commands plus the ordered agent notification
2728
- protocol, with transport backpressure and disconnect policy owned by that
2729
- adapter.
2730
-
2731
- This adapter is allowed even though a public Session-kernel semantic stream is a
2732
- non-goal. It must not derive notifications from a lossy, overflow-reset watch
2733
- when complete subscribed lifecycle delivery is promised.
2734
-
2735
- ## 10. Storage contract
2736
-
2737
- Ordered scans are cursor-based. Exact identity lookups are keyed.
2738
-
2739
- ```ts
2740
- type Page<T, C> = {
2741
- readonly items: readonly T[];
2742
- readonly next?: C;
2743
- };
2744
-
2745
- type Cursor = Readonly<Record<string, JsonValue>>;
2746
-
2747
- type ConversationQuery = {
2748
- readonly ownerConversationId?: ConversationId;
2749
- readonly ownerTaskId?: TaskId;
2750
- };
2751
-
2752
- type EntryQuery = {
2753
- readonly conversationId: ConversationId;
2754
- readonly minEntryId?: EntryId; // inclusive
2755
- readonly maxEntryId?: EntryId; // inclusive
2756
- };
2757
-
2758
- type TaskQuery = {
2759
- readonly conversationId?: ConversationId;
2760
- readonly kind?: string;
2761
- readonly status?: "pending" | "running" | "terminal";
2762
- readonly abortRequested?: boolean;
2763
- readonly background?: boolean;
2764
- };
2765
-
2766
- type SubmissionQuery = {
2767
- readonly conversationId?: ConversationId;
2768
- readonly status?: SubmissionRecord["status"];
2769
- };
2770
-
2771
- type DocumentPoint = Seq | "current";
2772
-
2773
- type DocumentAddress = {
2774
- readonly kind: string;
2775
- readonly scope: DocumentRecord["scope"];
2776
- readonly key?: string;
2777
- };
2778
-
2779
- type DocumentQuery = {
2780
- readonly scope: DocumentRecord["scope"];
2781
- readonly at: DocumentPoint;
2782
- readonly kind?: string;
2783
- };
2784
-
2785
- type DocumentContent =
2786
- | { readonly version: number; readonly kind: "base"; readonly value: JsonObject }
2787
- | { readonly version: number; readonly kind: "delta"; readonly ops: readonly Op[] };
2788
-
2789
- type StoredDocument = {
2790
- readonly record: DocumentRecord;
2791
- readonly version: number;
2792
- readonly value: JsonObject;
2793
- /** Deltas replayed after the selected base to materialize `value`. */
2794
- readonly deltasSinceBase: number;
2795
- };
2796
-
2797
- type StorageWrite =
2798
- | { readonly type: "conversation"; readonly value: ConversationRecord }
2799
- | { readonly type: "entry"; readonly value: EntryRecord }
2800
- | { readonly type: "task"; readonly value: TaskRecord<JsonValue, JsonValue, JsonValue> }
2801
- | { readonly type: "submission"; readonly value: SubmissionRecord }
2802
- | {
2803
- readonly type: "document.create";
2804
- readonly record: DocumentCreate;
2805
- readonly content: Extract<DocumentContent, { kind: "base" }>;
2806
- }
2807
- | {
2808
- readonly type: "document.copy";
2809
- readonly record: DocumentCreate;
2810
- readonly source: { readonly id: DocumentId; readonly at: DocumentPoint };
2811
- }
2812
- | {
2813
- readonly type: "document.change";
2814
- readonly id: DocumentId;
2815
- readonly content: DocumentContent;
2816
- }
2817
- | { readonly type: "document.retire"; readonly id: DocumentId };
2818
-
2819
- /**
2820
- * Trusts the owning Session to supply semantically valid records, references,
2821
- * ancestry, and transitions. Enforces atomicity, global ID ownership, immutable
2822
- * conversation/entry creation, document record consistency, and detached
2823
- * values; Session serializes commits. Sequences strictly increase but may have
2824
- * gaps. Once commit() resolves, later reads through that Storage observe it.
2825
- */
2826
- interface Storage {
2827
- commit(writes: readonly StorageWrite[], context: Context): Promise<Seq>;
2828
- /** Allocate from the one global numeric namespace; the generic brand is compile-time only. */
2829
- mintId<I extends Id<string>>(): Promise<I>;
2830
-
2831
- conversation(id: ConversationId, context: Context): Promise<ConversationRecord | undefined>;
2832
- scanConversations(query: ConversationQuery, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<ConversationRecord, Cursor>>;
2833
-
2834
- entry(id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;
2835
- entry(conversationId: ConversationId, id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;
2836
- findLatestHeadMarker(conversationId: ConversationId, atOrBeforeEntryId: EntryId | undefined, context: Context): Promise<(EntryRecord & { readonly head: EntryId }) | undefined>;
2837
- scanEntries(query: EntryQuery, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<EntryRecord, Cursor>>;
2838
-
2839
- task(id: TaskId, context: Context): Promise<TaskRecord<JsonValue, JsonValue, JsonValue> | undefined>;
2840
- scanTasks(query: TaskQuery, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<TaskRecord<JsonValue, JsonValue, JsonValue>, Cursor>>;
2841
-
2842
- submission(id: SubmissionId, context: Context): Promise<SubmissionRecord | undefined>;
2843
- scanSubmissions(query: SubmissionQuery, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<SubmissionRecord, Cursor>>;
2844
- submissionByRequest(conversationId: ConversationId, requestId: string, context: Context): Promise<SubmissionRecord | undefined>;
2845
-
2846
- findDocument(address: DocumentAddress, at: DocumentPoint, context: Context): Promise<DocumentRecord | undefined>;
2847
- document(id: DocumentId, at: DocumentPoint, context: Context): Promise<StoredDocument | undefined>;
2848
- scanDocuments(query: DocumentQuery, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<DocumentRecord, Cursor>>;
2849
-
2850
- close(context: Context): Promise<void>;
2851
- }
2852
- ```
2853
-
2854
- `StorageRejected` means a batch was rejected before any durable effect and is
2855
- guaranteed not to have committed. Session rolls such a batch back normally;
2856
- unknown failures after Storage admission remain fatal because their commit state
2857
- is uncertain. Backends use `StorageRejected` for deterministic `document.copy`
2858
- source, replay, and consistency failures only when rollback is guaranteed.
2859
-
2860
- A `document.copy` reads committed pre-batch source state independent of command
2861
- order. The source must be an alive conversation document at the selected point,
2862
- and kind/key/history/fork must match the child create record. Storage persists
2863
- one independent complete child base at the source's stored version. A batch may
2864
- not create, change, or retire a selected source. Later source changes,
2865
- reclamation, retirement, or backend reopen cannot affect the child.
2866
-
2867
- Cursors are backend-owned JSON objects. Callers only round-trip them to the same
2868
- scan on the same storage; cross-storage or cross-query use is unsupported. The
2869
- Session owns the mutation line, so storage implementations do not add a second
2870
- caller-facing commit mutex. Each backend still makes one admitted batch atomic.
2871
-
2872
- `findLatestHeadMarker()` returns the newest visible entry carrying `head` at or
2873
- below its optional inclusive cutoff. The returned entry is the marker; its
2874
- `head` value is the actual lower bound for context. `scanEntries()` pages the
2875
- inclusive ID range in newest-first order while applying every conversation
2876
- ancestry cap. With no bounds it pages complete visible history. To read context
2877
- through entry `E`, find the marker at or before `E`, then scan from
2878
- `marker?.head` through `E`. For current context the upper bound is omitted.
2879
- Conversation owner filters are indexed and conjunctive. They support ownership
2880
- traversal without an all-conversation scan; application-maintained registries
2881
- are not a substitute for these kernel indexes.
2882
-
2883
- `entry(id)` combines exact global lookup with the commit sequence required by
2884
- historical document reads. `entry(conversationId, id)` returns that pair only
2885
- when the entry is visible through the requested conversation's ancestry. `limit`
2886
- is always the maximum page size.
2887
- `findDocument()` resolves one exact logical kind/scope/key address at current or
2888
- historical membership. A missing key means the singleton, not every family
2889
- member. `scanDocuments()` enumerates only the incarnations alive in one exact
2890
- scope at its selected point and may restrict one family/singleton kind. It uses
2891
- ascending incarnation IDs. There is no ordinary open-time all-document scan.
2892
- Task queries support conversation, kind, live/terminal status, abort mark, and
2893
- background status.
2894
-
2895
- `document(id, at)` materializes one specific incarnation and never follows a
2896
- replacement at the same logical address. Callers resolve an address with
2897
- `findDocument()` when they do not already hold an incarnation ID. It selects the
2898
- newest applicable base, applies its ordered Chord delta tail, and returns the detached materialized value, stored
2899
- definition version, and number of replayed deltas after that base. Base/delta records are backend-private. The lookup never
2900
- scans unrelated documents. An unknown ID returns `undefined`. At `"current"`, a
2901
- retired incarnation returns `undefined`. A numeric lookup of a rewindable
2902
- conversation incarnation returns `undefined` outside its half-open lifetime and
2903
- reconstructs the selected value inside it. A numeric lookup of a known current-
2904
- only incarnation rejects rather than depending on reclaimed content. Metadata
2905
- membership remains queryable historically. A missing required base, a version
2906
- change inside a delta tail, or an operation that cannot be applied inside an
2907
- addressable lifetime is storage corruption, not absence.
2908
-
2909
- One normalized batch contains at most one create/change content command per
2910
- incarnation and may also retire that incarnation. Storage applies content before
2911
- retirement independent of write-array order. Create plus retire stamps both
2912
- lifetime bounds with the batch sequence. Retire plus create at one logical
2913
- address makes the new incarnation current at that sequence. Deltas cannot cross
2914
- a stored version boundary; a version transition must be a base.
2915
-
2916
- The semantic conformance suite covers memory, SQLite, and JSONL.
2917
-
2918
- ## 11. Backends
2919
-
2920
- ### 11.1 Memory
2921
-
2922
- Memory storage is the reference semantics. It copies retained write values and
2923
- all read results. This deliberately simulates the ownership boundary naturally
2924
- created by SQLite encoding/decoding and JSONL serialization; it is not defensive
2925
- validation. It preserves rewindable records and reclaims latest records only
2926
- after a committed base or retirement.
2927
-
2928
- ### 11.2 SQLite
2929
-
2930
- One SQL transaction is one Session commit. SQLite stores:
2931
-
2932
- - conversation, entry, task, and submission records;
2933
- - document records;
2934
- - indexed document bases/deltas by document and commit sequence.
2935
-
2936
- Live task transitions replace one row. Terminal tasks remain as small records.
2937
- Document reads use indexed base-plus-tail ranges. The first implementation stores
2938
- Chord records directly; it does not translate generic operations to SQLite JSON
2939
- functions.
2940
-
2941
- Schema shape, WAL checkpoint cadence, and synchronous defaults are backend
2942
- implementation choices validated by conformance, reopen, query-plan, and storage
2943
- benchmarks.
2944
-
2945
- ### 11.3 JSONL
2946
-
2947
- JSONL depends on the portable `FileSystem` capability, not the broader
2948
- `ExecutionEnv`. It uses reclaimable sidecars without exposing them to the
2949
- harness. Persistence alone does not provide the ownership boundary: any decoded
2950
- indexes, materialized values, or caches retained in memory must be detached from
2951
- commit arguments and must not be exposed directly by reads. A JSONL backend
2952
- cannot simply add file appends around aliasing memory tables.
2953
-
2954
- ```text
2955
- main.jsonl table writes, document records, and one marker per commit
2956
- doc-<id>.jsonl one document incarnation
2957
- task-<id>.jsonl live task replacements
2958
- ```
2959
-
2960
- Publication protocol:
2961
-
2962
- 1. Append complete prepared records to every affected sidecar.
2963
- 2. Append one complete main marker listing those records.
2964
- 3. Publish in memory only after the marker write succeeds.
2965
-
2966
- Every commit uses this protocol; there is no standalone-sidecar fast path.
2967
- JSONL creation accepts an `fsync` option that defaults to `false`. Without
2968
- `fsync`, it guarantees ordinary process-crash consistency, not survival of
2969
- power, host, kernel, or filesystem failure. With `fsync: true`, the backend
2970
- appends all affected sidecar records, flushes each affected sidecar, and only
2971
- then appends the main marker. Ordinary publication does not explicitly flush
2972
- `main.jsonl`; an acknowledged tail commit may therefore still disappear, but a
2973
- marker that survives should not overtake its sidecar data. A main-only commit has
2974
- no sidecars to flush. Before destructive reclamation with `fsync: true`, the
2975
- backend flushes `main.jsonl` once so the authorizing marker cannot disappear
2976
- while its replacement or removal survives. If that flush fails, the committed
2977
- state remains published and reclamation is deferred. A non-empty temporary
2978
- replacement is also flushed before rename.
2979
-
2980
- Recovery:
2981
-
2982
- - Remove torn final lines.
2983
- - Ignore and remove unconfirmed sidecar tails.
2984
- - Apply confirmed records only.
2985
- - Missing required confirmed data is corruption and opening fails.
2986
- - A later committed latest base or retirement may prove an earlier physical
2987
- record unnecessary.
2988
- - Any uncertain append failure poisons the open backend.
2989
-
2990
- Reclamation starts only after the authorizing base/retirement commits. When no
2991
- sidecar records remain, it removes the sidecar directly. Otherwise, it writes a
2992
- temporary replacement, renames it, and invalidates cached file descriptors so
2993
- future appends cannot target an unlinked inode. Flushing `main.jsonl` to
2994
- authorize reclamation does not compact it. `main.jsonl` is not compacted in the
2995
- initial implementation.
2996
-
2997
- ## 12. API footguns
2998
-
2999
- These are contracts, not invitations to add defensive machinery:
3000
-
3001
- - **Detached draft work:** draft reads, draft writes, and all `Tx` operations
3002
- reject after the Session callback settles. Fire-and-forget work that runs
3003
- before callback settlement can still mutate the active transaction and is
3004
- unsupported.
3005
- - **Read after write:** read every required table row before the first table
3006
- write. Document drafts remain usable afterward; table reads do not.
3007
- - **Writing to a busy conversation:** only the Harness appends to a conversation
3008
- with an active run. Raw entries appended by `Harness.commit()` or a custom
3009
- task while a generation prepares its request can misplace its system prompt entries;
3010
- use a write submission.
3011
- - **Long transactions:** an async commit callback holds the Session mutation
3012
- line. Never await models, tools, processes, network calls, humans, a nested
3013
- Session commit, or a Session waiter inside it. Use methods on the current `Tx`.
3014
- - **Explicit creation:** only typed `tx.doc()` creates an absent document. Snapshot,
3015
- state, and watch lookup return `undefined` instead.
3016
- - **Family initialization:** the first acquisition of an absent family address
3017
- selects its seed. Existing instances and later calls ignore seeds; a seed is
3018
- neither identity nor an update.
3019
- - **Checkpoint starvation:** if `checkpointWhen()` never returns true, replay
3020
- and current-only document storage can grow without bound while the document is
3021
- live.
3022
- - **Wrong fork setting:** `current`, `initial`, and `asOf` are product semantics,
3023
- not optimizations. Changing one changes child conversation behavior.
3024
- - **Schema stability:** document kinds and visible mount paths are
3025
- persisted/public protocol. Value migration cannot rename a kind; a kind
3026
- change requires explicit copy and retirement. Passing incompatible definition
3027
- tokens that claim the same kind is unsupported caller misuse; Session does not
3028
- maintain a document-definition registry to detect it.
3029
- - **Trusted immutable revisions:** `snapshot()`, state values, watch values, and
3030
- their descendants may share tracker-owned containers. Never mutate them; copy
3031
- first when mutable ownership is required. Runtime freezing is not provided.
3032
- - **Watch activation:** before `start()`, `watch.value` remains the immutable
3033
- acquisition revision. Initialize the consumer from it first. After start, the
3034
- property advances to each delivered immutable revision before its callback;
3035
- every earlier reference remains stable.
3036
- - **Buffered watches:** slow or unstarted watches retain up to 100 exact committed
3037
- frames. Overflow replaces the undelivered suffix with one full-value root
3038
- replacement, so intermediate committed states may be omitted. A consumer that
3039
- must audit every transition must persist each fact in an immutable entry or
3040
- journal and scan that history explicitly.
3041
- - **Watch stop:** a listener may call and await `stop()`; it prevents future
3042
- callbacks but neither aborts nor joins the callback already running.
3043
- - **Durable progress cadence:** clients see only committed progress. A crash may
3044
- lose the current uncommitted throttle window.
3045
- - **Large terminal results:** terminal task records remain queryable. Put large
3046
- results in entries or longer-lived documents and retain only their IDs in the
3047
- outcome. Never reference a task-scoped document retired by that same outcome.
3048
- - **Raw transcript:** view entries are not model context. Rendering edits,
3049
- display-only entries, and model filtering require the appropriate reducer.
3050
- - **Reserved `pi.` names:** task names, document kinds, and entry kinds starting
3051
- with `pi.` belong to built-ins by convention. Nothing enforces it; reusing one
3052
- collides with Harness behavior, such as `pi.system` entries being replayed as
3053
- system messages.
3054
- - **Early resource disposal:** disposing a `Registration` only stops new use.
3055
- Freeing resources immediately can fail calls that are still running.
3056
- - **Async batches:** `batch()` callbacks are synchronous. A callback that returns
3057
- a promise publishes nothing and throws.
3058
- - **Unstable prompt text:** a section renderer whose output changes without a
3059
- real content change, for example by embedding the time, appends system deltas
3060
- and defeats provider prompt caching.
3061
- - **Durable stream options:** `streamOptions.headers` and `metadata` are stored
3062
- in the conversation configuration history and copied into forks. Never put
3063
- credentials there; `Models` resolves auth.
3064
- - **Fatal storage errors:** after an uncertain storage failure the Session is
3065
- poisoned. Do not catch the error and continue using it.
3066
- - **JSONL durability:** default JSONL ordering handles ordinary process crashes;
3067
- without durable mode it does not promise acknowledged commits survive power or
3068
- host failure.
3069
-
3070
- ## 13. Non-goals
3071
-
3072
- Pico5 initially has no:
3073
-
3074
- - whole-Session DOM;
3075
- - visible-undurable publication;
3076
- - Session-kernel semantic event journal or independently maintained event state;
3077
- - session-scoped rewindable documents;
3078
- - automatic checkpoint heuristic;
3079
- - automatic third-party view mounting;
3080
- - CRDT/offline multi-writer merge;
3081
- - SQL translation of arbitrary Chord operations;
3082
- - JSONL global compaction or automatic corruption repair;
3083
- - compatibility layer for removed Pico prototypes;
3084
- - forced termination of non-cooperative extension code inside one process.