effect-durable-agent 0.1.0-alpha.21 → 0.1.0-alpha.22
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.
- package/README.md +2 -2
- package/dist/assert-never-CoyUpoRB.js +18 -0
- package/dist/assert-never-CoyUpoRB.js.map +1 -0
- package/dist/domain/command-queues.d.ts +1 -1
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/reduced-state.d.ts +1 -1
- package/dist/domain/reduced-state.js +927 -2
- package/dist/domain/reduced-state.js.map +1 -0
- package/dist/domain/run-scheduling.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/{reduced-state-BGd_yCBT.d.ts → reduced-state-PJdig48e.d.ts} +4171 -4171
- package/dist/{reducer-registry-BIhncOHH.d.ts → reducer-registry-BAbhZs6d.d.ts} +2 -2
- package/dist/{run-scheduling-wakeup-BH2pHE0U.d.ts → run-scheduling-wakeup-QLK87OqG.d.ts} +2 -2
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/model-call.d.ts +1 -1
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/reducer-registry.js +1 -1
- package/dist/services/run-scheduler.d.ts +1 -1
- package/dist/services/run-scheduling-wakeup.d.ts +1 -1
- package/dist/services/runtime-layer.d.ts +6 -6
- package/dist/services/runtime-layer.js +3 -3
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +1 -1
- package/dist/services/session-query.d.ts +1 -1
- package/dist/services/session-query.js +2 -2
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +2 -2
- package/dist/services/session-store.js +1 -251
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/tool-registry.d.ts +1 -1
- package/dist/{session-state-C_1XxhvE.js → session-state-StlO5B2N.js} +5 -4
- package/dist/{session-state-C_1XxhvE.js.map → session-state-StlO5B2N.js.map} +1 -1
- package/dist/session-store-ByDjS03N.d.ts +3184 -0
- package/dist/session-store-DcJjs4Fd.js +413 -0
- package/dist/session-store-DcJjs4Fd.js.map +1 -0
- package/dist/{sink-checkpoint-store-C-SY0cG2.d.ts → sink-checkpoint-store-BHb8YRTw.d.ts} +2 -2
- package/dist/{sink-registry-CjK5MC90.js → sink-registry-DEneTH8u.js} +3 -3
- package/dist/{sink-registry-CjK5MC90.js.map → sink-registry-DEneTH8u.js.map} +1 -1
- package/dist/testkit/layers.d.ts +6 -6
- package/dist/testkit/layers.js +3 -3
- package/dist/{tool-registry-wPsHagF_.d.ts → tool-registry-CxZ0iuYb.d.ts} +2 -2
- package/dist/transcript.d.ts +137 -0
- package/dist/transcript.js +178 -0
- package/dist/transcript.js.map +1 -0
- package/dist/websocket.d.ts +1 -1
- package/dist/window-read-B8aF_hDq.js +2173 -0
- package/dist/window-read-B8aF_hDq.js.map +1 -0
- package/package.json +5 -1
- package/dist/reduced-state-Vuud6LCM.js +0 -942
- package/dist/reduced-state-Vuud6LCM.js.map +0 -1
- package/dist/services/session-store.js.map +0 -1
- package/dist/session-store-BpitF4Wg.d.ts +0 -191
|
@@ -0,0 +1,2173 @@
|
|
|
1
|
+
import { CommandId, CompactionId, ContextVersion, EventId, InferenceId, MessageId, RunId, SequenceNumber, SummaryId, ToolCallId, TurnId } from "./types/core.js";
|
|
2
|
+
import { _ as UsagePayload, f as ProviderPartId, g as UnixEpochMillis, h as ToolName, l as ModelSelectionPayload, p as SchemaVersion, s as FailurePayload, u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
|
|
3
|
+
import { TokenConsumptionState, addModelUsage } from "./domain/model-usage.js";
|
|
4
|
+
import { CommandIdempotencyKey, SubmitMessageDisposition } from "./types/commands.js";
|
|
5
|
+
import { $n as pendingMessagesPausedEventType, An as baseStateCreatedEventType, Bn as compactionRequestedEventType, Cr as turnStartedEventType, Dn as assistantMessageCommittedEventType, Dr as userMessagePromotedEventType, Er as userMessageCommittedEventType, Fn as commandCompletedEventType, Hn as contextProjectedEventType, In as commandFailedEventType, Jn as inferenceCompletedEventType, Ln as commandStartedEventType, Mn as baseStateRequestedEventType, Nn as commandAdmittedEventType, On as assistantMessageImportedEventType, Or as userMessageSubmittedEventType, Pn as commandCancelledEventType, Qn as messageQueuePausedEventType, Rn as compactionCompletedEventType, Sr as turnFailedEventType, Tr as userMessageCancelledEventType, Un as contextRebasedEventType, Vn as compactionStartedEventType, Xn as inferenceStartedEventType, Yn as inferenceFailedEventType, Zn as interpretLegacyAttemptForReduction, _r as toolCallCreatedEventType, ar as runSchedulingGrantedEventType, br as toolCallStartedEventType, cr as runStartedEventType, dr as steeringMessageQueuedEventType, er as recoveryCompletedEventType, fr as stopTurnAppliedEventType, gr as toolCallCompletedEventType, hr as systemMessageCommittedEventType, ir as runSchedulingDeliveredEventType, jn as baseStateFailedEventType, kn as assistantPartialCommittedEventType, lr as sessionConfiguredEventType, mr as summaryCreatedEventType, nr as runFailedEventType, or as runSchedulingInvalidatedEventType, pr as stopTurnRequestedEventType, rr as runInterruptedEventType, sr as runSchedulingRequestedEventType, tn as ToolCallRejectionReason, tr as runCompletedEventType, ur as steeringMessageCancelledEventType, vr as toolCallFailedEventType, wr as turnStoppedEventType, xr as turnCompletedEventType, yr as toolCallRejectedEventType, zn as compactionFailedEventType } from "./durable-CD__3ztN.js";
|
|
6
|
+
import { t as assertNever } from "./assert-never-CoyUpoRB.js";
|
|
7
|
+
import { JsonUserMessageContent } from "./domain/reduced-state-schema.js";
|
|
8
|
+
import * as Context from "effect/Context";
|
|
9
|
+
import * as Effect from "effect/Effect";
|
|
10
|
+
import * as Schema from "effect/Schema";
|
|
11
|
+
import * as Order from "effect/Order";
|
|
12
|
+
import * as SchemaTransformation from "effect/SchemaTransformation";
|
|
13
|
+
import * as Result from "effect/Result";
|
|
14
|
+
import * as SchemaGetter from "effect/SchemaGetter";
|
|
15
|
+
//#region src/transcript/hash.ts
|
|
16
|
+
/**
|
|
17
|
+
* Synchronous hashing for transcript identities (versions and bounded record keys).
|
|
18
|
+
*/
|
|
19
|
+
const roundConstants = new Uint32Array([
|
|
20
|
+
1116352408,
|
|
21
|
+
1899447441,
|
|
22
|
+
3049323471,
|
|
23
|
+
3921009573,
|
|
24
|
+
961987163,
|
|
25
|
+
1508970993,
|
|
26
|
+
2453635748,
|
|
27
|
+
2870763221,
|
|
28
|
+
3624381080,
|
|
29
|
+
310598401,
|
|
30
|
+
607225278,
|
|
31
|
+
1426881987,
|
|
32
|
+
1925078388,
|
|
33
|
+
2162078206,
|
|
34
|
+
2614888103,
|
|
35
|
+
3248222580,
|
|
36
|
+
3835390401,
|
|
37
|
+
4022224774,
|
|
38
|
+
264347078,
|
|
39
|
+
604807628,
|
|
40
|
+
770255983,
|
|
41
|
+
1249150122,
|
|
42
|
+
1555081692,
|
|
43
|
+
1996064986,
|
|
44
|
+
2554220882,
|
|
45
|
+
2821834349,
|
|
46
|
+
2952996808,
|
|
47
|
+
3210313671,
|
|
48
|
+
3336571891,
|
|
49
|
+
3584528711,
|
|
50
|
+
113926993,
|
|
51
|
+
338241895,
|
|
52
|
+
666307205,
|
|
53
|
+
773529912,
|
|
54
|
+
1294757372,
|
|
55
|
+
1396182291,
|
|
56
|
+
1695183700,
|
|
57
|
+
1986661051,
|
|
58
|
+
2177026350,
|
|
59
|
+
2456956037,
|
|
60
|
+
2730485921,
|
|
61
|
+
2820302411,
|
|
62
|
+
3259730800,
|
|
63
|
+
3345764771,
|
|
64
|
+
3516065817,
|
|
65
|
+
3600352804,
|
|
66
|
+
4094571909,
|
|
67
|
+
275423344,
|
|
68
|
+
430227734,
|
|
69
|
+
506948616,
|
|
70
|
+
659060556,
|
|
71
|
+
883997877,
|
|
72
|
+
958139571,
|
|
73
|
+
1322822218,
|
|
74
|
+
1537002063,
|
|
75
|
+
1747873779,
|
|
76
|
+
1955562222,
|
|
77
|
+
2024104815,
|
|
78
|
+
2227730452,
|
|
79
|
+
2361852424,
|
|
80
|
+
2428436474,
|
|
81
|
+
2756734187,
|
|
82
|
+
3204031479,
|
|
83
|
+
3329325298
|
|
84
|
+
]);
|
|
85
|
+
const rotateRight = (value, bits) => value >>> bits | value << 32 - bits;
|
|
86
|
+
const at = (words, index) => words[index] ?? 0;
|
|
87
|
+
/** Lowercase hex SHA-256 of a string's UTF-8 bytes. */
|
|
88
|
+
const sha256Hex = (input) => {
|
|
89
|
+
const message = new TextEncoder().encode(input);
|
|
90
|
+
const bitLength = message.length * 8;
|
|
91
|
+
const paddedLength = Math.ceil((message.length + 9) / 64) * 64;
|
|
92
|
+
const padded = new Uint8Array(paddedLength);
|
|
93
|
+
padded.set(message);
|
|
94
|
+
padded[message.length] = 128;
|
|
95
|
+
const view = new DataView(padded.buffer);
|
|
96
|
+
view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296));
|
|
97
|
+
view.setUint32(paddedLength - 4, bitLength >>> 0);
|
|
98
|
+
const hash = new Uint32Array([
|
|
99
|
+
1779033703,
|
|
100
|
+
3144134277,
|
|
101
|
+
1013904242,
|
|
102
|
+
2773480762,
|
|
103
|
+
1359893119,
|
|
104
|
+
2600822924,
|
|
105
|
+
528734635,
|
|
106
|
+
1541459225
|
|
107
|
+
]);
|
|
108
|
+
const schedule = /* @__PURE__ */ new Uint32Array(64);
|
|
109
|
+
for (let offset = 0; offset < paddedLength; offset += 64) {
|
|
110
|
+
for (let index = 0; index < 16; index += 1) schedule[index] = view.getUint32(offset + index * 4);
|
|
111
|
+
for (let index = 16; index < 64; index += 1) {
|
|
112
|
+
const w15 = at(schedule, index - 15);
|
|
113
|
+
const w2 = at(schedule, index - 2);
|
|
114
|
+
const s0 = rotateRight(w15, 7) ^ rotateRight(w15, 18) ^ w15 >>> 3;
|
|
115
|
+
const s1 = rotateRight(w2, 17) ^ rotateRight(w2, 19) ^ w2 >>> 10;
|
|
116
|
+
schedule[index] = at(schedule, index - 16) + s0 + at(schedule, index - 7) + s1;
|
|
117
|
+
}
|
|
118
|
+
const working = Uint32Array.from(hash);
|
|
119
|
+
for (let index = 0; index < 64; index += 1) {
|
|
120
|
+
const [a, b, c, d, e, f, g, h] = Array.from(working);
|
|
121
|
+
const s1 = rotateRight(e ?? 0, 6) ^ rotateRight(e ?? 0, 11) ^ rotateRight(e ?? 0, 25);
|
|
122
|
+
const choice = (e ?? 0) & (f ?? 0) ^ ~(e ?? 0) & (g ?? 0);
|
|
123
|
+
const t1 = (h ?? 0) + s1 + choice + at(roundConstants, index) + at(schedule, index);
|
|
124
|
+
const s0 = rotateRight(a ?? 0, 2) ^ rotateRight(a ?? 0, 13) ^ rotateRight(a ?? 0, 22);
|
|
125
|
+
const majority = (a ?? 0) & (b ?? 0) ^ (a ?? 0) & (c ?? 0) ^ (b ?? 0) & (c ?? 0);
|
|
126
|
+
working.set([
|
|
127
|
+
t1 + s0 + majority,
|
|
128
|
+
a ?? 0,
|
|
129
|
+
b ?? 0,
|
|
130
|
+
c ?? 0,
|
|
131
|
+
(d ?? 0) + t1,
|
|
132
|
+
e ?? 0,
|
|
133
|
+
f ?? 0,
|
|
134
|
+
g ?? 0
|
|
135
|
+
]);
|
|
136
|
+
}
|
|
137
|
+
for (let index = 0; index < 8; index += 1) hash[index] = at(hash, index) + at(working, index);
|
|
138
|
+
}
|
|
139
|
+
return Array.from(hash, (word) => word.toString(16).padStart(8, "0")).join("");
|
|
140
|
+
};
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region src/transcript/records.ts
|
|
143
|
+
/** One logical user submission across every lifecycle state: `user:<commandId>`. */
|
|
144
|
+
const UserRecordId = Schema.TemplateLiteral(["user:", CommandId]);
|
|
145
|
+
/** One model inference's visible output: `assistant:<inferenceId>`. */
|
|
146
|
+
const InferenceAssistantRecordId = Schema.TemplateLiteral(["assistant:", InferenceId]);
|
|
147
|
+
/** Assistant context imported from another transport, keyed by its import event: `import:<eventId>`. */
|
|
148
|
+
const ImportAssistantRecordId = Schema.TemplateLiteral(["import:", EventId]);
|
|
149
|
+
/** Either assistant identity; both are top-level assistant records. */
|
|
150
|
+
const AssistantRecordId = Schema.Union([InferenceAssistantRecordId, ImportAssistantRecordId]);
|
|
151
|
+
/** The marker a context rebase leaves in history: `compaction:<compactionId>`. */
|
|
152
|
+
const CompactionRecordId = Schema.TemplateLiteral(["compaction:", CompactionId]);
|
|
153
|
+
/** A framework tool call, a dependency of its assistant: `tool:<toolCallId>`. */
|
|
154
|
+
const ToolRecordId = Schema.TemplateLiteral(["tool:", ToolCallId]);
|
|
155
|
+
/**
|
|
156
|
+
* A run plus every startup-recovery continuation of it: `run:<rootRunId>`.
|
|
157
|
+
*
|
|
158
|
+
* The id names the first run of the chain and never changes when a continuation joins.
|
|
159
|
+
*/
|
|
160
|
+
const RunGroupRecordId = Schema.TemplateLiteral(["run:", RunId]);
|
|
161
|
+
/** The session-context singleton. */
|
|
162
|
+
const SessionContextRecordId = Schema.Literal("session");
|
|
163
|
+
/**
|
|
164
|
+
* Internal holding record for decorations whose target user record does not exist yet.
|
|
165
|
+
*
|
|
166
|
+
* Hosts append decoration events before the command they describe (Gia submits
|
|
167
|
+
* `[author, attachments…, SubmitMessage]` in one batch), so the interpreter parks them under the
|
|
168
|
+
* association key and merges them when the user record is created. Never served by a window read.
|
|
169
|
+
*/
|
|
170
|
+
const DecorationBufferRecordId = Schema.TemplateLiteral([
|
|
171
|
+
"decorations:",
|
|
172
|
+
Schema.Literals(["command", "idempotencyKey"]),
|
|
173
|
+
":",
|
|
174
|
+
Schema.NonEmptyString.check(Schema.isMaxLength(512))
|
|
175
|
+
]);
|
|
176
|
+
/** Every transcript record identity this EDA release writes. */
|
|
177
|
+
const TranscriptRecordId = Schema.Union([
|
|
178
|
+
UserRecordId,
|
|
179
|
+
AssistantRecordId,
|
|
180
|
+
CompactionRecordId,
|
|
181
|
+
ToolRecordId,
|
|
182
|
+
RunGroupRecordId,
|
|
183
|
+
SessionContextRecordId,
|
|
184
|
+
DecorationBufferRecordId
|
|
185
|
+
]);
|
|
186
|
+
/** Constructors for record identities; the only place identities are spelled. */
|
|
187
|
+
const transcriptRecordId = {
|
|
188
|
+
user: (commandId) => `user:${commandId}`,
|
|
189
|
+
assistant: (inferenceId) => `assistant:${inferenceId}`,
|
|
190
|
+
import: (eventId) => `import:${eventId}`,
|
|
191
|
+
compaction: (compactionId) => `compaction:${compactionId}`,
|
|
192
|
+
tool: (toolCallId) => `tool:${toolCallId}`,
|
|
193
|
+
runGroup: (rootRunId) => `run:${rootRunId}`,
|
|
194
|
+
session: "session",
|
|
195
|
+
/**
|
|
196
|
+
* Keys longer than 256 characters (caller-owned idempotency keys) are hashed to stay bounded;
|
|
197
|
+
* keys starting with `#` are hashed too, so a literal key never collides with a hashed one.
|
|
198
|
+
*/
|
|
199
|
+
decorationBuffer: (association, key) => `decorations:${association}:${key.length > 0 && key.length <= 256 && !key.startsWith("#") ? key : `#sha256:${sha256Hex(key)}`}`
|
|
200
|
+
};
|
|
201
|
+
/**
|
|
202
|
+
* History position of a top-level record: the event that placed it and an ordinal among records
|
|
203
|
+
* placed by that same event. Assigned once and never moved.
|
|
204
|
+
*/
|
|
205
|
+
const TranscriptPosition = Schema.Struct({
|
|
206
|
+
anchorSeq: SequenceNumber,
|
|
207
|
+
ordinal: NonNegativeInt
|
|
208
|
+
});
|
|
209
|
+
/**
|
|
210
|
+
* Adapter-owned identity of one physical event log. A wiped log gets a new incarnation, which
|
|
211
|
+
* invalidates every cursor, chunk and body reference minted against the old one.
|
|
212
|
+
*/
|
|
213
|
+
const TranscriptLogIncarnation = Schema.NonEmptyString.pipe(Schema.brand("TranscriptLogIncarnation"));
|
|
214
|
+
/**
|
|
215
|
+
* Identity of one transcript interpretation: a hash of the EDA semantic revision and the host's
|
|
216
|
+
* canonical mapping data. Two sessions with equal versions interpret the same log identically.
|
|
217
|
+
*/
|
|
218
|
+
const TranscriptVersion = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/)).pipe(Schema.brand("TranscriptVersion"));
|
|
219
|
+
/**
|
|
220
|
+
* Paging cursor: a point in the total order `(anchorSeq, ordinal, recordId)`.
|
|
221
|
+
*
|
|
222
|
+
* A cursor is meaningful only for the incarnation and version that minted it; readers reject
|
|
223
|
+
* any other pairing rather than guess an equivalent point.
|
|
224
|
+
*/
|
|
225
|
+
const TranscriptCursor = Schema.Struct({
|
|
226
|
+
incarnation: TranscriptLogIncarnation,
|
|
227
|
+
version: TranscriptVersion,
|
|
228
|
+
anchorSeq: SequenceNumber,
|
|
229
|
+
ordinal: NonNegativeInt,
|
|
230
|
+
recordId: Schema.NonEmptyString
|
|
231
|
+
});
|
|
232
|
+
/** Total transcript order over top-level records. */
|
|
233
|
+
const TranscriptOrder = Order.Struct({
|
|
234
|
+
anchorSeq: Order.Number,
|
|
235
|
+
ordinal: Order.Number,
|
|
236
|
+
recordId: Order.String
|
|
237
|
+
});
|
|
238
|
+
/** A JSON path into an event payload; the empty path is the payload itself. */
|
|
239
|
+
const TranscriptFieldPath = Schema.Array(Schema.Union([Schema.String, NonNegativeInt]));
|
|
240
|
+
/** The immutable log location a body was read from. */
|
|
241
|
+
const TranscriptBodySource = Schema.Struct({
|
|
242
|
+
seq: SequenceNumber,
|
|
243
|
+
path: TranscriptFieldPath
|
|
244
|
+
});
|
|
245
|
+
/**
|
|
246
|
+
* Largest body a stored record holds inline, in canonical JSON bytes. Larger bodies are stored
|
|
247
|
+
* as references, which keeps every stored row far below a Durable Object's 2 MB value limit no
|
|
248
|
+
* matter how large an event payload is.
|
|
249
|
+
*/
|
|
250
|
+
const transcriptStoredInlineBodyLimit = 65536;
|
|
251
|
+
/**
|
|
252
|
+
* A potentially large body (tool parameters and results).
|
|
253
|
+
*
|
|
254
|
+
* Stored records hold a body inline up to `transcriptStoredInlineBodyLimit` and as a reference
|
|
255
|
+
* above it; a window read may also replace a smaller inline body with a reference. A reference
|
|
256
|
+
* points at the body's immutable source in the append-only log, so it stays resolvable after
|
|
257
|
+
* projection rows are rebuilt or deleted. The host authorizes reference resolution.
|
|
258
|
+
*/
|
|
259
|
+
const TranscriptBody = Schema.TaggedUnion({
|
|
260
|
+
Inline: {
|
|
261
|
+
value: Schema.Json,
|
|
262
|
+
source: TranscriptBodySource
|
|
263
|
+
},
|
|
264
|
+
Ref: {
|
|
265
|
+
source: TranscriptBodySource,
|
|
266
|
+
byteLength: NonNegativeInt
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
/** Host-defined decoration name, as written by a mapping operation. */
|
|
270
|
+
const TranscriptDecorationKey = Schema.String.check(Schema.isPattern(/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/));
|
|
271
|
+
/** Key of one decoration list entry: an entry id or a host-assigned ordinal. */
|
|
272
|
+
const TranscriptDecorationEntryKey = Schema.Union([Schema.String.check(Schema.isMaxLength(256)), NonNegativeInt]);
|
|
273
|
+
/**
|
|
274
|
+
* A host decoration value: a JSON scalar/object, or a keyed list whose entries are replaced by id
|
|
275
|
+
* or ordinal. EDA treats the JSON as opaque; only the host gives it meaning.
|
|
276
|
+
*/
|
|
277
|
+
const TranscriptDecoration = Schema.TaggedUnion({
|
|
278
|
+
Value: { value: Schema.Json },
|
|
279
|
+
List: { entries: Schema.Array(Schema.Struct({
|
|
280
|
+
key: TranscriptDecorationEntryKey,
|
|
281
|
+
value: Schema.Json
|
|
282
|
+
})) }
|
|
283
|
+
});
|
|
284
|
+
/** Decorations of one record, keyed by host decoration name. */
|
|
285
|
+
const TranscriptDecorations = Schema.Record(TranscriptDecorationKey, TranscriptDecoration);
|
|
286
|
+
/** Host classification of a user record, such as an authenticated subagent notice. */
|
|
287
|
+
const TranscriptClassification = TranscriptDecorationKey;
|
|
288
|
+
const LifecycleTimingFields = {
|
|
289
|
+
startedAtMs: Schema.optionalKey(UnixEpochMillis),
|
|
290
|
+
terminalAtMs: Schema.optionalKey(UnixEpochMillis),
|
|
291
|
+
durationMs: Schema.optionalKey(NonNegativeInt)
|
|
292
|
+
};
|
|
293
|
+
/**
|
|
294
|
+
* Where a user submission is in its lifecycle.
|
|
295
|
+
*
|
|
296
|
+
* Only `Consumed` records are rendered in history. `Pending`, `Paused`, `Promoted` and `Steering`
|
|
297
|
+
* are waiting to be read by the agent and are served as dependencies. `Cancelled` records stay
|
|
298
|
+
* stored so their aliases resolve but are never rendered.
|
|
299
|
+
*/
|
|
300
|
+
const TranscriptUserState = Schema.TaggedUnion({
|
|
301
|
+
/** Admitted and queued for a later run. */
|
|
302
|
+
Pending: {},
|
|
303
|
+
/** Queued, but held because the user interrupted the run that would have read it. */
|
|
304
|
+
Paused: { byCommandId: CommandId },
|
|
305
|
+
/** Moved from the queue to steer the active run. */
|
|
306
|
+
Promoted: {},
|
|
307
|
+
/** Waiting to steer the active run. */
|
|
308
|
+
Steering: {},
|
|
309
|
+
/** Read by the agent; the record's position is the consumption point. */
|
|
310
|
+
Consumed: {
|
|
311
|
+
turnId: Schema.optionalKey(TurnId),
|
|
312
|
+
runId: Schema.optionalKey(RunId)
|
|
313
|
+
},
|
|
314
|
+
/** Withdrawn before the agent read it, or withdrawn from the model context. */
|
|
315
|
+
Cancelled: {
|
|
316
|
+
reason: Schema.String,
|
|
317
|
+
byCommandId: Schema.optionalKey(CommandId)
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
const UserBodyFields = {
|
|
321
|
+
commandId: CommandId,
|
|
322
|
+
/** Every message id that has carried this submission; a replacement id joins as an alias. */
|
|
323
|
+
messageIds: Schema.Array(MessageId),
|
|
324
|
+
idempotencyKey: Schema.optionalKey(CommandIdempotencyKey),
|
|
325
|
+
disposition: Schema.optionalKey(SubmitMessageDisposition),
|
|
326
|
+
/**
|
|
327
|
+
* JSON projection of the content: file bytes become data URLs, URLs become strings. Content is
|
|
328
|
+
* inline; file data belongs in host attachments rather than message content.
|
|
329
|
+
*/
|
|
330
|
+
content: JsonUserMessageContent,
|
|
331
|
+
state: TranscriptUserState,
|
|
332
|
+
/** Present when the submission arrived as steering for a specific run. */
|
|
333
|
+
steering: Schema.optionalKey(Schema.Struct({ runId: RunId })),
|
|
334
|
+
classification: Schema.optionalKey(TranscriptClassification),
|
|
335
|
+
decorations: TranscriptDecorations,
|
|
336
|
+
/** The first event that named this submission; pending users are served in this order. */
|
|
337
|
+
submittedSeq: SequenceNumber,
|
|
338
|
+
submittedAtMs: UnixEpochMillis,
|
|
339
|
+
/** Present exactly when `position` is: the record was consumed at some point. */
|
|
340
|
+
consumedAtMs: Schema.optionalKey(UnixEpochMillis)
|
|
341
|
+
};
|
|
342
|
+
/** Lifecycle of one assistant record. Imports are `Completed` from the start. */
|
|
343
|
+
const TranscriptAssistantLifecycle = Schema.TaggedUnion({
|
|
344
|
+
Streaming: {},
|
|
345
|
+
Completed: {
|
|
346
|
+
finishReason: Schema.optionalKey(Schema.String),
|
|
347
|
+
usage: Schema.optionalKey(UsagePayload)
|
|
348
|
+
},
|
|
349
|
+
Failed: { error: FailurePayload }
|
|
350
|
+
});
|
|
351
|
+
/**
|
|
352
|
+
* One ordered part of assistant output. Tool calls are references; their bodies live on the tool
|
|
353
|
+
* dependency. Part types this release does not render are kept as `Unknown` so ordering survives.
|
|
354
|
+
*/
|
|
355
|
+
const KnownAssistantPart = Schema.TaggedUnion({
|
|
356
|
+
Text: { text: Schema.String },
|
|
357
|
+
Reasoning: { text: Schema.String },
|
|
358
|
+
ToolCall: {
|
|
359
|
+
providerPartId: ProviderPartId,
|
|
360
|
+
toolName: ToolName,
|
|
361
|
+
providerExecuted: Schema.Boolean,
|
|
362
|
+
/** The framework tool record, once the call has been sealed into one. */
|
|
363
|
+
toolId: Schema.optionalKey(ToolRecordId)
|
|
364
|
+
},
|
|
365
|
+
/** Result of a provider-executed tool, which has no framework tool record. */
|
|
366
|
+
ToolResult: {
|
|
367
|
+
providerPartId: ProviderPartId,
|
|
368
|
+
toolName: ToolName,
|
|
369
|
+
isFailure: Schema.Boolean,
|
|
370
|
+
result: TranscriptBody
|
|
371
|
+
},
|
|
372
|
+
Unknown: { partType: Schema.String }
|
|
373
|
+
});
|
|
374
|
+
/** A part whose tag or shape this reader does not know keeps its place as `Unknown`. */
|
|
375
|
+
const knownAssistantPartTags = /* @__PURE__ */ new Set([
|
|
376
|
+
"Text",
|
|
377
|
+
"Reasoning",
|
|
378
|
+
"ToolCall",
|
|
379
|
+
"ToolResult",
|
|
380
|
+
"Unknown"
|
|
381
|
+
]);
|
|
382
|
+
const UnrecognizedAssistantPart = Schema.Struct({ _tag: Schema.String.check(Schema.makeFilter((tag) => !knownAssistantPartTags.has(tag) || "a known part tag must decode as that part")) }).pipe(Schema.decodeTo(Schema.toType(KnownAssistantPart.cases.Unknown), {
|
|
383
|
+
decode: SchemaGetter.transform((part) => ({
|
|
384
|
+
_tag: "Unknown",
|
|
385
|
+
partType: part._tag
|
|
386
|
+
})),
|
|
387
|
+
encode: SchemaGetter.transform((part) => ({ _tag: part.partType }))
|
|
388
|
+
}));
|
|
389
|
+
/**
|
|
390
|
+
* One ordered part of assistant output. A part tag this reader does not know decodes as
|
|
391
|
+
* `Unknown`, keeping its place; a malformed part with a known tag is a decode failure.
|
|
392
|
+
*/
|
|
393
|
+
const TranscriptAssistantPart = Schema.Union([KnownAssistantPart, UnrecognizedAssistantPart]);
|
|
394
|
+
const AssistantBodyFields = {
|
|
395
|
+
source: Schema.Literals(["inference", "import"]),
|
|
396
|
+
inferenceId: InferenceId,
|
|
397
|
+
runId: RunId,
|
|
398
|
+
turnId: TurnId,
|
|
399
|
+
/** Run group of the producing run; absent for imports and for runs the log never started. */
|
|
400
|
+
runGroupId: Schema.optionalKey(RunGroupRecordId),
|
|
401
|
+
messageId: Schema.optionalKey(MessageId),
|
|
402
|
+
lifecycle: TranscriptAssistantLifecycle,
|
|
403
|
+
parts: Schema.Array(TranscriptAssistantPart),
|
|
404
|
+
/** Present when the visible parts were preserved from an interrupted or failed inference. */
|
|
405
|
+
partial: Schema.optionalKey(Schema.Struct({ reason: Schema.String })),
|
|
406
|
+
...LifecycleTimingFields
|
|
407
|
+
};
|
|
408
|
+
const CompactionBodyFields = {
|
|
409
|
+
compactionId: CompactionId,
|
|
410
|
+
/** Reference to the summary artifact; the transcript never copies summary text. */
|
|
411
|
+
summaryId: SummaryId,
|
|
412
|
+
contextVersion: ContextVersion,
|
|
413
|
+
retainedFromContextSeq: SequenceNumber,
|
|
414
|
+
createdAtMs: UnixEpochMillis,
|
|
415
|
+
/** Set by the first `CompactionCompleted`; later completions add no token usage. */
|
|
416
|
+
completedAtMs: Schema.optionalKey(UnixEpochMillis)
|
|
417
|
+
};
|
|
418
|
+
/** Lifecycle of one framework tool call. The last terminal event wins. */
|
|
419
|
+
const TranscriptToolLifecycle = Schema.TaggedUnion({
|
|
420
|
+
Created: {},
|
|
421
|
+
Running: {},
|
|
422
|
+
Completed: { result: TranscriptBody },
|
|
423
|
+
Failed: { error: FailurePayload },
|
|
424
|
+
/** The call was not executable; terminal from creation. */
|
|
425
|
+
Rejected: {
|
|
426
|
+
reason: ToolCallRejectionReason,
|
|
427
|
+
message: Schema.String,
|
|
428
|
+
modelFeedback: Schema.String
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
const ToolBodyFields = {
|
|
432
|
+
toolCallId: ToolCallId,
|
|
433
|
+
assistantId: InferenceAssistantRecordId,
|
|
434
|
+
providerPartId: ProviderPartId,
|
|
435
|
+
toolName: ToolName,
|
|
436
|
+
providerExecuted: Schema.Boolean,
|
|
437
|
+
/** Absent for a rejected call: a rejection records only the model-facing feedback. */
|
|
438
|
+
params: Schema.optionalKey(TranscriptBody),
|
|
439
|
+
lifecycle: TranscriptToolLifecycle,
|
|
440
|
+
createdAtMs: UnixEpochMillis,
|
|
441
|
+
...LifecycleTimingFields
|
|
442
|
+
};
|
|
443
|
+
/** Outcome of one run inside a run group. */
|
|
444
|
+
const TranscriptRunOutcome = Schema.TaggedUnion({
|
|
445
|
+
Running: {},
|
|
446
|
+
Completed: {},
|
|
447
|
+
Failed: { error: FailurePayload },
|
|
448
|
+
/** Stopped by the user or by a runtime restart; a continuation may follow. */
|
|
449
|
+
Interrupted: { reason: Schema.String }
|
|
450
|
+
});
|
|
451
|
+
/** One run in a run group, in start order. */
|
|
452
|
+
const TranscriptRunMember = Schema.Struct({
|
|
453
|
+
runId: RunId,
|
|
454
|
+
commandIds: Schema.Array(CommandId),
|
|
455
|
+
modelSelection: ModelSelectionPayload,
|
|
456
|
+
outcome: TranscriptRunOutcome,
|
|
457
|
+
/** The interrupted run this one continues, as recorded by startup recovery. */
|
|
458
|
+
continuationOf: Schema.optionalKey(RunId),
|
|
459
|
+
...LifecycleTimingFields
|
|
460
|
+
});
|
|
461
|
+
const RunGroupBodyFields = {
|
|
462
|
+
rootRunId: RunId,
|
|
463
|
+
/** Every run of the chain in start order; the last member's outcome is the group's status. */
|
|
464
|
+
runs: Schema.NonEmptyArray(TranscriptRunMember)
|
|
465
|
+
};
|
|
466
|
+
const SessionContextBodyFields = {
|
|
467
|
+
/** The run currently executing, if any. */
|
|
468
|
+
activeRunId: Schema.optionalKey(RunId),
|
|
469
|
+
/** The compaction currently in progress, if any. */
|
|
470
|
+
activeCompactionId: Schema.optionalKey(CompactionId),
|
|
471
|
+
/** Session execution policy: the first configured or started model, as the runtime reads it. */
|
|
472
|
+
modelSelection: Schema.optionalKey(ModelSelectionPayload),
|
|
473
|
+
/** Model of the most recently started run. */
|
|
474
|
+
lastRunModelSelection: Schema.optionalKey(ModelSelectionPayload),
|
|
475
|
+
tokenUsage: TokenConsumptionState,
|
|
476
|
+
decorations: TranscriptDecorations
|
|
477
|
+
};
|
|
478
|
+
/** One decoration operation parked until its target exists, in arrival order. */
|
|
479
|
+
const TranscriptBufferedDecoration = Schema.Struct({
|
|
480
|
+
seq: SequenceNumber,
|
|
481
|
+
mapping: TranscriptDecorationKey,
|
|
482
|
+
/** Operation index within the mapping. */
|
|
483
|
+
operation: NonNegativeInt,
|
|
484
|
+
value: Schema.Json,
|
|
485
|
+
entryKey: Schema.optionalKey(TranscriptDecorationEntryKey)
|
|
486
|
+
});
|
|
487
|
+
/**
|
|
488
|
+
* Operations one decoration buffer keeps. Later operations for the same key are dropped, as are
|
|
489
|
+
* operations beyond the mapping bounds' decoration byte budget.
|
|
490
|
+
*/
|
|
491
|
+
const transcriptDecorationBufferLimit = 32;
|
|
492
|
+
const DecorationBufferBodyFields = { operations: Schema.Array(TranscriptBufferedDecoration).check(Schema.isMaxLength(32)) };
|
|
493
|
+
const commonFields = (kind, id) => ({
|
|
494
|
+
kind: Schema.tag(kind),
|
|
495
|
+
id,
|
|
496
|
+
/** The last event that contributed to this record. */
|
|
497
|
+
updatedSeq: SequenceNumber
|
|
498
|
+
});
|
|
499
|
+
/**
|
|
500
|
+
* User submission, top-level once consumed; waiting states are dependencies.
|
|
501
|
+
*
|
|
502
|
+
* A position is assigned once, when the agent first reads the submission, so a consumed record
|
|
503
|
+
* always has one and a waiting record never does. A cancelled record keeps the position it was
|
|
504
|
+
* consumed at, if any, and is never rendered.
|
|
505
|
+
*/
|
|
506
|
+
const TranscriptUserRecord = Schema.Struct({
|
|
507
|
+
...commonFields("user", UserRecordId),
|
|
508
|
+
position: Schema.optionalKey(TranscriptPosition),
|
|
509
|
+
...UserBodyFields
|
|
510
|
+
}).check(Schema.makeFilter((user) => user.position === void 0 === (user.consumedAtMs === void 0) || "position and consumedAtMs are assigned together"), Schema.makeFilter((user) => user.id === `user:${user.commandId}` || "a user record id names its command"), Schema.makeFilter((user) => {
|
|
511
|
+
switch (user.state._tag) {
|
|
512
|
+
case "Consumed": return user.position !== void 0 || "a consumed user record has a position";
|
|
513
|
+
case "Cancelled": return true;
|
|
514
|
+
default: return user.position === void 0 || "a waiting user record has no position";
|
|
515
|
+
}
|
|
516
|
+
}));
|
|
517
|
+
/** Assistant output of one inference or one import; top-level. */
|
|
518
|
+
const TranscriptAssistantRecord = Schema.Struct({
|
|
519
|
+
...commonFields("assistant", AssistantRecordId),
|
|
520
|
+
position: TranscriptPosition,
|
|
521
|
+
...AssistantBodyFields
|
|
522
|
+
}).check(Schema.makeFilter((assistant) => (assistant.source === "import" ? assistant.id.startsWith("import:") : assistant.id === `assistant:${assistant.inferenceId}`) || "an assistant record id matches its source and inference"));
|
|
523
|
+
/** Compaction marker; top-level. */
|
|
524
|
+
const TranscriptCompactionRecord = Schema.Struct({
|
|
525
|
+
...commonFields("compaction", CompactionRecordId),
|
|
526
|
+
position: TranscriptPosition,
|
|
527
|
+
...CompactionBodyFields
|
|
528
|
+
}).check(Schema.makeFilter((compaction) => compaction.id === `compaction:${compaction.compactionId}` || "a compaction record id names its compaction"));
|
|
529
|
+
/** Framework tool call; a dependency of its assistant record. */
|
|
530
|
+
const TranscriptToolRecord = Schema.Struct({
|
|
531
|
+
...commonFields("tool", ToolRecordId),
|
|
532
|
+
...ToolBodyFields
|
|
533
|
+
}).check(Schema.makeFilter((tool) => tool.id === `tool:${tool.toolCallId}` || "a tool record id names its tool call"));
|
|
534
|
+
/** Run and its recovery continuations; a dependency of the records it produced. */
|
|
535
|
+
const TranscriptRunGroupRecord = Schema.Struct({
|
|
536
|
+
...commonFields("runGroup", RunGroupRecordId),
|
|
537
|
+
...RunGroupBodyFields
|
|
538
|
+
}).check(Schema.makeFilter((group) => group.id === `run:${group.rootRunId}` && group.runs[0].runId === group.rootRunId || "a run group is named by, and starts with, its root run"));
|
|
539
|
+
/** A run group's status: the outcome of its latest run. */
|
|
540
|
+
const runGroupStatus = (group) => (group.runs[group.runs.length - 1] ?? group.runs[0]).outcome;
|
|
541
|
+
/** Session activity, model selection and token totals; a singleton dependency. */
|
|
542
|
+
const TranscriptSessionContextRecord = Schema.Struct({
|
|
543
|
+
...commonFields("sessionContext", SessionContextRecordId),
|
|
544
|
+
...SessionContextBodyFields
|
|
545
|
+
});
|
|
546
|
+
/** Internal decoration holding record; stored, never served. */
|
|
547
|
+
const TranscriptDecorationBufferRecord = Schema.Struct({
|
|
548
|
+
...commonFields("decorationBuffer", DecorationBufferRecordId),
|
|
549
|
+
...DecorationBufferBodyFields
|
|
550
|
+
});
|
|
551
|
+
/** Every record kind this EDA release stores. */
|
|
552
|
+
const TranscriptRecord = Schema.Union([
|
|
553
|
+
TranscriptUserRecord,
|
|
554
|
+
TranscriptAssistantRecord,
|
|
555
|
+
TranscriptCompactionRecord,
|
|
556
|
+
TranscriptToolRecord,
|
|
557
|
+
TranscriptRunGroupRecord,
|
|
558
|
+
TranscriptSessionContextRecord,
|
|
559
|
+
TranscriptDecorationBufferRecord
|
|
560
|
+
]);
|
|
561
|
+
/**
|
|
562
|
+
* A record this reader cannot interpret: a newer kind, or a body written by a newer EDA.
|
|
563
|
+
*
|
|
564
|
+
* It keeps the identity, position and revision so a client can hold its place and render a safe
|
|
565
|
+
* placeholder. Storage readers do not produce it: an undecodable stored row makes a read
|
|
566
|
+
* unavailable instead of wrong.
|
|
567
|
+
*/
|
|
568
|
+
const TranscriptUnknownRecord = Schema.Struct({
|
|
569
|
+
kind: Schema.tag("unknown"),
|
|
570
|
+
originalKind: Schema.NonEmptyString,
|
|
571
|
+
/** The envelope format it arrived in, kept so it re-encodes exactly as it was read. */
|
|
572
|
+
format: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
|
|
573
|
+
/** The uninterpreted body, kept so a relaying reader forwards it unchanged. */
|
|
574
|
+
body: Schema.Record(Schema.String, Schema.Unknown),
|
|
575
|
+
id: Schema.NonEmptyString,
|
|
576
|
+
updatedSeq: SequenceNumber,
|
|
577
|
+
position: Schema.optionalKey(TranscriptPosition)
|
|
578
|
+
});
|
|
579
|
+
/** Top-level kinds count toward a window's record limit and carry a position. */
|
|
580
|
+
const isTopLevelTranscriptRecord = (record) => record.kind === "assistant" || record.kind === "compaction" || record.kind === "user" && record.state._tag === "Consumed" && record.position !== void 0;
|
|
581
|
+
/** A user record still waiting for the agent; served as a dependency, never twice. */
|
|
582
|
+
const isPendingTranscriptUserRecord = (record) => record.kind === "user" && (record.state._tag === "Pending" || record.state._tag === "Paused" || record.state._tag === "Promoted" || record.state._tag === "Steering");
|
|
583
|
+
/**
|
|
584
|
+
* Current stored-row envelope format. Readers accept every format up to this one.
|
|
585
|
+
*
|
|
586
|
+
* Bump it whenever a known kind gains a value an older reader of this format could not decode
|
|
587
|
+
* (a new lifecycle or state tag, a new required field). Older readers then show such rows as
|
|
588
|
+
* `unknown` records; without a bump, a strict older reader would reject the whole window.
|
|
589
|
+
*/
|
|
590
|
+
const transcriptRecordEnvelopeFormat = 1;
|
|
591
|
+
/**
|
|
592
|
+
* Backward-readable row and wire shape for one record.
|
|
593
|
+
*
|
|
594
|
+
* Identity, kind, revision and position sit outside the kind-specific `body` so any reader can
|
|
595
|
+
* place a record it cannot interpret.
|
|
596
|
+
*/
|
|
597
|
+
const TranscriptRecordEnvelope = Schema.Struct({
|
|
598
|
+
format: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
|
|
599
|
+
kind: Schema.NonEmptyString,
|
|
600
|
+
id: Schema.NonEmptyString,
|
|
601
|
+
updatedSeq: SequenceNumber,
|
|
602
|
+
position: Schema.optionalKey(TranscriptPosition),
|
|
603
|
+
body: Schema.Record(Schema.String, Schema.Unknown)
|
|
604
|
+
});
|
|
605
|
+
const envelopeToFlat = (envelope) => {
|
|
606
|
+
const { kind, id, updatedSeq, position, body } = envelope;
|
|
607
|
+
const { kind: _kind, id: _id, updatedSeq: _updatedSeq, position: _position, ...fields } = body;
|
|
608
|
+
return {
|
|
609
|
+
...fields,
|
|
610
|
+
kind,
|
|
611
|
+
id,
|
|
612
|
+
updatedSeq,
|
|
613
|
+
...position === void 0 ? {} : { position }
|
|
614
|
+
};
|
|
615
|
+
};
|
|
616
|
+
const flatToEnvelope = (record) => {
|
|
617
|
+
const { kind, id, updatedSeq, position, ...body } = record;
|
|
618
|
+
return Schema.decodeUnknownSync(TranscriptRecordEnvelope)({
|
|
619
|
+
format: 1,
|
|
620
|
+
kind,
|
|
621
|
+
id,
|
|
622
|
+
updatedSeq,
|
|
623
|
+
...position === void 0 ? {} : { position },
|
|
624
|
+
body
|
|
625
|
+
});
|
|
626
|
+
};
|
|
627
|
+
const FlatRecordFields = Schema.Record(Schema.String, Schema.Unknown);
|
|
628
|
+
/** A known record stored or sent as its envelope. Decoding fails for anything this reader cannot interpret. */
|
|
629
|
+
const TranscriptRecordFromEnvelope = TranscriptRecordEnvelope.check(Schema.makeFilter((envelope) => envelope.format <= 1 || `unsupported transcript record envelope format ${envelope.format}`)).pipe(Schema.decodeTo(FlatRecordFields, {
|
|
630
|
+
decode: SchemaGetter.transform(envelopeToFlat),
|
|
631
|
+
encode: SchemaGetter.transform(flatToEnvelope)
|
|
632
|
+
}), Schema.decodeTo(TranscriptRecord, SchemaTransformation.passthroughSupertype()));
|
|
633
|
+
const knownRecordKinds = /* @__PURE__ */ new Set([
|
|
634
|
+
"user",
|
|
635
|
+
"assistant",
|
|
636
|
+
"compaction",
|
|
637
|
+
"tool",
|
|
638
|
+
"runGroup",
|
|
639
|
+
"sessionContext",
|
|
640
|
+
"decorationBuffer"
|
|
641
|
+
]);
|
|
642
|
+
/**
|
|
643
|
+
* Only a kind this reader does not know, or a newer envelope format, becomes `unknown`; a
|
|
644
|
+
* malformed record of a known kind in a known format is a decode failure, never a placeholder.
|
|
645
|
+
*/
|
|
646
|
+
const TranscriptUnknownRecordFromEnvelope = TranscriptRecordEnvelope.check(Schema.makeFilter((envelope) => !knownRecordKinds.has(envelope.kind) || envelope.format > 1 || `a ${envelope.kind} record in format ${envelope.format} must decode as that kind`)).pipe(Schema.decodeTo(TranscriptUnknownRecord, {
|
|
647
|
+
decode: SchemaGetter.transform((envelope) => ({
|
|
648
|
+
kind: "unknown",
|
|
649
|
+
originalKind: envelope.kind,
|
|
650
|
+
format: envelope.format,
|
|
651
|
+
body: envelope.body,
|
|
652
|
+
id: envelope.id,
|
|
653
|
+
updatedSeq: envelope.updatedSeq,
|
|
654
|
+
...envelope.position === void 0 ? {} : { position: envelope.position }
|
|
655
|
+
})),
|
|
656
|
+
encode: SchemaGetter.transform((record) => Schema.decodeUnknownSync(TranscriptRecordEnvelope)({
|
|
657
|
+
format: record.format,
|
|
658
|
+
kind: record.originalKind,
|
|
659
|
+
id: record.id,
|
|
660
|
+
updatedSeq: record.updatedSeq,
|
|
661
|
+
...record.position === void 0 ? {} : { position: record.position },
|
|
662
|
+
body: record.body
|
|
663
|
+
}))
|
|
664
|
+
}));
|
|
665
|
+
/**
|
|
666
|
+
* Wire codec for one record: a known record when this reader can interpret it, otherwise an
|
|
667
|
+
* explicit unknown record that keeps its id and position.
|
|
668
|
+
*/
|
|
669
|
+
const TranscriptRecordViewFromEnvelope = Schema.Union([TranscriptRecordFromEnvelope, TranscriptUnknownRecordFromEnvelope]);
|
|
670
|
+
//#endregion
|
|
671
|
+
//#region src/transcript/version.ts
|
|
672
|
+
/**
|
|
673
|
+
* EDA's transcript semantic revision.
|
|
674
|
+
*
|
|
675
|
+
* Bump it deliberately whenever the interpreter, the legacy-attempt normalizer, the record
|
|
676
|
+
* decoders or the mapping executor would interpret any existing log differently. A bump changes
|
|
677
|
+
* every transcript version, so every session rebuilds and every host must run its backfill.
|
|
678
|
+
* A new durable event type needs a bump only if this release gives it transcript meaning;
|
|
679
|
+
* events the interpreter ignores leave the revision and every version unchanged.
|
|
680
|
+
*
|
|
681
|
+
* A CI fingerprint over a fixed scenario corpus (added with the interpreter) fails when
|
|
682
|
+
* interpretation output changes and this constant does not; re-record it together with the bump.
|
|
683
|
+
*/
|
|
684
|
+
const transcriptSemanticRevision = 1;
|
|
685
|
+
/**
|
|
686
|
+
* Deterministic JSON: object keys sorted by code unit, no whitespace. Only JSON values are
|
|
687
|
+
* accepted, so equal data always produces equal bytes.
|
|
688
|
+
*/
|
|
689
|
+
const canonicalJson = (value) => {
|
|
690
|
+
if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
|
|
691
|
+
if (typeof value === "number") {
|
|
692
|
+
if (!Number.isFinite(value)) throw new Error(`canonicalJson cannot encode non-finite number ${value}`);
|
|
693
|
+
return JSON.stringify(value);
|
|
694
|
+
}
|
|
695
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
696
|
+
if (typeof value === "object") {
|
|
697
|
+
const entries = Object.entries(value).filter(([, entry]) => entry !== void 0);
|
|
698
|
+
entries.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
|
|
699
|
+
return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
|
|
700
|
+
}
|
|
701
|
+
throw new Error(`canonicalJson cannot encode ${typeof value}`);
|
|
702
|
+
};
|
|
703
|
+
/** Transcript version for a semantic revision and already-encoded canonical mapping data. */
|
|
704
|
+
const computeTranscriptVersion = (semanticRevision, encodedMappings) => TranscriptVersion.make(sha256Hex(canonicalJson({
|
|
705
|
+
semanticRevision,
|
|
706
|
+
mappings: encodedMappings
|
|
707
|
+
})));
|
|
708
|
+
//#endregion
|
|
709
|
+
//#region src/transcript/mapping.ts
|
|
710
|
+
/**
|
|
711
|
+
* Host decorations are data, not code. A host registers mappings from its own durable app events
|
|
712
|
+
* to decorations on transcript records; EDA validates them at registration and executes them
|
|
713
|
+
* with fixed bounds inside the projection.
|
|
714
|
+
*/
|
|
715
|
+
/** Bounds EDA enforces on every definition and every decoration it executes. */
|
|
716
|
+
const transcriptMappingBounds = {
|
|
717
|
+
maxMappings: 64,
|
|
718
|
+
maxOperationsPerMapping: 16,
|
|
719
|
+
maxPathLength: 16,
|
|
720
|
+
/** Canonical JSON bytes of one decoration value or list entry. */
|
|
721
|
+
maxValueBytes: 8192,
|
|
722
|
+
/**
|
|
723
|
+
* Canonical JSON bytes of all decorations of one record, and of one decoration buffer. An
|
|
724
|
+
* operation that would exceed it is skipped, so no record's row can approach storage value
|
|
725
|
+
* limits whatever a host appends.
|
|
726
|
+
*/
|
|
727
|
+
maxDecorationBytes: 262144,
|
|
728
|
+
/** Entries kept in one decoration list; further distinct entries are dropped. */
|
|
729
|
+
maxListEntries: 64,
|
|
730
|
+
maxUserFallbacks: 16
|
|
731
|
+
};
|
|
732
|
+
const MappingPath = TranscriptFieldPath.check(Schema.isMaxLength(transcriptMappingBounds.maxPathLength));
|
|
733
|
+
/** The app event a mapping reads: one host namespace, type and schema version. */
|
|
734
|
+
const TranscriptMappedEvent = Schema.Struct({
|
|
735
|
+
namespace: Schema.NonEmptyString,
|
|
736
|
+
type: Schema.NonEmptyString,
|
|
737
|
+
schemaVersion: SchemaVersion
|
|
738
|
+
});
|
|
739
|
+
/**
|
|
740
|
+
* Which record a mapping decorates.
|
|
741
|
+
*
|
|
742
|
+
* User targets associate through a payload field: the submitting command's id, or the
|
|
743
|
+
* command's idempotency key. A decoration that arrives before its target user record is held
|
|
744
|
+
* and applied, in arrival order, when the record is created. `Session` decorates the
|
|
745
|
+
* session-context singleton.
|
|
746
|
+
*/
|
|
747
|
+
const TranscriptMappingTarget = Schema.TaggedUnion({
|
|
748
|
+
UserByCommandId: { path: MappingPath },
|
|
749
|
+
UserByIdempotencyKey: { path: MappingPath },
|
|
750
|
+
Session: {}
|
|
751
|
+
});
|
|
752
|
+
/** How a list entry is identified when it is replaced. */
|
|
753
|
+
const TranscriptListEntryKey = Schema.TaggedUnion({
|
|
754
|
+
/** A string id at this payload path (for example an attachment id). */
|
|
755
|
+
Id: { path: MappingPath },
|
|
756
|
+
/** A non-negative integer ordinal at this payload path; the list is kept in ordinal order. */
|
|
757
|
+
Ordinal: { path: MappingPath }
|
|
758
|
+
});
|
|
759
|
+
/** One declarative decoration operation. Every `from` path reads the authenticated event payload. */
|
|
760
|
+
const TranscriptMappingOperation = Schema.TaggedUnion({
|
|
761
|
+
/** Copy a payload value into a decoration; the latest event wins. */
|
|
762
|
+
Copy: {
|
|
763
|
+
from: MappingPath,
|
|
764
|
+
to: TranscriptDecorationKey
|
|
765
|
+
},
|
|
766
|
+
/** Copy a payload value into a decoration only if the decoration is still absent. */
|
|
767
|
+
FirstWins: {
|
|
768
|
+
from: MappingPath,
|
|
769
|
+
to: TranscriptDecorationKey
|
|
770
|
+
},
|
|
771
|
+
/** Insert or replace one entry of a decoration list, keyed by id or by ordinal. */
|
|
772
|
+
ReplaceListEntry: {
|
|
773
|
+
from: MappingPath,
|
|
774
|
+
to: TranscriptDecorationKey,
|
|
775
|
+
key: TranscriptListEntryKey
|
|
776
|
+
},
|
|
777
|
+
/**
|
|
778
|
+
* Classify the target user record, for example as an authenticated subagent notice. A record
|
|
779
|
+
* holds one classification; the last one applied wins.
|
|
780
|
+
*/
|
|
781
|
+
Classify: { classification: TranscriptClassification }
|
|
782
|
+
});
|
|
783
|
+
/** One host mapping: an app event, the record it decorates, and the operations to apply. */
|
|
784
|
+
const TranscriptMapping = Schema.Struct({
|
|
785
|
+
/** Unique name; buffered decorations refer to it. */
|
|
786
|
+
name: TranscriptDecorationKey,
|
|
787
|
+
event: TranscriptMappedEvent,
|
|
788
|
+
target: TranscriptMappingTarget,
|
|
789
|
+
operations: Schema.NonEmptyArray(TranscriptMappingOperation).check(Schema.isMaxLength(transcriptMappingBounds.maxOperationsPerMapping))
|
|
790
|
+
});
|
|
791
|
+
/**
|
|
792
|
+
* A user decoration copied from a session decoration when the user record is created without
|
|
793
|
+
* it, for example "the most recent author" for a message whose command carried no author event.
|
|
794
|
+
*
|
|
795
|
+
* Fallbacks apply in declaration order, after any parked decorations, and each one applies only
|
|
796
|
+
* if the user decoration is still absent; so `[author ← lastAuthor, author ← owner]` means "the
|
|
797
|
+
* latest author, else the session owner".
|
|
798
|
+
*/
|
|
799
|
+
const TranscriptUserFallback = Schema.Struct({
|
|
800
|
+
to: TranscriptDecorationKey,
|
|
801
|
+
fromSession: TranscriptDecorationKey
|
|
802
|
+
});
|
|
803
|
+
/** The host's complete declarative transcript mapping data. */
|
|
804
|
+
const TranscriptMappings = Schema.Struct({
|
|
805
|
+
mappings: Schema.Array(TranscriptMapping).check(Schema.isMaxLength(transcriptMappingBounds.maxMappings)),
|
|
806
|
+
userFallbacks: Schema.Array(TranscriptUserFallback).check(Schema.isMaxLength(transcriptMappingBounds.maxUserFallbacks))
|
|
807
|
+
});
|
|
808
|
+
/** Mappings for a host that registers no decorations. */
|
|
809
|
+
const emptyTranscriptMappings = {
|
|
810
|
+
mappings: [],
|
|
811
|
+
userFallbacks: []
|
|
812
|
+
};
|
|
813
|
+
/** Host mapping data rejected at registration. */
|
|
814
|
+
var TranscriptDefinitionError = class extends Schema.TaggedError()("TranscriptDefinitionError", { message: Schema.String }) {};
|
|
815
|
+
const validationProblems = (mappings) => {
|
|
816
|
+
const problems = [];
|
|
817
|
+
const names = /* @__PURE__ */ new Set();
|
|
818
|
+
const shapes = /* @__PURE__ */ new Map();
|
|
819
|
+
const sessionValueKeys = /* @__PURE__ */ new Set();
|
|
820
|
+
const recordShape = (scope, key, shape) => {
|
|
821
|
+
const scoped = `${scope}:${key}`;
|
|
822
|
+
const existing = shapes.get(scoped);
|
|
823
|
+
if (existing !== void 0 && existing !== shape) problems.push(`${scope} decoration "${key}" is written as both ${existing} and ${shape}`);
|
|
824
|
+
shapes.set(scoped, shape);
|
|
825
|
+
};
|
|
826
|
+
for (const mapping of mappings.mappings) {
|
|
827
|
+
if (names.has(mapping.name)) problems.push(`duplicate mapping name "${mapping.name}"`);
|
|
828
|
+
names.add(mapping.name);
|
|
829
|
+
if (mapping.event.namespace === "effect-durable-agent" || mapping.event.namespace === "__foreign") problems.push(`mapping "${mapping.name}" may not read namespace ${mapping.event.namespace}`);
|
|
830
|
+
const scope = mapping.target._tag === "Session" ? "session" : "user";
|
|
831
|
+
for (const operation of mapping.operations) switch (operation._tag) {
|
|
832
|
+
case "Copy":
|
|
833
|
+
case "FirstWins":
|
|
834
|
+
recordShape(scope, operation.to, operation._tag === "Copy" ? "copy" : "first-wins");
|
|
835
|
+
if (scope === "session") sessionValueKeys.add(operation.to);
|
|
836
|
+
break;
|
|
837
|
+
case "ReplaceListEntry":
|
|
838
|
+
recordShape(scope, operation.to, `list:${operation.key._tag}`);
|
|
839
|
+
break;
|
|
840
|
+
case "Classify": if (scope === "session") problems.push(`mapping "${mapping.name}" classifies the session; only users can be classified`);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
const fallbacks = /* @__PURE__ */ new Set();
|
|
844
|
+
for (const fallback of mappings.userFallbacks) {
|
|
845
|
+
const key = `${fallback.to}\u0000${fallback.fromSession}`;
|
|
846
|
+
if (fallbacks.has(key)) problems.push(`duplicate user fallback ${fallback.to} <- ${fallback.fromSession}`);
|
|
847
|
+
fallbacks.add(key);
|
|
848
|
+
if (!sessionValueKeys.has(fallback.fromSession)) problems.push(`user fallback reads session decoration "${fallback.fromSession}", which no mapping writes as a value`);
|
|
849
|
+
const userShape = shapes.get(`user:${fallback.to}`);
|
|
850
|
+
if (userShape !== void 0 && userShape.startsWith("list:")) problems.push(`user fallback writes "${fallback.to}", which is a list decoration`);
|
|
851
|
+
}
|
|
852
|
+
return problems;
|
|
853
|
+
};
|
|
854
|
+
/**
|
|
855
|
+
* A validated transcript interpretation: EDA's semantic revision plus host mappings, identified
|
|
856
|
+
* by `version`. Only `makeTranscriptDefinition` constructs one.
|
|
857
|
+
*/
|
|
858
|
+
var TranscriptDefinition = class TranscriptDefinition {
|
|
859
|
+
version;
|
|
860
|
+
semanticRevision;
|
|
861
|
+
mappings;
|
|
862
|
+
constructor(version, semanticRevision, mappings) {
|
|
863
|
+
this.version = version;
|
|
864
|
+
this.semanticRevision = semanticRevision;
|
|
865
|
+
this.mappings = mappings;
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
* Validate host mapping data and derive its transcript version.
|
|
869
|
+
*
|
|
870
|
+
* Validation happens here, at registration, never during append: an accepted definition can
|
|
871
|
+
* only degrade individual decorations at runtime (a missing field, an oversize value), never
|
|
872
|
+
* event admission or other records.
|
|
873
|
+
*/
|
|
874
|
+
static make = Effect.fnUntraced(function* (input) {
|
|
875
|
+
const mappings = yield* Schema.decodeUnknownEffect(TranscriptMappings)(input).pipe(Effect.mapError((error) => new TranscriptDefinitionError({ message: error.message })));
|
|
876
|
+
const problems = validationProblems(mappings);
|
|
877
|
+
if (problems.length > 0) return yield* new TranscriptDefinitionError({ message: problems.join("; ") });
|
|
878
|
+
return new TranscriptDefinition(computeTranscriptVersion(1, Schema.encodeSync(TranscriptMappings)(mappings)), 1, mappings);
|
|
879
|
+
});
|
|
880
|
+
};
|
|
881
|
+
/** Validate host mapping data and derive its transcript version; see `TranscriptDefinition.make`. */
|
|
882
|
+
const makeTranscriptDefinition = TranscriptDefinition.make;
|
|
883
|
+
//#endregion
|
|
884
|
+
//#region src/transcript/plan.ts
|
|
885
|
+
/**
|
|
886
|
+
* Secondary keys that resolve to a record through an indexed join, never an in-memory map.
|
|
887
|
+
*
|
|
888
|
+
* - `messageId`: every message id a user submission has carried, including replacement ids.
|
|
889
|
+
* - `idempotencyKey`: a submitting command's caller-owned retry key.
|
|
890
|
+
* - `runId`: every run of a run group, so continuations resolve to the root's group.
|
|
891
|
+
* - `runCommand`: commands owned by a run group; a run that reuses them continues the group.
|
|
892
|
+
* - `toolPart`: `<inferenceId>/<providerPartId>`, linking an assistant tool-call part to its tool.
|
|
893
|
+
*/
|
|
894
|
+
const TranscriptAliasNamespace = Schema.Literals([
|
|
895
|
+
"messageId",
|
|
896
|
+
"idempotencyKey",
|
|
897
|
+
"runId",
|
|
898
|
+
"runCommand",
|
|
899
|
+
"toolPart"
|
|
900
|
+
]);
|
|
901
|
+
/** The stored projection cannot be advanced from the given lookup and batch. */
|
|
902
|
+
var TranscriptProjectionError = class extends Schema.TaggedError()("TranscriptProjectionError", { message: Schema.String }) {};
|
|
903
|
+
//#endregion
|
|
904
|
+
//#region src/transcript/mapping-executor.ts
|
|
905
|
+
const indexes = /* @__PURE__ */ new WeakMap();
|
|
906
|
+
const eventKey = (namespace, type, schemaVersion) => `${namespace}\u0000${type}\u0000${schemaVersion}`;
|
|
907
|
+
const mappingIndex = (definition) => {
|
|
908
|
+
const cached = indexes.get(definition);
|
|
909
|
+
if (cached !== void 0) return cached;
|
|
910
|
+
const byEvent = /* @__PURE__ */ new Map();
|
|
911
|
+
const byName = /* @__PURE__ */ new Map();
|
|
912
|
+
for (const mapping of definition.mappings.mappings) {
|
|
913
|
+
const key = eventKey(mapping.event.namespace, mapping.event.type, mapping.event.schemaVersion);
|
|
914
|
+
byEvent.set(key, [...byEvent.get(key) ?? [], mapping]);
|
|
915
|
+
byName.set(mapping.name, mapping);
|
|
916
|
+
}
|
|
917
|
+
const index = {
|
|
918
|
+
byEvent,
|
|
919
|
+
byName
|
|
920
|
+
};
|
|
921
|
+
indexes.set(definition, index);
|
|
922
|
+
return index;
|
|
923
|
+
};
|
|
924
|
+
/** Apply every mapping that names this app event. Unmapped events are ignored. */
|
|
925
|
+
const applyForeignEvent = (batch, envelope, seq) => {
|
|
926
|
+
const mappings = mappingIndex(batch.definition).byEvent.get(eventKey(envelope.namespace, envelope.type, envelope.schemaVersion));
|
|
927
|
+
for (const mapping of mappings ?? []) applyMapping(batch, mapping, envelope.payload, seq);
|
|
928
|
+
};
|
|
929
|
+
const applyMapping = (batch, mapping, payload, seq) => {
|
|
930
|
+
const prepared = mapping.operations.flatMap((operation, index) => prepareOperation(mapping.name, operation, index, payload));
|
|
931
|
+
if (prepared.length === 0) return;
|
|
932
|
+
const target = mapping.target;
|
|
933
|
+
switch (target._tag) {
|
|
934
|
+
case "Session": {
|
|
935
|
+
const session = batch.session(seq);
|
|
936
|
+
const applied = prepared.reduce((decorated, operation) => applyPrepared(batch.definition, decorated, operation), { decorations: session.decorations });
|
|
937
|
+
batch.put({
|
|
938
|
+
...session,
|
|
939
|
+
updatedSeq: seq,
|
|
940
|
+
decorations: applied.decorations
|
|
941
|
+
});
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
case "UserByCommandId": {
|
|
945
|
+
const commandId = extract(payload, target.path);
|
|
946
|
+
if (!Schema.is(CommandId)(commandId)) return;
|
|
947
|
+
const user = batch.user(transcriptRecordId.user(commandId));
|
|
948
|
+
if (user === void 0) park(batch, seq, "command", commandId, prepared);
|
|
949
|
+
else batch.put(decorateUser(batch.definition, {
|
|
950
|
+
...user,
|
|
951
|
+
updatedSeq: seq
|
|
952
|
+
}, prepared));
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
case "UserByIdempotencyKey": {
|
|
956
|
+
const key = extract(payload, target.path);
|
|
957
|
+
if (!Schema.is(CommandIdempotencyKey)(key)) return;
|
|
958
|
+
const userId = batch.alias("idempotencyKey", key);
|
|
959
|
+
const user = userId === void 0 ? void 0 : batch.user(userId);
|
|
960
|
+
if (user === void 0) park(batch, seq, "idempotencyKey", key, prepared);
|
|
961
|
+
else batch.put(decorateUser(batch.definition, {
|
|
962
|
+
...user,
|
|
963
|
+
updatedSeq: seq
|
|
964
|
+
}, prepared));
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
};
|
|
969
|
+
const prepareOperation = (mapping, operation, index, payload) => {
|
|
970
|
+
switch (operation._tag) {
|
|
971
|
+
case "Classify": return [{
|
|
972
|
+
mapping,
|
|
973
|
+
operation: index,
|
|
974
|
+
value: null
|
|
975
|
+
}];
|
|
976
|
+
case "Copy":
|
|
977
|
+
case "FirstWins": {
|
|
978
|
+
const value = boundedJson(extract(payload, operation.from));
|
|
979
|
+
return value === void 0 ? [] : [{
|
|
980
|
+
mapping,
|
|
981
|
+
operation: index,
|
|
982
|
+
value
|
|
983
|
+
}];
|
|
984
|
+
}
|
|
985
|
+
case "ReplaceListEntry": {
|
|
986
|
+
const value = boundedJson(extract(payload, operation.from));
|
|
987
|
+
const entryKey = listEntryKey(operation.key, payload);
|
|
988
|
+
return value === void 0 || entryKey === void 0 ? [] : [{
|
|
989
|
+
mapping,
|
|
990
|
+
operation: index,
|
|
991
|
+
value,
|
|
992
|
+
entryKey
|
|
993
|
+
}];
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
};
|
|
997
|
+
const listEntryKey = (key, payload) => {
|
|
998
|
+
const value = extract(payload, key.path);
|
|
999
|
+
switch (key._tag) {
|
|
1000
|
+
case "Id": return typeof value === "string" && value.length > 0 && Schema.is(TranscriptDecorationEntryKey)(value) ? value : void 0;
|
|
1001
|
+
case "Ordinal": return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
1002
|
+
}
|
|
1003
|
+
};
|
|
1004
|
+
const park = (batch, seq, association, key, prepared) => {
|
|
1005
|
+
const id = transcriptRecordId.decorationBuffer(association, key);
|
|
1006
|
+
const existing = batch.get(id);
|
|
1007
|
+
if (existing !== void 0 && existing.kind !== "decorationBuffer") throw new TranscriptProjectionError({ message: `record ${id} is ${existing.kind}, expected decorationBuffer` });
|
|
1008
|
+
const buffer = {
|
|
1009
|
+
kind: "decorationBuffer",
|
|
1010
|
+
id,
|
|
1011
|
+
updatedSeq: seq,
|
|
1012
|
+
operations: withinBudget([...existing?.operations ?? [], ...prepared.map((operation) => ({
|
|
1013
|
+
...operation,
|
|
1014
|
+
seq
|
|
1015
|
+
}))])
|
|
1016
|
+
};
|
|
1017
|
+
batch.put(buffer);
|
|
1018
|
+
};
|
|
1019
|
+
/**
|
|
1020
|
+
* Apply decorations parked for a new user record, in arrival order, then the host's user
|
|
1021
|
+
* fallbacks for decorations that are still absent.
|
|
1022
|
+
*/
|
|
1023
|
+
const replayBufferedDecorations = (batch, seq, user) => {
|
|
1024
|
+
const buffered = [transcriptRecordId.decorationBuffer("command", user.commandId), ...user.idempotencyKey === void 0 ? [] : [transcriptRecordId.decorationBuffer("idempotencyKey", user.idempotencyKey)]].flatMap((id) => {
|
|
1025
|
+
const buffer = batch.get(id);
|
|
1026
|
+
if (buffer?.kind !== "decorationBuffer" || buffer.operations.length === 0) return [];
|
|
1027
|
+
batch.put({
|
|
1028
|
+
...buffer,
|
|
1029
|
+
updatedSeq: seq,
|
|
1030
|
+
operations: []
|
|
1031
|
+
});
|
|
1032
|
+
return buffer.operations;
|
|
1033
|
+
});
|
|
1034
|
+
buffered.sort((left, right) => left.seq - right.seq);
|
|
1035
|
+
const decorated = decorateUser(batch.definition, user, buffered);
|
|
1036
|
+
const session = batch.get(transcriptRecordId.session);
|
|
1037
|
+
if (session?.kind !== "sessionContext" || decorated.classification !== void 0) return decorated;
|
|
1038
|
+
let decorations = decorated.decorations;
|
|
1039
|
+
for (const fallback of batch.definition.mappings.userFallbacks) {
|
|
1040
|
+
const source = session.decorations[fallback.fromSession];
|
|
1041
|
+
if (decorations[fallback.to] === void 0 && source?._tag === "Value") {
|
|
1042
|
+
const next = {
|
|
1043
|
+
...decorations,
|
|
1044
|
+
[fallback.to]: source
|
|
1045
|
+
};
|
|
1046
|
+
if (jsonBytes$1(next) <= transcriptMappingBounds.maxDecorationBytes) decorations = next;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
return decorations === decorated.decorations ? decorated : {
|
|
1050
|
+
...decorated,
|
|
1051
|
+
updatedSeq: seq,
|
|
1052
|
+
decorations
|
|
1053
|
+
};
|
|
1054
|
+
};
|
|
1055
|
+
const decorateUser = (definition, user, operations) => {
|
|
1056
|
+
const decorated = operations.reduce((current, operation) => applyPrepared(definition, current, operation), {
|
|
1057
|
+
decorations: user.decorations,
|
|
1058
|
+
...user.classification === void 0 ? {} : { classification: user.classification }
|
|
1059
|
+
});
|
|
1060
|
+
return {
|
|
1061
|
+
...user,
|
|
1062
|
+
decorations: decorated.decorations,
|
|
1063
|
+
...decorated.classification === void 0 ? {} : { classification: decorated.classification }
|
|
1064
|
+
};
|
|
1065
|
+
};
|
|
1066
|
+
/** The longest prefix of parked operations within the buffer's count and byte bounds. */
|
|
1067
|
+
const withinBudget = (operations) => {
|
|
1068
|
+
const kept = [];
|
|
1069
|
+
let bytes = 2;
|
|
1070
|
+
for (const operation of operations.slice(0, 32)) {
|
|
1071
|
+
bytes += jsonBytes$1(operation) + 1;
|
|
1072
|
+
if (bytes > transcriptMappingBounds.maxDecorationBytes) break;
|
|
1073
|
+
kept.push(operation);
|
|
1074
|
+
}
|
|
1075
|
+
return kept;
|
|
1076
|
+
};
|
|
1077
|
+
/** Apply one operation unless the record's decorations would exceed their byte budget. */
|
|
1078
|
+
const applyPrepared = (definition, target, prepared) => {
|
|
1079
|
+
const next = applyOperation(definition, target, prepared);
|
|
1080
|
+
return next === target || jsonBytes$1(next.decorations) <= transcriptMappingBounds.maxDecorationBytes ? next : target;
|
|
1081
|
+
};
|
|
1082
|
+
const jsonBytes$1 = (value) => encoder$1.encode(canonicalJson(value)).length;
|
|
1083
|
+
const applyOperation = (definition, target, prepared) => {
|
|
1084
|
+
const operation = mappingIndex(definition).byName.get(prepared.mapping)?.operations[prepared.operation];
|
|
1085
|
+
if (operation === void 0) return target;
|
|
1086
|
+
switch (operation._tag) {
|
|
1087
|
+
case "Classify": return {
|
|
1088
|
+
...target,
|
|
1089
|
+
classification: operation.classification
|
|
1090
|
+
};
|
|
1091
|
+
case "Copy": return withDecoration(target, operation.to, {
|
|
1092
|
+
_tag: "Value",
|
|
1093
|
+
value: prepared.value
|
|
1094
|
+
});
|
|
1095
|
+
case "FirstWins": return target.decorations[operation.to] === void 0 ? withDecoration(target, operation.to, {
|
|
1096
|
+
_tag: "Value",
|
|
1097
|
+
value: prepared.value
|
|
1098
|
+
}) : target;
|
|
1099
|
+
case "ReplaceListEntry": {
|
|
1100
|
+
if (prepared.entryKey === void 0) return target;
|
|
1101
|
+
const list = replaceListEntry(target.decorations[operation.to], prepared.entryKey, prepared.value, operation.key._tag === "Ordinal");
|
|
1102
|
+
return list === void 0 ? target : withDecoration(target, operation.to, list);
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
const withDecoration = (target, key, decoration) => ({
|
|
1107
|
+
...target,
|
|
1108
|
+
decorations: {
|
|
1109
|
+
...target.decorations,
|
|
1110
|
+
[key]: decoration
|
|
1111
|
+
}
|
|
1112
|
+
});
|
|
1113
|
+
const replaceListEntry = (existing, key, value, ordered) => {
|
|
1114
|
+
const entries = existing?._tag === "List" ? existing.entries : [];
|
|
1115
|
+
const index = entries.findIndex((entry) => entry.key === key);
|
|
1116
|
+
if (index >= 0) return {
|
|
1117
|
+
_tag: "List",
|
|
1118
|
+
entries: entries.map((entry, position) => position === index ? {
|
|
1119
|
+
key,
|
|
1120
|
+
value
|
|
1121
|
+
} : entry)
|
|
1122
|
+
};
|
|
1123
|
+
if (entries.length >= transcriptMappingBounds.maxListEntries) return void 0;
|
|
1124
|
+
const next = [...entries, {
|
|
1125
|
+
key,
|
|
1126
|
+
value
|
|
1127
|
+
}];
|
|
1128
|
+
if (ordered) next.sort((left, right) => Number(left.key) - Number(right.key));
|
|
1129
|
+
return {
|
|
1130
|
+
_tag: "List",
|
|
1131
|
+
entries: next
|
|
1132
|
+
};
|
|
1133
|
+
};
|
|
1134
|
+
/** Read a payload value by path through own properties only. */
|
|
1135
|
+
const extract = (value, path) => path.reduce((current, key) => {
|
|
1136
|
+
if (typeof key === "number") return Array.isArray(current) ? current[key] : void 0;
|
|
1137
|
+
if (current === null || typeof current !== "object" || Array.isArray(current)) return;
|
|
1138
|
+
return Object.getOwnPropertyDescriptor(current, key)?.value;
|
|
1139
|
+
}, value);
|
|
1140
|
+
const encoder$1 = new TextEncoder();
|
|
1141
|
+
/**
|
|
1142
|
+
* A payload value as the JSON a persisted log holds (so a live projection and a rebuild agree),
|
|
1143
|
+
* within the value bound; otherwise nothing.
|
|
1144
|
+
*/
|
|
1145
|
+
const boundedJson = (value) => {
|
|
1146
|
+
if (value === void 0) return void 0;
|
|
1147
|
+
try {
|
|
1148
|
+
const json = JSON.stringify(value);
|
|
1149
|
+
if (json === void 0) return void 0;
|
|
1150
|
+
const normalized = JSON.parse(json);
|
|
1151
|
+
return Schema.is(Schema.Json)(normalized) && encoder$1.encode(canonicalJson(normalized)).length <= transcriptMappingBounds.maxValueBytes ? normalized : void 0;
|
|
1152
|
+
} catch {
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
};
|
|
1156
|
+
//#endregion
|
|
1157
|
+
//#region src/transcript/interpreter.ts
|
|
1158
|
+
/**
|
|
1159
|
+
* Accumulates one batch's changes over a committed lookup.
|
|
1160
|
+
*
|
|
1161
|
+
* Every handler reads through this overlay, so later events in a batch see earlier ones, and the
|
|
1162
|
+
* plan is the same whichever way a log is split into batches: interpretation is a sequential fold
|
|
1163
|
+
* whose only state is the records themselves.
|
|
1164
|
+
*/
|
|
1165
|
+
var TranscriptBatch = class {
|
|
1166
|
+
lookup;
|
|
1167
|
+
definition;
|
|
1168
|
+
records = /* @__PURE__ */ new Map();
|
|
1169
|
+
aliases = /* @__PURE__ */ new Map();
|
|
1170
|
+
ordinals = /* @__PURE__ */ new Map();
|
|
1171
|
+
constructor(lookup, definition) {
|
|
1172
|
+
this.lookup = lookup;
|
|
1173
|
+
this.definition = definition;
|
|
1174
|
+
}
|
|
1175
|
+
get(id) {
|
|
1176
|
+
return this.records.get(id) ?? this.lookup.record(id);
|
|
1177
|
+
}
|
|
1178
|
+
put(record) {
|
|
1179
|
+
this.records.set(record.id, record);
|
|
1180
|
+
}
|
|
1181
|
+
user(id) {
|
|
1182
|
+
const record = this.get(id);
|
|
1183
|
+
if (record === void 0) return void 0;
|
|
1184
|
+
if (record.kind !== "user") throw kindMismatch(id, "user", record.kind);
|
|
1185
|
+
return record;
|
|
1186
|
+
}
|
|
1187
|
+
assistant(id) {
|
|
1188
|
+
const record = this.get(id);
|
|
1189
|
+
if (record === void 0) return void 0;
|
|
1190
|
+
if (record.kind !== "assistant") throw kindMismatch(id, "assistant", record.kind);
|
|
1191
|
+
return record;
|
|
1192
|
+
}
|
|
1193
|
+
tool(id) {
|
|
1194
|
+
const record = this.get(id);
|
|
1195
|
+
if (record === void 0) return void 0;
|
|
1196
|
+
if (record.kind !== "tool") throw kindMismatch(id, "tool", record.kind);
|
|
1197
|
+
return record;
|
|
1198
|
+
}
|
|
1199
|
+
runGroup(id) {
|
|
1200
|
+
const record = this.get(id);
|
|
1201
|
+
if (record === void 0) return void 0;
|
|
1202
|
+
if (record.kind !== "runGroup") throw kindMismatch(id, "runGroup", record.kind);
|
|
1203
|
+
return record;
|
|
1204
|
+
}
|
|
1205
|
+
session(seq) {
|
|
1206
|
+
const record = this.get(transcriptRecordId.session);
|
|
1207
|
+
if (record === void 0) return {
|
|
1208
|
+
kind: "sessionContext",
|
|
1209
|
+
id: transcriptRecordId.session,
|
|
1210
|
+
updatedSeq: seq,
|
|
1211
|
+
tokenUsage: { byModel: [] },
|
|
1212
|
+
decorations: {}
|
|
1213
|
+
};
|
|
1214
|
+
if (record.kind !== "sessionContext") throw kindMismatch(transcriptRecordId.session, "sessionContext", record.kind);
|
|
1215
|
+
return record;
|
|
1216
|
+
}
|
|
1217
|
+
alias(namespace, key) {
|
|
1218
|
+
return this.aliases.get(aliasKey(namespace, key))?.recordId ?? this.lookup.alias(namespace, key);
|
|
1219
|
+
}
|
|
1220
|
+
/** Insert an alias unless one exists; an alias never moves to another record. */
|
|
1221
|
+
insertAlias(namespace, key, recordId) {
|
|
1222
|
+
if (this.alias(namespace, key) !== void 0) return;
|
|
1223
|
+
this.aliases.set(aliasKey(namespace, key), {
|
|
1224
|
+
namespace,
|
|
1225
|
+
key,
|
|
1226
|
+
recordId
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
position(anchorSeq) {
|
|
1230
|
+
const ordinal = this.ordinals.get(anchorSeq) ?? this.lookup.nextOrdinal(anchorSeq);
|
|
1231
|
+
this.ordinals.set(anchorSeq, ordinal + 1);
|
|
1232
|
+
return {
|
|
1233
|
+
anchorSeq,
|
|
1234
|
+
ordinal
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
plan(throughSeq) {
|
|
1238
|
+
for (const record of this.records.values()) {
|
|
1239
|
+
const problem = storageProblem(record);
|
|
1240
|
+
if (problem !== void 0) throw new TranscriptProjectionError({ message: `planned record ${record.id} ${problem}` });
|
|
1241
|
+
}
|
|
1242
|
+
return {
|
|
1243
|
+
records: Array.from(this.records.values()),
|
|
1244
|
+
aliases: Array.from(this.aliases.values()),
|
|
1245
|
+
throughSeq
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
};
|
|
1249
|
+
const aliasKey = (namespace, key) => `${namespace}\u0000${key}`;
|
|
1250
|
+
const matchesRecordSchema = Schema.is(TranscriptRecord);
|
|
1251
|
+
const encodeRecord$1 = Schema.encodeSync(TranscriptRecordFromEnvelope);
|
|
1252
|
+
const describeCause = (cause) => cause instanceof Error ? cause.message : String(cause);
|
|
1253
|
+
/**
|
|
1254
|
+
* Why a record could not be stored, if it could not: it must satisfy the stored-row schema,
|
|
1255
|
+
* filters included, and its envelope must be JSON, which is exactly what a store can write and
|
|
1256
|
+
* every reader can encode. The cause is kept so a frozen version can be diagnosed from its meta.
|
|
1257
|
+
*/
|
|
1258
|
+
const storageProblem = (record) => {
|
|
1259
|
+
let envelope;
|
|
1260
|
+
try {
|
|
1261
|
+
envelope = encodeRecord$1(record);
|
|
1262
|
+
} catch (cause) {
|
|
1263
|
+
return `does not satisfy the transcript record schema: ${describeCause(cause)}`;
|
|
1264
|
+
}
|
|
1265
|
+
if (!matchesRecordSchema(record)) return "does not satisfy the transcript record schema";
|
|
1266
|
+
try {
|
|
1267
|
+
return JSON.stringify(envelope) === void 0 ? "has no JSON envelope" : void 0;
|
|
1268
|
+
} catch (cause) {
|
|
1269
|
+
return `is not JSON: ${describeCause(cause)}`;
|
|
1270
|
+
}
|
|
1271
|
+
};
|
|
1272
|
+
const kindMismatch = (id, expected, actual) => new TranscriptProjectionError({ message: `record ${id} is ${actual}, expected ${expected}` });
|
|
1273
|
+
/**
|
|
1274
|
+
* Interpret one committed batch into a transcript change plan.
|
|
1275
|
+
*
|
|
1276
|
+
* Mirrors the `ReducedState` message, tool and inference fold without pruning: a
|
|
1277
|
+
* `ContextRebased` only adds a compaction marker. Events at or below the lookup cursor are
|
|
1278
|
+
* skipped, so an idempotent re-append is harmless. Foreign events are ignored unless a mapping
|
|
1279
|
+
* of `definition` names their namespace, type and schema version.
|
|
1280
|
+
*/
|
|
1281
|
+
const planTranscriptBatch = (lookup, committed, definition) => {
|
|
1282
|
+
const batch = new TranscriptBatch(lookup, definition);
|
|
1283
|
+
let throughSeq = lookup.cursor;
|
|
1284
|
+
for (const entry of committed) {
|
|
1285
|
+
const seq = entry.position.seq;
|
|
1286
|
+
if (seq <= throughSeq) continue;
|
|
1287
|
+
throughSeq = seq;
|
|
1288
|
+
if (entry.event.namespace === "__foreign") {
|
|
1289
|
+
applyForeignEvent(batch, entry.event.envelope, seq);
|
|
1290
|
+
continue;
|
|
1291
|
+
}
|
|
1292
|
+
if (entry.event.namespace !== "effect-durable-agent") continue;
|
|
1293
|
+
interpretEvent(batch, entry, seq);
|
|
1294
|
+
}
|
|
1295
|
+
return batch.plan(throughSeq);
|
|
1296
|
+
};
|
|
1297
|
+
const eventTime = (createdAtMs) => UnixEpochMillis.make(createdAtMs);
|
|
1298
|
+
const interpretEvent = (batch, entry, seq) => {
|
|
1299
|
+
if (entry.event.namespace === "__foreign") return;
|
|
1300
|
+
const event = interpretLegacyAttemptForReduction(entry.event);
|
|
1301
|
+
const at = eventTime(event.createdAtMs);
|
|
1302
|
+
switch (event.type) {
|
|
1303
|
+
case sessionConfiguredEventType: {
|
|
1304
|
+
const session = batch.session(seq);
|
|
1305
|
+
if (session.modelSelection === void 0) batch.put({
|
|
1306
|
+
...session,
|
|
1307
|
+
updatedSeq: seq,
|
|
1308
|
+
modelSelection: jsonModelSelection(event.payload.modelSelection)
|
|
1309
|
+
});
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
case commandAdmittedEventType: {
|
|
1313
|
+
const { command } = event.payload;
|
|
1314
|
+
if (command._tag !== "SubmitMessage" || command.commandId === void 0) return;
|
|
1315
|
+
const id = transcriptRecordId.user(command.commandId);
|
|
1316
|
+
if (batch.get(id) !== void 0) return;
|
|
1317
|
+
createUser(batch, seq, at, {
|
|
1318
|
+
commandId: command.commandId,
|
|
1319
|
+
content: command.content,
|
|
1320
|
+
state: command.disposition === "steer" ? { _tag: "Steering" } : { _tag: "Pending" },
|
|
1321
|
+
disposition: command.disposition,
|
|
1322
|
+
...command.idempotencyKey === void 0 ? {} : { idempotencyKey: command.idempotencyKey }
|
|
1323
|
+
});
|
|
1324
|
+
return;
|
|
1325
|
+
}
|
|
1326
|
+
case commandCancelledEventType:
|
|
1327
|
+
case commandFailedEventType: {
|
|
1328
|
+
const user = batch.user(transcriptRecordId.user(event.payload.commandId));
|
|
1329
|
+
if (user === void 0 || user.messageIds.length > 0 || !isWaiting(user.state)) return;
|
|
1330
|
+
batch.put({
|
|
1331
|
+
...user,
|
|
1332
|
+
updatedSeq: seq,
|
|
1333
|
+
state: {
|
|
1334
|
+
_tag: "Cancelled",
|
|
1335
|
+
reason: event.type === commandFailedEventType ? `failed: ${event.payload.error.message}` : event.payload.reason
|
|
1336
|
+
}
|
|
1337
|
+
});
|
|
1338
|
+
return;
|
|
1339
|
+
}
|
|
1340
|
+
case userMessageSubmittedEventType: {
|
|
1341
|
+
const { commandId, messageId, disposition, content } = event.payload;
|
|
1342
|
+
const user = userForMessage(batch, seq, at, commandId, messageId, content);
|
|
1343
|
+
batch.put({
|
|
1344
|
+
...user,
|
|
1345
|
+
updatedSeq: seq,
|
|
1346
|
+
content,
|
|
1347
|
+
disposition,
|
|
1348
|
+
state: isWaiting(user.state) ? disposition === "steer" ? { _tag: "Steering" } : { _tag: "Pending" } : user.state
|
|
1349
|
+
});
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
case userMessageCommittedEventType: {
|
|
1353
|
+
const { commandId, messageId, content } = event.payload;
|
|
1354
|
+
const user = userForMessage(batch, seq, at, commandId, messageId, content);
|
|
1355
|
+
batch.put(user.state._tag === "Consumed" ? {
|
|
1356
|
+
...user,
|
|
1357
|
+
updatedSeq: seq,
|
|
1358
|
+
content
|
|
1359
|
+
} : consume(batch, {
|
|
1360
|
+
...user,
|
|
1361
|
+
content
|
|
1362
|
+
}, seq, at, {}));
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
case steeringMessageQueuedEventType: {
|
|
1366
|
+
const { commandId, messageId, runId, content } = event.payload;
|
|
1367
|
+
const user = userForMessage(batch, seq, at, commandId, messageId, content);
|
|
1368
|
+
batch.put({
|
|
1369
|
+
...user,
|
|
1370
|
+
updatedSeq: seq,
|
|
1371
|
+
content,
|
|
1372
|
+
steering: { runId },
|
|
1373
|
+
state: isWaiting(user.state) ? { _tag: "Steering" } : user.state
|
|
1374
|
+
});
|
|
1375
|
+
return;
|
|
1376
|
+
}
|
|
1377
|
+
case steeringMessageCancelledEventType: {
|
|
1378
|
+
const user = userByMessage(batch, event.payload.messageId);
|
|
1379
|
+
if (user?.steering === void 0 || user.state._tag === "Consumed") return;
|
|
1380
|
+
batch.put({
|
|
1381
|
+
...user,
|
|
1382
|
+
updatedSeq: seq,
|
|
1383
|
+
state: {
|
|
1384
|
+
_tag: "Cancelled",
|
|
1385
|
+
reason: event.payload.reason
|
|
1386
|
+
}
|
|
1387
|
+
});
|
|
1388
|
+
return;
|
|
1389
|
+
}
|
|
1390
|
+
case userMessagePromotedEventType: {
|
|
1391
|
+
const user = userByMessage(batch, event.payload.messageId);
|
|
1392
|
+
if (user === void 0) return;
|
|
1393
|
+
if (user.state._tag !== "Pending" && user.state._tag !== "Paused") return;
|
|
1394
|
+
batch.put({
|
|
1395
|
+
...user,
|
|
1396
|
+
updatedSeq: seq,
|
|
1397
|
+
...user.steering === void 0 ? { disposition: "steer" } : {},
|
|
1398
|
+
state: { _tag: "Promoted" }
|
|
1399
|
+
});
|
|
1400
|
+
return;
|
|
1401
|
+
}
|
|
1402
|
+
case userMessageCancelledEventType: {
|
|
1403
|
+
const { commandId, messageId, reason } = event.payload;
|
|
1404
|
+
const user = userByMessage(batch, messageId);
|
|
1405
|
+
if (user === void 0 || user.state._tag === "Cancelled") return;
|
|
1406
|
+
if (user.steering !== void 0 && user.state._tag === "Consumed") return;
|
|
1407
|
+
batch.put({
|
|
1408
|
+
...user,
|
|
1409
|
+
updatedSeq: seq,
|
|
1410
|
+
state: {
|
|
1411
|
+
_tag: "Cancelled",
|
|
1412
|
+
reason,
|
|
1413
|
+
byCommandId: commandId
|
|
1414
|
+
}
|
|
1415
|
+
});
|
|
1416
|
+
return;
|
|
1417
|
+
}
|
|
1418
|
+
case messageQueuePausedEventType:
|
|
1419
|
+
case pendingMessagesPausedEventType: {
|
|
1420
|
+
const byCommandId = event.type === messageQueuePausedEventType ? event.payload.stopCommandId : event.payload.interruptionCommandId;
|
|
1421
|
+
for (const messageId of event.payload.messageIds) {
|
|
1422
|
+
const user = userByMessage(batch, messageId);
|
|
1423
|
+
if (user === void 0 || !isWaiting(user.state)) continue;
|
|
1424
|
+
batch.put({
|
|
1425
|
+
...user,
|
|
1426
|
+
updatedSeq: seq,
|
|
1427
|
+
...user.steering === void 0 ? { disposition: "queue" } : {},
|
|
1428
|
+
state: {
|
|
1429
|
+
_tag: "Paused",
|
|
1430
|
+
byCommandId
|
|
1431
|
+
}
|
|
1432
|
+
});
|
|
1433
|
+
}
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
case turnStartedEventType: {
|
|
1437
|
+
const { runId, turnId, inputMessageIds } = event.payload;
|
|
1438
|
+
for (const messageId of inputMessageIds ?? []) {
|
|
1439
|
+
const user = userByMessage(batch, messageId);
|
|
1440
|
+
if (user === void 0 || user.state._tag === "Consumed") continue;
|
|
1441
|
+
if (user.state._tag === "Cancelled" && user.steering === void 0) continue;
|
|
1442
|
+
batch.put(consume(batch, user, seq, at, {
|
|
1443
|
+
runId,
|
|
1444
|
+
turnId
|
|
1445
|
+
}));
|
|
1446
|
+
}
|
|
1447
|
+
return;
|
|
1448
|
+
}
|
|
1449
|
+
case assistantMessageCommittedEventType:
|
|
1450
|
+
case assistantPartialCommittedEventType: {
|
|
1451
|
+
const { messageId, runId, turnId, inferenceId, promptParts } = event.payload;
|
|
1452
|
+
const id = transcriptRecordId.assistant(inferenceId);
|
|
1453
|
+
const { partial: _partial, ...withoutPartial } = batch.assistant(id) ?? newAssistant(batch, id, seq, "inference", inferenceId, runId, turnId);
|
|
1454
|
+
batch.put({
|
|
1455
|
+
...withoutPartial,
|
|
1456
|
+
updatedSeq: seq,
|
|
1457
|
+
messageId,
|
|
1458
|
+
parts: assistantParts(batch, inferenceId, promptParts, seq),
|
|
1459
|
+
...event.type === assistantPartialCommittedEventType ? { partial: { reason: event.payload.reason } } : {}
|
|
1460
|
+
});
|
|
1461
|
+
return;
|
|
1462
|
+
}
|
|
1463
|
+
case assistantMessageImportedEventType: {
|
|
1464
|
+
const { messageId, runId, turnId, inferenceId, promptParts } = event.payload;
|
|
1465
|
+
const id = transcriptRecordId.import(event.eventId);
|
|
1466
|
+
const { runGroupId: _runGroupId, ...imported } = newAssistant(batch, id, seq, "import", inferenceId, runId, turnId);
|
|
1467
|
+
batch.put({
|
|
1468
|
+
...imported,
|
|
1469
|
+
messageId,
|
|
1470
|
+
lifecycle: { _tag: "Completed" },
|
|
1471
|
+
parts: assistantParts(batch, inferenceId, promptParts, seq)
|
|
1472
|
+
});
|
|
1473
|
+
return;
|
|
1474
|
+
}
|
|
1475
|
+
case inferenceStartedEventType: {
|
|
1476
|
+
const { runId, turnId, inferenceId } = event.payload;
|
|
1477
|
+
const id = transcriptRecordId.assistant(inferenceId);
|
|
1478
|
+
const existing = batch.assistant(id) ?? newAssistant(batch, id, seq, "inference", inferenceId, runId, turnId);
|
|
1479
|
+
batch.put({
|
|
1480
|
+
...existing,
|
|
1481
|
+
updatedSeq: seq,
|
|
1482
|
+
startedAtMs: at
|
|
1483
|
+
});
|
|
1484
|
+
return;
|
|
1485
|
+
}
|
|
1486
|
+
case inferenceCompletedEventType: {
|
|
1487
|
+
const { runId, inferenceId, finishReason, usage } = event.payload;
|
|
1488
|
+
const assistant = batch.assistant(transcriptRecordId.assistant(inferenceId));
|
|
1489
|
+
if (assistant === void 0) return;
|
|
1490
|
+
if (assistant.startedAtMs !== void 0 && assistant.lifecycle._tag !== "Completed") {
|
|
1491
|
+
const model = runMember(batch, runId)?.modelSelection;
|
|
1492
|
+
if (model !== void 0 && usage !== void 0) {
|
|
1493
|
+
const session = batch.session(seq);
|
|
1494
|
+
batch.put({
|
|
1495
|
+
...session,
|
|
1496
|
+
updatedSeq: seq,
|
|
1497
|
+
tokenUsage: addModelUsage(session.tokenUsage, model, usage)
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
batch.put({
|
|
1502
|
+
...assistant,
|
|
1503
|
+
updatedSeq: seq,
|
|
1504
|
+
...terminalTiming(assistant.startedAtMs, at),
|
|
1505
|
+
lifecycle: {
|
|
1506
|
+
_tag: "Completed",
|
|
1507
|
+
...finishReason === void 0 ? {} : { finishReason },
|
|
1508
|
+
...usage === void 0 ? {} : { usage }
|
|
1509
|
+
}
|
|
1510
|
+
});
|
|
1511
|
+
return;
|
|
1512
|
+
}
|
|
1513
|
+
case inferenceFailedEventType: {
|
|
1514
|
+
const assistant = batch.assistant(transcriptRecordId.assistant(event.payload.inferenceId));
|
|
1515
|
+
if (assistant === void 0) return;
|
|
1516
|
+
batch.put({
|
|
1517
|
+
...assistant,
|
|
1518
|
+
updatedSeq: seq,
|
|
1519
|
+
...terminalTiming(assistant.startedAtMs, at),
|
|
1520
|
+
lifecycle: {
|
|
1521
|
+
_tag: "Failed",
|
|
1522
|
+
error: jsonFailure(event.payload.error)
|
|
1523
|
+
}
|
|
1524
|
+
});
|
|
1525
|
+
return;
|
|
1526
|
+
}
|
|
1527
|
+
case toolCallCreatedEventType: {
|
|
1528
|
+
const { inferenceId, toolCallId, promptPart } = event.payload;
|
|
1529
|
+
const id = transcriptRecordId.tool(toolCallId);
|
|
1530
|
+
const existing = batch.tool(id);
|
|
1531
|
+
batch.put({
|
|
1532
|
+
kind: "tool",
|
|
1533
|
+
id,
|
|
1534
|
+
updatedSeq: seq,
|
|
1535
|
+
toolCallId,
|
|
1536
|
+
assistantId: transcriptRecordId.assistant(inferenceId),
|
|
1537
|
+
providerPartId: promptPart.id,
|
|
1538
|
+
toolName: promptPart.name,
|
|
1539
|
+
providerExecuted: promptPart.providerExecuted,
|
|
1540
|
+
params: inlineBody(promptPart.params, seq, ["promptPart", "params"]),
|
|
1541
|
+
lifecycle: existing === void 0 || existing.lifecycle._tag === "Rejected" ? { _tag: "Created" } : existing.lifecycle,
|
|
1542
|
+
createdAtMs: existing?.createdAtMs ?? at,
|
|
1543
|
+
...timingOf(existing)
|
|
1544
|
+
});
|
|
1545
|
+
linkToolPart(batch, inferenceId, promptPart.id, id, seq);
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
case toolCallRejectedEventType: {
|
|
1549
|
+
const { inferenceId, toolCallId, promptPart } = event.payload;
|
|
1550
|
+
const id = transcriptRecordId.tool(toolCallId);
|
|
1551
|
+
const existing = batch.tool(id);
|
|
1552
|
+
batch.put({
|
|
1553
|
+
kind: "tool",
|
|
1554
|
+
id,
|
|
1555
|
+
updatedSeq: seq,
|
|
1556
|
+
toolCallId,
|
|
1557
|
+
assistantId: transcriptRecordId.assistant(inferenceId),
|
|
1558
|
+
providerPartId: promptPart.id,
|
|
1559
|
+
toolName: promptPart.name,
|
|
1560
|
+
providerExecuted: false,
|
|
1561
|
+
lifecycle: {
|
|
1562
|
+
_tag: "Rejected",
|
|
1563
|
+
reason: promptPart.result.reason,
|
|
1564
|
+
message: promptPart.result.message,
|
|
1565
|
+
modelFeedback: promptPart.result.modelFeedback
|
|
1566
|
+
},
|
|
1567
|
+
createdAtMs: existing?.createdAtMs ?? at,
|
|
1568
|
+
...timingOf(existing)
|
|
1569
|
+
});
|
|
1570
|
+
linkToolPart(batch, inferenceId, promptPart.id, id, seq);
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
case toolCallStartedEventType: {
|
|
1574
|
+
const tool = batch.tool(transcriptRecordId.tool(event.payload.toolCallId));
|
|
1575
|
+
if (tool === void 0) return;
|
|
1576
|
+
batch.put({
|
|
1577
|
+
...tool,
|
|
1578
|
+
updatedSeq: seq,
|
|
1579
|
+
startedAtMs: at,
|
|
1580
|
+
lifecycle: tool.lifecycle._tag === "Created" ? { _tag: "Running" } : tool.lifecycle
|
|
1581
|
+
});
|
|
1582
|
+
return;
|
|
1583
|
+
}
|
|
1584
|
+
case toolCallCompletedEventType: {
|
|
1585
|
+
const tool = batch.tool(transcriptRecordId.tool(event.payload.toolCallId));
|
|
1586
|
+
if (tool === void 0) return;
|
|
1587
|
+
batch.put({
|
|
1588
|
+
...tool,
|
|
1589
|
+
updatedSeq: seq,
|
|
1590
|
+
...terminalTiming(tool.startedAtMs, at),
|
|
1591
|
+
lifecycle: {
|
|
1592
|
+
_tag: "Completed",
|
|
1593
|
+
result: inlineBody(event.payload.promptPart.result, seq, ["promptPart", "result"])
|
|
1594
|
+
}
|
|
1595
|
+
});
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1598
|
+
case toolCallFailedEventType: {
|
|
1599
|
+
const tool = batch.tool(transcriptRecordId.tool(event.payload.toolCallId));
|
|
1600
|
+
if (tool === void 0) return;
|
|
1601
|
+
batch.put({
|
|
1602
|
+
...tool,
|
|
1603
|
+
updatedSeq: seq,
|
|
1604
|
+
...terminalTiming(tool.startedAtMs, at),
|
|
1605
|
+
lifecycle: {
|
|
1606
|
+
_tag: "Failed",
|
|
1607
|
+
error: jsonFailure(event.payload.error ?? event.payload.promptPart.result)
|
|
1608
|
+
}
|
|
1609
|
+
});
|
|
1610
|
+
return;
|
|
1611
|
+
}
|
|
1612
|
+
case contextRebasedEventType: {
|
|
1613
|
+
const { compactionId, summaryId, contextVersion, retainedFromContextSeq } = event.payload;
|
|
1614
|
+
const id = transcriptRecordId.compaction(compactionId);
|
|
1615
|
+
const existing = batch.get(id);
|
|
1616
|
+
if (existing !== void 0 && existing.kind !== "compaction") throw kindMismatch(id, "compaction", existing.kind);
|
|
1617
|
+
const record = {
|
|
1618
|
+
kind: "compaction",
|
|
1619
|
+
id,
|
|
1620
|
+
updatedSeq: seq,
|
|
1621
|
+
position: existing?.position ?? batch.position(seq),
|
|
1622
|
+
compactionId,
|
|
1623
|
+
summaryId,
|
|
1624
|
+
contextVersion,
|
|
1625
|
+
retainedFromContextSeq,
|
|
1626
|
+
createdAtMs: existing?.createdAtMs ?? at
|
|
1627
|
+
};
|
|
1628
|
+
batch.put(record);
|
|
1629
|
+
return;
|
|
1630
|
+
}
|
|
1631
|
+
case compactionStartedEventType: {
|
|
1632
|
+
const session = batch.session(seq);
|
|
1633
|
+
batch.put({
|
|
1634
|
+
...session,
|
|
1635
|
+
updatedSeq: seq,
|
|
1636
|
+
activeCompactionId: event.payload.compactionId
|
|
1637
|
+
});
|
|
1638
|
+
return;
|
|
1639
|
+
}
|
|
1640
|
+
case compactionCompletedEventType:
|
|
1641
|
+
case compactionFailedEventType: {
|
|
1642
|
+
const { compactionId, modelSelection, usage } = event.payload;
|
|
1643
|
+
const compactionRecordId = transcriptRecordId.compaction(compactionId);
|
|
1644
|
+
const compaction = batch.get(compactionRecordId);
|
|
1645
|
+
const repeated = event.type === compactionCompletedEventType && compaction?.kind === "compaction" && compaction.completedAtMs !== void 0;
|
|
1646
|
+
if (event.type === compactionCompletedEventType && compaction?.kind === "compaction" && compaction.completedAtMs === void 0) batch.put({
|
|
1647
|
+
...compaction,
|
|
1648
|
+
updatedSeq: seq,
|
|
1649
|
+
completedAtMs: at
|
|
1650
|
+
});
|
|
1651
|
+
const session = batch.session(seq);
|
|
1652
|
+
const { activeCompactionId, ...rest } = session;
|
|
1653
|
+
batch.put({
|
|
1654
|
+
...rest,
|
|
1655
|
+
updatedSeq: seq,
|
|
1656
|
+
...activeCompactionId === void 0 || activeCompactionId === compactionId ? {} : { activeCompactionId },
|
|
1657
|
+
tokenUsage: modelSelection === void 0 || repeated ? session.tokenUsage : addModelUsage(session.tokenUsage, modelSelection, usage)
|
|
1658
|
+
});
|
|
1659
|
+
return;
|
|
1660
|
+
}
|
|
1661
|
+
case runStartedEventType:
|
|
1662
|
+
startRun(batch, seq, at, event.payload.runId, event.payload.commandIds, jsonModelSelection(event.payload.modelSelection));
|
|
1663
|
+
return;
|
|
1664
|
+
case runCompletedEventType:
|
|
1665
|
+
finishRun(batch, seq, at, event.payload.runId, { _tag: "Completed" });
|
|
1666
|
+
return;
|
|
1667
|
+
case runFailedEventType:
|
|
1668
|
+
finishRun(batch, seq, at, event.payload.runId, runFailureOutcome(event.payload.error));
|
|
1669
|
+
return;
|
|
1670
|
+
case runInterruptedEventType:
|
|
1671
|
+
finishRun(batch, seq, at, event.payload.runId, {
|
|
1672
|
+
_tag: "Interrupted",
|
|
1673
|
+
reason: event.payload.reason
|
|
1674
|
+
});
|
|
1675
|
+
return;
|
|
1676
|
+
case recoveryCompletedEventType: {
|
|
1677
|
+
const continuation = event.payload.continuation;
|
|
1678
|
+
if (continuation === void 0) return;
|
|
1679
|
+
const groupId = batch.alias("runId", continuation.replacementRunId);
|
|
1680
|
+
const group = groupId === void 0 ? void 0 : batch.runGroup(groupId);
|
|
1681
|
+
if (group === void 0) return;
|
|
1682
|
+
batch.put({
|
|
1683
|
+
...group,
|
|
1684
|
+
updatedSeq: seq,
|
|
1685
|
+
runs: mapNonEmpty(group.runs, (member) => member.runId === continuation.replacementRunId ? {
|
|
1686
|
+
...member,
|
|
1687
|
+
continuationOf: continuation.interruptedRunId
|
|
1688
|
+
} : member)
|
|
1689
|
+
});
|
|
1690
|
+
return;
|
|
1691
|
+
}
|
|
1692
|
+
case systemMessageCommittedEventType:
|
|
1693
|
+
case runSchedulingRequestedEventType:
|
|
1694
|
+
case runSchedulingDeliveredEventType:
|
|
1695
|
+
case runSchedulingInvalidatedEventType:
|
|
1696
|
+
case runSchedulingGrantedEventType:
|
|
1697
|
+
case commandStartedEventType:
|
|
1698
|
+
case commandCompletedEventType:
|
|
1699
|
+
case turnCompletedEventType:
|
|
1700
|
+
case turnFailedEventType:
|
|
1701
|
+
case turnStoppedEventType:
|
|
1702
|
+
case stopTurnRequestedEventType:
|
|
1703
|
+
case stopTurnAppliedEventType:
|
|
1704
|
+
case contextProjectedEventType:
|
|
1705
|
+
case compactionRequestedEventType:
|
|
1706
|
+
case summaryCreatedEventType:
|
|
1707
|
+
case baseStateRequestedEventType:
|
|
1708
|
+
case baseStateCreatedEventType:
|
|
1709
|
+
case baseStateFailedEventType: return;
|
|
1710
|
+
default: return assertNever(event, "transcript durable event");
|
|
1711
|
+
}
|
|
1712
|
+
};
|
|
1713
|
+
/** Waiting for the agent: not yet consumed and not withdrawn. */
|
|
1714
|
+
const isWaiting = (state) => state._tag === "Pending" || state._tag === "Paused" || state._tag === "Promoted" || state._tag === "Steering";
|
|
1715
|
+
const createUser = (batch, seq, at, fields) => {
|
|
1716
|
+
const id = transcriptRecordId.user(fields.commandId);
|
|
1717
|
+
if (fields.idempotencyKey !== void 0) batch.insertAlias("idempotencyKey", fields.idempotencyKey, id);
|
|
1718
|
+
const user = replayBufferedDecorations(batch, seq, {
|
|
1719
|
+
kind: "user",
|
|
1720
|
+
id,
|
|
1721
|
+
updatedSeq: seq,
|
|
1722
|
+
messageIds: [],
|
|
1723
|
+
decorations: {},
|
|
1724
|
+
submittedSeq: seq,
|
|
1725
|
+
submittedAtMs: at,
|
|
1726
|
+
...fields
|
|
1727
|
+
});
|
|
1728
|
+
batch.put(user);
|
|
1729
|
+
return user;
|
|
1730
|
+
};
|
|
1731
|
+
/** The user record a message belongs to, created if the log never admitted its command. */
|
|
1732
|
+
const userForMessage = (batch, seq, at, commandId, messageId, content) => {
|
|
1733
|
+
const id = transcriptRecordId.user(commandId);
|
|
1734
|
+
const user = batch.user(id) ?? createUser(batch, seq, at, {
|
|
1735
|
+
commandId,
|
|
1736
|
+
content,
|
|
1737
|
+
state: { _tag: "Pending" }
|
|
1738
|
+
});
|
|
1739
|
+
batch.insertAlias("messageId", messageId, id);
|
|
1740
|
+
return user.messageIds.includes(messageId) ? user : {
|
|
1741
|
+
...user,
|
|
1742
|
+
messageIds: [...user.messageIds, messageId]
|
|
1743
|
+
};
|
|
1744
|
+
};
|
|
1745
|
+
const userByMessage = (batch, messageId) => {
|
|
1746
|
+
const id = batch.alias("messageId", messageId);
|
|
1747
|
+
return id === void 0 ? void 0 : batch.user(id);
|
|
1748
|
+
};
|
|
1749
|
+
const consume = (batch, user, seq, at, by) => ({
|
|
1750
|
+
...user,
|
|
1751
|
+
updatedSeq: seq,
|
|
1752
|
+
position: user.position ?? batch.position(seq),
|
|
1753
|
+
consumedAtMs: user.consumedAtMs ?? at,
|
|
1754
|
+
state: {
|
|
1755
|
+
_tag: "Consumed",
|
|
1756
|
+
...by
|
|
1757
|
+
}
|
|
1758
|
+
});
|
|
1759
|
+
const newAssistant = (batch, id, seq, source, inferenceId, runId, turnId) => {
|
|
1760
|
+
const groupId = batch.alias("runId", runId);
|
|
1761
|
+
const runGroupId = groupId === void 0 ? void 0 : batch.runGroup(groupId)?.id;
|
|
1762
|
+
return {
|
|
1763
|
+
kind: "assistant",
|
|
1764
|
+
id,
|
|
1765
|
+
updatedSeq: seq,
|
|
1766
|
+
position: batch.position(seq),
|
|
1767
|
+
source,
|
|
1768
|
+
inferenceId,
|
|
1769
|
+
runId,
|
|
1770
|
+
turnId,
|
|
1771
|
+
...runGroupId === void 0 ? {} : { runGroupId },
|
|
1772
|
+
lifecycle: { _tag: "Streaming" },
|
|
1773
|
+
parts: []
|
|
1774
|
+
};
|
|
1775
|
+
};
|
|
1776
|
+
const assistantParts = (batch, inferenceId, promptParts, seq) => promptParts.map((part, index) => {
|
|
1777
|
+
switch (part.type) {
|
|
1778
|
+
case "text": return {
|
|
1779
|
+
_tag: "Text",
|
|
1780
|
+
text: part.text
|
|
1781
|
+
};
|
|
1782
|
+
case "reasoning": return {
|
|
1783
|
+
_tag: "Reasoning",
|
|
1784
|
+
text: part.text
|
|
1785
|
+
};
|
|
1786
|
+
case "tool-call": {
|
|
1787
|
+
if (!Schema.is(ProviderPartId)(part.id) || !Schema.is(ToolName)(part.name)) return {
|
|
1788
|
+
_tag: "Unknown",
|
|
1789
|
+
partType: part.type
|
|
1790
|
+
};
|
|
1791
|
+
const toolAlias = batch.alias("toolPart", toolPartKey(inferenceId, part.id));
|
|
1792
|
+
const toolId = toolAlias === void 0 ? void 0 : batch.tool(toolAlias)?.id;
|
|
1793
|
+
return {
|
|
1794
|
+
_tag: "ToolCall",
|
|
1795
|
+
providerPartId: part.id,
|
|
1796
|
+
toolName: part.name,
|
|
1797
|
+
providerExecuted: part.providerExecuted,
|
|
1798
|
+
...toolId === void 0 ? {} : { toolId }
|
|
1799
|
+
};
|
|
1800
|
+
}
|
|
1801
|
+
case "tool-result":
|
|
1802
|
+
if (!Schema.is(ProviderPartId)(part.id) || !Schema.is(ToolName)(part.name)) return {
|
|
1803
|
+
_tag: "Unknown",
|
|
1804
|
+
partType: part.type
|
|
1805
|
+
};
|
|
1806
|
+
return {
|
|
1807
|
+
_tag: "ToolResult",
|
|
1808
|
+
providerPartId: part.id,
|
|
1809
|
+
toolName: part.name,
|
|
1810
|
+
isFailure: part.isFailure,
|
|
1811
|
+
result: inlineBody(part.result, seq, [
|
|
1812
|
+
"promptParts",
|
|
1813
|
+
index,
|
|
1814
|
+
"result"
|
|
1815
|
+
])
|
|
1816
|
+
};
|
|
1817
|
+
default: return {
|
|
1818
|
+
_tag: "Unknown",
|
|
1819
|
+
partType: part.type
|
|
1820
|
+
};
|
|
1821
|
+
}
|
|
1822
|
+
});
|
|
1823
|
+
const toolPartKey = (inferenceId, providerPartId) => `${inferenceId}/${providerPartId}`;
|
|
1824
|
+
/** Record the tool for its assistant part, whichever of the two the log wrote first. */
|
|
1825
|
+
const linkToolPart = (batch, inferenceId, providerPartId, toolId, seq) => {
|
|
1826
|
+
batch.insertAlias("toolPart", toolPartKey(inferenceId, providerPartId), toolId);
|
|
1827
|
+
const assistant = batch.assistant(transcriptRecordId.assistant(inferenceId));
|
|
1828
|
+
if (assistant === void 0) return;
|
|
1829
|
+
let changed = false;
|
|
1830
|
+
const parts = assistant.parts.map((part) => {
|
|
1831
|
+
if (part._tag !== "ToolCall" || part.providerPartId !== providerPartId || part.toolId !== void 0) return part;
|
|
1832
|
+
changed = true;
|
|
1833
|
+
return {
|
|
1834
|
+
...part,
|
|
1835
|
+
toolId
|
|
1836
|
+
};
|
|
1837
|
+
});
|
|
1838
|
+
if (changed) batch.put({
|
|
1839
|
+
...assistant,
|
|
1840
|
+
updatedSeq: seq,
|
|
1841
|
+
parts
|
|
1842
|
+
});
|
|
1843
|
+
};
|
|
1844
|
+
const startRun = (batch, seq, at, runId, commandIds, modelSelection) => {
|
|
1845
|
+
const group = runGroupForStart(batch, seq, runId, commandIds, {
|
|
1846
|
+
runId,
|
|
1847
|
+
commandIds,
|
|
1848
|
+
modelSelection,
|
|
1849
|
+
outcome: { _tag: "Running" },
|
|
1850
|
+
startedAtMs: at
|
|
1851
|
+
});
|
|
1852
|
+
batch.put(group);
|
|
1853
|
+
batch.insertAlias("runId", runId, group.id);
|
|
1854
|
+
for (const commandId of commandIds) batch.insertAlias("runCommand", commandId, group.id);
|
|
1855
|
+
const session = batch.session(seq);
|
|
1856
|
+
batch.put({
|
|
1857
|
+
...session,
|
|
1858
|
+
updatedSeq: seq,
|
|
1859
|
+
activeRunId: runId,
|
|
1860
|
+
lastRunModelSelection: modelSelection,
|
|
1861
|
+
modelSelection: session.modelSelection ?? modelSelection
|
|
1862
|
+
});
|
|
1863
|
+
};
|
|
1864
|
+
/**
|
|
1865
|
+
* The group a started run belongs to. A repeated start of a known run replaces its member and
|
|
1866
|
+
* keeps its outcome, as the reduced state keeps its terminal. A startup-recovery continuation
|
|
1867
|
+
* reuses its interrupted predecessor's command ids, so it joins that finished group; any other
|
|
1868
|
+
* run roots a new group.
|
|
1869
|
+
*/
|
|
1870
|
+
const runGroupForStart = (batch, seq, runId, commandIds, member) => {
|
|
1871
|
+
const knownId = batch.alias("runId", runId);
|
|
1872
|
+
const known = knownId === void 0 ? void 0 : batch.runGroup(knownId);
|
|
1873
|
+
if (known !== void 0) return {
|
|
1874
|
+
...known,
|
|
1875
|
+
updatedSeq: seq,
|
|
1876
|
+
runs: mapNonEmpty(known.runs, (candidate) => candidate.runId === runId ? {
|
|
1877
|
+
...member,
|
|
1878
|
+
outcome: candidate.outcome
|
|
1879
|
+
} : candidate)
|
|
1880
|
+
};
|
|
1881
|
+
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");
|
|
1882
|
+
if (predecessor !== void 0) return {
|
|
1883
|
+
...predecessor,
|
|
1884
|
+
updatedSeq: seq,
|
|
1885
|
+
runs: [...predecessor.runs, member]
|
|
1886
|
+
};
|
|
1887
|
+
return {
|
|
1888
|
+
kind: "runGroup",
|
|
1889
|
+
id: transcriptRecordId.runGroup(runId),
|
|
1890
|
+
updatedSeq: seq,
|
|
1891
|
+
rootRunId: runId,
|
|
1892
|
+
runs: [member]
|
|
1893
|
+
};
|
|
1894
|
+
};
|
|
1895
|
+
const finishRun = (batch, seq, at, runId, outcome) => {
|
|
1896
|
+
const groupId = batch.alias("runId", runId);
|
|
1897
|
+
const group = groupId === void 0 ? void 0 : batch.runGroup(groupId);
|
|
1898
|
+
if (group === void 0) return;
|
|
1899
|
+
batch.put({
|
|
1900
|
+
...group,
|
|
1901
|
+
updatedSeq: seq,
|
|
1902
|
+
runs: mapNonEmpty(group.runs, (member) => member.runId === runId ? {
|
|
1903
|
+
...member,
|
|
1904
|
+
...terminalTiming(member.startedAtMs, at),
|
|
1905
|
+
outcome
|
|
1906
|
+
} : member)
|
|
1907
|
+
});
|
|
1908
|
+
const session = batch.session(seq);
|
|
1909
|
+
if (session.activeRunId === runId) {
|
|
1910
|
+
const { activeRunId: _activeRunId, ...idle } = session;
|
|
1911
|
+
batch.put({
|
|
1912
|
+
...idle,
|
|
1913
|
+
updatedSeq: seq
|
|
1914
|
+
});
|
|
1915
|
+
}
|
|
1916
|
+
};
|
|
1917
|
+
const runMember = (batch, runId) => {
|
|
1918
|
+
const groupId = batch.alias("runId", runId);
|
|
1919
|
+
return (groupId === void 0 ? void 0 : batch.runGroup(groupId))?.runs.find((member) => member.runId === runId);
|
|
1920
|
+
};
|
|
1921
|
+
const runFailureOutcome = (error) => error.code === "run.interrupted" ? {
|
|
1922
|
+
_tag: "Interrupted",
|
|
1923
|
+
reason: error.message
|
|
1924
|
+
} : {
|
|
1925
|
+
_tag: "Failed",
|
|
1926
|
+
error: jsonFailure(error)
|
|
1927
|
+
};
|
|
1928
|
+
const terminalTiming = (startedAtMs, terminalAtMs) => ({
|
|
1929
|
+
terminalAtMs,
|
|
1930
|
+
...startedAtMs === void 0 ? {} : { durationMs: Math.max(0, terminalAtMs - startedAtMs) }
|
|
1931
|
+
});
|
|
1932
|
+
const timingOf = (record) => ({
|
|
1933
|
+
...record?.startedAtMs === void 0 ? {} : { startedAtMs: record.startedAtMs },
|
|
1934
|
+
...record?.terminalAtMs === void 0 ? {} : { terminalAtMs: record.terminalAtMs },
|
|
1935
|
+
...record?.durationMs === void 0 ? {} : { durationMs: record.durationMs }
|
|
1936
|
+
});
|
|
1937
|
+
const bodyEncoder = new TextEncoder();
|
|
1938
|
+
/**
|
|
1939
|
+
* A body read from a committed event, normalized to the JSON a persisted log holds, so a live
|
|
1940
|
+
* projection and a rebuild from storage agree. A value with no JSON form (a bigint or a cycle) is
|
|
1941
|
+
* a projection failure.
|
|
1942
|
+
*/
|
|
1943
|
+
const inlineBody = (value, seq, path) => {
|
|
1944
|
+
const notJson = () => new TranscriptProjectionError({ message: `body at seq ${seq} ${JSON.stringify(path)} is not JSON` });
|
|
1945
|
+
let json;
|
|
1946
|
+
try {
|
|
1947
|
+
json = JSON.stringify(value);
|
|
1948
|
+
} catch {
|
|
1949
|
+
throw notJson();
|
|
1950
|
+
}
|
|
1951
|
+
const normalized = json === void 0 ? null : JSON.parse(json);
|
|
1952
|
+
if (!Schema.is(Schema.Json)(normalized)) throw notJson();
|
|
1953
|
+
const byteLength = json === void 0 ? 4 : bodyEncoder.encode(json).length;
|
|
1954
|
+
return byteLength <= 65536 ? {
|
|
1955
|
+
_tag: "Inline",
|
|
1956
|
+
value: normalized,
|
|
1957
|
+
source: {
|
|
1958
|
+
seq,
|
|
1959
|
+
path
|
|
1960
|
+
}
|
|
1961
|
+
} : {
|
|
1962
|
+
_tag: "Ref",
|
|
1963
|
+
source: {
|
|
1964
|
+
seq,
|
|
1965
|
+
path
|
|
1966
|
+
},
|
|
1967
|
+
byteLength
|
|
1968
|
+
};
|
|
1969
|
+
};
|
|
1970
|
+
/** A model selection as the JSON a persisted log holds; settings with no JSON form are dropped. */
|
|
1971
|
+
const jsonModelSelection = (selection) => {
|
|
1972
|
+
try {
|
|
1973
|
+
const json = JSON.stringify(selection);
|
|
1974
|
+
const normalized = json === void 0 ? void 0 : JSON.parse(json);
|
|
1975
|
+
if (Schema.is(ModelSelectionPayload)(normalized)) return normalized;
|
|
1976
|
+
} catch {}
|
|
1977
|
+
return {
|
|
1978
|
+
provider: selection.provider,
|
|
1979
|
+
modelId: selection.modelId
|
|
1980
|
+
};
|
|
1981
|
+
};
|
|
1982
|
+
/** A failure as the JSON a persisted log holds; details with no JSON form are dropped. */
|
|
1983
|
+
const jsonFailure = (error) => {
|
|
1984
|
+
try {
|
|
1985
|
+
const json = JSON.stringify(error);
|
|
1986
|
+
const normalized = json === void 0 ? void 0 : JSON.parse(json);
|
|
1987
|
+
if (Schema.is(FailurePayload)(normalized)) return normalized;
|
|
1988
|
+
} catch {}
|
|
1989
|
+
return {
|
|
1990
|
+
message: error.message,
|
|
1991
|
+
...error.code === void 0 ? {} : { code: error.code }
|
|
1992
|
+
};
|
|
1993
|
+
};
|
|
1994
|
+
const mapNonEmpty = (items, f) => [f(items[0]), ...items.slice(1).map(f)];
|
|
1995
|
+
//#endregion
|
|
1996
|
+
//#region src/transcript/store.ts
|
|
1997
|
+
/** A cursor minted for another log incarnation or transcript version. The client takes `Latest`. */
|
|
1998
|
+
var TranscriptCursorMismatch = class extends Schema.TaggedError()("TranscriptCursorMismatch", { message: Schema.String }) {};
|
|
1999
|
+
/** Transcript read port, provided alongside `EDASessionStore` by stores that maintain transcripts. */
|
|
2000
|
+
var EDATranscriptStore = class extends Context.Service()("@effect-durable-agent/EDATranscriptStore") {};
|
|
2001
|
+
//#endregion
|
|
2002
|
+
//#region src/transcript/window-read.ts
|
|
2003
|
+
/** Readiness of a served version: why its cut may be behind the log. */
|
|
2004
|
+
const transcriptReadiness = (meta, carried) => {
|
|
2005
|
+
if (!carried) return { _tag: "UpdatingHistory" };
|
|
2006
|
+
switch (meta.status._tag) {
|
|
2007
|
+
case "Ok": return { _tag: "Ready" };
|
|
2008
|
+
case "Failed": return {
|
|
2009
|
+
_tag: "Degraded",
|
|
2010
|
+
failedAtSeq: meta.status.failedAtSeq,
|
|
2011
|
+
error: meta.status.error
|
|
2012
|
+
};
|
|
2013
|
+
}
|
|
2014
|
+
};
|
|
2015
|
+
/** The empty window served while no version is servable yet. */
|
|
2016
|
+
const buildingTranscriptWindow = (incarnation, version) => ({
|
|
2017
|
+
incarnation,
|
|
2018
|
+
version,
|
|
2019
|
+
throughSeq: SequenceNumber.make(0),
|
|
2020
|
+
records: [],
|
|
2021
|
+
dependencies: [],
|
|
2022
|
+
hasOlder: false,
|
|
2023
|
+
hasNewer: false,
|
|
2024
|
+
readiness: { _tag: "Building" }
|
|
2025
|
+
});
|
|
2026
|
+
const orderKey = (record) => ({
|
|
2027
|
+
anchorSeq: record.position?.anchorSeq ?? 0,
|
|
2028
|
+
ordinal: record.position?.ordinal ?? 0,
|
|
2029
|
+
recordId: record.id
|
|
2030
|
+
});
|
|
2031
|
+
const cursorKey = (cursor) => ({
|
|
2032
|
+
anchorSeq: cursor.anchorSeq,
|
|
2033
|
+
ordinal: cursor.ordinal,
|
|
2034
|
+
recordId: cursor.recordId
|
|
2035
|
+
});
|
|
2036
|
+
/**
|
|
2037
|
+
* Assemble one window from a source at a single cut.
|
|
2038
|
+
*
|
|
2039
|
+
* The response never contains anything newer than the served version's cursor: a frozen (failed
|
|
2040
|
+
* or no longer carried) version's rows, pending users and session context all stop at its last
|
|
2041
|
+
* good cut, which is the degraded-read rule. Bodies above the inline limit become references;
|
|
2042
|
+
* if the response still exceeds the byte budget, records are dropped from the far end of the
|
|
2043
|
+
* selection, keeping at least one so paging always progresses.
|
|
2044
|
+
*/
|
|
2045
|
+
const readTranscriptWindowFrom = (source, selector, limits) => {
|
|
2046
|
+
const version = source.meta.version;
|
|
2047
|
+
for (const cursor of selectorCursors(selector)) if (cursor.incarnation !== source.incarnation || cursor.version !== version) return Result.fail(new TranscriptCursorMismatch({ message: `cursor for ${cursor.incarnation}/${cursor.version} read against ${source.incarnation}/${version}` }));
|
|
2048
|
+
const selected = selectTopLevel(source, selector, limits.maxRecords);
|
|
2049
|
+
const keepNewest = selector._tag === "Latest" || selector._tag === "Page" && selector.direction === "before";
|
|
2050
|
+
let top = selected.map((record) => withBodyRefs(record, limits.maxInlineBodyBytes));
|
|
2051
|
+
let dependencies = collectDependencies(source, top, limits.maxInlineBodyBytes);
|
|
2052
|
+
while (top.length > 1 && windowBytes(top, dependencies) > limits.maxBytes) {
|
|
2053
|
+
top = keepNewest ? top.slice(1) : top.slice(0, -1);
|
|
2054
|
+
dependencies = collectDependencies(source, top, limits.maxInlineBodyBytes);
|
|
2055
|
+
}
|
|
2056
|
+
const first = top[0];
|
|
2057
|
+
const last = top[top.length - 1];
|
|
2058
|
+
const [hasOlder, hasNewer] = first === void 0 || last === void 0 ? emptySelectionNeighbours(source, selector) : [source.topLevelBefore(orderKey(first), 1, false).length > 0, source.topLevelAfter(orderKey(last), 1, false).length > 0];
|
|
2059
|
+
return Result.succeed({
|
|
2060
|
+
incarnation: source.incarnation,
|
|
2061
|
+
version,
|
|
2062
|
+
throughSeq: source.meta.cursor,
|
|
2063
|
+
records: top,
|
|
2064
|
+
dependencies,
|
|
2065
|
+
hasOlder,
|
|
2066
|
+
hasNewer,
|
|
2067
|
+
readiness: transcriptReadiness(source.meta, source.carried)
|
|
2068
|
+
});
|
|
2069
|
+
};
|
|
2070
|
+
const selectorCursors = (selector) => {
|
|
2071
|
+
switch (selector._tag) {
|
|
2072
|
+
case "Latest": return [];
|
|
2073
|
+
case "Page": return [selector.cursor];
|
|
2074
|
+
case "Range": return [selector.from, selector.to];
|
|
2075
|
+
}
|
|
2076
|
+
};
|
|
2077
|
+
const selectTopLevel = (source, selector, maxRecords) => {
|
|
2078
|
+
switch (selector._tag) {
|
|
2079
|
+
case "Latest": return [...source.topLevelBefore(void 0, Math.min(selector.count, maxRecords), false)].reverse();
|
|
2080
|
+
case "Page": {
|
|
2081
|
+
const count = Math.min(selector.count, maxRecords);
|
|
2082
|
+
return selector.direction === "before" ? [...source.topLevelBefore(cursorKey(selector.cursor), count, false)].reverse() : source.topLevelAfter(cursorKey(selector.cursor), count, false);
|
|
2083
|
+
}
|
|
2084
|
+
case "Range": {
|
|
2085
|
+
const to = cursorKey(selector.to);
|
|
2086
|
+
return source.topLevelAfter(cursorKey(selector.from), maxRecords, true).filter((record) => TranscriptOrder(orderKey(record), to) <= 0);
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
};
|
|
2090
|
+
const emptySelectionNeighbours = (source, selector) => {
|
|
2091
|
+
switch (selector._tag) {
|
|
2092
|
+
case "Latest": return [false, false];
|
|
2093
|
+
case "Page": {
|
|
2094
|
+
const key = cursorKey(selector.cursor);
|
|
2095
|
+
return selector.direction === "before" ? [false, source.topLevelAfter(key, 1, true).length > 0] : [source.topLevelBefore(key, 1, true).length > 0, false];
|
|
2096
|
+
}
|
|
2097
|
+
case "Range": return [source.topLevelBefore(cursorKey(selector.from), 1, false).length > 0, source.topLevelAfter(cursorKey(selector.to), 1, false).length > 0];
|
|
2098
|
+
}
|
|
2099
|
+
};
|
|
2100
|
+
/** Session context, then each record's run group and tools in part order, then pending users. */
|
|
2101
|
+
const collectDependencies = (source, top, maxInlineBodyBytes) => {
|
|
2102
|
+
const dependencies = /* @__PURE__ */ new Map();
|
|
2103
|
+
const add = (record) => {
|
|
2104
|
+
if (record !== void 0 && !dependencies.has(record.id)) dependencies.set(record.id, withBodyRefs(record, maxInlineBodyBytes));
|
|
2105
|
+
};
|
|
2106
|
+
add(source.record(transcriptRecordId.session));
|
|
2107
|
+
for (const record of top) switch (record.kind) {
|
|
2108
|
+
case "assistant": {
|
|
2109
|
+
if (record.runGroupId !== void 0) add(source.record(record.runGroupId));
|
|
2110
|
+
const partOrder = new Map(record.parts.flatMap((part, index) => part._tag === "ToolCall" && part.toolId !== void 0 ? [[part.toolId, index]] : []));
|
|
2111
|
+
[...source.toolsOf(record.id)].sort((left, right) => (partOrder.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (partOrder.get(right.id) ?? Number.MAX_SAFE_INTEGER) || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).forEach(add);
|
|
2112
|
+
break;
|
|
2113
|
+
}
|
|
2114
|
+
case "user": {
|
|
2115
|
+
const runId = record.state._tag === "Consumed" ? record.state.runId : void 0;
|
|
2116
|
+
const groupId = (runId === void 0 ? void 0 : source.alias("runId", runId)) ?? source.alias("runCommand", record.commandId);
|
|
2117
|
+
if (groupId !== void 0) add(source.record(groupId));
|
|
2118
|
+
break;
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
[...source.pendingUsers()].filter(isPendingTranscriptUserRecord).sort((left, right) => left.submittedSeq - right.submittedSeq || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).forEach(add);
|
|
2122
|
+
return Array.from(dependencies.values());
|
|
2123
|
+
};
|
|
2124
|
+
const encoder = new TextEncoder();
|
|
2125
|
+
const encodeRecord = Schema.encodeSync(TranscriptRecordFromEnvelope);
|
|
2126
|
+
const jsonBytes = (value) => {
|
|
2127
|
+
const json = JSON.stringify(value);
|
|
2128
|
+
return json === void 0 ? 0 : encoder.encode(json).length;
|
|
2129
|
+
};
|
|
2130
|
+
const windowBytes = (top, dependencies) => [...top, ...dependencies].reduce((total, record) => total + jsonBytes(encodeRecord(record)), 0);
|
|
2131
|
+
const bodyRef = (body, maxInlineBodyBytes) => {
|
|
2132
|
+
if (body._tag === "Ref") return body;
|
|
2133
|
+
const byteLength = jsonBytes(body.value);
|
|
2134
|
+
return byteLength <= maxInlineBodyBytes ? body : {
|
|
2135
|
+
_tag: "Ref",
|
|
2136
|
+
source: body.source,
|
|
2137
|
+
byteLength: NonNegativeInt.make(byteLength)
|
|
2138
|
+
};
|
|
2139
|
+
};
|
|
2140
|
+
/** Replace inline bodies above the limit with references to their immutable log source. */
|
|
2141
|
+
const withBodyRefs = (record, maxInlineBodyBytes) => {
|
|
2142
|
+
switch (record.kind) {
|
|
2143
|
+
case "tool": {
|
|
2144
|
+
const tool = {
|
|
2145
|
+
...record,
|
|
2146
|
+
...record.params === void 0 ? {} : { params: bodyRef(record.params, maxInlineBodyBytes) },
|
|
2147
|
+
lifecycle: record.lifecycle._tag === "Completed" ? {
|
|
2148
|
+
_tag: "Completed",
|
|
2149
|
+
result: bodyRef(record.lifecycle.result, maxInlineBodyBytes)
|
|
2150
|
+
} : record.lifecycle
|
|
2151
|
+
};
|
|
2152
|
+
return {
|
|
2153
|
+
...record,
|
|
2154
|
+
...tool
|
|
2155
|
+
};
|
|
2156
|
+
}
|
|
2157
|
+
case "assistant": {
|
|
2158
|
+
const parts = record.parts.map((part) => part._tag === "ToolResult" ? {
|
|
2159
|
+
...part,
|
|
2160
|
+
result: bodyRef(part.result, maxInlineBodyBytes)
|
|
2161
|
+
} : part);
|
|
2162
|
+
return {
|
|
2163
|
+
...record,
|
|
2164
|
+
parts
|
|
2165
|
+
};
|
|
2166
|
+
}
|
|
2167
|
+
default: return record;
|
|
2168
|
+
}
|
|
2169
|
+
};
|
|
2170
|
+
//#endregion
|
|
2171
|
+
export { TranscriptRecordId as $, SessionContextRecordId as A, TranscriptCursor as B, transcriptSemanticRevision as C, ImportAssistantRecordId as D, DecorationBufferRecordId as E, TranscriptBody as F, TranscriptDecorations as G, TranscriptDecorationBufferRecord as H, TranscriptBodySource as I, TranscriptOrder as J, TranscriptFieldPath as K, TranscriptBufferedDecoration as L, TranscriptAssistantLifecycle as M, TranscriptAssistantPart as N, InferenceAssistantRecordId as O, TranscriptAssistantRecord as P, TranscriptRecordFromEnvelope as Q, TranscriptClassification as R, computeTranscriptVersion as S, CompactionRecordId as T, TranscriptDecorationEntryKey as U, TranscriptDecoration as V, TranscriptDecorationKey as W, TranscriptRecord as X, TranscriptPosition as Y, TranscriptRecordEnvelope as Z, TranscriptUserFallback as _, transcriptRecordId as _t, TranscriptCursorMismatch as a, TranscriptToolLifecycle as at, transcriptMappingBounds as b, TranscriptProjectionError as c, TranscriptUserRecord as ct, TranscriptListEntryKey as d, UserRecordId as dt, TranscriptRecordViewFromEnvelope as et, TranscriptMappedEvent as f, isPendingTranscriptUserRecord as ft, TranscriptMappings as g, transcriptRecordEnvelopeFormat as gt, TranscriptMappingTarget as h, transcriptDecorationBufferLimit as ht, EDATranscriptStore as i, TranscriptSessionContextRecord as it, ToolRecordId as j, RunGroupRecordId as k, TranscriptDefinition as l, TranscriptUserState as lt, TranscriptMappingOperation as m, runGroupStatus as mt, readTranscriptWindowFrom as n, TranscriptRunMember as nt, planTranscriptBatch as o, TranscriptToolRecord as ot, TranscriptMapping as p, isTopLevelTranscriptRecord as pt, TranscriptLogIncarnation as q, transcriptReadiness as r, TranscriptRunOutcome as rt, TranscriptAliasNamespace as s, TranscriptUnknownRecord as st, buildingTranscriptWindow as t, TranscriptRunGroupRecord as tt, TranscriptDefinitionError as u, TranscriptVersion as ut, emptyTranscriptMappings as v, transcriptStoredInlineBodyLimit as vt, AssistantRecordId as w, canonicalJson as x, makeTranscriptDefinition as y, TranscriptCompactionRecord as z };
|
|
2172
|
+
|
|
2173
|
+
//# sourceMappingURL=window-read-B8aF_hDq.js.map
|