effect-durable-agent 0.1.0-alpha.24 → 0.1.0-alpha.26
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/delivery-Bb7pkQ9o.js +507 -0
- package/dist/delivery-Bb7pkQ9o.js.map +1 -0
- package/dist/delivery-o6sDIiwO.d.ts +2990 -0
- package/dist/{in-memory-D8qQXNc5.js → in-memory-IgxnTbGb.js} +2 -2
- package/dist/{in-memory-D8qQXNc5.js.map → in-memory-IgxnTbGb.js.map} +1 -1
- package/dist/{interpreter-BYstFpr4.js → interpreter-BdRoYrfL.js} +83 -18
- package/dist/interpreter-BdRoYrfL.js.map +1 -0
- package/dist/services/session-store.js +3 -3
- package/dist/{subscription-g5W0Ggqx.js → subscription-Dzr5LqPX.js} +5 -3
- package/dist/subscription-Dzr5LqPX.js.map +1 -0
- package/dist/testkit/layers.d.ts +8 -2
- package/dist/testkit/layers.js +4 -0
- package/dist/testkit/layers.js.map +1 -1
- package/dist/testkit/transcript.js +2 -2
- package/dist/transcript.d.ts +24 -1
- package/dist/transcript.js +4 -4
- package/dist/websocket/events.d.ts +2 -0
- package/dist/websocket/events.js +2 -0
- package/dist/websocket.d.ts +1 -2986
- package/dist/websocket.js +3 -504
- package/dist/websocket.js.map +1 -1
- package/dist/{window-read-U55aAeuz.js → window-read-Bk7-4ALN.js} +82 -21
- package/dist/window-read-Bk7-4ALN.js.map +1 -0
- package/package.json +5 -1
- package/dist/interpreter-BYstFpr4.js.map +0 -1
- package/dist/subscription-g5W0Ggqx.js.map +0 -1
- package/dist/window-read-U55aAeuz.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"interpreter-BYstFpr4.js","names":[],"sources":["../src/transcript/version.ts","../src/transcript/mapping.ts","../src/transcript/plan.ts","../src/transcript/mapping-executor.ts","../src/transcript/interpreter.ts"],"sourcesContent":["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 *\n * History: 1 — the initial interpreter (0.1.0-alpha.22). 2 — submissions consumed by one turn are\n * ordered by submission, as the prompt orders them, not by the turn's input list.\n */\nexport const transcriptSemanticRevision = 2;\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 /**\n * An id and an ordinal; the list is kept in ordinal order. A new entry replaces every entry with\n * the same id **or** the same ordinal, so an input retried with new ids, or in a different\n * order, never leaves a stale duplicate (attachments and references keyed by both).\n */\n IdOrOrdinal: { id: MappingPath, ordinal: 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, ordinal, or either. */\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\" | \"list:IdOrOrdinal\";\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 TranscriptDecorationEntryId,\n transcriptDecorationBufferLimit,\n transcriptRecordId,\n type TranscriptBufferedDecoration,\n type TranscriptClassification,\n type TranscriptDecoration,\n type TranscriptDecorationBufferRecord,\n type TranscriptDecorationEntryKey,\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 entry = listEntryKey(operation.key, payload);\n return value === undefined || entry === undefined\n ? []\n : [\n {\n mapping,\n operation: index,\n value,\n entryKey: entry.key,\n ...(entry.id === undefined ? {} : { entryId: entry.id }),\n },\n ];\n }\n }\n};\n\nconst entryIdAt = (payload: unknown, path: TranscriptFieldPath): string | undefined => {\n const value = extract(payload, path);\n return typeof value === \"string\" && Schema.is(TranscriptDecorationEntryId)(value)\n ? value\n : undefined;\n};\n\nconst ordinalAt = (payload: unknown, path: TranscriptFieldPath): number | undefined => {\n const value = extract(payload, path);\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;\n};\n\n/** The entry's list key, and its id when the list is keyed by id or ordinal. */\nconst listEntryKey = (\n key: Extract<TranscriptMappingOperation, { readonly _tag: \"ReplaceListEntry\" }>[\"key\"],\n payload: unknown,\n): { readonly key: TranscriptDecorationEntryKey; readonly id?: string } | undefined => {\n switch (key._tag) {\n case \"Id\": {\n const id = entryIdAt(payload, key.path);\n return id === undefined ? undefined : { key: id };\n }\n case \"Ordinal\": {\n const ordinal = ordinalAt(payload, key.path);\n return ordinal === undefined ? undefined : { key: ordinal };\n }\n case \"IdOrOrdinal\": {\n const id = entryIdAt(payload, key.id);\n const ordinal = ordinalAt(payload, key.ordinal);\n return id === undefined || ordinal === undefined ? undefined : { key: ordinal, id };\n }\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 !== \"Id\",\n operation.key._tag === \"IdOrOrdinal\" ? prepared.entryId : undefined,\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 id: string | undefined,\n): TranscriptDecoration | undefined => {\n const entries = existing?._tag === \"List\" ? existing.entries : [];\n if (id !== undefined) {\n // Keyed by id or ordinal: drop every entry either one matches, then insert in ordinal order.\n const kept = entries.filter((entry) => entry.key !== key && entry.id !== id);\n if (\n kept.length === entries.length &&\n entries.length >= transcriptMappingBounds.maxListEntries\n ) {\n return undefined;\n }\n return {\n _tag: \"List\",\n entries: [...kept, { key, value, id }].sort(\n (left, right) => Number(left.key) - Number(right.key),\n ),\n };\n }\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 const consumed = new Map<TranscriptRecordId, TranscriptUserRecord>();\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 consumed.set(user.id, user);\n }\n // Submissions read by one turn share its seq; the prompt breaks the tie by each message\n // record's own seq, not by the turn's input list. That equals submission order because\n // admission writes `CommandAdmitted` and `UserMessageSubmitted` together\n // (`prepareCommandAdmission`) and every later message id for a command is consumed at its\n // commit, never here. A runtime change that breaks either assumption must revisit this key.\n const ordered = [...consumed.values()].sort(\n (left, right) =>\n left.submittedSeq - right.submittedSeq ||\n (left.id < right.id ? -1 : left.id > right.id ? 1 : 0),\n );\n for (const user of ordered) batch.put(consume(batch, user, seq, at, { runId, turnId }));\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,6BAA6B;;;;;AAM1C,MAAa,iBAAiB,UAA2B;CACvD,IAAI,UAAU,QAAQ,OAAO,UAAU,aAAa,OAAO,UAAU,UACnE,OAAO,KAAK,UAAU,KAAK;CAE7B,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GACxB,MAAM,IAAI,MAAM,iDAAiD,OAAO;EAE1E,OAAO,KAAK,UAAU,KAAK;CAC7B;CACA,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,IAAI,MAAM,IAAI,aAAa,CAAC,CAAC,KAAK,GAAG,EAAE;CAEhD,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,UAAU,OAAO,QAAQ,KAAK,CAAC,CAAC,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS;EAC/E,QAAQ,MAAM,CAAC,OAAO,CAAC,WAAY,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI,CAAE;EAC5E,OAAO,IAAI,QAAQ,KAAK,CAAC,KAAK,WAAW,GAAG,KAAK,UAAU,GAAG,EAAE,GAAG,cAAc,KAAK,GAAG,CAAC,CAAC,K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Q;GAAE;GAAK;EAAK;EAAG;CAAW;AACvD;;AAGA,MAAM,sBAAsB,cAA4D;CACtF,IAAI;EACF,MAAM,OAAO,KAAK,UAAU,SAAS;EACrC,MAAM,aAAsB,SAAS,KAAA,IAAY,KAAA,IAAY,KAAK,MAAM,IAAI;EAC5E,IAAI,OAAO,GAAG,qBAAqB,CAAC,CAAC,UAAU,GAAG,OAAO;CAC3D,QAAQ,CAER;CACA,OAAO;EAAE,UAAU,UAAU;EAAU,SAAS,UAAU;CAAQ;AACpE;;AAGA,MAAM,eAAe,UAA0C;CAC7D,IAAI;EACF,MAAM,OAAO,KAAK,UAAU,KAAK;EACjC,MAAM,aAAsB,SAAS,KAAA,IAAY,KAAA,IAAY,KAAK,MAAM,IAAI;EAC5E,IAAI,OAAO,GAAG,cAAc,CAAC,CAAC,UAAU,GAAG,OAAO;CACpD,QAAQ,CAER;CACA,OAAO;EAAE,SAAS,MAAM;EAAS,GAAI,MAAM,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,MAAM,KAAK;CAAG;AAC7F;AAEA,MAAM,eACJ,OACA,MAC8B,CAAC,EAAE,MAAM,EAAE,GAAG,GAAG,MAAM,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"subscription-g5W0Ggqx.js","names":["PositiveInt"],"sources":["../src/transcript/window.ts","../src/transcript/subscription.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { NonNegativeInt } from \"../types/events/envelope\";\nimport {\n InferenceAssistantRecordId,\n TranscriptAssistantPart,\n TranscriptCursor,\n TranscriptLogIncarnation,\n TranscriptOrder,\n TranscriptRecordViewFromEnvelope,\n isPendingTranscriptUserRecord,\n isTopLevelTranscriptRecord,\n TranscriptVersion,\n type TranscriptOrderKey,\n type TranscriptRecordView,\n} from \"./records\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\n\nconst orderKeyOfCursor = (cursor: TranscriptCursor): TranscriptOrderKey => ({\n anchorSeq: cursor.anchorSeq,\n ordinal: cursor.ordinal,\n recordId: cursor.recordId,\n});\n\n/**\n * Which slice of history to read.\n *\n * `Latest` serves first paint (SSR, CLIs); `Page` walks either direction from a cursor;\n * `Range` re-reads exactly the span a client retains, inclusive of both ends, at one new cut.\n */\nexport const TranscriptWindowSelector = Schema.Union([\n Schema.TaggedStruct(\"Latest\", { count: PositiveInt }),\n Schema.TaggedStruct(\"Page\", {\n direction: Schema.Literals([\"before\", \"after\"]),\n cursor: TranscriptCursor,\n count: PositiveInt,\n }),\n Schema.TaggedStruct(\"Range\", { from: TranscriptCursor, to: TranscriptCursor }).check(\n Schema.makeFilter(\n (range) =>\n (range.from.incarnation === range.to.incarnation &&\n range.from.version === range.to.version) ||\n \"a range is scoped to one incarnation and version\",\n ),\n Schema.makeFilter(\n (range) =>\n TranscriptOrder(orderKeyOfCursor(range.from), orderKeyOfCursor(range.to)) <= 0 ||\n \"a range starts at or before its end\",\n ),\n ),\n]);\nexport type TranscriptWindowSelector = typeof TranscriptWindowSelector.Type;\n\n/**\n * Bounds on one window. `maxRecords` caps top-level records (a selector's `count` is further\n * capped by it); `maxBytes` caps the whole response, dependencies included; bodies above\n * `maxInlineBodyBytes` are sent as references.\n */\nexport const TranscriptWindowLimits = Schema.Struct({\n maxRecords: PositiveInt,\n maxBytes: PositiveInt,\n maxInlineBodyBytes: NonNegativeInt,\n});\nexport type TranscriptWindowLimits = typeof TranscriptWindowLimits.Type;\n\n/** Default bounds: the first window holds 100 top-level records (design decision 4). */\nexport const defaultTranscriptWindowLimits: TranscriptWindowLimits = {\n maxRecords: 100,\n maxBytes: 1_048_576,\n maxInlineBodyBytes: 16_384,\n};\n\n/**\n * Whether the window is the current interpretation of the log, and if not, why its cut is\n * behind.\n *\n * Every state other than `Ready` is a degraded read and obeys one rule: the response contains\n * nothing newer than `throughSeq` — no newer pending users, session context or live content.\n */\nconst KnownReadiness = Schema.TaggedUnion({\n /** The active version is healthy and projected through the log head at read time. */\n Ready: {},\n /** The active version failed while projecting `failedAtSeq`; this is its last good cut. */\n Degraded: { failedAtSeq: SequenceNumber, error: Schema.String },\n /**\n * The active version is no longer carried by this release; history is being rebuilt under\n * the current definition, and clients receive one replacement when it activates.\n */\n UpdatingHistory: {},\n /** No version is servable yet; the window is empty. */\n Building: {},\n /**\n * A stored row of the served version cannot be decoded by this release. Nothing is served\n * until a rebuild finishes, rather than a wrong view; the window is empty.\n */\n Unreadable: { error: Schema.String },\n /** A readiness this reader does not know; treated as degraded. */\n Unknown: { readinessType: Schema.String },\n});\n\nconst knownReadinessTags: ReadonlySet<string> = new Set([\n \"Ready\",\n \"Degraded\",\n \"UpdatingHistory\",\n \"Building\",\n \"Unreadable\",\n \"Unknown\",\n]);\n\nconst UnrecognizedReadiness = Schema.Struct({\n _tag: Schema.String.check(\n Schema.makeFilter(\n (tag) => !knownReadinessTags.has(tag) || \"a known readiness must decode as that readiness\",\n ),\n ),\n}).pipe(\n Schema.decodeTo(Schema.toType(KnownReadiness.cases.Unknown), {\n decode: SchemaGetter.transform((readiness) => ({\n _tag: \"Unknown\" as const,\n readinessType: readiness._tag,\n })),\n encode: SchemaGetter.transform((readiness) => ({ _tag: readiness.readinessType })),\n }),\n);\n\n/**\n * Whether the window is the current interpretation of the log. A readiness this reader does not\n * know decodes as `Unknown` and is treated as degraded: it carries no live content. A malformed\n * readiness with a known tag is a decode failure.\n */\nexport const TranscriptReadiness = Schema.Union([KnownReadiness, UnrecognizedReadiness]);\nexport type TranscriptReadiness = typeof TranscriptReadiness.Type;\n\n/**\n * One live part of the inference streaming now.\n *\n * `id` is stable for the life of the part (`text:<providerPartId>`, `reasoning:<providerPartId>`,\n * `tool:<toolCallId>`), so a client keys a streaming part by it and replaces it in place as it\n * grows. `paramsText` is the tool-call parameter text streamed so far; it is speculative until\n * the call is sealed into a tool record.\n */\nexport const TranscriptActivePart = Schema.Struct({\n id: Schema.NonEmptyString,\n part: TranscriptAssistantPart,\n paramsText: Schema.optionalKey(Schema.String),\n}).check(\n Schema.makeFilter(\n (active) =>\n (active.part._tag === \"Text\"\n ? active.id.startsWith(\"text:\")\n : active.part._tag === \"Reasoning\"\n ? active.id.startsWith(\"reasoning:\")\n : active.part._tag === \"ToolCall\"\n ? active.id.startsWith(\"tool:\")\n : true) || \"a live part's id names its kind\",\n ),\n Schema.makeFilter(\n (active) =>\n active.paramsText === undefined ||\n active.part._tag === \"ToolCall\" ||\n \"only a tool call streams parameter text\",\n ),\n);\nexport type TranscriptActivePart = typeof TranscriptActivePart.Type;\n\n/**\n * Accumulated parts of the inference streaming now, captured at the same publication boundary as\n * the window. Owned by the live runtime; storage-level reads never include it.\n */\nexport const TranscriptActiveContent = Schema.Struct({\n assistantId: InferenceAssistantRecordId,\n parts: Schema.Array(TranscriptActivePart),\n});\nexport type TranscriptActiveContent = typeof TranscriptActiveContent.Type;\n\nconst recordUpdatedSeq = (record: TranscriptRecordView): number => record.updatedSeq;\n\nconst recordPosition = (record: TranscriptRecordView) =>\n \"position\" in record ? record.position : undefined;\n\n/** Positioned history, which is served only as a top-level record and never as a dependency. */\nconst isHistoryRecord = (record: TranscriptRecordView): boolean =>\n record.kind === \"unknown\" ? record.position !== undefined : isTopLevelTranscriptRecord(record);\n\n/**\n * One complete, consistent read of a transcript version.\n *\n * `records` are top-level records in transcript order; `dependencies` are the tools and run\n * groups they reference, the session context, and every pending user record. Every record is\n * projected through `throughSeq` and none is newer, which is what makes a cut complete. A client\n * replaces, never merges, what a window covers.\n */\nexport const TranscriptWindow = Schema.Struct({\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n throughSeq: SequenceNumber,\n records: Schema.Array(TranscriptRecordViewFromEnvelope),\n dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),\n activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),\n hasOlder: Schema.Boolean,\n hasNewer: Schema.Boolean,\n readiness: TranscriptReadiness,\n}).check(\n Schema.makeFilter(\n (window) =>\n [...window.records, ...window.dependencies].every(\n (record) => recordUpdatedSeq(record) <= window.throughSeq,\n ) || \"every record must be projected through throughSeq and none may be newer\",\n ),\n Schema.makeFilter(\n (window) =>\n window.readiness._tag === \"Ready\" ||\n window.activeContent === undefined ||\n \"a degraded read never attaches live content\",\n ),\n Schema.makeFilter(\n (window) =>\n window.readiness._tag !== \"Degraded\" ||\n window.readiness.failedAtSeq > window.throughSeq ||\n \"a degraded cut ends before the seq that failed\",\n ),\n Schema.makeFilter(\n (window) =>\n [...window.records, ...window.dependencies].every(\n (record) =>\n record.kind !== \"decorationBuffer\" &&\n (record.kind !== \"unknown\" || record.originalKind !== \"decorationBuffer\"),\n ) || \"decoration buffers are never served\",\n ),\n Schema.makeFilter((window) => {\n const ids = [...window.records, ...window.dependencies].map((record) => record.id);\n return new Set(ids).size === ids.length || \"a record is served at most once\";\n }),\n Schema.makeFilter(\n (window) =>\n window.records.every((record, index) => {\n const position = recordPosition(record);\n if (position === undefined || !isHistoryRecord(record)) return false;\n const previous = index === 0 ? undefined : window.records[index - 1];\n const previousPosition = previous === undefined ? undefined : recordPosition(previous);\n return (\n previous === undefined ||\n previousPosition === undefined ||\n TranscriptOrder(\n { ...previousPosition, recordId: previous.id },\n { ...position, recordId: record.id },\n ) < 0\n );\n }) || \"records are positioned history records in transcript order\",\n ),\n Schema.makeFilter(\n (window) =>\n window.dependencies.every((record) => !isHistoryRecord(record)) ||\n \"dependencies never contain history records\",\n ),\n Schema.makeFilter(\n (window) =>\n window.dependencies.every(\n (record) => record.kind !== \"user\" || isPendingTranscriptUserRecord(record),\n ) || \"the only user dependencies are pending users; cancelled users are never served\",\n ),\n Schema.makeFilter(\n (window) =>\n (window.readiness._tag !== \"Building\" && window.readiness._tag !== \"Unreadable\") ||\n (window.records.length === 0 &&\n window.dependencies.length === 0 &&\n !window.hasOlder &&\n !window.hasNewer) ||\n \"a building or unreadable window is empty\",\n ),\n);\nexport type TranscriptWindow = typeof TranscriptWindow.Type;\n\n/** Paging cursor for one top-level record of a window. */\nexport const transcriptCursorOf = (\n window: Pick<TranscriptWindow, \"incarnation\" | \"version\">,\n record: TranscriptRecordView,\n): TranscriptCursor | undefined => {\n const position = \"position\" in record ? record.position : undefined;\n return position === undefined\n ? undefined\n : {\n incarnation: window.incarnation,\n version: window.version,\n anchorSeq: position.anchorSeq,\n ordinal: position.ordinal,\n recordId: record.id,\n };\n};\n\n/** Health of one stored transcript version. A failed version is frozen at its last good cursor. */\nexport const TranscriptVersionStatus = Schema.TaggedUnion({\n Ok: {},\n Failed: { failedAtSeq: SequenceNumber, error: Schema.String },\n});\nexport type TranscriptVersionStatus = typeof TranscriptVersionStatus.Type;\n\n/**\n * Per-version maintenance state, one per version present in a session's storage.\n *\n * `cursor` is the last fully projected seq, committed together with that version's rows. At most\n * one version is `active` (served) and at most one is `building` (catching up from the log).\n */\nexport const TranscriptVersionMeta = Schema.Struct({\n version: TranscriptVersion,\n role: Schema.Literals([\"active\", \"building\"]),\n cursor: SequenceNumber,\n status: TranscriptVersionStatus,\n}).check(\n Schema.makeFilter(\n (meta) =>\n meta.status._tag !== \"Failed\" ||\n meta.status.failedAtSeq > meta.cursor ||\n \"a failed version is frozen before the seq that failed\",\n ),\n);\nexport type TranscriptVersionMeta = typeof TranscriptVersionMeta.Type;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { EDASessionStoreError } from \"../services/session-store\";\nimport {\n TranscriptCursor,\n TranscriptLogIncarnation,\n TranscriptOrder,\n TranscriptRecordViewFromEnvelope,\n TranscriptVersion,\n type TranscriptOrderKey,\n type TranscriptRecordView,\n} from \"./records\";\nimport type { EDATranscriptStoreShape, TranscriptCursorMismatch } from \"./store\";\nimport {\n TranscriptActiveContent,\n TranscriptReadiness,\n transcriptCursorOf,\n type TranscriptWindow,\n type TranscriptWindowLimits,\n type TranscriptWindowSelector,\n} from \"./window\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\n\n/** Client-chosen correlation id echoed on the update that answers a request. */\nexport const TranscriptRequestId = Schema.NonEmptyString.check(Schema.isMaxLength(64));\nexport type TranscriptRequestId = typeof TranscriptRequestId.Type;\n\n/**\n * The contiguous span of top-level records a subscriber holds, both ends inclusive. Absent when\n * the subscriber holds no top-level records (an empty session, or a window still building).\n */\nexport const TranscriptCoverage = Schema.Struct({\n from: TranscriptCursor,\n to: TranscriptCursor,\n});\nexport type TranscriptCoverage = typeof TranscriptCoverage.Type;\n\n/**\n * What a subscriber holds after its last complete update: the cut it was read at and the span it\n * covers. Every update is planned relative to this base, which is also persisted with the socket\n * so a hibernated subscription resumes without volatile state.\n *\n * `tail` is true when the coverage reaches the newest record of its cut; new history then joins\n * the coverage as it is committed. A subscriber that paged back past the tail sees `hasNewer`\n * instead and pages forward to rejoin it.\n */\nexport const TranscriptSubscriptionBase = Schema.Struct({\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n throughSeq: SequenceNumber,\n coverage: Schema.optionalKey(TranscriptCoverage),\n tail: Schema.Boolean,\n});\nexport type TranscriptSubscriptionBase = typeof TranscriptSubscriptionBase.Type;\n\n/**\n * One ordered, complete change to a subscriber's window: the only way a live client's window\n * changes.\n *\n * - `replace` discards everything the client holds and installs this window.\n * - `patch` is relative to the client's previous complete update: `records` and `dependencies`\n * carry every record that changed or newly entered the window, `dependencyIds` lists the\n * complete dependency membership of the new cut (the client drops any other dependency), and\n * the client drops top-level records outside `coverage`.\n *\n * Either way the client ends at exactly the window read at `throughSeq`: a complete cut. When\n * present, `activeContent` replaces the client's active content completely (an empty array\n * clears it); when absent, active content is unchanged. A degraded update carries no live\n * content, and a client shows none while readiness is not `Ready`.\n */\nexport const TranscriptUpdate = Schema.Struct({\n updateSeq: PositiveInt,\n mode: Schema.Literals([\"replace\", \"patch\"]),\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n throughSeq: SequenceNumber,\n coverage: Schema.optionalKey(TranscriptCoverage),\n hasOlder: Schema.Boolean,\n hasNewer: Schema.Boolean,\n readiness: TranscriptReadiness,\n records: Schema.Array(TranscriptRecordViewFromEnvelope),\n dependencies: Schema.Array(TranscriptRecordViewFromEnvelope),\n dependencyIds: Schema.Array(Schema.NonEmptyString),\n activeContent: Schema.optionalKey(Schema.Array(TranscriptActiveContent)),\n requestId: Schema.optionalKey(TranscriptRequestId),\n}).check(\n Schema.makeFilter(\n (update) =>\n [...update.records, ...update.dependencies].every(\n (record) => record.updatedSeq <= update.throughSeq,\n ) || \"every record must be projected through throughSeq and none may be newer\",\n ),\n Schema.makeFilter(\n (update) =>\n update.readiness._tag === \"Ready\" ||\n update.activeContent === undefined ||\n update.activeContent.length === 0 ||\n \"a degraded update never carries live content\",\n ),\n Schema.makeFilter((update) => {\n const dependencyIds = new Set(update.dependencyIds);\n return (\n update.dependencies.every((record) => dependencyIds.has(record.id)) ||\n \"every sent dependency is a member of the cut\"\n );\n }),\n);\nexport type TranscriptUpdate = typeof TranscriptUpdate.Type;\n\n/** Bounds of one subscription. Retained coverage never exceeds `limits.maxRecords`. */\nexport interface TranscriptSubscriptionPolicy {\n /** Top-level records of a fresh subscription (design decision 4). */\n readonly initialCount: number;\n /** Largest page a client may request at once. */\n readonly maxPageCount: number;\n readonly limits: TranscriptWindowLimits;\n}\n\nexport const defaultTranscriptSubscriptionPolicy: TranscriptSubscriptionPolicy = {\n initialCount: 100,\n maxPageCount: 100,\n limits: { maxRecords: 300, maxBytes: 2 * 1_048_576, maxInlineBodyBytes: 16_384 },\n};\n\n/** A subscriber's request, decoded from its socket and handled strictly in arrival order. */\nexport type TranscriptSubscriptionRequest =\n /** Re-read the held coverage at a new cut, after committed changes. */\n | { readonly _tag: \"Refresh\" }\n /**\n * Start (or restart) a subscription. With `range` and `since` (what SSR rendered, or what a\n * reconnecting client last applied), the first update is a patch over that range; otherwise\n * it is a replacement of the latest `count` records.\n */\n | {\n readonly _tag: \"Subscribe\";\n readonly range?: TranscriptCoverage;\n readonly tail: boolean;\n readonly since?: SequenceNumber;\n readonly count?: number;\n }\n /** Extend the coverage by `count` records from its `before` or `after` edge. */\n | {\n readonly _tag: \"Page\";\n readonly direction: \"before\" | \"after\";\n readonly cursor: TranscriptCursor;\n readonly count: number;\n }\n /** Narrow the coverage to a span inside it, releasing the rest. */\n | { readonly _tag: \"Retain\"; readonly from: TranscriptCursor; readonly to: TranscriptCursor };\n\n/** One window read at a single cut, and the base the update for it is relative to. */\nexport interface TranscriptSubscriptionRead {\n readonly window: TranscriptWindow;\n /** What the client holds; `undefined` makes the update a replacement. */\n readonly patchBase: TranscriptSubscriptionBase | undefined;\n}\n\nconst orderKey = (cursor: TranscriptCursor): TranscriptOrderKey => ({\n anchorSeq: cursor.anchorSeq,\n ordinal: cursor.ordinal,\n recordId: cursor.recordId,\n});\n\nconst sameCursor = (left: TranscriptCursor, right: TranscriptCursor): boolean =>\n left.incarnation === right.incarnation &&\n left.version === right.version &&\n TranscriptOrder(orderKey(left), orderKey(right)) === 0;\n\n/**\n * A cursor after every possible record of one version, so a `Range` ending at it reads from a\n * point to the newest record. Never sent to clients.\n */\nconst tailCursor = (from: TranscriptCursor): TranscriptCursor => ({\n incarnation: from.incarnation,\n version: from.version,\n anchorSeq: SequenceNumber.make(Number.MAX_SAFE_INTEGER),\n ordinal: Number.MAX_SAFE_INTEGER,\n recordId: \"\",\n});\n\n/** The span a window's top-level records cover, or `undefined` when it has none. */\nexport const transcriptCoverageOf = (window: TranscriptWindow): TranscriptCoverage | undefined => {\n const first = window.records[0];\n const last = window.records[window.records.length - 1];\n const from = first === undefined ? undefined : transcriptCursorOf(window, first);\n const to = last === undefined ? undefined : transcriptCursorOf(window, last);\n return from === undefined || to === undefined ? undefined : { from, to };\n};\n\nconst withinCoverage = (\n coverage: TranscriptCoverage | undefined,\n record: TranscriptRecordView,\n): boolean => {\n if (coverage === undefined || !(\"position\" in record) || record.position === undefined) {\n return false;\n }\n const key = { ...record.position, recordId: record.id };\n return (\n TranscriptOrder(orderKey(coverage.from), key) <= 0 &&\n TranscriptOrder(key, orderKey(coverage.to)) <= 0\n );\n};\n\n/** The base a client holds after applying an update for `window`. */\nexport const transcriptSubscriptionBaseOf = (\n window: TranscriptWindow,\n): TranscriptSubscriptionBase => {\n const coverage = transcriptCoverageOf(window);\n return {\n incarnation: window.incarnation,\n version: window.version,\n throughSeq: window.throughSeq,\n ...(coverage === undefined ? {} : { coverage }),\n tail: !window.hasNewer,\n };\n};\n\n/**\n * Plan the one update that moves a client from `patchBase` to `window`.\n *\n * A patch sends a top-level record when it changed after the base cut or was outside the base\n * coverage. It sends a tool dependency when the tool changed or its assistant is sent, and any\n * other dependency (run groups, session context, pending users) when it changed or any top-level\n * record is sent. Everything else the client already holds unchanged from the base cut, because\n * the base cut was itself complete. A different incarnation or version, or a base cut ahead of\n * the window, makes the update a replacement.\n */\nexport const planTranscriptUpdate = (input: {\n readonly patchBase: TranscriptSubscriptionBase | undefined;\n readonly window: TranscriptWindow;\n readonly updateSeq: number;\n /** The live content captured at the same publication boundary as `window`. */\n readonly activeContent: ReadonlyArray<TranscriptActiveContent>;\n /**\n * Whether the client's active content must be replaced. A replacement always carries it;\n * otherwise the caller sends it only when it changed since its last send.\n */\n readonly includeActiveContent: boolean;\n readonly requestId?: TranscriptRequestId;\n}): TranscriptUpdate => {\n const { window } = input;\n const base = input.patchBase;\n const patch =\n base !== undefined &&\n base.incarnation === window.incarnation &&\n base.version === window.version &&\n base.throughSeq <= window.throughSeq;\n const records = patch\n ? window.records.filter(\n (record) => record.updatedSeq > base.throughSeq || !withinCoverage(base.coverage, record),\n )\n : window.records;\n const sentIds = new Set(records.map((record) => record.id));\n const dependencies = patch\n ? window.dependencies.filter(\n (record) =>\n record.updatedSeq > base.throughSeq ||\n (record.kind === \"tool\" ? sentIds.has(record.assistantId) : records.length > 0),\n )\n : window.dependencies;\n const coverage = transcriptCoverageOf(window);\n const activeContent =\n patch && !input.includeActiveContent\n ? undefined\n : servedActiveContent(window, input.activeContent);\n return {\n updateSeq: input.updateSeq,\n mode: patch ? \"patch\" : \"replace\",\n incarnation: window.incarnation,\n version: window.version,\n throughSeq: window.throughSeq,\n ...(coverage === undefined ? {} : { coverage }),\n hasOlder: window.hasOlder,\n hasNewer: window.hasNewer,\n readiness: window.readiness,\n records,\n dependencies,\n dependencyIds: window.dependencies.map((record) => record.id),\n ...(activeContent === undefined ? {} : { activeContent }),\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n };\n};\n\n/**\n * Live content as served with a window: none on a degraded read, and never for an inference the\n * window already shows as committed or failed, so a stale live part cannot override a terminal.\n */\nconst servedActiveContent = (\n window: TranscriptWindow,\n activeContent: ReadonlyArray<TranscriptActiveContent>,\n): ReadonlyArray<TranscriptActiveContent> => {\n if (window.readiness._tag !== \"Ready\") return [];\n const settled = new Set(\n window.records.flatMap((record) =>\n record.kind === \"assistant\" && record.lifecycle._tag !== \"Streaming\" ? [record.id] : [],\n ),\n );\n return activeContent.filter((content) => !settled.has(content.assistantId));\n};\n\n/**\n * Read the window that answers one request, at one cut.\n *\n * Helper reads (to find a page's far edge) may see other cuts; only the final read is served,\n * so the update is always one synchronous read. Coverage stays within `limits.maxRecords`:\n * paging back evicts the newest records, paging forward evicts the oldest, and a tail that\n * outgrows the bound keeps its newest records. A cursor minted for another incarnation or version\n * falls back to a replacement of the latest records.\n */\nexport const readTranscriptSubscription = (\n store: EDATranscriptStoreShape,\n base: TranscriptSubscriptionBase | undefined,\n request: TranscriptSubscriptionRequest,\n policy: TranscriptSubscriptionPolicy,\n): Effect.Effect<TranscriptSubscriptionRead, EDASessionStoreError> => {\n const read = (selector: TranscriptWindowSelector) =>\n store.readTranscriptWindow(selector, policy.limits);\n const latest = read({\n _tag: \"Latest\",\n count: Math.min(policy.initialCount, policy.limits.maxRecords),\n }).pipe(Effect.map((window) => ({ window, patchBase: undefined })));\n\n const readCoverage = Effect.fnUntraced(function* (\n coverage: TranscriptCoverage | undefined,\n tail: boolean,\n overflowToNewest: boolean,\n ) {\n if (coverage === undefined) {\n return yield* read({\n _tag: \"Latest\",\n count: Math.min(policy.initialCount, policy.limits.maxRecords),\n });\n }\n if (!tail) return yield* read({ _tag: \"Range\", ...coverage });\n const window = yield* read({\n _tag: \"Range\",\n from: coverage.from,\n to: tailCursor(coverage.from),\n });\n // The span outgrew the bound: keep as many of its newest records as the Range read held.\n return window.hasNewer && overflowToNewest\n ? yield* read({ _tag: \"Latest\", count: Math.max(1, window.records.length) })\n : window;\n });\n\n const handle = Effect.fnUntraced(function* () {\n switch (request._tag) {\n case \"Subscribe\": {\n const count = Math.min(request.count ?? policy.initialCount, policy.limits.maxRecords);\n if (request.range === undefined) {\n const window = yield* read({ _tag: \"Latest\", count });\n return { window, patchBase: undefined };\n }\n const claimed: TranscriptSubscriptionBase = {\n incarnation: request.range.from.incarnation,\n version: request.range.from.version,\n throughSeq: request.since ?? SequenceNumber.make(0),\n coverage: request.range,\n tail: request.tail,\n };\n const window = yield* readCoverage(request.range, request.tail, true);\n return { window, patchBase: request.since === undefined ? undefined : claimed };\n }\n case \"Refresh\": {\n if (base === undefined) return yield* latest;\n const window = yield* readCoverage(base.coverage, base.tail, true);\n return { window, patchBase: base };\n }\n case \"Page\": {\n const coverage = base?.coverage;\n const edge = request.direction === \"before\" ? coverage?.from : coverage?.to;\n if (base === undefined || coverage === undefined || edge === undefined) {\n return base === undefined\n ? yield* latest\n : { window: yield* readCoverage(base.coverage, base.tail, true), patchBase: base };\n }\n if (!sameCursor(edge, request.cursor)) {\n return { window: yield* readCoverage(coverage, base.tail, true), patchBase: base };\n }\n const page = yield* read({\n _tag: \"Page\",\n direction: request.direction,\n cursor: request.cursor,\n count: Math.min(request.count, policy.maxPageCount, policy.limits.maxRecords),\n });\n const first = page.records[0];\n const last = page.records[page.records.length - 1];\n const pageFrom = first === undefined ? undefined : transcriptCursorOf(page, first);\n const pageTo = last === undefined ? undefined : transcriptCursorOf(page, last);\n if (pageFrom === undefined || pageTo === undefined) {\n return { window: yield* readCoverage(coverage, base.tail, true), patchBase: base };\n }\n if (request.direction === \"before\") {\n // A Range keeps its oldest records when it is over a bound, evicting the newest.\n const window = yield* readCoverage({ from: pageFrom, to: coverage.to }, base.tail, false);\n return { window, patchBase: base };\n }\n const from = yield* evictOldest(read, coverage.from, pageTo, policy.limits.maxRecords);\n const window = yield* readCoverage({ from, to: pageTo }, !page.hasNewer, false);\n return { window, patchBase: base };\n }\n case \"Retain\": {\n const coverage = base?.coverage;\n if (base === undefined || coverage === undefined) {\n return base === undefined\n ? yield* latest\n : { window: yield* readCoverage(base.coverage, base.tail, true), patchBase: base };\n }\n const inside =\n request.from.incarnation === base.incarnation &&\n request.from.version === base.version &&\n request.to.incarnation === base.incarnation &&\n request.to.version === base.version &&\n TranscriptOrder(orderKey(coverage.from), orderKey(request.from)) <= 0 &&\n TranscriptOrder(orderKey(request.from), orderKey(request.to)) <= 0 &&\n TranscriptOrder(orderKey(request.to), orderKey(coverage.to)) <= 0;\n const retained = inside ? { from: request.from, to: request.to } : coverage;\n const tail = base.tail && sameCursor(retained.to, coverage.to);\n return { window: yield* readCoverage(retained, tail, true), patchBase: base };\n }\n }\n });\n\n // A Latest read names no cursor, so it cannot mismatch.\n return handle().pipe(\n Effect.catchTag(\"TranscriptCursorMismatch\", () =>\n latest.pipe(Effect.catchTag(\"TranscriptCursorMismatch\", Effect.die)),\n ),\n );\n};\n\n/**\n * The oldest cursor a span ending at `to` may start from without exceeding `maxRecords`: the\n * current `from`, or later when the span would be over the bound.\n */\nconst evictOldest = Effect.fnUntraced(function* (\n read: (\n selector: TranscriptWindowSelector,\n ) => Effect.Effect<TranscriptWindow, EDASessionStoreError | TranscriptCursorMismatch>,\n from: TranscriptCursor,\n to: TranscriptCursor,\n maxRecords: number,\n) {\n if (maxRecords <= 1) return to;\n const before = yield* read({\n _tag: \"Page\",\n direction: \"before\",\n cursor: to,\n count: maxRecords - 1,\n });\n const first = before.records[0];\n const oldest = first === undefined ? undefined : transcriptCursorOf(before, first);\n return oldest === undefined || TranscriptOrder(orderKey(oldest), orderKey(from)) <= 0\n ? from\n : oldest;\n});\n"],"mappings":";;;;;;;AAmBA,MAAMA,gBAAc,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;AAErE,MAAM,oBAAoB,YAAkD;CAC1E,WAAW,OAAO;CAClB,SAAS,OAAO;CAChB,UAAU,OAAO;AACnB;;;;;;;AAQA,MAAa,2BAA2B,OAAO,MAAM;CACnD,OAAO,aAAa,UAAU,EAAE,OAAOA,cAAY,CAAC;CACpD,OAAO,aAAa,QAAQ;EAC1B,WAAW,OAAO,SAAS,CAAC,UAAU,OAAO,CAAC;EAC9C,QAAQ;EACR,OAAOA;CACT,CAAC;CACD,OAAO,aAAa,SAAS;EAAE,MAAM;EAAkB,IAAI;CAAiB,CAAC,CAAC,CAAC,MAC7E,OAAO,YACJ,UACE,MAAM,KAAK,gBAAgB,MAAM,GAAG,eACnC,MAAM,KAAK,YAAY,MAAM,GAAG,WAClC,kDACJ,GACA,OAAO,YACJ,UACC,gBAAgB,iBAAiB,MAAM,IAAI,GAAG,iBAAiB,MAAM,EAAE,CAAC,KAAK,KAC7E,qCACJ,CACF;AACF,CAAC;;;;;;AAQD,MAAa,yBAAyB,OAAO,OAAO;CAClD,YAAYA;CACZ,UAAUA;CACV,oBAAoB;AACtB,CAAC;;AAID,MAAa,gCAAwD;CACnE,YAAY;CACZ,UAAU;CACV,oBAAoB;AACtB;;;;;;;;AASA,MAAM,iBAAiB,OAAO,YAAY;;CAExC,OAAO,CAAC;;CAER,UAAU;EAAE,aAAa;EAAgB,OAAO,OAAO;CAAO;;;;;CAK9D,iBAAiB,CAAC;;CAElB,UAAU,CAAC;;;;;CAKX,YAAY,EAAE,OAAO,OAAO,OAAO;;CAEnC,SAAS,EAAE,eAAe,OAAO,OAAO;AAC1C,CAAC;AAED,MAA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AM,QAAQ,OAAO,QAAQ;CAC7B,MAAM,SAAS,UAAU,KAAA,IAAY,KAAA,IAAY,mBAAmB,QAAQ,KAAK;CACjF,OAAO,WAAW,KAAA,KAAa,gBAAgB,SAAS,MAAM,GAAG,SAAS,IAAI,CAAC,KAAK,IAChF,OACA;AACN,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"window-read-U55aAeuz.js","names":[],"sources":["../src/transcript/store.ts","../src/transcript/window-read.ts"],"sourcesContent":["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":";;;;;;;;AA0BA,IAAa,2BAAb,cAA8C,OAAO,YAAsC,CAAC,CAC1F,4BACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;;AAwBH,IAAa,qBAAb,cAAwC,QAAQ,QAG9C,CAAC,CAAC,0CAA0C,CAAC,CAAC,CAAC;;;;ACajD,MAAa,uBACX,MACA,YACwB;CACxB,IAAI,CAAC,SAAS,OAAO,EAAE,MAAM,kBAAkB;CAC/C,QAAQ,KAAK,OAAO,MAApB;EACE,KAAK,MACH,OAAO,EAAE,MAAM,QAAQ;EACzB,KAAK,UACH,OAAO;GACL,MAAM;GACN,aAAa,KAAK,OAAO;GACzB,OAAO,KAAK,OAAO;EACrB;CACJ;AACF;;AAGA,MAAa,4BACX,aACA,aACsB;CACtB;CACA;CACA,YAAY,eAAe,KAAK,CAAC;CACjC,SAAS,CAAC;CACV,cAAc,CAAC;CACf,UAAU;CACV,UAAU;CACV,WAAW,EAAE,MAAM,WAAW;AAChC;AAEA,MAAM,YAAY,YAA0D;CAC1E,WAAW,OAAO,UAAU,aAAa;CACzC,SAAS,OAAO,UAAU,WAAW;CACrC,UAAU,OAAO;AACnB;AAEA,MAAM,aAAa,YAAkD;CACnE,WAAW,OAAO;CAClB,SAAS,OAAO;CAChB,UAAU,OAAO;AACnB;;;;;;;;;;AAWA,MAAa,4BACX,QACA,UACA,WAC8D;CAC9D,MAAM,UAAU,OAAO,KAAK;CAC5B,KAAK,MAAM,UAAU,gBAAgB,QAAQ,GAC3C,IAAI,OAAO,gBAAgB,OAAO,eAAe,OAAO,YAAY,SAClE,OAAO,O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