@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,827 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import { B as threadOf$1, C as Sender, D as ThreadMode, S as Role, T as ThreadId, a as ContextBind, g as ModelChange, k as ThreadOrigin, l as EventId, m as MergeMode } from "./chunk-Trajectory.mjs";
3
+ import { s as snapshot } from "./chunk-Transcript.mjs";
4
+ import * as HashMap from "effect/HashMap";
5
+ import * as Option from "effect/Option";
6
+ import * as Schema from "effect/Schema";
7
+ import * as SchemaTransformation from "effect/SchemaTransformation";
8
+ import { ContentBlock } from "@dxos/types";
9
+ //#region src/trajectory/Reducer.ts
10
+ var Reducer_exports = /* @__PURE__ */ __exportAll({
11
+ prompt: () => prompt,
12
+ promptFor: () => promptFor,
13
+ run: () => run,
14
+ session: () => session,
15
+ thread: () => thread
16
+ });
17
+ /**
18
+ * Folds `events` (the tail after `from.head`) onto a checkpoint, or onto the initial state.
19
+ * Fold in local order (`Feed.getLocalCursor`): it never changes under a reader, so a checkpoint stays valid as sync
20
+ * repositions the feed.
21
+ */
22
+ var run = (reducer, events, from) => {
23
+ const batch = [...events];
24
+ const initial = from?.state ?? reducer.initial;
25
+ return {
26
+ state: reducer.fold ? reducer.fold(initial, batch) : batch.reduce((next, event) => reducer.step(next, event), initial),
27
+ head: batch.at(-1)?.id ?? from?.head,
28
+ count: (from?.count ?? 0) + batch.length
29
+ };
30
+ };
31
+ /** Whether a message is a prompt a person typed, which ends a run of self-wakes. */
32
+ var isTypedPrompt = (event, payload) => event.sender.role === "user" && payload.blocks.some((block) => block._tag === "text" && block.disposition !== "synthetic");
33
+ var bind = (current, added) => added.reduce((refs, ref) => refs.some((existing) => existing.uri === ref.uri) ? refs : [...refs, ref], current);
34
+ var unbind = (current, removed) => current.filter((ref) => !removed.some((other) => other.uri === ref.uri));
35
+ var threadOf = threadOf$1;
36
+ /** `ids` with the thread an opener opens; an opener not yet on a branch (unwritten) opens nothing. */
37
+ var withThread = (ids, id) => id === void 0 ? ids : [...ids, id];
38
+ var withOpened = (state, id, mode) => id === void 0 ? state : {
39
+ ...state,
40
+ threads: [...state.threads, {
41
+ id,
42
+ mode,
43
+ status: "open"
44
+ }]
45
+ };
46
+ var setThreadStatus = (threads, id, status) => threads.map((thread) => thread.id === id ? {
47
+ ...thread,
48
+ status
49
+ } : thread);
50
+ var sessionFold = {
51
+ initial: {
52
+ queue: [],
53
+ alarms: [],
54
+ skills: [],
55
+ objects: [],
56
+ background: [],
57
+ threads: [],
58
+ turns: [],
59
+ rejected: [],
60
+ selfWakes: 0
61
+ },
62
+ step: (state, event) => {
63
+ const payload = event.payload;
64
+ switch (payload._tag) {
65
+ case "message": return event.sender.role === "user" ? {
66
+ ...state,
67
+ queue: [...state.queue, event.id],
68
+ selfWakes: isTypedPrompt(event, payload) ? 0 : state.selfWakes
69
+ } : state;
70
+ case "promptConsume":
71
+ case "promptCancel": return state.queue.includes(payload.message) ? {
72
+ ...state,
73
+ queue: state.queue.filter((id) => id !== payload.message)
74
+ } : {
75
+ ...state,
76
+ rejected: [...state.rejected, event.id]
77
+ };
78
+ case "turnBegin": return {
79
+ ...state,
80
+ turns: withThread(state.turns, threadOf(event)),
81
+ model: payload.model ?? state.model
82
+ };
83
+ case "turnEnd": return {
84
+ ...state,
85
+ turns: state.turns.filter((id) => id !== threadOf(event))
86
+ };
87
+ case "modelChange": return {
88
+ ...state,
89
+ model: payload.model
90
+ };
91
+ case "contextBind": return {
92
+ ...state,
93
+ skills: bind(state.skills, payload.skills),
94
+ objects: bind(state.objects, payload.objects)
95
+ };
96
+ case "contextUnbind": return {
97
+ ...state,
98
+ skills: unbind(state.skills, payload.skills),
99
+ objects: unbind(state.objects, payload.objects)
100
+ };
101
+ case "alarmSet": return {
102
+ ...state,
103
+ alarms: [...state.alarms, {
104
+ id: event.id,
105
+ wakeAt: payload.wakeAt,
106
+ message: payload.message
107
+ }]
108
+ };
109
+ case "alarmCancel": return {
110
+ ...state,
111
+ alarms: state.alarms.filter((alarm) => alarm.id !== payload.alarm)
112
+ };
113
+ case "alarmFire": return {
114
+ ...state,
115
+ alarms: state.alarms.filter((alarm) => alarm.id !== payload.alarm),
116
+ selfWakes: state.selfWakes + 1
117
+ };
118
+ case "toolBackground": return {
119
+ ...state,
120
+ background: [...state.background, {
121
+ toolCallId: payload.toolCallId,
122
+ pid: payload.pid
123
+ }]
124
+ };
125
+ case "toolDeliver": return {
126
+ ...state,
127
+ background: state.background.filter((tool) => tool.toolCallId !== payload.toolCallId)
128
+ };
129
+ case "threadOpen": return withOpened(state, threadOf(event), payload.mode);
130
+ case "threadMerge": return {
131
+ ...state,
132
+ threads: setThreadStatus(state.threads, threadOf(event), "merged")
133
+ };
134
+ case "threadClose": return {
135
+ ...state,
136
+ threads: setThreadStatus(state.threads, threadOf(event), payload.status)
137
+ };
138
+ default: return state;
139
+ }
140
+ }
141
+ };
142
+ /** `blocks` with the request the resolution answers settled; a request already settled keeps its first answer. */
143
+ var resolveRequest = (blocks, { requestId, resolution }) => blocks.map((block) => block._tag === "request" && block.requestId === requestId && block.resolution === void 0 ? {
144
+ ...block,
145
+ resolution
146
+ } : block);
147
+ var isRunning = (lane) => lane.status === "running" || lane.status === "waiting";
148
+ var updateLane = (view, id, update) => {
149
+ const index = id === void 0 ? void 0 : view.laneIndex.get(id);
150
+ if (index === void 0) return false;
151
+ const lane = update(view.lanes[index]);
152
+ view.lanes[index] = lane;
153
+ if (isRunning(lane)) view.running.add(lane.id);
154
+ else view.running.delete(lane.id);
155
+ return true;
156
+ };
157
+ /** Records a thread or turn opening: a lane of its own on main, or a member of its parent's lane. */
158
+ var openLane = (view, event, parent, lane) => {
159
+ const id = threadOf(event);
160
+ if (id === void 0) return false;
161
+ if (parent !== void 0) {
162
+ const parentLane = view.laneOf[parent];
163
+ if (parentLane !== void 0) {
164
+ view.laneOf[id] = parentLane;
165
+ updateLane(view, parentLane, (existing) => ({
166
+ ...existing,
167
+ status: "running",
168
+ waitingOn: void 0
169
+ }));
170
+ }
171
+ return parentLane !== void 0;
172
+ }
173
+ const running = (lane.kind === "fork" ? [] : [...view.running]).flatMap((id) => {
174
+ const index = view.laneIndex.get(id);
175
+ return index === void 0 ? [] : [view.lanes[index]];
176
+ });
177
+ for (const other of running) {
178
+ const sameOwner = other.owner.name === event.sender.name;
179
+ updateLane(view, other.id, (existing) => ({
180
+ ...existing,
181
+ overlapped: true,
182
+ ...sameOwner ? { backgrounded: true } : {}
183
+ }));
184
+ }
185
+ view.laneOf[id] = id;
186
+ view.laneIndex.set(id, view.lanes.length);
187
+ view.running.add(id);
188
+ view.lanes.push({
189
+ id,
190
+ status: "running",
191
+ owner: event.sender,
192
+ created: event.created,
193
+ ...lane,
194
+ ...running.length > 0 ? { overlapped: true } : {},
195
+ ...lane.kind === "fresh" ? { backgrounded: true } : {}
196
+ });
197
+ return true;
198
+ };
199
+ var laneOfThread = (view, thread) => thread === void 0 ? void 0 : view.laneOf[thread];
200
+ /** Applies one event to the view, in place; `false` when the event leaves the view as it was. */
201
+ var applyThread = (view, event) => {
202
+ const items = view.items;
203
+ const payload = event.payload;
204
+ switch (payload._tag) {
205
+ case "message": {
206
+ const lane = laneOfThread(view, threadOf(event));
207
+ items.push({
208
+ id: event.id,
209
+ sender: event.sender,
210
+ blocks: payload.blocks,
211
+ created: event.created,
212
+ thread: threadOf(event),
213
+ ...lane !== void 0 ? { lane } : {},
214
+ status: event.sender.role === "user" ? "queued" : "sent"
215
+ });
216
+ updateLane(view, lane, (existing) => existing.status === "waiting" ? {
217
+ ...existing,
218
+ status: "running",
219
+ waitingOn: void 0
220
+ } : existing);
221
+ return true;
222
+ }
223
+ case "turnBegin": return openLane(view, event, payload.from?.thread, { kind: "turn" });
224
+ case "threadOpen": return openLane(view, event, payload.from?.feed ? void 0 : payload.from?.thread, {
225
+ kind: payload.mode,
226
+ ...payload.mode === "fork" && payload.from !== void 0 ? { from: payload.from.event } : {},
227
+ ...payload.purpose !== void 0 ? { purpose: payload.purpose } : {}
228
+ });
229
+ case "turnEnd": {
230
+ const turn = threadOf(event);
231
+ const lane = laneOfThread(view, turn);
232
+ const laneIndex = lane === void 0 ? void 0 : view.laneIndex.get(lane);
233
+ if (turn !== void 0 && lane !== turn && laneIndex !== void 0 && view.lanes[laneIndex].kind === "fork") return updateLane(view, lane, (existing) => ({
234
+ ...existing,
235
+ status: "done",
236
+ waitingOn: void 0
237
+ }));
238
+ return turn !== void 0 && view.laneOf[turn] === turn ? updateLane(view, turn, (lane) => ({
239
+ ...lane,
240
+ status: payload.finishReason === "error" ? "failed" : "done",
241
+ waitingOn: void 0
242
+ })) : false;
243
+ }
244
+ case "threadMerge": {
245
+ const thread = threadOf(event);
246
+ const index = thread === void 0 ? void 0 : view.laneIndex.get(thread);
247
+ if (thread === void 0 || index === void 0 || view.lanes[index].kind !== "fork") return thread !== void 0 && view.laneOf[thread] === thread ? updateLane(view, thread, (lane) => ({
248
+ ...lane,
249
+ status: "done",
250
+ waitingOn: void 0
251
+ })) : false;
252
+ const fork = view.lanes[index];
253
+ if (payload.mode === "summary") items.push({
254
+ id: event.id,
255
+ sender: {
256
+ role: "assistant",
257
+ name: fork.purpose ?? "fork"
258
+ },
259
+ blocks: payload.summary ?? [],
260
+ created: event.created,
261
+ status: "sent"
262
+ });
263
+ return updateLane(view, thread, (lane) => ({
264
+ ...lane,
265
+ status: "done",
266
+ merged: payload.mode,
267
+ waitingOn: void 0
268
+ }));
269
+ }
270
+ case "threadClose": {
271
+ const failed = payload.status !== "completed";
272
+ const thread = threadOf(event);
273
+ return thread !== void 0 && view.laneOf[thread] === thread ? updateLane(view, thread, (lane) => ({
274
+ ...lane,
275
+ status: failed ? "failed" : "done",
276
+ waitingOn: void 0
277
+ })) : false;
278
+ }
279
+ case "threadWait": return updateLane(view, laneOfThread(view, threadOf(event)), (lane) => ({
280
+ ...lane,
281
+ status: "waiting",
282
+ waitingOn: view.laneOf[payload.on] ?? payload.on
283
+ }));
284
+ case "promptConsume": {
285
+ const index = items.findLastIndex((item) => item.id === payload.message && item.status === "queued");
286
+ if (index === -1) return false;
287
+ const [item] = items.splice(index, 1);
288
+ const lane = laneOfThread(view, threadOf(event));
289
+ items.push({
290
+ ...item,
291
+ thread: threadOf(event),
292
+ ...lane !== void 0 ? { lane } : {},
293
+ status: "consumed"
294
+ });
295
+ return true;
296
+ }
297
+ case "requestResolve": {
298
+ const index = items.findLastIndex((item) => item.id === payload.message);
299
+ if (index === -1) return false;
300
+ items[index] = {
301
+ ...items[index],
302
+ blocks: resolveRequest(items[index].blocks, payload)
303
+ };
304
+ return true;
305
+ }
306
+ case "rewind": {
307
+ const from = threadOf(event) === void 0 ? items.findIndex((item) => item.id === payload.from) : -1;
308
+ for (let index = Math.max(from, 0); from !== -1 && index < items.length; index++) if (items[index].status !== "queued") items[index] = {
309
+ ...items[index],
310
+ status: "rewound"
311
+ };
312
+ return from !== -1;
313
+ }
314
+ case "promptCancel": {
315
+ const index = items.findLastIndex((item) => item.id === payload.message && item.status === "queued");
316
+ if (index === -1) return false;
317
+ items[index] = {
318
+ ...items[index],
319
+ status: "cancelled"
320
+ };
321
+ return true;
322
+ }
323
+ default: return false;
324
+ }
325
+ };
326
+ /**
327
+ * Every message, including turn threads still streaming; a user message moves to where it is consumed, the position
328
+ * 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
329
+ * fold just the tail of a long conversation.
330
+ */
331
+ var foldThread = (state, events) => {
332
+ const view = {
333
+ items: [...state.items],
334
+ lanes: [...state.lanes],
335
+ laneOf: { ...state.laneOf },
336
+ laneIndex: new Map(state.lanes.map((lane, index) => [lane.id, index])),
337
+ running: new Set(state.lanes.filter(isRunning).map((lane) => lane.id))
338
+ };
339
+ let changed = false;
340
+ for (const event of events) changed = applyThread(view, event) || changed;
341
+ return changed ? {
342
+ items: view.items,
343
+ lanes: view.lanes,
344
+ laneOf: view.laneOf
345
+ } : state;
346
+ };
347
+ var threadFold = {
348
+ initial: {
349
+ items: [],
350
+ lanes: [],
351
+ laneOf: {}
352
+ },
353
+ step: (state, event) => foldThread(state, [event]),
354
+ fold: foldThread
355
+ };
356
+ var omit = (record, key) => Object.fromEntries(Object.entries(record).filter(([other]) => other !== key));
357
+ /**
358
+ * Entry arrays the running `fold` created, which nothing outside it holds yet, so it may push to them instead of
359
+ * copying; `undefined` outside a fold, where every append copies.
360
+ */
361
+ var owned;
362
+ var grow = (entries, entry) => {
363
+ const mutable = owned?.get(entries);
364
+ if (mutable) {
365
+ mutable.push(entry);
366
+ return mutable;
367
+ }
368
+ const copy = [...entries, entry];
369
+ owned?.set(copy, copy);
370
+ return copy;
371
+ };
372
+ var append = (state, threadId, placed) => {
373
+ const entry = {
374
+ ...placed,
375
+ at: state.position
376
+ };
377
+ if (threadId === void 0) return {
378
+ ...state,
379
+ entries: grow(state.entries, entry)
380
+ };
381
+ const buffer = state.threads[threadId] ?? {
382
+ fresh: false,
383
+ seen: state.position,
384
+ entries: []
385
+ };
386
+ return {
387
+ ...state,
388
+ threads: {
389
+ ...state.threads,
390
+ [threadId]: {
391
+ ...buffer,
392
+ entries: grow(buffer.entries, entry)
393
+ }
394
+ }
395
+ };
396
+ };
397
+ /**
398
+ * Closes a thread, appending `entries` to its parent; a parent that has already ended stands in for main.
399
+ * A fresh thread never saw its parent, so only a fork or turn can be stale.
400
+ */
401
+ var mergeInto = (state, threadId, entries) => {
402
+ const buffer = live(state, threadId);
403
+ const parent = buffer?.parent;
404
+ const target = parent !== void 0 && live(state, parent) ? parent : void 0;
405
+ const unseen = buffer && !buffer.fresh ? placedAfter(promptFor(state, target), buffer.seen) : [];
406
+ return entries.filter((entry) => !entry.ephemeral).reduce((next, entry) => append(next, target, entry), {
407
+ ...state,
408
+ threads: end(state.threads, threadId),
409
+ stale: unseen.length > 0 ? {
410
+ ...state.stale,
411
+ [threadId]: unseen
412
+ } : state.stale
413
+ });
414
+ };
415
+ /**
416
+ * Source events of the entries placed after `position`. A prompt's entries are in placement order (a compaction
417
+ * summary takes its range's earliest position), so the scan stops at the first entry placed at or before it.
418
+ */
419
+ var placedAfter = (entries, position) => {
420
+ let first = entries.length;
421
+ while (first > 0 && entries[first - 1].at > position) first--;
422
+ return entries.slice(first).flatMap((entry) => entry.source);
423
+ };
424
+ /** A thread that is open and has not been merged or closed. */
425
+ var live = (state, id) => {
426
+ const buffer = state.threads[id];
427
+ return buffer && !buffer.closed ? buffer : void 0;
428
+ };
429
+ /**
430
+ * Removes an ended thread, or freezes it while a child still builds on it; a frozen parent goes once its last child
431
+ * has ended.
432
+ */
433
+ var end = (threads, id) => {
434
+ const buffer = threads[id];
435
+ if (!buffer) return threads;
436
+ if (Object.values(threads).some((other) => other.parent === id)) return {
437
+ ...threads,
438
+ [id]: {
439
+ ...buffer,
440
+ closed: true
441
+ }
442
+ };
443
+ const rest = omit(threads, id);
444
+ const parent = buffer.parent === void 0 ? void 0 : rest[buffer.parent];
445
+ return buffer.parent !== void 0 && parent?.closed ? end(rest, buffer.parent) : rest;
446
+ };
447
+ /**
448
+ * Feed position a thread with this origin saw up to; an origin this log does not hold (it cannot precede the
449
+ * opener in local order) falls back to everything before the opener.
450
+ */
451
+ var seenAt = (state, origin) => origin && !origin.feed ? Option.getOrElse(HashMap.get(state.positions, origin.event), () => state.position) : state.position;
452
+ /**
453
+ * 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
454
+ * the turn ends, after the message itself, so the fork sees up to where the message was placed.
455
+ */
456
+ var forkSeen = (state, from) => {
457
+ const seen = seenAt(state, from);
458
+ const placed = from === void 0 ? void 0 : state.entries.find((entry) => entry.source.includes(from.event));
459
+ return placed === void 0 ? seen : Math.max(seen, placed.at);
460
+ };
461
+ var open = (state, id, buffer) => id === void 0 ? state : {
462
+ ...state,
463
+ threads: {
464
+ ...state.threads,
465
+ [id]: buffer
466
+ }
467
+ };
468
+ /**
469
+ * The prompt a turn in `thread` sends: its own entries after its parents', back to main, unless a fresh thread
470
+ * cuts the chain.
471
+ */
472
+ var promptFor = (state, thread) => {
473
+ const buffer = thread === void 0 ? void 0 : state.threads[thread];
474
+ if (!buffer) return state.entries;
475
+ return buffer.fresh ? buffer.entries : [...promptFor(state, buffer.parent).filter((entry) => entry.at <= buffer.seen), ...buffer.entries];
476
+ };
477
+ /**
478
+ * A thread's own entries and those of its open children, as a sibling sees them: placed at or before `seen`, in
479
+ * placement order.
480
+ */
481
+ var workOf = (state, id, seen) => {
482
+ const own = state.threads[id]?.entries ?? [];
483
+ const children = Object.entries(state.threads).flatMap(([childId, buffer]) => buffer.parent === id ? workOf(state, ThreadId.make(childId), seen) : []);
484
+ return [...own, ...children].filter((entry) => entry.at <= seen && !entry.ephemeral).sort((left, right) => left.at - right.at);
485
+ };
486
+ /** A turn's title when it has none of its own: the start of the request it answers. */
487
+ var titleOf = (entries) => {
488
+ const request = entries.find((entry) => entry.role === "user")?.blocks.flatMap((block) => block._tag === "text" ? [block.text] : []).join(" ").replace(/\s+/g, " ").trim();
489
+ return request ? request.length > 80 ? `${request.slice(0, 79)}…` : request : void 0;
490
+ };
491
+ /**
492
+ * Opens a light thread: a fork of main that starts with one entry holding the transcript of each running sibling.
493
+ */
494
+ var openLight = (state, event, payload) => {
495
+ const id = threadOf(event);
496
+ if (id === void 0) return state;
497
+ const seen = seenAt(state, payload.from);
498
+ const siblings = (payload.siblings ?? []).flatMap((id) => {
499
+ const buffer = state.threads[id];
500
+ if (!buffer) return [];
501
+ const entries = workOf(state, id, seen);
502
+ return [{
503
+ id,
504
+ purpose: buffer.purpose ?? titleOf(entries),
505
+ owner: buffer.owner,
506
+ status: "running",
507
+ entries
508
+ }];
509
+ });
510
+ const entries = siblings.length > 0 ? [{
511
+ role: "event",
512
+ name: "threads",
513
+ blocks: [{
514
+ _tag: "text",
515
+ text: snapshot(siblings, id),
516
+ disposition: "synthetic"
517
+ }],
518
+ source: [event.id],
519
+ at: state.position,
520
+ ephemeral: true
521
+ }] : [];
522
+ return open(state, id, {
523
+ mode: "light",
524
+ fresh: false,
525
+ seen,
526
+ purpose: payload.purpose,
527
+ owner: event.sender.name,
528
+ entries
529
+ });
530
+ };
531
+ var compact = (state, payload, id) => {
532
+ const entries = state.entries;
533
+ const first = entries.findIndex((entry) => entry.source.includes(payload.from));
534
+ const last = entries.findLastIndex((entry) => entry.source.includes(payload.to));
535
+ if (first === -1 || last === -1 || first > last) return entries;
536
+ const replaced = entries.slice(first, last + 1).flatMap((entry) => entry.source);
537
+ const at = Math.min(...entries.slice(first, last + 1).map((entry) => entry.at));
538
+ const summary = {
539
+ role: "event",
540
+ blocks: payload.summary,
541
+ source: [id, ...replaced],
542
+ at
543
+ };
544
+ return [
545
+ ...entries.slice(0, first),
546
+ summary,
547
+ ...entries.slice(last + 1)
548
+ ];
549
+ };
550
+ /**
551
+ * Builds the model prompt. Apart from `compact` and `rewind`, every event leaves `entries` as a prefix of what it was, which is
552
+ * what keeps the provider's prompt cache valid from one request to the next.
553
+ */
554
+ var stepPrompt = (state, event) => {
555
+ const next = place(state, event);
556
+ return {
557
+ ...next,
558
+ position: state.position + 1,
559
+ positions: HashMap.set(next.positions, event.id, state.position)
560
+ };
561
+ };
562
+ var promptFold = {
563
+ initial: {
564
+ entries: [],
565
+ held: {},
566
+ threads: {},
567
+ position: 0,
568
+ positions: HashMap.empty(),
569
+ stale: {}
570
+ },
571
+ step: stepPrompt,
572
+ fold: (state, events) => {
573
+ owned = /* @__PURE__ */ new WeakMap();
574
+ try {
575
+ return events.reduce(stepPrompt, state);
576
+ } finally {
577
+ owned = void 0;
578
+ }
579
+ }
580
+ };
581
+ var place = (state, event) => {
582
+ const payload = event.payload;
583
+ switch (payload._tag) {
584
+ case "message": {
585
+ const entry = {
586
+ role: event.sender.role,
587
+ ...event.sender.name !== void 0 ? { name: event.sender.name } : {},
588
+ blocks: payload.blocks,
589
+ source: [event.id],
590
+ at: state.position
591
+ };
592
+ return event.sender.role === "user" ? {
593
+ ...state,
594
+ held: {
595
+ ...state.held,
596
+ [event.id]: entry
597
+ }
598
+ } : append(state, threadOf(event), entry);
599
+ }
600
+ case "promptConsume": {
601
+ const entry = state.held[payload.message];
602
+ if (!entry) return state;
603
+ return append({
604
+ ...state,
605
+ held: omit(state.held, payload.message)
606
+ }, threadOf(event), {
607
+ ...entry,
608
+ source: [...entry.source, event.id]
609
+ });
610
+ }
611
+ case "promptCancel": return {
612
+ ...state,
613
+ held: omit(state.held, payload.message)
614
+ };
615
+ case "toolDeliver": return append(state, threadOf(event), {
616
+ role: "event",
617
+ blocks: [payload.result],
618
+ source: [event.id]
619
+ });
620
+ case "hookEnd": return payload.blocks ? append(state, threadOf(event), {
621
+ role: "event",
622
+ blocks: payload.blocks,
623
+ source: [event.id]
624
+ }) : state;
625
+ case "threadOpen":
626
+ if (payload.mode === "light") return openLight(state, event, payload);
627
+ return open(state, threadOf(event), {
628
+ parent: payload.from?.feed ? void 0 : payload.from?.thread,
629
+ mode: payload.mode,
630
+ ...payload.purpose !== void 0 ? { purpose: payload.purpose } : {},
631
+ ...event.sender.name !== void 0 ? { owner: event.sender.name } : {},
632
+ fresh: payload.mode === "fresh" || payload.from?.feed !== void 0,
633
+ seen: payload.mode === "fork" ? forkSeen(state, payload.from) : seenAt(state, payload.from),
634
+ entries: []
635
+ });
636
+ case "turnBegin": return open(state, threadOf(event), {
637
+ parent: payload.from?.thread,
638
+ fresh: false,
639
+ seen: seenAt(state, payload.from),
640
+ entries: []
641
+ });
642
+ case "turnEnd": {
643
+ const id = threadOf(event);
644
+ const turn = id === void 0 ? void 0 : live(state, id);
645
+ return id !== void 0 && turn ? mergeInto(state, id, turn.entries) : state;
646
+ }
647
+ case "threadMerge": {
648
+ const thread = threadOf(event);
649
+ if (thread === void 0 || state.threads[thread]?.closed) return state;
650
+ const merged = state.threads[thread]?.entries ?? [];
651
+ return payload.mode === "summary" ? mergeInto(state, thread, [{
652
+ role: "event",
653
+ blocks: payload.summary ?? [],
654
+ source: [event.id]
655
+ }]) : mergeInto(state, thread, merged);
656
+ }
657
+ case "threadClose": {
658
+ const thread = threadOf(event);
659
+ return thread !== void 0 && live(state, thread) ? {
660
+ ...state,
661
+ threads: end(state.threads, thread)
662
+ } : state;
663
+ }
664
+ case "compact": return threadOf(event) === void 0 ? {
665
+ ...state,
666
+ entries: compact(state, payload, event.id)
667
+ } : state;
668
+ case "rewind": {
669
+ const from = state.entries.findIndex((entry) => entry.source.includes(payload.from));
670
+ return threadOf(event) === void 0 && from !== -1 ? {
671
+ ...state,
672
+ entries: state.entries.slice(0, from)
673
+ } : state;
674
+ }
675
+ case "fork": return {
676
+ ...state,
677
+ origin: payload.from
678
+ };
679
+ case "requestResolve": {
680
+ const resolve = (entry) => entry.source.includes(payload.message) ? {
681
+ ...entry,
682
+ blocks: resolveRequest(entry.blocks, payload)
683
+ } : entry;
684
+ return {
685
+ ...state,
686
+ entries: state.entries.map(resolve),
687
+ threads: Object.fromEntries(Object.entries(state.threads).map(([id, buffer]) => [id, {
688
+ ...buffer,
689
+ entries: buffer.entries.map(resolve)
690
+ }]))
691
+ };
692
+ }
693
+ default: return state;
694
+ }
695
+ };
696
+ var EventIds = Schema.Array(EventId);
697
+ var ThreadIds = Schema.Array(ThreadId);
698
+ var SessionStateSchema = Schema.Struct({
699
+ queue: EventIds,
700
+ alarms: Schema.Array(Schema.Struct({
701
+ id: EventId,
702
+ wakeAt: Schema.Number,
703
+ message: Schema.optional(Schema.String)
704
+ })),
705
+ skills: ContextBind.fields.skills,
706
+ objects: ContextBind.fields.objects,
707
+ background: Schema.Array(Schema.Struct({
708
+ toolCallId: Schema.String,
709
+ pid: Schema.optional(Schema.String)
710
+ })),
711
+ threads: Schema.Array(Schema.Struct({
712
+ id: ThreadId,
713
+ mode: ThreadMode,
714
+ status: Schema.Literals([
715
+ "open",
716
+ "merged",
717
+ "completed",
718
+ "failed",
719
+ "cancelled"
720
+ ])
721
+ })),
722
+ model: Schema.optional(ModelChange.fields.model),
723
+ turns: ThreadIds,
724
+ rejected: EventIds,
725
+ selfWakes: Schema.Number
726
+ });
727
+ var ThreadViewSchema = Schema.Struct({
728
+ items: Schema.Array(Schema.Struct({
729
+ id: EventId,
730
+ sender: Sender,
731
+ blocks: Schema.Array(ContentBlock.Any),
732
+ created: Schema.String,
733
+ thread: Schema.optional(ThreadId),
734
+ lane: Schema.optional(ThreadId),
735
+ status: Schema.Literals([
736
+ "queued",
737
+ "consumed",
738
+ "cancelled",
739
+ "sent",
740
+ "rewound"
741
+ ])
742
+ })),
743
+ lanes: Schema.Array(Schema.Struct({
744
+ id: ThreadId,
745
+ kind: Schema.Literals([
746
+ "turn",
747
+ "fork",
748
+ "fresh",
749
+ "light"
750
+ ]),
751
+ from: Schema.optional(EventId),
752
+ merged: Schema.optional(MergeMode),
753
+ status: Schema.Literals([
754
+ "running",
755
+ "waiting",
756
+ "done",
757
+ "failed"
758
+ ]),
759
+ owner: Sender,
760
+ created: Schema.String,
761
+ purpose: Schema.optional(Schema.String),
762
+ waitingOn: Schema.optional(ThreadId),
763
+ overlapped: Schema.optional(Schema.Boolean),
764
+ backgrounded: Schema.optional(Schema.Boolean)
765
+ })),
766
+ laneOf: Schema.Record(ThreadId, ThreadId)
767
+ });
768
+ var PromptEntrySchema = Schema.Struct({
769
+ role: Role,
770
+ name: Schema.optional(Schema.String),
771
+ blocks: Schema.Array(ContentBlock.Any),
772
+ source: EventIds,
773
+ at: Schema.Number,
774
+ ephemeral: Schema.optional(Schema.Boolean)
775
+ });
776
+ var PromptStateSchema = Schema.Struct({
777
+ entries: Schema.Array(PromptEntrySchema),
778
+ held: Schema.Record(Schema.String, PromptEntrySchema),
779
+ threads: Schema.Record(Schema.String, Schema.Struct({
780
+ parent: Schema.optional(ThreadId),
781
+ mode: Schema.optional(ThreadMode),
782
+ fresh: Schema.Boolean,
783
+ seen: Schema.Number,
784
+ closed: Schema.optional(Schema.Boolean),
785
+ purpose: Schema.optional(Schema.String),
786
+ owner: Schema.optional(Schema.String),
787
+ entries: Schema.Array(PromptEntrySchema)
788
+ })),
789
+ position: Schema.Number,
790
+ positions: Schema.Record(EventId, Schema.Number).pipe(Schema.decodeTo(Schema.HashMap(EventId, Schema.Number), SchemaTransformation.transform({
791
+ decode: (record) => HashMap.fromIterable(Object.entries(record)),
792
+ encode: (positions) => Object.fromEntries(positions)
793
+ }))),
794
+ stale: Schema.Record(Schema.String, EventIds),
795
+ origin: Schema.optional(ThreadOrigin)
796
+ });
797
+ var session = {
798
+ ...sessionFold,
799
+ id: "session@3",
800
+ schema: SessionStateSchema,
801
+ rebind: (state, makeRef) => ({
802
+ ...state,
803
+ skills: state.skills.map((ref) => makeRef(ref)),
804
+ objects: state.objects.map((ref) => makeRef(ref))
805
+ })
806
+ };
807
+ var thread = {
808
+ ...threadFold,
809
+ id: "thread@5",
810
+ schema: ThreadViewSchema
811
+ };
812
+ var prompt = {
813
+ ...promptFold,
814
+ id: "prompt@3",
815
+ schema: PromptStateSchema,
816
+ rebind: (state, makeRef) => state.origin?.feed ? {
817
+ ...state,
818
+ origin: {
819
+ ...state.origin,
820
+ feed: makeRef(state.origin.feed)
821
+ }
822
+ } : state
823
+ };
824
+ //#endregion
825
+ export { session as a, run as i, prompt as n, thread as o, promptFor as r, Reducer_exports as t };
826
+
827
+ //# sourceMappingURL=chunk-Reducer.mjs.map