effect-durable-agent 0.1.0-alpha.9 → 0.2.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 (181) hide show
  1. package/README.md +5 -5
  2. package/dist/assert-never-CoyUpoRB.js +18 -0
  3. package/dist/assert-never-CoyUpoRB.js.map +1 -0
  4. package/dist/{commands-Ce1ec6kH.d.ts → commands-BUquEZVP.d.ts} +31 -12
  5. package/dist/{compaction-BgDr5VJy.js → compaction-D7WJa899.js} +63 -13
  6. package/dist/compaction-D7WJa899.js.map +1 -0
  7. package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-Bezx3drD.d.ts} +16 -40
  8. package/dist/{core-CYT6DBaS.d.ts → core-BcimKMIv.d.ts} +5 -3
  9. package/dist/delivery-B_LDTuIB.d.ts +3169 -0
  10. package/dist/delivery-BoF-NZbZ.js +507 -0
  11. package/dist/delivery-BoF-NZbZ.js.map +1 -0
  12. package/dist/domain/command-queues.d.ts +81 -2
  13. package/dist/domain/command-queues.js +1 -1
  14. package/dist/domain/command-queues.js.map +1 -1
  15. package/dist/domain/context-projection.d.ts +1 -1
  16. package/dist/domain/context-projection.js +1 -1
  17. package/dist/domain/context-projection.js.map +1 -1
  18. package/dist/domain/message-transcript.d.ts +36 -2
  19. package/dist/domain/message-transcript.js +10 -2
  20. package/dist/domain/message-transcript.js.map +1 -1
  21. package/dist/domain/model-usage.d.ts +1 -1
  22. package/dist/domain/model-usage.js +1 -1
  23. package/dist/domain/reduced-state-schema.d.ts +3 -992
  24. package/dist/domain/reduced-state-schema.js +126 -7
  25. package/dist/domain/reduced-state-schema.js.map +1 -1
  26. package/dist/domain/reduced-state.d.ts +2 -2
  27. package/dist/domain/reduced-state.js +937 -2
  28. package/dist/domain/reduced-state.js.map +1 -0
  29. package/dist/domain/run-scheduling.d.ts +2 -0
  30. package/dist/domain/run-scheduling.js +127 -0
  31. package/dist/domain/run-scheduling.js.map +1 -0
  32. package/dist/{durable-br2C1bWK.d.ts → durable-BXqwM70o.d.ts} +8983 -2800
  33. package/dist/{durable-BGFvX7Mh.js → durable-Da57Rcml.js} +243 -15
  34. package/dist/durable-Da57Rcml.js.map +1 -0
  35. package/dist/{envelope-DxQzo5rN.js → envelope-BSI_Xh-f.js} +31 -6
  36. package/dist/envelope-BSI_Xh-f.js.map +1 -0
  37. package/dist/{envelope-DkZyMIgp.d.ts → envelope-CJnPfbjC.d.ts} +121 -11
  38. package/dist/{event-factory-DTFdy0Cb.js → event-factory-BUoBwqAy.js} +7 -3
  39. package/dist/event-factory-BUoBwqAy.js.map +1 -0
  40. package/dist/{events-LZFNoESe.d.ts → events-AIIwZ6dS.d.ts} +139 -137
  41. package/dist/{id-generator-Ckl8_XWW.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
  42. package/dist/in-memory-E497WhtS.js +150 -0
  43. package/dist/in-memory-E497WhtS.js.map +1 -0
  44. package/dist/index.d.ts +8 -8
  45. package/dist/index.js +6 -6
  46. package/dist/interpreter-BwYN2PCC.js +1453 -0
  47. package/dist/interpreter-BwYN2PCC.js.map +1 -0
  48. package/dist/{keep-alive-Chl5SJxy.d.ts → keep-alive-_zFCUvt3.d.ts} +1 -2
  49. package/dist/{model-resolver-BPPJAsuh.d.ts → model-resolver-O8Kn27GH.d.ts} +11 -5
  50. package/dist/{model-usage-CdBEkTwU.d.ts → model-usage-mttrPN0j.d.ts} +2 -3
  51. package/dist/records-D0ZIAOzd.js +675 -0
  52. package/dist/records-D0ZIAOzd.js.map +1 -0
  53. package/dist/reduced-state-YbjpihEf.d.ts +52933 -0
  54. package/dist/reduced-state-schema-B9TYxkP9.d.ts +2338 -0
  55. package/dist/{reducer-registry-aFjz_ZLT.d.ts → reducer-registry-Bqn5B4JO.d.ts} +12 -6
  56. package/dist/run-scheduling-wakeup-DX2zRAxd.d.ts +24 -0
  57. package/dist/services/compaction.d.ts +2 -2
  58. package/dist/services/compaction.js +2 -2
  59. package/dist/services/decider.d.ts +2 -0
  60. package/dist/services/decider.js +97 -0
  61. package/dist/services/decider.js.map +1 -0
  62. package/dist/services/id-generator.d.ts +1 -1
  63. package/dist/services/id-generator.js +6 -12
  64. package/dist/services/id-generator.js.map +1 -1
  65. package/dist/services/keep-alive.d.ts +1 -1
  66. package/dist/services/keep-alive.js.map +1 -1
  67. package/dist/services/model-call.d.ts +15 -0
  68. package/dist/services/model-call.js +15 -0
  69. package/dist/services/model-call.js.map +1 -0
  70. package/dist/services/model-resolver.d.ts +1 -1
  71. package/dist/services/model-resolver.js +1 -1
  72. package/dist/services/model-resolver.js.map +1 -1
  73. package/dist/services/prompt-projector.d.ts +2 -2
  74. package/dist/services/prompt-projector.js +49 -5
  75. package/dist/services/prompt-projector.js.map +1 -1
  76. package/dist/services/reducer-registry.d.ts +1 -1
  77. package/dist/services/reducer-registry.js +19 -6
  78. package/dist/services/reducer-registry.js.map +1 -1
  79. package/dist/services/run-scheduler.d.ts +2 -2
  80. package/dist/services/run-scheduler.js +25 -2
  81. package/dist/services/run-scheduler.js.map +1 -0
  82. package/dist/services/run-scheduling-wakeup.d.ts +2 -0
  83. package/dist/services/run-scheduling-wakeup.js +13 -0
  84. package/dist/services/run-scheduling-wakeup.js.map +1 -0
  85. package/dist/services/runtime-layer.d.ts +21 -33
  86. package/dist/services/runtime-layer.js +24 -16
  87. package/dist/services/runtime-layer.js.map +1 -1
  88. package/dist/services/runtime.d.ts +1 -1
  89. package/dist/services/runtime.js +32 -20
  90. package/dist/services/runtime.js.map +1 -1
  91. package/dist/services/session-event-observer.d.ts +1 -1
  92. package/dist/services/session-event-observer.js.map +1 -1
  93. package/dist/services/session-query.d.ts +1 -1
  94. package/dist/services/session-query.js +57 -10
  95. package/dist/services/session-query.js.map +1 -1
  96. package/dist/services/session-state.d.ts +2 -2
  97. package/dist/services/session-state.js +2 -1
  98. package/dist/services/session-store.d.ts +2 -2
  99. package/dist/services/session-store.js +143 -38
  100. package/dist/services/session-store.js.map +1 -1
  101. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  102. package/dist/services/sink-checkpoint-store.js +2 -1
  103. package/dist/services/sink-checkpoint-store.js.map +1 -1
  104. package/dist/services/sink-registry.d.ts +2 -2
  105. package/dist/services/sink-registry.js +1 -1
  106. package/dist/services/span-names.d.ts +1 -1
  107. package/dist/services/span-names.js +7 -1
  108. package/dist/services/span-names.js.map +1 -1
  109. package/dist/services/tool-registry.d.ts +2 -2
  110. package/dist/services/tool-registry.js +12 -3
  111. package/dist/services/tool-registry.js.map +1 -1
  112. package/dist/services/tracing.d.ts +3 -3
  113. package/dist/services/tracing.js +2 -2
  114. package/dist/services/tracing.js.map +1 -1
  115. package/dist/session-admission-WE8J_0z9.js +138 -0
  116. package/dist/session-admission-WE8J_0z9.js.map +1 -0
  117. package/dist/{session-event-observer-DaFMKKNc.d.ts → session-event-observer-BWQUJTcN.d.ts} +3 -3
  118. package/dist/{session-state-Bkc6u-Wr.js → session-state-D02LCVcC.js} +815 -170
  119. package/dist/session-state-D02LCVcC.js.map +1 -0
  120. package/dist/session-store-DaSHeg8Q.d.ts +3343 -0
  121. package/dist/{sink-checkpoint-store-M7qIxoSH.d.ts → sink-checkpoint-store-CUvIVvlZ.d.ts} +3 -4
  122. package/dist/sink-registry-AOjX5_A1.js +369 -0
  123. package/dist/sink-registry-AOjX5_A1.js.map +1 -0
  124. package/dist/subscription-BhwUmsl4.d.ts +966 -0
  125. package/dist/subscription-D7U4Tziv.js +505 -0
  126. package/dist/subscription-D7U4Tziv.js.map +1 -0
  127. package/dist/testkit/layers.d.ts +33 -23
  128. package/dist/testkit/layers.js +34 -19
  129. package/dist/testkit/layers.js.map +1 -1
  130. package/dist/testkit/transcript.d.ts +232 -0
  131. package/dist/testkit/transcript.js +1526 -0
  132. package/dist/testkit/transcript.js.map +1 -0
  133. package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
  134. package/dist/transcript.d.ts +101 -0
  135. package/dist/transcript.js +107 -0
  136. package/dist/transcript.js.map +1 -0
  137. package/dist/types/commands.d.ts +2 -2
  138. package/dist/types/commands.js +8 -3
  139. package/dist/types/commands.js.map +1 -1
  140. package/dist/types/core.d.ts +2 -2
  141. package/dist/types/core.js +3 -1
  142. package/dist/types/core.js.map +1 -1
  143. package/dist/types/events/durable.d.ts +2 -2
  144. package/dist/types/events/durable.js +2 -2
  145. package/dist/types/events.d.ts +5 -5
  146. package/dist/types/events.js +3 -3
  147. package/dist/types/tracing.d.ts +1 -1
  148. package/dist/types/tracing.js.map +1 -1
  149. package/dist/websocket/events.d.ts +2 -0
  150. package/dist/websocket/events.js +2 -0
  151. package/dist/websocket.d.ts +2123 -2552
  152. package/dist/websocket.js +628 -442
  153. package/dist/websocket.js.map +1 -1
  154. package/dist/window-read-BELSkO-r.d.ts +113 -0
  155. package/dist/window-read-FJTCDaSq.js +264 -0
  156. package/dist/window-read-FJTCDaSq.js.map +1 -0
  157. package/package.json +41 -13
  158. package/dist/command-queues-DdDB_aYM.d.ts +0 -462
  159. package/dist/compaction-BgDr5VJy.js.map +0 -1
  160. package/dist/compaction-ch8z6G9x.d.ts +0 -165
  161. package/dist/durable-BGFvX7Mh.js.map +0 -1
  162. package/dist/envelope-DxQzo5rN.js.map +0 -1
  163. package/dist/event-factory-DTFdy0Cb.js.map +0 -1
  164. package/dist/event-factory-Di1jwQvm.d.ts +0 -87
  165. package/dist/index-BVVgDSdq.d.ts +0 -1
  166. package/dist/message-transcript-DQNlzxle.d.ts +0 -32
  167. package/dist/prompt-projector-f4ElyXCE.d.ts +0 -39
  168. package/dist/reduced-state-DF0-6mbR.js +0 -921
  169. package/dist/reduced-state-DF0-6mbR.js.map +0 -1
  170. package/dist/run-scheduler-CAt7dF6C.js +0 -21
  171. package/dist/run-scheduler-CAt7dF6C.js.map +0 -1
  172. package/dist/run-scheduler-xkhZyto5.d.ts +0 -44
  173. package/dist/runtime-DDSYP9jS.d.ts +0 -63
  174. package/dist/session-query-B72HY_0L.d.ts +0 -45
  175. package/dist/session-state-Bkc6u-Wr.js.map +0 -1
  176. package/dist/session-state-C9YLSAso.d.ts +0 -862
  177. package/dist/session-store-Cpi_NwTR.d.ts +0 -206
  178. package/dist/sink-registry-Bl-vQES6.d.ts +0 -133
  179. package/dist/sink-registry-NDgeyzO0.js +0 -272
  180. package/dist/sink-registry-NDgeyzO0.js.map +0 -1
  181. package/dist/tool-registry-BJaVNtw4.d.ts +0 -51
@@ -0,0 +1,1453 @@
1
+ import { CommandId } from "./types/core.js";
2
+ import { _ as UnixEpochMillis, c as FailurePayload, g as ToolName, m as SchemaVersion, p as ProviderPartId, u as ModelSelectionPayload } from "./envelope-BSI_Xh-f.js";
3
+ import { addModelUsage } from "./domain/model-usage.js";
4
+ import { CommandIdempotencyKey } from "./types/commands.js";
5
+ import { $n as inferenceStartedEventType, An as assistantMessageImportedEventType, Ar as userMessagePromotedEventType, Bn as compactionCompletedEventType, Cr as toolCallStartedEventType, Dr as turnStoppedEventType, Er as turnStartedEventType, Fn as commandAdmittedEventType, Gn as contextRebasedEventType, Hn as compactionRequestedEventType, In as commandCancelledEventType, Kn as deciderAcceptedEventType, Ln as commandCompletedEventType, Mn as baseStateCreatedEventType, Nn as baseStateFailedEventType, Or as userMessageCancelledEventType, Pn as baseStateRequestedEventType, Qn as inferenceFailedEventType, Rn as commandFailedEventType, Sr as toolCallRejectedEventType, Tr as turnFailedEventType, Un as compactionStartedEventType, Vn as compactionFailedEventType, Wn as contextProjectedEventType, Zn as inferenceCompletedEventType, _r as summaryCreatedEventType, ar as runFailedEventType, br as toolCallCreatedEventType, cr as runSchedulingGrantedEventType, dr as runStartedEventType, er as interpretLegacyAttemptForReduction, fr as sessionConfiguredEventType, gr as stopTurnRequestedEventType, hr as stopTurnAppliedEventType, ir as runCompletedEventType, jn as assistantPartialCommittedEventType, jr as userMessageSubmittedEventType, kn as assistantMessageCommittedEventType, kr as userMessageCommittedEventType, lr as runSchedulingInvalidatedEventType, mr as steeringMessageQueuedEventType, nr as pendingMessagesPausedEventType, or as runInterruptedEventType, pr as steeringMessageCancelledEventType, rr as recoveryCompletedEventType, sr as runSchedulingDeliveredEventType, tr as messageQueuePausedEventType, ur as runSchedulingRequestedEventType, vr as systemMessageCommittedEventType, wr as turnCompletedEventType, xr as toolCallFailedEventType, yr as toolCallCompletedEventType, zn as commandStartedEventType } from "./durable-Da57Rcml.js";
6
+ import { t as assertNever } from "./assert-never-CoyUpoRB.js";
7
+ import { A as TranscriptRecordFromEnvelope, H as TranscriptVersion, K as runGroupStatus, O as TranscriptRecord, S as TranscriptDecorationKey, Y as transcriptRecordId, Z as sha256Hex, b as TranscriptDecorationEntryId, h as TranscriptClassification, w as TranscriptFieldPath } from "./records-D0ZIAOzd.js";
8
+ import * as Effect from "effect/Effect";
9
+ import * as Schema from "effect/Schema";
10
+ //#region src/transcript/body.ts
11
+ const bodyEncoder = new TextEncoder();
12
+ /**
13
+ * A body value normalized to the JSON a persisted log holds: what the interpreter inlines and what
14
+ * a reference resolves to, so the two can never disagree. A value with no JSON text (`undefined`,
15
+ * a function) is `null`; a value with no JSON form at all (a bigint, a cycle) is `undefined`.
16
+ */
17
+ const normalizeTranscriptBodyValue = (value) => {
18
+ let json;
19
+ try {
20
+ json = JSON.stringify(value);
21
+ } catch {
22
+ return;
23
+ }
24
+ const normalized = json === void 0 ? null : JSON.parse(json);
25
+ if (!Schema.is(Schema.Json)(normalized)) return void 0;
26
+ return {
27
+ value: normalized,
28
+ byteLength: json === void 0 ? 4 : bodyEncoder.encode(json).length
29
+ };
30
+ };
31
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
32
+ /** An own property, or `undefined`: never an inherited name such as `toString`. */
33
+ const own = (value, key) => isRecord(value) && Object.prototype.hasOwnProperty.call(value, key) ? Reflect.get(value, key) : void 0;
34
+ const assistantEventTypes = /* @__PURE__ */ new Set([
35
+ assistantMessageCommittedEventType,
36
+ assistantPartialCommittedEventType,
37
+ assistantMessageImportedEventType
38
+ ]);
39
+ /**
40
+ * The value at a body site of a framework event, or `undefined` when `path` names no body.
41
+ *
42
+ * The interpreter creates bodies at exactly three sites: tool parameters
43
+ * (`ToolCallCreated` `promptPart.params`), tool results (`ToolCallCompleted` `promptPart.result`)
44
+ * and provider-executed tool results inside assistant output (`promptParts[i].result` of a
45
+ * well-formed `tool-result` part). Nothing else in the log is a body, so a reference can never
46
+ * reach a system prompt, a command input or an app event.
47
+ */
48
+ const bodySiteValue = (event, path) => {
49
+ if (event.namespace !== "effect-durable-agent") return void 0;
50
+ const [first, second, third, ...rest] = path;
51
+ if (rest.length > 0) return void 0;
52
+ if (event.type === toolCallCreatedEventType || event.type === toolCallCompletedEventType) {
53
+ const field = event.type === toolCallCreatedEventType ? "params" : "result";
54
+ const promptPart = own(event.payload, "promptPart");
55
+ return first === "promptPart" && second === field && third === void 0 && isRecord(promptPart) ? { value: own(promptPart, field) } : void 0;
56
+ }
57
+ if (!assistantEventTypes.has(event.type)) return void 0;
58
+ if (first !== "promptParts" || typeof second !== "number" || third !== "result") return void 0;
59
+ const parts = own(event.payload, "promptParts");
60
+ const part = Array.isArray(parts) ? parts[second] : void 0;
61
+ return own(part, "type") === "tool-result" && Schema.is(ProviderPartId)(own(part, "id")) && Schema.is(ToolName)(own(part, "name")) ? { value: own(part, "result") } : void 0;
62
+ };
63
+ /**
64
+ * Resolve a body reference against the committed event it names: the read side of the
65
+ * interpreter's body rule. Resolving through the log keeps a `Ref` valid after projection rows are
66
+ * rebuilt or deleted; any path that is not a body site resolves to nothing.
67
+ */
68
+ const resolveTranscriptBody = (event, path) => {
69
+ const site = bodySiteValue(event, path);
70
+ if (site === void 0) return {
71
+ _tag: "Missing",
72
+ message: "the path names no transcript body"
73
+ };
74
+ const normalized = normalizeTranscriptBodyValue(site.value);
75
+ return normalized === void 0 ? {
76
+ _tag: "Missing",
77
+ message: "the body has no JSON form"
78
+ } : {
79
+ _tag: "Found",
80
+ value: normalized.value
81
+ };
82
+ };
83
+ //#endregion
84
+ //#region src/transcript/version.ts
85
+ /**
86
+ * EDA's transcript semantic revision.
87
+ *
88
+ * Bump it deliberately whenever the interpreter, the legacy-attempt normalizer, the record
89
+ * decoders or the mapping executor would interpret any existing log differently. A bump changes
90
+ * every transcript version, so every session rebuilds and every host must run its backfill.
91
+ * A new durable event type needs a bump only if this release gives it transcript meaning;
92
+ * events the interpreter ignores leave the revision and every version unchanged.
93
+ *
94
+ * A CI fingerprint over a fixed scenario corpus (added with the interpreter) fails when
95
+ * interpretation output changes and this constant does not; re-record it together with the bump.
96
+ *
97
+ * History: 1 — the initial interpreter (0.1.0-alpha.22). 2 — submissions consumed by one turn are
98
+ * ordered by submission, as the prompt orders them, not by the turn's input list.
99
+ */
100
+ const transcriptSemanticRevision = 2;
101
+ /**
102
+ * Deterministic JSON: object keys sorted by code unit, no whitespace. Only JSON values are
103
+ * accepted, so equal data always produces equal bytes.
104
+ */
105
+ const canonicalJson = (value) => {
106
+ if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
107
+ if (typeof value === "number") {
108
+ if (!Number.isFinite(value)) throw new Error(`canonicalJson cannot encode non-finite number ${value}`);
109
+ return JSON.stringify(value);
110
+ }
111
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
112
+ if (typeof value === "object") {
113
+ const entries = Object.entries(value).filter(([, entry]) => entry !== void 0);
114
+ entries.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
115
+ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
116
+ }
117
+ throw new Error(`canonicalJson cannot encode ${typeof value}`);
118
+ };
119
+ /** Transcript version for a semantic revision and already-encoded canonical mapping data. */
120
+ const computeTranscriptVersion = (semanticRevision, encodedMappings) => TranscriptVersion.make(sha256Hex(canonicalJson({
121
+ semanticRevision,
122
+ mappings: encodedMappings
123
+ })));
124
+ //#endregion
125
+ //#region src/transcript/mapping.ts
126
+ /**
127
+ * Host decorations are data, not code. A host registers mappings from its own durable app events
128
+ * to decorations on transcript records; EDA validates them at registration and executes them
129
+ * with fixed bounds inside the projection.
130
+ */
131
+ /** Bounds EDA enforces on every definition and every decoration it executes. */
132
+ const transcriptMappingBounds = {
133
+ maxMappings: 64,
134
+ maxOperationsPerMapping: 16,
135
+ maxPathLength: 16,
136
+ /** Canonical JSON bytes of one decoration value or list entry. */
137
+ maxValueBytes: 8192,
138
+ /**
139
+ * Canonical JSON bytes of all decorations of one record, and of one decoration buffer. An
140
+ * operation that would exceed it is skipped, so no record's row can approach storage value
141
+ * limits whatever a host appends.
142
+ */
143
+ maxDecorationBytes: 262144,
144
+ /** Entries kept in one decoration list; further distinct entries are dropped. */
145
+ maxListEntries: 64,
146
+ maxUserFallbacks: 16
147
+ };
148
+ const MappingPath = TranscriptFieldPath.check(Schema.isMaxLength(transcriptMappingBounds.maxPathLength));
149
+ /** The app event a mapping reads: one host namespace, type and schema version. */
150
+ const TranscriptMappedEvent = Schema.Struct({
151
+ namespace: Schema.NonEmptyString,
152
+ type: Schema.NonEmptyString,
153
+ schemaVersion: SchemaVersion
154
+ });
155
+ /**
156
+ * Which record a mapping decorates.
157
+ *
158
+ * User targets associate through a payload field: the submitting command's id, or the
159
+ * command's idempotency key. A decoration that arrives before its target user record is held
160
+ * and applied, in arrival order, when the record is created. `Session` decorates the
161
+ * session-context singleton.
162
+ */
163
+ const TranscriptMappingTarget = Schema.TaggedUnion({
164
+ UserByCommandId: { path: MappingPath },
165
+ UserByIdempotencyKey: { path: MappingPath },
166
+ Session: {}
167
+ });
168
+ /** How a list entry is identified when it is replaced. */
169
+ const TranscriptListEntryKey = Schema.TaggedUnion({
170
+ /** A string id at this payload path (for example an attachment id). */
171
+ Id: { path: MappingPath },
172
+ /** A non-negative integer ordinal at this payload path; the list is kept in ordinal order. */
173
+ Ordinal: { path: MappingPath },
174
+ /**
175
+ * An id and an ordinal; the list is kept in ordinal order. A new entry replaces every entry with
176
+ * the same id **or** the same ordinal, so an input retried with new ids, or in a different
177
+ * order, never leaves a stale duplicate (attachments and references keyed by both).
178
+ */
179
+ IdOrOrdinal: {
180
+ id: MappingPath,
181
+ ordinal: MappingPath
182
+ }
183
+ });
184
+ /** One declarative decoration operation. Every `from` path reads the authenticated event payload. */
185
+ const TranscriptMappingOperation = Schema.TaggedUnion({
186
+ /** Copy a payload value into a decoration; the latest event wins. */
187
+ Copy: {
188
+ from: MappingPath,
189
+ to: TranscriptDecorationKey
190
+ },
191
+ /** Copy a payload value into a decoration only if the decoration is still absent. */
192
+ FirstWins: {
193
+ from: MappingPath,
194
+ to: TranscriptDecorationKey
195
+ },
196
+ /** Insert or replace one entry of a decoration list, keyed by id, ordinal, or either. */
197
+ ReplaceListEntry: {
198
+ from: MappingPath,
199
+ to: TranscriptDecorationKey,
200
+ key: TranscriptListEntryKey
201
+ },
202
+ /**
203
+ * Classify the target user record, for example as an authenticated subagent notice. A record
204
+ * holds one classification; the last one applied wins.
205
+ */
206
+ Classify: { classification: TranscriptClassification }
207
+ });
208
+ /** One host mapping: an app event, the record it decorates, and the operations to apply. */
209
+ const TranscriptMapping = Schema.Struct({
210
+ /** Unique name; buffered decorations refer to it. */
211
+ name: TranscriptDecorationKey,
212
+ event: TranscriptMappedEvent,
213
+ target: TranscriptMappingTarget,
214
+ operations: Schema.NonEmptyArray(TranscriptMappingOperation).check(Schema.isMaxLength(transcriptMappingBounds.maxOperationsPerMapping))
215
+ });
216
+ /**
217
+ * A user decoration copied from a session decoration when the user record is created without
218
+ * it, for example "the most recent author" for a message whose command carried no author event.
219
+ *
220
+ * Fallbacks apply in declaration order, after any parked decorations, and each one applies only
221
+ * if the user decoration is still absent; so `[author ← lastAuthor, author ← owner]` means "the
222
+ * latest author, else the session owner".
223
+ */
224
+ const TranscriptUserFallback = Schema.Struct({
225
+ to: TranscriptDecorationKey,
226
+ fromSession: TranscriptDecorationKey
227
+ });
228
+ /** The host's complete declarative transcript mapping data. */
229
+ const TranscriptMappings = Schema.Struct({
230
+ mappings: Schema.Array(TranscriptMapping).check(Schema.isMaxLength(transcriptMappingBounds.maxMappings)),
231
+ userFallbacks: Schema.Array(TranscriptUserFallback).check(Schema.isMaxLength(transcriptMappingBounds.maxUserFallbacks))
232
+ });
233
+ /** Mappings for a host that registers no decorations. */
234
+ const emptyTranscriptMappings = {
235
+ mappings: [],
236
+ userFallbacks: []
237
+ };
238
+ /** Host mapping data rejected at registration. */
239
+ var TranscriptDefinitionError = class extends Schema.TaggedError()("TranscriptDefinitionError", { message: Schema.String }) {};
240
+ const validationProblems = (mappings) => {
241
+ const problems = [];
242
+ const names = /* @__PURE__ */ new Set();
243
+ const shapes = /* @__PURE__ */ new Map();
244
+ const sessionValueKeys = /* @__PURE__ */ new Set();
245
+ const recordShape = (scope, key, shape) => {
246
+ const scoped = `${scope}:${key}`;
247
+ const existing = shapes.get(scoped);
248
+ if (existing !== void 0 && existing !== shape) problems.push(`${scope} decoration "${key}" is written as both ${existing} and ${shape}`);
249
+ shapes.set(scoped, shape);
250
+ };
251
+ for (const mapping of mappings.mappings) {
252
+ if (names.has(mapping.name)) problems.push(`duplicate mapping name "${mapping.name}"`);
253
+ names.add(mapping.name);
254
+ if (mapping.event.namespace === "effect-durable-agent" || mapping.event.namespace === "__foreign") problems.push(`mapping "${mapping.name}" may not read namespace ${mapping.event.namespace}`);
255
+ const scope = mapping.target._tag === "Session" ? "session" : "user";
256
+ for (const operation of mapping.operations) switch (operation._tag) {
257
+ case "Copy":
258
+ case "FirstWins":
259
+ recordShape(scope, operation.to, operation._tag === "Copy" ? "copy" : "first-wins");
260
+ if (scope === "session") sessionValueKeys.add(operation.to);
261
+ break;
262
+ case "ReplaceListEntry":
263
+ recordShape(scope, operation.to, `list:${operation.key._tag}`);
264
+ break;
265
+ case "Classify": if (scope === "session") problems.push(`mapping "${mapping.name}" classifies the session; only users can be classified`);
266
+ }
267
+ }
268
+ const fallbacks = /* @__PURE__ */ new Set();
269
+ for (const fallback of mappings.userFallbacks) {
270
+ const key = `${fallback.to}\u0000${fallback.fromSession}`;
271
+ if (fallbacks.has(key)) problems.push(`duplicate user fallback ${fallback.to} <- ${fallback.fromSession}`);
272
+ fallbacks.add(key);
273
+ if (!sessionValueKeys.has(fallback.fromSession)) problems.push(`user fallback reads session decoration "${fallback.fromSession}", which no mapping writes as a value`);
274
+ const userShape = shapes.get(`user:${fallback.to}`);
275
+ if (userShape !== void 0 && userShape.startsWith("list:")) problems.push(`user fallback writes "${fallback.to}", which is a list decoration`);
276
+ }
277
+ return problems;
278
+ };
279
+ /**
280
+ * A validated transcript interpretation: EDA's semantic revision plus host mappings, identified
281
+ * by `version`. Only `makeTranscriptDefinition` constructs one.
282
+ */
283
+ var TranscriptDefinition = class TranscriptDefinition {
284
+ version;
285
+ semanticRevision;
286
+ mappings;
287
+ constructor(version, semanticRevision, mappings) {
288
+ this.version = version;
289
+ this.semanticRevision = semanticRevision;
290
+ this.mappings = mappings;
291
+ }
292
+ /**
293
+ * Validate host mapping data and derive its transcript version.
294
+ *
295
+ * Validation happens here, at registration, never during append: an accepted definition can
296
+ * only degrade individual decorations at runtime (a missing field, an oversize value), never
297
+ * event admission or other records.
298
+ */
299
+ static make = Effect.fnUntraced(function* (input) {
300
+ const mappings = yield* Schema.decodeUnknownEffect(TranscriptMappings)(input).pipe(Effect.mapError((error) => new TranscriptDefinitionError({ message: error.message })));
301
+ const problems = validationProblems(mappings);
302
+ if (problems.length > 0) return yield* new TranscriptDefinitionError({ message: problems.join("; ") });
303
+ return new TranscriptDefinition(computeTranscriptVersion(2, Schema.encodeSync(TranscriptMappings)(mappings)), 2, mappings);
304
+ });
305
+ };
306
+ /** Validate host mapping data and derive its transcript version; see `TranscriptDefinition.make`. */
307
+ const makeTranscriptDefinition = TranscriptDefinition.make;
308
+ //#endregion
309
+ //#region src/transcript/plan.ts
310
+ /**
311
+ * Secondary keys that resolve to a record through an indexed join, never an in-memory map.
312
+ *
313
+ * - `messageId`: every message id a user submission has carried, including replacement ids.
314
+ * - `idempotencyKey`: a submitting command's caller-owned retry key.
315
+ * - `runId`: every run of a run group, so continuations resolve to the root's group.
316
+ * - `runCommand`: commands owned by a run group; a run that reuses them continues the group.
317
+ * - `toolPart`: `<inferenceId>/<providerPartId>`, linking an assistant tool-call part to its tool.
318
+ */
319
+ const TranscriptAliasNamespace = Schema.Literals([
320
+ "messageId",
321
+ "idempotencyKey",
322
+ "runId",
323
+ "runCommand",
324
+ "toolPart"
325
+ ]);
326
+ /** The stored projection cannot be advanced from the given lookup and batch. */
327
+ var TranscriptProjectionError = class extends Schema.TaggedError()("TranscriptProjectionError", { message: Schema.String }) {};
328
+ //#endregion
329
+ //#region src/transcript/mapping-executor.ts
330
+ const indexes = /* @__PURE__ */ new WeakMap();
331
+ const eventKey = (namespace, type, schemaVersion) => `${namespace}\u0000${type}\u0000${schemaVersion}`;
332
+ const mappingIndex = (definition) => {
333
+ const cached = indexes.get(definition);
334
+ if (cached !== void 0) return cached;
335
+ const byEvent = /* @__PURE__ */ new Map();
336
+ const byName = /* @__PURE__ */ new Map();
337
+ for (const mapping of definition.mappings.mappings) {
338
+ const key = eventKey(mapping.event.namespace, mapping.event.type, mapping.event.schemaVersion);
339
+ byEvent.set(key, [...byEvent.get(key) ?? [], mapping]);
340
+ byName.set(mapping.name, mapping);
341
+ }
342
+ const index = {
343
+ byEvent,
344
+ byName
345
+ };
346
+ indexes.set(definition, index);
347
+ return index;
348
+ };
349
+ /** Apply every mapping that names this app event. Unmapped events are ignored. */
350
+ const applyForeignEvent = (batch, envelope, seq) => {
351
+ const mappings = mappingIndex(batch.definition).byEvent.get(eventKey(envelope.namespace, envelope.type, envelope.schemaVersion));
352
+ for (const mapping of mappings ?? []) applyMapping(batch, mapping, envelope.payload, seq);
353
+ };
354
+ const applyMapping = (batch, mapping, payload, seq) => {
355
+ const prepared = mapping.operations.flatMap((operation, index) => prepareOperation(mapping.name, operation, index, payload));
356
+ if (prepared.length === 0) return;
357
+ const target = mapping.target;
358
+ switch (target._tag) {
359
+ case "Session": {
360
+ const session = batch.session(seq);
361
+ const applied = prepared.reduce((decorated, operation) => applyPrepared(batch.definition, decorated, operation), { decorations: session.decorations });
362
+ batch.put({
363
+ ...session,
364
+ updatedSeq: seq,
365
+ decorations: applied.decorations
366
+ });
367
+ return;
368
+ }
369
+ case "UserByCommandId": {
370
+ const commandId = extract(payload, target.path);
371
+ if (!Schema.is(CommandId)(commandId)) return;
372
+ const user = batch.user(transcriptRecordId.user(commandId));
373
+ if (user === void 0) park(batch, seq, "command", commandId, prepared);
374
+ else batch.put(decorateUser(batch.definition, {
375
+ ...user,
376
+ updatedSeq: seq
377
+ }, prepared));
378
+ return;
379
+ }
380
+ case "UserByIdempotencyKey": {
381
+ const key = extract(payload, target.path);
382
+ if (!Schema.is(CommandIdempotencyKey)(key)) return;
383
+ const userId = batch.alias("idempotencyKey", key);
384
+ const user = userId === void 0 ? void 0 : batch.user(userId);
385
+ if (user === void 0) park(batch, seq, "idempotencyKey", key, prepared);
386
+ else batch.put(decorateUser(batch.definition, {
387
+ ...user,
388
+ updatedSeq: seq
389
+ }, prepared));
390
+ return;
391
+ }
392
+ }
393
+ };
394
+ const prepareOperation = (mapping, operation, index, payload) => {
395
+ switch (operation._tag) {
396
+ case "Classify": return [{
397
+ mapping,
398
+ operation: index,
399
+ value: null
400
+ }];
401
+ case "Copy":
402
+ case "FirstWins": {
403
+ const value = boundedJson(extract(payload, operation.from));
404
+ return value === void 0 ? [] : [{
405
+ mapping,
406
+ operation: index,
407
+ value
408
+ }];
409
+ }
410
+ case "ReplaceListEntry": {
411
+ const value = boundedJson(extract(payload, operation.from));
412
+ const entry = listEntryKey(operation.key, payload);
413
+ return value === void 0 || entry === void 0 ? [] : [{
414
+ mapping,
415
+ operation: index,
416
+ value,
417
+ entryKey: entry.key,
418
+ ...entry.id === void 0 ? {} : { entryId: entry.id }
419
+ }];
420
+ }
421
+ }
422
+ };
423
+ const entryIdAt = (payload, path) => {
424
+ const value = extract(payload, path);
425
+ return typeof value === "string" && Schema.is(TranscriptDecorationEntryId)(value) ? value : void 0;
426
+ };
427
+ const ordinalAt = (payload, path) => {
428
+ const value = extract(payload, path);
429
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
430
+ };
431
+ /** The entry's list key, and its id when the list is keyed by id or ordinal. */
432
+ const listEntryKey = (key, payload) => {
433
+ switch (key._tag) {
434
+ case "Id": {
435
+ const id = entryIdAt(payload, key.path);
436
+ return id === void 0 ? void 0 : { key: id };
437
+ }
438
+ case "Ordinal": {
439
+ const ordinal = ordinalAt(payload, key.path);
440
+ return ordinal === void 0 ? void 0 : { key: ordinal };
441
+ }
442
+ case "IdOrOrdinal": {
443
+ const id = entryIdAt(payload, key.id);
444
+ const ordinal = ordinalAt(payload, key.ordinal);
445
+ return id === void 0 || ordinal === void 0 ? void 0 : {
446
+ key: ordinal,
447
+ id
448
+ };
449
+ }
450
+ }
451
+ };
452
+ const park = (batch, seq, association, key, prepared) => {
453
+ const id = transcriptRecordId.decorationBuffer(association, key);
454
+ const existing = batch.get(id);
455
+ if (existing !== void 0 && existing.kind !== "decorationBuffer") throw new TranscriptProjectionError({ message: `record ${id} is ${existing.kind}, expected decorationBuffer` });
456
+ const buffer = {
457
+ kind: "decorationBuffer",
458
+ id,
459
+ updatedSeq: seq,
460
+ operations: withinBudget([...existing?.operations ?? [], ...prepared.map((operation) => ({
461
+ ...operation,
462
+ seq
463
+ }))])
464
+ };
465
+ batch.put(buffer);
466
+ };
467
+ /**
468
+ * Apply decorations parked for a new user record, in arrival order, then the host's user
469
+ * fallbacks for decorations that are still absent.
470
+ */
471
+ const replayBufferedDecorations = (batch, seq, user) => {
472
+ const buffered = [transcriptRecordId.decorationBuffer("command", user.commandId), ...user.idempotencyKey === void 0 ? [] : [transcriptRecordId.decorationBuffer("idempotencyKey", user.idempotencyKey)]].flatMap((id) => {
473
+ const buffer = batch.get(id);
474
+ if (buffer?.kind !== "decorationBuffer" || buffer.operations.length === 0) return [];
475
+ batch.put({
476
+ ...buffer,
477
+ updatedSeq: seq,
478
+ operations: []
479
+ });
480
+ return buffer.operations;
481
+ });
482
+ buffered.sort((left, right) => left.seq - right.seq);
483
+ const decorated = decorateUser(batch.definition, user, buffered);
484
+ const session = batch.get(transcriptRecordId.session);
485
+ if (session?.kind !== "sessionContext" || decorated.classification !== void 0) return decorated;
486
+ let decorations = decorated.decorations;
487
+ for (const fallback of batch.definition.mappings.userFallbacks) {
488
+ const source = session.decorations[fallback.fromSession];
489
+ if (decorations[fallback.to] === void 0 && source?._tag === "Value") {
490
+ const next = {
491
+ ...decorations,
492
+ [fallback.to]: source
493
+ };
494
+ if (jsonBytes(next) <= transcriptMappingBounds.maxDecorationBytes) decorations = next;
495
+ }
496
+ }
497
+ return decorations === decorated.decorations ? decorated : {
498
+ ...decorated,
499
+ updatedSeq: seq,
500
+ decorations
501
+ };
502
+ };
503
+ const decorateUser = (definition, user, operations) => {
504
+ const decorated = operations.reduce((current, operation) => applyPrepared(definition, current, operation), {
505
+ decorations: user.decorations,
506
+ ...user.classification === void 0 ? {} : { classification: user.classification }
507
+ });
508
+ return {
509
+ ...user,
510
+ decorations: decorated.decorations,
511
+ ...decorated.classification === void 0 ? {} : { classification: decorated.classification }
512
+ };
513
+ };
514
+ /** The longest prefix of parked operations within the buffer's count and byte bounds. */
515
+ const withinBudget = (operations) => {
516
+ const kept = [];
517
+ let bytes = 2;
518
+ for (const operation of operations.slice(0, 32)) {
519
+ bytes += jsonBytes(operation) + 1;
520
+ if (bytes > transcriptMappingBounds.maxDecorationBytes) break;
521
+ kept.push(operation);
522
+ }
523
+ return kept;
524
+ };
525
+ /** Apply one operation unless the record's decorations would exceed their byte budget. */
526
+ const applyPrepared = (definition, target, prepared) => {
527
+ const next = applyOperation(definition, target, prepared);
528
+ return next === target || jsonBytes(next.decorations) <= transcriptMappingBounds.maxDecorationBytes ? next : target;
529
+ };
530
+ const jsonBytes = (value) => encoder.encode(canonicalJson(value)).length;
531
+ const applyOperation = (definition, target, prepared) => {
532
+ const operation = mappingIndex(definition).byName.get(prepared.mapping)?.operations[prepared.operation];
533
+ if (operation === void 0) return target;
534
+ switch (operation._tag) {
535
+ case "Classify": return {
536
+ ...target,
537
+ classification: operation.classification
538
+ };
539
+ case "Copy": return withDecoration(target, operation.to, {
540
+ _tag: "Value",
541
+ value: prepared.value
542
+ });
543
+ case "FirstWins": return target.decorations[operation.to] === void 0 ? withDecoration(target, operation.to, {
544
+ _tag: "Value",
545
+ value: prepared.value
546
+ }) : target;
547
+ case "ReplaceListEntry": {
548
+ if (prepared.entryKey === void 0) return target;
549
+ const list = replaceListEntry(target.decorations[operation.to], prepared.entryKey, prepared.value, operation.key._tag !== "Id", operation.key._tag === "IdOrOrdinal" ? prepared.entryId : void 0);
550
+ return list === void 0 ? target : withDecoration(target, operation.to, list);
551
+ }
552
+ }
553
+ };
554
+ const withDecoration = (target, key, decoration) => ({
555
+ ...target,
556
+ decorations: {
557
+ ...target.decorations,
558
+ [key]: decoration
559
+ }
560
+ });
561
+ const replaceListEntry = (existing, key, value, ordered, id) => {
562
+ const entries = existing?._tag === "List" ? existing.entries : [];
563
+ if (id !== void 0) {
564
+ const kept = entries.filter((entry) => entry.key !== key && entry.id !== id);
565
+ if (kept.length === entries.length && entries.length >= transcriptMappingBounds.maxListEntries) return;
566
+ return {
567
+ _tag: "List",
568
+ entries: [...kept, {
569
+ key,
570
+ value,
571
+ id
572
+ }].sort((left, right) => Number(left.key) - Number(right.key))
573
+ };
574
+ }
575
+ const index = entries.findIndex((entry) => entry.key === key);
576
+ if (index >= 0) return {
577
+ _tag: "List",
578
+ entries: entries.map((entry, position) => position === index ? {
579
+ key,
580
+ value
581
+ } : entry)
582
+ };
583
+ if (entries.length >= transcriptMappingBounds.maxListEntries) return void 0;
584
+ const next = [...entries, {
585
+ key,
586
+ value
587
+ }];
588
+ if (ordered) next.sort((left, right) => Number(left.key) - Number(right.key));
589
+ return {
590
+ _tag: "List",
591
+ entries: next
592
+ };
593
+ };
594
+ /** Read a payload value by path through own properties only. */
595
+ const extract = (value, path) => path.reduce((current, key) => {
596
+ if (typeof key === "number") return Array.isArray(current) ? current[key] : void 0;
597
+ if (current === null || typeof current !== "object" || Array.isArray(current)) return;
598
+ return Object.getOwnPropertyDescriptor(current, key)?.value;
599
+ }, value);
600
+ const encoder = new TextEncoder();
601
+ /**
602
+ * A payload value as the JSON a persisted log holds (so a live projection and a rebuild agree),
603
+ * within the value bound; otherwise nothing.
604
+ */
605
+ const boundedJson = (value) => {
606
+ if (value === void 0) return void 0;
607
+ try {
608
+ const json = JSON.stringify(value);
609
+ if (json === void 0) return void 0;
610
+ const normalized = JSON.parse(json);
611
+ return Schema.is(Schema.Json)(normalized) && encoder.encode(canonicalJson(normalized)).length <= transcriptMappingBounds.maxValueBytes ? normalized : void 0;
612
+ } catch {
613
+ return;
614
+ }
615
+ };
616
+ //#endregion
617
+ //#region src/transcript/interpreter.ts
618
+ /**
619
+ * Accumulates one batch's changes over a committed lookup.
620
+ *
621
+ * Every handler reads through this overlay, so later events in a batch see earlier ones, and the
622
+ * plan is the same whichever way a log is split into batches: interpretation is a sequential fold
623
+ * whose only state is the records themselves.
624
+ */
625
+ var TranscriptBatch = class {
626
+ lookup;
627
+ definition;
628
+ records = /* @__PURE__ */ new Map();
629
+ aliases = /* @__PURE__ */ new Map();
630
+ ordinals = /* @__PURE__ */ new Map();
631
+ constructor(lookup, definition) {
632
+ this.lookup = lookup;
633
+ this.definition = definition;
634
+ }
635
+ get(id) {
636
+ return this.records.get(id) ?? this.lookup.record(id);
637
+ }
638
+ put(record) {
639
+ this.records.set(record.id, record);
640
+ }
641
+ user(id) {
642
+ const record = this.get(id);
643
+ if (record === void 0) return void 0;
644
+ if (record.kind !== "user") throw kindMismatch(id, "user", record.kind);
645
+ return record;
646
+ }
647
+ assistant(id) {
648
+ const record = this.get(id);
649
+ if (record === void 0) return void 0;
650
+ if (record.kind !== "assistant") throw kindMismatch(id, "assistant", record.kind);
651
+ return record;
652
+ }
653
+ tool(id) {
654
+ const record = this.get(id);
655
+ if (record === void 0) return void 0;
656
+ if (record.kind !== "tool") throw kindMismatch(id, "tool", record.kind);
657
+ return record;
658
+ }
659
+ runGroup(id) {
660
+ const record = this.get(id);
661
+ if (record === void 0) return void 0;
662
+ if (record.kind !== "runGroup") throw kindMismatch(id, "runGroup", record.kind);
663
+ return record;
664
+ }
665
+ session(seq) {
666
+ const record = this.get(transcriptRecordId.session);
667
+ if (record === void 0) return {
668
+ kind: "sessionContext",
669
+ id: transcriptRecordId.session,
670
+ updatedSeq: seq,
671
+ tokenUsage: { byModel: [] },
672
+ decorations: {}
673
+ };
674
+ if (record.kind !== "sessionContext") throw kindMismatch(transcriptRecordId.session, "sessionContext", record.kind);
675
+ return record;
676
+ }
677
+ alias(namespace, key) {
678
+ return this.aliases.get(aliasKey(namespace, key))?.recordId ?? this.lookup.alias(namespace, key);
679
+ }
680
+ /** Insert an alias unless one exists; an alias never moves to another record. */
681
+ insertAlias(namespace, key, recordId) {
682
+ if (this.alias(namespace, key) !== void 0) return;
683
+ this.aliases.set(aliasKey(namespace, key), {
684
+ namespace,
685
+ key,
686
+ recordId
687
+ });
688
+ }
689
+ position(anchorSeq) {
690
+ const ordinal = this.ordinals.get(anchorSeq) ?? this.lookup.nextOrdinal(anchorSeq);
691
+ this.ordinals.set(anchorSeq, ordinal + 1);
692
+ return {
693
+ anchorSeq,
694
+ ordinal
695
+ };
696
+ }
697
+ plan(throughSeq) {
698
+ for (const record of this.records.values()) {
699
+ const problem = storageProblem(record);
700
+ if (problem !== void 0) throw new TranscriptProjectionError({ message: `planned record ${record.id} ${problem}` });
701
+ }
702
+ return {
703
+ records: Array.from(this.records.values()),
704
+ aliases: Array.from(this.aliases.values()),
705
+ throughSeq
706
+ };
707
+ }
708
+ };
709
+ const aliasKey = (namespace, key) => `${namespace}\u0000${key}`;
710
+ const matchesRecordSchema = Schema.is(TranscriptRecord);
711
+ const encodeRecord = Schema.encodeSync(TranscriptRecordFromEnvelope);
712
+ const describeCause = (cause) => cause instanceof Error ? cause.message : String(cause);
713
+ /**
714
+ * Why a record could not be stored, if it could not: it must satisfy the stored-row schema,
715
+ * filters included, and its envelope must be JSON, which is exactly what a store can write and
716
+ * every reader can encode. The cause is kept so a frozen version can be diagnosed from its meta.
717
+ */
718
+ const storageProblem = (record) => {
719
+ let envelope;
720
+ try {
721
+ envelope = encodeRecord(record);
722
+ } catch (cause) {
723
+ return `does not satisfy the transcript record schema: ${describeCause(cause)}`;
724
+ }
725
+ if (!matchesRecordSchema(record)) return "does not satisfy the transcript record schema";
726
+ try {
727
+ return JSON.stringify(envelope) === void 0 ? "has no JSON envelope" : void 0;
728
+ } catch (cause) {
729
+ return `is not JSON: ${describeCause(cause)}`;
730
+ }
731
+ };
732
+ const kindMismatch = (id, expected, actual) => new TranscriptProjectionError({ message: `record ${id} is ${actual}, expected ${expected}` });
733
+ /**
734
+ * Interpret one committed batch into a transcript change plan.
735
+ *
736
+ * Mirrors the `ReducedState` message, tool and inference fold without pruning: a
737
+ * `ContextRebased` only adds a compaction marker. Events at or below the lookup cursor are
738
+ * skipped, so an idempotent re-append is harmless. Foreign events are ignored unless a mapping
739
+ * of `definition` names their namespace, type and schema version.
740
+ */
741
+ const planTranscriptBatch = (lookup, committed, definition) => {
742
+ const batch = new TranscriptBatch(lookup, definition);
743
+ let throughSeq = lookup.cursor;
744
+ for (const entry of committed) {
745
+ const seq = entry.position.seq;
746
+ if (seq <= throughSeq) continue;
747
+ throughSeq = seq;
748
+ if (entry.event.namespace === "__foreign") {
749
+ applyForeignEvent(batch, entry.event.envelope, seq);
750
+ continue;
751
+ }
752
+ if (entry.event.namespace !== "effect-durable-agent") continue;
753
+ interpretEvent(batch, entry, seq);
754
+ }
755
+ return batch.plan(throughSeq);
756
+ };
757
+ const eventTime = (createdAtMs) => UnixEpochMillis.make(createdAtMs);
758
+ const interpretEvent = (batch, entry, seq) => {
759
+ if (entry.event.namespace === "__foreign") return;
760
+ const event = interpretLegacyAttemptForReduction(entry.event);
761
+ const at = eventTime(event.createdAtMs);
762
+ switch (event.type) {
763
+ case sessionConfiguredEventType: {
764
+ const session = batch.session(seq);
765
+ if (session.modelSelection === void 0) batch.put({
766
+ ...session,
767
+ updatedSeq: seq,
768
+ modelSelection: jsonModelSelection(event.payload.modelSelection)
769
+ });
770
+ return;
771
+ }
772
+ case commandAdmittedEventType: {
773
+ const { command } = event.payload;
774
+ if (command._tag !== "SubmitMessage" || command.commandId === void 0) return;
775
+ const id = transcriptRecordId.user(command.commandId);
776
+ if (batch.get(id) !== void 0) return;
777
+ createUser(batch, seq, at, {
778
+ commandId: command.commandId,
779
+ content: command.content,
780
+ state: command.disposition === "steer" ? { _tag: "Steering" } : { _tag: "Pending" },
781
+ disposition: command.disposition,
782
+ ...command.idempotencyKey === void 0 ? {} : { idempotencyKey: command.idempotencyKey }
783
+ });
784
+ return;
785
+ }
786
+ case commandCancelledEventType:
787
+ case commandFailedEventType: {
788
+ const user = batch.user(transcriptRecordId.user(event.payload.commandId));
789
+ if (user === void 0 || user.messageIds.length > 0 || !isWaiting(user.state)) return;
790
+ batch.put({
791
+ ...user,
792
+ updatedSeq: seq,
793
+ state: {
794
+ _tag: "Cancelled",
795
+ reason: event.type === commandFailedEventType ? `failed: ${event.payload.error.message}` : event.payload.reason
796
+ }
797
+ });
798
+ return;
799
+ }
800
+ case userMessageSubmittedEventType: {
801
+ const { commandId, messageId, disposition, content } = event.payload;
802
+ const user = userForMessage(batch, seq, at, commandId, messageId, content);
803
+ batch.put({
804
+ ...user,
805
+ updatedSeq: seq,
806
+ content,
807
+ disposition,
808
+ state: isWaiting(user.state) ? disposition === "steer" ? { _tag: "Steering" } : { _tag: "Pending" } : user.state
809
+ });
810
+ return;
811
+ }
812
+ case userMessageCommittedEventType: {
813
+ const { commandId, messageId, content } = event.payload;
814
+ const user = userForMessage(batch, seq, at, commandId, messageId, content);
815
+ batch.put(user.state._tag === "Consumed" ? {
816
+ ...user,
817
+ updatedSeq: seq,
818
+ content
819
+ } : consume(batch, {
820
+ ...user,
821
+ content
822
+ }, seq, at, {}));
823
+ return;
824
+ }
825
+ case steeringMessageQueuedEventType: {
826
+ const { commandId, messageId, runId, content } = event.payload;
827
+ const user = userForMessage(batch, seq, at, commandId, messageId, content);
828
+ batch.put({
829
+ ...user,
830
+ updatedSeq: seq,
831
+ content,
832
+ steering: { runId },
833
+ state: isWaiting(user.state) ? { _tag: "Steering" } : user.state
834
+ });
835
+ return;
836
+ }
837
+ case steeringMessageCancelledEventType: {
838
+ const user = userByMessage(batch, event.payload.messageId);
839
+ if (user?.steering === void 0 || user.state._tag === "Consumed") return;
840
+ batch.put({
841
+ ...user,
842
+ updatedSeq: seq,
843
+ state: {
844
+ _tag: "Cancelled",
845
+ reason: event.payload.reason
846
+ }
847
+ });
848
+ return;
849
+ }
850
+ case userMessagePromotedEventType: {
851
+ const user = userByMessage(batch, event.payload.messageId);
852
+ if (user === void 0) return;
853
+ if (user.state._tag !== "Pending" && user.state._tag !== "Paused") return;
854
+ batch.put({
855
+ ...user,
856
+ updatedSeq: seq,
857
+ ...user.steering === void 0 ? { disposition: "steer" } : {},
858
+ state: { _tag: "Promoted" }
859
+ });
860
+ return;
861
+ }
862
+ case userMessageCancelledEventType: {
863
+ const { commandId, messageId, reason } = event.payload;
864
+ const user = userByMessage(batch, messageId);
865
+ if (user === void 0 || user.state._tag === "Cancelled") return;
866
+ if (user.steering !== void 0 && user.state._tag === "Consumed") return;
867
+ batch.put({
868
+ ...user,
869
+ updatedSeq: seq,
870
+ state: {
871
+ _tag: "Cancelled",
872
+ reason,
873
+ byCommandId: commandId
874
+ }
875
+ });
876
+ return;
877
+ }
878
+ case messageQueuePausedEventType:
879
+ case pendingMessagesPausedEventType: {
880
+ const byCommandId = event.type === messageQueuePausedEventType ? event.payload.stopCommandId : event.payload.interruptionCommandId;
881
+ for (const messageId of event.payload.messageIds) {
882
+ const user = userByMessage(batch, messageId);
883
+ if (user === void 0 || !isWaiting(user.state)) continue;
884
+ batch.put({
885
+ ...user,
886
+ updatedSeq: seq,
887
+ ...user.steering === void 0 ? { disposition: "queue" } : {},
888
+ state: {
889
+ _tag: "Paused",
890
+ byCommandId
891
+ }
892
+ });
893
+ }
894
+ return;
895
+ }
896
+ case turnStartedEventType: {
897
+ const { runId, turnId, inputMessageIds } = event.payload;
898
+ const consumed = /* @__PURE__ */ new Map();
899
+ for (const messageId of inputMessageIds ?? []) {
900
+ const user = userByMessage(batch, messageId);
901
+ if (user === void 0 || user.state._tag === "Consumed") continue;
902
+ if (user.state._tag === "Cancelled" && user.steering === void 0) continue;
903
+ consumed.set(user.id, user);
904
+ }
905
+ const ordered = [...consumed.values()].sort((left, right) => left.submittedSeq - right.submittedSeq || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
906
+ for (const user of ordered) batch.put(consume(batch, user, seq, at, {
907
+ runId,
908
+ turnId
909
+ }));
910
+ return;
911
+ }
912
+ case assistantMessageCommittedEventType:
913
+ case assistantPartialCommittedEventType: {
914
+ const { messageId, runId, turnId, inferenceId, promptParts } = event.payload;
915
+ const id = transcriptRecordId.assistant(inferenceId);
916
+ const { partial: _partial, ...withoutPartial } = batch.assistant(id) ?? newAssistant(batch, id, seq, "inference", inferenceId, runId, turnId);
917
+ batch.put({
918
+ ...withoutPartial,
919
+ updatedSeq: seq,
920
+ messageId,
921
+ parts: assistantParts(batch, inferenceId, promptParts, seq),
922
+ ...event.type === assistantPartialCommittedEventType ? { partial: { reason: event.payload.reason } } : {}
923
+ });
924
+ return;
925
+ }
926
+ case assistantMessageImportedEventType: {
927
+ const { messageId, runId, turnId, inferenceId, promptParts } = event.payload;
928
+ const id = transcriptRecordId.import(event.eventId);
929
+ const { runGroupId: _runGroupId, ...imported } = newAssistant(batch, id, seq, "import", inferenceId, runId, turnId);
930
+ batch.put({
931
+ ...imported,
932
+ messageId,
933
+ lifecycle: { _tag: "Completed" },
934
+ parts: assistantParts(batch, inferenceId, promptParts, seq)
935
+ });
936
+ return;
937
+ }
938
+ case inferenceStartedEventType: {
939
+ const { runId, turnId, inferenceId } = event.payload;
940
+ const id = transcriptRecordId.assistant(inferenceId);
941
+ const existing = batch.assistant(id) ?? newAssistant(batch, id, seq, "inference", inferenceId, runId, turnId);
942
+ batch.put({
943
+ ...existing,
944
+ updatedSeq: seq,
945
+ startedAtMs: at
946
+ });
947
+ return;
948
+ }
949
+ case inferenceCompletedEventType: {
950
+ const { runId, inferenceId, finishReason, usage } = event.payload;
951
+ const assistant = batch.assistant(transcriptRecordId.assistant(inferenceId));
952
+ if (assistant === void 0) return;
953
+ if (assistant.startedAtMs !== void 0 && assistant.lifecycle._tag !== "Completed") {
954
+ const model = runMember(batch, runId)?.modelSelection;
955
+ if (model !== void 0 && usage !== void 0) {
956
+ const session = batch.session(seq);
957
+ batch.put({
958
+ ...session,
959
+ updatedSeq: seq,
960
+ tokenUsage: addModelUsage(session.tokenUsage, model, usage)
961
+ });
962
+ }
963
+ }
964
+ batch.put({
965
+ ...assistant,
966
+ updatedSeq: seq,
967
+ ...terminalTiming(assistant.startedAtMs, at),
968
+ lifecycle: {
969
+ _tag: "Completed",
970
+ ...finishReason === void 0 ? {} : { finishReason },
971
+ ...usage === void 0 ? {} : { usage }
972
+ }
973
+ });
974
+ return;
975
+ }
976
+ case inferenceFailedEventType: {
977
+ const assistant = batch.assistant(transcriptRecordId.assistant(event.payload.inferenceId));
978
+ if (assistant === void 0) return;
979
+ batch.put({
980
+ ...assistant,
981
+ updatedSeq: seq,
982
+ ...terminalTiming(assistant.startedAtMs, at),
983
+ lifecycle: {
984
+ _tag: "Failed",
985
+ error: jsonFailure(event.payload.error)
986
+ }
987
+ });
988
+ return;
989
+ }
990
+ case toolCallCreatedEventType: {
991
+ const { inferenceId, toolCallId, promptPart } = event.payload;
992
+ const id = transcriptRecordId.tool(toolCallId);
993
+ const existing = batch.tool(id);
994
+ batch.put({
995
+ kind: "tool",
996
+ id,
997
+ updatedSeq: seq,
998
+ toolCallId,
999
+ assistantId: transcriptRecordId.assistant(inferenceId),
1000
+ providerPartId: promptPart.id,
1001
+ toolName: promptPart.name,
1002
+ providerExecuted: promptPart.providerExecuted,
1003
+ params: inlineBody(promptPart.params, seq, ["promptPart", "params"]),
1004
+ lifecycle: existing === void 0 || existing.lifecycle._tag === "Rejected" ? { _tag: "Created" } : existing.lifecycle,
1005
+ createdAtMs: existing?.createdAtMs ?? at,
1006
+ ...timingOf(existing)
1007
+ });
1008
+ linkToolPart(batch, inferenceId, promptPart.id, id, seq);
1009
+ return;
1010
+ }
1011
+ case toolCallRejectedEventType: {
1012
+ const { inferenceId, toolCallId, promptPart } = event.payload;
1013
+ const id = transcriptRecordId.tool(toolCallId);
1014
+ const existing = batch.tool(id);
1015
+ batch.put({
1016
+ kind: "tool",
1017
+ id,
1018
+ updatedSeq: seq,
1019
+ toolCallId,
1020
+ assistantId: transcriptRecordId.assistant(inferenceId),
1021
+ providerPartId: promptPart.id,
1022
+ toolName: promptPart.name,
1023
+ providerExecuted: false,
1024
+ lifecycle: {
1025
+ _tag: "Rejected",
1026
+ reason: promptPart.result.reason,
1027
+ message: promptPart.result.message,
1028
+ modelFeedback: promptPart.result.modelFeedback
1029
+ },
1030
+ createdAtMs: existing?.createdAtMs ?? at,
1031
+ ...timingOf(existing)
1032
+ });
1033
+ linkToolPart(batch, inferenceId, promptPart.id, id, seq);
1034
+ return;
1035
+ }
1036
+ case toolCallStartedEventType: {
1037
+ const tool = batch.tool(transcriptRecordId.tool(event.payload.toolCallId));
1038
+ if (tool === void 0) return;
1039
+ batch.put({
1040
+ ...tool,
1041
+ updatedSeq: seq,
1042
+ startedAtMs: event.payload.attempt === void 0 ? at : tool.startedAtMs ?? at,
1043
+ lifecycle: tool.lifecycle._tag === "Created" ? { _tag: "Running" } : tool.lifecycle
1044
+ });
1045
+ return;
1046
+ }
1047
+ case toolCallCompletedEventType: {
1048
+ const tool = batch.tool(transcriptRecordId.tool(event.payload.toolCallId));
1049
+ if (tool === void 0) return;
1050
+ batch.put({
1051
+ ...tool,
1052
+ updatedSeq: seq,
1053
+ ...terminalTiming(tool.startedAtMs, at),
1054
+ lifecycle: {
1055
+ _tag: "Completed",
1056
+ result: inlineBody(event.payload.promptPart.result, seq, ["promptPart", "result"])
1057
+ }
1058
+ });
1059
+ return;
1060
+ }
1061
+ case toolCallFailedEventType: {
1062
+ const tool = batch.tool(transcriptRecordId.tool(event.payload.toolCallId));
1063
+ if (tool === void 0) return;
1064
+ batch.put({
1065
+ ...tool,
1066
+ updatedSeq: seq,
1067
+ ...terminalTiming(tool.startedAtMs, at),
1068
+ lifecycle: {
1069
+ _tag: "Failed",
1070
+ error: jsonFailure(event.payload.error ?? event.payload.promptPart.result)
1071
+ }
1072
+ });
1073
+ return;
1074
+ }
1075
+ case contextRebasedEventType: {
1076
+ const { compactionId, summaryId, contextVersion, retainedFromContextSeq } = event.payload;
1077
+ const id = transcriptRecordId.compaction(compactionId);
1078
+ const existing = batch.get(id);
1079
+ if (existing !== void 0 && existing.kind !== "compaction") throw kindMismatch(id, "compaction", existing.kind);
1080
+ const record = {
1081
+ kind: "compaction",
1082
+ id,
1083
+ updatedSeq: seq,
1084
+ position: existing?.position ?? batch.position(seq),
1085
+ compactionId,
1086
+ summaryId,
1087
+ contextVersion,
1088
+ retainedFromContextSeq,
1089
+ createdAtMs: existing?.createdAtMs ?? at
1090
+ };
1091
+ batch.put(record);
1092
+ return;
1093
+ }
1094
+ case compactionStartedEventType: {
1095
+ const session = batch.session(seq);
1096
+ batch.put({
1097
+ ...session,
1098
+ updatedSeq: seq,
1099
+ activeCompactionId: event.payload.compactionId
1100
+ });
1101
+ return;
1102
+ }
1103
+ case compactionCompletedEventType:
1104
+ case compactionFailedEventType: {
1105
+ const { compactionId, modelSelection, usage } = event.payload;
1106
+ const compactionRecordId = transcriptRecordId.compaction(compactionId);
1107
+ const compaction = batch.get(compactionRecordId);
1108
+ const repeated = event.type === compactionCompletedEventType && compaction?.kind === "compaction" && compaction.completedAtMs !== void 0;
1109
+ if (event.type === compactionCompletedEventType && compaction?.kind === "compaction" && compaction.completedAtMs === void 0) batch.put({
1110
+ ...compaction,
1111
+ updatedSeq: seq,
1112
+ completedAtMs: at
1113
+ });
1114
+ const session = batch.session(seq);
1115
+ const { activeCompactionId, ...rest } = session;
1116
+ batch.put({
1117
+ ...rest,
1118
+ updatedSeq: seq,
1119
+ ...activeCompactionId === void 0 || activeCompactionId === compactionId ? {} : { activeCompactionId },
1120
+ tokenUsage: modelSelection === void 0 || repeated ? session.tokenUsage : addModelUsage(session.tokenUsage, modelSelection, usage)
1121
+ });
1122
+ return;
1123
+ }
1124
+ case runStartedEventType:
1125
+ startRun(batch, seq, at, event.payload.runId, event.payload.commandIds, jsonModelSelection(event.payload.modelSelection));
1126
+ return;
1127
+ case runCompletedEventType:
1128
+ finishRun(batch, seq, at, event.payload.runId, { _tag: "Completed" });
1129
+ return;
1130
+ case runFailedEventType:
1131
+ finishRun(batch, seq, at, event.payload.runId, runFailureOutcome(event.payload.error));
1132
+ return;
1133
+ case runInterruptedEventType:
1134
+ finishRun(batch, seq, at, event.payload.runId, {
1135
+ _tag: "Interrupted",
1136
+ reason: event.payload.reason
1137
+ });
1138
+ return;
1139
+ case recoveryCompletedEventType: {
1140
+ const continuation = event.payload.continuation;
1141
+ if (continuation === void 0) return;
1142
+ const groupId = batch.alias("runId", continuation.replacementRunId);
1143
+ const group = groupId === void 0 ? void 0 : batch.runGroup(groupId);
1144
+ if (group === void 0) return;
1145
+ batch.put({
1146
+ ...group,
1147
+ updatedSeq: seq,
1148
+ runs: mapNonEmpty(group.runs, (member) => member.runId === continuation.replacementRunId ? {
1149
+ ...member,
1150
+ continuationOf: continuation.interruptedRunId
1151
+ } : member)
1152
+ });
1153
+ return;
1154
+ }
1155
+ case systemMessageCommittedEventType:
1156
+ case deciderAcceptedEventType:
1157
+ case runSchedulingRequestedEventType:
1158
+ case runSchedulingDeliveredEventType:
1159
+ case runSchedulingInvalidatedEventType:
1160
+ case runSchedulingGrantedEventType:
1161
+ case commandStartedEventType:
1162
+ case commandCompletedEventType:
1163
+ case turnCompletedEventType:
1164
+ case turnFailedEventType:
1165
+ case turnStoppedEventType:
1166
+ case stopTurnRequestedEventType:
1167
+ case stopTurnAppliedEventType:
1168
+ case contextProjectedEventType:
1169
+ case compactionRequestedEventType:
1170
+ case summaryCreatedEventType:
1171
+ case baseStateRequestedEventType:
1172
+ case baseStateCreatedEventType:
1173
+ case baseStateFailedEventType: return;
1174
+ default: return assertNever(event, "transcript durable event");
1175
+ }
1176
+ };
1177
+ /** Waiting for the agent: not yet consumed and not withdrawn. */
1178
+ const isWaiting = (state) => state._tag === "Pending" || state._tag === "Paused" || state._tag === "Promoted" || state._tag === "Steering";
1179
+ const createUser = (batch, seq, at, fields) => {
1180
+ const id = transcriptRecordId.user(fields.commandId);
1181
+ if (fields.idempotencyKey !== void 0) batch.insertAlias("idempotencyKey", fields.idempotencyKey, id);
1182
+ const user = replayBufferedDecorations(batch, seq, {
1183
+ kind: "user",
1184
+ id,
1185
+ updatedSeq: seq,
1186
+ messageIds: [],
1187
+ decorations: {},
1188
+ submittedSeq: seq,
1189
+ submittedAtMs: at,
1190
+ ...fields
1191
+ });
1192
+ batch.put(user);
1193
+ return user;
1194
+ };
1195
+ /** The user record a message belongs to, created if the log never admitted its command. */
1196
+ const userForMessage = (batch, seq, at, commandId, messageId, content) => {
1197
+ const id = transcriptRecordId.user(commandId);
1198
+ const user = batch.user(id) ?? createUser(batch, seq, at, {
1199
+ commandId,
1200
+ content,
1201
+ state: { _tag: "Pending" }
1202
+ });
1203
+ batch.insertAlias("messageId", messageId, id);
1204
+ return user.messageIds.includes(messageId) ? user : {
1205
+ ...user,
1206
+ messageIds: [...user.messageIds, messageId]
1207
+ };
1208
+ };
1209
+ const userByMessage = (batch, messageId) => {
1210
+ const id = batch.alias("messageId", messageId);
1211
+ return id === void 0 ? void 0 : batch.user(id);
1212
+ };
1213
+ const consume = (batch, user, seq, at, by) => ({
1214
+ ...user,
1215
+ updatedSeq: seq,
1216
+ position: user.position ?? batch.position(seq),
1217
+ consumedAtMs: user.consumedAtMs ?? at,
1218
+ state: {
1219
+ _tag: "Consumed",
1220
+ ...by
1221
+ }
1222
+ });
1223
+ const newAssistant = (batch, id, seq, source, inferenceId, runId, turnId) => {
1224
+ const groupId = batch.alias("runId", runId);
1225
+ const runGroupId = groupId === void 0 ? void 0 : batch.runGroup(groupId)?.id;
1226
+ return {
1227
+ kind: "assistant",
1228
+ id,
1229
+ updatedSeq: seq,
1230
+ position: batch.position(seq),
1231
+ source,
1232
+ inferenceId,
1233
+ runId,
1234
+ turnId,
1235
+ ...runGroupId === void 0 ? {} : { runGroupId },
1236
+ lifecycle: { _tag: "Streaming" },
1237
+ parts: []
1238
+ };
1239
+ };
1240
+ const assistantParts = (batch, inferenceId, promptParts, seq) => promptParts.map((part, index) => {
1241
+ switch (part.type) {
1242
+ case "text": return {
1243
+ _tag: "Text",
1244
+ text: part.text
1245
+ };
1246
+ case "reasoning": return {
1247
+ _tag: "Reasoning",
1248
+ text: part.text
1249
+ };
1250
+ case "tool-call": {
1251
+ if (!Schema.is(ProviderPartId)(part.id) || !Schema.is(ToolName)(part.name)) return {
1252
+ _tag: "Unknown",
1253
+ partType: part.type
1254
+ };
1255
+ const toolAlias = batch.alias("toolPart", toolPartKey(inferenceId, part.id));
1256
+ const toolId = toolAlias === void 0 ? void 0 : batch.tool(toolAlias)?.id;
1257
+ return {
1258
+ _tag: "ToolCall",
1259
+ providerPartId: part.id,
1260
+ toolName: part.name,
1261
+ providerExecuted: part.providerExecuted,
1262
+ ...toolId === void 0 ? {} : { toolId }
1263
+ };
1264
+ }
1265
+ case "tool-result":
1266
+ if (!Schema.is(ProviderPartId)(part.id) || !Schema.is(ToolName)(part.name)) return {
1267
+ _tag: "Unknown",
1268
+ partType: part.type
1269
+ };
1270
+ return {
1271
+ _tag: "ToolResult",
1272
+ providerPartId: part.id,
1273
+ toolName: part.name,
1274
+ isFailure: part.isFailure,
1275
+ result: inlineBody(part.result, seq, [
1276
+ "promptParts",
1277
+ index,
1278
+ "result"
1279
+ ])
1280
+ };
1281
+ default: return {
1282
+ _tag: "Unknown",
1283
+ partType: part.type
1284
+ };
1285
+ }
1286
+ });
1287
+ const toolPartKey = (inferenceId, providerPartId) => `${inferenceId}/${providerPartId}`;
1288
+ /** Record the tool for its assistant part, whichever of the two the log wrote first. */
1289
+ const linkToolPart = (batch, inferenceId, providerPartId, toolId, seq) => {
1290
+ batch.insertAlias("toolPart", toolPartKey(inferenceId, providerPartId), toolId);
1291
+ const assistant = batch.assistant(transcriptRecordId.assistant(inferenceId));
1292
+ if (assistant === void 0) return;
1293
+ let changed = false;
1294
+ const parts = assistant.parts.map((part) => {
1295
+ if (part._tag !== "ToolCall" || part.providerPartId !== providerPartId || part.toolId !== void 0) return part;
1296
+ changed = true;
1297
+ return {
1298
+ ...part,
1299
+ toolId
1300
+ };
1301
+ });
1302
+ if (changed) batch.put({
1303
+ ...assistant,
1304
+ updatedSeq: seq,
1305
+ parts
1306
+ });
1307
+ };
1308
+ const startRun = (batch, seq, at, runId, commandIds, modelSelection) => {
1309
+ const group = runGroupForStart(batch, seq, runId, commandIds, {
1310
+ runId,
1311
+ commandIds,
1312
+ modelSelection,
1313
+ outcome: { _tag: "Running" },
1314
+ startedAtMs: at
1315
+ });
1316
+ batch.put(group);
1317
+ batch.insertAlias("runId", runId, group.id);
1318
+ for (const commandId of commandIds) batch.insertAlias("runCommand", commandId, group.id);
1319
+ const session = batch.session(seq);
1320
+ batch.put({
1321
+ ...session,
1322
+ updatedSeq: seq,
1323
+ activeRunId: runId,
1324
+ lastRunModelSelection: modelSelection,
1325
+ modelSelection: session.modelSelection ?? modelSelection
1326
+ });
1327
+ };
1328
+ /**
1329
+ * The group a started run belongs to. A repeated start of a known run replaces its member and
1330
+ * keeps its outcome, as the reduced state keeps its terminal. A startup-recovery continuation
1331
+ * reuses its interrupted predecessor's command ids, so it joins that finished group; any other
1332
+ * run roots a new group.
1333
+ */
1334
+ const runGroupForStart = (batch, seq, runId, commandIds, member) => {
1335
+ const knownId = batch.alias("runId", runId);
1336
+ const known = knownId === void 0 ? void 0 : batch.runGroup(knownId);
1337
+ if (known !== void 0) return {
1338
+ ...known,
1339
+ updatedSeq: seq,
1340
+ runs: mapNonEmpty(known.runs, (candidate) => candidate.runId === runId ? {
1341
+ ...member,
1342
+ outcome: candidate.outcome
1343
+ } : candidate)
1344
+ };
1345
+ const predecessor = commandIds.map((commandId) => batch.alias("runCommand", commandId)).map((groupId) => groupId === void 0 ? void 0 : batch.runGroup(groupId)).find((group) => group !== void 0 && runGroupStatus(group)._tag !== "Running");
1346
+ if (predecessor !== void 0) return {
1347
+ ...predecessor,
1348
+ updatedSeq: seq,
1349
+ runs: [...predecessor.runs, member]
1350
+ };
1351
+ return {
1352
+ kind: "runGroup",
1353
+ id: transcriptRecordId.runGroup(runId),
1354
+ updatedSeq: seq,
1355
+ rootRunId: runId,
1356
+ runs: [member]
1357
+ };
1358
+ };
1359
+ const finishRun = (batch, seq, at, runId, outcome) => {
1360
+ const groupId = batch.alias("runId", runId);
1361
+ const group = groupId === void 0 ? void 0 : batch.runGroup(groupId);
1362
+ if (group === void 0) return;
1363
+ batch.put({
1364
+ ...group,
1365
+ updatedSeq: seq,
1366
+ runs: mapNonEmpty(group.runs, (member) => member.runId === runId ? {
1367
+ ...member,
1368
+ ...terminalTiming(member.startedAtMs, at),
1369
+ outcome
1370
+ } : member)
1371
+ });
1372
+ const session = batch.session(seq);
1373
+ if (session.activeRunId === runId) {
1374
+ const { activeRunId: _activeRunId, ...idle } = session;
1375
+ batch.put({
1376
+ ...idle,
1377
+ updatedSeq: seq
1378
+ });
1379
+ }
1380
+ };
1381
+ const runMember = (batch, runId) => {
1382
+ const groupId = batch.alias("runId", runId);
1383
+ return (groupId === void 0 ? void 0 : batch.runGroup(groupId))?.runs.find((member) => member.runId === runId);
1384
+ };
1385
+ const runFailureOutcome = (error) => error.code === "run.interrupted" ? {
1386
+ _tag: "Interrupted",
1387
+ reason: error.message
1388
+ } : {
1389
+ _tag: "Failed",
1390
+ error: jsonFailure(error)
1391
+ };
1392
+ const terminalTiming = (startedAtMs, terminalAtMs) => ({
1393
+ terminalAtMs,
1394
+ ...startedAtMs === void 0 ? {} : { durationMs: Math.max(0, terminalAtMs - startedAtMs) }
1395
+ });
1396
+ const timingOf = (record) => ({
1397
+ ...record?.startedAtMs === void 0 ? {} : { startedAtMs: record.startedAtMs },
1398
+ ...record?.terminalAtMs === void 0 ? {} : { terminalAtMs: record.terminalAtMs },
1399
+ ...record?.durationMs === void 0 ? {} : { durationMs: record.durationMs }
1400
+ });
1401
+ /**
1402
+ * A body read from a committed event, normalized to the JSON a persisted log holds, so a live
1403
+ * projection, a rebuild from storage and a reference resolved later all agree. A value with no
1404
+ * JSON form (a bigint or a cycle) is a projection failure.
1405
+ */
1406
+ const inlineBody = (value, seq, path) => {
1407
+ const normalized = normalizeTranscriptBodyValue(value);
1408
+ if (normalized === void 0) throw new TranscriptProjectionError({ message: `body at seq ${seq} ${JSON.stringify(path)} is not JSON` });
1409
+ return normalized.byteLength <= 65536 ? {
1410
+ _tag: "Inline",
1411
+ value: normalized.value,
1412
+ source: {
1413
+ seq,
1414
+ path
1415
+ }
1416
+ } : {
1417
+ _tag: "Ref",
1418
+ source: {
1419
+ seq,
1420
+ path
1421
+ },
1422
+ byteLength: normalized.byteLength
1423
+ };
1424
+ };
1425
+ /** A model selection as the JSON a persisted log holds; settings with no JSON form are dropped. */
1426
+ const jsonModelSelection = (selection) => {
1427
+ try {
1428
+ const json = JSON.stringify(selection);
1429
+ const normalized = json === void 0 ? void 0 : JSON.parse(json);
1430
+ if (Schema.is(ModelSelectionPayload)(normalized)) return normalized;
1431
+ } catch {}
1432
+ return {
1433
+ provider: selection.provider,
1434
+ modelId: selection.modelId
1435
+ };
1436
+ };
1437
+ /** A failure as the JSON a persisted log holds; details with no JSON form are dropped. */
1438
+ const jsonFailure = (error) => {
1439
+ try {
1440
+ const json = JSON.stringify(error);
1441
+ const normalized = json === void 0 ? void 0 : JSON.parse(json);
1442
+ if (Schema.is(FailurePayload)(normalized)) return normalized;
1443
+ } catch {}
1444
+ return {
1445
+ message: error.message,
1446
+ ...error.code === void 0 ? {} : { code: error.code }
1447
+ };
1448
+ };
1449
+ const mapNonEmpty = (items, f) => [f(items[0]), ...items.slice(1).map(f)];
1450
+ //#endregion
1451
+ export { computeTranscriptVersion as _, TranscriptDefinitionError as a, TranscriptMapping as c, TranscriptMappings as d, TranscriptUserFallback as f, canonicalJson as g, transcriptMappingBounds as h, TranscriptDefinition as i, TranscriptMappingOperation as l, makeTranscriptDefinition as m, TranscriptAliasNamespace as n, TranscriptListEntryKey as o, emptyTranscriptMappings as p, TranscriptProjectionError as r, TranscriptMappedEvent as s, planTranscriptBatch as t, TranscriptMappingTarget as u, transcriptSemanticRevision as v, resolveTranscriptBody as y };
1452
+
1453
+ //# sourceMappingURL=interpreter-BwYN2PCC.js.map