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