effect-durable-agent 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{compaction-D7WJa899.js → compaction-Dlq4wgZE.js} +12 -9
- package/dist/compaction-Dlq4wgZE.js.map +1 -0
- package/dist/{delivery-GCO7QmXQ.d.ts → delivery-BKYmgnKC.d.ts} +2 -2
- package/dist/domain/command-queues.d.ts +1 -1
- package/dist/domain/message-transcript.d.ts +1 -1
- package/dist/domain/message-transcript.js +15 -7
- package/dist/domain/message-transcript.js.map +1 -1
- package/dist/domain/reduced-state.d.ts +2 -2
- package/dist/domain/reduced-state.js +21 -5
- package/dist/domain/reduced-state.js.map +1 -1
- package/dist/domain/run-scheduling.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/{reduced-state-BGI8EJN5.d.ts → reduced-state-DV0696_s.d.ts} +16 -4
- package/dist/services/compaction.d.ts +1 -1
- package/dist/services/compaction.js +1 -1
- package/dist/services/decider.d.ts +1 -1
- package/dist/services/decider.js +1 -1
- package/dist/services/model-call.d.ts +1 -1
- package/dist/services/prompt-projector.d.ts +1 -1
- package/dist/services/run-scheduler.d.ts +1 -1
- package/dist/services/runtime-layer.d.ts +1 -1
- package/dist/services/runtime-layer.js +4 -4
- package/dist/services/runtime.d.ts +1 -1
- package/dist/services/runtime.js +1 -1
- package/dist/services/session-query.d.ts +1 -1
- package/dist/services/session-query.js +1 -1
- package/dist/services/session-state.d.ts +1 -1
- package/dist/services/session-state.js +2 -2
- package/dist/services/session-store.js +1 -1
- package/dist/services/sink-registry.d.ts +1 -1
- package/dist/services/sink-registry.js +1 -1
- package/dist/services/tool-registry.d.ts +1 -1
- package/dist/{session-admission-WE8J_0z9.js → session-admission-DC98zwtj.js} +1 -2
- package/dist/session-admission-DC98zwtj.js.map +1 -0
- package/dist/{session-state-OY3Wih8X.js → session-state-BbJW2_P0.js} +8 -19
- package/dist/session-state-BbJW2_P0.js.map +1 -0
- package/dist/{sink-registry-AOjX5_A1.js → sink-registry-CjdKeTUM.js} +2 -2
- package/dist/{sink-registry-AOjX5_A1.js.map → sink-registry-CjdKeTUM.js.map} +1 -1
- package/dist/testkit/layers.d.ts +1 -1
- package/dist/testkit/layers.js +4 -4
- package/dist/websocket/events.d.ts +1 -1
- package/dist/websocket.d.ts +1 -1
- package/package.json +1 -1
- package/dist/compaction-D7WJa899.js.map +0 -1
- package/dist/session-admission-WE8J_0z9.js.map +0 -1
- package/dist/session-state-OY3Wih8X.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { SequenceNumber } from "./types/core.js";
|
|
2
2
|
import { foldReducedState, initialReducedState } from "./domain/reduced-state.js";
|
|
3
|
-
import { n as SessionCommandAdmissionConflict, o as makeAppEventAdmission, r as appEventConflict, t as RegisteredAppEvents } from "./session-admission-
|
|
3
|
+
import { n as SessionCommandAdmissionConflict, o as makeAppEventAdmission, r as appEventConflict, t as RegisteredAppEvents } from "./session-admission-DC98zwtj.js";
|
|
4
4
|
import { EDASessionStore, EDASessionStoreError, selectCommittedEvent } from "./services/session-store.js";
|
|
5
5
|
import { n as SessionContext, t as EventFactory } from "./event-factory-BUoBwqAy.js";
|
|
6
6
|
import { IdGenerator } from "./services/id-generator.js";
|
|
@@ -366,4 +366,4 @@ const matchesInterest = (event, interests) => interests === void 0 || interests
|
|
|
366
366
|
//#endregion
|
|
367
367
|
export { EDASinkRegistry as n, EDASink as t };
|
|
368
368
|
|
|
369
|
-
//# sourceMappingURL=sink-registry-
|
|
369
|
+
//# sourceMappingURL=sink-registry-CjdKeTUM.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sink-registry-AOjX5_A1.js","names":[],"sources":["../src/services/sink-inbox.ts","../src/services/sink-registry.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\n\n/** Durable payloads stay in the log; only bounded best-effort ephemeral work is retained. */\nconst ephemeralCapacity = 128;\nconst ephemeralByteCapacity = 256 * 1024;\n\n/** An ephemeral update could not be measured as a JSON wire value. */\nexport class SinkEphemeralEncodingError extends Schema.TaggedError<SinkEphemeralEncodingError>()(\n \"SinkEphemeralEncodingError\",\n { cause: Schema.Defect() },\n) {}\n\n/** One ordered step on a sink's serialized delivery lane. */\ntype SinkWork =\n | { readonly _tag: \"Durable\"; readonly throughSeq: SequenceNumber }\n | { readonly _tag: \"Ephemeral\"; readonly event: PositionedEvent };\n\n/**\n * Coalesces durable heads without losing ephemeral ordering barriers. Publication never\n * waits for delivery. Overflow drops the newest ephemeral update, never durable work.\n */\nexport const makeSinkInbox = Effect.fnUntraced(function* (initialHead: SequenceNumber) {\n const wake = yield* Effect.acquireRelease(Queue.sliding<void>(1), Queue.shutdown);\n let head = initialHead;\n const pending: Array<{ readonly event: PositionedEvent; readonly bytes: number }> = [];\n let pendingBytes = 0;\n\n const notify = (throughSeq: SequenceNumber) =>\n Effect.sync(() => {\n head = SequenceNumber.make(Math.max(head, throughSeq));\n Queue.offerUnsafe(wake, undefined);\n });\n\n const offerEphemeral = (event: PositionedEvent) =>\n Effect.try({\n try: () => {\n const bytes = new TextEncoder().encode(JSON.stringify(event)).byteLength;\n if (pending.length >= ephemeralCapacity || bytes > ephemeralByteCapacity - pendingBytes) {\n return false;\n }\n pending.push({ event, bytes });\n pendingBytes += bytes;\n Queue.offerUnsafe(wake, undefined);\n return true;\n },\n catch: (cause) => new SinkEphemeralEncodingError({ cause }),\n });\n\n const poll = (cursor: SequenceNumber): Effect.Effect<SinkWork | undefined> =>\n Effect.sync(() => {\n while (pending.length > 0) {\n const first = pending[0];\n if (first === undefined) break;\n if (first.event.position.seq > cursor) {\n return { _tag: \"Durable\", throughSeq: first.event.position.seq };\n }\n pending.shift();\n pendingBytes -= first.bytes;\n if (first.event.position.seq === cursor) {\n return { _tag: \"Ephemeral\", event: first.event };\n }\n }\n return cursor < head ? { _tag: \"Durable\", throughSeq: head } : undefined;\n });\n\n return { notify, offerEphemeral, poll, awaitWork: Queue.take(wake) };\n});\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { type DecodedDurableEvent } from \"../types/events/durable\";\nimport { selectCommittedEvent } from \"./session-store\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport { foldReducedState, initialReducedState, type ReducedState } from \"../domain/reduced-state\";\nimport { EDAReducerRegistry, type EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { EventId, SessionId, SequenceNumber } from \"../types/core\";\nimport type {\n DurableEventEnvelope,\n EphemeralEventEnvelope,\n PositionedEvent,\n} from \"../types/events\";\nimport type { EDASessionStoreShape } from \"./session-store\";\nimport { type CommittedDurableEvent, EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { EventFactory } from \"./event-factory\";\nimport type { EventFactoryShape } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { makeSinkInbox } from \"./sink-inbox\";\nimport {\n appEventConflict,\n makeAppEventAdmission,\n RegisteredAppEvents,\n SessionCommandAdmissionConflict,\n type AdmittedAppEvent,\n} from \"./session-admission\";\nimport { SessionContext } from \"./session-context\";\nimport {\n EDASinkName,\n SinkCheckpointStore,\n type SinkCheckpointStoreShape,\n type StoredSinkCheckpoint,\n} from \"./sink-checkpoint-store\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Cursor-window input delivered to one durable sink drain. */\nexport interface EDASinkRawDurableBatch<E = DecodedDurableEvent> {\n /** All durable events replayed for this cursor window, including uninterested events. */\n readonly allEvents: ReadonlyArray<CommittedDurableEvent>;\n /** Events matching the sink's durable interests. */\n readonly events: ReadonlyArray<CommittedDurableEvent<E>>;\n /** Durable sequence through which the sink may advance after success. */\n readonly throughSeq: SequenceNumber;\n}\n\n/** Cursor window with framework and app projections, enabled by default. */\nexport interface EDASinkDurableBatch<E = DecodedDurableEvent> extends EDASinkRawDurableBatch<E> {\n /** Authoritative reduced state folded exactly through `throughSeq`. */\n readonly stateAfter: ReducedState;\n /** App-specific durable reducer states folded exactly through `throughSeq`. */\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\n/** Typed, sink-owned durable state stored independently from cursor advancement. */\nexport interface EDASinkCheckpoint {\n /** Decode current durable state, or return `initial` for a new or legacy cursor row. */\n readonly get: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n initial: State,\n ) => Effect.Effect<State, EDASessionStoreError>;\n /** Validate, encode, and durably save state without advancing the sink cursor. */\n readonly save: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/** Capabilities exposed to sink processors without granting raw store or bus access. */\nexport interface EDASinkContext {\n readonly sessionId: SessionId;\n /** Sink-owned checkpoint state, serialized with cursor commits and background writes. */\n readonly checkpoint: EDASinkCheckpoint;\n /**\n * Build a framework durable event. `stageDurable` accepts only the framework types app code may\n * write (`SessionConfigured`, `SystemMessageCommitted`, `AssistantMessageImported`).\n */\n readonly events: EventFactoryShape;\n /** Mint an app durable event id for staged custom events. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Publish a best-effort live-only event. */\n readonly emitEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n /**\n * Stage durable events; the runner commits them after the sink succeeds, in a transaction\n * separate from the cursor commit. A crash between the two redelivers the batch, so give each\n * staged event a `dedupeKey` derived from what caused it; one without a key logs a warning.\n *\n * An event the app event admission rules refuse fails with a `SessionCommandAdmissionConflict`\n * and is not staged: a framework lifecycle event (`framework_event`), a payload that is not\n * JSON-native (`payload_not_json`) or is over `maxAppEventBytes` (`event_too_large`), or one\n * the registered `appEvents` schema rejects (`invalid_event`). A sink that catches it keeps\n * what it staged besides. One that lets it escape `process` stops its runner before the batch\n * is acknowledged: nothing staged in that delivery commits, the cursor stays, and the next\n * runtime start redelivers the batch.\n */\n readonly stageDurable: (\n event: DurableEventEnvelope,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n /** Fork background sink work into the session scope. */\n readonly forkScoped: (effect: Effect.Effect<unknown, unknown>) => Effect.Effect<void>;\n}\n\n/** `\"*\"` and omission select every fact; a schema selects and narrows matching envelopes. */\nexport type EDASinkInterests = \"*\" | Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\n/** Delivery policy shared by raw and projected durable consumers. */\ninterface EDADurableSinkOptions {\n readonly interests?: EDASinkInterests;\n readonly batchSize?: number;\n}\n\n/** Default durable consumer with framework and app projections at each cursor window. */\nexport interface EDAProjectedDurableSinkDefinition extends EDADurableSinkOptions {\n readonly process: (\n batch: EDASinkDurableBatch,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n}\n\n/** Raw consumer that never hydrates, folds, or retains a session projection. */\nexport interface EDARawDurableSinkDefinition extends EDADurableSinkOptions {\n readonly process: (\n batch: EDASinkRawDurableBatch,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n}\n\n/** Durable sink definition backed by a checkpoint and an app-owned delivery policy. */\nexport type EDADurableSinkDefinition = EDAProjectedDurableSinkDefinition;\n\n/** Best-effort live-only sink definition. */\nexport interface EDAEphemeralSinkDefinition {\n readonly interests?:\n | \"*\"\n | Schema.Codec<import(\"../types/events\").EventEnvelope, unknown, never, never>;\n readonly process: (event: PositionedEvent, ctx: EDASinkContext) => Effect.Effect<void, never>;\n}\n\n/**\n * Named app integration hook with optional durable and ephemeral filters.\n *\n * Every sink runs on one serialized position-ordered lane. Sinks own retry and\n * terminal failure handling, so callbacks have no typed error channel except a\n * `stageDurable` refusal, which stops the runner without acknowledging the batch.\n * An unexpected defect is logged and skipped before the durable checkpoint\n * advances. Ephemeral callbacks are best-effort and are only processed after the\n * durable prefix at their anchor sequence has been projected.\n */\ninterface EDASinkOptions {\n readonly name: string;\n readonly ephemeral?: EDAEphemeralSinkDefinition;\n}\n\n/** Existing consumers receive framework and app projections unless explicitly opted out. */\nexport interface EDAProjectedSink extends EDASinkOptions {\n readonly state?: \"projected\";\n readonly durable?: EDAProjectedDurableSinkDefinition;\n}\n\n/** Raw consumers retain only their cursor and sink-owned checkpoint payload. */\nexport interface EDARawSink extends EDASinkOptions {\n readonly state: \"none\";\n readonly durable?: EDARawDurableSinkDefinition;\n}\n\n/** The outer discriminant preserves contextual callback typing for inline default sinks. */\nexport type EDASink = EDAProjectedSink | EDARawSink;\n\n/** Projected and raw overloads preserve contextual callback inference and literal names. */\nfunction makeSink<const Sink extends EDAProjectedSink>(sink: Sink): Sink;\nfunction makeSink<const Sink extends EDARawSink>(sink: Sink): Sink;\nfunction makeSink<const Sink extends EDASink>(sink: Sink): Sink;\nfunction makeSink(sink: EDASink): EDASink {\n return sink;\n}\n\n/** Convenience constructor preserving a sink's literal name/type information. */\nexport const EDASink = {\n make: makeSink,\n /** The live-event schema owns both subscription filtering and callback typing. */\n forEphemeralEvents: <E extends import(\"../types/events\").EventEnvelope>(\n interests: Schema.Codec<E, unknown, never, never>,\n process: (event: PositionedEvent<E>, ctx: EDASinkContext) => Effect.Effect<void, never>,\n ): EDAEphemeralSinkDefinition => ({\n interests,\n process: (entry, ctx) =>\n Schema.is(interests)(entry.event)\n ? process({ position: entry.position, event: entry.event }, ctx)\n : Effect.void,\n }),\n /** One schema selects and narrows the facts delivered to a projected durable consumer. */\n forEvents: <E extends DurableEventEnvelope>(\n interests: Schema.Codec<E, unknown, never, never>,\n sink: Omit<EDAProjectedSink, \"durable\"> & {\n readonly durable: {\n readonly batchSize?: number;\n readonly process: (\n batch: EDASinkDurableBatch<E>,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n };\n },\n ): EDAProjectedSink => ({\n ...sink,\n durable: {\n ...sink.durable,\n interests,\n process: (batch, ctx) =>\n sink.durable.process(\n {\n ...batch,\n events: batch.events.flatMap((entry) => {\n const selected = selectCommittedEvent(interests, entry);\n return selected === undefined ? [] : [selected];\n }),\n },\n ctx,\n ),\n },\n }),\n};\n\n/** Session-owned capabilities needed to start all registered sink runners. */\nexport interface EDASinkRunnerStartInput {\n readonly appendDurableBatch: (\n events: ReadonlyArray<DurableEventEnvelope>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Immutable framework and app projections at one common durable head. */\n readonly initialProjection: {\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n };\n readonly publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n readonly scope: Scope.Scope;\n}\n\n/** Registry service coordinating durable checkpoints and live sink delivery. */\nexport interface EDASinkRegistryShape {\n readonly sinks: ReadonlyArray<EDASink>;\n /** Start long-lived sink runners. Safe to call once during session-state acquisition. */\n readonly startSinkRunners: (\n input: EDASinkRunnerStartInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Coalesced non-blocking nudge that the durable log head advanced. */\n readonly notifyDurableHeadAdvanced: (head: SequenceNumber) => Effect.Effect<void>;\n /** Best-effort non-blocking delivery to ephemeral sink workers. */\n readonly publishEphemeralToSinks: (event: PositionedEvent) => Effect.Effect<void>;\n}\n\n/** Registry and runner for app-provided EDA sinks. */\nexport class EDASinkRegistry extends Context.Service<EDASinkRegistry, EDASinkRegistryShape>()(\n \"@effect-durable-agent/EDASinkRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDASinkRegistry, {\n sinks: [],\n startSinkRunners: () => Effect.void,\n notifyDurableHeadAdvanced: () => Effect.void,\n publishEphemeralToSinks: () => Effect.void,\n } satisfies EDASinkRegistryShape);\n\n static readonly Live = (sinks: ReadonlyArray<EDASink>) =>\n Layer.effect(EDASinkRegistry, makeSinkRegistry(sinks));\n}\n\nconst defaultBatchSize = 100;\nconst sinkCheckpointFormatVersion = 1;\n\ninterface SinkProjection {\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\ninterface SerializedSinkState {\n readonly formatVersion: typeof sinkCheckpointFormatVersion;\n readonly state: unknown;\n readonly updatedAtMs: number;\n}\n\nconst makeSinkRegistry = (sinks: ReadonlyArray<EDASink>) =>\n Effect.gen(function* () {\n const session = yield* SessionContext;\n const store = yield* EDASessionStore;\n const checkpointStore = yield* SinkCheckpointStore;\n const eventFactory = yield* EventFactory;\n const ids = yield* IdGenerator;\n const reducerRegistry = yield* EDAReducerRegistry;\n const keepAlive = yield* EDAKeepAlive;\n const appEventAdmission = makeAppEventAdmission(yield* RegisteredAppEvents);\n const started = yield* Ref.make(false);\n const hydrationGate = yield* Semaphore.make(1);\n const deliveries: Array<{\n readonly sink: EDASink;\n readonly inbox: Effect.Success<ReturnType<typeof makeSinkInbox>>;\n }> = [];\n\n const baseContext = (\n sinkName: string,\n staged: Array<AdmittedAppEvent>,\n publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>,\n scope: Scope.Scope,\n checkpoint: EDASinkCheckpoint,\n ): EDASinkContext => ({\n sessionId: session.sessionId,\n checkpoint,\n events: eventFactory,\n makeEventId: ids.makeEventId,\n emitEphemeral: publishEphemeral,\n stageDurable: (event) =>\n Effect.gen(function* () {\n const admitted = appEventAdmission.admit(event);\n if (Result.isFailure(admitted)) return yield* appEventConflict(admitted.failure);\n // Staged events and the cursor commit separately; only a key collapses a restaged event.\n if (event.dedupeKey === undefined) {\n yield* Effect.logWarning(\"EDA sink staged a durable event without a dedupeKey\", {\n sink: sinkName,\n namespace: event.namespace,\n type: event.type,\n });\n }\n staged.push(admitted.success);\n }),\n forkScoped: (effect) => effect.pipe(Effect.forkIn(scope), Effect.asVoid),\n });\n\n const makeSinkRunner = Effect.fnUntraced(function* (\n sink: EDASink,\n { initialProjection, appendDurableBatch, publishEphemeral, scope }: EDASinkRunnerStartInput,\n ) {\n // Long-lived fibers capture the head and capabilities, not the initial projection.\n const initialHead = initialProjection.reduced.lastSeq;\n const sinkName = EDASinkName.make(sink.name);\n const storedCheckpoint = yield* checkpointStore.load(sinkName);\n const checkpointRef = yield* SynchronizedRef.make(storedCheckpoint);\n const checkpoint = makeSinkCheckpoint(checkpointStore, sinkName, checkpointRef);\n const cursor = storedCheckpoint.afterSeq;\n const cursorRef = yield* Ref.make(cursor);\n if (cursor > initialHead) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} cursor exceeds session head`,\n });\n }\n // Keep only an exact projection seed; lagging workers reconstruct in their own scope.\n const state = yield* Ref.make<SinkProjection | undefined>(\n sink.state === \"none\"\n ? undefined\n : cursor === initialHead\n ? {\n reduced: initialProjection.reduced,\n reducerStates: initialProjection.reducerStates,\n }\n : cursor === 0\n ? { reduced: initialReducedState, reducerStates: reducerRegistry.initial }\n : undefined,\n );\n const inbox = yield* makeSinkInbox(initialHead).pipe(Scope.provide(scope));\n deliveries.push({ sink, inbox });\n const ensureProjection = Effect.fnUntraced(function* () {\n const existing = yield* Ref.get(state);\n if (existing !== undefined) return existing;\n const hydrated = yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((event) => event.position.seq <= cursor),\n Stream.chunks,\n Stream.runFold(\n (): SinkProjection => ({\n reduced: initialReducedState,\n reducerStates: reducerRegistry.initial,\n }),\n (current, page): SinkProjection => ({\n reduced: foldReducedState(current.reduced, page),\n reducerStates: reducerRegistry.reduce(current.reducerStates, page),\n }),\n ),\n Effect.withSpan(\"agent.sink.hydrate\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.session.id\": session.sessionId,\n \"eda.seq.through\": cursor,\n },\n }),\n hydrationGate.withPermits(1),\n );\n if (hydrated.reduced.lastSeq !== cursor) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} could not reconstruct its cursor`,\n });\n }\n yield* Ref.set(state, hydrated);\n return hydrated;\n });\n\n const processDurableBatch = Effect.fnUntraced(function* (\n allEvents: ReadonlyArray<CommittedDurableEvent>,\n ) {\n if (allEvents.length === 0) {\n return;\n }\n\n const currentCursor = yield* Ref.get(cursorRef);\n const fresh = allEvents.filter((entry) => entry.position.seq > currentCursor);\n if (fresh.length === 0) {\n return;\n }\n\n const durable = sink.durable;\n const last = fresh.at(-1);\n if (last === undefined) return;\n const throughSeq = last.position.seq;\n const nextProjection =\n sink.state === \"none\"\n ? undefined\n : yield* Effect.gen(function* () {\n const current = yield* ensureProjection();\n return {\n reduced: foldReducedState(current.reduced, fresh),\n reducerStates: reducerRegistry.reduce(current.reducerStates, fresh),\n };\n });\n const eventsForSink =\n durable === undefined ? [] : filterInterested(fresh, durable.interests);\n\n if (durable !== undefined && eventsForSink.length > 0) {\n yield* Effect.gen(function* () {\n const staged: Array<AdmittedAppEvent> = [];\n const rawBatch: EDASinkRawDurableBatch = {\n allEvents: fresh,\n events: eventsForSink,\n throughSeq,\n };\n const context = baseContext(sink.name, staged, publishEphemeral, scope, checkpoint);\n const delivery = Effect.gen(function* () {\n if (sink.durable === undefined) return;\n if (sink.state === \"none\") return yield* sink.durable.process(rawBatch, context);\n // The projected branch owns both construction and delivery of these fields.\n if (nextProjection === undefined)\n return yield* Effect.die(\"Projected sink missing its projection\");\n return yield* sink.durable.process(\n {\n ...rawBatch,\n stateAfter: nextProjection.reduced,\n reducerStates: nextProjection.reducerStates,\n },\n context,\n );\n });\n const completed = yield* delivery.pipe(\n Effect.as(true),\n Effect.catchCause((cause) => {\n if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);\n // Skipping would acknowledge a batch whose staged facts never commit: stop instead.\n const refusal = stagedEventRefusal(cause);\n if (refusal !== undefined) return Effect.fail(refusal);\n return Effect.logError(\"EDA durable sink violated its infallible contract\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }).pipe(Effect.as(false));\n }),\n );\n if (completed && staged.length > 0) {\n yield* annotateEdaSpan({ \"eda.sink.staged_events\": staged.length });\n yield* appendDurableBatch(staged);\n }\n }).pipe(\n Effect.withSpan(\"agent.sink.drain\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.sink.cursor.before\": currentCursor,\n \"eda.sink.events.read\": fresh.length,\n \"eda.sink.events.interested\": eventsForSink.length,\n \"eda.sink.cursor.after\": throughSeq,\n },\n }),\n );\n }\n\n yield* commitSinkCheckpoint(checkpointStore, sinkName, checkpointRef, throughSeq);\n yield* Ref.set(cursorRef, throughSeq);\n yield* Ref.set(state, nextProjection);\n });\n\n const drainDurablesThrough = Effect.fnUntraced(function* (targetHead: SequenceNumber) {\n const currentCursor = yield* Ref.get(cursorRef);\n if (currentCursor >= targetHead) return;\n const allEvents = yield* readCursorBatchThrough(\n store,\n currentCursor,\n targetHead,\n sink.durable?.batchSize,\n );\n if (allEvents.length === 0) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} could not read its durable backlog`,\n });\n }\n yield* processDurableBatch(allEvents);\n });\n\n const processEphemeral = Effect.fnUntraced(function* (event: PositionedEvent) {\n if (sink.ephemeral === undefined) return;\n if (sink.state !== \"none\") yield* ensureProjection();\n yield* sink.ephemeral\n .process(event, baseContext(sink.name, [], publishEphemeral, scope, checkpoint))\n .pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA sink ephemeral projection failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n });\n\n const runLoop = Effect.forever(\n Effect.gen(function* () {\n const currentCursor = yield* Ref.get(cursorRef);\n const work = yield* inbox.poll(currentCursor);\n if (work === undefined) {\n yield* inbox.awaitWork;\n return;\n }\n yield* keepAlive.withActiveWork(\n `sink:${sink.name}`,\n work._tag === \"Durable\"\n ? drainDurablesThrough(work.throughSeq)\n : processEphemeral(work.event),\n );\n yield* Effect.yieldNow;\n }),\n ).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA sink runner failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n\n return {\n runLoop,\n initialization:\n sink.state === \"none\"\n ? \"raw\"\n : cursor === initialHead\n ? \"reused\"\n : cursor > 0\n ? \"deferred\"\n : \"empty\",\n };\n });\n\n return {\n sinks,\n startSinkRunners: Effect.fnUntraced(function* (input: EDASinkRunnerStartInput) {\n const wasStarted = yield* Ref.getAndSet(started, true);\n if (wasStarted) {\n return;\n }\n const runners = yield* Effect.gen(function* () {\n const runners = yield* Effect.forEach(sinks, (sink) => makeSinkRunner(sink, input), {\n concurrency: 1,\n });\n yield* Effect.annotateCurrentSpan({\n \"eda.sinks.raw\": runners.filter((runner) => runner.initialization === \"raw\").length,\n \"eda.sinks.reused\": runners.filter((runner) => runner.initialization === \"reused\")\n .length,\n \"eda.sinks.deferred\": runners.filter((runner) => runner.initialization === \"deferred\")\n .length,\n \"eda.sinks.empty\": runners.filter((runner) => runner.initialization === \"empty\").length,\n });\n return runners;\n }).pipe(\n Effect.withSpan(\"agent.sinks.initialize\", {\n attributes: {\n sessionId: session.sessionId,\n \"eda.session.id\": session.sessionId,\n \"eda.seq.head\": input.initialProjection.reduced.lastSeq,\n \"eda.sinks.count\": sinks.length,\n },\n }),\n );\n // Catch-up can append events. Register every inbox before starting any delivery fiber.\n yield* Effect.forEach(\n runners,\n (runner) => runner.runLoop.pipe(Effect.forkIn(input.scope)),\n {\n discard: true,\n },\n );\n }),\n notifyDurableHeadAdvanced: (head) =>\n Effect.forEach(deliveries, ({ inbox }) => inbox.notify(head), { discard: true }),\n publishEphemeralToSinks: (event) =>\n Effect.forEach(\n deliveries,\n ({ sink, inbox }) => {\n if (\n sink.ephemeral === undefined ||\n !matchesInterest(event.event, sink.ephemeral.interests)\n )\n return Effect.void;\n return Effect.gen(function* () {\n const accepted = yield* inbox.offerEphemeral(event);\n if (!accepted) {\n yield* Effect.logWarning(\"EDA sink ephemeral buffer full\", { sink: sink.name });\n }\n }).pipe(\n Effect.catchTag(\"SinkEphemeralEncodingError\", (error) =>\n Effect.logWarning(\"EDA sink ephemeral serialization failed\", {\n cause: error.cause,\n sink: sink.name,\n }),\n ),\n );\n },\n { discard: true },\n ),\n } satisfies EDASinkRegistryShape;\n });\n\n/** The `stageDurable` refusal a sink let escape, as a failure or (through `orDie`) a defect. */\nconst stagedEventRefusal = (\n cause: Cause.Cause<unknown>,\n): SessionCommandAdmissionConflict | undefined => {\n for (const reason of cause.reasons) {\n const value = Cause.isFailReason(reason)\n ? reason.error\n : Cause.isDieReason(reason)\n ? reason.defect\n : undefined;\n if (value instanceof SessionCommandAdmissionConflict) return value;\n }\n return undefined;\n};\n\nconst makeSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n): EDASinkCheckpoint => ({\n get: (schema, initial) =>\n SynchronizedRef.get(checkpointRef).pipe(\n Effect.flatMap((checkpoint) => {\n const serialized = serializedSinkState(checkpoint.payload);\n return serialized === undefined\n ? Effect.succeed(initial)\n : decodeSinkState(schema, serialized.state);\n }),\n ),\n save: (schema, state) =>\n encodeSinkState(schema, state).pipe(\n Effect.flatMap((encoded) => {\n const payload: SerializedSinkState = {\n formatVersion: sinkCheckpointFormatVersion,\n state: encoded,\n updatedAtMs: Date.now(),\n };\n return SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.saveState(sinkName, payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq: checkpoint.afterSeq,\n payload,\n },\n ] as const),\n ),\n );\n }),\n ),\n});\n\nconst commitSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n afterSeq: SequenceNumber,\n): Effect.Effect<void, EDASessionStoreError> =>\n SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.commit(sinkName, afterSeq, checkpoint.payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq,\n payload: checkpoint.payload,\n },\n ] as const),\n ),\n );\n\nconst serializedSinkState = (payload: unknown): SerializedSinkState | undefined => {\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n !(\"formatVersion\" in payload) ||\n payload.formatVersion !== sinkCheckpointFormatVersion ||\n !(\"state\" in payload) ||\n !(\"updatedAtMs\" in payload) ||\n typeof payload.updatedAtMs !== \"number\"\n ) {\n return undefined;\n }\n return {\n formatVersion: sinkCheckpointFormatVersion,\n state: payload.state,\n updatedAtMs: payload.updatedAtMs,\n };\n};\n\nconst decodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n encoded: unknown,\n): Effect.Effect<State, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(schema)(encoded),\n catch: (cause) => sinkCheckpointCodecError(\"decoding\", cause),\n });\n\nconst encodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n): Effect.Effect<unknown, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.encodeUnknownSync(schema)(state),\n catch: (cause) => sinkCheckpointCodecError(\"encoding\", cause),\n });\n\nconst sinkCheckpointCodecError = (operation: string, cause: unknown) =>\n new EDASessionStoreError({\n message:\n cause instanceof Error\n ? `${operation} sink checkpoint: ${cause.message}`\n : `${operation} sink checkpoint: ${String(cause)}`,\n });\n\nconst readCursorBatchThrough = (\n store: EDASessionStoreShape,\n afterSeq: SequenceNumber,\n throughSeq: SequenceNumber,\n batchSize = defaultBatchSize,\n) =>\n store.eventsAfter(afterSeq).pipe(\n Stream.takeWhile((event) => event.position.seq <= throughSeq),\n Stream.take(batchSize),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n\nconst filterInterested = (\n events: ReadonlyArray<CommittedDurableEvent>,\n interests: EDASinkInterests | undefined,\n): ReadonlyArray<CommittedDurableEvent> =>\n events.filter(\n (entry) =>\n interests === undefined ||\n interests === \"*\" ||\n selectCommittedEvent(interests, entry) !== undefined,\n );\n\nconst matchesInterest = (\n event: import(\"../types/events\").EventEnvelope,\n interests:\n | \"*\"\n | Schema.Codec<import(\"../types/events\").EventEnvelope, unknown, never, never>\n | undefined,\n): boolean => interests === undefined || interests === \"*\" || Schema.is(interests)(event);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAQA,MAAM,oBAAoB;AAC1B,MAAM,wBAAwB;;AAG9B,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EAAE,OAAO,OAAO,OAAO,EAAE,CAC3B,CAAC,CAAC,CAAC;;;;;AAWH,MAAa,gBAAgB,OAAO,WAAW,WAAW,aAA6B;CACrF,MAAM,OAAO,OAAO,OAAO,eAAe,MAAM,QAAc,CAAC,GAAG,MAAM,QAAQ;CAChF,IAAI,OAAO;CACX,MAAM,UAA8E,CAAC;CACrF,IAAI,eAAe;CAEnB,MAAM,UAAU,eACd,OAAO,WAAW;EAChB,OAAO,eAAe,KAAK,KAAK,IAAI,MAAM,UAAU,CAAC;EACrD,MAAM,YAAY,MAAM,KAAA,CAAS;CACnC,CAAC;CAEH,MAAM,kBAAkB,UACtB,OAAO,IAAI;EACT,WAAW;GACT,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC,CAAC;GAC9D,IAAI,QAAQ,UAAU,qBAAqB,QAAQ,wBAAwB,cACzE,OAAO;GAET,QAAQ,KAAK;IAAE;IAAO;GAAM,CAAC;GAC7B,gBAAgB;GAChB,MAAM,YAAY,MAAM,KAAA,CAAS;GACjC,OAAO;EACT;EACA,QAAQ,UAAU,IAAI,2BAA2B,EAAE,MAAM,CAAC;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;CACnD,QAAQ,UAAU,yBAAyB,YAAY,KAAK;AAC9D,CAAC;AAEH,MAAM,mBACJ,QACA,UAEA,OAAO,IAAI;CACT,WAAW,OAAO,kBAAkB,MAAM,CAAC,CAAC,KAAK;CACjD,QAAQ,UAAU,yBAAyB,YAAY,KAAK;AAC9D,CAAC;AAEH,MAAM,4BAA4B,WAAmB,UACnD,IAAI,qBAAqB,EACvB,SACE,iBAAiB,QACb,GAAG,UAAU,oBAAoB,MAAM,YACvC,GAAG,UAAU,oBAAoB,OAAO,KAAK,IACrD,CAAC;AAEH,MAAM,0BACJ,OACA,UACA,YACA,YAAY,qBAEZ,MAAM,YAAY,QAAQ,CAAC,CAAC,KAC1B,OAAO,WAAW,UAAU,MAAM,SAAS,OAAO,UAAU,GAC5D,OAAO,KAAK,SAAS,GACrB,OAAO,YACP,OAAO,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAC3C;AAEF,MAAM,oBACJ,QACA,cAEA,OAAO,QACJ,UACC,cAAc,KAAA,KACd,cAAc,OACd,qBAAqB,WAAW,KAAK,MAAM,KAAA,CAC/C;AAEF,MAAM,mBACJ,OACA,cAIY,cAAc,KAAA,KAAa,cAAc,OAAO,OAAO,GAAG,SAAS,CAAC,CAAC,KAAK"}
|
|
1
|
+
{"version":3,"file":"sink-registry-CjdKeTUM.js","names":[],"sources":["../src/services/sink-inbox.ts","../src/services/sink-registry.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\n\n/** Durable payloads stay in the log; only bounded best-effort ephemeral work is retained. */\nconst ephemeralCapacity = 128;\nconst ephemeralByteCapacity = 256 * 1024;\n\n/** An ephemeral update could not be measured as a JSON wire value. */\nexport class SinkEphemeralEncodingError extends Schema.TaggedError<SinkEphemeralEncodingError>()(\n \"SinkEphemeralEncodingError\",\n { cause: Schema.Defect() },\n) {}\n\n/** One ordered step on a sink's serialized delivery lane. */\ntype SinkWork =\n | { readonly _tag: \"Durable\"; readonly throughSeq: SequenceNumber }\n | { readonly _tag: \"Ephemeral\"; readonly event: PositionedEvent };\n\n/**\n * Coalesces durable heads without losing ephemeral ordering barriers. Publication never\n * waits for delivery. Overflow drops the newest ephemeral update, never durable work.\n */\nexport const makeSinkInbox = Effect.fnUntraced(function* (initialHead: SequenceNumber) {\n const wake = yield* Effect.acquireRelease(Queue.sliding<void>(1), Queue.shutdown);\n let head = initialHead;\n const pending: Array<{ readonly event: PositionedEvent; readonly bytes: number }> = [];\n let pendingBytes = 0;\n\n const notify = (throughSeq: SequenceNumber) =>\n Effect.sync(() => {\n head = SequenceNumber.make(Math.max(head, throughSeq));\n Queue.offerUnsafe(wake, undefined);\n });\n\n const offerEphemeral = (event: PositionedEvent) =>\n Effect.try({\n try: () => {\n const bytes = new TextEncoder().encode(JSON.stringify(event)).byteLength;\n if (pending.length >= ephemeralCapacity || bytes > ephemeralByteCapacity - pendingBytes) {\n return false;\n }\n pending.push({ event, bytes });\n pendingBytes += bytes;\n Queue.offerUnsafe(wake, undefined);\n return true;\n },\n catch: (cause) => new SinkEphemeralEncodingError({ cause }),\n });\n\n const poll = (cursor: SequenceNumber): Effect.Effect<SinkWork | undefined> =>\n Effect.sync(() => {\n while (pending.length > 0) {\n const first = pending[0];\n if (first === undefined) break;\n if (first.event.position.seq > cursor) {\n return { _tag: \"Durable\", throughSeq: first.event.position.seq };\n }\n pending.shift();\n pendingBytes -= first.bytes;\n if (first.event.position.seq === cursor) {\n return { _tag: \"Ephemeral\", event: first.event };\n }\n }\n return cursor < head ? { _tag: \"Durable\", throughSeq: head } : undefined;\n });\n\n return { notify, offerEphemeral, poll, awaitWork: Queue.take(wake) };\n});\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { type DecodedDurableEvent } from \"../types/events/durable\";\nimport { selectCommittedEvent } from \"./session-store\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport { foldReducedState, initialReducedState, type ReducedState } from \"../domain/reduced-state\";\nimport { EDAReducerRegistry, type EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { EventId, SessionId, SequenceNumber } from \"../types/core\";\nimport type {\n DurableEventEnvelope,\n EphemeralEventEnvelope,\n PositionedEvent,\n} from \"../types/events\";\nimport type { EDASessionStoreShape } from \"./session-store\";\nimport { type CommittedDurableEvent, EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { EventFactory } from \"./event-factory\";\nimport type { EventFactoryShape } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { makeSinkInbox } from \"./sink-inbox\";\nimport {\n appEventConflict,\n makeAppEventAdmission,\n RegisteredAppEvents,\n SessionCommandAdmissionConflict,\n type AdmittedAppEvent,\n} from \"./session-admission\";\nimport { SessionContext } from \"./session-context\";\nimport {\n EDASinkName,\n SinkCheckpointStore,\n type SinkCheckpointStoreShape,\n type StoredSinkCheckpoint,\n} from \"./sink-checkpoint-store\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Cursor-window input delivered to one durable sink drain. */\nexport interface EDASinkRawDurableBatch<E = DecodedDurableEvent> {\n /** All durable events replayed for this cursor window, including uninterested events. */\n readonly allEvents: ReadonlyArray<CommittedDurableEvent>;\n /** Events matching the sink's durable interests. */\n readonly events: ReadonlyArray<CommittedDurableEvent<E>>;\n /** Durable sequence through which the sink may advance after success. */\n readonly throughSeq: SequenceNumber;\n}\n\n/** Cursor window with framework and app projections, enabled by default. */\nexport interface EDASinkDurableBatch<E = DecodedDurableEvent> extends EDASinkRawDurableBatch<E> {\n /** Authoritative reduced state folded exactly through `throughSeq`. */\n readonly stateAfter: ReducedState;\n /** App-specific durable reducer states folded exactly through `throughSeq`. */\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\n/** Typed, sink-owned durable state stored independently from cursor advancement. */\nexport interface EDASinkCheckpoint {\n /** Decode current durable state, or return `initial` for a new or legacy cursor row. */\n readonly get: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n initial: State,\n ) => Effect.Effect<State, EDASessionStoreError>;\n /** Validate, encode, and durably save state without advancing the sink cursor. */\n readonly save: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/** Capabilities exposed to sink processors without granting raw store or bus access. */\nexport interface EDASinkContext {\n readonly sessionId: SessionId;\n /** Sink-owned checkpoint state, serialized with cursor commits and background writes. */\n readonly checkpoint: EDASinkCheckpoint;\n /**\n * Build a framework durable event. `stageDurable` accepts only the framework types app code may\n * write (`SessionConfigured`, `SystemMessageCommitted`, `AssistantMessageImported`).\n */\n readonly events: EventFactoryShape;\n /** Mint an app durable event id for staged custom events. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Publish a best-effort live-only event. */\n readonly emitEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n /**\n * Stage durable events; the runner commits them after the sink succeeds, in a transaction\n * separate from the cursor commit. A crash between the two redelivers the batch, so give each\n * staged event a `dedupeKey` derived from what caused it; one without a key logs a warning.\n *\n * An event the app event admission rules refuse fails with a `SessionCommandAdmissionConflict`\n * and is not staged: a framework lifecycle event (`framework_event`), a payload that is not\n * JSON-native (`payload_not_json`) or is over `maxAppEventBytes` (`event_too_large`), or one\n * the registered `appEvents` schema rejects (`invalid_event`). A sink that catches it keeps\n * what it staged besides. One that lets it escape `process` stops its runner before the batch\n * is acknowledged: nothing staged in that delivery commits, the cursor stays, and the next\n * runtime start redelivers the batch.\n */\n readonly stageDurable: (\n event: DurableEventEnvelope,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n /** Fork background sink work into the session scope. */\n readonly forkScoped: (effect: Effect.Effect<unknown, unknown>) => Effect.Effect<void>;\n}\n\n/** `\"*\"` and omission select every fact; a schema selects and narrows matching envelopes. */\nexport type EDASinkInterests = \"*\" | Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\n/** Delivery policy shared by raw and projected durable consumers. */\ninterface EDADurableSinkOptions {\n readonly interests?: EDASinkInterests;\n readonly batchSize?: number;\n}\n\n/** Default durable consumer with framework and app projections at each cursor window. */\nexport interface EDAProjectedDurableSinkDefinition extends EDADurableSinkOptions {\n readonly process: (\n batch: EDASinkDurableBatch,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n}\n\n/** Raw consumer that never hydrates, folds, or retains a session projection. */\nexport interface EDARawDurableSinkDefinition extends EDADurableSinkOptions {\n readonly process: (\n batch: EDASinkRawDurableBatch,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n}\n\n/** Durable sink definition backed by a checkpoint and an app-owned delivery policy. */\nexport type EDADurableSinkDefinition = EDAProjectedDurableSinkDefinition;\n\n/** Best-effort live-only sink definition. */\nexport interface EDAEphemeralSinkDefinition {\n readonly interests?:\n | \"*\"\n | Schema.Codec<import(\"../types/events\").EventEnvelope, unknown, never, never>;\n readonly process: (event: PositionedEvent, ctx: EDASinkContext) => Effect.Effect<void, never>;\n}\n\n/**\n * Named app integration hook with optional durable and ephemeral filters.\n *\n * Every sink runs on one serialized position-ordered lane. Sinks own retry and\n * terminal failure handling, so callbacks have no typed error channel except a\n * `stageDurable` refusal, which stops the runner without acknowledging the batch.\n * An unexpected defect is logged and skipped before the durable checkpoint\n * advances. Ephemeral callbacks are best-effort and are only processed after the\n * durable prefix at their anchor sequence has been projected.\n */\ninterface EDASinkOptions {\n readonly name: string;\n readonly ephemeral?: EDAEphemeralSinkDefinition;\n}\n\n/** Existing consumers receive framework and app projections unless explicitly opted out. */\nexport interface EDAProjectedSink extends EDASinkOptions {\n readonly state?: \"projected\";\n readonly durable?: EDAProjectedDurableSinkDefinition;\n}\n\n/** Raw consumers retain only their cursor and sink-owned checkpoint payload. */\nexport interface EDARawSink extends EDASinkOptions {\n readonly state: \"none\";\n readonly durable?: EDARawDurableSinkDefinition;\n}\n\n/** The outer discriminant preserves contextual callback typing for inline default sinks. */\nexport type EDASink = EDAProjectedSink | EDARawSink;\n\n/** Projected and raw overloads preserve contextual callback inference and literal names. */\nfunction makeSink<const Sink extends EDAProjectedSink>(sink: Sink): Sink;\nfunction makeSink<const Sink extends EDARawSink>(sink: Sink): Sink;\nfunction makeSink<const Sink extends EDASink>(sink: Sink): Sink;\nfunction makeSink(sink: EDASink): EDASink {\n return sink;\n}\n\n/** Convenience constructor preserving a sink's literal name/type information. */\nexport const EDASink = {\n make: makeSink,\n /** The live-event schema owns both subscription filtering and callback typing. */\n forEphemeralEvents: <E extends import(\"../types/events\").EventEnvelope>(\n interests: Schema.Codec<E, unknown, never, never>,\n process: (event: PositionedEvent<E>, ctx: EDASinkContext) => Effect.Effect<void, never>,\n ): EDAEphemeralSinkDefinition => ({\n interests,\n process: (entry, ctx) =>\n Schema.is(interests)(entry.event)\n ? process({ position: entry.position, event: entry.event }, ctx)\n : Effect.void,\n }),\n /** One schema selects and narrows the facts delivered to a projected durable consumer. */\n forEvents: <E extends DurableEventEnvelope>(\n interests: Schema.Codec<E, unknown, never, never>,\n sink: Omit<EDAProjectedSink, \"durable\"> & {\n readonly durable: {\n readonly batchSize?: number;\n readonly process: (\n batch: EDASinkDurableBatch<E>,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, SessionCommandAdmissionConflict>;\n };\n },\n ): EDAProjectedSink => ({\n ...sink,\n durable: {\n ...sink.durable,\n interests,\n process: (batch, ctx) =>\n sink.durable.process(\n {\n ...batch,\n events: batch.events.flatMap((entry) => {\n const selected = selectCommittedEvent(interests, entry);\n return selected === undefined ? [] : [selected];\n }),\n },\n ctx,\n ),\n },\n }),\n};\n\n/** Session-owned capabilities needed to start all registered sink runners. */\nexport interface EDASinkRunnerStartInput {\n readonly appendDurableBatch: (\n events: ReadonlyArray<DurableEventEnvelope>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Immutable framework and app projections at one common durable head. */\n readonly initialProjection: {\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n };\n readonly publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n readonly scope: Scope.Scope;\n}\n\n/** Registry service coordinating durable checkpoints and live sink delivery. */\nexport interface EDASinkRegistryShape {\n readonly sinks: ReadonlyArray<EDASink>;\n /** Start long-lived sink runners. Safe to call once during session-state acquisition. */\n readonly startSinkRunners: (\n input: EDASinkRunnerStartInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Coalesced non-blocking nudge that the durable log head advanced. */\n readonly notifyDurableHeadAdvanced: (head: SequenceNumber) => Effect.Effect<void>;\n /** Best-effort non-blocking delivery to ephemeral sink workers. */\n readonly publishEphemeralToSinks: (event: PositionedEvent) => Effect.Effect<void>;\n}\n\n/** Registry and runner for app-provided EDA sinks. */\nexport class EDASinkRegistry extends Context.Service<EDASinkRegistry, EDASinkRegistryShape>()(\n \"@effect-durable-agent/EDASinkRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDASinkRegistry, {\n sinks: [],\n startSinkRunners: () => Effect.void,\n notifyDurableHeadAdvanced: () => Effect.void,\n publishEphemeralToSinks: () => Effect.void,\n } satisfies EDASinkRegistryShape);\n\n static readonly Live = (sinks: ReadonlyArray<EDASink>) =>\n Layer.effect(EDASinkRegistry, makeSinkRegistry(sinks));\n}\n\nconst defaultBatchSize = 100;\nconst sinkCheckpointFormatVersion = 1;\n\ninterface SinkProjection {\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\ninterface SerializedSinkState {\n readonly formatVersion: typeof sinkCheckpointFormatVersion;\n readonly state: unknown;\n readonly updatedAtMs: number;\n}\n\nconst makeSinkRegistry = (sinks: ReadonlyArray<EDASink>) =>\n Effect.gen(function* () {\n const session = yield* SessionContext;\n const store = yield* EDASessionStore;\n const checkpointStore = yield* SinkCheckpointStore;\n const eventFactory = yield* EventFactory;\n const ids = yield* IdGenerator;\n const reducerRegistry = yield* EDAReducerRegistry;\n const keepAlive = yield* EDAKeepAlive;\n const appEventAdmission = makeAppEventAdmission(yield* RegisteredAppEvents);\n const started = yield* Ref.make(false);\n const hydrationGate = yield* Semaphore.make(1);\n const deliveries: Array<{\n readonly sink: EDASink;\n readonly inbox: Effect.Success<ReturnType<typeof makeSinkInbox>>;\n }> = [];\n\n const baseContext = (\n sinkName: string,\n staged: Array<AdmittedAppEvent>,\n publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>,\n scope: Scope.Scope,\n checkpoint: EDASinkCheckpoint,\n ): EDASinkContext => ({\n sessionId: session.sessionId,\n checkpoint,\n events: eventFactory,\n makeEventId: ids.makeEventId,\n emitEphemeral: publishEphemeral,\n stageDurable: (event) =>\n Effect.gen(function* () {\n const admitted = appEventAdmission.admit(event);\n if (Result.isFailure(admitted)) return yield* appEventConflict(admitted.failure);\n // Staged events and the cursor commit separately; only a key collapses a restaged event.\n if (event.dedupeKey === undefined) {\n yield* Effect.logWarning(\"EDA sink staged a durable event without a dedupeKey\", {\n sink: sinkName,\n namespace: event.namespace,\n type: event.type,\n });\n }\n staged.push(admitted.success);\n }),\n forkScoped: (effect) => effect.pipe(Effect.forkIn(scope), Effect.asVoid),\n });\n\n const makeSinkRunner = Effect.fnUntraced(function* (\n sink: EDASink,\n { initialProjection, appendDurableBatch, publishEphemeral, scope }: EDASinkRunnerStartInput,\n ) {\n // Long-lived fibers capture the head and capabilities, not the initial projection.\n const initialHead = initialProjection.reduced.lastSeq;\n const sinkName = EDASinkName.make(sink.name);\n const storedCheckpoint = yield* checkpointStore.load(sinkName);\n const checkpointRef = yield* SynchronizedRef.make(storedCheckpoint);\n const checkpoint = makeSinkCheckpoint(checkpointStore, sinkName, checkpointRef);\n const cursor = storedCheckpoint.afterSeq;\n const cursorRef = yield* Ref.make(cursor);\n if (cursor > initialHead) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} cursor exceeds session head`,\n });\n }\n // Keep only an exact projection seed; lagging workers reconstruct in their own scope.\n const state = yield* Ref.make<SinkProjection | undefined>(\n sink.state === \"none\"\n ? undefined\n : cursor === initialHead\n ? {\n reduced: initialProjection.reduced,\n reducerStates: initialProjection.reducerStates,\n }\n : cursor === 0\n ? { reduced: initialReducedState, reducerStates: reducerRegistry.initial }\n : undefined,\n );\n const inbox = yield* makeSinkInbox(initialHead).pipe(Scope.provide(scope));\n deliveries.push({ sink, inbox });\n const ensureProjection = Effect.fnUntraced(function* () {\n const existing = yield* Ref.get(state);\n if (existing !== undefined) return existing;\n const hydrated = yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((event) => event.position.seq <= cursor),\n Stream.chunks,\n Stream.runFold(\n (): SinkProjection => ({\n reduced: initialReducedState,\n reducerStates: reducerRegistry.initial,\n }),\n (current, page): SinkProjection => ({\n reduced: foldReducedState(current.reduced, page),\n reducerStates: reducerRegistry.reduce(current.reducerStates, page),\n }),\n ),\n Effect.withSpan(\"agent.sink.hydrate\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.session.id\": session.sessionId,\n \"eda.seq.through\": cursor,\n },\n }),\n hydrationGate.withPermits(1),\n );\n if (hydrated.reduced.lastSeq !== cursor) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} could not reconstruct its cursor`,\n });\n }\n yield* Ref.set(state, hydrated);\n return hydrated;\n });\n\n const processDurableBatch = Effect.fnUntraced(function* (\n allEvents: ReadonlyArray<CommittedDurableEvent>,\n ) {\n if (allEvents.length === 0) {\n return;\n }\n\n const currentCursor = yield* Ref.get(cursorRef);\n const fresh = allEvents.filter((entry) => entry.position.seq > currentCursor);\n if (fresh.length === 0) {\n return;\n }\n\n const durable = sink.durable;\n const last = fresh.at(-1);\n if (last === undefined) return;\n const throughSeq = last.position.seq;\n const nextProjection =\n sink.state === \"none\"\n ? undefined\n : yield* Effect.gen(function* () {\n const current = yield* ensureProjection();\n return {\n reduced: foldReducedState(current.reduced, fresh),\n reducerStates: reducerRegistry.reduce(current.reducerStates, fresh),\n };\n });\n const eventsForSink =\n durable === undefined ? [] : filterInterested(fresh, durable.interests);\n\n if (durable !== undefined && eventsForSink.length > 0) {\n yield* Effect.gen(function* () {\n const staged: Array<AdmittedAppEvent> = [];\n const rawBatch: EDASinkRawDurableBatch = {\n allEvents: fresh,\n events: eventsForSink,\n throughSeq,\n };\n const context = baseContext(sink.name, staged, publishEphemeral, scope, checkpoint);\n const delivery = Effect.gen(function* () {\n if (sink.durable === undefined) return;\n if (sink.state === \"none\") return yield* sink.durable.process(rawBatch, context);\n // The projected branch owns both construction and delivery of these fields.\n if (nextProjection === undefined)\n return yield* Effect.die(\"Projected sink missing its projection\");\n return yield* sink.durable.process(\n {\n ...rawBatch,\n stateAfter: nextProjection.reduced,\n reducerStates: nextProjection.reducerStates,\n },\n context,\n );\n });\n const completed = yield* delivery.pipe(\n Effect.as(true),\n Effect.catchCause((cause) => {\n if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);\n // Skipping would acknowledge a batch whose staged facts never commit: stop instead.\n const refusal = stagedEventRefusal(cause);\n if (refusal !== undefined) return Effect.fail(refusal);\n return Effect.logError(\"EDA durable sink violated its infallible contract\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }).pipe(Effect.as(false));\n }),\n );\n if (completed && staged.length > 0) {\n yield* annotateEdaSpan({ \"eda.sink.staged_events\": staged.length });\n yield* appendDurableBatch(staged);\n }\n }).pipe(\n Effect.withSpan(\"agent.sink.drain\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.sink.cursor.before\": currentCursor,\n \"eda.sink.events.read\": fresh.length,\n \"eda.sink.events.interested\": eventsForSink.length,\n \"eda.sink.cursor.after\": throughSeq,\n },\n }),\n );\n }\n\n yield* commitSinkCheckpoint(checkpointStore, sinkName, checkpointRef, throughSeq);\n yield* Ref.set(cursorRef, throughSeq);\n yield* Ref.set(state, nextProjection);\n });\n\n const drainDurablesThrough = Effect.fnUntraced(function* (targetHead: SequenceNumber) {\n const currentCursor = yield* Ref.get(cursorRef);\n if (currentCursor >= targetHead) return;\n const allEvents = yield* readCursorBatchThrough(\n store,\n currentCursor,\n targetHead,\n sink.durable?.batchSize,\n );\n if (allEvents.length === 0) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} could not read its durable backlog`,\n });\n }\n yield* processDurableBatch(allEvents);\n });\n\n const processEphemeral = Effect.fnUntraced(function* (event: PositionedEvent) {\n if (sink.ephemeral === undefined) return;\n if (sink.state !== \"none\") yield* ensureProjection();\n yield* sink.ephemeral\n .process(event, baseContext(sink.name, [], publishEphemeral, scope, checkpoint))\n .pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA sink ephemeral projection failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n });\n\n const runLoop = Effect.forever(\n Effect.gen(function* () {\n const currentCursor = yield* Ref.get(cursorRef);\n const work = yield* inbox.poll(currentCursor);\n if (work === undefined) {\n yield* inbox.awaitWork;\n return;\n }\n yield* keepAlive.withActiveWork(\n `sink:${sink.name}`,\n work._tag === \"Durable\"\n ? drainDurablesThrough(work.throughSeq)\n : processEphemeral(work.event),\n );\n yield* Effect.yieldNow;\n }),\n ).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA sink runner failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n\n return {\n runLoop,\n initialization:\n sink.state === \"none\"\n ? \"raw\"\n : cursor === initialHead\n ? \"reused\"\n : cursor > 0\n ? \"deferred\"\n : \"empty\",\n };\n });\n\n return {\n sinks,\n startSinkRunners: Effect.fnUntraced(function* (input: EDASinkRunnerStartInput) {\n const wasStarted = yield* Ref.getAndSet(started, true);\n if (wasStarted) {\n return;\n }\n const runners = yield* Effect.gen(function* () {\n const runners = yield* Effect.forEach(sinks, (sink) => makeSinkRunner(sink, input), {\n concurrency: 1,\n });\n yield* Effect.annotateCurrentSpan({\n \"eda.sinks.raw\": runners.filter((runner) => runner.initialization === \"raw\").length,\n \"eda.sinks.reused\": runners.filter((runner) => runner.initialization === \"reused\")\n .length,\n \"eda.sinks.deferred\": runners.filter((runner) => runner.initialization === \"deferred\")\n .length,\n \"eda.sinks.empty\": runners.filter((runner) => runner.initialization === \"empty\").length,\n });\n return runners;\n }).pipe(\n Effect.withSpan(\"agent.sinks.initialize\", {\n attributes: {\n sessionId: session.sessionId,\n \"eda.session.id\": session.sessionId,\n \"eda.seq.head\": input.initialProjection.reduced.lastSeq,\n \"eda.sinks.count\": sinks.length,\n },\n }),\n );\n // Catch-up can append events. Register every inbox before starting any delivery fiber.\n yield* Effect.forEach(\n runners,\n (runner) => runner.runLoop.pipe(Effect.forkIn(input.scope)),\n {\n discard: true,\n },\n );\n }),\n notifyDurableHeadAdvanced: (head) =>\n Effect.forEach(deliveries, ({ inbox }) => inbox.notify(head), { discard: true }),\n publishEphemeralToSinks: (event) =>\n Effect.forEach(\n deliveries,\n ({ sink, inbox }) => {\n if (\n sink.ephemeral === undefined ||\n !matchesInterest(event.event, sink.ephemeral.interests)\n )\n return Effect.void;\n return Effect.gen(function* () {\n const accepted = yield* inbox.offerEphemeral(event);\n if (!accepted) {\n yield* Effect.logWarning(\"EDA sink ephemeral buffer full\", { sink: sink.name });\n }\n }).pipe(\n Effect.catchTag(\"SinkEphemeralEncodingError\", (error) =>\n Effect.logWarning(\"EDA sink ephemeral serialization failed\", {\n cause: error.cause,\n sink: sink.name,\n }),\n ),\n );\n },\n { discard: true },\n ),\n } satisfies EDASinkRegistryShape;\n });\n\n/** The `stageDurable` refusal a sink let escape, as a failure or (through `orDie`) a defect. */\nconst stagedEventRefusal = (\n cause: Cause.Cause<unknown>,\n): SessionCommandAdmissionConflict | undefined => {\n for (const reason of cause.reasons) {\n const value = Cause.isFailReason(reason)\n ? reason.error\n : Cause.isDieReason(reason)\n ? reason.defect\n : undefined;\n if (value instanceof SessionCommandAdmissionConflict) return value;\n }\n return undefined;\n};\n\nconst makeSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n): EDASinkCheckpoint => ({\n get: (schema, initial) =>\n SynchronizedRef.get(checkpointRef).pipe(\n Effect.flatMap((checkpoint) => {\n const serialized = serializedSinkState(checkpoint.payload);\n return serialized === undefined\n ? Effect.succeed(initial)\n : decodeSinkState(schema, serialized.state);\n }),\n ),\n save: (schema, state) =>\n encodeSinkState(schema, state).pipe(\n Effect.flatMap((encoded) => {\n const payload: SerializedSinkState = {\n formatVersion: sinkCheckpointFormatVersion,\n state: encoded,\n updatedAtMs: Date.now(),\n };\n return SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.saveState(sinkName, payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq: checkpoint.afterSeq,\n payload,\n },\n ] as const),\n ),\n );\n }),\n ),\n});\n\nconst commitSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n afterSeq: SequenceNumber,\n): Effect.Effect<void, EDASessionStoreError> =>\n SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.commit(sinkName, afterSeq, checkpoint.payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq,\n payload: checkpoint.payload,\n },\n ] as const),\n ),\n );\n\nconst serializedSinkState = (payload: unknown): SerializedSinkState | undefined => {\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n !(\"formatVersion\" in payload) ||\n payload.formatVersion !== sinkCheckpointFormatVersion ||\n !(\"state\" in payload) ||\n !(\"updatedAtMs\" in payload) ||\n typeof payload.updatedAtMs !== \"number\"\n ) {\n return undefined;\n }\n return {\n formatVersion: sinkCheckpointFormatVersion,\n state: payload.state,\n updatedAtMs: payload.updatedAtMs,\n };\n};\n\nconst decodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n encoded: unknown,\n): Effect.Effect<State, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(schema)(encoded),\n catch: (cause) => sinkCheckpointCodecError(\"decoding\", cause),\n });\n\nconst encodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n): Effect.Effect<unknown, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.encodeUnknownSync(schema)(state),\n catch: (cause) => sinkCheckpointCodecError(\"encoding\", cause),\n });\n\nconst sinkCheckpointCodecError = (operation: string, cause: unknown) =>\n new EDASessionStoreError({\n message:\n cause instanceof Error\n ? `${operation} sink checkpoint: ${cause.message}`\n : `${operation} sink checkpoint: ${String(cause)}`,\n });\n\nconst readCursorBatchThrough = (\n store: EDASessionStoreShape,\n afterSeq: SequenceNumber,\n throughSeq: SequenceNumber,\n batchSize = defaultBatchSize,\n) =>\n store.eventsAfter(afterSeq).pipe(\n Stream.takeWhile((event) => event.position.seq <= throughSeq),\n Stream.take(batchSize),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n\nconst filterInterested = (\n events: ReadonlyArray<CommittedDurableEvent>,\n interests: EDASinkInterests | undefined,\n): ReadonlyArray<CommittedDurableEvent> =>\n events.filter(\n (entry) =>\n interests === undefined ||\n interests === \"*\" ||\n selectCommittedEvent(interests, entry) !== undefined,\n );\n\nconst matchesInterest = (\n event: import(\"../types/events\").EventEnvelope,\n interests:\n | \"*\"\n | Schema.Codec<import(\"../types/events\").EventEnvelope, unknown, never, never>\n | undefined,\n): boolean => interests === undefined || interests === \"*\" || Schema.is(interests)(event);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAQA,MAAM,oBAAoB;AAC1B,MAAM,wBAAwB;;AAG9B,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EAAE,OAAO,OAAO,OAAO,EAAE,CAC3B,CAAC,CAAC,CAAC;;;;;AAWH,MAAa,gBAAgB,OAAO,WAAW,WAAW,aAA6B;CACrF,MAAM,OAAO,OAAO,OAAO,eAAe,MAAM,QAAc,CAAC,GAAG,MAAM,QAAQ;CAChF,IAAI,OAAO;CACX,MAAM,UAA8E,CAAC;CACrF,IAAI,eAAe;CAEnB,MAAM,UAAU,eACd,OAAO,WAAW;EAChB,OAAO,eAAe,KAAK,KAAK,IAAI,MAAM,UAAU,CAAC;EACrD,MAAM,YAAY,MAAM,KAAA,CAAS;CACnC,CAAC;CAEH,MAAM,kBAAkB,UACtB,OAAO,IAAI;EACT,WAAW;GACT,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC,CAAC;GAC9D,IAAI,QAAQ,UAAU,qBAAqB,QAAQ,wBAAwB,cACzE,OAAO;GAET,QAAQ,KAAK;IAAE;IAAO;GAAM,CAAC;GAC7B,gBAAgB;GAChB,MAAM,YAAY,MAAM,KAAA,CAAS;GACjC,OAAO;EACT;EACA,QAAQ,UAAU,IAAI,2BAA2B,EAAE,MAAM,CAAC;CAC5D,CAAC;CAEH,MAAM,QAAQ,WACZ,OAAO,WAAW;EAChB,OAAO,QAAQ,SAAS,GAAG;GACzB,MAAM,QAAQ,QAAQ;GACtB,IAAI,UAAU,KAAA,GAAW;GACzB,IAAI,MAAM,MAAM,SAAS,MAAM,QAC7B,OAAO;IAAE,MAAM;IAAW,YAAY,MAAM,MAAM,SAAS;GAAI;GAEjE,Q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B,EACvB,SACE,iBAAiB,QACb,GAAG,UAAU,oBAAoB,MAAM,YACvC,GAAG,UAAU,oBAAoB,OAAO,KAAK,IACrD,CAAC;AAEH,MAAM,0BACJ,OACA,UACA,YACA,YAAY,qBAEZ,MAAM,YAAY,QAAQ,CAAC,CAAC,KAC1B,OAAO,WAAW,UAAU,MAAM,SAAS,OAAO,UAAU,GAC5D,OAAO,KAAK,SAAS,GACrB,OAAO,YACP,OAAO,KAAK,WAAW,MAAM,KAAK,MAAM,CAAC,CAC3C;AAEF,MAAM,oBACJ,QACA,cAEA,OAAO,QACJ,UACC,cAAc,KAAA,KACd,cAAc,OACd,qBAAqB,WAAW,KAAK,MAAM,KAAA,CAC/C;AAEF,MAAM,mBACJ,OACA,cAIY,cAAc,KAAA,KAAa,cAAc,OAAO,OAAO,GAAG,SAAS,CAAC,CAAC,KAAK"}
|
package/dist/testkit/layers.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import "../events-AIIwZ6dS.js";
|
|
|
4
4
|
import { c as EDASessionStoreShape, i as EDAAppEvents, o as EDASessionStore, s as EDASessionStoreError } from "../session-store-DaSHeg8Q.js";
|
|
5
5
|
import { t as ModelResolver } from "../model-resolver-O8Kn27GH.js";
|
|
6
6
|
import { r as EDAReducerRegistry, t as EDAReducer } from "../reducer-registry-Bqn5B4JO.js";
|
|
7
|
-
import {
|
|
7
|
+
import { At as EDASink, Bn as EDADecider, It as EDASinkRegistry, Kt as CompactionPolicy, Vt as CompactionExecutor, Yt as CompactionRunner, _t as InferenceRunner, bt as RunScheduler, cr as EDAPromptProjector, dn as ToolParamsSchema, ft as SessionState, gt as TurnRunner, ir as SessionContext, ln as EDAToolRegistry, on as EventFactory, sn as EDAModelToolkit, un as EDAToolRegistryShape, vn as EDASessionQuery, vt as InferenceRunnerStreamPart, xn as LiveEventBus, yt as ToolExecutor } from "../reduced-state-DV0696_s.js";
|
|
8
8
|
import { t as SessionEventObserver } from "../session-event-observer-BWQUJTcN.js";
|
|
9
9
|
import { t as IdGenerator } from "../id-generator-BKGoKjt-.js";
|
|
10
10
|
import { t as EDAKeepAlive } from "../keep-alive-_zFCUvt3.js";
|
package/dist/testkit/layers.js
CHANGED
|
@@ -2,17 +2,17 @@ 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 { _ as UnixEpochMillis } from "../envelope-BSI_Xh-f.js";
|
|
5
|
-
import { d as InferenceRunner, f as ToolExecutor, l as SessionState, p as LiveEventBus, u as TurnRunner } from "../session-state-
|
|
6
|
-
import { t as RegisteredAppEvents } from "../session-admission-
|
|
5
|
+
import { d as InferenceRunner, f as ToolExecutor, l as SessionState, p as LiveEventBus, u as TurnRunner } from "../session-state-BbJW2_P0.js";
|
|
6
|
+
import { t as RegisteredAppEvents } from "../session-admission-DC98zwtj.js";
|
|
7
7
|
import { EDASessionStore, registerAppEvents } from "../services/session-store.js";
|
|
8
|
-
import { a as CompactionPolicy, n as CompactionExecutor, o as CompactionRunner } from "../compaction-
|
|
8
|
+
import { a as CompactionPolicy, n as CompactionExecutor, o as CompactionRunner } from "../compaction-Dlq4wgZE.js";
|
|
9
9
|
import { EDAPromptProjector } from "../services/prompt-projector.js";
|
|
10
10
|
import { n as SessionContext, t as EventFactory } from "../event-factory-BUoBwqAy.js";
|
|
11
11
|
import { EDAToolRegistry } from "../services/tool-registry.js";
|
|
12
12
|
import { IdGenerator } from "../services/id-generator.js";
|
|
13
13
|
import { EDAKeepAlive } from "../services/keep-alive.js";
|
|
14
14
|
import { EDAReducerRegistry } from "../services/reducer-registry.js";
|
|
15
|
-
import { n as EDASinkRegistry } from "../sink-registry-
|
|
15
|
+
import { n as EDASinkRegistry } from "../sink-registry-CjdKeTUM.js";
|
|
16
16
|
import { SinkCheckpointStore } from "../services/sink-checkpoint-store.js";
|
|
17
17
|
import { EDADeciderRegistry, makeEDADeciderRegistry } from "../services/decider.js";
|
|
18
18
|
import { EDASessionQuery } from "../services/session-query.js";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as EDAWebSocketWireProtocol, A as EDA_WS_CLOSE_LAGGED, B as EDAFrameworkWebSocketEvent, C as EDAWebSocketHelloFrame, D as EDAWebSocketServerFrame, E as EDAWebSocketPongFrame, F as SubscriberId, G as EDAWebSocketWireClientFrame, H as EDAWebSocketServerFrameEncoder, I as decodeEDAWebSocketClientMessage, J as EDAWebSocketWireHeartbeatFrame, K as EDAWebSocketWireErrorFrame, L as defaultEDAWebSocketFlowControl, M as EDA_WS_CLOSE_SEND_FAILED, N as EDA_WS_CLOSE_UNSUPPORTED_DATA, O as EDA_WEB_SOCKET_PROTOCOL_VERSION, P as FrameId, Q as EDAWebSocketWirePongFrame, R as encodeEDAWebSocketServerFrame, S as EDAWebSocketHeartbeatFrame, T as EDAWebSocketPingFrame, U as EDAWebSocketServerFrameInput, V as EDAWebSocketEventConsumerPolicy, W as EDAWebSocketWireAckFrame, X as EDAWebSocketWireLaggedFrame, Y as EDAWebSocketWireHelloFrame, Z as EDAWebSocketWirePingFrame, _ as EDAWebSocketAckFrame, a as EDAWebSocketInFlightFrame, b as EDAWebSocketEventsFrame, c as SubscriberLagReason, d as makeWebSocketDeliveryState, et as EDA_WEB_SOCKET_PING_MESSAGE, f as onClientAck, g as restoreWebSocketDeliveryState, h as onHostSuppressedFrame, i as EDAWebSocketDeliveryState, it as makeEDAWebSocketWireProtocol, j as EDA_WS_CLOSE_PROTOCOL_ERROR, k as EDA_WS_CLOSE_GOING_AWAY, l as checkpointWebSocketDeliveryState, m as onEphemeralEvent, n as EDAWebSocketDeliveryCheckpoint, nt as EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION, o as EDAWebSocketSuppressedRange, p as onDurableEvents, q as EDAWebSocketWireFlowControl, r as EDAWebSocketDeliveryResult, rt as edaFrameworkWebSocketWireProtocol, s as MakeDeliveryStateInput, t as EDAWebSocketDeliveryAction, tt as EDA_WEB_SOCKET_PONG_MESSAGE, u as deliveryHelloFrame, v as EDAWebSocketClientFrame, w as EDAWebSocketLaggedFrame, x as EDAWebSocketFlowControl, y as EDAWebSocketErrorFrame, z as laggedCloseReason } from "../delivery-
|
|
1
|
+
import { $ as EDAWebSocketWireProtocol, A as EDA_WS_CLOSE_LAGGED, B as EDAFrameworkWebSocketEvent, C as EDAWebSocketHelloFrame, D as EDAWebSocketServerFrame, E as EDAWebSocketPongFrame, F as SubscriberId, G as EDAWebSocketWireClientFrame, H as EDAWebSocketServerFrameEncoder, I as decodeEDAWebSocketClientMessage, J as EDAWebSocketWireHeartbeatFrame, K as EDAWebSocketWireErrorFrame, L as defaultEDAWebSocketFlowControl, M as EDA_WS_CLOSE_SEND_FAILED, N as EDA_WS_CLOSE_UNSUPPORTED_DATA, O as EDA_WEB_SOCKET_PROTOCOL_VERSION, P as FrameId, Q as EDAWebSocketWirePongFrame, R as encodeEDAWebSocketServerFrame, S as EDAWebSocketHeartbeatFrame, T as EDAWebSocketPingFrame, U as EDAWebSocketServerFrameInput, V as EDAWebSocketEventConsumerPolicy, W as EDAWebSocketWireAckFrame, X as EDAWebSocketWireLaggedFrame, Y as EDAWebSocketWireHelloFrame, Z as EDAWebSocketWirePingFrame, _ as EDAWebSocketAckFrame, a as EDAWebSocketInFlightFrame, b as EDAWebSocketEventsFrame, c as SubscriberLagReason, d as makeWebSocketDeliveryState, et as EDA_WEB_SOCKET_PING_MESSAGE, f as onClientAck, g as restoreWebSocketDeliveryState, h as onHostSuppressedFrame, i as EDAWebSocketDeliveryState, it as makeEDAWebSocketWireProtocol, j as EDA_WS_CLOSE_PROTOCOL_ERROR, k as EDA_WS_CLOSE_GOING_AWAY, l as checkpointWebSocketDeliveryState, m as onEphemeralEvent, n as EDAWebSocketDeliveryCheckpoint, nt as EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION, o as EDAWebSocketSuppressedRange, p as onDurableEvents, q as EDAWebSocketWireFlowControl, r as EDAWebSocketDeliveryResult, rt as edaFrameworkWebSocketWireProtocol, s as MakeDeliveryStateInput, t as EDAWebSocketDeliveryAction, tt as EDA_WEB_SOCKET_PONG_MESSAGE, u as deliveryHelloFrame, v as EDAWebSocketClientFrame, w as EDAWebSocketLaggedFrame, x as EDAWebSocketFlowControl, y as EDAWebSocketErrorFrame, z as laggedCloseReason } from "../delivery-BKYmgnKC.js";
|
|
2
2
|
export { EDAFrameworkWebSocketEvent, EDAWebSocketAckFrame, EDAWebSocketClientFrame, EDAWebSocketDeliveryAction, EDAWebSocketDeliveryCheckpoint, EDAWebSocketDeliveryResult, EDAWebSocketDeliveryState, EDAWebSocketErrorFrame, EDAWebSocketEventConsumerPolicy, EDAWebSocketEventsFrame, EDAWebSocketFlowControl, EDAWebSocketHeartbeatFrame, EDAWebSocketHelloFrame, EDAWebSocketInFlightFrame, EDAWebSocketLaggedFrame, EDAWebSocketPingFrame, EDAWebSocketPongFrame, EDAWebSocketServerFrame, EDAWebSocketServerFrameEncoder, EDAWebSocketServerFrameInput, EDAWebSocketSuppressedRange, EDAWebSocketWireAckFrame, EDAWebSocketWireClientFrame, EDAWebSocketWireErrorFrame, EDAWebSocketWireFlowControl, EDAWebSocketWireHeartbeatFrame, EDAWebSocketWireHelloFrame, EDAWebSocketWireLaggedFrame, EDAWebSocketWirePingFrame, EDAWebSocketWirePongFrame, EDAWebSocketWireProtocol, EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE, EDA_WEB_SOCKET_PROTOCOL_VERSION, EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION, EDA_WS_CLOSE_GOING_AWAY, EDA_WS_CLOSE_LAGGED, EDA_WS_CLOSE_PROTOCOL_ERROR, EDA_WS_CLOSE_SEND_FAILED, EDA_WS_CLOSE_UNSUPPORTED_DATA, FrameId, MakeDeliveryStateInput, SubscriberId, SubscriberLagReason, checkpointWebSocketDeliveryState, decodeEDAWebSocketClientMessage, defaultEDAWebSocketFlowControl, deliveryHelloFrame, edaFrameworkWebSocketWireProtocol, encodeEDAWebSocketServerFrame, laggedCloseReason, makeEDAWebSocketWireProtocol, makeWebSocketDeliveryState, onClientAck, onDurableEvents, onEphemeralEvent, onHostSuppressedFrame, restoreWebSocketDeliveryState };
|
package/dist/websocket.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { h as SequenceNumber } from "./core-BcimKMIv.js";
|
|
2
2
|
import { C as TranscriptReadiness, E as TranscriptWindow, It as TranscriptVersion, ht as TranscriptLogIncarnation, wt as TranscriptRecordView, x as TranscriptActiveContent } from "./session-store-DaSHeg8Q.js";
|
|
3
3
|
import { r as TranscriptSubscriptionBase, s as TranscriptUpdate, t as TranscriptCoverage } from "./subscription-BhwUmsl4.js";
|
|
4
|
-
import { $ as EDAWebSocketWireProtocol, A as EDA_WS_CLOSE_LAGGED, B as EDAFrameworkWebSocketEvent, C as EDAWebSocketHelloFrame, D as EDAWebSocketServerFrame, E as EDAWebSocketPongFrame, F as SubscriberId, G as EDAWebSocketWireClientFrame, H as EDAWebSocketServerFrameEncoder, I as decodeEDAWebSocketClientMessage, J as EDAWebSocketWireHeartbeatFrame, K as EDAWebSocketWireErrorFrame, L as defaultEDAWebSocketFlowControl, M as EDA_WS_CLOSE_SEND_FAILED, N as EDA_WS_CLOSE_UNSUPPORTED_DATA, O as EDA_WEB_SOCKET_PROTOCOL_VERSION, P as FrameId, Q as EDAWebSocketWirePongFrame, R as encodeEDAWebSocketServerFrame, S as EDAWebSocketHeartbeatFrame, T as EDAWebSocketPingFrame, U as EDAWebSocketServerFrameInput, V as EDAWebSocketEventConsumerPolicy, W as EDAWebSocketWireAckFrame, X as EDAWebSocketWireLaggedFrame, Y as EDAWebSocketWireHelloFrame, Z as EDAWebSocketWirePingFrame, _ as EDAWebSocketAckFrame, a as EDAWebSocketInFlightFrame, b as EDAWebSocketEventsFrame, c as SubscriberLagReason, d as makeWebSocketDeliveryState, et as EDA_WEB_SOCKET_PING_MESSAGE, f as onClientAck, g as restoreWebSocketDeliveryState, h as onHostSuppressedFrame, i as EDAWebSocketDeliveryState, it as makeEDAWebSocketWireProtocol, j as EDA_WS_CLOSE_PROTOCOL_ERROR, k as EDA_WS_CLOSE_GOING_AWAY, l as checkpointWebSocketDeliveryState, m as onEphemeralEvent, n as EDAWebSocketDeliveryCheckpoint, nt as EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION, o as EDAWebSocketSuppressedRange, p as onDurableEvents, q as EDAWebSocketWireFlowControl, r as EDAWebSocketDeliveryResult, rt as edaFrameworkWebSocketWireProtocol, s as MakeDeliveryStateInput, t as EDAWebSocketDeliveryAction, tt as EDA_WEB_SOCKET_PONG_MESSAGE, u as deliveryHelloFrame, v as EDAWebSocketClientFrame, w as EDAWebSocketLaggedFrame, x as EDAWebSocketFlowControl, y as EDAWebSocketErrorFrame, z as laggedCloseReason } from "./delivery-
|
|
4
|
+
import { $ as EDAWebSocketWireProtocol, A as EDA_WS_CLOSE_LAGGED, B as EDAFrameworkWebSocketEvent, C as EDAWebSocketHelloFrame, D as EDAWebSocketServerFrame, E as EDAWebSocketPongFrame, F as SubscriberId, G as EDAWebSocketWireClientFrame, H as EDAWebSocketServerFrameEncoder, I as decodeEDAWebSocketClientMessage, J as EDAWebSocketWireHeartbeatFrame, K as EDAWebSocketWireErrorFrame, L as defaultEDAWebSocketFlowControl, M as EDA_WS_CLOSE_SEND_FAILED, N as EDA_WS_CLOSE_UNSUPPORTED_DATA, O as EDA_WEB_SOCKET_PROTOCOL_VERSION, P as FrameId, Q as EDAWebSocketWirePongFrame, R as encodeEDAWebSocketServerFrame, S as EDAWebSocketHeartbeatFrame, T as EDAWebSocketPingFrame, U as EDAWebSocketServerFrameInput, V as EDAWebSocketEventConsumerPolicy, W as EDAWebSocketWireAckFrame, X as EDAWebSocketWireLaggedFrame, Y as EDAWebSocketWireHelloFrame, Z as EDAWebSocketWirePingFrame, _ as EDAWebSocketAckFrame, a as EDAWebSocketInFlightFrame, b as EDAWebSocketEventsFrame, c as SubscriberLagReason, d as makeWebSocketDeliveryState, et as EDA_WEB_SOCKET_PING_MESSAGE, f as onClientAck, g as restoreWebSocketDeliveryState, h as onHostSuppressedFrame, i as EDAWebSocketDeliveryState, it as makeEDAWebSocketWireProtocol, j as EDA_WS_CLOSE_PROTOCOL_ERROR, k as EDA_WS_CLOSE_GOING_AWAY, l as checkpointWebSocketDeliveryState, m as onEphemeralEvent, n as EDAWebSocketDeliveryCheckpoint, nt as EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION, o as EDAWebSocketSuppressedRange, p as onDurableEvents, q as EDAWebSocketWireFlowControl, r as EDAWebSocketDeliveryResult, rt as edaFrameworkWebSocketWireProtocol, s as MakeDeliveryStateInput, t as EDAWebSocketDeliveryAction, tt as EDA_WEB_SOCKET_PONG_MESSAGE, u as deliveryHelloFrame, v as EDAWebSocketClientFrame, w as EDAWebSocketLaggedFrame, x as EDAWebSocketFlowControl, y as EDAWebSocketErrorFrame, z as laggedCloseReason } from "./delivery-BKYmgnKC.js";
|
|
5
5
|
import * as Schema from "effect/Schema";
|
|
6
6
|
//#region src/websocket/transcript.d.ts
|
|
7
7
|
/**
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-D7WJa899.js","names":[],"sources":["../src/services/provider-usage.ts","../src/services/compaction.ts"],"sourcesContent":["import type * as Response from \"effect/ai/Response\";\nimport { UsagePayload } from \"../types/events\";\n\n/** Normalizes provider usage for both conversation and compaction calls. */\nexport const makeUsagePayload = (usage: Response.Usage) => {\n const uncachedInputTokens = nonNegativeInt(usage.inputTokens.uncached);\n const cachedInputTokens = nonNegativeInt(usage.inputTokens.cacheRead);\n const cacheWriteInputTokens = nonNegativeInt(usage.inputTokens.cacheWrite);\n const inputTokens =\n nonNegativeInt(usage.inputTokens.total) ??\n sumDefined([uncachedInputTokens, cachedInputTokens, cacheWriteInputTokens]);\n const textTokens = nonNegativeInt(usage.outputTokens.text);\n const reasoningTokens = nonNegativeInt(usage.outputTokens.reasoning);\n const outputTokens =\n nonNegativeInt(usage.outputTokens.total) ?? sumDefined([textTokens, reasoningTokens]);\n\n return UsagePayload.make({\n ...(inputTokens === undefined ? {} : { inputTokens }),\n ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),\n ...(cacheWriteInputTokens === undefined ? {} : { cacheWriteInputTokens }),\n ...(outputTokens === undefined ? {} : { outputTokens }),\n ...(textTokens === undefined ? {} : { textTokens }),\n ...(reasoningTokens === undefined ? {} : { reasoningTokens }),\n });\n};\n\nconst sumDefined = (values: ReadonlyArray<number | undefined>) => {\n const present = values.filter((value): value is number => value !== undefined);\n return present.length === 0 ? undefined : present.reduce((sum, value) => sum + value, 0);\n};\n\nconst nonNegativeInt = (value: number | undefined) =>\n value === undefined || !Number.isFinite(value) ? undefined : Math.max(0, Math.trunc(value));\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Prompt from \"effect/ai/Prompt\";\nimport * as Schema from \"effect/Schema\";\nimport type * as LanguageModel from \"effect/ai/LanguageModel\";\nimport { ModelResolver } from \"./model-resolver\";\nimport { generateTextOfferingTools } from \"./model-call\";\nimport { makeUsagePayload } from \"./provider-usage\";\nimport { buildEDAPrompt, EDAPromptProjector } from \"./prompt-projector\";\nimport type { EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { SessionContext } from \"./session-context\";\nimport { EDAToolRegistry, type EDAModelToolkit } from \"./tool-registry\";\n\nimport type { ContextProjection } from \"../domain/context-projection\";\nimport {\n durableMessageTranscript,\n projectionStateThrough,\n type DurableTranscriptMessage,\n} from \"../domain/message-transcript\";\nimport {\n CompactionExecutorId,\n CompactionPolicyId,\n CompactionSummaryArtifact,\n} from \"../domain/context-projection\";\nimport type { ReducedState } from \"../domain/reduced-state\";\nimport { InferenceId, ContextVersion, SequenceNumber } from \"../types/core\";\nimport { FailurePayload, UsagePayload, type AssistantMessageContent } from \"../types/events\";\nimport { CommittedDurableEvent, DurableAppendEntry, EDASessionStoreError } from \"./session-store\";\nimport { EventFactory } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { annotateEdaSpan, committedBatchAttributes } from \"./tracing\";\n\n/** Candidate durable range and retained cursor selected by compaction policy. */\nexport const CompactionPlan = Schema.Struct({\n policyId: CompactionPolicyId,\n sourceFromSeq: SequenceNumber,\n sourceToSeq: SequenceNumber,\n retainedFromContextSeq: SequenceNumber,\n});\nexport type CompactionPlan = typeof CompactionPlan.Type;\n\n/** Rough token heuristic used by the built-in compaction presets. */\nexport const defaultCompactionCharsPerToken = 4;\n\n/** Production-oriented context threshold for the built-in approximate-token policy. */\nexport const defaultCompactionThresholdTokens = 220_000;\n\n/** Recent model-facing tail retained verbatim by the built-in approximate-token policy. */\nexport const defaultCompactionRetainTailTokens = 40_000;\n\n/** Minimum newly summarizable prefix needed before the approximate-token policy plans work. */\nexport const defaultCompactionMinSummarizableTokens = 10_000;\n\n/** Approximate-token policy options for common production compaction. */\nexport interface ApproximateTokenThresholdCompactionPolicyOptions {\n /** Stable policy id stored on summary artifacts. */\n readonly policyId?: string;\n /** Context-size threshold that triggers compaction. Defaults to 220k tokens. */\n readonly thresholdTokens?: number;\n /** Recent tail retained verbatim after compaction. Defaults to 40k tokens. */\n readonly retainTailTokens?: number;\n /** Smallest prefix worth summarizing. Defaults to 10k tokens. */\n readonly minSummarizableTokens?: number;\n /** Character-to-token divisor for the approximate estimator. Defaults to 4. */\n readonly charsPerToken?: number;\n /**\n * What stays verbatim after the summary. `tail-tokens` (default) keeps roughly\n * `retainTailTokens` of recent context. `last-response` keeps exactly the latest assistant\n * response and what followed it, so the summarized range equals the prompt of a request already\n * sent: provider caches cover the compaction call and provider-native compaction keeps the\n * retained response's reasoning valid.\n */\n readonly retain?: \"tail-tokens\" | \"last-response\";\n}\n\n/** LanguageModel-backed summary executor options. */\nexport interface LanguageModelSummaryCompactionExecutorOptions {\n /** Stable executor id stored on summary artifacts. */\n readonly executorId?: string;\n /** Prefix used for the synthetic prompt message inserted into future context. */\n readonly summaryMessagePrefix?: string;\n}\n\n/** Input visible to policy decisions. */\nexport interface CompactionPolicyInput {\n readonly state: ReducedState;\n readonly context: ContextProjection;\n}\n\n/** Result produced by the summary executor before the framework commits it. */\nexport const CompactionOutput = Schema.Struct({\n text: Schema.NonEmptyString,\n promptMessage: Prompt.UserMessage,\n executorId: Schema.optionalKey(CompactionExecutorId),\n usage: Schema.optionalKey(UsagePayload),\n});\nexport type CompactionOutput = typeof CompactionOutput.Type;\n\n/** Executor input with framework-minted lifecycle identities. */\nexport interface CompactionExecutorInput extends CompactionPolicyInput {\n readonly plan: CompactionPlan;\n /** Provider service resolved from the same durable selection used for accounting. */\n readonly model: LanguageModel.LanguageModel;\n /**\n * The provider prompt as it stood through `plan.sourceToSeq`: the same instructions, history and\n * trailing context an inference at that point would send. Executors that reuse it share the\n * conversation's provider cache.\n */\n readonly prompt: Prompt.Prompt;\n /** Tools offered with every inference; reusing them keeps the cached prefix identical. */\n readonly toolkit: EDAModelToolkit | undefined;\n}\n\n/** Typed failure from policy planning or summary generation. */\nexport class CompactionError extends Schema.TaggedError<CompactionError>()(\"CompactionError\", {\n message: Schema.String,\n usage: Schema.optionalKey(UsagePayload),\n}) {}\n\n/** Service contract for deciding whether the current context should be compacted. */\nexport interface CompactionPolicyShape {\n readonly id: CompactionPolicyId;\n readonly plan: (\n input: CompactionPolicyInput,\n ) => Effect.Effect<CompactionPlan | undefined, CompactionError>;\n}\n\n/** Decides whether a safe prompt-context rebase should be attempted. */\nexport class CompactionPolicy extends Context.Service<CompactionPolicy, CompactionPolicyShape>()(\n \"@effect-durable-agent/CompactionPolicy\",\n) {\n /** Default policy: compaction is disabled and commits no skip events. */\n static readonly Disabled = Layer.succeed(CompactionPolicy, {\n id: CompactionPolicyId.make(\"disabled\"),\n plan: () => Effect.succeed(undefined),\n } satisfies CompactionPolicyShape);\n\n /** Test/app hook for replacing the policy with a concrete planner. */\n static readonly FromFunction = (\n id: string,\n plan: CompactionPolicyShape[\"plan\"],\n ): Layer.Layer<CompactionPolicy> =>\n Layer.succeed(CompactionPolicy, {\n id: CompactionPolicyId.make(id),\n plan,\n });\n\n /**\n * Common production policy: compact when approximate prompt context exceeds a token threshold.\n *\n * The policy keeps a recent tail verbatim, summarizes the older prefix, and advances from the\n * current summary cursor so repeated compactions behave like the first one.\n */\n static readonly ApproximateTokenThreshold = (\n options: ApproximateTokenThresholdCompactionPolicyOptions = {},\n ): Layer.Layer<CompactionPolicy> => {\n const normalized = normalizeApproximateTokenPolicyOptions(options);\n return Layer.succeed(CompactionPolicy, {\n id: normalized.policyId,\n plan: ({ state, context }) =>\n Effect.sync(() => planApproximateTokenCompaction(state, context, normalized)),\n });\n };\n}\n\n/** Service contract for turning a selected compaction range into a summary artifact. */\nexport interface CompactionExecutorShape {\n readonly id: CompactionExecutorId;\n readonly execute: (\n input: CompactionExecutorInput,\n ) => Effect.Effect<CompactionOutput, CompactionError>;\n}\n\n/** Produces a cumulative summary artifact for a selected compaction plan. */\nexport class CompactionExecutor extends Context.Service<\n CompactionExecutor,\n CompactionExecutorShape\n>()(\"@effect-durable-agent/CompactionExecutor\") {\n /** Placeholder executor for the disabled default policy. It should never be called. */\n static readonly Disabled = Layer.succeed(CompactionExecutor, {\n id: CompactionExecutorId.make(\"disabled\"),\n execute: () => Effect.die(new Error(\"CompactionExecutor.Disabled was called\")),\n } satisfies CompactionExecutorShape);\n\n /** Test/app hook for replacing summary generation. */\n static readonly FromFunction = (\n id: string,\n execute: CompactionExecutorShape[\"execute\"],\n ): Layer.Layer<CompactionExecutor> =>\n Layer.succeed(CompactionExecutor, {\n id: CompactionExecutorId.make(id),\n execute,\n });\n\n /** Summary executor backed by the configured Effect AI LanguageModel. */\n static readonly LanguageModelSummary = (\n options: LanguageModelSummaryCompactionExecutorOptions = {},\n ): Layer.Layer<CompactionExecutor> =>\n Layer.effect(\n CompactionExecutor,\n Effect.sync(() => {\n const executorId = CompactionExecutorId.make(\n options.executorId ?? \"language-model-summary\",\n );\n const summaryMessagePrefix = options.summaryMessagePrefix ?? \"Conversation summary:\";\n return {\n id: executorId,\n execute: Effect.fn(\"agent.compaction\")(function* (input) {\n yield* annotateEdaSpan({\n \"eda.compaction.policy_id\": input.plan.policyId,\n \"eda.compaction.source_from_seq\": input.plan.sourceFromSeq,\n \"eda.compaction.source_to_seq\": input.plan.sourceToSeq,\n \"eda.compaction.retained_from_context_seq\": input.plan.retainedFromContextSeq,\n \"eda.compaction.executor_id\": executorId,\n });\n const promptText = buildSummaryPrompt(input);\n if (promptText === undefined) {\n return yield* new CompactionError({\n message: \"compaction plan selected no source messages\",\n });\n }\n const response = yield* input.model\n .generateText({\n prompt: Prompt.fromMessages([\n Prompt.makeMessage(\"system\", { content: summarizationSystemPrompt }),\n Prompt.makeMessage(\"user\", {\n content: [Prompt.textPart({ text: promptText })],\n }),\n ]),\n toolChoice: \"none\",\n })\n .pipe(\n Effect.mapError(\n (error) =>\n new CompactionError({\n message: `summary model failed: ${formatUnknownError(error)}`,\n }),\n ),\n );\n const text = response.text.trim();\n if (text.length === 0) {\n return yield* new CompactionError({\n message: \"summary model returned no text\",\n usage: makeUsagePayload(response.usage),\n });\n }\n return CompactionOutput.make({\n usage: makeUsagePayload(response.usage),\n text,\n promptMessage: Prompt.makeMessage(\"user\", {\n content: [Prompt.textPart({ text: `${summaryMessagePrefix}\\n\\n${text}` })],\n }),\n executorId,\n });\n }),\n } satisfies CompactionExecutorShape;\n }),\n );\n}\n\n/** Prompt-prefix summary executor options. */\nexport interface PromptPrefixSummaryCompactionExecutorOptions {\n /** Stable executor id stored on summary artifacts. */\n readonly executorId?: string;\n /** Summarization request appended after the conversation. Defaults to EDA's checkpoint prompt. */\n readonly instructions?: string;\n /** Prefix used for the synthetic prompt message inserted into future context. */\n readonly summaryMessagePrefix?: string;\n}\n\n/**\n * Provider-neutral summary that reuses the conversation's own prompt prefix (instructions, tools,\n * history) and appends the summarization request, so the call reads the conversation from the\n * provider cache. Pair it with a policy that retains nothing (`retainTailTokens: 0`) on providers\n * that bind reasoning to its conversation; use provider-native executors to keep a tail.\n */\nexport const promptPrefixSummaryCompactionExecutor = (\n options: PromptPrefixSummaryCompactionExecutorOptions = {},\n): Layer.Layer<CompactionExecutor> =>\n Layer.succeed(CompactionExecutor, {\n id: CompactionExecutorId.make(options.executorId ?? \"prompt-prefix-summary\"),\n execute: Effect.fn(\"agent.compaction\")(function* (input) {\n const request = options.instructions ?? `Do not call any tools. ${summaryPromptText}`;\n const prompt = Prompt.fromMessages([\n ...input.prompt.content,\n Prompt.makeMessage(\"user\", { content: [Prompt.textPart({ text: request })] }),\n ]);\n const response = yield* generateTextOfferingTools(input.model, prompt, input.toolkit).pipe(\n Effect.mapError(\n (error) =>\n new CompactionError({ message: `summary model failed: ${formatUnknownError(error)}` }),\n ),\n );\n const text = response.text.trim();\n if (text.length === 0) {\n return yield* new CompactionError({\n message: \"summary model returned no text\",\n usage: makeUsagePayload(response.usage),\n });\n }\n return CompactionOutput.make({\n usage: makeUsagePayload(response.usage),\n text,\n promptMessage: Prompt.makeMessage(\"user\", {\n content: [\n Prompt.textPart({\n text: `${options.summaryMessagePrefix ?? \"Conversation summary:\"}\\n\\n${text}`,\n }),\n ],\n }),\n executorId: CompactionExecutorId.make(options.executorId ?? \"prompt-prefix-summary\"),\n });\n }),\n } satisfies CompactionExecutorShape);\n\n/** EDA's checkpoint summary request, exposed for executors that pass custom instructions. */\nexport const defaultCompactionSummaryInstructions = (): string => summaryPromptText;\n\n/** Inputs needed by the framework-owned compaction lifecycle runner. */\nexport interface CompactionRunnerInput {\n readonly state: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n readonly context: ContextProjection;\n readonly appendDurableEntries: (\n entries: ReadonlyArray<DurableAppendEntry>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n}\n\n/** Runtime service that executes framework-owned compaction lifecycles. */\nexport interface CompactionRunnerShape {\n /** Evaluate policy and run one compaction if a plan is selected. */\n readonly maybeCompact: (\n input: CompactionRunnerInput,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n}\n\n/** Framework-owned compaction lifecycle runner. */\nexport class CompactionRunner extends Context.Service<CompactionRunner, CompactionRunnerShape>()(\n \"@effect-durable-agent/CompactionRunner\",\n) {\n static readonly Live = Layer.effect(\n CompactionRunner,\n Effect.suspend(() => makeLiveCompactionRunner),\n );\n}\n\ninterface NormalizedApproximateTokenPolicyOptions {\n readonly retain: \"tail-tokens\" | \"last-response\";\n readonly policyId: CompactionPolicyId;\n readonly thresholdTokens: number;\n readonly retainTailTokens: number;\n readonly minSummarizableTokens: number;\n readonly charsPerToken: number;\n}\n\ninterface EstimatedContextMessage {\n readonly chars: number;\n readonly message: DurableTranscriptMessage;\n readonly seq: SequenceNumber;\n}\n\nconst makeLiveCompactionRunner = Effect.gen(function* () {\n const ids = yield* IdGenerator;\n const events = yield* EventFactory;\n const policy = yield* CompactionPolicy;\n const executor = yield* CompactionExecutor;\n const keepAlive = yield* EDAKeepAlive;\n const models = yield* ModelResolver;\n const promptProjector = yield* EDAPromptProjector;\n const toolRegistry = yield* EDAToolRegistry;\n const session = yield* SessionContext;\n\n const maybeCompact = Effect.fnUntraced(function* (input: CompactionRunnerInput) {\n const plan = yield* policy\n .plan({ state: input.state, context: input.context })\n .pipe(\n Effect.catchTag(\"CompactionError\", (error) =>\n Effect.logError(\"compaction policy failed\", { error }).pipe(Effect.as(undefined)),\n ),\n );\n if (plan === undefined) {\n yield* annotateEdaSpan({ \"eda.compaction.selected\": false });\n return [];\n }\n yield* annotateEdaSpan({\n \"eda.compaction.selected\": true,\n \"eda.compaction.policy_id\": plan.policyId,\n \"eda.compaction.source_from_seq\": plan.sourceFromSeq,\n \"eda.compaction.source_to_seq\": plan.sourceToSeq,\n \"eda.compaction.retained_from_context_seq\": plan.retainedFromContextSeq,\n });\n const invalidPlan = validatePlan(plan, input.state, input.context);\n if (invalidPlan !== undefined) {\n yield* Effect.logError(\"compaction policy returned invalid plan\", { reason: invalidPlan });\n return [];\n }\n\n const compactionId = yield* ids.makeCompactionId();\n const summaryId = yield* ids.makeSummaryId();\n yield* annotateEdaSpan({\n \"eda.compaction.id\": compactionId,\n \"eda.summary.id\": summaryId,\n });\n const requested = yield* events.compactionRequested({\n compactionId,\n sourceFromSeq: plan.sourceFromSeq,\n sourceToSeq: plan.sourceToSeq,\n });\n const started = yield* events.compactionStarted({ compactionId });\n const startedEvents = yield* input.appendDurableEntries([\n { event: requested },\n { event: started },\n ]);\n\n const model = yield* models.resolve(input.state.modelSelection);\n const projected = yield* buildEDAPrompt(promptProjector, {\n sessionId: session.sessionId,\n state: projectionStateThrough(input.state, plan.sourceToSeq),\n reducerStates: input.reducerStates,\n context: input.context,\n });\n const prompt = models.preparePrompt?.(input.state.modelSelection, projected) ?? projected;\n const toolkit = yield* toolRegistry.getModelToolkit();\n const output = yield* keepAlive\n .withActiveWork(\n `compaction:${compactionId}`,\n executor.execute({\n plan,\n state: input.state,\n context: input.context,\n model,\n prompt,\n toolkit,\n }),\n )\n .pipe(\n Effect.catchTag(\"CompactionError\", (error) =>\n Effect.gen(function* () {\n const failed = yield* events.compactionFailed({\n compactionId,\n ...(input.state.modelSelection === undefined\n ? {}\n : { modelSelection: input.state.modelSelection }),\n ...(error.usage === undefined ? {} : { usage: error.usage }),\n error: FailurePayload.make({ message: error.message }),\n });\n const committed = yield* input.appendDurableEntries([{ event: failed }]);\n return { _tag: \"Failed\" as const, committed };\n }),\n ),\n Effect.map((result) =>\n \"_tag\" in result ? result : { _tag: \"Output\" as const, output: result },\n ),\n );\n\n if (output._tag === \"Failed\") {\n return [...startedEvents, ...output.committed];\n }\n\n const artifact = CompactionSummaryArtifact.make({\n compactionId,\n summaryId,\n ...(input.context.currentSummary === undefined\n ? {}\n : { previousSummaryId: input.context.currentSummary.summaryId }),\n sourceFromSeq: plan.sourceFromSeq,\n sourceToSeq: plan.sourceToSeq,\n retainedFromContextSeq: plan.retainedFromContextSeq,\n text: output.output.text,\n promptMessage: output.output.promptMessage,\n policyId: plan.policyId,\n ...(output.output.executorId === undefined ? {} : { executorId: output.output.executorId }),\n });\n const summaryCreated = yield* events.summaryCreated({\n compactionId,\n summaryId,\n sourceFromSeq: plan.sourceFromSeq,\n sourceToSeq: plan.sourceToSeq,\n summary: artifact,\n });\n const contextRebased = yield* events.contextRebased({\n compactionId,\n summaryId,\n contextVersion: ContextVersion.make(input.context.contextVersion + 1),\n retainedFromContextSeq: plan.retainedFromContextSeq,\n });\n const completed = yield* events.compactionCompleted({\n compactionId,\n ...(input.state.modelSelection === undefined\n ? {}\n : { modelSelection: input.state.modelSelection }),\n ...(output.output.usage === undefined ? {} : { usage: output.output.usage }),\n });\n const committed = yield* input.appendDurableEntries([\n { event: summaryCreated },\n { event: contextRebased },\n { event: completed },\n ]);\n yield* annotateEdaSpan(committedBatchAttributes([...startedEvents, ...committed]));\n return [...startedEvents, ...committed];\n });\n\n return { maybeCompact } satisfies CompactionRunnerShape;\n});\n\nconst validatePlan = (\n plan: CompactionPlan,\n state: ReducedState,\n context: ContextProjection,\n): string | undefined => {\n const currentRetainedFromSeq =\n context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);\n if (plan.retainedFromContextSeq <= currentRetainedFromSeq) {\n return \"retainedFromContextSeq must advance beyond the current summary cursor\";\n }\n if (plan.sourceToSeq > state.lastSeq) {\n return \"sourceToSeq must not exceed the current durable head\";\n }\n if (plan.retainedFromContextSeq > state.lastSeq + 1) {\n return \"retainedFromContextSeq must not skip unsummarized future context\";\n }\n if (plan.sourceFromSeq > plan.sourceToSeq) {\n return \"sourceFromSeq must be less than or equal to sourceToSeq\";\n }\n if (plan.retainedFromContextSeq <= plan.sourceToSeq) {\n return \"retainedFromContextSeq must start after the summarized source range\";\n }\n return undefined;\n};\n\nconst normalizeApproximateTokenPolicyOptions = (\n options: ApproximateTokenThresholdCompactionPolicyOptions,\n): NormalizedApproximateTokenPolicyOptions => ({\n retain: options.retain ?? \"tail-tokens\",\n policyId: CompactionPolicyId.make(options.policyId ?? \"approximate-token-threshold\"),\n thresholdTokens: positiveNumber(\n options.thresholdTokens ?? defaultCompactionThresholdTokens,\n \"thresholdTokens\",\n ),\n retainTailTokens: nonNegativeNumber(\n options.retainTailTokens ?? defaultCompactionRetainTailTokens,\n \"retainTailTokens\",\n ),\n minSummarizableTokens: nonNegativeNumber(\n options.minSummarizableTokens ?? defaultCompactionMinSummarizableTokens,\n \"minSummarizableTokens\",\n ),\n charsPerToken: positiveNumber(\n options.charsPerToken ?? defaultCompactionCharsPerToken,\n \"charsPerToken\",\n ),\n});\n\nconst positiveNumber = (value: number, name: string): number => {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`${name} must be a positive finite number`);\n }\n return value;\n};\n\nconst nonNegativeNumber = (value: number, name: string): number => {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${name} must be a non-negative finite number`);\n }\n return value;\n};\n\n/** Plan one Pi-style approximate-token compaction while keeping a recent tail verbatim. */\nconst planApproximateTokenCompaction = (\n state: ReducedState,\n context: ContextProjection,\n options: NormalizedApproximateTokenPolicyOptions,\n): CompactionPlan | undefined => {\n const messages = estimatedContextMessages(state);\n const totalChars = estimateCurrentPromptChars(state, context, messages);\n if (totalChars <= options.thresholdTokens * options.charsPerToken) {\n return undefined;\n }\n\n const currentRetainedFromSeq =\n context.currentSummary?.retainedFromContextSeq ?? SequenceNumber.make(0);\n const retainedFromSeq =\n options.retain === \"last-response\"\n ? lastResponseSeq(messages, currentRetainedFromSeq)\n : selectRetainedFromSeq(messages, state.lastSeq, options);\n if (retainedFromSeq === undefined) {\n return undefined;\n }\n if (retainedFromSeq <= currentRetainedFromSeq) {\n return undefined;\n }\n\n const sourceMessages = messages.filter((message) => message.seq < retainedFromSeq);\n if (sourceMessages.length === 0) {\n return undefined;\n }\n\n const summarizableTokens = charsToTokens(\n sourceMessages.reduce((sum, message) => sum + message.chars, 0),\n options.charsPerToken,\n );\n if (summarizableTokens < options.minSummarizableTokens) {\n return undefined;\n }\n\n const sourceFromSeq =\n currentRetainedFromSeq > 0 ? currentRetainedFromSeq : sourceMessages[0]!.seq;\n const sourceToSeq = SequenceNumber.make(retainedFromSeq - 1);\n if (sourceFromSeq > sourceToSeq) {\n return undefined;\n }\n\n return CompactionPlan.make({\n policyId: options.policyId,\n sourceFromSeq,\n sourceToSeq,\n retainedFromContextSeq: retainedFromSeq,\n });\n};\n\n/** Sequence of the latest assistant response past the current cursor, if any. */\nconst lastResponseSeq = (\n messages: ReadonlyArray<EstimatedContextMessage>,\n currentRetainedFromSeq: SequenceNumber,\n): SequenceNumber | undefined => {\n for (const entry of [...messages].reverse()) {\n if (entry.seq <= currentRetainedFromSeq) {\n return undefined;\n }\n if (entry.message._tag === \"Assistant\" || entry.message._tag === \"AssistantPartial\") {\n return entry.seq;\n }\n }\n return undefined;\n};\n\nconst selectRetainedFromSeq = (\n messages: ReadonlyArray<EstimatedContextMessage>,\n lastSeq: SequenceNumber,\n options: NormalizedApproximateTokenPolicyOptions,\n): SequenceNumber => {\n if (options.retainTailTokens === 0) {\n return SequenceNumber.make(lastSeq + 1);\n }\n\n const retainTailChars = options.retainTailTokens * options.charsPerToken;\n let tailChars = 0;\n let retainedIndex = messages.length;\n for (let index = messages.length - 1; index >= 0; index--) {\n tailChars += messages[index]!.chars;\n retainedIndex = index;\n if (tailChars >= retainTailChars) {\n break;\n }\n }\n return retainedIndex >= messages.length\n ? SequenceNumber.make(lastSeq + 1)\n : messages[retainedIndex]!.seq;\n};\n\nconst estimateCurrentPromptChars = (\n state: ReducedState,\n context: ContextProjection,\n messages: ReadonlyArray<EstimatedContextMessage>,\n): number => {\n const systemChars = Array.from(state.messages.values()).reduce(\n (sum, message) => (message._tag === \"System\" ? sum + message.content.length : sum),\n 0,\n );\n const summaryChars =\n context.currentSummary === undefined\n ? 0\n : estimatePromptMessageChars(context.currentSummary.promptMessage);\n const messageChars = messages.reduce((sum, message) => sum + message.chars, 0);\n return systemChars + summaryChars + messageChars;\n};\n\nconst estimatedContextMessages = (state: ReducedState): ReadonlyArray<EstimatedContextMessage> =>\n durableMessageTranscript(state).map((message) => ({\n message,\n seq: messageSeq(message),\n chars: estimateDurableMessageChars(message) + estimateAssociatedToolChars(message, state),\n }));\n\nconst estimateDurableMessageChars = (message: DurableTranscriptMessage): number => {\n switch (message._tag) {\n case \"User\":\n case \"Steering\":\n return estimateUserContentChars(message.content);\n case \"Assistant\":\n case \"AssistantPartial\":\n return estimateAssistantPromptChars(message.promptParts, message.content);\n }\n};\n\nconst estimateAssociatedToolChars = (\n message: DurableTranscriptMessage,\n state: ReducedState,\n): number => {\n if (message._tag !== \"Assistant\" && message._tag !== \"AssistantPartial\") {\n return 0;\n }\n return toolPromptPartsForInference(message.inferenceId, state.toolCalls).reduce(\n (sum, part) => sum + estimatePromptPartChars(part),\n 0,\n );\n};\n\nconst messageSeq = (message: DurableTranscriptMessage): SequenceNumber =>\n message._tag === \"Steering\" ? message.consumedSeq : message.seq;\n\nconst charsToTokens = (chars: number, charsPerToken: number): number =>\n Math.ceil(chars / charsPerToken);\n\nconst buildSummaryPrompt = (input: CompactionExecutorInput): string | undefined => {\n const sourceText = serializeCompactionSource(input);\n if (sourceText.trim().length === 0) {\n return undefined;\n }\n\n const previousSummary =\n input.context.currentSummary === undefined\n ? \"\"\n : `<previous-summary>\\n${input.context.currentSummary.text}\\n</previous-summary>\\n\\n`;\n return `${previousSummary}<conversation>\\n${sourceText}\\n</conversation>\\n\\n${summaryPromptText}`;\n};\n\nconst serializeCompactionSource = (input: CompactionExecutorInput): string => {\n const lines: Array<string> = [];\n for (const message of durableMessageTranscript(input.state)) {\n const seq = messageSeq(message);\n if (seq < input.plan.sourceFromSeq || seq > input.plan.sourceToSeq) {\n continue;\n }\n lines.push(serializeDurableMessage(message));\n if (message._tag === \"Assistant\" || message._tag === \"AssistantPartial\") {\n for (const part of toolPromptPartsForInference(message.inferenceId, input.state.toolCalls)) {\n lines.push(serializeToolResultPart(part));\n }\n }\n }\n return lines.filter((line) => line.trim().length > 0).join(\"\\n\\n\");\n};\n\nconst serializeDurableMessage = (message: DurableTranscriptMessage): string => {\n switch (message._tag) {\n case \"User\":\n return `[User]: ${userContentText(message.content)}`;\n case \"Steering\":\n return `[User steering]: ${userContentText(message.content)}`;\n case \"Assistant\":\n case \"AssistantPartial\":\n return serializeAssistantMessage(message.promptParts, message.content);\n }\n};\n\nconst serializeAssistantMessage = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart> | undefined,\n content: AssistantMessageContent,\n): string => {\n const parts = promptParts ?? assistantContentToPromptParts(content);\n const text: Array<string> = [];\n const reasoning: Array<string> = [];\n const toolCalls: Array<string> = [];\n const sideband: Array<string> = [];\n for (const part of parts) {\n switch (part.type) {\n case \"text\":\n text.push(part.text);\n break;\n case \"reasoning\":\n reasoning.push(part.text);\n break;\n case \"tool-call\":\n toolCalls.push(`${part.name}(${safeJsonStringify(part.params)})`);\n break;\n case \"file\":\n sideband.push(`file(${part.fileName ?? \"unnamed\"}, ${part.mediaType})`);\n break;\n case \"tool-result\":\n sideband.push(\n `tool-result(${part.name}, ${truncateForSummary(safeJsonStringify(part.result))})`,\n );\n break;\n case \"tool-approval-request\":\n sideband.push(`tool-approval-request(${part.approvalId}, ${part.toolCallId})`);\n break;\n }\n }\n return [\n reasoning.length === 0 ? \"\" : `[Assistant reasoning]: ${reasoning.join(\"\\n\")}`,\n text.length === 0 ? \"\" : `[Assistant]: ${text.join(\"\\n\")}`,\n toolCalls.length === 0 ? \"\" : `[Assistant tool calls]: ${toolCalls.join(\"; \")}`,\n sideband.length === 0 ? \"\" : `[Assistant context]: ${sideband.join(\"; \")}`,\n ]\n .filter((line) => line.length > 0)\n .join(\"\\n\");\n};\n\nconst serializeToolResultPart = (part: Prompt.ToolResultPart): string =>\n `[Tool result ${part.name}${part.isFailure ? \" failed\" : \"\"}]: ${truncateForSummary(\n safeJsonStringify(part.result),\n )}`;\n\nconst toolPromptPartsForInference = (\n inferenceId: InferenceId,\n toolCalls: ReducedState[\"toolCalls\"],\n): ReadonlyArray<Prompt.ToolResultPart> =>\n Array.from(toolCalls.values()).flatMap((tool): ReadonlyArray<Prompt.ToolResultPart> => {\n const { decision } = tool;\n if (decision === undefined || decision.inferenceId !== inferenceId) {\n return [];\n }\n if (decision._tag === \"Rejected\") {\n return decision.promptPart === undefined ? [] : [decision.promptPart];\n }\n const terminal = tool.terminal;\n if (terminal === undefined || terminal.promptPart === undefined) {\n return [];\n }\n return [terminal.promptPart];\n });\n\nconst assistantContentToPromptParts = (\n content: AssistantMessageContent,\n): ReadonlyArray<Prompt.AssistantMessagePart> => [\n ...(content.reasoning === undefined ? [] : [Prompt.reasoningPart({ text: content.reasoning })]),\n ...(content.text.length === 0 ? [] : [Prompt.textPart({ text: content.text })]),\n];\n\nconst estimateAssistantPromptChars = (\n promptParts: ReadonlyArray<Prompt.AssistantMessagePart> | undefined,\n content: AssistantMessageContent,\n): number =>\n (promptParts ?? assistantContentToPromptParts(content)).reduce(\n (sum, part) => sum + estimatePromptPartChars(part),\n 0,\n );\n\nconst estimateUserContentChars = (\n content: string | ReadonlyArray<Prompt.UserMessagePart>,\n): number =>\n typeof content === \"string\"\n ? content.length\n : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);\n\nconst estimatePromptMessageChars = (message: Prompt.Message): number => {\n if (!(\"content\" in message)) {\n return 0;\n }\n const { content } = message;\n return typeof content === \"string\"\n ? content.length\n : content.reduce((sum, part) => sum + estimatePromptPartChars(part), 0);\n};\n\ntype PromptContentPart =\n | Prompt.UserMessagePart\n | Prompt.AssistantMessagePart\n | Prompt.ToolMessagePart;\n\nconst estimatePromptPartChars = (part: PromptContentPart): number => {\n switch (part.type) {\n case \"text\":\n return part.text.length;\n case \"reasoning\":\n return part.text.length;\n case \"file\":\n return (\n part.mediaType.length +\n (part.fileName?.length ?? 0) +\n (typeof part.data === \"string\"\n ? part.data.length\n : part.data instanceof URL\n ? part.data.toString().length\n : estimatedBinaryFileChars)\n );\n case \"tool-call\":\n return part.name.length + safeJsonStringify(part.params).length;\n case \"tool-result\":\n return part.name.length + safeJsonStringify(part.result).length;\n case \"tool-approval-response\":\n return part.approvalId.length + (part.reason?.length ?? 0) + 8;\n case \"tool-approval-request\":\n return part.approvalId.length + part.toolCallId.length;\n default:\n return safeJsonStringify(part).length;\n }\n};\n\nconst userContentText = (content: string | ReadonlyArray<Prompt.UserMessagePart>): string =>\n typeof content === \"string\"\n ? content\n : content\n .map((part) => {\n switch (part.type) {\n case \"text\":\n return part.text;\n case \"file\":\n return `[file ${part.fileName ?? \"unnamed\"} ${part.mediaType}]`;\n }\n })\n .join(\"\\n\");\n\nconst safeJsonStringify = (value: unknown): string => {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\nconst truncateForSummary = (text: string, maxChars = 2_000): string => {\n if (text.length <= maxChars) {\n return text;\n }\n return `${text.slice(0, maxChars)}\\n\\n[... ${text.length - maxChars} more characters truncated]`;\n};\n\nconst formatUnknownError = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\nconst estimatedBinaryFileChars = 4_800;\n\nconst summarizationSystemPrompt =\n \"You are a context summarization assistant. Do not continue the conversation. Only output the requested structured summary.\";\n\nconst summaryPromptText = `The messages above are conversation history selected for compaction. Create a cumulative context checkpoint summary that another LLM will use to continue the work.\n\nUse this exact structure:\n\n## Goal\n[What the user is trying to accomplish]\n\n## Constraints & Preferences\n- [Requirements, constraints, and preferences]\n\n## Progress\n### Done\n- [x] [Completed work]\n\n### In Progress\n- [ ] [Current unfinished work]\n\n### Blocked\n- [Current blockers, or \"(none)\"]\n\n## Key Decisions\n- **[Decision]**: [Rationale]\n\n## Next Steps\n1. [Concrete next step]\n\n## Critical Context\n- [Important facts, data, IDs, file paths, function names, and exact errors needed to continue]\n\nRules:\n- If <previous-summary> is present, preserve important existing facts and update it with the new conversation.\n- Keep the summary concise but sufficient to replace the compacted history.\n- Preserve exact file paths, tool names, identifiers, and error messages.\n- Do not answer questions from the conversation.`;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAIA,MAAa,oBAAoB,UAA0B;CACzD,MAAM,sBAAsB,eAAe,MAAM,YAAY,QAAQ;CACrE,MAAM,oBAAoB,eAAe,MAAM,YAAY,SAAS;CACpE,MAAM,wBAAwB,eAAe,MAAM,YAAY,UAAU;CACzE,MAAM,cACJ,eAAe,MAAM,YAAY,KAAK,KACtC,WAAW;EAAC;EAAqB;EAAmB;CAAqB,CAAC;CAC5E,MAAM,aAAa,eAAe,MAAM,aAAa,IAAI;CACzD,MAAM,kBAAkB,eAAe,MAAM,aAAa,SAAS;CACnE,MAAM,eACJ,eAAe,MAAM,aAAa,KAAK,KAAK,WAAW,CAAC,YAAY,eAAe,CAAC;CAEtF,OAAO,aAAa,KAAK;EACvB,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;EACnD,GAAI,sBAAsB,KAAA,IAAY,CAAC,IAAI,EAAE,kBAAkB;EAC/D,GAAI,0BAA0B,KAAA,IAAY,CAAC,IAAI,EAAE,sBAAsB;EACvE,GAAI,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa;EACrD,GAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW;EACjD,GAAI,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAgB;CAC7D,CAAC;AACH;AAEA,MAAM,cAAc,WAA8C;CAChE,MAAM,UAAU,OAAO,QAAQ,UAA2B,UAAU,KAAA,CAAS;CAC7E,OAAO,QAAQ,WAAW,IAAI,KAAA,IAAY,QAAQ,QAAQ,KAAK,UAAU,MAAM,OAAO,CAAC;AACzF;AAEA,MAAM,kBAAkB,UACtB,UAAU,KAAA,KAAa,CAAC,OAAO,SAAS,KAAK,IAAI,KAAA,IAAY,KAAK,IAAI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AAG,KAAK,MAAM,GAAG,QAAQ,EAAE,WAAW,KAAK,SAAS,SAAS;AACtE;AAEA,MAAM,sBAAsB,UAC1B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAEvD,MAAM,2BAA2B;AAEjC,MAAM,4BACJ;AAEF,MAAM,oBAAoB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"session-admission-WE8J_0z9.js","names":[],"sources":["../src/services/session-admission.ts"],"sourcesContent":["import * as Brand from \"effect/Brand\";\nimport * as Context from \"effect/Context\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport type * as SchemaAST from \"effect/SchemaAST\";\n\nimport { MessageId } from \"../types/core\";\nimport {\n type DurableEventEnvelope,\n effectDurableAgentNamespace,\n maxAppEventBytes,\n} from \"../types/events/envelope\";\nimport { decodeDurableEventSync } from \"../types/events/durable\";\nimport { decodeRetainingExcess } from \"../types/events/internal\";\n\n/**\n * Admission rules every app-written durable event passes before it reaches the store, shared by\n * `submit`, decider drafts, tool `emitDurable` and sink `stageDurable`. A refusal here is not a\n * store error, so it never makes the live runtime fatal. Internal: not an exported subpath.\n */\n\nexport class SessionCommandAdmissionConflict extends Schema.TaggedError<SessionCommandAdmissionConflict>()(\n \"SessionCommandAdmissionConflict\",\n {\n code: Schema.Literals([\n \"queue_paused\",\n \"paused_queue_changed\",\n \"event_too_large\",\n \"framework_event\",\n \"invalid_event\",\n \"payload_not_json\",\n ]),\n message: Schema.String,\n pausedMessageIds: Schema.Array(MessageId),\n },\n) {}\n\n/** Why an app event is refused. */\nexport interface AppEventRefusal {\n readonly code: \"event_too_large\" | \"framework_event\" | \"invalid_event\" | \"payload_not_json\";\n readonly message: string;\n}\n\n/**\n * Framework event types app code may still write through `submit`, decider drafts, `emitDurable`\n * and `stageDurable`: a session seed (`SessionConfigured`, `SystemMessageCommitted`) and imported\n * history. Every other `effect-durable-agent` event is the framework's alone; a forged\n * `DeciderAccepted` would make a later decision replay a result nobody decided.\n */\nexport const appWritableFrameworkEventTypes: ReadonlySet<string> = new Set([\n \"SessionConfigured\",\n \"SystemMessageCommitted\",\n \"AssistantMessageImported\",\n]);\n\n/** App event schemas are a union of structs with literal namespaces; throw for any other shape. */\nexport const eventSchemaNamespaces = (ast: SchemaAST.AST): ReadonlyArray<string> => {\n if (ast._tag === \"Union\") return ast.types.flatMap(eventSchemaNamespaces);\n if (ast._tag === \"Objects\") {\n const namespace = ast.propertySignatures.find((field) => field.name === \"namespace\")?.type;\n if (namespace?._tag === \"Literal\" && typeof namespace.literal === \"string\")\n return [namespace.literal];\n }\n throw new Error(\"App event schemas must be a union of structs with literal namespaces\");\n};\n\n/**\n * The JSON form the store keeps, `JSON.parse(JSON.stringify(value))`, or why `value` has none.\n * The round trip may only drop an object property whose value is `undefined`; anything else it\n * would change is refused rather than silently rewritten: anything with a prototype (`Redacted`,\n * `Option`, `Date`, a class instance), `undefined` in an array, a non-finite number, a bigint, a\n * function, a symbol or a cycle. Every check that must hold for what is stored runs on this form.\n */\nexport const storedJsonForm = (\n value: unknown,\n path: string,\n): Result.Result<Schema.Json, string> => {\n const violation = jsonNativeAt(value, path, new Set());\n if (violation !== undefined) return Result.fail(violation);\n const json: Schema.Json = JSON.parse(JSON.stringify(value));\n return Result.succeed(json);\n};\n\nconst jsonNativeAt = (value: unknown, path: string, seen: Set<object>): string | undefined => {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return undefined;\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? undefined : `${path} is the non-finite number ${value}`;\n }\n if (typeof value !== \"object\") return `${path} is a ${typeof value}`;\n if (seen.has(value)) return `${path} is a cycle`;\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n for (let index = 0; index < value.length; index += 1) {\n if (!(index in value) || value[index] === undefined) {\n return `${path}[${index}] is undefined`;\n }\n const violation = jsonNativeAt(value[index], `${path}[${index}]`, seen);\n if (violation !== undefined) return violation;\n }\n return undefined;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n const name =\n typeof prototype === \"object\" &&\n prototype !== null &&\n \"constructor\" in prototype &&\n typeof prototype.constructor === \"function\"\n ? prototype.constructor.name\n : \"unknown\";\n return `${path} is not a plain object (prototype ${name || \"anonymous\"})`;\n }\n if (Object.getOwnPropertySymbols(value).length > 0) return `${path} has symbol keys`;\n for (const [key, entry] of Object.entries(value)) {\n if (entry === undefined) continue;\n const violation = jsonNativeAt(entry, `${path}.${key}`, seen);\n if (violation !== undefined) return violation;\n }\n return undefined;\n } finally {\n seen.delete(value);\n }\n};\n\nconst jsonEncoder = new TextEncoder();\n\n/** UTF-8 size of a JSON-native value's JSON text. */\nexport const jsonBytes = (value: unknown): number => {\n const json: string | undefined = JSON.stringify(value);\n return json === undefined ? 0 : jsonEncoder.encode(json).byteLength;\n};\n\n/** The registered application event union, if the runtime has one. */\nexport type AppEventCodec = Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\n/** The runtime's registered `appEvents` union; absent for a framework-only runtime. */\nexport const RegisteredAppEvents = Context.Reference<AppEventCodec | undefined>(\n \"effect-durable-agent/RegisteredAppEvents\",\n { defaultValue: () => undefined },\n);\n\n/**\n * An app-written durable event that passed admission. Its payload is already the JSON form the\n * store keeps, so what is appended is exactly what was checked. Only `admit` makes one.\n */\nexport type AdmittedAppEvent = DurableEventEnvelope & Brand.Brand<\"AdmittedAppEvent\">;\nconst AdmittedAppEvent = Brand.nominal<AdmittedAppEvent>();\n\n/** Admits app-written durable events under the runtime's rules. */\nexport interface AppEventAdmission {\n /**\n * The event to append in place of `event`, or why it is refused. The payload is replaced by its\n * stored JSON form first; the size, framework-schema and `appEvents` checks all read that form.\n */\n readonly admit: (event: DurableEventEnvelope) => Result.Result<AdmittedAppEvent, AppEventRefusal>;\n}\n\n/** Build the checker for a runtime, with its registered `appEvents` codec if any. */\nexport const makeAppEventAdmission = (appEvents: AppEventCodec | undefined): AppEventAdmission => {\n const namespaces = new Set(appEvents === undefined ? [] : eventSchemaNamespaces(appEvents.ast));\n const decode = appEvents === undefined ? undefined : decodeRetainingExcess(appEvents);\n const describe = (event: DurableEventEnvelope) =>\n `Event ${event.namespace}/${event.type} ${event.eventId}`;\n const refuse = (code: AppEventRefusal[\"code\"], message: string) =>\n Result.fail<AppEventRefusal>({ code, message });\n return {\n admit: (event) => {\n const isFramework = event.namespace === effectDurableAgentNamespace;\n if (isFramework && !appWritableFrameworkEventTypes.has(event.type)) {\n return refuse(\n \"framework_event\",\n `${describe(event)} is a framework lifecycle event; app code may write only ${Array.from(appWritableFrameworkEventTypes).join(\", \")}`,\n );\n }\n const payload = storedJsonForm(event.payload, \"payload\");\n if (Result.isFailure(payload)) {\n return refuse(\n \"payload_not_json\",\n `${describe(event)} payload is not JSON-native: ${payload.failure}. Encode it before writing; the store keeps JSON only.`,\n );\n }\n const stored = { ...event, payload: payload.success };\n const bytes = jsonBytes(stored.payload);\n if (bytes > maxAppEventBytes) {\n return refuse(\n \"event_too_large\",\n `${describe(event)} payload is ${bytes} bytes; the limit is ${maxAppEventBytes} bytes`,\n );\n }\n try {\n // The store decodes framework events with their own schema and would fail a malformed one\n // as a store error, so an allowlisted type is checked against that schema here.\n if (isFramework) decodeDurableEventSync(stored);\n } catch (cause) {\n return refuse(\n \"invalid_event\",\n `${describe(event)} does not match its framework event schema once stored as JSON: ${String(cause)}`,\n );\n }\n try {\n if (decode !== undefined && namespaces.has(event.namespace)) decode(stored);\n } catch (cause) {\n return refuse(\n \"invalid_event\",\n `${describe(event)} does not match the registered appEvents schema once stored as JSON: ${String(cause)}`,\n );\n }\n return Result.succeed(AdmittedAppEvent(stored));\n },\n };\n};\n\n/** The admission conflict a refused `submit` item fails with. */\nexport const appEventConflict = (refusal: AppEventRefusal): SessionCommandAdmissionConflict =>\n new SessionCommandAdmissionConflict({\n code: refusal.code,\n message: refusal.message,\n pausedMessageIds: [],\n });\n"],"mappings":";;;;;;;;;;;;;AAqBA,IAAa,kCAAb,cAAq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