effect-durable-agent 0.1.0-alpha.21 → 0.1.0-alpha.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +2 -2
  2. package/dist/assert-never-CoyUpoRB.js +18 -0
  3. package/dist/assert-never-CoyUpoRB.js.map +1 -0
  4. package/dist/domain/command-queues.d.ts +1 -1
  5. package/dist/domain/message-transcript.d.ts +1 -1
  6. package/dist/domain/reduced-state.d.ts +1 -1
  7. package/dist/domain/reduced-state.js +927 -2
  8. package/dist/domain/reduced-state.js.map +1 -0
  9. package/dist/domain/run-scheduling.d.ts +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/records-DWKEjuqb.js +675 -0
  12. package/dist/records-DWKEjuqb.js.map +1 -0
  13. package/dist/{reduced-state-BGd_yCBT.d.ts → reduced-state-B5WxKSM5.d.ts} +6 -6
  14. package/dist/{reducer-registry-BIhncOHH.d.ts → reducer-registry-CPObI3cs.d.ts} +2 -2
  15. package/dist/{run-scheduling-wakeup-BH2pHE0U.d.ts → run-scheduling-wakeup-B19JTeyq.d.ts} +2 -2
  16. package/dist/services/compaction.d.ts +1 -1
  17. package/dist/services/model-call.d.ts +1 -1
  18. package/dist/services/prompt-projector.d.ts +1 -1
  19. package/dist/services/reducer-registry.d.ts +1 -1
  20. package/dist/services/reducer-registry.js +1 -1
  21. package/dist/services/run-scheduler.d.ts +1 -1
  22. package/dist/services/run-scheduling-wakeup.d.ts +1 -1
  23. package/dist/services/runtime-layer.d.ts +6 -6
  24. package/dist/services/runtime-layer.js +3 -3
  25. package/dist/services/runtime.d.ts +1 -1
  26. package/dist/services/runtime.js +1 -1
  27. package/dist/services/session-query.d.ts +1 -1
  28. package/dist/services/session-query.js +2 -2
  29. package/dist/services/session-state.d.ts +1 -1
  30. package/dist/services/session-state.js +1 -1
  31. package/dist/services/session-store.d.ts +2 -2
  32. package/dist/services/session-store.js +1 -251
  33. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  34. package/dist/services/sink-registry.d.ts +1 -1
  35. package/dist/services/sink-registry.js +1 -1
  36. package/dist/services/tool-registry.d.ts +1 -1
  37. package/dist/{session-state-C_1XxhvE.js → session-state-C6SyphC0.js} +5 -4
  38. package/dist/{session-state-C_1XxhvE.js.map → session-state-C6SyphC0.js.map} +1 -1
  39. package/dist/session-store-CWYZ29CV.d.ts +3302 -0
  40. package/dist/session-store-DuEhcqIC.js +414 -0
  41. package/dist/session-store-DuEhcqIC.js.map +1 -0
  42. package/dist/{sink-checkpoint-store-C-SY0cG2.d.ts → sink-checkpoint-store-B8Ky5nfW.d.ts} +2 -2
  43. package/dist/{sink-registry-CjK5MC90.js → sink-registry-DtrssBxF.js} +3 -3
  44. package/dist/{sink-registry-CjK5MC90.js.map → sink-registry-DtrssBxF.js.map} +1 -1
  45. package/dist/subscription-DelB8L87.d.ts +958 -0
  46. package/dist/subscription-g5W0Ggqx.js +498 -0
  47. package/dist/subscription-g5W0Ggqx.js.map +1 -0
  48. package/dist/testkit/layers.d.ts +9 -6
  49. package/dist/testkit/layers.js +4 -4
  50. package/dist/testkit/layers.js.map +1 -1
  51. package/dist/{tool-registry-wPsHagF_.d.ts → tool-registry-B_WE2ZwK.d.ts} +2 -2
  52. package/dist/transcript.d.ts +177 -0
  53. package/dist/transcript.js +106 -0
  54. package/dist/transcript.js.map +1 -0
  55. package/dist/websocket.d.ts +2209 -2
  56. package/dist/websocket.js +704 -18
  57. package/dist/websocket.js.map +1 -1
  58. package/dist/window-read-BDayZf7O.js +1564 -0
  59. package/dist/window-read-BDayZf7O.js.map +1 -0
  60. package/package.json +5 -1
  61. package/dist/reduced-state-Vuud6LCM.js +0 -942
  62. package/dist/reduced-state-Vuud6LCM.js.map +0 -1
  63. package/dist/services/session-store.js.map +0 -1
  64. package/dist/session-store-BpitF4Wg.d.ts +0 -191
@@ -2,8 +2,8 @@ import { RunSchedulingWakeup } from "../services/run-scheduling-wakeup.js";
2
2
  import { RunScheduler } from "../services/run-scheduler.js";
3
3
  import { ModelResolver } from "../services/model-resolver.js";
4
4
  import { g as UnixEpochMillis } from "../envelope-BCzKUq_z.js";
5
- import { d as TurnRunner, f as InferenceRunner, m as LiveEventBus, p as ToolExecutor, u as SessionState } from "../session-state-C_1XxhvE.js";
6
- import { EDASessionStore } from "../services/session-store.js";
5
+ import { d as TurnRunner, f as InferenceRunner, m as LiveEventBus, p as ToolExecutor, u as SessionState } from "../session-state-C6SyphC0.js";
6
+ import { i as EDASessionStore } from "../session-store-DuEhcqIC.js";
7
7
  import { a as CompactionPolicy, n as CompactionExecutor, o as CompactionRunner } from "../compaction-ajHZ5l7f.js";
8
8
  import { EDAPromptProjector } from "../services/prompt-projector.js";
9
9
  import { n as SessionContext, t as EventFactory } from "../event-factory-VAci3NJb.js";
@@ -11,7 +11,7 @@ import { EDAToolRegistry } from "../services/tool-registry.js";
11
11
  import { IdGenerator } from "../services/id-generator.js";
12
12
  import { EDAKeepAlive } from "../services/keep-alive.js";
13
13
  import { EDAReducerRegistry } from "../services/reducer-registry.js";
14
- import { n as EDASinkRegistry } from "../sink-registry-CjK5MC90.js";
14
+ import { n as EDASinkRegistry } from "../sink-registry-DtrssBxF.js";
15
15
  import { SinkCheckpointStore } from "../services/sink-checkpoint-store.js";
16
16
  import { EDASessionQuery } from "../services/session-query.js";
17
17
  import * as Effect from "effect/Effect";
@@ -83,7 +83,7 @@ const makeEdaTestLayer = (options) => {
83
83
  const inner = yield* EDASessionStore;
84
84
  return options.wrapStore(inner);
85
85
  })).pipe(Layer.provide(BaseStore));
86
- const Bus = LiveEventBus.Noop;
86
+ const Bus = options.sessionEventObserverLayer === void 0 ? LiveEventBus.Noop : LiveEventBus.Live.pipe(Layer.provide(options.sessionEventObserverLayer));
87
87
  const KeepAlive = options.keepAliveLayer ?? EDAKeepAlive.Noop;
88
88
  const SinkCheckpoints = SinkCheckpointStore.InMemory;
89
89
  const Ids = options.ids === void 0 ? IdGenerator.Sequential : IdGenerator.Deterministic(options.ids);
@@ -1 +1 @@
1
- {"version":3,"file":"layers.js","names":[],"sources":["../../src/testkit/layers.ts"],"sourcesContent":["import * as Clock from \"effect/Clock\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Stream from \"effect/Stream\";\nimport * as LanguageModel from \"effect/ai/LanguageModel\";\nimport type * as Prompt from \"effect/ai/Prompt\";\nimport * as Response from \"effect/ai/Response\";\n\nimport { SessionId } from \"../types/core\";\nimport { type DurableEventEnvelope, UnixEpochMillis } from \"../types/events\";\n\nimport { EDASessionStore } from \"../services/session-store\";\nimport { CompactionExecutor, CompactionPolicy, CompactionRunner } from \"../services/compaction\";\nimport type { EDASessionStoreShape } from \"../services/session-store\";\nimport { EventFactory } from \"../services/event-factory\";\nimport { IdGenerator } from \"../services/id-generator\";\nimport { EDAKeepAlive } from \"../services/keep-alive\";\nimport { LiveEventBus } from \"../services/live-event-bus\";\nimport { EDAPromptProjector } from \"../services/prompt-projector\";\nimport { EDAReducerRegistry, type EDAReducer } from \"../services/reducer-registry\";\nimport { EDASinkRegistry, type EDASink } from \"../services/sink-registry\";\nimport { SinkCheckpointStore } from \"../services/sink-checkpoint-store\";\nimport { RunScheduler } from \"../services/run-scheduler\";\nimport { RunSchedulingWakeup } from \"../services/run-scheduling-wakeup\";\nimport { SessionContext } from \"../services/session-context\";\nimport { EDASessionQuery } from \"../services/session-query\";\nimport { SessionState } from \"../services/session-state\";\nimport { ToolExecutor } from \"../services/tool-executor\";\nimport { EDAToolRegistry } from \"../services/tool-registry\";\nimport type { EDAModelToolkit, ToolParamsSchema } from \"../services/tool-registry\";\nimport { InferenceRunner } from \"../services/inference-runner\";\nimport { ModelResolver } from \"../services/model-resolver\";\nimport type { InferenceRunnerStreamPart } from \"../services/inference-runner\";\nimport { TurnRunner } from \"../services/turn-runner\";\n\n/** Default fixed test wall-clock; matches the historical CREATED_AT_MS test constant. */\nexport const testNowMs = UnixEpochMillis.make(1_715_000_000_000);\n\n/** A Clock whose current time never advances; sleep resolves immediately. */\nexport const makeFixedClock = (nowMs: number): Clock.Clock => ({\n currentTimeMillisUnsafe: () => nowMs,\n currentTimeMillis: Effect.sync(() => nowMs),\n currentTimeNanosUnsafe: () => BigInt(nowMs) * 1_000_000n,\n currentTimeNanos: Effect.sync(() => BigInt(nowMs) * 1_000_000n),\n monotonicTimeNanosUnsafe: () => BigInt(nowMs) * 1_000_000n,\n monotonicTimeNanos: Effect.sync(() => BigInt(nowMs) * 1_000_000n),\n sleep: () => Effect.void,\n});\n\n/** Layer pinning the ambient Clock reference to a fixed instant. */\nexport const FixedClock = (nowMs: number) => Layer.succeed(Clock.Clock, makeFixedClock(nowMs));\n\n/** Fake provider stream input; arrays are consumed one streamText call at a time. */\nexport type TestModelParts =\n | Stream.Stream<InferenceRunnerStreamPart, unknown>\n | ReadonlyArray<Stream.Stream<InferenceRunnerStreamPart, unknown>>;\n\n/** Options for the fake Effect AI LanguageModel used by EDA runtime tests. */\nexport interface TestLanguageModelOptions {\n readonly parts: TestModelParts;\n /** Optional fake generateText output for compaction/summarization tests. */\n readonly generateText?: string | ((input: { readonly prompt: Prompt.RawInput }) => string);\n readonly onGenerateText?: (input: { readonly prompt: Prompt.RawInput }) => void;\n readonly onStreamText?: (input: {\n readonly index: number;\n readonly prompt: Prompt.RawInput;\n readonly toolNames: ReadonlyArray<string>;\n }) => void;\n}\n\n/** Fake provider whose streamText returns configured test streams; other methods die. */\nexport const makeLanguageModelLayer = (options: TestModelParts | TestLanguageModelOptions) => {\n const config = isTestLanguageModelOptions(options) ? options : { parts: options };\n const unused = () => Effect.die(new Error(\"unused fake LanguageModel method\"));\n return Layer.effect(\n LanguageModel.LanguageModel,\n Effect.gen(function* () {\n const nextIndex = yield* Ref.make(0);\n const streamText = ((input: { readonly prompt: Prompt.RawInput }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const index = yield* Ref.getAndUpdate(nextIndex, (current) => current + 1);\n config.onStreamText?.({\n index,\n prompt: input.prompt,\n toolNames: Object.keys(inputToolkit(input)?.tools ?? {}),\n });\n if (!Array.isArray(config.parts)) {\n return config.parts;\n }\n const stream = config.parts[index];\n return stream === undefined\n ? yield* Effect.die(\n new Error(`No fake LanguageModel stream configured for call ${index}`),\n )\n : stream;\n }),\n )) as LanguageModel.LanguageModel[\"streamText\"];\n const generateText = ((input: { readonly prompt: Prompt.RawInput }) =>\n Effect.sync(() => {\n config.onGenerateText?.({ prompt: input.prompt });\n if (config.generateText === undefined) {\n return Effect.runSync(unused()) as never;\n }\n const text =\n typeof config.generateText === \"function\"\n ? config.generateText({ prompt: input.prompt })\n : config.generateText;\n return new LanguageModel.GenerateTextResponse([Response.makePart(\"text\", { text })]);\n })) as unknown as LanguageModel.LanguageModel[\"generateText\"];\n return {\n [LanguageModel.TypeId]: LanguageModel.TypeId,\n generateText,\n generateObject: unused as LanguageModel.LanguageModel[\"generateObject\"],\n streamText,\n };\n }),\n );\n};\n\nconst inputToolkit = (input: {\n readonly prompt: Prompt.RawInput;\n readonly toolkit?: unknown;\n}): { readonly tools: Record<string, unknown> } | undefined => {\n const toolkit = input.toolkit;\n return typeof toolkit === \"object\" && toolkit !== null && \"tools\" in toolkit\n ? (toolkit as { readonly tools: Record<string, unknown> })\n : undefined;\n};\n\nconst isTestLanguageModelOptions = (\n options: TestModelParts | TestLanguageModelOptions,\n): options is TestLanguageModelOptions =>\n typeof options === \"object\" &&\n options !== null &&\n \"parts\" in options &&\n !Stream.isStream(options);\n\n/** Single-session in-memory layer graph options for EDA service tests. */\nexport interface EdaTestLayerOptions {\n readonly runSchedulerLayer?: Layer.Layer<RunScheduler>;\n readonly runSchedulingWakeupLayer?: Layer.Layer<RunSchedulingWakeup>;\n readonly sessionId: SessionId;\n /** Explicit ID sequence (Deterministic); omit for counter-based Sequential IDs. */\n readonly ids?: ReadonlyArray<string>;\n /** Real/alternate provider layer; when absent, the fake stream provider is used. */\n readonly modelLayer?: Layer.Layer<LanguageModel.LanguageModel>;\n /** Replaces the external model-selection boundary when testing execution policy. */\n readonly modelResolverLayer?: Layer.Layer<ModelResolver>;\n /** Fake provider stream parts; defaults to an empty stream. Ignored when `modelLayer` is provided. */\n readonly parts?: TestModelParts;\n /** Optional fake generateText output for compaction/summarization tests. */\n readonly generateText?: string | ((input: { readonly prompt: Prompt.RawInput }) => string);\n /** Test hook for inspecting each fake generateText call. */\n readonly onGenerateText?: (input: { readonly prompt: Prompt.RawInput }) => void;\n /** Test hook for inspecting each fake streamText call. */\n readonly onStreamText?: (input: {\n readonly index: number;\n readonly prompt: Prompt.RawInput;\n readonly toolNames: ReadonlyArray<string>;\n }) => void;\n /** Handler-backed Effect Toolkit; overrides `toolSchemas` when present. */\n readonly toolkit?: EDAModelToolkit;\n /** Test/convenience schema-only tools; execution fails unless `toolkit` is provided. */\n readonly toolSchemas?: ReadonlyMap<string, ToolParamsSchema>;\n /** Durable prefix used when constructing a fresh in-memory runtime for recovery tests. */\n readonly seedEvents?: ReadonlyArray<DurableEventEnvelope>;\n /** Fixed wall-clock for event timestamps; defaults to `testNowMs`. */\n readonly nowMs?: number;\n /** Use the ambient live Clock instead of pinning test time. Intended for offline trace latency runs. */\n readonly clock?: \"fixed\" | \"live\";\n /** Wrap the in-memory store shape, e.g. to inject one-shot failures. Test-only. */\n readonly wrapStore?: (inner: EDASessionStoreShape) => EDASessionStoreShape;\n /** Override host keepAlive tracking. Test-only. */\n readonly keepAliveLayer?: Layer.Layer<EDAKeepAlive>;\n /** Override compaction policy; defaults to disabled. */\n readonly compactionPolicyLayer?: Layer.Layer<CompactionPolicy>;\n /** Override compaction executor; defaults to disabled. */\n readonly compactionExecutorLayer?: Layer.Layer<CompactionExecutor>;\n /** App-specific durable metadata reducers. */\n readonly reducers?: ReadonlyArray<EDAReducer>;\n /** Override state-to-LLM context projection. */\n readonly promptProjectorLayer?: Layer.Layer<EDAPromptProjector>;\n /** App-provided EDA sinks. */\n readonly sinks?: ReadonlyArray<EDASink>;\n}\n\n/**\n * One in-memory layer graph for the whole session runtime, exposing every\n * EDA service plus the fixed Clock. Layer constants are shared by reference,\n * so all services see the same store, bus, and ID counter.\n */\nexport const makeEdaTestLayer = (options: EdaTestLayerOptions) => {\n const BaseStore =\n options.seedEvents === undefined\n ? EDASessionStore.InMemory(options.sessionId)\n : EDASessionStore.InMemorySeeded(options.sessionId, options.seedEvents);\n const Store =\n options.wrapStore === undefined\n ? BaseStore\n : Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const inner = yield* EDASessionStore;\n return options.wrapStore!(inner);\n }),\n ).pipe(Layer.provide(BaseStore));\n const Bus = LiveEventBus.Noop;\n const KeepAlive = options.keepAliveLayer ?? EDAKeepAlive.Noop;\n const SinkCheckpoints = SinkCheckpointStore.InMemory;\n const Ids =\n options.ids === undefined ? IdGenerator.Sequential : IdGenerator.Deterministic(options.ids);\n const Session = SessionContext.Live(options.sessionId);\n const TestClock = options.clock === \"live\" ? Layer.empty : FixedClock(options.nowMs ?? testNowMs);\n const Factory = EventFactory.Live.pipe(Layer.provideMerge(Layer.mergeAll(Session, Ids)));\n const ReducerRegistry = EDAReducerRegistry.Live(options.reducers ?? []);\n const PromptProjector = options.promptProjectorLayer ?? EDAPromptProjector.Default;\n const Model =\n options.modelLayer ??\n makeLanguageModelLayer({\n generateText: options.generateText,\n onGenerateText: options.onGenerateText,\n onStreamText: options.onStreamText,\n parts: options.parts ?? Stream.empty,\n });\n const CompactionPolicyLayer = options.compactionPolicyLayer ?? CompactionPolicy.Disabled;\n const Models = options.modelResolverLayer ?? ModelResolver.Fixed.pipe(Layer.provideMerge(Model));\n const CompactionExecutorLayer = options.compactionExecutorLayer ?? CompactionExecutor.Disabled;\n const Registry =\n options.toolkit !== undefined\n ? EDAToolRegistry.FromToolkit(options.toolkit)\n : options.toolSchemas === undefined\n ? EDAToolRegistry.Empty\n : EDAToolRegistry.FromSchemas(options.toolSchemas);\n const Compaction = CompactionRunner.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Factory,\n Ids,\n KeepAlive,\n Models,\n Session,\n PromptProjector,\n Registry,\n CompactionPolicyLayer,\n CompactionExecutorLayer,\n ),\n ),\n );\n const SinkRegistry = EDASinkRegistry.Live(options.sinks ?? []).pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Session,\n Store,\n Bus,\n SinkCheckpoints,\n Factory,\n Ids,\n ReducerRegistry,\n KeepAlive,\n ),\n ),\n );\n const State = SessionState.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Bus,\n Session,\n ReducerRegistry,\n SinkRegistry,\n KeepAlive,\n Compaction,\n PromptProjector,\n options.runSchedulerLayer ?? RunScheduler.Immediate,\n options.runSchedulingWakeupLayer ?? RunSchedulingWakeup.Unsupported,\n ),\n ),\n );\n const InferenceRunnerLayer = InferenceRunner.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(Factory, Models, Registry, Ids)),\n );\n const ToolExec = ToolExecutor.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(Factory, Registry, Ids, Session, Store)),\n );\n const Turn = TurnRunner.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(InferenceRunnerLayer, ToolExec, Factory, Ids)),\n );\n const StateWithRun = State.pipe(Layer.provideMerge(Layer.mergeAll(Turn, Factory, Ids)));\n const Query = EDASessionQuery.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(StateWithRun, Store, Bus)),\n );\n\n return Layer.mergeAll(StateWithRun, Query, InferenceRunnerLayer, ToolExec, TestClock);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,YAAY,gBAAgB,KAAK,MAAiB;;AAG/D,MAAa,kBAAkB,WAAgC;CAC7D,+BAA+B;CAC/B,mBAAmB,OAAO,WAAW,KAAK;CAC1C,8BAA8B,OAAO,KAAK,IAAI;CAC9C,kBAAkB,OAAO,WAAW,OAAO,KAAK,IAAI,QAAU;CAC9D,gCAAgC,OAAO,KAAK,IAAI;CA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C,CAC7D;CAEA,OAAO,MAAM,SAAS,cAAc,OAAO,sBAAsB,UAAU,SAAS;AACtF"}
1
+ {"version":3,"file":"layers.js","names":[],"sources":["../../src/testkit/layers.ts"],"sourcesContent":["import * as Clock from \"effect/Clock\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Stream from \"effect/Stream\";\nimport * as LanguageModel from \"effect/ai/LanguageModel\";\nimport type * as Prompt from \"effect/ai/Prompt\";\nimport * as Response from \"effect/ai/Response\";\n\nimport { SessionId } from \"../types/core\";\nimport { type DurableEventEnvelope, UnixEpochMillis } from \"../types/events\";\n\nimport { EDASessionStore } from \"../services/session-store\";\nimport { CompactionExecutor, CompactionPolicy, CompactionRunner } from \"../services/compaction\";\nimport type { EDASessionStoreShape } from \"../services/session-store\";\nimport { EventFactory } from \"../services/event-factory\";\nimport { IdGenerator } from \"../services/id-generator\";\nimport { EDAKeepAlive } from \"../services/keep-alive\";\nimport { LiveEventBus } from \"../services/live-event-bus\";\nimport type { SessionEventObserver } from \"../services/session-event-observer\";\nimport { EDAPromptProjector } from \"../services/prompt-projector\";\nimport { EDAReducerRegistry, type EDAReducer } from \"../services/reducer-registry\";\nimport { EDASinkRegistry, type EDASink } from \"../services/sink-registry\";\nimport { SinkCheckpointStore } from \"../services/sink-checkpoint-store\";\nimport { RunScheduler } from \"../services/run-scheduler\";\nimport { RunSchedulingWakeup } from \"../services/run-scheduling-wakeup\";\nimport { SessionContext } from \"../services/session-context\";\nimport { EDASessionQuery } from \"../services/session-query\";\nimport { SessionState } from \"../services/session-state\";\nimport { ToolExecutor } from \"../services/tool-executor\";\nimport { EDAToolRegistry } from \"../services/tool-registry\";\nimport type { EDAModelToolkit, ToolParamsSchema } from \"../services/tool-registry\";\nimport { InferenceRunner } from \"../services/inference-runner\";\nimport { ModelResolver } from \"../services/model-resolver\";\nimport type { InferenceRunnerStreamPart } from \"../services/inference-runner\";\nimport { TurnRunner } from \"../services/turn-runner\";\n\n/** Default fixed test wall-clock; matches the historical CREATED_AT_MS test constant. */\nexport const testNowMs = UnixEpochMillis.make(1_715_000_000_000);\n\n/** A Clock whose current time never advances; sleep resolves immediately. */\nexport const makeFixedClock = (nowMs: number): Clock.Clock => ({\n currentTimeMillisUnsafe: () => nowMs,\n currentTimeMillis: Effect.sync(() => nowMs),\n currentTimeNanosUnsafe: () => BigInt(nowMs) * 1_000_000n,\n currentTimeNanos: Effect.sync(() => BigInt(nowMs) * 1_000_000n),\n monotonicTimeNanosUnsafe: () => BigInt(nowMs) * 1_000_000n,\n monotonicTimeNanos: Effect.sync(() => BigInt(nowMs) * 1_000_000n),\n sleep: () => Effect.void,\n});\n\n/** Layer pinning the ambient Clock reference to a fixed instant. */\nexport const FixedClock = (nowMs: number) => Layer.succeed(Clock.Clock, makeFixedClock(nowMs));\n\n/** Fake provider stream input; arrays are consumed one streamText call at a time. */\nexport type TestModelParts =\n | Stream.Stream<InferenceRunnerStreamPart, unknown>\n | ReadonlyArray<Stream.Stream<InferenceRunnerStreamPart, unknown>>;\n\n/** Options for the fake Effect AI LanguageModel used by EDA runtime tests. */\nexport interface TestLanguageModelOptions {\n readonly parts: TestModelParts;\n /** Optional fake generateText output for compaction/summarization tests. */\n readonly generateText?: string | ((input: { readonly prompt: Prompt.RawInput }) => string);\n readonly onGenerateText?: (input: { readonly prompt: Prompt.RawInput }) => void;\n readonly onStreamText?: (input: {\n readonly index: number;\n readonly prompt: Prompt.RawInput;\n readonly toolNames: ReadonlyArray<string>;\n }) => void;\n}\n\n/** Fake provider whose streamText returns configured test streams; other methods die. */\nexport const makeLanguageModelLayer = (options: TestModelParts | TestLanguageModelOptions) => {\n const config = isTestLanguageModelOptions(options) ? options : { parts: options };\n const unused = () => Effect.die(new Error(\"unused fake LanguageModel method\"));\n return Layer.effect(\n LanguageModel.LanguageModel,\n Effect.gen(function* () {\n const nextIndex = yield* Ref.make(0);\n const streamText = ((input: { readonly prompt: Prompt.RawInput }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const index = yield* Ref.getAndUpdate(nextIndex, (current) => current + 1);\n config.onStreamText?.({\n index,\n prompt: input.prompt,\n toolNames: Object.keys(inputToolkit(input)?.tools ?? {}),\n });\n if (!Array.isArray(config.parts)) {\n return config.parts;\n }\n const stream = config.parts[index];\n return stream === undefined\n ? yield* Effect.die(\n new Error(`No fake LanguageModel stream configured for call ${index}`),\n )\n : stream;\n }),\n )) as LanguageModel.LanguageModel[\"streamText\"];\n const generateText = ((input: { readonly prompt: Prompt.RawInput }) =>\n Effect.sync(() => {\n config.onGenerateText?.({ prompt: input.prompt });\n if (config.generateText === undefined) {\n return Effect.runSync(unused()) as never;\n }\n const text =\n typeof config.generateText === \"function\"\n ? config.generateText({ prompt: input.prompt })\n : config.generateText;\n return new LanguageModel.GenerateTextResponse([Response.makePart(\"text\", { text })]);\n })) as unknown as LanguageModel.LanguageModel[\"generateText\"];\n return {\n [LanguageModel.TypeId]: LanguageModel.TypeId,\n generateText,\n generateObject: unused as LanguageModel.LanguageModel[\"generateObject\"],\n streamText,\n };\n }),\n );\n};\n\nconst inputToolkit = (input: {\n readonly prompt: Prompt.RawInput;\n readonly toolkit?: unknown;\n}): { readonly tools: Record<string, unknown> } | undefined => {\n const toolkit = input.toolkit;\n return typeof toolkit === \"object\" && toolkit !== null && \"tools\" in toolkit\n ? (toolkit as { readonly tools: Record<string, unknown> })\n : undefined;\n};\n\nconst isTestLanguageModelOptions = (\n options: TestModelParts | TestLanguageModelOptions,\n): options is TestLanguageModelOptions =>\n typeof options === \"object\" &&\n options !== null &&\n \"parts\" in options &&\n !Stream.isStream(options);\n\n/** Single-session in-memory layer graph options for EDA service tests. */\nexport interface EdaTestLayerOptions {\n readonly runSchedulerLayer?: Layer.Layer<RunScheduler>;\n readonly runSchedulingWakeupLayer?: Layer.Layer<RunSchedulingWakeup>;\n readonly sessionId: SessionId;\n /** Explicit ID sequence (Deterministic); omit for counter-based Sequential IDs. */\n readonly ids?: ReadonlyArray<string>;\n /** Real/alternate provider layer; when absent, the fake stream provider is used. */\n readonly modelLayer?: Layer.Layer<LanguageModel.LanguageModel>;\n /** Replaces the external model-selection boundary when testing execution policy. */\n readonly modelResolverLayer?: Layer.Layer<ModelResolver>;\n /** Fake provider stream parts; defaults to an empty stream. Ignored when `modelLayer` is provided. */\n readonly parts?: TestModelParts;\n /** Optional fake generateText output for compaction/summarization tests. */\n readonly generateText?: string | ((input: { readonly prompt: Prompt.RawInput }) => string);\n /** Test hook for inspecting each fake generateText call. */\n readonly onGenerateText?: (input: { readonly prompt: Prompt.RawInput }) => void;\n /** Test hook for inspecting each fake streamText call. */\n readonly onStreamText?: (input: {\n readonly index: number;\n readonly prompt: Prompt.RawInput;\n readonly toolNames: ReadonlyArray<string>;\n }) => void;\n /** Handler-backed Effect Toolkit; overrides `toolSchemas` when present. */\n readonly toolkit?: EDAModelToolkit;\n /** Test/convenience schema-only tools; execution fails unless `toolkit` is provided. */\n readonly toolSchemas?: ReadonlyMap<string, ToolParamsSchema>;\n /** Durable prefix used when constructing a fresh in-memory runtime for recovery tests. */\n readonly seedEvents?: ReadonlyArray<DurableEventEnvelope>;\n /** Fixed wall-clock for event timestamps; defaults to `testNowMs`. */\n readonly nowMs?: number;\n /** Use the ambient live Clock instead of pinning test time. Intended for offline trace latency runs. */\n readonly clock?: \"fixed\" | \"live\";\n /** Wrap the in-memory store shape, e.g. to inject one-shot failures. Test-only. */\n readonly wrapStore?: (inner: EDASessionStoreShape) => EDASessionStoreShape;\n /** Override host keepAlive tracking. Test-only. */\n readonly keepAliveLayer?: Layer.Layer<EDAKeepAlive>;\n /** Override compaction policy; defaults to disabled. */\n readonly compactionPolicyLayer?: Layer.Layer<CompactionPolicy>;\n /** Override compaction executor; defaults to disabled. */\n readonly compactionExecutorLayer?: Layer.Layer<CompactionExecutor>;\n /** App-specific durable metadata reducers. */\n readonly reducers?: ReadonlyArray<EDAReducer>;\n /** Override state-to-LLM context projection. */\n readonly promptProjectorLayer?: Layer.Layer<EDAPromptProjector>;\n /** App-provided EDA sinks. */\n readonly sinks?: ReadonlyArray<EDASink>;\n /** Host publication observer, such as a WebSocket connection manager. */\n readonly sessionEventObserverLayer?: Layer.Layer<SessionEventObserver>;\n}\n\n/**\n * One in-memory layer graph for the whole session runtime, exposing every\n * EDA service plus the fixed Clock. Layer constants are shared by reference,\n * so all services see the same store, bus, and ID counter.\n */\nexport const makeEdaTestLayer = (options: EdaTestLayerOptions) => {\n const BaseStore =\n options.seedEvents === undefined\n ? EDASessionStore.InMemory(options.sessionId)\n : EDASessionStore.InMemorySeeded(options.sessionId, options.seedEvents);\n const Store =\n options.wrapStore === undefined\n ? BaseStore\n : Layer.effect(\n EDASessionStore,\n Effect.gen(function* () {\n const inner = yield* EDASessionStore;\n return options.wrapStore!(inner);\n }),\n ).pipe(Layer.provide(BaseStore));\n const Bus =\n options.sessionEventObserverLayer === undefined\n ? LiveEventBus.Noop\n : LiveEventBus.Live.pipe(Layer.provide(options.sessionEventObserverLayer));\n const KeepAlive = options.keepAliveLayer ?? EDAKeepAlive.Noop;\n const SinkCheckpoints = SinkCheckpointStore.InMemory;\n const Ids =\n options.ids === undefined ? IdGenerator.Sequential : IdGenerator.Deterministic(options.ids);\n const Session = SessionContext.Live(options.sessionId);\n const TestClock = options.clock === \"live\" ? Layer.empty : FixedClock(options.nowMs ?? testNowMs);\n const Factory = EventFactory.Live.pipe(Layer.provideMerge(Layer.mergeAll(Session, Ids)));\n const ReducerRegistry = EDAReducerRegistry.Live(options.reducers ?? []);\n const PromptProjector = options.promptProjectorLayer ?? EDAPromptProjector.Default;\n const Model =\n options.modelLayer ??\n makeLanguageModelLayer({\n generateText: options.generateText,\n onGenerateText: options.onGenerateText,\n onStreamText: options.onStreamText,\n parts: options.parts ?? Stream.empty,\n });\n const CompactionPolicyLayer = options.compactionPolicyLayer ?? CompactionPolicy.Disabled;\n const Models = options.modelResolverLayer ?? ModelResolver.Fixed.pipe(Layer.provideMerge(Model));\n const CompactionExecutorLayer = options.compactionExecutorLayer ?? CompactionExecutor.Disabled;\n const Registry =\n options.toolkit !== undefined\n ? EDAToolRegistry.FromToolkit(options.toolkit)\n : options.toolSchemas === undefined\n ? EDAToolRegistry.Empty\n : EDAToolRegistry.FromSchemas(options.toolSchemas);\n const Compaction = CompactionRunner.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Factory,\n Ids,\n KeepAlive,\n Models,\n Session,\n PromptProjector,\n Registry,\n CompactionPolicyLayer,\n CompactionExecutorLayer,\n ),\n ),\n );\n const SinkRegistry = EDASinkRegistry.Live(options.sinks ?? []).pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Session,\n Store,\n Bus,\n SinkCheckpoints,\n Factory,\n Ids,\n ReducerRegistry,\n KeepAlive,\n ),\n ),\n );\n const State = SessionState.Live.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n Store,\n Bus,\n Session,\n ReducerRegistry,\n SinkRegistry,\n KeepAlive,\n Compaction,\n PromptProjector,\n options.runSchedulerLayer ?? RunScheduler.Immediate,\n options.runSchedulingWakeupLayer ?? RunSchedulingWakeup.Unsupported,\n ),\n ),\n );\n const InferenceRunnerLayer = InferenceRunner.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(Factory, Models, Registry, Ids)),\n );\n const ToolExec = ToolExecutor.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(Factory, Registry, Ids, Session, Store)),\n );\n const Turn = TurnRunner.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(InferenceRunnerLayer, ToolExec, Factory, Ids)),\n );\n const StateWithRun = State.pipe(Layer.provideMerge(Layer.mergeAll(Turn, Factory, Ids)));\n const Query = EDASessionQuery.Live.pipe(\n Layer.provideMerge(Layer.mergeAll(StateWithRun, Store, Bus)),\n );\n\n return Layer.mergeAll(StateWithRun, Query, InferenceRunnerLayer, ToolExec, TestClock);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAa,YAA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,SAAS,UAAU,KAAK,SAAS,KAAK,CAAC,CAC3E;CACA,MAAM,OAAO,WAAW,KAAK,KAC3B,MAAM,aAAa,MAAM,SAAS,sBAAsB,UAAU,SAAS,GAAG,CAAC,CACjF;CACA,MAAM,eAAe,MAAM,KAAK,MAAM,aAAa,MAAM,SAAS,MAAM,SAAS,GAAG,CAAC,CAAC;CACtF,MAAM,QAAQ,gBAAgB,KAAK,KACjC,MAAM,aAAa,MAAM,SAAS,cAAc,OAAO,GAAG,CAAC,CAC7D;CAEA,OAAO,MAAM,SAAS,cAAc,OAAO,sBAAsB,UAAU,SAAS;AACtF"}
@@ -1,7 +1,7 @@
1
1
  import { b as TurnId, c as EventId, g as SessionId, p as RunId, y as ToolCallId } from "./core-BcimKMIv.js";
2
2
  import { g as ToolName, t as DurableEventEnvelope } from "./envelope-Che6KatU.js";
3
3
  import "./events-BWuvzVml.js";
4
- import { s as EDASessionStoreError, t as CommittedDurableEvent } from "./session-store-BpitF4Wg.js";
4
+ import { s as EDASessionStoreError, t as CommittedDurableEvent } from "./session-store-CWYZ29CV.js";
5
5
  import * as Context from "effect/Context";
6
6
  import * as Effect from "effect/Effect";
7
7
  import * as Layer from "effect/Layer";
@@ -55,4 +55,4 @@ declare class EDAToolRegistry extends EDAToolRegistry_base {
55
55
  }
56
56
  //#endregion
57
57
  export { ToolParamsSchema as a, EDAToolRegistryShape as i, EDAToolExecutionContext as n, makeEDAToolkit as o, EDAToolRegistry as r, EDAModelToolkit as t };
58
- //# sourceMappingURL=tool-registry-wPsHagF_.d.ts.map
58
+ //# sourceMappingURL=tool-registry-B_WE2ZwK.d.ts.map
@@ -0,0 +1,177 @@
1
+ import { b as TurnId, h as SequenceNumber, l as InferenceId } from "./core-BcimKMIv.js";
2
+ import { f as PositionedEvent } from "./envelope-Che6KatU.js";
3
+ import "./events-BWuvzVml.js";
4
+ import { $ as TranscriptAssistantPart, A as TranscriptDefinition, At as TranscriptToolRecord, B as makeTranscriptDefinition, Bt as transcriptDecorationBufferLimit, C as TranscriptVersionMeta, Ct as TranscriptRecordView, D as TranscriptWindowSelector, Dt as TranscriptRunOutcome, E as TranscriptWindowLimits, Et as TranscriptRunMember, F as TranscriptMappingOperation, Ft as TranscriptVersion, G as DecorationBufferRecordId, H as AssistantRecordId, Ht as transcriptRecordId, I as TranscriptMappingTarget, It as UserRecordId, J as PendingTranscriptUserRecord, K as ImportAssistantRecordId, L as TranscriptMappings, Lt as isPendingTranscriptUserRecord, M as TranscriptListEntryKey, Mt as TranscriptUnknownRecord, N as TranscriptMappedEvent, Nt as TranscriptUserRecord, O as defaultTranscriptWindowLimits, Ot as TranscriptSessionContextRecord, P as TranscriptMapping, Pt as TranscriptUserState, Q as TranscriptAssistantLifecycle, R as TranscriptUserFallback, Rt as isTopLevelTranscriptRecord, S as TranscriptReadiness, St as TranscriptRecordKind, T as TranscriptWindow, Tt as TranscriptRunGroupRecord, U as CompactionRecordId, Ut as transcriptStoredInlineBodyLimit, V as transcriptMappingBounds, Vt as transcriptRecordEnvelopeFormat, W as ConsumedTranscriptUserRecord, X as SessionContextRecordId, Y as RunGroupRecordId, Z as ToolRecordId, _ as EDATranscriptStoreShape, _t as TranscriptPosition, at as TranscriptCompactionRecord, b as TranscriptActiveContent, bt as TranscriptRecordFromEnvelope, ct as TranscriptDecorationBufferRecord, dt as TranscriptDecorationKey, et as TranscriptAssistantRecord, ft as TranscriptDecorations, g as EDATranscriptStore, gt as TranscriptOrderKey, ht as TranscriptOrder, it as TranscriptClassification, j as TranscriptDefinitionError, jt as TranscriptTopLevelRecord, k as transcriptCursorOf, kt as TranscriptToolLifecycle, lt as TranscriptDecorationEntryId, mt as TranscriptLogIncarnation, nt as TranscriptBodySource, ot as TranscriptCursor, pt as TranscriptFieldPath, q as InferenceAssistantRecordId, rt as TranscriptBufferedDecoration, st as TranscriptDecoration, t as CommittedDurableEvent, tt as TranscriptBody, ut as TranscriptDecorationEntryKey, v as TranscriptCursorMismatch, vt as TranscriptRecord, w as TranscriptVersionStatus, wt as TranscriptRecordViewFromEnvelope, x as TranscriptActivePart, xt as TranscriptRecordId, y as TranscriptMaintenanceConfig, yt as TranscriptRecordEnvelope, z as emptyTranscriptMappings, zt as runGroupStatus } from "./session-store-CWYZ29CV.js";
5
+ import { a as TranscriptSubscriptionRead, c as defaultTranscriptSubscriptionPolicy, d as transcriptCoverageOf, f as transcriptSubscriptionBaseOf, i as TranscriptSubscriptionPolicy, l as planTranscriptUpdate, n as TranscriptRequestId, o as TranscriptSubscriptionRequest, r as TranscriptSubscriptionBase, s as TranscriptUpdate, t as TranscriptCoverage, u as readTranscriptSubscription } from "./subscription-DelB8L87.js";
6
+ import * as Schema from "effect/Schema";
7
+ import * as Result from "effect/Result";
8
+ //#region src/transcript/plan.d.ts
9
+ /**
10
+ * Secondary keys that resolve to a record through an indexed join, never an in-memory map.
11
+ *
12
+ * - `messageId`: every message id a user submission has carried, including replacement ids.
13
+ * - `idempotencyKey`: a submitting command's caller-owned retry key.
14
+ * - `runId`: every run of a run group, so continuations resolve to the root's group.
15
+ * - `runCommand`: commands owned by a run group; a run that reuses them continues the group.
16
+ * - `toolPart`: `<inferenceId>/<providerPartId>`, linking an assistant tool-call part to its tool.
17
+ */
18
+ declare const TranscriptAliasNamespace: Schema.Literals<readonly ["messageId", "idempotencyKey", "runId", "runCommand", "toolPart"]>;
19
+ type TranscriptAliasNamespace = typeof TranscriptAliasNamespace.Type;
20
+ /** One alias row: `(namespace, key)` resolves to `recordId` within one version. */
21
+ interface TranscriptAlias {
22
+ readonly namespace: TranscriptAliasNamespace;
23
+ readonly key: string;
24
+ readonly recordId: TranscriptRecordId;
25
+ }
26
+ /**
27
+ * Synchronous indexed reads of one transcript version, as committed before the batch.
28
+ *
29
+ * Adapters back this with indexed storage reads so the interpreter can run inside a synchronous
30
+ * transaction (Cloudflare `storage.transactionSync`). Reads see no uncommitted plan; the
31
+ * interpreter overlays its own in-batch changes.
32
+ */
33
+ interface TranscriptLookup {
34
+ /** Last seq already projected into this version. Events at or below it are skipped. */
35
+ readonly cursor: SequenceNumber;
36
+ readonly record: (id: TranscriptRecordId) => TranscriptRecord | undefined;
37
+ readonly alias: (namespace: TranscriptAliasNamespace, key: string) => TranscriptRecordId | undefined;
38
+ /** Next free ordinal among records positioned at `anchorSeq`; 0 when none are. */
39
+ readonly nextOrdinal: (anchorSeq: SequenceNumber) => number;
40
+ }
41
+ /**
42
+ * Deterministic changes for one committed batch: the final state of every record the batch
43
+ * touched, in first-touch order, the aliases it introduced, and the new cursor.
44
+ *
45
+ * There are no deletions. Aliases are inserts only: an alias never moves to another record.
46
+ * Applying the plan and advancing the cursor must commit atomically with each other.
47
+ */
48
+ interface TranscriptChangePlan {
49
+ readonly records: ReadonlyArray<TranscriptRecord>;
50
+ readonly aliases: ReadonlyArray<TranscriptAlias>;
51
+ readonly throughSeq: SequenceNumber;
52
+ }
53
+ /**
54
+ * The interpretation boundary: a pure, synchronous function from a lookup, committed events and
55
+ * a definition to a change plan.
56
+ *
57
+ * It throws `TranscriptProjectionError` when the stored projection is inconsistent with the log.
58
+ * The adapter treats any throw as a recoverable projection failure of that version only.
59
+ */
60
+ type PlanTranscriptBatch = (lookup: TranscriptLookup, committed: ReadonlyArray<CommittedDurableEvent>, definition: TranscriptDefinition) => TranscriptChangePlan;
61
+ declare const TranscriptProjectionError_base: Schema.Class<TranscriptProjectionError, Schema.TaggedStruct<"TranscriptProjectionError", {
62
+ readonly message: Schema.String;
63
+ }>, import("effect/Cause").YieldableError>;
64
+ /** The stored projection cannot be advanced from the given lookup and batch. */
65
+ declare class TranscriptProjectionError extends TranscriptProjectionError_base {}
66
+ //#endregion
67
+ //#region src/transcript/interpreter.d.ts
68
+ /**
69
+ * Interpret one committed batch into a transcript change plan.
70
+ *
71
+ * Mirrors the `ReducedState` message, tool and inference fold without pruning: a
72
+ * `ContextRebased` only adds a compaction marker. Events at or below the lookup cursor are
73
+ * skipped, so an idempotent re-append is harmless. Foreign events are ignored unless a mapping
74
+ * of `definition` names their namespace, type and schema version.
75
+ */
76
+ declare const planTranscriptBatch: PlanTranscriptBatch;
77
+ //#endregion
78
+ //#region src/transcript/version.d.ts
79
+ /**
80
+ * EDA's transcript semantic revision.
81
+ *
82
+ * Bump it deliberately whenever the interpreter, the legacy-attempt normalizer, the record
83
+ * decoders or the mapping executor would interpret any existing log differently. A bump changes
84
+ * every transcript version, so every session rebuilds and every host must run its backfill.
85
+ * A new durable event type needs a bump only if this release gives it transcript meaning;
86
+ * events the interpreter ignores leave the revision and every version unchanged.
87
+ *
88
+ * A CI fingerprint over a fixed scenario corpus (added with the interpreter) fails when
89
+ * interpretation output changes and this constant does not; re-record it together with the bump.
90
+ *
91
+ * History: 1 — the initial interpreter (0.1.0-alpha.22). 2 — submissions consumed by one turn are
92
+ * ordered by submission, as the prompt orders them, not by the turn's input list.
93
+ */
94
+ declare const transcriptSemanticRevision = 2;
95
+ /**
96
+ * Deterministic JSON: object keys sorted by code unit, no whitespace. Only JSON values are
97
+ * accepted, so equal data always produces equal bytes.
98
+ */
99
+ declare const canonicalJson: (value: unknown) => string;
100
+ /** Transcript version for a semantic revision and already-encoded canonical mapping data. */
101
+ declare const computeTranscriptVersion: (semanticRevision: number, encodedMappings: unknown) => TranscriptVersion;
102
+ //#endregion
103
+ //#region src/transcript/window-read.d.ts
104
+ /**
105
+ * Synchronous indexed reads of the served version at one cut, as a store provides them.
106
+ *
107
+ * Window assembly (paging, dependency collection, byte budgeting and body references) is shared
108
+ * by every store through `readTranscriptWindowFrom`; a store only supplies these reads.
109
+ */
110
+ interface TranscriptWindowSource {
111
+ readonly incarnation: TranscriptLogIncarnation;
112
+ /** Maintenance state of the served (active) version; its cursor is the window's `throughSeq`. */
113
+ readonly meta: TranscriptVersionMeta;
114
+ /** False when this release no longer carries the served version (a missed session). */
115
+ readonly carried: boolean;
116
+ /** Top-level records before `key` (or before the end), newest first. */
117
+ readonly topLevelBefore: (key: TranscriptOrderKey | undefined, limit: number, inclusive: boolean) => ReadonlyArray<TranscriptTopLevelRecord>;
118
+ /** Top-level records after `key` (or after the start), oldest first. */
119
+ readonly topLevelAfter: (key: TranscriptOrderKey | undefined, limit: number, inclusive: boolean) => ReadonlyArray<TranscriptTopLevelRecord>;
120
+ readonly record: (id: TranscriptRecordId) => TranscriptRecord | undefined;
121
+ readonly alias: (namespace: TranscriptAliasNamespace, key: string) => TranscriptRecordId | undefined;
122
+ /** Tool records of one assistant (the typed dependency lookup). */
123
+ readonly toolsOf: (assistantId: AssistantRecordId) => ReadonlyArray<TranscriptToolRecord>;
124
+ /** Every user record still waiting for the agent (the pending-membership index). */
125
+ readonly pendingUsers: () => ReadonlyArray<TranscriptUserRecord>;
126
+ }
127
+ /** Readiness of a served version: why its cut may be behind the log. */
128
+ declare const transcriptReadiness: (meta: TranscriptVersionMeta, carried: boolean) => TranscriptReadiness;
129
+ /** The empty window served while no version is servable yet. */
130
+ declare const buildingTranscriptWindow: (incarnation: TranscriptLogIncarnation, version: TranscriptVersion) => TranscriptWindow;
131
+ /**
132
+ * Assemble one window from a source at a single cut.
133
+ *
134
+ * The response never contains anything newer than the served version's cursor: a frozen (failed
135
+ * or no longer carried) version's rows, pending users and session context all stop at its last
136
+ * good cut, which is the degraded-read rule. Bodies above the inline limit become references;
137
+ * if the response still exceeds the byte budget, records are dropped from the far end of the
138
+ * selection, keeping at least one so paging always progresses.
139
+ */
140
+ declare const readTranscriptWindowFrom: (source: TranscriptWindowSource, selector: TranscriptWindowSelector, limits: TranscriptWindowLimits) => Result.Result<TranscriptWindow, TranscriptCursorMismatch>;
141
+ //#endregion
142
+ //#region src/transcript/active-content.d.ts
143
+ /**
144
+ * The accumulated value of the inference streaming now, folded from the published live stream.
145
+ *
146
+ * Text and reasoning deltas carry only a `providerPartId`; they belong to the session's one
147
+ * active inference, which is the latest `InferenceStarted` without a terminal. That association
148
+ * is sound because `SessionState` publishes every durable and ephemeral event under one append
149
+ * gate, in commit order: an inference's start is published before its first delta and its
150
+ * terminal after its last. A session runs at most one inference at a time.
151
+ *
152
+ * The value is retired on every inference terminal (commit, partial plus failure, empty success
153
+ * and recovery failure all end in `InferenceCompleted` or `InferenceFailed`), and on its turn's
154
+ * terminal as a backstop. It is volatile: an isolate loss loses it, and recovery records the
155
+ * inference as failed (design decision 6).
156
+ */
157
+ interface TranscriptActiveContentState {
158
+ /** Highest durable seq this accumulator has folded; the publication side of the capture fence. */
159
+ readonly publishedThroughSeq: SequenceNumber;
160
+ /** Increases whenever the served active content changes; lets subscribers skip unchanged sends. */
161
+ readonly revision: number;
162
+ readonly inference: ActiveInference | undefined;
163
+ }
164
+ interface ActiveInference {
165
+ readonly inferenceId: InferenceId;
166
+ readonly turnId: TurnId;
167
+ readonly parts: ReadonlyArray<TranscriptActivePart>;
168
+ }
169
+ /** The accumulator before anything is published in this isolate. */
170
+ declare const emptyTranscriptActiveContentState: TranscriptActiveContentState;
171
+ /** Fold one published event, in publication order, into the active-content accumulator. */
172
+ declare const foldTranscriptActiveContent: (state: TranscriptActiveContentState, positioned: PositionedEvent) => TranscriptActiveContentState;
173
+ /** The active content to serve, in the window's shape; empty when nothing is streaming. */
174
+ declare const transcriptActiveContentOf: (state: TranscriptActiveContentState) => ReadonlyArray<TranscriptActiveContent>;
175
+ //#endregion
176
+ export { AssistantRecordId, CompactionRecordId, ConsumedTranscriptUserRecord, DecorationBufferRecordId, EDATranscriptStore, EDATranscriptStoreShape, ImportAssistantRecordId, InferenceAssistantRecordId, PendingTranscriptUserRecord, PlanTranscriptBatch, RunGroupRecordId, SessionContextRecordId, ToolRecordId, TranscriptActiveContent, TranscriptActiveContentState, TranscriptActivePart, TranscriptAlias, TranscriptAliasNamespace, TranscriptAssistantLifecycle, TranscriptAssistantPart, TranscriptAssistantRecord, TranscriptBody, TranscriptBodySource, TranscriptBufferedDecoration, TranscriptChangePlan, TranscriptClassification, TranscriptCompactionRecord, TranscriptCoverage, TranscriptCursor, TranscriptCursorMismatch, TranscriptDecoration, TranscriptDecorationBufferRecord, TranscriptDecorationEntryId, TranscriptDecorationEntryKey, TranscriptDecorationKey, TranscriptDecorations, TranscriptDefinition, TranscriptDefinitionError, TranscriptFieldPath, TranscriptListEntryKey, TranscriptLogIncarnation, TranscriptLookup, TranscriptMaintenanceConfig, TranscriptMappedEvent, TranscriptMapping, TranscriptMappingOperation, TranscriptMappingTarget, TranscriptMappings, TranscriptOrder, TranscriptOrderKey, TranscriptPosition, TranscriptProjectionError, TranscriptReadiness, TranscriptRecord, TranscriptRecordEnvelope, TranscriptRecordFromEnvelope, TranscriptRecordId, TranscriptRecordKind, TranscriptRecordView, TranscriptRecordViewFromEnvelope, TranscriptRequestId, TranscriptRunGroupRecord, TranscriptRunMember, TranscriptRunOutcome, TranscriptSessionContextRecord, TranscriptSubscriptionBase, TranscriptSubscriptionPolicy, TranscriptSubscriptionRead, TranscriptSubscriptionRequest, TranscriptToolLifecycle, TranscriptToolRecord, TranscriptTopLevelRecord, TranscriptUnknownRecord, TranscriptUpdate, TranscriptUserFallback, TranscriptUserRecord, TranscriptUserState, TranscriptVersion, TranscriptVersionMeta, TranscriptVersionStatus, TranscriptWindow, TranscriptWindowLimits, TranscriptWindowSelector, type TranscriptWindowSource, UserRecordId, buildingTranscriptWindow, canonicalJson, computeTranscriptVersion, defaultTranscriptSubscriptionPolicy, defaultTranscriptWindowLimits, emptyTranscriptActiveContentState, emptyTranscriptMappings, foldTranscriptActiveContent, isPendingTranscriptUserRecord, isTopLevelTranscriptRecord, makeTranscriptDefinition, planTranscriptBatch, planTranscriptUpdate, readTranscriptSubscription, readTranscriptWindowFrom, runGroupStatus, transcriptActiveContentOf, transcriptCoverageOf, transcriptCursorOf, transcriptDecorationBufferLimit, transcriptMappingBounds, transcriptReadiness, transcriptRecordEnvelopeFormat, transcriptRecordId, transcriptSemanticRevision, transcriptStoredInlineBodyLimit, transcriptSubscriptionBaseOf };
177
+ //# sourceMappingURL=transcript.d.ts.map
@@ -0,0 +1,106 @@
1
+ import { SequenceNumber } from "./types/core.js";
2
+ import { G as InferenceCompletedEvent, J as InferenceFailedEvent, X as InferenceStartedEvent, cn as TurnCompletedEvent, dn as TurnFailedEvent, hn as TurnStoppedEvent } from "./durable-CD__3ztN.js";
3
+ import { ReasoningDeltaEvent, TextDeltaEvent, ToolParamsDeltaEvent, ToolParamsStartEvent } from "./types/events.js";
4
+ import { A as TranscriptRecordFromEnvelope, B as TranscriptUserRecord, C as TranscriptDecorations, D as TranscriptPosition, E as TranscriptOrder, F as TranscriptRunOutcome, G as isTopLevelTranscriptRecord, H as TranscriptVersion, I as TranscriptSessionContextRecord, J as transcriptRecordEnvelopeFormat, K as runGroupStatus, L as TranscriptToolLifecycle, M as TranscriptRecordViewFromEnvelope, N as TranscriptRunGroupRecord, O as TranscriptRecord, P as TranscriptRunMember, R as TranscriptToolRecord, S as TranscriptDecorationKey, T as TranscriptLogIncarnation, U as UserRecordId, V as TranscriptUserState, W as isPendingTranscriptUserRecord, X as transcriptStoredInlineBodyLimit, Y as transcriptRecordId, _ as TranscriptCursor, a as InferenceAssistantRecordId, b as TranscriptDecorationEntryId, c as ToolRecordId, d as TranscriptAssistantRecord, f as TranscriptBody, g as TranscriptCompactionRecord, h as TranscriptClassification, i as ImportAssistantRecordId, j as TranscriptRecordId, k as TranscriptRecordEnvelope, l as TranscriptAssistantLifecycle, m as TranscriptBufferedDecoration, n as CompactionRecordId, o as RunGroupRecordId, p as TranscriptBodySource, q as transcriptDecorationBufferLimit, r as DecorationBufferRecordId, s as SessionContextRecordId, t as AssistantRecordId, u as TranscriptAssistantPart, v as TranscriptDecoration, w as TranscriptFieldPath, x as TranscriptDecorationEntryKey, y as TranscriptDecorationBufferRecord, z as TranscriptUnknownRecord } from "./records-DWKEjuqb.js";
5
+ import { C as transcriptSemanticRevision, S as computeTranscriptVersion, _ as TranscriptUserFallback, a as TranscriptCursorMismatch, b as transcriptMappingBounds, c as TranscriptProjectionError, d as TranscriptListEntryKey, f as TranscriptMappedEvent, g as TranscriptMappings, h as TranscriptMappingTarget, i as EDATranscriptStore, l as TranscriptDefinition, m as TranscriptMappingOperation, n as readTranscriptWindowFrom, o as planTranscriptBatch, p as TranscriptMapping, r as transcriptReadiness, s as TranscriptAliasNamespace, t as buildingTranscriptWindow, u as TranscriptDefinitionError, v as emptyTranscriptMappings, x as canonicalJson, y as makeTranscriptDefinition } from "./window-read-BDayZf7O.js";
6
+ import { _ as TranscriptWindowSelector, a as defaultTranscriptSubscriptionPolicy, c as transcriptCoverageOf, d as TranscriptActivePart, f as TranscriptReadiness, g as TranscriptWindowLimits, h as TranscriptWindow, i as TranscriptUpdate, l as transcriptSubscriptionBaseOf, m as TranscriptVersionStatus, n as TranscriptRequestId, o as planTranscriptUpdate, p as TranscriptVersionMeta, r as TranscriptSubscriptionBase, s as readTranscriptSubscription, t as TranscriptCoverage, u as TranscriptActiveContent, v as defaultTranscriptWindowLimits, y as transcriptCursorOf } from "./subscription-g5W0Ggqx.js";
7
+ import * as Schema from "effect/Schema";
8
+ //#region src/transcript/active-content.ts
9
+ /** The accumulator before anything is published in this isolate. */
10
+ const emptyTranscriptActiveContentState = {
11
+ publishedThroughSeq: SequenceNumber.make(0),
12
+ revision: 0,
13
+ inference: void 0
14
+ };
15
+ const isInferenceStarted = Schema.is(InferenceStartedEvent);
16
+ const isInferenceCompleted = Schema.is(InferenceCompletedEvent);
17
+ const isInferenceFailed = Schema.is(InferenceFailedEvent);
18
+ const isTurnCompleted = Schema.is(TurnCompletedEvent);
19
+ const isTurnFailed = Schema.is(TurnFailedEvent);
20
+ const isTurnStopped = Schema.is(TurnStoppedEvent);
21
+ const isTextDelta = Schema.is(TextDeltaEvent);
22
+ const isReasoningDelta = Schema.is(ReasoningDeltaEvent);
23
+ const isToolParamsStart = Schema.is(ToolParamsStartEvent);
24
+ const isToolParamsDelta = Schema.is(ToolParamsDeltaEvent);
25
+ /** Fold one published event, in publication order, into the active-content accumulator. */
26
+ const foldTranscriptActiveContent = (state, positioned) => {
27
+ const event = positioned.event;
28
+ if (event.durability === "durable") {
29
+ const published = {
30
+ ...state,
31
+ publishedThroughSeq: SequenceNumber.make(Math.max(state.publishedThroughSeq, positioned.position.seq))
32
+ };
33
+ if (isInferenceStarted(event)) return withInference(published, {
34
+ inferenceId: event.payload.inferenceId,
35
+ turnId: event.payload.turnId,
36
+ parts: []
37
+ });
38
+ const active = published.inference;
39
+ if (active === void 0) return published;
40
+ return (isInferenceCompleted(event) || isInferenceFailed(event)) && event.payload.inferenceId === active.inferenceId || (isTurnCompleted(event) || isTurnFailed(event) || isTurnStopped(event)) && event.payload.turnId === active.turnId ? withInference(published, void 0) : published;
41
+ }
42
+ const active = state.inference;
43
+ if (active === void 0) return state;
44
+ if (isTextDelta(event)) return appendText(state, active, "Text", `text:${event.payload.providerPartId}`, event.payload.delta);
45
+ if (isReasoningDelta(event)) return appendText(state, active, "Reasoning", `reasoning:${event.payload.providerPartId}`, event.payload.delta);
46
+ if (isToolParamsStart(event)) {
47
+ const id = `tool:${event.payload.toolCallId}`;
48
+ if (active.parts.some((part) => part.id === id)) return state;
49
+ return withInference(state, {
50
+ ...active,
51
+ parts: [...active.parts, {
52
+ id,
53
+ part: {
54
+ _tag: "ToolCall",
55
+ providerPartId: event.payload.providerPartId,
56
+ toolName: event.payload.toolName,
57
+ providerExecuted: event.payload.providerExecuted
58
+ },
59
+ paramsText: ""
60
+ }]
61
+ });
62
+ }
63
+ if (isToolParamsDelta(event)) {
64
+ const id = `tool:${event.payload.toolCallId}`;
65
+ const delta = event.payload.delta;
66
+ if (delta.length === 0 || !active.parts.some((part) => part.id === id)) return state;
67
+ return withInference(state, {
68
+ ...active,
69
+ parts: active.parts.map((part) => part.id === id ? {
70
+ ...part,
71
+ paramsText: (part.paramsText ?? "") + delta
72
+ } : part)
73
+ });
74
+ }
75
+ return state;
76
+ };
77
+ const appendText = (state, active, tag, id, delta) => {
78
+ if (delta.length === 0) return state;
79
+ const index = active.parts.findIndex((part) => part.id === id);
80
+ const existing = index === -1 ? void 0 : active.parts[index];
81
+ const part = {
82
+ id,
83
+ part: {
84
+ _tag: tag,
85
+ text: existing !== void 0 && existing.part._tag === tag ? existing.part.text + delta : delta
86
+ }
87
+ };
88
+ return withInference(state, {
89
+ ...active,
90
+ parts: index === -1 ? [...active.parts, part] : active.parts.map((candidate, candidateIndex) => candidateIndex === index ? part : candidate)
91
+ });
92
+ };
93
+ const withInference = (state, inference) => state.inference === void 0 && inference === void 0 ? state : {
94
+ ...state,
95
+ revision: state.revision + 1,
96
+ inference
97
+ };
98
+ /** The active content to serve, in the window's shape; empty when nothing is streaming. */
99
+ const transcriptActiveContentOf = (state) => state.inference === void 0 ? [] : [{
100
+ assistantId: transcriptRecordId.assistant(state.inference.inferenceId),
101
+ parts: state.inference.parts
102
+ }];
103
+ //#endregion
104
+ export { AssistantRecordId, CompactionRecordId, DecorationBufferRecordId, EDATranscriptStore, ImportAssistantRecordId, InferenceAssistantRecordId, RunGroupRecordId, SessionContextRecordId, ToolRecordId, TranscriptActiveContent, TranscriptActivePart, TranscriptAliasNamespace, TranscriptAssistantLifecycle, TranscriptAssistantPart, TranscriptAssistantRecord, TranscriptBody, TranscriptBodySource, TranscriptBufferedDecoration, TranscriptClassification, TranscriptCompactionRecord, TranscriptCoverage, TranscriptCursor, TranscriptCursorMismatch, TranscriptDecoration, TranscriptDecorationBufferRecord, TranscriptDecorationEntryId, TranscriptDecorationEntryKey, TranscriptDecorationKey, TranscriptDecorations, TranscriptDefinition, TranscriptDefinitionError, TranscriptFieldPath, TranscriptListEntryKey, TranscriptLogIncarnation, TranscriptMappedEvent, TranscriptMapping, TranscriptMappingOperation, TranscriptMappingTarget, TranscriptMappings, TranscriptOrder, TranscriptPosition, TranscriptProjectionError, TranscriptReadiness, TranscriptRecord, TranscriptRecordEnvelope, TranscriptRecordFromEnvelope, TranscriptRecordId, TranscriptRecordViewFromEnvelope, TranscriptRequestId, TranscriptRunGroupRecord, TranscriptRunMember, TranscriptRunOutcome, TranscriptSessionContextRecord, TranscriptSubscriptionBase, TranscriptToolLifecycle, TranscriptToolRecord, TranscriptUnknownRecord, TranscriptUpdate, TranscriptUserFallback, TranscriptUserRecord, TranscriptUserState, TranscriptVersion, TranscriptVersionMeta, TranscriptVersionStatus, TranscriptWindow, TranscriptWindowLimits, TranscriptWindowSelector, UserRecordId, buildingTranscriptWindow, canonicalJson, computeTranscriptVersion, defaultTranscriptSubscriptionPolicy, defaultTranscriptWindowLimits, emptyTranscriptActiveContentState, emptyTranscriptMappings, foldTranscriptActiveContent, isPendingTranscriptUserRecord, isTopLevelTranscriptRecord, makeTranscriptDefinition, planTranscriptBatch, planTranscriptUpdate, readTranscriptSubscription, readTranscriptWindowFrom, runGroupStatus, transcriptActiveContentOf, transcriptCoverageOf, transcriptCursorOf, transcriptDecorationBufferLimit, transcriptMappingBounds, transcriptReadiness, transcriptRecordEnvelopeFormat, transcriptRecordId, transcriptSemanticRevision, transcriptStoredInlineBodyLimit, transcriptSubscriptionBaseOf };
105
+
106
+ //# sourceMappingURL=transcript.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transcript.js","names":[],"sources":["../src/transcript/active-content.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber, type InferenceId, type TurnId } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\nimport {\n InferenceCompletedEvent,\n InferenceFailedEvent,\n InferenceStartedEvent,\n TurnCompletedEvent,\n TurnFailedEvent,\n TurnStoppedEvent,\n} from \"../types/events/durable\";\nimport {\n ReasoningDeltaEvent,\n TextDeltaEvent,\n ToolParamsDeltaEvent,\n ToolParamsStartEvent,\n} from \"../types/events/ephemeral\";\nimport { transcriptRecordId } from \"./records\";\nimport type { TranscriptActiveContent, TranscriptActivePart } from \"./window\";\n\n/**\n * The accumulated value of the inference streaming now, folded from the published live stream.\n *\n * Text and reasoning deltas carry only a `providerPartId`; they belong to the session's one\n * active inference, which is the latest `InferenceStarted` without a terminal. That association\n * is sound because `SessionState` publishes every durable and ephemeral event under one append\n * gate, in commit order: an inference's start is published before its first delta and its\n * terminal after its last. A session runs at most one inference at a time.\n *\n * The value is retired on every inference terminal (commit, partial plus failure, empty success\n * and recovery failure all end in `InferenceCompleted` or `InferenceFailed`), and on its turn's\n * terminal as a backstop. It is volatile: an isolate loss loses it, and recovery records the\n * inference as failed (design decision 6).\n */\nexport interface TranscriptActiveContentState {\n /** Highest durable seq this accumulator has folded; the publication side of the capture fence. */\n readonly publishedThroughSeq: SequenceNumber;\n /** Increases whenever the served active content changes; lets subscribers skip unchanged sends. */\n readonly revision: number;\n readonly inference: ActiveInference | undefined;\n}\n\ninterface ActiveInference {\n readonly inferenceId: InferenceId;\n readonly turnId: TurnId;\n readonly parts: ReadonlyArray<TranscriptActivePart>;\n}\n\n/** The accumulator before anything is published in this isolate. */\nexport const emptyTranscriptActiveContentState: TranscriptActiveContentState = {\n publishedThroughSeq: SequenceNumber.make(0),\n revision: 0,\n inference: undefined,\n};\n\nconst isInferenceStarted = Schema.is(InferenceStartedEvent);\nconst isInferenceCompleted = Schema.is(InferenceCompletedEvent);\nconst isInferenceFailed = Schema.is(InferenceFailedEvent);\nconst isTurnCompleted = Schema.is(TurnCompletedEvent);\nconst isTurnFailed = Schema.is(TurnFailedEvent);\nconst isTurnStopped = Schema.is(TurnStoppedEvent);\nconst isTextDelta = Schema.is(TextDeltaEvent);\nconst isReasoningDelta = Schema.is(ReasoningDeltaEvent);\nconst isToolParamsStart = Schema.is(ToolParamsStartEvent);\nconst isToolParamsDelta = Schema.is(ToolParamsDeltaEvent);\n\n/** Fold one published event, in publication order, into the active-content accumulator. */\nexport const foldTranscriptActiveContent = (\n state: TranscriptActiveContentState,\n positioned: PositionedEvent,\n): TranscriptActiveContentState => {\n const event = positioned.event;\n if (event.durability === \"durable\") {\n const published: TranscriptActiveContentState = {\n ...state,\n publishedThroughSeq: SequenceNumber.make(\n Math.max(state.publishedThroughSeq, positioned.position.seq),\n ),\n };\n if (isInferenceStarted(event)) {\n return withInference(published, {\n inferenceId: event.payload.inferenceId,\n turnId: event.payload.turnId,\n parts: [],\n });\n }\n const active = published.inference;\n if (active === undefined) return published;\n const retires =\n ((isInferenceCompleted(event) || isInferenceFailed(event)) &&\n event.payload.inferenceId === active.inferenceId) ||\n ((isTurnCompleted(event) || isTurnFailed(event) || isTurnStopped(event)) &&\n event.payload.turnId === active.turnId);\n return retires ? withInference(published, undefined) : published;\n }\n\n const active = state.inference;\n if (active === undefined) return state;\n if (isTextDelta(event)) {\n return appendText(\n state,\n active,\n \"Text\",\n `text:${event.payload.providerPartId}`,\n event.payload.delta,\n );\n }\n if (isReasoningDelta(event)) {\n return appendText(\n state,\n active,\n \"Reasoning\",\n `reasoning:${event.payload.providerPartId}`,\n event.payload.delta,\n );\n }\n if (isToolParamsStart(event)) {\n const id = `tool:${event.payload.toolCallId}`;\n if (active.parts.some((part) => part.id === id)) return state;\n return withInference(state, {\n ...active,\n parts: [\n ...active.parts,\n {\n id,\n part: {\n _tag: \"ToolCall\",\n providerPartId: event.payload.providerPartId,\n toolName: event.payload.toolName,\n providerExecuted: event.payload.providerExecuted,\n },\n paramsText: \"\",\n },\n ],\n });\n }\n if (isToolParamsDelta(event)) {\n const id = `tool:${event.payload.toolCallId}`;\n const delta = event.payload.delta;\n if (delta.length === 0 || !active.parts.some((part) => part.id === id)) return state;\n return withInference(state, {\n ...active,\n parts: active.parts.map((part) =>\n part.id === id ? { ...part, paramsText: (part.paramsText ?? \"\") + delta } : part,\n ),\n });\n }\n return state;\n};\n\nconst appendText = (\n state: TranscriptActiveContentState,\n active: ActiveInference,\n tag: \"Text\" | \"Reasoning\",\n id: string,\n delta: string,\n): TranscriptActiveContentState => {\n if (delta.length === 0) return state;\n const index = active.parts.findIndex((part) => part.id === id);\n const existing = index === -1 ? undefined : active.parts[index];\n const text =\n existing !== undefined && existing.part._tag === tag ? existing.part.text + delta : delta;\n const part: TranscriptActivePart = { id, part: { _tag: tag, text } };\n return withInference(state, {\n ...active,\n parts:\n index === -1\n ? [...active.parts, part]\n : active.parts.map((candidate, candidateIndex) =>\n candidateIndex === index ? part : candidate,\n ),\n });\n};\n\nconst withInference = (\n state: TranscriptActiveContentState,\n inference: ActiveInference | undefined,\n): TranscriptActiveContentState =>\n state.inference === undefined && inference === undefined\n ? state\n : { ...state, revision: state.revision + 1, inference };\n\n/** The active content to serve, in the window's shape; empty when nothing is streaming. */\nexport const transcriptActiveContentOf = (\n state: TranscriptActiveContentState,\n): ReadonlyArray<TranscriptActiveContent> =>\n state.inference === undefined\n ? []\n : [\n {\n assistantId: transcriptRecordId.assistant(state.inference.inferenceId),\n parts: state.inference.parts,\n },\n ];\n"],"mappings":";;;;;;;;;AAkDA,MAAa,oCAAkE;CAC7E,qBAAqB,eAAe,KAAK,CAAC;CAC1C,UAAU;CACV,WAAW,KAAA;AACb;AAEA,MAAM,qBAAqB,OAAO,GAAG,qBAAqB;AAC1D,MAAM,uBAAuB,OAAO,GAAG,uBAAuB;AAC9D,MAAM,oBAAoB,OAAO,GAAG,oBAAoB;AACxD,MAAM,kBAAkB,OAAO,GAAG,kBAAkB;AACpD,MAAM,eAAe,OAAO,GAAG,eAAe;AAC9C,MAAM,gBAAgB,OAAO,GAAG,gBAAgB;AAChD,MAAM,cAAc,OAAO,GAAG,cAAc;AAC5C,MAAM,mBAAmB,OAAO,GAAG,mBAAmB;AACtD,MAAM,oBAAoB,OAAO,GAAG,oBAAoB;AACxD,MAAM,oBAAoB,OAAO,GAAG,oBAAoB;;AAGxD,MAAa,+BACX,OACA,eACiC;CACjC,MAAM,QAAQ,WAAW;CACzB,IAAI,MAAM,eAAe,WAAW;EAClC,MAAM,YAA0C;GAC9C,GAAG;GACH,qBAAqB,eAAe,KAClC,KAAK,IAAI,MAAM,qBAAqB,WAAW,SAAS,GAAG,CAC7D;EACF;EACA,IAAI,mBAAmB,KAAK,GAC1B,OAAO,cAAc,WAAW;GAC9B,aAAa,MAAM,QAAQ;GAC3B,QAAQ,MAAM,QAAQ;GACtB,OAAO,CAAC;EACV,CAAC;EAEH,MAAM,SAAS,UAA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