@dxos/compute 0.16.0 → 0.17.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 (136) hide show
  1. package/dist/lib/AiMetering.mjs +1 -0
  2. package/dist/lib/Hook.mjs +1 -0
  3. package/dist/lib/Operation.mjs +3 -3
  4. package/dist/lib/Process.mjs +2 -2
  5. package/dist/lib/Trace.mjs +1 -1
  6. package/dist/lib/chunk-AgentIdentity.mjs +1 -1
  7. package/dist/lib/chunk-AgentService.mjs.map +1 -1
  8. package/dist/lib/chunk-AiMetering.mjs +77 -0
  9. package/dist/lib/chunk-AiMetering.mjs.map +1 -0
  10. package/dist/lib/chunk-Cancellation.mjs +1 -1
  11. package/dist/lib/chunk-Hook.mjs +78 -0
  12. package/dist/lib/chunk-Hook.mjs.map +1 -0
  13. package/dist/lib/chunk-Instructions.mjs +1 -1
  14. package/dist/lib/chunk-Operation.mjs +169 -5
  15. package/dist/lib/chunk-Operation.mjs.map +1 -1
  16. package/dist/lib/chunk-OperationHandlerSet.mjs +1 -1
  17. package/dist/lib/chunk-OperationRegistry.mjs +1 -1
  18. package/dist/lib/chunk-OperationRegistry.mjs.map +1 -1
  19. package/dist/lib/chunk-Process.mjs +18 -10
  20. package/dist/lib/chunk-Process.mjs.map +1 -1
  21. package/dist/lib/chunk-Project.mjs +52 -24
  22. package/dist/lib/chunk-Project.mjs.map +1 -1
  23. package/dist/lib/chunk-Reducer.mjs +827 -0
  24. package/dist/lib/chunk-Reducer.mjs.map +1 -0
  25. package/dist/lib/chunk-Routine.mjs +1 -1
  26. package/dist/lib/chunk-Runnable.mjs +1 -1
  27. package/dist/lib/chunk-ServiceResolver.mjs +1 -1
  28. package/dist/lib/chunk-Skill.mjs +10 -47
  29. package/dist/lib/chunk-Skill.mjs.map +1 -1
  30. package/dist/lib/chunk-Spec.mjs +49 -0
  31. package/dist/lib/chunk-Spec.mjs.map +1 -0
  32. package/dist/lib/chunk-SpecReview.mjs +98 -0
  33. package/dist/lib/chunk-SpecReview.mjs.map +1 -0
  34. package/dist/lib/chunk-SqlService.mjs.map +1 -1
  35. package/dist/lib/chunk-StorageService.mjs +1 -1
  36. package/dist/lib/chunk-Template.mjs +2 -2
  37. package/dist/lib/chunk-Trace.mjs +97 -13
  38. package/dist/lib/chunk-Trace.mjs.map +1 -1
  39. package/dist/lib/chunk-Trajectory.mjs +326 -0
  40. package/dist/lib/chunk-Trajectory.mjs.map +1 -0
  41. package/dist/lib/chunk-Transcript.mjs +84 -0
  42. package/dist/lib/chunk-Transcript.mjs.map +1 -0
  43. package/dist/lib/chunk-definitions.mjs +1 -1
  44. package/dist/lib/errors.mjs +3 -1
  45. package/dist/lib/errors.mjs.map +1 -1
  46. package/dist/lib/index.mjs +14 -8
  47. package/dist/lib/testing.mjs +2 -2
  48. package/dist/lib/trajectory/Reducer.mjs +1 -0
  49. package/dist/lib/trajectory/Trajectory.mjs +1 -0
  50. package/dist/lib/trajectory/Transcript.mjs +1 -0
  51. package/dist/lib/types/Project.mjs +1 -1
  52. package/dist/lib/types/Skill.mjs +1 -1
  53. package/dist/lib/types/Spec.mjs +1 -0
  54. package/dist/lib/types/SpecReview.mjs +1 -0
  55. package/dist/types/src/AgentService.d.ts +9 -0
  56. package/dist/types/src/AgentService.d.ts.map +1 -1
  57. package/dist/types/src/AiMetering.d.ts +23 -0
  58. package/dist/types/src/AiMetering.d.ts.map +1 -0
  59. package/dist/types/src/AiMetering.test.d.ts +2 -0
  60. package/dist/types/src/AiMetering.test.d.ts.map +1 -0
  61. package/dist/types/src/Hook.d.ts +84 -0
  62. package/dist/types/src/Hook.d.ts.map +1 -0
  63. package/dist/types/src/Hook.test.d.ts +2 -0
  64. package/dist/types/src/Hook.test.d.ts.map +1 -0
  65. package/dist/types/src/Operation.d.ts +276 -2
  66. package/dist/types/src/Operation.d.ts.map +1 -1
  67. package/dist/types/src/Process.d.ts +26 -4
  68. package/dist/types/src/Process.d.ts.map +1 -1
  69. package/dist/types/src/Script.test.d.ts +2 -0
  70. package/dist/types/src/Script.test.d.ts.map +1 -0
  71. package/dist/types/src/Trace.d.ts +103 -1
  72. package/dist/types/src/Trace.d.ts.map +1 -1
  73. package/dist/types/src/errors.d.ts +30 -0
  74. package/dist/types/src/errors.d.ts.map +1 -1
  75. package/dist/types/src/index.d.ts +3 -1
  76. package/dist/types/src/index.d.ts.map +1 -1
  77. package/dist/types/src/trajectory/Reducer.d.ts +191 -0
  78. package/dist/types/src/trajectory/Reducer.d.ts.map +1 -0
  79. package/dist/types/src/trajectory/Reducer.test.d.ts +2 -0
  80. package/dist/types/src/trajectory/Reducer.test.d.ts.map +1 -0
  81. package/dist/types/src/trajectory/Trajectory.d.ts +3211 -0
  82. package/dist/types/src/trajectory/Trajectory.d.ts.map +1 -0
  83. package/dist/types/src/trajectory/Trajectory.test.d.ts +2 -0
  84. package/dist/types/src/trajectory/Trajectory.test.d.ts.map +1 -0
  85. package/dist/types/src/trajectory/Transcript.d.ts +40 -0
  86. package/dist/types/src/trajectory/Transcript.d.ts.map +1 -0
  87. package/dist/types/src/trajectory/index.d.ts +4 -0
  88. package/dist/types/src/trajectory/index.d.ts.map +1 -0
  89. package/dist/types/src/trajectory/light-threads.test.d.ts +2 -0
  90. package/dist/types/src/trajectory/light-threads.test.d.ts.map +1 -0
  91. package/dist/types/src/trajectory/samples.test.d.ts +2 -0
  92. package/dist/types/src/trajectory/samples.test.d.ts.map +1 -0
  93. package/dist/types/src/types/Project.d.ts +11 -12
  94. package/dist/types/src/types/Project.d.ts.map +1 -1
  95. package/dist/types/src/types/Skill.d.ts +6 -51
  96. package/dist/types/src/types/Skill.d.ts.map +1 -1
  97. package/dist/types/src/types/Spec.d.ts +26 -0
  98. package/dist/types/src/types/Spec.d.ts.map +1 -0
  99. package/dist/types/src/types/SpecReview.d.ts +76 -0
  100. package/dist/types/src/types/SpecReview.d.ts.map +1 -0
  101. package/dist/types/src/types/index.d.ts +2 -0
  102. package/dist/types/src/types/index.d.ts.map +1 -1
  103. package/dist/types/tsconfig.tsbuildinfo +1 -1
  104. package/package.json +59 -26
  105. package/src/AgentService.ts +9 -0
  106. package/src/AiMetering.test.ts +89 -0
  107. package/src/AiMetering.ts +93 -0
  108. package/src/Hook.test.ts +75 -0
  109. package/src/Hook.ts +154 -0
  110. package/src/Operation.test.ts +23 -0
  111. package/src/Operation.ts +334 -0
  112. package/src/Process.ts +33 -6
  113. package/src/Script.test.ts +74 -0
  114. package/src/Trace.ts +97 -4
  115. package/src/errors.ts +3 -0
  116. package/src/index.ts +3 -1
  117. package/src/trajectory/Reducer.test.ts +575 -0
  118. package/src/trajectory/Reducer.ts +1026 -0
  119. package/src/trajectory/Trajectory.test.ts +114 -0
  120. package/src/trajectory/Trajectory.ts +440 -0
  121. package/src/trajectory/Transcript.ts +113 -0
  122. package/src/trajectory/index.ts +7 -0
  123. package/src/trajectory/light-threads.test.ts +310 -0
  124. package/src/trajectory/samples.test.ts +285 -0
  125. package/src/types/Project.test.ts +2 -1
  126. package/src/types/Project.ts +43 -27
  127. package/src/types/Skill.ts +6 -61
  128. package/src/types/Spec.ts +68 -0
  129. package/src/types/SpecReview.ts +98 -0
  130. package/src/types/index.ts +2 -0
  131. package/dist/lib/McpServer.mjs +0 -1
  132. package/dist/lib/chunk-McpServer.mjs +0 -124
  133. package/dist/lib/chunk-McpServer.mjs.map +0 -1
  134. package/dist/types/src/McpServer.d.ts +0 -113
  135. package/dist/types/src/McpServer.d.ts.map +0 -1
  136. package/src/McpServer.ts +0 -142
@@ -0,0 +1,1026 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as HashMap from 'effect/HashMap';
8
+ import * as Option from 'effect/Option';
9
+ import * as Schema from 'effect/Schema';
10
+ import * as SchemaTransformation from 'effect/SchemaTransformation';
11
+
12
+ import { type Obj, type Ref } from '@dxos/echo';
13
+ import { ContentBlock } from '@dxos/types';
14
+
15
+ import * as Trajectory from './Trajectory.ts';
16
+ import * as Transcript from './Transcript.ts';
17
+
18
+ /**
19
+ * A left fold over events in feed order; every view of a trajectory is one of these, so state after `n + k` events
20
+ * is `step` applied `k` times to the state after `n`, and a reader never has to start from the first event.
21
+ */
22
+ export interface Reducer<S> {
23
+ readonly initial: S;
24
+ readonly step: (state: S, event: Trajectory.Event) => S;
25
+ /**
26
+ * Folds a batch at once, equal to stepping each event; lets a reducer copy its state once per batch rather than once
27
+ * per event, which keeps a long fold linear. The state passed in is never modified.
28
+ */
29
+ readonly fold?: (state: S, events: readonly Trajectory.Event[]) => S;
30
+ }
31
+
32
+ /**
33
+ * Reducer state after the event `head`; a cache that is always safe to drop, since replaying from the start
34
+ * rebuilds it exactly.
35
+ */
36
+ export type Checkpoint<S> = {
37
+ readonly state: S;
38
+ readonly head?: Trajectory.EventId;
39
+ /** Events folded so far. */
40
+ readonly count: number;
41
+ };
42
+
43
+ /**
44
+ * Folds `events` (the tail after `from.head`) onto a checkpoint, or onto the initial state.
45
+ * Fold in local order (`Feed.getLocalCursor`): it never changes under a reader, so a checkpoint stays valid as sync
46
+ * repositions the feed.
47
+ */
48
+ export const run = <S>(
49
+ reducer: Reducer<S>,
50
+ events: Iterable<Trajectory.Event>,
51
+ from?: Checkpoint<S>,
52
+ ): Checkpoint<S> => {
53
+ const batch = [...events];
54
+ const initial = from?.state ?? reducer.initial;
55
+ const state = reducer.fold
56
+ ? reducer.fold(initial, batch)
57
+ : batch.reduce((next, event) => reducer.step(next, event), initial);
58
+ return { state, head: batch.at(-1)?.id ?? from?.head, count: (from?.count ?? 0) + batch.length };
59
+ };
60
+
61
+ //
62
+ // Session state: what the agent process needs to decide its next step.
63
+ //
64
+
65
+ export type Alarm = { readonly id: Trajectory.EventId; readonly wakeAt: number; readonly message?: string };
66
+
67
+ export type BackgroundTool = { readonly toolCallId: string; readonly pid?: string };
68
+
69
+ export type ThreadStatus = 'open' | 'merged' | Trajectory.ThreadStatus;
70
+
71
+ export type ThreadInfo = {
72
+ readonly id: Trajectory.ThreadId;
73
+ readonly mode: Trajectory.ThreadMode;
74
+ readonly status: ThreadStatus;
75
+ };
76
+
77
+ type SkillRef = Trajectory.ContextBind['skills'][number];
78
+ type ObjectRef = Trajectory.ContextBind['objects'][number];
79
+
80
+ export type SessionState = {
81
+ /** User messages no `promptConsume` or `promptCancel` has named yet, oldest first. */
82
+ readonly queue: readonly Trajectory.EventId[];
83
+ readonly alarms: readonly Alarm[];
84
+ readonly skills: readonly SkillRef[];
85
+ readonly objects: readonly ObjectRef[];
86
+ readonly background: readonly BackgroundTool[];
87
+ readonly threads: readonly ThreadInfo[];
88
+ readonly model?: Trajectory.ModelChange['model'];
89
+ /** `turnBegin`s of turns that have not ended; more than one when several writers run turns at once. */
90
+ readonly turns: readonly Trajectory.ThreadId[];
91
+ /**
92
+ * `promptConsume`s and `promptCancel`s whose message was no longer queued, because another writer consumed or
93
+ * cancelled it first; a harness claims a message by writing its consume and runs only if that consume is not listed
94
+ * here.
95
+ */
96
+ readonly rejected: readonly Trajectory.EventId[];
97
+ /** Alarms fired since the last prompt a person typed: the count a harness caps self-wakes at. */
98
+ readonly selfWakes: number;
99
+ };
100
+
101
+ /** Whether a message is a prompt a person typed, which ends a run of self-wakes. */
102
+ const isTypedPrompt = (event: Trajectory.Event, payload: Trajectory.Message): boolean =>
103
+ event.sender.role === 'user' &&
104
+ payload.blocks.some((block) => block._tag === 'text' && block.disposition !== 'synthetic');
105
+
106
+ const bind = <T extends { uri: string }>(current: readonly T[], added: readonly T[]): readonly T[] =>
107
+ added.reduce<readonly T[]>(
108
+ (refs, ref) => (refs.some((existing) => existing.uri === ref.uri) ? refs : [...refs, ref]),
109
+ current,
110
+ );
111
+
112
+ const unbind = <T extends { uri: string }>(current: readonly T[], removed: readonly T[]): readonly T[] =>
113
+ current.filter((ref) => !removed.some((other) => other.uri === ref.uri));
114
+
115
+ const threadOf = Trajectory.threadOf;
116
+
117
+ /** `ids` with the thread an opener opens; an opener not yet on a branch (unwritten) opens nothing. */
118
+ const withThread = (ids: readonly Trajectory.ThreadId[], id: Trajectory.ThreadId | undefined) =>
119
+ id === undefined ? ids : [...ids, id];
120
+
121
+ const withOpened = (state: SessionState, id: Trajectory.ThreadId | undefined, mode: Trajectory.ThreadMode) =>
122
+ id === undefined ? state : { ...state, threads: [...state.threads, { id, mode, status: 'open' as const }] };
123
+
124
+ const setThreadStatus = (threads: readonly ThreadInfo[], id: Trajectory.ThreadId | undefined, status: ThreadStatus) =>
125
+ threads.map((thread) => (thread.id === id ? { ...thread, status } : thread));
126
+
127
+ const sessionFold: Reducer<SessionState> = {
128
+ initial: {
129
+ queue: [],
130
+ alarms: [],
131
+ skills: [],
132
+ objects: [],
133
+ background: [],
134
+ threads: [],
135
+ turns: [],
136
+ rejected: [],
137
+ selfWakes: 0,
138
+ },
139
+ step: (state, event) => {
140
+ const payload = event.payload;
141
+ switch (payload._tag) {
142
+ case 'message':
143
+ return event.sender.role === 'user'
144
+ ? {
145
+ ...state,
146
+ queue: [...state.queue, event.id],
147
+ selfWakes: isTypedPrompt(event, payload) ? 0 : state.selfWakes,
148
+ }
149
+ : state;
150
+ case 'promptConsume':
151
+ case 'promptCancel':
152
+ return state.queue.includes(payload.message)
153
+ ? { ...state, queue: state.queue.filter((id) => id !== payload.message) }
154
+ : { ...state, rejected: [...state.rejected, event.id] };
155
+ case 'turnBegin':
156
+ return {
157
+ ...state,
158
+ turns: withThread(state.turns, threadOf(event)),
159
+ model: payload.model ?? state.model,
160
+ };
161
+ case 'turnEnd':
162
+ return { ...state, turns: state.turns.filter((id) => id !== threadOf(event)) };
163
+ case 'modelChange':
164
+ return { ...state, model: payload.model };
165
+ case 'contextBind':
166
+ return { ...state, skills: bind(state.skills, payload.skills), objects: bind(state.objects, payload.objects) };
167
+ case 'contextUnbind':
168
+ return {
169
+ ...state,
170
+ skills: unbind(state.skills, payload.skills),
171
+ objects: unbind(state.objects, payload.objects),
172
+ };
173
+ case 'alarmSet':
174
+ return {
175
+ ...state,
176
+ alarms: [...state.alarms, { id: event.id, wakeAt: payload.wakeAt, message: payload.message }],
177
+ };
178
+ case 'alarmCancel':
179
+ return { ...state, alarms: state.alarms.filter((alarm) => alarm.id !== payload.alarm) };
180
+ case 'alarmFire':
181
+ return {
182
+ ...state,
183
+ alarms: state.alarms.filter((alarm) => alarm.id !== payload.alarm),
184
+ selfWakes: state.selfWakes + 1,
185
+ };
186
+ case 'toolBackground':
187
+ return { ...state, background: [...state.background, { toolCallId: payload.toolCallId, pid: payload.pid }] };
188
+ case 'toolDeliver':
189
+ return { ...state, background: state.background.filter((tool) => tool.toolCallId !== payload.toolCallId) };
190
+ case 'threadOpen':
191
+ return withOpened(state, threadOf(event), payload.mode);
192
+ case 'threadMerge':
193
+ return { ...state, threads: setThreadStatus(state.threads, threadOf(event), 'merged') };
194
+ case 'threadClose':
195
+ return { ...state, threads: setThreadStatus(state.threads, threadOf(event), payload.status) };
196
+ default:
197
+ return state;
198
+ }
199
+ },
200
+ };
201
+
202
+ //
203
+ // Thread view: what the UI renders.
204
+ //
205
+
206
+ /** `rewound`: discarded by a rewind; kept so a reader can tell a message it already showed from a new one. */
207
+ export type ItemStatus = 'queued' | 'consumed' | 'cancelled' | 'sent' | 'rewound';
208
+
209
+ export type ThreadItem = {
210
+ readonly id: Trajectory.EventId;
211
+ readonly sender: Trajectory.Sender;
212
+ readonly blocks: readonly ContentBlock.Any[];
213
+ readonly created: string;
214
+ /** Thread the message was written in; absent for the main thread. */
215
+ readonly thread?: Trajectory.ThreadId;
216
+ /** The lane the message belongs to: the top-level thread or turn its thread nests in; absent outside any. */
217
+ readonly lane?: Trajectory.ThreadId;
218
+ readonly status: ItemStatus;
219
+ };
220
+
221
+ export type LaneStatus = 'running' | 'waiting' | 'done' | 'failed';
222
+
223
+ /**
224
+ * One top-level unit of work: a light (or other) thread opened on main, or a turn that runs on main. Several lanes
225
+ * running at once are what the chat shows side by side.
226
+ */
227
+ export type Lane = {
228
+ readonly id: Trajectory.ThreadId;
229
+ readonly kind: 'turn' | Trajectory.ThreadMode;
230
+ readonly status: LaneStatus;
231
+ readonly owner: Trajectory.Sender;
232
+ readonly created: string;
233
+ readonly purpose?: string;
234
+ /** The lane this one is waiting for (`threadWait`). */
235
+ readonly waitingOn?: Trajectory.ThreadId;
236
+ /** Whether another lane was running at some point while this one was. */
237
+ readonly overlapped?: boolean;
238
+ /**
239
+ * Whether a newer lane of the same owner opened while this one ran: the reader moved on to the newer request, so
240
+ * this one works in the background from then on. Another owner's lane does not background it; agents talking to the
241
+ * reader at once stay side by side. A delegated subagent (a `fresh` thread on main) is in the background from the
242
+ * start.
243
+ */
244
+ readonly backgrounded?: boolean;
245
+ /** A fork's fork point: the message of main it forks at. */
246
+ readonly from?: Trajectory.EventId;
247
+ /** How a person merged a fork into main: its whole work (`raw`), or its conclusion (`summary`). */
248
+ readonly merged?: Trajectory.MergeMode;
249
+ };
250
+
251
+ export type ThreadView = {
252
+ readonly items: readonly ThreadItem[];
253
+ /** In the order they opened. */
254
+ readonly lanes: readonly Lane[];
255
+ /** The lane of every thread and turn opened so far. */
256
+ readonly laneOf: Readonly<Record<Trajectory.ThreadId, Trajectory.ThreadId>>;
257
+ };
258
+
259
+ /** `blocks` with the request the resolution answers settled; a request already settled keeps its first answer. */
260
+ const resolveRequest = (
261
+ blocks: readonly ContentBlock.Any[],
262
+ { requestId, resolution }: Trajectory.RequestResolve,
263
+ ): readonly ContentBlock.Any[] =>
264
+ blocks.map((block) =>
265
+ block._tag === 'request' && block.requestId === requestId && block.resolution === undefined
266
+ ? { ...block, resolution }
267
+ : block,
268
+ );
269
+
270
+ type MutableView = {
271
+ items: ThreadItem[];
272
+ lanes: Lane[];
273
+ laneOf: Record<Trajectory.ThreadId, Trajectory.ThreadId>;
274
+ /** Where each lane is in `lanes`: every turn is a lane, so a search per update would make a fold quadratic. */
275
+ laneIndex: Map<Trajectory.ThreadId, number>;
276
+ /** The lanes still running or waiting, so opening a lane does not scan every lane. */
277
+ running: Set<Trajectory.ThreadId>;
278
+ };
279
+
280
+ const isRunning = (lane: Lane) => lane.status === 'running' || lane.status === 'waiting';
281
+
282
+ const updateLane = (view: MutableView, id: Trajectory.ThreadId | undefined, update: (lane: Lane) => Lane): boolean => {
283
+ const index = id === undefined ? undefined : view.laneIndex.get(id);
284
+ if (index === undefined) {
285
+ return false;
286
+ }
287
+ const lane = update(view.lanes[index]);
288
+ view.lanes[index] = lane;
289
+ if (isRunning(lane)) {
290
+ view.running.add(lane.id);
291
+ } else {
292
+ view.running.delete(lane.id);
293
+ }
294
+ return true;
295
+ };
296
+
297
+ /** Records a thread or turn opening: a lane of its own on main, or a member of its parent's lane. */
298
+ const openLane = (
299
+ view: MutableView,
300
+ event: Trajectory.Event,
301
+ parent: Trajectory.ThreadId | undefined,
302
+ lane: Omit<Lane, 'id' | 'status' | 'owner' | 'created'>,
303
+ ): boolean => {
304
+ const id = threadOf(event);
305
+ if (id === undefined) {
306
+ return false;
307
+ }
308
+ if (parent !== undefined) {
309
+ const parentLane = view.laneOf[parent];
310
+ if (parentLane !== undefined) {
311
+ view.laneOf[id] = parentLane;
312
+ // A lane that runs another turn (after a wait, or for a queued prompt) is running again.
313
+ updateLane(view, parentLane, (existing) => ({ ...existing, status: 'running', waitingOn: undefined }));
314
+ }
315
+ return parentLane !== undefined;
316
+ }
317
+ // A fork runs apart from main, so it neither overlaps the lanes on main nor sends them to the background.
318
+ const running = (lane.kind === 'fork' ? [] : [...view.running]).flatMap((id) => {
319
+ const index = view.laneIndex.get(id);
320
+ return index === undefined ? [] : [view.lanes[index]];
321
+ });
322
+ for (const other of running) {
323
+ const sameOwner = other.owner.name === event.sender.name;
324
+ updateLane(view, other.id, (existing) => ({
325
+ ...existing,
326
+ overlapped: true,
327
+ ...(sameOwner ? { backgrounded: true } : {}),
328
+ }));
329
+ }
330
+ view.laneOf[id] = id;
331
+ view.laneIndex.set(id, view.lanes.length);
332
+ view.running.add(id);
333
+ view.lanes.push({
334
+ id,
335
+ status: 'running',
336
+ owner: event.sender,
337
+ created: event.created,
338
+ ...lane,
339
+ ...(running.length > 0 ? { overlapped: true } : {}),
340
+ // A fresh thread on main is a delegated subagent: the reader never asked it anything, so it works out of view.
341
+ ...(lane.kind === 'fresh' ? { backgrounded: true } : {}),
342
+ });
343
+ return true;
344
+ };
345
+
346
+ const laneOfThread = (view: MutableView, thread: Trajectory.ThreadId | undefined) =>
347
+ thread === undefined ? undefined : view.laneOf[thread];
348
+
349
+ /** Applies one event to the view, in place; `false` when the event leaves the view as it was. */
350
+ const applyThread = (view: MutableView, event: Trajectory.Event): boolean => {
351
+ const items = view.items;
352
+ const payload = event.payload;
353
+ switch (payload._tag) {
354
+ case 'message': {
355
+ const lane = laneOfThread(view, threadOf(event));
356
+ items.push({
357
+ id: event.id,
358
+ sender: event.sender,
359
+ blocks: payload.blocks,
360
+ created: event.created,
361
+ thread: threadOf(event),
362
+ ...(lane !== undefined ? { lane } : {}),
363
+ status: event.sender.role === 'user' ? 'queued' : 'sent',
364
+ });
365
+ // A message after a wait means the lane is working again.
366
+ updateLane(view, lane, (existing) =>
367
+ existing.status === 'waiting' ? { ...existing, status: 'running', waitingOn: undefined } : existing,
368
+ );
369
+ return true;
370
+ }
371
+ case 'turnBegin':
372
+ return openLane(view, event, payload.from?.thread, { kind: 'turn' });
373
+ case 'threadOpen':
374
+ return openLane(view, event, payload.from?.feed ? undefined : payload.from?.thread, {
375
+ kind: payload.mode,
376
+ ...(payload.mode === 'fork' && payload.from !== undefined ? { from: payload.from.event } : {}),
377
+ ...(payload.purpose !== undefined ? { purpose: payload.purpose } : {}),
378
+ });
379
+ case 'turnEnd': {
380
+ // A turn that is its own lane ends it; a turn inside a thread leaves the thread to its merge or close, except
381
+ // in a fork, which rests between its turns because nothing merges it on its own.
382
+ const turn = threadOf(event);
383
+ const lane = laneOfThread(view, turn);
384
+ const laneIndex = lane === undefined ? undefined : view.laneIndex.get(lane);
385
+ if (turn !== undefined && lane !== turn && laneIndex !== undefined && view.lanes[laneIndex].kind === 'fork') {
386
+ return updateLane(view, lane, (existing) => ({ ...existing, status: 'done', waitingOn: undefined }));
387
+ }
388
+ return turn !== undefined && view.laneOf[turn] === turn
389
+ ? updateLane(view, turn, (lane) => ({
390
+ ...lane,
391
+ status: payload.finishReason === 'error' ? 'failed' : 'done',
392
+ waitingOn: undefined,
393
+ }))
394
+ : false;
395
+ }
396
+ case 'threadMerge': {
397
+ const thread = threadOf(event);
398
+ const index = thread === undefined ? undefined : view.laneIndex.get(thread);
399
+ if (thread === undefined || index === undefined || view.lanes[index].kind !== 'fork') {
400
+ return thread !== undefined && view.laneOf[thread] === thread
401
+ ? updateLane(view, thread, (lane) => ({ ...lane, status: 'done', waitingOn: undefined }))
402
+ : false;
403
+ }
404
+ // A fork joins main only when a person merges it, so main shows the merge: its conclusion as one message.
405
+ const fork = view.lanes[index];
406
+ if (payload.mode === 'summary') {
407
+ items.push({
408
+ id: event.id,
409
+ sender: { role: 'assistant', name: fork.purpose ?? 'fork' },
410
+ blocks: payload.summary ?? [],
411
+ created: event.created,
412
+ status: 'sent',
413
+ });
414
+ }
415
+ return updateLane(view, thread, (lane) => ({
416
+ ...lane,
417
+ status: 'done',
418
+ merged: payload.mode,
419
+ waitingOn: undefined,
420
+ }));
421
+ }
422
+ case 'threadClose': {
423
+ const failed = payload.status !== 'completed';
424
+ const thread = threadOf(event);
425
+ return thread !== undefined && view.laneOf[thread] === thread
426
+ ? updateLane(view, thread, (lane) => ({
427
+ ...lane,
428
+ status: failed ? 'failed' : 'done',
429
+ waitingOn: undefined,
430
+ }))
431
+ : false;
432
+ }
433
+ case 'threadWait':
434
+ return updateLane(view, laneOfThread(view, threadOf(event)), (lane) => ({
435
+ ...lane,
436
+ status: 'waiting',
437
+ waitingOn: view.laneOf[payload.on] ?? payload.on,
438
+ }));
439
+ case 'promptConsume': {
440
+ // A second consume of the same message lost the claim, so the message stays where the first one put it.
441
+ const index = items.findLastIndex((item) => item.id === payload.message && item.status === 'queued');
442
+ if (index === -1) {
443
+ return false;
444
+ }
445
+ const [item] = items.splice(index, 1);
446
+ const lane = laneOfThread(view, threadOf(event));
447
+ items.push({ ...item, thread: threadOf(event), ...(lane !== undefined ? { lane } : {}), status: 'consumed' });
448
+ return true;
449
+ }
450
+ case 'requestResolve': {
451
+ const index = items.findLastIndex((item) => item.id === payload.message);
452
+ if (index === -1) {
453
+ return false;
454
+ }
455
+ items[index] = { ...items[index], blocks: resolveRequest(items[index].blocks, payload) };
456
+ return true;
457
+ }
458
+ case 'rewind': {
459
+ const from = threadOf(event) === undefined ? items.findIndex((item) => item.id === payload.from) : -1;
460
+ for (let index = Math.max(from, 0); from !== -1 && index < items.length; index++) {
461
+ if (items[index].status !== 'queued') {
462
+ items[index] = { ...items[index], status: 'rewound' };
463
+ }
464
+ }
465
+ return from !== -1;
466
+ }
467
+ case 'promptCancel': {
468
+ const index = items.findLastIndex((item) => item.id === payload.message && item.status === 'queued');
469
+ if (index === -1) {
470
+ return false;
471
+ }
472
+ items[index] = { ...items[index], status: 'cancelled' };
473
+ return true;
474
+ }
475
+ default:
476
+ return false;
477
+ }
478
+ };
479
+
480
+ /**
481
+ * Every message, including turn threads still streaming; a user message moves to where it is consumed, the position
482
+ * the model sees it at, and joins the consuming turn's thread. A consume or cancel whose message lies outside the loaded window is ignored, so the UI can
483
+ * fold just the tail of a long conversation.
484
+ */
485
+ const foldThread = (state: ThreadView, events: readonly Trajectory.Event[]): ThreadView => {
486
+ const view: MutableView = {
487
+ items: [...state.items],
488
+ lanes: [...state.lanes],
489
+ laneOf: { ...state.laneOf },
490
+ laneIndex: new Map(state.lanes.map((lane, index) => [lane.id, index])),
491
+ running: new Set(state.lanes.filter(isRunning).map((lane) => lane.id)),
492
+ };
493
+ let changed = false;
494
+ for (const event of events) {
495
+ changed = applyThread(view, event) || changed;
496
+ }
497
+ return changed ? { items: view.items, lanes: view.lanes, laneOf: view.laneOf } : state;
498
+ };
499
+
500
+ const threadFold: Reducer<ThreadView> = {
501
+ initial: { items: [], lanes: [], laneOf: {} },
502
+ step: (state, event) => foldThread(state, [event]),
503
+ fold: foldThread,
504
+ };
505
+
506
+ //
507
+ // Prompt: what the session process sends to the model.
508
+ //
509
+
510
+ export type PromptEntry = {
511
+ readonly role: Trajectory.Role;
512
+ /** The sender's name, which lets the model tell several people (or sources) apart. */
513
+ readonly name?: string;
514
+ readonly blocks: readonly ContentBlock.Any[];
515
+ /** Events this entry was built from, so a later `compact` can find its range. */
516
+ readonly source: readonly Trajectory.EventId[];
517
+ /** Feed position of the event that placed the entry in its current buffer. */
518
+ readonly at: number;
519
+ /** A light thread's snapshot of the threads running beside it; dropped when the thread merges. */
520
+ readonly ephemeral?: boolean;
521
+ };
522
+
523
+ /**
524
+ * Entries written in an open thread or turn, merged into `parent` (absent: main) when it ends.
525
+ */
526
+ export type ThreadBuffer = {
527
+ readonly parent?: Trajectory.ThreadId;
528
+ /** How the thread opened; absent for a turn. The session engine's merge policy is per mode. */
529
+ readonly mode?: Trajectory.ThreadMode;
530
+ /** A fresh thread's prompt is its own entries only; a fork's starts with its parent's. */
531
+ readonly fresh: boolean;
532
+ /**
533
+ * Feed position of the last event the thread saw when it opened (its `from.event`); parent entries placed later
534
+ * were written concurrently and are not in its prompt.
535
+ */
536
+ readonly seen: number;
537
+ /** Merged or closed while a child was still open; kept, frozen, so the child's prompt does not change under it. */
538
+ readonly closed?: boolean;
539
+ /** Title and owner a light thread's siblings see it by. */
540
+ readonly purpose?: string;
541
+ readonly owner?: string;
542
+ readonly entries: readonly PromptEntry[];
543
+ };
544
+
545
+ export type PromptState = {
546
+ /** The main thread's prompt; only appended to, except by `compact`. */
547
+ readonly entries: readonly PromptEntry[];
548
+ /** User messages waiting for a `promptConsume`. */
549
+ readonly held: Readonly<Record<Trajectory.EventId, PromptEntry>>;
550
+ readonly threads: Readonly<Record<Trajectory.ThreadId, ThreadBuffer>>;
551
+ /** Events folded so far, which is the feed position of the next one. */
552
+ readonly position: number;
553
+ /** Feed position of every folded event, to resolve a `from.event`; persistent, since a copy per event is quadratic. */
554
+ readonly positions: HashMap.HashMap<Trajectory.EventId, number>;
555
+ /**
556
+ * Threads and turns that merged into a parent holding entries they never saw, with those entries' source events.
557
+ * The merge still happens; whether to accept, re-run or correct is the harness's call.
558
+ */
559
+ readonly stale: Readonly<Record<Trajectory.ThreadId, readonly Trajectory.EventId[]>>;
560
+ /** Conversation this feed continues (`fork`); its prompt up to `origin.event` precedes `entries`. */
561
+ readonly origin?: Trajectory.ThreadOrigin;
562
+ };
563
+
564
+ const omit = <V>(record: Readonly<Record<string, V>>, key: string): Readonly<Record<string, V>> =>
565
+ Object.fromEntries(Object.entries(record).filter(([other]) => other !== key));
566
+
567
+ /**
568
+ * Entry arrays the running `fold` created, which nothing outside it holds yet, so it may push to them instead of
569
+ * copying; `undefined` outside a fold, where every append copies.
570
+ */
571
+ let owned: WeakMap<readonly PromptEntry[], PromptEntry[]> | undefined;
572
+
573
+ const grow = (entries: readonly PromptEntry[], entry: PromptEntry): readonly PromptEntry[] => {
574
+ const mutable = owned?.get(entries);
575
+ if (mutable) {
576
+ mutable.push(entry);
577
+ return mutable;
578
+ }
579
+ const copy = [...entries, entry];
580
+ owned?.set(copy, copy);
581
+ return copy;
582
+ };
583
+
584
+ const append = (
585
+ state: PromptState,
586
+ threadId: Trajectory.ThreadId | undefined,
587
+ placed: Omit<PromptEntry, 'at'>,
588
+ ): PromptState => {
589
+ const entry: PromptEntry = { ...placed, at: state.position };
590
+ if (threadId === undefined) {
591
+ return { ...state, entries: grow(state.entries, entry) };
592
+ }
593
+
594
+ const buffer = state.threads[threadId] ?? { fresh: false, seen: state.position, entries: [] };
595
+ return { ...state, threads: { ...state.threads, [threadId]: { ...buffer, entries: grow(buffer.entries, entry) } } };
596
+ };
597
+
598
+ /**
599
+ * Closes a thread, appending `entries` to its parent; a parent that has already ended stands in for main.
600
+ * A fresh thread never saw its parent, so only a fork or turn can be stale.
601
+ */
602
+ const mergeInto = (state: PromptState, threadId: Trajectory.ThreadId, entries: readonly Omit<PromptEntry, 'at'>[]) => {
603
+ const buffer = live(state, threadId);
604
+ const parent = buffer?.parent;
605
+ const target = parent !== undefined && live(state, parent) ? parent : undefined;
606
+ const unseen = buffer && !buffer.fresh ? placedAfter(promptFor(state, target), buffer.seen) : [];
607
+ return entries
608
+ .filter((entry) => !entry.ephemeral)
609
+ .reduce<PromptState>((next, entry) => append(next, target, entry), {
610
+ ...state,
611
+ threads: end(state.threads, threadId),
612
+ stale: unseen.length > 0 ? { ...state.stale, [threadId]: unseen } : state.stale,
613
+ });
614
+ };
615
+
616
+ /**
617
+ * Source events of the entries placed after `position`. A prompt's entries are in placement order (a compaction
618
+ * summary takes its range's earliest position), so the scan stops at the first entry placed at or before it.
619
+ */
620
+ const placedAfter = (entries: readonly PromptEntry[], position: number): Trajectory.EventId[] => {
621
+ let first = entries.length;
622
+ while (first > 0 && entries[first - 1].at > position) {
623
+ first--;
624
+ }
625
+ return entries.slice(first).flatMap((entry) => entry.source);
626
+ };
627
+
628
+ /** A thread that is open and has not been merged or closed. */
629
+ const live = (state: PromptState, id: Trajectory.ThreadId) => {
630
+ const buffer = state.threads[id];
631
+ return buffer && !buffer.closed ? buffer : undefined;
632
+ };
633
+
634
+ /**
635
+ * Removes an ended thread, or freezes it while a child still builds on it; a frozen parent goes once its last child
636
+ * has ended.
637
+ */
638
+ const end = (threads: PromptState['threads'], id: Trajectory.ThreadId): PromptState['threads'] => {
639
+ const buffer = threads[id];
640
+ if (!buffer) {
641
+ return threads;
642
+ }
643
+
644
+ if (Object.values(threads).some((other) => other.parent === id)) {
645
+ return { ...threads, [id]: { ...buffer, closed: true } };
646
+ }
647
+
648
+ const rest = omit(threads, id);
649
+ const parent = buffer.parent === undefined ? undefined : rest[buffer.parent];
650
+ return buffer.parent !== undefined && parent?.closed ? end(rest, buffer.parent) : rest;
651
+ };
652
+
653
+ /**
654
+ * Feed position a thread with this origin saw up to; an origin this log does not hold (it cannot precede the
655
+ * opener in local order) falls back to everything before the opener.
656
+ */
657
+ const seenAt = (state: PromptState, origin?: Trajectory.ThreadOrigin) =>
658
+ origin && !origin.feed
659
+ ? Option.getOrElse(HashMap.get(state.positions, origin.event), () => state.position)
660
+ : state.position;
661
+
662
+ /**
663
+ * What a fork sees: main as it stood once the message it forks at was in it. A message a turn wrote joins main when
664
+ * the turn ends, after the message itself, so the fork sees up to where the message was placed.
665
+ */
666
+ const forkSeen = (state: PromptState, from: Trajectory.ThreadOrigin | undefined): number => {
667
+ const seen = seenAt(state, from);
668
+ const placed = from === undefined ? undefined : state.entries.find((entry) => entry.source.includes(from.event));
669
+ return placed === undefined ? seen : Math.max(seen, placed.at);
670
+ };
671
+
672
+ const open = (state: PromptState, id: Trajectory.ThreadId | undefined, buffer: ThreadBuffer): PromptState =>
673
+ id === undefined ? state : { ...state, threads: { ...state.threads, [id]: buffer } };
674
+
675
+ /**
676
+ * The prompt a turn in `thread` sends: its own entries after its parents', back to main, unless a fresh thread
677
+ * cuts the chain.
678
+ */
679
+ export const promptFor = (state: PromptState, thread?: Trajectory.ThreadId): readonly PromptEntry[] => {
680
+ const buffer = thread === undefined ? undefined : state.threads[thread];
681
+ if (!buffer) {
682
+ return state.entries;
683
+ }
684
+
685
+ return buffer.fresh
686
+ ? buffer.entries
687
+ : [...promptFor(state, buffer.parent).filter((entry) => entry.at <= buffer.seen), ...buffer.entries];
688
+ };
689
+
690
+ /**
691
+ * A thread's own entries and those of its open children, as a sibling sees them: placed at or before `seen`, in
692
+ * placement order.
693
+ */
694
+ const workOf = (state: PromptState, id: Trajectory.ThreadId, seen: number): PromptEntry[] => {
695
+ const own = state.threads[id]?.entries ?? [];
696
+ const children = Object.entries(state.threads).flatMap(([childId, buffer]) =>
697
+ buffer.parent === id ? workOf(state, Trajectory.ThreadId.make(childId), seen) : [],
698
+ );
699
+ return [...own, ...children]
700
+ .filter((entry) => entry.at <= seen && !entry.ephemeral)
701
+ .sort((left, right) => left.at - right.at);
702
+ };
703
+
704
+ /** A turn's title when it has none of its own: the start of the request it answers. */
705
+ const titleOf = (entries: readonly PromptEntry[]): string | undefined => {
706
+ const request = entries
707
+ .find((entry) => entry.role === 'user')
708
+ ?.blocks.flatMap((block) => (block._tag === 'text' ? [block.text] : []))
709
+ .join(' ')
710
+ .replace(/\s+/g, ' ')
711
+ .trim();
712
+ return request ? (request.length > 80 ? `${request.slice(0, 79)}…` : request) : undefined;
713
+ };
714
+
715
+ /**
716
+ * Opens a light thread: a fork of main that starts with one entry holding the transcript of each running sibling.
717
+ */
718
+ const openLight = (state: PromptState, event: Trajectory.Event, payload: Trajectory.ThreadOpen): PromptState => {
719
+ const id = threadOf(event);
720
+ if (id === undefined) {
721
+ return state;
722
+ }
723
+ const seen = seenAt(state, payload.from);
724
+ const siblings = (payload.siblings ?? []).flatMap((id): Transcript.Thread[] => {
725
+ const buffer = state.threads[id];
726
+ if (!buffer) {
727
+ return [];
728
+ }
729
+ const entries = workOf(state, id, seen);
730
+ return [{ id, purpose: buffer.purpose ?? titleOf(entries), owner: buffer.owner, status: 'running', entries }];
731
+ });
732
+ const entries: PromptEntry[] =
733
+ siblings.length > 0
734
+ ? [
735
+ {
736
+ role: 'event',
737
+ name: 'threads',
738
+ // Synthetic, as the system wrote it: it is context for the thread's prompt, not a prompt of its own.
739
+ blocks: [{ _tag: 'text', text: Transcript.snapshot(siblings, id), disposition: 'synthetic' }],
740
+ source: [event.id],
741
+ at: state.position,
742
+ ephemeral: true,
743
+ },
744
+ ]
745
+ : [];
746
+ return open(state, id, {
747
+ mode: 'light',
748
+ fresh: false,
749
+ seen,
750
+ purpose: payload.purpose,
751
+ owner: event.sender.name,
752
+ entries,
753
+ });
754
+ };
755
+
756
+ const compact = (state: PromptState, payload: Trajectory.Compact, id: Trajectory.EventId) => {
757
+ const entries = state.entries;
758
+ const first = entries.findIndex((entry) => entry.source.includes(payload.from));
759
+ const last = entries.findLastIndex((entry) => entry.source.includes(payload.to));
760
+ // An id that is not in the prompt (a queued or cancelled message, a non-content event) cannot place the range.
761
+ if (first === -1 || last === -1 || first > last) {
762
+ return entries;
763
+ }
764
+
765
+ // The summary keeps the ids it replaced, so a later range that starts inside it still finds where to begin.
766
+ const replaced = entries.slice(first, last + 1).flatMap((entry) => entry.source);
767
+ // A thread that saw only part of the range sees the whole summary; compaction rewrites history either way.
768
+ const at = Math.min(...entries.slice(first, last + 1).map((entry) => entry.at));
769
+ const summary: PromptEntry = { role: 'event', blocks: payload.summary, source: [id, ...replaced], at };
770
+ return [...entries.slice(0, first), summary, ...entries.slice(last + 1)];
771
+ };
772
+
773
+ /**
774
+ * Builds the model prompt. Apart from `compact` and `rewind`, every event leaves `entries` as a prefix of what it was, which is
775
+ * what keeps the provider's prompt cache valid from one request to the next.
776
+ */
777
+ const stepPrompt = (state: PromptState, event: Trajectory.Event): PromptState => {
778
+ const next = place(state, event);
779
+ return { ...next, position: state.position + 1, positions: HashMap.set(next.positions, event.id, state.position) };
780
+ };
781
+
782
+ const promptFold: Reducer<PromptState> = {
783
+ initial: { entries: [], held: {}, threads: {}, position: 0, positions: HashMap.empty(), stale: {} },
784
+ step: stepPrompt,
785
+ fold: (state, events) => {
786
+ owned = new WeakMap();
787
+ try {
788
+ return events.reduce(stepPrompt, state);
789
+ } finally {
790
+ owned = undefined;
791
+ }
792
+ },
793
+ };
794
+
795
+ const place = (state: PromptState, event: Trajectory.Event): PromptState => {
796
+ const payload = event.payload;
797
+ switch (payload._tag) {
798
+ case 'message': {
799
+ const entry: PromptEntry = {
800
+ role: event.sender.role,
801
+ ...(event.sender.name !== undefined ? { name: event.sender.name } : {}),
802
+ blocks: payload.blocks,
803
+ source: [event.id],
804
+ at: state.position,
805
+ };
806
+ return event.sender.role === 'user'
807
+ ? { ...state, held: { ...state.held, [event.id]: entry } }
808
+ : append(state, threadOf(event), entry);
809
+ }
810
+ case 'promptConsume': {
811
+ const entry = state.held[payload.message];
812
+ if (!entry) {
813
+ return state;
814
+ }
815
+
816
+ return append({ ...state, held: omit(state.held, payload.message) }, threadOf(event), {
817
+ ...entry,
818
+ source: [...entry.source, event.id],
819
+ });
820
+ }
821
+ case 'promptCancel':
822
+ return { ...state, held: omit(state.held, payload.message) };
823
+ case 'toolDeliver':
824
+ return append(state, threadOf(event), { role: 'event', blocks: [payload.result], source: [event.id] });
825
+ case 'hookEnd':
826
+ return payload.blocks
827
+ ? append(state, threadOf(event), { role: 'event', blocks: payload.blocks, source: [event.id] })
828
+ : state;
829
+ case 'threadOpen':
830
+ if (payload.mode === 'light') {
831
+ return openLight(state, event, payload);
832
+ }
833
+ // A fork of another conversation has no parent in this log, so its history starts empty.
834
+ return open(state, threadOf(event), {
835
+ parent: payload.from?.feed ? undefined : payload.from?.thread,
836
+ mode: payload.mode,
837
+ ...(payload.purpose !== undefined ? { purpose: payload.purpose } : {}),
838
+ ...(event.sender.name !== undefined ? { owner: event.sender.name } : {}),
839
+ fresh: payload.mode === 'fresh' || payload.from?.feed !== undefined,
840
+ seen: payload.mode === 'fork' ? forkSeen(state, payload.from) : seenAt(state, payload.from),
841
+ entries: [],
842
+ });
843
+ case 'turnBegin':
844
+ return open(state, threadOf(event), {
845
+ parent: payload.from?.thread,
846
+ fresh: false,
847
+ seen: seenAt(state, payload.from),
848
+ entries: [],
849
+ });
850
+ case 'turnEnd': {
851
+ const id = threadOf(event);
852
+ const turn = id === undefined ? undefined : live(state, id);
853
+ return id !== undefined && turn ? mergeInto(state, id, turn.entries) : state;
854
+ }
855
+ case 'threadMerge': {
856
+ const thread = threadOf(event);
857
+ if (thread === undefined || state.threads[thread]?.closed) {
858
+ return state;
859
+ }
860
+
861
+ const merged = state.threads[thread]?.entries ?? [];
862
+ return payload.mode === 'summary'
863
+ ? mergeInto(state, thread, [{ role: 'event', blocks: payload.summary ?? [], source: [event.id] }])
864
+ : mergeInto(state, thread, merged);
865
+ }
866
+ case 'threadClose': {
867
+ const thread = threadOf(event);
868
+ return thread !== undefined && live(state, thread) ? { ...state, threads: end(state.threads, thread) } : state;
869
+ }
870
+ case 'compact':
871
+ return threadOf(event) === undefined ? { ...state, entries: compact(state, payload, event.id) } : state;
872
+ case 'rewind': {
873
+ const from = state.entries.findIndex((entry) => entry.source.includes(payload.from));
874
+ return threadOf(event) === undefined && from !== -1 ? { ...state, entries: state.entries.slice(0, from) } : state;
875
+ }
876
+ case 'fork':
877
+ return { ...state, origin: payload.from };
878
+ case 'requestResolve': {
879
+ const resolve = (entry: PromptEntry): PromptEntry =>
880
+ entry.source.includes(payload.message) ? { ...entry, blocks: resolveRequest(entry.blocks, payload) } : entry;
881
+ return {
882
+ ...state,
883
+ entries: state.entries.map(resolve),
884
+ threads: Object.fromEntries(
885
+ Object.entries(state.threads).map(([id, buffer]) => [
886
+ id,
887
+ { ...buffer, entries: buffer.entries.map(resolve) },
888
+ ]),
889
+ ),
890
+ };
891
+ }
892
+ default:
893
+ return state;
894
+ }
895
+ };
896
+
897
+ //
898
+ // Durable: the reducers above, with a codec so a checkpoint can be stored and resumed.
899
+ //
900
+
901
+ /**
902
+ * A reducer whose state can be stored, so a reader resumes from a saved checkpoint instead of refolding the feed.
903
+ */
904
+ export interface Durable<S> extends Reducer<S> {
905
+ /** Names the reducer and its state shape; a stored checkpoint under a different id is never read back. */
906
+ readonly id: string;
907
+ readonly schema: Schema.Codec<S, unknown>;
908
+ /** Points decoded refs at a database, since a stored ref keeps its URI but not what resolves it. */
909
+ readonly rebind?: (state: S, makeRef: MakeRef) => S;
910
+ }
911
+
912
+ export type MakeRef = <T extends Obj.Unknown>(ref: Ref.Ref<T>) => Ref.Ref<T>;
913
+
914
+ const EventIds = Schema.Array(Trajectory.EventId);
915
+ const ThreadIds = Schema.Array(Trajectory.ThreadId);
916
+
917
+ const SessionStateSchema = Schema.Struct({
918
+ queue: EventIds,
919
+ alarms: Schema.Array(
920
+ Schema.Struct({ id: Trajectory.EventId, wakeAt: Schema.Number, message: Schema.optional(Schema.String) }),
921
+ ),
922
+ skills: Trajectory.ContextBind.fields.skills,
923
+ objects: Trajectory.ContextBind.fields.objects,
924
+ background: Schema.Array(Schema.Struct({ toolCallId: Schema.String, pid: Schema.optional(Schema.String) })),
925
+ threads: Schema.Array(
926
+ Schema.Struct({
927
+ id: Trajectory.ThreadId,
928
+ mode: Trajectory.ThreadMode,
929
+ status: Schema.Literals(['open', 'merged', 'completed', 'failed', 'cancelled']),
930
+ }),
931
+ ),
932
+ model: Schema.optional(Trajectory.ModelChange.fields.model),
933
+ turns: ThreadIds,
934
+ rejected: EventIds,
935
+ selfWakes: Schema.Number,
936
+ });
937
+
938
+ const ThreadViewSchema = Schema.Struct({
939
+ items: Schema.Array(
940
+ Schema.Struct({
941
+ id: Trajectory.EventId,
942
+ sender: Trajectory.Sender,
943
+ blocks: Schema.Array(ContentBlock.Any),
944
+ created: Schema.String,
945
+ thread: Schema.optional(Trajectory.ThreadId),
946
+ lane: Schema.optional(Trajectory.ThreadId),
947
+ status: Schema.Literals(['queued', 'consumed', 'cancelled', 'sent', 'rewound']),
948
+ }),
949
+ ),
950
+ lanes: Schema.Array(
951
+ Schema.Struct({
952
+ id: Trajectory.ThreadId,
953
+ kind: Schema.Literals(['turn', 'fork', 'fresh', 'light']),
954
+ from: Schema.optional(Trajectory.EventId),
955
+ merged: Schema.optional(Trajectory.MergeMode),
956
+ status: Schema.Literals(['running', 'waiting', 'done', 'failed']),
957
+ owner: Trajectory.Sender,
958
+ created: Schema.String,
959
+ purpose: Schema.optional(Schema.String),
960
+ waitingOn: Schema.optional(Trajectory.ThreadId),
961
+ overlapped: Schema.optional(Schema.Boolean),
962
+ backgrounded: Schema.optional(Schema.Boolean),
963
+ }),
964
+ ),
965
+ laneOf: Schema.Record(Trajectory.ThreadId, Trajectory.ThreadId),
966
+ });
967
+
968
+ const PromptEntrySchema = Schema.Struct({
969
+ role: Trajectory.Role,
970
+ name: Schema.optional(Schema.String),
971
+ blocks: Schema.Array(ContentBlock.Any),
972
+ source: EventIds,
973
+ at: Schema.Number,
974
+ ephemeral: Schema.optional(Schema.Boolean),
975
+ });
976
+
977
+ const PromptStateSchema = Schema.Struct({
978
+ entries: Schema.Array(PromptEntrySchema),
979
+ held: Schema.Record(Schema.String, PromptEntrySchema),
980
+ threads: Schema.Record(
981
+ Schema.String,
982
+ Schema.Struct({
983
+ parent: Schema.optional(Trajectory.ThreadId),
984
+ mode: Schema.optional(Trajectory.ThreadMode),
985
+ fresh: Schema.Boolean,
986
+ seen: Schema.Number,
987
+ closed: Schema.optional(Schema.Boolean),
988
+ purpose: Schema.optional(Schema.String),
989
+ owner: Schema.optional(Schema.String),
990
+ entries: Schema.Array(PromptEntrySchema),
991
+ }),
992
+ ),
993
+ position: Schema.Number,
994
+ positions: Schema.Record(Trajectory.EventId, Schema.Number).pipe(
995
+ Schema.decodeTo(
996
+ Schema.HashMap(Trajectory.EventId, Schema.Number),
997
+ SchemaTransformation.transform({
998
+ decode: (record) => HashMap.fromIterable(Object.entries(record)),
999
+ encode: (positions) => Object.fromEntries(positions),
1000
+ }),
1001
+ ),
1002
+ ),
1003
+ stale: Schema.Record(Schema.String, EventIds),
1004
+ origin: Schema.optional(Trajectory.ThreadOrigin),
1005
+ });
1006
+
1007
+ export const session: Durable<SessionState> = {
1008
+ ...sessionFold,
1009
+ id: 'session@3',
1010
+ schema: SessionStateSchema,
1011
+ rebind: (state, makeRef) => ({
1012
+ ...state,
1013
+ skills: state.skills.map((ref) => makeRef(ref)),
1014
+ objects: state.objects.map((ref) => makeRef(ref)),
1015
+ }),
1016
+ };
1017
+
1018
+ export const thread: Durable<ThreadView> = { ...threadFold, id: 'thread@5', schema: ThreadViewSchema };
1019
+
1020
+ export const prompt: Durable<PromptState> = {
1021
+ ...promptFold,
1022
+ id: 'prompt@3',
1023
+ schema: PromptStateSchema,
1024
+ rebind: (state, makeRef) =>
1025
+ state.origin?.feed ? { ...state, origin: { ...state.origin, feed: makeRef(state.origin.feed) } } : state,
1026
+ };