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

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