effect-durable-agent 0.1.0-alpha.22 → 0.1.0-alpha.23
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/dist/domain/command-queues.d.ts +1 -1
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/reduced-state.d.ts +1 -1
- package/dist/domain/run-scheduling.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/records-DWKEjuqb.js +675 -0
- package/dist/records-DWKEjuqb.js.map +1 -0
- package/dist/{reduced-state-PJdig48e.d.ts → reduced-state-B5WxKSM5.d.ts} +4206 -4206
- package/dist/{reducer-registry-BAbhZs6d.d.ts → reducer-registry-CPObI3cs.d.ts} +2 -2
- package/dist/{run-scheduling-wakeup-QLK87OqG.d.ts → run-scheduling-wakeup-B19JTeyq.d.ts} +2 -2
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/model-call.d.ts +1 -1
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/reducer-registry.d.ts +1 -1
- package/dist/services/reducer-registry.js +1 -1
- package/dist/services/run-scheduler.d.ts +1 -1
- package/dist/services/run-scheduling-wakeup.d.ts +1 -1
- package/dist/services/runtime-layer.d.ts +6 -6
- package/dist/services/runtime-layer.js +3 -3
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +1 -1
- package/dist/services/session-query.d.ts +1 -1
- package/dist/services/session-query.js +2 -2
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.d.ts +1 -1
- package/dist/services/session-store.js +1 -1
- package/dist/services/sink-checkpoint-store.d.ts +1 -1
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/tool-registry.d.ts +1 -1
- package/dist/{session-state-StlO5B2N.js → session-state-C6SyphC0.js} +3 -3
- package/dist/{session-state-StlO5B2N.js.map → session-state-C6SyphC0.js.map} +1 -1
- package/dist/{session-store-ByDjS03N.d.ts → session-store-CWYZ29CV.d.ts} +163 -45
- package/dist/{session-store-DcJjs4Fd.js → session-store-DuEhcqIC.js} +3 -2
- package/dist/{session-store-DcJjs4Fd.js.map → session-store-DuEhcqIC.js.map} +1 -1
- package/dist/{sink-checkpoint-store-BHb8YRTw.d.ts → sink-checkpoint-store-B8Ky5nfW.d.ts} +2 -2
- package/dist/{sink-registry-DEneTH8u.js → sink-registry-DtrssBxF.js} +2 -2
- package/dist/{sink-registry-DEneTH8u.js.map → sink-registry-DtrssBxF.js.map} +1 -1
- package/dist/subscription-DelB8L87.d.ts +958 -0
- package/dist/subscription-g5W0Ggqx.js +498 -0
- package/dist/subscription-g5W0Ggqx.js.map +1 -0
- package/dist/testkit/layers.d.ts +9 -6
- package/dist/testkit/layers.js +4 -4
- package/dist/testkit/layers.js.map +1 -1
- package/dist/{tool-registry-CxZ0iuYb.d.ts → tool-registry-B_WE2ZwK.d.ts} +2 -2
- package/dist/transcript.d.ts +44 -4
- package/dist/transcript.js +98 -170
- package/dist/transcript.js.map +1 -1
- package/dist/websocket.d.ts +2209 -2
- package/dist/websocket.js +704 -18
- package/dist/websocket.js.map +1 -1
- package/dist/{window-read-B8aF_hDq.js → window-read-BDayZf7O.js} +74 -683
- package/dist/window-read-BDayZf7O.js.map +1 -0
- package/package.json +1 -1
- package/dist/window-read-B8aF_hDq.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"window-read-B8aF_hDq.js","names":["jsonBytes","encoder","encodeRecord"],"sources":["../src/transcript/hash.ts","../src/transcript/records.ts","../src/transcript/version.ts","../src/transcript/mapping.ts","../src/transcript/plan.ts","../src/transcript/mapping-executor.ts","../src/transcript/interpreter.ts","../src/transcript/store.ts","../src/transcript/window-read.ts"],"sourcesContent":["/**\n * Synchronous hashing for transcript identities (versions and bounded record keys).\n */\n\n// SHA-256 (FIPS 180-4). Synchronous so version identity is available inside synchronous storage\n// transactions and at module construction; Web Crypto digests are asynchronous only.\nconst roundConstants = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nconst rotateRight = (value: number, bits: number): number =>\n (value >>> bits) | (value << (32 - bits));\n\n// Typed-array reads are always in bounds here; the fallback only satisfies index typing.\nconst at = (words: Uint32Array, index: number): number => words[index] ?? 0;\n\n/** Lowercase hex SHA-256 of a string's UTF-8 bytes. */\nexport const sha256Hex = (input: string): string => {\n const message = new TextEncoder().encode(input);\n const bitLength = message.length * 8;\n const paddedLength = Math.ceil((message.length + 9) / 64) * 64;\n const padded = new Uint8Array(paddedLength);\n padded.set(message);\n padded[message.length] = 0x80;\n const view = new DataView(padded.buffer);\n view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x1_0000_0000));\n view.setUint32(paddedLength - 4, bitLength >>> 0);\n\n const hash = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ]);\n const schedule = new Uint32Array(64);\n for (let offset = 0; offset < paddedLength; offset += 64) {\n for (let index = 0; index < 16; index += 1) {\n schedule[index] = view.getUint32(offset + index * 4);\n }\n for (let index = 16; index < 64; index += 1) {\n const w15 = at(schedule, index - 15);\n const w2 = at(schedule, index - 2);\n const s0 = rotateRight(w15, 7) ^ rotateRight(w15, 18) ^ (w15 >>> 3);\n const s1 = rotateRight(w2, 17) ^ rotateRight(w2, 19) ^ (w2 >>> 10);\n schedule[index] = at(schedule, index - 16) + s0 + at(schedule, index - 7) + s1;\n }\n const working = Uint32Array.from(hash);\n for (let index = 0; index < 64; index += 1) {\n const [a, b, c, d, e, f, g, h] = Array.from(working);\n const s1 = rotateRight(e ?? 0, 6) ^ rotateRight(e ?? 0, 11) ^ rotateRight(e ?? 0, 25);\n const choice = ((e ?? 0) & (f ?? 0)) ^ (~(e ?? 0) & (g ?? 0));\n const t1 = (h ?? 0) + s1 + choice + at(roundConstants, index) + at(schedule, index);\n const s0 = rotateRight(a ?? 0, 2) ^ rotateRight(a ?? 0, 13) ^ rotateRight(a ?? 0, 22);\n const majority = ((a ?? 0) & (b ?? 0)) ^ ((a ?? 0) & (c ?? 0)) ^ ((b ?? 0) & (c ?? 0));\n // Uint32Array stores modulo 2^32, which is the algorithm's addition.\n working.set([\n t1 + s0 + majority,\n a ?? 0,\n b ?? 0,\n c ?? 0,\n (d ?? 0) + t1,\n e ?? 0,\n f ?? 0,\n g ?? 0,\n ]);\n }\n for (let index = 0; index < 8; index += 1) {\n hash[index] = at(hash, index) + at(working, index);\n }\n }\n return Array.from(hash, (word) => word.toString(16).padStart(8, \"0\")).join(\"\");\n};\n","import * as Order from \"effect/Order\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\n\nimport { TokenConsumptionState } from \"../domain/model-usage\";\nimport { sha256Hex } from \"./hash\";\nimport { JsonUserMessageContent } from \"../domain/reduced-state-schema\";\nimport { CommandIdempotencyKey, SubmitMessageDisposition } from \"../types/commands\";\nimport {\n CommandId,\n CompactionId,\n ContextVersion,\n EventId,\n InferenceId,\n MessageId,\n RunId,\n SequenceNumber,\n SummaryId,\n ToolCallId,\n TurnId,\n} from \"../types/core\";\nimport {\n FailurePayload,\n ModelSelectionPayload,\n NonNegativeInt,\n ProviderPartId,\n ToolName,\n UnixEpochMillis,\n UsagePayload,\n} from \"../types/events/envelope\";\nimport { ToolCallRejectionReason } from \"../types/events/durable\";\n\n// ---------------------------------------------------------------------------------------------\n// Identity\n// ---------------------------------------------------------------------------------------------\n\n/** One logical user submission across every lifecycle state: `user:<commandId>`. */\nexport const UserRecordId = Schema.TemplateLiteral([\"user:\", CommandId]);\nexport type UserRecordId = typeof UserRecordId.Type;\n\n/** One model inference's visible output: `assistant:<inferenceId>`. */\nexport const InferenceAssistantRecordId = Schema.TemplateLiteral([\"assistant:\", InferenceId]);\nexport type InferenceAssistantRecordId = typeof InferenceAssistantRecordId.Type;\n\n/** Assistant context imported from another transport, keyed by its import event: `import:<eventId>`. */\nexport const ImportAssistantRecordId = Schema.TemplateLiteral([\"import:\", EventId]);\nexport type ImportAssistantRecordId = typeof ImportAssistantRecordId.Type;\n\n/** Either assistant identity; both are top-level assistant records. */\nexport const AssistantRecordId = Schema.Union([\n InferenceAssistantRecordId,\n ImportAssistantRecordId,\n]);\nexport type AssistantRecordId = typeof AssistantRecordId.Type;\n\n/** The marker a context rebase leaves in history: `compaction:<compactionId>`. */\nexport const CompactionRecordId = Schema.TemplateLiteral([\"compaction:\", CompactionId]);\nexport type CompactionRecordId = typeof CompactionRecordId.Type;\n\n/** A framework tool call, a dependency of its assistant: `tool:<toolCallId>`. */\nexport const ToolRecordId = Schema.TemplateLiteral([\"tool:\", ToolCallId]);\nexport type ToolRecordId = typeof ToolRecordId.Type;\n\n/**\n * A run plus every startup-recovery continuation of it: `run:<rootRunId>`.\n *\n * The id names the first run of the chain and never changes when a continuation joins.\n */\nexport const RunGroupRecordId = Schema.TemplateLiteral([\"run:\", RunId]);\nexport type RunGroupRecordId = typeof RunGroupRecordId.Type;\n\n/** The session-context singleton. */\nexport const SessionContextRecordId = Schema.Literal(\"session\");\nexport type SessionContextRecordId = typeof SessionContextRecordId.Type;\n\n/**\n * Internal holding record for decorations whose target user record does not exist yet.\n *\n * Hosts append decoration events before the command they describe (Gia submits\n * `[author, attachments…, SubmitMessage]` in one batch), so the interpreter parks them under the\n * association key and merges them when the user record is created. Never served by a window read.\n */\nexport const DecorationBufferRecordId = Schema.TemplateLiteral([\n \"decorations:\",\n Schema.Literals([\"command\", \"idempotencyKey\"]),\n \":\",\n Schema.NonEmptyString.check(Schema.isMaxLength(512)),\n]);\nexport type DecorationBufferRecordId = typeof DecorationBufferRecordId.Type;\n\n/** Every transcript record identity this EDA release writes. */\nexport const TranscriptRecordId = Schema.Union([\n UserRecordId,\n AssistantRecordId,\n CompactionRecordId,\n ToolRecordId,\n RunGroupRecordId,\n SessionContextRecordId,\n DecorationBufferRecordId,\n]);\nexport type TranscriptRecordId = typeof TranscriptRecordId.Type;\n\n/** Constructors for record identities; the only place identities are spelled. */\nexport const transcriptRecordId = {\n user: (commandId: CommandId): UserRecordId => `user:${commandId}`,\n assistant: (inferenceId: InferenceId): InferenceAssistantRecordId => `assistant:${inferenceId}`,\n import: (eventId: EventId): ImportAssistantRecordId => `import:${eventId}`,\n compaction: (compactionId: CompactionId): CompactionRecordId => `compaction:${compactionId}`,\n tool: (toolCallId: ToolCallId): ToolRecordId => `tool:${toolCallId}`,\n runGroup: (rootRunId: RunId): RunGroupRecordId => `run:${rootRunId}`,\n session: \"session\",\n /**\n * Keys longer than 256 characters (caller-owned idempotency keys) are hashed to stay bounded;\n * keys starting with `#` are hashed too, so a literal key never collides with a hashed one.\n */\n decorationBuffer: (\n association: \"command\" | \"idempotencyKey\",\n key: string,\n ): DecorationBufferRecordId =>\n `decorations:${association}:${\n key.length > 0 && key.length <= 256 && !key.startsWith(\"#\")\n ? key\n : `#sha256:${sha256Hex(key)}`\n }`,\n} as const;\n\n// ---------------------------------------------------------------------------------------------\n// Position and cursor\n// ---------------------------------------------------------------------------------------------\n\n/**\n * History position of a top-level record: the event that placed it and an ordinal among records\n * placed by that same event. Assigned once and never moved.\n */\nexport const TranscriptPosition = Schema.Struct({\n anchorSeq: SequenceNumber,\n ordinal: NonNegativeInt,\n});\nexport type TranscriptPosition = typeof TranscriptPosition.Type;\n\n/**\n * Adapter-owned identity of one physical event log. A wiped log gets a new incarnation, which\n * invalidates every cursor, chunk and body reference minted against the old one.\n */\nexport const TranscriptLogIncarnation = Schema.NonEmptyString.pipe(\n Schema.brand(\"TranscriptLogIncarnation\"),\n);\nexport type TranscriptLogIncarnation = typeof TranscriptLogIncarnation.Type;\n\n/**\n * Identity of one transcript interpretation: a hash of the EDA semantic revision and the host's\n * canonical mapping data. Two sessions with equal versions interpret the same log identically.\n */\nexport const TranscriptVersion = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/)).pipe(\n Schema.brand(\"TranscriptVersion\"),\n);\nexport type TranscriptVersion = typeof TranscriptVersion.Type;\n\n/**\n * Paging cursor: a point in the total order `(anchorSeq, ordinal, recordId)`.\n *\n * A cursor is meaningful only for the incarnation and version that minted it; readers reject\n * any other pairing rather than guess an equivalent point.\n */\nexport const TranscriptCursor = Schema.Struct({\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n anchorSeq: SequenceNumber,\n ordinal: NonNegativeInt,\n recordId: Schema.NonEmptyString,\n});\nexport type TranscriptCursor = typeof TranscriptCursor.Type;\n\n/** A point in transcript order, without the incarnation and version scope of a cursor. */\nexport interface TranscriptOrderKey {\n readonly anchorSeq: number;\n readonly ordinal: number;\n readonly recordId: string;\n}\n\n/** Total transcript order over top-level records. */\nexport const TranscriptOrder: Order.Order<TranscriptOrderKey> = Order.Struct({\n anchorSeq: Order.Number,\n ordinal: Order.Number,\n recordId: Order.String,\n});\n\n// ---------------------------------------------------------------------------------------------\n// Shared values\n// ---------------------------------------------------------------------------------------------\n\n/** A JSON path into an event payload; the empty path is the payload itself. */\nexport const TranscriptFieldPath = Schema.Array(Schema.Union([Schema.String, NonNegativeInt]));\nexport type TranscriptFieldPath = typeof TranscriptFieldPath.Type;\n\n/** The immutable log location a body was read from. */\nexport const TranscriptBodySource = Schema.Struct({\n seq: SequenceNumber,\n path: TranscriptFieldPath,\n});\nexport type TranscriptBodySource = typeof TranscriptBodySource.Type;\n\n/**\n * Largest body a stored record holds inline, in canonical JSON bytes. Larger bodies are stored\n * as references, which keeps every stored row far below a Durable Object's 2 MB value limit no\n * matter how large an event payload is.\n */\nexport const transcriptStoredInlineBodyLimit = 65_536;\n\n/**\n * A potentially large body (tool parameters and results).\n *\n * Stored records hold a body inline up to `transcriptStoredInlineBodyLimit` and as a reference\n * above it; a window read may also replace a smaller inline body with a reference. A reference\n * points at the body's immutable source in the append-only log, so it stays resolvable after\n * projection rows are rebuilt or deleted. The host authorizes reference resolution.\n */\nexport const TranscriptBody = Schema.TaggedUnion({\n Inline: { value: Schema.Json, source: TranscriptBodySource },\n Ref: { source: TranscriptBodySource, byteLength: NonNegativeInt },\n});\nexport type TranscriptBody = typeof TranscriptBody.Type;\n\n/** Host-defined decoration name, as written by a mapping operation. */\nexport const TranscriptDecorationKey = Schema.String.check(\n Schema.isPattern(/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/),\n);\nexport type TranscriptDecorationKey = typeof TranscriptDecorationKey.Type;\n\n/** Key of one decoration list entry: an entry id or a host-assigned ordinal. */\nexport const TranscriptDecorationEntryKey = Schema.Union([\n Schema.String.check(Schema.isMaxLength(256)),\n NonNegativeInt,\n]);\nexport type TranscriptDecorationEntryKey = typeof TranscriptDecorationEntryKey.Type;\n\n/**\n * A host decoration value: a JSON scalar/object, or a keyed list whose entries are replaced by id\n * or ordinal. EDA treats the JSON as opaque; only the host gives it meaning.\n */\nexport const TranscriptDecoration = Schema.TaggedUnion({\n Value: { value: Schema.Json },\n List: {\n entries: Schema.Array(Schema.Struct({ key: TranscriptDecorationEntryKey, value: Schema.Json })),\n },\n});\nexport type TranscriptDecoration = typeof TranscriptDecoration.Type;\n\n/** Decorations of one record, keyed by host decoration name. */\nexport const TranscriptDecorations = Schema.Record(TranscriptDecorationKey, TranscriptDecoration);\nexport type TranscriptDecorations = typeof TranscriptDecorations.Type;\n\n/** Host classification of a user record, such as an authenticated subagent notice. */\nexport const TranscriptClassification = TranscriptDecorationKey;\nexport type TranscriptClassification = typeof TranscriptClassification.Type;\n\nconst LifecycleTimingFields = {\n startedAtMs: Schema.optionalKey(UnixEpochMillis),\n terminalAtMs: Schema.optionalKey(UnixEpochMillis),\n durationMs: Schema.optionalKey(NonNegativeInt),\n};\n\n// ---------------------------------------------------------------------------------------------\n// Record bodies\n// ---------------------------------------------------------------------------------------------\n\n/**\n * Where a user submission is in its lifecycle.\n *\n * Only `Consumed` records are rendered in history. `Pending`, `Paused`, `Promoted` and `Steering`\n * are waiting to be read by the agent and are served as dependencies. `Cancelled` records stay\n * stored so their aliases resolve but are never rendered.\n */\nexport const TranscriptUserState = Schema.TaggedUnion({\n /** Admitted and queued for a later run. */\n Pending: {},\n /** Queued, but held because the user interrupted the run that would have read it. */\n Paused: { byCommandId: CommandId },\n /** Moved from the queue to steer the active run. */\n Promoted: {},\n /** Waiting to steer the active run. */\n Steering: {},\n /** Read by the agent; the record's position is the consumption point. */\n Consumed: {\n turnId: Schema.optionalKey(TurnId),\n runId: Schema.optionalKey(RunId),\n },\n /** Withdrawn before the agent read it, or withdrawn from the model context. */\n Cancelled: {\n reason: Schema.String,\n byCommandId: Schema.optionalKey(CommandId),\n },\n});\nexport type TranscriptUserState = typeof TranscriptUserState.Type;\n\nconst UserBodyFields = {\n commandId: CommandId,\n /** Every message id that has carried this submission; a replacement id joins as an alias. */\n messageIds: Schema.Array(MessageId),\n idempotencyKey: Schema.optionalKey(CommandIdempotencyKey),\n disposition: Schema.optionalKey(SubmitMessageDisposition),\n /**\n * JSON projection of the content: file bytes become data URLs, URLs become strings. Content is\n * inline; file data belongs in host attachments rather than message content.\n */\n content: JsonUserMessageContent,\n state: TranscriptUserState,\n /** Present when the submission arrived as steering for a specific run. */\n steering: Schema.optionalKey(Schema.Struct({ runId: RunId })),\n classification: Schema.optionalKey(TranscriptClassification),\n decorations: TranscriptDecorations,\n /** The first event that named this submission; pending users are served in this order. */\n submittedSeq: SequenceNumber,\n submittedAtMs: UnixEpochMillis,\n /** Present exactly when `position` is: the record was consumed at some point. */\n consumedAtMs: Schema.optionalKey(UnixEpochMillis),\n};\n\n/** Lifecycle of one assistant record. Imports are `Completed` from the start. */\nexport const TranscriptAssistantLifecycle = Schema.TaggedUnion({\n Streaming: {},\n Completed: {\n finishReason: Schema.optionalKey(Schema.String),\n usage: Schema.optionalKey(UsagePayload),\n },\n Failed: { error: FailurePayload },\n});\nexport type TranscriptAssistantLifecycle = typeof TranscriptAssistantLifecycle.Type;\n\n/**\n * One ordered part of assistant output. Tool calls are references; their bodies live on the tool\n * dependency. Part types this release does not render are kept as `Unknown` so ordering survives.\n */\nconst KnownAssistantPart = Schema.TaggedUnion({\n Text: { text: Schema.String },\n Reasoning: { text: Schema.String },\n ToolCall: {\n providerPartId: ProviderPartId,\n toolName: ToolName,\n providerExecuted: Schema.Boolean,\n /** The framework tool record, once the call has been sealed into one. */\n toolId: Schema.optionalKey(ToolRecordId),\n },\n /** Result of a provider-executed tool, which has no framework tool record. */\n ToolResult: {\n providerPartId: ProviderPartId,\n toolName: ToolName,\n isFailure: Schema.Boolean,\n result: TranscriptBody,\n },\n Unknown: { partType: Schema.String },\n});\n\n/** A part whose tag or shape this reader does not know keeps its place as `Unknown`. */\nconst knownAssistantPartTags: ReadonlySet<string> = new Set([\n \"Text\",\n \"Reasoning\",\n \"ToolCall\",\n \"ToolResult\",\n \"Unknown\",\n]);\n\nconst UnrecognizedAssistantPart = Schema.Struct({\n _tag: Schema.String.check(\n Schema.makeFilter(\n (tag) => !knownAssistantPartTags.has(tag) || \"a known part tag must decode as that part\",\n ),\n ),\n}).pipe(\n Schema.decodeTo(Schema.toType(KnownAssistantPart.cases.Unknown), {\n decode: SchemaGetter.transform((part) => ({ _tag: \"Unknown\" as const, partType: part._tag })),\n encode: SchemaGetter.transform((part) => ({ _tag: part.partType })),\n }),\n);\n\n/**\n * One ordered part of assistant output. A part tag this reader does not know decodes as\n * `Unknown`, keeping its place; a malformed part with a known tag is a decode failure.\n */\nexport const TranscriptAssistantPart = Schema.Union([\n KnownAssistantPart,\n UnrecognizedAssistantPart,\n]);\nexport type TranscriptAssistantPart = typeof TranscriptAssistantPart.Type;\n\nconst AssistantBodyFields = {\n source: Schema.Literals([\"inference\", \"import\"]),\n inferenceId: InferenceId,\n runId: RunId,\n turnId: TurnId,\n /** Run group of the producing run; absent for imports and for runs the log never started. */\n runGroupId: Schema.optionalKey(RunGroupRecordId),\n messageId: Schema.optionalKey(MessageId),\n lifecycle: TranscriptAssistantLifecycle,\n parts: Schema.Array(TranscriptAssistantPart),\n /** Present when the visible parts were preserved from an interrupted or failed inference. */\n partial: Schema.optionalKey(Schema.Struct({ reason: Schema.String })),\n ...LifecycleTimingFields,\n};\n\nconst CompactionBodyFields = {\n compactionId: CompactionId,\n /** Reference to the summary artifact; the transcript never copies summary text. */\n summaryId: SummaryId,\n contextVersion: ContextVersion,\n retainedFromContextSeq: SequenceNumber,\n createdAtMs: UnixEpochMillis,\n /** Set by the first `CompactionCompleted`; later completions add no token usage. */\n completedAtMs: Schema.optionalKey(UnixEpochMillis),\n};\n\n/** Lifecycle of one framework tool call. The last terminal event wins. */\nexport const TranscriptToolLifecycle = Schema.TaggedUnion({\n Created: {},\n Running: {},\n Completed: { result: TranscriptBody },\n Failed: { error: FailurePayload },\n /** The call was not executable; terminal from creation. */\n Rejected: {\n reason: ToolCallRejectionReason,\n message: Schema.String,\n modelFeedback: Schema.String,\n },\n});\nexport type TranscriptToolLifecycle = typeof TranscriptToolLifecycle.Type;\n\nconst ToolBodyFields = {\n toolCallId: ToolCallId,\n assistantId: InferenceAssistantRecordId,\n providerPartId: ProviderPartId,\n toolName: ToolName,\n providerExecuted: Schema.Boolean,\n /** Absent for a rejected call: a rejection records only the model-facing feedback. */\n params: Schema.optionalKey(TranscriptBody),\n lifecycle: TranscriptToolLifecycle,\n createdAtMs: UnixEpochMillis,\n ...LifecycleTimingFields,\n};\n\n/** Outcome of one run inside a run group. */\nexport const TranscriptRunOutcome = Schema.TaggedUnion({\n Running: {},\n Completed: {},\n Failed: { error: FailurePayload },\n /** Stopped by the user or by a runtime restart; a continuation may follow. */\n Interrupted: { reason: Schema.String },\n});\nexport type TranscriptRunOutcome = typeof TranscriptRunOutcome.Type;\n\n/** One run in a run group, in start order. */\nexport const TranscriptRunMember = Schema.Struct({\n runId: RunId,\n commandIds: Schema.Array(CommandId),\n modelSelection: ModelSelectionPayload,\n outcome: TranscriptRunOutcome,\n /** The interrupted run this one continues, as recorded by startup recovery. */\n continuationOf: Schema.optionalKey(RunId),\n ...LifecycleTimingFields,\n});\nexport type TranscriptRunMember = typeof TranscriptRunMember.Type;\n\nconst RunGroupBodyFields = {\n rootRunId: RunId,\n /** Every run of the chain in start order; the last member's outcome is the group's status. */\n runs: Schema.NonEmptyArray(TranscriptRunMember),\n};\n\nconst SessionContextBodyFields = {\n /** The run currently executing, if any. */\n activeRunId: Schema.optionalKey(RunId),\n /** The compaction currently in progress, if any. */\n activeCompactionId: Schema.optionalKey(CompactionId),\n /** Session execution policy: the first configured or started model, as the runtime reads it. */\n modelSelection: Schema.optionalKey(ModelSelectionPayload),\n /** Model of the most recently started run. */\n lastRunModelSelection: Schema.optionalKey(ModelSelectionPayload),\n tokenUsage: TokenConsumptionState,\n decorations: TranscriptDecorations,\n};\n\n/** One decoration operation parked until its target exists, in arrival order. */\nexport const TranscriptBufferedDecoration = Schema.Struct({\n seq: SequenceNumber,\n mapping: TranscriptDecorationKey,\n /** Operation index within the mapping. */\n operation: NonNegativeInt,\n value: Schema.Json,\n entryKey: Schema.optionalKey(TranscriptDecorationEntryKey),\n});\nexport type TranscriptBufferedDecoration = typeof TranscriptBufferedDecoration.Type;\n\n/**\n * Operations one decoration buffer keeps. Later operations for the same key are dropped, as are\n * operations beyond the mapping bounds' decoration byte budget.\n */\nexport const transcriptDecorationBufferLimit = 32;\n\nconst DecorationBufferBodyFields = {\n operations: Schema.Array(TranscriptBufferedDecoration).check(\n Schema.isMaxLength(transcriptDecorationBufferLimit),\n ),\n};\n\n// ---------------------------------------------------------------------------------------------\n// Records\n// ---------------------------------------------------------------------------------------------\n\nconst commonFields = <Kind extends string, Id extends Schema.Top>(kind: Kind, id: Id) => ({\n kind: Schema.tag(kind),\n id,\n /** The last event that contributed to this record. */\n updatedSeq: SequenceNumber,\n});\n\n/**\n * User submission, top-level once consumed; waiting states are dependencies.\n *\n * A position is assigned once, when the agent first reads the submission, so a consumed record\n * always has one and a waiting record never does. A cancelled record keeps the position it was\n * consumed at, if any, and is never rendered.\n */\nexport const TranscriptUserRecord = Schema.Struct({\n ...commonFields(\"user\", UserRecordId),\n position: Schema.optionalKey(TranscriptPosition),\n ...UserBodyFields,\n}).check(\n Schema.makeFilter(\n (user) =>\n (user.position === undefined) === (user.consumedAtMs === undefined) ||\n \"position and consumedAtMs are assigned together\",\n ),\n Schema.makeFilter(\n (user) => user.id === `user:${user.commandId}` || \"a user record id names its command\",\n ),\n Schema.makeFilter((user) => {\n switch (user.state._tag) {\n case \"Consumed\":\n return user.position !== undefined || \"a consumed user record has a position\";\n case \"Cancelled\":\n return true;\n default:\n return user.position === undefined || \"a waiting user record has no position\";\n }\n }),\n);\nexport type TranscriptUserRecord = typeof TranscriptUserRecord.Type;\n\n/** Assistant output of one inference or one import; top-level. */\nexport const TranscriptAssistantRecord = Schema.Struct({\n ...commonFields(\"assistant\", AssistantRecordId),\n position: TranscriptPosition,\n ...AssistantBodyFields,\n}).check(\n Schema.makeFilter(\n (assistant) =>\n (assistant.source === \"import\"\n ? assistant.id.startsWith(\"import:\")\n : assistant.id === `assistant:${assistant.inferenceId}`) ||\n \"an assistant record id matches its source and inference\",\n ),\n);\nexport type TranscriptAssistantRecord = typeof TranscriptAssistantRecord.Type;\n\n/** Compaction marker; top-level. */\nexport const TranscriptCompactionRecord = Schema.Struct({\n ...commonFields(\"compaction\", CompactionRecordId),\n position: TranscriptPosition,\n ...CompactionBodyFields,\n}).check(\n Schema.makeFilter(\n (compaction) =>\n compaction.id === `compaction:${compaction.compactionId}` ||\n \"a compaction record id names its compaction\",\n ),\n);\nexport type TranscriptCompactionRecord = typeof TranscriptCompactionRecord.Type;\n\n/** Framework tool call; a dependency of its assistant record. */\nexport const TranscriptToolRecord = Schema.Struct({\n ...commonFields(\"tool\", ToolRecordId),\n ...ToolBodyFields,\n}).check(\n Schema.makeFilter(\n (tool) => tool.id === `tool:${tool.toolCallId}` || \"a tool record id names its tool call\",\n ),\n);\nexport type TranscriptToolRecord = typeof TranscriptToolRecord.Type;\n\n/** Run and its recovery continuations; a dependency of the records it produced. */\nexport const TranscriptRunGroupRecord = Schema.Struct({\n ...commonFields(\"runGroup\", RunGroupRecordId),\n ...RunGroupBodyFields,\n}).check(\n Schema.makeFilter(\n (group) =>\n (group.id === `run:${group.rootRunId}` && group.runs[0].runId === group.rootRunId) ||\n \"a run group is named by, and starts with, its root run\",\n ),\n);\nexport type TranscriptRunGroupRecord = typeof TranscriptRunGroupRecord.Type;\n\n/** A run group's status: the outcome of its latest run. */\nexport const runGroupStatus = (group: TranscriptRunGroupRecord): TranscriptRunOutcome =>\n (group.runs[group.runs.length - 1] ?? group.runs[0]).outcome;\n\n/** Session activity, model selection and token totals; a singleton dependency. */\nexport const TranscriptSessionContextRecord = Schema.Struct({\n ...commonFields(\"sessionContext\", SessionContextRecordId),\n ...SessionContextBodyFields,\n});\nexport type TranscriptSessionContextRecord = typeof TranscriptSessionContextRecord.Type;\n\n/** Internal decoration holding record; stored, never served. */\nexport const TranscriptDecorationBufferRecord = Schema.Struct({\n ...commonFields(\"decorationBuffer\", DecorationBufferRecordId),\n ...DecorationBufferBodyFields,\n});\nexport type TranscriptDecorationBufferRecord = typeof TranscriptDecorationBufferRecord.Type;\n\n/** Every record kind this EDA release stores. */\nexport const TranscriptRecord = Schema.Union([\n TranscriptUserRecord,\n TranscriptAssistantRecord,\n TranscriptCompactionRecord,\n TranscriptToolRecord,\n TranscriptRunGroupRecord,\n TranscriptSessionContextRecord,\n TranscriptDecorationBufferRecord,\n]);\nexport type TranscriptRecord = typeof TranscriptRecord.Type;\nexport type TranscriptRecordKind = TranscriptRecord[\"kind\"];\n\n/**\n * A record this reader cannot interpret: a newer kind, or a body written by a newer EDA.\n *\n * It keeps the identity, position and revision so a client can hold its place and render a safe\n * placeholder. Storage readers do not produce it: an undecodable stored row makes a read\n * unavailable instead of wrong.\n */\nexport const TranscriptUnknownRecord = Schema.Struct({\n kind: Schema.tag(\"unknown\"),\n originalKind: Schema.NonEmptyString,\n /** The envelope format it arrived in, kept so it re-encodes exactly as it was read. */\n format: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n /** The uninterpreted body, kept so a relaying reader forwards it unchanged. */\n body: Schema.Record(Schema.String, Schema.Unknown),\n id: Schema.NonEmptyString,\n updatedSeq: SequenceNumber,\n position: Schema.optionalKey(TranscriptPosition),\n});\nexport type TranscriptUnknownRecord = typeof TranscriptUnknownRecord.Type;\n\n/** What a wire reader sees for one record. */\nexport type TranscriptRecordView = TranscriptRecord | TranscriptUnknownRecord;\n\n/** A user record the agent has read: positioned history. */\nexport type ConsumedTranscriptUserRecord = TranscriptUserRecord & {\n readonly state: Extract<TranscriptUserState, { readonly _tag: \"Consumed\" }>;\n readonly position: TranscriptPosition;\n};\n\n/** A user record still waiting for the agent. */\nexport type PendingTranscriptUserRecord = TranscriptUserRecord & {\n readonly state: Extract<\n TranscriptUserState,\n { readonly _tag: \"Pending\" | \"Paused\" | \"Promoted\" | \"Steering\" }\n >;\n};\n\n/** A positioned record that counts toward a window's record limit. */\nexport type TranscriptTopLevelRecord =\n | ConsumedTranscriptUserRecord\n | TranscriptAssistantRecord\n | TranscriptCompactionRecord;\n\n/** Top-level kinds count toward a window's record limit and carry a position. */\nexport const isTopLevelTranscriptRecord = (\n record: TranscriptRecord,\n): record is TranscriptTopLevelRecord =>\n record.kind === \"assistant\" ||\n record.kind === \"compaction\" ||\n (record.kind === \"user\" && record.state._tag === \"Consumed\" && record.position !== undefined);\n\n/** A user record still waiting for the agent; served as a dependency, never twice. */\nexport const isPendingTranscriptUserRecord = (\n record: TranscriptRecord,\n): record is PendingTranscriptUserRecord =>\n record.kind === \"user\" &&\n (record.state._tag === \"Pending\" ||\n record.state._tag === \"Paused\" ||\n record.state._tag === \"Promoted\" ||\n record.state._tag === \"Steering\");\n\n// ---------------------------------------------------------------------------------------------\n// Stored envelope\n// ---------------------------------------------------------------------------------------------\n\n/**\n * Current stored-row envelope format. Readers accept every format up to this one.\n *\n * Bump it whenever a known kind gains a value an older reader of this format could not decode\n * (a new lifecycle or state tag, a new required field). Older readers then show such rows as\n * `unknown` records; without a bump, a strict older reader would reject the whole window.\n */\nexport const transcriptRecordEnvelopeFormat = 1;\n\n/**\n * Backward-readable row and wire shape for one record.\n *\n * Identity, kind, revision and position sit outside the kind-specific `body` so any reader can\n * place a record it cannot interpret.\n */\nexport const TranscriptRecordEnvelope = Schema.Struct({\n format: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n kind: Schema.NonEmptyString,\n id: Schema.NonEmptyString,\n updatedSeq: SequenceNumber,\n position: Schema.optionalKey(TranscriptPosition),\n body: Schema.Record(Schema.String, Schema.Unknown),\n});\nexport type TranscriptRecordEnvelope = typeof TranscriptRecordEnvelope.Type;\n\nconst envelopeToFlat = (envelope: TranscriptRecordEnvelope): Record<string, unknown> => {\n const { kind, id, updatedSeq, position, body } = envelope;\n // Identity, revision and position come only from the envelope, never from the body.\n const { kind: _kind, id: _id, updatedSeq: _updatedSeq, position: _position, ...fields } = body;\n return {\n ...fields,\n kind,\n id,\n updatedSeq,\n ...(position === undefined ? {} : { position }),\n };\n};\n\nconst flatToEnvelope = (record: Record<string, unknown>): TranscriptRecordEnvelope => {\n const { kind, id, updatedSeq, position, ...body } = record;\n return Schema.decodeUnknownSync(TranscriptRecordEnvelope)({\n format: transcriptRecordEnvelopeFormat,\n kind,\n id,\n updatedSeq,\n ...(position === undefined ? {} : { position }),\n body,\n });\n};\n\nconst FlatRecordFields = Schema.Record(Schema.String, Schema.Unknown);\n\n/** A known record stored or sent as its envelope. Decoding fails for anything this reader cannot interpret. */\nexport const TranscriptRecordFromEnvelope = TranscriptRecordEnvelope.check(\n Schema.makeFilter(\n (envelope) =>\n envelope.format <= transcriptRecordEnvelopeFormat ||\n `unsupported transcript record envelope format ${envelope.format}`,\n ),\n).pipe(\n Schema.decodeTo(FlatRecordFields, {\n decode: SchemaGetter.transform(envelopeToFlat),\n encode: SchemaGetter.transform(flatToEnvelope),\n }),\n Schema.decodeTo(TranscriptRecord, SchemaTransformation.passthroughSupertype()),\n);\n\nconst knownRecordKinds: ReadonlySet<string> = new Set([\n \"user\",\n \"assistant\",\n \"compaction\",\n \"tool\",\n \"runGroup\",\n \"sessionContext\",\n \"decorationBuffer\",\n]);\n\n/**\n * Only a kind this reader does not know, or a newer envelope format, becomes `unknown`; a\n * malformed record of a known kind in a known format is a decode failure, never a placeholder.\n */\nconst TranscriptUnknownRecordFromEnvelope = TranscriptRecordEnvelope.check(\n Schema.makeFilter(\n (envelope) =>\n !knownRecordKinds.has(envelope.kind) ||\n envelope.format > transcriptRecordEnvelopeFormat ||\n `a ${envelope.kind} record in format ${envelope.format} must decode as that kind`,\n ),\n).pipe(\n Schema.decodeTo(TranscriptUnknownRecord, {\n decode: SchemaGetter.transform((envelope) => ({\n kind: \"unknown\" as const,\n originalKind: envelope.kind,\n format: envelope.format,\n body: envelope.body,\n id: envelope.id,\n updatedSeq: envelope.updatedSeq,\n ...(envelope.position === undefined ? {} : { position: envelope.position }),\n })),\n // Every field was validated on the unknown record itself, so this decode cannot fail.\n encode: SchemaGetter.transform((record) =>\n Schema.decodeUnknownSync(TranscriptRecordEnvelope)({\n format: record.format,\n kind: record.originalKind,\n id: record.id,\n updatedSeq: record.updatedSeq,\n ...(record.position === undefined ? {} : { position: record.position }),\n body: record.body,\n }),\n ),\n }),\n);\n\n/**\n * Wire codec for one record: a known record when this reader can interpret it, otherwise an\n * explicit unknown record that keeps its id and position.\n */\nexport const TranscriptRecordViewFromEnvelope = Schema.Union([\n TranscriptRecordFromEnvelope,\n TranscriptUnknownRecordFromEnvelope,\n]);\n","import { sha256Hex } from \"./hash\";\nimport { TranscriptVersion } from \"./records\";\n\n/**\n * EDA's transcript semantic revision.\n *\n * Bump it deliberately whenever the interpreter, the legacy-attempt normalizer, the record\n * decoders or the mapping executor would interpret any existing log differently. A bump changes\n * every transcript version, so every session rebuilds and every host must run its backfill.\n * A new durable event type needs a bump only if this release gives it transcript meaning;\n * events the interpreter ignores leave the revision and every version unchanged.\n *\n * A CI fingerprint over a fixed scenario corpus (added with the interpreter) fails when\n * interpretation output changes and this constant does not; re-record it together with the bump.\n */\nexport const transcriptSemanticRevision = 1;\n\n/**\n * Deterministic JSON: object keys sorted by code unit, no whitespace. Only JSON values are\n * accepted, so equal data always produces equal bytes.\n */\nexport const canonicalJson = (value: unknown): string => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new Error(`canonicalJson cannot encode non-finite number ${value}`);\n }\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJson).join(\",\")}]`;\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value).filter(([, entry]) => entry !== undefined);\n entries.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(\",\")}}`;\n }\n throw new Error(`canonicalJson cannot encode ${typeof value}`);\n};\n\n/** Transcript version for a semantic revision and already-encoded canonical mapping data. */\nexport const computeTranscriptVersion = (\n semanticRevision: number,\n encodedMappings: unknown,\n): TranscriptVersion =>\n TranscriptVersion.make(sha256Hex(canonicalJson({ semanticRevision, mappings: encodedMappings })));\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { effectDurableAgentNamespace, SchemaVersion } from \"../types/events/envelope\";\nimport {\n TranscriptClassification,\n TranscriptDecorationKey,\n TranscriptFieldPath,\n type TranscriptVersion,\n} from \"./records\";\nimport { computeTranscriptVersion, transcriptSemanticRevision } from \"./version\";\n\n/**\n * Host decorations are data, not code. A host registers mappings from its own durable app events\n * to decorations on transcript records; EDA validates them at registration and executes them\n * with fixed bounds inside the projection.\n */\n\n/** Bounds EDA enforces on every definition and every decoration it executes. */\nexport const transcriptMappingBounds = {\n maxMappings: 64,\n maxOperationsPerMapping: 16,\n maxPathLength: 16,\n /** Canonical JSON bytes of one decoration value or list entry. */\n maxValueBytes: 8_192,\n /**\n * Canonical JSON bytes of all decorations of one record, and of one decoration buffer. An\n * operation that would exceed it is skipped, so no record's row can approach storage value\n * limits whatever a host appends.\n */\n maxDecorationBytes: 262_144,\n /** Entries kept in one decoration list; further distinct entries are dropped. */\n maxListEntries: 64,\n maxUserFallbacks: 16,\n} as const;\n\nconst MappingPath = TranscriptFieldPath.check(\n Schema.isMaxLength(transcriptMappingBounds.maxPathLength),\n);\n\n/** The app event a mapping reads: one host namespace, type and schema version. */\nexport const TranscriptMappedEvent = Schema.Struct({\n namespace: Schema.NonEmptyString,\n type: Schema.NonEmptyString,\n schemaVersion: SchemaVersion,\n});\nexport type TranscriptMappedEvent = typeof TranscriptMappedEvent.Type;\n\n/**\n * Which record a mapping decorates.\n *\n * User targets associate through a payload field: the submitting command's id, or the\n * command's idempotency key. A decoration that arrives before its target user record is held\n * and applied, in arrival order, when the record is created. `Session` decorates the\n * session-context singleton.\n */\nexport const TranscriptMappingTarget = Schema.TaggedUnion({\n UserByCommandId: { path: MappingPath },\n UserByIdempotencyKey: { path: MappingPath },\n Session: {},\n});\nexport type TranscriptMappingTarget = typeof TranscriptMappingTarget.Type;\n\n/** How a list entry is identified when it is replaced. */\nexport const TranscriptListEntryKey = Schema.TaggedUnion({\n /** A string id at this payload path (for example an attachment id). */\n Id: { path: MappingPath },\n /** A non-negative integer ordinal at this payload path; the list is kept in ordinal order. */\n Ordinal: { path: MappingPath },\n});\nexport type TranscriptListEntryKey = typeof TranscriptListEntryKey.Type;\n\n/** One declarative decoration operation. Every `from` path reads the authenticated event payload. */\nexport const TranscriptMappingOperation = Schema.TaggedUnion({\n /** Copy a payload value into a decoration; the latest event wins. */\n Copy: { from: MappingPath, to: TranscriptDecorationKey },\n /** Copy a payload value into a decoration only if the decoration is still absent. */\n FirstWins: { from: MappingPath, to: TranscriptDecorationKey },\n /** Insert or replace one entry of a decoration list, keyed by id or by ordinal. */\n ReplaceListEntry: {\n from: MappingPath,\n to: TranscriptDecorationKey,\n key: TranscriptListEntryKey,\n },\n /**\n * Classify the target user record, for example as an authenticated subagent notice. A record\n * holds one classification; the last one applied wins.\n */\n Classify: { classification: TranscriptClassification },\n});\nexport type TranscriptMappingOperation = typeof TranscriptMappingOperation.Type;\n\n/** One host mapping: an app event, the record it decorates, and the operations to apply. */\nexport const TranscriptMapping = Schema.Struct({\n /** Unique name; buffered decorations refer to it. */\n name: TranscriptDecorationKey,\n event: TranscriptMappedEvent,\n target: TranscriptMappingTarget,\n operations: Schema.NonEmptyArray(TranscriptMappingOperation).check(\n Schema.isMaxLength(transcriptMappingBounds.maxOperationsPerMapping),\n ),\n});\nexport type TranscriptMapping = typeof TranscriptMapping.Type;\n\n/**\n * A user decoration copied from a session decoration when the user record is created without\n * it, for example \"the most recent author\" for a message whose command carried no author event.\n *\n * Fallbacks apply in declaration order, after any parked decorations, and each one applies only\n * if the user decoration is still absent; so `[author ← lastAuthor, author ← owner]` means \"the\n * latest author, else the session owner\".\n */\nexport const TranscriptUserFallback = Schema.Struct({\n to: TranscriptDecorationKey,\n fromSession: TranscriptDecorationKey,\n});\nexport type TranscriptUserFallback = typeof TranscriptUserFallback.Type;\n\n/** The host's complete declarative transcript mapping data. */\nexport const TranscriptMappings = Schema.Struct({\n mappings: Schema.Array(TranscriptMapping).check(\n Schema.isMaxLength(transcriptMappingBounds.maxMappings),\n ),\n userFallbacks: Schema.Array(TranscriptUserFallback).check(\n Schema.isMaxLength(transcriptMappingBounds.maxUserFallbacks),\n ),\n});\nexport type TranscriptMappings = typeof TranscriptMappings.Type;\n\n/** Mappings for a host that registers no decorations. */\nexport const emptyTranscriptMappings: TranscriptMappings = { mappings: [], userFallbacks: [] };\n\n/** Host mapping data rejected at registration. */\nexport class TranscriptDefinitionError extends Schema.TaggedError<TranscriptDefinitionError>()(\n \"TranscriptDefinitionError\",\n { message: Schema.String },\n) {}\n\n/** How a decoration key is written; one key has exactly one shape across all mappings. */\ntype DecorationShape = \"copy\" | \"first-wins\" | \"list:Id\" | \"list:Ordinal\";\n\nconst validationProblems = (mappings: TranscriptMappings): ReadonlyArray<string> => {\n const problems: Array<string> = [];\n const names = new Set<string>();\n const shapes = new Map<string, DecorationShape>();\n const sessionValueKeys = new Set<string>();\n const recordShape = (scope: \"user\" | \"session\", key: string, shape: DecorationShape) => {\n const scoped = `${scope}:${key}`;\n const existing = shapes.get(scoped);\n if (existing !== undefined && existing !== shape) {\n problems.push(`${scope} decoration \"${key}\" is written as both ${existing} and ${shape}`);\n }\n shapes.set(scoped, shape);\n };\n\n for (const mapping of mappings.mappings) {\n if (names.has(mapping.name)) problems.push(`duplicate mapping name \"${mapping.name}\"`);\n names.add(mapping.name);\n if (\n mapping.event.namespace === effectDurableAgentNamespace ||\n mapping.event.namespace === \"__foreign\"\n ) {\n problems.push(`mapping \"${mapping.name}\" may not read namespace ${mapping.event.namespace}`);\n }\n const scope = mapping.target._tag === \"Session\" ? \"session\" : \"user\";\n for (const operation of mapping.operations) {\n switch (operation._tag) {\n case \"Copy\":\n case \"FirstWins\":\n recordShape(scope, operation.to, operation._tag === \"Copy\" ? \"copy\" : \"first-wins\");\n if (scope === \"session\") sessionValueKeys.add(operation.to);\n break;\n case \"ReplaceListEntry\":\n recordShape(scope, operation.to, `list:${operation.key._tag}`);\n break;\n case \"Classify\":\n if (scope === \"session\") {\n problems.push(\n `mapping \"${mapping.name}\" classifies the session; only users can be classified`,\n );\n }\n break;\n }\n }\n }\n\n const fallbacks = new Set<string>();\n for (const fallback of mappings.userFallbacks) {\n const key = `${fallback.to}\\u0000${fallback.fromSession}`;\n if (fallbacks.has(key)) {\n problems.push(`duplicate user fallback ${fallback.to} <- ${fallback.fromSession}`);\n }\n fallbacks.add(key);\n if (!sessionValueKeys.has(fallback.fromSession)) {\n problems.push(\n `user fallback reads session decoration \"${fallback.fromSession}\", which no mapping writes as a value`,\n );\n }\n const userShape = shapes.get(`user:${fallback.to}`);\n if (userShape !== undefined && userShape.startsWith(\"list:\")) {\n problems.push(`user fallback writes \"${fallback.to}\", which is a list decoration`);\n }\n }\n return problems;\n};\n\n/**\n * A validated transcript interpretation: EDA's semantic revision plus host mappings, identified\n * by `version`. Only `makeTranscriptDefinition` constructs one.\n */\nexport class TranscriptDefinition {\n private constructor(\n readonly version: TranscriptVersion,\n readonly semanticRevision: number,\n readonly mappings: TranscriptMappings,\n ) {}\n\n /**\n * Validate host mapping data and derive its transcript version.\n *\n * Validation happens here, at registration, never during append: an accepted definition can\n * only degrade individual decorations at runtime (a missing field, an oversize value), never\n * event admission or other records.\n */\n static readonly make = Effect.fnUntraced(function* (input: unknown) {\n const mappings = yield* Schema.decodeUnknownEffect(TranscriptMappings)(input).pipe(\n Effect.mapError((error) => new TranscriptDefinitionError({ message: error.message })),\n );\n const problems = validationProblems(mappings);\n if (problems.length > 0) {\n return yield* new TranscriptDefinitionError({ message: problems.join(\"; \") });\n }\n return new TranscriptDefinition(\n computeTranscriptVersion(\n transcriptSemanticRevision,\n Schema.encodeSync(TranscriptMappings)(mappings),\n ),\n transcriptSemanticRevision,\n mappings,\n );\n });\n}\n\n/** Validate host mapping data and derive its transcript version; see `TranscriptDefinition.make`. */\nexport const makeTranscriptDefinition = TranscriptDefinition.make;\n","import * as Schema from \"effect/Schema\";\n\nimport type { SequenceNumber } from \"../types/core\";\nimport type { CommittedDurableEvent } from \"../services/session-store\";\nimport type { TranscriptDefinition } from \"./mapping\";\nimport type { TranscriptRecord, TranscriptRecordId } from \"./records\";\n\n/**\n * Secondary keys that resolve to a record through an indexed join, never an in-memory map.\n *\n * - `messageId`: every message id a user submission has carried, including replacement ids.\n * - `idempotencyKey`: a submitting command's caller-owned retry key.\n * - `runId`: every run of a run group, so continuations resolve to the root's group.\n * - `runCommand`: commands owned by a run group; a run that reuses them continues the group.\n * - `toolPart`: `<inferenceId>/<providerPartId>`, linking an assistant tool-call part to its tool.\n */\nexport const TranscriptAliasNamespace = Schema.Literals([\n \"messageId\",\n \"idempotencyKey\",\n \"runId\",\n \"runCommand\",\n \"toolPart\",\n]);\nexport type TranscriptAliasNamespace = typeof TranscriptAliasNamespace.Type;\n\n/** One alias row: `(namespace, key)` resolves to `recordId` within one version. */\nexport interface TranscriptAlias {\n readonly namespace: TranscriptAliasNamespace;\n readonly key: string;\n readonly recordId: TranscriptRecordId;\n}\n\n/**\n * Synchronous indexed reads of one transcript version, as committed before the batch.\n *\n * Adapters back this with indexed storage reads so the interpreter can run inside a synchronous\n * transaction (Cloudflare `storage.transactionSync`). Reads see no uncommitted plan; the\n * interpreter overlays its own in-batch changes.\n */\nexport interface TranscriptLookup {\n /** Last seq already projected into this version. Events at or below it are skipped. */\n readonly cursor: SequenceNumber;\n readonly record: (id: TranscriptRecordId) => TranscriptRecord | undefined;\n readonly alias: (\n namespace: TranscriptAliasNamespace,\n key: string,\n ) => TranscriptRecordId | undefined;\n /** Next free ordinal among records positioned at `anchorSeq`; 0 when none are. */\n readonly nextOrdinal: (anchorSeq: SequenceNumber) => number;\n}\n\n/**\n * Deterministic changes for one committed batch: the final state of every record the batch\n * touched, in first-touch order, the aliases it introduced, and the new cursor.\n *\n * There are no deletions. Aliases are inserts only: an alias never moves to another record.\n * Applying the plan and advancing the cursor must commit atomically with each other.\n */\nexport interface TranscriptChangePlan {\n readonly records: ReadonlyArray<TranscriptRecord>;\n readonly aliases: ReadonlyArray<TranscriptAlias>;\n readonly throughSeq: SequenceNumber;\n}\n\n/**\n * The interpretation boundary: a pure, synchronous function from a lookup, committed events and\n * a definition to a change plan.\n *\n * It throws `TranscriptProjectionError` when the stored projection is inconsistent with the log.\n * The adapter treats any throw as a recoverable projection failure of that version only.\n */\nexport type PlanTranscriptBatch = (\n lookup: TranscriptLookup,\n committed: ReadonlyArray<CommittedDurableEvent>,\n definition: TranscriptDefinition,\n) => TranscriptChangePlan;\n\n/** The stored projection cannot be advanced from the given lookup and batch. */\nexport class TranscriptProjectionError extends Schema.TaggedError<TranscriptProjectionError>()(\n \"TranscriptProjectionError\",\n { message: Schema.String },\n) {}\n","import * as Schema from \"effect/Schema\";\n\nimport { CommandIdempotencyKey } from \"../types/commands\";\nimport { CommandId, type SequenceNumber } from \"../types/core\";\nimport type { DurableEventEnvelope } from \"../types/events/envelope\";\nimport type { TranscriptBatch } from \"./interpreter\";\nimport {\n transcriptMappingBounds,\n type TranscriptDefinition,\n type TranscriptMapping,\n type TranscriptMappingOperation,\n} from \"./mapping\";\nimport { TranscriptProjectionError } from \"./plan\";\nimport {\n TranscriptDecorationEntryKey,\n transcriptDecorationBufferLimit,\n transcriptRecordId,\n type TranscriptBufferedDecoration,\n type TranscriptClassification,\n type TranscriptDecoration,\n type TranscriptDecorationBufferRecord,\n type TranscriptDecorations,\n type TranscriptFieldPath,\n type TranscriptUserRecord,\n} from \"./records\";\nimport { canonicalJson } from \"./version\";\n\n/**\n * Executes host mappings inside the projection. Every failure is local: a missing or oversize\n * value skips only that operation, and an unresolvable target skips only that mapping. Nothing\n * here can reject an event or touch a record the mapping does not target.\n */\n\ninterface MappingIndex {\n readonly byEvent: ReadonlyMap<string, ReadonlyArray<TranscriptMapping>>;\n readonly byName: ReadonlyMap<string, TranscriptMapping>;\n}\n\nconst indexes = new WeakMap<TranscriptDefinition, MappingIndex>();\n\nconst eventKey = (namespace: string, type: string, schemaVersion: number) =>\n `${namespace}\\u0000${type}\\u0000${schemaVersion}`;\n\nconst mappingIndex = (definition: TranscriptDefinition): MappingIndex => {\n const cached = indexes.get(definition);\n if (cached !== undefined) return cached;\n const byEvent = new Map<string, Array<TranscriptMapping>>();\n const byName = new Map<string, TranscriptMapping>();\n for (const mapping of definition.mappings.mappings) {\n const key = eventKey(mapping.event.namespace, mapping.event.type, mapping.event.schemaVersion);\n byEvent.set(key, [...(byEvent.get(key) ?? []), mapping]);\n byName.set(mapping.name, mapping);\n }\n const index = { byEvent, byName };\n indexes.set(definition, index);\n return index;\n};\n\n/** A validated value for one operation of one mapping, ready to apply or to park. */\ntype PreparedOperation = Omit<TranscriptBufferedDecoration, \"seq\">;\n\n/** Apply every mapping that names this app event. Unmapped events are ignored. */\nexport const applyForeignEvent = (\n batch: TranscriptBatch,\n envelope: DurableEventEnvelope,\n seq: SequenceNumber,\n): void => {\n const mappings = mappingIndex(batch.definition).byEvent.get(\n eventKey(envelope.namespace, envelope.type, envelope.schemaVersion),\n );\n for (const mapping of mappings ?? []) {\n applyMapping(batch, mapping, envelope.payload, seq);\n }\n};\n\nconst applyMapping = (\n batch: TranscriptBatch,\n mapping: TranscriptMapping,\n payload: unknown,\n seq: SequenceNumber,\n) => {\n const prepared = mapping.operations.flatMap((operation, index) =>\n prepareOperation(mapping.name, operation, index, payload),\n );\n if (prepared.length === 0) return;\n const target = mapping.target;\n switch (target._tag) {\n case \"Session\": {\n const session = batch.session(seq);\n const applied = prepared.reduce<Decorated>(\n (decorated, operation) => applyPrepared(batch.definition, decorated, operation),\n { decorations: session.decorations },\n );\n batch.put({ ...session, updatedSeq: seq, decorations: applied.decorations });\n return;\n }\n case \"UserByCommandId\": {\n const commandId = extract(payload, target.path);\n if (!Schema.is(CommandId)(commandId)) return;\n const user = batch.user(transcriptRecordId.user(commandId));\n if (user === undefined) park(batch, seq, \"command\", commandId, prepared);\n else batch.put(decorateUser(batch.definition, { ...user, updatedSeq: seq }, prepared));\n return;\n }\n case \"UserByIdempotencyKey\": {\n const key = extract(payload, target.path);\n if (!Schema.is(CommandIdempotencyKey)(key)) return;\n const userId = batch.alias(\"idempotencyKey\", key);\n const user = userId === undefined ? undefined : batch.user(userId);\n if (user === undefined) park(batch, seq, \"idempotencyKey\", key, prepared);\n else batch.put(decorateUser(batch.definition, { ...user, updatedSeq: seq }, prepared));\n return;\n }\n }\n};\n\nconst prepareOperation = (\n mapping: string,\n operation: TranscriptMappingOperation,\n index: number,\n payload: unknown,\n): ReadonlyArray<PreparedOperation> => {\n switch (operation._tag) {\n case \"Classify\":\n return [{ mapping, operation: index, value: null }];\n case \"Copy\":\n case \"FirstWins\": {\n const value = boundedJson(extract(payload, operation.from));\n return value === undefined ? [] : [{ mapping, operation: index, value }];\n }\n case \"ReplaceListEntry\": {\n const value = boundedJson(extract(payload, operation.from));\n const entryKey = listEntryKey(operation.key, payload);\n return value === undefined || entryKey === undefined\n ? []\n : [{ mapping, operation: index, value, entryKey }];\n }\n }\n};\n\nconst listEntryKey = (\n key: Extract<TranscriptMappingOperation, { readonly _tag: \"ReplaceListEntry\" }>[\"key\"],\n payload: unknown,\n): TranscriptDecorationEntryKey | undefined => {\n const value = extract(payload, key.path);\n switch (key._tag) {\n case \"Id\":\n return typeof value === \"string\" &&\n value.length > 0 &&\n Schema.is(TranscriptDecorationEntryKey)(value)\n ? value\n : undefined;\n case \"Ordinal\":\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0\n ? value\n : undefined;\n }\n};\n\nconst park = (\n batch: TranscriptBatch,\n seq: SequenceNumber,\n association: \"command\" | \"idempotencyKey\",\n key: string,\n prepared: ReadonlyArray<PreparedOperation>,\n) => {\n const id = transcriptRecordId.decorationBuffer(association, key);\n const existing = batch.get(id);\n if (existing !== undefined && existing.kind !== \"decorationBuffer\") {\n throw new TranscriptProjectionError({\n message: `record ${id} is ${existing.kind}, expected decorationBuffer`,\n });\n }\n const buffer: TranscriptDecorationBufferRecord = {\n kind: \"decorationBuffer\",\n id,\n updatedSeq: seq,\n // Bounded in count and bytes: an orphaned key (its command never arrives) cannot grow\n // without limit.\n operations: withinBudget([\n ...(existing?.operations ?? []),\n ...prepared.map((operation) => ({ ...operation, seq })),\n ]),\n };\n batch.put(buffer);\n};\n\n/**\n * Apply decorations parked for a new user record, in arrival order, then the host's user\n * fallbacks for decorations that are still absent.\n */\nexport const replayBufferedDecorations = (\n batch: TranscriptBatch,\n seq: SequenceNumber,\n user: TranscriptUserRecord,\n): TranscriptUserRecord => {\n const buffered = [\n transcriptRecordId.decorationBuffer(\"command\", user.commandId),\n ...(user.idempotencyKey === undefined\n ? []\n : [transcriptRecordId.decorationBuffer(\"idempotencyKey\", user.idempotencyKey)]),\n ].flatMap((id) => {\n const buffer = batch.get(id);\n if (buffer?.kind !== \"decorationBuffer\" || buffer.operations.length === 0) return [];\n // Drained once applied: the user record now holds these decorations.\n batch.put({ ...buffer, updatedSeq: seq, operations: [] });\n return buffer.operations;\n });\n buffered.sort((left, right) => left.seq - right.seq);\n const decorated = decorateUser(batch.definition, user, buffered);\n\n // Fallbacks describe ordinary submissions; a host-classified record (such as a subagent\n // notice) keeps only the decorations its own mappings give it.\n const session = batch.get(transcriptRecordId.session);\n if (session?.kind !== \"sessionContext\" || decorated.classification !== undefined) {\n return decorated;\n }\n let decorations = decorated.decorations;\n for (const fallback of batch.definition.mappings.userFallbacks) {\n const source = session.decorations[fallback.fromSession];\n if (decorations[fallback.to] === undefined && source?._tag === \"Value\") {\n const next = { ...decorations, [fallback.to]: source };\n if (jsonBytes(next) <= transcriptMappingBounds.maxDecorationBytes) decorations = next;\n }\n }\n return decorations === decorated.decorations\n ? decorated\n : { ...decorated, updatedSeq: seq, decorations };\n};\n\ninterface Decorated {\n readonly decorations: TranscriptDecorations;\n readonly classification?: TranscriptClassification;\n}\n\nconst decorateUser = (\n definition: TranscriptDefinition,\n user: TranscriptUserRecord,\n operations: ReadonlyArray<PreparedOperation>,\n): TranscriptUserRecord => {\n const decorated = operations.reduce<Decorated>(\n (current, operation) => applyPrepared(definition, current, operation),\n {\n decorations: user.decorations,\n ...(user.classification === undefined ? {} : { classification: user.classification }),\n },\n );\n return {\n ...user,\n decorations: decorated.decorations,\n ...(decorated.classification === undefined ? {} : { classification: decorated.classification }),\n };\n};\n\n/** The longest prefix of parked operations within the buffer's count and byte bounds. */\nconst withinBudget = (\n operations: ReadonlyArray<TranscriptBufferedDecoration>,\n): ReadonlyArray<TranscriptBufferedDecoration> => {\n const kept: Array<TranscriptBufferedDecoration> = [];\n let bytes = 2;\n for (const operation of operations.slice(0, transcriptDecorationBufferLimit)) {\n bytes += jsonBytes(operation) + 1;\n if (bytes > transcriptMappingBounds.maxDecorationBytes) break;\n kept.push(operation);\n }\n return kept;\n};\n\n/** Apply one operation unless the record's decorations would exceed their byte budget. */\nconst applyPrepared = (\n definition: TranscriptDefinition,\n target: Decorated,\n prepared: PreparedOperation,\n): Decorated => {\n const next = applyOperation(definition, target, prepared);\n return next === target ||\n jsonBytes(next.decorations) <= transcriptMappingBounds.maxDecorationBytes\n ? next\n : target;\n};\n\nconst jsonBytes = (value: unknown): number => encoder.encode(canonicalJson(value)).length;\n\nconst applyOperation = (\n definition: TranscriptDefinition,\n target: Decorated,\n prepared: PreparedOperation,\n): Decorated => {\n const operation = mappingIndex(definition).byName.get(prepared.mapping)?.operations[\n prepared.operation\n ];\n if (operation === undefined) return target;\n switch (operation._tag) {\n case \"Classify\":\n return { ...target, classification: operation.classification };\n case \"Copy\":\n return withDecoration(target, operation.to, { _tag: \"Value\", value: prepared.value });\n case \"FirstWins\":\n return target.decorations[operation.to] === undefined\n ? withDecoration(target, operation.to, { _tag: \"Value\", value: prepared.value })\n : target;\n case \"ReplaceListEntry\": {\n if (prepared.entryKey === undefined) return target;\n const list = replaceListEntry(\n target.decorations[operation.to],\n prepared.entryKey,\n prepared.value,\n operation.key._tag === \"Ordinal\",\n );\n return list === undefined ? target : withDecoration(target, operation.to, list);\n }\n }\n};\n\nconst withDecoration = (\n target: Decorated,\n key: string,\n decoration: TranscriptDecoration,\n): Decorated => ({ ...target, decorations: { ...target.decorations, [key]: decoration } });\n\nconst replaceListEntry = (\n existing: TranscriptDecoration | undefined,\n key: TranscriptDecorationEntryKey,\n value: Schema.Json,\n ordered: boolean,\n): TranscriptDecoration | undefined => {\n const entries = existing?._tag === \"List\" ? existing.entries : [];\n const index = entries.findIndex((entry) => entry.key === key);\n if (index >= 0) {\n return {\n _tag: \"List\",\n entries: entries.map((entry, position) => (position === index ? { key, value } : entry)),\n };\n }\n if (entries.length >= transcriptMappingBounds.maxListEntries) return undefined;\n const next = [...entries, { key, value }];\n if (ordered) next.sort((left, right) => Number(left.key) - Number(right.key));\n return { _tag: \"List\", entries: next };\n};\n\n/** Read a payload value by path through own properties only. */\nconst extract = (value: unknown, path: TranscriptFieldPath): unknown =>\n path.reduce<unknown>((current, key) => {\n if (typeof key === \"number\") return Array.isArray(current) ? current[key] : undefined;\n if (current === null || typeof current !== \"object\" || Array.isArray(current)) {\n return undefined;\n }\n return Object.getOwnPropertyDescriptor(current, key)?.value;\n }, value);\n\nconst encoder = new TextEncoder();\n\n/**\n * A payload value as the JSON a persisted log holds (so a live projection and a rebuild agree),\n * within the value bound; otherwise nothing.\n */\nconst boundedJson = (value: unknown): Schema.Json | undefined => {\n if (value === undefined) return undefined;\n try {\n const json = JSON.stringify(value);\n if (json === undefined) return undefined;\n const normalized: unknown = JSON.parse(json);\n return Schema.is(Schema.Json)(normalized) &&\n encoder.encode(canonicalJson(normalized)).length <= transcriptMappingBounds.maxValueBytes\n ? normalized\n : undefined;\n } catch {\n return undefined;\n }\n};\n","import * as Schema from \"effect/Schema\";\n\nimport { assertNever } from \"../domain/assert-never\";\nimport { addModelUsage } from \"../domain/model-usage\";\nimport type { CommittedDurableEvent } from \"../services/session-store\";\nimport type { UserMessageContent } from \"../types/commands\";\nimport {\n type CommandId,\n type InferenceId,\n type MessageId,\n type RunId,\n SequenceNumber,\n type TurnId,\n} from \"../types/core\";\nimport {\n ProviderPartId,\n UnixEpochMillis,\n effectDurableAgentNamespace,\n FailurePayload,\n ToolName,\n ModelSelectionPayload,\n} from \"../types/events/envelope\";\nimport {\n assistantMessageCommittedEventType,\n assistantMessageImportedEventType,\n assistantPartialCommittedEventType,\n baseStateCreatedEventType,\n baseStateFailedEventType,\n baseStateRequestedEventType,\n commandAdmittedEventType,\n commandCancelledEventType,\n commandCompletedEventType,\n commandFailedEventType,\n commandStartedEventType,\n compactionCompletedEventType,\n compactionFailedEventType,\n compactionRequestedEventType,\n compactionStartedEventType,\n contextProjectedEventType,\n contextRebasedEventType,\n inferenceCompletedEventType,\n inferenceFailedEventType,\n inferenceStartedEventType,\n interpretLegacyAttemptForReduction,\n messageQueuePausedEventType,\n pendingMessagesPausedEventType,\n recoveryCompletedEventType,\n runCompletedEventType,\n runFailedEventType,\n runInterruptedEventType,\n runSchedulingDeliveredEventType,\n runSchedulingGrantedEventType,\n runSchedulingInvalidatedEventType,\n runSchedulingRequestedEventType,\n runStartedEventType,\n sessionConfiguredEventType,\n steeringMessageCancelledEventType,\n steeringMessageQueuedEventType,\n stopTurnAppliedEventType,\n stopTurnRequestedEventType,\n summaryCreatedEventType,\n systemMessageCommittedEventType,\n toolCallCompletedEventType,\n toolCallCreatedEventType,\n toolCallFailedEventType,\n toolCallRejectedEventType,\n toolCallStartedEventType,\n turnCompletedEventType,\n turnFailedEventType,\n turnStartedEventType,\n turnStoppedEventType,\n userMessageCancelledEventType,\n userMessageCommittedEventType,\n userMessagePromotedEventType,\n userMessageSubmittedEventType,\n type AssistantPromptPart,\n} from \"../types/events/durable\";\nimport { applyForeignEvent, replayBufferedDecorations } from \"./mapping-executor\";\nimport type { TranscriptDefinition } from \"./mapping\";\nimport {\n TranscriptProjectionError,\n type PlanTranscriptBatch,\n type TranscriptAlias,\n type TranscriptAliasNamespace,\n type TranscriptChangePlan,\n type TranscriptLookup,\n} from \"./plan\";\nimport {\n runGroupStatus,\n transcriptRecordId,\n transcriptStoredInlineBodyLimit,\n type AssistantRecordId,\n type TranscriptAssistantPart,\n type TranscriptAssistantRecord,\n type TranscriptBody,\n type TranscriptFieldPath,\n type TranscriptCompactionRecord,\n type TranscriptPosition,\n TranscriptRecord,\n TranscriptRecordFromEnvelope,\n type TranscriptRecordId,\n type TranscriptRunGroupRecord,\n type TranscriptRunMember,\n type TranscriptRunOutcome,\n type TranscriptSessionContextRecord,\n type TranscriptToolRecord,\n type TranscriptUserRecord,\n type TranscriptUserState,\n} from \"./records\";\n\n/**\n * Accumulates one batch's changes over a committed lookup.\n *\n * Every handler reads through this overlay, so later events in a batch see earlier ones, and the\n * plan is the same whichever way a log is split into batches: interpretation is a sequential fold\n * whose only state is the records themselves.\n */\nexport class TranscriptBatch {\n private readonly records = new Map<TranscriptRecordId, TranscriptRecord>();\n private readonly aliases = new Map<string, TranscriptAlias>();\n private readonly ordinals = new Map<number, number>();\n\n constructor(\n private readonly lookup: TranscriptLookup,\n readonly definition: TranscriptDefinition,\n ) {}\n\n get(id: TranscriptRecordId): TranscriptRecord | undefined {\n return this.records.get(id) ?? this.lookup.record(id);\n }\n\n put(record: TranscriptRecord): void {\n this.records.set(record.id, record);\n }\n\n user(id: TranscriptRecordId): TranscriptUserRecord | undefined {\n const record = this.get(id);\n if (record === undefined) return undefined;\n if (record.kind !== \"user\") throw kindMismatch(id, \"user\", record.kind);\n return record;\n }\n\n assistant(id: AssistantRecordId): TranscriptAssistantRecord | undefined {\n const record = this.get(id);\n if (record === undefined) return undefined;\n if (record.kind !== \"assistant\") throw kindMismatch(id, \"assistant\", record.kind);\n return record;\n }\n\n tool(id: TranscriptRecordId): TranscriptToolRecord | undefined {\n const record = this.get(id);\n if (record === undefined) return undefined;\n if (record.kind !== \"tool\") throw kindMismatch(id, \"tool\", record.kind);\n return record;\n }\n\n runGroup(id: TranscriptRecordId): TranscriptRunGroupRecord | undefined {\n const record = this.get(id);\n if (record === undefined) return undefined;\n if (record.kind !== \"runGroup\") throw kindMismatch(id, \"runGroup\", record.kind);\n return record;\n }\n\n session(seq: SequenceNumber): TranscriptSessionContextRecord {\n const record = this.get(transcriptRecordId.session);\n if (record === undefined) {\n return {\n kind: \"sessionContext\",\n id: transcriptRecordId.session,\n updatedSeq: seq,\n tokenUsage: { byModel: [] },\n decorations: {},\n };\n }\n if (record.kind !== \"sessionContext\") {\n throw kindMismatch(transcriptRecordId.session, \"sessionContext\", record.kind);\n }\n return record;\n }\n\n alias(namespace: TranscriptAliasNamespace, key: string): TranscriptRecordId | undefined {\n return (\n this.aliases.get(aliasKey(namespace, key))?.recordId ?? this.lookup.alias(namespace, key)\n );\n }\n\n /** Insert an alias unless one exists; an alias never moves to another record. */\n insertAlias(\n namespace: TranscriptAliasNamespace,\n key: string,\n recordId: TranscriptRecordId,\n ): void {\n if (this.alias(namespace, key) !== undefined) return;\n this.aliases.set(aliasKey(namespace, key), { namespace, key, recordId });\n }\n\n position(anchorSeq: SequenceNumber): TranscriptPosition {\n const ordinal = this.ordinals.get(anchorSeq) ?? this.lookup.nextOrdinal(anchorSeq);\n this.ordinals.set(anchorSeq, ordinal + 1);\n return { anchorSeq, ordinal };\n }\n\n plan(throughSeq: SequenceNumber): TranscriptChangePlan {\n // Every planned record must satisfy the strict stored-row schema: an invalid record fails\n // this version's projection (freezing it) rather than becoming a row no reader can decode.\n for (const record of this.records.values()) {\n const problem = storageProblem(record);\n if (problem !== undefined) {\n throw new TranscriptProjectionError({ message: `planned record ${record.id} ${problem}` });\n }\n }\n return {\n records: Array.from(this.records.values()),\n aliases: Array.from(this.aliases.values()),\n throughSeq,\n };\n }\n}\n\nconst aliasKey = (namespace: TranscriptAliasNamespace, key: string) => `${namespace}\\u0000${key}`;\n\nconst matchesRecordSchema = Schema.is(TranscriptRecord);\n\nconst encodeRecord = Schema.encodeSync(TranscriptRecordFromEnvelope);\n\nconst describeCause = (cause: unknown): string =>\n cause instanceof Error ? cause.message : String(cause);\n\n/**\n * Why a record could not be stored, if it could not: it must satisfy the stored-row schema,\n * filters included, and its envelope must be JSON, which is exactly what a store can write and\n * every reader can encode. The cause is kept so a frozen version can be diagnosed from its meta.\n */\nconst storageProblem = (record: TranscriptRecord): string | undefined => {\n let envelope: unknown;\n try {\n envelope = encodeRecord(record);\n } catch (cause) {\n return `does not satisfy the transcript record schema: ${describeCause(cause)}`;\n }\n if (!matchesRecordSchema(record)) {\n return \"does not satisfy the transcript record schema\";\n }\n try {\n return JSON.stringify(envelope) === undefined ? \"has no JSON envelope\" : undefined;\n } catch (cause) {\n return `is not JSON: ${describeCause(cause)}`;\n }\n};\n\nconst kindMismatch = (id: string, expected: string, actual: string) =>\n new TranscriptProjectionError({ message: `record ${id} is ${actual}, expected ${expected}` });\n\n/**\n * Interpret one committed batch into a transcript change plan.\n *\n * Mirrors the `ReducedState` message, tool and inference fold without pruning: a\n * `ContextRebased` only adds a compaction marker. Events at or below the lookup cursor are\n * skipped, so an idempotent re-append is harmless. Foreign events are ignored unless a mapping\n * of `definition` names their namespace, type and schema version.\n */\nexport const planTranscriptBatch: PlanTranscriptBatch = (lookup, committed, definition) => {\n const batch = new TranscriptBatch(lookup, definition);\n let throughSeq = lookup.cursor;\n for (const entry of committed) {\n const seq = entry.position.seq;\n if (seq <= throughSeq) continue;\n throughSeq = seq;\n if (entry.event.namespace === \"__foreign\") {\n applyForeignEvent(batch, entry.event.envelope, seq);\n continue;\n }\n if (entry.event.namespace !== effectDurableAgentNamespace) continue;\n interpretEvent(batch, entry, seq);\n }\n return batch.plan(throughSeq);\n};\n\nconst eventTime = (createdAtMs: number) => UnixEpochMillis.make(createdAtMs);\n\nconst interpretEvent = (\n batch: TranscriptBatch,\n entry: CommittedDurableEvent,\n seq: SequenceNumber,\n) => {\n if (entry.event.namespace === \"__foreign\") return;\n const event = interpretLegacyAttemptForReduction(entry.event);\n const at = eventTime(event.createdAtMs);\n switch (event.type) {\n case sessionConfiguredEventType: {\n const session = batch.session(seq);\n if (session.modelSelection === undefined) {\n batch.put({\n ...session,\n updatedSeq: seq,\n modelSelection: jsonModelSelection(event.payload.modelSelection),\n });\n }\n return;\n }\n case commandAdmittedEventType: {\n const { command } = event.payload;\n if (command._tag !== \"SubmitMessage\" || command.commandId === undefined) return;\n const id = transcriptRecordId.user(command.commandId);\n if (batch.get(id) !== undefined) return;\n createUser(batch, seq, at, {\n commandId: command.commandId,\n content: command.content,\n state: command.disposition === \"steer\" ? { _tag: \"Steering\" } : { _tag: \"Pending\" },\n disposition: command.disposition,\n ...(command.idempotencyKey === undefined ? {} : { idempotencyKey: command.idempotencyKey }),\n });\n return;\n }\n case commandCancelledEventType:\n case commandFailedEventType: {\n const user = batch.user(transcriptRecordId.user(event.payload.commandId));\n // Only a submission that never became a message is withdrawn by its command (an interrupt\n // whose start failed or was cancelled); messages follow their own lifecycle events, as in\n // the reduced state.\n if (user === undefined || user.messageIds.length > 0 || !isWaiting(user.state)) return;\n batch.put({\n ...user,\n updatedSeq: seq,\n state: {\n _tag: \"Cancelled\",\n reason:\n event.type === commandFailedEventType\n ? `failed: ${event.payload.error.message}`\n : event.payload.reason,\n },\n });\n return;\n }\n case userMessageSubmittedEventType: {\n const { commandId, messageId, disposition, content } = event.payload;\n const user = userForMessage(batch, seq, at, commandId, messageId, content);\n batch.put({\n ...user,\n updatedSeq: seq,\n content,\n disposition,\n state: isWaiting(user.state)\n ? disposition === \"steer\"\n ? { _tag: \"Steering\" }\n : { _tag: \"Pending\" }\n : user.state,\n });\n return;\n }\n case userMessageCommittedEventType: {\n // A committed user message is model context immediately: this is its consumption point.\n // A replacement message id for the same command joins the same record as an alias.\n const { commandId, messageId, content } = event.payload;\n const user = userForMessage(batch, seq, at, commandId, messageId, content);\n batch.put(\n user.state._tag === \"Consumed\"\n ? { ...user, updatedSeq: seq, content }\n : consume(batch, { ...user, content }, seq, at, {}),\n );\n return;\n }\n case steeringMessageQueuedEventType: {\n const { commandId, messageId, runId, content } = event.payload;\n const user = userForMessage(batch, seq, at, commandId, messageId, content);\n batch.put({\n ...user,\n updatedSeq: seq,\n content,\n steering: { runId },\n state: isWaiting(user.state) ? { _tag: \"Steering\" } : user.state,\n });\n return;\n }\n case steeringMessageCancelledEventType: {\n const user = userByMessage(batch, event.payload.messageId);\n if (user?.steering === undefined || user.state._tag === \"Consumed\") return;\n batch.put({\n ...user,\n updatedSeq: seq,\n state: { _tag: \"Cancelled\", reason: event.payload.reason },\n });\n return;\n }\n case userMessagePromotedEventType: {\n const user = userByMessage(batch, event.payload.messageId);\n if (user === undefined) return;\n if (user.state._tag !== \"Pending\" && user.state._tag !== \"Paused\") return;\n batch.put({\n ...user,\n updatedSeq: seq,\n ...(user.steering === undefined ? { disposition: \"steer\" as const } : {}),\n state: { _tag: \"Promoted\" },\n });\n return;\n }\n case userMessageCancelledEventType: {\n const { commandId, messageId, reason } = event.payload;\n const user = userByMessage(batch, messageId);\n if (user === undefined || user.state._tag === \"Cancelled\") return;\n // Steering that the agent already read stays in history; a cancelled user submission is\n // withdrawn from the model context even after consumption, exactly as the prompt does.\n if (user.steering !== undefined && user.state._tag === \"Consumed\") return;\n batch.put({\n ...user,\n updatedSeq: seq,\n state: { _tag: \"Cancelled\", reason, byCommandId: commandId },\n });\n return;\n }\n case messageQueuePausedEventType:\n case pendingMessagesPausedEventType: {\n const byCommandId =\n event.type === messageQueuePausedEventType\n ? event.payload.stopCommandId\n : event.payload.interruptionCommandId;\n for (const messageId of event.payload.messageIds) {\n const user = userByMessage(batch, messageId);\n if (user === undefined || !isWaiting(user.state)) continue;\n batch.put({\n ...user,\n updatedSeq: seq,\n ...(user.steering === undefined ? { disposition: \"queue\" as const } : {}),\n state: { _tag: \"Paused\", byCommandId },\n });\n }\n return;\n }\n case turnStartedEventType: {\n const { runId, turnId, inputMessageIds } = event.payload;\n for (const messageId of inputMessageIds ?? []) {\n const user = userByMessage(batch, messageId);\n if (user === undefined || user.state._tag === \"Consumed\") continue;\n // The reduced state marks a cancelled submission consumed but keeps it out of the\n // prompt; cancelled steering re-enters it once consumed.\n if (user.state._tag === \"Cancelled\" && user.steering === undefined) continue;\n batch.put(consume(batch, user, seq, at, { runId, turnId }));\n }\n return;\n }\n case assistantMessageCommittedEventType:\n case assistantPartialCommittedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts } = event.payload;\n const id = transcriptRecordId.assistant(inferenceId);\n const existing =\n batch.assistant(id) ??\n newAssistant(batch, id, seq, \"inference\", inferenceId, runId, turnId);\n const { partial: _partial, ...withoutPartial } = existing;\n batch.put({\n ...withoutPartial,\n updatedSeq: seq,\n messageId,\n parts: assistantParts(batch, inferenceId, promptParts, seq),\n ...(event.type === assistantPartialCommittedEventType\n ? { partial: { reason: event.payload.reason } }\n : {}),\n });\n return;\n }\n case assistantMessageImportedEventType: {\n const { messageId, runId, turnId, inferenceId, promptParts } = event.payload;\n const id = transcriptRecordId.import(event.eventId);\n const created = newAssistant(batch, id, seq, \"import\", inferenceId, runId, turnId);\n const { runGroupId: _runGroupId, ...imported } = created;\n batch.put({\n ...imported,\n messageId,\n lifecycle: { _tag: \"Completed\" },\n parts: assistantParts(batch, inferenceId, promptParts, seq),\n });\n return;\n }\n case inferenceStartedEventType: {\n const { runId, turnId, inferenceId } = event.payload;\n const id = transcriptRecordId.assistant(inferenceId);\n const existing =\n batch.assistant(id) ??\n newAssistant(batch, id, seq, \"inference\", inferenceId, runId, turnId);\n batch.put({ ...existing, updatedSeq: seq, startedAtMs: at });\n return;\n }\n case inferenceCompletedEventType: {\n const { runId, inferenceId, finishReason, usage } = event.payload;\n const assistant = batch.assistant(transcriptRecordId.assistant(inferenceId));\n if (assistant === undefined) return;\n // Token totals follow the reduced state: count the first completion of a started inference.\n if (assistant.startedAtMs !== undefined && assistant.lifecycle._tag !== \"Completed\") {\n const model = runMember(batch, runId)?.modelSelection;\n if (model !== undefined && usage !== undefined) {\n const session = batch.session(seq);\n batch.put({\n ...session,\n updatedSeq: seq,\n tokenUsage: addModelUsage(session.tokenUsage, model, usage),\n });\n }\n }\n batch.put({\n ...assistant,\n updatedSeq: seq,\n ...terminalTiming(assistant.startedAtMs, at),\n lifecycle: {\n _tag: \"Completed\",\n ...(finishReason === undefined ? {} : { finishReason }),\n ...(usage === undefined ? {} : { usage }),\n },\n });\n return;\n }\n case inferenceFailedEventType: {\n const assistant = batch.assistant(transcriptRecordId.assistant(event.payload.inferenceId));\n if (assistant === undefined) return;\n batch.put({\n ...assistant,\n updatedSeq: seq,\n ...terminalTiming(assistant.startedAtMs, at),\n lifecycle: { _tag: \"Failed\", error: jsonFailure(event.payload.error) },\n });\n return;\n }\n case toolCallCreatedEventType: {\n const { inferenceId, toolCallId, promptPart } = event.payload;\n const id = transcriptRecordId.tool(toolCallId);\n const existing = batch.tool(id);\n batch.put({\n kind: \"tool\",\n id,\n updatedSeq: seq,\n toolCallId,\n assistantId: transcriptRecordId.assistant(inferenceId),\n providerPartId: promptPart.id,\n toolName: promptPart.name,\n providerExecuted: promptPart.providerExecuted,\n params: inlineBody(promptPart.params, seq, [\"promptPart\", \"params\"]),\n lifecycle:\n existing === undefined || existing.lifecycle._tag === \"Rejected\"\n ? { _tag: \"Created\" }\n : existing.lifecycle,\n createdAtMs: existing?.createdAtMs ?? at,\n ...timingOf(existing),\n });\n linkToolPart(batch, inferenceId, promptPart.id, id, seq);\n return;\n }\n case toolCallRejectedEventType: {\n const { inferenceId, toolCallId, promptPart } = event.payload;\n const id = transcriptRecordId.tool(toolCallId);\n const existing = batch.tool(id);\n batch.put({\n kind: \"tool\",\n id,\n updatedSeq: seq,\n toolCallId,\n assistantId: transcriptRecordId.assistant(inferenceId),\n providerPartId: promptPart.id,\n toolName: promptPart.name,\n providerExecuted: false,\n lifecycle: {\n _tag: \"Rejected\",\n reason: promptPart.result.reason,\n message: promptPart.result.message,\n modelFeedback: promptPart.result.modelFeedback,\n },\n createdAtMs: existing?.createdAtMs ?? at,\n ...timingOf(existing),\n });\n linkToolPart(batch, inferenceId, promptPart.id, id, seq);\n return;\n }\n case toolCallStartedEventType: {\n const tool = batch.tool(transcriptRecordId.tool(event.payload.toolCallId));\n if (tool === undefined) return;\n batch.put({\n ...tool,\n updatedSeq: seq,\n startedAtMs: at,\n lifecycle: tool.lifecycle._tag === \"Created\" ? { _tag: \"Running\" } : tool.lifecycle,\n });\n return;\n }\n case toolCallCompletedEventType: {\n const tool = batch.tool(transcriptRecordId.tool(event.payload.toolCallId));\n if (tool === undefined) return;\n batch.put({\n ...tool,\n updatedSeq: seq,\n ...terminalTiming(tool.startedAtMs, at),\n lifecycle: {\n _tag: \"Completed\",\n result: inlineBody(event.payload.promptPart.result, seq, [\"promptPart\", \"result\"]),\n },\n });\n return;\n }\n case toolCallFailedEventType: {\n const tool = batch.tool(transcriptRecordId.tool(event.payload.toolCallId));\n if (tool === undefined) return;\n batch.put({\n ...tool,\n updatedSeq: seq,\n ...terminalTiming(tool.startedAtMs, at),\n lifecycle: {\n _tag: \"Failed\",\n error: jsonFailure(event.payload.error ?? event.payload.promptPart.result),\n },\n });\n return;\n }\n case contextRebasedEventType: {\n const { compactionId, summaryId, contextVersion, retainedFromContextSeq } = event.payload;\n const id = transcriptRecordId.compaction(compactionId);\n const existing = batch.get(id);\n if (existing !== undefined && existing.kind !== \"compaction\") {\n throw kindMismatch(id, \"compaction\", existing.kind);\n }\n const record: TranscriptCompactionRecord = {\n kind: \"compaction\",\n id,\n updatedSeq: seq,\n position: existing?.position ?? batch.position(seq),\n compactionId,\n summaryId,\n contextVersion,\n retainedFromContextSeq,\n createdAtMs: existing?.createdAtMs ?? at,\n };\n batch.put(record);\n return;\n }\n case compactionStartedEventType: {\n const session = batch.session(seq);\n batch.put({ ...session, updatedSeq: seq, activeCompactionId: event.payload.compactionId });\n return;\n }\n case compactionCompletedEventType:\n case compactionFailedEventType: {\n const { compactionId, modelSelection, usage } = event.payload;\n // As in the reduced state, a repeated completion adds no usage; failures always do.\n const compactionRecordId = transcriptRecordId.compaction(compactionId);\n const compaction = batch.get(compactionRecordId);\n const repeated =\n event.type === compactionCompletedEventType &&\n compaction?.kind === \"compaction\" &&\n compaction.completedAtMs !== undefined;\n if (\n event.type === compactionCompletedEventType &&\n compaction?.kind === \"compaction\" &&\n compaction.completedAtMs === undefined\n ) {\n batch.put({ ...compaction, updatedSeq: seq, completedAtMs: at });\n }\n const session = batch.session(seq);\n const { activeCompactionId, ...rest } = session;\n batch.put({\n ...rest,\n updatedSeq: seq,\n ...(activeCompactionId === undefined || activeCompactionId === compactionId\n ? {}\n : { activeCompactionId }),\n tokenUsage:\n modelSelection === undefined || repeated\n ? session.tokenUsage\n : addModelUsage(session.tokenUsage, modelSelection, usage),\n });\n return;\n }\n case runStartedEventType: {\n startRun(\n batch,\n seq,\n at,\n event.payload.runId,\n event.payload.commandIds,\n jsonModelSelection(event.payload.modelSelection),\n );\n return;\n }\n case runCompletedEventType:\n finishRun(batch, seq, at, event.payload.runId, { _tag: \"Completed\" });\n return;\n case runFailedEventType:\n finishRun(batch, seq, at, event.payload.runId, runFailureOutcome(event.payload.error));\n return;\n case runInterruptedEventType:\n finishRun(batch, seq, at, event.payload.runId, {\n _tag: \"Interrupted\",\n reason: event.payload.reason,\n });\n return;\n case recoveryCompletedEventType: {\n const continuation = event.payload.continuation;\n if (continuation === undefined) return;\n const groupId = batch.alias(\"runId\", continuation.replacementRunId);\n const group = groupId === undefined ? undefined : batch.runGroup(groupId);\n if (group === undefined) return;\n batch.put({\n ...group,\n updatedSeq: seq,\n runs: mapNonEmpty(group.runs, (member) =>\n member.runId === continuation.replacementRunId\n ? { ...member, continuationOf: continuation.interruptedRunId }\n : member,\n ),\n });\n return;\n }\n case systemMessageCommittedEventType:\n case runSchedulingRequestedEventType:\n case runSchedulingDeliveredEventType:\n case runSchedulingInvalidatedEventType:\n case runSchedulingGrantedEventType:\n case commandStartedEventType:\n case commandCompletedEventType:\n case turnCompletedEventType:\n case turnFailedEventType:\n case turnStoppedEventType:\n case stopTurnRequestedEventType:\n case stopTurnAppliedEventType:\n case contextProjectedEventType:\n case compactionRequestedEventType:\n case summaryCreatedEventType:\n case baseStateRequestedEventType:\n case baseStateCreatedEventType:\n case baseStateFailedEventType:\n // Deliberately without transcript meaning in this semantic revision.\n return;\n default:\n return assertNever(event, \"transcript durable event\");\n }\n};\n\n// ---------------------------------------------------------------------------------------------\n// Users\n// ---------------------------------------------------------------------------------------------\n\n/** Waiting for the agent: not yet consumed and not withdrawn. */\nconst isWaiting = (state: TranscriptUserState): boolean =>\n state._tag === \"Pending\" ||\n state._tag === \"Paused\" ||\n state._tag === \"Promoted\" ||\n state._tag === \"Steering\";\n\n/** What the first event that names a submission knows about it. */\ninterface NewUserFields {\n readonly commandId: CommandId;\n readonly content: UserMessageContent;\n readonly state: TranscriptUserState;\n readonly disposition?: TranscriptUserRecord[\"disposition\"];\n readonly idempotencyKey?: TranscriptUserRecord[\"idempotencyKey\"];\n}\n\nconst createUser = (\n batch: TranscriptBatch,\n seq: SequenceNumber,\n at: UnixEpochMillis,\n fields: NewUserFields,\n): TranscriptUserRecord => {\n const id = transcriptRecordId.user(fields.commandId);\n if (fields.idempotencyKey !== undefined) {\n batch.insertAlias(\"idempotencyKey\", fields.idempotencyKey, id);\n }\n const user = replayBufferedDecorations(batch, seq, {\n kind: \"user\",\n id,\n updatedSeq: seq,\n messageIds: [],\n decorations: {},\n submittedSeq: seq,\n submittedAtMs: at,\n ...fields,\n });\n batch.put(user);\n return user;\n};\n\n/** The user record a message belongs to, created if the log never admitted its command. */\nconst userForMessage = (\n batch: TranscriptBatch,\n seq: SequenceNumber,\n at: UnixEpochMillis,\n commandId: CommandId,\n messageId: MessageId,\n content: UserMessageContent,\n): TranscriptUserRecord => {\n const id = transcriptRecordId.user(commandId);\n const user =\n batch.user(id) ??\n createUser(batch, seq, at, { commandId, content, state: { _tag: \"Pending\" } });\n batch.insertAlias(\"messageId\", messageId, id);\n return user.messageIds.includes(messageId)\n ? user\n : { ...user, messageIds: [...user.messageIds, messageId] };\n};\n\nconst userByMessage = (batch: TranscriptBatch, messageId: MessageId) => {\n const id = batch.alias(\"messageId\", messageId);\n return id === undefined ? undefined : batch.user(id);\n};\n\nconst consume = (\n batch: TranscriptBatch,\n user: TranscriptUserRecord,\n seq: SequenceNumber,\n at: UnixEpochMillis,\n by: { readonly runId?: RunId; readonly turnId?: TurnId },\n): TranscriptUserRecord => ({\n ...user,\n updatedSeq: seq,\n // Positions are assigned once; a later consumption never moves a record.\n position: user.position ?? batch.position(seq),\n consumedAtMs: user.consumedAtMs ?? at,\n state: { _tag: \"Consumed\", ...by },\n});\n\n// ---------------------------------------------------------------------------------------------\n// Assistants and tools\n// ---------------------------------------------------------------------------------------------\n\nconst newAssistant = (\n batch: TranscriptBatch,\n id: AssistantRecordId,\n seq: SequenceNumber,\n source: \"inference\" | \"import\",\n inferenceId: InferenceId,\n runId: RunId,\n turnId: TurnId,\n): TranscriptAssistantRecord => {\n const groupId = batch.alias(\"runId\", runId);\n const runGroupId = groupId === undefined ? undefined : batch.runGroup(groupId)?.id;\n return {\n kind: \"assistant\",\n id,\n updatedSeq: seq,\n position: batch.position(seq),\n source,\n inferenceId,\n runId,\n turnId,\n ...(runGroupId === undefined ? {} : { runGroupId }),\n lifecycle: { _tag: \"Streaming\" },\n parts: [],\n };\n};\n\nconst assistantParts = (\n batch: TranscriptBatch,\n inferenceId: InferenceId,\n promptParts: ReadonlyArray<AssistantPromptPart>,\n seq: SequenceNumber,\n): ReadonlyArray<TranscriptAssistantPart> =>\n promptParts.map((part, index): TranscriptAssistantPart => {\n switch (part.type) {\n case \"text\":\n return { _tag: \"Text\", text: part.text };\n case \"reasoning\":\n return { _tag: \"Reasoning\", text: part.text };\n case \"tool-call\": {\n if (!Schema.is(ProviderPartId)(part.id) || !Schema.is(ToolName)(part.name)) {\n return { _tag: \"Unknown\", partType: part.type };\n }\n const toolAlias = batch.alias(\"toolPart\", toolPartKey(inferenceId, part.id));\n const toolId = toolAlias === undefined ? undefined : batch.tool(toolAlias)?.id;\n return {\n _tag: \"ToolCall\",\n providerPartId: part.id,\n toolName: part.name,\n providerExecuted: part.providerExecuted,\n ...(toolId === undefined ? {} : { toolId }),\n };\n }\n case \"tool-result\":\n if (!Schema.is(ProviderPartId)(part.id) || !Schema.is(ToolName)(part.name)) {\n return { _tag: \"Unknown\", partType: part.type };\n }\n return {\n _tag: \"ToolResult\",\n providerPartId: part.id,\n toolName: part.name,\n isFailure: part.isFailure,\n result: inlineBody(part.result, seq, [\"promptParts\", index, \"result\"]),\n };\n default:\n return { _tag: \"Unknown\", partType: part.type };\n }\n });\n\nconst toolPartKey = (inferenceId: InferenceId, providerPartId: string) =>\n `${inferenceId}/${providerPartId}`;\n\n/** Record the tool for its assistant part, whichever of the two the log wrote first. */\nconst linkToolPart = (\n batch: TranscriptBatch,\n inferenceId: InferenceId,\n providerPartId: ProviderPartId,\n toolId: ReturnType<typeof transcriptRecordId.tool>,\n seq: SequenceNumber,\n) => {\n batch.insertAlias(\"toolPart\", toolPartKey(inferenceId, providerPartId), toolId);\n const assistant = batch.assistant(transcriptRecordId.assistant(inferenceId));\n if (assistant === undefined) return;\n let changed = false;\n const parts = assistant.parts.map((part): TranscriptAssistantPart => {\n if (\n part._tag !== \"ToolCall\" ||\n part.providerPartId !== providerPartId ||\n part.toolId !== undefined\n ) {\n return part;\n }\n changed = true;\n return { ...part, toolId };\n });\n if (changed) batch.put({ ...assistant, updatedSeq: seq, parts });\n};\n\n// ---------------------------------------------------------------------------------------------\n// Runs\n// ---------------------------------------------------------------------------------------------\n\nconst startRun = (\n batch: TranscriptBatch,\n seq: SequenceNumber,\n at: UnixEpochMillis,\n runId: RunId,\n commandIds: ReadonlyArray<CommandId>,\n modelSelection: ModelSelectionPayload,\n) => {\n const member: TranscriptRunMember = {\n runId,\n commandIds,\n modelSelection,\n outcome: { _tag: \"Running\" },\n startedAtMs: at,\n };\n const group = runGroupForStart(batch, seq, runId, commandIds, member);\n batch.put(group);\n batch.insertAlias(\"runId\", runId, group.id);\n for (const commandId of commandIds) batch.insertAlias(\"runCommand\", commandId, group.id);\n\n const session = batch.session(seq);\n batch.put({\n ...session,\n updatedSeq: seq,\n activeRunId: runId,\n lastRunModelSelection: modelSelection,\n modelSelection: session.modelSelection ?? modelSelection,\n });\n};\n\n/**\n * The group a started run belongs to. A repeated start of a known run replaces its member and\n * keeps its outcome, as the reduced state keeps its terminal. A startup-recovery continuation\n * reuses its interrupted predecessor's command ids, so it joins that finished group; any other\n * run roots a new group.\n */\nconst runGroupForStart = (\n batch: TranscriptBatch,\n seq: SequenceNumber,\n runId: RunId,\n commandIds: ReadonlyArray<CommandId>,\n member: TranscriptRunMember,\n): TranscriptRunGroupRecord => {\n const knownId = batch.alias(\"runId\", runId);\n const known = knownId === undefined ? undefined : batch.runGroup(knownId);\n if (known !== undefined) {\n return {\n ...known,\n updatedSeq: seq,\n runs: mapNonEmpty(known.runs, (candidate) =>\n candidate.runId === runId ? { ...member, outcome: candidate.outcome } : candidate,\n ),\n };\n }\n const predecessor = commandIds\n .map((commandId) => batch.alias(\"runCommand\", commandId))\n .map((groupId) => (groupId === undefined ? undefined : batch.runGroup(groupId)))\n .find((group) => group !== undefined && runGroupStatus(group)._tag !== \"Running\");\n if (predecessor !== undefined) {\n return { ...predecessor, updatedSeq: seq, runs: [...predecessor.runs, member] };\n }\n return {\n kind: \"runGroup\",\n id: transcriptRecordId.runGroup(runId),\n updatedSeq: seq,\n rootRunId: runId,\n runs: [member],\n };\n};\n\nconst finishRun = (\n batch: TranscriptBatch,\n seq: SequenceNumber,\n at: UnixEpochMillis,\n runId: RunId,\n outcome: TranscriptRunOutcome,\n) => {\n const groupId = batch.alias(\"runId\", runId);\n const group = groupId === undefined ? undefined : batch.runGroup(groupId);\n if (group === undefined) return;\n batch.put({\n ...group,\n updatedSeq: seq,\n runs: mapNonEmpty(group.runs, (member) =>\n member.runId === runId\n ? { ...member, ...terminalTiming(member.startedAtMs, at), outcome }\n : member,\n ),\n });\n const session = batch.session(seq);\n if (session.activeRunId === runId) {\n const { activeRunId: _activeRunId, ...idle } = session;\n batch.put({ ...idle, updatedSeq: seq });\n }\n};\n\nconst runMember = (batch: TranscriptBatch, runId: RunId) => {\n const groupId = batch.alias(\"runId\", runId);\n const group = groupId === undefined ? undefined : batch.runGroup(groupId);\n return group?.runs.find((member) => member.runId === runId);\n};\n\nconst runFailureOutcome = (error: FailurePayload): TranscriptRunOutcome =>\n error.code === \"run.interrupted\"\n ? { _tag: \"Interrupted\", reason: error.message }\n : { _tag: \"Failed\", error: jsonFailure(error) };\n\n// ---------------------------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------------------------\n\nconst terminalTiming = (\n startedAtMs: UnixEpochMillis | undefined,\n terminalAtMs: UnixEpochMillis,\n) => ({\n terminalAtMs,\n ...(startedAtMs === undefined ? {} : { durationMs: Math.max(0, terminalAtMs - startedAtMs) }),\n});\n\nconst timingOf = (record: TranscriptToolRecord | undefined) => ({\n ...(record?.startedAtMs === undefined ? {} : { startedAtMs: record.startedAtMs }),\n ...(record?.terminalAtMs === undefined ? {} : { terminalAtMs: record.terminalAtMs }),\n ...(record?.durationMs === undefined ? {} : { durationMs: record.durationMs }),\n});\n\nconst bodyEncoder = new TextEncoder();\n\n/**\n * A body read from a committed event, normalized to the JSON a persisted log holds, so a live\n * projection and a rebuild from storage agree. A value with no JSON form (a bigint or a cycle) is\n * a projection failure.\n */\nconst inlineBody = (\n value: unknown,\n seq: SequenceNumber,\n path: TranscriptFieldPath,\n): TranscriptBody => {\n const notJson = () =>\n new TranscriptProjectionError({\n message: `body at seq ${seq} ${JSON.stringify(path)} is not JSON`,\n });\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n throw notJson();\n }\n const normalized: unknown = json === undefined ? null : JSON.parse(json);\n if (!Schema.is(Schema.Json)(normalized)) throw notJson();\n // Large bodies stay in the log; the stored row keeps only a reference to them.\n const byteLength = json === undefined ? 4 : bodyEncoder.encode(json).length;\n return byteLength <= transcriptStoredInlineBodyLimit\n ? { _tag: \"Inline\", value: normalized, source: { seq, path } }\n : { _tag: \"Ref\", source: { seq, path }, byteLength };\n};\n\n/** A model selection as the JSON a persisted log holds; settings with no JSON form are dropped. */\nconst jsonModelSelection = (selection: ModelSelectionPayload): ModelSelectionPayload => {\n try {\n const json = JSON.stringify(selection);\n const normalized: unknown = json === undefined ? undefined : JSON.parse(json);\n if (Schema.is(ModelSelectionPayload)(normalized)) return normalized;\n } catch {\n // Fall through to the fields every selection has.\n }\n return { provider: selection.provider, modelId: selection.modelId };\n};\n\n/** A failure as the JSON a persisted log holds; details with no JSON form are dropped. */\nconst jsonFailure = (error: FailurePayload): FailurePayload => {\n try {\n const json = JSON.stringify(error);\n const normalized: unknown = json === undefined ? undefined : JSON.parse(json);\n if (Schema.is(FailurePayload)(normalized)) return normalized;\n } catch {\n // Fall through to the fields every failure has.\n }\n return { message: error.message, ...(error.code === undefined ? {} : { code: error.code }) };\n};\n\nconst mapNonEmpty = <A>(\n items: readonly [A, ...Array<A>],\n f: (item: A) => A,\n): readonly [A, ...Array<A>] => [f(items[0]), ...items.slice(1).map(f)];\n","import * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport type { EDASessionStoreError } from \"../services/session-store\";\nimport type { TranscriptDefinition } from \"./mapping\";\nimport type {\n TranscriptVersionMeta,\n TranscriptWindow,\n TranscriptWindowLimits,\n TranscriptWindowSelector,\n} from \"./window\";\n\n/**\n * The transcript definitions a store maintains, fixed when the store is constructed.\n *\n * `current` is what new sessions start with and every session converges to. `previous` is\n * carried for one release only, so a session not yet rebuilt keeps its active rows maintained.\n * A stored version that matches neither is frozen.\n */\nexport interface TranscriptMaintenanceConfig {\n readonly current: TranscriptDefinition;\n readonly previous?: TranscriptDefinition;\n}\n\n/** A cursor minted for another log incarnation or transcript version. The client takes `Latest`. */\nexport class TranscriptCursorMismatch extends Schema.TaggedError<TranscriptCursorMismatch>()(\n \"TranscriptCursorMismatch\",\n { message: Schema.String },\n) {}\n\n/**\n * Storage-level transcript reads for one session.\n *\n * Maintenance has no method here: the store runs it inside its own append transaction for every\n * carried, healthy version, so `EDASessionStore.append` semantics are unchanged. These reads never\n * construct the model runtime and never include live active content, which only the delivery\n * layer can capture.\n */\nexport interface EDATranscriptStoreShape {\n /** Read one complete window of the served version at a single cut. */\n readonly readTranscriptWindow: (\n selector: TranscriptWindowSelector,\n limits: TranscriptWindowLimits,\n ) => Effect.Effect<TranscriptWindow, EDASessionStoreError | TranscriptCursorMismatch>;\n /** Maintenance state of every version present, for builders, backfill proofs and alerts. */\n readonly readTranscriptMeta: Effect.Effect<\n ReadonlyArray<TranscriptVersionMeta>,\n EDASessionStoreError\n >;\n}\n\n/** Transcript read port, provided alongside `EDASessionStore` by stores that maintain transcripts. */\nexport class EDATranscriptStore extends Context.Service<\n EDATranscriptStore,\n EDATranscriptStoreShape\n>()(\"@effect-durable-agent/EDATranscriptStore\") {}\n","import * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { NonNegativeInt } from \"../types/events/envelope\";\nimport type { TranscriptAliasNamespace } from \"./plan\";\nimport {\n TranscriptOrder,\n TranscriptRecordFromEnvelope,\n isPendingTranscriptUserRecord,\n transcriptRecordId,\n type AssistantRecordId,\n type TranscriptAssistantPart,\n type TranscriptBody,\n type TranscriptCursor,\n type TranscriptLogIncarnation,\n type TranscriptOrderKey,\n type TranscriptRecord,\n type TranscriptRecordId,\n type TranscriptToolRecord,\n type TranscriptTopLevelRecord,\n type TranscriptUserRecord,\n type TranscriptVersion,\n} from \"./records\";\nimport { TranscriptCursorMismatch } from \"./store\";\nimport type {\n TranscriptReadiness,\n TranscriptVersionMeta,\n TranscriptWindow,\n TranscriptWindowLimits,\n TranscriptWindowSelector,\n} from \"./window\";\n\n/**\n * Synchronous indexed reads of the served version at one cut, as a store provides them.\n *\n * Window assembly (paging, dependency collection, byte budgeting and body references) is shared\n * by every store through `readTranscriptWindowFrom`; a store only supplies these reads.\n */\nexport interface TranscriptWindowSource {\n readonly incarnation: TranscriptLogIncarnation;\n /** Maintenance state of the served (active) version; its cursor is the window's `throughSeq`. */\n readonly meta: TranscriptVersionMeta;\n /** False when this release no longer carries the served version (a missed session). */\n readonly carried: boolean;\n /** Top-level records before `key` (or before the end), newest first. */\n readonly topLevelBefore: (\n key: TranscriptOrderKey | undefined,\n limit: number,\n inclusive: boolean,\n ) => ReadonlyArray<TranscriptTopLevelRecord>;\n /** Top-level records after `key` (or after the start), oldest first. */\n readonly topLevelAfter: (\n key: TranscriptOrderKey | undefined,\n limit: number,\n inclusive: boolean,\n ) => ReadonlyArray<TranscriptTopLevelRecord>;\n readonly record: (id: TranscriptRecordId) => TranscriptRecord | undefined;\n readonly alias: (\n namespace: TranscriptAliasNamespace,\n key: string,\n ) => TranscriptRecordId | undefined;\n /** Tool records of one assistant (the typed dependency lookup). */\n readonly toolsOf: (assistantId: AssistantRecordId) => ReadonlyArray<TranscriptToolRecord>;\n /** Every user record still waiting for the agent (the pending-membership index). */\n readonly pendingUsers: () => ReadonlyArray<TranscriptUserRecord>;\n}\n\n/** Readiness of a served version: why its cut may be behind the log. */\nexport const transcriptReadiness = (\n meta: TranscriptVersionMeta,\n carried: boolean,\n): TranscriptReadiness => {\n if (!carried) return { _tag: \"UpdatingHistory\" };\n switch (meta.status._tag) {\n case \"Ok\":\n return { _tag: \"Ready\" };\n case \"Failed\":\n return {\n _tag: \"Degraded\",\n failedAtSeq: meta.status.failedAtSeq,\n error: meta.status.error,\n };\n }\n};\n\n/** The empty window served while no version is servable yet. */\nexport const buildingTranscriptWindow = (\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n): TranscriptWindow => ({\n incarnation,\n version,\n throughSeq: SequenceNumber.make(0),\n records: [],\n dependencies: [],\n hasOlder: false,\n hasNewer: false,\n readiness: { _tag: \"Building\" },\n});\n\nconst orderKey = (record: TranscriptTopLevelRecord): TranscriptOrderKey => ({\n anchorSeq: record.position?.anchorSeq ?? 0,\n ordinal: record.position?.ordinal ?? 0,\n recordId: record.id,\n});\n\nconst cursorKey = (cursor: TranscriptCursor): TranscriptOrderKey => ({\n anchorSeq: cursor.anchorSeq,\n ordinal: cursor.ordinal,\n recordId: cursor.recordId,\n});\n\n/**\n * Assemble one window from a source at a single cut.\n *\n * The response never contains anything newer than the served version's cursor: a frozen (failed\n * or no longer carried) version's rows, pending users and session context all stop at its last\n * good cut, which is the degraded-read rule. Bodies above the inline limit become references;\n * if the response still exceeds the byte budget, records are dropped from the far end of the\n * selection, keeping at least one so paging always progresses.\n */\nexport const readTranscriptWindowFrom = (\n source: TranscriptWindowSource,\n selector: TranscriptWindowSelector,\n limits: TranscriptWindowLimits,\n): Result.Result<TranscriptWindow, TranscriptCursorMismatch> => {\n const version = source.meta.version;\n for (const cursor of selectorCursors(selector)) {\n if (cursor.incarnation !== source.incarnation || cursor.version !== version) {\n return Result.fail(\n new TranscriptCursorMismatch({\n message: `cursor for ${cursor.incarnation}/${cursor.version} read against ${source.incarnation}/${version}`,\n }),\n );\n }\n }\n\n const selected = selectTopLevel(source, selector, limits.maxRecords);\n // Latest and Page(before) keep the newest records when trimming; the others keep the oldest.\n const keepNewest =\n selector._tag === \"Latest\" || (selector._tag === \"Page\" && selector.direction === \"before\");\n let top = selected.map((record) => withBodyRefs(record, limits.maxInlineBodyBytes));\n let dependencies = collectDependencies(source, top, limits.maxInlineBodyBytes);\n while (top.length > 1 && windowBytes(top, dependencies) > limits.maxBytes) {\n top = keepNewest ? top.slice(1) : top.slice(0, -1);\n dependencies = collectDependencies(source, top, limits.maxInlineBodyBytes);\n }\n\n const first = top[0];\n const last = top[top.length - 1];\n const [hasOlder, hasNewer] =\n first === undefined || last === undefined\n ? emptySelectionNeighbours(source, selector)\n : [\n source.topLevelBefore(orderKey(first), 1, false).length > 0,\n source.topLevelAfter(orderKey(last), 1, false).length > 0,\n ];\n\n return Result.succeed({\n incarnation: source.incarnation,\n version,\n throughSeq: source.meta.cursor,\n records: top,\n dependencies,\n hasOlder,\n hasNewer,\n readiness: transcriptReadiness(source.meta, source.carried),\n });\n};\n\nconst selectorCursors = (selector: TranscriptWindowSelector): ReadonlyArray<TranscriptCursor> => {\n switch (selector._tag) {\n case \"Latest\":\n return [];\n case \"Page\":\n return [selector.cursor];\n case \"Range\":\n return [selector.from, selector.to];\n }\n};\n\nconst selectTopLevel = (\n source: TranscriptWindowSource,\n selector: TranscriptWindowSelector,\n maxRecords: number,\n): ReadonlyArray<TranscriptTopLevelRecord> => {\n switch (selector._tag) {\n case \"Latest\":\n return [\n ...source.topLevelBefore(undefined, Math.min(selector.count, maxRecords), false),\n ].reverse();\n case \"Page\": {\n const count = Math.min(selector.count, maxRecords);\n return selector.direction === \"before\"\n ? [...source.topLevelBefore(cursorKey(selector.cursor), count, false)].reverse()\n : source.topLevelAfter(cursorKey(selector.cursor), count, false);\n }\n case \"Range\": {\n const to = cursorKey(selector.to);\n return source\n .topLevelAfter(cursorKey(selector.from), maxRecords, true)\n .filter((record) => TranscriptOrder(orderKey(record), to) <= 0);\n }\n }\n};\n\nconst emptySelectionNeighbours = (\n source: TranscriptWindowSource,\n selector: TranscriptWindowSelector,\n): readonly [boolean, boolean] => {\n switch (selector._tag) {\n case \"Latest\":\n return [false, false];\n case \"Page\": {\n const key = cursorKey(selector.cursor);\n return selector.direction === \"before\"\n ? [false, source.topLevelAfter(key, 1, true).length > 0]\n : [source.topLevelBefore(key, 1, true).length > 0, false];\n }\n case \"Range\":\n return [\n source.topLevelBefore(cursorKey(selector.from), 1, false).length > 0,\n source.topLevelAfter(cursorKey(selector.to), 1, false).length > 0,\n ];\n }\n};\n\n/** Session context, then each record's run group and tools in part order, then pending users. */\nconst collectDependencies = (\n source: TranscriptWindowSource,\n top: ReadonlyArray<TranscriptTopLevelRecord>,\n maxInlineBodyBytes: number,\n): ReadonlyArray<TranscriptRecord> => {\n const dependencies = new Map<string, TranscriptRecord>();\n const add = (record: TranscriptRecord | undefined) => {\n if (record !== undefined && !dependencies.has(record.id)) {\n dependencies.set(record.id, withBodyRefs(record, maxInlineBodyBytes));\n }\n };\n add(source.record(transcriptRecordId.session));\n for (const record of top) {\n switch (record.kind) {\n case \"assistant\": {\n if (record.runGroupId !== undefined) add(source.record(record.runGroupId));\n const partOrder = new Map(\n record.parts.flatMap((part, index) =>\n part._tag === \"ToolCall\" && part.toolId !== undefined ? [[part.toolId, index]] : [],\n ),\n );\n const tools = [...source.toolsOf(record.id)].sort(\n (left, right) =>\n (partOrder.get(left.id) ?? Number.MAX_SAFE_INTEGER) -\n (partOrder.get(right.id) ?? Number.MAX_SAFE_INTEGER) ||\n (left.id < right.id ? -1 : left.id > right.id ? 1 : 0),\n );\n tools.forEach(add);\n break;\n }\n case \"user\": {\n // The consuming run's group, or, for a submission committed at its own run's start (the\n // interrupt path, which records no run on the user), the group that owns its command.\n const runId = record.state._tag === \"Consumed\" ? record.state.runId : undefined;\n const groupId =\n (runId === undefined ? undefined : source.alias(\"runId\", runId)) ??\n source.alias(\"runCommand\", record.commandId);\n if (groupId !== undefined) add(source.record(groupId));\n break;\n }\n case \"compaction\":\n break;\n }\n }\n [...source.pendingUsers()]\n .filter(isPendingTranscriptUserRecord)\n .sort(\n (left, right) =>\n left.submittedSeq - right.submittedSeq ||\n (left.id < right.id ? -1 : left.id > right.id ? 1 : 0),\n )\n .forEach(add);\n return Array.from(dependencies.values());\n};\n\nconst encoder = new TextEncoder();\nconst encodeRecord = Schema.encodeSync(TranscriptRecordFromEnvelope);\n\nconst jsonBytes = (value: unknown): number => {\n const json = JSON.stringify(value);\n return json === undefined ? 0 : encoder.encode(json).length;\n};\n\nconst windowBytes = (\n top: ReadonlyArray<TranscriptRecord>,\n dependencies: ReadonlyArray<TranscriptRecord>,\n): number =>\n [...top, ...dependencies].reduce((total, record) => total + jsonBytes(encodeRecord(record)), 0);\n\nconst bodyRef = (body: TranscriptBody, maxInlineBodyBytes: number): TranscriptBody => {\n if (body._tag === \"Ref\") return body;\n const byteLength = jsonBytes(body.value);\n return byteLength <= maxInlineBodyBytes\n ? body\n : { _tag: \"Ref\", source: body.source, byteLength: NonNegativeInt.make(byteLength) };\n};\n\n/** Replace inline bodies above the limit with references to their immutable log source. */\nconst withBodyRefs = <R extends TranscriptRecord>(record: R, maxInlineBodyBytes: number): R => {\n switch (record.kind) {\n case \"tool\": {\n const tool: TranscriptToolRecord = {\n ...record,\n ...(record.params === undefined\n ? {}\n : { params: bodyRef(record.params, maxInlineBodyBytes) }),\n lifecycle:\n record.lifecycle._tag === \"Completed\"\n ? { _tag: \"Completed\", result: bodyRef(record.lifecycle.result, maxInlineBodyBytes) }\n : record.lifecycle,\n };\n return { ...record, ...tool };\n }\n case \"assistant\": {\n const parts = record.parts.map((part): TranscriptAssistantPart =>\n part._tag === \"ToolResult\"\n ? { ...part, result: bodyRef(part.result, maxInlineBodyBytes) }\n : part,\n );\n return { ...record, parts };\n }\n default:\n return record;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAMA,MAAM,iBAAiB,IAAI,YAAY;CACrC;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CACpF;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CACpF;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CACpF;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CACpF;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CACpF;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CACpF;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CACpF;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;CAAY;AACtF,CAAC;AAED,MAAM,eAAe,OAAe,SACjC,UAAU,OAAS,SAAU,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