effect-durable-agent 0.1.0-alpha.22 → 0.1.0-alpha.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/domain/command-queues.d.ts +1 -1
  2. package/dist/domain/message-transcript.d.ts +1 -1
  3. package/dist/domain/reduced-state.d.ts +1 -1
  4. package/dist/domain/run-scheduling.d.ts +1 -1
  5. package/dist/in-memory-D8qQXNc5.js +150 -0
  6. package/dist/in-memory-D8qQXNc5.js.map +1 -0
  7. package/dist/index.d.ts +1 -1
  8. package/dist/{window-read-B8aF_hDq.js → interpreter-BYstFpr4.js} +82 -868
  9. package/dist/interpreter-BYstFpr4.js.map +1 -0
  10. package/dist/records-DWKEjuqb.js +675 -0
  11. package/dist/records-DWKEjuqb.js.map +1 -0
  12. package/dist/{reduced-state-PJdig48e.d.ts → reduced-state-B5WxKSM5.d.ts} +4206 -4206
  13. package/dist/{reducer-registry-BAbhZs6d.d.ts → reducer-registry-CPObI3cs.d.ts} +2 -2
  14. package/dist/{run-scheduling-wakeup-QLK87OqG.d.ts → run-scheduling-wakeup-B19JTeyq.d.ts} +2 -2
  15. package/dist/services/compaction.d.ts +1 -1
  16. package/dist/services/model-call.d.ts +1 -1
  17. package/dist/services/prompt-projector.d.ts +1 -1
  18. package/dist/services/reducer-registry.d.ts +1 -1
  19. package/dist/services/reducer-registry.js +1 -1
  20. package/dist/services/run-scheduler.d.ts +1 -1
  21. package/dist/services/run-scheduling-wakeup.d.ts +1 -1
  22. package/dist/services/runtime-layer.d.ts +6 -6
  23. package/dist/services/runtime-layer.js +3 -3
  24. package/dist/services/runtime.d.ts +1 -1
  25. package/dist/services/runtime.js +1 -1
  26. package/dist/services/session-query.d.ts +1 -1
  27. package/dist/services/session-query.js +2 -2
  28. package/dist/services/session-state.d.ts +1 -1
  29. package/dist/services/session-state.js +1 -1
  30. package/dist/services/session-store.d.ts +1 -1
  31. package/dist/services/session-store.js +271 -1
  32. package/dist/services/session-store.js.map +1 -0
  33. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  34. package/dist/services/sink-registry.d.ts +1 -1
  35. package/dist/services/sink-registry.js +1 -1
  36. package/dist/services/tool-registry.d.ts +1 -1
  37. package/dist/{session-state-StlO5B2N.js → session-state-BW0l2aNk.js} +3 -3
  38. package/dist/{session-state-StlO5B2N.js.map → session-state-BW0l2aNk.js.map} +1 -1
  39. package/dist/{session-store-ByDjS03N.d.ts → session-store-CWYZ29CV.d.ts} +163 -45
  40. package/dist/{sink-checkpoint-store-BHb8YRTw.d.ts → sink-checkpoint-store-B8Ky5nfW.d.ts} +2 -2
  41. package/dist/{sink-registry-DEneTH8u.js → sink-registry-D0MetcNq.js} +2 -2
  42. package/dist/{sink-registry-DEneTH8u.js.map → sink-registry-D0MetcNq.js.map} +1 -1
  43. package/dist/subscription-DelB8L87.d.ts +958 -0
  44. package/dist/subscription-g5W0Ggqx.js +498 -0
  45. package/dist/subscription-g5W0Ggqx.js.map +1 -0
  46. package/dist/testkit/layers.d.ts +9 -6
  47. package/dist/testkit/layers.js +4 -4
  48. package/dist/testkit/layers.js.map +1 -1
  49. package/dist/testkit/transcript.d.ts +226 -0
  50. package/dist/testkit/transcript.js +1475 -0
  51. package/dist/testkit/transcript.js.map +1 -0
  52. package/dist/{tool-registry-CxZ0iuYb.d.ts → tool-registry-B_WE2ZwK.d.ts} +2 -2
  53. package/dist/transcript.d.ts +40 -99
  54. package/dist/transcript.js +99 -170
  55. package/dist/transcript.js.map +1 -1
  56. package/dist/websocket.d.ts +2209 -2
  57. package/dist/websocket.js +704 -18
  58. package/dist/websocket.js.map +1 -1
  59. package/dist/window-read-DBf1Iktt.d.ts +104 -0
  60. package/dist/window-read-U55aAeuz.js +184 -0
  61. package/dist/window-read-U55aAeuz.js.map +1 -0
  62. package/package.json +5 -1
  63. package/dist/session-store-DcJjs4Fd.js +0 -413
  64. package/dist/session-store-DcJjs4Fd.js.map +0 -1
  65. package/dist/window-read-B8aF_hDq.js.map +0 -1
@@ -1,178 +1,107 @@
1
1
  import { SequenceNumber } from "./types/core.js";
2
- import { u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
3
- import { $ as TranscriptRecordId, A as SessionContextRecordId, B as TranscriptCursor, C as transcriptSemanticRevision, D as ImportAssistantRecordId, E as DecorationBufferRecordId, F as TranscriptBody, G as TranscriptDecorations, H as TranscriptDecorationBufferRecord, I as TranscriptBodySource, J as TranscriptOrder, K as TranscriptFieldPath, L as TranscriptBufferedDecoration, M as TranscriptAssistantLifecycle, N as TranscriptAssistantPart, O as InferenceAssistantRecordId, P as TranscriptAssistantRecord, Q as TranscriptRecordFromEnvelope, R as TranscriptClassification, S as computeTranscriptVersion, T as CompactionRecordId, U as TranscriptDecorationEntryKey, V as TranscriptDecoration, W as TranscriptDecorationKey, X as TranscriptRecord, Y as TranscriptPosition, Z as TranscriptRecordEnvelope, _ as TranscriptUserFallback, _t as transcriptRecordId, a as TranscriptCursorMismatch, at as TranscriptToolLifecycle, b as transcriptMappingBounds, c as TranscriptProjectionError, ct as TranscriptUserRecord, d as TranscriptListEntryKey, dt as UserRecordId, et as TranscriptRecordViewFromEnvelope, f as TranscriptMappedEvent, ft as isPendingTranscriptUserRecord, g as TranscriptMappings, gt as transcriptRecordEnvelopeFormat, h as TranscriptMappingTarget, ht as transcriptDecorationBufferLimit, i as EDATranscriptStore, it as TranscriptSessionContextRecord, j as ToolRecordId, k as RunGroupRecordId, l as TranscriptDefinition, lt as TranscriptUserState, m as TranscriptMappingOperation, mt as runGroupStatus, n as readTranscriptWindowFrom, nt as TranscriptRunMember, o as planTranscriptBatch, ot as TranscriptToolRecord, p as TranscriptMapping, pt as isTopLevelTranscriptRecord, q as TranscriptLogIncarnation, r as transcriptReadiness, rt as TranscriptRunOutcome, s as TranscriptAliasNamespace, st as TranscriptUnknownRecord, t as buildingTranscriptWindow, tt as TranscriptRunGroupRecord, u as TranscriptDefinitionError, ut as TranscriptVersion, v as emptyTranscriptMappings, vt as transcriptStoredInlineBodyLimit, w as AssistantRecordId, x as canonicalJson, y as makeTranscriptDefinition, z as TranscriptCompactionRecord } from "./window-read-B8aF_hDq.js";
2
+ import { G as InferenceCompletedEvent, J as InferenceFailedEvent, X as InferenceStartedEvent, cn as TurnCompletedEvent, dn as TurnFailedEvent, hn as TurnStoppedEvent } from "./durable-CD__3ztN.js";
3
+ import { ReasoningDeltaEvent, TextDeltaEvent, ToolParamsDeltaEvent, ToolParamsStartEvent } from "./types/events.js";
4
+ import { A as TranscriptRecordFromEnvelope, B as TranscriptUserRecord, C as TranscriptDecorations, D as TranscriptPosition, E as TranscriptOrder, F as TranscriptRunOutcome, G as isTopLevelTranscriptRecord, H as TranscriptVersion, I as TranscriptSessionContextRecord, J as transcriptRecordEnvelopeFormat, K as runGroupStatus, L as TranscriptToolLifecycle, M as TranscriptRecordViewFromEnvelope, N as TranscriptRunGroupRecord, O as TranscriptRecord, P as TranscriptRunMember, R as TranscriptToolRecord, S as TranscriptDecorationKey, T as TranscriptLogIncarnation, U as UserRecordId, V as TranscriptUserState, W as isPendingTranscriptUserRecord, X as transcriptStoredInlineBodyLimit, Y as transcriptRecordId, _ as TranscriptCursor, a as InferenceAssistantRecordId, b as TranscriptDecorationEntryId, c as ToolRecordId, d as TranscriptAssistantRecord, f as TranscriptBody, g as TranscriptCompactionRecord, h as TranscriptClassification, i as ImportAssistantRecordId, j as TranscriptRecordId, k as TranscriptRecordEnvelope, l as TranscriptAssistantLifecycle, m as TranscriptBufferedDecoration, n as CompactionRecordId, o as RunGroupRecordId, p as TranscriptBodySource, q as transcriptDecorationBufferLimit, r as DecorationBufferRecordId, s as SessionContextRecordId, t as AssistantRecordId, u as TranscriptAssistantPart, v as TranscriptDecoration, w as TranscriptFieldPath, x as TranscriptDecorationEntryKey, y as TranscriptDecorationBufferRecord, z as TranscriptUnknownRecord } from "./records-DWKEjuqb.js";
5
+ import { _ as computeTranscriptVersion, a as TranscriptDefinitionError, c as TranscriptMapping, d as TranscriptMappings, f as TranscriptUserFallback, g as canonicalJson, h as transcriptMappingBounds, i as TranscriptDefinition, l as TranscriptMappingOperation, m as makeTranscriptDefinition, n as TranscriptAliasNamespace, o as TranscriptListEntryKey, p as emptyTranscriptMappings, r as TranscriptProjectionError, s as TranscriptMappedEvent, t as planTranscriptBatch, u as TranscriptMappingTarget, v as transcriptSemanticRevision } from "./interpreter-BYstFpr4.js";
6
+ import { a as TranscriptCursorMismatch, i as EDATranscriptStore, n as readTranscriptWindowFrom, r as transcriptReadiness, t as buildingTranscriptWindow } from "./window-read-U55aAeuz.js";
7
+ import { _ as TranscriptWindowSelector, a as defaultTranscriptSubscriptionPolicy, c as transcriptCoverageOf, d as TranscriptActivePart, f as TranscriptReadiness, g as TranscriptWindowLimits, h as TranscriptWindow, i as TranscriptUpdate, l as transcriptSubscriptionBaseOf, m as TranscriptVersionStatus, n as TranscriptRequestId, o as planTranscriptUpdate, p as TranscriptVersionMeta, r as TranscriptSubscriptionBase, s as readTranscriptSubscription, t as TranscriptCoverage, u as TranscriptActiveContent, v as defaultTranscriptWindowLimits, y as transcriptCursorOf } from "./subscription-g5W0Ggqx.js";
4
8
  import * as Schema from "effect/Schema";
5
- import * as SchemaGetter from "effect/SchemaGetter";
6
- //#region src/transcript/window.ts
7
- const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));
8
- const orderKeyOfCursor = (cursor) => ({
9
- anchorSeq: cursor.anchorSeq,
10
- ordinal: cursor.ordinal,
11
- recordId: cursor.recordId
12
- });
13
- /**
14
- * Which slice of history to read.
15
- *
16
- * `Latest` serves first paint (SSR, CLIs); `Page` walks either direction from a cursor;
17
- * `Range` re-reads exactly the span a client retains, inclusive of both ends, at one new cut.
18
- */
19
- const TranscriptWindowSelector = Schema.Union([
20
- Schema.TaggedStruct("Latest", { count: PositiveInt }),
21
- Schema.TaggedStruct("Page", {
22
- direction: Schema.Literals(["before", "after"]),
23
- cursor: TranscriptCursor,
24
- count: PositiveInt
25
- }),
26
- Schema.TaggedStruct("Range", {
27
- from: TranscriptCursor,
28
- to: TranscriptCursor
29
- }).check(Schema.makeFilter((range) => range.from.incarnation === range.to.incarnation && range.from.version === range.to.version || "a range is scoped to one incarnation and version"), Schema.makeFilter((range) => TranscriptOrder(orderKeyOfCursor(range.from), orderKeyOfCursor(range.to)) <= 0 || "a range starts at or before its end"))
30
- ]);
31
- /**
32
- * Bounds on one window. `maxRecords` caps top-level records (a selector's `count` is further
33
- * capped by it); `maxBytes` caps the whole response, dependencies included; bodies above
34
- * `maxInlineBodyBytes` are sent as references.
35
- */
36
- const TranscriptWindowLimits = Schema.Struct({
37
- maxRecords: PositiveInt,
38
- maxBytes: PositiveInt,
39
- maxInlineBodyBytes: NonNegativeInt
40
- });
41
- /** Default bounds: the first window holds 100 top-level records (design decision 4). */
42
- const defaultTranscriptWindowLimits = {
43
- maxRecords: 100,
44
- maxBytes: 1048576,
45
- maxInlineBodyBytes: 16384
9
+ //#region src/transcript/active-content.ts
10
+ /** The accumulator before anything is published in this isolate. */
11
+ const emptyTranscriptActiveContentState = {
12
+ publishedThroughSeq: SequenceNumber.make(0),
13
+ revision: 0,
14
+ inference: void 0
46
15
  };
47
- /**
48
- * Whether the window is the current interpretation of the log, and if not, why its cut is
49
- * behind.
50
- *
51
- * Every state other than `Ready` is a degraded read and obeys one rule: the response contains
52
- * nothing newer than `throughSeq` — no newer pending users, session context or live content.
53
- */
54
- const KnownReadiness = Schema.TaggedUnion({
55
- /** The active version is healthy and projected through the log head at read time. */
56
- Ready: {},
57
- /** The active version failed while projecting `failedAtSeq`; this is its last good cut. */
58
- Degraded: {
59
- failedAtSeq: SequenceNumber,
60
- error: Schema.String
61
- },
62
- /**
63
- * The active version is no longer carried by this release; history is being rebuilt under
64
- * the current definition, and clients receive one replacement when it activates.
65
- */
66
- UpdatingHistory: {},
67
- /** No version is servable yet; the window is empty. */
68
- Building: {},
69
- /**
70
- * A stored row of the served version cannot be decoded by this release. Nothing is served
71
- * until a rebuild finishes, rather than a wrong view; the window is empty.
72
- */
73
- Unreadable: { error: Schema.String },
74
- /** A readiness this reader does not know; treated as degraded. */
75
- Unknown: { readinessType: Schema.String }
76
- });
77
- const knownReadinessTags = /* @__PURE__ */ new Set([
78
- "Ready",
79
- "Degraded",
80
- "UpdatingHistory",
81
- "Building",
82
- "Unreadable",
83
- "Unknown"
84
- ]);
85
- const UnrecognizedReadiness = Schema.Struct({ _tag: Schema.String.check(Schema.makeFilter((tag) => !knownReadinessTags.has(tag) || "a known readiness must decode as that readiness")) }).pipe(Schema.decodeTo(Schema.toType(KnownReadiness.cases.Unknown), {
86
- decode: SchemaGetter.transform((readiness) => ({
87
- _tag: "Unknown",
88
- readinessType: readiness._tag
89
- })),
90
- encode: SchemaGetter.transform((readiness) => ({ _tag: readiness.readinessType }))
91
- }));
92
- /**
93
- * Whether the window is the current interpretation of the log. A readiness this reader does not
94
- * know decodes as `Unknown` and is treated as degraded: it carries no live content. A malformed
95
- * readiness with a known tag is a decode failure.
96
- */
97
- const TranscriptReadiness = Schema.Union([KnownReadiness, UnrecognizedReadiness]);
98
- /**
99
- * Accumulated parts of the inference streaming now, captured at the same publication boundary as
100
- * the window. Owned by the live runtime; storage-level reads never include it.
101
- */
102
- const TranscriptActiveContent = Schema.Struct({
103
- assistantId: InferenceAssistantRecordId,
104
- parts: Schema.Array(TranscriptAssistantPart)
105
- });
106
- const recordUpdatedSeq = (record) => record.updatedSeq;
107
- const recordPosition = (record) => "position" in record ? record.position : void 0;
108
- /** Positioned history, which is served only as a top-level record and never as a dependency. */
109
- const isHistoryRecord = (record) => record.kind === "unknown" ? record.position !== void 0 : isTopLevelTranscriptRecord(record);
110
- /**
111
- * One complete, consistent read of a transcript version.
112
- *
113
- * `records` are top-level records in transcript order; `dependencies` are the tools and run
114
- * groups they reference, the session context, and every pending user record. Every record is
115
- * projected through `throughSeq` and none is newer, which is what makes a cut complete. A client
116
- * replaces, never merges, what a window covers.
117
- */
118
- const TranscriptWindow = Schema.Struct({
119
- incarnation: TranscriptLogIncarnation,
120
- version: TranscriptVersion,
121
- throughSeq: SequenceNumber,
122
- records: Schema.Array(TranscriptRecordViewFromEnvelope),
123
- dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),
124
- activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),
125
- hasOlder: Schema.Boolean,
126
- hasNewer: Schema.Boolean,
127
- readiness: TranscriptReadiness
128
- }).check(Schema.makeFilter((window) => [...window.records, ...window.dependencies].every((record) => recordUpdatedSeq(record) <= window.throughSeq) || "every record must be projected through throughSeq and none may be newer"), Schema.makeFilter((window) => window.readiness._tag === "Ready" || window.activeContent === void 0 || "a degraded read never attaches live content"), Schema.makeFilter((window) => window.readiness._tag !== "Degraded" || window.readiness.failedAtSeq > window.throughSeq || "a degraded cut ends before the seq that failed"), Schema.makeFilter((window) => [...window.records, ...window.dependencies].every((record) => record.kind !== "decorationBuffer" && (record.kind !== "unknown" || record.originalKind !== "decorationBuffer")) || "decoration buffers are never served"), Schema.makeFilter((window) => {
129
- const ids = [...window.records, ...window.dependencies].map((record) => record.id);
130
- return new Set(ids).size === ids.length || "a record is served at most once";
131
- }), Schema.makeFilter((window) => window.records.every((record, index) => {
132
- const position = recordPosition(record);
133
- if (position === void 0 || !isHistoryRecord(record)) return false;
134
- const previous = index === 0 ? void 0 : window.records[index - 1];
135
- const previousPosition = previous === void 0 ? void 0 : recordPosition(previous);
136
- return previous === void 0 || previousPosition === void 0 || TranscriptOrder({
137
- ...previousPosition,
138
- recordId: previous.id
139
- }, {
140
- ...position,
141
- recordId: record.id
142
- }) < 0;
143
- }) || "records are positioned history records in transcript order"), Schema.makeFilter((window) => window.dependencies.every((record) => !isHistoryRecord(record)) || "dependencies never contain history records"), Schema.makeFilter((window) => window.dependencies.every((record) => record.kind !== "user" || isPendingTranscriptUserRecord(record)) || "the only user dependencies are pending users; cancelled users are never served"), Schema.makeFilter((window) => window.readiness._tag !== "Building" && window.readiness._tag !== "Unreadable" || window.records.length === 0 && window.dependencies.length === 0 && !window.hasOlder && !window.hasNewer || "a building or unreadable window is empty"));
144
- /** Paging cursor for one top-level record of a window. */
145
- const transcriptCursorOf = (window, record) => {
146
- const position = "position" in record ? record.position : void 0;
147
- return position === void 0 ? void 0 : {
148
- incarnation: window.incarnation,
149
- version: window.version,
150
- anchorSeq: position.anchorSeq,
151
- ordinal: position.ordinal,
152
- recordId: record.id
16
+ const isInferenceStarted = Schema.is(InferenceStartedEvent);
17
+ const isInferenceCompleted = Schema.is(InferenceCompletedEvent);
18
+ const isInferenceFailed = Schema.is(InferenceFailedEvent);
19
+ const isTurnCompleted = Schema.is(TurnCompletedEvent);
20
+ const isTurnFailed = Schema.is(TurnFailedEvent);
21
+ const isTurnStopped = Schema.is(TurnStoppedEvent);
22
+ const isTextDelta = Schema.is(TextDeltaEvent);
23
+ const isReasoningDelta = Schema.is(ReasoningDeltaEvent);
24
+ const isToolParamsStart = Schema.is(ToolParamsStartEvent);
25
+ const isToolParamsDelta = Schema.is(ToolParamsDeltaEvent);
26
+ /** Fold one published event, in publication order, into the active-content accumulator. */
27
+ const foldTranscriptActiveContent = (state, positioned) => {
28
+ const event = positioned.event;
29
+ if (event.durability === "durable") {
30
+ const published = {
31
+ ...state,
32
+ publishedThroughSeq: SequenceNumber.make(Math.max(state.publishedThroughSeq, positioned.position.seq))
33
+ };
34
+ if (isInferenceStarted(event)) return withInference(published, {
35
+ inferenceId: event.payload.inferenceId,
36
+ turnId: event.payload.turnId,
37
+ parts: []
38
+ });
39
+ const active = published.inference;
40
+ if (active === void 0) return published;
41
+ return (isInferenceCompleted(event) || isInferenceFailed(event)) && event.payload.inferenceId === active.inferenceId || (isTurnCompleted(event) || isTurnFailed(event) || isTurnStopped(event)) && event.payload.turnId === active.turnId ? withInference(published, void 0) : published;
42
+ }
43
+ const active = state.inference;
44
+ if (active === void 0) return state;
45
+ if (isTextDelta(event)) return appendText(state, active, "Text", `text:${event.payload.providerPartId}`, event.payload.delta);
46
+ if (isReasoningDelta(event)) return appendText(state, active, "Reasoning", `reasoning:${event.payload.providerPartId}`, event.payload.delta);
47
+ if (isToolParamsStart(event)) {
48
+ const id = `tool:${event.payload.toolCallId}`;
49
+ if (active.parts.some((part) => part.id === id)) return state;
50
+ return withInference(state, {
51
+ ...active,
52
+ parts: [...active.parts, {
53
+ id,
54
+ part: {
55
+ _tag: "ToolCall",
56
+ providerPartId: event.payload.providerPartId,
57
+ toolName: event.payload.toolName,
58
+ providerExecuted: event.payload.providerExecuted
59
+ },
60
+ paramsText: ""
61
+ }]
62
+ });
63
+ }
64
+ if (isToolParamsDelta(event)) {
65
+ const id = `tool:${event.payload.toolCallId}`;
66
+ const delta = event.payload.delta;
67
+ if (delta.length === 0 || !active.parts.some((part) => part.id === id)) return state;
68
+ return withInference(state, {
69
+ ...active,
70
+ parts: active.parts.map((part) => part.id === id ? {
71
+ ...part,
72
+ paramsText: (part.paramsText ?? "") + delta
73
+ } : part)
74
+ });
75
+ }
76
+ return state;
77
+ };
78
+ const appendText = (state, active, tag, id, delta) => {
79
+ if (delta.length === 0) return state;
80
+ const index = active.parts.findIndex((part) => part.id === id);
81
+ const existing = index === -1 ? void 0 : active.parts[index];
82
+ const part = {
83
+ id,
84
+ part: {
85
+ _tag: tag,
86
+ text: existing !== void 0 && existing.part._tag === tag ? existing.part.text + delta : delta
87
+ }
153
88
  };
89
+ return withInference(state, {
90
+ ...active,
91
+ parts: index === -1 ? [...active.parts, part] : active.parts.map((candidate, candidateIndex) => candidateIndex === index ? part : candidate)
92
+ });
154
93
  };
155
- /** Health of one stored transcript version. A failed version is frozen at its last good cursor. */
156
- const TranscriptVersionStatus = Schema.TaggedUnion({
157
- Ok: {},
158
- Failed: {
159
- failedAtSeq: SequenceNumber,
160
- error: Schema.String
161
- }
162
- });
163
- /**
164
- * Per-version maintenance state, one per version present in a session's storage.
165
- *
166
- * `cursor` is the last fully projected seq, committed together with that version's rows. At most
167
- * one version is `active` (served) and at most one is `building` (catching up from the log).
168
- */
169
- const TranscriptVersionMeta = Schema.Struct({
170
- version: TranscriptVersion,
171
- role: Schema.Literals(["active", "building"]),
172
- cursor: SequenceNumber,
173
- status: TranscriptVersionStatus
174
- }).check(Schema.makeFilter((meta) => meta.status._tag !== "Failed" || meta.status.failedAtSeq > meta.cursor || "a failed version is frozen before the seq that failed"));
94
+ const withInference = (state, inference) => state.inference === void 0 && inference === void 0 ? state : {
95
+ ...state,
96
+ revision: state.revision + 1,
97
+ inference
98
+ };
99
+ /** The active content to serve, in the window's shape; empty when nothing is streaming. */
100
+ const transcriptActiveContentOf = (state) => state.inference === void 0 ? [] : [{
101
+ assistantId: transcriptRecordId.assistant(state.inference.inferenceId),
102
+ parts: state.inference.parts
103
+ }];
175
104
  //#endregion
176
- export { AssistantRecordId, CompactionRecordId, DecorationBufferRecordId, EDATranscriptStore, ImportAssistantRecordId, InferenceAssistantRecordId, RunGroupRecordId, SessionContextRecordId, ToolRecordId, TranscriptActiveContent, TranscriptAliasNamespace, TranscriptAssistantLifecycle, TranscriptAssistantPart, TranscriptAssistantRecord, TranscriptBody, TranscriptBodySource, TranscriptBufferedDecoration, TranscriptClassification, TranscriptCompactionRecord, TranscriptCursor, TranscriptCursorMismatch, TranscriptDecoration, TranscriptDecorationBufferRecord, TranscriptDecorationEntryKey, TranscriptDecorationKey, TranscriptDecorations, TranscriptDefinition, TranscriptDefinitionError, TranscriptFieldPath, TranscriptListEntryKey, TranscriptLogIncarnation, TranscriptMappedEvent, TranscriptMapping, TranscriptMappingOperation, TranscriptMappingTarget, TranscriptMappings, TranscriptOrder, TranscriptPosition, TranscriptProjectionError, TranscriptReadiness, TranscriptRecord, TranscriptRecordEnvelope, TranscriptRecordFromEnvelope, TranscriptRecordId, TranscriptRecordViewFromEnvelope, TranscriptRunGroupRecord, TranscriptRunMember, TranscriptRunOutcome, TranscriptSessionContextRecord, TranscriptToolLifecycle, TranscriptToolRecord, TranscriptUnknownRecord, TranscriptUserFallback, TranscriptUserRecord, TranscriptUserState, TranscriptVersion, TranscriptVersionMeta, TranscriptVersionStatus, TranscriptWindow, TranscriptWindowLimits, TranscriptWindowSelector, UserRecordId, buildingTranscriptWindow, canonicalJson, computeTranscriptVersion, defaultTranscriptWindowLimits, emptyTranscriptMappings, isPendingTranscriptUserRecord, isTopLevelTranscriptRecord, makeTranscriptDefinition, planTranscriptBatch, readTranscriptWindowFrom, runGroupStatus, transcriptCursorOf, transcriptDecorationBufferLimit, transcriptMappingBounds, transcriptReadiness, transcriptRecordEnvelopeFormat, transcriptRecordId, transcriptSemanticRevision, transcriptStoredInlineBodyLimit };
105
+ export { AssistantRecordId, CompactionRecordId, DecorationBufferRecordId, EDATranscriptStore, ImportAssistantRecordId, InferenceAssistantRecordId, RunGroupRecordId, SessionContextRecordId, ToolRecordId, TranscriptActiveContent, TranscriptActivePart, TranscriptAliasNamespace, TranscriptAssistantLifecycle, TranscriptAssistantPart, TranscriptAssistantRecord, TranscriptBody, TranscriptBodySource, TranscriptBufferedDecoration, TranscriptClassification, TranscriptCompactionRecord, TranscriptCoverage, TranscriptCursor, TranscriptCursorMismatch, TranscriptDecoration, TranscriptDecorationBufferRecord, TranscriptDecorationEntryId, TranscriptDecorationEntryKey, TranscriptDecorationKey, TranscriptDecorations, TranscriptDefinition, TranscriptDefinitionError, TranscriptFieldPath, TranscriptListEntryKey, TranscriptLogIncarnation, TranscriptMappedEvent, TranscriptMapping, TranscriptMappingOperation, TranscriptMappingTarget, TranscriptMappings, TranscriptOrder, TranscriptPosition, TranscriptProjectionError, TranscriptReadiness, TranscriptRecord, TranscriptRecordEnvelope, TranscriptRecordFromEnvelope, TranscriptRecordId, TranscriptRecordViewFromEnvelope, TranscriptRequestId, TranscriptRunGroupRecord, TranscriptRunMember, TranscriptRunOutcome, TranscriptSessionContextRecord, TranscriptSubscriptionBase, TranscriptToolLifecycle, TranscriptToolRecord, TranscriptUnknownRecord, TranscriptUpdate, TranscriptUserFallback, TranscriptUserRecord, TranscriptUserState, TranscriptVersion, TranscriptVersionMeta, TranscriptVersionStatus, TranscriptWindow, TranscriptWindowLimits, TranscriptWindowSelector, UserRecordId, buildingTranscriptWindow, canonicalJson, computeTranscriptVersion, defaultTranscriptSubscriptionPolicy, defaultTranscriptWindowLimits, emptyTranscriptActiveContentState, emptyTranscriptMappings, foldTranscriptActiveContent, isPendingTranscriptUserRecord, isTopLevelTranscriptRecord, makeTranscriptDefinition, planTranscriptBatch, planTranscriptUpdate, readTranscriptSubscription, readTranscriptWindowFrom, runGroupStatus, transcriptActiveContentOf, transcriptCoverageOf, transcriptCursorOf, transcriptDecorationBufferLimit, transcriptMappingBounds, transcriptReadiness, transcriptRecordEnvelopeFormat, transcriptRecordId, transcriptSemanticRevision, transcriptStoredInlineBodyLimit, transcriptSubscriptionBaseOf };
177
106
 
178
107
  //# sourceMappingURL=transcript.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"transcript.js","names":[],"sources":["../src/transcript/window.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { NonNegativeInt } from \"../types/events/envelope\";\nimport {\n InferenceAssistantRecordId,\n TranscriptAssistantPart,\n TranscriptCursor,\n TranscriptLogIncarnation,\n TranscriptOrder,\n TranscriptRecordViewFromEnvelope,\n isPendingTranscriptUserRecord,\n isTopLevelTranscriptRecord,\n TranscriptVersion,\n type TranscriptOrderKey,\n type TranscriptRecordView,\n} from \"./records\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\n\nconst orderKeyOfCursor = (cursor: TranscriptCursor): TranscriptOrderKey => ({\n anchorSeq: cursor.anchorSeq,\n ordinal: cursor.ordinal,\n recordId: cursor.recordId,\n});\n\n/**\n * Which slice of history to read.\n *\n * `Latest` serves first paint (SSR, CLIs); `Page` walks either direction from a cursor;\n * `Range` re-reads exactly the span a client retains, inclusive of both ends, at one new cut.\n */\nexport const TranscriptWindowSelector = Schema.Union([\n Schema.TaggedStruct(\"Latest\", { count: PositiveInt }),\n Schema.TaggedStruct(\"Page\", {\n direction: Schema.Literals([\"before\", \"after\"]),\n cursor: TranscriptCursor,\n count: PositiveInt,\n }),\n Schema.TaggedStruct(\"Range\", { from: TranscriptCursor, to: TranscriptCursor }).check(\n Schema.makeFilter(\n (range) =>\n (range.from.incarnation === range.to.incarnation &&\n range.from.version === range.to.version) ||\n \"a range is scoped to one incarnation and version\",\n ),\n Schema.makeFilter(\n (range) =>\n TranscriptOrder(orderKeyOfCursor(range.from), orderKeyOfCursor(range.to)) <= 0 ||\n \"a range starts at or before its end\",\n ),\n ),\n]);\nexport type TranscriptWindowSelector = typeof TranscriptWindowSelector.Type;\n\n/**\n * Bounds on one window. `maxRecords` caps top-level records (a selector's `count` is further\n * capped by it); `maxBytes` caps the whole response, dependencies included; bodies above\n * `maxInlineBodyBytes` are sent as references.\n */\nexport const TranscriptWindowLimits = Schema.Struct({\n maxRecords: PositiveInt,\n maxBytes: PositiveInt,\n maxInlineBodyBytes: NonNegativeInt,\n});\nexport type TranscriptWindowLimits = typeof TranscriptWindowLimits.Type;\n\n/** Default bounds: the first window holds 100 top-level records (design decision 4). */\nexport const defaultTranscriptWindowLimits: TranscriptWindowLimits = {\n maxRecords: 100,\n maxBytes: 1_048_576,\n maxInlineBodyBytes: 16_384,\n};\n\n/**\n * Whether the window is the current interpretation of the log, and if not, why its cut is\n * behind.\n *\n * Every state other than `Ready` is a degraded read and obeys one rule: the response contains\n * nothing newer than `throughSeq` — no newer pending users, session context or live content.\n */\nconst KnownReadiness = Schema.TaggedUnion({\n /** The active version is healthy and projected through the log head at read time. */\n Ready: {},\n /** The active version failed while projecting `failedAtSeq`; this is its last good cut. */\n Degraded: { failedAtSeq: SequenceNumber, error: Schema.String },\n /**\n * The active version is no longer carried by this release; history is being rebuilt under\n * the current definition, and clients receive one replacement when it activates.\n */\n UpdatingHistory: {},\n /** No version is servable yet; the window is empty. */\n Building: {},\n /**\n * A stored row of the served version cannot be decoded by this release. Nothing is served\n * until a rebuild finishes, rather than a wrong view; the window is empty.\n */\n Unreadable: { error: Schema.String },\n /** A readiness this reader does not know; treated as degraded. */\n Unknown: { readinessType: Schema.String },\n});\n\nconst knownReadinessTags: ReadonlySet<string> = new Set([\n \"Ready\",\n \"Degraded\",\n \"UpdatingHistory\",\n \"Building\",\n \"Unreadable\",\n \"Unknown\",\n]);\n\nconst UnrecognizedReadiness = Schema.Struct({\n _tag: Schema.String.check(\n Schema.makeFilter(\n (tag) => !knownReadinessTags.has(tag) || \"a known readiness must decode as that readiness\",\n ),\n ),\n}).pipe(\n Schema.decodeTo(Schema.toType(KnownReadiness.cases.Unknown), {\n decode: SchemaGetter.transform((readiness) => ({\n _tag: \"Unknown\" as const,\n readinessType: readiness._tag,\n })),\n encode: SchemaGetter.transform((readiness) => ({ _tag: readiness.readinessType })),\n }),\n);\n\n/**\n * Whether the window is the current interpretation of the log. A readiness this reader does not\n * know decodes as `Unknown` and is treated as degraded: it carries no live content. A malformed\n * readiness with a known tag is a decode failure.\n */\nexport const TranscriptReadiness = Schema.Union([KnownReadiness, UnrecognizedReadiness]);\nexport type TranscriptReadiness = typeof TranscriptReadiness.Type;\n\n/**\n * Accumulated parts of the inference streaming now, captured at the same publication boundary as\n * the window. Owned by the live runtime; storage-level reads never include it.\n */\nexport const TranscriptActiveContent = Schema.Struct({\n assistantId: InferenceAssistantRecordId,\n parts: Schema.Array(TranscriptAssistantPart),\n});\nexport type TranscriptActiveContent = typeof TranscriptActiveContent.Type;\n\nconst recordUpdatedSeq = (record: TranscriptRecordView): number => record.updatedSeq;\n\nconst recordPosition = (record: TranscriptRecordView) =>\n \"position\" in record ? record.position : undefined;\n\n/** Positioned history, which is served only as a top-level record and never as a dependency. */\nconst isHistoryRecord = (record: TranscriptRecordView): boolean =>\n record.kind === \"unknown\" ? record.position !== undefined : isTopLevelTranscriptRecord(record);\n\n/**\n * One complete, consistent read of a transcript version.\n *\n * `records` are top-level records in transcript order; `dependencies` are the tools and run\n * groups they reference, the session context, and every pending user record. Every record is\n * projected through `throughSeq` and none is newer, which is what makes a cut complete. A client\n * replaces, never merges, what a window covers.\n */\nexport const TranscriptWindow = Schema.Struct({\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n throughSeq: SequenceNumber,\n records: Schema.Array(TranscriptRecordViewFromEnvelope),\n dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),\n activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),\n hasOlder: Schema.Boolean,\n hasNewer: Schema.Boolean,\n readiness: TranscriptReadiness,\n}).check(\n Schema.makeFilter(\n (window) =>\n [...window.records, ...window.dependencies].every(\n (record) => recordUpdatedSeq(record) <= window.throughSeq,\n ) || \"every record must be projected through throughSeq and none may be newer\",\n ),\n Schema.makeFilter(\n (window) =>\n window.readiness._tag === \"Ready\" ||\n window.activeContent === undefined ||\n \"a degraded read never attaches live content\",\n ),\n Schema.makeFilter(\n (window) =>\n window.readiness._tag !== \"Degraded\" ||\n window.readiness.failedAtSeq > window.throughSeq ||\n \"a degraded cut ends before the seq that failed\",\n ),\n Schema.makeFilter(\n (window) =>\n [...window.records, ...window.dependencies].every(\n (record) =>\n record.kind !== \"decorationBuffer\" &&\n (record.kind !== \"unknown\" || record.originalKind !== \"decorationBuffer\"),\n ) || \"decoration buffers are never served\",\n ),\n Schema.makeFilter((window) => {\n const ids = [...window.records, ...window.dependencies].map((record) => record.id);\n return new Set(ids).size === ids.length || \"a record is served at most once\";\n }),\n Schema.makeFilter(\n (window) =>\n window.records.every((record, index) => {\n const position = recordPosition(record);\n if (position === undefined || !isHistoryRecord(record)) return false;\n const previous = index === 0 ? undefined : window.records[index - 1];\n const previousPosition = previous === undefined ? undefined : recordPosition(previous);\n return (\n previous === undefined ||\n previousPosition === undefined ||\n TranscriptOrder(\n { ...previousPosition, recordId: previous.id },\n { ...position, recordId: record.id },\n ) < 0\n );\n }) || \"records are positioned history records in transcript order\",\n ),\n Schema.makeFilter(\n (window) =>\n window.dependencies.every((record) => !isHistoryRecord(record)) ||\n \"dependencies never contain history records\",\n ),\n Schema.makeFilter(\n (window) =>\n window.dependencies.every(\n (record) => record.kind !== \"user\" || isPendingTranscriptUserRecord(record),\n ) || \"the only user dependencies are pending users; cancelled users are never served\",\n ),\n Schema.makeFilter(\n (window) =>\n (window.readiness._tag !== \"Building\" && window.readiness._tag !== \"Unreadable\") ||\n (window.records.length === 0 &&\n window.dependencies.length === 0 &&\n !window.hasOlder &&\n !window.hasNewer) ||\n \"a building or unreadable window is empty\",\n ),\n);\nexport type TranscriptWindow = typeof TranscriptWindow.Type;\n\n/** Paging cursor for one top-level record of a window. */\nexport const transcriptCursorOf = (\n window: Pick<TranscriptWindow, \"incarnation\" | \"version\">,\n record: TranscriptRecordView,\n): TranscriptCursor | undefined => {\n const position = \"position\" in record ? record.position : undefined;\n return position === undefined\n ? undefined\n : {\n incarnation: window.incarnation,\n version: window.version,\n anchorSeq: position.anchorSeq,\n ordinal: position.ordinal,\n recordId: record.id,\n };\n};\n\n/** Health of one stored transcript version. A failed version is frozen at its last good cursor. */\nexport const TranscriptVersionStatus = Schema.TaggedUnion({\n Ok: {},\n Failed: { failedAtSeq: SequenceNumber, error: Schema.String },\n});\nexport type TranscriptVersionStatus = typeof TranscriptVersionStatus.Type;\n\n/**\n * Per-version maintenance state, one per version present in a session's storage.\n *\n * `cursor` is the last fully projected seq, committed together with that version's rows. At most\n * one version is `active` (served) and at most one is `building` (catching up from the log).\n */\nexport const TranscriptVersionMeta = Schema.Struct({\n version: TranscriptVersion,\n role: Schema.Literals([\"active\", \"building\"]),\n cursor: SequenceNumber,\n status: TranscriptVersionStatus,\n}).check(\n Schema.makeFilter(\n (meta) =>\n meta.status._tag !== \"Failed\" ||\n meta.status.failedAtSeq > meta.cursor ||\n \"a failed version is frozen before the seq that failed\",\n ),\n);\nexport type TranscriptVersionMeta = typeof TranscriptVersionMeta.Type;\n"],"mappings":";;;;;;AAmBA,MAAM,cAAc,OAAO,IAAI,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,OAAO;CACnB;AACN;;AAGA,MAAa,0BAA0B,OAAO,YAAY;CACxD,IAAI,CAAC;CACL,QAAQ;EAAE,aAAa;EAAgB,OAAO,OAAO;CAAO;AAC9D,CAAC;;;;;;;AASD,MAAa,wBAAwB,OAAO,OAAO;CACjD,SAAS;CACT,MAAM,OAAO,SAAS,CAAC,UAAU,UAAU,CAAC;CAC5C,QAAQ;CACR,QAAQ;AACV,CAAC,CAAC,CAAC,MACD,OAAO,YACJ,SACC,KAAK,OAAO,SAAS,YACrB,KAAK,OAAO,cAAc,KAAK,UAC/B,uDACJ,CACF"}
1
+ {"version":3,"file":"transcript.js","names":[],"sources":["../src/transcript/active-content.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber, type InferenceId, type TurnId } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\nimport {\n InferenceCompletedEvent,\n InferenceFailedEvent,\n InferenceStartedEvent,\n TurnCompletedEvent,\n TurnFailedEvent,\n TurnStoppedEvent,\n} from \"../types/events/durable\";\nimport {\n ReasoningDeltaEvent,\n TextDeltaEvent,\n ToolParamsDeltaEvent,\n ToolParamsStartEvent,\n} from \"../types/events/ephemeral\";\nimport { transcriptRecordId } from \"./records\";\nimport type { TranscriptActiveContent, TranscriptActivePart } from \"./window\";\n\n/**\n * The accumulated value of the inference streaming now, folded from the published live stream.\n *\n * Text and reasoning deltas carry only a `providerPartId`; they belong to the session's one\n * active inference, which is the latest `InferenceStarted` without a terminal. That association\n * is sound because `SessionState` publishes every durable and ephemeral event under one append\n * gate, in commit order: an inference's start is published before its first delta and its\n * terminal after its last. A session runs at most one inference at a time.\n *\n * The value is retired on every inference terminal (commit, partial plus failure, empty success\n * and recovery failure all end in `InferenceCompleted` or `InferenceFailed`), and on its turn's\n * terminal as a backstop. It is volatile: an isolate loss loses it, and recovery records the\n * inference as failed (design decision 6).\n */\nexport interface TranscriptActiveContentState {\n /** Highest durable seq this accumulator has folded; the publication side of the capture fence. */\n readonly publishedThroughSeq: SequenceNumber;\n /** Increases whenever the served active content changes; lets subscribers skip unchanged sends. */\n readonly revision: number;\n readonly inference: ActiveInference | undefined;\n}\n\ninterface ActiveInference {\n readonly inferenceId: InferenceId;\n readonly turnId: TurnId;\n readonly parts: ReadonlyArray<TranscriptActivePart>;\n}\n\n/** The accumulator before anything is published in this isolate. */\nexport const emptyTranscriptActiveContentState: TranscriptActiveContentState = {\n publishedThroughSeq: SequenceNumber.make(0),\n revision: 0,\n inference: undefined,\n};\n\nconst isInferenceStarted = Schema.is(InferenceStartedEvent);\nconst isInferenceCompleted = Schema.is(InferenceCompletedEvent);\nconst isInferenceFailed = Schema.is(InferenceFailedEvent);\nconst isTurnCompleted = Schema.is(TurnCompletedEvent);\nconst isTurnFailed = Schema.is(TurnFailedEvent);\nconst isTurnStopped = Schema.is(TurnStoppedEvent);\nconst isTextDelta = Schema.is(TextDeltaEvent);\nconst isReasoningDelta = Schema.is(ReasoningDeltaEvent);\nconst isToolParamsStart = Schema.is(ToolParamsStartEvent);\nconst isToolParamsDelta = Schema.is(ToolParamsDeltaEvent);\n\n/** Fold one published event, in publication order, into the active-content accumulator. */\nexport const foldTranscriptActiveContent = (\n state: TranscriptActiveContentState,\n positioned: PositionedEvent,\n): TranscriptActiveContentState => {\n const event = positioned.event;\n if (event.durability === \"durable\") {\n const published: TranscriptActiveContentState = {\n ...state,\n publishedThroughSeq: SequenceNumber.make(\n Math.max(state.publishedThroughSeq, positioned.position.seq),\n ),\n };\n if (isInferenceStarted(event)) {\n return withInference(published, {\n inferenceId: event.payload.inferenceId,\n turnId: event.payload.turnId,\n parts: [],\n });\n }\n const active = published.inference;\n if (active === undefined) return published;\n const retires =\n ((isInferenceCompleted(event) || isInferenceFailed(event)) &&\n event.payload.inferenceId === active.inferenceId) ||\n ((isTurnCompleted(event) || isTurnFailed(event) || isTurnStopped(event)) &&\n event.payload.turnId === active.turnId);\n return retires ? withInference(published, undefined) : published;\n }\n\n const active = state.inference;\n if (active === undefined) return state;\n if (isTextDelta(event)) {\n return appendText(\n state,\n active,\n \"Text\",\n `text:${event.payload.providerPartId}`,\n event.payload.delta,\n );\n }\n if (isReasoningDelta(event)) {\n return appendText(\n state,\n active,\n \"Reasoning\",\n `reasoning:${event.payload.providerPartId}`,\n event.payload.delta,\n );\n }\n if (isToolParamsStart(event)) {\n const id = `tool:${event.payload.toolCallId}`;\n if (active.parts.some((part) => part.id === id)) return state;\n return withInference(state, {\n ...active,\n parts: [\n ...active.parts,\n {\n id,\n part: {\n _tag: \"ToolCall\",\n providerPartId: event.payload.providerPartId,\n toolName: event.payload.toolName,\n providerExecuted: event.payload.providerExecuted,\n },\n paramsText: \"\",\n },\n ],\n });\n }\n if (isToolParamsDelta(event)) {\n const id = `tool:${event.payload.toolCallId}`;\n const delta = event.payload.delta;\n if (delta.length === 0 || !active.parts.some((part) => part.id === id)) return state;\n return withInference(state, {\n ...active,\n parts: active.parts.map((part) =>\n part.id === id ? { ...part, paramsText: (part.paramsText ?? \"\") + delta } : part,\n ),\n });\n }\n return state;\n};\n\nconst appendText = (\n state: TranscriptActiveContentState,\n active: ActiveInference,\n tag: \"Text\" | \"Reasoning\",\n id: string,\n delta: string,\n): TranscriptActiveContentState => {\n if (delta.length === 0) return state;\n const index = active.parts.findIndex((part) => part.id === id);\n const existing = index === -1 ? undefined : active.parts[index];\n const text =\n existing !== undefined && existing.part._tag === tag ? existing.part.text + delta : delta;\n const part: TranscriptActivePart = { id, part: { _tag: tag, text } };\n return withInference(state, {\n ...active,\n parts:\n index === -1\n ? [...active.parts, part]\n : active.parts.map((candidate, candidateIndex) =>\n candidateIndex === index ? part : candidate,\n ),\n });\n};\n\nconst withInference = (\n state: TranscriptActiveContentState,\n inference: ActiveInference | undefined,\n): TranscriptActiveContentState =>\n state.inference === undefined && inference === undefined\n ? state\n : { ...state, revision: state.revision + 1, inference };\n\n/** The active content to serve, in the window's shape; empty when nothing is streaming. */\nexport const transcriptActiveContentOf = (\n state: TranscriptActiveContentState,\n): ReadonlyArray<TranscriptActiveContent> =>\n state.inference === undefined\n ? []\n : [\n {\n assistantId: transcriptRecordId.assistant(state.inference.inferenceId),\n parts: state.inference.parts,\n },\n ];\n"],"mappings":";;;;;;;;;;AAkDA,MAAa,oCAAkE;CAC7E,qBAAqB,eAAe,KAAK,CAAC;CAC1C,UAAU;CACV,WAAW,KAAA;AACb;AAEA,MAAM,qBAAqB,OAAO,GAAG,qBAAqB;AAC1D,MAAM,uBAAuB,OAAO,GAAG,uBAAuB;AAC9D,MAAM,oBAAoB,OAAO,GAAG,oBAAoB;AACxD,MAAM,kBAAkB,OAAO,GAAG,kBAAkB;AACpD,MAAM,eAAe,OAAO,GAAG,eAAe;AAC9C,MAAM,gBAAgB,OAAO,GAAG,gBAAgB;AAChD,MAAM,cAAc,OAAO,GAAG,cAAc;AAC5C,MAAM,mBAAmB,OAAO,GAAG,mBAAmB;AACtD,MAAM,oBAAoB,OAAO,GAAG,oBAAoB;AACxD,MAAM,oBAAoB,OAAO,GAAG,oBAAoB;;AAGxD,MAAa,+BACX,OACA,eACiC;CACjC,MAAM,QAAQ,WAAW;CACzB,IAAI,MAAM,eAAe,WAAW;EAClC,MAAM,YAA0C;GAC9C,GAAG;GACH,qBAAqB,eAAe,KAClC,KAAK,IAAI,MAAM,qBAAqB,WAAW,SAAS,GAAG,CAC7D;EACF;EACA,IAAI,mBAAmB,KAAK,GAC1B,OAAO,cAAc,WAAW;GAC9B,aAAa,MAAM,QAAQ;GAC3B,QAAQ,MAAM,QAAQ;GACtB,OAAO,CAAC;EACV,CAAC;EAEH,MAAM,SAAS,UAAU;EACzB,IAAI,WAAW,KAAA,GAAW,OAAO;EAMjC,QAJI,qBAAqB,KAAK,KAAK,kBAAkB,KAAK,MACtD,MAAM,QAAQ,gBAAgB,OAAO,gBACrC,gBAAgB,KAAK,KAAK,aAAa,KAAK,KAAK,cAAc,KAAK,MACpE,MAAM,QAAQ,WAAW,OAAO,SACnB,cAAc,WAAW,KAAA,CAAS,IA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